Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/AArch64/ABIAArch64.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/AArch64/ABIAArch64.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/AArch64/ABIAArch64.cpp (revision 363961) @@ -1,52 +1,58 @@ //===-- AArch66.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 // //===----------------------------------------------------------------------===// #include "ABIAArch64.h" +#ifdef LLDB_ENABLE_ALL #include "ABIMacOSX_arm64.h" +#endif // LLDB_ENABLE_ALL #include "ABISysV_arm64.h" #include "Utility/ARM64_DWARF_Registers.h" #include "lldb/Core/PluginManager.h" LLDB_PLUGIN_DEFINE(ABIAArch64) void ABIAArch64::Initialize() { ABISysV_arm64::Initialize(); +#ifdef LLDB_ENABLE_ALL ABIMacOSX_arm64::Initialize(); +#endif // LLDB_ENABLE_ALL } void ABIAArch64::Terminate() { ABISysV_arm64::Terminate(); +#ifdef LLDB_ENABLE_ALL ABIMacOSX_arm64::Terminate(); +#endif // LLDB_ENABLE_ALL } std::pair ABIAArch64::GetEHAndDWARFNums(llvm::StringRef name) { if (name == "pc") return {LLDB_INVALID_REGNUM, arm64_dwarf::pc}; if (name == "cpsr") return {LLDB_INVALID_REGNUM, arm64_dwarf::cpsr}; return MCBasedABI::GetEHAndDWARFNums(name); } uint32_t ABIAArch64::GetGenericNum(llvm::StringRef name) { return llvm::StringSwitch(name) .Case("pc", LLDB_REGNUM_GENERIC_PC) .Case("lr", LLDB_REGNUM_GENERIC_RA) .Case("sp", LLDB_REGNUM_GENERIC_SP) .Case("fp", LLDB_REGNUM_GENERIC_FP) .Case("cpsr", LLDB_REGNUM_GENERIC_FLAGS) .Case("x0", LLDB_REGNUM_GENERIC_ARG1) .Case("x1", LLDB_REGNUM_GENERIC_ARG2) .Case("x2", LLDB_REGNUM_GENERIC_ARG3) .Case("x3", LLDB_REGNUM_GENERIC_ARG4) .Case("x4", LLDB_REGNUM_GENERIC_ARG5) .Case("x5", LLDB_REGNUM_GENERIC_ARG6) .Case("x6", LLDB_REGNUM_GENERIC_ARG7) .Case("x7", LLDB_REGNUM_GENERIC_ARG8) .Default(LLDB_INVALID_REGNUM); } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/ARM/ABIARM.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/ARM/ABIARM.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/ARM/ABIARM.cpp (revision 363961) @@ -1,24 +1,30 @@ //===-- ARM.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 // //===----------------------------------------------------------------------===// #include "ABIARM.h" +#ifdef LLDB_ENABLE_ALL #include "ABIMacOSX_arm.h" +#endif // LLDB_ENABLE_ALL #include "ABISysV_arm.h" #include "lldb/Core/PluginManager.h" LLDB_PLUGIN_DEFINE(ABIARM) void ABIARM::Initialize() { ABISysV_arm::Initialize(); +#ifdef LLDB_ENABLE_ALL ABIMacOSX_arm::Initialize(); +#endif // LLDB_ENABLE_ALL } void ABIARM::Terminate() { ABISysV_arm::Terminate(); +#ifdef LLDB_ENABLE_ALL ABIMacOSX_arm::Terminate(); +#endif // LLDB_ENABLE_ALL } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/X86/ABIX86.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/X86/ABIX86.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/ABI/X86/ABIX86.cpp (revision 363961) @@ -1,43 +1,55 @@ //===-- X86.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 // //===----------------------------------------------------------------------===// #include "ABIX86.h" +#ifdef LLDB_ENABLE_ALL #include "ABIMacOSX_i386.h" +#endif // LLDB_ENABLE_ALL #include "ABISysV_i386.h" #include "ABISysV_x86_64.h" +#ifdef LLDB_ENABLE_ALL #include "ABIWindows_x86_64.h" +#endif // LLDB_ENABLE_ALL #include "lldb/Core/PluginManager.h" LLDB_PLUGIN_DEFINE(ABIX86) void ABIX86::Initialize() { +#ifdef LLDB_ENABLE_ALL ABIMacOSX_i386::Initialize(); +#endif // LLDB_ENABLE_ALL ABISysV_i386::Initialize(); ABISysV_x86_64::Initialize(); +#ifdef LLDB_ENABLE_ALL ABIWindows_x86_64::Initialize(); +#endif // LLDB_ENABLE_ALL } void ABIX86::Terminate() { +#ifdef LLDB_ENABLE_ALL ABIMacOSX_i386::Terminate(); +#endif // LLDB_ENABLE_ALL ABISysV_i386::Terminate(); ABISysV_x86_64::Terminate(); +#ifdef LLDB_ENABLE_ALL ABIWindows_x86_64::Terminate(); +#endif // LLDB_ENABLE_ALL } uint32_t ABIX86::GetGenericNum(llvm::StringRef name) { return llvm::StringSwitch(name) .Case("eip", LLDB_REGNUM_GENERIC_PC) .Case("esp", LLDB_REGNUM_GENERIC_SP) .Case("ebp", LLDB_REGNUM_GENERIC_FP) .Case("eflags", LLDB_REGNUM_GENERIC_FLAGS) .Case("edi", LLDB_REGNUM_GENERIC_ARG1) .Case("esi", LLDB_REGNUM_GENERIC_ARG2) .Case("edx", LLDB_REGNUM_GENERIC_ARG3) .Case("ecx", LLDB_REGNUM_GENERIC_ARG4) .Default(LLDB_INVALID_REGNUM); } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/JITLoader/GDB/JITLoaderGDB.cpp (revision 363961) @@ -1,476 +1,481 @@ //===-- JITLoaderGDB.cpp --------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "JITLoaderGDB.h" +#ifdef LLDB_ENABLE_ALL #include "Plugins/ObjectFile/Mach-O/ObjectFileMachO.h" +#endif // LLDB_ENABLE_ALL #include "lldb/Breakpoint/Breakpoint.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/Section.h" #include "lldb/Interpreter/OptionValueProperties.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/Symbol.h" #include "lldb/Symbol/SymbolContext.h" #include "lldb/Symbol/SymbolVendor.h" #include "lldb/Target/Process.h" #include "lldb/Target/SectionLoadList.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/StreamString.h" #include "llvm/Support/MathExtras.h" #include using namespace lldb; using namespace lldb_private; LLDB_PLUGIN_DEFINE(JITLoaderGDB) // Debug Interface Structures enum jit_actions_t { JIT_NOACTION = 0, JIT_REGISTER_FN, JIT_UNREGISTER_FN }; template struct jit_code_entry { ptr_t next_entry; // pointer ptr_t prev_entry; // pointer ptr_t symfile_addr; // pointer uint64_t symfile_size; }; template struct jit_descriptor { uint32_t version; uint32_t action_flag; // Values are jit_action_t ptr_t relevant_entry; // pointer ptr_t first_entry; // pointer }; namespace { enum EnableJITLoaderGDB { eEnableJITLoaderGDBDefault, eEnableJITLoaderGDBOn, eEnableJITLoaderGDBOff, }; 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", }, }; #define LLDB_PROPERTIES_jitloadergdb #include "JITLoaderGDBProperties.inc" enum { #define LLDB_PROPERTIES_jitloadergdb #include "JITLoaderGDBPropertiesEnum.inc" ePropertyEnableJITBreakpoint }; class PluginProperties : public Properties { public: static ConstString GetSettingName() { return JITLoaderGDB::GetPluginNameStatic(); } PluginProperties() { m_collection_sp = std::make_shared(GetSettingName()); m_collection_sp->Initialize(g_jitloadergdb_properties); } EnableJITLoaderGDB GetEnable() const { return (EnableJITLoaderGDB)m_collection_sp->GetPropertyAtIndexAsEnumeration( nullptr, ePropertyEnable, g_jitloadergdb_properties[ePropertyEnable].default_uint_value); } }; typedef std::shared_ptr JITLoaderGDBPropertiesSP; static const JITLoaderGDBPropertiesSP &GetGlobalPluginProperties() { static const auto g_settings_sp(std::make_shared()); return g_settings_sp; } template bool ReadJITEntry(const addr_t from_addr, Process *process, jit_code_entry *entry) { lldbassert(from_addr % sizeof(ptr_t) == 0); ArchSpec::Core core = process->GetTarget().GetArchitecture().GetCore(); bool i386_target = ArchSpec::kCore_x86_32_first <= core && core <= ArchSpec::kCore_x86_32_last; uint8_t uint64_align_bytes = i386_target ? 4 : 8; const size_t data_byte_size = llvm::alignTo(sizeof(ptr_t) * 3, uint64_align_bytes) + sizeof(uint64_t); Status error; DataBufferHeap data(data_byte_size, 0); size_t bytes_read = process->ReadMemory(from_addr, data.GetBytes(), data.GetByteSize(), error); if (bytes_read != data_byte_size || !error.Success()) return false; DataExtractor extractor(data.GetBytes(), data.GetByteSize(), process->GetByteOrder(), sizeof(ptr_t)); lldb::offset_t offset = 0; entry->next_entry = extractor.GetAddress(&offset); entry->prev_entry = extractor.GetAddress(&offset); entry->symfile_addr = extractor.GetAddress(&offset); offset = llvm::alignTo(offset, uint64_align_bytes); entry->symfile_size = extractor.GetU64(&offset); return true; } } // anonymous namespace end JITLoaderGDB::JITLoaderGDB(lldb_private::Process *process) : JITLoader(process), m_jit_objects(), m_jit_break_id(LLDB_INVALID_BREAK_ID), m_jit_descriptor_addr(LLDB_INVALID_ADDRESS) {} JITLoaderGDB::~JITLoaderGDB() { if (LLDB_BREAK_ID_IS_VALID(m_jit_break_id)) m_process->GetTarget().RemoveBreakpointByID(m_jit_break_id); } void JITLoaderGDB::DebuggerInitialize(Debugger &debugger) { if (!PluginManager::GetSettingForJITLoaderPlugin( debugger, PluginProperties::GetSettingName())) { const bool is_global_setting = true; PluginManager::CreateSettingForJITLoaderPlugin( debugger, GetGlobalPluginProperties()->GetValueProperties(), ConstString("Properties for the JIT LoaderGDB plug-in."), is_global_setting); } } void JITLoaderGDB::DidAttach() { Target &target = m_process->GetTarget(); ModuleList &module_list = target.GetImages(); SetJITBreakpoint(module_list); } void JITLoaderGDB::DidLaunch() { Target &target = m_process->GetTarget(); ModuleList &module_list = target.GetImages(); SetJITBreakpoint(module_list); } void JITLoaderGDB::ModulesDidLoad(ModuleList &module_list) { if (!DidSetJITBreakpoint() && m_process->IsAlive()) SetJITBreakpoint(module_list); } // Setup the JIT Breakpoint void JITLoaderGDB::SetJITBreakpoint(lldb_private::ModuleList &module_list) { if (DidSetJITBreakpoint()) return; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER)); LLDB_LOGF(log, "JITLoaderGDB::%s looking for JIT register hook", __FUNCTION__); addr_t jit_addr = GetSymbolAddress( module_list, ConstString("__jit_debug_register_code"), eSymbolTypeAny); if (jit_addr == LLDB_INVALID_ADDRESS) return; m_jit_descriptor_addr = GetSymbolAddress( module_list, ConstString("__jit_debug_descriptor"), eSymbolTypeData); if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS) { LLDB_LOGF(log, "JITLoaderGDB::%s failed to find JIT descriptor address", __FUNCTION__); return; } LLDB_LOGF(log, "JITLoaderGDB::%s setting JIT breakpoint", __FUNCTION__); Breakpoint *bp = m_process->GetTarget().CreateBreakpoint(jit_addr, true, false).get(); bp->SetCallback(JITDebugBreakpointHit, this, true); bp->SetBreakpointKind("jit-debug-register"); m_jit_break_id = bp->GetID(); ReadJITDescriptor(true); } bool JITLoaderGDB::JITDebugBreakpointHit(void *baton, StoppointCallbackContext *context, user_id_t break_id, user_id_t break_loc_id) { Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER)); LLDB_LOGF(log, "JITLoaderGDB::%s hit JIT breakpoint", __FUNCTION__); JITLoaderGDB *instance = static_cast(baton); return instance->ReadJITDescriptor(false); } static void updateSectionLoadAddress(const SectionList §ion_list, Target &target, uint64_t symbolfile_addr, uint64_t symbolfile_size, uint64_t &vmaddrheuristic, uint64_t &min_addr, uint64_t &max_addr) { const uint32_t num_sections = section_list.GetSize(); for (uint32_t i = 0; i < num_sections; ++i) { SectionSP section_sp(section_list.GetSectionAtIndex(i)); if (section_sp) { if (section_sp->IsFake()) { uint64_t lower = (uint64_t)-1; uint64_t upper = 0; updateSectionLoadAddress(section_sp->GetChildren(), target, symbolfile_addr, symbolfile_size, vmaddrheuristic, lower, upper); if (lower < min_addr) min_addr = lower; if (upper > max_addr) max_addr = upper; const lldb::addr_t slide_amount = lower - section_sp->GetFileAddress(); section_sp->Slide(slide_amount, false); section_sp->GetChildren().Slide(-slide_amount, false); section_sp->SetByteSize(upper - lower); } else { vmaddrheuristic += 2 << section_sp->GetLog2Align(); uint64_t lower; if (section_sp->GetFileAddress() > vmaddrheuristic) lower = section_sp->GetFileAddress(); else { lower = symbolfile_addr + section_sp->GetFileOffset(); section_sp->SetFileAddress(symbolfile_addr + section_sp->GetFileOffset()); } target.SetSectionLoadAddress(section_sp, lower, true); uint64_t upper = lower + section_sp->GetByteSize(); if (lower < min_addr) min_addr = lower; if (upper > max_addr) max_addr = upper; // This is an upper bound, but a good enough heuristic vmaddrheuristic += section_sp->GetByteSize(); } } } } bool JITLoaderGDB::ReadJITDescriptor(bool all_entries) { if (m_process->GetTarget().GetArchitecture().GetAddressByteSize() == 8) return ReadJITDescriptorImpl(all_entries); else return ReadJITDescriptorImpl(all_entries); } template bool JITLoaderGDB::ReadJITDescriptorImpl(bool all_entries) { if (m_jit_descriptor_addr == LLDB_INVALID_ADDRESS) return false; Log *log(GetLogIfAnyCategoriesSet(LIBLLDB_LOG_JIT_LOADER)); Target &target = m_process->GetTarget(); ModuleList &module_list = target.GetImages(); jit_descriptor jit_desc; const size_t jit_desc_size = sizeof(jit_desc); Status error; size_t bytes_read = m_process->DoReadMemory(m_jit_descriptor_addr, &jit_desc, jit_desc_size, error); if (bytes_read != jit_desc_size || !error.Success()) { LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT descriptor", __FUNCTION__); return false; } jit_actions_t jit_action = (jit_actions_t)jit_desc.action_flag; addr_t jit_relevant_entry = (addr_t)jit_desc.relevant_entry; if (all_entries) { jit_action = JIT_REGISTER_FN; jit_relevant_entry = (addr_t)jit_desc.first_entry; } while (jit_relevant_entry != 0) { jit_code_entry jit_entry; if (!ReadJITEntry(jit_relevant_entry, m_process, &jit_entry)) { LLDB_LOGF(log, "JITLoaderGDB::%s failed to read JIT entry at 0x%" PRIx64, __FUNCTION__, jit_relevant_entry); return false; } const addr_t &symbolfile_addr = (addr_t)jit_entry.symfile_addr; const size_t &symbolfile_size = (size_t)jit_entry.symfile_size; ModuleSP module_sp; if (jit_action == JIT_REGISTER_FN) { LLDB_LOGF(log, "JITLoaderGDB::%s registering JIT entry at 0x%" PRIx64 " (%" PRIu64 " bytes)", __FUNCTION__, symbolfile_addr, (uint64_t)symbolfile_size); char jit_name[64]; snprintf(jit_name, 64, "JIT(0x%" PRIx64 ")", symbolfile_addr); module_sp = m_process->ReadModuleFromMemory( 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(); m_jit_objects.insert(std::make_pair(symbolfile_addr, module_sp)); +#ifdef LLDB_ENABLE_ALL if (auto image_object_file = llvm::dyn_cast(module_sp->GetObjectFile())) { const SectionList *section_list = image_object_file->GetSectionList(); if (section_list) { uint64_t vmaddrheuristic = 0; uint64_t lower = (uint64_t)-1; uint64_t upper = 0; updateSectionLoadAddress(*section_list, target, symbolfile_addr, symbolfile_size, vmaddrheuristic, lower, upper); } - } else { + } else +#endif // LLDB_ENABLE_ALL + { bool changed = false; module_sp->SetLoadAddress(target, 0, true, changed); } module_list.AppendIfNeeded(module_sp); ModuleList module_list; module_list.Append(module_sp); target.ModulesDidLoad(module_list); } else { LLDB_LOGF(log, "JITLoaderGDB::%s failed to load module for " "JIT entry at 0x%" PRIx64, __FUNCTION__, symbolfile_addr); } } else if (jit_action == JIT_UNREGISTER_FN) { LLDB_LOGF(log, "JITLoaderGDB::%s unregistering JIT entry at 0x%" PRIx64, __FUNCTION__, symbolfile_addr); JITObjectMap::iterator it = m_jit_objects.find(symbolfile_addr); if (it != m_jit_objects.end()) { module_sp = it->second; ObjectFile *image_object_file = module_sp->GetObjectFile(); if (image_object_file) { const SectionList *section_list = image_object_file->GetSectionList(); if (section_list) { const uint32_t num_sections = section_list->GetSize(); for (uint32_t i = 0; i < num_sections; ++i) { SectionSP section_sp(section_list->GetSectionAtIndex(i)); if (section_sp) { target.GetSectionLoadList().SetSectionUnloaded(section_sp); } } } } module_list.Remove(module_sp); m_jit_objects.erase(it); } } else if (jit_action == JIT_NOACTION) { // Nothing to do } else { assert(false && "Unknown jit action"); } if (all_entries) jit_relevant_entry = (addr_t)jit_entry.next_entry; else jit_relevant_entry = 0; } return false; // Continue Running. } // PluginInterface protocol lldb_private::ConstString JITLoaderGDB::GetPluginNameStatic() { static ConstString g_name("gdb"); return g_name; } JITLoaderSP JITLoaderGDB::CreateInstance(Process *process, bool force) { JITLoaderSP jit_loader_sp; 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(process); return jit_loader_sp; } const char *JITLoaderGDB::GetPluginDescriptionStatic() { return "JIT loader plug-in that watches for JIT events using the GDB " "interface."; } lldb_private::ConstString JITLoaderGDB::GetPluginName() { return GetPluginNameStatic(); } uint32_t JITLoaderGDB::GetPluginVersion() { return 1; } void JITLoaderGDB::Initialize() { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance, DebuggerInitialize); } void JITLoaderGDB::Terminate() { PluginManager::UnregisterPlugin(CreateInstance); } bool JITLoaderGDB::DidSetJITBreakpoint() const { return LLDB_BREAK_ID_IS_VALID(m_jit_break_id); } addr_t JITLoaderGDB::GetSymbolAddress(ModuleList &module_list, ConstString name, SymbolType symbol_type) const { SymbolContextList target_symbols; Target &target = m_process->GetTarget(); module_list.FindSymbolsWithNameAndType(name, symbol_type, target_symbols); if (target_symbols.IsEmpty()) return LLDB_INVALID_ADDRESS; SymbolContext sym_ctx; target_symbols.GetContextAtIndex(0, sym_ctx); const Address jit_descriptor_addr = sym_ctx.symbol->GetAddress(); if (!jit_descriptor_addr.IsValid()) return LLDB_INVALID_ADDRESS; const addr_t jit_addr = jit_descriptor_addr.GetLoadAddress(&target); return jit_addr; } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/elf-core/ThreadElfCore.cpp (revision 363961) @@ -1,428 +1,436 @@ //===-- ThreadElfCore.cpp -------------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Target/RegisterContext.h" #include "lldb/Target/StopInfo.h" #include "lldb/Target/Target.h" #include "lldb/Target/Unwind.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Log.h" #include "Plugins/Process/Utility/RegisterContextFreeBSD_i386.h" #include "Plugins/Process/Utility/RegisterContextFreeBSD_mips64.h" #include "Plugins/Process/Utility/RegisterContextFreeBSD_powerpc.h" #include "Plugins/Process/Utility/RegisterContextFreeBSD_x86_64.h" #include "Plugins/Process/Utility/RegisterContextLinux_i386.h" #include "Plugins/Process/Utility/RegisterContextLinux_mips.h" #include "Plugins/Process/Utility/RegisterContextLinux_mips64.h" +#ifdef LLDB_ENABLE_ALL #include "Plugins/Process/Utility/RegisterContextLinux_s390x.h" +#endif // LLDB_ENABLE_ALL #include "Plugins/Process/Utility/RegisterContextLinux_x86_64.h" #include "Plugins/Process/Utility/RegisterContextNetBSD_x86_64.h" #include "Plugins/Process/Utility/RegisterContextOpenBSD_i386.h" #include "Plugins/Process/Utility/RegisterContextOpenBSD_x86_64.h" #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm.h" #include "Plugins/Process/Utility/RegisterInfoPOSIX_arm64.h" #include "Plugins/Process/Utility/RegisterInfoPOSIX_ppc64le.h" #include "ProcessElfCore.h" #include "RegisterContextPOSIXCore_arm.h" #include "RegisterContextPOSIXCore_arm64.h" #include "RegisterContextPOSIXCore_mips64.h" #include "RegisterContextPOSIXCore_powerpc.h" #include "RegisterContextPOSIXCore_ppc64le.h" +#ifdef LLDB_ENABLE_ALL #include "RegisterContextPOSIXCore_s390x.h" +#endif // LLDB_ENABLE_ALL #include "RegisterContextPOSIXCore_x86_64.h" #include "ThreadElfCore.h" #include 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) {} ThreadElfCore::~ThreadElfCore() { DestroyThread(); } void ThreadElfCore::RefreshStateAfterStop() { GetRegisterContext()->InvalidateIfNeeded(false); } RegisterContextSP ThreadElfCore::GetRegisterContext() { if (!m_reg_context_sp) { m_reg_context_sp = CreateRegisterContextForFrame(nullptr); } return m_reg_context_sp; } RegisterContextSP ThreadElfCore::CreateRegisterContextForFrame(StackFrame *frame) { RegisterContextSP reg_ctx_sp; uint32_t concrete_frame_idx = 0; Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_THREAD)); if (frame) concrete_frame_idx = frame->GetConcreteFrameIndex(); if (concrete_frame_idx == 0) { if (m_thread_reg_ctx_sp) return m_thread_reg_ctx_sp; ProcessElfCore *process = static_cast(GetProcess().get()); ArchSpec arch = process->GetArchitecture(); RegisterInfoInterface *reg_interface = nullptr; switch (arch.GetTriple().getOS()) { case llvm::Triple::FreeBSD: { switch (arch.GetMachine()) { case llvm::Triple::aarch64: break; case llvm::Triple::arm: reg_interface = new RegisterInfoPOSIX_arm(arch); break; case llvm::Triple::ppc: reg_interface = new RegisterContextFreeBSD_powerpc32(arch); break; case llvm::Triple::ppc64: reg_interface = new RegisterContextFreeBSD_powerpc64(arch); break; case llvm::Triple::mips64: reg_interface = new RegisterContextFreeBSD_mips64(arch); break; case llvm::Triple::x86: reg_interface = new RegisterContextFreeBSD_i386(arch); break; case llvm::Triple::x86_64: reg_interface = new RegisterContextFreeBSD_x86_64(arch); break; default: break; } break; } case llvm::Triple::NetBSD: { switch (arch.GetMachine()) { case llvm::Triple::aarch64: break; case llvm::Triple::x86_64: reg_interface = new RegisterContextNetBSD_x86_64(arch); break; default: break; } break; } case llvm::Triple::Linux: { switch (arch.GetMachine()) { case llvm::Triple::arm: reg_interface = new RegisterInfoPOSIX_arm(arch); break; case llvm::Triple::aarch64: break; case llvm::Triple::mipsel: case llvm::Triple::mips: reg_interface = new RegisterContextLinux_mips(arch); break; case llvm::Triple::mips64el: case llvm::Triple::mips64: reg_interface = new RegisterContextLinux_mips64(arch); break; case llvm::Triple::ppc64le: reg_interface = new RegisterInfoPOSIX_ppc64le(arch); break; +#ifdef LLDB_ENABLE_ALL case llvm::Triple::systemz: reg_interface = new RegisterContextLinux_s390x(arch); break; +#endif // LLDB_ENABLE_ALL case llvm::Triple::x86: reg_interface = new RegisterContextLinux_i386(arch); break; case llvm::Triple::x86_64: reg_interface = new RegisterContextLinux_x86_64(arch); break; default: break; } break; } case llvm::Triple::OpenBSD: { switch (arch.GetMachine()) { case llvm::Triple::aarch64: break; case llvm::Triple::arm: reg_interface = new RegisterInfoPOSIX_arm(arch); break; case llvm::Triple::x86: reg_interface = new RegisterContextOpenBSD_i386(arch); break; case llvm::Triple::x86_64: reg_interface = new RegisterContextOpenBSD_x86_64(arch); break; default: break; } break; } default: break; } if (!reg_interface && arch.GetMachine() != llvm::Triple::aarch64) { LLDB_LOGF(log, "elf-core::%s:: Architecture(%d) or OS(%d) not supported", __FUNCTION__, arch.GetMachine(), arch.GetTriple().getOS()); assert(false && "Architecture or OS not supported"); } switch (arch.GetMachine()) { case llvm::Triple::aarch64: m_thread_reg_ctx_sp = std::make_shared( *this, std::make_unique(arch), m_gpregset_data, m_notes); break; case llvm::Triple::arm: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::mipsel: case llvm::Triple::mips: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::mips64: case llvm::Triple::mips64el: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::ppc: case llvm::Triple::ppc64: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; case llvm::Triple::ppc64le: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; +#ifdef LLDB_ENABLE_ALL case llvm::Triple::systemz: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; +#endif // LLDB_ENABLE_ALL case llvm::Triple::x86: case llvm::Triple::x86_64: m_thread_reg_ctx_sp = std::make_shared( *this, reg_interface, m_gpregset_data, m_notes); break; default: break; } reg_ctx_sp = m_thread_reg_ctx_sp; } else { reg_ctx_sp = GetUnwinder().CreateRegisterContextForFrame(frame); } return reg_ctx_sp; } bool ThreadElfCore::CalculateStopInfo() { ProcessSP process_sp(GetProcess()); if (process_sp) { SetStopInfo(StopInfo::CreateStopReasonWithSignal(*this, m_signo)); return true; } return false; } // Parse PRSTATUS from NOTE entry ELFLinuxPrStatus::ELFLinuxPrStatus() { memset(this, 0, sizeof(ELFLinuxPrStatus)); } 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"); if (!abi.compare("n64")) return sizeof(ELFLinuxPrStatus); else if (!abi.compare("o32")) return mips_linux_pr_status_size_o32; // N32 ABI return mips_linux_pr_status_size_n32; } switch (arch.GetCore()) { case lldb_private::ArchSpec::eCore_x86_32_i386: case lldb_private::ArchSpec::eCore_x86_32_i486: return 72; default: if (arch.GetAddressByteSize() == 8) return sizeof(ELFLinuxPrStatus); else return sizeof(ELFLinuxPrStatus) - num_ptr_size_members * 4; } } Status ELFLinuxPrStatus::Parse(const DataExtractor &data, const ArchSpec &arch) { Status error; if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( "NT_PRSTATUS size should be %zu, but the remaining bytes are: %" PRIu64, GetSize(arch), data.GetByteSize()); return error; } // Read field by field to correctly account for endianess of both the core // dump and the platform running lldb. offset_t offset = 0; si_signo = data.GetU32(&offset); si_code = data.GetU32(&offset); si_errno = data.GetU32(&offset); pr_cursig = data.GetU16(&offset); offset += 2; // pad pr_sigpend = data.GetAddress(&offset); pr_sighold = data.GetAddress(&offset); pr_pid = data.GetU32(&offset); pr_ppid = data.GetU32(&offset); pr_pgrp = data.GetU32(&offset); pr_sid = data.GetU32(&offset); pr_utime.tv_sec = data.GetAddress(&offset); pr_utime.tv_usec = data.GetAddress(&offset); pr_stime.tv_sec = data.GetAddress(&offset); pr_stime.tv_usec = data.GetAddress(&offset); pr_cutime.tv_sec = data.GetAddress(&offset); pr_cutime.tv_usec = data.GetAddress(&offset); pr_cstime.tv_sec = data.GetAddress(&offset); pr_cstime.tv_usec = data.GetAddress(&offset); return error; } // Parse PRPSINFO from NOTE entry ELFLinuxPrPsInfo::ELFLinuxPrPsInfo() { memset(this, 0, sizeof(ELFLinuxPrPsInfo)); } size_t ELFLinuxPrPsInfo::GetSize(const lldb_private::ArchSpec &arch) { constexpr size_t mips_linux_pr_psinfo_size_o32_n32 = 128; if (arch.IsMIPS()) { uint8_t address_byte_size = arch.GetAddressByteSize(); if (address_byte_size == 8) return sizeof(ELFLinuxPrPsInfo); return mips_linux_pr_psinfo_size_o32_n32; } switch (arch.GetCore()) { case lldb_private::ArchSpec::eCore_s390x_generic: case lldb_private::ArchSpec::eCore_x86_64_x86_64: return sizeof(ELFLinuxPrPsInfo); case lldb_private::ArchSpec::eCore_x86_32_i386: case lldb_private::ArchSpec::eCore_x86_32_i486: return 124; default: return 0; } } Status ELFLinuxPrPsInfo::Parse(const DataExtractor &data, const ArchSpec &arch) { Status error; ByteOrder byteorder = data.GetByteOrder(); if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( "NT_PRPSINFO size should be %zu, but the remaining bytes are: %" PRIu64, GetSize(arch), data.GetByteSize()); return error; } size_t size = 0; offset_t offset = 0; pr_state = data.GetU8(&offset); pr_sname = data.GetU8(&offset); pr_zomb = data.GetU8(&offset); pr_nice = data.GetU8(&offset); if (data.GetAddressByteSize() == 8) { // Word align the next field on 64 bit. offset += 4; } pr_flag = data.GetAddress(&offset); if (arch.IsMIPS()) { // The pr_uid and pr_gid is always 32 bit irrespective of platforms pr_uid = data.GetU32(&offset); pr_gid = data.GetU32(&offset); } else { // 16 bit on 32 bit platforms, 32 bit on 64 bit platforms pr_uid = data.GetMaxU64(&offset, data.GetAddressByteSize() >> 1); pr_gid = data.GetMaxU64(&offset, data.GetAddressByteSize() >> 1); } pr_pid = data.GetU32(&offset); pr_ppid = data.GetU32(&offset); pr_pgrp = data.GetU32(&offset); pr_sid = data.GetU32(&offset); size = 16; data.ExtractBytes(offset, size, byteorder, pr_fname); offset += size; size = 80; data.ExtractBytes(offset, size, byteorder, pr_psargs); offset += size; return error; } // Parse SIGINFO from NOTE entry ELFLinuxSigInfo::ELFLinuxSigInfo() { memset(this, 0, sizeof(ELFLinuxSigInfo)); } size_t ELFLinuxSigInfo::GetSize(const lldb_private::ArchSpec &arch) { if (arch.IsMIPS()) return sizeof(ELFLinuxSigInfo); switch (arch.GetCore()) { case lldb_private::ArchSpec::eCore_x86_64_x86_64: return sizeof(ELFLinuxSigInfo); case lldb_private::ArchSpec::eCore_s390x_generic: case lldb_private::ArchSpec::eCore_x86_32_i386: case lldb_private::ArchSpec::eCore_x86_32_i486: return 12; default: return 0; } } Status ELFLinuxSigInfo::Parse(const DataExtractor &data, const ArchSpec &arch) { Status error; if (GetSize(arch) > data.GetByteSize()) { error.SetErrorStringWithFormat( "NT_SIGINFO size should be %zu, but the remaining bytes are: %" PRIu64, GetSize(arch), data.GetByteSize()); return error; } // Parsing from a 32 bit ELF core file, and populating/reusing the structure // properly, because the struct is for the 64 bit version offset_t offset = 0; si_signo = data.GetU32(&offset); si_code = data.GetU32(&offset); si_errno = data.GetU32(&offset); return error; } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/Process/gdb-remote/ProcessGDBRemote.cpp (revision 363961) @@ -1,5382 +1,5386 @@ //===-- ProcessGDBRemote.cpp ----------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "lldb/Host/Config.h" #include #include #if LLDB_ENABLE_POSIX #include #include #include #include #endif #include #if defined(__APPLE__) #include #endif #include #include #include #include #include #include #include #include #include "lldb/Breakpoint/Watchpoint.h" #include "lldb/Core/Debugger.h" #include "lldb/Core/Module.h" #include "lldb/Core/ModuleSpec.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/Value.h" #include "lldb/DataFormatters/FormatManager.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/FileSystem.h" #include "lldb/Host/HostThread.h" #include "lldb/Host/PosixApi.h" #include "lldb/Host/PseudoTerminal.h" #include "lldb/Host/StringConvert.h" #include "lldb/Host/ThreadLauncher.h" #include "lldb/Host/XML.h" #include "lldb/Interpreter/CommandInterpreter.h" #include "lldb/Interpreter/CommandObject.h" #include "lldb/Interpreter/CommandObjectMultiword.h" #include "lldb/Interpreter/CommandReturnObject.h" #include "lldb/Interpreter/OptionArgParser.h" #include "lldb/Interpreter/OptionGroupBoolean.h" #include "lldb/Interpreter/OptionGroupUInt64.h" #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" #include "lldb/Target/MemoryRegionInfo.h" #include "lldb/Target/SystemRuntime.h" #include "lldb/Target/Target.h" #include "lldb/Target/TargetList.h" #include "lldb/Target/ThreadPlanCallFunction.h" #include "lldb/Utility/Args.h" #include "lldb/Utility/FileSpec.h" #include "lldb/Utility/Reproducer.h" #include "lldb/Utility/State.h" #include "lldb/Utility/StreamString.h" #include "lldb/Utility/Timer.h" #include "GDBRemoteRegisterContext.h" +#ifdef LLDB_ENABLE_ALL #include "Plugins/Platform/MacOSX/PlatformRemoteiOS.h" +#endif // LLDB_ENABLE_ALL #include "Plugins/Process/Utility/GDBRemoteSignals.h" #include "Plugins/Process/Utility/InferiorCallPOSIX.h" #include "Plugins/Process/Utility/StopInfoMachException.h" #include "ProcessGDBRemote.h" #include "ProcessGDBRemoteLog.h" #include "ThreadGDBRemote.h" #include "lldb/Host/Host.h" #include "lldb/Utility/StringExtractorGDBRemote.h" #include "llvm/ADT/ScopeExit.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/Support/Threading.h" #include "llvm/Support/raw_ostream.h" #define DEBUGSERVER_BASENAME "debugserver" using namespace lldb; using namespace lldb_private; using namespace lldb_private::process_gdb_remote; LLDB_PLUGIN_DEFINE(ProcessGDBRemote) namespace lldb { // Provide a function that can easily dump the packet history if we know a // ProcessGDBRemote * value (which we can get from logs or from debugging). We // need the function in the lldb namespace so it makes it into the final // executable since the LLDB shared library only exports stuff in the lldb // namespace. This allows you to attach with a debugger and call this function // and get the packet history dumped to a file. void DumpProcessGDBRemotePacketHistory(void *p, const char *path) { auto file = FileSystem::Instance().Open( FileSpec(path), File::eOpenOptionWrite | File::eOpenOptionCanCreate); if (!file) { llvm::consumeError(file.takeError()); return; } StreamFile stream(std::move(file.get())); ((ProcessGDBRemote *)p)->GetGDBRemote().DumpHistory(stream); } } // namespace lldb namespace { #define LLDB_PROPERTIES_processgdbremote #include "ProcessGDBRemoteProperties.inc" enum { #define LLDB_PROPERTIES_processgdbremote #include "ProcessGDBRemotePropertiesEnum.inc" }; class PluginProperties : public Properties { public: static ConstString GetSettingName() { return ProcessGDBRemote::GetPluginNameStatic(); } PluginProperties() : Properties() { m_collection_sp = std::make_shared(GetSettingName()); m_collection_sp->Initialize(g_processgdbremote_properties); } ~PluginProperties() override {} uint64_t GetPacketTimeout() { const uint32_t idx = ePropertyPacketTimeout; return m_collection_sp->GetPropertyAtIndexAsUInt64( nullptr, idx, g_processgdbremote_properties[idx].default_uint_value); } bool SetPacketTimeout(uint64_t timeout) { const uint32_t idx = ePropertyPacketTimeout; return m_collection_sp->SetPropertyAtIndexAsUInt64(nullptr, idx, timeout); } FileSpec GetTargetDefinitionFile() const { const uint32_t idx = ePropertyTargetDefinitionFile; return m_collection_sp->GetPropertyAtIndexAsFileSpec(nullptr, idx); } bool GetUseSVR4() const { const uint32_t idx = ePropertyUseSVR4; return m_collection_sp->GetPropertyAtIndexAsBoolean( nullptr, idx, g_processgdbremote_properties[idx].default_uint_value != 0); } bool GetUseGPacketForReading() const { const uint32_t idx = ePropertyUseGPacketForReading; return m_collection_sp->GetPropertyAtIndexAsBoolean(nullptr, idx, true); } }; typedef std::shared_ptr ProcessKDPPropertiesSP; static const ProcessKDPPropertiesSP &GetGlobalPluginProperties() { static ProcessKDPPropertiesSP g_settings_sp; if (!g_settings_sp) g_settings_sp = std::make_shared(); return g_settings_sp; } } // namespace // TODO Randomly assigning a port is unsafe. We should get an unused // ephemeral port from the kernel and make sure we reserve it before passing it // to debugserver. #if defined(__APPLE__) #define LOW_PORT (IPPORT_RESERVED) #define HIGH_PORT (IPPORT_HIFIRSTAUTO) #else #define LOW_PORT (1024u) #define HIGH_PORT (49151u) #endif ConstString ProcessGDBRemote::GetPluginNameStatic() { static ConstString g_name("gdb-remote"); return g_name; } const char *ProcessGDBRemote::GetPluginDescriptionStatic() { return "GDB Remote protocol based debugging plug-in."; } void ProcessGDBRemote::Terminate() { PluginManager::UnregisterPlugin(ProcessGDBRemote::CreateInstance); } lldb::ProcessSP ProcessGDBRemote::CreateInstance(lldb::TargetSP target_sp, ListenerSP listener_sp, const FileSpec *crash_file_path) { lldb::ProcessSP process_sp; if (crash_file_path == nullptr) process_sp = std::make_shared(target_sp, listener_sp); return process_sp; } bool ProcessGDBRemote::CanDebug(lldb::TargetSP target_sp, bool plugin_specified_by_name) { if (plugin_specified_by_name) return true; // For now we are just making sure the file exists for a given module Module *exe_module = target_sp->GetExecutableModulePointer(); if (exe_module) { ObjectFile *exe_objfile = exe_module->GetObjectFile(); // We can't debug core files... switch (exe_objfile->GetType()) { case ObjectFile::eTypeInvalid: case ObjectFile::eTypeCoreFile: case ObjectFile::eTypeDebugInfo: case ObjectFile::eTypeObjectFile: case ObjectFile::eTypeSharedLibrary: case ObjectFile::eTypeStubLibrary: case ObjectFile::eTypeJIT: return false; case ObjectFile::eTypeExecutable: case ObjectFile::eTypeDynamicLinker: case ObjectFile::eTypeUnknown: break; } return FileSystem::Instance().Exists(exe_module->GetFileSpec()); } // However, if there is no executable module, we return true since we might // be preparing to attach. 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(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(), m_jstopinfo_sp(), m_jthreadsinfo_sp(), m_continue_c_tids(), m_continue_C_tids(), m_continue_s_tids(), m_continue_S_tids(), m_max_memory_size(0), m_remote_stub_max_memory_size(0), m_addr_to_mmap_size(), m_thread_create_bp_sp(), m_waiting_for_attach(false), m_destroy_tried_resuming(false), m_command_sp(), m_breakpoint_pc_offset(0), m_initial_tid(LLDB_INVALID_THREAD_ID), m_replay_mode(false), m_allow_flash_writes(false), m_erased_flash_ranges() { m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadShouldExit, "async thread should exit"); m_async_broadcaster.SetEventName(eBroadcastBitAsyncContinue, "async thread continue"); m_async_broadcaster.SetEventName(eBroadcastBitAsyncThreadDidExit, "async thread did exit"); if (repro::Generator *g = repro::Reproducer::Instance().GetGenerator()) { repro::GDBRemoteProvider &provider = g->GetOrCreate(); m_gdb_comm.SetPacketRecorder(provider.GetNewPacketRecorder()); } Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_ASYNC)); const uint32_t async_event_mask = eBroadcastBitAsyncContinue | eBroadcastBitAsyncThreadShouldExit; if (m_async_listener_sp->StartListeningForEvents( &m_async_broadcaster, async_event_mask) != async_event_mask) { LLDB_LOGF(log, "ProcessGDBRemote::%s failed to listen for " "m_async_broadcaster events", __FUNCTION__); } const uint32_t gdb_event_mask = Communication::eBroadcastBitReadThreadDidExit | GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify; if (m_async_listener_sp->StartListeningForEvents( &m_gdb_comm, gdb_event_mask) != gdb_event_mask) { LLDB_LOGF(log, "ProcessGDBRemote::%s failed to listen for m_gdb_comm events", __FUNCTION__); } const uint64_t timeout_seconds = GetGlobalPluginProperties()->GetPacketTimeout(); if (timeout_seconds > 0) m_gdb_comm.SetPacketTimeout(std::chrono::seconds(timeout_seconds)); m_use_g_packet_for_reading = GetGlobalPluginProperties()->GetUseGPacketForReading(); } // Destructor ProcessGDBRemote::~ProcessGDBRemote() { // m_mach_process.UnregisterNotificationCallbacks (this); Clear(); // We need to call finalize on the process before destroying ourselves to // make sure all of the broadcaster cleanup goes as planned. If we destruct // this class, then Process::~Process() might have problems trying to fully // destroy the broadcaster. Finalize(); // The general Finalize is going to try to destroy the process and that // SHOULD shut down the async thread. However, if we don't kill it it will // get stranded and its connection will go away so when it wakes up it will // crash. So kill it for sure here. StopAsyncThread(); KillDebugserverProcess(); } // PluginInterface ConstString ProcessGDBRemote::GetPluginName() { return GetPluginNameStatic(); } uint32_t ProcessGDBRemote::GetPluginVersion() { return 1; } bool ProcessGDBRemote::ParsePythonTargetDefinition( const FileSpec &target_definition_fspec) { ScriptInterpreter *interpreter = GetTarget().GetDebugger().GetScriptInterpreter(); Status error; StructuredData::ObjectSP module_object_sp( interpreter->LoadPluginModule(target_definition_fspec, error)); if (module_object_sp) { StructuredData::DictionarySP target_definition_sp( interpreter->GetDynamicSettings(module_object_sp, &GetTarget(), "gdb-server-target-definition", error)); if (target_definition_sp) { StructuredData::ObjectSP target_object( target_definition_sp->GetValueForKey("host-info")); if (target_object) { if (auto host_info_dict = target_object->GetAsDictionary()) { StructuredData::ObjectSP triple_value = host_info_dict->GetValueForKey("triple"); if (auto triple_string_value = triple_value->GetAsString()) { std::string triple_string = std::string(triple_string_value->GetValue()); ArchSpec host_arch(triple_string.c_str()); if (!host_arch.IsCompatibleMatch(GetTarget().GetArchitecture())) { GetTarget().SetArchitecture(host_arch); } } } } m_breakpoint_pc_offset = 0; StructuredData::ObjectSP breakpoint_pc_offset_value = target_definition_sp->GetValueForKey("breakpoint-pc-offset"); if (breakpoint_pc_offset_value) { if (auto breakpoint_pc_int_value = breakpoint_pc_offset_value->GetAsInteger()) m_breakpoint_pc_offset = breakpoint_pc_int_value->GetValue(); } if (m_register_info.SetRegisterInfo(*target_definition_sp, GetTarget().GetArchitecture()) > 0) { return true; } } } return false; } static size_t SplitCommaSeparatedRegisterNumberString( const llvm::StringRef &comma_separated_regiter_numbers, std::vector ®nums, int base) { regnums.clear(); std::pair value_pair; value_pair.second = comma_separated_regiter_numbers; do { value_pair = value_pair.second.split(','); if (!value_pair.first.empty()) { uint32_t reg = StringConvert::ToUInt32(value_pair.first.str().c_str(), LLDB_INVALID_REGNUM, base); if (reg != LLDB_INVALID_REGNUM) regnums.push_back(reg); } } while (!value_pair.second.empty()); return regnums.size(); } void ProcessGDBRemote::BuildDynamicRegisterInfo(bool force) { if (!force && m_register_info.GetNumRegisters() > 0) return; m_register_info.Clear(); // Check if qHostInfo specified a specific packet timeout for this // connection. If so then lets update our setting so the user knows what the // timeout is and can see it. const auto host_packet_timeout = m_gdb_comm.GetHostDefaultPacketTimeout(); if (host_packet_timeout > std::chrono::seconds(0)) { GetGlobalPluginProperties()->SetPacketTimeout(host_packet_timeout.count()); } // Register info search order: // 1 - Use the target definition python file if one is specified. // 2 - If the target definition doesn't have any of the info from the // target.xml (registers) then proceed to read the target.xml. // 3 - Fall back on the qRegisterInfo packets. FileSpec target_definition_fspec = GetGlobalPluginProperties()->GetTargetDefinitionFile(); if (!FileSystem::Instance().Exists(target_definition_fspec)) { // If the filename doesn't exist, it may be a ~ not having been expanded - // try to resolve it. FileSystem::Instance().Resolve(target_definition_fspec); } if (target_definition_fspec) { // See if we can get register definitions from a python file if (ParsePythonTargetDefinition(target_definition_fspec)) { return; } else { StreamSP stream_sp = GetTarget().GetDebugger().GetAsyncOutputStream(); stream_sp->Printf("ERROR: target description file %s failed to parse.\n", target_definition_fspec.GetPath().c_str()); } } const ArchSpec &target_arch = GetTarget().GetArchitecture(); const ArchSpec &remote_host_arch = m_gdb_comm.GetHostArchitecture(); const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); // Use the process' architecture instead of the host arch, if available ArchSpec arch_to_use; if (remote_process_arch.IsValid()) arch_to_use = remote_process_arch; else arch_to_use = remote_host_arch; if (!arch_to_use.IsValid()) arch_to_use = target_arch; if (GetGDBServerRegisterInfo(arch_to_use)) return; char packet[128]; uint32_t reg_offset = 0; uint32_t reg_num = 0; for (StringExtractorGDBRemote::ResponseType response_type = StringExtractorGDBRemote::eResponse; response_type == StringExtractorGDBRemote::eResponse; ++reg_num) { const int packet_len = ::snprintf(packet, sizeof(packet), "qRegisterInfo%x", reg_num); assert(packet_len < (int)sizeof(packet)); UNUSED_IF_ASSERT_DISABLED(packet_len); StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, false) == GDBRemoteCommunication::PacketResult::Success) { response_type = response.GetResponseType(); if (response_type == StringExtractorGDBRemote::eResponse) { llvm::StringRef name; llvm::StringRef value; ConstString reg_name; ConstString alt_name; ConstString set_name; std::vector value_regs; std::vector invalidate_regs; std::vector dwarf_opcode_bytes; RegisterInfo reg_info = { nullptr, // Name nullptr, // Alt name 0, // byte size reg_offset, // offset eEncodingUint, // encoding eFormatHex, // format { LLDB_INVALID_REGNUM, // eh_frame reg num LLDB_INVALID_REGNUM, // DWARF reg num LLDB_INVALID_REGNUM, // generic reg num reg_num, // process plugin reg num reg_num // native register number }, nullptr, nullptr, nullptr, // Dwarf expression opcode bytes pointer 0 // Dwarf expression opcode bytes length }; while (response.GetNameColonValue(name, value)) { if (name.equals("name")) { reg_name.SetString(value); } else if (name.equals("alt-name")) { alt_name.SetString(value); } else if (name.equals("bitsize")) { value.getAsInteger(0, reg_info.byte_size); reg_info.byte_size /= CHAR_BIT; } else if (name.equals("offset")) { if (value.getAsInteger(0, reg_offset)) reg_offset = UINT32_MAX; } else if (name.equals("encoding")) { const Encoding encoding = Args::StringToEncoding(value); if (encoding != eEncodingInvalid) reg_info.encoding = encoding; } else if (name.equals("format")) { Format format = eFormatInvalid; if (OptionArgParser::ToFormat(value.str().c_str(), format, nullptr) .Success()) reg_info.format = format; else { reg_info.format = llvm::StringSwitch(value) .Case("binary", eFormatBinary) .Case("decimal", eFormatDecimal) .Case("hex", eFormatHex) .Case("float", eFormatFloat) .Case("vector-sint8", eFormatVectorOfSInt8) .Case("vector-uint8", eFormatVectorOfUInt8) .Case("vector-sint16", eFormatVectorOfSInt16) .Case("vector-uint16", eFormatVectorOfUInt16) .Case("vector-sint32", eFormatVectorOfSInt32) .Case("vector-uint32", eFormatVectorOfUInt32) .Case("vector-float32", eFormatVectorOfFloat32) .Case("vector-uint64", eFormatVectorOfUInt64) .Case("vector-uint128", eFormatVectorOfUInt128) .Default(eFormatInvalid); } } else if (name.equals("set")) { set_name.SetString(value); } else if (name.equals("gcc") || name.equals("ehframe")) { if (value.getAsInteger(0, reg_info.kinds[eRegisterKindEHFrame])) reg_info.kinds[eRegisterKindEHFrame] = LLDB_INVALID_REGNUM; } else if (name.equals("dwarf")) { if (value.getAsInteger(0, reg_info.kinds[eRegisterKindDWARF])) reg_info.kinds[eRegisterKindDWARF] = LLDB_INVALID_REGNUM; } else if (name.equals("generic")) { reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value); } else if (name.equals("container-regs")) { SplitCommaSeparatedRegisterNumberString(value, value_regs, 16); } else if (name.equals("invalidate-regs")) { SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 16); } else if (name.equals("dynamic_size_dwarf_expr_bytes")) { size_t dwarf_opcode_len = value.size() / 2; assert(dwarf_opcode_len > 0); dwarf_opcode_bytes.resize(dwarf_opcode_len); reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; StringExtractor opcode_extractor(value); uint32_t ret_val = opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); assert(dwarf_opcode_len == ret_val); UNUSED_IF_ASSERT_DISABLED(ret_val); reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); } } reg_info.byte_offset = reg_offset; assert(reg_info.byte_size != 0); reg_offset += reg_info.byte_size; if (!value_regs.empty()) { value_regs.push_back(LLDB_INVALID_REGNUM); reg_info.value_regs = value_regs.data(); } if (!invalidate_regs.empty()) { invalidate_regs.push_back(LLDB_INVALID_REGNUM); reg_info.invalidate_regs = invalidate_regs.data(); } reg_info.name = reg_name.AsCString(); // We have to make a temporary ABI here, and not use the GetABI because // this code gets called in DidAttach, when the target architecture // (and consequently the ABI we'll get from the process) may be wrong. if (ABISP abi_sp = ABI::FindPlugin(shared_from_this(), arch_to_use)) abi_sp->AugmentRegisterInfo(reg_info); m_register_info.AddRegister(reg_info, reg_name, alt_name, set_name); } else { break; // ensure exit before reg_num is incremented } } else { break; } } if (m_register_info.GetNumRegisters() > 0) { m_register_info.Finalize(GetTarget().GetArchitecture()); return; } // We didn't get anything if the accumulated reg_num is zero. See if we are // debugging ARM and fill with a hard coded register set until we can get an // updated debugserver down on the devices. On the other hand, if the // accumulated reg_num is positive, see if we can add composite registers to // the existing primordial ones. bool from_scratch = (m_register_info.GetNumRegisters() == 0); if (!target_arch.IsValid()) { if (arch_to_use.IsValid() && (arch_to_use.GetMachine() == llvm::Triple::arm || arch_to_use.GetMachine() == llvm::Triple::thumb) && arch_to_use.GetTriple().getVendor() == llvm::Triple::Apple) m_register_info.HardcodeARMRegisters(from_scratch); } else if (target_arch.GetMachine() == llvm::Triple::arm || target_arch.GetMachine() == llvm::Triple::thumb) { m_register_info.HardcodeARMRegisters(from_scratch); } // At this point, we can finalize our register info. m_register_info.Finalize(GetTarget().GetArchitecture()); } Status ProcessGDBRemote::WillLaunch(lldb_private::Module *module) { return WillLaunchOrAttach(); } Status ProcessGDBRemote::WillAttachToProcessWithID(lldb::pid_t pid) { return WillLaunchOrAttach(); } Status ProcessGDBRemote::WillAttachToProcessWithName(const char *process_name, bool wait_for_launch) { return WillLaunchOrAttach(); } Status ProcessGDBRemote::DoConnectRemote(llvm::StringRef remote_url) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); Status error(WillLaunchOrAttach()); if (error.Fail()) return error; if (repro::Reproducer::Instance().IsReplaying()) error = ConnectToReplayServer(); else error = ConnectToDebugserver(remote_url); if (error.Fail()) return error; StartAsyncThread(); lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); if (pid == LLDB_INVALID_PROCESS_ID) { // We don't have a valid process ID, so note that we are connected and // could now request to launch or attach, or get remote process listings... SetPrivateState(eStateConnected); } else { // We have a valid process SetID(pid); GetThreadList(); StringExtractorGDBRemote response; if (m_gdb_comm.GetStopReply(response)) { SetLastStopPacket(response); // '?' Packets must be handled differently in non-stop mode if (GetTarget().GetNonStopModeEnabled()) HandleStopReplySequence(); Target &target = GetTarget(); if (!target.GetArchitecture().IsValid()) { if (m_gdb_comm.GetProcessArchitecture().IsValid()) { target.SetArchitecture(m_gdb_comm.GetProcessArchitecture()); } else { if (m_gdb_comm.GetHostArchitecture().IsValid()) { target.SetArchitecture(m_gdb_comm.GetHostArchitecture()); } } } const StateType state = SetThreadStopInfo(response); if (state != eStateInvalid) { SetPrivateState(state); } else error.SetErrorStringWithFormat( "Process %" PRIu64 " was reported after connecting to " "'%s', but state was not stopped: %s", pid, remote_url.str().c_str(), StateAsCString(state)); } else error.SetErrorStringWithFormat("Process %" PRIu64 " was reported after connecting to '%s', " "but no stop reply packet was received", pid, remote_url.str().c_str()); } LLDB_LOGF(log, "ProcessGDBRemote::%s pid %" PRIu64 ": normalizing target architecture initial triple: %s " "(GetTarget().GetArchitecture().IsValid() %s, " "m_gdb_comm.GetHostArchitecture().IsValid(): %s)", __FUNCTION__, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple().c_str(), GetTarget().GetArchitecture().IsValid() ? "true" : "false", m_gdb_comm.GetHostArchitecture().IsValid() ? "true" : "false"); if (error.Success() && !GetTarget().GetArchitecture().IsValid() && m_gdb_comm.GetHostArchitecture().IsValid()) { // Prefer the *process'* architecture over that of the *host*, if // available. if (m_gdb_comm.GetProcessArchitecture().IsValid()) GetTarget().SetArchitecture(m_gdb_comm.GetProcessArchitecture()); else GetTarget().SetArchitecture(m_gdb_comm.GetHostArchitecture()); } LLDB_LOGF(log, "ProcessGDBRemote::%s pid %" PRIu64 ": normalized target architecture triple: %s", __FUNCTION__, GetID(), GetTarget().GetArchitecture().GetTriple().getTriple().c_str()); if (error.Success()) { PlatformSP platform_sp = GetTarget().GetPlatform(); if (platform_sp && platform_sp->IsConnected()) SetUnixSignals(platform_sp->GetUnixSignals()); else SetUnixSignals(UnixSignals::Create(GetTarget().GetArchitecture())); } return error; } Status ProcessGDBRemote::WillLaunchOrAttach() { Status error; m_stdio_communication.Clear(); return error; } // Process Control Status ProcessGDBRemote::DoLaunch(lldb_private::Module *exe_module, ProcessLaunchInfo &launch_info) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); Status error; LLDB_LOGF(log, "ProcessGDBRemote::%s() entered", __FUNCTION__); uint32_t launch_flags = launch_info.GetFlags().Get(); FileSpec stdin_file_spec{}; FileSpec stdout_file_spec{}; FileSpec stderr_file_spec{}; FileSpec working_dir = launch_info.GetWorkingDirectory(); const FileAction *file_action; file_action = launch_info.GetFileActionForFD(STDIN_FILENO); if (file_action) { if (file_action->GetAction() == FileAction::eFileActionOpen) stdin_file_spec = file_action->GetFileSpec(); } file_action = launch_info.GetFileActionForFD(STDOUT_FILENO); if (file_action) { if (file_action->GetAction() == FileAction::eFileActionOpen) stdout_file_spec = file_action->GetFileSpec(); } file_action = launch_info.GetFileActionForFD(STDERR_FILENO); if (file_action) { if (file_action->GetAction() == FileAction::eFileActionOpen) stderr_file_spec = file_action->GetFileSpec(); } if (log) { if (stdin_file_spec || stdout_file_spec || stderr_file_spec) LLDB_LOGF(log, "ProcessGDBRemote::%s provided with STDIO paths via " "launch_info: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetCString() : "", stdout_file_spec ? stdout_file_spec.GetCString() : "", stderr_file_spec ? stderr_file_spec.GetCString() : ""); else LLDB_LOGF(log, "ProcessGDBRemote::%s no STDIO paths given via launch_info", __FUNCTION__); } const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; if (stdin_file_spec || disable_stdio) { // the inferior will be reading stdin from the specified file or stdio is // completely disabled m_stdin_forward = false; } else { m_stdin_forward = true; } // ::LogSetBitMask (GDBR_LOG_DEFAULT); // ::LogSetOptions (LLDB_LOG_OPTION_THREADSAFE | // LLDB_LOG_OPTION_PREPEND_TIMESTAMP | // LLDB_LOG_OPTION_PREPEND_PROC_AND_THREAD); // ::LogSetLogFile ("/dev/stdout"); ObjectFile *object_file = exe_module->GetObjectFile(); if (object_file) { error = EstablishConnectionIfNeeded(launch_info); if (error.Success()) { PseudoTerminal pty; const bool disable_stdio = (launch_flags & eLaunchFlagDisableSTDIO) != 0; PlatformSP platform_sp(GetTarget().GetPlatform()); if (disable_stdio) { // set to /dev/null unless redirected to a file above if (!stdin_file_spec) stdin_file_spec.SetFile(FileSystem::DEV_NULL, FileSpec::Style::native); if (!stdout_file_spec) stdout_file_spec.SetFile(FileSystem::DEV_NULL, FileSpec::Style::native); if (!stderr_file_spec) stderr_file_spec.SetFile(FileSystem::DEV_NULL, FileSpec::Style::native); } else if (platform_sp && platform_sp->IsHost()) { // If the debugserver is local and we aren't disabling STDIO, lets use // a pseudo terminal to instead of relying on the 'O' packets for stdio // 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.OpenFirstAvailablePrimary(O_RDWR | O_NOCTTY, nullptr, 0)) { FileSpec secondary_name{pty.GetSecondaryName(nullptr, 0)}; if (!stdin_file_spec) stdin_file_spec = secondary_name; if (!stdout_file_spec) stdout_file_spec = secondary_name; if (!stderr_file_spec) stderr_file_spec = secondary_name; } LLDB_LOGF( log, "ProcessGDBRemote::%s adjusted STDIO paths for local platform " "(IsHost() is true) using secondary: stdin=%s, stdout=%s, " "stderr=%s", __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetCString() : "", stdout_file_spec ? stdout_file_spec.GetCString() : "", stderr_file_spec ? stderr_file_spec.GetCString() : ""); } LLDB_LOGF(log, "ProcessGDBRemote::%s final STDIO paths after all " "adjustments: stdin=%s, stdout=%s, stderr=%s", __FUNCTION__, stdin_file_spec ? stdin_file_spec.GetCString() : "", stdout_file_spec ? stdout_file_spec.GetCString() : "", stderr_file_spec ? stderr_file_spec.GetCString() : ""); if (stdin_file_spec) m_gdb_comm.SetSTDIN(stdin_file_spec); if (stdout_file_spec) m_gdb_comm.SetSTDOUT(stdout_file_spec); if (stderr_file_spec) m_gdb_comm.SetSTDERR(stderr_file_spec); m_gdb_comm.SetDisableASLR(launch_flags & eLaunchFlagDisableASLR); m_gdb_comm.SetDetachOnError(launch_flags & eLaunchFlagDetachOnError); m_gdb_comm.SendLaunchArchPacket( GetTarget().GetArchitecture().GetArchitectureName()); const char *launch_event_data = launch_info.GetLaunchEventData(); if (launch_event_data != nullptr && *launch_event_data != '\0') m_gdb_comm.SendLaunchEventDataPacket(launch_event_data); if (working_dir) { m_gdb_comm.SetWorkingDir(working_dir); } // Send the environment and the program + arguments after we connect m_gdb_comm.SendEnvironment(launch_info.GetEnvironment()); { // Scope for the scoped timeout object GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, std::chrono::seconds(10)); int arg_packet_err = m_gdb_comm.SendArgumentsPacket(launch_info); if (arg_packet_err == 0) { std::string error_str; if (m_gdb_comm.GetLaunchSuccess(error_str)) { SetID(m_gdb_comm.GetCurrentProcessID()); } else { error.SetErrorString(error_str.c_str()); } } else { error.SetErrorStringWithFormat("'A' packet returned an error: %i", arg_packet_err); } } if (GetID() == LLDB_INVALID_PROCESS_ID) { LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString()); KillDebugserverProcess(); return error; } StringExtractorGDBRemote response; if (m_gdb_comm.GetStopReply(response)) { SetLastStopPacket(response); // '?' Packets must be handled differently in non-stop mode if (GetTarget().GetNonStopModeEnabled()) HandleStopReplySequence(); const ArchSpec &process_arch = m_gdb_comm.GetProcessArchitecture(); if (process_arch.IsValid()) { GetTarget().MergeArchitecture(process_arch); } else { const ArchSpec &host_arch = m_gdb_comm.GetHostArchitecture(); if (host_arch.IsValid()) GetTarget().MergeArchitecture(host_arch); } SetPrivateState(SetThreadStopInfo(response)); if (!disable_stdio) { if (pty.GetPrimaryFileDescriptor() != PseudoTerminal::invalid_fd) SetSTDIOFileDescriptor(pty.ReleasePrimaryFileDescriptor()); } } } else { LLDB_LOGF(log, "failed to connect to debugserver: %s", error.AsCString()); } } else { // Set our user ID to an invalid process ID. SetID(LLDB_INVALID_PROCESS_ID); error.SetErrorStringWithFormat( "failed to get object file from '%s' for arch %s", exe_module->GetFileSpec().GetFilename().AsCString(), exe_module->GetArchitecture().GetArchitectureName()); } return error; } Status ProcessGDBRemote::ConnectToDebugserver(llvm::StringRef connect_url) { Status error; // Only connect if we have a valid connect URL Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (!connect_url.empty()) { LLDB_LOGF(log, "ProcessGDBRemote::%s Connecting to %s", __FUNCTION__, connect_url.str().c_str()); std::unique_ptr conn_up( new ConnectionFileDescriptor()); if (conn_up) { const uint32_t max_retry_count = 50; uint32_t retry_count = 0; while (!m_gdb_comm.IsConnected()) { if (conn_up->Connect(connect_url, &error) == eConnectionStatusSuccess) { m_gdb_comm.SetConnection(std::move(conn_up)); break; } else if (error.WasInterrupted()) { // If we were interrupted, don't keep retrying. break; } retry_count++; if (retry_count >= max_retry_count) break; std::this_thread::sleep_for(std::chrono::milliseconds(100)); } } } if (!m_gdb_comm.IsConnected()) { if (error.Success()) error.SetErrorString("not connected to remote gdb server"); return error; } // Start the communications read thread so all incoming data can be parsed // into packets and queued as they arrive. if (GetTarget().GetNonStopModeEnabled()) m_gdb_comm.StartReadThread(); // We always seem to be able to open a connection to a local port so we need // to make sure we can then send data to it. If we can't then we aren't // actually connected to anything, so try and do the handshake with the // remote GDB server and make sure that goes alright. if (!m_gdb_comm.HandshakeWithServer(&error)) { m_gdb_comm.Disconnect(); if (error.Success()) error.SetErrorString("not connected to remote gdb server"); return error; } // Send $QNonStop:1 packet on startup if required if (GetTarget().GetNonStopModeEnabled()) GetTarget().SetNonStopModeEnabled(m_gdb_comm.SetNonStopMode(true)); m_gdb_comm.GetEchoSupported(); m_gdb_comm.GetThreadSuffixSupported(); m_gdb_comm.GetListThreadsInStopReplySupported(); m_gdb_comm.GetHostInfo(); m_gdb_comm.GetVContSupported('c'); m_gdb_comm.GetVAttachOrWaitSupported(); m_gdb_comm.EnableErrorStringInPacket(); // Ask the remote server for the default thread id if (GetTarget().GetNonStopModeEnabled()) m_gdb_comm.GetDefaultThreadId(m_initial_tid); size_t num_cmds = GetExtraStartupCommands().GetArgumentCount(); for (size_t idx = 0; idx < num_cmds; idx++) { StringExtractorGDBRemote response; m_gdb_comm.SendPacketAndWaitForResponse( GetExtraStartupCommands().GetArgumentAtIndex(idx), response, false); } return error; } void ProcessGDBRemote::DidLaunchOrAttach(ArchSpec &process_arch) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); BuildDynamicRegisterInfo(false); // See if the GDB server supports qHostInfo or qProcessInfo packets. Prefer // qProcessInfo as it will be more specific to our process. const ArchSpec &remote_process_arch = m_gdb_comm.GetProcessArchitecture(); if (remote_process_arch.IsValid()) { process_arch = remote_process_arch; LLDB_LOG(log, "gdb-remote had process architecture, using {0} {1}", process_arch.GetArchitectureName(), process_arch.GetTriple().getTriple()); } else { process_arch = m_gdb_comm.GetHostArchitecture(); LLDB_LOG(log, "gdb-remote did not have process architecture, using gdb-remote " "host architecture {0} {1}", process_arch.GetArchitectureName(), process_arch.GetTriple().getTriple()); } if (process_arch.IsValid()) { const ArchSpec &target_arch = GetTarget().GetArchitecture(); if (target_arch.IsValid()) { LLDB_LOG(log, "analyzing target arch, currently {0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple().getTriple()); // If the remote host is ARM and we have apple as the vendor, then // ARM executables and shared libraries can have mixed ARM // architectures. // You can have an armv6 executable, and if the host is armv7, then the // system will load the best possible architecture for all shared // libraries it has, so we really need to take the remote host // architecture as our defacto architecture in this case. if ((process_arch.GetMachine() == llvm::Triple::arm || process_arch.GetMachine() == llvm::Triple::thumb) && process_arch.GetTriple().getVendor() == llvm::Triple::Apple) { GetTarget().SetArchitecture(process_arch); LLDB_LOG(log, "remote process is ARM/Apple, " "setting target arch to {0} {1}", process_arch.GetArchitectureName(), process_arch.GetTriple().getTriple()); } else { // Fill in what is missing in the triple const llvm::Triple &remote_triple = process_arch.GetTriple(); llvm::Triple new_target_triple = target_arch.GetTriple(); if (new_target_triple.getVendorName().size() == 0) { new_target_triple.setVendor(remote_triple.getVendor()); if (new_target_triple.getOSName().size() == 0) { new_target_triple.setOS(remote_triple.getOS()); if (new_target_triple.getEnvironmentName().size() == 0) new_target_triple.setEnvironment(remote_triple.getEnvironment()); } ArchSpec new_target_arch = target_arch; new_target_arch.SetTriple(new_target_triple); GetTarget().SetArchitecture(new_target_arch); } } LLDB_LOG(log, "final target arch after adjustments for remote architecture: " "{0} {1}", target_arch.GetArchitectureName(), target_arch.GetTriple().getTriple()); } else { // The target doesn't have a valid architecture yet, set it from the // architecture we got from the remote GDB server GetTarget().SetArchitecture(process_arch); } } MaybeLoadExecutableModule(); // Find out which StructuredDataPlugins are supported by the debug monitor. // These plugins transmit data over async $J packets. if (StructuredData::Array *supported_packets = m_gdb_comm.GetSupportedStructuredDataPlugins()) MapSupportedStructuredDataPlugins(*supported_packets); } void ProcessGDBRemote::MaybeLoadExecutableModule() { ModuleSP module_sp = GetTarget().GetExecutableModule(); if (!module_sp) return; llvm::Optional offsets = m_gdb_comm.GetQOffsets(); if (!offsets) return; bool is_uniform = size_t(llvm::count(offsets->offsets, offsets->offsets[0])) == offsets->offsets.size(); if (!is_uniform) return; // TODO: Handle non-uniform responses. bool changed = false; module_sp->SetLoadAddress(GetTarget(), offsets->offsets[0], /*value_is_offset=*/true, changed); if (changed) { ModuleList list; list.Append(module_sp); m_process->GetTarget().ModulesDidLoad(list); } } void ProcessGDBRemote::DidLaunch() { ArchSpec process_arch; DidLaunchOrAttach(process_arch); } Status ProcessGDBRemote::DoAttachToProcessWithID( lldb::pid_t attach_pid, const ProcessAttachInfo &attach_info) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); Status error; LLDB_LOGF(log, "ProcessGDBRemote::%s()", __FUNCTION__); // Clear out and clean up from any current state Clear(); if (attach_pid != LLDB_INVALID_PROCESS_ID) { error = EstablishConnectionIfNeeded(attach_info); if (error.Success()) { m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); char packet[64]; const int packet_len = ::snprintf(packet, sizeof(packet), "vAttach;%" PRIx64, attach_pid); SetID(attach_pid); m_async_broadcaster.BroadcastEvent( eBroadcastBitAsyncContinue, new EventDataBytes(packet, packet_len)); } else SetExitStatus(-1, error.AsCString()); } return error; } Status ProcessGDBRemote::DoAttachToProcessWithName( const char *process_name, const ProcessAttachInfo &attach_info) { Status error; // Clear out and clean up from any current state Clear(); if (process_name && process_name[0]) { error = EstablishConnectionIfNeeded(attach_info); if (error.Success()) { StreamString packet; m_gdb_comm.SetDetachOnError(attach_info.GetDetachOnError()); if (attach_info.GetWaitForLaunch()) { if (!m_gdb_comm.GetVAttachOrWaitSupported()) { packet.PutCString("vAttachWait"); } else { if (attach_info.GetIgnoreExisting()) packet.PutCString("vAttachWait"); else packet.PutCString("vAttachOrWait"); } } else packet.PutCString("vAttachName"); packet.PutChar(';'); packet.PutBytesAsRawHex8(process_name, strlen(process_name), endian::InlHostByteOrder(), endian::InlHostByteOrder()); m_async_broadcaster.BroadcastEvent( eBroadcastBitAsyncContinue, new EventDataBytes(packet.GetString().data(), packet.GetSize())); } else SetExitStatus(-1, error.AsCString()); } return error; } lldb::user_id_t ProcessGDBRemote::StartTrace(const TraceOptions &options, Status &error) { return m_gdb_comm.SendStartTracePacket(options, error); } Status ProcessGDBRemote::StopTrace(lldb::user_id_t uid, lldb::tid_t thread_id) { return m_gdb_comm.SendStopTracePacket(uid, thread_id); } Status ProcessGDBRemote::GetData(lldb::user_id_t uid, lldb::tid_t thread_id, llvm::MutableArrayRef &buffer, size_t offset) { return m_gdb_comm.SendGetDataPacket(uid, thread_id, buffer, offset); } Status ProcessGDBRemote::GetMetaData(lldb::user_id_t uid, lldb::tid_t thread_id, llvm::MutableArrayRef &buffer, size_t offset) { return m_gdb_comm.SendGetMetaDataPacket(uid, thread_id, buffer, offset); } Status ProcessGDBRemote::GetTraceConfig(lldb::user_id_t uid, TraceOptions &options) { return m_gdb_comm.SendGetTraceConfigPacket(uid, options); } void ProcessGDBRemote::DidExit() { // When we exit, disconnect from the GDB server communications m_gdb_comm.Disconnect(); } void ProcessGDBRemote::DidAttach(ArchSpec &process_arch) { // If you can figure out what the architecture is, fill it in here. process_arch.Clear(); DidLaunchOrAttach(process_arch); } Status ProcessGDBRemote::WillResume() { m_continue_c_tids.clear(); m_continue_C_tids.clear(); m_continue_s_tids.clear(); m_continue_S_tids.clear(); m_jstopinfo_sp.reset(); m_jthreadsinfo_sp.reset(); return Status(); } Status ProcessGDBRemote::DoResume() { Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::Resume()"); ListenerSP listener_sp( Listener::MakeListener("gdb-remote.resume-packet-sent")); if (listener_sp->StartListeningForEvents( &m_gdb_comm, GDBRemoteCommunication::eBroadcastBitRunPacketSent)) { listener_sp->StartListeningForEvents( &m_async_broadcaster, ProcessGDBRemote::eBroadcastBitAsyncThreadDidExit); const size_t num_threads = GetThreadList().GetSize(); StreamString continue_packet; bool continue_packet_error = false; if (m_gdb_comm.HasAnyVContSupport()) { if (!GetTarget().GetNonStopModeEnabled() && (m_continue_c_tids.size() == num_threads || (m_continue_c_tids.empty() && m_continue_C_tids.empty() && m_continue_s_tids.empty() && m_continue_S_tids.empty()))) { // All threads are continuing, just send a "c" packet continue_packet.PutCString("c"); } else { continue_packet.PutCString("vCont"); if (!m_continue_c_tids.empty()) { if (m_gdb_comm.GetVContSupported('c')) { for (tid_collection::const_iterator t_pos = m_continue_c_tids.begin(), t_end = m_continue_c_tids.end(); t_pos != t_end; ++t_pos) continue_packet.Printf(";c:%4.4" PRIx64, *t_pos); } else continue_packet_error = true; } if (!continue_packet_error && !m_continue_C_tids.empty()) { if (m_gdb_comm.GetVContSupported('C')) { for (tid_sig_collection::const_iterator s_pos = m_continue_C_tids.begin(), s_end = m_continue_C_tids.end(); s_pos != s_end; ++s_pos) continue_packet.Printf(";C%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); } else continue_packet_error = true; } if (!continue_packet_error && !m_continue_s_tids.empty()) { if (m_gdb_comm.GetVContSupported('s')) { for (tid_collection::const_iterator t_pos = m_continue_s_tids.begin(), t_end = m_continue_s_tids.end(); t_pos != t_end; ++t_pos) continue_packet.Printf(";s:%4.4" PRIx64, *t_pos); } else continue_packet_error = true; } if (!continue_packet_error && !m_continue_S_tids.empty()) { if (m_gdb_comm.GetVContSupported('S')) { for (tid_sig_collection::const_iterator s_pos = m_continue_S_tids.begin(), s_end = m_continue_S_tids.end(); s_pos != s_end; ++s_pos) continue_packet.Printf(";S%2.2x:%4.4" PRIx64, s_pos->second, s_pos->first); } else continue_packet_error = true; } if (continue_packet_error) continue_packet.Clear(); } } else continue_packet_error = true; if (continue_packet_error) { // Either no vCont support, or we tried to use part of the vCont packet // that wasn't supported by the remote GDB server. We need to try and // make a simple packet that can do our continue const size_t num_continue_c_tids = m_continue_c_tids.size(); const size_t num_continue_C_tids = m_continue_C_tids.size(); const size_t num_continue_s_tids = m_continue_s_tids.size(); const size_t num_continue_S_tids = m_continue_S_tids.size(); if (num_continue_c_tids > 0) { if (num_continue_c_tids == num_threads) { // All threads are resuming... m_gdb_comm.SetCurrentThreadForRun(-1); continue_packet.PutChar('c'); continue_packet_error = false; } else if (num_continue_c_tids == 1 && num_continue_C_tids == 0 && num_continue_s_tids == 0 && num_continue_S_tids == 0) { // Only one thread is continuing m_gdb_comm.SetCurrentThreadForRun(m_continue_c_tids.front()); continue_packet.PutChar('c'); continue_packet_error = false; } } if (continue_packet_error && num_continue_C_tids > 0) { if ((num_continue_C_tids + num_continue_c_tids) == num_threads && num_continue_C_tids > 0 && num_continue_s_tids == 0 && num_continue_S_tids == 0) { const int continue_signo = m_continue_C_tids.front().second; // Only one thread is continuing if (num_continue_C_tids > 1) { // More that one thread with a signal, yet we don't have vCont // support and we are being asked to resume each thread with a // signal, we need to make sure they are all the same signal, or we // can't issue the continue accurately with the current support... if (num_continue_C_tids > 1) { continue_packet_error = false; for (size_t i = 1; i < m_continue_C_tids.size(); ++i) { if (m_continue_C_tids[i].second != continue_signo) continue_packet_error = true; } } if (!continue_packet_error) m_gdb_comm.SetCurrentThreadForRun(-1); } else { // Set the continue thread ID continue_packet_error = false; m_gdb_comm.SetCurrentThreadForRun(m_continue_C_tids.front().first); } if (!continue_packet_error) { // Add threads continuing with the same signo... continue_packet.Printf("C%2.2x", continue_signo); } } } if (continue_packet_error && num_continue_s_tids > 0) { if (num_continue_s_tids == num_threads) { // All threads are resuming... m_gdb_comm.SetCurrentThreadForRun(-1); // If in Non-Stop-Mode use vCont when stepping if (GetTarget().GetNonStopModeEnabled()) { if (m_gdb_comm.GetVContSupported('s')) continue_packet.PutCString("vCont;s"); else continue_packet.PutChar('s'); } else continue_packet.PutChar('s'); continue_packet_error = false; } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && num_continue_s_tids == 1 && num_continue_S_tids == 0) { // Only one thread is stepping m_gdb_comm.SetCurrentThreadForRun(m_continue_s_tids.front()); continue_packet.PutChar('s'); continue_packet_error = false; } } if (!continue_packet_error && num_continue_S_tids > 0) { if (num_continue_S_tids == num_threads) { const int step_signo = m_continue_S_tids.front().second; // Are all threads trying to step with the same signal? continue_packet_error = false; if (num_continue_S_tids > 1) { for (size_t i = 1; i < num_threads; ++i) { if (m_continue_S_tids[i].second != step_signo) continue_packet_error = true; } } if (!continue_packet_error) { // Add threads stepping with the same signo... m_gdb_comm.SetCurrentThreadForRun(-1); continue_packet.Printf("S%2.2x", step_signo); } } else if (num_continue_c_tids == 0 && num_continue_C_tids == 0 && num_continue_s_tids == 0 && num_continue_S_tids == 1) { // Only one thread is stepping with signal m_gdb_comm.SetCurrentThreadForRun(m_continue_S_tids.front().first); continue_packet.Printf("S%2.2x", m_continue_S_tids.front().second); continue_packet_error = false; } } } if (continue_packet_error) { error.SetErrorString("can't make continue packet for this resume"); } else { EventSP event_sp; if (!m_async_thread.IsJoinable()) { error.SetErrorString("Trying to resume but the async thread is dead."); LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Trying to resume but the " "async thread is dead."); return error; } m_async_broadcaster.BroadcastEvent( eBroadcastBitAsyncContinue, new EventDataBytes(continue_packet.GetString().data(), continue_packet.GetSize())); if (!listener_sp->GetEvent(event_sp, std::chrono::seconds(5))) { error.SetErrorString("Resume timed out."); LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Resume timed out."); } else if (event_sp->BroadcasterIs(&m_async_broadcaster)) { error.SetErrorString("Broadcast continue, but the async thread was " "killed before we got an ack back."); LLDB_LOGF(log, "ProcessGDBRemote::DoResume: Broadcast continue, but the " "async thread was killed before we got an ack back."); return error; } } } return error; } void ProcessGDBRemote::HandleStopReplySequence() { while (true) { // Send vStopped StringExtractorGDBRemote response; m_gdb_comm.SendPacketAndWaitForResponse("vStopped", response, false); // OK represents end of signal list if (response.IsOKResponse()) break; // If not OK or a normal packet we have a problem if (!response.IsNormalResponse()) break; SetLastStopPacket(response); } } void ProcessGDBRemote::ClearThreadIDList() { std::lock_guard guard(m_thread_list_real.GetMutex()); m_thread_ids.clear(); m_thread_pcs.clear(); } size_t ProcessGDBRemote::UpdateThreadIDsFromStopReplyThreadsValue(std::string &value) { m_thread_ids.clear(); size_t comma_pos; lldb::tid_t tid; while ((comma_pos = value.find(',')) != std::string::npos) { value[comma_pos] = '\0'; // thread in big endian hex tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); if (tid != LLDB_INVALID_THREAD_ID) m_thread_ids.push_back(tid); value.erase(0, comma_pos + 1); } tid = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_THREAD_ID, 16); if (tid != LLDB_INVALID_THREAD_ID) m_thread_ids.push_back(tid); return m_thread_ids.size(); } size_t ProcessGDBRemote::UpdateThreadPCsFromStopReplyThreadsValue(std::string &value) { m_thread_pcs.clear(); size_t comma_pos; lldb::addr_t pc; while ((comma_pos = value.find(',')) != std::string::npos) { value[comma_pos] = '\0'; pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16); if (pc != LLDB_INVALID_ADDRESS) m_thread_pcs.push_back(pc); value.erase(0, comma_pos + 1); } pc = StringConvert::ToUInt64(value.c_str(), LLDB_INVALID_ADDRESS, 16); if (pc != LLDB_INVALID_THREAD_ID) m_thread_pcs.push_back(pc); return m_thread_pcs.size(); } bool ProcessGDBRemote::UpdateThreadIDList() { std::lock_guard guard(m_thread_list_real.GetMutex()); if (m_jthreadsinfo_sp) { // If we have the JSON threads info, we can get the thread list from that StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); if (thread_infos && thread_infos->GetSize() > 0) { m_thread_ids.clear(); m_thread_pcs.clear(); thread_infos->ForEach([this](StructuredData::Object *object) -> bool { StructuredData::Dictionary *thread_dict = object->GetAsDictionary(); if (thread_dict) { // Set the thread stop info from the JSON dictionary SetThreadStopInfo(thread_dict); lldb::tid_t tid = LLDB_INVALID_THREAD_ID; if (thread_dict->GetValueForKeyAsInteger("tid", tid)) m_thread_ids.push_back(tid); } return true; // Keep iterating through all thread_info objects }); } if (!m_thread_ids.empty()) return true; } else { // See if we can get the thread IDs from the current stop reply packets // that might contain a "threads" key/value pair // Lock the thread stack while we access it // Mutex::Locker stop_stack_lock(m_last_stop_packet_mutex); std::unique_lock stop_stack_lock( m_last_stop_packet_mutex, std::defer_lock); if (stop_stack_lock.try_lock()) { // Get the number of stop packets on the stack int nItems = m_stop_packet_stack.size(); // Iterate over them for (int i = 0; i < nItems; i++) { // Get the thread stop info StringExtractorGDBRemote &stop_info = m_stop_packet_stack[i]; const std::string &stop_info_str = std::string(stop_info.GetStringRef()); m_thread_pcs.clear(); const size_t thread_pcs_pos = stop_info_str.find(";thread-pcs:"); if (thread_pcs_pos != std::string::npos) { const size_t start = thread_pcs_pos + strlen(";thread-pcs:"); const size_t end = stop_info_str.find(';', start); if (end != std::string::npos) { std::string value = stop_info_str.substr(start, end - start); UpdateThreadPCsFromStopReplyThreadsValue(value); } } const size_t threads_pos = stop_info_str.find(";threads:"); if (threads_pos != std::string::npos) { const size_t start = threads_pos + strlen(";threads:"); const size_t end = stop_info_str.find(';', start); if (end != std::string::npos) { std::string value = stop_info_str.substr(start, end - start); if (UpdateThreadIDsFromStopReplyThreadsValue(value)) return true; } } } } } bool sequence_mutex_unavailable = false; m_gdb_comm.GetCurrentThreadIDs(m_thread_ids, sequence_mutex_unavailable); if (sequence_mutex_unavailable) { return false; // We just didn't get the list } return true; } bool ProcessGDBRemote::UpdateThreadList(ThreadList &old_thread_list, ThreadList &new_thread_list) { // locker will keep a mutex locked until it goes out of scope Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_THREAD)); LLDB_LOGV(log, "pid = {0}", GetID()); size_t num_thread_ids = m_thread_ids.size(); // The "m_thread_ids" thread ID list should always be updated after each stop // reply packet, but in case it isn't, update it here. if (num_thread_ids == 0) { if (!UpdateThreadIDList()) return false; num_thread_ids = m_thread_ids.size(); } ThreadList old_thread_list_copy(old_thread_list); if (num_thread_ids > 0) { for (size_t i = 0; i < num_thread_ids; ++i) { tid_t tid = m_thread_ids[i]; ThreadSP thread_sp( old_thread_list_copy.RemoveThreadByProtocolID(tid, false)); if (!thread_sp) { thread_sp = std::make_shared(*this, tid); LLDB_LOGV(log, "Making new thread: {0} for thread ID: {1:x}.", thread_sp.get(), thread_sp->GetID()); } else { LLDB_LOGV(log, "Found old thread: {0} for thread ID: {1:x}.", thread_sp.get(), thread_sp->GetID()); } SetThreadPc(thread_sp, i); new_thread_list.AddThreadSortedByIndexID(thread_sp); } } // Whatever that is left in old_thread_list_copy are not present in // new_thread_list. Remove non-existent threads from internal id table. size_t old_num_thread_ids = old_thread_list_copy.GetSize(false); for (size_t i = 0; i < old_num_thread_ids; i++) { ThreadSP old_thread_sp(old_thread_list_copy.GetThreadAtIndex(i, false)); if (old_thread_sp) { lldb::tid_t old_thread_id = old_thread_sp->GetProtocolID(); m_thread_id_to_index_id_map.erase(old_thread_id); } } return true; } void ProcessGDBRemote::SetThreadPc(const ThreadSP &thread_sp, uint64_t index) { if (m_thread_ids.size() == m_thread_pcs.size() && thread_sp.get() && GetByteOrder() != eByteOrderInvalid) { ThreadGDBRemote *gdb_thread = static_cast(thread_sp.get()); RegisterContextSP reg_ctx_sp(thread_sp->GetRegisterContext()); if (reg_ctx_sp) { uint32_t pc_regnum = reg_ctx_sp->ConvertRegisterKindToRegisterNumber( eRegisterKindGeneric, LLDB_REGNUM_GENERIC_PC); if (pc_regnum != LLDB_INVALID_REGNUM) { gdb_thread->PrivateSetRegisterValue(pc_regnum, m_thread_pcs[index]); } } } } bool ProcessGDBRemote::GetThreadStopInfoFromJSON( ThreadGDBRemote *thread, const StructuredData::ObjectSP &thread_infos_sp) { // See if we got thread stop infos for all threads via the "jThreadsInfo" // packet if (thread_infos_sp) { StructuredData::Array *thread_infos = thread_infos_sp->GetAsArray(); if (thread_infos) { lldb::tid_t tid; const size_t n = thread_infos->GetSize(); for (size_t i = 0; i < n; ++i) { StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary(); if (thread_dict) { if (thread_dict->GetValueForKeyAsInteger( "tid", tid, LLDB_INVALID_THREAD_ID)) { if (tid == thread->GetID()) return (bool)SetThreadStopInfo(thread_dict); } } } } } return false; } bool ProcessGDBRemote::CalculateThreadStopInfo(ThreadGDBRemote *thread) { // See if we got thread stop infos for all threads via the "jThreadsInfo" // packet if (GetThreadStopInfoFromJSON(thread, m_jthreadsinfo_sp)) return true; // See if we got thread stop info for any threads valid stop info reasons // threads via the "jstopinfo" packet stop reply packet key/value pair? if (m_jstopinfo_sp) { // If we have "jstopinfo" then we have stop descriptions for all threads // that have stop reasons, and if there is no entry for a thread, then it // has no stop reason. thread->GetRegisterContext()->InvalidateIfNeeded(true); if (!GetThreadStopInfoFromJSON(thread, m_jstopinfo_sp)) { thread->SetStopInfo(StopInfoSP()); } return true; } // Fall back to using the qThreadStopInfo packet StringExtractorGDBRemote stop_packet; if (GetGDBRemote().GetThreadStopInfo(thread->GetProtocolID(), stop_packet)) return SetThreadStopInfo(stop_packet) == eStateStopped; return false; } ThreadSP ProcessGDBRemote::SetThreadStopInfo( lldb::tid_t tid, ExpeditedRegisterMap &expedited_register_map, uint8_t signo, const std::string &thread_name, const std::string &reason, const std::string &description, uint32_t exc_type, const std::vector &exc_data, addr_t thread_dispatch_qaddr, bool queue_vars_valid, // Set to true if queue_name, queue_kind and // queue_serial are valid LazyBool associated_with_dispatch_queue, addr_t dispatch_queue_t, std::string &queue_name, QueueKind queue_kind, uint64_t queue_serial) { ThreadSP thread_sp; if (tid != LLDB_INVALID_THREAD_ID) { // Scope for "locker" below { // m_thread_list_real does have its own mutex, but we need to hold onto // the mutex between the call to m_thread_list_real.FindThreadByID(...) // and the m_thread_list_real.AddThread(...) so it doesn't change on us std::lock_guard guard( m_thread_list_real.GetMutex()); thread_sp = m_thread_list_real.FindThreadByProtocolID(tid, false); if (!thread_sp) { // Create the thread if we need to thread_sp = std::make_shared(*this, tid); m_thread_list_real.AddThread(thread_sp); } } if (thread_sp) { ThreadGDBRemote *gdb_thread = static_cast(thread_sp.get()); gdb_thread->GetRegisterContext()->InvalidateIfNeeded(true); auto iter = std::find(m_thread_ids.begin(), m_thread_ids.end(), tid); if (iter != m_thread_ids.end()) { SetThreadPc(thread_sp, iter - m_thread_ids.begin()); } for (const auto &pair : expedited_register_map) { StringExtractor reg_value_extractor(pair.second); DataBufferSP buffer_sp(new DataBufferHeap( reg_value_extractor.GetStringRef().size() / 2, 0)); reg_value_extractor.GetHexBytes(buffer_sp->GetData(), '\xcc'); gdb_thread->PrivateSetRegisterValue(pair.first, buffer_sp->GetData()); } 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 // serial number if (queue_vars_valid) gdb_thread->SetQueueInfo(std::move(queue_name), queue_kind, queue_serial, dispatch_queue_t, associated_with_dispatch_queue); else gdb_thread->ClearQueueInfo(); gdb_thread->SetAssociatedWithLibdispatchQueue( associated_with_dispatch_queue); if (dispatch_queue_t != LLDB_INVALID_ADDRESS) gdb_thread->SetQueueLibdispatchQueueAddress(dispatch_queue_t); // Make sure we update our thread stop reason just once if (!thread_sp->StopInfoIsUpToDate()) { thread_sp->SetStopInfo(StopInfoSP()); // If there's a memory thread backed by this thread, we need to use it // to calculate StopInfo. if (ThreadSP memory_thread_sp = m_thread_list.GetBackingThread(thread_sp)) thread_sp = memory_thread_sp; if (exc_type != 0) { const size_t exc_data_size = exc_data.size(); thread_sp->SetStopInfo( StopInfoMachException::CreateStopReasonWithMachException( *thread_sp, exc_type, exc_data_size, exc_data_size >= 1 ? exc_data[0] : 0, exc_data_size >= 2 ? exc_data[1] : 0, exc_data_size >= 3 ? exc_data[2] : 0)); } else { bool handled = false; bool did_exec = false; if (!reason.empty()) { if (reason == "trace") { addr_t pc = thread_sp->GetRegisterContext()->GetPC(); lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() ->GetBreakpointSiteList() .FindByAddress(pc); // If the current pc is a breakpoint site then the StopInfo // should be set to Breakpoint Otherwise, it will be set to // Trace. if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) { thread_sp->SetStopInfo( StopInfo::CreateStopReasonWithBreakpointSiteID( *thread_sp, bp_site_sp->GetID())); } else thread_sp->SetStopInfo( StopInfo::CreateStopReasonToTrace(*thread_sp)); handled = true; } else if (reason == "breakpoint") { addr_t pc = thread_sp->GetRegisterContext()->GetPC(); lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() ->GetBreakpointSiteList() .FindByAddress(pc); if (bp_site_sp) { // If the breakpoint is for this thread, then we'll report the // hit, but if it is for another thread, we can just report no // reason. We don't need to worry about stepping over the // breakpoint here, that will be taken care of when the thread // resumes and notices that there's a breakpoint under the pc. handled = true; if (bp_site_sp->ValidForThisThread(thread_sp.get())) { thread_sp->SetStopInfo( StopInfo::CreateStopReasonWithBreakpointSiteID( *thread_sp, bp_site_sp->GetID())); } else { StopInfoSP invalid_stop_info_sp; thread_sp->SetStopInfo(invalid_stop_info_sp); } } } else if (reason == "trap") { // Let the trap just use the standard signal stop reason below... } else if (reason == "watchpoint") { StringExtractor desc_extractor(description.c_str()); addr_t wp_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); uint32_t wp_index = desc_extractor.GetU32(LLDB_INVALID_INDEX32); addr_t wp_hit_addr = desc_extractor.GetU64(LLDB_INVALID_ADDRESS); watch_id_t watch_id = LLDB_INVALID_WATCH_ID; if (wp_addr != LLDB_INVALID_ADDRESS) { WatchpointSP wp_sp; ArchSpec::Core core = GetTarget().GetArchitecture().GetCore(); if ((core >= ArchSpec::kCore_mips_first && core <= ArchSpec::kCore_mips_last) || (core >= ArchSpec::eCore_arm_generic && core <= ArchSpec::eCore_arm_aarch64)) wp_sp = GetTarget().GetWatchpointList().FindByAddress( wp_hit_addr); if (!wp_sp) wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr); if (wp_sp) { wp_sp->SetHardwareIndex(wp_index); watch_id = wp_sp->GetID(); } } if (watch_id == LLDB_INVALID_WATCH_ID) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet( GDBR_LOG_WATCHPOINTS)); LLDB_LOGF(log, "failed to find watchpoint"); } thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithWatchpointID( *thread_sp, watch_id, wp_hit_addr)); handled = true; } else if (reason == "exception") { thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( *thread_sp, description.c_str())); handled = true; } else if (reason == "exec") { did_exec = true; thread_sp->SetStopInfo( StopInfo::CreateStopReasonWithExec(*thread_sp)); handled = true; } } else if (!signo) { addr_t pc = thread_sp->GetRegisterContext()->GetPC(); lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess()->GetBreakpointSiteList().FindByAddress( pc); // If the current pc is a breakpoint site then the StopInfo should // be set to Breakpoint even though the remote stub did not set it // as such. This can happen when the thread is involuntarily // interrupted (e.g. due to stops on other threads) just as it is // about to execute the breakpoint instruction. if (bp_site_sp && bp_site_sp->ValidForThisThread(thread_sp.get())) { thread_sp->SetStopInfo( StopInfo::CreateStopReasonWithBreakpointSiteID( *thread_sp, bp_site_sp->GetID())); handled = true; } } if (!handled && signo && !did_exec) { if (signo == SIGTRAP) { // Currently we are going to assume SIGTRAP means we are either // hitting a breakpoint or hardware single stepping. handled = true; addr_t pc = thread_sp->GetRegisterContext()->GetPC() + m_breakpoint_pc_offset; lldb::BreakpointSiteSP bp_site_sp = thread_sp->GetProcess() ->GetBreakpointSiteList() .FindByAddress(pc); if (bp_site_sp) { // If the breakpoint is for this thread, then we'll report the // hit, but if it is for another thread, we can just report no // reason. We don't need to worry about stepping over the // breakpoint here, that will be taken care of when the thread // resumes and notices that there's a breakpoint under the pc. if (bp_site_sp->ValidForThisThread(thread_sp.get())) { if (m_breakpoint_pc_offset != 0) thread_sp->GetRegisterContext()->SetPC(pc); thread_sp->SetStopInfo( StopInfo::CreateStopReasonWithBreakpointSiteID( *thread_sp, bp_site_sp->GetID())); } else { StopInfoSP invalid_stop_info_sp; thread_sp->SetStopInfo(invalid_stop_info_sp); } } else { // If we were stepping then assume the stop was the result of // the trace. If we were not stepping then report the SIGTRAP. // FIXME: We are still missing the case where we single step // over a trap instruction. if (thread_sp->GetTemporaryResumeState() == eStateStepping) thread_sp->SetStopInfo( StopInfo::CreateStopReasonToTrace(*thread_sp)); else thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( *thread_sp, signo, description.c_str())); } } if (!handled) thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithSignal( *thread_sp, signo, description.c_str())); } if (!description.empty()) { lldb::StopInfoSP stop_info_sp(thread_sp->GetStopInfo()); if (stop_info_sp) { const char *stop_info_desc = stop_info_sp->GetDescription(); if (!stop_info_desc || !stop_info_desc[0]) stop_info_sp->SetDescription(description.c_str()); } else { thread_sp->SetStopInfo(StopInfo::CreateStopReasonWithException( *thread_sp, description.c_str())); } } } } } } return thread_sp; } lldb::ThreadSP ProcessGDBRemote::SetThreadStopInfo(StructuredData::Dictionary *thread_dict) { static ConstString g_key_tid("tid"); static ConstString g_key_name("name"); static ConstString g_key_reason("reason"); static ConstString g_key_metype("metype"); static ConstString g_key_medata("medata"); static ConstString g_key_qaddr("qaddr"); static ConstString g_key_dispatch_queue_t("dispatch_queue_t"); static ConstString g_key_associated_with_dispatch_queue( "associated_with_dispatch_queue"); static ConstString g_key_queue_name("qname"); static ConstString g_key_queue_kind("qkind"); static ConstString g_key_queue_serial_number("qserialnum"); static ConstString g_key_registers("registers"); static ConstString g_key_memory("memory"); static ConstString g_key_address("address"); static ConstString g_key_bytes("bytes"); static ConstString g_key_description("description"); static ConstString g_key_signal("signal"); // Stop with signal and thread info lldb::tid_t tid = LLDB_INVALID_THREAD_ID; uint8_t signo = 0; std::string value; std::string thread_name; std::string reason; std::string description; uint32_t exc_type = 0; std::vector exc_data; addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; ExpeditedRegisterMap expedited_register_map; bool queue_vars_valid = false; addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; std::string queue_name; QueueKind queue_kind = eQueueKindUnknown; uint64_t queue_serial_number = 0; // Iterate through all of the thread dictionary key/value pairs from the // structured data dictionary thread_dict->ForEach([this, &tid, &expedited_register_map, &thread_name, &signo, &reason, &description, &exc_type, &exc_data, &thread_dispatch_qaddr, &queue_vars_valid, &associated_with_dispatch_queue, &dispatch_queue_t, &queue_name, &queue_kind, &queue_serial_number]( ConstString key, StructuredData::Object *object) -> bool { if (key == g_key_tid) { // thread in big endian hex tid = object->GetIntegerValue(LLDB_INVALID_THREAD_ID); } else if (key == g_key_metype) { // exception type in big endian hex exc_type = object->GetIntegerValue(0); } else if (key == g_key_medata) { // exception data in big endian hex StructuredData::Array *array = object->GetAsArray(); if (array) { array->ForEach([&exc_data](StructuredData::Object *object) -> bool { exc_data.push_back(object->GetIntegerValue()); return true; // Keep iterating through all array items }); } } else if (key == g_key_name) { thread_name = std::string(object->GetStringValue()); } else if (key == g_key_qaddr) { thread_dispatch_qaddr = object->GetIntegerValue(LLDB_INVALID_ADDRESS); } else if (key == g_key_queue_name) { queue_vars_valid = true; queue_name = std::string(object->GetStringValue()); } else if (key == g_key_queue_kind) { std::string queue_kind_str = std::string(object->GetStringValue()); if (queue_kind_str == "serial") { queue_vars_valid = true; queue_kind = eQueueKindSerial; } else if (queue_kind_str == "concurrent") { queue_vars_valid = true; queue_kind = eQueueKindConcurrent; } } else if (key == g_key_queue_serial_number) { queue_serial_number = object->GetIntegerValue(0); if (queue_serial_number != 0) queue_vars_valid = true; } else if (key == g_key_dispatch_queue_t) { dispatch_queue_t = object->GetIntegerValue(0); if (dispatch_queue_t != 0 && dispatch_queue_t != LLDB_INVALID_ADDRESS) queue_vars_valid = true; } else if (key == g_key_associated_with_dispatch_queue) { queue_vars_valid = true; bool associated = object->GetBooleanValue(); if (associated) associated_with_dispatch_queue = eLazyBoolYes; else associated_with_dispatch_queue = eLazyBoolNo; } else if (key == g_key_reason) { reason = std::string(object->GetStringValue()); } else if (key == g_key_description) { description = std::string(object->GetStringValue()); } else if (key == g_key_registers) { StructuredData::Dictionary *registers_dict = object->GetAsDictionary(); if (registers_dict) { registers_dict->ForEach( [&expedited_register_map](ConstString key, StructuredData::Object *object) -> bool { const uint32_t reg = StringConvert::ToUInt32(key.GetCString(), UINT32_MAX, 10); if (reg != UINT32_MAX) expedited_register_map[reg] = std::string(object->GetStringValue()); return true; // Keep iterating through all array items }); } } else if (key == g_key_memory) { StructuredData::Array *array = object->GetAsArray(); if (array) { array->ForEach([this](StructuredData::Object *object) -> bool { StructuredData::Dictionary *mem_cache_dict = object->GetAsDictionary(); if (mem_cache_dict) { lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; if (mem_cache_dict->GetValueForKeyAsInteger( "address", mem_cache_addr)) { if (mem_cache_addr != LLDB_INVALID_ADDRESS) { llvm::StringRef str; if (mem_cache_dict->GetValueForKeyAsString("bytes", str)) { StringExtractor bytes(str); bytes.SetFilePos(0); const size_t byte_size = bytes.GetStringRef().size() / 2; DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); const size_t bytes_copied = bytes.GetHexBytes(data_buffer_sp->GetData(), 0); if (bytes_copied == byte_size) m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); } } } } return true; // Keep iterating through all array items }); } } else if (key == g_key_signal) signo = object->GetIntegerValue(LLDB_INVALID_SIGNAL_NUMBER); return true; // Keep iterating through all dictionary key/value pairs }); return SetThreadStopInfo(tid, expedited_register_map, signo, thread_name, reason, description, exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind, queue_serial_number); } StateType ProcessGDBRemote::SetThreadStopInfo(StringExtractor &stop_packet) { stop_packet.SetFilePos(0); const char stop_type = stop_packet.GetChar(); switch (stop_type) { case 'T': case 'S': { // This is a bit of a hack, but is is required. If we did exec, we need to // clear our thread lists and also know to rebuild our dynamic register // info before we lookup and threads and populate the expedited register // values so we need to know this right away so we can cleanup and update // our registers. const uint32_t stop_id = GetStopID(); if (stop_id == 0) { // Our first stop, make sure we have a process ID, and also make sure we // know about our registers if (GetID() == LLDB_INVALID_PROCESS_ID) { lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); if (pid != LLDB_INVALID_PROCESS_ID) SetID(pid); } BuildDynamicRegisterInfo(true); } // Stop with signal and thread info lldb::tid_t tid = LLDB_INVALID_THREAD_ID; const uint8_t signo = stop_packet.GetHexU8(); llvm::StringRef key; llvm::StringRef value; std::string thread_name; std::string reason; std::string description; uint32_t exc_type = 0; std::vector exc_data; addr_t thread_dispatch_qaddr = LLDB_INVALID_ADDRESS; bool queue_vars_valid = false; // says if locals below that start with "queue_" are valid addr_t dispatch_queue_t = LLDB_INVALID_ADDRESS; LazyBool associated_with_dispatch_queue = eLazyBoolCalculate; std::string queue_name; QueueKind queue_kind = eQueueKindUnknown; uint64_t queue_serial_number = 0; ExpeditedRegisterMap expedited_register_map; while (stop_packet.GetNameColonValue(key, value)) { if (key.compare("metype") == 0) { // exception type in big endian hex value.getAsInteger(16, exc_type); } else if (key.compare("medata") == 0) { // exception data in big endian hex uint64_t x; value.getAsInteger(16, x); exc_data.push_back(x); } else if (key.compare("thread") == 0) { // thread in big endian hex if (value.getAsInteger(16, tid)) tid = LLDB_INVALID_THREAD_ID; } else if (key.compare("threads") == 0) { std::lock_guard guard( m_thread_list_real.GetMutex()); m_thread_ids.clear(); // A comma separated list of all threads in the current // process that includes the thread for this stop reply packet lldb::tid_t tid; while (!value.empty()) { llvm::StringRef tid_str; std::tie(tid_str, value) = value.split(','); if (tid_str.getAsInteger(16, tid)) tid = LLDB_INVALID_THREAD_ID; m_thread_ids.push_back(tid); } } else if (key.compare("thread-pcs") == 0) { m_thread_pcs.clear(); // A comma separated list of all threads in the current // process that includes the thread for this stop reply packet lldb::addr_t pc; while (!value.empty()) { llvm::StringRef pc_str; std::tie(pc_str, value) = value.split(','); if (pc_str.getAsInteger(16, pc)) pc = LLDB_INVALID_ADDRESS; m_thread_pcs.push_back(pc); } } else if (key.compare("jstopinfo") == 0) { StringExtractor json_extractor(value); std::string json; // Now convert the HEX bytes into a string value json_extractor.GetHexByteString(json); // This JSON contains thread IDs and thread stop info for all threads. // It doesn't contain expedited registers, memory or queue info. m_jstopinfo_sp = StructuredData::ParseJSON(json); } else if (key.compare("hexname") == 0) { StringExtractor name_extractor(value); std::string name; // Now convert the HEX bytes into a string value name_extractor.GetHexByteString(thread_name); } else if (key.compare("name") == 0) { thread_name = std::string(value); } else if (key.compare("qaddr") == 0) { value.getAsInteger(16, thread_dispatch_qaddr); } else if (key.compare("dispatch_queue_t") == 0) { queue_vars_valid = true; value.getAsInteger(16, dispatch_queue_t); } else if (key.compare("qname") == 0) { queue_vars_valid = true; StringExtractor name_extractor(value); // Now convert the HEX bytes into a string value name_extractor.GetHexByteString(queue_name); } else if (key.compare("qkind") == 0) { queue_kind = llvm::StringSwitch(value) .Case("serial", eQueueKindSerial) .Case("concurrent", eQueueKindConcurrent) .Default(eQueueKindUnknown); queue_vars_valid = queue_kind != eQueueKindUnknown; } else if (key.compare("qserialnum") == 0) { if (!value.getAsInteger(0, queue_serial_number)) queue_vars_valid = true; } else if (key.compare("reason") == 0) { reason = std::string(value); } else if (key.compare("description") == 0) { StringExtractor desc_extractor(value); // Now convert the HEX bytes into a string value desc_extractor.GetHexByteString(description); } else if (key.compare("memory") == 0) { // Expedited memory. GDB servers can choose to send back expedited // memory that can populate the L1 memory cache in the process so that // things like the frame pointer backchain can be expedited. This will // help stack backtracing be more efficient by not having to send as // many memory read requests down the remote GDB server. // Key/value pair format: memory:=; // is a number whose base will be interpreted by the prefix: // "0x[0-9a-fA-F]+" for hex // "0[0-7]+" for octal // "[1-9]+" for decimal // is native endian ASCII hex bytes just like the register // values llvm::StringRef addr_str, bytes_str; std::tie(addr_str, bytes_str) = value.split('='); if (!addr_str.empty() && !bytes_str.empty()) { lldb::addr_t mem_cache_addr = LLDB_INVALID_ADDRESS; if (!addr_str.getAsInteger(0, mem_cache_addr)) { StringExtractor bytes(bytes_str); const size_t byte_size = bytes.GetBytesLeft() / 2; DataBufferSP data_buffer_sp(new DataBufferHeap(byte_size, 0)); const size_t bytes_copied = bytes.GetHexBytes(data_buffer_sp->GetData(), 0); if (bytes_copied == byte_size) m_memory_cache.AddL1CacheData(mem_cache_addr, data_buffer_sp); } } } else if (key.compare("watch") == 0 || key.compare("rwatch") == 0 || key.compare("awatch") == 0) { // Support standard GDB remote stop reply packet 'TAAwatch:addr' lldb::addr_t wp_addr = LLDB_INVALID_ADDRESS; value.getAsInteger(16, wp_addr); WatchpointSP wp_sp = GetTarget().GetWatchpointList().FindByAddress(wp_addr); uint32_t wp_index = LLDB_INVALID_INDEX32; if (wp_sp) wp_index = wp_sp->GetHardwareIndex(); reason = "watchpoint"; StreamString ostr; ostr.Printf("%" PRIu64 " %" PRIu32, wp_addr, wp_index); description = std::string(ostr.GetString()); } else if (key.compare("library") == 0) { auto error = LoadModules(); if (error) { Log *log( ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOG_ERROR(log, std::move(error), "Failed to load modules: {0}"); } } else if (key.size() == 2 && ::isxdigit(key[0]) && ::isxdigit(key[1])) { uint32_t reg = UINT32_MAX; if (!key.getAsInteger(16, reg)) expedited_register_map[reg] = std::string(std::move(value)); } } if (tid == LLDB_INVALID_THREAD_ID) { // A thread id may be invalid if the response is old style 'S' packet // which does not provide the // thread information. So update the thread list and choose the first // one. UpdateThreadIDList(); if (!m_thread_ids.empty()) { tid = m_thread_ids.front(); } } ThreadSP thread_sp = SetThreadStopInfo( tid, expedited_register_map, signo, thread_name, reason, description, exc_type, exc_data, thread_dispatch_qaddr, queue_vars_valid, associated_with_dispatch_queue, dispatch_queue_t, queue_name, queue_kind, queue_serial_number); return eStateStopped; } break; case 'W': case 'X': // process exited return eStateExited; default: break; } return eStateInvalid; } void ProcessGDBRemote::RefreshStateAfterStop() { std::lock_guard guard(m_thread_list_real.GetMutex()); m_thread_ids.clear(); m_thread_pcs.clear(); // Set the thread stop info. It might have a "threads" key whose value is a // list of all thread IDs in the current process, so m_thread_ids might get // set. // 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(); // Scope for the lock { // Lock the thread stack while we access it std::lock_guard guard(m_last_stop_packet_mutex); // Get the number of stop packets on the stack int nItems = m_stop_packet_stack.size(); // Iterate over them for (int i = 0; i < nItems; i++) { // Get the thread stop info StringExtractorGDBRemote stop_info = m_stop_packet_stack[i]; // Process thread stop info SetThreadStopInfo(stop_info); } // Clear the thread stop stack m_stop_packet_stack.clear(); } // If we have queried for a default thread id if (m_initial_tid != LLDB_INVALID_THREAD_ID) { m_thread_list.SetSelectedThreadByID(m_initial_tid); m_initial_tid = LLDB_INVALID_THREAD_ID; } // Let all threads recover from stopping and do any clean up based on the // previous thread state (if any). m_thread_list_real.RefreshStateAfterStop(); } Status ProcessGDBRemote::DoHalt(bool &caused_stop) { Status error; if (m_public_state.GetValue() == eStateAttaching) { // We are being asked to halt during an attach. We need to just close our // file handle and debugserver will go away, and we can be done... m_gdb_comm.Disconnect(); } else caused_stop = m_gdb_comm.Interrupt(); return error; } Status ProcessGDBRemote::DoDetach(bool keep_stopped) { Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::DoDetach(keep_stopped: %i)", keep_stopped); error = m_gdb_comm.Detach(keep_stopped); if (log) { if (error.Success()) log->PutCString( "ProcessGDBRemote::DoDetach() detach packet sent successfully"); else LLDB_LOGF(log, "ProcessGDBRemote::DoDetach() detach packet send failed: %s", error.AsCString() ? error.AsCString() : ""); } if (!error.Success()) return error; // Sleep for one second to let the process get all detached... StopAsyncThread(); SetPrivateState(eStateDetached); ResumePrivateStateThread(); // KillDebugserverProcess (); return error; } Status ProcessGDBRemote::DoDestroy() { Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy()"); +#ifdef LLDB_ENABLE_ALL // XXX Currently no iOS target support on FreeBSD // There is a bug in older iOS debugservers where they don't shut down the // process they are debugging properly. If the process is sitting at a // breakpoint or an exception, this can cause problems with restarting. So // we check to see if any of our threads are stopped at a breakpoint, and if // so we remove all the breakpoints, resume the process, and THEN destroy it // again. // // Note, we don't have a good way to test the version of debugserver, but I // happen to know that the set of all the iOS debugservers which don't // support GetThreadSuffixSupported() and that of the debugservers with this // bug are equal. There really should be a better way to test this! // // We also use m_destroy_tried_resuming to make sure we only do this once, if // we resume and then halt and get called here to destroy again and we're // still at a breakpoint or exception, then we should just do the straight- // forward kill. // // And of course, if we weren't able to stop the process by the time we get // here, it isn't necessary (or helpful) to do any of this. if (!m_gdb_comm.GetThreadSuffixSupported() && m_public_state.GetValue() != eStateRunning) { PlatformSP platform_sp = GetTarget().GetPlatform(); // FIXME: These should be ConstStrings so we aren't doing strcmp'ing. if (platform_sp && platform_sp->GetName() && platform_sp->GetName() == PlatformRemoteiOS::GetPluginNameStatic()) { if (m_destroy_tried_resuming) { if (log) log->PutCString("ProcessGDBRemote::DoDestroy() - Tried resuming to " "destroy once already, not doing it again."); } else { // At present, the plans are discarded and the breakpoints disabled // Process::Destroy, but we really need it to happen here and it // doesn't matter if we do it twice. m_thread_list.DiscardThreadPlans(); DisableAllBreakpointSites(); bool stop_looks_like_crash = false; ThreadList &threads = GetThreadList(); { std::lock_guard guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); for (size_t i = 0; i < num_threads; i++) { ThreadSP thread_sp = threads.GetThreadAtIndex(i); StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); StopReason reason = eStopReasonInvalid; if (stop_info_sp) reason = stop_info_sp->GetStopReason(); if (reason == eStopReasonBreakpoint || reason == eStopReasonException) { LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy() - thread: 0x%4.4" PRIx64 " stopped with reason: %s.", thread_sp->GetProtocolID(), stop_info_sp->GetDescription()); stop_looks_like_crash = true; break; } } } if (stop_looks_like_crash) { if (log) log->PutCString("ProcessGDBRemote::DoDestroy() - Stopped at a " "breakpoint, continue and then kill."); m_destroy_tried_resuming = true; // If we are going to run again before killing, it would be good to // suspend all the threads before resuming so they won't get into // more trouble. Sadly, for the threads stopped with the breakpoint // or exception, the exception doesn't get cleared if it is // suspended, so we do have to run the risk of letting those threads // proceed a bit. { std::lock_guard guard(threads.GetMutex()); size_t num_threads = threads.GetSize(); for (size_t i = 0; i < num_threads; i++) { ThreadSP thread_sp = threads.GetThreadAtIndex(i); StopInfoSP stop_info_sp = thread_sp->GetPrivateStopInfo(); StopReason reason = eStopReasonInvalid; if (stop_info_sp) reason = stop_info_sp->GetStopReason(); if (reason != eStopReasonBreakpoint && reason != eStopReasonException) { LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy() - Suspending " "thread: 0x%4.4" PRIx64 " before running.", thread_sp->GetProtocolID()); thread_sp->SetResumeState(eStateSuspended); } } } Resume(); return Destroy(false); } } } } +#endif // LLDB_ENABLE_ALL // Interrupt if our inferior is running... int exit_status = SIGABRT; std::string exit_string; if (m_gdb_comm.IsConnected()) { if (m_public_state.GetValue() != eStateAttaching) { StringExtractorGDBRemote response; bool send_async = true; GDBRemoteCommunication::ScopedTimeout(m_gdb_comm, std::chrono::seconds(3)); if (m_gdb_comm.SendPacketAndWaitForResponse("k", response, send_async) == GDBRemoteCommunication::PacketResult::Success) { char packet_cmd = response.GetChar(0); if (packet_cmd == 'W' || packet_cmd == 'X') { #if defined(__APPLE__) // For Native processes on Mac OS X, we launch through the Host // Platform, then hand the process off to debugserver, which becomes // the parent process through "PT_ATTACH". Then when we go to kill // the process on Mac OS X we call ptrace(PT_KILL) to kill it, then // we call waitpid which returns with no error and the correct // status. But amusingly enough that doesn't seem to actually reap // the process, but instead it is left around as a Zombie. Probably // the kernel is in the process of switching ownership back to lldb // which was the original parent, and gets confused in the handoff. // Anyway, so call waitpid here to finally reap it. PlatformSP platform_sp(GetTarget().GetPlatform()); if (platform_sp && platform_sp->IsHost()) { int status; ::pid_t reap_pid; reap_pid = waitpid(GetID(), &status, WNOHANG); LLDB_LOGF(log, "Reaped pid: %d, status: %d.\n", reap_pid, status); } #endif SetLastStopPacket(response); ClearThreadIDList(); exit_status = response.GetHexU8(); } else { LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - got unexpected response " "to k packet: %s", response.GetStringRef().data()); exit_string.assign("got unexpected response to k packet: "); exit_string.append(std::string(response.GetStringRef())); } } else { LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - failed to send k packet"); exit_string.assign("failed to send the k packet"); } } else { LLDB_LOGF(log, "ProcessGDBRemote::DoDestroy - killed or interrupted while " "attaching"); exit_string.assign("killed or interrupted while attaching."); } } else { // If we missed setting the exit status on the way out, do it here. // NB set exit status can be called multiple times, the first one sets the // status. exit_string.assign("destroying when not connected to debugserver"); } SetExitStatus(exit_status, exit_string.c_str()); StopAsyncThread(); KillDebugserverProcess(); return error; } void ProcessGDBRemote::SetLastStopPacket( const StringExtractorGDBRemote &response) { const bool did_exec = response.GetStringRef().find(";reason:exec;") != std::string::npos; if (did_exec) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::SetLastStopPacket () - detected exec"); m_thread_list_real.Clear(); m_thread_list.Clear(); BuildDynamicRegisterInfo(true); m_gdb_comm.ResetDiscoverableSettings(did_exec); } // Scope the lock { // Lock the thread stack while we access it std::lock_guard guard(m_last_stop_packet_mutex); // We are are not using non-stop mode, there can only be one last stop // reply packet, so clear the list. if (!GetTarget().GetNonStopModeEnabled()) m_stop_packet_stack.clear(); // Add this stop packet to the stop packet stack This stack will get popped // and examined when we switch to the Stopped state m_stop_packet_stack.push_back(response); } } void ProcessGDBRemote::SetUnixSignals(const UnixSignalsSP &signals_sp) { Process::SetUnixSignals(std::make_shared(signals_sp)); } // Process Queries bool ProcessGDBRemote::IsAlive() { return m_gdb_comm.IsConnected() && Process::IsAlive(); } addr_t ProcessGDBRemote::GetImageInfoAddress() { // request the link map address via the $qShlibInfoAddr packet lldb::addr_t addr = m_gdb_comm.GetShlibInfoAddr(); // the loaded module list can also provides a link map address if (addr == LLDB_INVALID_ADDRESS) { llvm::Expected list = GetLoadedModuleList(); if (!list) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOG_ERROR(log, list.takeError(), "Failed to read module list: {0}"); } else { addr = list->m_link_map; } } return addr; } void ProcessGDBRemote::WillPublicStop() { // See if the GDB remote client supports the JSON threads info. If so, we // gather stop info for all threads, expedited registers, expedited memory, // runtime queue information (iOS and MacOSX only), and more. Expediting // memory will help stack backtracing be much faster. Expediting registers // will make sure we don't have to read the thread registers for GPRs. m_jthreadsinfo_sp = m_gdb_comm.GetThreadsInfo(); if (m_jthreadsinfo_sp) { // Now set the stop info for each thread and also expedite any registers // and memory that was in the jThreadsInfo response. StructuredData::Array *thread_infos = m_jthreadsinfo_sp->GetAsArray(); if (thread_infos) { const size_t n = thread_infos->GetSize(); for (size_t i = 0; i < n; ++i) { StructuredData::Dictionary *thread_dict = thread_infos->GetItemAtIndex(i)->GetAsDictionary(); if (thread_dict) SetThreadStopInfo(thread_dict); } } } } // Process Memory size_t ProcessGDBRemote::DoReadMemory(addr_t addr, void *buf, size_t size, Status &error) { GetMaxMemorySize(); bool binary_memory_read = m_gdb_comm.GetxPacketSupported(); // M and m packets take 2 bytes for 1 byte of memory size_t max_memory_size = binary_memory_read ? m_max_memory_size : m_max_memory_size / 2; if (size > max_memory_size) { // Keep memory read sizes down to a sane limit. This function will be // called multiple times in order to complete the task by // lldb_private::Process so it is ok to do this. size = max_memory_size; } char packet[64]; int packet_len; packet_len = ::snprintf(packet, sizeof(packet), "%c%" PRIx64 ",%" PRIx64, binary_memory_read ? 'x' : 'm', (uint64_t)addr, (uint64_t)size); assert(packet_len + 1 < (int)sizeof(packet)); UNUSED_IF_ASSERT_DISABLED(packet_len); StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet, response, true) == GDBRemoteCommunication::PacketResult::Success) { if (response.IsNormalResponse()) { error.Clear(); if (binary_memory_read) { // The lower level GDBRemoteCommunication packet receive layer has // already de-quoted any 0x7d character escaping that was present in // the packet size_t data_received_size = response.GetBytesLeft(); if (data_received_size > size) { // Don't write past the end of BUF if the remote debug server gave us // too much data for some reason. data_received_size = size; } memcpy(buf, response.GetStringRef().data(), data_received_size); return data_received_size; } else { return response.GetHexBytes( llvm::MutableArrayRef((uint8_t *)buf, size), '\xdd'); } } else if (response.IsErrorResponse()) error.SetErrorStringWithFormat("memory read failed for 0x%" PRIx64, addr); else if (response.IsUnsupportedResponse()) error.SetErrorStringWithFormat( "GDB server does not support reading memory"); else error.SetErrorStringWithFormat( "unexpected response to GDB server memory read packet '%s': '%s'", packet, response.GetStringRef().data()); } else { error.SetErrorStringWithFormat("failed to send packet: '%s'", packet); } return 0; } Status ProcessGDBRemote::WriteObjectFile( std::vector entries) { Status error; // Sort the entries by address because some writes, like those to flash // memory, must happen in order of increasing address. std::stable_sort( std::begin(entries), std::end(entries), [](const ObjectFile::LoadableData a, const ObjectFile::LoadableData b) { return a.Dest < b.Dest; }); m_allow_flash_writes = true; error = Process::WriteObjectFile(entries); if (error.Success()) error = FlashDone(); else // Even though some of the writing failed, try to send a flash done if some // of the writing succeeded so the flash state is reset to normal, but // don't stomp on the error status that was set in the write failure since // that's the one we want to report back. FlashDone(); m_allow_flash_writes = false; return error; } bool ProcessGDBRemote::HasErased(FlashRange range) { auto size = m_erased_flash_ranges.GetSize(); for (size_t i = 0; i < size; ++i) if (m_erased_flash_ranges.GetEntryAtIndex(i)->Contains(range)) return true; return false; } Status ProcessGDBRemote::FlashErase(lldb::addr_t addr, size_t size) { Status status; MemoryRegionInfo region; status = GetMemoryRegionInfo(addr, region); if (!status.Success()) return status; // The gdb spec doesn't say if erasures are allowed across multiple regions, // but we'll disallow it to be safe and to keep the logic simple by worring // about only one region's block size. DoMemoryWrite is this function's // primary user, and it can easily keep writes within a single memory region if (addr + size > region.GetRange().GetRangeEnd()) { status.SetErrorString("Unable to erase flash in multiple regions"); return status; } uint64_t blocksize = region.GetBlocksize(); if (blocksize == 0) { status.SetErrorString("Unable to erase flash because blocksize is 0"); return status; } // Erasures can only be done on block boundary adresses, so round down addr // and round up size lldb::addr_t block_start_addr = addr - (addr % blocksize); size += (addr - block_start_addr); if ((size % blocksize) != 0) size += (blocksize - size % blocksize); FlashRange range(block_start_addr, size); if (HasErased(range)) return status; // We haven't erased the entire range, but we may have erased part of it. // (e.g., block A is already erased and range starts in A and ends in B). So, // adjust range if necessary to exclude already erased blocks. if (!m_erased_flash_ranges.IsEmpty()) { // Assuming that writes and erasures are done in increasing addr order, // because that is a requirement of the vFlashWrite command. Therefore, we // only need to look at the last range in the list for overlap. const auto &last_range = *m_erased_flash_ranges.Back(); if (range.GetRangeBase() < last_range.GetRangeEnd()) { auto overlap = last_range.GetRangeEnd() - range.GetRangeBase(); // overlap will be less than range.GetByteSize() or else HasErased() // would have been true range.SetByteSize(range.GetByteSize() - overlap); range.SetRangeBase(range.GetRangeBase() + overlap); } } StreamString packet; packet.Printf("vFlashErase:%" PRIx64 ",%" PRIx64, range.GetRangeBase(), (uint64_t)range.GetByteSize()); StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, true) == GDBRemoteCommunication::PacketResult::Success) { if (response.IsOKResponse()) { m_erased_flash_ranges.Insert(range, true); } else { if (response.IsErrorResponse()) status.SetErrorStringWithFormat("flash erase failed for 0x%" PRIx64, addr); else if (response.IsUnsupportedResponse()) status.SetErrorStringWithFormat("GDB server does not support flashing"); else status.SetErrorStringWithFormat( "unexpected response to GDB server flash erase packet '%s': '%s'", packet.GetData(), response.GetStringRef().data()); } } else { status.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetData()); } return status; } Status ProcessGDBRemote::FlashDone() { Status status; // If we haven't erased any blocks, then we must not have written anything // either, so there is no need to actually send a vFlashDone command if (m_erased_flash_ranges.IsEmpty()) return status; StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse("vFlashDone", response, true) == GDBRemoteCommunication::PacketResult::Success) { if (response.IsOKResponse()) { m_erased_flash_ranges.Clear(); } else { if (response.IsErrorResponse()) status.SetErrorStringWithFormat("flash done failed"); else if (response.IsUnsupportedResponse()) status.SetErrorStringWithFormat("GDB server does not support flashing"); else status.SetErrorStringWithFormat( "unexpected response to GDB server flash done packet: '%s'", response.GetStringRef().data()); } } else { status.SetErrorStringWithFormat("failed to send flash done packet"); } return status; } size_t ProcessGDBRemote::DoWriteMemory(addr_t addr, const void *buf, size_t size, Status &error) { GetMaxMemorySize(); // M and m packets take 2 bytes for 1 byte of memory size_t max_memory_size = m_max_memory_size / 2; if (size > max_memory_size) { // Keep memory read sizes down to a sane limit. This function will be // called multiple times in order to complete the task by // lldb_private::Process so it is ok to do this. size = max_memory_size; } StreamGDBRemote packet; MemoryRegionInfo region; Status region_status = GetMemoryRegionInfo(addr, region); bool is_flash = region_status.Success() && region.GetFlash() == MemoryRegionInfo::eYes; if (is_flash) { if (!m_allow_flash_writes) { error.SetErrorString("Writing to flash memory is not allowed"); return 0; } // Keep the write within a flash memory region if (addr + size > region.GetRange().GetRangeEnd()) size = region.GetRange().GetRangeEnd() - addr; // Flash memory must be erased before it can be written error = FlashErase(addr, size); if (!error.Success()) return 0; packet.Printf("vFlashWrite:%" PRIx64 ":", addr); packet.PutEscapedBytes(buf, size); } else { packet.Printf("M%" PRIx64 ",%" PRIx64 ":", addr, (uint64_t)size); packet.PutBytesAsRawHex8(buf, size, endian::InlHostByteOrder(), endian::InlHostByteOrder()); } StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, true) == GDBRemoteCommunication::PacketResult::Success) { if (response.IsOKResponse()) { error.Clear(); return size; } else if (response.IsErrorResponse()) error.SetErrorStringWithFormat("memory write failed for 0x%" PRIx64, addr); else if (response.IsUnsupportedResponse()) error.SetErrorStringWithFormat( "GDB server does not support writing memory"); else error.SetErrorStringWithFormat( "unexpected response to GDB server memory write packet '%s': '%s'", packet.GetData(), response.GetStringRef().data()); } else { error.SetErrorStringWithFormat("failed to send packet: '%s'", packet.GetData()); } return 0; } lldb::addr_t ProcessGDBRemote::DoAllocateMemory(size_t size, uint32_t permissions, Status &error) { Log *log( GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS | LIBLLDB_LOG_EXPRESSIONS)); addr_t allocated_addr = LLDB_INVALID_ADDRESS; if (m_gdb_comm.SupportsAllocDeallocMemory() != eLazyBoolNo) { allocated_addr = m_gdb_comm.AllocateMemory(size, permissions); if (allocated_addr != LLDB_INVALID_ADDRESS || m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolYes) return allocated_addr; } if (m_gdb_comm.SupportsAllocDeallocMemory() == eLazyBoolNo) { // Call mmap() to create memory in the inferior.. unsigned prot = 0; if (permissions & lldb::ePermissionsReadable) prot |= eMmapProtRead; if (permissions & lldb::ePermissionsWritable) prot |= eMmapProtWrite; if (permissions & lldb::ePermissionsExecutable) prot |= eMmapProtExec; if (InferiorCallMmap(this, allocated_addr, 0, size, prot, eMmapFlagsAnon | eMmapFlagsPrivate, -1, 0)) m_addr_to_mmap_size[allocated_addr] = size; else { allocated_addr = LLDB_INVALID_ADDRESS; LLDB_LOGF(log, "ProcessGDBRemote::%s no direct stub support for memory " "allocation, and InferiorCallMmap also failed - is stub " "missing register context save/restore capability?", __FUNCTION__); } } if (allocated_addr == LLDB_INVALID_ADDRESS) error.SetErrorStringWithFormat( "unable to allocate %" PRIu64 " bytes of memory with permissions %s", (uint64_t)size, GetPermissionsAsCString(permissions)); else error.Clear(); return allocated_addr; } Status ProcessGDBRemote::GetMemoryRegionInfo(addr_t load_addr, MemoryRegionInfo ®ion_info) { Status error(m_gdb_comm.GetMemoryRegionInfo(load_addr, region_info)); return error; } Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num) { Status error(m_gdb_comm.GetWatchpointSupportInfo(num)); return error; } Status ProcessGDBRemote::GetWatchpointSupportInfo(uint32_t &num, bool &after) { Status error(m_gdb_comm.GetWatchpointSupportInfo( num, after, GetTarget().GetArchitecture())); return error; } Status ProcessGDBRemote::DoDeallocateMemory(lldb::addr_t addr) { Status error; LazyBool supported = m_gdb_comm.SupportsAllocDeallocMemory(); switch (supported) { case eLazyBoolCalculate: // We should never be deallocating memory without allocating memory first // so we should never get eLazyBoolCalculate error.SetErrorString( "tried to deallocate memory without ever allocating memory"); break; case eLazyBoolYes: if (!m_gdb_comm.DeallocateMemory(addr)) error.SetErrorStringWithFormat( "unable to deallocate memory at 0x%" PRIx64, addr); break; case eLazyBoolNo: // Call munmap() to deallocate memory in the inferior.. { MMapMap::iterator pos = m_addr_to_mmap_size.find(addr); if (pos != m_addr_to_mmap_size.end() && InferiorCallMunmap(this, addr, pos->second)) m_addr_to_mmap_size.erase(pos); else error.SetErrorStringWithFormat( "unable to deallocate memory at 0x%" PRIx64, addr); } break; } 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, nullptr); } else if (m_stdin_forward) { m_gdb_comm.SendStdinNotification(src, src_len); } return 0; } Status ProcessGDBRemote::EnableBreakpointSite(BreakpointSite *bp_site) { Status error; assert(bp_site != nullptr); // Get logging info Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_BREAKPOINTS)); user_id_t site_id = bp_site->GetID(); // Get the breakpoint address const addr_t addr = bp_site->GetLoadAddress(); // Log that a breakpoint was requested LLDB_LOGF(log, "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64, site_id, (uint64_t)addr); // Breakpoint already exists and is enabled if (bp_site->IsEnabled()) { LLDB_LOGF(log, "ProcessGDBRemote::EnableBreakpointSite (size_id = %" PRIu64 ") address = 0x%" PRIx64 " -- SUCCESS (already enabled)", site_id, (uint64_t)addr); return error; } // Get the software breakpoint trap opcode size const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); // SupportsGDBStoppointPacket() simply checks a boolean, indicating if this // breakpoint type is supported by the remote stub. These are set to true by // default, and later set to false only after we receive an unimplemented // response when sending a breakpoint packet. This means initially that // unless we were specifically instructed to use a hardware breakpoint, LLDB // will attempt to set a software breakpoint. HardwareRequired() also queries // a boolean variable which indicates if the user specifically asked for // hardware breakpoints. If true then we will skip over software // breakpoints. if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware) && (!bp_site->HardwareRequired())) { // Try to send off a software breakpoint packet ($Z0) uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( eBreakpointSoftware, true, addr, bp_op_size); if (error_no == 0) { // The breakpoint was placed successfully bp_site->SetEnabled(true); bp_site->SetType(BreakpointSite::eExternal); return error; } // SendGDBStoppointTypePacket() will return an error if it was unable to // set this breakpoint. We need to differentiate between a error specific // to placing this breakpoint or if we have learned that this breakpoint // type is unsupported. To do this, we must test the support boolean for // this breakpoint type to see if it now indicates that this breakpoint // type is unsupported. If they are still supported then we should return // with the error code. If they are now unsupported, then we would like to // fall through and try another form of breakpoint. if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointSoftware)) { if (error_no != UINT8_MAX) error.SetErrorStringWithFormat( "error: %d sending the breakpoint request", error_no); else error.SetErrorString("error sending the breakpoint request"); return error; } // We reach here when software breakpoints have been found to be // unsupported. For future calls to set a breakpoint, we will not attempt // to set a breakpoint with a type that is known not to be supported. LLDB_LOGF(log, "Software breakpoints are unsupported"); // So we will fall through and try a hardware breakpoint } // The process of setting a hardware breakpoint is much the same as above. // We check the supported boolean for this breakpoint type, and if it is // thought to be supported then we will try to set this breakpoint with a // hardware breakpoint. if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { // Try to send off a hardware breakpoint packet ($Z1) uint8_t error_no = m_gdb_comm.SendGDBStoppointTypePacket( eBreakpointHardware, true, addr, bp_op_size); if (error_no == 0) { // The breakpoint was placed successfully bp_site->SetEnabled(true); bp_site->SetType(BreakpointSite::eHardware); return error; } // Check if the error was something other then an unsupported breakpoint // type if (m_gdb_comm.SupportsGDBStoppointPacket(eBreakpointHardware)) { // Unable to set this hardware breakpoint if (error_no != UINT8_MAX) error.SetErrorStringWithFormat( "error: %d sending the hardware breakpoint request " "(hardware breakpoint resources might be exhausted or unavailable)", error_no); else error.SetErrorString("error sending the hardware breakpoint request " "(hardware breakpoint resources " "might be exhausted or unavailable)"); return error; } // We will reach here when the stub gives an unsupported response to a // hardware breakpoint LLDB_LOGF(log, "Hardware breakpoints are unsupported"); // Finally we will falling through to a #trap style breakpoint } // Don't fall through when hardware breakpoints were specifically requested if (bp_site->HardwareRequired()) { error.SetErrorString("hardware breakpoints are not supported"); return error; } // As a last resort we want to place a manual breakpoint. An instruction is // placed into the process memory using memory write packets. return EnableSoftwareBreakpoint(bp_site); } Status ProcessGDBRemote::DisableBreakpointSite(BreakpointSite *bp_site) { Status error; 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)); LLDB_LOGF(log, "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64, site_id, (uint64_t)addr); if (bp_site->IsEnabled()) { const size_t bp_op_size = GetSoftwareBreakpointTrapOpcode(bp_site); BreakpointSite::Type bp_type = bp_site->GetType(); switch (bp_type) { case BreakpointSite::eSoftware: error = DisableSoftwareBreakpoint(bp_site); break; case BreakpointSite::eHardware: if (m_gdb_comm.SendGDBStoppointTypePacket(eBreakpointHardware, false, addr, bp_op_size)) error.SetErrorToGenericError(); break; case BreakpointSite::eExternal: { GDBStoppointType stoppoint_type; if (bp_site->IsHardware()) stoppoint_type = eBreakpointHardware; else stoppoint_type = eBreakpointSoftware; if (m_gdb_comm.SendGDBStoppointTypePacket(stoppoint_type, false, addr, bp_op_size)) error.SetErrorToGenericError(); } break; } if (error.Success()) bp_site->SetEnabled(false); } else { LLDB_LOGF(log, "ProcessGDBRemote::DisableBreakpointSite (site_id = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", site_id, (uint64_t)addr); return error; } if (error.Success()) error.SetErrorToGenericError(); return error; } // Pre-requisite: wp != NULL. static GDBStoppointType GetGDBStoppointType(Watchpoint *wp) { assert(wp); bool watch_read = wp->WatchpointRead(); bool watch_write = wp->WatchpointWrite(); // watch_read and watch_write cannot both be false. assert(watch_read || watch_write); if (watch_read && watch_write) return eWatchpointReadWrite; else if (watch_read) return eWatchpointRead; else // Must be watch_write, then. return eWatchpointWrite; } Status ProcessGDBRemote::EnableWatchpoint(Watchpoint *wp, bool notify) { Status error; if (wp) { user_id_t watchID = wp->GetID(); addr_t addr = wp->GetLoadAddress(); Log *log( ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ")", watchID); if (wp->IsEnabled()) { LLDB_LOGF(log, "ProcessGDBRemote::EnableWatchpoint(watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 ": watchpoint already enabled.", watchID, (uint64_t)addr); return error; } GDBStoppointType type = GetGDBStoppointType(wp); // Pass down an appropriate z/Z packet... if (m_gdb_comm.SupportsGDBStoppointPacket(type)) { if (m_gdb_comm.SendGDBStoppointTypePacket(type, true, addr, wp->GetByteSize()) == 0) { wp->SetEnabled(true, notify); return error; } else error.SetErrorString("sending gdb watchpoint packet failed"); } else error.SetErrorString("watchpoints not supported"); } else { error.SetErrorString("Watchpoint argument was NULL."); } if (error.Success()) error.SetErrorToGenericError(); return error; } Status ProcessGDBRemote::DisableWatchpoint(Watchpoint *wp, bool notify) { Status error; if (wp) { user_id_t watchID = wp->GetID(); Log *log( ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_WATCHPOINTS)); addr_t addr = wp->GetLoadAddress(); LLDB_LOGF(log, "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64, watchID, (uint64_t)addr); if (!wp->IsEnabled()) { LLDB_LOGF(log, "ProcessGDBRemote::DisableWatchpoint (watchID = %" PRIu64 ") addr = 0x%8.8" PRIx64 " -- SUCCESS (already disabled)", watchID, (uint64_t)addr); // See also 'class WatchpointSentry' within StopInfo.cpp. This disabling // attempt might come from the user-supplied actions, we'll route it in // order for the watchpoint object to intelligently process this action. wp->SetEnabled(false, notify); return error; } if (wp->IsHardware()) { GDBStoppointType type = GetGDBStoppointType(wp); // Pass down an appropriate z/Z packet... if (m_gdb_comm.SendGDBStoppointTypePacket(type, false, addr, wp->GetByteSize()) == 0) { wp->SetEnabled(false, notify); return error; } else error.SetErrorString("sending gdb watchpoint packet failed"); } // TODO: clear software watchpoints if we implement them } else { error.SetErrorString("Watchpoint argument was NULL."); } if (error.Success()) error.SetErrorToGenericError(); return error; } void ProcessGDBRemote::Clear() { m_thread_list_real.Clear(); m_thread_list.Clear(); } Status ProcessGDBRemote::DoSignal(int signo) { Status error; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::DoSignal (signal = %d)", signo); if (!m_gdb_comm.SendAsyncSignal(signo)) error.SetErrorStringWithFormat("failed to send signal %i", signo); return error; } Status ProcessGDBRemote::ConnectToReplayServer() { Status status = m_gdb_replay_server.Connect(m_gdb_comm); if (status.Fail()) return status; // Enable replay mode. m_replay_mode = true; // Start server thread. m_gdb_replay_server.StartAsyncThread(); // Start client thread. StartAsyncThread(); // Do the usual setup. return ConnectToDebugserver(""); } Status ProcessGDBRemote::EstablishConnectionIfNeeded(const ProcessInfo &process_info) { // Make sure we aren't already connected? if (m_gdb_comm.IsConnected()) return Status(); PlatformSP platform_sp(GetTarget().GetPlatform()); if (platform_sp && !platform_sp->IsHost()) return Status("Lost debug server connection"); if (repro::Reproducer::Instance().IsReplaying()) return ConnectToReplayServer(); auto error = LaunchAndConnectToDebugserver(process_info); if (error.Fail()) { const char *error_string = error.AsCString(); if (error_string == nullptr) error_string = "unable to launch " DEBUGSERVER_BASENAME; } return error; } #if !defined(_WIN32) #define USE_SOCKETPAIR_FOR_LOCAL_CONNECTION 1 #endif #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION static bool SetCloexecFlag(int fd) { #if defined(FD_CLOEXEC) int flags = ::fcntl(fd, F_GETFD); if (flags == -1) return false; return (::fcntl(fd, F_SETFD, flags | FD_CLOEXEC) == 0); #else return false; #endif } #endif Status ProcessGDBRemote::LaunchAndConnectToDebugserver( const ProcessInfo &process_info) { using namespace std::placeholders; // For _1, _2, etc. Status error; if (m_debugserver_pid == LLDB_INVALID_PROCESS_ID) { // If we locate debugserver, keep that located version around static FileSpec g_debugserver_file_spec; ProcessLaunchInfo debugserver_launch_info; // Make debugserver run in its own session so signals generated by special // terminal key sequences (^C) don't affect debugserver. debugserver_launch_info.SetLaunchInSeparateProcessGroup(true); const std::weak_ptr this_wp = std::static_pointer_cast(shared_from_this()); debugserver_launch_info.SetMonitorProcessCallback( std::bind(MonitorDebugserverProcess, this_wp, _1, _2, _3, _4), false); debugserver_launch_info.SetUserID(process_info.GetUserID()); #if defined(__APPLE__) // On macOS 11, we need to support x86_64 applications translated to // arm64. We check whether a binary is translated and spawn the correct // debugserver accordingly. int mib[] = { CTL_KERN, KERN_PROC, KERN_PROC_PID, static_cast(process_info.GetProcessID()) }; struct kinfo_proc processInfo; size_t bufsize = sizeof(processInfo); if (sysctl(mib, (unsigned)(sizeof(mib)/sizeof(int)), &processInfo, &bufsize, NULL, 0) == 0 && bufsize > 0) { if (processInfo.kp_proc.p_flag & P_TRANSLATED) { FileSpec rosetta_debugserver("/Library/Apple/usr/libexec/oah/debugserver"); debugserver_launch_info.SetExecutableFile(rosetta_debugserver, false); } } #endif int communication_fd = -1; #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION // Use a socketpair on non-Windows systems for security and performance // reasons. int sockets[2]; /* the pair of socket descriptors */ if (socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == -1) { error.SetErrorToErrno(); return error; } int our_socket = sockets[0]; int gdb_socket = sockets[1]; auto cleanup_our = llvm::make_scope_exit([&]() { close(our_socket); }); auto cleanup_gdb = llvm::make_scope_exit([&]() { close(gdb_socket); }); // Don't let any child processes inherit our communication socket SetCloexecFlag(our_socket); communication_fd = gdb_socket; #endif error = m_gdb_comm.StartDebugserverProcess( nullptr, GetTarget().GetPlatform().get(), debugserver_launch_info, nullptr, nullptr, communication_fd); if (error.Success()) m_debugserver_pid = debugserver_launch_info.GetProcessID(); else m_debugserver_pid = LLDB_INVALID_PROCESS_ID; if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { #ifdef USE_SOCKETPAIR_FOR_LOCAL_CONNECTION // Our process spawned correctly, we can now set our connection to use // our end of the socket pair cleanup_our.release(); m_gdb_comm.SetConnection( std::make_unique(our_socket, true)); #endif StartAsyncThread(); } if (error.Fail()) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "failed to start debugserver process: %s", error.AsCString()); return error; } if (m_gdb_comm.IsConnected()) { // Finish the connection process by doing the handshake without // connecting (send NULL URL) error = ConnectToDebugserver(""); } else { error.SetErrorString("connection failed"); } } return error; } bool ProcessGDBRemote::MonitorDebugserverProcess( std::weak_ptr process_wp, lldb::pid_t debugserver_pid, bool exited, // True if the process did exit int signo, // Zero for no signal int exit_status // Exit value of process if signal is zero ) { // "debugserver_pid" argument passed in is the process ID for debugserver // that we are tracking... Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); const bool handled = true; LLDB_LOGF(log, "ProcessGDBRemote::%s(process_wp, pid=%" PRIu64 ", signo=%i (0x%x), exit_status=%i)", __FUNCTION__, debugserver_pid, signo, signo, exit_status); std::shared_ptr process_sp = process_wp.lock(); LLDB_LOGF(log, "ProcessGDBRemote::%s(process = %p)", __FUNCTION__, static_cast(process_sp.get())); if (!process_sp || process_sp->m_debugserver_pid != debugserver_pid) return handled; // Sleep for a half a second to make sure our inferior process has time to // set its exit status before we set it incorrectly when both the debugserver // and the inferior process shut down. std::this_thread::sleep_for(std::chrono::milliseconds(500)); // If our process hasn't yet exited, debugserver might have died. If the // process did exit, then we are reaping it. const StateType state = process_sp->GetState(); if (state != eStateInvalid && state != eStateUnloaded && state != eStateExited && state != eStateDetached) { char error_str[1024]; if (signo) { const char *signal_cstr = process_sp->GetUnixSignals()->GetSignalAsCString(signo); if (signal_cstr) ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %s", signal_cstr); else ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with signal %i", signo); } else { ::snprintf(error_str, sizeof(error_str), DEBUGSERVER_BASENAME " died with an exit status of 0x%8.8x", exit_status); } process_sp->SetExitStatus(-1, error_str); } // Debugserver has exited we need to let our ProcessGDBRemote know that it no // longer has a debugserver instance process_sp->m_debugserver_pid = LLDB_INVALID_PROCESS_ID; return handled; } void ProcessGDBRemote::KillDebugserverProcess() { m_gdb_comm.Disconnect(); if (m_debugserver_pid != LLDB_INVALID_PROCESS_ID) { Host::Kill(m_debugserver_pid, SIGINT); m_debugserver_pid = LLDB_INVALID_PROCESS_ID; } } void ProcessGDBRemote::Initialize() { static llvm::once_flag g_once_flag; llvm::call_once(g_once_flag, []() { PluginManager::RegisterPlugin(GetPluginNameStatic(), GetPluginDescriptionStatic(), CreateInstance, DebuggerInitialize); }); } void ProcessGDBRemote::DebuggerInitialize(Debugger &debugger) { if (!PluginManager::GetSettingForProcessPlugin( debugger, PluginProperties::GetSettingName())) { const bool is_global_setting = true; PluginManager::CreateSettingForProcessPlugin( debugger, GetGlobalPluginProperties()->GetValueProperties(), ConstString("Properties for the gdb-remote process plug-in."), is_global_setting); } } bool ProcessGDBRemote::StartAsyncThread() { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); std::lock_guard guard(m_async_thread_state_mutex); 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). llvm::Expected async_thread = ThreadLauncher::LaunchThread( "", ProcessGDBRemote::AsyncThread, this); if (!async_thread) { LLDB_LOG_ERROR(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_HOST), async_thread.takeError(), "failed to launch host thread: {}"); return false; } m_async_thread = *async_thread; } else LLDB_LOGF(log, "ProcessGDBRemote::%s () - Called when Async thread was " "already running.", __FUNCTION__); return m_async_thread.IsJoinable(); } void ProcessGDBRemote::StopAsyncThread() { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::%s ()", __FUNCTION__); std::lock_guard guard(m_async_thread_state_mutex); if (m_async_thread.IsJoinable()) { m_async_broadcaster.BroadcastEvent(eBroadcastBitAsyncThreadShouldExit); // This will shut down the async thread. m_gdb_comm.Disconnect(); // Disconnect from the debug server. // Stop the stdio thread m_async_thread.Join(nullptr); m_async_thread.Reset(); } else LLDB_LOGF( log, "ProcessGDBRemote::%s () - Called when Async thread was not running.", __FUNCTION__); } bool ProcessGDBRemote::HandleNotifyPacket(StringExtractorGDBRemote &packet) { // get the packet at a string const std::string &pkt = std::string(packet.GetStringRef()); // skip %stop: StringExtractorGDBRemote stop_info(pkt.c_str() + 5); // pass as a thread stop info packet SetLastStopPacket(stop_info); // check for more stop reasons HandleStopReplySequence(); // if the process is stopped then we need to fake a resume so that we can // stop properly with the new break. This is possible due to // SetPrivateState() broadcasting the state change as a side effect. if (GetPrivateState() == lldb::StateType::eStateStopped) { SetPrivateState(lldb::StateType::eStateRunning); } // since we have some stopped packets we can halt the process SetPrivateState(lldb::StateType::eStateStopped); return true; } thread_result_t ProcessGDBRemote::AsyncThread(void *arg) { ProcessGDBRemote *process = (ProcessGDBRemote *)arg; Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread starting...", __FUNCTION__, arg, process->GetID()); EventSP event_sp; bool done = false; while (!done) { LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp)...", __FUNCTION__, arg, process->GetID()); if (process->m_async_listener_sp->GetEvent(event_sp, llvm::None)) { const uint32_t event_type = event_sp->GetType(); if (event_sp->BroadcasterIs(&process->m_async_broadcaster)) { LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") Got an event of type: %d...", __FUNCTION__, arg, process->GetID(), event_type); switch (event_type) { case eBroadcastBitAsyncContinue: { const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event_sp.get()); if (continue_packet) { const char *continue_cstr = (const char *)continue_packet->GetBytes(); const size_t continue_cstr_len = continue_packet->GetByteSize(); LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncContinue: %s", __FUNCTION__, arg, process->GetID(), continue_cstr); if (::strstr(continue_cstr, "vAttach") == nullptr) process->SetPrivateState(eStateRunning); StringExtractorGDBRemote response; // If in Non-Stop-Mode if (process->GetTarget().GetNonStopModeEnabled()) { // send the vCont packet if (!process->GetGDBRemote().SendvContPacket( llvm::StringRef(continue_cstr, continue_cstr_len), response)) { // Something went wrong done = true; break; } } // If in All-Stop-Mode else { StateType stop_state = process->GetGDBRemote().SendContinuePacketAndWaitForResponse( *process, *process->GetUnixSignals(), llvm::StringRef(continue_cstr, continue_cstr_len), response); // We need to immediately clear the thread ID list so we are sure // to get a valid list of threads. The thread ID list might be // contained within the "response", or the stop reply packet that // caused the stop. So clear it now before we give the stop reply // packet to the process using the // process->SetLastStopPacket()... process->ClearThreadIDList(); switch (stop_state) { case eStateStopped: case eStateCrashed: case eStateSuspended: process->SetLastStopPacket(response); process->SetPrivateState(stop_state); break; case eStateExited: { process->SetLastStopPacket(response); process->ClearThreadIDList(); response.SetFilePos(1); int exit_status = response.GetHexU8(); std::string desc_string; if (response.GetBytesLeft() > 0 && response.GetChar('-') == ';') { llvm::StringRef desc_str; llvm::StringRef desc_token; while (response.GetNameColonValue(desc_token, desc_str)) { if (desc_token != "description") continue; StringExtractor extractor(desc_str); extractor.GetHexByteString(desc_string); } } process->SetExitStatus(exit_status, desc_string.c_str()); done = true; break; } case eStateInvalid: { // Check to see if we were trying to attach and if we got back // 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") != nullptr && response.GetError() == 0x87) { process->SetExitStatus(-1, "cannot attach to process due to " "System Integrity Protection"); } else if (::strstr(continue_cstr, "vAttach") != nullptr && response.GetStatus().Fail()) { process->SetExitStatus(-1, response.GetStatus().AsCString()); } else { process->SetExitStatus(-1, "lost connection"); } break; } default: process->SetPrivateState(stop_state); break; } // switch(stop_state) } // else // if in All-stop-mode } // if (continue_packet) } // case eBroadcastBitAsyncContinue break; case eBroadcastBitAsyncThreadShouldExit: LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got eBroadcastBitAsyncThreadShouldExit...", __FUNCTION__, arg, process->GetID()); done = true; break; default: LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); done = true; break; } } else if (event_sp->BroadcasterIs(&process->m_gdb_comm)) { switch (event_type) { case Communication::eBroadcastBitReadThreadDidExit: process->SetExitStatus(-1, "lost connection"); done = true; break; case GDBRemoteCommunication::eBroadcastBitGdbReadThreadGotNotify: { lldb_private::Event *event = event_sp.get(); const EventDataBytes *continue_packet = EventDataBytes::GetEventDataFromEvent(event); StringExtractorGDBRemote notify( (const char *)continue_packet->GetBytes()); // Hand this over to the process to handle process->HandleNotifyPacket(notify); break; } default: LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") got unknown event 0x%8.8x", __FUNCTION__, arg, process->GetID(), event_type); done = true; break; } } } else { LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") listener.WaitForEvent (NULL, event_sp) => false", __FUNCTION__, arg, process->GetID()); done = true; } } LLDB_LOGF(log, "ProcessGDBRemote::%s (arg = %p, pid = %" PRIu64 ") thread exiting...", __FUNCTION__, arg, process->GetID()); return {}; } // uint32_t // ProcessGDBRemote::ListProcessesMatchingName (const char *name, StringList // &matches, std::vector &pids) //{ // // If we are planning to launch the debugserver remotely, then we need to // fire up a debugserver // // process and ask it for the list of processes. But if we are local, we // can let the Host do it. // if (m_local_debugserver) // { // return Host::ListProcessesMatchingName (name, matches, pids); // } // else // { // // FIXME: Implement talking to the remote debugserver. // return 0; // } // //} // bool ProcessGDBRemote::NewThreadNotifyBreakpointHit( void *baton, StoppointCallbackContext *context, lldb::user_id_t break_id, lldb::user_id_t break_loc_id) { // I don't think I have to do anything here, just make sure I notice the new // thread when it starts to // run so I can stop it if that's what I want to do. Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); LLDB_LOGF(log, "Hit New Thread Notification breakpoint."); return false; } Status ProcessGDBRemote::UpdateAutomaticSignalFiltering() { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); LLDB_LOG(log, "Check if need to update ignored signals"); // QPassSignals package is not supported by the server, there is no way we // can ignore any signals on server side. if (!m_gdb_comm.GetQPassSignalsSupported()) return Status(); // No signals, nothing to send. if (m_unix_signals_sp == nullptr) return Status(); // Signals' version hasn't changed, no need to send anything. uint64_t new_signals_version = m_unix_signals_sp->GetVersion(); if (new_signals_version == m_last_signals_version) { LLDB_LOG(log, "Signals' version hasn't changed. version={0}", m_last_signals_version); return Status(); } auto signals_to_ignore = m_unix_signals_sp->GetFilteredSignals(false, false, false); Status error = m_gdb_comm.SendSignalsToIgnore(signals_to_ignore); LLDB_LOG(log, "Signals' version changed. old version={0}, new version={1}, " "signals ignored={2}, update result={3}", m_last_signals_version, new_signals_version, signals_to_ignore.size(), error); if (error.Success()) m_last_signals_version = new_signals_version; return error; } bool ProcessGDBRemote::StartNoticingNewThreads() { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); if (m_thread_create_bp_sp) { if (log && log->GetVerbose()) LLDB_LOGF(log, "Enabled noticing new thread breakpoint."); m_thread_create_bp_sp->SetEnabled(true); } else { PlatformSP platform_sp(GetTarget().GetPlatform()); if (platform_sp) { m_thread_create_bp_sp = platform_sp->SetThreadCreationBreakpoint(GetTarget()); if (m_thread_create_bp_sp) { if (log && log->GetVerbose()) LLDB_LOGF( log, "Successfully created new thread notification breakpoint %i", m_thread_create_bp_sp->GetID()); m_thread_create_bp_sp->SetCallback( ProcessGDBRemote::NewThreadNotifyBreakpointHit, this, true); } else { LLDB_LOGF(log, "Failed to create new thread notification breakpoint."); } } } return m_thread_create_bp_sp.get() != nullptr; } bool ProcessGDBRemote::StopNoticingNewThreads() { Log *log(GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); if (log && log->GetVerbose()) LLDB_LOGF(log, "Disabling new thread notification breakpoint."); if (m_thread_create_bp_sp) m_thread_create_bp_sp->SetEnabled(false); return true; } DynamicLoader *ProcessGDBRemote::GetDynamicLoader() { 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) { int return_value; bool was_supported; Status error; return_value = m_gdb_comm.SendLaunchEventDataPacket(data, &was_supported); if (return_value != 0) { if (!was_supported) error.SetErrorString("Sending events is not supported for this process."); else error.SetErrorStringWithFormat("Error sending event data: %d.", return_value); } return error; } 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 = std::make_shared(response_string.c_str(), response_string.length()); } return DataExtractor(buf, GetByteOrder(), GetAddressByteSize()); } StructuredData::ObjectSP ProcessGDBRemote::GetExtendedInfoForThread(lldb::tid_t tid) { StructuredData::ObjectSP object_sp; if (m_gdb_comm.GetThreadExtendedInfoSupported()) { StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); SystemRuntime *runtime = GetSystemRuntime(); if (runtime) { runtime->AddThreadExtendedInfoPacketHints(args_dict); } args_dict->GetAsDictionary()->AddIntegerItem("thread", tid); StreamString packet; packet << "jThreadExtendedInfo:"; args_dict->Dump(packet, false); // FIXME the final character of a JSON dictionary, '}', is the escape // character in gdb-remote binary mode. lldb currently doesn't escape // these characters in its packet output -- so we add the quoted version of // the } character here manually in case we talk to a debugserver which un- // escapes the characters at packet read time. packet << (char)(0x7d ^ 0x20); StringExtractorGDBRemote response; response.SetResponseValidatorToJSON(); if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, false) == GDBRemoteCommunication::PacketResult::Success) { StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); if (response_type == StringExtractorGDBRemote::eResponse) { if (!response.Empty()) { object_sp = StructuredData::ParseJSON(std::string(response.GetStringRef())); } } } } return object_sp; } StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( lldb::addr_t image_list_address, lldb::addr_t image_count) { StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); args_dict->GetAsDictionary()->AddIntegerItem("image_list_address", image_list_address); args_dict->GetAsDictionary()->AddIntegerItem("image_count", image_count); return GetLoadedDynamicLibrariesInfos_sender(args_dict); } StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos() { StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); args_dict->GetAsDictionary()->AddBooleanItem("fetch_all_solibs", true); return GetLoadedDynamicLibrariesInfos_sender(args_dict); } StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos( const std::vector &load_addresses) { StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); StructuredData::ArraySP addresses(new StructuredData::Array); for (auto addr : load_addresses) { StructuredData::ObjectSP addr_sp(new StructuredData::Integer(addr)); addresses->AddItem(addr_sp); } args_dict->GetAsDictionary()->AddItem("solib_addresses", addresses); return GetLoadedDynamicLibrariesInfos_sender(args_dict); } StructuredData::ObjectSP ProcessGDBRemote::GetLoadedDynamicLibrariesInfos_sender( StructuredData::ObjectSP args_dict) { StructuredData::ObjectSP object_sp; if (m_gdb_comm.GetLoadedDynamicLibrariesInfosSupported()) { // Scope for the scoped timeout object GDBRemoteCommunication::ScopedTimeout timeout(m_gdb_comm, std::chrono::seconds(10)); StreamString packet; packet << "jGetLoadedDynamicLibrariesInfos:"; args_dict->Dump(packet, false); // FIXME the final character of a JSON dictionary, '}', is the escape // character in gdb-remote binary mode. lldb currently doesn't escape // these characters in its packet output -- so we add the quoted version of // the } character here manually in case we talk to a debugserver which un- // escapes the characters at packet read time. packet << (char)(0x7d ^ 0x20); StringExtractorGDBRemote response; response.SetResponseValidatorToJSON(); if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, false) == GDBRemoteCommunication::PacketResult::Success) { StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); if (response_type == StringExtractorGDBRemote::eResponse) { if (!response.Empty()) { object_sp = StructuredData::ParseJSON(std::string(response.GetStringRef())); } } } } return object_sp; } StructuredData::ObjectSP ProcessGDBRemote::GetSharedCacheInfo() { StructuredData::ObjectSP object_sp; StructuredData::ObjectSP args_dict(new StructuredData::Dictionary()); if (m_gdb_comm.GetSharedCacheInfoSupported()) { StreamString packet; packet << "jGetSharedCacheInfo:"; args_dict->Dump(packet, false); // FIXME the final character of a JSON dictionary, '}', is the escape // character in gdb-remote binary mode. lldb currently doesn't escape // these characters in its packet output -- so we add the quoted version of // the } character here manually in case we talk to a debugserver which un- // escapes the characters at packet read time. packet << (char)(0x7d ^ 0x20); StringExtractorGDBRemote response; response.SetResponseValidatorToJSON(); if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, false) == GDBRemoteCommunication::PacketResult::Success) { StringExtractorGDBRemote::ResponseType response_type = response.GetResponseType(); if (response_type == StringExtractorGDBRemote::eResponse) { if (!response.Empty()) { object_sp = StructuredData::ParseJSON(std::string(response.GetStringRef())); } } } } return object_sp; } Status ProcessGDBRemote::ConfigureStructuredData( ConstString type_name, const StructuredData::ObjectSP &config_sp) { return m_gdb_comm.ConfigureRemoteStructuredData(type_name, config_sp); } // Establish the largest memory read/write payloads we should use. If the // remote stub has a max packet size, stay under that size. // // If the remote stub's max packet size is crazy large, use a reasonable // largeish default. // // If the remote stub doesn't advertise a max packet size, use a conservative // default. void ProcessGDBRemote::GetMaxMemorySize() { const uint64_t reasonable_largeish_default = 128 * 1024; const uint64_t conservative_default = 512; if (m_max_memory_size == 0) { uint64_t stub_max_size = m_gdb_comm.GetRemoteMaxPacketSize(); if (stub_max_size != UINT64_MAX && stub_max_size != 0) { // Save the stub's claimed maximum packet size m_remote_stub_max_memory_size = stub_max_size; // Even if the stub says it can support ginormous packets, don't exceed // our reasonable largeish default packet size. if (stub_max_size > reasonable_largeish_default) { stub_max_size = reasonable_largeish_default; } // Memory packet have other overheads too like Maddr,size:#NN Instead of // calculating the bytes taken by size and addr every time, we take a // maximum guess here. if (stub_max_size > 70) stub_max_size -= 32 + 32 + 6; else { // In unlikely scenario that max packet size is less then 70, we will // hope that data being written is small enough to fit. Log *log(ProcessGDBRemoteLog::GetLogIfAnyCategoryIsSet( GDBR_LOG_COMM | GDBR_LOG_MEMORY)); if (log) log->Warning("Packet size is too small. " "LLDB may face problems while writing memory"); } m_max_memory_size = stub_max_size; } else { m_max_memory_size = conservative_default; } } } void ProcessGDBRemote::SetUserSpecifiedMaxMemoryTransferSize( uint64_t user_specified_max) { if (user_specified_max != 0) { GetMaxMemorySize(); if (m_remote_stub_max_memory_size != 0) { if (m_remote_stub_max_memory_size < user_specified_max) { m_max_memory_size = m_remote_stub_max_memory_size; // user specified a // packet size too // big, go as big // as the remote stub says we can go. } else { m_max_memory_size = user_specified_max; // user's packet size is good } } else { m_max_memory_size = user_specified_max; // user's packet size is probably fine } } } bool ProcessGDBRemote::GetModuleSpec(const FileSpec &module_file_spec, const ArchSpec &arch, ModuleSpec &module_spec) { Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PLATFORM); const ModuleCacheKey key(module_file_spec.GetPath(), arch.GetTriple().getTriple()); auto cached = m_cached_module_specs.find(key); if (cached != m_cached_module_specs.end()) { module_spec = cached->second; return bool(module_spec); } if (!m_gdb_comm.GetModuleInfo(module_file_spec, arch, module_spec)) { LLDB_LOGF(log, "ProcessGDBRemote::%s - failed to get module info for %s:%s", __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple().getTriple().c_str()); return false; } if (log) { StreamString stream; module_spec.Dump(stream); LLDB_LOGF(log, "ProcessGDBRemote::%s - got module info for (%s:%s) : %s", __FUNCTION__, module_file_spec.GetPath().c_str(), arch.GetTriple().getTriple().c_str(), stream.GetData()); } m_cached_module_specs[key] = module_spec; return true; } void ProcessGDBRemote::PrefetchModuleSpecs( llvm::ArrayRef module_file_specs, const llvm::Triple &triple) { auto module_specs = m_gdb_comm.GetModulesInfo(module_file_specs, triple); if (module_specs) { for (const FileSpec &spec : module_file_specs) m_cached_module_specs[ModuleCacheKey(spec.GetPath(), triple.getTriple())] = ModuleSpec(); for (const ModuleSpec &spec : *module_specs) m_cached_module_specs[ModuleCacheKey(spec.GetFileSpec().GetPath(), triple.getTriple())] = spec; } } llvm::VersionTuple ProcessGDBRemote::GetHostOSVersion() { return m_gdb_comm.GetOSVersion(); } llvm::VersionTuple ProcessGDBRemote::GetHostMacCatalystVersion() { return m_gdb_comm.GetMacCatalystVersion(); } namespace { typedef std::vector stringVec; typedef std::vector GDBServerRegisterVec; struct RegisterSetInfo { ConstString name; }; typedef std::map RegisterSetMap; struct GdbServerTargetInfo { std::string arch; std::string osabi; stringVec includes; RegisterSetMap reg_set_map; }; bool ParseRegisters(XMLNode feature_node, GdbServerTargetInfo &target_info, GDBRemoteDynamicRegisterInfo &dyn_reg_info, ABISP abi_sp, uint32_t &cur_reg_num, uint32_t ®_offset) { if (!feature_node) return false; feature_node.ForEachChildElementWithName( "reg", [&target_info, &dyn_reg_info, &cur_reg_num, ®_offset, &abi_sp](const XMLNode ®_node) -> bool { std::string gdb_group; std::string gdb_type; ConstString reg_name; ConstString alt_name; ConstString set_name; std::vector value_regs; std::vector invalidate_regs; std::vector dwarf_opcode_bytes; bool encoding_set = false; bool format_set = false; RegisterInfo reg_info = { nullptr, // Name nullptr, // Alt name 0, // byte size reg_offset, // offset eEncodingUint, // encoding eFormatHex, // format { LLDB_INVALID_REGNUM, // eh_frame reg num LLDB_INVALID_REGNUM, // DWARF reg num LLDB_INVALID_REGNUM, // generic reg num cur_reg_num, // process plugin reg num cur_reg_num // native register number }, nullptr, nullptr, nullptr, // Dwarf Expression opcode bytes pointer 0 // Dwarf Expression opcode bytes length }; reg_node.ForEachAttribute([&target_info, &gdb_group, &gdb_type, ®_name, &alt_name, &set_name, &value_regs, &invalidate_regs, &encoding_set, &format_set, ®_info, ®_offset, &dwarf_opcode_bytes]( const llvm::StringRef &name, const llvm::StringRef &value) -> bool { if (name == "name") { reg_name.SetString(value); } else if (name == "bitsize") { reg_info.byte_size = StringConvert::ToUInt32(value.data(), 0, 0) / CHAR_BIT; } else if (name == "type") { gdb_type = value.str(); } else if (name == "group") { gdb_group = value.str(); } else if (name == "regnum") { const uint32_t regnum = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); if (regnum != LLDB_INVALID_REGNUM) { reg_info.kinds[eRegisterKindProcessPlugin] = regnum; } } else if (name == "offset") { reg_offset = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); } else if (name == "altname") { alt_name.SetString(value); } else if (name == "encoding") { encoding_set = true; reg_info.encoding = Args::StringToEncoding(value, eEncodingUint); } else if (name == "format") { format_set = true; Format format = eFormatInvalid; if (OptionArgParser::ToFormat(value.data(), format, nullptr) .Success()) reg_info.format = format; else if (value == "vector-sint8") reg_info.format = eFormatVectorOfSInt8; else if (value == "vector-uint8") reg_info.format = eFormatVectorOfUInt8; else if (value == "vector-sint16") reg_info.format = eFormatVectorOfSInt16; else if (value == "vector-uint16") reg_info.format = eFormatVectorOfUInt16; else if (value == "vector-sint32") reg_info.format = eFormatVectorOfSInt32; else if (value == "vector-uint32") reg_info.format = eFormatVectorOfUInt32; else if (value == "vector-float32") reg_info.format = eFormatVectorOfFloat32; else if (value == "vector-uint64") reg_info.format = eFormatVectorOfUInt64; else if (value == "vector-uint128") reg_info.format = eFormatVectorOfUInt128; } else if (name == "group_id") { const uint32_t set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); RegisterSetMap::const_iterator pos = target_info.reg_set_map.find(set_id); if (pos != target_info.reg_set_map.end()) set_name = pos->second.name; } else if (name == "gcc_regnum" || name == "ehframe_regnum") { reg_info.kinds[eRegisterKindEHFrame] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); } else if (name == "dwarf_regnum") { reg_info.kinds[eRegisterKindDWARF] = StringConvert::ToUInt32(value.data(), LLDB_INVALID_REGNUM, 0); } else if (name == "generic") { reg_info.kinds[eRegisterKindGeneric] = Args::StringToGenericRegister(value); } else if (name == "value_regnums") { SplitCommaSeparatedRegisterNumberString(value, value_regs, 0); } else if (name == "invalidate_regnums") { SplitCommaSeparatedRegisterNumberString(value, invalidate_regs, 0); } else if (name == "dynamic_size_dwarf_expr_bytes") { std::string opcode_string = value.str(); size_t dwarf_opcode_len = opcode_string.length() / 2; assert(dwarf_opcode_len > 0); dwarf_opcode_bytes.resize(dwarf_opcode_len); reg_info.dynamic_size_dwarf_len = dwarf_opcode_len; StringExtractor opcode_extractor(opcode_string); uint32_t ret_val = opcode_extractor.GetHexBytesAvail(dwarf_opcode_bytes); assert(dwarf_opcode_len == ret_val); UNUSED_IF_ASSERT_DISABLED(ret_val); reg_info.dynamic_size_dwarf_expr_bytes = dwarf_opcode_bytes.data(); } else { printf("unhandled attribute %s = %s\n", name.data(), value.data()); } return true; // Keep iterating through all attributes }); if (!gdb_type.empty() && !(encoding_set || format_set)) { if (llvm::StringRef(gdb_type).startswith("int")) { reg_info.format = eFormatHex; reg_info.encoding = eEncodingUint; } else if (gdb_type == "data_ptr" || gdb_type == "code_ptr") { reg_info.format = eFormatAddressInfo; reg_info.encoding = eEncodingUint; } else if (gdb_type == "i387_ext" || gdb_type == "float") { reg_info.format = eFormatFloat; reg_info.encoding = eEncodingIEEE754; } } // 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) { 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); reg_offset += reg_info.byte_size; if (!value_regs.empty()) { value_regs.push_back(LLDB_INVALID_REGNUM); reg_info.value_regs = value_regs.data(); } if (!invalidate_regs.empty()) { invalidate_regs.push_back(LLDB_INVALID_REGNUM); reg_info.invalidate_regs = invalidate_regs.data(); } ++cur_reg_num; reg_info.name = reg_name.AsCString(); if (abi_sp) abi_sp->AugmentRegisterInfo(reg_info); dyn_reg_info.AddRegister(reg_info, reg_name, alt_name, set_name); return true; // Keep iterating through all "reg" elements }); return true; } } // namespace // 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 (!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(), xml_filename.c_str())) { GdbServerTargetInfo target_info; std::vector feature_nodes; // The top level feature XML file will start with a tag. XMLNode target_node = xml_document.GetRootElement("target"); if (target_node) { target_node.ForEachChildElement([&target_info, &feature_nodes]( const XMLNode &node) -> bool { llvm::StringRef name = node.GetName(); if (name == "architecture") { node.GetElementText(target_info.arch); } else if (name == "osabi") { node.GetElementText(target_info.osabi); } else if (name == "xi:include" || name == "include") { llvm::StringRef href = node.GetAttributeValue("href"); if (!href.empty()) target_info.includes.push_back(href.str()); } else if (name == "feature") { feature_nodes.push_back(node); } else if (name == "groups") { node.ForEachChildElementWithName( "group", [&target_info](const XMLNode &node) -> bool { uint32_t set_id = UINT32_MAX; RegisterSetInfo set_info; node.ForEachAttribute( [&set_id, &set_info](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { if (name == "id") set_id = StringConvert::ToUInt32(value.data(), UINT32_MAX, 0); if (name == "name") set_info.name = ConstString(value); return true; // Keep iterating through all attributes }); if (set_id != UINT32_MAX) target_info.reg_set_map[set_id] = set_info; return true; // Keep iterating through all "group" elements }); } return true; // Keep iterating through all children of the target_node }); } else { // In an included XML feature file, we're already "inside" the // tag of the initial XML file; this included file will likely only have // a tag. Need to check for any more included files in this // 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 // i386:x86-64 (seen from VMWare ESXi) // arm (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 (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. ABISP abi_to_use_sp = ABI::FindPlugin(shared_from_this(), arch_to_use); for (auto &feature_node : feature_nodes) { ParseRegisters(feature_node, target_info, this->m_register_info, abi_to_use_sp, cur_reg_num, reg_offset); } for (const auto &include : target_info.includes) { GetGDBServerRegisterInfoXMLAndProcess(arch_to_use, include, cur_reg_num, reg_offset); } } } 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; } llvm::Expected ProcessGDBRemote::GetLoadedModuleList() { // Make sure LLDB has an XML parser it can use first if (!XMLDocument::XMLEnabled()) return llvm::createStringError(llvm::inconvertibleErrorCode(), "XML parsing not available"); Log *log = GetLogIfAnyCategoriesSet(LIBLLDB_LOG_PROCESS); LLDB_LOGF(log, "ProcessGDBRemote::%s", __FUNCTION__); LoadedModuleInfoList list; GDBRemoteCommunicationClient &comm = m_gdb_comm; bool can_use_svr4 = GetGlobalPluginProperties()->GetUseSVR4(); // check that we have extended feature read support if (can_use_svr4 && comm.GetQXferLibrariesSVR4ReadSupported()) { // request the loaded library list std::string raw; lldb_private::Status lldberr; if (!comm.ReadExtFeature(ConstString("libraries-svr4"), ConstString(""), raw, lldberr)) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Error in libraries-svr4 packet"); // parse the xml file in memory LLDB_LOGF(log, "parsing: %s", raw.c_str()); XMLDocument doc; if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Error reading noname.xml"); XMLNode root_element = doc.GetRootElement("library-list-svr4"); if (!root_element) return llvm::createStringError( llvm::inconvertibleErrorCode(), "Error finding library-list-svr4 xml element"); // main link map structure llvm::StringRef main_lm = root_element.GetAttributeValue("main-lm"); if (!main_lm.empty()) { list.m_link_map = StringConvert::ToUInt64(main_lm.data(), LLDB_INVALID_ADDRESS, 0); } root_element.ForEachChildElementWithName( "library", [log, &list](const XMLNode &library) -> bool { LoadedModuleInfoList::LoadedModuleInfo module; library.ForEachAttribute( [&module](const llvm::StringRef &name, const llvm::StringRef &value) -> bool { if (name == "name") module.set_name(value.str()); else if (name == "lm") { // the address of the link_map struct. module.set_link_map(StringConvert::ToUInt64( value.data(), LLDB_INVALID_ADDRESS, 0)); } else if (name == "l_addr") { // the displacement as read from the field 'l_addr' of the // link_map struct. module.set_base(StringConvert::ToUInt64( value.data(), LLDB_INVALID_ADDRESS, 0)); // base address is always a displacement, not an absolute // value. module.set_base_is_offset(true); } else if (name == "l_ld") { // the memory address of the libraries PT_DYNAMIC section. module.set_dynamic(StringConvert::ToUInt64( value.data(), LLDB_INVALID_ADDRESS, 0)); } return true; // Keep iterating over all properties of "library" }); if (log) { std::string name; lldb::addr_t lm = 0, base = 0, ld = 0; bool base_is_offset; module.get_name(name); module.get_link_map(lm); module.get_base(base); module.get_base_is_offset(base_is_offset); module.get_dynamic(ld); LLDB_LOGF(log, "found (link_map:0x%08" PRIx64 ", base:0x%08" PRIx64 "[%s], ld:0x%08" PRIx64 ", name:'%s')", lm, base, (base_is_offset ? "offset" : "absolute"), ld, name.c_str()); } list.add(module); return true; // Keep iterating over all "library" elements in the root // node }); if (log) LLDB_LOGF(log, "found %" PRId32 " modules in total", (int)list.m_list.size()); return list; } else if (comm.GetQXferLibrariesReadSupported()) { // request the loaded library list std::string raw; lldb_private::Status lldberr; if (!comm.ReadExtFeature(ConstString("libraries"), ConstString(""), raw, lldberr)) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Error in libraries packet"); LLDB_LOGF(log, "parsing: %s", raw.c_str()); XMLDocument doc; if (!doc.ParseMemory(raw.c_str(), raw.size(), "noname.xml")) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Error reading noname.xml"); XMLNode root_element = doc.GetRootElement("library-list"); if (!root_element) return llvm::createStringError(llvm::inconvertibleErrorCode(), "Error finding library-list xml element"); root_element.ForEachChildElementWithName( "library", [log, &list](const XMLNode &library) -> bool { LoadedModuleInfoList::LoadedModuleInfo module; llvm::StringRef name = library.GetAttributeValue("name"); module.set_name(name.str()); // The base address of a given library will be the address of its // first section. Most remotes send only one section for Windows // targets for example. const XMLNode §ion = library.FindFirstChildElementWithName("section"); llvm::StringRef address = section.GetAttributeValue("address"); module.set_base( StringConvert::ToUInt64(address.data(), LLDB_INVALID_ADDRESS, 0)); // These addresses are absolute values. module.set_base_is_offset(false); if (log) { std::string name; lldb::addr_t base = 0; bool base_is_offset; module.get_name(name); module.get_base(base); module.get_base_is_offset(base_is_offset); LLDB_LOGF(log, "found (base:0x%08" PRIx64 "[%s], name:'%s')", base, (base_is_offset ? "offset" : "absolute"), name.c_str()); } list.add(module); return true; // Keep iterating over all "library" elements in the root // node }); if (log) LLDB_LOGF(log, "found %" PRId32 " modules in total", (int)list.m_list.size()); return list; } else { return llvm::createStringError(llvm::inconvertibleErrorCode(), "Remote libraries not supported"); } } lldb::ModuleSP ProcessGDBRemote::LoadModuleAtAddress(const FileSpec &file, lldb::addr_t link_map, lldb::addr_t base_addr, bool value_is_offset) { DynamicLoader *loader = GetDynamicLoader(); if (!loader) return nullptr; return loader->LoadModuleAtAddress(file, link_map, base_addr, value_is_offset); } llvm::Error ProcessGDBRemote::LoadModules() { using lldb_private::process_gdb_remote::ProcessGDBRemote; // request a list of loaded libraries from GDBServer llvm::Expected module_list = GetLoadedModuleList(); if (!module_list) return module_list.takeError(); // get a list of all the modules ModuleList new_modules; for (LoadedModuleInfoList::LoadedModuleInfo &modInfo : module_list->m_list) { std::string mod_name; lldb::addr_t mod_base; lldb::addr_t link_map; bool mod_base_is_offset; bool valid = true; valid &= modInfo.get_name(mod_name); valid &= modInfo.get_base(mod_base); valid &= modInfo.get_base_is_offset(mod_base_is_offset); if (!valid) continue; if (!modInfo.get_link_map(link_map)) link_map = LLDB_INVALID_ADDRESS; FileSpec file(mod_name); FileSystem::Instance().Resolve(file); lldb::ModuleSP module_sp = LoadModuleAtAddress(file, link_map, mod_base, mod_base_is_offset); if (module_sp.get()) new_modules.Append(module_sp); } if (new_modules.GetSize() > 0) { ModuleList removed_modules; Target &target = GetTarget(); ModuleList &loaded_modules = m_process->GetTarget().GetImages(); for (size_t i = 0; i < loaded_modules.GetSize(); ++i) { const lldb::ModuleSP loaded_module = loaded_modules.GetModuleAtIndex(i); bool found = false; for (size_t j = 0; j < new_modules.GetSize(); ++j) { if (new_modules.GetModuleAtIndex(j).get() == loaded_module.get()) found = true; } // The main executable will never be included in libraries-svr4, don't // remove it if (!found && loaded_module.get() != target.GetExecutableModulePointer()) { removed_modules.Append(loaded_module); } } loaded_modules.Remove(removed_modules); m_process->GetTarget().ModulesDidUnload(removed_modules, false); new_modules.ForEach([&target](const lldb::ModuleSP module_sp) -> bool { lldb_private::ObjectFile *obj = module_sp->GetObjectFile(); if (!obj) return true; if (obj->GetType() != ObjectFile::Type::eTypeExecutable) return true; lldb::ModuleSP module_copy_sp = module_sp; target.SetExecutableModule(module_copy_sp, eLoadDependentsNo); return false; }); loaded_modules.AppendIfNeeded(new_modules); m_process->GetTarget().ModulesDidLoad(new_modules); } return llvm::ErrorSuccess(); } Status ProcessGDBRemote::GetFileLoadAddress(const FileSpec &file, bool &is_loaded, lldb::addr_t &load_addr) { is_loaded = false; load_addr = LLDB_INVALID_ADDRESS; std::string file_path = file.GetPath(false); if (file_path.empty()) return Status("Empty file name specified"); StreamString packet; packet.PutCString("qFileLoadAddress:"); packet.PutStringAsRawHex8(file_path); StringExtractorGDBRemote response; if (m_gdb_comm.SendPacketAndWaitForResponse(packet.GetString(), response, false) != GDBRemoteCommunication::PacketResult::Success) return Status("Sending qFileLoadAddress packet failed"); if (response.IsErrorResponse()) { if (response.GetError() == 1) { // The file is not loaded into the inferior is_loaded = false; load_addr = LLDB_INVALID_ADDRESS; return Status(); } return Status( "Fetching file load address from remote server returned an error"); } if (response.IsNormalResponse()) { is_loaded = true; load_addr = response.GetHexMaxU64(false, LLDB_INVALID_ADDRESS); return Status(); } return Status( "Unknown error happened during sending the load address packet"); } void ProcessGDBRemote::ModulesDidLoad(ModuleList &module_list) { // We must call the lldb_private::Process::ModulesDidLoad () first before we // do anything Process::ModulesDidLoad(module_list); // After loading shared libraries, we can ask our remote GDB server if it // needs any symbols. m_gdb_comm.ServeSymbolLookups(this); } void ProcessGDBRemote::HandleAsyncStdout(llvm::StringRef out) { AppendSTDOUT(out.data(), out.size()); } static const char *end_delimiter = "--end--;"; static const int end_delimiter_len = 8; void ProcessGDBRemote::HandleAsyncMisc(llvm::StringRef data) { std::string input = data.str(); // '1' to move beyond 'A' if (m_partial_profile_data.length() > 0) { m_partial_profile_data.append(input); input = m_partial_profile_data; m_partial_profile_data.clear(); } size_t found, pos = 0, len = input.length(); while ((found = input.find(end_delimiter, pos)) != std::string::npos) { StringExtractorGDBRemote profileDataExtractor( input.substr(pos, found).c_str()); std::string profile_data = HarmonizeThreadIdsForProfileData(profileDataExtractor); BroadcastAsyncProfileData(profile_data); pos = found + end_delimiter_len; } if (pos < len) { // Last incomplete chunk. m_partial_profile_data = input.substr(pos); } } std::string ProcessGDBRemote::HarmonizeThreadIdsForProfileData( StringExtractorGDBRemote &profileDataExtractor) { std::map new_thread_id_to_used_usec_map; std::string output; llvm::raw_string_ostream output_stream(output); llvm::StringRef name, value; // Going to assuming thread_used_usec comes first, else bail out. while (profileDataExtractor.GetNameColonValue(name, value)) { if (name.compare("thread_used_id") == 0) { StringExtractor threadIDHexExtractor(value); uint64_t thread_id = threadIDHexExtractor.GetHexMaxU64(false, 0); bool has_used_usec = false; uint32_t curr_used_usec = 0; llvm::StringRef usec_name, usec_value; uint32_t input_file_pos = profileDataExtractor.GetFilePos(); if (profileDataExtractor.GetNameColonValue(usec_name, usec_value)) { if (usec_name.equals("thread_used_usec")) { has_used_usec = true; usec_value.getAsInteger(0, curr_used_usec); } else { // We didn't find what we want, it is probably an older version. Bail // out. profileDataExtractor.SetFilePos(input_file_pos); } } if (has_used_usec) { uint32_t prev_used_usec = 0; std::map::iterator iterator = m_thread_id_to_used_usec_map.find(thread_id); if (iterator != m_thread_id_to_used_usec_map.end()) { prev_used_usec = m_thread_id_to_used_usec_map[thread_id]; } uint32_t real_used_usec = curr_used_usec - prev_used_usec; // A good first time record is one that runs for at least 0.25 sec bool good_first_time = (prev_used_usec == 0) && (real_used_usec > 250000); bool good_subsequent_time = (prev_used_usec > 0) && ((real_used_usec > 0) || (HasAssignedIndexIDToThread(thread_id))); if (good_first_time || good_subsequent_time) { // We try to avoid doing too many index id reservation, resulting in // fast increase of index ids. output_stream << name << ":"; int32_t index_id = AssignIndexIDToThread(thread_id); output_stream << index_id << ";"; output_stream << usec_name << ":" << usec_value << ";"; } else { // Skip past 'thread_used_name'. llvm::StringRef local_name, local_value; profileDataExtractor.GetNameColonValue(local_name, local_value); } // Store current time as previous time so that they can be compared // later. new_thread_id_to_used_usec_map[thread_id] = curr_used_usec; } else { // Bail out and use old string. output_stream << name << ":" << value << ";"; } } else { output_stream << name << ":" << value << ";"; } } output_stream << end_delimiter; m_thread_id_to_used_usec_map = new_thread_id_to_used_usec_map; return output_stream.str(); } void ProcessGDBRemote::HandleStopReply() { if (GetStopID() != 0) return; if (GetID() == LLDB_INVALID_PROCESS_ID) { lldb::pid_t pid = m_gdb_comm.GetCurrentProcessID(); if (pid != LLDB_INVALID_PROCESS_ID) SetID(pid); } BuildDynamicRegisterInfo(true); } static const char *const s_async_json_packet_prefix = "JSON-async:"; static StructuredData::ObjectSP ParseStructuredDataPacket(llvm::StringRef packet) { Log *log(ProcessGDBRemoteLog::GetLogIfAllCategoriesSet(GDBR_LOG_PROCESS)); if (!packet.consume_front(s_async_json_packet_prefix)) { if (log) { LLDB_LOGF( log, "GDBRemoteCommunicationClientBase::%s() received $J packet " "but was not a StructuredData packet: packet starts with " "%s", __FUNCTION__, packet.slice(0, strlen(s_async_json_packet_prefix)).str().c_str()); } return StructuredData::ObjectSP(); } // This is an asynchronous JSON packet, destined for a StructuredDataPlugin. StructuredData::ObjectSP json_sp = StructuredData::ParseJSON(std::string(packet)); if (log) { if (json_sp) { StreamString json_str; json_sp->Dump(json_str, true); json_str.Flush(); LLDB_LOGF(log, "ProcessGDBRemote::%s() " "received Async StructuredData packet: %s", __FUNCTION__, json_str.GetData()); } else { LLDB_LOGF(log, "ProcessGDBRemote::%s" "() received StructuredData packet:" " parse failure", __FUNCTION__); } } return json_sp; } void ProcessGDBRemote::HandleAsyncStructuredDataPacket(llvm::StringRef data) { auto structured_data_sp = ParseStructuredDataPacket(data); if (structured_data_sp) RouteAsyncStructuredData(structured_data_sp); } class CommandObjectProcessGDBRemoteSpeedTest : public CommandObjectParsed { public: CommandObjectProcessGDBRemoteSpeedTest(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process plugin packet speed-test", "Tests packet speeds of various sizes to determine " "the performance characteristics of the GDB remote " "connection. ", 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 " "(default is 1000).", 1000), m_max_send(LLDB_OPT_SET_1, false, "max-send", 's', 0, eArgTypeCount, "The maximum number of bytes to send in a packet. Sizes " "increase in powers of 2 while the size is less than or " "equal to this option value. (default 1024).", 1024), m_max_recv(LLDB_OPT_SET_1, false, "max-receive", 'r', 0, eArgTypeCount, "The maximum number of bytes to receive in a packet. Sizes " "increase in powers of 2 while the size is less than or " "equal to this option value. (default 1024).", 1024), m_json(LLDB_OPT_SET_1, false, "json", 'j', "Print the output as JSON data for easy parsing.", false, true) { m_option_group.Append(&m_num_packets, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); m_option_group.Append(&m_max_send, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); m_option_group.Append(&m_max_recv, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); m_option_group.Append(&m_json, LLDB_OPT_SET_ALL, LLDB_OPT_SET_1); m_option_group.Finalize(); } ~CommandObjectProcessGDBRemoteSpeedTest() override {} Options *GetOptions() override { return &m_option_group; } bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); if (argc == 0) { ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext() .GetProcessPtr(); if (process) { StreamSP output_stream_sp( m_interpreter.GetDebugger().GetAsyncOutputStream()); result.SetImmediateOutputStream(output_stream_sp); const uint32_t num_packets = (uint32_t)m_num_packets.GetOptionValue().GetCurrentValue(); const uint64_t max_send = m_max_send.GetOptionValue().GetCurrentValue(); const uint64_t max_recv = m_max_recv.GetOptionValue().GetCurrentValue(); const bool json = m_json.GetOptionValue().GetCurrentValue(); const uint64_t k_recv_amount = 4 * 1024 * 1024; // Receive amount in bytes process->GetGDBRemote().TestPacketSpeed( num_packets, max_send, max_recv, k_recv_amount, json, output_stream_sp ? *output_stream_sp : result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; } } else { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); } result.SetStatus(eReturnStatusFailed); return false; } protected: OptionGroupOptions m_option_group; OptionGroupUInt64 m_num_packets; OptionGroupUInt64 m_max_send; OptionGroupUInt64 m_max_recv; OptionGroupBoolean m_json; }; class CommandObjectProcessGDBRemotePacketHistory : public CommandObjectParsed { private: public: CommandObjectProcessGDBRemotePacketHistory(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process plugin packet history", "Dumps the packet history buffer. ", nullptr) {} ~CommandObjectProcessGDBRemotePacketHistory() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); if (argc == 0) { ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext() .GetProcessPtr(); if (process) { process->GetGDBRemote().DumpHistory(result.GetOutputStream()); result.SetStatus(eReturnStatusSuccessFinishResult); return true; } } else { result.AppendErrorWithFormat("'%s' takes no arguments", m_cmd_name.c_str()); } result.SetStatus(eReturnStatusFailed); return false; } }; class CommandObjectProcessGDBRemotePacketXferSize : public CommandObjectParsed { private: public: CommandObjectProcessGDBRemotePacketXferSize(CommandInterpreter &interpreter) : CommandObjectParsed( interpreter, "process plugin packet xfer-size", "Maximum size that lldb will try to read/write one one chunk.", nullptr) {} ~CommandObjectProcessGDBRemotePacketXferSize() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); if (argc == 0) { result.AppendErrorWithFormat("'%s' takes an argument to specify the max " "amount to be transferred when " "reading/writing", m_cmd_name.c_str()); result.SetStatus(eReturnStatusFailed); return false; } ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); if (process) { const char *packet_size = command.GetArgumentAtIndex(0); errno = 0; 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); return true; } } result.SetStatus(eReturnStatusFailed); return false; } }; class CommandObjectProcessGDBRemotePacketSend : public CommandObjectParsed { private: public: CommandObjectProcessGDBRemotePacketSend(CommandInterpreter &interpreter) : CommandObjectParsed(interpreter, "process plugin packet send", "Send a custom packet through the GDB remote " "protocol and print the answer. " "The packet header and footer will automatically " "be added to the packet prior to sending and " "stripped from the result.", nullptr) {} ~CommandObjectProcessGDBRemotePacketSend() override {} bool DoExecute(Args &command, CommandReturnObject &result) override { const size_t argc = command.GetArgumentCount(); if (argc == 0) { result.AppendErrorWithFormat( "'%s' takes a one or more packet content arguments", m_cmd_name.c_str()); result.SetStatus(eReturnStatusFailed); return false; } ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); if (process) { for (size_t i = 0; i < argc; ++i) { const char *packet_cstr = command.GetArgumentAtIndex(0); bool send_async = true; StringExtractorGDBRemote response; process->GetGDBRemote().SendPacketAndWaitForResponse( packet_cstr, response, send_async); result.SetStatus(eReturnStatusSuccessFinishResult); Stream &output_strm = result.GetOutputStream(); output_strm.Printf(" packet: %s\n", packet_cstr); std::string response_str = std::string(response.GetStringRef()); if (strstr(packet_cstr, "qGetProfileData") != nullptr) { response_str = process->HarmonizeThreadIdsForProfileData(response); } if (response_str.empty()) output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); else output_strm.Printf("response: %s\n", response.GetStringRef().data()); } } return true; } }; class CommandObjectProcessGDBRemotePacketMonitor : public CommandObjectRaw { private: public: CommandObjectProcessGDBRemotePacketMonitor(CommandInterpreter &interpreter) : CommandObjectRaw(interpreter, "process plugin packet monitor", "Send a qRcmd packet through the GDB remote protocol " "and print the response." "The argument passed to this command will be hex " "encoded into a valid 'qRcmd' packet, sent and the " "response will be printed.") {} ~CommandObjectProcessGDBRemotePacketMonitor() override {} bool DoExecute(llvm::StringRef command, CommandReturnObject &result) override { if (command.empty()) { result.AppendErrorWithFormat("'%s' takes a command string argument", m_cmd_name.c_str()); result.SetStatus(eReturnStatusFailed); return false; } ProcessGDBRemote *process = (ProcessGDBRemote *)m_interpreter.GetExecutionContext().GetProcessPtr(); if (process) { StreamString packet; packet.PutCString("qRcmd,"); packet.PutBytesAsRawHex8(command.data(), command.size()); bool send_async = true; StringExtractorGDBRemote response; Stream &output_strm = result.GetOutputStream(); process->GetGDBRemote().SendPacketAndReceiveResponseWithOutputSupport( packet.GetString(), response, send_async, [&output_strm](llvm::StringRef output) { output_strm << output; }); result.SetStatus(eReturnStatusSuccessFinishResult); output_strm.Printf(" packet: %s\n", packet.GetData()); const std::string &response_str = std::string(response.GetStringRef()); if (response_str.empty()) output_strm.PutCString("response: \nerror: UNIMPLEMENTED\n"); else output_strm.Printf("response: %s\n", response.GetStringRef().data()); } return true; } }; class CommandObjectProcessGDBRemotePacket : public CommandObjectMultiword { private: public: CommandObjectProcessGDBRemotePacket(CommandInterpreter &interpreter) : CommandObjectMultiword(interpreter, "process plugin packet", "Commands that deal with GDB remote packets.", nullptr) { LoadSubCommand( "history", CommandObjectSP( new CommandObjectProcessGDBRemotePacketHistory(interpreter))); LoadSubCommand( "send", CommandObjectSP( new CommandObjectProcessGDBRemotePacketSend(interpreter))); LoadSubCommand( "monitor", CommandObjectSP( new CommandObjectProcessGDBRemotePacketMonitor(interpreter))); LoadSubCommand( "xfer-size", CommandObjectSP( new CommandObjectProcessGDBRemotePacketXferSize(interpreter))); LoadSubCommand("speed-test", CommandObjectSP(new CommandObjectProcessGDBRemoteSpeedTest( interpreter))); } ~CommandObjectProcessGDBRemotePacket() override {} }; class CommandObjectMultiwordProcessGDBRemote : public CommandObjectMultiword { public: CommandObjectMultiwordProcessGDBRemote(CommandInterpreter &interpreter) : CommandObjectMultiword( interpreter, "process plugin", "Commands for operating on a ProcessGDBRemote process.", "process plugin []") { LoadSubCommand( "packet", CommandObjectSP(new CommandObjectProcessGDBRemotePacket(interpreter))); } ~CommandObjectMultiwordProcessGDBRemote() override {} }; CommandObject *ProcessGDBRemote::GetPluginCommandObject() { if (!m_command_sp) m_command_sp = std::make_shared( GetTarget().GetDebugger().GetCommandInterpreter()); return m_command_sp.get(); } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp (revision 363961) @@ -1,9587 +1,9591 @@ //===-- TypeSystemClang.cpp -----------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #include "TypeSystemClang.h" #include "llvm/Support/FormatAdapters.h" #include "llvm/Support/FormatVariadic.h" #include #include #include #include "clang/AST/ASTContext.h" #include "clang/AST/ASTImporter.h" #include "clang/AST/Attr.h" #include "clang/AST/CXXInheritance.h" #include "clang/AST/DeclObjC.h" #include "clang/AST/DeclTemplate.h" #include "clang/AST/Mangle.h" #include "clang/AST/RecordLayout.h" #include "clang/AST/Type.h" #include "clang/AST/VTableBuilder.h" #include "clang/Basic/Builtins.h" #include "clang/Basic/Diagnostic.h" #include "clang/Basic/FileManager.h" #include "clang/Basic/FileSystemOptions.h" #include "clang/Basic/LangStandard.h" #include "clang/Basic/SourceManager.h" #include "clang/Basic/TargetInfo.h" #include "clang/Basic/TargetOptions.h" #include "clang/Frontend/FrontendOptions.h" #include "clang/Lex/HeaderSearch.h" #include "clang/Lex/HeaderSearchOptions.h" #include "clang/Lex/ModuleMap.h" #include "clang/Sema/Sema.h" #include "llvm/Support/Signals.h" #include "llvm/Support/Threading.h" #include "Plugins/ExpressionParser/Clang/ClangASTImporter.h" #include "Plugins/ExpressionParser/Clang/ClangASTMetadata.h" #include "Plugins/ExpressionParser/Clang/ClangExternalASTSourceCallbacks.h" #include "Plugins/ExpressionParser/Clang/ClangFunctionCaller.h" #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "Plugins/ExpressionParser/Clang/ClangUserExpression.h" #include "Plugins/ExpressionParser/Clang/ClangUtil.h" #include "Plugins/ExpressionParser/Clang/ClangUtilityFunction.h" #include "lldb/Utility/ArchSpec.h" #include "lldb/Utility/Flags.h" #include "lldb/Core/DumpDataExtractor.h" #include "lldb/Core/Module.h" #include "lldb/Core/PluginManager.h" #include "lldb/Core/StreamFile.h" #include "lldb/Core/ThreadSafeDenseMap.h" #include "lldb/Core/UniqueCStringMap.h" #include "lldb/Symbol/ObjectFile.h" #include "lldb/Symbol/SymbolFile.h" #include "lldb/Target/ExecutionContext.h" #include "lldb/Target/Language.h" #include "lldb/Target/Process.h" #include "lldb/Target/Target.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/LLDBAssert.h" #include "lldb/Utility/Log.h" #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" #include #include using namespace lldb; using namespace lldb_private; using namespace clang; using llvm::StringSwitch; LLDB_PLUGIN_DEFINE(TypeSystemClang) namespace { static void VerifyDecl(clang::Decl *decl) { assert(decl && "VerifyDecl called with nullptr?"); #ifndef NDEBUG // We don't care about the actual access value here but only want to trigger // that Clang calls its internal Decl::AccessDeclContextSanity check. decl->getAccess(); #endif } static inline bool TypeSystemClangSupportsLanguage(lldb::LanguageType language) { return language == eLanguageTypeUnknown || // Clang is the default type system lldb_private::Language::LanguageIsC(language) || lldb_private::Language::LanguageIsCPlusPlus(language) || lldb_private::Language::LanguageIsObjC(language) || lldb_private::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 || // Open Dylan compiler debug info is designed to be Clang-compatible language == eLanguageTypeDylan; } // Checks whether m1 is an overload of m2 (as opposed to an override). This is // called by addOverridesForMethod to distinguish overrides (which share a // vtable entry) from overloads (which require distinct entries). bool isOverload(clang::CXXMethodDecl *m1, clang::CXXMethodDecl *m2) { // FIXME: This should detect covariant return types, but currently doesn't. lldbassert(&m1->getASTContext() == &m2->getASTContext() && "Methods should have the same AST context"); clang::ASTContext &context = m1->getASTContext(); const auto *m1Type = llvm::cast( context.getCanonicalType(m1->getType())); const auto *m2Type = llvm::cast( context.getCanonicalType(m2->getType())); auto compareArgTypes = [&context](const clang::QualType &m1p, const clang::QualType &m2p) { return context.hasSameType(m1p.getUnqualifiedType(), m2p.getUnqualifiedType()); }; // FIXME: In C++14 and later, we can just pass m2Type->param_type_end() // as a fourth parameter to std::equal(). return (m1->getNumParams() != m2->getNumParams()) || !std::equal(m1Type->param_type_begin(), m1Type->param_type_end(), m2Type->param_type_begin(), compareArgTypes); } // If decl is a virtual method, walk the base classes looking for methods that // decl overrides. This table of overridden methods is used by IRGen to // determine the vtable layout for decl's parent class. void addOverridesForMethod(clang::CXXMethodDecl *decl) { if (!decl->isVirtual()) return; clang::CXXBasePaths paths; auto find_overridden_methods = [decl](const clang::CXXBaseSpecifier *specifier, clang::CXXBasePath &path) { if (auto *base_record = llvm::dyn_cast( specifier->getType()->getAs()->getDecl())) { clang::DeclarationName name = decl->getDeclName(); // If this is a destructor, check whether the base class destructor is // virtual. if (name.getNameKind() == clang::DeclarationName::CXXDestructorName) if (auto *baseDtorDecl = base_record->getDestructor()) { if (baseDtorDecl->isVirtual()) { path.Decls = baseDtorDecl; return true; } else return false; } // Otherwise, search for name in the base class. for (path.Decls = base_record->lookup(name); !path.Decls.empty(); path.Decls = path.Decls.slice(1)) { if (auto *method_decl = llvm::dyn_cast(path.Decls.front())) if (method_decl->isVirtual() && !isOverload(decl, method_decl)) { path.Decls = method_decl; return true; } } } return false; }; if (decl->getParent()->lookupInBases(find_overridden_methods, paths)) { for (auto *overridden_decl : paths.found_decls()) decl->addOverriddenMethod( llvm::cast(overridden_decl)); } } } static lldb::addr_t GetVTableAddress(Process &process, VTableContextBase &vtable_ctx, ValueObject &valobj, const ASTRecordLayout &record_layout) { // Retrieve type info CompilerType pointee_type; CompilerType this_type(valobj.GetCompilerType()); uint32_t type_info = this_type.GetTypeInfo(&pointee_type); if (!type_info) return LLDB_INVALID_ADDRESS; // Check if it's a pointer or reference bool ptr_or_ref = false; if (type_info & (eTypeIsPointer | eTypeIsReference)) { ptr_or_ref = true; type_info = pointee_type.GetTypeInfo(); } // We process only C++ classes const uint32_t cpp_class = eTypeIsClass | eTypeIsCPlusPlus; if ((type_info & cpp_class) != cpp_class) return LLDB_INVALID_ADDRESS; // Calculate offset to VTable pointer lldb::offset_t vbtable_ptr_offset = vtable_ctx.isMicrosoft() ? record_layout.getVBPtrOffset().getQuantity() : 0; if (ptr_or_ref) { // We have a pointer / ref to object, so read // VTable pointer from process memory if (valobj.GetAddressTypeOfChildren() != eAddressTypeLoad) return LLDB_INVALID_ADDRESS; auto vbtable_ptr_addr = valobj.GetValueAsUnsigned(LLDB_INVALID_ADDRESS); if (vbtable_ptr_addr == LLDB_INVALID_ADDRESS) return LLDB_INVALID_ADDRESS; vbtable_ptr_addr += vbtable_ptr_offset; Status err; return process.ReadPointerFromMemory(vbtable_ptr_addr, err); } // We have an object already read from process memory, // so just extract VTable pointer from it DataExtractor data; Status err; auto size = valobj.GetData(data, err); if (err.Fail() || vbtable_ptr_offset + data.GetAddressByteSize() > size) return LLDB_INVALID_ADDRESS; return data.GetAddress(&vbtable_ptr_offset); } static int64_t ReadVBaseOffsetFromVTable(Process &process, VTableContextBase &vtable_ctx, lldb::addr_t vtable_ptr, const CXXRecordDecl *cxx_record_decl, const CXXRecordDecl *base_class_decl) { if (vtable_ctx.isMicrosoft()) { clang::MicrosoftVTableContext &msoft_vtable_ctx = static_cast(vtable_ctx); // Get the index into the virtual base table. The // index is the index in uint32_t from vbtable_ptr const unsigned vbtable_index = msoft_vtable_ctx.getVBTableIndex(cxx_record_decl, base_class_decl); const lldb::addr_t base_offset_addr = vtable_ptr + vbtable_index * 4; Status err; return process.ReadSignedIntegerFromMemory(base_offset_addr, 4, INT64_MAX, err); } clang::ItaniumVTableContext &itanium_vtable_ctx = static_cast(vtable_ctx); clang::CharUnits base_offset_offset = itanium_vtable_ctx.getVirtualBaseOffsetOffset(cxx_record_decl, base_class_decl); const lldb::addr_t base_offset_addr = vtable_ptr + base_offset_offset.getQuantity(); const uint32_t base_offset_size = process.GetAddressByteSize(); Status err; return process.ReadSignedIntegerFromMemory(base_offset_addr, base_offset_size, INT64_MAX, err); } static bool GetVBaseBitOffset(VTableContextBase &vtable_ctx, ValueObject &valobj, const ASTRecordLayout &record_layout, const CXXRecordDecl *cxx_record_decl, const CXXRecordDecl *base_class_decl, int32_t &bit_offset) { ExecutionContext exe_ctx(valobj.GetExecutionContextRef()); Process *process = exe_ctx.GetProcessPtr(); if (!process) return false; lldb::addr_t vtable_ptr = GetVTableAddress(*process, vtable_ctx, valobj, record_layout); if (vtable_ptr == LLDB_INVALID_ADDRESS) return false; auto base_offset = ReadVBaseOffsetFromVTable( *process, vtable_ctx, vtable_ptr, cxx_record_decl, base_class_decl); if (base_offset == INT64_MAX) return false; bit_offset = base_offset * 8; return true; } typedef lldb_private::ThreadSafeDenseMap ClangASTMap; static ClangASTMap &GetASTMap() { static ClangASTMap *g_map_ptr = nullptr; static llvm::once_flag g_once_flag; llvm::call_once(g_once_flag, []() { g_map_ptr = new ClangASTMap(); // leaked on purpose to avoid spins }); return *g_map_ptr; } TypePayloadClang::TypePayloadClang(OptionalClangModuleID owning_module, bool is_complete_objc_class) : m_payload(owning_module.GetValue()) { SetIsCompleteObjCClass(is_complete_objc_class); } void TypePayloadClang::SetOwningModule(OptionalClangModuleID id) { assert(id.GetValue() < ObjCClassBit); bool is_complete = IsCompleteObjCClass(); m_payload = id.GetValue(); SetIsCompleteObjCClass(is_complete); } static void SetMemberOwningModule(clang::Decl *member, const clang::Decl *parent) { if (!member || !parent) return; OptionalClangModuleID id(parent->getOwningModuleID()); if (!id.HasValue()) return; member->setFromASTFile(); member->setOwningModuleID(id.GetValue()); member->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); if (llvm::isa(member)) if (auto *dc = llvm::dyn_cast(parent)) { dc->setHasExternalVisibleStorage(true); // This triggers ExternalASTSource::FindExternalVisibleDeclsByName() to be // called when searching for members. dc->setHasExternalLexicalStorage(true); } } char TypeSystemClang::ID; bool TypeSystemClang::IsOperator(llvm::StringRef name, clang::OverloadedOperatorKind &op_kind) { // All operators have to start with "operator". if (!name.consume_front("operator")) return false; // Remember if there was a space after "operator". This is necessary to // check for collisions with strangely named functions like "operatorint()". bool space_after_operator = name.consume_front(" "); op_kind = StringSwitch(name) .Case("+", clang::OO_Plus) .Case("+=", clang::OO_PlusEqual) .Case("++", clang::OO_PlusPlus) .Case("-", clang::OO_Minus) .Case("-=", clang::OO_MinusEqual) .Case("--", clang::OO_MinusMinus) .Case("->", clang::OO_Arrow) .Case("->*", clang::OO_ArrowStar) .Case("*", clang::OO_Star) .Case("*=", clang::OO_StarEqual) .Case("/", clang::OO_Slash) .Case("/=", clang::OO_SlashEqual) .Case("%", clang::OO_Percent) .Case("%=", clang::OO_PercentEqual) .Case("^", clang::OO_Caret) .Case("^=", clang::OO_CaretEqual) .Case("&", clang::OO_Amp) .Case("&=", clang::OO_AmpEqual) .Case("&&", clang::OO_AmpAmp) .Case("|", clang::OO_Pipe) .Case("|=", clang::OO_PipeEqual) .Case("||", clang::OO_PipePipe) .Case("~", clang::OO_Tilde) .Case("!", clang::OO_Exclaim) .Case("!=", clang::OO_ExclaimEqual) .Case("=", clang::OO_Equal) .Case("==", clang::OO_EqualEqual) .Case("<", clang::OO_Less) .Case("<<", clang::OO_LessLess) .Case("<<=", clang::OO_LessLessEqual) .Case("<=", clang::OO_LessEqual) .Case(">", clang::OO_Greater) .Case(">>", clang::OO_GreaterGreater) .Case(">>=", clang::OO_GreaterGreaterEqual) .Case(">=", clang::OO_GreaterEqual) .Case("()", clang::OO_Call) .Case("[]", clang::OO_Subscript) .Case(",", clang::OO_Comma) .Default(clang::NUM_OVERLOADED_OPERATORS); // We found a fitting operator, so we can exit now. if (op_kind != clang::NUM_OVERLOADED_OPERATORS) return true; // After the "operator " or "operator" part is something unknown. This means // it's either one of the named operators (new/delete), a conversion operator // (e.g. operator bool) or a function which name starts with "operator" // (e.g. void operatorbool). // If it's a function that starts with operator it can't have a space after // "operator" because identifiers can't contain spaces. // E.g. "operator int" (conversion operator) // vs. "operatorint" (function with colliding name). if (!space_after_operator) return false; // not an operator. // Now the operator is either one of the named operators or a conversion // operator. op_kind = StringSwitch(name) .Case("new", clang::OO_New) .Case("new[]", clang::OO_Array_New) .Case("delete", clang::OO_Delete) .Case("delete[]", clang::OO_Array_Delete) // conversion operators hit this case. .Default(clang::NUM_OVERLOADED_OPERATORS); return true; } clang::AccessSpecifier TypeSystemClang::ConvertAccessTypeToAccessSpecifier(AccessType access) { switch (access) { default: break; case eAccessNone: return AS_none; case eAccessPublic: return AS_public; case eAccessPrivate: return AS_private; case eAccessProtected: return AS_protected; } return AS_none; } static void ParseLangArgs(LangOptions &Opts, InputKind IK, const char *triple) { // FIXME: Cleanup per-file based stuff. // Set some properties which depend solely on the input kind; it would be // nice to move these to the language standard, and have the driver resolve // the input kind + language standard. if (IK.getLanguage() == clang::Language::Asm) { Opts.AsmPreprocessor = 1; } else if (IK.isObjectiveC()) { Opts.ObjC = 1; } LangStandard::Kind LangStd = LangStandard::lang_unspecified; if (LangStd == LangStandard::lang_unspecified) { // Based on the base language, pick one. switch (IK.getLanguage()) { case clang::Language::Unknown: case clang::Language::LLVM_IR: case clang::Language::RenderScript: llvm_unreachable("Invalid input kind!"); case clang::Language::OpenCL: LangStd = LangStandard::lang_opencl10; break; case clang::Language::CUDA: LangStd = LangStandard::lang_cuda; break; case clang::Language::Asm: case clang::Language::C: case clang::Language::ObjC: LangStd = LangStandard::lang_gnu99; break; case clang::Language::CXX: case clang::Language::ObjCXX: LangStd = LangStandard::lang_gnucxx98; break; case clang::Language::HIP: LangStd = LangStandard::lang_hip; break; } } const LangStandard &Std = LangStandard::getLangStandardForKind(LangStd); Opts.LineComment = Std.hasLineComments(); Opts.C99 = Std.isC99(); Opts.CPlusPlus = Std.isCPlusPlus(); Opts.CPlusPlus11 = Std.isCPlusPlus11(); Opts.Digraphs = Std.hasDigraphs(); Opts.GNUMode = Std.isGNUMode(); Opts.GNUInline = !Std.isC99(); Opts.HexFloats = Std.hasHexFloats(); Opts.ImplicitInt = Std.hasImplicitInt(); Opts.WChar = true; // OpenCL has some additional defaults. if (LangStd == LangStandard::lang_opencl10) { Opts.OpenCL = 1; Opts.AltiVec = 1; Opts.CXXOperatorNames = 1; Opts.setLaxVectorConversions(LangOptions::LaxVectorConversionKind::All); } // OpenCL and C++ both have bool, true, false keywords. Opts.Bool = Opts.OpenCL || Opts.CPlusPlus; Opts.setValueVisibilityMode(DefaultVisibility); // Mimicing gcc's behavior, trigraphs are only enabled if -trigraphs is // specified, or -std is set to a conforming mode. Opts.Trigraphs = !Opts.GNUMode; Opts.CharIsSigned = ArchSpec(triple).CharIsSignedByDefault(); Opts.OptimizeSize = 0; // FIXME: Eliminate this dependency. // unsigned Opt = // Args.hasArg(OPT_Os) ? 2 : getLastArgIntValue(Args, OPT_O, 0, Diags); // Opts.Optimize = Opt != 0; unsigned Opt = 0; // This is the __NO_INLINE__ define, which just depends on things like the // optimization level and -fno-inline, not actually whether the backend has // inlining enabled. // // FIXME: This is affected by other options (-fno-inline). Opts.NoInlineDefine = !Opt; // This is needed to allocate the extra space for the owning module // on each decl. Opts.ModulesLocalVisibility = 1; } TypeSystemClang::TypeSystemClang(llvm::StringRef name, llvm::Triple target_triple) { m_display_name = name.str(); if (!target_triple.str().empty()) SetTargetTriple(target_triple.str()); // The caller didn't pass an ASTContext so create a new one for this // TypeSystemClang. CreateASTContext(); } TypeSystemClang::TypeSystemClang(llvm::StringRef name, ASTContext &existing_ctxt) { m_display_name = name.str(); SetTargetTriple(existing_ctxt.getTargetInfo().getTriple().str()); m_ast_up.reset(&existing_ctxt); GetASTMap().Insert(&existing_ctxt, this); } // Destructor TypeSystemClang::~TypeSystemClang() { Finalize(); } ConstString TypeSystemClang::GetPluginNameStatic() { return ConstString("clang"); } ConstString TypeSystemClang::GetPluginName() { return TypeSystemClang::GetPluginNameStatic(); } uint32_t TypeSystemClang::GetPluginVersion() { return 1; } lldb::TypeSystemSP TypeSystemClang::CreateInstance(lldb::LanguageType language, lldb_private::Module *module, Target *target) { if (!TypeSystemClangSupportsLanguage(language)) return lldb::TypeSystemSP(); ArchSpec arch; if (module) arch = module->GetArchitecture(); else if (target) arch = target->GetArchitecture(); if (!arch.IsValid()) return lldb::TypeSystemSP(); llvm::Triple triple = arch.GetTriple(); // LLVM wants this to be set to iOS or MacOSX; if we're working on // a bare-boards type image, change the triple for llvm's benefit. if (triple.getVendor() == llvm::Triple::Apple && triple.getOS() == llvm::Triple::UnknownOS) { if (triple.getArch() == llvm::Triple::arm || triple.getArch() == llvm::Triple::aarch64 || triple.getArch() == llvm::Triple::aarch64_32 || triple.getArch() == llvm::Triple::thumb) { triple.setOS(llvm::Triple::IOS); } else { triple.setOS(llvm::Triple::MacOSX); } } if (module) { std::string ast_name = "ASTContext for '" + module->GetFileSpec().GetPath() + "'"; return std::make_shared(ast_name, triple); } else if (target && target->IsValid()) return std::make_shared(*target, triple); return lldb::TypeSystemSP(); } LanguageSet TypeSystemClang::GetSupportedLanguagesForTypes() { LanguageSet languages; languages.Insert(lldb::eLanguageTypeC89); languages.Insert(lldb::eLanguageTypeC); languages.Insert(lldb::eLanguageTypeC11); languages.Insert(lldb::eLanguageTypeC_plus_plus); languages.Insert(lldb::eLanguageTypeC99); languages.Insert(lldb::eLanguageTypeObjC); languages.Insert(lldb::eLanguageTypeObjC_plus_plus); languages.Insert(lldb::eLanguageTypeC_plus_plus_03); languages.Insert(lldb::eLanguageTypeC_plus_plus_11); languages.Insert(lldb::eLanguageTypeC11); languages.Insert(lldb::eLanguageTypeC_plus_plus_14); return languages; } LanguageSet TypeSystemClang::GetSupportedLanguagesForExpressions() { LanguageSet languages; languages.Insert(lldb::eLanguageTypeC_plus_plus); languages.Insert(lldb::eLanguageTypeObjC_plus_plus); languages.Insert(lldb::eLanguageTypeC_plus_plus_03); languages.Insert(lldb::eLanguageTypeC_plus_plus_11); languages.Insert(lldb::eLanguageTypeC_plus_plus_14); return languages; } void TypeSystemClang::Initialize() { PluginManager::RegisterPlugin( GetPluginNameStatic(), "clang base AST context plug-in", CreateInstance, GetSupportedLanguagesForTypes(), GetSupportedLanguagesForExpressions()); } void TypeSystemClang::Terminate() { PluginManager::UnregisterPlugin(CreateInstance); } void TypeSystemClang::Finalize() { assert(m_ast_up); GetASTMap().Erase(m_ast_up.get()); if (!m_ast_owned) m_ast_up.release(); 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_up.reset(); m_source_manager_up.reset(); m_language_options_up.reset(); } void TypeSystemClang::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 *TypeSystemClang::GetTargetTriple() { return m_target_triple.c_str(); } void TypeSystemClang::SetTargetTriple(llvm::StringRef target_triple) { m_target_triple = target_triple.str(); } void TypeSystemClang::SetExternalSource( llvm::IntrusiveRefCntPtr &ast_source_up) { ASTContext &ast = getASTContext(); ast.setExternalSource(ast_source_up); ast.getTranslationUnitDecl()->setHasExternalLexicalStorage(true); } ASTContext &TypeSystemClang::getASTContext() { assert(m_ast_up); return *m_ast_up; } class NullDiagnosticConsumer : public DiagnosticConsumer { public: NullDiagnosticConsumer() { m_log = lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_EXPRESSIONS); } void HandleDiagnostic(DiagnosticsEngine::Level DiagLevel, const clang::Diagnostic &info) override { if (m_log) { llvm::SmallVector diag_str(10); info.FormatDiagnostic(diag_str); diag_str.push_back('\0'); LLDB_LOGF(m_log, "Compiler diagnostic: %s\n", diag_str.data()); } } DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const { return new NullDiagnosticConsumer(); } private: Log *m_log; }; void TypeSystemClang::CreateASTContext() { assert(!m_ast_up); m_ast_owned = true; m_language_options_up = std::make_unique(); ParseLangArgs(*m_language_options_up, clang::Language::ObjCXX, GetTargetTriple()); m_identifier_table_up = std::make_unique(*m_language_options_up, nullptr); m_builtins_up = std::make_unique(); m_selector_table_up = std::make_unique(); clang::FileSystemOptions file_system_options; m_file_manager_up = std::make_unique( file_system_options, FileSystem::Instance().GetVirtualFileSystem()); llvm::IntrusiveRefCntPtr diag_id_sp(new DiagnosticIDs()); m_diagnostics_engine_up = std::make_unique(diag_id_sp, new DiagnosticOptions()); m_source_manager_up = std::make_unique( *m_diagnostics_engine_up, *m_file_manager_up); m_ast_up = std::make_unique( *m_language_options_up, *m_source_manager_up, *m_identifier_table_up, *m_selector_table_up, *m_builtins_up); m_diagnostic_consumer_up = std::make_unique(); m_ast_up->getDiagnostics().setClient(m_diagnostic_consumer_up.get(), 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_up->InitBuiltinTypes(*target_info); GetASTMap().Insert(m_ast_up.get(), this); llvm::IntrusiveRefCntPtr ast_source_up( new ClangExternalASTSourceCallbacks(*this)); SetExternalSource(ast_source_up); } TypeSystemClang *TypeSystemClang::GetASTContext(clang::ASTContext *ast) { TypeSystemClang *clang_ast = GetASTMap().Lookup(ast); return clang_ast; } clang::MangleContext *TypeSystemClang::getMangleContext() { if (m_mangle_ctx_up == nullptr) m_mangle_ctx_up.reset(getASTContext().createMangleContext()); return m_mangle_ctx_up.get(); } std::shared_ptr &TypeSystemClang::getTargetOptions() { if (m_target_options_rp == nullptr && !m_target_triple.empty()) { m_target_options_rp = std::make_shared(); if (m_target_options_rp != nullptr) m_target_options_rp->Triple = m_target_triple; } return m_target_options_rp; } TargetInfo *TypeSystemClang::getTargetInfo() { // target_triple should be something like "x86_64-apple-macosx" if (m_target_info_up == nullptr && !m_target_triple.empty()) m_target_info_up.reset(TargetInfo::CreateTargetInfo( getASTContext().getDiagnostics(), getTargetOptions())); return m_target_info_up.get(); } #pragma mark Basic Types static inline bool QualTypeMatchesBitSize(const uint64_t bit_size, ASTContext &ast, QualType qual_type) { uint64_t qual_type_bit_size = ast.getTypeSize(qual_type); return qual_type_bit_size == bit_size; } CompilerType TypeSystemClang::GetBuiltinTypeForEncodingAndBitSize(Encoding encoding, size_t bit_size) { ASTContext &ast = getASTContext(); switch (encoding) { case eEncodingInvalid: if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) return GetType(ast.VoidPtrTy); break; case eEncodingUint: if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) return GetType(ast.UnsignedIntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) return GetType(ast.UnsignedLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) return GetType(ast.UnsignedLongLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) return GetType(ast.UnsignedInt128Ty); break; case eEncodingSint: if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) return GetType(ast.SignedCharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) return GetType(ast.ShortTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) return GetType(ast.IntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) return GetType(ast.LongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) return GetType(ast.LongLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) return GetType(ast.Int128Ty); break; case eEncodingIEEE754: if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) return GetType(ast.FloatTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) return GetType(ast.DoubleTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) return GetType(ast.LongDoubleTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) return GetType(ast.HalfTy); break; case eEncodingVector: // Sanity check that bit_size is a multiple of 8's. if (bit_size && !(bit_size & 0x7u)) return GetType(ast.getExtVectorType(ast.UnsignedCharTy, bit_size / 8)); break; } return CompilerType(); } lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(ConstString name) { if (name) { typedef UniqueCStringMap TypeNameToBasicTypeMap; static TypeNameToBasicTypeMap g_type_map; static llvm::once_flag g_once_flag; llvm::call_once(g_once_flag, []() { // "void" g_type_map.Append(ConstString("void"), eBasicTypeVoid); // "char" g_type_map.Append(ConstString("char"), eBasicTypeChar); g_type_map.Append(ConstString("signed char"), eBasicTypeSignedChar); g_type_map.Append(ConstString("unsigned char"), eBasicTypeUnsignedChar); g_type_map.Append(ConstString("wchar_t"), eBasicTypeWChar); g_type_map.Append(ConstString("signed wchar_t"), eBasicTypeSignedWChar); g_type_map.Append(ConstString("unsigned wchar_t"), eBasicTypeUnsignedWChar); // "short" g_type_map.Append(ConstString("short"), eBasicTypeShort); g_type_map.Append(ConstString("short int"), eBasicTypeShort); g_type_map.Append(ConstString("unsigned short"), eBasicTypeUnsignedShort); g_type_map.Append(ConstString("unsigned short int"), eBasicTypeUnsignedShort); // "int" g_type_map.Append(ConstString("int"), eBasicTypeInt); g_type_map.Append(ConstString("signed int"), eBasicTypeInt); g_type_map.Append(ConstString("unsigned int"), eBasicTypeUnsignedInt); g_type_map.Append(ConstString("unsigned"), eBasicTypeUnsignedInt); // "long" g_type_map.Append(ConstString("long"), eBasicTypeLong); g_type_map.Append(ConstString("long int"), eBasicTypeLong); g_type_map.Append(ConstString("unsigned long"), eBasicTypeUnsignedLong); g_type_map.Append(ConstString("unsigned long int"), eBasicTypeUnsignedLong); // "long long" g_type_map.Append(ConstString("long long"), eBasicTypeLongLong); g_type_map.Append(ConstString("long long int"), eBasicTypeLongLong); g_type_map.Append(ConstString("unsigned long long"), eBasicTypeUnsignedLongLong); g_type_map.Append(ConstString("unsigned long long int"), eBasicTypeUnsignedLongLong); // "int128" g_type_map.Append(ConstString("__int128_t"), eBasicTypeInt128); g_type_map.Append(ConstString("__uint128_t"), eBasicTypeUnsignedInt128); // Miscellaneous g_type_map.Append(ConstString("bool"), eBasicTypeBool); g_type_map.Append(ConstString("float"), eBasicTypeFloat); g_type_map.Append(ConstString("double"), eBasicTypeDouble); g_type_map.Append(ConstString("long double"), eBasicTypeLongDouble); g_type_map.Append(ConstString("id"), eBasicTypeObjCID); g_type_map.Append(ConstString("SEL"), eBasicTypeObjCSel); g_type_map.Append(ConstString("nullptr"), eBasicTypeNullPtr); g_type_map.Sort(); }); return g_type_map.Find(name, eBasicTypeInvalid); } return eBasicTypeInvalid; } uint32_t TypeSystemClang::GetPointerByteSize() { if (m_pointer_byte_size == 0) if (auto size = GetBasicType(lldb::eBasicTypeVoid) .GetPointerType() .GetByteSize(nullptr)) m_pointer_byte_size = *size; return m_pointer_byte_size; } CompilerType TypeSystemClang::GetBasicType(lldb::BasicType basic_type) { clang::ASTContext &ast = getASTContext(); lldb::opaque_compiler_type_t clang_type = GetOpaqueCompilerType(&ast, basic_type); if (clang_type) return CompilerType(this, clang_type); return CompilerType(); } CompilerType TypeSystemClang::GetBuiltinTypeForDWARFEncodingAndBitSize( llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size) { ASTContext &ast = getASTContext(); switch (dw_ate) { default: break; case DW_ATE_address: if (QualTypeMatchesBitSize(bit_size, ast, ast.VoidPtrTy)) return GetType(ast.VoidPtrTy); break; case DW_ATE_boolean: if (QualTypeMatchesBitSize(bit_size, ast, ast.BoolTy)) return GetType(ast.BoolTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) return GetType(ast.UnsignedIntTy); break; case DW_ATE_lo_user: // This has been seen to mean DW_AT_complex_integer if (type_name.contains("complex")) { CompilerType complex_int_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize("int", DW_ATE_signed, bit_size / 2); return GetType( ast.getComplexType(ClangUtil::GetQualType(complex_int_clang_type))); } break; case DW_ATE_complex_float: if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatComplexTy)) return GetType(ast.FloatComplexTy); else if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleComplexTy)) return GetType(ast.DoubleComplexTy); else if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleComplexTy)) return GetType(ast.LongDoubleComplexTy); else { CompilerType complex_float_clang_type = GetBuiltinTypeForDWARFEncodingAndBitSize("float", DW_ATE_float, bit_size / 2); return GetType( ast.getComplexType(ClangUtil::GetQualType(complex_float_clang_type))); } break; case DW_ATE_float: if (type_name == "float" && QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) return GetType(ast.FloatTy); if (type_name == "double" && QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) return GetType(ast.DoubleTy); if (type_name == "long double" && QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) return GetType(ast.LongDoubleTy); // Fall back to not requiring a name match if (QualTypeMatchesBitSize(bit_size, ast, ast.FloatTy)) return GetType(ast.FloatTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.DoubleTy)) return GetType(ast.DoubleTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongDoubleTy)) return GetType(ast.LongDoubleTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.HalfTy)) return GetType(ast.HalfTy); break; case DW_ATE_signed: if (!type_name.empty()) { if (type_name == "wchar_t" && QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy) && (getTargetInfo() && TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) return GetType(ast.WCharTy); if (type_name == "void" && QualTypeMatchesBitSize(bit_size, ast, ast.VoidTy)) return GetType(ast.VoidTy); if (type_name.contains("long long") && QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) return GetType(ast.LongLongTy); if (type_name.contains("long") && QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) return GetType(ast.LongTy); if (type_name.contains("short") && QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) return GetType(ast.ShortTy); if (type_name.contains("char")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) return GetType(ast.CharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) return GetType(ast.SignedCharTy); } if (type_name.contains("int")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) return GetType(ast.IntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) return GetType(ast.Int128Ty); } } // We weren't able to match up a type name, just search by size if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) return GetType(ast.CharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.ShortTy)) return GetType(ast.ShortTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.IntTy)) return GetType(ast.IntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongTy)) return GetType(ast.LongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.LongLongTy)) return GetType(ast.LongLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.Int128Ty)) return GetType(ast.Int128Ty); break; case DW_ATE_signed_char: if (ast.getLangOpts().CharIsSigned && type_name == "char") { if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) return GetType(ast.CharTy); } if (QualTypeMatchesBitSize(bit_size, ast, ast.SignedCharTy)) return GetType(ast.SignedCharTy); break; case DW_ATE_unsigned: if (!type_name.empty()) { if (type_name == "wchar_t") { if (QualTypeMatchesBitSize(bit_size, ast, ast.WCharTy)) { if (!(getTargetInfo() && TargetInfo::isTypeSigned(getTargetInfo()->getWCharType()))) return GetType(ast.WCharTy); } } if (type_name.contains("long long")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) return GetType(ast.UnsignedLongLongTy); } else if (type_name.contains("long")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) return GetType(ast.UnsignedLongTy); } else if (type_name.contains("short")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); } else if (type_name.contains("char")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); } else if (type_name.contains("int")) { if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) return GetType(ast.UnsignedIntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) return GetType(ast.UnsignedInt128Ty); } } // We weren't able to match up a type name, just search by size if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedIntTy)) return GetType(ast.UnsignedIntTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongTy)) return GetType(ast.UnsignedLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedLongLongTy)) return GetType(ast.UnsignedLongLongTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedInt128Ty)) return GetType(ast.UnsignedInt128Ty); break; case DW_ATE_unsigned_char: if (!ast.getLangOpts().CharIsSigned && type_name == "char") { if (QualTypeMatchesBitSize(bit_size, ast, ast.CharTy)) return GetType(ast.CharTy); } if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); if (QualTypeMatchesBitSize(bit_size, ast, ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); break; case DW_ATE_imaginary_float: break; case DW_ATE_UTF: switch (bit_size) { case 8: return GetType(ast.Char8Ty); case 16: return GetType(ast.Char16Ty); case 32: return GetType(ast.Char32Ty); default: if (!type_name.empty()) { if (type_name == "char16_t") return GetType(ast.Char16Ty); if (type_name == "char32_t") return GetType(ast.Char32Ty); if (type_name == "char8_t") return GetType(ast.Char8Ty); } } break; } // This assert should fire for anything that we don't catch above so we know // to fix any issues we run into. if (!type_name.empty()) { std::string type_name_str = type_name.str(); Host::SystemLog(Host::eSystemLogError, "error: need to add support for DW_TAG_base_type '%s' " "encoded with DW_ATE = 0x%x, bit_size = %u\n", type_name_str.c_str(), dw_ate, bit_size); } else { Host::SystemLog(Host::eSystemLogError, "error: need to add support for " "DW_TAG_base_type encoded with " "DW_ATE = 0x%x, bit_size = %u\n", dw_ate, bit_size); } return CompilerType(); } CompilerType TypeSystemClang::GetCStringType(bool is_const) { ASTContext &ast = getASTContext(); QualType char_type(ast.CharTy); if (is_const) char_type.addConst(); return GetType(ast.getPointerType(char_type)); } bool TypeSystemClang::AreTypesSame(CompilerType type1, CompilerType type2, bool ignore_qualifiers) { TypeSystemClang *ast = llvm::dyn_cast_or_null(type1.GetTypeSystem()); if (!ast || ast != type2.GetTypeSystem()) return false; if (type1.GetOpaqueQualType() == type2.GetOpaqueQualType()) return true; QualType type1_qual = ClangUtil::GetQualType(type1); QualType type2_qual = ClangUtil::GetQualType(type2); if (ignore_qualifiers) { type1_qual = type1_qual.getUnqualifiedType(); type2_qual = type2_qual.getUnqualifiedType(); } return ast->getASTContext().hasSameType(type1_qual, type2_qual); } CompilerType TypeSystemClang::GetTypeForDecl(void *opaque_decl) { if (!opaque_decl) return CompilerType(); clang::Decl *decl = static_cast(opaque_decl); if (auto *named_decl = llvm::dyn_cast(decl)) return GetTypeForDecl(named_decl); return CompilerType(); } CompilerDeclContext TypeSystemClang::CreateDeclContext(DeclContext *ctx) { // Check that the DeclContext actually belongs to this ASTContext. assert(&ctx->getParentASTContext() == &getASTContext()); return CompilerDeclContext(this, ctx); } CompilerType TypeSystemClang::GetTypeForDecl(clang::NamedDecl *decl) { if (clang::ObjCInterfaceDecl *interface_decl = llvm::dyn_cast(decl)) return GetTypeForDecl(interface_decl); if (clang::TagDecl *tag_decl = llvm::dyn_cast(decl)) return GetTypeForDecl(tag_decl); return CompilerType(); } CompilerType TypeSystemClang::GetTypeForDecl(TagDecl *decl) { return GetType(getASTContext().getTagDeclType(decl)); } CompilerType TypeSystemClang::GetTypeForDecl(ObjCInterfaceDecl *decl) { return GetType(getASTContext().getObjCInterfaceType(decl)); } #pragma mark Structure, Unions, Classes void TypeSystemClang::SetOwningModule(clang::Decl *decl, OptionalClangModuleID owning_module) { if (!decl || !owning_module.HasValue()) return; decl->setFromASTFile(); decl->setOwningModuleID(owning_module.GetValue()); decl->setModuleOwnershipKind(clang::Decl::ModuleOwnershipKind::Visible); } OptionalClangModuleID TypeSystemClang::GetOrCreateClangModule(llvm::StringRef name, OptionalClangModuleID parent, bool is_framework, bool is_explicit) { // Get the external AST source which holds the modules. auto *ast_source = llvm::dyn_cast_or_null( getASTContext().getExternalSource()); assert(ast_source && "external ast source was lost"); if (!ast_source) return {}; // Lazily initialize the module map. if (!m_header_search_up) { auto HSOpts = std::make_shared(); m_header_search_up = std::make_unique( HSOpts, *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up, m_target_info_up.get()); m_module_map_up = std::make_unique( *m_source_manager_up, *m_diagnostics_engine_up, *m_language_options_up, m_target_info_up.get(), *m_header_search_up); } // Get or create the module context. bool created; clang::Module *module; auto parent_desc = ast_source->getSourceDescriptor(parent.GetValue()); std::tie(module, created) = m_module_map_up->findOrCreateModule( name, parent_desc ? parent_desc->getModuleOrNull() : nullptr, is_framework, is_explicit); if (!created) return ast_source->GetIDForModule(module); return ast_source->RegisterModule(module); } CompilerType TypeSystemClang::CreateRecordType( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, AccessType access_type, llvm::StringRef name, int kind, LanguageType language, ClangASTMetadata *metadata, bool exports_symbols) { ASTContext &ast = getASTContext(); if (decl_ctx == nullptr) decl_ctx = ast.getTranslationUnitDecl(); if (language == eLanguageTypeObjC || language == eLanguageTypeObjC_plus_plus) { bool isForwardDecl = true; bool isInternal = false; return CreateObjCClass(name, decl_ctx, owning_module, isForwardDecl, isInternal, metadata); } // NOTE: Eventually CXXRecordDecl will be merged back into RecordDecl and // we will need to update this code. I was told to currently always use the // CXXRecordDecl class since we often don't know from debug information if // something is struct or a class, so we default to always use the more // complete definition just in case. bool has_name = !name.empty(); CXXRecordDecl *decl = CXXRecordDecl::CreateDeserialized(ast, 0); decl->setTagKind(static_cast(kind)); decl->setDeclContext(decl_ctx); if (has_name) decl->setDeclName(&ast.Idents.get(name)); SetOwningModule(decl, owning_module); if (!has_name) { // In C++ a lambda is also represented as an unnamed class. This is // different from an *anonymous class* that the user wrote: // // struct A { // // anonymous class (GNU/MSVC extension) // struct { // int x; // }; // // unnamed class within a class // struct { // int y; // } B; // }; // // void f() { // // unammed class outside of a class // struct { // int z; // } C; // } // // Anonymous classes is a GNU/MSVC extension that clang supports. It // requires the anonymous class be embedded within a class. So the new // heuristic verifies this condition. if (isa(decl_ctx) && exports_symbols) decl->setAnonymousStructOrUnion(true); } if (decl) { if (metadata) SetMetadata(decl, *metadata); if (access_type != eAccessNone) decl->setAccess(ConvertAccessTypeToAccessSpecifier(access_type)); if (decl_ctx) decl_ctx->addDecl(decl); return GetType(ast.getTagDeclType(decl)); } return CompilerType(); } namespace { bool IsValueParam(const clang::TemplateArgument &argument) { return argument.getKind() == TemplateArgument::Integral; } } static TemplateParameterList *CreateTemplateParameterList( ASTContext &ast, const TypeSystemClang::TemplateParameterInfos &template_param_infos, llvm::SmallVector &template_param_decls) { const bool parameter_pack = false; const bool is_typename = false; const unsigned depth = 0; const size_t num_template_params = template_param_infos.args.size(); DeclContext *const decl_context = ast.getTranslationUnitDecl(); // Is this the right decl context?, for (size_t i = 0; i < num_template_params; ++i) { const char *name = template_param_infos.names[i]; IdentifierInfo *identifier_info = nullptr; if (name && name[0]) identifier_info = &ast.Idents.get(name); if (IsValueParam(template_param_infos.args[i])) { QualType template_param_type = template_param_infos.args[i].getIntegralType(); template_param_decls.push_back(NonTypeTemplateParmDecl::Create( ast, decl_context, SourceLocation(), SourceLocation(), depth, i, identifier_info, template_param_type, parameter_pack, ast.getTrivialTypeSourceInfo(template_param_type))); } else { template_param_decls.push_back(TemplateTypeParmDecl::Create( ast, decl_context, SourceLocation(), SourceLocation(), depth, i, identifier_info, is_typename, parameter_pack)); } } 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 (!template_param_infos.packed_args->args.empty() && IsValueParam(template_param_infos.packed_args->args[0])) { QualType template_param_type = template_param_infos.packed_args->args[0].getIntegralType(); template_param_decls.push_back(NonTypeTemplateParmDecl::Create( ast, decl_context, SourceLocation(), SourceLocation(), depth, num_template_params, identifier_info, template_param_type, parameter_pack_true, ast.getTrivialTypeSourceInfo(template_param_type))); } else { template_param_decls.push_back(TemplateTypeParmDecl::Create( ast, decl_context, SourceLocation(), SourceLocation(), depth, num_template_params, identifier_info, is_typename, parameter_pack_true)); } } clang::Expr *const requires_clause = nullptr; // TODO: Concepts TemplateParameterList *template_param_list = TemplateParameterList::Create( ast, SourceLocation(), SourceLocation(), template_param_decls, SourceLocation(), requires_clause); return template_param_list; } clang::FunctionTemplateDecl *TypeSystemClang::CreateFunctionTemplateDecl( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, clang::FunctionDecl *func_decl, const char *name, const TemplateParameterInfos &template_param_infos) { // /// Create a function template node. ASTContext &ast = getASTContext(); llvm::SmallVector template_param_decls; TemplateParameterList *template_param_list = CreateTemplateParameterList( ast, template_param_infos, template_param_decls); FunctionTemplateDecl *func_tmpl_decl = FunctionTemplateDecl::CreateDeserialized(ast, 0); func_tmpl_decl->setDeclContext(decl_ctx); func_tmpl_decl->setLocation(func_decl->getLocation()); func_tmpl_decl->setDeclName(func_decl->getDeclName()); func_tmpl_decl->init(func_decl, template_param_list); SetOwningModule(func_tmpl_decl, owning_module); for (size_t i = 0, template_param_decl_count = template_param_decls.size(); i < template_param_decl_count; ++i) { // TODO: verify which decl context we should put template_param_decls into.. template_param_decls[i]->setDeclContext(func_decl); } // Function templates inside a record need to have an access specifier. // It doesn't matter what access specifier we give the template as LLDB // anyway allows accessing everything inside a record. if (decl_ctx->isRecord()) func_tmpl_decl->setAccess(clang::AccessSpecifier::AS_public); return func_tmpl_decl; } void TypeSystemClang::CreateFunctionTemplateSpecializationInfo( FunctionDecl *func_decl, clang::FunctionTemplateDecl *func_tmpl_decl, const TemplateParameterInfos &infos) { TemplateArgumentList *template_args_ptr = TemplateArgumentList::CreateCopy(func_decl->getASTContext(), infos.args); func_decl->setFunctionTemplateSpecialization(func_tmpl_decl, template_args_ptr, nullptr); } ClassTemplateDecl *TypeSystemClang::CreateClassTemplateDecl( DeclContext *decl_ctx, OptionalClangModuleID owning_module, lldb::AccessType access_type, const char *class_name, int kind, const TemplateParameterInfos &template_param_infos) { ASTContext &ast = getASTContext(); ClassTemplateDecl *class_template_decl = nullptr; if (decl_ctx == nullptr) decl_ctx = ast.getTranslationUnitDecl(); IdentifierInfo &identifier_info = ast.Idents.get(class_name); DeclarationName decl_name(&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); for (NamedDecl *decl : result) { class_template_decl = dyn_cast(decl); if (class_template_decl) return class_template_decl; } llvm::SmallVector template_param_decls; TemplateParameterList *template_param_list = CreateTemplateParameterList( ast, template_param_infos, template_param_decls); CXXRecordDecl *template_cxx_decl = CXXRecordDecl::CreateDeserialized(ast, 0); template_cxx_decl->setTagKind(static_cast(kind)); // What decl context do we use here? TU? The actual decl context? template_cxx_decl->setDeclContext(decl_ctx); template_cxx_decl->setDeclName(decl_name); SetOwningModule(template_cxx_decl, owning_module); for (size_t i = 0, template_param_decl_count = template_param_decls.size(); i < template_param_decl_count; ++i) { template_param_decls[i]->setDeclContext(template_cxx_decl); } // With templated classes, we say that a class is templated with // specializations, but that the bare class has no functions. // template_cxx_decl->startDefinition(); // template_cxx_decl->completeDefinition(); class_template_decl = ClassTemplateDecl::CreateDeserialized(ast, 0); // What decl context do we use here? TU? The actual decl context? class_template_decl->setDeclContext(decl_ctx); class_template_decl->setDeclName(decl_name); class_template_decl->init(template_cxx_decl, template_param_list); template_cxx_decl->setDescribedClassTemplate(class_template_decl); SetOwningModule(class_template_decl, owning_module); if (class_template_decl) { if (access_type != eAccessNone) class_template_decl->setAccess( ConvertAccessTypeToAccessSpecifier(access_type)); decl_ctx->addDecl(class_template_decl); VerifyDecl(class_template_decl); } return class_template_decl; } TemplateTemplateParmDecl * TypeSystemClang::CreateTemplateTemplateParmDecl(const char *template_name) { ASTContext &ast = getASTContext(); auto *decl_ctx = ast.getTranslationUnitDecl(); IdentifierInfo &identifier_info = ast.Idents.get(template_name); llvm::SmallVector template_param_decls; TypeSystemClang::TemplateParameterInfos template_param_infos; TemplateParameterList *template_param_list = CreateTemplateParameterList( ast, template_param_infos, template_param_decls); // LLDB needs to create those decls only to be able to display a // type that includes a template template argument. Only the name matters for // this purpose, so we use dummy values for the other characteristics of the // type. return TemplateTemplateParmDecl::Create( ast, decl_ctx, SourceLocation(), /*Depth*/ 0, /*Position*/ 0, /*IsParameterPack*/ false, &identifier_info, template_param_list); } ClassTemplateSpecializationDecl * TypeSystemClang::CreateClassTemplateSpecializationDecl( DeclContext *decl_ctx, OptionalClangModuleID owning_module, ClassTemplateDecl *class_template_decl, int kind, const TemplateParameterInfos &template_param_infos) { ASTContext &ast = getASTContext(); llvm::SmallVector args( template_param_infos.args.size() + (template_param_infos.packed_args ? 1 : 0)); std::copy(template_param_infos.args.begin(), template_param_infos.args.end(), args.begin()); if (template_param_infos.packed_args) { args[args.size() - 1] = TemplateArgument::CreatePackCopy( ast, template_param_infos.packed_args->args); } ClassTemplateSpecializationDecl *class_template_specialization_decl = ClassTemplateSpecializationDecl::CreateDeserialized(ast, 0); class_template_specialization_decl->setTagKind( static_cast(kind)); class_template_specialization_decl->setDeclContext(decl_ctx); class_template_specialization_decl->setInstantiationOf(class_template_decl); class_template_specialization_decl->setTemplateArgs( TemplateArgumentList::CreateCopy(ast, args)); ast.getTypeDeclType(class_template_specialization_decl, nullptr); class_template_specialization_decl->setDeclName( class_template_decl->getDeclName()); SetOwningModule(class_template_specialization_decl, owning_module); decl_ctx->addDecl(class_template_specialization_decl); class_template_specialization_decl->setSpecializationKind( TSK_ExplicitSpecialization); return class_template_specialization_decl; } CompilerType TypeSystemClang::CreateClassTemplateSpecializationType( ClassTemplateSpecializationDecl *class_template_specialization_decl) { if (class_template_specialization_decl) { ASTContext &ast = getASTContext(); return GetType(ast.getTagDeclType(class_template_specialization_decl)); } return CompilerType(); } static inline bool check_op_param(bool is_method, clang::OverloadedOperatorKind op_kind, bool unary, bool binary, uint32_t num_params) { // Special-case call since it can take any number of operands if (op_kind == OO_Call) return true; // The parameter count doesn't include "this" if (is_method) ++num_params; if (num_params == 1) return unary; if (num_params == 2) return binary; else return false; } bool TypeSystemClang::CheckOverloadedOperatorKindParameterCount( bool is_method, clang::OverloadedOperatorKind op_kind, uint32_t num_params) { switch (op_kind) { default: break; // C++ standard allows any number of arguments to new/delete case OO_New: case OO_Array_New: case OO_Delete: case OO_Array_Delete: return true; } #define OVERLOADED_OPERATOR(Name, Spelling, Token, Unary, Binary, MemberOnly) \ case OO_##Name: \ return check_op_param(is_method, op_kind, Unary, Binary, num_params); switch (op_kind) { #include "clang/Basic/OperatorKinds.def" default: break; } return false; } clang::AccessSpecifier TypeSystemClang::UnifyAccessSpecifiers(clang::AccessSpecifier lhs, clang::AccessSpecifier rhs) { // Make the access equal to the stricter of the field and the nested field's // access if (lhs == AS_none || rhs == AS_none) return AS_none; if (lhs == AS_private || rhs == AS_private) return AS_private; if (lhs == AS_protected || rhs == AS_protected) return AS_protected; return AS_public; } bool TypeSystemClang::FieldIsBitfield(FieldDecl *field, uint32_t &bitfield_bit_size) { ASTContext &ast = getASTContext(); if (field == nullptr) return false; if (field->isBitField()) { Expr *bit_width_expr = field->getBitWidth(); if (bit_width_expr) { llvm::APSInt bit_width_apsint; if (bit_width_expr->isIntegerConstantExpr(bit_width_apsint, ast)) { bitfield_bit_size = bit_width_apsint.getLimitedValue(UINT32_MAX); return true; } } } return false; } bool TypeSystemClang::RecordHasFields(const RecordDecl *record_decl) { if (record_decl == nullptr) return false; if (!record_decl->field_empty()) return true; // No fields, lets check this is a CXX record and check the base classes const CXXRecordDecl *cxx_record_decl = dyn_cast(record_decl); if (cxx_record_decl) { CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { const CXXRecordDecl *base_class_decl = cast( base_class->getType()->getAs()->getDecl()); if (RecordHasFields(base_class_decl)) return true; } } return false; } #pragma mark Objective-C Classes CompilerType TypeSystemClang::CreateObjCClass( llvm::StringRef name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal, ClangASTMetadata *metadata) { ASTContext &ast = getASTContext(); assert(!name.empty()); if (!decl_ctx) decl_ctx = ast.getTranslationUnitDecl(); ObjCInterfaceDecl *decl = ObjCInterfaceDecl::CreateDeserialized(ast, 0); decl->setDeclContext(decl_ctx); decl->setDeclName(&ast.Idents.get(name)); /*isForwardDecl,*/ decl->setImplicit(isInternal); SetOwningModule(decl, owning_module); if (decl && metadata) SetMetadata(decl, *metadata); return GetType(ast.getObjCInterfaceType(decl)); } static inline bool BaseSpecifierIsEmpty(const CXXBaseSpecifier *b) { return !TypeSystemClang::RecordHasFields(b->getType()->getAsCXXRecordDecl()); } uint32_t TypeSystemClang::GetNumBaseClasses(const CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes) { uint32_t num_bases = 0; if (cxx_record_decl) { if (omit_empty_base_classes) { CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { // Skip empty base classes if (BaseSpecifierIsEmpty(base_class)) continue; ++num_bases; } } else num_bases = cxx_record_decl->getNumBases(); } return num_bases; } #pragma mark Namespace Declarations NamespaceDecl *TypeSystemClang::GetUniqueNamespaceDeclaration( const char *name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, bool is_inline) { NamespaceDecl *namespace_decl = nullptr; ASTContext &ast = getASTContext(); TranslationUnitDecl *translation_unit_decl = ast.getTranslationUnitDecl(); if (!decl_ctx) decl_ctx = translation_unit_decl; if (name) { IdentifierInfo &identifier_info = ast.Idents.get(name); DeclarationName decl_name(&identifier_info); clang::DeclContext::lookup_result result = decl_ctx->lookup(decl_name); for (NamedDecl *decl : result) { namespace_decl = dyn_cast(decl); if (namespace_decl) return namespace_decl; } namespace_decl = NamespaceDecl::Create(ast, decl_ctx, is_inline, SourceLocation(), SourceLocation(), &identifier_info, nullptr); decl_ctx->addDecl(namespace_decl); } else { if (decl_ctx == translation_unit_decl) { namespace_decl = translation_unit_decl->getAnonymousNamespace(); if (namespace_decl) return namespace_decl; namespace_decl = NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), SourceLocation(), nullptr, nullptr); translation_unit_decl->setAnonymousNamespace(namespace_decl); translation_unit_decl->addDecl(namespace_decl); assert(namespace_decl == translation_unit_decl->getAnonymousNamespace()); } else { NamespaceDecl *parent_namespace_decl = cast(decl_ctx); if (parent_namespace_decl) { namespace_decl = parent_namespace_decl->getAnonymousNamespace(); if (namespace_decl) return namespace_decl; namespace_decl = NamespaceDecl::Create(ast, decl_ctx, false, SourceLocation(), SourceLocation(), nullptr, nullptr); parent_namespace_decl->setAnonymousNamespace(namespace_decl); parent_namespace_decl->addDecl(namespace_decl); assert(namespace_decl == parent_namespace_decl->getAnonymousNamespace()); } else { assert(false && "GetUniqueNamespaceDeclaration called with no name and " "no namespace as decl_ctx"); } } } // Note: namespaces can span multiple modules, so perhaps this isn't a good // idea. SetOwningModule(namespace_decl, owning_module); VerifyDecl(namespace_decl); return namespace_decl; } clang::BlockDecl * TypeSystemClang::CreateBlockDeclaration(clang::DeclContext *ctx, OptionalClangModuleID owning_module) { if (ctx) { clang::BlockDecl *decl = clang::BlockDecl::CreateDeserialized(getASTContext(), 0); decl->setDeclContext(ctx); ctx->addDecl(decl); SetOwningModule(decl, owning_module); return decl; } return nullptr; } clang::DeclContext *FindLCABetweenDecls(clang::DeclContext *left, clang::DeclContext *right, clang::DeclContext *root) { if (root == nullptr) return nullptr; std::set path_left; for (clang::DeclContext *d = left; d != nullptr; d = d->getParent()) path_left.insert(d); for (clang::DeclContext *d = right; d != nullptr; d = d->getParent()) if (path_left.find(d) != path_left.end()) return d; return nullptr; } clang::UsingDirectiveDecl *TypeSystemClang::CreateUsingDirectiveDeclaration( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, clang::NamespaceDecl *ns_decl) { if (decl_ctx && ns_decl) { auto *translation_unit = getASTContext().getTranslationUnitDecl(); clang::UsingDirectiveDecl *using_decl = clang::UsingDirectiveDecl::Create( getASTContext(), decl_ctx, clang::SourceLocation(), clang::SourceLocation(), clang::NestedNameSpecifierLoc(), clang::SourceLocation(), ns_decl, FindLCABetweenDecls(decl_ctx, ns_decl, translation_unit)); decl_ctx->addDecl(using_decl); SetOwningModule(using_decl, owning_module); return using_decl; } return nullptr; } clang::UsingDecl * TypeSystemClang::CreateUsingDeclaration(clang::DeclContext *current_decl_ctx, OptionalClangModuleID owning_module, clang::NamedDecl *target) { if (current_decl_ctx && target) { clang::UsingDecl *using_decl = clang::UsingDecl::Create( getASTContext(), current_decl_ctx, clang::SourceLocation(), clang::NestedNameSpecifierLoc(), clang::DeclarationNameInfo(), false); SetOwningModule(using_decl, owning_module); clang::UsingShadowDecl *shadow_decl = clang::UsingShadowDecl::Create( getASTContext(), current_decl_ctx, clang::SourceLocation(), using_decl, target); SetOwningModule(shadow_decl, owning_module); using_decl->addShadowDecl(shadow_decl); current_decl_ctx->addDecl(using_decl); return using_decl; } return nullptr; } clang::VarDecl *TypeSystemClang::CreateVariableDeclaration( clang::DeclContext *decl_context, OptionalClangModuleID owning_module, const char *name, clang::QualType type) { if (decl_context) { clang::VarDecl *var_decl = clang::VarDecl::CreateDeserialized(getASTContext(), 0); var_decl->setDeclContext(decl_context); if (name && name[0]) var_decl->setDeclName(&getASTContext().Idents.getOwn(name)); var_decl->setType(type); SetOwningModule(var_decl, owning_module); var_decl->setAccess(clang::AS_public); decl_context->addDecl(var_decl); return var_decl; } return nullptr; } lldb::opaque_compiler_type_t TypeSystemClang::GetOpaqueCompilerType(clang::ASTContext *ast, lldb::BasicType basic_type) { switch (basic_type) { case eBasicTypeVoid: return ast->VoidTy.getAsOpaquePtr(); case eBasicTypeChar: return ast->CharTy.getAsOpaquePtr(); case eBasicTypeSignedChar: return ast->SignedCharTy.getAsOpaquePtr(); case eBasicTypeUnsignedChar: return ast->UnsignedCharTy.getAsOpaquePtr(); case eBasicTypeWChar: return ast->getWCharType().getAsOpaquePtr(); case eBasicTypeSignedWChar: return ast->getSignedWCharType().getAsOpaquePtr(); case eBasicTypeUnsignedWChar: return ast->getUnsignedWCharType().getAsOpaquePtr(); case eBasicTypeChar16: return ast->Char16Ty.getAsOpaquePtr(); case eBasicTypeChar32: return ast->Char32Ty.getAsOpaquePtr(); case eBasicTypeShort: return ast->ShortTy.getAsOpaquePtr(); case eBasicTypeUnsignedShort: return ast->UnsignedShortTy.getAsOpaquePtr(); case eBasicTypeInt: return ast->IntTy.getAsOpaquePtr(); case eBasicTypeUnsignedInt: return ast->UnsignedIntTy.getAsOpaquePtr(); case eBasicTypeLong: return ast->LongTy.getAsOpaquePtr(); case eBasicTypeUnsignedLong: return ast->UnsignedLongTy.getAsOpaquePtr(); case eBasicTypeLongLong: return ast->LongLongTy.getAsOpaquePtr(); case eBasicTypeUnsignedLongLong: return ast->UnsignedLongLongTy.getAsOpaquePtr(); case eBasicTypeInt128: return ast->Int128Ty.getAsOpaquePtr(); case eBasicTypeUnsignedInt128: return ast->UnsignedInt128Ty.getAsOpaquePtr(); case eBasicTypeBool: return ast->BoolTy.getAsOpaquePtr(); case eBasicTypeHalf: return ast->HalfTy.getAsOpaquePtr(); case eBasicTypeFloat: return ast->FloatTy.getAsOpaquePtr(); case eBasicTypeDouble: return ast->DoubleTy.getAsOpaquePtr(); case eBasicTypeLongDouble: return ast->LongDoubleTy.getAsOpaquePtr(); case eBasicTypeFloatComplex: return ast->FloatComplexTy.getAsOpaquePtr(); case eBasicTypeDoubleComplex: return ast->DoubleComplexTy.getAsOpaquePtr(); case eBasicTypeLongDoubleComplex: return ast->LongDoubleComplexTy.getAsOpaquePtr(); case eBasicTypeObjCID: return ast->getObjCIdType().getAsOpaquePtr(); case eBasicTypeObjCClass: return ast->getObjCClassType().getAsOpaquePtr(); case eBasicTypeObjCSel: return ast->getObjCSelType().getAsOpaquePtr(); case eBasicTypeNullPtr: return ast->NullPtrTy.getAsOpaquePtr(); default: return nullptr; } } #pragma mark Function Types clang::DeclarationName TypeSystemClang::GetDeclarationName(const char *name, const CompilerType &function_clang_type) { if (!name || !name[0]) return clang::DeclarationName(); clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; if (!IsOperator(name, op_kind) || op_kind == clang::NUM_OVERLOADED_OPERATORS) return DeclarationName(&getASTContext().Idents.get( name)); // Not operator, but a regular function. // Check the number of operator parameters. Sometimes we have seen bad DWARF // that doesn't correctly describe operators and if we try to create a method // and add it to the class, clang will assert and crash, so we need to make // sure things are acceptable. clang::QualType method_qual_type(ClangUtil::GetQualType(function_clang_type)); const clang::FunctionProtoType *function_type = llvm::dyn_cast(method_qual_type.getTypePtr()); if (function_type == nullptr) return clang::DeclarationName(); const bool is_method = false; const unsigned int num_params = function_type->getNumParams(); if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount( is_method, op_kind, num_params)) return clang::DeclarationName(); return getASTContext().DeclarationNames.getCXXOperatorName(op_kind); } FunctionDecl *TypeSystemClang::CreateFunctionDeclaration( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const char *name, const CompilerType &function_clang_type, int storage, bool is_inline) { FunctionDecl *func_decl = nullptr; ASTContext &ast = getASTContext(); if (!decl_ctx) decl_ctx = ast.getTranslationUnitDecl(); const bool hasWrittenPrototype = true; const bool isConstexprSpecified = false; clang::DeclarationName declarationName = GetDeclarationName(name, function_clang_type); func_decl = FunctionDecl::CreateDeserialized(ast, 0); func_decl->setDeclContext(decl_ctx); func_decl->setDeclName(declarationName); func_decl->setType(ClangUtil::GetQualType(function_clang_type)); func_decl->setStorageClass(static_cast(storage)); func_decl->setInlineSpecified(is_inline); func_decl->setHasWrittenPrototype(hasWrittenPrototype); func_decl->setConstexprKind(isConstexprSpecified ? CSK_constexpr : CSK_unspecified); SetOwningModule(func_decl, owning_module); if (func_decl) decl_ctx->addDecl(func_decl); VerifyDecl(func_decl); return func_decl; } CompilerType TypeSystemClang::CreateFunctionType(const CompilerType &result_type, const CompilerType *args, unsigned num_args, bool is_variadic, unsigned type_quals, clang::CallingConv cc) { if (!result_type || !ClangUtil::IsClangType(result_type)) return CompilerType(); // invalid return type std::vector qual_type_args; if (num_args > 0 && args == nullptr) return CompilerType(); // invalid argument array passed in // Verify that all arguments are valid and the right type for (unsigned i = 0; i < num_args; ++i) { if (args[i]) { // Make sure we have a clang type in args[i] and not a type from another // language whose name might match const bool is_clang_type = ClangUtil::IsClangType(args[i]); lldbassert(is_clang_type); if (is_clang_type) qual_type_args.push_back(ClangUtil::GetQualType(args[i])); else return CompilerType(); // invalid argument type (must be a clang type) } else return CompilerType(); // invalid argument type (empty) } // TODO: Detect calling convention in DWARF? FunctionProtoType::ExtProtoInfo proto_info; proto_info.ExtInfo = cc; proto_info.Variadic = is_variadic; proto_info.ExceptionSpec = EST_None; proto_info.TypeQuals = clang::Qualifiers::fromFastMask(type_quals); proto_info.RefQualifier = RQ_None; return GetType(getASTContext().getFunctionType( ClangUtil::GetQualType(result_type), qual_type_args, proto_info)); } ParmVarDecl *TypeSystemClang::CreateParameterDeclaration( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const char *name, const CompilerType ¶m_type, int storage, bool add_decl) { ASTContext &ast = getASTContext(); auto *decl = ParmVarDecl::CreateDeserialized(ast, 0); decl->setDeclContext(decl_ctx); if (name && name[0]) decl->setDeclName(&ast.Idents.get(name)); decl->setType(ClangUtil::GetQualType(param_type)); decl->setStorageClass(static_cast(storage)); SetOwningModule(decl, owning_module); if (add_decl) decl_ctx->addDecl(decl); return decl; } void TypeSystemClang::SetFunctionParameters(FunctionDecl *function_decl, ParmVarDecl **params, unsigned num_params) { if (function_decl) function_decl->setParams(ArrayRef(params, num_params)); } CompilerType TypeSystemClang::CreateBlockPointerType(const CompilerType &function_type) { QualType block_type = m_ast_up->getBlockPointerType( clang::QualType::getFromOpaquePtr(function_type.GetOpaqueQualType())); return GetType(block_type); } #pragma mark Array Types CompilerType TypeSystemClang::CreateArrayType(const CompilerType &element_type, size_t element_count, bool is_vector) { if (element_type.IsValid()) { ASTContext &ast = getASTContext(); if (is_vector) { return GetType(ast.getExtVectorType(ClangUtil::GetQualType(element_type), element_count)); } else { llvm::APInt ap_element_count(64, element_count); if (element_count == 0) { return GetType(ast.getIncompleteArrayType( ClangUtil::GetQualType(element_type), clang::ArrayType::Normal, 0)); } else { return GetType(ast.getConstantArrayType( ClangUtil::GetQualType(element_type), ap_element_count, nullptr, clang::ArrayType::Normal, 0)); } } } return CompilerType(); } CompilerType TypeSystemClang::CreateStructForIdentifier( ConstString type_name, const std::initializer_list> &type_fields, bool packed) { CompilerType type; if (!type_name.IsEmpty() && (type = GetTypeForIdentifier(type_name)) .IsValid()) { lldbassert(0 && "Trying to create a type for an existing name"); return type; } type = CreateRecordType(nullptr, OptionalClangModuleID(), lldb::eAccessPublic, type_name.GetCString(), clang::TTK_Struct, lldb::eLanguageTypeC); StartTagDeclarationDefinition(type); for (const auto &field : type_fields) AddFieldToRecordType(type, field.first, field.second, lldb::eAccessPublic, 0); if (packed) SetIsPacked(type); CompleteTagDeclarationDefinition(type); return type; } CompilerType TypeSystemClang::GetOrCreateStructForIdentifier( ConstString type_name, const std::initializer_list> &type_fields, bool packed) { CompilerType type; if ((type = GetTypeForIdentifier(type_name)).IsValid()) return type; return CreateStructForIdentifier(type_name, type_fields, packed); } #pragma mark Enumeration Types CompilerType TypeSystemClang::CreateEnumerationType( const char *name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const Declaration &decl, const CompilerType &integer_clang_type, bool is_scoped) { // TODO: Do something intelligent with the Declaration object passed in // like maybe filling in the SourceLocation with it... ASTContext &ast = getASTContext(); // TODO: ask about these... // const bool IsFixed = false; EnumDecl *enum_decl = EnumDecl::CreateDeserialized(ast, 0); enum_decl->setDeclContext(decl_ctx); if (name && name[0]) enum_decl->setDeclName(&ast.Idents.get(name)); enum_decl->setScoped(is_scoped); enum_decl->setScopedUsingClassTag(is_scoped); enum_decl->setFixed(false); SetOwningModule(enum_decl, owning_module); if (enum_decl) { if (decl_ctx) decl_ctx->addDecl(enum_decl); // TODO: check if we should be setting the promotion type too? enum_decl->setIntegerType(ClangUtil::GetQualType(integer_clang_type)); enum_decl->setAccess(AS_public); // TODO respect what's in the debug info return GetType(ast.getTagDeclType(enum_decl)); } return CompilerType(); } CompilerType TypeSystemClang::GetIntTypeFromBitSize(size_t bit_size, bool is_signed) { clang::ASTContext &ast = getASTContext(); if (is_signed) { if (bit_size == ast.getTypeSize(ast.SignedCharTy)) return GetType(ast.SignedCharTy); if (bit_size == ast.getTypeSize(ast.ShortTy)) return GetType(ast.ShortTy); if (bit_size == ast.getTypeSize(ast.IntTy)) return GetType(ast.IntTy); if (bit_size == ast.getTypeSize(ast.LongTy)) return GetType(ast.LongTy); if (bit_size == ast.getTypeSize(ast.LongLongTy)) return GetType(ast.LongLongTy); if (bit_size == ast.getTypeSize(ast.Int128Ty)) return GetType(ast.Int128Ty); } else { if (bit_size == ast.getTypeSize(ast.UnsignedCharTy)) return GetType(ast.UnsignedCharTy); if (bit_size == ast.getTypeSize(ast.UnsignedShortTy)) return GetType(ast.UnsignedShortTy); if (bit_size == ast.getTypeSize(ast.UnsignedIntTy)) return GetType(ast.UnsignedIntTy); if (bit_size == ast.getTypeSize(ast.UnsignedLongTy)) return GetType(ast.UnsignedLongTy); if (bit_size == ast.getTypeSize(ast.UnsignedLongLongTy)) return GetType(ast.UnsignedLongLongTy); if (bit_size == ast.getTypeSize(ast.UnsignedInt128Ty)) return GetType(ast.UnsignedInt128Ty); } return CompilerType(); } CompilerType TypeSystemClang::GetPointerSizedIntType(bool is_signed) { return GetIntTypeFromBitSize( getASTContext().getTypeSize(getASTContext().VoidPtrTy), is_signed); } void TypeSystemClang::DumpDeclContextHiearchy(clang::DeclContext *decl_ctx) { if (decl_ctx) { DumpDeclContextHiearchy(decl_ctx->getParent()); clang::NamedDecl *named_decl = llvm::dyn_cast(decl_ctx); if (named_decl) { printf("%20s: %s\n", decl_ctx->getDeclKindName(), named_decl->getDeclName().getAsString().c_str()); } else { printf("%20s\n", decl_ctx->getDeclKindName()); } } } void TypeSystemClang::DumpDeclHiearchy(clang::Decl *decl) { if (decl == nullptr) return; DumpDeclContextHiearchy(decl->getDeclContext()); clang::RecordDecl *record_decl = llvm::dyn_cast(decl); if (record_decl) { printf("%20s: %s%s\n", decl->getDeclKindName(), record_decl->getDeclName().getAsString().c_str(), record_decl->isInjectedClassName() ? " (injected class name)" : ""); } else { clang::NamedDecl *named_decl = llvm::dyn_cast(decl); if (named_decl) { printf("%20s: %s\n", decl->getDeclKindName(), named_decl->getDeclName().getAsString().c_str()); } else { printf("%20s\n", decl->getDeclKindName()); } } } bool TypeSystemClang::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 (true) { if (lhs_decl_ctx && rhs_decl_ctx) { const clang::Decl::Kind lhs_decl_ctx_kind = lhs_decl_ctx->getDeclKind(); const clang::Decl::Kind rhs_decl_ctx_kind = rhs_decl_ctx->getDeclKind(); if (lhs_decl_ctx_kind == rhs_decl_ctx_kind) { lhs_decl_ctx = lhs_decl_ctx->getParent(); rhs_decl_ctx = rhs_decl_ctx->getParent(); if (lhs_decl_ctx == nullptr && rhs_decl_ctx == nullptr) break; } else return false; } else return false; } // Now make sure the name of the decls match clang::NamedDecl *lhs_named_decl = llvm::dyn_cast(lhs_decl); clang::NamedDecl *rhs_named_decl = llvm::dyn_cast(rhs_decl); if (lhs_named_decl && rhs_named_decl) { clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName(); clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName(); if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) { if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString()) return false; } else return false; } 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 (true) { switch (lhs_decl_ctx->getDeclKind()) { case clang::Decl::TranslationUnit: // We don't care about the translation unit names return true; default: { clang::NamedDecl *lhs_named_decl = llvm::dyn_cast(lhs_decl_ctx); clang::NamedDecl *rhs_named_decl = llvm::dyn_cast(rhs_decl_ctx); if (lhs_named_decl && rhs_named_decl) { clang::DeclarationName lhs_decl_name = lhs_named_decl->getDeclName(); clang::DeclarationName rhs_decl_name = rhs_named_decl->getDeclName(); if (lhs_decl_name.getNameKind() == rhs_decl_name.getNameKind()) { if (lhs_decl_name.getAsString() != rhs_decl_name.getAsString()) return false; } else return false; } else return false; } break; } lhs_decl_ctx = lhs_decl_ctx->getParent(); rhs_decl_ctx = rhs_decl_ctx->getParent(); } } } } return false; } bool TypeSystemClang::GetCompleteDecl(clang::ASTContext *ast, clang::Decl *decl) { if (!decl) return false; ExternalASTSource *ast_source = ast->getExternalSource(); if (!ast_source) return false; if (clang::TagDecl *tag_decl = llvm::dyn_cast(decl)) { if (tag_decl->isCompleteDefinition()) return true; if (!tag_decl->hasExternalLexicalStorage()) return false; ast_source->CompleteType(tag_decl); return !tag_decl->getTypeForDecl()->isIncompleteType(); } else if (clang::ObjCInterfaceDecl *objc_interface_decl = llvm::dyn_cast(decl)) { if (objc_interface_decl->getDefinition()) return true; if (!objc_interface_decl->hasExternalLexicalStorage()) return false; ast_source->CompleteType(objc_interface_decl); return !objc_interface_decl->getTypeForDecl()->isIncompleteType(); } else { return false; } } void TypeSystemClang::SetMetadataAsUserID(const clang::Decl *decl, user_id_t user_id) { ClangASTMetadata meta_data; meta_data.SetUserID(user_id); SetMetadata(decl, meta_data); } void TypeSystemClang::SetMetadataAsUserID(const clang::Type *type, user_id_t user_id) { ClangASTMetadata meta_data; meta_data.SetUserID(user_id); SetMetadata(type, meta_data); } void TypeSystemClang::SetMetadata(const clang::Decl *object, ClangASTMetadata &metadata) { m_decl_metadata[object] = metadata; } void TypeSystemClang::SetMetadata(const clang::Type *object, ClangASTMetadata &metadata) { m_type_metadata[object] = metadata; } ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Decl *object) { auto It = m_decl_metadata.find(object); if (It != m_decl_metadata.end()) return &It->second; return nullptr; } ClangASTMetadata *TypeSystemClang::GetMetadata(const clang::Type *object) { auto It = m_type_metadata.find(object); if (It != m_type_metadata.end()) return &It->second; return nullptr; } bool TypeSystemClang::SetTagTypeKind(clang::QualType tag_qual_type, int kind) const { const clang::Type *clang_type = tag_qual_type.getTypePtr(); if (clang_type) { const clang::TagType *tag_type = llvm::dyn_cast(clang_type); if (tag_type) { clang::TagDecl *tag_decl = llvm::dyn_cast(tag_type->getDecl()); if (tag_decl) { tag_decl->setTagKind((clang::TagDecl::TagKind)kind); return true; } } } return false; } bool TypeSystemClang::SetDefaultAccessForRecordFields( clang::RecordDecl *record_decl, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities) { if (record_decl) { uint32_t field_idx; clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(), field_idx = 0; field != field_end; ++field, ++field_idx) { // If no accessibility was assigned, assign the correct one if (field_idx < num_assigned_accessibilities && assigned_accessibilities[field_idx] == clang::AS_none) field->setAccess((clang::AccessSpecifier)default_accessibility); } return true; } return false; } clang::DeclContext * TypeSystemClang::GetDeclContextForType(const CompilerType &type) { return GetDeclContextForType(ClangUtil::GetQualType(type)); } /// Aggressively desugar the provided type, skipping past various kinds of /// syntactic sugar and other constructs one typically wants to ignore. /// The \p mask argument allows one to skip certain kinds of simplifications, /// when one wishes to handle a certain kind of type directly. static QualType RemoveWrappingTypes(QualType type, ArrayRef mask = {}) { while (true) { if (find(mask, type->getTypeClass()) != mask.end()) return type; switch (type->getTypeClass()) { // This is not fully correct as _Atomic is more than sugar, but it is // sufficient for the purposes we care about. case clang::Type::Atomic: type = cast(type)->getValueType(); break; case clang::Type::Auto: case clang::Type::Decltype: case clang::Type::Elaborated: case clang::Type::Paren: case clang::Type::Typedef: case clang::Type::TypeOf: case clang::Type::TypeOfExpr: type = type->getLocallyUnqualifiedSingleStepDesugaredType(); break; default: return type; } } } clang::DeclContext * TypeSystemClang::GetDeclContextForType(clang::QualType type) { if (type.isNull()) return nullptr; clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType()); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::ObjCInterface: return llvm::cast(qual_type.getTypePtr()) ->getInterface(); case clang::Type::ObjCObjectPointer: return GetDeclContextForType( llvm::cast(qual_type.getTypePtr()) ->getPointeeType()); case clang::Type::Record: return llvm::cast(qual_type)->getDecl(); case clang::Type::Enum: return llvm::cast(qual_type)->getDecl(); default: break; } // No DeclContext in this type... return nullptr; } static bool GetCompleteQualType(clang::ASTContext *ast, clang::QualType qual_type, bool allow_completion = true) { qual_type = RemoveWrappingTypes(qual_type); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::ConstantArray: case clang::Type::IncompleteArray: case clang::Type::VariableArray: { const clang::ArrayType *array_type = llvm::dyn_cast(qual_type.getTypePtr()); if (array_type) return GetCompleteQualType(ast, array_type->getElementType(), allow_completion); } break; case clang::Type::Record: { clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { if (cxx_record_decl->hasExternalLexicalStorage()) { const bool is_complete = cxx_record_decl->isCompleteDefinition(); const bool fields_loaded = cxx_record_decl->hasLoadedFieldsFromExternalStorage(); if (is_complete && fields_loaded) return true; if (!allow_completion) return false; // Call the field_begin() accessor to for it to use the external source // to load the fields... clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); if (external_ast_source) { external_ast_source->CompleteType(cxx_record_decl); if (cxx_record_decl->isCompleteDefinition()) { cxx_record_decl->field_begin(); cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true); } } } } const clang::TagType *tag_type = llvm::cast(qual_type.getTypePtr()); return !tag_type->isIncompleteType(); } break; case clang::Type::Enum: { const clang::TagType *tag_type = llvm::dyn_cast(qual_type.getTypePtr()); if (tag_type) { clang::TagDecl *tag_decl = tag_type->getDecl(); if (tag_decl) { if (tag_decl->getDefinition()) return true; if (!allow_completion) return false; if (tag_decl->hasExternalLexicalStorage()) { if (ast) { clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); if (external_ast_source) { external_ast_source->CompleteType(tag_decl); return !tag_type->isIncompleteType(); } } } return false; } } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); // 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 (class_interface_decl->getDefinition()) return true; if (!allow_completion) return false; if (class_interface_decl->hasExternalLexicalStorage()) { if (ast) { clang::ExternalASTSource *external_ast_source = ast->getExternalSource(); if (external_ast_source) { external_ast_source->CompleteType(class_interface_decl); return !objc_class_type->isIncompleteType(); } } } return false; } } } break; case clang::Type::Attributed: return GetCompleteQualType( ast, llvm::cast(qual_type)->getModifiedType(), allow_completion); default: break; } return true; } static clang::ObjCIvarDecl::AccessControl ConvertAccessTypeToObjCIvarAccessControl(AccessType access) { switch (access) { case eAccessNone: return clang::ObjCIvarDecl::None; case eAccessPublic: return clang::ObjCIvarDecl::Public; case eAccessPrivate: return clang::ObjCIvarDecl::Private; case eAccessProtected: return clang::ObjCIvarDecl::Protected; case eAccessPackage: return clang::ObjCIvarDecl::Package; } return clang::ObjCIvarDecl::None; } // Tests #ifndef NDEBUG bool TypeSystemClang::Verify(lldb::opaque_compiler_type_t type) { return !type || llvm::isa(GetQualType(type).getTypePtr()); } #endif bool TypeSystemClang::IsAggregateType(lldb::opaque_compiler_type_t type) { clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::IncompleteArray: case clang::Type::VariableArray: case clang::Type::ConstantArray: case clang::Type::ExtVector: case clang::Type::Vector: case clang::Type::Record: case clang::Type::ObjCObject: case clang::Type::ObjCInterface: return true; default: break; } // The clang type does have a value return false; } bool TypeSystemClang::IsAnonymousType(lldb::opaque_compiler_type_t type) { clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: { if (const clang::RecordType *record_type = llvm::dyn_cast_or_null( qual_type.getTypePtrOrNull())) { if (const clang::RecordDecl *record_decl = record_type->getDecl()) { return record_decl->isAnonymousStructOrUnion(); } } break; } default: break; } // The clang type does have a value return false; } bool TypeSystemClang::IsArrayType(lldb::opaque_compiler_type_t type, CompilerType *element_type_ptr, uint64_t *size, bool *is_incomplete) { clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { default: break; case clang::Type::ConstantArray: if (element_type_ptr) element_type_ptr->SetCompilerType( this, llvm::cast(qual_type) ->getElementType() .getAsOpaquePtr()); if (size) *size = llvm::cast(qual_type) ->getSize() .getLimitedValue(ULLONG_MAX); if (is_incomplete) *is_incomplete = false; return true; case clang::Type::IncompleteArray: if (element_type_ptr) element_type_ptr->SetCompilerType( this, llvm::cast(qual_type) ->getElementType() .getAsOpaquePtr()); if (size) *size = 0; if (is_incomplete) *is_incomplete = true; return true; case clang::Type::VariableArray: if (element_type_ptr) element_type_ptr->SetCompilerType( this, llvm::cast(qual_type) ->getElementType() .getAsOpaquePtr()); if (size) *size = 0; if (is_incomplete) *is_incomplete = false; return true; case clang::Type::DependentSizedArray: if (element_type_ptr) element_type_ptr->SetCompilerType( this, llvm::cast(qual_type) ->getElementType() .getAsOpaquePtr()); if (size) *size = 0; if (is_incomplete) *is_incomplete = false; return true; } if (element_type_ptr) element_type_ptr->Clear(); if (size) *size = 0; if (is_incomplete) *is_incomplete = false; return false; } bool TypeSystemClang::IsVectorType(lldb::opaque_compiler_type_t type, CompilerType *element_type, uint64_t *size) { clang::QualType qual_type(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Vector: { const clang::VectorType *vector_type = qual_type->getAs(); if (vector_type) { if (size) *size = vector_type->getNumElements(); if (element_type) *element_type = GetType(vector_type->getElementType()); } return true; } break; case clang::Type::ExtVector: { const clang::ExtVectorType *ext_vector_type = qual_type->getAs(); if (ext_vector_type) { if (size) *size = ext_vector_type->getNumElements(); if (element_type) *element_type = CompilerType(this, ext_vector_type->getElementType().getAsOpaquePtr()); } return true; } default: break; } return false; } bool TypeSystemClang::IsRuntimeGeneratedType( lldb::opaque_compiler_type_t type) { clang::DeclContext *decl_ctx = GetDeclContextForType(GetQualType(type)); if (!decl_ctx) return false; if (!llvm::isa(decl_ctx)) return false; clang::ObjCInterfaceDecl *result_iface_decl = llvm::dyn_cast(decl_ctx); ClangASTMetadata *ast_metadata = GetMetadata(result_iface_decl); if (!ast_metadata) return false; return (ast_metadata->GetISAPtr() != 0); } bool TypeSystemClang::IsCharType(lldb::opaque_compiler_type_t type) { return GetQualType(type).getUnqualifiedType()->isCharType(); } bool TypeSystemClang::IsCompleteType(lldb::opaque_compiler_type_t type) { const bool allow_completion = false; return GetCompleteQualType(&getASTContext(), GetQualType(type), allow_completion); } bool TypeSystemClang::IsConst(lldb::opaque_compiler_type_t type) { return GetQualType(type).isConstQualified(); } bool TypeSystemClang::IsCStringType(lldb::opaque_compiler_type_t type, uint32_t &length) { CompilerType pointee_or_element_clang_type; length = 0; Flags type_flags(GetTypeInfo(type, &pointee_or_element_clang_type)); if (!pointee_or_element_clang_type.IsValid()) return false; if (type_flags.AnySet(eTypeIsArray | eTypeIsPointer)) { if (pointee_or_element_clang_type.IsCharType()) { if (type_flags.Test(eTypeIsArray)) { // We know the size of the array and it could be a C string since it is // an array of characters length = llvm::cast( GetCanonicalQualType(type).getTypePtr()) ->getSize() .getLimitedValue(); } return true; } } return false; } bool TypeSystemClang::IsFunctionType(lldb::opaque_compiler_type_t type, bool *is_variadic_ptr) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); if (qual_type->isFunctionType()) { if (is_variadic_ptr) { const clang::FunctionProtoType *function_proto_type = llvm::dyn_cast(qual_type.getTypePtr()); if (function_proto_type) *is_variadic_ptr = function_proto_type->isVariadic(); else *is_variadic_ptr = false; } return true; } const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { default: break; case clang::Type::LValueReference: case clang::Type::RValueReference: { const clang::ReferenceType *reference_type = llvm::cast(qual_type.getTypePtr()); if (reference_type) return IsFunctionType(reference_type->getPointeeType().getAsOpaquePtr(), nullptr); } break; } } return false; } // Used to detect "Homogeneous Floating-point Aggregates" uint32_t TypeSystemClang::IsHomogeneousAggregate(lldb::opaque_compiler_type_t type, CompilerType *base_type_ptr) { if (!type) return 0; clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { if (cxx_record_decl->getNumBases() || cxx_record_decl->isDynamicClass()) return 0; } const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); if (record_type) { const clang::RecordDecl *record_decl = record_type->getDecl(); if (record_decl) { // We are looking for a structure that contains only floating point // types clang::RecordDecl::field_iterator field_pos, field_end = record_decl->field_end(); uint32_t num_fields = 0; bool is_hva = false; bool is_hfa = false; clang::QualType base_qual_type; uint64_t base_bitwidth = 0; for (field_pos = record_decl->field_begin(); field_pos != field_end; ++field_pos) { clang::QualType field_qual_type = field_pos->getType(); uint64_t field_bitwidth = getASTContext().getTypeSize(qual_type); if (field_qual_type->isFloatingType()) { if (field_qual_type->isComplexType()) return 0; else { if (num_fields == 0) base_qual_type = field_qual_type; else { if (is_hva) return 0; is_hfa = true; if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr()) return 0; } } } else if (field_qual_type->isVectorType() || field_qual_type->isExtVectorType()) { if (num_fields == 0) { base_qual_type = field_qual_type; base_bitwidth = field_bitwidth; } else { if (is_hfa) return 0; is_hva = true; if (base_bitwidth != field_bitwidth) return 0; if (field_qual_type.getTypePtr() != base_qual_type.getTypePtr()) return 0; } } else return 0; ++num_fields; } if (base_type_ptr) *base_type_ptr = CompilerType(this, base_qual_type.getAsOpaquePtr()); return num_fields; } } } break; default: break; } return 0; } size_t TypeSystemClang::GetNumberOfFunctionArguments( lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetCanonicalQualType(type)); const clang::FunctionProtoType *func = llvm::dyn_cast(qual_type.getTypePtr()); if (func) return func->getNumParams(); } return 0; } CompilerType TypeSystemClang::GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type, const size_t index) { if (type) { clang::QualType qual_type(GetQualType(type)); const clang::FunctionProtoType *func = llvm::dyn_cast(qual_type.getTypePtr()); if (func) { if (index < func->getNumParams()) return CompilerType(this, func->getParamType(index).getAsOpaquePtr()); } } return CompilerType(); } bool TypeSystemClang::IsFunctionPointerType(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); if (qual_type->isFunctionPointerType()) return true; const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { default: break; case clang::Type::LValueReference: case clang::Type::RValueReference: { const clang::ReferenceType *reference_type = llvm::cast(qual_type.getTypePtr()); if (reference_type) return IsFunctionPointerType( reference_type->getPointeeType().getAsOpaquePtr()); } break; } } return false; } bool TypeSystemClang::IsBlockPointerType( lldb::opaque_compiler_type_t type, CompilerType *function_pointer_type_ptr) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); if (qual_type->isBlockPointerType()) { if (function_pointer_type_ptr) { const clang::BlockPointerType *block_pointer_type = qual_type->getAs(); QualType pointee_type = block_pointer_type->getPointeeType(); QualType function_pointer_type = m_ast_up->getPointerType(pointee_type); *function_pointer_type_ptr = CompilerType(this, function_pointer_type.getAsOpaquePtr()); } return true; } const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { default: break; case clang::Type::LValueReference: case clang::Type::RValueReference: { const clang::ReferenceType *reference_type = llvm::cast(qual_type.getTypePtr()); if (reference_type) return IsBlockPointerType( reference_type->getPointeeType().getAsOpaquePtr(), function_pointer_type_ptr); } break; } } return false; } bool TypeSystemClang::IsIntegerType(lldb::opaque_compiler_type_t type, bool &is_signed) { if (!type) return false; clang::QualType qual_type(GetCanonicalQualType(type)); const clang::BuiltinType *builtin_type = llvm::dyn_cast(qual_type->getCanonicalTypeInternal()); if (builtin_type) { if (builtin_type->isInteger()) { is_signed = builtin_type->isSignedInteger(); return true; } } return false; } bool TypeSystemClang::IsEnumerationType(lldb::opaque_compiler_type_t type, bool &is_signed) { if (type) { const clang::EnumType *enum_type = llvm::dyn_cast( GetCanonicalQualType(type)->getCanonicalTypeInternal()); if (enum_type) { IsIntegerType(enum_type->getDecl()->getIntegerType().getAsOpaquePtr(), is_signed); return true; } } return false; } bool TypeSystemClang::IsPointerType(lldb::opaque_compiler_type_t type, CompilerType *pointee_type) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { default: break; case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: return true; } return false; case clang::Type::ObjCObjectPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::BlockPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::Pointer: if (pointee_type) pointee_type->SetCompilerType(this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::MemberPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; default: break; } } if (pointee_type) pointee_type->Clear(); return false; } bool TypeSystemClang::IsPointerOrReferenceType( lldb::opaque_compiler_type_t type, CompilerType *pointee_type) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { default: break; case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: return true; } return false; case clang::Type::ObjCObjectPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType().getAsOpaquePtr()); return true; case clang::Type::BlockPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::Pointer: if (pointee_type) pointee_type->SetCompilerType(this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::MemberPointer: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; case clang::Type::LValueReference: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->desugar() .getAsOpaquePtr()); return true; case clang::Type::RValueReference: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->desugar() .getAsOpaquePtr()); return true; default: break; } } if (pointee_type) pointee_type->Clear(); return false; } bool TypeSystemClang::IsReferenceType(lldb::opaque_compiler_type_t type, CompilerType *pointee_type, bool *is_rvalue) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::LValueReference: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->desugar() .getAsOpaquePtr()); if (is_rvalue) *is_rvalue = false; return true; case clang::Type::RValueReference: if (pointee_type) pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->desugar() .getAsOpaquePtr()); if (is_rvalue) *is_rvalue = true; return true; default: break; } } if (pointee_type) pointee_type->Clear(); return false; } bool TypeSystemClang::IsFloatingPointType(lldb::opaque_compiler_type_t type, uint32_t &count, bool &is_complex) { if (type) { clang::QualType qual_type(GetCanonicalQualType(type)); if (const clang::BuiltinType *BT = llvm::dyn_cast( qual_type->getCanonicalTypeInternal())) { clang::BuiltinType::Kind kind = BT->getKind(); if (kind >= clang::BuiltinType::Float && kind <= clang::BuiltinType::LongDouble) { count = 1; is_complex = false; return true; } } else if (const clang::ComplexType *CT = llvm::dyn_cast( qual_type->getCanonicalTypeInternal())) { if (IsFloatingPointType(CT->getElementType().getAsOpaquePtr(), count, is_complex)) { count = 2; is_complex = true; return true; } } else if (const clang::VectorType *VT = llvm::dyn_cast( qual_type->getCanonicalTypeInternal())) { if (IsFloatingPointType(VT->getElementType().getAsOpaquePtr(), count, is_complex)) { count = VT->getNumElements(); is_complex = false; return true; } } } count = 0; is_complex = false; return false; } bool TypeSystemClang::IsDefined(lldb::opaque_compiler_type_t type) { if (!type) return false; clang::QualType qual_type(GetQualType(type)); const clang::TagType *tag_type = llvm::dyn_cast(qual_type.getTypePtr()); if (tag_type) { clang::TagDecl *tag_decl = tag_type->getDecl(); if (tag_decl) return tag_decl->isCompleteDefinition(); return false; } else { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) return class_interface_decl->getDefinition() != nullptr; return false; } } return true; } bool TypeSystemClang::IsObjCClassType(const CompilerType &type) { if (ClangUtil::IsClangType(type)) { clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); const clang::ObjCObjectPointerType *obj_pointer_type = llvm::dyn_cast(qual_type); if (obj_pointer_type) return obj_pointer_type->isObjCClassType(); } return false; } bool TypeSystemClang::IsObjCObjectOrInterfaceType(const CompilerType &type) { if (ClangUtil::IsClangType(type)) return ClangUtil::GetCanonicalQualType(type)->isObjCObjectOrInterfaceType(); return false; } bool TypeSystemClang::IsClassType(lldb::opaque_compiler_type_t type) { if (!type) return false; clang::QualType qual_type(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); return (type_class == clang::Type::Record); } bool TypeSystemClang::IsEnumType(lldb::opaque_compiler_type_t type) { if (!type) return false; clang::QualType qual_type(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); return (type_class == clang::Type::Enum); } bool TypeSystemClang::IsPolymorphicClass(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); if (record_decl) { const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) return cxx_record_decl->isPolymorphic(); } } break; default: break; } } return false; } bool TypeSystemClang::IsPossibleDynamicType(lldb::opaque_compiler_type_t type, CompilerType *dynamic_pointee_type, bool check_cplusplus, bool check_objc) { clang::QualType pointee_qual_type; if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); bool success = false; const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Builtin: if (check_objc && llvm::cast(qual_type)->getKind() == clang::BuiltinType::ObjCId) { if (dynamic_pointee_type) dynamic_pointee_type->SetCompilerType(this, type); return true; } break; case clang::Type::ObjCObjectPointer: if (check_objc) { if (const auto *objc_pointee_type = qual_type->getPointeeType().getTypePtrOrNull()) { if (const auto *objc_object_type = llvm::dyn_cast_or_null( objc_pointee_type)) { if (objc_object_type->isObjCClass()) return false; } } if (dynamic_pointee_type) dynamic_pointee_type->SetCompilerType( this, llvm::cast(qual_type) ->getPointeeType() .getAsOpaquePtr()); return true; } break; case clang::Type::Pointer: pointee_qual_type = llvm::cast(qual_type)->getPointeeType(); success = true; break; case clang::Type::LValueReference: case clang::Type::RValueReference: pointee_qual_type = llvm::cast(qual_type)->getPointeeType(); success = true; break; default: break; } if (success) { // Check to make sure what we are pointing too is a possible dynamic C++ // type We currently accept any "void *" (in case we have a class that // has been watered down to an opaque pointer) and virtual C++ classes. const clang::Type::TypeClass pointee_type_class = pointee_qual_type.getCanonicalType()->getTypeClass(); switch (pointee_type_class) { case clang::Type::Builtin: switch (llvm::cast(pointee_qual_type)->getKind()) { case clang::BuiltinType::UnknownAny: case clang::BuiltinType::Void: if (dynamic_pointee_type) dynamic_pointee_type->SetCompilerType( this, pointee_qual_type.getAsOpaquePtr()); return true; default: break; } break; case clang::Type::Record: if (check_cplusplus) { clang::CXXRecordDecl *cxx_record_decl = pointee_qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { bool is_complete = cxx_record_decl->isCompleteDefinition(); if (is_complete) success = cxx_record_decl->isDynamicClass(); else { ClangASTMetadata *metadata = GetMetadata(cxx_record_decl); if (metadata) success = metadata->GetIsDynamicCXXType(); else { is_complete = GetType(pointee_qual_type).GetCompleteType(); if (is_complete) success = cxx_record_decl->isDynamicClass(); else success = false; } } if (success) { if (dynamic_pointee_type) dynamic_pointee_type->SetCompilerType( this, pointee_qual_type.getAsOpaquePtr()); return true; } } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (check_objc) { if (dynamic_pointee_type) dynamic_pointee_type->SetCompilerType( this, pointee_qual_type.getAsOpaquePtr()); return true; } break; default: break; } } } if (dynamic_pointee_type) dynamic_pointee_type->Clear(); return false; } bool TypeSystemClang::IsScalarType(lldb::opaque_compiler_type_t type) { if (!type) return false; return (GetTypeInfo(type, nullptr) & eTypeIsScalar) != 0; } bool TypeSystemClang::IsTypedefType(lldb::opaque_compiler_type_t type) { if (!type) return false; return RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}) ->getTypeClass() == clang::Type::Typedef; } bool TypeSystemClang::IsVoidType(lldb::opaque_compiler_type_t type) { if (!type) return false; return GetCanonicalQualType(type)->isVoidType(); } bool TypeSystemClang::CanPassInRegisters(const CompilerType &type) { if (auto *record_decl = TypeSystemClang::GetAsRecordDecl(type)) { return record_decl->canPassInRegisters(); } return false; } bool TypeSystemClang::SupportsLanguage(lldb::LanguageType language) { return TypeSystemClangSupportsLanguage(language); } Optional TypeSystemClang::GetCXXClassName(const CompilerType &type) { if (!type) return llvm::None; clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); if (qual_type.isNull()) return llvm::None; clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (!cxx_record_decl) return llvm::None; return std::string(cxx_record_decl->getIdentifier()->getNameStart()); } bool TypeSystemClang::IsCXXClassType(const CompilerType &type) { if (!type) return false; clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); return !qual_type.isNull() && qual_type->getAsCXXRecordDecl() != nullptr; } bool TypeSystemClang::IsBeingDefined(lldb::opaque_compiler_type_t type) { if (!type) return false; clang::QualType qual_type(GetCanonicalQualType(type)); const clang::TagType *tag_type = llvm::dyn_cast(qual_type); if (tag_type) return tag_type->isBeingDefined(); return false; } bool TypeSystemClang::IsObjCObjectPointerType(const CompilerType &type, CompilerType *class_type_ptr) { if (!ClangUtil::IsClangType(type)) return false; clang::QualType qual_type(ClangUtil::GetCanonicalQualType(type)); if (!qual_type.isNull() && qual_type->isObjCObjectPointerType()) { if (class_type_ptr) { if (!qual_type->isObjCClassType() && !qual_type->isObjCIdType()) { const clang::ObjCObjectPointerType *obj_pointer_type = llvm::dyn_cast(qual_type); if (obj_pointer_type == nullptr) class_type_ptr->Clear(); else class_type_ptr->SetCompilerType( type.GetTypeSystem(), clang::QualType(obj_pointer_type->getInterfaceType(), 0) .getAsOpaquePtr()); } } return true; } if (class_type_ptr) class_type_ptr->Clear(); return false; } // Type Completion bool TypeSystemClang::GetCompleteType(lldb::opaque_compiler_type_t type) { if (!type) return false; const bool allow_completion = true; return GetCompleteQualType(&getASTContext(), GetQualType(type), allow_completion); } ConstString TypeSystemClang::GetTypeName(lldb::opaque_compiler_type_t type) { if (!type) return ConstString(); clang::QualType qual_type(GetQualType(type)); // For a typedef just return the qualified name. if (const auto *typedef_type = qual_type->getAs()) { const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl(); return ConstString(typedef_decl->getQualifiedNameAsString()); } clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy()); printing_policy.SuppressTagKeyword = true; return ConstString(qual_type.getAsString(printing_policy)); } ConstString TypeSystemClang::GetDisplayTypeName(lldb::opaque_compiler_type_t type) { if (!type) return ConstString(); clang::QualType qual_type(GetQualType(type)); clang::PrintingPolicy printing_policy(getASTContext().getPrintingPolicy()); printing_policy.SuppressTagKeyword = true; printing_policy.SuppressScope = false; printing_policy.SuppressUnwrittenScope = true; return ConstString(qual_type.getAsString(printing_policy)); } uint32_t TypeSystemClang::GetTypeInfo(lldb::opaque_compiler_type_t type, CompilerType *pointee_or_element_clang_type) { if (!type) return 0; if (pointee_or_element_clang_type) pointee_or_element_clang_type->Clear(); clang::QualType qual_type = RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Attributed: return GetTypeInfo( qual_type->getAs() ->getModifiedType().getAsOpaquePtr(), pointee_or_element_clang_type); case clang::Type::Builtin: { const clang::BuiltinType *builtin_type = llvm::dyn_cast( qual_type->getCanonicalTypeInternal()); uint32_t builtin_type_flags = eTypeIsBuiltIn | eTypeHasValue; switch (builtin_type->getKind()) { case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, getASTContext().ObjCBuiltinClassTy.getAsOpaquePtr()); builtin_type_flags |= eTypeIsPointer | eTypeIsObjC; break; case clang::BuiltinType::ObjCSel: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, getASTContext().CharTy.getAsOpaquePtr()); builtin_type_flags |= eTypeIsPointer | eTypeIsObjC; break; case clang::BuiltinType::Bool: case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::WChar_U: case clang::BuiltinType::Char16: case clang::BuiltinType::Char32: case clang::BuiltinType::UShort: case clang::BuiltinType::UInt: case clang::BuiltinType::ULong: case clang::BuiltinType::ULongLong: case clang::BuiltinType::UInt128: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: case clang::BuiltinType::WChar_S: case clang::BuiltinType::Short: case clang::BuiltinType::Int: case clang::BuiltinType::Long: case clang::BuiltinType::LongLong: case clang::BuiltinType::Int128: case clang::BuiltinType::Float: case clang::BuiltinType::Double: case clang::BuiltinType::LongDouble: builtin_type_flags |= eTypeIsScalar; if (builtin_type->isInteger()) { builtin_type_flags |= eTypeIsInteger; if (builtin_type->isSignedInteger()) builtin_type_flags |= eTypeIsSigned; } else if (builtin_type->isFloatingPoint()) builtin_type_flags |= eTypeIsFloat; break; default: break; } return builtin_type_flags; } case clang::Type::BlockPointer: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, qual_type->getPointeeType().getAsOpaquePtr()); return eTypeIsPointer | eTypeHasChildren | eTypeIsBlock; case clang::Type::Complex: { uint32_t complex_type_flags = eTypeIsBuiltIn | eTypeHasValue | eTypeIsComplex; const clang::ComplexType *complex_type = llvm::dyn_cast( qual_type->getCanonicalTypeInternal()); if (complex_type) { clang::QualType complex_element_type(complex_type->getElementType()); if (complex_element_type->isIntegerType()) complex_type_flags |= eTypeIsFloat; else if (complex_element_type->isFloatingType()) complex_type_flags |= eTypeIsInteger; } return complex_type_flags; } break; case clang::Type::ConstantArray: case clang::Type::DependentSizedArray: case clang::Type::IncompleteArray: case clang::Type::VariableArray: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, llvm::cast(qual_type.getTypePtr()) ->getElementType() .getAsOpaquePtr()); return eTypeHasChildren | eTypeIsArray; case clang::Type::DependentName: return 0; case clang::Type::DependentSizedExtVector: return eTypeHasChildren | eTypeIsVector; case clang::Type::DependentTemplateSpecialization: return eTypeIsTemplate; case clang::Type::Enum: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, llvm::cast(qual_type) ->getDecl() ->getIntegerType() .getAsOpaquePtr()); return eTypeIsEnumeration | eTypeHasValue; case clang::Type::FunctionProto: return eTypeIsFuncPrototype | eTypeHasValue; case clang::Type::FunctionNoProto: return eTypeIsFuncPrototype | eTypeHasValue; case clang::Type::InjectedClassName: return 0; case clang::Type::LValueReference: case clang::Type::RValueReference: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, llvm::cast(qual_type.getTypePtr()) ->getPointeeType() .getAsOpaquePtr()); return eTypeHasChildren | eTypeIsReference | eTypeHasValue; case clang::Type::MemberPointer: return eTypeIsPointer | eTypeIsMember | eTypeHasValue; case clang::Type::ObjCObjectPointer: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, qual_type->getPointeeType().getAsOpaquePtr()); return eTypeHasChildren | eTypeIsObjC | eTypeIsClass | eTypeIsPointer | eTypeHasValue; case clang::Type::ObjCObject: return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; case clang::Type::ObjCInterface: return eTypeHasChildren | eTypeIsObjC | eTypeIsClass; case clang::Type::Pointer: if (pointee_or_element_clang_type) pointee_or_element_clang_type->SetCompilerType( this, qual_type->getPointeeType().getAsOpaquePtr()); return eTypeHasChildren | eTypeIsPointer | eTypeHasValue; case clang::Type::Record: if (qual_type->getAsCXXRecordDecl()) return eTypeHasChildren | eTypeIsClass | eTypeIsCPlusPlus; else return eTypeHasChildren | eTypeIsStructUnion; break; case clang::Type::SubstTemplateTypeParm: return eTypeIsTemplate; case clang::Type::TemplateTypeParm: return eTypeIsTemplate; case clang::Type::TemplateSpecialization: return eTypeIsTemplate; case clang::Type::Typedef: return eTypeIsTypedef | GetType(llvm::cast(qual_type) ->getDecl() ->getUnderlyingType()) .GetTypeInfo(pointee_or_element_clang_type); case clang::Type::UnresolvedUsing: return 0; case clang::Type::ExtVector: case clang::Type::Vector: { uint32_t vector_type_flags = eTypeHasChildren | eTypeIsVector; const clang::VectorType *vector_type = llvm::dyn_cast( qual_type->getCanonicalTypeInternal()); if (vector_type) { if (vector_type->isIntegerType()) vector_type_flags |= eTypeIsFloat; else if (vector_type->isFloatingType()) vector_type_flags |= eTypeIsInteger; } return vector_type_flags; } default: return 0; } return 0; } lldb::LanguageType TypeSystemClang::GetMinimumLanguage(lldb::opaque_compiler_type_t type) { if (!type) return lldb::eLanguageTypeC; // If the type is a reference, then resolve it to what it refers to first: clang::QualType qual_type(GetCanonicalQualType(type).getNonReferenceType()); 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()) return lldb::eLanguageTypeC_plus_plus; if (pointee_type->isObjCObjectOrInterfaceType()) return lldb::eLanguageTypeObjC; if (pointee_type->isObjCClassType()) return lldb::eLanguageTypeObjC; if (pointee_type.getTypePtr() == getASTContext().ObjCBuiltinIdTy.getTypePtr()) return lldb::eLanguageTypeObjC; } else { if (qual_type->isObjCObjectOrInterfaceType()) return lldb::eLanguageTypeObjC; if (qual_type->getAsCXXRecordDecl()) return lldb::eLanguageTypeC_plus_plus; switch (qual_type->getTypeClass()) { default: break; case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { default: case clang::BuiltinType::Void: case clang::BuiltinType::Bool: case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::WChar_U: case clang::BuiltinType::Char16: case clang::BuiltinType::Char32: case clang::BuiltinType::UShort: case clang::BuiltinType::UInt: case clang::BuiltinType::ULong: case clang::BuiltinType::ULongLong: case clang::BuiltinType::UInt128: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: case clang::BuiltinType::WChar_S: case clang::BuiltinType::Short: case clang::BuiltinType::Int: case clang::BuiltinType::Long: case clang::BuiltinType::LongLong: case clang::BuiltinType::Int128: case clang::BuiltinType::Float: case clang::BuiltinType::Double: case clang::BuiltinType::LongDouble: break; case clang::BuiltinType::NullPtr: return eLanguageTypeC_plus_plus; case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: case clang::BuiltinType::ObjCSel: return eLanguageTypeObjC; case clang::BuiltinType::Dependent: case clang::BuiltinType::Overload: case clang::BuiltinType::BoundMember: case clang::BuiltinType::UnknownAny: break; } break; case clang::Type::Typedef: return GetType(llvm::cast(qual_type) ->getDecl() ->getUnderlyingType()) .GetMinimumLanguage(); } } return lldb::eLanguageTypeC; } lldb::TypeClass TypeSystemClang::GetTypeClass(lldb::opaque_compiler_type_t type) { if (!type) return lldb::eTypeClassInvalid; clang::QualType qual_type = RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); switch (qual_type->getTypeClass()) { case clang::Type::Atomic: case clang::Type::Auto: case clang::Type::Decltype: case clang::Type::Elaborated: case clang::Type::Paren: case clang::Type::TypeOf: case clang::Type::TypeOfExpr: llvm_unreachable("Handled in RemoveWrappingTypes!"); case clang::Type::UnaryTransform: break; case clang::Type::FunctionNoProto: return lldb::eTypeClassFunction; case clang::Type::FunctionProto: return lldb::eTypeClassFunction; case clang::Type::IncompleteArray: return lldb::eTypeClassArray; case clang::Type::VariableArray: return lldb::eTypeClassArray; case clang::Type::ConstantArray: return lldb::eTypeClassArray; case clang::Type::DependentSizedArray: return lldb::eTypeClassArray; case clang::Type::DependentSizedExtVector: return lldb::eTypeClassVector; case clang::Type::DependentVector: return lldb::eTypeClassVector; case clang::Type::ExtVector: return lldb::eTypeClassVector; case clang::Type::Vector: return lldb::eTypeClassVector; case clang::Type::Builtin: // Ext-Int is just an integer type. case clang::Type::ExtInt: case clang::Type::DependentExtInt: return lldb::eTypeClassBuiltin; case clang::Type::ObjCObjectPointer: return lldb::eTypeClassObjCObjectPointer; case clang::Type::BlockPointer: return lldb::eTypeClassBlockPointer; case clang::Type::Pointer: return lldb::eTypeClassPointer; case clang::Type::LValueReference: return lldb::eTypeClassReference; case clang::Type::RValueReference: return lldb::eTypeClassReference; case clang::Type::MemberPointer: return lldb::eTypeClassMemberPointer; case clang::Type::Complex: if (qual_type->isComplexType()) return lldb::eTypeClassComplexFloat; else return lldb::eTypeClassComplexInteger; case clang::Type::ObjCObject: return lldb::eTypeClassObjCObject; case clang::Type::ObjCInterface: return lldb::eTypeClassObjCInterface; case clang::Type::Record: { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); if (record_decl->isUnion()) return lldb::eTypeClassUnion; else if (record_decl->isStruct()) return lldb::eTypeClassStruct; else return lldb::eTypeClassClass; } break; case clang::Type::Enum: return lldb::eTypeClassEnumeration; case clang::Type::Typedef: return lldb::eTypeClassTypedef; case clang::Type::UnresolvedUsing: break; case clang::Type::Attributed: break; case clang::Type::TemplateTypeParm: break; case clang::Type::SubstTemplateTypeParm: break; case clang::Type::SubstTemplateTypeParmPack: break; case clang::Type::InjectedClassName: break; case clang::Type::DependentName: break; case clang::Type::DependentTemplateSpecialization: break; case clang::Type::PackExpansion: break; case clang::Type::TemplateSpecialization: break; case clang::Type::DeducedTemplateSpecialization: break; case clang::Type::Pipe: break; // pointer type decayed from an array or function type. case clang::Type::Decayed: break; case clang::Type::Adjusted: break; case clang::Type::ObjCTypeParam: break; case clang::Type::DependentAddressSpace: break; case clang::Type::MacroQualified: break; // Matrix types that we're not sure how to display at the moment. case clang::Type::ConstantMatrix: case clang::Type::DependentSizedMatrix: break; } // We don't know hot to display this type... return lldb::eTypeClassOther; } unsigned TypeSystemClang::GetTypeQualifiers(lldb::opaque_compiler_type_t type) { if (type) return GetQualType(type).getQualifiers().getCVRQualifiers(); return 0; } // Creating related types CompilerType TypeSystemClang::GetArrayElementType(lldb::opaque_compiler_type_t type, uint64_t *stride) { if (type) { clang::QualType qual_type(GetQualType(type)); const clang::Type *array_eletype = qual_type.getTypePtr()->getArrayElementTypeNoTypeQual(); if (!array_eletype) return CompilerType(); CompilerType element_type = GetType(clang::QualType(array_eletype, 0)); // TODO: the real stride will be >= this value.. find the real one! if (stride) if (Optional size = element_type.GetByteSize(nullptr)) *stride = *size; return element_type; } return CompilerType(); } CompilerType TypeSystemClang::GetArrayType(lldb::opaque_compiler_type_t type, uint64_t size) { if (type) { clang::QualType qual_type(GetCanonicalQualType(type)); clang::ASTContext &ast_ctx = getASTContext(); if (size != 0) return GetType(ast_ctx.getConstantArrayType( qual_type, llvm::APInt(64, size), nullptr, clang::ArrayType::ArraySizeModifier::Normal, 0)); else return GetType(ast_ctx.getIncompleteArrayType( qual_type, clang::ArrayType::ArraySizeModifier::Normal, 0)); } return CompilerType(); } CompilerType TypeSystemClang::GetCanonicalType(lldb::opaque_compiler_type_t type) { if (type) return GetType(GetCanonicalQualType(type)); return CompilerType(); } static clang::QualType GetFullyUnqualifiedType_Impl(clang::ASTContext *ast, clang::QualType qual_type) { if (qual_type->isPointerType()) qual_type = ast->getPointerType( GetFullyUnqualifiedType_Impl(ast, qual_type->getPointeeType())); else qual_type = qual_type.getUnqualifiedType(); qual_type.removeLocalConst(); qual_type.removeLocalRestrict(); qual_type.removeLocalVolatile(); return qual_type; } CompilerType TypeSystemClang::GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) { if (type) return GetType( GetFullyUnqualifiedType_Impl(&getASTContext(), GetQualType(type))); return CompilerType(); } int TypeSystemClang::GetFunctionArgumentCount( lldb::opaque_compiler_type_t type) { if (type) { const clang::FunctionProtoType *func = llvm::dyn_cast(GetCanonicalQualType(type)); if (func) return func->getNumParams(); } return -1; } CompilerType TypeSystemClang::GetFunctionArgumentTypeAtIndex( lldb::opaque_compiler_type_t type, size_t idx) { if (type) { const clang::FunctionProtoType *func = llvm::dyn_cast(GetQualType(type)); if (func) { const uint32_t num_args = func->getNumParams(); if (idx < num_args) return GetType(func->getParamType(idx)); } } return CompilerType(); } CompilerType TypeSystemClang::GetFunctionReturnType(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetQualType(type)); const clang::FunctionProtoType *func = llvm::dyn_cast(qual_type.getTypePtr()); if (func) return GetType(func->getReturnType()); } return CompilerType(); } size_t TypeSystemClang::GetNumMemberFunctions(lldb::opaque_compiler_type_t type) { size_t num_functions = 0; if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); switch (qual_type->getTypeClass()) { case clang::Type::Record: if (GetCompleteQualType(&getASTContext(), qual_type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) num_functions = std::distance(cxx_record_decl->method_begin(), cxx_record_decl->method_end()); } break; case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = qual_type->getAs(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && GetCompleteType(static_cast( const_cast(objc_interface_type)))) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getDecl(); if (class_interface_decl) { num_functions = std::distance(class_interface_decl->meth_begin(), class_interface_decl->meth_end()); } } break; } case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) num_functions = std::distance(class_interface_decl->meth_begin(), class_interface_decl->meth_end()); } } break; default: break; } } return num_functions; } TypeMemberFunctionImpl TypeSystemClang::GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type, size_t idx) { std::string name; MemberFunctionKind kind(MemberFunctionKind::eMemberFunctionKindUnknown); CompilerType clang_type; CompilerDecl clang_decl; if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); switch (qual_type->getTypeClass()) { case clang::Type::Record: if (GetCompleteQualType(&getASTContext(), qual_type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { auto method_iter = cxx_record_decl->method_begin(); auto method_end = cxx_record_decl->method_end(); if (idx < static_cast(std::distance(method_iter, method_end))) { std::advance(method_iter, idx); clang::CXXMethodDecl *cxx_method_decl = method_iter->getCanonicalDecl(); if (cxx_method_decl) { name = cxx_method_decl->getDeclName().getAsString(); if (cxx_method_decl->isStatic()) kind = lldb::eMemberFunctionKindStaticMethod; else if (llvm::isa(cxx_method_decl)) kind = lldb::eMemberFunctionKindConstructor; else if (llvm::isa(cxx_method_decl)) kind = lldb::eMemberFunctionKindDestructor; else kind = lldb::eMemberFunctionKindInstanceMethod; clang_type = GetType(cxx_method_decl->getType()); clang_decl = GetCompilerDecl(cxx_method_decl); } } } } break; case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = qual_type->getAs(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && GetCompleteType(static_cast( const_cast(objc_interface_type)))) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getDecl(); if (class_interface_decl) { auto method_iter = class_interface_decl->meth_begin(); auto method_end = class_interface_decl->meth_end(); if (idx < static_cast(std::distance(method_iter, method_end))) { std::advance(method_iter, idx); clang::ObjCMethodDecl *objc_method_decl = method_iter->getCanonicalDecl(); if (objc_method_decl) { clang_decl = GetCompilerDecl(objc_method_decl); name = objc_method_decl->getSelector().getAsString(); if (objc_method_decl->isClassMethod()) kind = lldb::eMemberFunctionKindStaticMethod; else kind = lldb::eMemberFunctionKindInstanceMethod; } } } } break; } case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { auto method_iter = class_interface_decl->meth_begin(); auto method_end = class_interface_decl->meth_end(); if (idx < static_cast(std::distance(method_iter, method_end))) { std::advance(method_iter, idx); clang::ObjCMethodDecl *objc_method_decl = method_iter->getCanonicalDecl(); if (objc_method_decl) { clang_decl = GetCompilerDecl(objc_method_decl); name = objc_method_decl->getSelector().getAsString(); if (objc_method_decl->isClassMethod()) kind = lldb::eMemberFunctionKindStaticMethod; else kind = lldb::eMemberFunctionKindInstanceMethod; } } } } } break; default: break; } } if (kind == eMemberFunctionKindUnknown) return TypeMemberFunctionImpl(); else return TypeMemberFunctionImpl(clang_type, clang_decl, name, kind); } CompilerType TypeSystemClang::GetNonReferenceType(lldb::opaque_compiler_type_t type) { if (type) return GetType(GetQualType(type).getNonReferenceType()); return CompilerType(); } CompilerType TypeSystemClang::CreateTypedefType( const CompilerType &type, const char *typedef_name, const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) { if (type && typedef_name && typedef_name[0]) { TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (!ast) return CompilerType(); clang::ASTContext &clang_ast = ast->getASTContext(); clang::QualType qual_type(ClangUtil::GetQualType(type)); clang::DeclContext *decl_ctx = TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx); if (!decl_ctx) decl_ctx = ast->getASTContext().getTranslationUnitDecl(); clang::TypedefDecl *decl = clang::TypedefDecl::CreateDeserialized(clang_ast, 0); decl->setDeclContext(decl_ctx); decl->setDeclName(&clang_ast.Idents.get(typedef_name)); decl->setTypeSourceInfo(clang_ast.getTrivialTypeSourceInfo(qual_type)); SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule()); decl->setAccess(clang::AS_public); // TODO respect proper access specifier decl_ctx->addDecl(decl); // Get a uniqued clang::QualType for the typedef decl type return ast->GetType(clang_ast.getTypedefType(decl)); } return CompilerType(); } CompilerType TypeSystemClang::GetPointeeType(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetQualType(type)); return GetType(qual_type.getTypePtr()->getPointeeType()); } return CompilerType(); } CompilerType TypeSystemClang::GetPointerType(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetQualType(type)); switch (qual_type.getDesugaredType(getASTContext())->getTypeClass()) { case clang::Type::ObjCObject: case clang::Type::ObjCInterface: return GetType(getASTContext().getObjCObjectPointerType(qual_type)); default: return GetType(getASTContext().getPointerType(qual_type)); } } return CompilerType(); } CompilerType TypeSystemClang::GetLValueReferenceType(lldb::opaque_compiler_type_t type) { if (type) return GetType(getASTContext().getLValueReferenceType(GetQualType(type))); else return CompilerType(); } CompilerType TypeSystemClang::GetRValueReferenceType(lldb::opaque_compiler_type_t type) { if (type) return GetType(getASTContext().getRValueReferenceType(GetQualType(type))); else return CompilerType(); } CompilerType TypeSystemClang::GetAtomicType(lldb::opaque_compiler_type_t type) { if (!type) return CompilerType(); return GetType(getASTContext().getAtomicType(GetQualType(type))); } CompilerType TypeSystemClang::AddConstModifier(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType result(GetQualType(type)); result.addConst(); return GetType(result); } return CompilerType(); } CompilerType TypeSystemClang::AddVolatileModifier(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType result(GetQualType(type)); result.addVolatile(); return GetType(result); } return CompilerType(); } CompilerType TypeSystemClang::AddRestrictModifier(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType result(GetQualType(type)); result.addRestrict(); return GetType(result); } return CompilerType(); } CompilerType TypeSystemClang::CreateTypedef( lldb::opaque_compiler_type_t type, const char *typedef_name, const CompilerDeclContext &compiler_decl_ctx, uint32_t payload) { if (type) { clang::ASTContext &clang_ast = getASTContext(); clang::QualType qual_type(GetQualType(type)); clang::DeclContext *decl_ctx = TypeSystemClang::DeclContextGetAsDeclContext(compiler_decl_ctx); if (!decl_ctx) decl_ctx = getASTContext().getTranslationUnitDecl(); clang::TypedefDecl *decl = clang::TypedefDecl::Create( clang_ast, decl_ctx, clang::SourceLocation(), clang::SourceLocation(), &clang_ast.Idents.get(typedef_name), clang_ast.getTrivialTypeSourceInfo(qual_type)); SetOwningModule(decl, TypePayloadClang(payload).GetOwningModule()); clang::TagDecl *tdecl = nullptr; if (!qual_type.isNull()) { if (const clang::RecordType *rt = qual_type->getAs()) tdecl = rt->getDecl(); if (const clang::EnumType *et = qual_type->getAs()) tdecl = et->getDecl(); } // Check whether this declaration is an anonymous struct, union, or enum, // hidden behind a typedef. If so, we try to check whether we have a // typedef tag to attach to the original record declaration if (tdecl && !tdecl->getIdentifier() && !tdecl->getTypedefNameForAnonDecl()) tdecl->setTypedefNameForAnonDecl(decl); decl->setAccess(clang::AS_public); // TODO respect proper access specifier // Get a uniqued clang::QualType for the typedef decl type return GetType(clang_ast.getTypedefType(decl)); } return CompilerType(); } CompilerType TypeSystemClang::GetTypedefedType(lldb::opaque_compiler_type_t type) { if (type) { const clang::TypedefType *typedef_type = llvm::dyn_cast( RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef})); if (typedef_type) return GetType(typedef_type->getDecl()->getUnderlyingType()); } return CompilerType(); } // Create related types using the current type's AST CompilerType TypeSystemClang::GetBasicTypeFromAST(lldb::BasicType basic_type) { return TypeSystemClang::GetBasicType(basic_type); } // Exploring the type const llvm::fltSemantics & TypeSystemClang::GetFloatTypeSemantics(size_t byte_size) { clang::ASTContext &ast = getASTContext(); const size_t bit_size = byte_size * 8; if (bit_size == ast.getTypeSize(ast.FloatTy)) return ast.getFloatTypeSemantics(ast.FloatTy); else if (bit_size == ast.getTypeSize(ast.DoubleTy)) return ast.getFloatTypeSemantics(ast.DoubleTy); else if (bit_size == ast.getTypeSize(ast.LongDoubleTy)) return ast.getFloatTypeSemantics(ast.LongDoubleTy); else if (bit_size == ast.getTypeSize(ast.HalfTy)) return ast.getFloatTypeSemantics(ast.HalfTy); return llvm::APFloatBase::Bogus(); } Optional TypeSystemClang::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(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) return getASTContext().getTypeSize(qual_type); else return None; break; case clang::Type::ObjCInterface: case clang::Type::ObjCObject: { ExecutionContext exe_ctx(exe_scope); Process *process = exe_ctx.GetProcessPtr(); if (process) { ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); if (objc_runtime) { uint64_t bit_size = 0; if (objc_runtime->GetTypeBitSize(GetType(qual_type), bit_size)) return bit_size; } } else { static bool g_printed = false; if (!g_printed) { StreamString s; DumpTypeDescription(type, &s); llvm::outs() << "warning: trying to determine the size of type "; llvm::outs() << s.GetString() << "\n"; llvm::outs() << "without a valid ExecutionContext. this is not " "reliable. please file a bug against LLDB.\n"; llvm::outs() << "backtrace:\n"; llvm::sys::PrintStackTrace(llvm::outs()); llvm::outs() << "\n"; g_printed = true; } } } LLVM_FALLTHROUGH; default: const uint32_t bit_size = getASTContext().getTypeSize(qual_type); if (bit_size == 0) { if (qual_type->isIncompleteArrayType()) return getASTContext().getTypeSize( qual_type->getArrayElementTypeNoTypeQual() ->getCanonicalTypeUnqualified()); } if (qual_type->isObjCObjectOrInterfaceType()) return bit_size + getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy); // 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 None; } llvm::Optional TypeSystemClang::GetTypeBitAlign(lldb::opaque_compiler_type_t type, ExecutionContextScope *exe_scope) { if (GetCompleteType(type)) return getASTContext().getTypeAlign(GetQualType(type)); return {}; } lldb::Encoding TypeSystemClang::GetEncoding(lldb::opaque_compiler_type_t type, uint64_t &count) { if (!type) return lldb::eEncodingInvalid; count = 1; clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); switch (qual_type->getTypeClass()) { case clang::Type::Atomic: case clang::Type::Auto: case clang::Type::Decltype: case clang::Type::Elaborated: case clang::Type::Paren: case clang::Type::Typedef: case clang::Type::TypeOf: case clang::Type::TypeOfExpr: llvm_unreachable("Handled in RemoveWrappingTypes!"); case clang::Type::UnaryTransform: break; case clang::Type::FunctionNoProto: case clang::Type::FunctionProto: break; case clang::Type::IncompleteArray: case clang::Type::VariableArray: break; case clang::Type::ConstantArray: break; case clang::Type::DependentVector: case clang::Type::ExtVector: case clang::Type::Vector: // TODO: Set this to more than one??? break; case clang::Type::ExtInt: case clang::Type::DependentExtInt: return qual_type->isUnsignedIntegerType() ? lldb::eEncodingUint : lldb::eEncodingSint; case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { case clang::BuiltinType::Void: break; case clang::BuiltinType::Bool: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: case clang::BuiltinType::WChar_S: case clang::BuiltinType::Short: case clang::BuiltinType::Int: case clang::BuiltinType::Long: case clang::BuiltinType::LongLong: case clang::BuiltinType::Int128: return lldb::eEncodingSint; case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::WChar_U: case clang::BuiltinType::Char8: case clang::BuiltinType::Char16: case clang::BuiltinType::Char32: case clang::BuiltinType::UShort: case clang::BuiltinType::UInt: case clang::BuiltinType::ULong: case clang::BuiltinType::ULongLong: case clang::BuiltinType::UInt128: return lldb::eEncodingUint; // Fixed point types. Note that they are currently ignored. case clang::BuiltinType::ShortAccum: case clang::BuiltinType::Accum: case clang::BuiltinType::LongAccum: case clang::BuiltinType::UShortAccum: case clang::BuiltinType::UAccum: case clang::BuiltinType::ULongAccum: case clang::BuiltinType::ShortFract: case clang::BuiltinType::Fract: case clang::BuiltinType::LongFract: case clang::BuiltinType::UShortFract: case clang::BuiltinType::UFract: case clang::BuiltinType::ULongFract: case clang::BuiltinType::SatShortAccum: case clang::BuiltinType::SatAccum: case clang::BuiltinType::SatLongAccum: case clang::BuiltinType::SatUShortAccum: case clang::BuiltinType::SatUAccum: case clang::BuiltinType::SatULongAccum: case clang::BuiltinType::SatShortFract: case clang::BuiltinType::SatFract: case clang::BuiltinType::SatLongFract: case clang::BuiltinType::SatUShortFract: case clang::BuiltinType::SatUFract: case clang::BuiltinType::SatULongFract: break; case clang::BuiltinType::Half: case clang::BuiltinType::Float: case clang::BuiltinType::Float16: case clang::BuiltinType::Float128: case clang::BuiltinType::Double: case clang::BuiltinType::LongDouble: case clang::BuiltinType::BFloat16: return lldb::eEncodingIEEE754; case clang::BuiltinType::ObjCClass: case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCSel: return lldb::eEncodingUint; case clang::BuiltinType::NullPtr: return lldb::eEncodingUint; case clang::BuiltinType::Kind::ARCUnbridgedCast: case clang::BuiltinType::Kind::BoundMember: case clang::BuiltinType::Kind::BuiltinFn: case clang::BuiltinType::Kind::Dependent: case clang::BuiltinType::Kind::OCLClkEvent: case clang::BuiltinType::Kind::OCLEvent: case clang::BuiltinType::Kind::OCLImage1dRO: case clang::BuiltinType::Kind::OCLImage1dWO: case clang::BuiltinType::Kind::OCLImage1dRW: case clang::BuiltinType::Kind::OCLImage1dArrayRO: case clang::BuiltinType::Kind::OCLImage1dArrayWO: case clang::BuiltinType::Kind::OCLImage1dArrayRW: case clang::BuiltinType::Kind::OCLImage1dBufferRO: case clang::BuiltinType::Kind::OCLImage1dBufferWO: case clang::BuiltinType::Kind::OCLImage1dBufferRW: case clang::BuiltinType::Kind::OCLImage2dRO: case clang::BuiltinType::Kind::OCLImage2dWO: case clang::BuiltinType::Kind::OCLImage2dRW: case clang::BuiltinType::Kind::OCLImage2dArrayRO: case clang::BuiltinType::Kind::OCLImage2dArrayWO: case clang::BuiltinType::Kind::OCLImage2dArrayRW: case clang::BuiltinType::Kind::OCLImage2dArrayDepthRO: case clang::BuiltinType::Kind::OCLImage2dArrayDepthWO: case clang::BuiltinType::Kind::OCLImage2dArrayDepthRW: case clang::BuiltinType::Kind::OCLImage2dArrayMSAARO: case clang::BuiltinType::Kind::OCLImage2dArrayMSAAWO: case clang::BuiltinType::Kind::OCLImage2dArrayMSAARW: case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRO: case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthWO: case clang::BuiltinType::Kind::OCLImage2dArrayMSAADepthRW: case clang::BuiltinType::Kind::OCLImage2dDepthRO: case clang::BuiltinType::Kind::OCLImage2dDepthWO: case clang::BuiltinType::Kind::OCLImage2dDepthRW: case clang::BuiltinType::Kind::OCLImage2dMSAARO: case clang::BuiltinType::Kind::OCLImage2dMSAAWO: case clang::BuiltinType::Kind::OCLImage2dMSAARW: case clang::BuiltinType::Kind::OCLImage2dMSAADepthRO: case clang::BuiltinType::Kind::OCLImage2dMSAADepthWO: case clang::BuiltinType::Kind::OCLImage2dMSAADepthRW: case clang::BuiltinType::Kind::OCLImage3dRO: case clang::BuiltinType::Kind::OCLImage3dWO: case clang::BuiltinType::Kind::OCLImage3dRW: case clang::BuiltinType::Kind::OCLQueue: case clang::BuiltinType::Kind::OCLReserveID: case clang::BuiltinType::Kind::OCLSampler: case clang::BuiltinType::Kind::OMPArraySection: case clang::BuiltinType::Kind::OMPArrayShaping: case clang::BuiltinType::Kind::OMPIterator: case clang::BuiltinType::Kind::Overload: case clang::BuiltinType::Kind::PseudoObject: case clang::BuiltinType::Kind::UnknownAny: break; case clang::BuiltinType::OCLIntelSubgroupAVCMcePayload: case clang::BuiltinType::OCLIntelSubgroupAVCImePayload: case clang::BuiltinType::OCLIntelSubgroupAVCRefPayload: case clang::BuiltinType::OCLIntelSubgroupAVCSicPayload: case clang::BuiltinType::OCLIntelSubgroupAVCMceResult: case clang::BuiltinType::OCLIntelSubgroupAVCImeResult: case clang::BuiltinType::OCLIntelSubgroupAVCRefResult: case clang::BuiltinType::OCLIntelSubgroupAVCSicResult: case clang::BuiltinType::OCLIntelSubgroupAVCImeResultSingleRefStreamout: case clang::BuiltinType::OCLIntelSubgroupAVCImeResultDualRefStreamout: case clang::BuiltinType::OCLIntelSubgroupAVCImeSingleRefStreamin: case clang::BuiltinType::OCLIntelSubgroupAVCImeDualRefStreamin: break; case clang::BuiltinType::SveBool: case clang::BuiltinType::SveInt8: case clang::BuiltinType::SveInt8x2: case clang::BuiltinType::SveInt8x3: case clang::BuiltinType::SveInt8x4: case clang::BuiltinType::SveInt16: case clang::BuiltinType::SveInt16x2: case clang::BuiltinType::SveInt16x3: case clang::BuiltinType::SveInt16x4: case clang::BuiltinType::SveInt32: case clang::BuiltinType::SveInt32x2: case clang::BuiltinType::SveInt32x3: case clang::BuiltinType::SveInt32x4: case clang::BuiltinType::SveInt64: case clang::BuiltinType::SveInt64x2: case clang::BuiltinType::SveInt64x3: case clang::BuiltinType::SveInt64x4: case clang::BuiltinType::SveUint8: case clang::BuiltinType::SveUint8x2: case clang::BuiltinType::SveUint8x3: case clang::BuiltinType::SveUint8x4: case clang::BuiltinType::SveUint16: case clang::BuiltinType::SveUint16x2: case clang::BuiltinType::SveUint16x3: case clang::BuiltinType::SveUint16x4: case clang::BuiltinType::SveUint32: case clang::BuiltinType::SveUint32x2: case clang::BuiltinType::SveUint32x3: case clang::BuiltinType::SveUint32x4: case clang::BuiltinType::SveUint64: case clang::BuiltinType::SveUint64x2: case clang::BuiltinType::SveUint64x3: case clang::BuiltinType::SveUint64x4: case clang::BuiltinType::SveFloat16: case clang::BuiltinType::SveBFloat16: case clang::BuiltinType::SveBFloat16x2: case clang::BuiltinType::SveBFloat16x3: case clang::BuiltinType::SveBFloat16x4: case clang::BuiltinType::SveFloat16x2: case clang::BuiltinType::SveFloat16x3: case clang::BuiltinType::SveFloat16x4: case clang::BuiltinType::SveFloat32: case clang::BuiltinType::SveFloat32x2: case clang::BuiltinType::SveFloat32x3: case clang::BuiltinType::SveFloat32x4: case clang::BuiltinType::SveFloat64: case clang::BuiltinType::SveFloat64x2: case clang::BuiltinType::SveFloat64x3: case clang::BuiltinType::SveFloat64x4: break; case clang::BuiltinType::IncompleteMatrixIdx: break; } break; // All pointer types are represented as unsigned integer encodings. We may // nee to add a eEncodingPointer if we ever need to know the difference case clang::Type::ObjCObjectPointer: case clang::Type::BlockPointer: case clang::Type::Pointer: case clang::Type::LValueReference: case clang::Type::RValueReference: case clang::Type::MemberPointer: return lldb::eEncodingUint; case clang::Type::Complex: { lldb::Encoding encoding = lldb::eEncodingIEEE754; if (qual_type->isComplexType()) encoding = lldb::eEncodingIEEE754; else { const clang::ComplexType *complex_type = qual_type->getAsComplexIntegerType(); if (complex_type) encoding = GetType(complex_type->getElementType()).GetEncoding(count); else encoding = lldb::eEncodingSint; } count = 2; return encoding; } case clang::Type::ObjCInterface: break; case clang::Type::Record: break; case clang::Type::Enum: return lldb::eEncodingSint; case clang::Type::DependentSizedArray: case clang::Type::DependentSizedExtVector: case clang::Type::UnresolvedUsing: case clang::Type::Attributed: case clang::Type::TemplateTypeParm: case clang::Type::SubstTemplateTypeParm: case clang::Type::SubstTemplateTypeParmPack: case clang::Type::InjectedClassName: case clang::Type::DependentName: case clang::Type::DependentTemplateSpecialization: case clang::Type::PackExpansion: case clang::Type::ObjCObject: case clang::Type::TemplateSpecialization: case clang::Type::DeducedTemplateSpecialization: case clang::Type::Adjusted: case clang::Type::Pipe: break; // pointer type decayed from an array or function type. case clang::Type::Decayed: break; case clang::Type::ObjCTypeParam: break; case clang::Type::DependentAddressSpace: break; case clang::Type::MacroQualified: break; case clang::Type::ConstantMatrix: case clang::Type::DependentSizedMatrix: break; } count = 0; return lldb::eEncodingInvalid; } lldb::Format TypeSystemClang::GetFormat(lldb::opaque_compiler_type_t type) { if (!type) return lldb::eFormatDefault; clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); switch (qual_type->getTypeClass()) { case clang::Type::Atomic: case clang::Type::Auto: case clang::Type::Decltype: case clang::Type::Elaborated: case clang::Type::Paren: case clang::Type::Typedef: case clang::Type::TypeOf: case clang::Type::TypeOfExpr: llvm_unreachable("Handled in RemoveWrappingTypes!"); case clang::Type::UnaryTransform: break; case clang::Type::FunctionNoProto: case clang::Type::FunctionProto: break; case clang::Type::IncompleteArray: case clang::Type::VariableArray: break; case clang::Type::ConstantArray: return lldb::eFormatVoid; // no value case clang::Type::DependentVector: case clang::Type::ExtVector: case clang::Type::Vector: break; case clang::Type::ExtInt: case clang::Type::DependentExtInt: return qual_type->isUnsignedIntegerType() ? lldb::eFormatUnsigned : lldb::eFormatDecimal; case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { case clang::BuiltinType::UnknownAny: case clang::BuiltinType::Void: case clang::BuiltinType::BoundMember: break; case clang::BuiltinType::Bool: return lldb::eFormatBoolean; case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: case clang::BuiltinType::WChar_S: case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::WChar_U: return lldb::eFormatChar; case clang::BuiltinType::Char16: return lldb::eFormatUnicode16; case clang::BuiltinType::Char32: return lldb::eFormatUnicode32; case clang::BuiltinType::UShort: return lldb::eFormatUnsigned; case clang::BuiltinType::Short: return lldb::eFormatDecimal; case clang::BuiltinType::UInt: return lldb::eFormatUnsigned; case clang::BuiltinType::Int: return lldb::eFormatDecimal; case clang::BuiltinType::ULong: return lldb::eFormatUnsigned; case clang::BuiltinType::Long: return lldb::eFormatDecimal; case clang::BuiltinType::ULongLong: return lldb::eFormatUnsigned; case clang::BuiltinType::LongLong: return lldb::eFormatDecimal; case clang::BuiltinType::UInt128: return lldb::eFormatUnsigned; case clang::BuiltinType::Int128: return lldb::eFormatDecimal; case clang::BuiltinType::Half: case clang::BuiltinType::Float: case clang::BuiltinType::Double: case clang::BuiltinType::LongDouble: return lldb::eFormatFloat; default: return lldb::eFormatHex; } break; case clang::Type::ObjCObjectPointer: return lldb::eFormatHex; case clang::Type::BlockPointer: return lldb::eFormatHex; case clang::Type::Pointer: return lldb::eFormatHex; case clang::Type::LValueReference: case clang::Type::RValueReference: return lldb::eFormatHex; case clang::Type::MemberPointer: break; case clang::Type::Complex: { if (qual_type->isComplexType()) return lldb::eFormatComplex; else return lldb::eFormatComplexInteger; } case clang::Type::ObjCInterface: break; case clang::Type::Record: break; case clang::Type::Enum: return lldb::eFormatEnum; case clang::Type::DependentSizedArray: case clang::Type::DependentSizedExtVector: case clang::Type::UnresolvedUsing: case clang::Type::Attributed: case clang::Type::TemplateTypeParm: case clang::Type::SubstTemplateTypeParm: case clang::Type::SubstTemplateTypeParmPack: case clang::Type::InjectedClassName: case clang::Type::DependentName: case clang::Type::DependentTemplateSpecialization: case clang::Type::PackExpansion: case clang::Type::ObjCObject: case clang::Type::TemplateSpecialization: case clang::Type::DeducedTemplateSpecialization: case clang::Type::Adjusted: case clang::Type::Pipe: break; // pointer type decayed from an array or function type. case clang::Type::Decayed: break; case clang::Type::ObjCTypeParam: break; case clang::Type::DependentAddressSpace: break; case clang::Type::MacroQualified: break; // Matrix types we're not sure how to display yet. case clang::Type::ConstantMatrix: case clang::Type::DependentSizedMatrix: break; } // We don't know hot to display this type... return lldb::eFormatBytes; } static bool ObjCDeclHasIVars(clang::ObjCInterfaceDecl *class_interface_decl, bool check_superclass) { while (class_interface_decl) { if (class_interface_decl->ivar_size() > 0) return true; if (check_superclass) class_interface_decl = class_interface_decl->getSuperClass(); else break; } return false; } static Optional GetDynamicArrayInfo(TypeSystemClang &ast, SymbolFile *sym_file, clang::QualType qual_type, const ExecutionContext *exe_ctx) { if (qual_type->isIncompleteArrayType()) if (auto *metadata = ast.GetMetadata(qual_type.getTypePtr())) return sym_file->GetDynamicArrayInfoForUID(metadata->GetUserID(), exe_ctx); return llvm::None; } uint32_t TypeSystemClang::GetNumChildren(lldb::opaque_compiler_type_t type, bool omit_empty_base_classes, const ExecutionContext *exe_ctx) { if (!type) return 0; uint32_t num_children = 0; clang::QualType qual_type(RemoveWrappingTypes(GetQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { case clang::BuiltinType::ObjCId: // child is Class case clang::BuiltinType::ObjCClass: // child is Class num_children = 1; break; default: break; } break; case clang::Type::Complex: return 0; case clang::Type::Record: if (GetCompleteQualType(&getASTContext(), qual_type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { if (omit_empty_base_classes) { // Check each base classes to see if it or any of its base classes // contain any fields. This can help limit the noise in variable // views by not having to show base classes that contain no members. clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { const clang::CXXRecordDecl *base_class_decl = llvm::cast( base_class->getType() ->getAs() ->getDecl()); // Skip empty base classes if (!TypeSystemClang::RecordHasFields(base_class_decl)) continue; num_children++; } } else { // Include all base classes num_children += cxx_record_decl->getNumBases(); } } clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field) ++num_children; } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteQualType(&getASTContext(), qual_type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); if (superclass_interface_decl) { if (omit_empty_base_classes) { if (ObjCDeclHasIVars(superclass_interface_decl, true)) ++num_children; } else ++num_children; } num_children += class_interface_decl->ivar_size(); } } } break; case clang::Type::LValueReference: case clang::Type::RValueReference: case clang::Type::ObjCObjectPointer: { CompilerType pointee_clang_type(GetPointeeType(type)); uint32_t num_pointee_children = 0; if (pointee_clang_type.IsAggregateType()) num_pointee_children = pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx); // If this type points to a simple type, then it has 1 child if (num_pointee_children == 0) num_children = 1; else num_children = num_pointee_children; } break; case clang::Type::Vector: case clang::Type::ExtVector: num_children = llvm::cast(qual_type.getTypePtr())->getNumElements(); break; case clang::Type::ConstantArray: num_children = llvm::cast(qual_type.getTypePtr()) ->getSize() .getLimitedValue(); break; case clang::Type::IncompleteArray: if (auto array_info = GetDynamicArrayInfo(*this, GetSymbolFile(), qual_type, exe_ctx)) // Only 1-dimensional arrays are supported. num_children = array_info->element_orders.size() ? array_info->element_orders.back() : 0; break; case clang::Type::Pointer: { const clang::PointerType *pointer_type = llvm::cast(qual_type.getTypePtr()); clang::QualType pointee_type(pointer_type->getPointeeType()); CompilerType pointee_clang_type(GetType(pointee_type)); uint32_t num_pointee_children = 0; if (pointee_clang_type.IsAggregateType()) num_pointee_children = pointee_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx); if (num_pointee_children == 0) { // We have a pointer to a pointee type that claims it has no children. We // will want to look at num_children = GetNumPointeeChildren(pointee_type); } else num_children = num_pointee_children; } break; default: break; } return num_children; } CompilerType TypeSystemClang::GetBuiltinTypeByName(ConstString name) { return GetBasicType(GetBasicTypeEnumeration(name)); } lldb::BasicType TypeSystemClang::GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) { if (type) { clang::QualType qual_type(GetQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); if (type_class == clang::Type::Builtin) { switch (llvm::cast(qual_type)->getKind()) { case clang::BuiltinType::Void: return eBasicTypeVoid; case clang::BuiltinType::Bool: return eBasicTypeBool; case clang::BuiltinType::Char_S: return eBasicTypeSignedChar; case clang::BuiltinType::Char_U: return eBasicTypeUnsignedChar; case clang::BuiltinType::Char16: return eBasicTypeChar16; case clang::BuiltinType::Char32: return eBasicTypeChar32; case clang::BuiltinType::UChar: return eBasicTypeUnsignedChar; case clang::BuiltinType::SChar: return eBasicTypeSignedChar; case clang::BuiltinType::WChar_S: return eBasicTypeSignedWChar; case clang::BuiltinType::WChar_U: return eBasicTypeUnsignedWChar; case clang::BuiltinType::Short: return eBasicTypeShort; case clang::BuiltinType::UShort: return eBasicTypeUnsignedShort; case clang::BuiltinType::Int: return eBasicTypeInt; case clang::BuiltinType::UInt: return eBasicTypeUnsignedInt; case clang::BuiltinType::Long: return eBasicTypeLong; case clang::BuiltinType::ULong: return eBasicTypeUnsignedLong; case clang::BuiltinType::LongLong: return eBasicTypeLongLong; case clang::BuiltinType::ULongLong: return eBasicTypeUnsignedLongLong; case clang::BuiltinType::Int128: return eBasicTypeInt128; case clang::BuiltinType::UInt128: return eBasicTypeUnsignedInt128; case clang::BuiltinType::Half: return eBasicTypeHalf; case clang::BuiltinType::Float: return eBasicTypeFloat; case clang::BuiltinType::Double: return eBasicTypeDouble; case clang::BuiltinType::LongDouble: return eBasicTypeLongDouble; case clang::BuiltinType::NullPtr: return eBasicTypeNullPtr; case clang::BuiltinType::ObjCId: return eBasicTypeObjCID; case clang::BuiltinType::ObjCClass: return eBasicTypeObjCClass; case clang::BuiltinType::ObjCSel: return eBasicTypeObjCSel; default: return eBasicTypeOther; } } } return eBasicTypeInvalid; } void TypeSystemClang::ForEachEnumerator( lldb::opaque_compiler_type_t type, std::function const &callback) { const clang::EnumType *enum_type = llvm::dyn_cast(GetCanonicalQualType(type)); if (enum_type) { const clang::EnumDecl *enum_decl = enum_type->getDecl(); if (enum_decl) { CompilerType integer_type = GetType(enum_decl->getIntegerType()); clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos; for (enum_pos = enum_decl->enumerator_begin(), enum_end_pos = enum_decl->enumerator_end(); enum_pos != enum_end_pos; ++enum_pos) { ConstString name(enum_pos->getNameAsString().c_str()); if (!callback(integer_type, name, enum_pos->getInitVal())) break; } } } } #pragma mark Aggregate Types uint32_t TypeSystemClang::GetNumFields(lldb::opaque_compiler_type_t type) { if (!type) return 0; uint32_t count = 0; clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::dyn_cast(qual_type.getTypePtr()); if (record_type) { clang::RecordDecl *record_decl = record_type->getDecl(); if (record_decl) { uint32_t field_idx = 0; clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field) ++field_idx; count = field_idx; } } } break; case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = qual_type->getAs(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && GetCompleteType(static_cast( const_cast(objc_interface_type)))) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getDecl(); if (class_interface_decl) { count = class_interface_decl->ivar_size(); } } break; } case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) count = class_interface_decl->ivar_size(); } } break; default: break; } return count; } static lldb::opaque_compiler_type_t GetObjCFieldAtIndex(clang::ASTContext *ast, clang::ObjCInterfaceDecl *class_interface_decl, size_t idx, std::string &name, uint64_t *bit_offset_ptr, uint32_t *bitfield_bit_size_ptr, bool *is_bitfield_ptr) { if (class_interface_decl) { if (idx < (class_interface_decl->ivar_size())) { clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end(); uint32_t ivar_idx = 0; for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++ivar_idx) { if (ivar_idx == idx) { const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; clang::QualType ivar_qual_type(ivar_decl->getType()); name.assign(ivar_decl->getNameAsString()); if (bit_offset_ptr) { const clang::ASTRecordLayout &interface_layout = ast->getASTObjCInterfaceLayout(class_interface_decl); *bit_offset_ptr = interface_layout.getFieldOffset(ivar_idx); } const bool is_bitfield = ivar_pos->isBitField(); if (bitfield_bit_size_ptr) { *bitfield_bit_size_ptr = 0; if (is_bitfield && ast) { clang::Expr *bitfield_bit_size_expr = ivar_pos->getBitWidth(); clang::Expr::EvalResult result; if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(result, *ast)) { llvm::APSInt bitfield_apsint = result.Val.getInt(); *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue(); } } } if (is_bitfield_ptr) *is_bitfield_ptr = is_bitfield; return ivar_qual_type.getAsOpaquePtr(); } } } } return nullptr; } CompilerType TypeSystemClang::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 (!type) return CompilerType(); clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); uint32_t field_idx = 0; clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx) { if (idx == field_idx) { // Print the member type if requested // Print the member name and equal sign name.assign(field->getNameAsString()); // Figure out the type byte size (field_type_info.first) and // alignment (field_type_info.second) from the AST context. if (bit_offset_ptr) { const clang::ASTRecordLayout &record_layout = getASTContext().getASTRecordLayout(record_decl); *bit_offset_ptr = record_layout.getFieldOffset(field_idx); } const bool is_bitfield = field->isBitField(); if (bitfield_bit_size_ptr) { *bitfield_bit_size_ptr = 0; if (is_bitfield) { clang::Expr *bitfield_bit_size_expr = field->getBitWidth(); clang::Expr::EvalResult result; if (bitfield_bit_size_expr && bitfield_bit_size_expr->EvaluateAsInt(result, getASTContext())) { llvm::APSInt bitfield_apsint = result.Val.getInt(); *bitfield_bit_size_ptr = bitfield_apsint.getLimitedValue(); } } } if (is_bitfield_ptr) *is_bitfield_ptr = is_bitfield; return GetType(field->getType()); } } } break; case clang::Type::ObjCObjectPointer: { const clang::ObjCObjectPointerType *objc_class_type = qual_type->getAs(); const clang::ObjCInterfaceType *objc_interface_type = objc_class_type->getInterfaceType(); if (objc_interface_type && GetCompleteType(static_cast( const_cast(objc_interface_type)))) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getDecl(); if (class_interface_decl) { return CompilerType( this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx, name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr)); } } break; } case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); return CompilerType( this, GetObjCFieldAtIndex(&getASTContext(), class_interface_decl, idx, name, bit_offset_ptr, bitfield_bit_size_ptr, is_bitfield_ptr)); } } break; default: break; } return CompilerType(); } uint32_t TypeSystemClang::GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) { uint32_t count = 0; clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) count = cxx_record_decl->getNumBases(); } break; case clang::Type::ObjCObjectPointer: count = GetPointeeType(type).GetNumDirectBaseClasses(); break; case clang::Type::ObjCObject: if (GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType(); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl && class_interface_decl->getSuperClass()) count = 1; } } break; case clang::Type::ObjCInterface: if (GetCompleteType(type)) { const clang::ObjCInterfaceType *objc_interface_type = qual_type->getAs(); if (objc_interface_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getInterface(); if (class_interface_decl && class_interface_decl->getSuperClass()) count = 1; } } break; default: break; } return count; } uint32_t TypeSystemClang::GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) { uint32_t count = 0; clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) count = cxx_record_decl->getNumVBases(); } break; default: break; } return count; } CompilerType TypeSystemClang::GetDirectBaseClassAtIndex( lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { uint32_t curr_idx = 0; clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class, ++curr_idx) { if (curr_idx == idx) { if (bit_offset_ptr) { const clang::ASTRecordLayout &record_layout = getASTContext().getASTRecordLayout(cxx_record_decl); const clang::CXXRecordDecl *base_class_decl = llvm::cast( base_class->getType() ->getAs() ->getDecl()); if (base_class->isVirtual()) *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl) .getQuantity() * 8; else *bit_offset_ptr = record_layout.getBaseClassOffset(base_class_decl) .getQuantity() * 8; } return GetType(base_class->getType()); } } } } break; case clang::Type::ObjCObjectPointer: return GetPointeeType(type).GetDirectBaseClassAtIndex(idx, bit_offset_ptr); case clang::Type::ObjCObject: if (idx == 0 && GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = qual_type->getAsObjCQualifiedInterfaceType(); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); if (superclass_interface_decl) { if (bit_offset_ptr) *bit_offset_ptr = 0; return GetType(getASTContext().getObjCInterfaceType( superclass_interface_decl)); } } } } break; case clang::Type::ObjCInterface: if (idx == 0 && GetCompleteType(type)) { const clang::ObjCObjectType *objc_interface_type = qual_type->getAs(); if (objc_interface_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_interface_type->getInterface(); if (class_interface_decl) { clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); if (superclass_interface_decl) { if (bit_offset_ptr) *bit_offset_ptr = 0; return GetType(getASTContext().getObjCInterfaceType( superclass_interface_decl)); } } } } break; default: break; } return CompilerType(); } CompilerType TypeSystemClang::GetVirtualBaseClassAtIndex( lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { uint32_t curr_idx = 0; clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->vbases_begin(), base_class_end = cxx_record_decl->vbases_end(); base_class != base_class_end; ++base_class, ++curr_idx) { if (curr_idx == idx) { if (bit_offset_ptr) { const clang::ASTRecordLayout &record_layout = getASTContext().getASTRecordLayout(cxx_record_decl); const clang::CXXRecordDecl *base_class_decl = llvm::cast( base_class->getType() ->getAs() ->getDecl()); *bit_offset_ptr = record_layout.getVBaseClassOffset(base_class_decl) .getQuantity() * 8; } return GetType(base_class->getType()); } } } } break; default: break; } return CompilerType(); } // If a pointer to a pointee type (the clang_type arg) says that it has no // children, then we either need to trust it, or override it and return a // different result. For example, an "int *" has one child that is an integer, // but a function pointer doesn't have any children. Likewise if a Record type // claims it has no children, then there really is nothing to show. uint32_t TypeSystemClang::GetNumPointeeChildren(clang::QualType type) { if (type.isNull()) return 0; clang::QualType qual_type = RemoveWrappingTypes(type.getCanonicalType()); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Builtin: switch (llvm::cast(qual_type)->getKind()) { case clang::BuiltinType::UnknownAny: case clang::BuiltinType::Void: case clang::BuiltinType::NullPtr: case clang::BuiltinType::OCLEvent: case clang::BuiltinType::OCLImage1dRO: case clang::BuiltinType::OCLImage1dWO: case clang::BuiltinType::OCLImage1dRW: case clang::BuiltinType::OCLImage1dArrayRO: case clang::BuiltinType::OCLImage1dArrayWO: case clang::BuiltinType::OCLImage1dArrayRW: case clang::BuiltinType::OCLImage1dBufferRO: case clang::BuiltinType::OCLImage1dBufferWO: case clang::BuiltinType::OCLImage1dBufferRW: case clang::BuiltinType::OCLImage2dRO: case clang::BuiltinType::OCLImage2dWO: case clang::BuiltinType::OCLImage2dRW: case clang::BuiltinType::OCLImage2dArrayRO: case clang::BuiltinType::OCLImage2dArrayWO: case clang::BuiltinType::OCLImage2dArrayRW: case clang::BuiltinType::OCLImage3dRO: case clang::BuiltinType::OCLImage3dWO: case clang::BuiltinType::OCLImage3dRW: case clang::BuiltinType::OCLSampler: return 0; case clang::BuiltinType::Bool: case clang::BuiltinType::Char_U: case clang::BuiltinType::UChar: case clang::BuiltinType::WChar_U: case clang::BuiltinType::Char16: case clang::BuiltinType::Char32: case clang::BuiltinType::UShort: case clang::BuiltinType::UInt: case clang::BuiltinType::ULong: case clang::BuiltinType::ULongLong: case clang::BuiltinType::UInt128: case clang::BuiltinType::Char_S: case clang::BuiltinType::SChar: case clang::BuiltinType::WChar_S: case clang::BuiltinType::Short: case clang::BuiltinType::Int: case clang::BuiltinType::Long: case clang::BuiltinType::LongLong: case clang::BuiltinType::Int128: case clang::BuiltinType::Float: case clang::BuiltinType::Double: case clang::BuiltinType::LongDouble: case clang::BuiltinType::Dependent: case clang::BuiltinType::Overload: case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: case clang::BuiltinType::ObjCSel: case clang::BuiltinType::BoundMember: case clang::BuiltinType::Half: case clang::BuiltinType::ARCUnbridgedCast: case clang::BuiltinType::PseudoObject: case clang::BuiltinType::BuiltinFn: case clang::BuiltinType::OMPArraySection: return 1; default: return 0; } break; case clang::Type::Complex: return 1; case clang::Type::Pointer: return 1; case clang::Type::BlockPointer: return 0; // If block pointers don't have debug info, then no children for // them case clang::Type::LValueReference: return 1; case clang::Type::RValueReference: return 1; case clang::Type::MemberPointer: return 0; case clang::Type::ConstantArray: return 0; case clang::Type::IncompleteArray: return 0; case clang::Type::VariableArray: return 0; case clang::Type::DependentSizedArray: return 0; case clang::Type::DependentSizedExtVector: return 0; case clang::Type::Vector: return 0; case clang::Type::ExtVector: return 0; case clang::Type::FunctionProto: return 0; // When we function pointers, they have no children... case clang::Type::FunctionNoProto: return 0; // When we function pointers, they have no children... case clang::Type::UnresolvedUsing: return 0; case clang::Type::Record: return 0; case clang::Type::Enum: return 1; case clang::Type::TemplateTypeParm: return 1; case clang::Type::SubstTemplateTypeParm: return 1; case clang::Type::TemplateSpecialization: return 1; case clang::Type::InjectedClassName: return 0; case clang::Type::DependentName: return 1; case clang::Type::DependentTemplateSpecialization: return 1; case clang::Type::ObjCObject: return 0; case clang::Type::ObjCInterface: return 0; case clang::Type::ObjCObjectPointer: return 1; default: break; } return 0; } CompilerType TypeSystemClang::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) { if (!type) return CompilerType(); auto get_exe_scope = [&exe_ctx]() { return exe_ctx ? exe_ctx->GetBestExecutionContextScope() : nullptr; }; clang::QualType parent_qual_type( RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass parent_type_class = parent_qual_type->getTypeClass(); child_bitfield_bit_size = 0; child_bitfield_bit_offset = 0; child_is_base_class = false; language_flags = 0; const bool idx_is_valid = idx < GetNumChildren(type, omit_empty_base_classes, exe_ctx); int32_t bit_offset; switch (parent_type_class) { case clang::Type::Builtin: if (idx_is_valid) { switch (llvm::cast(parent_qual_type)->getKind()) { case clang::BuiltinType::ObjCId: case clang::BuiltinType::ObjCClass: child_name = "isa"; child_byte_size = getASTContext().getTypeSize(getASTContext().ObjCBuiltinClassTy) / CHAR_BIT; return GetType(getASTContext().ObjCBuiltinClassTy); default: break; } } break; case clang::Type::Record: if (idx_is_valid && GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(parent_qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); const clang::ASTRecordLayout &record_layout = getASTContext().getASTRecordLayout(record_decl); uint32_t child_idx = 0; const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { // We might have base classes to print out first clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { const clang::CXXRecordDecl *base_class_decl = nullptr; // Skip empty base classes if (omit_empty_base_classes) { base_class_decl = llvm::cast( base_class->getType()->getAs()->getDecl()); if (!TypeSystemClang::RecordHasFields(base_class_decl)) continue; } if (idx == child_idx) { if (base_class_decl == nullptr) base_class_decl = llvm::cast( base_class->getType()->getAs()->getDecl()); if (base_class->isVirtual()) { bool handled = false; if (valobj) { clang::VTableContextBase *vtable_ctx = getASTContext().getVTableContext(); if (vtable_ctx) handled = GetVBaseBitOffset(*vtable_ctx, *valobj, record_layout, cxx_record_decl, base_class_decl, bit_offset); } if (!handled) bit_offset = record_layout.getVBaseClassOffset(base_class_decl) .getQuantity() * 8; } else bit_offset = record_layout.getBaseClassOffset(base_class_decl) .getQuantity() * 8; // Base classes should be a multiple of 8 bits in size child_byte_offset = bit_offset / 8; CompilerType base_class_clang_type = GetType(base_class->getType()); child_name = base_class_clang_type.GetTypeName().AsCString(""); Optional size = base_class_clang_type.GetBitSize(get_exe_scope()); if (!size) return {}; uint64_t base_class_clang_type_bit_size = *size; // Base classes bit sizes should be a multiple of 8 bits in size assert(base_class_clang_type_bit_size % 8 == 0); child_byte_size = base_class_clang_type_bit_size / 8; child_is_base_class = true; return base_class_clang_type; } // We don't increment the child index in the for loop since we might // be skipping empty base classes ++child_idx; } } // Make sure index is in range... uint32_t field_idx = 0; clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx) { if (idx == child_idx) { // Print the member type if requested // Print the member name and equal sign child_name.assign(field->getNameAsString()); // Figure out the type byte size (field_type_info.first) and // alignment (field_type_info.second) from the AST context. CompilerType field_clang_type = GetType(field->getType()); assert(field_idx < record_layout.getFieldCount()); Optional size = field_clang_type.GetByteSize(get_exe_scope()); if (!size) return {}; child_byte_size = *size; const uint32_t child_bit_size = child_byte_size * 8; // Figure out the field offset within the current struct/union/class // type bit_offset = record_layout.getFieldOffset(field_idx); if (FieldIsBitfield(*field, child_bitfield_bit_size)) { child_bitfield_bit_offset = bit_offset % child_bit_size; const uint32_t child_bit_offset = bit_offset - child_bitfield_bit_offset; child_byte_offset = child_bit_offset / 8; } else { child_byte_offset = bit_offset / 8; } return field_clang_type; } } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (idx_is_valid && GetCompleteType(type)) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(parent_qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { uint32_t child_idx = 0; clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { const clang::ASTRecordLayout &interface_layout = getASTContext().getASTObjCInterfaceLayout(class_interface_decl); clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); if (superclass_interface_decl) { if (omit_empty_base_classes) { CompilerType base_class_clang_type = GetType(getASTContext().getObjCInterfaceType( superclass_interface_decl)); if (base_class_clang_type.GetNumChildren(omit_empty_base_classes, exe_ctx) > 0) { if (idx == 0) { clang::QualType ivar_qual_type( getASTContext().getObjCInterfaceType( superclass_interface_decl)); child_name.assign( superclass_interface_decl->getNameAsString()); clang::TypeInfo ivar_type_info = getASTContext().getTypeInfo(ivar_qual_type.getTypePtr()); child_byte_size = ivar_type_info.Width / 8; child_byte_offset = 0; child_is_base_class = true; return GetType(ivar_qual_type); } ++child_idx; } } else ++child_idx; } const uint32_t superclass_idx = child_idx; if (idx < (child_idx + class_interface_decl->ivar_size())) { clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end(); for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos) { if (child_idx == idx) { clang::ObjCIvarDecl *ivar_decl = *ivar_pos; clang::QualType ivar_qual_type(ivar_decl->getType()); child_name.assign(ivar_decl->getNameAsString()); clang::TypeInfo ivar_type_info = getASTContext().getTypeInfo(ivar_qual_type.getTypePtr()); child_byte_size = ivar_type_info.Width / 8; // Figure out the field offset within the current // struct/union/class type For ObjC objects, we can't trust the // bit offset we get from the Clang AST, since that doesn't // account for the space taken up by unbacked properties, or // from the changing size of base classes that are newer than // this class. So if we have a process around that we can ask // about this object, do so. child_byte_offset = LLDB_INVALID_IVAR_OFFSET; Process *process = nullptr; if (exe_ctx) process = exe_ctx->GetProcessPtr(); if (process) { ObjCLanguageRuntime *objc_runtime = ObjCLanguageRuntime::Get(*process); if (objc_runtime != nullptr) { CompilerType parent_ast_type = GetType(parent_qual_type); child_byte_offset = objc_runtime->GetByteOffsetForIvar( parent_ast_type, ivar_decl->getNameAsString().c_str()); } } // Setting this to INT32_MAX to make sure we don't compute it // twice... bit_offset = INT32_MAX; if (child_byte_offset == static_cast(LLDB_INVALID_IVAR_OFFSET)) { bit_offset = interface_layout.getFieldOffset(child_idx - superclass_idx); child_byte_offset = bit_offset / 8; } // Note, the ObjC Ivar Byte offset is just that, it doesn't // account for the bit offset of a bitfield within its // containing object. So regardless of where we get the byte // offset from, we still need to get the bit offset for // bitfields from the layout. if (FieldIsBitfield(ivar_decl, child_bitfield_bit_size)) { if (bit_offset == INT32_MAX) bit_offset = interface_layout.getFieldOffset( child_idx - superclass_idx); child_bitfield_bit_offset = bit_offset % 8; } return GetType(ivar_qual_type); } ++child_idx; } } } } } break; case clang::Type::ObjCObjectPointer: if (idx_is_valid) { CompilerType pointee_clang_type(GetPointeeType(type)); if (transparent_pointers && pointee_clang_type.IsAggregateType()) { child_is_deref_of_parent = false; bool tmp_child_is_deref_of_parent = false; return pointee_clang_type.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() : nullptr; if (parent_name) { child_name.assign(1, '*'); child_name += parent_name; } // We have a pointer to an simple type if (idx == 0 && pointee_clang_type.GetCompleteType()) { if (Optional size = pointee_clang_type.GetByteSize(get_exe_scope())) { child_byte_size = *size; child_byte_offset = 0; return pointee_clang_type; } } } } break; case clang::Type::Vector: case clang::Type::ExtVector: if (idx_is_valid) { const clang::VectorType *array = llvm::cast(parent_qual_type.getTypePtr()); if (array) { CompilerType element_type = GetType(array->getElementType()); if (element_type.GetCompleteType()) { char element_name[64]; ::snprintf(element_name, sizeof(element_name), "[%" PRIu64 "]", static_cast(idx)); child_name.assign(element_name); if (Optional size = element_type.GetByteSize(get_exe_scope())) { child_byte_size = *size; child_byte_offset = (int32_t)idx * (int32_t)child_byte_size; return element_type; } } } } break; case clang::Type::ConstantArray: case clang::Type::IncompleteArray: if (ignore_array_bounds || idx_is_valid) { const clang::ArrayType *array = GetQualType(type)->getAsArrayTypeUnsafe(); if (array) { CompilerType element_type = GetType(array->getElementType()); if (element_type.GetCompleteType()) { child_name = std::string(llvm::formatv("[{0}]", idx)); if (Optional size = element_type.GetByteSize(get_exe_scope())) { child_byte_size = *size; child_byte_offset = (int32_t)idx * (int32_t)child_byte_size; return element_type; } } } } break; case clang::Type::Pointer: { CompilerType pointee_clang_type(GetPointeeType(type)); // Don't dereference "void *" pointers if (pointee_clang_type.IsVoidType()) return CompilerType(); if (transparent_pointers && pointee_clang_type.IsAggregateType()) { child_is_deref_of_parent = false; bool tmp_child_is_deref_of_parent = false; return pointee_clang_type.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() : nullptr; if (parent_name) { child_name.assign(1, '*'); child_name += parent_name; } // We have a pointer to an simple type if (idx == 0) { if (Optional size = pointee_clang_type.GetByteSize(get_exe_scope())) { child_byte_size = *size; child_byte_offset = 0; return pointee_clang_type; } } } break; } case clang::Type::LValueReference: case clang::Type::RValueReference: if (idx_is_valid) { const clang::ReferenceType *reference_type = llvm::cast(parent_qual_type.getTypePtr()); CompilerType pointee_clang_type = GetType(reference_type->getPointeeType()); if (transparent_pointers && pointee_clang_type.IsAggregateType()) { child_is_deref_of_parent = false; bool tmp_child_is_deref_of_parent = false; return pointee_clang_type.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 { const char *parent_name = valobj ? valobj->GetName().GetCString() : nullptr; if (parent_name) { child_name.assign(1, '&'); child_name += parent_name; } // We have a pointer to an simple type if (idx == 0) { if (Optional size = pointee_clang_type.GetByteSize(get_exe_scope())) { child_byte_size = *size; child_byte_offset = 0; return pointee_clang_type; } } } } break; default: break; } return CompilerType(); } static uint32_t GetIndexForRecordBase(const clang::RecordDecl *record_decl, const clang::CXXBaseSpecifier *base_spec, bool omit_empty_base_classes) { uint32_t child_idx = 0; const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { if (omit_empty_base_classes) { if (BaseSpecifierIsEmpty(base_class)) continue; } if (base_class == base_spec) return child_idx; ++child_idx; } } return UINT32_MAX; } static uint32_t GetIndexForRecordChild(const clang::RecordDecl *record_decl, clang::NamedDecl *canonical_decl, bool omit_empty_base_classes) { uint32_t child_idx = TypeSystemClang::GetNumBaseClasses( llvm::dyn_cast(record_decl), omit_empty_base_classes); clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++child_idx) { if (field->getCanonicalDecl() == canonical_decl) return child_idx; } return UINT32_MAX; } // Look for a child member (doesn't include base classes, but it does include // their members) in the type hierarchy. Returns an index path into // "clang_type" on how to reach the appropriate member. // // class A // { // public: // int m_a; // int m_b; // }; // // class B // { // }; // // class C : // public B, // public A // { // }; // // If we have a clang type that describes "class C", and we wanted to looked // "m_b" in it: // // With omit_empty_base_classes == false we would get an integer array back // with: { 1, 1 } The first index 1 is the child index for "class A" within // class C The second index 1 is the child index for "m_b" within class A // // With omit_empty_base_classes == true we would get an integer array back // with: { 0, 1 } The first index 0 is the child index for "class A" within // class C (since class B doesn't have any members it doesn't count) The second // index 1 is the child index for "m_b" within class A size_t TypeSystemClang::GetIndexOfChildMemberWithName( lldb::opaque_compiler_type_t type, const char *name, bool omit_empty_base_classes, std::vector &child_indexes) { if (type && name && name[0]) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); uint32_t child_idx = 0; const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); // Try and find a field that matches NAME clang::RecordDecl::field_iterator field, field_end; llvm::StringRef name_sref(name); for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++child_idx) { llvm::StringRef field_name = field->getName(); if (field_name.empty()) { CompilerType field_type = GetType(field->getType()); child_indexes.push_back(child_idx); if (field_type.GetIndexOfChildMemberWithName( name, omit_empty_base_classes, child_indexes)) return child_indexes.size(); child_indexes.pop_back(); } else if (field_name.equals(name_sref)) { // We have to add on the number of base classes to this index! child_indexes.push_back( child_idx + TypeSystemClang::GetNumBaseClasses( cxx_record_decl, omit_empty_base_classes)); return child_indexes.size(); } } if (cxx_record_decl) { const clang::RecordDecl *parent_record_decl = cxx_record_decl; // Didn't find things easily, lets let clang do its thang... clang::IdentifierInfo &ident_ref = getASTContext().Idents.get(name_sref); clang::DeclarationName decl_name(&ident_ref); clang::CXXBasePaths paths; if (cxx_record_decl->lookupInBases( [decl_name](const clang::CXXBaseSpecifier *specifier, clang::CXXBasePath &path) { return clang::CXXRecordDecl::FindOrdinaryMember( specifier, path, decl_name); }, paths)) { clang::CXXBasePaths::const_paths_iterator path, path_end = paths.end(); for (path = paths.begin(); path != path_end; ++path) { const size_t num_path_elements = path->size(); for (size_t e = 0; e < num_path_elements; ++e) { clang::CXXBasePathElement elem = (*path)[e]; child_idx = GetIndexForRecordBase(parent_record_decl, elem.Base, omit_empty_base_classes); if (child_idx == UINT32_MAX) { child_indexes.clear(); return 0; } else { child_indexes.push_back(child_idx); parent_record_decl = llvm::cast( elem.Base->getType() ->getAs() ->getDecl()); } } for (clang::NamedDecl *path_decl : path->Decls) { child_idx = GetIndexForRecordChild( parent_record_decl, path_decl, omit_empty_base_classes); if (child_idx == UINT32_MAX) { child_indexes.clear(); return 0; } else { child_indexes.push_back(child_idx); } } } return child_indexes.size(); } } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { llvm::StringRef name_sref(name); const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { uint32_t child_idx = 0; clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end(); clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx) { const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; if (ivar_decl->getName().equals(name_sref)) { if ((!omit_empty_base_classes && superclass_interface_decl) || (omit_empty_base_classes && ObjCDeclHasIVars(superclass_interface_decl, true))) ++child_idx; child_indexes.push_back(child_idx); return child_indexes.size(); } } if (superclass_interface_decl) { // The super class index is always zero for ObjC classes, so we // push it onto the child indexes in case we find an ivar in our // superclass... child_indexes.push_back(0); CompilerType superclass_clang_type = GetType(getASTContext().getObjCInterfaceType( superclass_interface_decl)); if (superclass_clang_type.GetIndexOfChildMemberWithName( name, omit_empty_base_classes, child_indexes)) { // We did find an ivar in a superclass so just return the // results! return child_indexes.size(); } // We didn't find an ivar matching "name" in our superclass, pop // the superclass zero index that we pushed on above. child_indexes.pop_back(); } } } } break; case clang::Type::ObjCObjectPointer: { CompilerType objc_object_clang_type = GetType( llvm::cast(qual_type.getTypePtr()) ->getPointeeType()); return objc_object_clang_type.GetIndexOfChildMemberWithName( name, omit_empty_base_classes, child_indexes); } break; case clang::Type::ConstantArray: { // const clang::ConstantArrayType *array = // llvm::cast(parent_qual_type.getTypePtr()); // const uint64_t element_count = // array->getSize().getLimitedValue(); // // if (idx < element_count) // { // std::pair field_type_info = // ast->getTypeInfo(array->getElementType()); // // char element_name[32]; // ::snprintf (element_name, sizeof (element_name), // "%s[%u]", parent_name ? parent_name : "", idx); // // child_name.assign(element_name); // assert(field_type_info.first % 8 == 0); // child_byte_size = field_type_info.first / 8; // child_byte_offset = idx * child_byte_size; // return array->getElementType().getAsOpaquePtr(); // } } break; // case clang::Type::MemberPointerType: // { // MemberPointerType *mem_ptr_type = // llvm::cast(qual_type.getTypePtr()); // clang::QualType pointee_type = // mem_ptr_type->getPointeeType(); // // if (TypeSystemClang::IsAggregateType // (pointee_type.getAsOpaquePtr())) // { // return GetIndexOfChildWithName (ast, // mem_ptr_type->getPointeeType().getAsOpaquePtr(), // name); // } // } // break; // case clang::Type::LValueReference: case clang::Type::RValueReference: { const clang::ReferenceType *reference_type = llvm::cast(qual_type.getTypePtr()); clang::QualType pointee_type(reference_type->getPointeeType()); CompilerType pointee_clang_type = GetType(pointee_type); if (pointee_clang_type.IsAggregateType()) { return pointee_clang_type.GetIndexOfChildMemberWithName( name, omit_empty_base_classes, child_indexes); } } break; case clang::Type::Pointer: { CompilerType pointee_clang_type(GetPointeeType(type)); if (pointee_clang_type.IsAggregateType()) { return pointee_clang_type.GetIndexOfChildMemberWithName( name, omit_empty_base_classes, child_indexes); } } break; default: break; } } return 0; } // Get the index of the child of "clang_type" whose name matches. This function // doesn't descend into the children, but only looks one level deep and name // matches can include base class names. uint32_t TypeSystemClang::GetIndexOfChildWithName(lldb::opaque_compiler_type_t type, const char *name, bool omit_empty_base_classes) { if (type && name && name[0]) { clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); uint32_t child_idx = 0; const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { // Skip empty base classes clang::CXXRecordDecl *base_class_decl = llvm::cast( base_class->getType() ->getAs() ->getDecl()); if (omit_empty_base_classes && !TypeSystemClang::RecordHasFields(base_class_decl)) continue; CompilerType base_class_clang_type = GetType(base_class->getType()); std::string base_class_type_name( base_class_clang_type.GetTypeName().AsCString("")); if (base_class_type_name == name) return child_idx; ++child_idx; } } // Try and find a field that matches NAME clang::RecordDecl::field_iterator field, field_end; llvm::StringRef name_sref(name); for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++child_idx) { if (field->getName().equals(name_sref)) return child_idx; } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: if (GetCompleteType(type)) { llvm::StringRef name_sref(name); const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { uint32_t child_idx = 0; clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { clang::ObjCInterfaceDecl::ivar_iterator ivar_pos, ivar_end = class_interface_decl->ivar_end(); clang::ObjCInterfaceDecl *superclass_interface_decl = class_interface_decl->getSuperClass(); for (ivar_pos = class_interface_decl->ivar_begin(); ivar_pos != ivar_end; ++ivar_pos, ++child_idx) { const clang::ObjCIvarDecl *ivar_decl = *ivar_pos; if (ivar_decl->getName().equals(name_sref)) { if ((!omit_empty_base_classes && superclass_interface_decl) || (omit_empty_base_classes && ObjCDeclHasIVars(superclass_interface_decl, true))) ++child_idx; return child_idx; } } if (superclass_interface_decl) { if (superclass_interface_decl->getName().equals(name_sref)) return 0; } } } } break; case clang::Type::ObjCObjectPointer: { CompilerType pointee_clang_type = GetType( llvm::cast(qual_type.getTypePtr()) ->getPointeeType()); return pointee_clang_type.GetIndexOfChildWithName( name, omit_empty_base_classes); } break; case clang::Type::ConstantArray: { // const clang::ConstantArrayType *array = // llvm::cast(parent_qual_type.getTypePtr()); // const uint64_t element_count = // array->getSize().getLimitedValue(); // // if (idx < element_count) // { // std::pair field_type_info = // ast->getTypeInfo(array->getElementType()); // // char element_name[32]; // ::snprintf (element_name, sizeof (element_name), // "%s[%u]", parent_name ? parent_name : "", idx); // // child_name.assign(element_name); // assert(field_type_info.first % 8 == 0); // child_byte_size = field_type_info.first / 8; // child_byte_offset = idx * child_byte_size; // return array->getElementType().getAsOpaquePtr(); // } } break; // case clang::Type::MemberPointerType: // { // MemberPointerType *mem_ptr_type = // llvm::cast(qual_type.getTypePtr()); // clang::QualType pointee_type = // mem_ptr_type->getPointeeType(); // // if (TypeSystemClang::IsAggregateType // (pointee_type.getAsOpaquePtr())) // { // return GetIndexOfChildWithName (ast, // mem_ptr_type->getPointeeType().getAsOpaquePtr(), // name); // } // } // break; // case clang::Type::LValueReference: case clang::Type::RValueReference: { const clang::ReferenceType *reference_type = llvm::cast(qual_type.getTypePtr()); CompilerType pointee_type = GetType(reference_type->getPointeeType()); if (pointee_type.IsAggregateType()) { return pointee_type.GetIndexOfChildWithName(name, omit_empty_base_classes); } } break; case clang::Type::Pointer: { const clang::PointerType *pointer_type = llvm::cast(qual_type.getTypePtr()); CompilerType pointee_type = GetType(pointer_type->getPointeeType()); if (pointee_type.IsAggregateType()) { return pointee_type.GetIndexOfChildWithName(name, omit_empty_base_classes); } else { // if (parent_name) // { // child_name.assign(1, '*'); // child_name += parent_name; // } // // // We have a pointer to an simple type // if (idx == 0) // { // std::pair clang_type_info // = ast->getTypeInfo(pointee_type); // assert(clang_type_info.first % 8 == 0); // child_byte_size = clang_type_info.first / 8; // child_byte_offset = 0; // return pointee_type.getAsOpaquePtr(); // } } } break; default: break; } } return UINT32_MAX; } size_t TypeSystemClang::GetNumTemplateArguments(lldb::opaque_compiler_type_t type) { if (!type) return 0; clang::QualType qual_type = RemoveWrappingTypes(GetCanonicalQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { const clang::ClassTemplateSpecializationDecl *template_decl = llvm::dyn_cast( cxx_record_decl); if (template_decl) return template_decl->getTemplateArgs().size(); } } break; default: break; } return 0; } const clang::ClassTemplateSpecializationDecl * TypeSystemClang::GetAsTemplateSpecialization( lldb::opaque_compiler_type_t type) { if (!type) return nullptr; clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: { if (! GetCompleteType(type)) return nullptr; const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (!cxx_record_decl) return nullptr; return llvm::dyn_cast( cxx_record_decl); } default: return nullptr; } } lldb::TemplateArgumentKind TypeSystemClang::GetTemplateArgumentKind(lldb::opaque_compiler_type_t type, size_t arg_idx) { const clang::ClassTemplateSpecializationDecl *template_decl = GetAsTemplateSpecialization(type); if (! template_decl || arg_idx >= template_decl->getTemplateArgs().size()) return eTemplateArgumentKindNull; switch (template_decl->getTemplateArgs()[arg_idx].getKind()) { case clang::TemplateArgument::Null: return eTemplateArgumentKindNull; case clang::TemplateArgument::NullPtr: return eTemplateArgumentKindNullPtr; case clang::TemplateArgument::Type: return eTemplateArgumentKindType; case clang::TemplateArgument::Declaration: return eTemplateArgumentKindDeclaration; case clang::TemplateArgument::Integral: return eTemplateArgumentKindIntegral; case clang::TemplateArgument::Template: return eTemplateArgumentKindTemplate; case clang::TemplateArgument::TemplateExpansion: return eTemplateArgumentKindTemplateExpansion; case clang::TemplateArgument::Expression: return eTemplateArgumentKindExpression; case clang::TemplateArgument::Pack: return eTemplateArgumentKindPack; } llvm_unreachable("Unhandled clang::TemplateArgument::ArgKind"); } CompilerType TypeSystemClang::GetTypeTemplateArgument(lldb::opaque_compiler_type_t type, size_t idx) { const clang::ClassTemplateSpecializationDecl *template_decl = GetAsTemplateSpecialization(type); if (!template_decl || idx >= template_decl->getTemplateArgs().size()) return CompilerType(); const clang::TemplateArgument &template_arg = template_decl->getTemplateArgs()[idx]; if (template_arg.getKind() != clang::TemplateArgument::Type) return CompilerType(); return GetType(template_arg.getAsType()); } Optional TypeSystemClang::GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type, size_t idx) { const clang::ClassTemplateSpecializationDecl *template_decl = GetAsTemplateSpecialization(type); if (! template_decl || idx >= template_decl->getTemplateArgs().size()) return llvm::None; const clang::TemplateArgument &template_arg = template_decl->getTemplateArgs()[idx]; if (template_arg.getKind() != clang::TemplateArgument::Integral) return llvm::None; return { {template_arg.getAsIntegral(), GetType(template_arg.getIntegralType())}}; } CompilerType TypeSystemClang::GetTypeForFormatters(void *type) { if (type) return ClangUtil::RemoveFastQualifiers(CompilerType(this, type)); return CompilerType(); } clang::EnumDecl *TypeSystemClang::GetAsEnumDecl(const CompilerType &type) { const clang::EnumType *enutype = llvm::dyn_cast(ClangUtil::GetCanonicalQualType(type)); if (enutype) return enutype->getDecl(); return nullptr; } clang::RecordDecl *TypeSystemClang::GetAsRecordDecl(const CompilerType &type) { const clang::RecordType *record_type = llvm::dyn_cast(ClangUtil::GetCanonicalQualType(type)); if (record_type) return record_type->getDecl(); return nullptr; } clang::TagDecl *TypeSystemClang::GetAsTagDecl(const CompilerType &type) { return ClangUtil::GetAsTagDecl(type); } clang::TypedefNameDecl * TypeSystemClang::GetAsTypedefDecl(const CompilerType &type) { const clang::TypedefType *typedef_type = llvm::dyn_cast(ClangUtil::GetQualType(type)); if (typedef_type) return typedef_type->getDecl(); return nullptr; } clang::CXXRecordDecl * TypeSystemClang::GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type) { return GetCanonicalQualType(type)->getAsCXXRecordDecl(); } clang::ObjCInterfaceDecl * TypeSystemClang::GetAsObjCInterfaceDecl(const CompilerType &type) { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast( ClangUtil::GetCanonicalQualType(type)); if (objc_class_type) return objc_class_type->getInterface(); return nullptr; } clang::FieldDecl *TypeSystemClang::AddFieldToRecordType( const CompilerType &type, llvm::StringRef name, const CompilerType &field_clang_type, AccessType access, uint32_t bitfield_bit_size) { if (!type.IsValid() || !field_clang_type.IsValid()) return nullptr; TypeSystemClang *ast = llvm::dyn_cast_or_null(type.GetTypeSystem()); if (!ast) return nullptr; clang::ASTContext &clang_ast = ast->getASTContext(); clang::IdentifierInfo *ident = nullptr; if (!name.empty()) ident = &clang_ast.Idents.get(name); clang::FieldDecl *field = nullptr; clang::Expr *bit_width = nullptr; if (bitfield_bit_size != 0) { llvm::APInt bitfield_bit_size_apint(clang_ast.getTypeSize(clang_ast.IntTy), bitfield_bit_size); bit_width = new (clang_ast) clang::IntegerLiteral(clang_ast, bitfield_bit_size_apint, clang_ast.IntTy, clang::SourceLocation()); } clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); if (record_decl) { field = clang::FieldDecl::CreateDeserialized(clang_ast, 0); field->setDeclContext(record_decl); field->setDeclName(ident); field->setType(ClangUtil::GetQualType(field_clang_type)); if (bit_width) field->setBitWidth(bit_width); SetMemberOwningModule(field, record_decl); if (name.empty()) { // Determine whether this field corresponds to an anonymous struct or // union. if (const clang::TagType *TagT = field->getType()->getAs()) { if (clang::RecordDecl *Rec = llvm::dyn_cast(TagT->getDecl())) if (!Rec->getDeclName()) { Rec->setAnonymousStructOrUnion(true); field->setImplicit(); } } } if (field) { field->setAccess( TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access)); record_decl->addDecl(field); VerifyDecl(field); } } else { clang::ObjCInterfaceDecl *class_interface_decl = ast->GetAsObjCInterfaceDecl(type); if (class_interface_decl) { const bool is_synthesized = false; field_clang_type.GetCompleteType(); auto *ivar = clang::ObjCIvarDecl::CreateDeserialized(clang_ast, 0); ivar->setDeclContext(class_interface_decl); ivar->setDeclName(ident); ivar->setType(ClangUtil::GetQualType(field_clang_type)); ivar->setAccessControl(ConvertAccessTypeToObjCIvarAccessControl(access)); if (bit_width) ivar->setBitWidth(bit_width); ivar->setSynthesize(is_synthesized); field = ivar; SetMemberOwningModule(field, class_interface_decl); if (field) { class_interface_decl->addDecl(field); VerifyDecl(field); } } } return field; } void TypeSystemClang::BuildIndirectFields(const CompilerType &type) { if (!type) return; TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (!ast) return; clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); if (!record_decl) return; typedef llvm::SmallVector IndirectFieldVector; IndirectFieldVector indirect_fields; clang::RecordDecl::field_iterator field_pos; clang::RecordDecl::field_iterator field_end_pos = record_decl->field_end(); clang::RecordDecl::field_iterator last_field_pos = field_end_pos; for (field_pos = record_decl->field_begin(); field_pos != field_end_pos; last_field_pos = field_pos++) { if (field_pos->isAnonymousStructOrUnion()) { clang::QualType field_qual_type = field_pos->getType(); const clang::RecordType *field_record_type = field_qual_type->getAs(); if (!field_record_type) continue; clang::RecordDecl *field_record_decl = field_record_type->getDecl(); if (!field_record_decl) continue; for (clang::RecordDecl::decl_iterator di = field_record_decl->decls_begin(), de = field_record_decl->decls_end(); di != de; ++di) { if (clang::FieldDecl *nested_field_decl = llvm::dyn_cast(*di)) { clang::NamedDecl **chain = new (ast->getASTContext()) clang::NamedDecl *[2]; chain[0] = *field_pos; chain[1] = nested_field_decl; clang::IndirectFieldDecl *indirect_field = clang::IndirectFieldDecl::Create( ast->getASTContext(), record_decl, clang::SourceLocation(), nested_field_decl->getIdentifier(), nested_field_decl->getType(), {chain, 2}); SetMemberOwningModule(indirect_field, record_decl); indirect_field->setImplicit(); indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers( field_pos->getAccess(), nested_field_decl->getAccess())); indirect_fields.push_back(indirect_field); } else if (clang::IndirectFieldDecl *nested_indirect_field_decl = llvm::dyn_cast(*di)) { size_t nested_chain_size = nested_indirect_field_decl->getChainingSize(); clang::NamedDecl **chain = new (ast->getASTContext()) clang::NamedDecl *[nested_chain_size + 1]; chain[0] = *field_pos; int chain_index = 1; for (clang::IndirectFieldDecl::chain_iterator nci = nested_indirect_field_decl->chain_begin(), nce = nested_indirect_field_decl->chain_end(); nci < nce; ++nci) { chain[chain_index] = *nci; chain_index++; } clang::IndirectFieldDecl *indirect_field = clang::IndirectFieldDecl::Create( ast->getASTContext(), record_decl, clang::SourceLocation(), nested_indirect_field_decl->getIdentifier(), nested_indirect_field_decl->getType(), {chain, nested_chain_size + 1}); SetMemberOwningModule(indirect_field, record_decl); indirect_field->setImplicit(); indirect_field->setAccess(TypeSystemClang::UnifyAccessSpecifiers( field_pos->getAccess(), nested_indirect_field_decl->getAccess())); indirect_fields.push_back(indirect_field); } } } } // Check the last field to see if it has an incomplete array type as its last // member and if it does, the tell the record decl about it if (last_field_pos != field_end_pos) { if (last_field_pos->getType()->isIncompleteArrayType()) record_decl->hasFlexibleArrayMember(); } for (IndirectFieldVector::iterator ifi = indirect_fields.begin(), ife = indirect_fields.end(); ifi < ife; ++ifi) { record_decl->addDecl(*ifi); } } void TypeSystemClang::SetIsPacked(const CompilerType &type) { if (type) { TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (ast) { clang::RecordDecl *record_decl = GetAsRecordDecl(type); if (!record_decl) return; record_decl->addAttr( clang::PackedAttr::CreateImplicit(ast->getASTContext())); } } } clang::VarDecl *TypeSystemClang::AddVariableToRecordType( const CompilerType &type, llvm::StringRef name, const CompilerType &var_type, AccessType access) { if (!type.IsValid() || !var_type.IsValid()) return nullptr; TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (!ast) return nullptr; clang::RecordDecl *record_decl = ast->GetAsRecordDecl(type); if (!record_decl) return nullptr; clang::VarDecl *var_decl = nullptr; clang::IdentifierInfo *ident = nullptr; if (!name.empty()) ident = &ast->getASTContext().Idents.get(name); var_decl = clang::VarDecl::CreateDeserialized(ast->getASTContext(), 0); var_decl->setDeclContext(record_decl); var_decl->setDeclName(ident); var_decl->setType(ClangUtil::GetQualType(var_type)); var_decl->setStorageClass(clang::SC_Static); SetMemberOwningModule(var_decl, record_decl); if (!var_decl) return nullptr; var_decl->setAccess( TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access)); record_decl->addDecl(var_decl); VerifyDecl(var_decl); return var_decl; } void TypeSystemClang::SetIntegerInitializerForVariable( VarDecl *var, const llvm::APInt &init_value) { assert(!var->hasInit() && "variable already initialized"); clang::ASTContext &ast = var->getASTContext(); QualType qt = var->getType(); assert(qt->isIntegralOrEnumerationType() && "only integer or enum types supported"); // If the variable is an enum type, take the underlying integer type as // the type of the integer literal. if (const EnumType *enum_type = llvm::dyn_cast(qt.getTypePtr())) { const EnumDecl *enum_decl = enum_type->getDecl(); qt = enum_decl->getIntegerType(); } var->setInit(IntegerLiteral::Create(ast, init_value, qt.getUnqualifiedType(), SourceLocation())); } void TypeSystemClang::SetFloatingInitializerForVariable( clang::VarDecl *var, const llvm::APFloat &init_value) { assert(!var->hasInit() && "variable already initialized"); clang::ASTContext &ast = var->getASTContext(); QualType qt = var->getType(); assert(qt->isFloatingType() && "only floating point types supported"); var->setInit(FloatingLiteral::Create( ast, init_value, true, qt.getUnqualifiedType(), SourceLocation())); } clang::CXXMethodDecl *TypeSystemClang::AddMethodToCXXRecordType( lldb::opaque_compiler_type_t type, llvm::StringRef name, const char *mangled_name, const CompilerType &method_clang_type, lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline, bool is_explicit, bool is_attr_used, bool is_artificial) { if (!type || !method_clang_type.IsValid() || name.empty()) return nullptr; clang::QualType record_qual_type(GetCanonicalQualType(type)); clang::CXXRecordDecl *cxx_record_decl = record_qual_type->getAsCXXRecordDecl(); if (cxx_record_decl == nullptr) return nullptr; clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type)); clang::CXXMethodDecl *cxx_method_decl = nullptr; clang::DeclarationName decl_name(&getASTContext().Idents.get(name)); const clang::FunctionType *function_type = llvm::dyn_cast(method_qual_type.getTypePtr()); if (function_type == nullptr) return nullptr; const clang::FunctionProtoType *method_function_prototype( llvm::dyn_cast(function_type)); if (!method_function_prototype) return nullptr; unsigned int num_params = method_function_prototype->getNumParams(); clang::CXXDestructorDecl *cxx_dtor_decl(nullptr); clang::CXXConstructorDecl *cxx_ctor_decl(nullptr); 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.startswith("~")) { cxx_dtor_decl = clang::CXXDestructorDecl::CreateDeserialized(getASTContext(), 0); cxx_dtor_decl->setDeclContext(cxx_record_decl); cxx_dtor_decl->setDeclName( getASTContext().DeclarationNames.getCXXDestructorName( getASTContext().getCanonicalType(record_qual_type))); cxx_dtor_decl->setType(method_qual_type); cxx_dtor_decl->setImplicit(is_artificial); cxx_dtor_decl->setInlineSpecified(is_inline); cxx_dtor_decl->setConstexprKind(CSK_unspecified); cxx_method_decl = cxx_dtor_decl; } else if (decl_name == cxx_record_decl->getDeclName()) { cxx_ctor_decl = clang::CXXConstructorDecl::CreateDeserialized( getASTContext(), 0, 0); cxx_ctor_decl->setDeclContext(cxx_record_decl); cxx_ctor_decl->setDeclName( getASTContext().DeclarationNames.getCXXConstructorName( getASTContext().getCanonicalType(record_qual_type))); cxx_ctor_decl->setType(method_qual_type); cxx_ctor_decl->setImplicit(is_artificial); cxx_ctor_decl->setInlineSpecified(is_inline); cxx_ctor_decl->setConstexprKind(CSK_unspecified); cxx_ctor_decl->setNumCtorInitializers(0); cxx_ctor_decl->setExplicitSpecifier(explicit_spec); cxx_method_decl = cxx_ctor_decl; } else { clang::StorageClass SC = is_static ? clang::SC_Static : clang::SC_None; clang::OverloadedOperatorKind op_kind = clang::NUM_OVERLOADED_OPERATORS; if (IsOperator(name, op_kind)) { if (op_kind != clang::NUM_OVERLOADED_OPERATORS) { // Check the number of operator parameters. Sometimes we have seen bad // DWARF that doesn't correctly describe operators and if we try to // create a method and add it to the class, clang will assert and // crash, so we need to make sure things are acceptable. const bool is_method = true; if (!TypeSystemClang::CheckOverloadedOperatorKindParameterCount( is_method, op_kind, num_params)) return nullptr; cxx_method_decl = clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0); cxx_method_decl->setDeclContext(cxx_record_decl); cxx_method_decl->setDeclName( getASTContext().DeclarationNames.getCXXOperatorName(op_kind)); cxx_method_decl->setType(method_qual_type); cxx_method_decl->setStorageClass(SC); cxx_method_decl->setInlineSpecified(is_inline); cxx_method_decl->setConstexprKind(CSK_unspecified); } else if (num_params == 0) { // Conversion operators don't take params... auto *cxx_conversion_decl = clang::CXXConversionDecl::CreateDeserialized(getASTContext(), 0); cxx_conversion_decl->setDeclContext(cxx_record_decl); cxx_conversion_decl->setDeclName( getASTContext().DeclarationNames.getCXXConversionFunctionName( getASTContext().getCanonicalType( function_type->getReturnType()))); cxx_conversion_decl->setType(method_qual_type); cxx_conversion_decl->setInlineSpecified(is_inline); cxx_conversion_decl->setExplicitSpecifier(explicit_spec); cxx_conversion_decl->setConstexprKind(CSK_unspecified); cxx_method_decl = cxx_conversion_decl; } } if (cxx_method_decl == nullptr) { cxx_method_decl = clang::CXXMethodDecl::CreateDeserialized(getASTContext(), 0); cxx_method_decl->setDeclContext(cxx_record_decl); cxx_method_decl->setDeclName(decl_name); cxx_method_decl->setType(method_qual_type); cxx_method_decl->setInlineSpecified(is_inline); cxx_method_decl->setStorageClass(SC); cxx_method_decl->setConstexprKind(CSK_unspecified); } } SetMemberOwningModule(cxx_method_decl, cxx_record_decl); clang::AccessSpecifier access_specifier = TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access); cxx_method_decl->setAccess(access_specifier); cxx_method_decl->setVirtualAsWritten(is_virtual); if (is_attr_used) cxx_method_decl->addAttr(clang::UsedAttr::CreateImplicit(getASTContext())); if (mangled_name != nullptr) { cxx_method_decl->addAttr(clang::AsmLabelAttr::CreateImplicit( getASTContext(), mangled_name, /*literal=*/false)); } // Populate the method decl with parameter decls llvm::SmallVector params; for (unsigned param_index = 0; param_index < num_params; ++param_index) { params.push_back(clang::ParmVarDecl::Create( getASTContext(), cxx_method_decl, clang::SourceLocation(), clang::SourceLocation(), nullptr, // anonymous method_function_prototype->getParamType(param_index), nullptr, clang::SC_None, nullptr)); } cxx_method_decl->setParams(llvm::ArrayRef(params)); cxx_record_decl->addDecl(cxx_method_decl); // Sometimes the debug info will mention a constructor (default/copy/move), // destructor, or assignment operator (copy/move) but there won't be any // version of this in the code. So we check if the function was artificially // generated and if it is trivial and this lets the compiler/backend know // that it can inline the IR for these when it needs to and we can avoid a // "missing function" error when running expressions. if (is_artificial) { if (cxx_ctor_decl && ((cxx_ctor_decl->isDefaultConstructor() && cxx_record_decl->hasTrivialDefaultConstructor()) || (cxx_ctor_decl->isCopyConstructor() && cxx_record_decl->hasTrivialCopyConstructor()) || (cxx_ctor_decl->isMoveConstructor() && cxx_record_decl->hasTrivialMoveConstructor()))) { cxx_ctor_decl->setDefaulted(); cxx_ctor_decl->setTrivial(true); } else if (cxx_dtor_decl) { if (cxx_record_decl->hasTrivialDestructor()) { cxx_dtor_decl->setDefaulted(); cxx_dtor_decl->setTrivial(true); } } else if ((cxx_method_decl->isCopyAssignmentOperator() && cxx_record_decl->hasTrivialCopyAssignment()) || (cxx_method_decl->isMoveAssignmentOperator() && cxx_record_decl->hasTrivialMoveAssignment())) { cxx_method_decl->setDefaulted(); cxx_method_decl->setTrivial(true); } } VerifyDecl(cxx_method_decl); return cxx_method_decl; } void TypeSystemClang::AddMethodOverridesForCXXRecordType( lldb::opaque_compiler_type_t type) { if (auto *record = GetAsCXXRecordDecl(type)) for (auto *method : record->methods()) addOverridesForMethod(method); } #pragma mark C++ Base Classes std::unique_ptr TypeSystemClang::CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type, AccessType access, bool is_virtual, bool base_of_class) { if (!type) return nullptr; return std::make_unique( clang::SourceRange(), is_virtual, base_of_class, TypeSystemClang::ConvertAccessTypeToAccessSpecifier(access), getASTContext().getTrivialTypeSourceInfo(GetQualType(type)), clang::SourceLocation()); } bool TypeSystemClang::TransferBaseClasses( lldb::opaque_compiler_type_t type, std::vector> bases) { if (!type) return false; clang::CXXRecordDecl *cxx_record_decl = GetAsCXXRecordDecl(type); if (!cxx_record_decl) return false; std::vector raw_bases; raw_bases.reserve(bases.size()); // Clang will make a copy of them, so it's ok that we pass pointers that we're // about to destroy. for (auto &b : bases) raw_bases.push_back(b.get()); cxx_record_decl->setBases(raw_bases.data(), raw_bases.size()); return true; } bool TypeSystemClang::SetObjCSuperClass( const CompilerType &type, const CompilerType &superclass_clang_type) { TypeSystemClang *ast = llvm::dyn_cast_or_null(type.GetTypeSystem()); if (!ast) return false; clang::ASTContext &clang_ast = ast->getASTContext(); if (type && superclass_clang_type.IsValid() && superclass_clang_type.GetTypeSystem() == type.GetTypeSystem()) { clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); clang::ObjCInterfaceDecl *super_interface_decl = GetAsObjCInterfaceDecl(superclass_clang_type); if (class_interface_decl && super_interface_decl) { class_interface_decl->setSuperClass(clang_ast.getTrivialTypeSourceInfo( clang_ast.getObjCInterfaceType(super_interface_decl))); return true; } } return false; } bool TypeSystemClang::AddObjCClassProperty( const CompilerType &type, const char *property_name, const CompilerType &property_clang_type, clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name, const char *property_getter_name, uint32_t property_attributes, ClangASTMetadata *metadata) { if (!type || !property_clang_type.IsValid() || property_name == nullptr || property_name[0] == '\0') return false; TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (!ast) return false; clang::ASTContext &clang_ast = ast->getASTContext(); clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); if (!class_interface_decl) return false; CompilerType property_clang_type_to_access; if (property_clang_type.IsValid()) property_clang_type_to_access = property_clang_type; else if (ivar_decl) property_clang_type_to_access = ast->GetType(ivar_decl->getType()); if (!class_interface_decl || !property_clang_type_to_access.IsValid()) return false; clang::TypeSourceInfo *prop_type_source; if (ivar_decl) prop_type_source = clang_ast.getTrivialTypeSourceInfo(ivar_decl->getType()); else prop_type_source = clang_ast.getTrivialTypeSourceInfo( ClangUtil::GetQualType(property_clang_type)); clang::ObjCPropertyDecl *property_decl = clang::ObjCPropertyDecl::CreateDeserialized(clang_ast, 0); property_decl->setDeclContext(class_interface_decl); property_decl->setDeclName(&clang_ast.Idents.get(property_name)); property_decl->setType(ivar_decl ? ivar_decl->getType() : ClangUtil::GetQualType(property_clang_type), prop_type_source); SetMemberOwningModule(property_decl, class_interface_decl); if (!property_decl) return false; if (metadata) ast->SetMetadata(property_decl, *metadata); class_interface_decl->addDecl(property_decl); clang::Selector setter_sel, getter_sel; if (property_setter_name) { std::string property_setter_no_colon(property_setter_name, strlen(property_setter_name) - 1); clang::IdentifierInfo *setter_ident = &clang_ast.Idents.get(property_setter_no_colon); setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident); } else if (!(property_attributes & DW_APPLE_PROPERTY_readonly)) { std::string setter_sel_string("set"); setter_sel_string.push_back(::toupper(property_name[0])); setter_sel_string.append(&property_name[1]); clang::IdentifierInfo *setter_ident = &clang_ast.Idents.get(setter_sel_string); setter_sel = clang_ast.Selectors.getSelector(1, &setter_ident); } property_decl->setSetterName(setter_sel); property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_setter); if (property_getter_name != nullptr) { clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_getter_name); getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident); } else { clang::IdentifierInfo *getter_ident = &clang_ast.Idents.get(property_name); getter_sel = clang_ast.Selectors.getSelector(0, &getter_ident); } property_decl->setGetterName(getter_sel); property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_getter); if (ivar_decl) property_decl->setPropertyIvarDecl(ivar_decl); if (property_attributes & DW_APPLE_PROPERTY_readonly) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readonly); if (property_attributes & DW_APPLE_PROPERTY_readwrite) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_readwrite); if (property_attributes & DW_APPLE_PROPERTY_assign) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_assign); if (property_attributes & DW_APPLE_PROPERTY_retain) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_retain); if (property_attributes & DW_APPLE_PROPERTY_copy) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_copy); if (property_attributes & DW_APPLE_PROPERTY_nonatomic) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_nonatomic); if (property_attributes & ObjCPropertyAttribute::kind_nullability) property_decl->setPropertyAttributes( ObjCPropertyAttribute::kind_nullability); if (property_attributes & ObjCPropertyAttribute::kind_null_resettable) property_decl->setPropertyAttributes( ObjCPropertyAttribute::kind_null_resettable); if (property_attributes & ObjCPropertyAttribute::kind_class) property_decl->setPropertyAttributes(ObjCPropertyAttribute::kind_class); const bool isInstance = (property_attributes & ObjCPropertyAttribute::kind_class) == 0; clang::ObjCMethodDecl *getter = nullptr; if (!getter_sel.isNull()) getter = isInstance ? class_interface_decl->lookupInstanceMethod(getter_sel) : class_interface_decl->lookupClassMethod(getter_sel); if (!getter_sel.isNull() && !getter) { const bool isVariadic = false; const bool isPropertyAccessor = true; const bool isSynthesizedAccessorStub = false; const bool isImplicitlyDeclared = true; const bool isDefined = false; const clang::ObjCMethodDecl::ImplementationControl impControl = clang::ObjCMethodDecl::None; const bool HasRelatedResultType = false; getter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0); getter->setDeclName(getter_sel); getter->setReturnType(ClangUtil::GetQualType(property_clang_type_to_access)); getter->setDeclContext(class_interface_decl); getter->setInstanceMethod(isInstance); getter->setVariadic(isVariadic); getter->setPropertyAccessor(isPropertyAccessor); getter->setSynthesizedAccessorStub(isSynthesizedAccessorStub); getter->setImplicit(isImplicitlyDeclared); getter->setDefined(isDefined); getter->setDeclImplementation(impControl); getter->setRelatedResultType(HasRelatedResultType); SetMemberOwningModule(getter, class_interface_decl); if (getter) { if (metadata) ast->SetMetadata(getter, *metadata); getter->setMethodParams(clang_ast, llvm::ArrayRef(), llvm::ArrayRef()); class_interface_decl->addDecl(getter); } } if (getter) { getter->setPropertyAccessor(true); property_decl->setGetterMethodDecl(getter); } clang::ObjCMethodDecl *setter = nullptr; setter = isInstance ? class_interface_decl->lookupInstanceMethod(setter_sel) : class_interface_decl->lookupClassMethod(setter_sel); if (!setter_sel.isNull() && !setter) { clang::QualType result_type = clang_ast.VoidTy; const bool isVariadic = false; const bool isPropertyAccessor = true; const bool isSynthesizedAccessorStub = false; const bool isImplicitlyDeclared = true; const bool isDefined = false; const clang::ObjCMethodDecl::ImplementationControl impControl = clang::ObjCMethodDecl::None; const bool HasRelatedResultType = false; setter = clang::ObjCMethodDecl::CreateDeserialized(clang_ast, 0); setter->setDeclName(setter_sel); setter->setReturnType(result_type); setter->setDeclContext(class_interface_decl); setter->setInstanceMethod(isInstance); setter->setVariadic(isVariadic); setter->setPropertyAccessor(isPropertyAccessor); setter->setSynthesizedAccessorStub(isSynthesizedAccessorStub); setter->setImplicit(isImplicitlyDeclared); setter->setDefined(isDefined); setter->setDeclImplementation(impControl); setter->setRelatedResultType(HasRelatedResultType); SetMemberOwningModule(setter, class_interface_decl); if (setter) { if (metadata) ast->SetMetadata(setter, *metadata); llvm::SmallVector params; params.push_back(clang::ParmVarDecl::Create( clang_ast, setter, clang::SourceLocation(), clang::SourceLocation(), nullptr, // anonymous ClangUtil::GetQualType(property_clang_type_to_access), nullptr, clang::SC_Auto, nullptr)); setter->setMethodParams(clang_ast, llvm::ArrayRef(params), llvm::ArrayRef()); class_interface_decl->addDecl(setter); } } if (setter) { setter->setPropertyAccessor(true); property_decl->setSetterMethodDecl(setter); } return true; } bool TypeSystemClang::IsObjCClassTypeAndHasIVars(const CompilerType &type, bool check_superclass) { clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); if (class_interface_decl) return ObjCDeclHasIVars(class_interface_decl, check_superclass); return false; } clang::ObjCMethodDecl *TypeSystemClang::AddMethodToObjCObjectType( const CompilerType &type, const char *name, // the full symbol name as seen in the symbol table // (lldb::opaque_compiler_type_t type, "-[NString // stringWithCString:]") const CompilerType &method_clang_type, lldb::AccessType access, bool is_artificial, bool is_variadic, bool is_objc_direct_call) { if (!type || !method_clang_type.IsValid()) return nullptr; clang::ObjCInterfaceDecl *class_interface_decl = GetAsObjCInterfaceDecl(type); if (class_interface_decl == nullptr) return nullptr; TypeSystemClang *lldb_ast = llvm::dyn_cast(type.GetTypeSystem()); if (lldb_ast == nullptr) return nullptr; clang::ASTContext &ast = lldb_ast->getASTContext(); const char *selector_start = ::strchr(name, ' '); if (selector_start == nullptr) return nullptr; selector_start++; llvm::SmallVector selector_idents; size_t len = 0; const char *start; unsigned num_selectors_with_args = 0; for (start = selector_start; start && *start != '\0' && *start != ']'; start += len) { len = ::strcspn(start, ":]"); bool has_arg = (start[len] == ':'); if (has_arg) ++num_selectors_with_args; selector_idents.push_back(&ast.Idents.get(llvm::StringRef(start, len))); if (has_arg) len += 1; } if (selector_idents.size() == 0) return nullptr; clang::Selector method_selector = ast.Selectors.getSelector( num_selectors_with_args ? selector_idents.size() : 0, selector_idents.data()); clang::QualType method_qual_type(ClangUtil::GetQualType(method_clang_type)); // Populate the method decl with parameter decls const clang::Type *method_type(method_qual_type.getTypePtr()); if (method_type == nullptr) return nullptr; const clang::FunctionProtoType *method_function_prototype( llvm::dyn_cast(method_type)); if (!method_function_prototype) return nullptr; const bool isInstance = (name[0] == '-'); const bool isVariadic = is_variadic; const bool isPropertyAccessor = false; const bool isSynthesizedAccessorStub = false; /// Force this to true because we don't have source locations. const bool isImplicitlyDeclared = true; const bool isDefined = false; const clang::ObjCMethodDecl::ImplementationControl impControl = clang::ObjCMethodDecl::None; const bool HasRelatedResultType = false; const unsigned num_args = method_function_prototype->getNumParams(); if (num_args != num_selectors_with_args) return nullptr; // some debug information is corrupt. We are not going to // deal with it. auto *objc_method_decl = clang::ObjCMethodDecl::CreateDeserialized(ast, 0); objc_method_decl->setDeclName(method_selector); objc_method_decl->setReturnType(method_function_prototype->getReturnType()); objc_method_decl->setDeclContext( lldb_ast->GetDeclContextForType(ClangUtil::GetQualType(type))); objc_method_decl->setInstanceMethod(isInstance); objc_method_decl->setVariadic(isVariadic); objc_method_decl->setPropertyAccessor(isPropertyAccessor); objc_method_decl->setSynthesizedAccessorStub(isSynthesizedAccessorStub); objc_method_decl->setImplicit(isImplicitlyDeclared); objc_method_decl->setDefined(isDefined); objc_method_decl->setDeclImplementation(impControl); objc_method_decl->setRelatedResultType(HasRelatedResultType); SetMemberOwningModule(objc_method_decl, class_interface_decl); if (objc_method_decl == nullptr) return nullptr; if (num_args > 0) { llvm::SmallVector params; for (unsigned param_index = 0; param_index < num_args; ++param_index) { params.push_back(clang::ParmVarDecl::Create( ast, objc_method_decl, clang::SourceLocation(), clang::SourceLocation(), nullptr, // anonymous method_function_prototype->getParamType(param_index), nullptr, clang::SC_Auto, nullptr)); } objc_method_decl->setMethodParams( ast, llvm::ArrayRef(params), llvm::ArrayRef()); } if (is_objc_direct_call) { // Add a the objc_direct attribute to the declaration we generate that // we generate a direct method call for this ObjCMethodDecl. objc_method_decl->addAttr( clang::ObjCDirectAttr::CreateImplicit(ast, SourceLocation())); // Usually Sema is creating implicit parameters (e.g., self) when it // parses the method. We don't have a parsing Sema when we build our own // AST here so we manually need to create these implicit parameters to // make the direct call code generation happy. objc_method_decl->createImplicitParams(ast, class_interface_decl); } class_interface_decl->addDecl(objc_method_decl); VerifyDecl(objc_method_decl); return objc_method_decl; } bool TypeSystemClang::SetHasExternalStorage(lldb::opaque_compiler_type_t type, bool has_extern) { if (!type) return false; clang::QualType qual_type(RemoveWrappingTypes(GetCanonicalQualType(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: { clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) { cxx_record_decl->setHasExternalLexicalStorage(has_extern); cxx_record_decl->setHasExternalVisibleStorage(has_extern); return true; } } break; case clang::Type::Enum: { clang::EnumDecl *enum_decl = llvm::cast(qual_type)->getDecl(); if (enum_decl) { enum_decl->setHasExternalLexicalStorage(has_extern); enum_decl->setHasExternalVisibleStorage(has_extern); return true; } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (class_interface_decl) { class_interface_decl->setHasExternalLexicalStorage(has_extern); class_interface_decl->setHasExternalVisibleStorage(has_extern); return true; } } } break; default: break; } return false; } #pragma mark TagDecl bool TypeSystemClang::StartTagDeclarationDefinition(const CompilerType &type) { clang::QualType qual_type(ClangUtil::GetQualType(type)); if (!qual_type.isNull()) { const clang::TagType *tag_type = qual_type->getAs(); if (tag_type) { clang::TagDecl *tag_decl = tag_type->getDecl(); if (tag_decl) { tag_decl->startDefinition(); return true; } } const clang::ObjCObjectType *object_type = qual_type->getAs(); if (object_type) { clang::ObjCInterfaceDecl *interface_decl = object_type->getInterface(); if (interface_decl) { interface_decl->startDefinition(); return true; } } } return false; } bool TypeSystemClang::CompleteTagDeclarationDefinition( const CompilerType &type) { clang::QualType qual_type(ClangUtil::GetQualType(type)); if (qual_type.isNull()) return false; // Make sure we use the same methodology as // TypeSystemClang::StartTagDeclarationDefinition() as to how we start/end // the definition. const clang::TagType *tag_type = qual_type->getAs(); if (tag_type) { clang::TagDecl *tag_decl = tag_type->getDecl(); if (auto *cxx_record_decl = llvm::dyn_cast(tag_decl)) { // If we have a move constructor declared but no copy constructor we // need to explicitly mark it as deleted. Usually Sema would do this for // us in Sema::DeclareImplicitCopyConstructor but we don't have a Sema // when building an AST from debug information. // See also: // C++11 [class.copy]p7, p18: // If the class definition declares a move constructor or move assignment // operator, an implicitly declared copy constructor or copy assignment // operator is defined as deleted. if (cxx_record_decl->hasUserDeclaredMoveConstructor() || cxx_record_decl->hasUserDeclaredMoveAssignment()) { if (cxx_record_decl->needsImplicitCopyConstructor()) cxx_record_decl->setImplicitCopyConstructorIsDeleted(); if (cxx_record_decl->needsImplicitCopyAssignment()) cxx_record_decl->setImplicitCopyAssignmentIsDeleted(); } if (!cxx_record_decl->isCompleteDefinition()) cxx_record_decl->completeDefinition(); cxx_record_decl->setHasLoadedFieldsFromExternalStorage(true); cxx_record_decl->setHasExternalLexicalStorage(false); cxx_record_decl->setHasExternalVisibleStorage(false); return true; } } const clang::EnumType *enutype = qual_type->getAs(); if (!enutype) return false; clang::EnumDecl *enum_decl = enutype->getDecl(); if (enum_decl->isCompleteDefinition()) return true; TypeSystemClang *lldb_ast = llvm::dyn_cast(type.GetTypeSystem()); if (lldb_ast == nullptr) return false; clang::ASTContext &ast = lldb_ast->getASTContext(); /// TODO This really needs to be fixed. QualType integer_type(enum_decl->getIntegerType()); if (!integer_type.isNull()) { unsigned NumPositiveBits = 1; unsigned NumNegativeBits = 0; clang::QualType promotion_qual_type; // If the enum integer type is less than an integer in bit width, // then we must promote it to an integer size. if (ast.getTypeSize(enum_decl->getIntegerType()) < ast.getTypeSize(ast.IntTy)) { if (enum_decl->getIntegerType()->isSignedIntegerType()) promotion_qual_type = ast.IntTy; else promotion_qual_type = ast.UnsignedIntTy; } else promotion_qual_type = enum_decl->getIntegerType(); enum_decl->completeDefinition(enum_decl->getIntegerType(), promotion_qual_type, NumPositiveBits, NumNegativeBits); } return true; } clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType( const CompilerType &enum_type, const Declaration &decl, const char *name, const llvm::APSInt &value) { if (!enum_type || ConstString(name).IsEmpty()) return nullptr; lldbassert(enum_type.GetTypeSystem() == static_cast(this)); lldb::opaque_compiler_type_t enum_opaque_compiler_type = enum_type.GetOpaqueQualType(); if (!enum_opaque_compiler_type) return nullptr; clang::QualType enum_qual_type( GetCanonicalQualType(enum_opaque_compiler_type)); const clang::Type *clang_type = enum_qual_type.getTypePtr(); if (!clang_type) return nullptr; const clang::EnumType *enutype = llvm::dyn_cast(clang_type); if (!enutype) return nullptr; clang::EnumConstantDecl *enumerator_decl = clang::EnumConstantDecl::CreateDeserialized(getASTContext(), 0); enumerator_decl->setDeclContext(enutype->getDecl()); if (name && name[0]) enumerator_decl->setDeclName(&getASTContext().Idents.get(name)); enumerator_decl->setType(clang::QualType(enutype, 0)); enumerator_decl->setInitVal(value); SetMemberOwningModule(enumerator_decl, enutype->getDecl()); if (!enumerator_decl) return nullptr; enutype->getDecl()->addDecl(enumerator_decl); VerifyDecl(enumerator_decl); return enumerator_decl; } clang::EnumConstantDecl *TypeSystemClang::AddEnumerationValueToEnumerationType( const CompilerType &enum_type, const Declaration &decl, const char *name, int64_t enum_value, uint32_t enum_value_bit_size) { CompilerType underlying_type = GetEnumerationIntegerType(enum_type); bool is_signed = false; underlying_type.IsIntegerType(is_signed); llvm::APSInt value(enum_value_bit_size, is_signed); value = enum_value; return AddEnumerationValueToEnumerationType(enum_type, decl, name, value); } CompilerType TypeSystemClang::GetEnumerationIntegerType(CompilerType type) { clang::QualType qt(ClangUtil::GetQualType(type)); const clang::Type *clang_type = qt.getTypePtrOrNull(); const auto *enum_type = llvm::dyn_cast_or_null(clang_type); if (!enum_type) return CompilerType(); return GetType(enum_type->getDecl()->getIntegerType()); } CompilerType TypeSystemClang::CreateMemberPointerType(const CompilerType &type, const CompilerType &pointee_type) { if (type && pointee_type.IsValid() && type.GetTypeSystem() == pointee_type.GetTypeSystem()) { TypeSystemClang *ast = llvm::dyn_cast(type.GetTypeSystem()); if (!ast) return CompilerType(); return ast->GetType(ast->getASTContext().getMemberPointerType( ClangUtil::GetQualType(pointee_type), ClangUtil::GetQualType(type).getTypePtr())); } return CompilerType(); } // Dumping types #define DEPTH_INCREMENT 2 #ifndef NDEBUG LLVM_DUMP_METHOD void TypeSystemClang::dump(lldb::opaque_compiler_type_t type) const { if (!type) return; clang::QualType qual_type(GetQualType(type)); qual_type.dump(); } #endif void TypeSystemClang::Dump(Stream &s) { Decl *tu = Decl::castFromDeclContext(GetTranslationUnitDecl()); tu->dump(s.AsRawOstream()); } void TypeSystemClang::DumpFromSymbolFile(Stream &s, llvm::StringRef symbol_name) { SymbolFile *symfile = GetSymbolFile(); if (!symfile) return; lldb_private::TypeList type_list; symfile->GetTypes(nullptr, eTypeClassAny, type_list); size_t ntypes = type_list.GetSize(); for (size_t i = 0; i < ntypes; ++i) { TypeSP type = type_list.GetTypeAtIndex(i); if (!symbol_name.empty()) if (symbol_name != type->GetName().GetStringRef()) continue; s << type->GetName().AsCString() << "\n"; CompilerType full_type = type->GetFullCompilerType(); if (clang::TagDecl *tag_decl = GetAsTagDecl(full_type)) { tag_decl->dump(s.AsRawOstream()); continue; } if (clang::TypedefNameDecl *typedef_decl = GetAsTypedefDecl(full_type)) { typedef_decl->dump(s.AsRawOstream()); continue; } if (auto *objc_obj = llvm::dyn_cast( ClangUtil::GetQualType(full_type).getTypePtr())) { if (clang::ObjCInterfaceDecl *interface_decl = objc_obj->getInterface()) { interface_decl->dump(s.AsRawOstream()); continue; } } GetCanonicalQualType(full_type.GetOpaqueQualType()) .dump(s.AsRawOstream(), getASTContext()); } } void TypeSystemClang::DumpValue( lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s, lldb::Format format, const lldb_private::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) { if (!type) return; clang::QualType qual_type(GetQualType(type)); switch (qual_type->getTypeClass()) { case clang::Type::Record: if (GetCompleteType(type)) { const clang::RecordType *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); assert(record_decl); uint32_t field_bit_offset = 0; uint32_t field_byte_offset = 0; const clang::ASTRecordLayout &record_layout = getASTContext().getASTRecordLayout(record_decl); uint32_t child_idx = 0; const clang::CXXRecordDecl *cxx_record_decl = llvm::dyn_cast(record_decl); if (cxx_record_decl) { // We might have base classes to print out first clang::CXXRecordDecl::base_class_const_iterator base_class, base_class_end; for (base_class = cxx_record_decl->bases_begin(), base_class_end = cxx_record_decl->bases_end(); base_class != base_class_end; ++base_class) { const clang::CXXRecordDecl *base_class_decl = llvm::cast( base_class->getType()->getAs()->getDecl()); // Skip empty base classes if (!verbose && !TypeSystemClang::RecordHasFields(base_class_decl)) continue; if (base_class->isVirtual()) field_bit_offset = record_layout.getVBaseClassOffset(base_class_decl) .getQuantity() * 8; else field_bit_offset = record_layout.getBaseClassOffset(base_class_decl) .getQuantity() * 8; field_byte_offset = field_bit_offset / 8; assert(field_bit_offset % 8 == 0); if (child_idx == 0) s->PutChar('{'); else s->PutChar(','); clang::QualType base_class_qual_type = base_class->getType(); std::string base_class_type_name(base_class_qual_type.getAsString()); // Indent and print the base class type name s->Format("\n{0}{1}", llvm::fmt_repeat(" ", depth + DEPTH_INCREMENT), base_class_type_name); clang::TypeInfo base_class_type_info = getASTContext().getTypeInfo(base_class_qual_type); // Dump the value of the member CompilerType base_clang_type = GetType(base_class_qual_type); base_clang_type.DumpValue( exe_ctx, s, // Stream to dump to base_clang_type .GetFormat(), // The format with which to display the member data, // Data buffer containing all bytes for this type data_byte_offset + field_byte_offset, // Offset into "data" where // to grab value from base_class_type_info.Width / 8, // Size of this type in bytes 0, // Bitfield bit size 0, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable // types show_summary, // Boolean indicating if we should show a summary // for the current type verbose, // Verbose output? depth + DEPTH_INCREMENT); // Scope depth for any types that have // children ++child_idx; } } uint32_t field_idx = 0; clang::RecordDecl::field_iterator field, field_end; for (field = record_decl->field_begin(), field_end = record_decl->field_end(); field != field_end; ++field, ++field_idx, ++child_idx) { // Print the starting squiggly bracket (if this is the first member) or // comma (for member 2 and beyond) for the struct/union/class member. if (child_idx == 0) s->PutChar('{'); else s->PutChar(','); // Indent s->Printf("\n%*s", depth + DEPTH_INCREMENT, ""); clang::QualType field_type = field->getType(); // Print the member type if requested // Figure out the type byte size (field_type_info.first) and alignment // (field_type_info.second) from the AST context. clang::TypeInfo field_type_info = getASTContext().getTypeInfo(field_type); assert(field_idx < record_layout.getFieldCount()); // Figure out the field offset within the current struct/union/class // type field_bit_offset = record_layout.getFieldOffset(field_idx); field_byte_offset = field_bit_offset / 8; uint32_t field_bitfield_bit_size = 0; uint32_t field_bitfield_bit_offset = 0; if (FieldIsBitfield(*field, field_bitfield_bit_size)) field_bitfield_bit_offset = field_bit_offset % 8; if (show_types) { std::string field_type_name(field_type.getAsString()); if (field_bitfield_bit_size > 0) s->Printf("(%s:%u) ", field_type_name.c_str(), field_bitfield_bit_size); else s->Printf("(%s) ", field_type_name.c_str()); } // Print the member name and equal sign s->Printf("%s = ", field->getNameAsString().c_str()); // Dump the value of the member CompilerType field_clang_type = GetType(field_type); field_clang_type.DumpValue( exe_ctx, s, // Stream to dump to field_clang_type .GetFormat(), // The format with which to display the member data, // Data buffer containing all bytes for this type data_byte_offset + field_byte_offset, // Offset into "data" where to // grab value from field_type_info.Width / 8, // Size of this type in bytes field_bitfield_bit_size, // Bitfield bit size field_bitfield_bit_offset, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable // types show_summary, // Boolean indicating if we should show a summary for // the current type verbose, // Verbose output? depth + DEPTH_INCREMENT); // Scope depth for any types that have // children } // Indent the trailing squiggly bracket if (child_idx > 0) s->Printf("\n%*s}", depth, ""); } return; case clang::Type::Enum: if (GetCompleteType(type)) { const clang::EnumType *enutype = llvm::cast(qual_type.getTypePtr()); const clang::EnumDecl *enum_decl = enutype->getDecl(); assert(enum_decl); clang::EnumDecl::enumerator_iterator enum_pos, enum_end_pos; lldb::offset_t offset = data_byte_offset; const int64_t enum_value = data.GetMaxU64Bitfield( &offset, data_byte_size, bitfield_bit_size, bitfield_bit_offset); for (enum_pos = enum_decl->enumerator_begin(), enum_end_pos = enum_decl->enumerator_end(); enum_pos != enum_end_pos; ++enum_pos) { if (enum_pos->getInitVal() == enum_value) { s->Printf("%s", enum_pos->getNameAsString().c_str()); return; } } // If we have gotten here we didn't get find the enumerator in the enum // decl, so just print the integer. s->Printf("%" PRIi64, enum_value); } return; case clang::Type::ConstantArray: { const clang::ConstantArrayType *array = llvm::cast(qual_type.getTypePtr()); bool is_array_of_characters = false; clang::QualType element_qual_type = array->getElementType(); const clang::Type *canonical_type = element_qual_type->getCanonicalTypeInternal().getTypePtr(); if (canonical_type) is_array_of_characters = canonical_type->isCharType(); const uint64_t element_count = array->getSize().getLimitedValue(); clang::TypeInfo field_type_info = getASTContext().getTypeInfo(element_qual_type); uint32_t element_idx = 0; uint32_t element_offset = 0; uint64_t element_byte_size = field_type_info.Width / 8; uint32_t element_stride = element_byte_size; if (is_array_of_characters) { s->PutChar('"'); DumpDataExtractor(data, s, data_byte_offset, lldb::eFormatChar, element_byte_size, element_count, UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0); s->PutChar('"'); return; } else { CompilerType element_clang_type = GetType(element_qual_type); lldb::Format element_format = element_clang_type.GetFormat(); for (element_idx = 0; element_idx < element_count; ++element_idx) { // Print the starting squiggly bracket (if this is the first member) or // comman (for member 2 and beyong) for the struct/union/class member. if (element_idx == 0) s->PutChar('{'); else s->PutChar(','); // Indent and print the index s->Printf("\n%*s[%u] ", depth + DEPTH_INCREMENT, "", element_idx); // Figure out the field offset within the current struct/union/class // type element_offset = element_idx * element_stride; // Dump the value of the member element_clang_type.DumpValue( exe_ctx, s, // Stream to dump to element_format, // The format with which to display the element data, // Data buffer containing all bytes for this type data_byte_offset + element_offset, // Offset into "data" where to grab value from element_byte_size, // Size of this type in bytes 0, // Bitfield bit size 0, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable // types show_summary, // Boolean indicating if we should show a summary for // the current type verbose, // Verbose output? depth + DEPTH_INCREMENT); // Scope depth for any types that have // children } // Indent the trailing squiggly bracket if (element_idx > 0) s->Printf("\n%*s}", depth, ""); } } return; case clang::Type::Typedef: { clang::QualType typedef_qual_type = llvm::cast(qual_type) ->getDecl() ->getUnderlyingType(); CompilerType typedef_clang_type = GetType(typedef_qual_type); lldb::Format typedef_format = typedef_clang_type.GetFormat(); clang::TypeInfo typedef_type_info = getASTContext().getTypeInfo(typedef_qual_type); uint64_t typedef_byte_size = typedef_type_info.Width / 8; return typedef_clang_type.DumpValue( exe_ctx, s, // Stream to dump to typedef_format, // The format with which to display the element data, // Data buffer containing all bytes for this type data_byte_offset, // Offset into "data" where to grab value from typedef_byte_size, // Size of this type in bytes bitfield_bit_size, // Bitfield bit size bitfield_bit_offset, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable types show_summary, // Boolean indicating if we should show a summary for the // current type verbose, // Verbose output? depth); // Scope depth for any types that have children } break; case clang::Type::Auto: { clang::QualType elaborated_qual_type = llvm::cast(qual_type)->getDeducedType(); CompilerType elaborated_clang_type = GetType(elaborated_qual_type); lldb::Format elaborated_format = elaborated_clang_type.GetFormat(); clang::TypeInfo elaborated_type_info = getASTContext().getTypeInfo(elaborated_qual_type); uint64_t elaborated_byte_size = elaborated_type_info.Width / 8; return elaborated_clang_type.DumpValue( exe_ctx, s, // Stream to dump to elaborated_format, // The format with which to display the element data, // Data buffer containing all bytes for this type data_byte_offset, // Offset into "data" where to grab value from elaborated_byte_size, // Size of this type in bytes bitfield_bit_size, // Bitfield bit size bitfield_bit_offset, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable types show_summary, // Boolean indicating if we should show a summary for the // current type verbose, // Verbose output? depth); // Scope depth for any types that have children } break; case clang::Type::Elaborated: { clang::QualType elaborated_qual_type = llvm::cast(qual_type)->getNamedType(); CompilerType elaborated_clang_type = GetType(elaborated_qual_type); lldb::Format elaborated_format = elaborated_clang_type.GetFormat(); clang::TypeInfo elaborated_type_info = getASTContext().getTypeInfo(elaborated_qual_type); uint64_t elaborated_byte_size = elaborated_type_info.Width / 8; return elaborated_clang_type.DumpValue( exe_ctx, s, // Stream to dump to elaborated_format, // The format with which to display the element data, // Data buffer containing all bytes for this type data_byte_offset, // Offset into "data" where to grab value from elaborated_byte_size, // Size of this type in bytes bitfield_bit_size, // Bitfield bit size bitfield_bit_offset, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable types show_summary, // Boolean indicating if we should show a summary for the // current type verbose, // Verbose output? depth); // Scope depth for any types that have children } break; case clang::Type::Paren: { clang::QualType desugar_qual_type = llvm::cast(qual_type)->desugar(); CompilerType desugar_clang_type = GetType(desugar_qual_type); lldb::Format desugar_format = desugar_clang_type.GetFormat(); clang::TypeInfo desugar_type_info = getASTContext().getTypeInfo(desugar_qual_type); uint64_t desugar_byte_size = desugar_type_info.Width / 8; return desugar_clang_type.DumpValue( exe_ctx, s, // Stream to dump to desugar_format, // The format with which to display the element data, // Data buffer containing all bytes for this type data_byte_offset, // Offset into "data" where to grab value from desugar_byte_size, // Size of this type in bytes bitfield_bit_size, // Bitfield bit size bitfield_bit_offset, // Bitfield bit offset show_types, // Boolean indicating if we should show the variable types show_summary, // Boolean indicating if we should show a summary for the // current type verbose, // Verbose output? depth); // Scope depth for any types that have children } break; default: // We are down to a scalar type that we just need to display. DumpDataExtractor(data, s, data_byte_offset, format, data_byte_size, 1, UINT32_MAX, LLDB_INVALID_ADDRESS, bitfield_bit_size, bitfield_bit_offset); if (show_summary) DumpSummary(type, exe_ctx, s, data, data_byte_offset, data_byte_size); break; } } static bool DumpEnumValue(const clang::QualType &qual_type, Stream *s, const DataExtractor &data, lldb::offset_t byte_offset, size_t byte_size, uint32_t bitfield_bit_offset, uint32_t bitfield_bit_size) { const clang::EnumType *enutype = llvm::cast(qual_type.getTypePtr()); const clang::EnumDecl *enum_decl = enutype->getDecl(); assert(enum_decl); lldb::offset_t offset = byte_offset; const uint64_t enum_svalue = data.GetMaxS64Bitfield( &offset, byte_size, bitfield_bit_size, bitfield_bit_offset); bool can_be_bitfield = true; uint64_t covered_bits = 0; int num_enumerators = 0; // Try to find an exact match for the value. // At the same time, we're applying a heuristic to determine whether we want // to print this enum as a bitfield. We're likely dealing with a bitfield if // every enumerator is either a one bit value or a superset of the previous // enumerators. Also 0 doesn't make sense when the enumerators are used as // flags. for (auto *enumerator : enum_decl->enumerators()) { uint64_t val = enumerator->getInitVal().getSExtValue(); val = llvm::SignExtend64(val, 8*byte_size); if (llvm::countPopulation(val) != 1 && (val & ~covered_bits) != 0) can_be_bitfield = false; covered_bits |= val; ++num_enumerators; if (val == enum_svalue) { // Found an exact match, that's all we need to do. s->PutCString(enumerator->getNameAsString()); return true; } } // Unsigned values make more sense for flags. offset = byte_offset; const uint64_t enum_uvalue = data.GetMaxU64Bitfield( &offset, byte_size, bitfield_bit_size, bitfield_bit_offset); // No exact match, but we don't think this is a bitfield. Print the value as // decimal. if (!can_be_bitfield) { if (qual_type->isSignedIntegerOrEnumerationType()) s->Printf("%" PRIi64, enum_svalue); else s->Printf("%" PRIu64, enum_uvalue); return true; } uint64_t remaining_value = enum_uvalue; std::vector> values; values.reserve(num_enumerators); for (auto *enumerator : enum_decl->enumerators()) if (auto val = enumerator->getInitVal().getZExtValue()) values.emplace_back(val, enumerator->getName()); // Sort in reverse order of the number of the population count, so that in // `enum {A, B, ALL = A|B }` we visit ALL first. Use a stable sort so that // A | C where A is declared before C is displayed in this order. std::stable_sort(values.begin(), values.end(), [](const auto &a, const auto &b) { return llvm::countPopulation(a.first) > llvm::countPopulation(b.first); }); for (const auto &val : values) { if ((remaining_value & val.first) != val.first) continue; remaining_value &= ~val.first; s->PutCString(val.second); if (remaining_value) s->PutCString(" | "); } // If there is a remainder that is not covered by the value, print it as hex. if (remaining_value) s->Printf("0x%" PRIx64, remaining_value); return true; } bool TypeSystemClang::DumpTypeValue( lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format, const lldb_private::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 { clang::QualType qual_type(GetQualType(type)); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); if (type_class == clang::Type::Elaborated) { qual_type = llvm::cast(qual_type)->getNamedType(); return DumpTypeValue(qual_type.getAsOpaquePtr(), s, format, data, byte_offset, byte_size, bitfield_bit_size, bitfield_bit_offset, exe_scope); } switch (type_class) { case clang::Type::Typedef: { clang::QualType typedef_qual_type = llvm::cast(qual_type) ->getDecl() ->getUnderlyingType(); CompilerType typedef_clang_type = GetType(typedef_qual_type); if (format == eFormatDefault) format = typedef_clang_type.GetFormat(); clang::TypeInfo typedef_type_info = getASTContext().getTypeInfo(typedef_qual_type); uint64_t typedef_byte_size = typedef_type_info.Width / 8; return typedef_clang_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); } break; case clang::Type::Enum: // If our format is enum or default, show the enumeration value as its // enumeration string value, else just display it as requested. if ((format == eFormatEnum || format == eFormatDefault) && GetCompleteType(type)) return DumpEnumValue(qual_type, s, data, byte_offset, byte_size, bitfield_bit_offset, bitfield_bit_size); // format was not enum, just fall through and dump the value as // requested.... LLVM_FALLTHROUGH; default: // We are down to a scalar type that we just need to display. { uint32_t item_count = 1; // A few formats, we might need to modify our size and count for // depending // on how we are trying to display the value... switch (format) { default: case eFormatBoolean: case eFormatBinary: case eFormatComplex: case eFormatCString: // NULL terminated C strings 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); } break; } } return false; } void TypeSystemClang::DumpSummary(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s, const lldb_private::DataExtractor &data, lldb::offset_t data_byte_offset, size_t data_byte_size) { uint32_t length = 0; if (IsCStringType(type, length)) { if (exe_ctx) { Process *process = exe_ctx->GetProcessPtr(); if (process) { lldb::offset_t offset = data_byte_offset; lldb::addr_t pointer_address = data.GetMaxU64(&offset, data_byte_size); std::vector buf; if (length > 0) buf.resize(length); else buf.resize(256); DataExtractor cstr_data(&buf.front(), buf.size(), process->GetByteOrder(), 4); buf.back() = '\0'; size_t bytes_read; size_t total_cstr_len = 0; Status error; while ((bytes_read = process->ReadMemory(pointer_address, &buf.front(), buf.size(), error)) > 0) { const size_t len = strlen((const char *)&buf.front()); if (len == 0) break; if (total_cstr_len == 0) s->PutCString(" \""); DumpDataExtractor(cstr_data, s, 0, lldb::eFormatChar, 1, len, UINT32_MAX, LLDB_INVALID_ADDRESS, 0, 0); total_cstr_len += len; if (len < buf.size()) break; pointer_address += total_cstr_len; } if (total_cstr_len > 0) s->PutChar('"'); } } } } void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type, lldb::DescriptionLevel level) { StreamFile s(stdout, false); DumpTypeDescription(type, &s, level); CompilerType ct(this, type); const clang::Type *clang_type = ClangUtil::GetQualType(ct).getTypePtr(); ClangASTMetadata *metadata = GetMetadata(clang_type); if (metadata) { metadata->Dump(&s); } } void TypeSystemClang::DumpTypeDescription(lldb::opaque_compiler_type_t type, Stream *s, lldb::DescriptionLevel level) { if (type) { clang::QualType qual_type = RemoveWrappingTypes(GetQualType(type), {clang::Type::Typedef}); llvm::SmallVector buf; llvm::raw_svector_ostream llvm_ostrm(buf); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::ObjCObject: case clang::Type::ObjCInterface: { GetCompleteType(type); auto *objc_class_type = llvm::dyn_cast(qual_type.getTypePtr()); assert(objc_class_type); if (!objc_class_type) break; clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); if (!class_interface_decl) break; if (level == eDescriptionLevelVerbose) class_interface_decl->dump(llvm_ostrm); else class_interface_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(), s->GetIndentLevel()); } break; case clang::Type::Typedef: { auto *typedef_type = qual_type->getAs(); if (!typedef_type) break; const clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl(); if (level == eDescriptionLevelVerbose) typedef_decl->dump(llvm_ostrm); else { std::string clang_typedef_name( typedef_decl->getQualifiedNameAsString()); if (!clang_typedef_name.empty()) { s->PutCString("typedef "); s->PutCString(clang_typedef_name); } } } break; case clang::Type::Record: { GetCompleteType(type); auto *record_type = llvm::cast(qual_type.getTypePtr()); const clang::RecordDecl *record_decl = record_type->getDecl(); if (level == eDescriptionLevelVerbose) record_decl->dump(llvm_ostrm); else { if (auto *cxx_record_decl = llvm::dyn_cast(record_decl)) cxx_record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(), s->GetIndentLevel()); else record_decl->print(llvm_ostrm, getASTContext().getPrintingPolicy(), s->GetIndentLevel()); } } break; default: { if (auto *tag_type = llvm::dyn_cast(qual_type.getTypePtr())) { if (clang::TagDecl *tag_decl = tag_type->getDecl()) { if (level == eDescriptionLevelVerbose) tag_decl->dump(llvm_ostrm); else tag_decl->print(llvm_ostrm, 0); } } else { if (level == eDescriptionLevelVerbose) qual_type->dump(llvm_ostrm, getASTContext()); else { std::string clang_type_name(qual_type.getAsString()); if (!clang_type_name.empty()) s->PutCString(clang_type_name); } } } } if (buf.size() > 0) { s->Write(buf.data(), buf.size()); } } } void TypeSystemClang::DumpTypeName(const CompilerType &type) { if (ClangUtil::IsClangType(type)) { clang::QualType qual_type( ClangUtil::GetCanonicalQualType(ClangUtil::RemoveFastQualifiers(type))); const clang::Type::TypeClass type_class = qual_type->getTypeClass(); switch (type_class) { case clang::Type::Record: { const clang::CXXRecordDecl *cxx_record_decl = qual_type->getAsCXXRecordDecl(); if (cxx_record_decl) printf("class %s", cxx_record_decl->getName().str().c_str()); } break; case clang::Type::Enum: { clang::EnumDecl *enum_decl = llvm::cast(qual_type)->getDecl(); if (enum_decl) { printf("enum %s", enum_decl->getName().str().c_str()); } } break; case clang::Type::ObjCObject: case clang::Type::ObjCInterface: { const clang::ObjCObjectType *objc_class_type = llvm::dyn_cast(qual_type); if (objc_class_type) { clang::ObjCInterfaceDecl *class_interface_decl = objc_class_type->getInterface(); // 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) printf("@class %s", class_interface_decl->getName().str().c_str()); } } break; case clang::Type::Typedef: printf("typedef %s", llvm::cast(qual_type) ->getDecl() ->getName() .str() .c_str()); break; case clang::Type::Auto: printf("auto "); return DumpTypeName(CompilerType(type.GetTypeSystem(), llvm::cast(qual_type) ->getDeducedType() .getAsOpaquePtr())); case clang::Type::Elaborated: printf("elaborated "); return DumpTypeName(CompilerType( type.GetTypeSystem(), llvm::cast(qual_type) ->getNamedType() .getAsOpaquePtr())); case clang::Type::Paren: printf("paren "); return DumpTypeName(CompilerType( type.GetTypeSystem(), llvm::cast(qual_type)->desugar().getAsOpaquePtr())); default: printf("TypeSystemClang::DumpTypeName() type_class = %u", type_class); break; } } } clang::ClassTemplateDecl *TypeSystemClang::ParseClassTemplateDecl( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, lldb::AccessType access_type, const char *parent_name, int tag_decl_kind, const TypeSystemClang::TemplateParameterInfos &template_param_infos) { if (template_param_infos.IsValid()) { std::string template_basename(parent_name); template_basename.erase(template_basename.find('<')); return CreateClassTemplateDecl(decl_ctx, owning_module, access_type, template_basename.c_str(), tag_decl_kind, template_param_infos); } return nullptr; } void TypeSystemClang::CompleteTagDecl(clang::TagDecl *decl) { SymbolFile *sym_file = GetSymbolFile(); if (sym_file) { CompilerType clang_type = GetTypeForDecl(decl); if (clang_type) sym_file->CompleteType(clang_type); } } void TypeSystemClang::CompleteObjCInterfaceDecl( clang::ObjCInterfaceDecl *decl) { SymbolFile *sym_file = GetSymbolFile(); if (sym_file) { CompilerType clang_type = GetTypeForDecl(decl); if (clang_type) sym_file->CompleteType(clang_type); } } DWARFASTParser *TypeSystemClang::GetDWARFParser() { if (!m_dwarf_ast_parser_up) m_dwarf_ast_parser_up = std::make_unique(*this); return m_dwarf_ast_parser_up.get(); } +#ifdef LLDB_ENABLE_ALL PDBASTParser *TypeSystemClang::GetPDBParser() { if (!m_pdb_ast_parser_up) m_pdb_ast_parser_up = std::make_unique(*this); return m_pdb_ast_parser_up.get(); } +#endif // LLDB_ENABLE_ALL bool TypeSystemClang::LayoutRecordType( const clang::RecordDecl *record_decl, uint64_t &bit_size, uint64_t &alignment, llvm::DenseMap &field_offsets, llvm::DenseMap &base_offsets, llvm::DenseMap &vbase_offsets) { lldb_private::ClangASTImporter *importer = nullptr; if (m_dwarf_ast_parser_up) importer = &m_dwarf_ast_parser_up->GetClangASTImporter(); +#ifdef LLDB_ENABLE_ALL if (!importer && m_pdb_ast_parser_up) importer = &m_pdb_ast_parser_up->GetClangASTImporter(); +#endif // LLDB_ENABLE_ALL if (!importer) return false; return importer->LayoutRecordType(record_decl, bit_size, alignment, field_offsets, base_offsets, vbase_offsets); } // CompilerDecl override functions ConstString TypeSystemClang::DeclGetName(void *opaque_decl) { if (opaque_decl) { clang::NamedDecl *nd = llvm::dyn_cast((clang::Decl *)opaque_decl); if (nd != nullptr) return ConstString(nd->getDeclName().getAsString()); } return ConstString(); } ConstString TypeSystemClang::DeclGetMangledName(void *opaque_decl) { if (opaque_decl) { clang::NamedDecl *nd = llvm::dyn_cast((clang::Decl *)opaque_decl); if (nd != nullptr && !llvm::isa(nd)) { clang::MangleContext *mc = getMangleContext(); if (mc && mc->shouldMangleCXXName(nd)) { llvm::SmallVector buf; llvm::raw_svector_ostream llvm_ostrm(buf); if (llvm::isa(nd)) { mc->mangleName( clang::GlobalDecl(llvm::dyn_cast(nd), Ctor_Complete), llvm_ostrm); } else if (llvm::isa(nd)) { mc->mangleName( clang::GlobalDecl(llvm::dyn_cast(nd), Dtor_Complete), llvm_ostrm); } else { mc->mangleName(nd, llvm_ostrm); } if (buf.size() > 0) return ConstString(buf.data(), buf.size()); } } } return ConstString(); } CompilerDeclContext TypeSystemClang::DeclGetDeclContext(void *opaque_decl) { if (opaque_decl) return CreateDeclContext(((clang::Decl *)opaque_decl)->getDeclContext()); return CompilerDeclContext(); } CompilerType TypeSystemClang::DeclGetFunctionReturnType(void *opaque_decl) { if (clang::FunctionDecl *func_decl = llvm::dyn_cast((clang::Decl *)opaque_decl)) return GetType(func_decl->getReturnType()); if (clang::ObjCMethodDecl *objc_method = llvm::dyn_cast((clang::Decl *)opaque_decl)) return GetType(objc_method->getReturnType()); else return CompilerType(); } size_t TypeSystemClang::DeclGetFunctionNumArguments(void *opaque_decl) { if (clang::FunctionDecl *func_decl = llvm::dyn_cast((clang::Decl *)opaque_decl)) return func_decl->param_size(); if (clang::ObjCMethodDecl *objc_method = llvm::dyn_cast((clang::Decl *)opaque_decl)) return objc_method->param_size(); else return 0; } CompilerType TypeSystemClang::DeclGetFunctionArgumentType(void *opaque_decl, size_t idx) { if (clang::FunctionDecl *func_decl = llvm::dyn_cast((clang::Decl *)opaque_decl)) { if (idx < func_decl->param_size()) { ParmVarDecl *var_decl = func_decl->getParamDecl(idx); if (var_decl) return GetType(var_decl->getOriginalType()); } } else if (clang::ObjCMethodDecl *objc_method = llvm::dyn_cast( (clang::Decl *)opaque_decl)) { if (idx < objc_method->param_size()) return GetType(objc_method->parameters()[idx]->getOriginalType()); } return CompilerType(); } // CompilerDeclContext functions std::vector TypeSystemClang::DeclContextFindDeclByName( void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) { std::vector found_decls; if (opaque_decl_ctx) { DeclContext *root_decl_ctx = (DeclContext *)opaque_decl_ctx; std::set searched; std::multimap search_queue; SymbolFile *symbol_file = GetSymbolFile(); for (clang::DeclContext *decl_context = root_decl_ctx; decl_context != nullptr && found_decls.empty(); decl_context = decl_context->getParent()) { search_queue.insert(std::make_pair(decl_context, decl_context)); for (auto it = search_queue.find(decl_context); it != search_queue.end(); it++) { if (!searched.insert(it->second).second) continue; symbol_file->ParseDeclsForContext( CreateDeclContext(it->second)); for (clang::Decl *child : it->second->decls()) { if (clang::UsingDirectiveDecl *ud = llvm::dyn_cast(child)) { if (ignore_using_decls) continue; clang::DeclContext *from = ud->getCommonAncestor(); if (searched.find(ud->getNominatedNamespace()) == searched.end()) search_queue.insert( std::make_pair(from, ud->getNominatedNamespace())); } else if (clang::UsingDecl *ud = llvm::dyn_cast(child)) { if (ignore_using_decls) continue; for (clang::UsingShadowDecl *usd : ud->shadows()) { clang::Decl *target = usd->getTargetDecl(); if (clang::NamedDecl *nd = llvm::dyn_cast(target)) { IdentifierInfo *ii = nd->getIdentifier(); if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr))) found_decls.push_back(GetCompilerDecl(nd)); } } } else if (clang::NamedDecl *nd = llvm::dyn_cast(child)) { IdentifierInfo *ii = nd->getIdentifier(); if (ii != nullptr && ii->getName().equals(name.AsCString(nullptr))) found_decls.push_back(GetCompilerDecl(nd)); } } } } } return found_decls; } // Look for child_decl_ctx's lookup scope in frame_decl_ctx and its parents, // and return the number of levels it took to find it, or // LLDB_INVALID_DECL_LEVEL if not found. If the decl was imported via a using // declaration, its name and/or type, if set, will be used to check that the // decl found in the scope is a match. // // The optional name is required by languages (like C++) to handle using // declarations like: // // void poo(); // namespace ns { // void foo(); // void goo(); // } // void bar() { // using ns::foo; // // CountDeclLevels returns 0 for 'foo', 1 for 'poo', and // // LLDB_INVALID_DECL_LEVEL for 'goo'. // } // // The optional type is useful in the case that there's a specific overload // that we're looking for that might otherwise be shadowed, like: // // void foo(int); // namespace ns { // void foo(); // } // void bar() { // using ns::foo; // // CountDeclLevels returns 0 for { 'foo', void() }, // // 1 for { 'foo', void(int) }, and // // LLDB_INVALID_DECL_LEVEL for { 'foo', void(int, int) }. // } // // NOTE: Because file statics are at the TranslationUnit along with globals, a // function at file scope will return the same level as a function at global // scope. Ideally we'd like to treat the file scope as an additional scope just // below the global scope. More work needs to be done to recognise that, if // the decl we're trying to look up is static, we should compare its source // file with that of the current scope and return a lower number for it. uint32_t TypeSystemClang::CountDeclLevels(clang::DeclContext *frame_decl_ctx, clang::DeclContext *child_decl_ctx, ConstString *child_name, CompilerType *child_type) { if (frame_decl_ctx) { std::set searched; std::multimap search_queue; SymbolFile *symbol_file = GetSymbolFile(); // Get the lookup scope for the decl we're trying to find. clang::DeclContext *parent_decl_ctx = child_decl_ctx->getParent(); // Look for it in our scope's decl context and its parents. uint32_t level = 0; for (clang::DeclContext *decl_ctx = frame_decl_ctx; decl_ctx != nullptr; decl_ctx = decl_ctx->getParent()) { if (!decl_ctx->isLookupContext()) continue; if (decl_ctx == parent_decl_ctx) // Found it! return level; search_queue.insert(std::make_pair(decl_ctx, decl_ctx)); for (auto it = search_queue.find(decl_ctx); it != search_queue.end(); it++) { if (searched.find(it->second) != searched.end()) continue; // Currently DWARF has one shared translation unit for all Decls at top // level, so this would erroneously find using statements anywhere. So // don't look at the top-level translation unit. // TODO fix this and add a testcase that depends on it. if (llvm::isa(it->second)) continue; searched.insert(it->second); symbol_file->ParseDeclsForContext( CreateDeclContext(it->second)); for (clang::Decl *child : it->second->decls()) { if (clang::UsingDirectiveDecl *ud = llvm::dyn_cast(child)) { clang::DeclContext *ns = ud->getNominatedNamespace(); if (ns == parent_decl_ctx) // Found it! return level; clang::DeclContext *from = ud->getCommonAncestor(); if (searched.find(ns) == searched.end()) search_queue.insert(std::make_pair(from, ns)); } else if (child_name) { if (clang::UsingDecl *ud = llvm::dyn_cast(child)) { for (clang::UsingShadowDecl *usd : ud->shadows()) { clang::Decl *target = usd->getTargetDecl(); clang::NamedDecl *nd = llvm::dyn_cast(target); if (!nd) continue; // Check names. IdentifierInfo *ii = nd->getIdentifier(); if (ii == nullptr || !ii->getName().equals(child_name->AsCString(nullptr))) continue; // Check types, if one was provided. if (child_type) { CompilerType clang_type = GetTypeForDecl(nd); if (!AreTypesSame(clang_type, *child_type, /*ignore_qualifiers=*/true)) continue; } // Found it! return level; } } } } } ++level; } } return LLDB_INVALID_DECL_LEVEL; } ConstString TypeSystemClang::DeclContextGetName(void *opaque_decl_ctx) { if (opaque_decl_ctx) { clang::NamedDecl *named_decl = llvm::dyn_cast((clang::DeclContext *)opaque_decl_ctx); if (named_decl) return ConstString(named_decl->getName()); } return ConstString(); } ConstString TypeSystemClang::DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) { if (opaque_decl_ctx) { clang::NamedDecl *named_decl = llvm::dyn_cast((clang::DeclContext *)opaque_decl_ctx); if (named_decl) return ConstString( llvm::StringRef(named_decl->getQualifiedNameAsString())); } return ConstString(); } bool TypeSystemClang::DeclContextIsClassMethod( void *opaque_decl_ctx, lldb::LanguageType *language_ptr, bool *is_instance_method_ptr, ConstString *language_object_name_ptr) { if (opaque_decl_ctx) { clang::DeclContext *decl_ctx = (clang::DeclContext *)opaque_decl_ctx; if (ObjCMethodDecl *objc_method = llvm::dyn_cast(decl_ctx)) { if (is_instance_method_ptr) *is_instance_method_ptr = objc_method->isInstanceMethod(); if (language_ptr) *language_ptr = eLanguageTypeObjC; if (language_object_name_ptr) language_object_name_ptr->SetCString("self"); return true; } else if (CXXMethodDecl *cxx_method = llvm::dyn_cast(decl_ctx)) { if (is_instance_method_ptr) *is_instance_method_ptr = cxx_method->isInstance(); if (language_ptr) *language_ptr = eLanguageTypeC_plus_plus; if (language_object_name_ptr) language_object_name_ptr->SetCString("this"); return true; } else if (clang::FunctionDecl *function_decl = llvm::dyn_cast(decl_ctx)) { ClangASTMetadata *metadata = GetMetadata(function_decl); if (metadata && metadata->HasObjectPtr()) { if (is_instance_method_ptr) *is_instance_method_ptr = true; if (language_ptr) *language_ptr = eLanguageTypeObjC; if (language_object_name_ptr) language_object_name_ptr->SetCString(metadata->GetObjectPtrName()); return true; } } } return false; } bool TypeSystemClang::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; } static bool IsClangDeclContext(const CompilerDeclContext &dc) { return dc.IsValid() && isa(dc.GetTypeSystem()); } clang::DeclContext * TypeSystemClang::DeclContextGetAsDeclContext(const CompilerDeclContext &dc) { if (IsClangDeclContext(dc)) return (clang::DeclContext *)dc.GetOpaqueDeclContext(); return nullptr; } ObjCMethodDecl * TypeSystemClang::DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc) { if (IsClangDeclContext(dc)) return llvm::dyn_cast( (clang::DeclContext *)dc.GetOpaqueDeclContext()); return nullptr; } CXXMethodDecl * TypeSystemClang::DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc) { if (IsClangDeclContext(dc)) return llvm::dyn_cast( (clang::DeclContext *)dc.GetOpaqueDeclContext()); return nullptr; } clang::FunctionDecl * TypeSystemClang::DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc) { if (IsClangDeclContext(dc)) return llvm::dyn_cast( (clang::DeclContext *)dc.GetOpaqueDeclContext()); return nullptr; } clang::NamespaceDecl * TypeSystemClang::DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc) { if (IsClangDeclContext(dc)) return llvm::dyn_cast( (clang::DeclContext *)dc.GetOpaqueDeclContext()); return nullptr; } ClangASTMetadata * TypeSystemClang::DeclContextGetMetaData(const CompilerDeclContext &dc, const Decl *object) { TypeSystemClang *ast = llvm::cast(dc.GetTypeSystem()); return ast->GetMetadata(object); } clang::ASTContext * TypeSystemClang::DeclContextGetTypeSystemClang(const CompilerDeclContext &dc) { TypeSystemClang *ast = llvm::dyn_cast_or_null(dc.GetTypeSystem()); if (ast) return &ast->getASTContext(); return nullptr; } TypeSystemClangForExpressions::TypeSystemClangForExpressions( Target &target, llvm::Triple triple) : TypeSystemClang("scratch ASTContext", triple), m_target_wp(target.shared_from_this()), m_persistent_variables(new ClangPersistentVariables) { m_scratch_ast_source_up = std::make_unique( target.shared_from_this(), m_persistent_variables->GetClangASTImporter()); m_scratch_ast_source_up->InstallASTContext(*this); llvm::IntrusiveRefCntPtr proxy_ast_source( m_scratch_ast_source_up->CreateProxy()); SetExternalSource(proxy_ast_source); } void TypeSystemClangForExpressions::Finalize() { TypeSystemClang::Finalize(); m_scratch_ast_source_up.reset(); } UserExpression *TypeSystemClangForExpressions::GetUserExpression( llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, 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, ctx_obj); } FunctionCaller *TypeSystemClangForExpressions::GetFunctionCaller( const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name) { TargetSP target_sp = m_target_wp.lock(); if (!target_sp) return nullptr; Process *process = target_sp->GetProcessSP().get(); if (!process) return nullptr; return new ClangFunctionCaller(*process, return_type, function_address, arg_value_list, name); } UtilityFunction * TypeSystemClangForExpressions::GetUtilityFunction(const char *text, const char *name) { TargetSP target_sp = m_target_wp.lock(); if (!target_sp) return nullptr; return new ClangUtilityFunction(*target_sp.get(), text, name); } PersistentExpressionState * TypeSystemClangForExpressions::GetPersistentExpressionState() { return m_persistent_variables.get(); } Index: projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h =================================================================== --- projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h (revision 363960) +++ projects/clang1100-import/contrib/llvm-project/lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.h (revision 363961) @@ -1,1153 +1,1157 @@ //===-- TypeSystemClang.h ---------------------------------------*- C++ -*-===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// #ifndef LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H #define LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H #include #include #include #include #include #include #include #include #include #include "clang/AST/ASTContext.h" #include "clang/AST/ASTFwd.h" #include "clang/AST/TemplateBase.h" #include "clang/Basic/TargetInfo.h" #include "llvm/ADT/APSInt.h" #include "llvm/ADT/SmallVector.h" #include "Plugins/ExpressionParser/Clang/ClangPersistentVariables.h" #include "lldb/Expression/ExpressionVariable.h" #include "lldb/Symbol/CompilerType.h" #include "lldb/Symbol/TypeSystem.h" #include "lldb/Target/Target.h" #include "lldb/Utility/ConstString.h" #include "lldb/Utility/Flags.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/Logging.h" #include "lldb/lldb-enumerations.h" class DWARFASTParserClang; class PDBASTParser; namespace clang { class FileManager; class HeaderSearch; class ModuleMap; } // namespace clang namespace lldb_private { class ClangASTMetadata; class ClangASTSource; class Declaration; /// A Clang module ID. class OptionalClangModuleID { unsigned m_id = 0; public: OptionalClangModuleID() = default; explicit OptionalClangModuleID(unsigned id) : m_id(id) {} bool HasValue() const { return m_id != 0; } unsigned GetValue() const { return m_id; } }; /// The implementation of lldb::Type's m_payload field for TypeSystemClang. class TypePayloadClang { /// The Layout is as follows: /// \verbatim /// bit 0..30 ... Owning Module ID. /// bit 31 ...... IsCompleteObjCClass. /// \endverbatim Type::Payload m_payload = 0; public: TypePayloadClang() = default; explicit TypePayloadClang(OptionalClangModuleID owning_module, bool is_complete_objc_class = false); explicit TypePayloadClang(uint32_t opaque_payload) : m_payload(opaque_payload) {} operator Type::Payload() { return m_payload; } static constexpr unsigned ObjCClassBit = 1 << 31; bool IsCompleteObjCClass() { return Flags(m_payload).Test(ObjCClassBit); } void SetIsCompleteObjCClass(bool is_complete_objc_class) { m_payload = is_complete_objc_class ? Flags(m_payload).Set(ObjCClassBit) : Flags(m_payload).Clear(ObjCClassBit); } OptionalClangModuleID GetOwningModule() { return OptionalClangModuleID(Flags(m_payload).Clear(ObjCClassBit)); } void SetOwningModule(OptionalClangModuleID id); /// \} }; /// A TypeSystem implementation based on Clang. /// /// This class uses a single clang::ASTContext as the backend for storing /// its types and declarations. Every clang::ASTContext should also just have /// a single associated TypeSystemClang instance that manages it. /// /// The clang::ASTContext instance can either be created by TypeSystemClang /// itself or it can adopt an existing clang::ASTContext (for example, when /// it is necessary to provide a TypeSystem interface for an existing /// clang::ASTContext that was created by clang::CompilerInstance). class TypeSystemClang : public TypeSystem { // LLVM RTTI support static char ID; public: typedef void (*CompleteTagDeclCallback)(void *baton, clang::TagDecl *); typedef void (*CompleteObjCInterfaceDeclCallback)(void *baton, clang::ObjCInterfaceDecl *); // llvm casting support bool isA(const void *ClassID) const override { return ClassID == &ID; } static bool classof(const TypeSystem *ts) { return ts->isA(&ID); } /// Constructs a TypeSystemClang with an ASTContext using the given triple. /// /// \param name The name for the TypeSystemClang (for logging purposes) /// \param triple The llvm::Triple used for the ASTContext. The triple defines /// certain characteristics of the ASTContext and its types /// (e.g., whether certain primitive types exist or what their /// signedness is). explicit TypeSystemClang(llvm::StringRef name, llvm::Triple triple); /// Constructs a TypeSystemClang that uses an existing ASTContext internally. /// Useful when having an existing ASTContext created by Clang. /// /// \param name The name for the TypeSystemClang (for logging purposes) /// \param existing_ctxt An existing ASTContext. explicit TypeSystemClang(llvm::StringRef name, clang::ASTContext &existing_ctxt); ~TypeSystemClang() override; void Finalize() override; // PluginInterface functions ConstString GetPluginName() override; uint32_t GetPluginVersion() override; static ConstString GetPluginNameStatic(); static lldb::TypeSystemSP CreateInstance(lldb::LanguageType language, Module *module, Target *target); static LanguageSet GetSupportedLanguagesForTypes(); static LanguageSet GetSupportedLanguagesForExpressions(); static void Initialize(); static void Terminate(); static TypeSystemClang *GetASTContext(clang::ASTContext *ast_ctx); static TypeSystemClang *GetScratch(Target &target, bool create_on_demand = true) { auto type_system_or_err = target.GetScratchTypeSystemForLanguage( lldb::eLanguageTypeC, create_on_demand); if (auto err = type_system_or_err.takeError()) { LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_TARGET), std::move(err), "Couldn't get scratch TypeSystemClang"); return nullptr; } return llvm::dyn_cast(&type_system_or_err.get()); } /// Returns the display name of this TypeSystemClang that indicates what /// purpose it serves in LLDB. Used for example in logs. llvm::StringRef getDisplayName() const { return m_display_name; } /// Returns the clang::ASTContext instance managed by this TypeSystemClang. clang::ASTContext &getASTContext(); clang::MangleContext *getMangleContext(); std::shared_ptr &getTargetOptions(); clang::TargetInfo *getTargetInfo(); void setSema(clang::Sema *s); clang::Sema *getSema() { return m_sema; } const char *GetTargetTriple(); void SetExternalSource( llvm::IntrusiveRefCntPtr &ast_source_up); bool GetCompleteDecl(clang::Decl *decl) { return TypeSystemClang::GetCompleteDecl(&getASTContext(), decl); } static void DumpDeclHiearchy(clang::Decl *decl); static void DumpDeclContextHiearchy(clang::DeclContext *decl_ctx); static bool DeclsAreEquivalent(clang::Decl *lhs_decl, clang::Decl *rhs_decl); static bool GetCompleteDecl(clang::ASTContext *ast, clang::Decl *decl); void SetMetadataAsUserID(const clang::Decl *decl, lldb::user_id_t user_id); void SetMetadataAsUserID(const clang::Type *type, lldb::user_id_t user_id); void SetMetadata(const clang::Decl *object, ClangASTMetadata &meta_data); void SetMetadata(const clang::Type *object, ClangASTMetadata &meta_data); ClangASTMetadata *GetMetadata(const clang::Decl *object); ClangASTMetadata *GetMetadata(const clang::Type *object); // Basic Types CompilerType GetBuiltinTypeForEncodingAndBitSize(lldb::Encoding encoding, size_t bit_size) override; CompilerType GetBasicType(lldb::BasicType type); static lldb::BasicType GetBasicTypeEnumeration(ConstString name); CompilerType GetBuiltinTypeForDWARFEncodingAndBitSize(llvm::StringRef type_name, uint32_t dw_ate, uint32_t bit_size); CompilerType GetCStringType(bool is_const); static clang::DeclContext *GetDeclContextForType(clang::QualType type); static clang::DeclContext *GetDeclContextForType(const CompilerType &type); uint32_t GetPointerByteSize() override; clang::TranslationUnitDecl *GetTranslationUnitDecl() { return getASTContext().getTranslationUnitDecl(); } static bool AreTypesSame(CompilerType type1, CompilerType type2, bool ignore_qualifiers = false); /// Creates a CompilerType form the given QualType with the current /// TypeSystemClang instance as the CompilerType's typesystem. /// \param qt The QualType for a type that belongs to the ASTContext of this /// TypeSystemClang. /// \return The CompilerType representing the given QualType. If the /// QualType's type pointer is a nullptr then the function returns an /// invalid CompilerType. CompilerType GetType(clang::QualType qt) { if (qt.getTypePtrOrNull() == nullptr) return CompilerType(); // Check that the type actually belongs to this TypeSystemClang. assert(qt->getAsTagDecl() == nullptr || &qt->getAsTagDecl()->getASTContext() == &getASTContext()); return CompilerType(this, qt.getAsOpaquePtr()); } CompilerType GetTypeForDecl(clang::NamedDecl *decl); CompilerType GetTypeForDecl(clang::TagDecl *decl); CompilerType GetTypeForDecl(clang::ObjCInterfaceDecl *objc_decl); template CompilerType GetTypeForIdentifier(ConstString type_name, clang::DeclContext *decl_context = nullptr) { CompilerType compiler_type; if (type_name.GetLength()) { clang::ASTContext &ast = getASTContext(); if (!decl_context) decl_context = ast.getTranslationUnitDecl(); clang::IdentifierInfo &myIdent = ast.Idents.get(type_name.GetCString()); clang::DeclarationName myName = ast.DeclarationNames.getIdentifier(&myIdent); clang::DeclContext::lookup_result result = decl_context->lookup(myName); if (!result.empty()) { clang::NamedDecl *named_decl = result[0]; if (const RecordDeclType *record_decl = llvm::dyn_cast(named_decl)) compiler_type.SetCompilerType( this, clang::QualType(record_decl->getTypeForDecl(), 0) .getAsOpaquePtr()); } } return compiler_type; } CompilerType CreateStructForIdentifier( ConstString type_name, const std::initializer_list> &type_fields, bool packed = false); CompilerType GetOrCreateStructForIdentifier( ConstString type_name, const std::initializer_list> &type_fields, bool packed = false); static bool IsOperator(llvm::StringRef name, clang::OverloadedOperatorKind &op_kind); // Structure, Unions, Classes static clang::AccessSpecifier ConvertAccessTypeToAccessSpecifier(lldb::AccessType access); static clang::AccessSpecifier UnifyAccessSpecifiers(clang::AccessSpecifier lhs, clang::AccessSpecifier rhs); static uint32_t GetNumBaseClasses(const clang::CXXRecordDecl *cxx_record_decl, bool omit_empty_base_classes); /// Synthesize a clang::Module and return its ID or a default-constructed ID. OptionalClangModuleID GetOrCreateClangModule(llvm::StringRef name, OptionalClangModuleID parent, bool is_framework = false, bool is_explicit = false); CompilerType CreateRecordType(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, lldb::AccessType access_type, llvm::StringRef name, int kind, lldb::LanguageType language, ClangASTMetadata *metadata = nullptr, bool exports_symbols = false); class TemplateParameterInfos { public: bool IsValid() const { if (args.empty()) return false; return args.size() == names.size() && ((bool)pack_name == (bool)packed_args) && (!packed_args || !packed_args->packed_args); } llvm::SmallVector names; llvm::SmallVector args; const char * pack_name = nullptr; std::unique_ptr packed_args; }; clang::FunctionTemplateDecl * CreateFunctionTemplateDecl(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, clang::FunctionDecl *func_decl, const char *name, const TemplateParameterInfos &infos); void CreateFunctionTemplateSpecializationInfo( clang::FunctionDecl *func_decl, clang::FunctionTemplateDecl *Template, const TemplateParameterInfos &infos); clang::ClassTemplateDecl * CreateClassTemplateDecl(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, lldb::AccessType access_type, const char *class_name, int kind, const TemplateParameterInfos &infos); clang::TemplateTemplateParmDecl * CreateTemplateTemplateParmDecl(const char *template_name); clang::ClassTemplateSpecializationDecl *CreateClassTemplateSpecializationDecl( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, clang::ClassTemplateDecl *class_template_decl, int kind, const TemplateParameterInfos &infos); CompilerType CreateClassTemplateSpecializationType(clang::ClassTemplateSpecializationDecl * class_template_specialization_decl); static clang::DeclContext * GetAsDeclContext(clang::FunctionDecl *function_decl); static bool CheckOverloadedOperatorKindParameterCount( bool is_method, clang::OverloadedOperatorKind op_kind, uint32_t num_params); bool FieldIsBitfield(clang::FieldDecl *field, uint32_t &bitfield_bit_size); static bool RecordHasFields(const clang::RecordDecl *record_decl); CompilerType CreateObjCClass(llvm::StringRef name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, bool isForwardDecl, bool isInternal, ClangASTMetadata *metadata = nullptr); bool SetTagTypeKind(clang::QualType type, int kind) const; bool SetDefaultAccessForRecordFields(clang::RecordDecl *record_decl, int default_accessibility, int *assigned_accessibilities, size_t num_assigned_accessibilities); // Returns a mask containing bits from the TypeSystemClang::eTypeXXX // enumerations // Namespace Declarations clang::NamespaceDecl * GetUniqueNamespaceDeclaration(const char *name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, bool is_inline = false); // Function Types clang::FunctionDecl * CreateFunctionDeclaration(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const char *name, const CompilerType &function_Type, int storage, bool is_inline); CompilerType CreateFunctionType(const CompilerType &result_type, const CompilerType *args, unsigned num_args, bool is_variadic, unsigned type_quals, clang::CallingConv cc); CompilerType CreateFunctionType(const CompilerType &result_type, const CompilerType *args, unsigned num_args, bool is_variadic, unsigned type_quals) { return CreateFunctionType(result_type, args, num_args, is_variadic, type_quals, clang::CC_C); } clang::ParmVarDecl * CreateParameterDeclaration(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const char *name, const CompilerType ¶m_type, int storage, bool add_decl = false); void SetFunctionParameters(clang::FunctionDecl *function_decl, clang::ParmVarDecl **params, unsigned num_params); CompilerType CreateBlockPointerType(const CompilerType &function_type); // Array Types CompilerType CreateArrayType(const CompilerType &element_type, size_t element_count, bool is_vector); // Enumeration Types CompilerType CreateEnumerationType(const char *name, clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, const Declaration &decl, const CompilerType &integer_qual_type, bool is_scoped); // Integer type functions CompilerType GetIntTypeFromBitSize(size_t bit_size, bool is_signed); CompilerType GetPointerSizedIntType(bool is_signed); // Floating point functions static CompilerType GetFloatTypeFromBitSize(clang::ASTContext *ast, size_t bit_size); // TypeSystem methods DWARFASTParser *GetDWARFParser() override; +#ifdef LLDB_ENABLE_ALL PDBASTParser *GetPDBParser() override; +#endif // LLDB_ENABLE_ALL // TypeSystemClang callbacks for external source lookups. void CompleteTagDecl(clang::TagDecl *); void CompleteObjCInterfaceDecl(clang::ObjCInterfaceDecl *); bool LayoutRecordType( const clang::RecordDecl *record_decl, uint64_t &size, uint64_t &alignment, llvm::DenseMap &field_offsets, llvm::DenseMap &base_offsets, llvm::DenseMap &vbase_offsets); /// Creates a CompilerDecl from the given Decl with the current /// TypeSystemClang instance as its typesystem. /// The Decl has to come from the ASTContext of this /// TypeSystemClang. CompilerDecl GetCompilerDecl(clang::Decl *decl) { assert(&decl->getASTContext() == &getASTContext() && "CreateCompilerDecl for Decl from wrong ASTContext?"); return CompilerDecl(this, decl); } // CompilerDecl override functions ConstString DeclGetName(void *opaque_decl) override; ConstString DeclGetMangledName(void *opaque_decl) override; CompilerDeclContext DeclGetDeclContext(void *opaque_decl) override; CompilerType DeclGetFunctionReturnType(void *opaque_decl) override; size_t DeclGetFunctionNumArguments(void *opaque_decl) override; CompilerType DeclGetFunctionArgumentType(void *opaque_decl, size_t arg_idx) override; CompilerType GetTypeForDecl(void *opaque_decl) override; // CompilerDeclContext override functions /// Creates a CompilerDeclContext from the given DeclContext /// with the current TypeSystemClang instance as its typesystem. /// The DeclContext has to come from the ASTContext of this /// TypeSystemClang. CompilerDeclContext CreateDeclContext(clang::DeclContext *ctx); /// Set the owning module for \p decl. static void SetOwningModule(clang::Decl *decl, OptionalClangModuleID owning_module); std::vector DeclContextFindDeclByName(void *opaque_decl_ctx, ConstString name, const bool ignore_using_decls) override; ConstString DeclContextGetName(void *opaque_decl_ctx) override; ConstString DeclContextGetScopeQualifiedName(void *opaque_decl_ctx) override; bool DeclContextIsClassMethod(void *opaque_decl_ctx, lldb::LanguageType *language_ptr, bool *is_instance_method_ptr, ConstString *language_object_name_ptr) override; bool DeclContextIsContainedInLookup(void *opaque_decl_ctx, void *other_opaque_decl_ctx) override; // Clang specific clang::DeclContext functions static clang::DeclContext * DeclContextGetAsDeclContext(const CompilerDeclContext &dc); static clang::ObjCMethodDecl * DeclContextGetAsObjCMethodDecl(const CompilerDeclContext &dc); static clang::CXXMethodDecl * DeclContextGetAsCXXMethodDecl(const CompilerDeclContext &dc); static clang::FunctionDecl * DeclContextGetAsFunctionDecl(const CompilerDeclContext &dc); static clang::NamespaceDecl * DeclContextGetAsNamespaceDecl(const CompilerDeclContext &dc); static ClangASTMetadata *DeclContextGetMetaData(const CompilerDeclContext &dc, const clang::Decl *object); static clang::ASTContext * DeclContextGetTypeSystemClang(const CompilerDeclContext &dc); // Tests #ifndef NDEBUG bool Verify(lldb::opaque_compiler_type_t type) override; #endif bool IsArrayType(lldb::opaque_compiler_type_t type, CompilerType *element_type, uint64_t *size, bool *is_incomplete) override; bool IsVectorType(lldb::opaque_compiler_type_t type, CompilerType *element_type, uint64_t *size) override; bool IsAggregateType(lldb::opaque_compiler_type_t type) override; bool IsAnonymousType(lldb::opaque_compiler_type_t type) override; bool IsBeingDefined(lldb::opaque_compiler_type_t type) override; bool IsCharType(lldb::opaque_compiler_type_t type) override; bool IsCompleteType(lldb::opaque_compiler_type_t type) override; bool IsConst(lldb::opaque_compiler_type_t type) override; bool IsCStringType(lldb::opaque_compiler_type_t type, uint32_t &length) override; static bool IsCXXClassType(const CompilerType &type); bool IsDefined(lldb::opaque_compiler_type_t type) override; bool IsFloatingPointType(lldb::opaque_compiler_type_t type, uint32_t &count, bool &is_complex) override; bool IsFunctionType(lldb::opaque_compiler_type_t type, bool *is_variadic_ptr) override; uint32_t IsHomogeneousAggregate(lldb::opaque_compiler_type_t type, CompilerType *base_type_ptr) override; size_t GetNumberOfFunctionArguments(lldb::opaque_compiler_type_t type) override; CompilerType GetFunctionArgumentAtIndex(lldb::opaque_compiler_type_t type, const size_t index) override; bool IsFunctionPointerType(lldb::opaque_compiler_type_t type) override; bool IsBlockPointerType(lldb::opaque_compiler_type_t type, CompilerType *function_pointer_type_ptr) override; bool IsIntegerType(lldb::opaque_compiler_type_t type, bool &is_signed) override; bool IsEnumerationType(lldb::opaque_compiler_type_t type, bool &is_signed) override; static bool IsObjCClassType(const CompilerType &type); static bool IsObjCClassTypeAndHasIVars(const CompilerType &type, bool check_superclass); static bool IsObjCObjectOrInterfaceType(const CompilerType &type); static bool IsObjCObjectPointerType(const CompilerType &type, CompilerType *target_type = nullptr); bool IsPolymorphicClass(lldb::opaque_compiler_type_t type) override; static bool IsClassType(lldb::opaque_compiler_type_t type); static bool IsEnumType(lldb::opaque_compiler_type_t type); bool IsPossibleDynamicType(lldb::opaque_compiler_type_t type, CompilerType *target_type, // Can pass nullptr bool check_cplusplus, bool check_objc) override; bool IsRuntimeGeneratedType(lldb::opaque_compiler_type_t type) override; bool IsPointerType(lldb::opaque_compiler_type_t type, CompilerType *pointee_type) override; bool IsPointerOrReferenceType(lldb::opaque_compiler_type_t type, CompilerType *pointee_type) override; bool IsReferenceType(lldb::opaque_compiler_type_t type, CompilerType *pointee_type, bool *is_rvalue) override; bool IsScalarType(lldb::opaque_compiler_type_t type) override; bool IsTypedefType(lldb::opaque_compiler_type_t type) override; bool IsVoidType(lldb::opaque_compiler_type_t type) override; bool CanPassInRegisters(const CompilerType &type) override; bool SupportsLanguage(lldb::LanguageType language) override; static llvm::Optional GetCXXClassName(const CompilerType &type); // Type Completion bool GetCompleteType(lldb::opaque_compiler_type_t type) override; // Accessors ConstString GetTypeName(lldb::opaque_compiler_type_t type) override; ConstString GetDisplayTypeName(lldb::opaque_compiler_type_t type) override; uint32_t GetTypeInfo(lldb::opaque_compiler_type_t type, CompilerType *pointee_or_element_compiler_type) override; lldb::LanguageType GetMinimumLanguage(lldb::opaque_compiler_type_t type) override; lldb::TypeClass GetTypeClass(lldb::opaque_compiler_type_t type) override; unsigned GetTypeQualifiers(lldb::opaque_compiler_type_t type) override; // Creating related types /// Using the current type, create a new typedef to that type using /// "typedef_name" as the name and "decl_ctx" as the decl context. /// \param payload is an opaque TypePayloadClang. static CompilerType CreateTypedefType(const CompilerType &type, const char *typedef_name, const CompilerDeclContext &compiler_decl_ctx, uint32_t opaque_payload); CompilerType GetArrayElementType(lldb::opaque_compiler_type_t type, uint64_t *stride) override; CompilerType GetArrayType(lldb::opaque_compiler_type_t type, uint64_t size) override; CompilerType GetCanonicalType(lldb::opaque_compiler_type_t type) override; CompilerType GetFullyUnqualifiedType(lldb::opaque_compiler_type_t type) override; // Returns -1 if this isn't a function of if the function doesn't have a // prototype Returns a value >= 0 if there is a prototype. int GetFunctionArgumentCount(lldb::opaque_compiler_type_t type) override; CompilerType GetFunctionArgumentTypeAtIndex(lldb::opaque_compiler_type_t type, size_t idx) override; CompilerType GetFunctionReturnType(lldb::opaque_compiler_type_t type) override; size_t GetNumMemberFunctions(lldb::opaque_compiler_type_t type) override; TypeMemberFunctionImpl GetMemberFunctionAtIndex(lldb::opaque_compiler_type_t type, size_t idx) override; CompilerType GetNonReferenceType(lldb::opaque_compiler_type_t type) override; CompilerType GetPointeeType(lldb::opaque_compiler_type_t type) override; CompilerType GetPointerType(lldb::opaque_compiler_type_t type) override; CompilerType GetLValueReferenceType(lldb::opaque_compiler_type_t type) override; CompilerType GetRValueReferenceType(lldb::opaque_compiler_type_t type) override; CompilerType GetAtomicType(lldb::opaque_compiler_type_t type) override; CompilerType AddConstModifier(lldb::opaque_compiler_type_t type) override; CompilerType AddVolatileModifier(lldb::opaque_compiler_type_t type) override; CompilerType AddRestrictModifier(lldb::opaque_compiler_type_t type) override; CompilerType CreateTypedef(lldb::opaque_compiler_type_t type, const char *name, const CompilerDeclContext &decl_ctx, uint32_t opaque_payload) override; // If the current object represents a typedef type, get the underlying type CompilerType GetTypedefedType(lldb::opaque_compiler_type_t type) override; // Create related types using the current type's AST CompilerType GetBasicTypeFromAST(lldb::BasicType basic_type) override; // Exploring the type const llvm::fltSemantics &GetFloatTypeSemantics(size_t byte_size) override; llvm::Optional GetByteSize(lldb::opaque_compiler_type_t type, ExecutionContextScope *exe_scope) { if (llvm::Optional bit_size = GetBitSize(type, exe_scope)) return (*bit_size + 7) / 8; return llvm::None; } llvm::Optional GetBitSize(lldb::opaque_compiler_type_t type, ExecutionContextScope *exe_scope) override; lldb::Encoding GetEncoding(lldb::opaque_compiler_type_t type, uint64_t &count) override; lldb::Format GetFormat(lldb::opaque_compiler_type_t type) override; llvm::Optional GetTypeBitAlign(lldb::opaque_compiler_type_t type, ExecutionContextScope *exe_scope) override; uint32_t GetNumChildren(lldb::opaque_compiler_type_t type, bool omit_empty_base_classes, const ExecutionContext *exe_ctx) override; CompilerType GetBuiltinTypeByName(ConstString name) override; lldb::BasicType GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type) override; static lldb::BasicType GetBasicTypeEnumeration(lldb::opaque_compiler_type_t type, ConstString name); void ForEachEnumerator( lldb::opaque_compiler_type_t type, std::function const &callback) override; uint32_t GetNumFields(lldb::opaque_compiler_type_t type) override; CompilerType 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) override; uint32_t GetNumDirectBaseClasses(lldb::opaque_compiler_type_t type) override; uint32_t GetNumVirtualBaseClasses(lldb::opaque_compiler_type_t type) override; CompilerType GetDirectBaseClassAtIndex(lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) override; CompilerType GetVirtualBaseClassAtIndex(lldb::opaque_compiler_type_t type, size_t idx, uint32_t *bit_offset_ptr) override; static uint32_t GetNumPointeeChildren(clang::QualType type); CompilerType 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) override; // 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 GetIndexOfChildWithName(lldb::opaque_compiler_type_t type, const char *name, bool omit_empty_base_classes) override; // 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> // so we catch all names that match a given child name, not just the first. size_t GetIndexOfChildMemberWithName(lldb::opaque_compiler_type_t type, const char *name, bool omit_empty_base_classes, std::vector &child_indexes) override; size_t GetNumTemplateArguments(lldb::opaque_compiler_type_t type) override; lldb::TemplateArgumentKind GetTemplateArgumentKind(lldb::opaque_compiler_type_t type, size_t idx) override; CompilerType GetTypeTemplateArgument(lldb::opaque_compiler_type_t type, size_t idx) override; llvm::Optional GetIntegralTemplateArgument(lldb::opaque_compiler_type_t type, size_t idx) override; CompilerType GetTypeForFormatters(void *type) override; #define LLDB_INVALID_DECL_LEVEL UINT32_MAX // LLDB_INVALID_DECL_LEVEL is returned by CountDeclLevels if child_decl_ctx // could not be found in decl_ctx. uint32_t CountDeclLevels(clang::DeclContext *frame_decl_ctx, clang::DeclContext *child_decl_ctx, ConstString *child_name = nullptr, CompilerType *child_type = nullptr); // Modifying RecordType static clang::FieldDecl *AddFieldToRecordType(const CompilerType &type, llvm::StringRef name, const CompilerType &field_type, lldb::AccessType access, uint32_t bitfield_bit_size); static void BuildIndirectFields(const CompilerType &type); static void SetIsPacked(const CompilerType &type); static clang::VarDecl *AddVariableToRecordType(const CompilerType &type, llvm::StringRef name, const CompilerType &var_type, lldb::AccessType access); /// Initializes a variable with an integer value. /// \param var The variable to initialize. Must not already have an /// initializer and must have an integer or enum type. /// \param init_value The integer value that the variable should be /// initialized to. Has to match the bit width of the /// variable type. static void SetIntegerInitializerForVariable(clang::VarDecl *var, const llvm::APInt &init_value); /// Initializes a variable with a floating point value. /// \param var The variable to initialize. Must not already have an /// initializer and must have a floating point type. /// \param init_value The float value that the variable should be /// initialized to. static void SetFloatingInitializerForVariable(clang::VarDecl *var, const llvm::APFloat &init_value); clang::CXXMethodDecl *AddMethodToCXXRecordType( lldb::opaque_compiler_type_t type, llvm::StringRef name, const char *mangled_name, const CompilerType &method_type, lldb::AccessType access, bool is_virtual, bool is_static, bool is_inline, bool is_explicit, bool is_attr_used, bool is_artificial); void AddMethodOverridesForCXXRecordType(lldb::opaque_compiler_type_t type); // C++ Base Classes std::unique_ptr CreateBaseClassSpecifier(lldb::opaque_compiler_type_t type, lldb::AccessType access, bool is_virtual, bool base_of_class); bool TransferBaseClasses( lldb::opaque_compiler_type_t type, std::vector> bases); static bool SetObjCSuperClass(const CompilerType &type, const CompilerType &superclass_compiler_type); static bool AddObjCClassProperty(const CompilerType &type, const char *property_name, const CompilerType &property_compiler_type, clang::ObjCIvarDecl *ivar_decl, const char *property_setter_name, const char *property_getter_name, uint32_t property_attributes, ClangASTMetadata *metadata); static clang::ObjCMethodDecl *AddMethodToObjCObjectType( const CompilerType &type, const char *name, // the full symbol name as seen in the symbol table // (lldb::opaque_compiler_type_t type, "-[NString // stringWithCString:]") const CompilerType &method_compiler_type, lldb::AccessType access, bool is_artificial, bool is_variadic, bool is_objc_direct_call); static bool SetHasExternalStorage(lldb::opaque_compiler_type_t type, bool has_extern); // Tag Declarations static bool StartTagDeclarationDefinition(const CompilerType &type); static bool CompleteTagDeclarationDefinition(const CompilerType &type); // Modifying Enumeration types clang::EnumConstantDecl *AddEnumerationValueToEnumerationType( const CompilerType &enum_type, const Declaration &decl, const char *name, int64_t enum_value, uint32_t enum_value_bit_size); clang::EnumConstantDecl *AddEnumerationValueToEnumerationType( const CompilerType &enum_type, const Declaration &decl, const char *name, const llvm::APSInt &value); /// Returns the underlying integer type for an enum type. If the given type /// is invalid or not an enum-type, the function returns an invalid /// CompilerType. CompilerType GetEnumerationIntegerType(CompilerType type); // Pointers & References // Call this function using the class type when you want to make a member // pointer type to pointee_type. static CompilerType CreateMemberPointerType(const CompilerType &type, const CompilerType &pointee_type); // Dumping types #ifndef NDEBUG /// Convenience LLVM-style dump method for use in the debugger only. /// In contrast to the other \p Dump() methods this directly invokes /// \p clang::QualType::dump(). LLVM_DUMP_METHOD void dump(lldb::opaque_compiler_type_t type) const override; #endif void Dump(Stream &s); /// Dump clang AST types from the symbol file. /// /// \param[in] s /// A stream to send the dumped AST node(s) to /// \param[in] symbol_name /// The name of the symbol to dump, if it is empty dump all the symbols void DumpFromSymbolFile(Stream &s, llvm::StringRef symbol_name); void DumpValue(lldb::opaque_compiler_type_t type, ExecutionContext *exe_ctx, Stream *s, lldb::Format format, const DataExtractor &data, lldb::offset_t data_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) override; bool DumpTypeValue(lldb::opaque_compiler_type_t type, Stream *s, lldb::Format format, const DataExtractor &data, lldb::offset_t data_offset, size_t data_byte_size, uint32_t bitfield_bit_size, uint32_t bitfield_bit_offset, ExecutionContextScope *exe_scope) override; void 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) override; void DumpTypeDescription( lldb::opaque_compiler_type_t type, lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override; void DumpTypeDescription( lldb::opaque_compiler_type_t type, Stream *s, lldb::DescriptionLevel level = lldb::eDescriptionLevelFull) override; static void DumpTypeName(const CompilerType &type); static clang::EnumDecl *GetAsEnumDecl(const CompilerType &type); static clang::RecordDecl *GetAsRecordDecl(const CompilerType &type); static clang::TagDecl *GetAsTagDecl(const CompilerType &type); static clang::TypedefNameDecl *GetAsTypedefDecl(const CompilerType &type); static clang::CXXRecordDecl * GetAsCXXRecordDecl(lldb::opaque_compiler_type_t type); static clang::ObjCInterfaceDecl * GetAsObjCInterfaceDecl(const CompilerType &type); clang::ClassTemplateDecl *ParseClassTemplateDecl( clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, lldb::AccessType access_type, const char *parent_name, int tag_decl_kind, const TypeSystemClang::TemplateParameterInfos &template_param_infos); clang::BlockDecl *CreateBlockDeclaration(clang::DeclContext *ctx, OptionalClangModuleID owning_module); clang::UsingDirectiveDecl * CreateUsingDirectiveDeclaration(clang::DeclContext *decl_ctx, OptionalClangModuleID owning_module, clang::NamespaceDecl *ns_decl); clang::UsingDecl *CreateUsingDeclaration(clang::DeclContext *current_decl_ctx, OptionalClangModuleID owning_module, clang::NamedDecl *target); clang::VarDecl *CreateVariableDeclaration(clang::DeclContext *decl_context, OptionalClangModuleID owning_module, const char *name, clang::QualType type); static lldb::opaque_compiler_type_t GetOpaqueCompilerType(clang::ASTContext *ast, lldb::BasicType basic_type); static clang::QualType GetQualType(lldb::opaque_compiler_type_t type) { if (type) return clang::QualType::getFromOpaquePtr(type); return clang::QualType(); } static clang::QualType GetCanonicalQualType(lldb::opaque_compiler_type_t type) { if (type) return clang::QualType::getFromOpaquePtr(type).getCanonicalType(); return clang::QualType(); } clang::DeclarationName GetDeclarationName(const char *name, const CompilerType &function_clang_type); clang::LangOptions *GetLangOpts() const { return m_language_options_up.get(); } clang::SourceManager *GetSourceMgr() const { return m_source_manager_up.get(); } private: const clang::ClassTemplateSpecializationDecl * GetAsTemplateSpecialization(lldb::opaque_compiler_type_t type); // Classes that inherit from TypeSystemClang can see and modify these std::string m_target_triple; std::unique_ptr m_ast_up; std::unique_ptr m_language_options_up; std::unique_ptr m_file_manager_up; std::unique_ptr m_source_manager_up; std::unique_ptr m_diagnostics_engine_up; std::unique_ptr m_diagnostic_consumer_up; std::shared_ptr m_target_options_rp; std::unique_ptr m_target_info_up; std::unique_ptr m_identifier_table_up; std::unique_ptr m_selector_table_up; std::unique_ptr m_builtins_up; std::unique_ptr m_header_search_up; std::unique_ptr m_module_map_up; std::unique_ptr m_dwarf_ast_parser_up; +#ifdef LLDB_ENABLE_ALL std::unique_ptr m_pdb_ast_parser_up; +#endif // LLDB_ENABLE_ALL std::unique_ptr m_mangle_ctx_up; uint32_t m_pointer_byte_size = 0; bool m_ast_owned = false; /// A string describing what this TypeSystemClang represents (e.g., /// AST for debug information, an expression, some other utility ClangAST). /// Useful for logging and debugging. std::string m_display_name; typedef llvm::DenseMap DeclMetadataMap; /// Maps Decls to their associated ClangASTMetadata. DeclMetadataMap m_decl_metadata; typedef llvm::DenseMap TypeMetadataMap; /// Maps Types to their associated ClangASTMetadata. TypeMetadataMap m_type_metadata; /// The sema associated that is currently used to build this ASTContext. /// May be null if we are already done parsing this ASTContext or the /// ASTContext wasn't created by parsing source code. clang::Sema *m_sema = nullptr; // For TypeSystemClang only TypeSystemClang(const TypeSystemClang &); const TypeSystemClang &operator=(const TypeSystemClang &); /// Creates the internal ASTContext. void CreateASTContext(); void SetTargetTriple(llvm::StringRef target_triple); }; /// The TypeSystemClang instance used for the scratch ASTContext in a /// lldb::Target. class TypeSystemClangForExpressions : public TypeSystemClang { public: TypeSystemClangForExpressions(Target &target, llvm::Triple triple); ~TypeSystemClangForExpressions() override = default; void Finalize() override; UserExpression * GetUserExpression(llvm::StringRef expr, llvm::StringRef prefix, lldb::LanguageType language, Expression::ResultType desired_type, const EvaluateExpressionOptions &options, ValueObject *ctx_obj) override; FunctionCaller *GetFunctionCaller(const CompilerType &return_type, const Address &function_address, const ValueList &arg_value_list, const char *name) override; UtilityFunction *GetUtilityFunction(const char *text, const char *name) override; PersistentExpressionState *GetPersistentExpressionState() override; private: lldb::TargetWP m_target_wp; std::unique_ptr m_persistent_variables; // These are the persistent variables associated // with this process for the expression parser std::unique_ptr m_scratch_ast_source_up; }; } // namespace lldb_private #endif // LLDB_SOURCE_PLUGINS_TYPESYSTEM_CLANG_TYPESYSTEMCLANG_H