1//===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===// 2// 3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4// See https://llvm.org/LICENSE.txt for license information. 5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6// 7//===----------------------------------------------------------------------===// 8 9#include "SymbolFileDWARF.h" 10 11#include "llvm/ADT/Optional.h" 12#include "llvm/Support/Casting.h" 13#include "llvm/Support/Threading.h" 14 15#include "lldb/Core/Module.h" 16#include "lldb/Core/ModuleList.h" 17#include "lldb/Core/ModuleSpec.h" 18#include "lldb/Core/PluginManager.h" 19#include "lldb/Core/Section.h" 20#include "lldb/Core/StreamFile.h" 21#include "lldb/Core/Value.h" 22#include "lldb/Utility/ArchSpec.h" 23#include "lldb/Utility/RegularExpression.h" 24#include "lldb/Utility/Scalar.h" 25#include "lldb/Utility/StreamString.h" 26#include "lldb/Utility/Timer.h" 27 28#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h" 29#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h" 30 31#include "lldb/Host/FileSystem.h" 32#include "lldb/Host/Host.h" 33 34#include "lldb/Interpreter/OptionValueFileSpecList.h" 35#include "lldb/Interpreter/OptionValueProperties.h" 36 37#include "lldb/Symbol/Block.h" 38#include "lldb/Symbol/ClangASTContext.h" 39#include "lldb/Symbol/ClangUtil.h" 40#include "lldb/Symbol/CompileUnit.h" 41#include "lldb/Symbol/CompilerDecl.h" 42#include "lldb/Symbol/CompilerDeclContext.h" 43#include "lldb/Symbol/DebugMacros.h" 44#include "lldb/Symbol/LineTable.h" 45#include "lldb/Symbol/LocateSymbolFile.h" 46#include "lldb/Symbol/ObjectFile.h" 47#include "lldb/Symbol/SymbolFile.h" 48#include "lldb/Symbol/TypeMap.h" 49#include "lldb/Symbol/TypeSystem.h" 50#include "lldb/Symbol/VariableList.h" 51 52#include "lldb/Target/Language.h" 53#include "lldb/Target/Target.h" 54 55#include "AppleDWARFIndex.h" 56#include "DWARFASTParser.h" 57#include "DWARFASTParserClang.h" 58#include "DWARFCompileUnit.h" 59#include "DWARFDebugAbbrev.h" 60#include "DWARFDebugAranges.h" 61#include "DWARFDebugInfo.h" 62#include "DWARFDebugMacro.h" 63#include "DWARFDebugRanges.h" 64#include "DWARFDeclContext.h" 65#include "DWARFFormValue.h" 66#include "DWARFTypeUnit.h" 67#include "DWARFUnit.h" 68#include "DebugNamesDWARFIndex.h" 69#include "LogChannelDWARF.h" 70#include "ManualDWARFIndex.h" 71#include "SymbolFileDWARFDebugMap.h" 72#include "SymbolFileDWARFDwo.h" 73#include "SymbolFileDWARFDwp.h" 74 75#include "llvm/DebugInfo/DWARF/DWARFContext.h" 76#include "llvm/Support/FileSystem.h" 77 78#include <algorithm> 79#include <map> 80#include <memory> 81 82#include <ctype.h> 83#include <string.h> 84 85//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN 86 87#ifdef ENABLE_DEBUG_PRINTF 88#include <stdio.h> 89#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__) 90#else 91#define DEBUG_PRINTF(fmt, ...) 92#endif 93 94using namespace lldb; 95using namespace lldb_private; 96 97char SymbolFileDWARF::ID; 98 99// static inline bool 100// child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag) 101//{ 102// switch (tag) 103// { 104// default: 105// break; 106// case DW_TAG_subprogram: 107// case DW_TAG_inlined_subroutine: 108// case DW_TAG_class_type: 109// case DW_TAG_structure_type: 110// case DW_TAG_union_type: 111// return true; 112// } 113// return false; 114//} 115// 116 117namespace { 118 119#define LLDB_PROPERTIES_symbolfiledwarf 120#include "SymbolFileDWARFProperties.inc" 121 122enum { 123#define LLDB_PROPERTIES_symbolfiledwarf 124#include "SymbolFileDWARFPropertiesEnum.inc" 125}; 126 127class PluginProperties : public Properties { 128public: 129 static ConstString GetSettingName() { 130 return SymbolFileDWARF::GetPluginNameStatic(); 131 } 132 133 PluginProperties() { 134 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName()); 135 m_collection_sp->Initialize(g_symbolfiledwarf_properties); 136 } 137 138 FileSpecList GetSymLinkPaths() { 139 const OptionValueFileSpecList *option_value = 140 m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList( 141 nullptr, true, ePropertySymLinkPaths); 142 assert(option_value); 143 return option_value->GetCurrentValue(); 144 } 145 146 bool IgnoreFileIndexes() const { 147 return m_collection_sp->GetPropertyAtIndexAsBoolean( 148 nullptr, ePropertyIgnoreIndexes, false); 149 } 150}; 151 152typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP; 153 154static const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() { 155 static const auto g_settings_sp(std::make_shared<PluginProperties>()); 156 return g_settings_sp; 157} 158 159} // namespace 160 161static const llvm::DWARFDebugLine::LineTable * 162ParseLLVMLineTable(lldb_private::DWARFContext &context, 163 llvm::DWARFDebugLine &line, dw_offset_t line_offset, 164 dw_offset_t unit_offset) { 165 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); 166 167 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM(); 168 llvm::DWARFContext &ctx = context.GetAsLLVM(); 169 llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table = 170 line.getOrParseLineTable( 171 data, line_offset, ctx, nullptr, [&](llvm::Error e) { 172 LLDB_LOG_ERROR(log, std::move(e), 173 "SymbolFileDWARF::ParseLineTable failed to parse"); 174 }); 175 176 if (!line_table) { 177 LLDB_LOG_ERROR(log, line_table.takeError(), 178 "SymbolFileDWARF::ParseLineTable failed to parse"); 179 return nullptr; 180 } 181 return *line_table; 182} 183 184static llvm::Optional<std::string> 185GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx, 186 llvm::StringRef compile_dir, FileSpec::Style style) { 187 // Try to get an absolute path first. 188 std::string abs_path; 189 auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath; 190 if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style)) 191 return std::move(abs_path); 192 193 // Otherwise ask for a relative path. 194 std::string rel_path; 195 auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::Default; 196 if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style)) 197 return {}; 198 return std::move(rel_path); 199} 200 201static FileSpecList 202ParseSupportFilesFromPrologue(const lldb::ModuleSP &module, 203 const llvm::DWARFDebugLine::Prologue &prologue, 204 FileSpec::Style style, 205 llvm::StringRef compile_dir = {}) { 206 FileSpecList support_files; 207 size_t first_file = 0; 208 if (prologue.getVersion() <= 4) { 209 // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure 210 // support file list indices match those we get from the debug info and line 211 // tables. 212 support_files.Append(FileSpec()); 213 first_file = 1; 214 } 215 216 const size_t number_of_files = prologue.FileNames.size(); 217 for (size_t idx = first_file; idx <= number_of_files; ++idx) { 218 std::string remapped_file; 219 if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style)) 220 if (!module->RemapSourceFile(llvm::StringRef(*file_path), remapped_file)) 221 remapped_file = std::move(*file_path); 222 223 // Unconditionally add an entry, so the indices match up. 224 support_files.EmplaceBack(remapped_file, style); 225 } 226 227 return support_files; 228} 229 230FileSpecList SymbolFileDWARF::GetSymlinkPaths() { 231 return GetGlobalPluginProperties()->GetSymLinkPaths(); 232} 233 234void SymbolFileDWARF::Initialize() { 235 LogChannelDWARF::Initialize(); 236 PluginManager::RegisterPlugin(GetPluginNameStatic(), 237 GetPluginDescriptionStatic(), CreateInstance, 238 DebuggerInitialize); 239} 240 241void SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) { 242 if (!PluginManager::GetSettingForSymbolFilePlugin( 243 debugger, PluginProperties::GetSettingName())) { 244 const bool is_global_setting = true; 245 PluginManager::CreateSettingForSymbolFilePlugin( 246 debugger, GetGlobalPluginProperties()->GetValueProperties(), 247 ConstString("Properties for the dwarf symbol-file plug-in."), 248 is_global_setting); 249 } 250} 251 252void SymbolFileDWARF::Terminate() { 253 PluginManager::UnregisterPlugin(CreateInstance); 254 LogChannelDWARF::Terminate(); 255} 256 257lldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() { 258 static ConstString g_name("dwarf"); 259 return g_name; 260} 261 262const char *SymbolFileDWARF::GetPluginDescriptionStatic() { 263 return "DWARF and DWARF3 debug symbol file reader."; 264} 265 266SymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) { 267 return new SymbolFileDWARF(std::move(objfile_sp), 268 /*dwo_section_list*/ nullptr); 269} 270 271TypeList &SymbolFileDWARF::GetTypeList() { 272 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 273 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) 274 return debug_map_symfile->GetTypeList(); 275 return SymbolFile::GetTypeList(); 276} 277void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset, 278 dw_offset_t max_die_offset, uint32_t type_mask, 279 TypeSet &type_set) { 280 if (die) { 281 const dw_offset_t die_offset = die.GetOffset(); 282 283 if (die_offset >= max_die_offset) 284 return; 285 286 if (die_offset >= min_die_offset) { 287 const dw_tag_t tag = die.Tag(); 288 289 bool add_type = false; 290 291 switch (tag) { 292 case DW_TAG_array_type: 293 add_type = (type_mask & eTypeClassArray) != 0; 294 break; 295 case DW_TAG_unspecified_type: 296 case DW_TAG_base_type: 297 add_type = (type_mask & eTypeClassBuiltin) != 0; 298 break; 299 case DW_TAG_class_type: 300 add_type = (type_mask & eTypeClassClass) != 0; 301 break; 302 case DW_TAG_structure_type: 303 add_type = (type_mask & eTypeClassStruct) != 0; 304 break; 305 case DW_TAG_union_type: 306 add_type = (type_mask & eTypeClassUnion) != 0; 307 break; 308 case DW_TAG_enumeration_type: 309 add_type = (type_mask & eTypeClassEnumeration) != 0; 310 break; 311 case DW_TAG_subroutine_type: 312 case DW_TAG_subprogram: 313 case DW_TAG_inlined_subroutine: 314 add_type = (type_mask & eTypeClassFunction) != 0; 315 break; 316 case DW_TAG_pointer_type: 317 add_type = (type_mask & eTypeClassPointer) != 0; 318 break; 319 case DW_TAG_rvalue_reference_type: 320 case DW_TAG_reference_type: 321 add_type = (type_mask & eTypeClassReference) != 0; 322 break; 323 case DW_TAG_typedef: 324 add_type = (type_mask & eTypeClassTypedef) != 0; 325 break; 326 case DW_TAG_ptr_to_member_type: 327 add_type = (type_mask & eTypeClassMemberPointer) != 0; 328 break; 329 default: 330 break; 331 } 332 333 if (add_type) { 334 const bool assert_not_being_parsed = true; 335 Type *type = ResolveTypeUID(die, assert_not_being_parsed); 336 if (type) { 337 if (type_set.find(type) == type_set.end()) 338 type_set.insert(type); 339 } 340 } 341 } 342 343 for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid(); 344 child_die = child_die.GetSibling()) { 345 GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set); 346 } 347 } 348} 349 350void SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope, 351 TypeClass type_mask, TypeList &type_list) 352 353{ 354 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 355 TypeSet type_set; 356 357 CompileUnit *comp_unit = nullptr; 358 DWARFUnit *dwarf_cu = nullptr; 359 if (sc_scope) 360 comp_unit = sc_scope->CalculateSymbolContextCompileUnit(); 361 362 if (comp_unit) { 363 dwarf_cu = GetDWARFCompileUnit(comp_unit); 364 if (!dwarf_cu) 365 return; 366 GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(), 367 dwarf_cu->GetNextUnitOffset(), type_mask, type_set); 368 } else { 369 DWARFDebugInfo *info = DebugInfo(); 370 if (info) { 371 const size_t num_cus = info->GetNumUnits(); 372 for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) { 373 dwarf_cu = info->GetUnitAtIndex(cu_idx); 374 if (dwarf_cu) { 375 GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set); 376 } 377 } 378 } 379 } 380 381 std::set<CompilerType> compiler_type_set; 382 for (Type *type : type_set) { 383 CompilerType compiler_type = type->GetForwardCompilerType(); 384 if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) { 385 compiler_type_set.insert(compiler_type); 386 type_list.Insert(type->shared_from_this()); 387 } 388 } 389} 390 391// Gets the first parent that is a lexical block, function or inlined 392// subroutine, or compile unit. 393DWARFDIE 394SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) { 395 DWARFDIE die; 396 for (die = child_die.GetParent(); die; die = die.GetParent()) { 397 dw_tag_t tag = die.Tag(); 398 399 switch (tag) { 400 case DW_TAG_compile_unit: 401 case DW_TAG_partial_unit: 402 case DW_TAG_subprogram: 403 case DW_TAG_inlined_subroutine: 404 case DW_TAG_lexical_block: 405 return die; 406 default: 407 break; 408 } 409 } 410 return DWARFDIE(); 411} 412 413SymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp, 414 SectionList *dwo_section_list) 415 : SymbolFile(std::move(objfile_sp)), 416 UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to 417 // when this class parses .o files to 418 // contain the .o file index/ID 419 m_debug_map_module_wp(), m_debug_map_symfile(nullptr), 420 m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list), 421 m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false), 422 m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate), 423 m_unique_ast_type_map() {} 424 425SymbolFileDWARF::~SymbolFileDWARF() {} 426 427static ConstString GetDWARFMachOSegmentName() { 428 static ConstString g_dwarf_section_name("__DWARF"); 429 return g_dwarf_section_name; 430} 431 432UniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() { 433 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); 434 if (debug_map_symfile) 435 return debug_map_symfile->GetUniqueDWARFASTTypeMap(); 436 else 437 return m_unique_ast_type_map; 438} 439 440llvm::Expected<TypeSystem &> 441SymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) { 442 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) 443 return debug_map_symfile->GetTypeSystemForLanguage(language); 444 445 auto type_system_or_err = 446 m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language); 447 if (type_system_or_err) { 448 type_system_or_err->SetSymbolFile(this); 449 } 450 return type_system_or_err; 451} 452 453void SymbolFileDWARF::InitializeObject() { 454 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); 455 456 if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) { 457 DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc; 458 LoadSectionData(eSectionTypeDWARFAppleNames, apple_names); 459 LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces); 460 LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types); 461 LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc); 462 463 m_index = AppleDWARFIndex::Create( 464 *GetObjectFile()->GetModule(), apple_names, apple_namespaces, 465 apple_types, apple_objc, m_context.getOrLoadStrData()); 466 467 if (m_index) 468 return; 469 470 DWARFDataExtractor debug_names; 471 LoadSectionData(eSectionTypeDWARFDebugNames, debug_names); 472 if (debug_names.GetByteSize() > 0) { 473 llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or = 474 DebugNamesDWARFIndex::Create( 475 *GetObjectFile()->GetModule(), debug_names, 476 m_context.getOrLoadStrData(), DebugInfo()); 477 if (index_or) { 478 m_index = std::move(*index_or); 479 return; 480 } 481 LLDB_LOG_ERROR(log, index_or.takeError(), 482 "Unable to read .debug_names data: {0}"); 483 } 484 } 485 486 m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(), 487 DebugInfo()); 488} 489 490bool SymbolFileDWARF::SupportedVersion(uint16_t version) { 491 return version >= 2 && version <= 5; 492} 493 494uint32_t SymbolFileDWARF::CalculateAbilities() { 495 uint32_t abilities = 0; 496 if (m_objfile_sp != nullptr) { 497 const Section *section = nullptr; 498 const SectionList *section_list = m_objfile_sp->GetSectionList(); 499 if (section_list == nullptr) 500 return 0; 501 502 uint64_t debug_abbrev_file_size = 0; 503 uint64_t debug_info_file_size = 0; 504 uint64_t debug_line_file_size = 0; 505 506 section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get(); 507 508 if (section) 509 section_list = §ion->GetChildren(); 510 511 section = 512 section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get(); 513 if (section != nullptr) { 514 debug_info_file_size = section->GetFileSize(); 515 516 section = 517 section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true) 518 .get(); 519 if (section) 520 debug_abbrev_file_size = section->GetFileSize(); 521 522 DWARFDebugAbbrev *abbrev = DebugAbbrev(); 523 if (abbrev) { 524 std::set<dw_form_t> invalid_forms; 525 abbrev->GetUnsupportedForms(invalid_forms); 526 if (!invalid_forms.empty()) { 527 StreamString error; 528 error.Printf("unsupported DW_FORM value%s:", 529 invalid_forms.size() > 1 ? "s" : ""); 530 for (auto form : invalid_forms) 531 error.Printf(" %#x", form); 532 m_objfile_sp->GetModule()->ReportWarning( 533 "%s", error.GetString().str().c_str()); 534 return 0; 535 } 536 } 537 538 section = 539 section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true) 540 .get(); 541 if (section) 542 debug_line_file_size = section->GetFileSize(); 543 } else { 544 const char *symfile_dir_cstr = 545 m_objfile_sp->GetFileSpec().GetDirectory().GetCString(); 546 if (symfile_dir_cstr) { 547 if (strcasestr(symfile_dir_cstr, ".dsym")) { 548 if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) { 549 // We have a dSYM file that didn't have a any debug info. If the 550 // string table has a size of 1, then it was made from an 551 // executable with no debug info, or from an executable that was 552 // stripped. 553 section = 554 section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true) 555 .get(); 556 if (section && section->GetFileSize() == 1) { 557 m_objfile_sp->GetModule()->ReportWarning( 558 "empty dSYM file detected, dSYM was created with an " 559 "executable with no debug info."); 560 } 561 } 562 } 563 } 564 } 565 566 if (debug_abbrev_file_size > 0 && debug_info_file_size > 0) 567 abilities |= CompileUnits | Functions | Blocks | GlobalVariables | 568 LocalVariables | VariableTypes; 569 570 if (debug_line_file_size > 0) 571 abilities |= LineTables; 572 } 573 return abilities; 574} 575 576const DWARFDataExtractor & 577SymbolFileDWARF::GetCachedSectionData(lldb::SectionType sect_type, 578 DWARFDataSegment &data_segment) { 579 llvm::call_once(data_segment.m_flag, [this, sect_type, &data_segment] { 580 this->LoadSectionData(sect_type, std::ref(data_segment.m_data)); 581 }); 582 return data_segment.m_data; 583} 584 585void SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type, 586 DWARFDataExtractor &data) { 587 ModuleSP module_sp(m_objfile_sp->GetModule()); 588 const SectionList *section_list = module_sp->GetSectionList(); 589 if (!section_list) 590 return; 591 592 SectionSP section_sp(section_list->FindSectionByType(sect_type, true)); 593 if (!section_sp) 594 return; 595 596 data.Clear(); 597 m_objfile_sp->ReadSectionData(section_sp.get(), data); 598} 599 600DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() { 601 if (m_abbr) 602 return m_abbr.get(); 603 604 const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData(); 605 if (debug_abbrev_data.GetByteSize() == 0) 606 return nullptr; 607 608 auto abbr = std::make_unique<DWARFDebugAbbrev>(); 609 llvm::Error error = abbr->parse(debug_abbrev_data); 610 if (error) { 611 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); 612 LLDB_LOG_ERROR(log, std::move(error), 613 "Unable to read .debug_abbrev section: {0}"); 614 return nullptr; 615 } 616 617 m_abbr = std::move(abbr); 618 return m_abbr.get(); 619} 620 621const DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const { 622 return m_abbr.get(); 623} 624 625DWARFDebugInfo *SymbolFileDWARF::DebugInfo() { 626 if (m_info == nullptr) { 627 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 628 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, 629 static_cast<void *>(this)); 630 if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0) 631 m_info = std::make_unique<DWARFDebugInfo>(*this, m_context); 632 } 633 return m_info.get(); 634} 635 636const DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const { 637 return m_info.get(); 638} 639 640DWARFUnit * 641SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) { 642 if (!comp_unit) 643 return nullptr; 644 645 DWARFDebugInfo *info = DebugInfo(); 646 if (info) { 647 // The compile unit ID is the index of the DWARF unit. 648 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID()); 649 if (dwarf_cu && dwarf_cu->GetUserData() == nullptr) 650 dwarf_cu->SetUserData(comp_unit); 651 return dwarf_cu; 652 } 653 return nullptr; 654} 655 656DWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() { 657 if (!m_ranges) { 658 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 659 Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION, 660 static_cast<void *>(this)); 661 662 if (m_context.getOrLoadRangesData().GetByteSize() > 0) 663 m_ranges.reset(new DWARFDebugRanges()); 664 665 if (m_ranges) 666 m_ranges->Extract(m_context); 667 } 668 return m_ranges.get(); 669} 670 671lldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) { 672 CompUnitSP cu_sp; 673 CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData(); 674 if (comp_unit) { 675 // We already parsed this compile unit, had out a shared pointer to it 676 cu_sp = comp_unit->shared_from_this(); 677 } else { 678 if (&dwarf_cu.GetSymbolFileDWARF() != this) { 679 return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu); 680 } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) { 681 // Let the debug map create the compile unit 682 cu_sp = m_debug_map_symfile->GetCompileUnit(this); 683 dwarf_cu.SetUserData(cu_sp.get()); 684 } else { 685 ModuleSP module_sp(m_objfile_sp->GetModule()); 686 if (module_sp) { 687 const DWARFBaseDIE cu_die = 688 dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly(); 689 if (cu_die) { 690 FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle()); 691 if (cu_file_spec) { 692 // If we have a full path to the compile unit, we don't need to 693 // resolve the file. This can be expensive e.g. when the source 694 // files are NFS mounted. 695 cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory()); 696 697 std::string remapped_file; 698 if (module_sp->RemapSourceFile(cu_file_spec.GetPath(), 699 remapped_file)) 700 cu_file_spec.SetFile(remapped_file, FileSpec::Style::native); 701 } 702 703 LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF( 704 cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0)); 705 706 bool is_optimized = dwarf_cu.GetNonSkeletonUnit().GetIsOptimized(); 707 BuildCuTranslationTable(); 708 cu_sp = std::make_shared<CompileUnit>( 709 module_sp, &dwarf_cu, cu_file_spec, 710 *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language, 711 is_optimized ? eLazyBoolYes : eLazyBoolNo); 712 713 dwarf_cu.SetUserData(cu_sp.get()); 714 715 SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp); 716 } 717 } 718 } 719 } 720 return cu_sp; 721} 722 723void SymbolFileDWARF::BuildCuTranslationTable() { 724 if (!m_lldb_cu_to_dwarf_unit.empty()) 725 return; 726 727 DWARFDebugInfo *info = DebugInfo(); 728 if (!info) 729 return; 730 731 if (!info->ContainsTypeUnits()) { 732 // We can use a 1-to-1 mapping. No need to build a translation table. 733 return; 734 } 735 for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) { 736 if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) { 737 cu->SetID(m_lldb_cu_to_dwarf_unit.size()); 738 m_lldb_cu_to_dwarf_unit.push_back(i); 739 } 740 } 741} 742 743llvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) { 744 BuildCuTranslationTable(); 745 if (m_lldb_cu_to_dwarf_unit.empty()) 746 return cu_idx; 747 if (cu_idx >= m_lldb_cu_to_dwarf_unit.size()) 748 return llvm::None; 749 return m_lldb_cu_to_dwarf_unit[cu_idx]; 750} 751 752uint32_t SymbolFileDWARF::CalculateNumCompileUnits() { 753 DWARFDebugInfo *info = DebugInfo(); 754 if (!info) 755 return 0; 756 BuildCuTranslationTable(); 757 return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits() 758 : m_lldb_cu_to_dwarf_unit.size(); 759} 760 761CompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) { 762 ASSERT_MODULE_LOCK(this); 763 DWARFDebugInfo *info = DebugInfo(); 764 if (!info) 765 return {}; 766 767 if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) { 768 if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>( 769 info->GetUnitAtIndex(*dwarf_idx))) 770 return ParseCompileUnit(*dwarf_cu); 771 } 772 return {}; 773} 774 775Function *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit, 776 const DWARFDIE &die) { 777 ASSERT_MODULE_LOCK(this); 778 if (!die.IsValid()) 779 return nullptr; 780 781 auto type_system_or_err = 782 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType()); 783 if (auto err = type_system_or_err.takeError()) { 784 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 785 std::move(err), "Unable to parse function"); 786 return nullptr; 787 } 788 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser(); 789 if (!dwarf_ast) 790 return nullptr; 791 792 return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die); 793} 794 795bool SymbolFileDWARF::FixupAddress(Address &addr) { 796 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); 797 if (debug_map_symfile) { 798 return debug_map_symfile->LinkOSOAddress(addr); 799 } 800 // This is a normal DWARF file, no address fixups need to happen 801 return true; 802} 803lldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) { 804 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 805 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 806 if (dwarf_cu) 807 return dwarf_cu->GetLanguageType(); 808 else 809 return eLanguageTypeUnknown; 810} 811 812size_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) { 813 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 814 Timer scoped_timer(func_cat, "SymbolFileDWARF::ParseFunctions"); 815 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 816 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 817 if (!dwarf_cu) 818 return 0; 819 820 size_t functions_added = 0; 821 dwarf_cu = &dwarf_cu->GetNonSkeletonUnit(); 822 for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) { 823 if (entry.Tag() != DW_TAG_subprogram) 824 continue; 825 826 DWARFDIE die(dwarf_cu, &entry); 827 if (comp_unit.FindFunctionByUID(die.GetID())) 828 continue; 829 if (ParseFunction(comp_unit, die)) 830 ++functions_added; 831 } 832 // FixupTypes(); 833 return functions_added; 834} 835 836bool SymbolFileDWARF::ForEachExternalModule( 837 CompileUnit &comp_unit, 838 llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files, 839 llvm::function_ref<bool(Module &)> lambda) { 840 // Only visit each symbol file once. 841 if (!visited_symbol_files.insert(this).second) 842 return false; 843 844 UpdateExternalModuleListIfNeeded(); 845 for (auto &p : m_external_type_modules) { 846 ModuleSP module = p.second; 847 if (!module) 848 continue; 849 850 // Invoke the action and potentially early-exit. 851 if (lambda(*module)) 852 return true; 853 854 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) { 855 auto cu = module->GetCompileUnitAtIndex(i); 856 bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda); 857 if (early_exit) 858 return true; 859 } 860 } 861 return false; 862} 863 864bool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit, 865 FileSpecList &support_files) { 866 if (!comp_unit.GetLineTable()) 867 ParseLineTable(comp_unit); 868 return true; 869} 870 871FileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) { 872 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) { 873 if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu)) 874 return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx); 875 return FileSpec(); 876 } 877 878 auto &tu = llvm::cast<DWARFTypeUnit>(unit); 879 return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx); 880} 881 882const FileSpecList & 883SymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) { 884 static FileSpecList empty_list; 885 886 dw_offset_t offset = tu.GetLineTableOffset(); 887 if (offset == DW_INVALID_OFFSET || 888 offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() || 889 offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey()) 890 return empty_list; 891 892 // Many type units can share a line table, so parse the support file list 893 // once, and cache it based on the offset field. 894 auto iter_bool = m_type_unit_support_files.try_emplace(offset); 895 FileSpecList &list = iter_bool.first->second; 896 if (iter_bool.second) { 897 uint64_t line_table_offset = offset; 898 llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM(); 899 llvm::DWARFContext &ctx = m_context.GetAsLLVM(); 900 llvm::DWARFDebugLine::Prologue prologue; 901 llvm::Error error = prologue.parse(data, &line_table_offset, ctx); 902 if (error) { 903 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); 904 LLDB_LOG_ERROR(log, std::move(error), 905 "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse " 906 "the line table prologue"); 907 } else { 908 list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(), 909 prologue, tu.GetPathStyle()); 910 } 911 } 912 return list; 913} 914 915bool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) { 916 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 917 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 918 if (dwarf_cu) 919 return dwarf_cu->GetIsOptimized(); 920 return false; 921} 922 923bool SymbolFileDWARF::ParseImportedModules( 924 const lldb_private::SymbolContext &sc, 925 std::vector<SourceModule> &imported_modules) { 926 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 927 assert(sc.comp_unit); 928 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit); 929 if (!dwarf_cu) 930 return false; 931 if (!ClangModulesDeclVendor::LanguageSupportsClangModules( 932 sc.comp_unit->GetLanguage())) 933 return false; 934 UpdateExternalModuleListIfNeeded(); 935 936 const DWARFDIE die = dwarf_cu->DIE(); 937 if (!die) 938 return false; 939 940 for (DWARFDIE child_die = die.GetFirstChild(); child_die; 941 child_die = child_die.GetSibling()) { 942 if (child_die.Tag() != DW_TAG_imported_declaration) 943 continue; 944 945 DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import); 946 if (module_die.Tag() != DW_TAG_module) 947 continue; 948 949 if (const char *name = 950 module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) { 951 SourceModule module; 952 module.path.push_back(ConstString(name)); 953 954 DWARFDIE parent_die = module_die; 955 while ((parent_die = parent_die.GetParent())) { 956 if (parent_die.Tag() != DW_TAG_module) 957 break; 958 if (const char *name = 959 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr)) 960 module.path.push_back(ConstString(name)); 961 } 962 std::reverse(module.path.begin(), module.path.end()); 963 if (const char *include_path = module_die.GetAttributeValueAsString( 964 DW_AT_LLVM_include_path, nullptr)) 965 module.search_path = ConstString(include_path); 966 if (const char *sysroot = module_die.GetAttributeValueAsString( 967 DW_AT_LLVM_sysroot, nullptr)) 968 module.sysroot = ConstString(sysroot); 969 imported_modules.push_back(module); 970 } 971 } 972 return true; 973} 974 975bool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) { 976 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 977 if (comp_unit.GetLineTable() != nullptr) 978 return true; 979 980 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 981 if (!dwarf_cu) 982 return false; 983 984 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly(); 985 if (!dwarf_cu_die) 986 return false; 987 988 const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned( 989 DW_AT_stmt_list, DW_INVALID_OFFSET); 990 if (cu_line_offset == DW_INVALID_OFFSET) 991 return false; 992 993 llvm::DWARFDebugLine line; 994 const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable( 995 m_context, line, cu_line_offset, dwarf_cu->GetOffset()); 996 997 if (!line_table) 998 return false; 999 1000 // FIXME: Rather than parsing the whole line table and then copying it over 1001 // into LLDB, we should explore using a callback to populate the line table 1002 // while we parse to reduce memory usage. 1003 std::unique_ptr<LineTable> line_table_up = 1004 std::make_unique<LineTable>(&comp_unit); 1005 LineSequence *sequence = line_table_up->CreateLineSequenceContainer(); 1006 for (auto &row : line_table->Rows) { 1007 line_table_up->AppendLineEntryToSequence( 1008 sequence, row.Address.Address, row.Line, row.Column, row.File, 1009 row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin, 1010 row.EndSequence); 1011 if (row.EndSequence) { 1012 line_table_up->InsertSequence(sequence); 1013 sequence = line_table_up->CreateLineSequenceContainer(); 1014 } 1015 } 1016 1017 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) { 1018 // We have an object file that has a line table with addresses that are not 1019 // linked. We need to link the line table and convert the addresses that 1020 // are relative to the .o file into addresses for the main executable. 1021 comp_unit.SetLineTable( 1022 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get())); 1023 } else { 1024 comp_unit.SetLineTable(line_table_up.release()); 1025 } 1026 1027 comp_unit.SetSupportFiles(ParseSupportFilesFromPrologue( 1028 comp_unit.GetModule(), line_table->Prologue, dwarf_cu->GetPathStyle(), 1029 dwarf_cu->GetCompilationDirectory().GetCString())); 1030 1031 return true; 1032} 1033 1034lldb_private::DebugMacrosSP 1035SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) { 1036 auto iter = m_debug_macros_map.find(*offset); 1037 if (iter != m_debug_macros_map.end()) 1038 return iter->second; 1039 1040 const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData(); 1041 if (debug_macro_data.GetByteSize() == 0) 1042 return DebugMacrosSP(); 1043 1044 lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros()); 1045 m_debug_macros_map[*offset] = debug_macros_sp; 1046 1047 const DWARFDebugMacroHeader &header = 1048 DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset); 1049 DWARFDebugMacroEntry::ReadMacroEntries( 1050 debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(), 1051 offset, this, debug_macros_sp); 1052 1053 return debug_macros_sp; 1054} 1055 1056bool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) { 1057 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1058 1059 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 1060 if (dwarf_cu == nullptr) 1061 return false; 1062 1063 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly(); 1064 if (!dwarf_cu_die) 1065 return false; 1066 1067 lldb::offset_t sect_offset = 1068 dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET); 1069 if (sect_offset == DW_INVALID_OFFSET) 1070 sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros, 1071 DW_INVALID_OFFSET); 1072 if (sect_offset == DW_INVALID_OFFSET) 1073 return false; 1074 1075 comp_unit.SetDebugMacros(ParseDebugMacros(§_offset)); 1076 1077 return true; 1078} 1079 1080size_t SymbolFileDWARF::ParseBlocksRecursive( 1081 lldb_private::CompileUnit &comp_unit, Block *parent_block, 1082 const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) { 1083 size_t blocks_added = 0; 1084 DWARFDIE die = orig_die; 1085 while (die) { 1086 dw_tag_t tag = die.Tag(); 1087 1088 switch (tag) { 1089 case DW_TAG_inlined_subroutine: 1090 case DW_TAG_subprogram: 1091 case DW_TAG_lexical_block: { 1092 Block *block = nullptr; 1093 if (tag == DW_TAG_subprogram) { 1094 // Skip any DW_TAG_subprogram DIEs that are inside of a normal or 1095 // inlined functions. These will be parsed on their own as separate 1096 // entities. 1097 1098 if (depth > 0) 1099 break; 1100 1101 block = parent_block; 1102 } else { 1103 BlockSP block_sp(new Block(die.GetID())); 1104 parent_block->AddChild(block_sp); 1105 block = block_sp.get(); 1106 } 1107 DWARFRangeList ranges; 1108 const char *name = nullptr; 1109 const char *mangled_name = nullptr; 1110 1111 int decl_file = 0; 1112 int decl_line = 0; 1113 int decl_column = 0; 1114 int call_file = 0; 1115 int call_line = 0; 1116 int call_column = 0; 1117 if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file, 1118 decl_line, decl_column, call_file, call_line, 1119 call_column, nullptr)) { 1120 if (tag == DW_TAG_subprogram) { 1121 assert(subprogram_low_pc == LLDB_INVALID_ADDRESS); 1122 subprogram_low_pc = ranges.GetMinRangeBase(0); 1123 } else if (tag == DW_TAG_inlined_subroutine) { 1124 // We get called here for inlined subroutines in two ways. The first 1125 // time is when we are making the Function object for this inlined 1126 // concrete instance. Since we're creating a top level block at 1127 // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS. So we 1128 // need to adjust the containing address. The second time is when we 1129 // are parsing the blocks inside the function that contains the 1130 // inlined concrete instance. Since these will be blocks inside the 1131 // containing "real" function the offset will be for that function. 1132 if (subprogram_low_pc == LLDB_INVALID_ADDRESS) { 1133 subprogram_low_pc = ranges.GetMinRangeBase(0); 1134 } 1135 } 1136 1137 const size_t num_ranges = ranges.GetSize(); 1138 for (size_t i = 0; i < num_ranges; ++i) { 1139 const DWARFRangeList::Entry &range = ranges.GetEntryRef(i); 1140 const addr_t range_base = range.GetRangeBase(); 1141 if (range_base >= subprogram_low_pc) 1142 block->AddRange(Block::Range(range_base - subprogram_low_pc, 1143 range.GetByteSize())); 1144 else { 1145 GetObjectFile()->GetModule()->ReportError( 1146 "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64 1147 ") which has a base that is less than the function's low PC " 1148 "0x%" PRIx64 ". Please file a bug and attach the file at the " 1149 "start of this error message", 1150 block->GetID(), range_base, range.GetRangeEnd(), 1151 subprogram_low_pc); 1152 } 1153 } 1154 block->FinalizeRanges(); 1155 1156 if (tag != DW_TAG_subprogram && 1157 (name != nullptr || mangled_name != nullptr)) { 1158 std::unique_ptr<Declaration> decl_up; 1159 if (decl_file != 0 || decl_line != 0 || decl_column != 0) 1160 decl_up.reset(new Declaration( 1161 comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file), 1162 decl_line, decl_column)); 1163 1164 std::unique_ptr<Declaration> call_up; 1165 if (call_file != 0 || call_line != 0 || call_column != 0) 1166 call_up.reset(new Declaration( 1167 comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file), 1168 call_line, call_column)); 1169 1170 block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(), 1171 call_up.get()); 1172 } 1173 1174 ++blocks_added; 1175 1176 if (die.HasChildren()) { 1177 blocks_added += 1178 ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(), 1179 subprogram_low_pc, depth + 1); 1180 } 1181 } 1182 } break; 1183 default: 1184 break; 1185 } 1186 1187 // Only parse siblings of the block if we are not at depth zero. A depth of 1188 // zero indicates we are currently parsing the top level DW_TAG_subprogram 1189 // DIE 1190 1191 if (depth == 0) 1192 die.Clear(); 1193 else 1194 die = die.GetSibling(); 1195 } 1196 return blocks_added; 1197} 1198 1199bool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) { 1200 if (parent_die) { 1201 for (DWARFDIE die = parent_die.GetFirstChild(); die; 1202 die = die.GetSibling()) { 1203 dw_tag_t tag = die.Tag(); 1204 bool check_virtuality = false; 1205 switch (tag) { 1206 case DW_TAG_inheritance: 1207 case DW_TAG_subprogram: 1208 check_virtuality = true; 1209 break; 1210 default: 1211 break; 1212 } 1213 if (check_virtuality) { 1214 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0) 1215 return true; 1216 } 1217 } 1218 } 1219 return false; 1220} 1221 1222void SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) { 1223 auto *type_system = decl_ctx.GetTypeSystem(); 1224 if (type_system != nullptr) 1225 type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed( 1226 decl_ctx); 1227} 1228 1229user_id_t SymbolFileDWARF::GetUID(DIERef ref) { 1230 if (GetDebugMapSymfile()) 1231 return GetID() | ref.die_offset(); 1232 1233 return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 | 1234 ref.die_offset() | 1235 (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63); 1236} 1237 1238llvm::Optional<SymbolFileDWARF::DecodedUID> 1239SymbolFileDWARF::DecodeUID(lldb::user_id_t uid) { 1240 // This method can be called without going through the symbol vendor so we 1241 // need to lock the module. 1242 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1243 // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we 1244 // must make sure we use the correct DWARF file when resolving things. On 1245 // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple 1246 // SymbolFileDWARF classes, one for each .o file. We can often end up with 1247 // references to other DWARF objects and we must be ready to receive a 1248 // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF 1249 // instance. 1250 if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) { 1251 SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex( 1252 debug_map->GetOSOIndexFromUserID(uid)); 1253 return DecodedUID{ 1254 *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}}; 1255 } 1256 dw_offset_t die_offset = uid; 1257 if (die_offset == DW_INVALID_OFFSET) 1258 return llvm::None; 1259 1260 DIERef::Section section = 1261 uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo; 1262 1263 llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff; 1264 if (*dwo_num == 0x7fffffff) 1265 dwo_num = llvm::None; 1266 1267 return DecodedUID{*this, {dwo_num, section, die_offset}}; 1268} 1269 1270DWARFDIE 1271SymbolFileDWARF::GetDIE(lldb::user_id_t uid) { 1272 // This method can be called without going through the symbol vendor so we 1273 // need to lock the module. 1274 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1275 1276 llvm::Optional<DecodedUID> decoded = DecodeUID(uid); 1277 1278 if (decoded) 1279 return decoded->dwarf.GetDIE(decoded->ref); 1280 1281 return DWARFDIE(); 1282} 1283 1284CompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) { 1285 // This method can be called without going through the symbol vendor so we 1286 // need to lock the module. 1287 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1288 // Anytime we have a lldb::user_id_t, we must get the DIE by calling 1289 // SymbolFileDWARF::GetDIE(). See comments inside the 1290 // SymbolFileDWARF::GetDIE() for details. 1291 if (DWARFDIE die = GetDIE(type_uid)) 1292 return die.GetDecl(); 1293 return CompilerDecl(); 1294} 1295 1296CompilerDeclContext 1297SymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) { 1298 // This method can be called without going through the symbol vendor so we 1299 // need to lock the module. 1300 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1301 // Anytime we have a lldb::user_id_t, we must get the DIE by calling 1302 // SymbolFileDWARF::GetDIE(). See comments inside the 1303 // SymbolFileDWARF::GetDIE() for details. 1304 if (DWARFDIE die = GetDIE(type_uid)) 1305 return die.GetDeclContext(); 1306 return CompilerDeclContext(); 1307} 1308 1309CompilerDeclContext 1310SymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) { 1311 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1312 // Anytime we have a lldb::user_id_t, we must get the DIE by calling 1313 // SymbolFileDWARF::GetDIE(). See comments inside the 1314 // SymbolFileDWARF::GetDIE() for details. 1315 if (DWARFDIE die = GetDIE(type_uid)) 1316 return die.GetContainingDeclContext(); 1317 return CompilerDeclContext(); 1318} 1319 1320Type *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) { 1321 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1322 // Anytime we have a lldb::user_id_t, we must get the DIE by calling 1323 // SymbolFileDWARF::GetDIE(). See comments inside the 1324 // SymbolFileDWARF::GetDIE() for details. 1325 if (DWARFDIE type_die = GetDIE(type_uid)) 1326 return type_die.ResolveType(); 1327 else 1328 return nullptr; 1329} 1330 1331llvm::Optional<SymbolFile::ArrayInfo> 1332SymbolFileDWARF::GetDynamicArrayInfoForUID( 1333 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) { 1334 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1335 if (DWARFDIE type_die = GetDIE(type_uid)) 1336 return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx); 1337 else 1338 return llvm::None; 1339} 1340 1341Type *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) { 1342 return ResolveType(GetDIE(die_ref), true); 1343} 1344 1345Type *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die, 1346 bool assert_not_being_parsed) { 1347 if (die) { 1348 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO)); 1349 if (log) 1350 GetObjectFile()->GetModule()->LogMessage( 1351 log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'", 1352 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 1353 1354 // We might be coming in in the middle of a type tree (a class within a 1355 // class, an enum within a class), so parse any needed parent DIEs before 1356 // we get to this one... 1357 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die); 1358 if (decl_ctx_die) { 1359 if (log) { 1360 switch (decl_ctx_die.Tag()) { 1361 case DW_TAG_structure_type: 1362 case DW_TAG_union_type: 1363 case DW_TAG_class_type: { 1364 // Get the type, which could be a forward declaration 1365 if (log) 1366 GetObjectFile()->GetModule()->LogMessage( 1367 log, 1368 "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' " 1369 "resolve parent forward type for 0x%8.8x", 1370 die.GetOffset(), die.GetTagAsCString(), die.GetName(), 1371 decl_ctx_die.GetOffset()); 1372 } break; 1373 1374 default: 1375 break; 1376 } 1377 } 1378 } 1379 return ResolveType(die); 1380 } 1381 return nullptr; 1382} 1383 1384// This function is used when SymbolFileDWARFDebugMap owns a bunch of 1385// SymbolFileDWARF objects to detect if this DWARF file is the one that can 1386// resolve a compiler_type. 1387bool SymbolFileDWARF::HasForwardDeclForClangType( 1388 const CompilerType &compiler_type) { 1389 CompilerType compiler_type_no_qualifiers = 1390 ClangUtil::RemoveFastQualifiers(compiler_type); 1391 if (GetForwardDeclClangTypeToDie().count( 1392 compiler_type_no_qualifiers.GetOpaqueQualType())) { 1393 return true; 1394 } 1395 TypeSystem *type_system = compiler_type.GetTypeSystem(); 1396 1397 ClangASTContext *clang_type_system = 1398 llvm::dyn_cast_or_null<ClangASTContext>(type_system); 1399 if (!clang_type_system) 1400 return false; 1401 DWARFASTParserClang *ast_parser = 1402 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser()); 1403 return ast_parser->GetClangASTImporter().CanImport(compiler_type); 1404} 1405 1406bool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) { 1407 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1408 1409 ClangASTContext *clang_type_system = 1410 llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem()); 1411 if (clang_type_system) { 1412 DWARFASTParserClang *ast_parser = 1413 static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser()); 1414 if (ast_parser && 1415 ast_parser->GetClangASTImporter().CanImport(compiler_type)) 1416 return ast_parser->GetClangASTImporter().CompleteType(compiler_type); 1417 } 1418 1419 // We have a struct/union/class/enum that needs to be fully resolved. 1420 CompilerType compiler_type_no_qualifiers = 1421 ClangUtil::RemoveFastQualifiers(compiler_type); 1422 auto die_it = GetForwardDeclClangTypeToDie().find( 1423 compiler_type_no_qualifiers.GetOpaqueQualType()); 1424 if (die_it == GetForwardDeclClangTypeToDie().end()) { 1425 // We have already resolved this type... 1426 return true; 1427 } 1428 1429 DWARFDIE dwarf_die = GetDIE(die_it->getSecond()); 1430 if (dwarf_die) { 1431 // Once we start resolving this type, remove it from the forward 1432 // declaration map in case anyone child members or other types require this 1433 // type to get resolved. The type will get resolved when all of the calls 1434 // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done. 1435 GetForwardDeclClangTypeToDie().erase(die_it); 1436 1437 Type *type = GetDIEToType().lookup(dwarf_die.GetDIE()); 1438 1439 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | 1440 DWARF_LOG_TYPE_COMPLETION)); 1441 if (log) 1442 GetObjectFile()->GetModule()->LogMessageVerboseBacktrace( 1443 log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...", 1444 dwarf_die.GetID(), dwarf_die.GetTagAsCString(), 1445 type->GetName().AsCString()); 1446 assert(compiler_type); 1447 DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser(); 1448 if (dwarf_ast) 1449 return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type); 1450 } 1451 return false; 1452} 1453 1454Type *SymbolFileDWARF::ResolveType(const DWARFDIE &die, 1455 bool assert_not_being_parsed, 1456 bool resolve_function_context) { 1457 if (die) { 1458 Type *type = GetTypeForDIE(die, resolve_function_context).get(); 1459 1460 if (assert_not_being_parsed) { 1461 if (type != DIE_IS_BEING_PARSED) 1462 return type; 1463 1464 GetObjectFile()->GetModule()->ReportError( 1465 "Parsing a die that is being parsed die: 0x%8.8x: %s %s", 1466 die.GetOffset(), die.GetTagAsCString(), die.GetName()); 1467 1468 } else 1469 return type; 1470 } 1471 return nullptr; 1472} 1473 1474CompileUnit * 1475SymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) { 1476 // Check if the symbol vendor already knows about this compile unit? 1477 if (dwarf_cu.GetUserData() == nullptr) { 1478 // The symbol vendor doesn't know about this compile unit, we need to parse 1479 // and add it to the symbol vendor object. 1480 return ParseCompileUnit(dwarf_cu).get(); 1481 } 1482 return (CompileUnit *)dwarf_cu.GetUserData(); 1483} 1484 1485size_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name, 1486 DIEArray &method_die_offsets) { 1487 method_die_offsets.clear(); 1488 m_index->GetObjCMethods(class_name, method_die_offsets); 1489 return method_die_offsets.size(); 1490} 1491 1492bool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) { 1493 sc.Clear(false); 1494 1495 if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) { 1496 // Check if the symbol vendor already knows about this compile unit? 1497 sc.comp_unit = 1498 GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU())); 1499 1500 sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); 1501 if (sc.function == nullptr) 1502 sc.function = ParseFunction(*sc.comp_unit, die); 1503 1504 if (sc.function) { 1505 sc.module_sp = sc.function->CalculateSymbolContextModule(); 1506 return true; 1507 } 1508 } 1509 1510 return false; 1511} 1512 1513lldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) { 1514 UpdateExternalModuleListIfNeeded(); 1515 const auto &pos = m_external_type_modules.find(name); 1516 if (pos != m_external_type_modules.end()) 1517 return pos->second; 1518 else 1519 return lldb::ModuleSP(); 1520} 1521 1522DWARFDIE 1523SymbolFileDWARF::GetDIE(const DIERef &die_ref) { 1524 if (die_ref.dwo_num()) { 1525 return DebugInfo() 1526 ->GetUnitAtIndex(*die_ref.dwo_num()) 1527 ->GetDwoSymbolFile() 1528 ->GetDIE(die_ref); 1529 } 1530 1531 DWARFDebugInfo *debug_info = DebugInfo(); 1532 if (debug_info) 1533 return debug_info->GetDIE(die_ref); 1534 else 1535 return DWARFDIE(); 1536} 1537 1538/// Return the DW_AT_(GNU_)dwo_name. 1539static const char *GetDWOName(DWARFCompileUnit &dwarf_cu, 1540 const DWARFDebugInfoEntry &cu_die) { 1541 const char *dwo_name = 1542 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr); 1543 if (!dwo_name) 1544 dwo_name = 1545 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr); 1546 return dwo_name; 1547} 1548 1549/// Return the DW_AT_(GNU_)dwo_id. 1550/// FIXME: Technically 0 is a valid hash. 1551static uint64_t GetDWOId(DWARFCompileUnit &dwarf_cu, 1552 const DWARFDebugInfoEntry &cu_die) { 1553 uint64_t dwo_id = 1554 cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id, 0); 1555 if (!dwo_id) 1556 dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_dwo_id, 0); 1557 return dwo_id; 1558} 1559 1560llvm::Optional<uint64_t> SymbolFileDWARF::GetDWOId() { 1561 if (GetNumCompileUnits() == 1) { 1562 if (auto comp_unit = GetCompileUnitAtIndex(0)) 1563 if (DWARFCompileUnit *cu = llvm::dyn_cast_or_null<DWARFCompileUnit>( 1564 GetDWARFCompileUnit(comp_unit.get()))) 1565 if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE()) 1566 if (uint64_t dwo_id = ::GetDWOId(*cu, *cu_die)) 1567 return dwo_id; 1568 } 1569 return {}; 1570} 1571 1572std::unique_ptr<SymbolFileDWARFDwo> 1573SymbolFileDWARF::GetDwoSymbolFileForCompileUnit( 1574 DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) { 1575 // If this is a Darwin-style debug map (non-.dSYM) symbol file, 1576 // never attempt to load ELF-style DWO files since the -gmodules 1577 // support uses the same DWO machanism to specify full debug info 1578 // files for modules. This is handled in 1579 // UpdateExternalModuleListIfNeeded(). 1580 if (GetDebugMapSymfile()) 1581 return nullptr; 1582 1583 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit); 1584 // Only compile units can be split into two parts. 1585 if (!dwarf_cu) 1586 return nullptr; 1587 1588 const char *dwo_name = GetDWOName(*dwarf_cu, cu_die); 1589 if (!dwo_name) 1590 return nullptr; 1591 1592 SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile(); 1593 if (dwp_symfile) { 1594 uint64_t dwo_id = ::GetDWOId(*dwarf_cu, cu_die); 1595 std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile = 1596 dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id); 1597 if (dwo_symfile) 1598 return dwo_symfile; 1599 } 1600 1601 FileSpec dwo_file(dwo_name); 1602 FileSystem::Instance().Resolve(dwo_file); 1603 if (dwo_file.IsRelative()) { 1604 const char *comp_dir = 1605 cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr); 1606 if (!comp_dir) 1607 return nullptr; 1608 1609 dwo_file.SetFile(comp_dir, FileSpec::Style::native); 1610 FileSystem::Instance().Resolve(dwo_file); 1611 dwo_file.AppendPathComponent(dwo_name); 1612 } 1613 1614 if (!FileSystem::Instance().Exists(dwo_file)) 1615 return nullptr; 1616 1617 const lldb::offset_t file_offset = 0; 1618 DataBufferSP dwo_file_data_sp; 1619 lldb::offset_t dwo_file_data_offset = 0; 1620 ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin( 1621 GetObjectFile()->GetModule(), &dwo_file, file_offset, 1622 FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp, 1623 dwo_file_data_offset); 1624 if (dwo_obj_file == nullptr) 1625 return nullptr; 1626 1627 return std::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu); 1628} 1629 1630void SymbolFileDWARF::UpdateExternalModuleListIfNeeded() { 1631 if (m_fetched_external_modules) 1632 return; 1633 m_fetched_external_modules = true; 1634 DWARFDebugInfo *debug_info = DebugInfo(); 1635 1636 // Follow DWO skeleton unit breadcrumbs. 1637 const uint32_t num_compile_units = GetNumCompileUnits(); 1638 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { 1639 auto *dwarf_cu = 1640 llvm::dyn_cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(cu_idx)); 1641 if (!dwarf_cu) 1642 continue; 1643 1644 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly(); 1645 if (!die || die.HasChildren() || !die.GetDIE()) 1646 continue; 1647 1648 const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr); 1649 if (!name) 1650 continue; 1651 1652 ConstString const_name(name); 1653 ModuleSP &module_sp = m_external_type_modules[const_name]; 1654 if (module_sp) 1655 continue; 1656 1657 const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE()); 1658 if (!dwo_path) 1659 continue; 1660 1661 ModuleSpec dwo_module_spec; 1662 dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native); 1663 if (dwo_module_spec.GetFileSpec().IsRelative()) { 1664 const char *comp_dir = 1665 die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr); 1666 if (comp_dir) { 1667 dwo_module_spec.GetFileSpec().SetFile(comp_dir, 1668 FileSpec::Style::native); 1669 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec()); 1670 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path); 1671 } 1672 } 1673 dwo_module_spec.GetArchitecture() = 1674 m_objfile_sp->GetModule()->GetArchitecture(); 1675 1676 // When LLDB loads "external" modules it looks at the presence of 1677 // DW_AT_dwo_name. However, when the already created module 1678 // (corresponding to .dwo itself) is being processed, it will see 1679 // the presence of DW_AT_dwo_name (which contains the name of dwo 1680 // file) and will try to call ModuleList::GetSharedModule 1681 // again. In some cases (i.e., for empty files) Clang 4.0 1682 // generates a *.dwo file which has DW_AT_dwo_name, but no 1683 // DW_AT_comp_dir. In this case the method 1684 // ModuleList::GetSharedModule will fail and the warning will be 1685 // printed. However, as one can notice in this case we don't 1686 // actually need to try to load the already loaded module 1687 // (corresponding to .dwo) so we simply skip it. 1688 if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" && 1689 llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath()) 1690 .endswith(dwo_module_spec.GetFileSpec().GetPath())) { 1691 continue; 1692 } 1693 1694 Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp, 1695 nullptr, nullptr, nullptr); 1696 if (!module_sp) { 1697 GetObjectFile()->GetModule()->ReportWarning( 1698 "0x%8.8x: unable to locate module needed for external types: " 1699 "%s\nerror: %s\nDebugging will be degraded due to missing " 1700 "types. Rebuilding the project will regenerate the needed " 1701 "module files.", 1702 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(), 1703 error.AsCString("unknown error")); 1704 continue; 1705 } 1706 1707 // Verify the DWO hash. 1708 // FIXME: Technically "0" is a valid hash. 1709 uint64_t dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE()); 1710 if (!dwo_id) 1711 continue; 1712 1713 auto *dwo_symfile = 1714 llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile()); 1715 if (!dwo_symfile) 1716 continue; 1717 llvm::Optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId(); 1718 if (!dwo_dwo_id) 1719 continue; 1720 1721 if (dwo_id != dwo_dwo_id) { 1722 GetObjectFile()->GetModule()->ReportWarning( 1723 "0x%8.8x: Module %s is out-of-date (hash mismatch). Type information " 1724 "from this module may be incomplete or inconsistent with the rest of " 1725 "the program. Rebuilding the project will regenerate the needed " 1726 "module files.", 1727 die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str()); 1728 } 1729 } 1730} 1731 1732SymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() { 1733 if (!m_global_aranges_up) { 1734 m_global_aranges_up.reset(new GlobalVariableMap()); 1735 1736 ModuleSP module_sp = GetObjectFile()->GetModule(); 1737 if (module_sp) { 1738 const size_t num_cus = module_sp->GetNumCompileUnits(); 1739 for (size_t i = 0; i < num_cus; ++i) { 1740 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i); 1741 if (cu_sp) { 1742 VariableListSP globals_sp = cu_sp->GetVariableList(true); 1743 if (globals_sp) { 1744 const size_t num_globals = globals_sp->GetSize(); 1745 for (size_t g = 0; g < num_globals; ++g) { 1746 VariableSP var_sp = globals_sp->GetVariableAtIndex(g); 1747 if (var_sp && !var_sp->GetLocationIsConstantValueData()) { 1748 const DWARFExpression &location = var_sp->LocationExpression(); 1749 Value location_result; 1750 Status error; 1751 if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr, 1752 nullptr, location_result, &error)) { 1753 if (location_result.GetValueType() == 1754 Value::eValueTypeFileAddress) { 1755 lldb::addr_t file_addr = 1756 location_result.GetScalar().ULongLong(); 1757 lldb::addr_t byte_size = 1; 1758 if (var_sp->GetType()) 1759 byte_size = 1760 var_sp->GetType()->GetByteSize().getValueOr(0); 1761 m_global_aranges_up->Append(GlobalVariableMap::Entry( 1762 file_addr, byte_size, var_sp.get())); 1763 } 1764 } 1765 } 1766 } 1767 } 1768 } 1769 } 1770 } 1771 m_global_aranges_up->Sort(); 1772 } 1773 return *m_global_aranges_up; 1774} 1775 1776uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr, 1777 SymbolContextItem resolve_scope, 1778 SymbolContext &sc) { 1779 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1780 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 1781 Timer scoped_timer(func_cat, 1782 "SymbolFileDWARF::" 1783 "ResolveSymbolContext (so_addr = { " 1784 "section = %p, offset = 0x%" PRIx64 1785 " }, resolve_scope = 0x%8.8x)", 1786 static_cast<void *>(so_addr.GetSection().get()), 1787 so_addr.GetOffset(), resolve_scope); 1788 uint32_t resolved = 0; 1789 if (resolve_scope & 1790 (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock | 1791 eSymbolContextLineEntry | eSymbolContextVariable)) { 1792 lldb::addr_t file_vm_addr = so_addr.GetFileAddress(); 1793 1794 DWARFDebugInfo *debug_info = DebugInfo(); 1795 if (debug_info) { 1796 llvm::Expected<DWARFDebugAranges &> aranges = 1797 debug_info->GetCompileUnitAranges(); 1798 if (!aranges) { 1799 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO); 1800 LLDB_LOG_ERROR(log, aranges.takeError(), 1801 "SymbolFileDWARF::ResolveSymbolContext failed to get cu " 1802 "aranges. {0}"); 1803 return 0; 1804 } 1805 1806 const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr); 1807 if (cu_offset == DW_INVALID_OFFSET) { 1808 // Global variables are not in the compile unit address ranges. The 1809 // only way to currently find global variables is to iterate over the 1810 // .debug_pubnames or the __apple_names table and find all items in 1811 // there that point to DW_TAG_variable DIEs and then find the address 1812 // that matches. 1813 if (resolve_scope & eSymbolContextVariable) { 1814 GlobalVariableMap &map = GetGlobalAranges(); 1815 const GlobalVariableMap::Entry *entry = 1816 map.FindEntryThatContains(file_vm_addr); 1817 if (entry && entry->data) { 1818 Variable *variable = entry->data; 1819 SymbolContextScope *scc = variable->GetSymbolContextScope(); 1820 if (scc) { 1821 scc->CalculateSymbolContext(&sc); 1822 sc.variable = variable; 1823 } 1824 return sc.GetResolvedMask(); 1825 } 1826 } 1827 } else { 1828 uint32_t cu_idx = DW_INVALID_INDEX; 1829 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>( 1830 debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo, 1831 cu_offset, &cu_idx))) { 1832 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 1833 if (sc.comp_unit) { 1834 resolved |= eSymbolContextCompUnit; 1835 1836 bool force_check_line_table = false; 1837 if (resolve_scope & 1838 (eSymbolContextFunction | eSymbolContextBlock)) { 1839 DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr); 1840 DWARFDIE block_die; 1841 if (function_die) { 1842 sc.function = 1843 sc.comp_unit->FindFunctionByUID(function_die.GetID()).get(); 1844 if (sc.function == nullptr) 1845 sc.function = ParseFunction(*sc.comp_unit, function_die); 1846 1847 if (sc.function && (resolve_scope & eSymbolContextBlock)) 1848 block_die = function_die.LookupDeepestBlock(file_vm_addr); 1849 } else { 1850 // We might have had a compile unit that had discontiguous 1851 // address ranges where the gaps are symbols that don't have 1852 // any debug info. Discontiguous compile unit address ranges 1853 // should only happen when there aren't other functions from 1854 // other compile units in these gaps. This helps keep the size 1855 // of the aranges down. 1856 force_check_line_table = true; 1857 } 1858 1859 if (sc.function != nullptr) { 1860 resolved |= eSymbolContextFunction; 1861 1862 if (resolve_scope & eSymbolContextBlock) { 1863 Block &block = sc.function->GetBlock(true); 1864 1865 if (block_die) 1866 sc.block = block.FindBlockByID(block_die.GetID()); 1867 else 1868 sc.block = block.FindBlockByID(function_die.GetID()); 1869 if (sc.block) 1870 resolved |= eSymbolContextBlock; 1871 } 1872 } 1873 } 1874 1875 if ((resolve_scope & eSymbolContextLineEntry) || 1876 force_check_line_table) { 1877 LineTable *line_table = sc.comp_unit->GetLineTable(); 1878 if (line_table != nullptr) { 1879 // And address that makes it into this function should be in 1880 // terms of this debug file if there is no debug map, or it 1881 // will be an address in the .o file which needs to be fixed up 1882 // to be in terms of the debug map executable. Either way, 1883 // calling FixupAddress() will work for us. 1884 Address exe_so_addr(so_addr); 1885 if (FixupAddress(exe_so_addr)) { 1886 if (line_table->FindLineEntryByAddress(exe_so_addr, 1887 sc.line_entry)) { 1888 resolved |= eSymbolContextLineEntry; 1889 } 1890 } 1891 } 1892 } 1893 1894 if (force_check_line_table && 1895 !(resolved & eSymbolContextLineEntry)) { 1896 // We might have had a compile unit that had discontiguous 1897 // address ranges where the gaps are symbols that don't have any 1898 // debug info. Discontiguous compile unit address ranges should 1899 // only happen when there aren't other functions from other 1900 // compile units in these gaps. This helps keep the size of the 1901 // aranges down. 1902 sc.comp_unit = nullptr; 1903 resolved &= ~eSymbolContextCompUnit; 1904 } 1905 } else { 1906 GetObjectFile()->GetModule()->ReportWarning( 1907 "0x%8.8x: compile unit %u failed to create a valid " 1908 "lldb_private::CompileUnit class.", 1909 cu_offset, cu_idx); 1910 } 1911 } 1912 } 1913 } 1914 } 1915 return resolved; 1916} 1917 1918uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec, 1919 uint32_t line, 1920 bool check_inlines, 1921 SymbolContextItem resolve_scope, 1922 SymbolContextList &sc_list) { 1923 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1924 const uint32_t prev_size = sc_list.GetSize(); 1925 if (resolve_scope & eSymbolContextCompUnit) { 1926 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus; 1927 ++cu_idx) { 1928 CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get(); 1929 if (!dc_cu) 1930 continue; 1931 1932 bool file_spec_matches_cu_file_spec = 1933 FileSpec::Match(file_spec, dc_cu->GetPrimaryFile()); 1934 if (check_inlines || file_spec_matches_cu_file_spec) { 1935 SymbolContext sc(m_objfile_sp->GetModule()); 1936 sc.comp_unit = dc_cu; 1937 uint32_t file_idx = UINT32_MAX; 1938 1939 // If we are looking for inline functions only and we don't find it 1940 // in the support files, we are done. 1941 if (check_inlines) { 1942 file_idx = 1943 sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true); 1944 if (file_idx == UINT32_MAX) 1945 continue; 1946 } 1947 1948 if (line != 0) { 1949 LineTable *line_table = sc.comp_unit->GetLineTable(); 1950 1951 if (line_table != nullptr && line != 0) { 1952 // We will have already looked up the file index if we are 1953 // searching for inline entries. 1954 if (!check_inlines) 1955 file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex( 1956 1, file_spec, true); 1957 1958 if (file_idx != UINT32_MAX) { 1959 uint32_t found_line; 1960 uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex( 1961 0, file_idx, line, false, &sc.line_entry); 1962 found_line = sc.line_entry.line; 1963 1964 while (line_idx != UINT32_MAX) { 1965 sc.function = nullptr; 1966 sc.block = nullptr; 1967 if (resolve_scope & 1968 (eSymbolContextFunction | eSymbolContextBlock)) { 1969 const lldb::addr_t file_vm_addr = 1970 sc.line_entry.range.GetBaseAddress().GetFileAddress(); 1971 if (file_vm_addr != LLDB_INVALID_ADDRESS) { 1972 DWARFDIE function_die = 1973 GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr); 1974 DWARFDIE block_die; 1975 if (function_die) { 1976 sc.function = 1977 sc.comp_unit->FindFunctionByUID(function_die.GetID()) 1978 .get(); 1979 if (sc.function == nullptr) 1980 sc.function = 1981 ParseFunction(*sc.comp_unit, function_die); 1982 1983 if (sc.function && (resolve_scope & eSymbolContextBlock)) 1984 block_die = 1985 function_die.LookupDeepestBlock(file_vm_addr); 1986 } 1987 1988 if (sc.function != nullptr) { 1989 Block &block = sc.function->GetBlock(true); 1990 1991 if (block_die) 1992 sc.block = block.FindBlockByID(block_die.GetID()); 1993 else if (function_die) 1994 sc.block = block.FindBlockByID(function_die.GetID()); 1995 } 1996 } 1997 } 1998 1999 sc_list.Append(sc); 2000 line_idx = line_table->FindLineEntryIndexByFileIndex( 2001 line_idx + 1, file_idx, found_line, true, &sc.line_entry); 2002 } 2003 } 2004 } else if (file_spec_matches_cu_file_spec && !check_inlines) { 2005 // only append the context if we aren't looking for inline call 2006 // sites by file and line and if the file spec matches that of 2007 // the compile unit 2008 sc_list.Append(sc); 2009 } 2010 } else if (file_spec_matches_cu_file_spec && !check_inlines) { 2011 // only append the context if we aren't looking for inline call 2012 // sites by file and line and if the file spec matches that of 2013 // the compile unit 2014 sc_list.Append(sc); 2015 } 2016 2017 if (!check_inlines) 2018 break; 2019 } 2020 } 2021 } 2022 return sc_list.GetSize() - prev_size; 2023} 2024 2025void SymbolFileDWARF::PreloadSymbols() { 2026 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2027 m_index->Preload(); 2028} 2029 2030std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const { 2031 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); 2032 if (module_sp) 2033 return module_sp->GetMutex(); 2034 return GetObjectFile()->GetModule()->GetMutex(); 2035} 2036 2037bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile( 2038 const lldb_private::CompilerDeclContext *decl_ctx) { 2039 if (decl_ctx == nullptr || !decl_ctx->IsValid()) { 2040 // Invalid namespace decl which means we aren't matching only things in 2041 // this symbol file, so return true to indicate it matches this symbol 2042 // file. 2043 return true; 2044 } 2045 2046 TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem(); 2047 auto type_system_or_err = GetTypeSystemForLanguage( 2048 decl_ctx_type_system->GetMinimumLanguage(nullptr)); 2049 if (auto err = type_system_or_err.takeError()) { 2050 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 2051 std::move(err), 2052 "Unable to match namespace decl using TypeSystem"); 2053 return false; 2054 } 2055 2056 if (decl_ctx_type_system == &type_system_or_err.get()) 2057 return true; // The type systems match, return true 2058 2059 // The namespace AST was valid, and it does not match... 2060 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2061 2062 if (log) 2063 GetObjectFile()->GetModule()->LogMessage( 2064 log, "Valid namespace does not match symbol file"); 2065 2066 return false; 2067} 2068 2069void SymbolFileDWARF::FindGlobalVariables( 2070 ConstString name, const CompilerDeclContext *parent_decl_ctx, 2071 uint32_t max_matches, VariableList &variables) { 2072 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2073 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2074 2075 if (log) 2076 GetObjectFile()->GetModule()->LogMessage( 2077 log, 2078 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " 2079 "parent_decl_ctx=%p, max_matches=%u, variables)", 2080 name.GetCString(), static_cast<const void *>(parent_decl_ctx), 2081 max_matches); 2082 2083 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2084 return; 2085 2086 DWARFDebugInfo *info = DebugInfo(); 2087 if (!info) 2088 return; 2089 2090 // Remember how many variables are in the list before we search. 2091 const uint32_t original_size = variables.GetSize(); 2092 2093 llvm::StringRef basename; 2094 llvm::StringRef context; 2095 bool name_is_mangled = (bool)Mangled(name); 2096 2097 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(), 2098 context, basename)) 2099 basename = name.GetStringRef(); 2100 2101 DIEArray die_offsets; 2102 m_index->GetGlobalVariables(ConstString(basename), die_offsets); 2103 const size_t num_die_matches = die_offsets.size(); 2104 if (num_die_matches) { 2105 SymbolContext sc; 2106 sc.module_sp = m_objfile_sp->GetModule(); 2107 assert(sc.module_sp); 2108 2109 // Loop invariant: Variables up to this index have been checked for context 2110 // matches. 2111 uint32_t pruned_idx = original_size; 2112 2113 bool done = false; 2114 for (size_t i = 0; i < num_die_matches && !done; ++i) { 2115 const DIERef &die_ref = die_offsets[i]; 2116 DWARFDIE die = GetDIE(die_ref); 2117 2118 if (die) { 2119 switch (die.Tag()) { 2120 default: 2121 case DW_TAG_subprogram: 2122 case DW_TAG_inlined_subroutine: 2123 case DW_TAG_try_block: 2124 case DW_TAG_catch_block: 2125 break; 2126 2127 case DW_TAG_variable: { 2128 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); 2129 if (!dwarf_cu) 2130 continue; 2131 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2132 2133 if (parent_decl_ctx) { 2134 DWARFASTParser *dwarf_ast = die.GetDWARFParser(); 2135 if (dwarf_ast) { 2136 CompilerDeclContext actual_parent_decl_ctx = 2137 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); 2138 if (!actual_parent_decl_ctx || 2139 actual_parent_decl_ctx != *parent_decl_ctx) 2140 continue; 2141 } 2142 } 2143 2144 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, 2145 &variables); 2146 while (pruned_idx < variables.GetSize()) { 2147 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx); 2148 if (name_is_mangled || 2149 var_sp->GetName().GetStringRef().contains(name.GetStringRef())) 2150 ++pruned_idx; 2151 else 2152 variables.RemoveVariableAtIndex(pruned_idx); 2153 } 2154 2155 if (variables.GetSize() - original_size >= max_matches) 2156 done = true; 2157 } break; 2158 } 2159 } else { 2160 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); 2161 } 2162 } 2163 } 2164 2165 // Return the number of variable that were appended to the list 2166 const uint32_t num_matches = variables.GetSize() - original_size; 2167 if (log && num_matches > 0) { 2168 GetObjectFile()->GetModule()->LogMessage( 2169 log, 2170 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " 2171 "parent_decl_ctx=%p, max_matches=%u, variables) => %u", 2172 name.GetCString(), static_cast<const void *>(parent_decl_ctx), 2173 max_matches, num_matches); 2174 } 2175} 2176 2177void SymbolFileDWARF::FindGlobalVariables(const RegularExpression ®ex, 2178 uint32_t max_matches, 2179 VariableList &variables) { 2180 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2181 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2182 2183 if (log) { 2184 GetObjectFile()->GetModule()->LogMessage( 2185 log, 2186 "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", " 2187 "max_matches=%u, variables)", 2188 regex.GetText().str().c_str(), max_matches); 2189 } 2190 2191 DWARFDebugInfo *info = DebugInfo(); 2192 if (!info) 2193 return; 2194 2195 // Remember how many variables are in the list before we search. 2196 const uint32_t original_size = variables.GetSize(); 2197 2198 DIEArray die_offsets; 2199 m_index->GetGlobalVariables(regex, die_offsets); 2200 2201 SymbolContext sc; 2202 sc.module_sp = m_objfile_sp->GetModule(); 2203 assert(sc.module_sp); 2204 2205 const size_t num_matches = die_offsets.size(); 2206 if (num_matches) { 2207 for (size_t i = 0; i < num_matches; ++i) { 2208 const DIERef &die_ref = die_offsets[i]; 2209 DWARFDIE die = GetDIE(die_ref); 2210 2211 if (die) { 2212 DWARFCompileUnit *dwarf_cu = 2213 llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); 2214 if (!dwarf_cu) 2215 continue; 2216 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2217 2218 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); 2219 2220 if (variables.GetSize() - original_size >= max_matches) 2221 break; 2222 } else 2223 m_index->ReportInvalidDIERef(die_ref, regex.GetText()); 2224 } 2225 } 2226} 2227 2228bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die, 2229 bool include_inlines, 2230 SymbolContextList &sc_list) { 2231 SymbolContext sc; 2232 2233 if (!orig_die) 2234 return false; 2235 2236 // If we were passed a die that is not a function, just return false... 2237 if (!(orig_die.Tag() == DW_TAG_subprogram || 2238 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine))) 2239 return false; 2240 2241 DWARFDIE die = orig_die; 2242 DWARFDIE inlined_die; 2243 if (die.Tag() == DW_TAG_inlined_subroutine) { 2244 inlined_die = die; 2245 2246 while (true) { 2247 die = die.GetParent(); 2248 2249 if (die) { 2250 if (die.Tag() == DW_TAG_subprogram) 2251 break; 2252 } else 2253 break; 2254 } 2255 } 2256 assert(die && die.Tag() == DW_TAG_subprogram); 2257 if (GetFunction(die, sc)) { 2258 Address addr; 2259 // Parse all blocks if needed 2260 if (inlined_die) { 2261 Block &function_block = sc.function->GetBlock(true); 2262 sc.block = function_block.FindBlockByID(inlined_die.GetID()); 2263 if (sc.block == nullptr) 2264 sc.block = function_block.FindBlockByID(inlined_die.GetOffset()); 2265 if (sc.block == nullptr || !sc.block->GetStartAddress(addr)) 2266 addr.Clear(); 2267 } else { 2268 sc.block = nullptr; 2269 addr = sc.function->GetAddressRange().GetBaseAddress(); 2270 } 2271 2272 2273 if (auto section_sp = addr.GetSection()) { 2274 if (section_sp->GetPermissions() & ePermissionsExecutable) { 2275 sc_list.Append(sc); 2276 return true; 2277 } 2278 } 2279 } 2280 2281 return false; 2282} 2283 2284bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx, 2285 const DWARFDIE &die) { 2286 // If we have no parent decl context to match this DIE matches, and if the 2287 // parent decl context isn't valid, we aren't trying to look for any 2288 // particular decl context so any die matches. 2289 if (decl_ctx == nullptr || !decl_ctx->IsValid()) 2290 return true; 2291 2292 if (die) { 2293 DWARFASTParser *dwarf_ast = die.GetDWARFParser(); 2294 if (dwarf_ast) { 2295 CompilerDeclContext actual_decl_ctx = 2296 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); 2297 if (actual_decl_ctx) 2298 return decl_ctx->IsContainedInLookup(actual_decl_ctx); 2299 } 2300 } 2301 return false; 2302} 2303 2304void SymbolFileDWARF::FindFunctions(ConstString name, 2305 const CompilerDeclContext *parent_decl_ctx, 2306 FunctionNameType name_type_mask, 2307 bool include_inlines, 2308 SymbolContextList &sc_list) { 2309 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2310 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 2311 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')", 2312 name.AsCString()); 2313 2314 // eFunctionNameTypeAuto should be pre-resolved by a call to 2315 // Module::LookupInfo::LookupInfo() 2316 assert((name_type_mask & eFunctionNameTypeAuto) == 0); 2317 2318 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2319 2320 if (log) { 2321 GetObjectFile()->GetModule()->LogMessage( 2322 log, 2323 "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)", 2324 name.GetCString(), name_type_mask); 2325 } 2326 2327 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2328 return; 2329 2330 // If name is empty then we won't find anything. 2331 if (name.IsEmpty()) 2332 return; 2333 2334 // Remember how many sc_list are in the list before we search in case we are 2335 // appending the results to a variable list. 2336 2337 const uint32_t original_size = sc_list.GetSize(); 2338 2339 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; 2340 DIEArray offsets; 2341 CompilerDeclContext empty_decl_ctx; 2342 if (!parent_decl_ctx) 2343 parent_decl_ctx = &empty_decl_ctx; 2344 2345 std::vector<DWARFDIE> dies; 2346 m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies); 2347 for (const DWARFDIE &die : dies) { 2348 if (resolved_dies.insert(die.GetDIE()).second) 2349 ResolveFunction(die, include_inlines, sc_list); 2350 } 2351 2352 // Return the number of variable that were appended to the list 2353 const uint32_t num_matches = sc_list.GetSize() - original_size; 2354 2355 if (log && num_matches > 0) { 2356 GetObjectFile()->GetModule()->LogMessage( 2357 log, 2358 "SymbolFileDWARF::FindFunctions (name=\"%s\", " 2359 "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u", 2360 name.GetCString(), name_type_mask, include_inlines, 2361 num_matches); 2362 } 2363} 2364 2365void SymbolFileDWARF::FindFunctions(const RegularExpression ®ex, 2366 bool include_inlines, 2367 SymbolContextList &sc_list) { 2368 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2369 static Timer::Category func_cat(LLVM_PRETTY_FUNCTION); 2370 Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')", 2371 regex.GetText().str().c_str()); 2372 2373 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2374 2375 if (log) { 2376 GetObjectFile()->GetModule()->LogMessage( 2377 log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)", 2378 regex.GetText().str().c_str()); 2379 } 2380 2381 DWARFDebugInfo *info = DebugInfo(); 2382 if (!info) 2383 return; 2384 2385 DIEArray offsets; 2386 m_index->GetFunctions(regex, offsets); 2387 2388 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; 2389 for (DIERef ref : offsets) { 2390 DWARFDIE die = info->GetDIE(ref); 2391 if (!die) { 2392 m_index->ReportInvalidDIERef(ref, regex.GetText()); 2393 continue; 2394 } 2395 if (resolved_dies.insert(die.GetDIE()).second) 2396 ResolveFunction(die, include_inlines, sc_list); 2397 } 2398} 2399 2400void SymbolFileDWARF::GetMangledNamesForFunction( 2401 const std::string &scope_qualified_name, 2402 std::vector<ConstString> &mangled_names) { 2403 DWARFDebugInfo *info = DebugInfo(); 2404 uint32_t num_comp_units = 0; 2405 if (info) 2406 num_comp_units = info->GetNumUnits(); 2407 2408 for (uint32_t i = 0; i < num_comp_units; i++) { 2409 DWARFUnit *cu = info->GetUnitAtIndex(i); 2410 if (cu == nullptr) 2411 continue; 2412 2413 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile(); 2414 if (dwo) 2415 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names); 2416 } 2417 2418 for (lldb::user_id_t uid : 2419 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) { 2420 DWARFDIE die = GetDIE(uid); 2421 mangled_names.push_back(ConstString(die.GetMangledName())); 2422 } 2423} 2424 2425void SymbolFileDWARF::FindTypes( 2426 ConstString name, const CompilerDeclContext *parent_decl_ctx, 2427 uint32_t max_matches, 2428 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 2429 TypeMap &types) { 2430 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2431 // Make sure we haven't already searched this SymbolFile before. 2432 if (!searched_symbol_files.insert(this).second) 2433 return; 2434 2435 DWARFDebugInfo *info = DebugInfo(); 2436 if (!info) 2437 return; 2438 2439 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2440 2441 if (log) { 2442 if (parent_decl_ctx) 2443 GetObjectFile()->GetModule()->LogMessage( 2444 log, 2445 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " 2446 "%p (\"%s\"), max_matches=%u, type_list)", 2447 name.GetCString(), static_cast<const void *>(parent_decl_ctx), 2448 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches); 2449 else 2450 GetObjectFile()->GetModule()->LogMessage( 2451 log, 2452 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " 2453 "NULL, max_matches=%u, type_list)", 2454 name.GetCString(), max_matches); 2455 } 2456 2457 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2458 return; 2459 2460 DIEArray die_offsets; 2461 m_index->GetTypes(name, die_offsets); 2462 const size_t num_die_matches = die_offsets.size(); 2463 2464 for (size_t i = 0; i < num_die_matches; ++i) { 2465 const DIERef &die_ref = die_offsets[i]; 2466 DWARFDIE die = GetDIE(die_ref); 2467 if (die) { 2468 if (!DIEInDeclContext(parent_decl_ctx, die)) 2469 continue; // The containing decl contexts don't match 2470 2471 Type *matching_type = ResolveType(die, true, true); 2472 if (matching_type) { 2473 // We found a type pointer, now find the shared pointer form our type 2474 // list 2475 types.InsertUnique(matching_type->shared_from_this()); 2476 if (types.GetSize() >= max_matches) 2477 break; 2478 } 2479 } else { 2480 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); 2481 } 2482 } 2483 2484 // Next search through the reachable Clang modules. This only applies for 2485 // DWARF objects compiled with -gmodules that haven't been processed by 2486 // dsymutil. 2487 if (num_die_matches < max_matches) { 2488 UpdateExternalModuleListIfNeeded(); 2489 2490 for (const auto &pair : m_external_type_modules) 2491 if (ModuleSP external_module_sp = pair.second) 2492 if (SymbolFile *sym_file = external_module_sp->GetSymbolFile()) 2493 sym_file->FindTypes(name, parent_decl_ctx, max_matches, 2494 searched_symbol_files, types); 2495 } 2496 2497 if (log && types.GetSize()) { 2498 if (parent_decl_ctx) { 2499 GetObjectFile()->GetModule()->LogMessage( 2500 log, 2501 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " 2502 "= %p (\"%s\"), max_matches=%u, type_list) => %u", 2503 name.GetCString(), static_cast<const void *>(parent_decl_ctx), 2504 parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches, 2505 types.GetSize()); 2506 } else { 2507 GetObjectFile()->GetModule()->LogMessage( 2508 log, 2509 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " 2510 "= NULL, max_matches=%u, type_list) => %u", 2511 name.GetCString(), max_matches, types.GetSize()); 2512 } 2513 } 2514} 2515 2516void SymbolFileDWARF::FindTypes( 2517 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, 2518 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) { 2519 // Make sure we haven't already searched this SymbolFile before. 2520 if (!searched_symbol_files.insert(this).second) 2521 return; 2522 2523 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2524 if (pattern.empty()) 2525 return; 2526 2527 ConstString name = pattern.back().name; 2528 2529 if (!name) 2530 return; 2531 2532 DIEArray die_offsets; 2533 m_index->GetTypes(name, die_offsets); 2534 const size_t num_die_matches = die_offsets.size(); 2535 2536 for (size_t i = 0; i < num_die_matches; ++i) { 2537 const DIERef &die_ref = die_offsets[i]; 2538 DWARFDIE die = GetDIE(die_ref); 2539 2540 if (!die) { 2541 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); 2542 continue; 2543 } 2544 if (!languages[die.GetCU()->GetLanguageType()]) 2545 continue; 2546 2547 llvm::SmallVector<CompilerContext, 4> die_context; 2548 die.GetDeclContext(die_context); 2549 if (!contextMatches(die_context, pattern)) 2550 continue; 2551 2552 if (Type *matching_type = ResolveType(die, true, true)) { 2553 // We found a type pointer, now find the shared pointer form our type 2554 // list. 2555 types.InsertUnique(matching_type->shared_from_this()); 2556 } 2557 } 2558 2559 // Next search through the reachable Clang modules. This only applies for 2560 // DWARF objects compiled with -gmodules that haven't been processed by 2561 // dsymutil. 2562 UpdateExternalModuleListIfNeeded(); 2563 2564 for (const auto &pair : m_external_type_modules) 2565 if (ModuleSP external_module_sp = pair.second) 2566 external_module_sp->FindTypes(pattern, languages, searched_symbol_files, 2567 types); 2568} 2569 2570CompilerDeclContext 2571SymbolFileDWARF::FindNamespace(ConstString name, 2572 const CompilerDeclContext *parent_decl_ctx) { 2573 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2574 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2575 2576 if (log) { 2577 GetObjectFile()->GetModule()->LogMessage( 2578 log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")", 2579 name.GetCString()); 2580 } 2581 2582 CompilerDeclContext namespace_decl_ctx; 2583 2584 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2585 return namespace_decl_ctx; 2586 2587 DWARFDebugInfo *info = DebugInfo(); 2588 if (info) { 2589 DIEArray die_offsets; 2590 m_index->GetNamespaces(name, die_offsets); 2591 const size_t num_matches = die_offsets.size(); 2592 if (num_matches) { 2593 for (size_t i = 0; i < num_matches; ++i) { 2594 const DIERef &die_ref = die_offsets[i]; 2595 DWARFDIE die = GetDIE(die_ref); 2596 2597 if (die) { 2598 if (!DIEInDeclContext(parent_decl_ctx, die)) 2599 continue; // The containing decl contexts don't match 2600 2601 DWARFASTParser *dwarf_ast = die.GetDWARFParser(); 2602 if (dwarf_ast) { 2603 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die); 2604 if (namespace_decl_ctx) 2605 break; 2606 } 2607 } else { 2608 m_index->ReportInvalidDIERef(die_ref, name.GetStringRef()); 2609 } 2610 } 2611 } 2612 } 2613 if (log && namespace_decl_ctx) { 2614 GetObjectFile()->GetModule()->LogMessage( 2615 log, 2616 "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => " 2617 "CompilerDeclContext(%p/%p) \"%s\"", 2618 name.GetCString(), 2619 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()), 2620 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()), 2621 namespace_decl_ctx.GetName().AsCString("<NULL>")); 2622 } 2623 2624 return namespace_decl_ctx; 2625} 2626 2627TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die, 2628 bool resolve_function_context) { 2629 TypeSP type_sp; 2630 if (die) { 2631 Type *type_ptr = GetDIEToType().lookup(die.GetDIE()); 2632 if (type_ptr == nullptr) { 2633 SymbolContextScope *scope; 2634 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU())) 2635 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2636 else 2637 scope = GetObjectFile()->GetModule().get(); 2638 assert(scope); 2639 SymbolContext sc(scope); 2640 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE(); 2641 while (parent_die != nullptr) { 2642 if (parent_die->Tag() == DW_TAG_subprogram) 2643 break; 2644 parent_die = parent_die->GetParent(); 2645 } 2646 SymbolContext sc_backup = sc; 2647 if (resolve_function_context && parent_die != nullptr && 2648 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc)) 2649 sc = sc_backup; 2650 2651 type_sp = ParseType(sc, die, nullptr); 2652 } else if (type_ptr != DIE_IS_BEING_PARSED) { 2653 // Grab the existing type from the master types lists 2654 type_sp = type_ptr->shared_from_this(); 2655 } 2656 } 2657 return type_sp; 2658} 2659 2660DWARFDIE 2661SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) { 2662 if (orig_die) { 2663 DWARFDIE die = orig_die; 2664 2665 while (die) { 2666 // If this is the original DIE that we are searching for a declaration 2667 // for, then don't look in the cache as we don't want our own decl 2668 // context to be our decl context... 2669 if (orig_die != die) { 2670 switch (die.Tag()) { 2671 case DW_TAG_compile_unit: 2672 case DW_TAG_partial_unit: 2673 case DW_TAG_namespace: 2674 case DW_TAG_structure_type: 2675 case DW_TAG_union_type: 2676 case DW_TAG_class_type: 2677 case DW_TAG_lexical_block: 2678 case DW_TAG_subprogram: 2679 return die; 2680 case DW_TAG_inlined_subroutine: { 2681 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); 2682 if (abs_die) { 2683 return abs_die; 2684 } 2685 break; 2686 } 2687 default: 2688 break; 2689 } 2690 } 2691 2692 DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification); 2693 if (spec_die) { 2694 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die); 2695 if (decl_ctx_die) 2696 return decl_ctx_die; 2697 } 2698 2699 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); 2700 if (abs_die) { 2701 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die); 2702 if (decl_ctx_die) 2703 return decl_ctx_die; 2704 } 2705 2706 die = die.GetParent(); 2707 } 2708 } 2709 return DWARFDIE(); 2710} 2711 2712Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) { 2713 Symbol *objc_class_symbol = nullptr; 2714 if (m_objfile_sp) { 2715 Symtab *symtab = m_objfile_sp->GetSymtab(); 2716 if (symtab) { 2717 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType( 2718 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo, 2719 Symtab::eVisibilityAny); 2720 } 2721 } 2722 return objc_class_symbol; 2723} 2724 2725// Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If 2726// they don't then we can end up looking through all class types for a complete 2727// type and never find the full definition. We need to know if this attribute 2728// is supported, so we determine this here and cache th result. We also need to 2729// worry about the debug map 2730// DWARF file 2731// if we are doing darwin DWARF in .o file debugging. 2732bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) { 2733 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) { 2734 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo; 2735 if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type()) 2736 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; 2737 else { 2738 DWARFDebugInfo *debug_info = DebugInfo(); 2739 const uint32_t num_compile_units = GetNumCompileUnits(); 2740 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { 2741 DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx); 2742 if (dwarf_cu != cu && 2743 dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) { 2744 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; 2745 break; 2746 } 2747 } 2748 } 2749 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && 2750 GetDebugMapSymfile()) 2751 return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this); 2752 } 2753 return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes; 2754} 2755 2756// This function can be used when a DIE is found that is a forward declaration 2757// DIE and we want to try and find a type that has the complete definition. 2758TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE( 2759 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) { 2760 2761 TypeSP type_sp; 2762 2763 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name))) 2764 return type_sp; 2765 2766 DIEArray die_offsets; 2767 m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets); 2768 2769 const size_t num_matches = die_offsets.size(); 2770 2771 if (num_matches) { 2772 for (size_t i = 0; i < num_matches; ++i) { 2773 const DIERef &die_ref = die_offsets[i]; 2774 DWARFDIE type_die = GetDIE(die_ref); 2775 2776 if (type_die) { 2777 bool try_resolving_type = false; 2778 2779 // Don't try and resolve the DIE we are looking for with the DIE 2780 // itself! 2781 if (type_die != die) { 2782 switch (type_die.Tag()) { 2783 case DW_TAG_class_type: 2784 case DW_TAG_structure_type: 2785 try_resolving_type = true; 2786 break; 2787 default: 2788 break; 2789 } 2790 } 2791 2792 if (try_resolving_type) { 2793 if (must_be_implementation && 2794 type_die.Supports_DW_AT_APPLE_objc_complete_type()) 2795 try_resolving_type = type_die.GetAttributeValueAsUnsigned( 2796 DW_AT_APPLE_objc_complete_type, 0); 2797 2798 if (try_resolving_type) { 2799 Type *resolved_type = ResolveType(type_die, false, true); 2800 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) { 2801 DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 2802 " (cu 0x%8.8" PRIx64 ")\n", 2803 die.GetID(), 2804 m_objfile_sp->GetFileSpec().GetFilename().AsCString( 2805 "<Unknown>"), 2806 type_die.GetID(), type_cu->GetID()); 2807 2808 if (die) 2809 GetDIEToType()[die.GetDIE()] = resolved_type; 2810 type_sp = resolved_type->shared_from_this(); 2811 break; 2812 } 2813 } 2814 } 2815 } else { 2816 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef()); 2817 } 2818 } 2819 } 2820 return type_sp; 2821} 2822 2823// This function helps to ensure that the declaration contexts match for two 2824// different DIEs. Often times debug information will refer to a forward 2825// declaration of a type (the equivalent of "struct my_struct;". There will 2826// often be a declaration of that type elsewhere that has the full definition. 2827// When we go looking for the full type "my_struct", we will find one or more 2828// matches in the accelerator tables and we will then need to make sure the 2829// type was in the same declaration context as the original DIE. This function 2830// can efficiently compare two DIEs and will return true when the declaration 2831// context matches, and false when they don't. 2832bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1, 2833 const DWARFDIE &die2) { 2834 if (die1 == die2) 2835 return true; 2836 2837 std::vector<DWARFDIE> decl_ctx_1; 2838 std::vector<DWARFDIE> decl_ctx_2; 2839 // The declaration DIE stack is a stack of the declaration context DIEs all 2840 // the way back to the compile unit. If a type "T" is declared inside a class 2841 // "B", and class "B" is declared inside a class "A" and class "A" is in a 2842 // namespace "lldb", and the namespace is in a compile unit, there will be a 2843 // stack of DIEs: 2844 // 2845 // [0] DW_TAG_class_type for "B" 2846 // [1] DW_TAG_class_type for "A" 2847 // [2] DW_TAG_namespace for "lldb" 2848 // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file. 2849 // 2850 // We grab both contexts and make sure that everything matches all the way 2851 // back to the compiler unit. 2852 2853 // First lets grab the decl contexts for both DIEs 2854 decl_ctx_1 = die1.GetDeclContextDIEs(); 2855 decl_ctx_2 = die2.GetDeclContextDIEs(); 2856 // Make sure the context arrays have the same size, otherwise we are done 2857 const size_t count1 = decl_ctx_1.size(); 2858 const size_t count2 = decl_ctx_2.size(); 2859 if (count1 != count2) 2860 return false; 2861 2862 // Make sure the DW_TAG values match all the way back up the compile unit. If 2863 // they don't, then we are done. 2864 DWARFDIE decl_ctx_die1; 2865 DWARFDIE decl_ctx_die2; 2866 size_t i; 2867 for (i = 0; i < count1; i++) { 2868 decl_ctx_die1 = decl_ctx_1[i]; 2869 decl_ctx_die2 = decl_ctx_2[i]; 2870 if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag()) 2871 return false; 2872 } 2873#ifndef NDEBUG 2874 2875 // Make sure the top item in the decl context die array is always 2876 // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then 2877 // something went wrong in the DWARFDIE::GetDeclContextDIEs() 2878 // function. 2879 dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag(); 2880 UNUSED_IF_ASSERT_DISABLED(cu_tag); 2881 assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit); 2882 2883#endif 2884 // Always skip the compile unit when comparing by only iterating up to "count 2885 // - 1". Here we compare the names as we go. 2886 for (i = 0; i < count1 - 1; i++) { 2887 decl_ctx_die1 = decl_ctx_1[i]; 2888 decl_ctx_die2 = decl_ctx_2[i]; 2889 const char *name1 = decl_ctx_die1.GetName(); 2890 const char *name2 = decl_ctx_die2.GetName(); 2891 // If the string was from a DW_FORM_strp, then the pointer will often be 2892 // the same! 2893 if (name1 == name2) 2894 continue; 2895 2896 // Name pointers are not equal, so only compare the strings if both are not 2897 // NULL. 2898 if (name1 && name2) { 2899 // If the strings don't compare, we are done... 2900 if (strcmp(name1, name2) != 0) 2901 return false; 2902 } else { 2903 // One name was NULL while the other wasn't 2904 return false; 2905 } 2906 } 2907 // We made it through all of the checks and the declaration contexts are 2908 // equal. 2909 return true; 2910} 2911 2912TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext( 2913 const DWARFDeclContext &dwarf_decl_ctx) { 2914 TypeSP type_sp; 2915 2916 const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize(); 2917 if (dwarf_decl_ctx_count > 0) { 2918 const ConstString type_name(dwarf_decl_ctx[0].name); 2919 const dw_tag_t tag = dwarf_decl_ctx[0].tag; 2920 2921 if (type_name) { 2922 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION | 2923 DWARF_LOG_LOOKUPS)); 2924 if (log) { 2925 GetObjectFile()->GetModule()->LogMessage( 2926 log, 2927 "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%" 2928 "s, qualified-name='%s')", 2929 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 2930 dwarf_decl_ctx.GetQualifiedName()); 2931 } 2932 2933 DIEArray die_offsets; 2934 m_index->GetTypes(dwarf_decl_ctx, die_offsets); 2935 const size_t num_matches = die_offsets.size(); 2936 2937 // Get the type system that we are looking to find a type for. We will 2938 // use this to ensure any matches we find are in a language that this 2939 // type system supports 2940 const LanguageType language = dwarf_decl_ctx.GetLanguage(); 2941 TypeSystem *type_system = nullptr; 2942 if (language != eLanguageTypeUnknown) { 2943 auto type_system_or_err = GetTypeSystemForLanguage(language); 2944 if (auto err = type_system_or_err.takeError()) { 2945 LLDB_LOG_ERROR( 2946 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 2947 std::move(err), "Cannot get TypeSystem for language {}", 2948 Language::GetNameForLanguageType(language)); 2949 } else { 2950 type_system = &type_system_or_err.get(); 2951 } 2952 } 2953 if (num_matches) { 2954 for (size_t i = 0; i < num_matches; ++i) { 2955 const DIERef &die_ref = die_offsets[i]; 2956 DWARFDIE type_die = GetDIE(die_ref); 2957 2958 if (type_die) { 2959 // Make sure type_die's langauge matches the type system we are 2960 // looking for. We don't want to find a "Foo" type from Java if we 2961 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++. 2962 if (type_system && 2963 !type_system->SupportsLanguage(type_die.GetLanguage())) 2964 continue; 2965 bool try_resolving_type = false; 2966 2967 // Don't try and resolve the DIE we are looking for with the DIE 2968 // itself! 2969 const dw_tag_t type_tag = type_die.Tag(); 2970 // Make sure the tags match 2971 if (type_tag == tag) { 2972 // The tags match, lets try resolving this type 2973 try_resolving_type = true; 2974 } else { 2975 // The tags don't match, but we need to watch our for a forward 2976 // declaration for a struct and ("struct foo") ends up being a 2977 // class ("class foo { ... };") or vice versa. 2978 switch (type_tag) { 2979 case DW_TAG_class_type: 2980 // We had a "class foo", see if we ended up with a "struct foo 2981 // { ... };" 2982 try_resolving_type = (tag == DW_TAG_structure_type); 2983 break; 2984 case DW_TAG_structure_type: 2985 // We had a "struct foo", see if we ended up with a "class foo 2986 // { ... };" 2987 try_resolving_type = (tag == DW_TAG_class_type); 2988 break; 2989 default: 2990 // Tags don't match, don't event try to resolve using this type 2991 // whose name matches.... 2992 break; 2993 } 2994 } 2995 2996 if (try_resolving_type) { 2997 DWARFDeclContext type_dwarf_decl_ctx; 2998 type_die.GetDWARFDeclContext(type_dwarf_decl_ctx); 2999 3000 if (log) { 3001 GetObjectFile()->GetModule()->LogMessage( 3002 log, 3003 "SymbolFileDWARF::" 3004 "FindDefinitionTypeForDWARFDeclContext(tag=%s, " 3005 "qualified-name='%s') trying die=0x%8.8x (%s)", 3006 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 3007 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), 3008 type_dwarf_decl_ctx.GetQualifiedName()); 3009 } 3010 3011 // Make sure the decl contexts match all the way up 3012 if (dwarf_decl_ctx == type_dwarf_decl_ctx) { 3013 Type *resolved_type = ResolveType(type_die, false); 3014 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) { 3015 type_sp = resolved_type->shared_from_this(); 3016 break; 3017 } 3018 } 3019 } else { 3020 if (log) { 3021 std::string qualified_name; 3022 type_die.GetQualifiedName(qualified_name); 3023 GetObjectFile()->GetModule()->LogMessage( 3024 log, 3025 "SymbolFileDWARF::" 3026 "FindDefinitionTypeForDWARFDeclContext(tag=%s, " 3027 "qualified-name='%s') ignoring die=0x%8.8x (%s)", 3028 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 3029 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), 3030 qualified_name.c_str()); 3031 } 3032 } 3033 } else { 3034 m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef()); 3035 } 3036 } 3037 } 3038 } 3039 } 3040 return type_sp; 3041} 3042 3043TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die, 3044 bool *type_is_new_ptr) { 3045 if (!die) 3046 return {}; 3047 3048 auto type_system_or_err = 3049 GetTypeSystemForLanguage(die.GetCU()->GetLanguageType()); 3050 if (auto err = type_system_or_err.takeError()) { 3051 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 3052 std::move(err), "Unable to parse type"); 3053 return {}; 3054 } 3055 3056 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser(); 3057 if (!dwarf_ast) 3058 return {}; 3059 3060 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr); 3061 if (type_sp) { 3062 GetTypeList().Insert(type_sp); 3063 3064 if (die.Tag() == DW_TAG_subprogram) { 3065 std::string scope_qualified_name(GetDeclContextForUID(die.GetID()) 3066 .GetScopeQualifiedName() 3067 .AsCString("")); 3068 if (scope_qualified_name.size()) { 3069 m_function_scope_qualified_name_map[scope_qualified_name].insert( 3070 die.GetID()); 3071 } 3072 } 3073 } 3074 3075 return type_sp; 3076} 3077 3078size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc, 3079 const DWARFDIE &orig_die, 3080 bool parse_siblings, bool parse_children) { 3081 size_t types_added = 0; 3082 DWARFDIE die = orig_die; 3083 3084 while (die) { 3085 const dw_tag_t tag = die.Tag(); 3086 bool type_is_new = false; 3087 3088 Tag dwarf_tag = static_cast<Tag>(tag); 3089 3090 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...) 3091 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or 3092 // not. 3093 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type) 3094 ParseType(sc, die, &type_is_new); 3095 3096 if (type_is_new) 3097 ++types_added; 3098 3099 if (parse_children && die.HasChildren()) { 3100 if (die.Tag() == DW_TAG_subprogram) { 3101 SymbolContext child_sc(sc); 3102 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); 3103 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true); 3104 } else 3105 types_added += ParseTypes(sc, die.GetFirstChild(), true, true); 3106 } 3107 3108 if (parse_siblings) 3109 die = die.GetSibling(); 3110 else 3111 die.Clear(); 3112 } 3113 return types_added; 3114} 3115 3116size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) { 3117 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 3118 CompileUnit *comp_unit = func.GetCompileUnit(); 3119 lldbassert(comp_unit); 3120 3121 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit); 3122 if (!dwarf_cu) 3123 return 0; 3124 3125 size_t functions_added = 0; 3126 const dw_offset_t function_die_offset = func.GetID(); 3127 DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset); 3128 if (function_die) { 3129 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die, 3130 LLDB_INVALID_ADDRESS, 0); 3131 } 3132 3133 return functions_added; 3134} 3135 3136size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) { 3137 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 3138 size_t types_added = 0; 3139 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 3140 if (dwarf_cu) { 3141 DWARFDIE dwarf_cu_die = dwarf_cu->DIE(); 3142 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) { 3143 SymbolContext sc; 3144 sc.comp_unit = &comp_unit; 3145 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true); 3146 } 3147 } 3148 3149 return types_added; 3150} 3151 3152size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) { 3153 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 3154 if (sc.comp_unit != nullptr) { 3155 DWARFDebugInfo *info = DebugInfo(); 3156 if (info == nullptr) 3157 return 0; 3158 3159 if (sc.function) { 3160 DWARFDIE function_die = GetDIE(sc.function->GetID()); 3161 3162 const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress( 3163 DW_AT_low_pc, LLDB_INVALID_ADDRESS); 3164 if (func_lo_pc != LLDB_INVALID_ADDRESS) { 3165 const size_t num_variables = ParseVariables( 3166 sc, function_die.GetFirstChild(), func_lo_pc, true, true); 3167 3168 // Let all blocks know they have parse all their variables 3169 sc.function->GetBlock(false).SetDidParseVariables(true, true); 3170 return num_variables; 3171 } 3172 } else if (sc.comp_unit) { 3173 DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID()); 3174 3175 if (dwarf_cu == nullptr) 3176 return 0; 3177 3178 uint32_t vars_added = 0; 3179 VariableListSP variables(sc.comp_unit->GetVariableList(false)); 3180 3181 if (variables.get() == nullptr) { 3182 variables = std::make_shared<VariableList>(); 3183 sc.comp_unit->SetVariableList(variables); 3184 3185 DIEArray die_offsets; 3186 m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(), 3187 die_offsets); 3188 const size_t num_matches = die_offsets.size(); 3189 if (num_matches) { 3190 for (size_t i = 0; i < num_matches; ++i) { 3191 const DIERef &die_ref = die_offsets[i]; 3192 DWARFDIE die = GetDIE(die_ref); 3193 if (die) { 3194 VariableSP var_sp( 3195 ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS)); 3196 if (var_sp) { 3197 variables->AddVariableIfUnique(var_sp); 3198 ++vars_added; 3199 } 3200 } else 3201 m_index->ReportInvalidDIERef(die_ref, ""); 3202 } 3203 } 3204 } 3205 return vars_added; 3206 } 3207 } 3208 return 0; 3209} 3210 3211VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc, 3212 const DWARFDIE &die, 3213 const lldb::addr_t func_low_pc) { 3214 if (die.GetDWARF() != this) 3215 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc); 3216 3217 VariableSP var_sp; 3218 if (!die) 3219 return var_sp; 3220 3221 var_sp = GetDIEToVariable()[die.GetDIE()]; 3222 if (var_sp) 3223 return var_sp; // Already been parsed! 3224 3225 const dw_tag_t tag = die.Tag(); 3226 ModuleSP module = GetObjectFile()->GetModule(); 3227 3228 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) || 3229 (tag == DW_TAG_formal_parameter && sc.function)) { 3230 DWARFAttributes attributes; 3231 const size_t num_attributes = die.GetAttributes(attributes); 3232 DWARFDIE spec_die; 3233 if (num_attributes > 0) { 3234 const char *name = nullptr; 3235 const char *mangled = nullptr; 3236 Declaration decl; 3237 uint32_t i; 3238 DWARFFormValue type_die_form; 3239 DWARFExpression location; 3240 bool is_external = false; 3241 bool is_artificial = false; 3242 bool location_is_const_value_data = false; 3243 bool has_explicit_location = false; 3244 DWARFFormValue const_value; 3245 Variable::RangeList scope_ranges; 3246 // AccessType accessibility = eAccessNone; 3247 3248 for (i = 0; i < num_attributes; ++i) { 3249 dw_attr_t attr = attributes.AttributeAtIndex(i); 3250 DWARFFormValue form_value; 3251 3252 if (attributes.ExtractFormValueAtIndex(i, form_value)) { 3253 switch (attr) { 3254 case DW_AT_decl_file: 3255 decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex( 3256 form_value.Unsigned())); 3257 break; 3258 case DW_AT_decl_line: 3259 decl.SetLine(form_value.Unsigned()); 3260 break; 3261 case DW_AT_decl_column: 3262 decl.SetColumn(form_value.Unsigned()); 3263 break; 3264 case DW_AT_name: 3265 name = form_value.AsCString(); 3266 break; 3267 case DW_AT_linkage_name: 3268 case DW_AT_MIPS_linkage_name: 3269 mangled = form_value.AsCString(); 3270 break; 3271 case DW_AT_type: 3272 type_die_form = form_value; 3273 break; 3274 case DW_AT_external: 3275 is_external = form_value.Boolean(); 3276 break; 3277 case DW_AT_const_value: 3278 // If we have already found a DW_AT_location attribute, ignore this 3279 // attribute. 3280 if (!has_explicit_location) { 3281 location_is_const_value_data = true; 3282 // The constant value will be either a block, a data value or a 3283 // string. 3284 auto debug_info_data = die.GetData(); 3285 if (DWARFFormValue::IsBlockForm(form_value.Form())) { 3286 // Retrieve the value as a block expression. 3287 uint32_t block_offset = 3288 form_value.BlockData() - debug_info_data.GetDataStart(); 3289 uint32_t block_length = form_value.Unsigned(); 3290 location = DWARFExpression( 3291 module, 3292 DataExtractor(debug_info_data, block_offset, block_length), 3293 die.GetCU()); 3294 } else if (DWARFFormValue::IsDataForm(form_value.Form())) { 3295 // Retrieve the value as a data expression. 3296 uint32_t data_offset = attributes.DIEOffsetAtIndex(i); 3297 if (auto data_length = form_value.GetFixedSize()) 3298 location = DWARFExpression( 3299 module, 3300 DataExtractor(debug_info_data, data_offset, *data_length), 3301 die.GetCU()); 3302 else { 3303 const uint8_t *data_pointer = form_value.BlockData(); 3304 if (data_pointer) { 3305 form_value.Unsigned(); 3306 } else if (DWARFFormValue::IsDataForm(form_value.Form())) { 3307 // we need to get the byte size of the type later after we 3308 // create the variable 3309 const_value = form_value; 3310 } 3311 } 3312 } else { 3313 // Retrieve the value as a string expression. 3314 if (form_value.Form() == DW_FORM_strp) { 3315 uint32_t data_offset = attributes.DIEOffsetAtIndex(i); 3316 if (auto data_length = form_value.GetFixedSize()) 3317 location = DWARFExpression(module, 3318 DataExtractor(debug_info_data, 3319 data_offset, 3320 *data_length), 3321 die.GetCU()); 3322 } else { 3323 const char *str = form_value.AsCString(); 3324 uint32_t string_offset = 3325 str - (const char *)debug_info_data.GetDataStart(); 3326 uint32_t string_length = strlen(str) + 1; 3327 location = DWARFExpression(module, 3328 DataExtractor(debug_info_data, 3329 string_offset, 3330 string_length), 3331 die.GetCU()); 3332 } 3333 } 3334 } 3335 break; 3336 case DW_AT_location: { 3337 location_is_const_value_data = false; 3338 has_explicit_location = true; 3339 if (DWARFFormValue::IsBlockForm(form_value.Form())) { 3340 auto data = die.GetData(); 3341 3342 uint32_t block_offset = 3343 form_value.BlockData() - data.GetDataStart(); 3344 uint32_t block_length = form_value.Unsigned(); 3345 location = DWARFExpression( 3346 module, DataExtractor(data, block_offset, block_length), 3347 die.GetCU()); 3348 } else { 3349 DataExtractor data = die.GetCU()->GetLocationData(); 3350 dw_offset_t offset = form_value.Unsigned(); 3351 if (form_value.Form() == DW_FORM_loclistx) 3352 offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1); 3353 if (data.ValidOffset(offset)) { 3354 data = DataExtractor(data, offset, data.GetByteSize() - offset); 3355 location = DWARFExpression(module, data, die.GetCU()); 3356 assert(func_low_pc != LLDB_INVALID_ADDRESS); 3357 location.SetLocationListAddresses( 3358 attributes.CompileUnitAtIndex(i)->GetBaseAddress(), 3359 func_low_pc); 3360 } 3361 } 3362 } break; 3363 case DW_AT_specification: 3364 spec_die = form_value.Reference(); 3365 break; 3366 case DW_AT_start_scope: 3367 // TODO: Implement this. 3368 break; 3369 case DW_AT_artificial: 3370 is_artificial = form_value.Boolean(); 3371 break; 3372 case DW_AT_accessibility: 3373 break; // accessibility = 3374 // DW_ACCESS_to_AccessType(form_value.Unsigned()); break; 3375 case DW_AT_declaration: 3376 case DW_AT_description: 3377 case DW_AT_endianity: 3378 case DW_AT_segment: 3379 case DW_AT_visibility: 3380 default: 3381 case DW_AT_abstract_origin: 3382 case DW_AT_sibling: 3383 break; 3384 } 3385 } 3386 } 3387 3388 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die); 3389 const dw_tag_t parent_tag = die.GetParent().Tag(); 3390 bool is_static_member = 3391 (parent_tag == DW_TAG_compile_unit || 3392 parent_tag == DW_TAG_partial_unit) && 3393 (parent_context_die.Tag() == DW_TAG_class_type || 3394 parent_context_die.Tag() == DW_TAG_structure_type); 3395 3396 ValueType scope = eValueTypeInvalid; 3397 3398 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die); 3399 SymbolContextScope *symbol_context_scope = nullptr; 3400 3401 bool has_explicit_mangled = mangled != nullptr; 3402 if (!mangled) { 3403 // LLDB relies on the mangled name (DW_TAG_linkage_name or 3404 // DW_AT_MIPS_linkage_name) to generate fully qualified names 3405 // of global variables with commands like "frame var j". For 3406 // example, if j were an int variable holding a value 4 and 3407 // declared in a namespace B which in turn is contained in a 3408 // namespace A, the command "frame var j" returns 3409 // "(int) A::B::j = 4". 3410 // If the compiler does not emit a linkage name, we should be 3411 // able to generate a fully qualified name from the 3412 // declaration context. 3413 if ((parent_tag == DW_TAG_compile_unit || 3414 parent_tag == DW_TAG_partial_unit) && 3415 Language::LanguageIsCPlusPlus(die.GetLanguage())) { 3416 DWARFDeclContext decl_ctx; 3417 3418 die.GetDWARFDeclContext(decl_ctx); 3419 mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString(); 3420 } 3421 } 3422 3423 if (tag == DW_TAG_formal_parameter) 3424 scope = eValueTypeVariableArgument; 3425 else { 3426 // DWARF doesn't specify if a DW_TAG_variable is a local, global 3427 // or static variable, so we have to do a little digging: 3428 // 1) DW_AT_linkage_name implies static lifetime (but may be missing) 3429 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var. 3430 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime. 3431 // Clang likes to combine small global variables into the same symbol 3432 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus 3433 // so we need to look through the whole expression. 3434 bool is_static_lifetime = 3435 has_explicit_mangled || 3436 (has_explicit_location && !location.IsValid()); 3437 // Check if the location has a DW_OP_addr with any address value... 3438 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS; 3439 if (!location_is_const_value_data) { 3440 bool op_error = false; 3441 location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error); 3442 if (op_error) { 3443 StreamString strm; 3444 location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0, 3445 nullptr); 3446 GetObjectFile()->GetModule()->ReportError( 3447 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(), 3448 die.GetTagAsCString(), strm.GetData()); 3449 } 3450 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS) 3451 is_static_lifetime = true; 3452 } 3453 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); 3454 if (debug_map_symfile) 3455 // Set the module of the expression to the linked module 3456 // instead of the oject file so the relocated address can be 3457 // found there. 3458 location.SetModule(debug_map_symfile->GetObjectFile()->GetModule()); 3459 3460 if (is_static_lifetime) { 3461 if (is_external) 3462 scope = eValueTypeVariableGlobal; 3463 else 3464 scope = eValueTypeVariableStatic; 3465 3466 if (debug_map_symfile) { 3467 // When leaving the DWARF in the .o files on darwin, when we have a 3468 // global variable that wasn't initialized, the .o file might not 3469 // have allocated a virtual address for the global variable. In 3470 // this case it will have created a symbol for the global variable 3471 // that is undefined/data and external and the value will be the 3472 // byte size of the variable. When we do the address map in 3473 // SymbolFileDWARFDebugMap we rely on having an address, we need to 3474 // do some magic here so we can get the correct address for our 3475 // global variable. The address for all of these entries will be 3476 // zero, and there will be an undefined symbol in this object file, 3477 // and the executable will have a matching symbol with a good 3478 // address. So here we dig up the correct address and replace it in 3479 // the location for the variable, and set the variable's symbol 3480 // context scope to be that of the main executable so the file 3481 // address will resolve correctly. 3482 bool linked_oso_file_addr = false; 3483 if (is_external && location_DW_OP_addr == 0) { 3484 // we have a possible uninitialized extern global 3485 ConstString const_name(mangled ? mangled : name); 3486 ObjectFile *debug_map_objfile = 3487 debug_map_symfile->GetObjectFile(); 3488 if (debug_map_objfile) { 3489 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab(); 3490 if (debug_map_symtab) { 3491 Symbol *exe_symbol = 3492 debug_map_symtab->FindFirstSymbolWithNameAndType( 3493 const_name, eSymbolTypeData, Symtab::eDebugYes, 3494 Symtab::eVisibilityExtern); 3495 if (exe_symbol) { 3496 if (exe_symbol->ValueIsAddress()) { 3497 const addr_t exe_file_addr = 3498 exe_symbol->GetAddressRef().GetFileAddress(); 3499 if (exe_file_addr != LLDB_INVALID_ADDRESS) { 3500 if (location.Update_DW_OP_addr(exe_file_addr)) { 3501 linked_oso_file_addr = true; 3502 symbol_context_scope = exe_symbol; 3503 } 3504 } 3505 } 3506 } 3507 } 3508 } 3509 } 3510 3511 if (!linked_oso_file_addr) { 3512 // The DW_OP_addr is not zero, but it contains a .o file address 3513 // which needs to be linked up correctly. 3514 const lldb::addr_t exe_file_addr = 3515 debug_map_symfile->LinkOSOFileAddress(this, 3516 location_DW_OP_addr); 3517 if (exe_file_addr != LLDB_INVALID_ADDRESS) { 3518 // Update the file address for this variable 3519 location.Update_DW_OP_addr(exe_file_addr); 3520 } else { 3521 // Variable didn't make it into the final executable 3522 return var_sp; 3523 } 3524 } 3525 } 3526 } else { 3527 if (location_is_const_value_data) 3528 scope = eValueTypeVariableStatic; 3529 else { 3530 scope = eValueTypeVariableLocal; 3531 if (debug_map_symfile) { 3532 // We need to check for TLS addresses that we need to fixup 3533 if (location.ContainsThreadLocalStorage()) { 3534 location.LinkThreadLocalStorage( 3535 debug_map_symfile->GetObjectFile()->GetModule(), 3536 [this, debug_map_symfile]( 3537 lldb::addr_t unlinked_file_addr) -> lldb::addr_t { 3538 return debug_map_symfile->LinkOSOFileAddress( 3539 this, unlinked_file_addr); 3540 }); 3541 scope = eValueTypeVariableThreadLocal; 3542 } 3543 } 3544 } 3545 } 3546 } 3547 3548 if (symbol_context_scope == nullptr) { 3549 switch (parent_tag) { 3550 case DW_TAG_subprogram: 3551 case DW_TAG_inlined_subroutine: 3552 case DW_TAG_lexical_block: 3553 if (sc.function) { 3554 symbol_context_scope = sc.function->GetBlock(true).FindBlockByID( 3555 sc_parent_die.GetID()); 3556 if (symbol_context_scope == nullptr) 3557 symbol_context_scope = sc.function; 3558 } 3559 break; 3560 3561 default: 3562 symbol_context_scope = sc.comp_unit; 3563 break; 3564 } 3565 } 3566 3567 if (symbol_context_scope) { 3568 SymbolFileTypeSP type_sp( 3569 new SymbolFileType(*this, GetUID(type_die_form.Reference()))); 3570 3571 if (const_value.Form() && type_sp && type_sp->GetType()) 3572 location.UpdateValue(const_value.Unsigned(), 3573 type_sp->GetType()->GetByteSize().getValueOr(0), 3574 die.GetCU()->GetAddressByteSize()); 3575 3576 var_sp = std::make_shared<Variable>( 3577 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope, 3578 scope_ranges, &decl, location, is_external, is_artificial, 3579 is_static_member); 3580 3581 var_sp->SetLocationIsConstantValueData(location_is_const_value_data); 3582 } else { 3583 // Not ready to parse this variable yet. It might be a global or static 3584 // variable that is in a function scope and the function in the symbol 3585 // context wasn't filled in yet 3586 return var_sp; 3587 } 3588 } 3589 // Cache var_sp even if NULL (the variable was just a specification or was 3590 // missing vital information to be able to be displayed in the debugger 3591 // (missing location due to optimization, etc)) so we don't re-parse this 3592 // DIE over and over later... 3593 GetDIEToVariable()[die.GetDIE()] = var_sp; 3594 if (spec_die) 3595 GetDIEToVariable()[spec_die.GetDIE()] = var_sp; 3596 } 3597 return var_sp; 3598} 3599 3600DWARFDIE 3601SymbolFileDWARF::FindBlockContainingSpecification( 3602 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) { 3603 // Give the concrete function die specified by "func_die_offset", find the 3604 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points 3605 // to "spec_block_die_offset" 3606 return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref), 3607 spec_block_die_offset); 3608} 3609 3610DWARFDIE 3611SymbolFileDWARF::FindBlockContainingSpecification( 3612 const DWARFDIE &die, dw_offset_t spec_block_die_offset) { 3613 if (die) { 3614 switch (die.Tag()) { 3615 case DW_TAG_subprogram: 3616 case DW_TAG_inlined_subroutine: 3617 case DW_TAG_lexical_block: { 3618 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() == 3619 spec_block_die_offset) 3620 return die; 3621 3622 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() == 3623 spec_block_die_offset) 3624 return die; 3625 } break; 3626 default: 3627 break; 3628 } 3629 3630 // Give the concrete function die specified by "func_die_offset", find the 3631 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points 3632 // to "spec_block_die_offset" 3633 for (DWARFDIE child_die = die.GetFirstChild(); child_die; 3634 child_die = child_die.GetSibling()) { 3635 DWARFDIE result_die = 3636 FindBlockContainingSpecification(child_die, spec_block_die_offset); 3637 if (result_die) 3638 return result_die; 3639 } 3640 } 3641 3642 return DWARFDIE(); 3643} 3644 3645size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc, 3646 const DWARFDIE &orig_die, 3647 const lldb::addr_t func_low_pc, 3648 bool parse_siblings, bool parse_children, 3649 VariableList *cc_variable_list) { 3650 if (!orig_die) 3651 return 0; 3652 3653 VariableListSP variable_list_sp; 3654 3655 size_t vars_added = 0; 3656 DWARFDIE die = orig_die; 3657 while (die) { 3658 dw_tag_t tag = die.Tag(); 3659 3660 // Check to see if we have already parsed this variable or constant? 3661 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()]; 3662 if (var_sp) { 3663 if (cc_variable_list) 3664 cc_variable_list->AddVariableIfUnique(var_sp); 3665 } else { 3666 // We haven't already parsed it, lets do that now. 3667 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) || 3668 (tag == DW_TAG_formal_parameter && sc.function)) { 3669 if (variable_list_sp.get() == nullptr) { 3670 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die); 3671 dw_tag_t parent_tag = sc_parent_die.Tag(); 3672 switch (parent_tag) { 3673 case DW_TAG_compile_unit: 3674 case DW_TAG_partial_unit: 3675 if (sc.comp_unit != nullptr) { 3676 variable_list_sp = sc.comp_unit->GetVariableList(false); 3677 if (variable_list_sp.get() == nullptr) { 3678 variable_list_sp = std::make_shared<VariableList>(); 3679 } 3680 } else { 3681 GetObjectFile()->GetModule()->ReportError( 3682 "parent 0x%8.8" PRIx64 " %s with no valid compile unit in " 3683 "symbol context for 0x%8.8" PRIx64 " %s.\n", 3684 sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(), 3685 orig_die.GetID(), orig_die.GetTagAsCString()); 3686 } 3687 break; 3688 3689 case DW_TAG_subprogram: 3690 case DW_TAG_inlined_subroutine: 3691 case DW_TAG_lexical_block: 3692 if (sc.function != nullptr) { 3693 // Check to see if we already have parsed the variables for the 3694 // given scope 3695 3696 Block *block = sc.function->GetBlock(true).FindBlockByID( 3697 sc_parent_die.GetID()); 3698 if (block == nullptr) { 3699 // This must be a specification or abstract origin with a 3700 // concrete block counterpart in the current function. We need 3701 // to find the concrete block so we can correctly add the 3702 // variable to it 3703 const DWARFDIE concrete_block_die = 3704 FindBlockContainingSpecification( 3705 GetDIE(sc.function->GetID()), 3706 sc_parent_die.GetOffset()); 3707 if (concrete_block_die) 3708 block = sc.function->GetBlock(true).FindBlockByID( 3709 concrete_block_die.GetID()); 3710 } 3711 3712 if (block != nullptr) { 3713 const bool can_create = false; 3714 variable_list_sp = block->GetBlockVariableList(can_create); 3715 if (variable_list_sp.get() == nullptr) { 3716 variable_list_sp = std::make_shared<VariableList>(); 3717 block->SetVariableList(variable_list_sp); 3718 } 3719 } 3720 } 3721 break; 3722 3723 default: 3724 GetObjectFile()->GetModule()->ReportError( 3725 "didn't find appropriate parent DIE for variable list for " 3726 "0x%8.8" PRIx64 " %s.\n", 3727 orig_die.GetID(), orig_die.GetTagAsCString()); 3728 break; 3729 } 3730 } 3731 3732 if (variable_list_sp) { 3733 VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc)); 3734 if (var_sp) { 3735 variable_list_sp->AddVariableIfUnique(var_sp); 3736 if (cc_variable_list) 3737 cc_variable_list->AddVariableIfUnique(var_sp); 3738 ++vars_added; 3739 } 3740 } 3741 } 3742 } 3743 3744 bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram); 3745 3746 if (!skip_children && parse_children && die.HasChildren()) { 3747 vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, 3748 true, cc_variable_list); 3749 } 3750 3751 if (parse_siblings) 3752 die = die.GetSibling(); 3753 else 3754 die.Clear(); 3755 } 3756 return vars_added; 3757} 3758 3759/// Collect call site parameters in a DW_TAG_call_site DIE. 3760static CallSiteParameterArray 3761CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) { 3762 CallSiteParameterArray parameters; 3763 for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid(); 3764 child = child.GetSibling()) { 3765 if (child.Tag() != DW_TAG_call_site_parameter) 3766 continue; 3767 3768 llvm::Optional<DWARFExpression> LocationInCallee; 3769 llvm::Optional<DWARFExpression> LocationInCaller; 3770 3771 DWARFAttributes attributes; 3772 const size_t num_attributes = child.GetAttributes(attributes); 3773 3774 // Parse the location at index \p attr_index within this call site parameter 3775 // DIE, or return None on failure. 3776 auto parse_simple_location = 3777 [&](int attr_index) -> llvm::Optional<DWARFExpression> { 3778 DWARFFormValue form_value; 3779 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value)) 3780 return {}; 3781 if (!DWARFFormValue::IsBlockForm(form_value.Form())) 3782 return {}; 3783 auto data = child.GetData(); 3784 uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); 3785 uint32_t block_length = form_value.Unsigned(); 3786 return DWARFExpression(module, 3787 DataExtractor(data, block_offset, block_length), 3788 child.GetCU()); 3789 }; 3790 3791 for (size_t i = 0; i < num_attributes; ++i) { 3792 dw_attr_t attr = attributes.AttributeAtIndex(i); 3793 if (attr == DW_AT_location) 3794 LocationInCallee = parse_simple_location(i); 3795 if (attr == DW_AT_call_value) 3796 LocationInCaller = parse_simple_location(i); 3797 } 3798 3799 if (LocationInCallee && LocationInCaller) { 3800 CallSiteParameter param = {*LocationInCallee, *LocationInCaller}; 3801 parameters.push_back(param); 3802 } 3803 } 3804 return parameters; 3805} 3806 3807/// Collect call graph edges present in a function DIE. 3808static std::vector<std::unique_ptr<lldb_private::CallEdge>> 3809CollectCallEdges(ModuleSP module, DWARFDIE function_die) { 3810 // Check if the function has a supported call site-related attribute. 3811 // TODO: In the future it may be worthwhile to support call_all_source_calls. 3812 uint64_t has_call_edges = 3813 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0); 3814 if (!has_call_edges) 3815 return {}; 3816 3817 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3818 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}", 3819 function_die.GetPubname()); 3820 3821 // Scan the DIE for TAG_call_site entries. 3822 // TODO: A recursive scan of all blocks in the subprogram is needed in order 3823 // to be DWARF5-compliant. This may need to be done lazily to be performant. 3824 // For now, assume that all entries are nested directly under the subprogram 3825 // (this is the kind of DWARF LLVM produces) and parse them eagerly. 3826 std::vector<std::unique_ptr<CallEdge>> call_edges; 3827 for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid(); 3828 child = child.GetSibling()) { 3829 if (child.Tag() != DW_TAG_call_site) 3830 continue; 3831 3832 llvm::Optional<DWARFDIE> call_origin; 3833 llvm::Optional<DWARFExpression> call_target; 3834 addr_t return_pc = LLDB_INVALID_ADDRESS; 3835 3836 DWARFAttributes attributes; 3837 const size_t num_attributes = child.GetAttributes(attributes); 3838 for (size_t i = 0; i < num_attributes; ++i) { 3839 DWARFFormValue form_value; 3840 if (!attributes.ExtractFormValueAtIndex(i, form_value)) { 3841 LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form"); 3842 break; 3843 } 3844 3845 dw_attr_t attr = attributes.AttributeAtIndex(i); 3846 3847 // Extract DW_AT_call_origin (the call target's DIE). 3848 if (attr == DW_AT_call_origin) { 3849 call_origin = form_value.Reference(); 3850 if (!call_origin->IsValid()) { 3851 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}", 3852 function_die.GetPubname()); 3853 break; 3854 } 3855 } 3856 3857 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's 3858 // available. It should only ever be unavailable for tail call edges, in 3859 // which case use LLDB_INVALID_ADDRESS. 3860 if (attr == DW_AT_call_return_pc) 3861 return_pc = form_value.Address(); 3862 3863 // Extract DW_AT_call_target (the location of the address of the indirect 3864 // call). 3865 if (attr == DW_AT_call_target) { 3866 if (!DWARFFormValue::IsBlockForm(form_value.Form())) { 3867 LLDB_LOG(log, 3868 "CollectCallEdges: AT_call_target does not have block form"); 3869 break; 3870 } 3871 3872 auto data = child.GetData(); 3873 uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); 3874 uint32_t block_length = form_value.Unsigned(); 3875 call_target = DWARFExpression( 3876 module, DataExtractor(data, block_offset, block_length), 3877 child.GetCU()); 3878 } 3879 } 3880 if (!call_origin && !call_target) { 3881 LLDB_LOG(log, "CollectCallEdges: call site without any call target"); 3882 continue; 3883 } 3884 3885 // Extract call site parameters. 3886 CallSiteParameterArray parameters = 3887 CollectCallSiteParameters(module, child); 3888 3889 std::unique_ptr<CallEdge> edge; 3890 if (call_origin) { 3891 LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})", 3892 call_origin->GetPubname(), return_pc); 3893 edge = std::make_unique<DirectCallEdge>(call_origin->GetMangledName(), 3894 return_pc, std::move(parameters)); 3895 } else { 3896 if (log) { 3897 StreamString call_target_desc; 3898 call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief, 3899 LLDB_INVALID_ADDRESS, nullptr); 3900 LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}", 3901 call_target_desc.GetString()); 3902 } 3903 edge = std::make_unique<IndirectCallEdge>(*call_target, return_pc, 3904 std::move(parameters)); 3905 } 3906 3907 if (log && parameters.size()) { 3908 for (const CallSiteParameter ¶m : parameters) { 3909 StreamString callee_loc_desc, caller_loc_desc; 3910 param.LocationInCallee.GetDescription(&callee_loc_desc, 3911 eDescriptionLevelBrief, 3912 LLDB_INVALID_ADDRESS, nullptr); 3913 param.LocationInCaller.GetDescription(&caller_loc_desc, 3914 eDescriptionLevelBrief, 3915 LLDB_INVALID_ADDRESS, nullptr); 3916 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}", 3917 callee_loc_desc.GetString(), caller_loc_desc.GetString()); 3918 } 3919 } 3920 3921 call_edges.push_back(std::move(edge)); 3922 } 3923 return call_edges; 3924} 3925 3926std::vector<std::unique_ptr<lldb_private::CallEdge>> 3927SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) { 3928 DWARFDIE func_die = GetDIE(func_id.GetID()); 3929 if (func_die.IsValid()) 3930 return CollectCallEdges(GetObjectFile()->GetModule(), func_die); 3931 return {}; 3932} 3933 3934// PluginInterface protocol 3935ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); } 3936 3937uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; } 3938 3939void SymbolFileDWARF::Dump(lldb_private::Stream &s) { 3940 SymbolFile::Dump(s); 3941 m_index->Dump(s); 3942} 3943 3944void SymbolFileDWARF::DumpClangAST(Stream &s) { 3945 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus); 3946 if (!ts_or_err) 3947 return; 3948 ClangASTContext *clang = 3949 llvm::dyn_cast_or_null<ClangASTContext>(&ts_or_err.get()); 3950 if (!clang) 3951 return; 3952 clang->Dump(s); 3953} 3954 3955SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() { 3956 if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) { 3957 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); 3958 if (module_sp) { 3959 m_debug_map_symfile = 3960 (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile(); 3961 } 3962 } 3963 return m_debug_map_symfile; 3964} 3965 3966SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() { 3967 llvm::call_once(m_dwp_symfile_once_flag, [this]() { 3968 ModuleSpec module_spec; 3969 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec(); 3970 module_spec.GetSymbolFileSpec() = 3971 FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp"); 3972 3973 FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); 3974 FileSpec dwp_filespec = 3975 Symbols::LocateExecutableSymbolFile(module_spec, search_paths); 3976 if (FileSystem::Instance().Exists(dwp_filespec)) { 3977 m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(), 3978 dwp_filespec); 3979 } 3980 }); 3981 return m_dwp_symfile.get(); 3982} 3983