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