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