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