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