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