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