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