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