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