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 const DWARFDebugAranges &aranges = debug_info.GetCompileUnitAranges(); 1866 const dw_offset_t cu_offset = aranges.FindAddress(file_vm_addr); 1867 if (cu_offset == DW_INVALID_OFFSET) { 1868 // Global variables are not in the compile unit address ranges. The only 1869 // way to currently find global variables is to iterate over the 1870 // .debug_pubnames or the __apple_names table and find all items in there 1871 // that point to DW_TAG_variable DIEs and then find the address that 1872 // matches. 1873 if (resolve_scope & eSymbolContextVariable) { 1874 GlobalVariableMap &map = GetGlobalAranges(); 1875 const GlobalVariableMap::Entry *entry = 1876 map.FindEntryThatContains(file_vm_addr); 1877 if (entry && entry->data) { 1878 Variable *variable = entry->data; 1879 SymbolContextScope *scc = variable->GetSymbolContextScope(); 1880 if (scc) { 1881 scc->CalculateSymbolContext(&sc); 1882 sc.variable = variable; 1883 } 1884 return sc.GetResolvedMask(); 1885 } 1886 } 1887 } else { 1888 uint32_t cu_idx = DW_INVALID_INDEX; 1889 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>( 1890 debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, cu_offset, 1891 &cu_idx))) { 1892 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 1893 if (sc.comp_unit) { 1894 resolved |= eSymbolContextCompUnit; 1895 1896 bool force_check_line_table = false; 1897 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) { 1898 ResolveFunctionAndBlock(file_vm_addr, 1899 resolve_scope & eSymbolContextBlock, sc); 1900 if (sc.function) 1901 resolved |= eSymbolContextFunction; 1902 else { 1903 // We might have had a compile unit that had discontiguous address 1904 // ranges where the gaps are symbols that don't have any debug 1905 // info. Discontiguous compile unit address ranges should only 1906 // happen when there aren't other functions from other compile 1907 // units in these gaps. This helps keep the size of the aranges 1908 // down. 1909 force_check_line_table = true; 1910 } 1911 if (sc.block) 1912 resolved |= eSymbolContextBlock; 1913 } 1914 1915 if ((resolve_scope & eSymbolContextLineEntry) || 1916 force_check_line_table) { 1917 LineTable *line_table = sc.comp_unit->GetLineTable(); 1918 if (line_table != nullptr) { 1919 // And address that makes it into this function should be in terms 1920 // of this debug file if there is no debug map, or it will be an 1921 // address in the .o file which needs to be fixed up to be in 1922 // terms of the debug map executable. Either way, calling 1923 // FixupAddress() will work for us. 1924 Address exe_so_addr(so_addr); 1925 if (FixupAddress(exe_so_addr)) { 1926 if (line_table->FindLineEntryByAddress(exe_so_addr, 1927 sc.line_entry)) { 1928 resolved |= eSymbolContextLineEntry; 1929 } 1930 } 1931 } 1932 } 1933 1934 if (force_check_line_table && !(resolved & eSymbolContextLineEntry)) { 1935 // We might have had a compile unit that had discontiguous address 1936 // ranges where the gaps are symbols that don't have any debug info. 1937 // Discontiguous compile unit address ranges should only happen when 1938 // there aren't other functions from other compile units in these 1939 // gaps. This helps keep the size of the aranges down. 1940 sc.comp_unit = nullptr; 1941 resolved &= ~eSymbolContextCompUnit; 1942 } 1943 } else { 1944 GetObjectFile()->GetModule()->ReportWarning( 1945 "0x%8.8x: compile unit %u failed to create a valid " 1946 "lldb_private::CompileUnit class.", 1947 cu_offset, cu_idx); 1948 } 1949 } 1950 } 1951 } 1952 return resolved; 1953 } 1954 1955 uint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec, 1956 uint32_t line, 1957 bool check_inlines, 1958 SymbolContextItem resolve_scope, 1959 SymbolContextList &sc_list) { 1960 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1961 const uint32_t prev_size = sc_list.GetSize(); 1962 if (resolve_scope & eSymbolContextCompUnit) { 1963 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus; 1964 ++cu_idx) { 1965 CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get(); 1966 if (!dc_cu) 1967 continue; 1968 1969 bool file_spec_matches_cu_file_spec = 1970 FileSpec::Match(file_spec, dc_cu->GetPrimaryFile()); 1971 if (check_inlines || file_spec_matches_cu_file_spec) { 1972 dc_cu->ResolveSymbolContext(file_spec, line, check_inlines, false, 1973 resolve_scope, sc_list); 1974 if (!check_inlines) 1975 break; 1976 } 1977 } 1978 } 1979 return sc_list.GetSize() - prev_size; 1980 } 1981 1982 void SymbolFileDWARF::PreloadSymbols() { 1983 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 1984 m_index->Preload(); 1985 } 1986 1987 std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const { 1988 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); 1989 if (module_sp) 1990 return module_sp->GetMutex(); 1991 return GetObjectFile()->GetModule()->GetMutex(); 1992 } 1993 1994 bool SymbolFileDWARF::DeclContextMatchesThisSymbolFile( 1995 const lldb_private::CompilerDeclContext &decl_ctx) { 1996 if (!decl_ctx.IsValid()) { 1997 // Invalid namespace decl which means we aren't matching only things in 1998 // this symbol file, so return true to indicate it matches this symbol 1999 // file. 2000 return true; 2001 } 2002 2003 TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem(); 2004 auto type_system_or_err = GetTypeSystemForLanguage( 2005 decl_ctx_type_system->GetMinimumLanguage(nullptr)); 2006 if (auto err = type_system_or_err.takeError()) { 2007 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 2008 std::move(err), 2009 "Unable to match namespace decl using TypeSystem"); 2010 return false; 2011 } 2012 2013 if (decl_ctx_type_system == &type_system_or_err.get()) 2014 return true; // The type systems match, return true 2015 2016 // The namespace AST was valid, and it does not match... 2017 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2018 2019 if (log) 2020 GetObjectFile()->GetModule()->LogMessage( 2021 log, "Valid namespace does not match symbol file"); 2022 2023 return false; 2024 } 2025 2026 void SymbolFileDWARF::FindGlobalVariables( 2027 ConstString name, const CompilerDeclContext &parent_decl_ctx, 2028 uint32_t max_matches, VariableList &variables) { 2029 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2030 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2031 2032 if (log) 2033 GetObjectFile()->GetModule()->LogMessage( 2034 log, 2035 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " 2036 "parent_decl_ctx=%p, max_matches=%u, variables)", 2037 name.GetCString(), static_cast<const void *>(&parent_decl_ctx), 2038 max_matches); 2039 2040 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2041 return; 2042 2043 // Remember how many variables are in the list before we search. 2044 const uint32_t original_size = variables.GetSize(); 2045 2046 llvm::StringRef basename; 2047 llvm::StringRef context; 2048 bool name_is_mangled = (bool)Mangled(name); 2049 2050 if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(), 2051 context, basename)) 2052 basename = name.GetStringRef(); 2053 2054 // Loop invariant: Variables up to this index have been checked for context 2055 // matches. 2056 uint32_t pruned_idx = original_size; 2057 2058 SymbolContext sc; 2059 m_index->GetGlobalVariables(ConstString(basename), [&](DWARFDIE die) { 2060 if (!sc.module_sp) 2061 sc.module_sp = m_objfile_sp->GetModule(); 2062 assert(sc.module_sp); 2063 2064 if (die.Tag() != DW_TAG_variable) 2065 return true; 2066 2067 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); 2068 if (!dwarf_cu) 2069 return true; 2070 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2071 2072 if (parent_decl_ctx) { 2073 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) { 2074 CompilerDeclContext actual_parent_decl_ctx = 2075 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); 2076 if (!actual_parent_decl_ctx || 2077 actual_parent_decl_ctx != parent_decl_ctx) 2078 return true; 2079 } 2080 } 2081 2082 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); 2083 while (pruned_idx < variables.GetSize()) { 2084 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx); 2085 if (name_is_mangled || 2086 var_sp->GetName().GetStringRef().contains(name.GetStringRef())) 2087 ++pruned_idx; 2088 else 2089 variables.RemoveVariableAtIndex(pruned_idx); 2090 } 2091 2092 return variables.GetSize() - original_size < max_matches; 2093 }); 2094 2095 // Return the number of variable that were appended to the list 2096 const uint32_t num_matches = variables.GetSize() - original_size; 2097 if (log && num_matches > 0) { 2098 GetObjectFile()->GetModule()->LogMessage( 2099 log, 2100 "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", " 2101 "parent_decl_ctx=%p, max_matches=%u, variables) => %u", 2102 name.GetCString(), static_cast<const void *>(&parent_decl_ctx), 2103 max_matches, num_matches); 2104 } 2105 } 2106 2107 void SymbolFileDWARF::FindGlobalVariables(const RegularExpression ®ex, 2108 uint32_t max_matches, 2109 VariableList &variables) { 2110 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2111 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2112 2113 if (log) { 2114 GetObjectFile()->GetModule()->LogMessage( 2115 log, 2116 "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", " 2117 "max_matches=%u, variables)", 2118 regex.GetText().str().c_str(), max_matches); 2119 } 2120 2121 // Remember how many variables are in the list before we search. 2122 const uint32_t original_size = variables.GetSize(); 2123 2124 SymbolContext sc; 2125 m_index->GetGlobalVariables(regex, [&](DWARFDIE die) { 2126 if (!sc.module_sp) 2127 sc.module_sp = m_objfile_sp->GetModule(); 2128 assert(sc.module_sp); 2129 2130 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()); 2131 if (!dwarf_cu) 2132 return true; 2133 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2134 2135 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables); 2136 2137 return variables.GetSize() - original_size < max_matches; 2138 }); 2139 } 2140 2141 bool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die, 2142 bool include_inlines, 2143 SymbolContextList &sc_list) { 2144 SymbolContext sc; 2145 2146 if (!orig_die) 2147 return false; 2148 2149 // If we were passed a die that is not a function, just return false... 2150 if (!(orig_die.Tag() == DW_TAG_subprogram || 2151 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine))) 2152 return false; 2153 2154 DWARFDIE die = orig_die; 2155 DWARFDIE inlined_die; 2156 if (die.Tag() == DW_TAG_inlined_subroutine) { 2157 inlined_die = die; 2158 2159 while (true) { 2160 die = die.GetParent(); 2161 2162 if (die) { 2163 if (die.Tag() == DW_TAG_subprogram) 2164 break; 2165 } else 2166 break; 2167 } 2168 } 2169 assert(die && die.Tag() == DW_TAG_subprogram); 2170 if (GetFunction(die, sc)) { 2171 Address addr; 2172 // Parse all blocks if needed 2173 if (inlined_die) { 2174 Block &function_block = sc.function->GetBlock(true); 2175 sc.block = function_block.FindBlockByID(inlined_die.GetID()); 2176 if (sc.block == nullptr) 2177 sc.block = function_block.FindBlockByID(inlined_die.GetOffset()); 2178 if (sc.block == nullptr || !sc.block->GetStartAddress(addr)) 2179 addr.Clear(); 2180 } else { 2181 sc.block = nullptr; 2182 addr = sc.function->GetAddressRange().GetBaseAddress(); 2183 } 2184 2185 2186 if (auto section_sp = addr.GetSection()) { 2187 if (section_sp->GetPermissions() & ePermissionsExecutable) { 2188 sc_list.Append(sc); 2189 return true; 2190 } 2191 } 2192 } 2193 2194 return false; 2195 } 2196 2197 bool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext &decl_ctx, 2198 const DWARFDIE &die) { 2199 // If we have no parent decl context to match this DIE matches, and if the 2200 // parent decl context isn't valid, we aren't trying to look for any 2201 // particular decl context so any die matches. 2202 if (!decl_ctx.IsValid()) 2203 return true; 2204 2205 if (die) { 2206 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) { 2207 if (CompilerDeclContext actual_decl_ctx = 2208 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die)) 2209 return decl_ctx.IsContainedInLookup(actual_decl_ctx); 2210 } 2211 } 2212 return false; 2213 } 2214 2215 void SymbolFileDWARF::FindFunctions(ConstString name, 2216 const CompilerDeclContext &parent_decl_ctx, 2217 FunctionNameType name_type_mask, 2218 bool include_inlines, 2219 SymbolContextList &sc_list) { 2220 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2221 LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (name = '%s')", 2222 name.AsCString()); 2223 2224 // eFunctionNameTypeAuto should be pre-resolved by a call to 2225 // Module::LookupInfo::LookupInfo() 2226 assert((name_type_mask & eFunctionNameTypeAuto) == 0); 2227 2228 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2229 2230 if (log) { 2231 GetObjectFile()->GetModule()->LogMessage( 2232 log, 2233 "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)", 2234 name.GetCString(), name_type_mask); 2235 } 2236 2237 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2238 return; 2239 2240 // If name is empty then we won't find anything. 2241 if (name.IsEmpty()) 2242 return; 2243 2244 // Remember how many sc_list are in the list before we search in case we are 2245 // appending the results to a variable list. 2246 2247 const uint32_t original_size = sc_list.GetSize(); 2248 2249 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; 2250 2251 m_index->GetFunctions(name, *this, parent_decl_ctx, name_type_mask, 2252 [&](DWARFDIE die) { 2253 if (resolved_dies.insert(die.GetDIE()).second) 2254 ResolveFunction(die, include_inlines, sc_list); 2255 return true; 2256 }); 2257 2258 // Return the number of variable that were appended to the list 2259 const uint32_t num_matches = sc_list.GetSize() - original_size; 2260 2261 if (log && num_matches > 0) { 2262 GetObjectFile()->GetModule()->LogMessage( 2263 log, 2264 "SymbolFileDWARF::FindFunctions (name=\"%s\", " 2265 "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u", 2266 name.GetCString(), name_type_mask, include_inlines, 2267 num_matches); 2268 } 2269 } 2270 2271 void SymbolFileDWARF::FindFunctions(const RegularExpression ®ex, 2272 bool include_inlines, 2273 SymbolContextList &sc_list) { 2274 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2275 LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (regex = '%s')", 2276 regex.GetText().str().c_str()); 2277 2278 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2279 2280 if (log) { 2281 GetObjectFile()->GetModule()->LogMessage( 2282 log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)", 2283 regex.GetText().str().c_str()); 2284 } 2285 2286 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies; 2287 m_index->GetFunctions(regex, [&](DWARFDIE die) { 2288 if (resolved_dies.insert(die.GetDIE()).second) 2289 ResolveFunction(die, include_inlines, sc_list); 2290 return true; 2291 }); 2292 } 2293 2294 void SymbolFileDWARF::GetMangledNamesForFunction( 2295 const std::string &scope_qualified_name, 2296 std::vector<ConstString> &mangled_names) { 2297 DWARFDebugInfo &info = DebugInfo(); 2298 uint32_t num_comp_units = info.GetNumUnits(); 2299 for (uint32_t i = 0; i < num_comp_units; i++) { 2300 DWARFUnit *cu = info.GetUnitAtIndex(i); 2301 if (cu == nullptr) 2302 continue; 2303 2304 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile(); 2305 if (dwo) 2306 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names); 2307 } 2308 2309 for (DIERef die_ref : 2310 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) { 2311 DWARFDIE die = GetDIE(die_ref); 2312 mangled_names.push_back(ConstString(die.GetMangledName())); 2313 } 2314 } 2315 2316 void SymbolFileDWARF::FindTypes( 2317 ConstString name, const CompilerDeclContext &parent_decl_ctx, 2318 uint32_t max_matches, 2319 llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files, 2320 TypeMap &types) { 2321 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2322 // Make sure we haven't already searched this SymbolFile before. 2323 if (!searched_symbol_files.insert(this).second) 2324 return; 2325 2326 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2327 2328 if (log) { 2329 if (parent_decl_ctx) 2330 GetObjectFile()->GetModule()->LogMessage( 2331 log, 2332 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " 2333 "%p (\"%s\"), max_matches=%u, type_list)", 2334 name.GetCString(), static_cast<const void *>(&parent_decl_ctx), 2335 parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches); 2336 else 2337 GetObjectFile()->GetModule()->LogMessage( 2338 log, 2339 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = " 2340 "NULL, max_matches=%u, type_list)", 2341 name.GetCString(), max_matches); 2342 } 2343 2344 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2345 return; 2346 2347 m_index->GetTypes(name, [&](DWARFDIE die) { 2348 if (!DIEInDeclContext(parent_decl_ctx, die)) 2349 return true; // The containing decl contexts don't match 2350 2351 Type *matching_type = ResolveType(die, true, true); 2352 if (!matching_type) 2353 return true; 2354 2355 // We found a type pointer, now find the shared pointer form our type 2356 // list 2357 types.InsertUnique(matching_type->shared_from_this()); 2358 return types.GetSize() < max_matches; 2359 }); 2360 2361 // Next search through the reachable Clang modules. This only applies for 2362 // DWARF objects compiled with -gmodules that haven't been processed by 2363 // dsymutil. 2364 if (types.GetSize() < max_matches) { 2365 UpdateExternalModuleListIfNeeded(); 2366 2367 for (const auto &pair : m_external_type_modules) 2368 if (ModuleSP external_module_sp = pair.second) 2369 if (SymbolFile *sym_file = external_module_sp->GetSymbolFile()) 2370 sym_file->FindTypes(name, parent_decl_ctx, max_matches, 2371 searched_symbol_files, types); 2372 } 2373 2374 if (log && types.GetSize()) { 2375 if (parent_decl_ctx) { 2376 GetObjectFile()->GetModule()->LogMessage( 2377 log, 2378 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " 2379 "= %p (\"%s\"), max_matches=%u, type_list) => %u", 2380 name.GetCString(), static_cast<const void *>(&parent_decl_ctx), 2381 parent_decl_ctx.GetName().AsCString("<NULL>"), max_matches, 2382 types.GetSize()); 2383 } else { 2384 GetObjectFile()->GetModule()->LogMessage( 2385 log, 2386 "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx " 2387 "= NULL, max_matches=%u, type_list) => %u", 2388 name.GetCString(), max_matches, types.GetSize()); 2389 } 2390 } 2391 } 2392 2393 void SymbolFileDWARF::FindTypes( 2394 llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages, 2395 llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) { 2396 // Make sure we haven't already searched this SymbolFile before. 2397 if (!searched_symbol_files.insert(this).second) 2398 return; 2399 2400 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2401 if (pattern.empty()) 2402 return; 2403 2404 ConstString name = pattern.back().name; 2405 2406 if (!name) 2407 return; 2408 2409 m_index->GetTypes(name, [&](DWARFDIE die) { 2410 if (!languages[GetLanguage(*die.GetCU())]) 2411 return true; 2412 2413 llvm::SmallVector<CompilerContext, 4> die_context; 2414 die.GetDeclContext(die_context); 2415 if (!contextMatches(die_context, pattern)) 2416 return true; 2417 2418 if (Type *matching_type = ResolveType(die, true, true)) { 2419 // We found a type pointer, now find the shared pointer form our type 2420 // list. 2421 types.InsertUnique(matching_type->shared_from_this()); 2422 } 2423 return true; 2424 }); 2425 2426 // Next search through the reachable Clang modules. This only applies for 2427 // DWARF objects compiled with -gmodules that haven't been processed by 2428 // dsymutil. 2429 UpdateExternalModuleListIfNeeded(); 2430 2431 for (const auto &pair : m_external_type_modules) 2432 if (ModuleSP external_module_sp = pair.second) 2433 external_module_sp->FindTypes(pattern, languages, searched_symbol_files, 2434 types); 2435 } 2436 2437 CompilerDeclContext 2438 SymbolFileDWARF::FindNamespace(ConstString name, 2439 const CompilerDeclContext &parent_decl_ctx) { 2440 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2441 Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS)); 2442 2443 if (log) { 2444 GetObjectFile()->GetModule()->LogMessage( 2445 log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")", 2446 name.GetCString()); 2447 } 2448 2449 CompilerDeclContext namespace_decl_ctx; 2450 2451 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx)) 2452 return namespace_decl_ctx; 2453 2454 m_index->GetNamespaces(name, [&](DWARFDIE die) { 2455 if (!DIEInDeclContext(parent_decl_ctx, die)) 2456 return true; // The containing decl contexts don't match 2457 2458 DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()); 2459 if (!dwarf_ast) 2460 return true; 2461 2462 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die); 2463 return !namespace_decl_ctx.IsValid(); 2464 }); 2465 2466 if (log && namespace_decl_ctx) { 2467 GetObjectFile()->GetModule()->LogMessage( 2468 log, 2469 "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => " 2470 "CompilerDeclContext(%p/%p) \"%s\"", 2471 name.GetCString(), 2472 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()), 2473 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()), 2474 namespace_decl_ctx.GetName().AsCString("<NULL>")); 2475 } 2476 2477 return namespace_decl_ctx; 2478 } 2479 2480 TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die, 2481 bool resolve_function_context) { 2482 TypeSP type_sp; 2483 if (die) { 2484 Type *type_ptr = GetDIEToType().lookup(die.GetDIE()); 2485 if (type_ptr == nullptr) { 2486 SymbolContextScope *scope; 2487 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU())) 2488 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu); 2489 else 2490 scope = GetObjectFile()->GetModule().get(); 2491 assert(scope); 2492 SymbolContext sc(scope); 2493 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE(); 2494 while (parent_die != nullptr) { 2495 if (parent_die->Tag() == DW_TAG_subprogram) 2496 break; 2497 parent_die = parent_die->GetParent(); 2498 } 2499 SymbolContext sc_backup = sc; 2500 if (resolve_function_context && parent_die != nullptr && 2501 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc)) 2502 sc = sc_backup; 2503 2504 type_sp = ParseType(sc, die, nullptr); 2505 } else if (type_ptr != DIE_IS_BEING_PARSED) { 2506 // Grab the existing type from the master types lists 2507 type_sp = type_ptr->shared_from_this(); 2508 } 2509 } 2510 return type_sp; 2511 } 2512 2513 DWARFDIE 2514 SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) { 2515 if (orig_die) { 2516 DWARFDIE die = orig_die; 2517 2518 while (die) { 2519 // If this is the original DIE that we are searching for a declaration 2520 // for, then don't look in the cache as we don't want our own decl 2521 // context to be our decl context... 2522 if (orig_die != die) { 2523 switch (die.Tag()) { 2524 case DW_TAG_compile_unit: 2525 case DW_TAG_partial_unit: 2526 case DW_TAG_namespace: 2527 case DW_TAG_structure_type: 2528 case DW_TAG_union_type: 2529 case DW_TAG_class_type: 2530 case DW_TAG_lexical_block: 2531 case DW_TAG_subprogram: 2532 return die; 2533 case DW_TAG_inlined_subroutine: { 2534 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); 2535 if (abs_die) { 2536 return abs_die; 2537 } 2538 break; 2539 } 2540 default: 2541 break; 2542 } 2543 } 2544 2545 DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification); 2546 if (spec_die) { 2547 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die); 2548 if (decl_ctx_die) 2549 return decl_ctx_die; 2550 } 2551 2552 DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin); 2553 if (abs_die) { 2554 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die); 2555 if (decl_ctx_die) 2556 return decl_ctx_die; 2557 } 2558 2559 die = die.GetParent(); 2560 } 2561 } 2562 return DWARFDIE(); 2563 } 2564 2565 Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) { 2566 Symbol *objc_class_symbol = nullptr; 2567 if (m_objfile_sp) { 2568 Symtab *symtab = m_objfile_sp->GetSymtab(); 2569 if (symtab) { 2570 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType( 2571 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo, 2572 Symtab::eVisibilityAny); 2573 } 2574 } 2575 return objc_class_symbol; 2576 } 2577 2578 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If 2579 // they don't then we can end up looking through all class types for a complete 2580 // type and never find the full definition. We need to know if this attribute 2581 // is supported, so we determine this here and cache th result. We also need to 2582 // worry about the debug map 2583 // DWARF file 2584 // if we are doing darwin DWARF in .o file debugging. 2585 bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) { 2586 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) { 2587 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo; 2588 if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type()) 2589 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; 2590 else { 2591 DWARFDebugInfo &debug_info = DebugInfo(); 2592 const uint32_t num_compile_units = GetNumCompileUnits(); 2593 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) { 2594 DWARFUnit *dwarf_cu = debug_info.GetUnitAtIndex(cu_idx); 2595 if (dwarf_cu != cu && 2596 dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) { 2597 m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes; 2598 break; 2599 } 2600 } 2601 } 2602 if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && 2603 GetDebugMapSymfile()) 2604 return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this); 2605 } 2606 return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes; 2607 } 2608 2609 // This function can be used when a DIE is found that is a forward declaration 2610 // DIE and we want to try and find a type that has the complete definition. 2611 TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE( 2612 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) { 2613 2614 TypeSP type_sp; 2615 2616 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name))) 2617 return type_sp; 2618 2619 m_index->GetCompleteObjCClass( 2620 type_name, must_be_implementation, [&](DWARFDIE type_die) { 2621 bool try_resolving_type = false; 2622 2623 // Don't try and resolve the DIE we are looking for with the DIE 2624 // itself! 2625 if (type_die != die) { 2626 switch (type_die.Tag()) { 2627 case DW_TAG_class_type: 2628 case DW_TAG_structure_type: 2629 try_resolving_type = true; 2630 break; 2631 default: 2632 break; 2633 } 2634 } 2635 if (!try_resolving_type) 2636 return true; 2637 2638 if (must_be_implementation && 2639 type_die.Supports_DW_AT_APPLE_objc_complete_type()) 2640 try_resolving_type = type_die.GetAttributeValueAsUnsigned( 2641 DW_AT_APPLE_objc_complete_type, 0); 2642 if (!try_resolving_type) 2643 return true; 2644 2645 Type *resolved_type = ResolveType(type_die, false, true); 2646 if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED) 2647 return true; 2648 2649 DEBUG_PRINTF( 2650 "resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 2651 " (cu 0x%8.8" PRIx64 ")\n", 2652 die.GetID(), 2653 m_objfile_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"), 2654 type_die.GetID(), type_cu->GetID()); 2655 2656 if (die) 2657 GetDIEToType()[die.GetDIE()] = resolved_type; 2658 type_sp = resolved_type->shared_from_this(); 2659 return false; 2660 }); 2661 return type_sp; 2662 } 2663 2664 // This function helps to ensure that the declaration contexts match for two 2665 // different DIEs. Often times debug information will refer to a forward 2666 // declaration of a type (the equivalent of "struct my_struct;". There will 2667 // often be a declaration of that type elsewhere that has the full definition. 2668 // When we go looking for the full type "my_struct", we will find one or more 2669 // matches in the accelerator tables and we will then need to make sure the 2670 // type was in the same declaration context as the original DIE. This function 2671 // can efficiently compare two DIEs and will return true when the declaration 2672 // context matches, and false when they don't. 2673 bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1, 2674 const DWARFDIE &die2) { 2675 if (die1 == die2) 2676 return true; 2677 2678 std::vector<DWARFDIE> decl_ctx_1; 2679 std::vector<DWARFDIE> decl_ctx_2; 2680 // The declaration DIE stack is a stack of the declaration context DIEs all 2681 // the way back to the compile unit. If a type "T" is declared inside a class 2682 // "B", and class "B" is declared inside a class "A" and class "A" is in a 2683 // namespace "lldb", and the namespace is in a compile unit, there will be a 2684 // stack of DIEs: 2685 // 2686 // [0] DW_TAG_class_type for "B" 2687 // [1] DW_TAG_class_type for "A" 2688 // [2] DW_TAG_namespace for "lldb" 2689 // [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file. 2690 // 2691 // We grab both contexts and make sure that everything matches all the way 2692 // back to the compiler unit. 2693 2694 // First lets grab the decl contexts for both DIEs 2695 decl_ctx_1 = die1.GetDeclContextDIEs(); 2696 decl_ctx_2 = die2.GetDeclContextDIEs(); 2697 // Make sure the context arrays have the same size, otherwise we are done 2698 const size_t count1 = decl_ctx_1.size(); 2699 const size_t count2 = decl_ctx_2.size(); 2700 if (count1 != count2) 2701 return false; 2702 2703 // Make sure the DW_TAG values match all the way back up the compile unit. If 2704 // they don't, then we are done. 2705 DWARFDIE decl_ctx_die1; 2706 DWARFDIE decl_ctx_die2; 2707 size_t i; 2708 for (i = 0; i < count1; i++) { 2709 decl_ctx_die1 = decl_ctx_1[i]; 2710 decl_ctx_die2 = decl_ctx_2[i]; 2711 if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag()) 2712 return false; 2713 } 2714 #ifndef NDEBUG 2715 2716 // Make sure the top item in the decl context die array is always 2717 // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then 2718 // something went wrong in the DWARFDIE::GetDeclContextDIEs() 2719 // function. 2720 dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag(); 2721 UNUSED_IF_ASSERT_DISABLED(cu_tag); 2722 assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit); 2723 2724 #endif 2725 // Always skip the compile unit when comparing by only iterating up to "count 2726 // - 1". Here we compare the names as we go. 2727 for (i = 0; i < count1 - 1; i++) { 2728 decl_ctx_die1 = decl_ctx_1[i]; 2729 decl_ctx_die2 = decl_ctx_2[i]; 2730 const char *name1 = decl_ctx_die1.GetName(); 2731 const char *name2 = decl_ctx_die2.GetName(); 2732 // If the string was from a DW_FORM_strp, then the pointer will often be 2733 // the same! 2734 if (name1 == name2) 2735 continue; 2736 2737 // Name pointers are not equal, so only compare the strings if both are not 2738 // NULL. 2739 if (name1 && name2) { 2740 // If the strings don't compare, we are done... 2741 if (strcmp(name1, name2) != 0) 2742 return false; 2743 } else { 2744 // One name was NULL while the other wasn't 2745 return false; 2746 } 2747 } 2748 // We made it through all of the checks and the declaration contexts are 2749 // equal. 2750 return true; 2751 } 2752 2753 TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext( 2754 const DWARFDeclContext &dwarf_decl_ctx) { 2755 TypeSP type_sp; 2756 2757 const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize(); 2758 if (dwarf_decl_ctx_count > 0) { 2759 const ConstString type_name(dwarf_decl_ctx[0].name); 2760 const dw_tag_t tag = dwarf_decl_ctx[0].tag; 2761 2762 if (type_name) { 2763 Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION | 2764 DWARF_LOG_LOOKUPS)); 2765 if (log) { 2766 GetObjectFile()->GetModule()->LogMessage( 2767 log, 2768 "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%" 2769 "s, qualified-name='%s')", 2770 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 2771 dwarf_decl_ctx.GetQualifiedName()); 2772 } 2773 2774 // Get the type system that we are looking to find a type for. We will 2775 // use this to ensure any matches we find are in a language that this 2776 // type system supports 2777 const LanguageType language = dwarf_decl_ctx.GetLanguage(); 2778 TypeSystem *type_system = nullptr; 2779 if (language != eLanguageTypeUnknown) { 2780 auto type_system_or_err = GetTypeSystemForLanguage(language); 2781 if (auto err = type_system_or_err.takeError()) { 2782 LLDB_LOG_ERROR( 2783 lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 2784 std::move(err), "Cannot get TypeSystem for language {}", 2785 Language::GetNameForLanguageType(language)); 2786 } else { 2787 type_system = &type_system_or_err.get(); 2788 } 2789 } 2790 2791 m_index->GetTypes(dwarf_decl_ctx, [&](DWARFDIE type_die) { 2792 // Make sure type_die's langauge matches the type system we are 2793 // looking for. We don't want to find a "Foo" type from Java if we 2794 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++. 2795 if (type_system && 2796 !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU()))) 2797 return true; 2798 bool try_resolving_type = false; 2799 2800 // Don't try and resolve the DIE we are looking for with the DIE 2801 // itself! 2802 const dw_tag_t type_tag = type_die.Tag(); 2803 // Make sure the tags match 2804 if (type_tag == tag) { 2805 // The tags match, lets try resolving this type 2806 try_resolving_type = true; 2807 } else { 2808 // The tags don't match, but we need to watch our for a forward 2809 // declaration for a struct and ("struct foo") ends up being a 2810 // class ("class foo { ... };") or vice versa. 2811 switch (type_tag) { 2812 case DW_TAG_class_type: 2813 // We had a "class foo", see if we ended up with a "struct foo 2814 // { ... };" 2815 try_resolving_type = (tag == DW_TAG_structure_type); 2816 break; 2817 case DW_TAG_structure_type: 2818 // We had a "struct foo", see if we ended up with a "class foo 2819 // { ... };" 2820 try_resolving_type = (tag == DW_TAG_class_type); 2821 break; 2822 default: 2823 // Tags don't match, don't event try to resolve using this type 2824 // whose name matches.... 2825 break; 2826 } 2827 } 2828 2829 if (!try_resolving_type) { 2830 if (log) { 2831 std::string qualified_name; 2832 type_die.GetQualifiedName(qualified_name); 2833 GetObjectFile()->GetModule()->LogMessage( 2834 log, 2835 "SymbolFileDWARF::" 2836 "FindDefinitionTypeForDWARFDeclContext(tag=%s, " 2837 "qualified-name='%s') ignoring die=0x%8.8x (%s)", 2838 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 2839 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), 2840 qualified_name.c_str()); 2841 } 2842 return true; 2843 } 2844 2845 DWARFDeclContext type_dwarf_decl_ctx = GetDWARFDeclContext(type_die); 2846 2847 if (log) { 2848 GetObjectFile()->GetModule()->LogMessage( 2849 log, 2850 "SymbolFileDWARF::" 2851 "FindDefinitionTypeForDWARFDeclContext(tag=%s, " 2852 "qualified-name='%s') trying die=0x%8.8x (%s)", 2853 DW_TAG_value_to_name(dwarf_decl_ctx[0].tag), 2854 dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(), 2855 type_dwarf_decl_ctx.GetQualifiedName()); 2856 } 2857 2858 // Make sure the decl contexts match all the way up 2859 if (dwarf_decl_ctx != type_dwarf_decl_ctx) 2860 return true; 2861 2862 Type *resolved_type = ResolveType(type_die, false); 2863 if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED) 2864 return true; 2865 2866 type_sp = resolved_type->shared_from_this(); 2867 return false; 2868 }); 2869 } 2870 } 2871 return type_sp; 2872 } 2873 2874 TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die, 2875 bool *type_is_new_ptr) { 2876 if (!die) 2877 return {}; 2878 2879 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU())); 2880 if (auto err = type_system_or_err.takeError()) { 2881 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 2882 std::move(err), "Unable to parse type"); 2883 return {}; 2884 } 2885 2886 DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser(); 2887 if (!dwarf_ast) 2888 return {}; 2889 2890 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr); 2891 if (type_sp) { 2892 GetTypeList().Insert(type_sp); 2893 2894 if (die.Tag() == DW_TAG_subprogram) { 2895 std::string scope_qualified_name(GetDeclContextForUID(die.GetID()) 2896 .GetScopeQualifiedName() 2897 .AsCString("")); 2898 if (scope_qualified_name.size()) { 2899 m_function_scope_qualified_name_map[scope_qualified_name].insert( 2900 *die.GetDIERef()); 2901 } 2902 } 2903 } 2904 2905 return type_sp; 2906 } 2907 2908 size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc, 2909 const DWARFDIE &orig_die, 2910 bool parse_siblings, bool parse_children) { 2911 size_t types_added = 0; 2912 DWARFDIE die = orig_die; 2913 2914 while (die) { 2915 const dw_tag_t tag = die.Tag(); 2916 bool type_is_new = false; 2917 2918 Tag dwarf_tag = static_cast<Tag>(tag); 2919 2920 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...) 2921 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or 2922 // not. 2923 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type) 2924 ParseType(sc, die, &type_is_new); 2925 2926 if (type_is_new) 2927 ++types_added; 2928 2929 if (parse_children && die.HasChildren()) { 2930 if (die.Tag() == DW_TAG_subprogram) { 2931 SymbolContext child_sc(sc); 2932 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get(); 2933 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true); 2934 } else 2935 types_added += ParseTypes(sc, die.GetFirstChild(), true, true); 2936 } 2937 2938 if (parse_siblings) 2939 die = die.GetSibling(); 2940 else 2941 die.Clear(); 2942 } 2943 return types_added; 2944 } 2945 2946 size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) { 2947 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2948 CompileUnit *comp_unit = func.GetCompileUnit(); 2949 lldbassert(comp_unit); 2950 2951 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit); 2952 if (!dwarf_cu) 2953 return 0; 2954 2955 size_t functions_added = 0; 2956 const dw_offset_t function_die_offset = func.GetID(); 2957 DWARFDIE function_die = 2958 dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset); 2959 if (function_die) { 2960 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die, 2961 LLDB_INVALID_ADDRESS, 0); 2962 } 2963 2964 return functions_added; 2965 } 2966 2967 size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) { 2968 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2969 size_t types_added = 0; 2970 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit); 2971 if (dwarf_cu) { 2972 DWARFDIE dwarf_cu_die = dwarf_cu->DIE(); 2973 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) { 2974 SymbolContext sc; 2975 sc.comp_unit = &comp_unit; 2976 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true); 2977 } 2978 } 2979 2980 return types_added; 2981 } 2982 2983 size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) { 2984 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex()); 2985 if (sc.comp_unit != nullptr) { 2986 if (sc.function) { 2987 DWARFDIE function_die = GetDIE(sc.function->GetID()); 2988 2989 dw_addr_t func_lo_pc = LLDB_INVALID_ADDRESS; 2990 DWARFRangeList ranges; 2991 if (function_die.GetDIE()->GetAttributeAddressRanges( 2992 function_die.GetCU(), ranges, 2993 /*check_hi_lo_pc=*/true)) 2994 func_lo_pc = ranges.GetMinRangeBase(0); 2995 if (func_lo_pc != LLDB_INVALID_ADDRESS) { 2996 const size_t num_variables = ParseVariables( 2997 sc, function_die.GetFirstChild(), func_lo_pc, true, true); 2998 2999 // Let all blocks know they have parse all their variables 3000 sc.function->GetBlock(false).SetDidParseVariables(true, true); 3001 return num_variables; 3002 } 3003 } else if (sc.comp_unit) { 3004 DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(sc.comp_unit->GetID()); 3005 3006 if (dwarf_cu == nullptr) 3007 return 0; 3008 3009 uint32_t vars_added = 0; 3010 VariableListSP variables(sc.comp_unit->GetVariableList(false)); 3011 3012 if (variables.get() == nullptr) { 3013 variables = std::make_shared<VariableList>(); 3014 sc.comp_unit->SetVariableList(variables); 3015 3016 m_index->GetGlobalVariables( 3017 dwarf_cu->GetNonSkeletonUnit(), [&](DWARFDIE die) { 3018 VariableSP var_sp( 3019 ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS)); 3020 if (var_sp) { 3021 variables->AddVariableIfUnique(var_sp); 3022 ++vars_added; 3023 } 3024 return true; 3025 }); 3026 } 3027 return vars_added; 3028 } 3029 } 3030 return 0; 3031 } 3032 3033 VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc, 3034 const DWARFDIE &die, 3035 const lldb::addr_t func_low_pc) { 3036 if (die.GetDWARF() != this) 3037 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc); 3038 3039 if (!die) 3040 return nullptr; 3041 3042 if (VariableSP var_sp = GetDIEToVariable()[die.GetDIE()]) 3043 return var_sp; // Already been parsed! 3044 3045 const dw_tag_t tag = die.Tag(); 3046 ModuleSP module = GetObjectFile()->GetModule(); 3047 3048 if (tag != DW_TAG_variable && tag != DW_TAG_constant && 3049 (tag != DW_TAG_formal_parameter || !sc.function)) 3050 return nullptr; 3051 3052 DWARFAttributes attributes; 3053 const size_t num_attributes = die.GetAttributes(attributes); 3054 DWARFDIE spec_die; 3055 VariableSP var_sp; 3056 const char *name = nullptr; 3057 const char *mangled = nullptr; 3058 Declaration decl; 3059 DWARFFormValue type_die_form; 3060 DWARFExpression location; 3061 bool is_external = false; 3062 bool is_artificial = false; 3063 DWARFFormValue const_value_form, location_form; 3064 Variable::RangeList scope_ranges; 3065 3066 for (size_t i = 0; i < num_attributes; ++i) { 3067 dw_attr_t attr = attributes.AttributeAtIndex(i); 3068 DWARFFormValue form_value; 3069 3070 if (!attributes.ExtractFormValueAtIndex(i, form_value)) 3071 continue; 3072 switch (attr) { 3073 case DW_AT_decl_file: 3074 decl.SetFile( 3075 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned())); 3076 break; 3077 case DW_AT_decl_line: 3078 decl.SetLine(form_value.Unsigned()); 3079 break; 3080 case DW_AT_decl_column: 3081 decl.SetColumn(form_value.Unsigned()); 3082 break; 3083 case DW_AT_name: 3084 name = form_value.AsCString(); 3085 break; 3086 case DW_AT_linkage_name: 3087 case DW_AT_MIPS_linkage_name: 3088 mangled = form_value.AsCString(); 3089 break; 3090 case DW_AT_type: 3091 type_die_form = form_value; 3092 break; 3093 case DW_AT_external: 3094 is_external = form_value.Boolean(); 3095 break; 3096 case DW_AT_const_value: 3097 const_value_form = form_value; 3098 break; 3099 case DW_AT_location: 3100 location_form = form_value; 3101 break; 3102 case DW_AT_specification: 3103 spec_die = form_value.Reference(); 3104 break; 3105 case DW_AT_start_scope: 3106 // TODO: Implement this. 3107 break; 3108 case DW_AT_artificial: 3109 is_artificial = form_value.Boolean(); 3110 break; 3111 case DW_AT_declaration: 3112 case DW_AT_description: 3113 case DW_AT_endianity: 3114 case DW_AT_segment: 3115 case DW_AT_visibility: 3116 default: 3117 case DW_AT_abstract_origin: 3118 case DW_AT_sibling: 3119 break; 3120 } 3121 } 3122 3123 // Prefer DW_AT_location over DW_AT_const_value. Both can be emitted e.g. 3124 // for static constexpr member variables -- DW_AT_const_value will be 3125 // present in the class declaration and DW_AT_location in the DIE defining 3126 // the member. 3127 bool location_is_const_value_data = false; 3128 bool has_explicit_location = false; 3129 bool use_type_size_for_value = false; 3130 if (location_form.IsValid()) { 3131 has_explicit_location = true; 3132 if (DWARFFormValue::IsBlockForm(location_form.Form())) { 3133 const DWARFDataExtractor &data = die.GetData(); 3134 3135 uint32_t block_offset = location_form.BlockData() - data.GetDataStart(); 3136 uint32_t block_length = location_form.Unsigned(); 3137 location = DWARFExpression( 3138 module, DataExtractor(data, block_offset, block_length), die.GetCU()); 3139 } else { 3140 DataExtractor data = die.GetCU()->GetLocationData(); 3141 dw_offset_t offset = location_form.Unsigned(); 3142 if (location_form.Form() == DW_FORM_loclistx) 3143 offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1); 3144 if (data.ValidOffset(offset)) { 3145 data = DataExtractor(data, offset, data.GetByteSize() - offset); 3146 location = DWARFExpression(module, data, die.GetCU()); 3147 assert(func_low_pc != LLDB_INVALID_ADDRESS); 3148 location.SetLocationListAddresses( 3149 location_form.GetUnit()->GetBaseAddress(), func_low_pc); 3150 } 3151 } 3152 } else if (const_value_form.IsValid()) { 3153 location_is_const_value_data = true; 3154 // The constant value will be either a block, a data value or a 3155 // string. 3156 const DWARFDataExtractor &debug_info_data = die.GetData(); 3157 if (DWARFFormValue::IsBlockForm(const_value_form.Form())) { 3158 // Retrieve the value as a block expression. 3159 uint32_t block_offset = 3160 const_value_form.BlockData() - debug_info_data.GetDataStart(); 3161 uint32_t block_length = const_value_form.Unsigned(); 3162 location = DWARFExpression( 3163 module, DataExtractor(debug_info_data, block_offset, block_length), 3164 die.GetCU()); 3165 } else if (DWARFFormValue::IsDataForm(const_value_form.Form())) { 3166 // Constant value size does not have to match the size of the 3167 // variable. We will fetch the size of the type after we create 3168 // it. 3169 use_type_size_for_value = true; 3170 } else if (const char *str = const_value_form.AsCString()) { 3171 uint32_t string_length = strlen(str) + 1; 3172 location = DWARFExpression( 3173 module, 3174 DataExtractor(str, string_length, die.GetCU()->GetByteOrder(), 3175 die.GetCU()->GetAddressByteSize()), 3176 die.GetCU()); 3177 } 3178 } 3179 3180 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die); 3181 const dw_tag_t parent_tag = die.GetParent().Tag(); 3182 bool is_static_member = (parent_tag == DW_TAG_compile_unit || 3183 parent_tag == DW_TAG_partial_unit) && 3184 (parent_context_die.Tag() == DW_TAG_class_type || 3185 parent_context_die.Tag() == DW_TAG_structure_type); 3186 3187 ValueType scope = eValueTypeInvalid; 3188 3189 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die); 3190 SymbolContextScope *symbol_context_scope = nullptr; 3191 3192 bool has_explicit_mangled = mangled != nullptr; 3193 if (!mangled) { 3194 // LLDB relies on the mangled name (DW_TAG_linkage_name or 3195 // DW_AT_MIPS_linkage_name) to generate fully qualified names 3196 // of global variables with commands like "frame var j". For 3197 // example, if j were an int variable holding a value 4 and 3198 // declared in a namespace B which in turn is contained in a 3199 // namespace A, the command "frame var j" returns 3200 // "(int) A::B::j = 4". 3201 // If the compiler does not emit a linkage name, we should be 3202 // able to generate a fully qualified name from the 3203 // declaration context. 3204 if ((parent_tag == DW_TAG_compile_unit || 3205 parent_tag == DW_TAG_partial_unit) && 3206 Language::LanguageIsCPlusPlus(GetLanguage(*die.GetCU()))) 3207 mangled = 3208 GetDWARFDeclContext(die).GetQualifiedNameAsConstString().GetCString(); 3209 } 3210 3211 if (tag == DW_TAG_formal_parameter) 3212 scope = eValueTypeVariableArgument; 3213 else { 3214 // DWARF doesn't specify if a DW_TAG_variable is a local, global 3215 // or static variable, so we have to do a little digging: 3216 // 1) DW_AT_linkage_name implies static lifetime (but may be missing) 3217 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var. 3218 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime. 3219 // Clang likes to combine small global variables into the same symbol 3220 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus 3221 // so we need to look through the whole expression. 3222 bool is_static_lifetime = 3223 has_explicit_mangled || (has_explicit_location && !location.IsValid()); 3224 // Check if the location has a DW_OP_addr with any address value... 3225 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS; 3226 if (!location_is_const_value_data) { 3227 bool op_error = false; 3228 location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error); 3229 if (op_error) { 3230 StreamString strm; 3231 location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0, 3232 nullptr); 3233 GetObjectFile()->GetModule()->ReportError( 3234 "0x%8.8x: %s has an invalid location: %s", die.GetOffset(), 3235 die.GetTagAsCString(), strm.GetData()); 3236 } 3237 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS) 3238 is_static_lifetime = true; 3239 } 3240 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile(); 3241 if (debug_map_symfile) 3242 // Set the module of the expression to the linked module 3243 // instead of the oject file so the relocated address can be 3244 // found there. 3245 location.SetModule(debug_map_symfile->GetObjectFile()->GetModule()); 3246 3247 if (is_static_lifetime) { 3248 if (is_external) 3249 scope = eValueTypeVariableGlobal; 3250 else 3251 scope = eValueTypeVariableStatic; 3252 3253 if (debug_map_symfile) { 3254 // When leaving the DWARF in the .o files on darwin, when we have a 3255 // global variable that wasn't initialized, the .o file might not 3256 // have allocated a virtual address for the global variable. In 3257 // this case it will have created a symbol for the global variable 3258 // that is undefined/data and external and the value will be the 3259 // byte size of the variable. When we do the address map in 3260 // SymbolFileDWARFDebugMap we rely on having an address, we need to 3261 // do some magic here so we can get the correct address for our 3262 // global variable. The address for all of these entries will be 3263 // zero, and there will be an undefined symbol in this object file, 3264 // and the executable will have a matching symbol with a good 3265 // address. So here we dig up the correct address and replace it in 3266 // the location for the variable, and set the variable's symbol 3267 // context scope to be that of the main executable so the file 3268 // address will resolve correctly. 3269 bool linked_oso_file_addr = false; 3270 if (is_external && location_DW_OP_addr == 0) { 3271 // we have a possible uninitialized extern global 3272 ConstString const_name(mangled ? mangled : name); 3273 ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile(); 3274 if (debug_map_objfile) { 3275 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab(); 3276 if (debug_map_symtab) { 3277 Symbol *exe_symbol = 3278 debug_map_symtab->FindFirstSymbolWithNameAndType( 3279 const_name, eSymbolTypeData, Symtab::eDebugYes, 3280 Symtab::eVisibilityExtern); 3281 if (exe_symbol) { 3282 if (exe_symbol->ValueIsAddress()) { 3283 const addr_t exe_file_addr = 3284 exe_symbol->GetAddressRef().GetFileAddress(); 3285 if (exe_file_addr != LLDB_INVALID_ADDRESS) { 3286 if (location.Update_DW_OP_addr(exe_file_addr)) { 3287 linked_oso_file_addr = true; 3288 symbol_context_scope = exe_symbol; 3289 } 3290 } 3291 } 3292 } 3293 } 3294 } 3295 } 3296 3297 if (!linked_oso_file_addr) { 3298 // The DW_OP_addr is not zero, but it contains a .o file address 3299 // which needs to be linked up correctly. 3300 const lldb::addr_t exe_file_addr = 3301 debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr); 3302 if (exe_file_addr != LLDB_INVALID_ADDRESS) { 3303 // Update the file address for this variable 3304 location.Update_DW_OP_addr(exe_file_addr); 3305 } else { 3306 // Variable didn't make it into the final executable 3307 return var_sp; 3308 } 3309 } 3310 } 3311 } else { 3312 if (location_is_const_value_data && 3313 die.GetDIE()->IsGlobalOrStaticScopeVariable()) 3314 scope = eValueTypeVariableStatic; 3315 else { 3316 scope = eValueTypeVariableLocal; 3317 if (debug_map_symfile) { 3318 // We need to check for TLS addresses that we need to fixup 3319 if (location.ContainsThreadLocalStorage()) { 3320 location.LinkThreadLocalStorage( 3321 debug_map_symfile->GetObjectFile()->GetModule(), 3322 [this, debug_map_symfile]( 3323 lldb::addr_t unlinked_file_addr) -> lldb::addr_t { 3324 return debug_map_symfile->LinkOSOFileAddress( 3325 this, unlinked_file_addr); 3326 }); 3327 scope = eValueTypeVariableThreadLocal; 3328 } 3329 } 3330 } 3331 } 3332 } 3333 3334 if (symbol_context_scope == nullptr) { 3335 switch (parent_tag) { 3336 case DW_TAG_subprogram: 3337 case DW_TAG_inlined_subroutine: 3338 case DW_TAG_lexical_block: 3339 if (sc.function) { 3340 symbol_context_scope = 3341 sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID()); 3342 if (symbol_context_scope == nullptr) 3343 symbol_context_scope = sc.function; 3344 } 3345 break; 3346 3347 default: 3348 symbol_context_scope = sc.comp_unit; 3349 break; 3350 } 3351 } 3352 3353 if (symbol_context_scope) { 3354 auto type_sp = std::make_shared<SymbolFileType>( 3355 *this, GetUID(type_die_form.Reference())); 3356 3357 if (use_type_size_for_value && type_sp->GetType()) 3358 location.UpdateValue( 3359 const_value_form.Unsigned(), 3360 type_sp->GetType()->GetByteSize(nullptr).getValueOr(0), 3361 die.GetCU()->GetAddressByteSize()); 3362 3363 var_sp = std::make_shared<Variable>( 3364 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope, 3365 scope_ranges, &decl, location, is_external, is_artificial, 3366 location_is_const_value_data, is_static_member); 3367 } else { 3368 // Not ready to parse this variable yet. It might be a global or static 3369 // variable that is in a function scope and the function in the symbol 3370 // context wasn't filled in yet 3371 return var_sp; 3372 } 3373 // Cache var_sp even if NULL (the variable was just a specification or was 3374 // missing vital information to be able to be displayed in the debugger 3375 // (missing location due to optimization, etc)) so we don't re-parse this 3376 // DIE over and over later... 3377 GetDIEToVariable()[die.GetDIE()] = var_sp; 3378 if (spec_die) 3379 GetDIEToVariable()[spec_die.GetDIE()] = var_sp; 3380 3381 return var_sp; 3382 } 3383 3384 DWARFDIE 3385 SymbolFileDWARF::FindBlockContainingSpecification( 3386 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) { 3387 // Give the concrete function die specified by "func_die_offset", find the 3388 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points 3389 // to "spec_block_die_offset" 3390 return FindBlockContainingSpecification(DebugInfo().GetDIE(func_die_ref), 3391 spec_block_die_offset); 3392 } 3393 3394 DWARFDIE 3395 SymbolFileDWARF::FindBlockContainingSpecification( 3396 const DWARFDIE &die, dw_offset_t spec_block_die_offset) { 3397 if (die) { 3398 switch (die.Tag()) { 3399 case DW_TAG_subprogram: 3400 case DW_TAG_inlined_subroutine: 3401 case DW_TAG_lexical_block: { 3402 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() == 3403 spec_block_die_offset) 3404 return die; 3405 3406 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() == 3407 spec_block_die_offset) 3408 return die; 3409 } break; 3410 default: 3411 break; 3412 } 3413 3414 // Give the concrete function die specified by "func_die_offset", find the 3415 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points 3416 // to "spec_block_die_offset" 3417 for (DWARFDIE child_die = die.GetFirstChild(); child_die; 3418 child_die = child_die.GetSibling()) { 3419 DWARFDIE result_die = 3420 FindBlockContainingSpecification(child_die, spec_block_die_offset); 3421 if (result_die) 3422 return result_die; 3423 } 3424 } 3425 3426 return DWARFDIE(); 3427 } 3428 3429 size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc, 3430 const DWARFDIE &orig_die, 3431 const lldb::addr_t func_low_pc, 3432 bool parse_siblings, bool parse_children, 3433 VariableList *cc_variable_list) { 3434 if (!orig_die) 3435 return 0; 3436 3437 VariableListSP variable_list_sp; 3438 3439 size_t vars_added = 0; 3440 DWARFDIE die = orig_die; 3441 while (die) { 3442 dw_tag_t tag = die.Tag(); 3443 3444 // Check to see if we have already parsed this variable or constant? 3445 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()]; 3446 if (var_sp) { 3447 if (cc_variable_list) 3448 cc_variable_list->AddVariableIfUnique(var_sp); 3449 } else { 3450 // We haven't already parsed it, lets do that now. 3451 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) || 3452 (tag == DW_TAG_formal_parameter && sc.function)) { 3453 if (variable_list_sp.get() == nullptr) { 3454 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die); 3455 dw_tag_t parent_tag = sc_parent_die.Tag(); 3456 switch (parent_tag) { 3457 case DW_TAG_compile_unit: 3458 case DW_TAG_partial_unit: 3459 if (sc.comp_unit != nullptr) { 3460 variable_list_sp = sc.comp_unit->GetVariableList(false); 3461 if (variable_list_sp.get() == nullptr) { 3462 variable_list_sp = std::make_shared<VariableList>(); 3463 } 3464 } else { 3465 GetObjectFile()->GetModule()->ReportError( 3466 "parent 0x%8.8" PRIx64 " %s with no valid compile unit in " 3467 "symbol context for 0x%8.8" PRIx64 " %s.\n", 3468 sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(), 3469 orig_die.GetID(), orig_die.GetTagAsCString()); 3470 } 3471 break; 3472 3473 case DW_TAG_subprogram: 3474 case DW_TAG_inlined_subroutine: 3475 case DW_TAG_lexical_block: 3476 if (sc.function != nullptr) { 3477 // Check to see if we already have parsed the variables for the 3478 // given scope 3479 3480 Block *block = sc.function->GetBlock(true).FindBlockByID( 3481 sc_parent_die.GetID()); 3482 if (block == nullptr) { 3483 // This must be a specification or abstract origin with a 3484 // concrete block counterpart in the current function. We need 3485 // to find the concrete block so we can correctly add the 3486 // variable to it 3487 const DWARFDIE concrete_block_die = 3488 FindBlockContainingSpecification( 3489 GetDIE(sc.function->GetID()), 3490 sc_parent_die.GetOffset()); 3491 if (concrete_block_die) 3492 block = sc.function->GetBlock(true).FindBlockByID( 3493 concrete_block_die.GetID()); 3494 } 3495 3496 if (block != nullptr) { 3497 const bool can_create = false; 3498 variable_list_sp = block->GetBlockVariableList(can_create); 3499 if (variable_list_sp.get() == nullptr) { 3500 variable_list_sp = std::make_shared<VariableList>(); 3501 block->SetVariableList(variable_list_sp); 3502 } 3503 } 3504 } 3505 break; 3506 3507 default: 3508 GetObjectFile()->GetModule()->ReportError( 3509 "didn't find appropriate parent DIE for variable list for " 3510 "0x%8.8" PRIx64 " %s.\n", 3511 orig_die.GetID(), orig_die.GetTagAsCString()); 3512 break; 3513 } 3514 } 3515 3516 if (variable_list_sp) { 3517 VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc)); 3518 if (var_sp) { 3519 variable_list_sp->AddVariableIfUnique(var_sp); 3520 if (cc_variable_list) 3521 cc_variable_list->AddVariableIfUnique(var_sp); 3522 ++vars_added; 3523 } 3524 } 3525 } 3526 } 3527 3528 bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram); 3529 3530 if (!skip_children && parse_children && die.HasChildren()) { 3531 vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, 3532 true, cc_variable_list); 3533 } 3534 3535 if (parse_siblings) 3536 die = die.GetSibling(); 3537 else 3538 die.Clear(); 3539 } 3540 return vars_added; 3541 } 3542 3543 /// Collect call site parameters in a DW_TAG_call_site DIE. 3544 static CallSiteParameterArray 3545 CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) { 3546 CallSiteParameterArray parameters; 3547 for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid(); 3548 child = child.GetSibling()) { 3549 if (child.Tag() != DW_TAG_call_site_parameter && 3550 child.Tag() != DW_TAG_GNU_call_site_parameter) 3551 continue; 3552 3553 llvm::Optional<DWARFExpression> LocationInCallee; 3554 llvm::Optional<DWARFExpression> LocationInCaller; 3555 3556 DWARFAttributes attributes; 3557 const size_t num_attributes = child.GetAttributes(attributes); 3558 3559 // Parse the location at index \p attr_index within this call site parameter 3560 // DIE, or return None on failure. 3561 auto parse_simple_location = 3562 [&](int attr_index) -> llvm::Optional<DWARFExpression> { 3563 DWARFFormValue form_value; 3564 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value)) 3565 return {}; 3566 if (!DWARFFormValue::IsBlockForm(form_value.Form())) 3567 return {}; 3568 auto data = child.GetData(); 3569 uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); 3570 uint32_t block_length = form_value.Unsigned(); 3571 return DWARFExpression(module, 3572 DataExtractor(data, block_offset, block_length), 3573 child.GetCU()); 3574 }; 3575 3576 for (size_t i = 0; i < num_attributes; ++i) { 3577 dw_attr_t attr = attributes.AttributeAtIndex(i); 3578 if (attr == DW_AT_location) 3579 LocationInCallee = parse_simple_location(i); 3580 if (attr == DW_AT_call_value || attr == DW_AT_GNU_call_site_value) 3581 LocationInCaller = parse_simple_location(i); 3582 } 3583 3584 if (LocationInCallee && LocationInCaller) { 3585 CallSiteParameter param = {*LocationInCallee, *LocationInCaller}; 3586 parameters.push_back(param); 3587 } 3588 } 3589 return parameters; 3590 } 3591 3592 /// Collect call graph edges present in a function DIE. 3593 std::vector<std::unique_ptr<lldb_private::CallEdge>> 3594 SymbolFileDWARF::CollectCallEdges(ModuleSP module, DWARFDIE function_die) { 3595 // Check if the function has a supported call site-related attribute. 3596 // TODO: In the future it may be worthwhile to support call_all_source_calls. 3597 bool has_call_edges = 3598 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0) || 3599 function_die.GetAttributeValueAsUnsigned(DW_AT_GNU_all_call_sites, 0); 3600 if (!has_call_edges) 3601 return {}; 3602 3603 Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP)); 3604 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}", 3605 function_die.GetPubname()); 3606 3607 // Scan the DIE for TAG_call_site entries. 3608 // TODO: A recursive scan of all blocks in the subprogram is needed in order 3609 // to be DWARF5-compliant. This may need to be done lazily to be performant. 3610 // For now, assume that all entries are nested directly under the subprogram 3611 // (this is the kind of DWARF LLVM produces) and parse them eagerly. 3612 std::vector<std::unique_ptr<CallEdge>> call_edges; 3613 for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid(); 3614 child = child.GetSibling()) { 3615 if (child.Tag() != DW_TAG_call_site && child.Tag() != DW_TAG_GNU_call_site) 3616 continue; 3617 3618 llvm::Optional<DWARFDIE> call_origin; 3619 llvm::Optional<DWARFExpression> call_target; 3620 addr_t return_pc = LLDB_INVALID_ADDRESS; 3621 addr_t call_inst_pc = LLDB_INVALID_ADDRESS; 3622 addr_t low_pc = LLDB_INVALID_ADDRESS; 3623 bool tail_call = false; 3624 3625 // Second DW_AT_low_pc may come from DW_TAG_subprogram referenced by 3626 // DW_TAG_GNU_call_site's DW_AT_abstract_origin overwriting our 'low_pc'. 3627 // So do not inherit attributes from DW_AT_abstract_origin. 3628 DWARFAttributes attributes; 3629 const size_t num_attributes = 3630 child.GetAttributes(attributes, DWARFDIE::Recurse::no); 3631 for (size_t i = 0; i < num_attributes; ++i) { 3632 DWARFFormValue form_value; 3633 if (!attributes.ExtractFormValueAtIndex(i, form_value)) { 3634 LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form"); 3635 break; 3636 } 3637 3638 dw_attr_t attr = attributes.AttributeAtIndex(i); 3639 3640 if (attr == DW_AT_call_tail_call || attr == DW_AT_GNU_tail_call) 3641 tail_call = form_value.Boolean(); 3642 3643 // Extract DW_AT_call_origin (the call target's DIE). 3644 if (attr == DW_AT_call_origin || attr == DW_AT_abstract_origin) { 3645 call_origin = form_value.Reference(); 3646 if (!call_origin->IsValid()) { 3647 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}", 3648 function_die.GetPubname()); 3649 break; 3650 } 3651 } 3652 3653 if (attr == DW_AT_low_pc) 3654 low_pc = form_value.Address(); 3655 3656 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's 3657 // available. It should only ever be unavailable for tail call edges, in 3658 // which case use LLDB_INVALID_ADDRESS. 3659 if (attr == DW_AT_call_return_pc) 3660 return_pc = form_value.Address(); 3661 3662 // Extract DW_AT_call_pc (the PC at the call/branch instruction). It 3663 // should only ever be unavailable for non-tail calls, in which case use 3664 // LLDB_INVALID_ADDRESS. 3665 if (attr == DW_AT_call_pc) 3666 call_inst_pc = form_value.Address(); 3667 3668 // Extract DW_AT_call_target (the location of the address of the indirect 3669 // call). 3670 if (attr == DW_AT_call_target || attr == DW_AT_GNU_call_site_target) { 3671 if (!DWARFFormValue::IsBlockForm(form_value.Form())) { 3672 LLDB_LOG(log, 3673 "CollectCallEdges: AT_call_target does not have block form"); 3674 break; 3675 } 3676 3677 auto data = child.GetData(); 3678 uint32_t block_offset = form_value.BlockData() - data.GetDataStart(); 3679 uint32_t block_length = form_value.Unsigned(); 3680 call_target = DWARFExpression( 3681 module, DataExtractor(data, block_offset, block_length), 3682 child.GetCU()); 3683 } 3684 } 3685 if (!call_origin && !call_target) { 3686 LLDB_LOG(log, "CollectCallEdges: call site without any call target"); 3687 continue; 3688 } 3689 3690 addr_t caller_address; 3691 CallEdge::AddrType caller_address_type; 3692 if (return_pc != LLDB_INVALID_ADDRESS) { 3693 caller_address = return_pc; 3694 caller_address_type = CallEdge::AddrType::AfterCall; 3695 } else if (low_pc != LLDB_INVALID_ADDRESS) { 3696 caller_address = low_pc; 3697 caller_address_type = CallEdge::AddrType::AfterCall; 3698 } else if (call_inst_pc != LLDB_INVALID_ADDRESS) { 3699 caller_address = call_inst_pc; 3700 caller_address_type = CallEdge::AddrType::Call; 3701 } else { 3702 LLDB_LOG(log, "CollectCallEdges: No caller address"); 3703 continue; 3704 } 3705 // Adjust any PC forms. It needs to be fixed up if the main executable 3706 // contains a debug map (i.e. pointers to object files), because we need a 3707 // file address relative to the executable's text section. 3708 caller_address = FixupAddress(caller_address); 3709 3710 // Extract call site parameters. 3711 CallSiteParameterArray parameters = 3712 CollectCallSiteParameters(module, child); 3713 3714 std::unique_ptr<CallEdge> edge; 3715 if (call_origin) { 3716 LLDB_LOG(log, 3717 "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x}) " 3718 "(call-PC: {2:x})", 3719 call_origin->GetPubname(), return_pc, call_inst_pc); 3720 edge = std::make_unique<DirectCallEdge>( 3721 call_origin->GetMangledName(), caller_address_type, caller_address, 3722 tail_call, std::move(parameters)); 3723 } else { 3724 if (log) { 3725 StreamString call_target_desc; 3726 call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief, 3727 LLDB_INVALID_ADDRESS, nullptr); 3728 LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}", 3729 call_target_desc.GetString()); 3730 } 3731 edge = std::make_unique<IndirectCallEdge>( 3732 *call_target, caller_address_type, caller_address, tail_call, 3733 std::move(parameters)); 3734 } 3735 3736 if (log && parameters.size()) { 3737 for (const CallSiteParameter ¶m : parameters) { 3738 StreamString callee_loc_desc, caller_loc_desc; 3739 param.LocationInCallee.GetDescription(&callee_loc_desc, 3740 eDescriptionLevelBrief, 3741 LLDB_INVALID_ADDRESS, nullptr); 3742 param.LocationInCaller.GetDescription(&caller_loc_desc, 3743 eDescriptionLevelBrief, 3744 LLDB_INVALID_ADDRESS, nullptr); 3745 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}", 3746 callee_loc_desc.GetString(), caller_loc_desc.GetString()); 3747 } 3748 } 3749 3750 call_edges.push_back(std::move(edge)); 3751 } 3752 return call_edges; 3753 } 3754 3755 std::vector<std::unique_ptr<lldb_private::CallEdge>> 3756 SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) { 3757 // ParseCallEdgesInFunction must be called at the behest of an exclusively 3758 // locked lldb::Function instance. Storage for parsed call edges is owned by 3759 // the lldb::Function instance: locking at the SymbolFile level would be too 3760 // late, because the act of storing results from ParseCallEdgesInFunction 3761 // would be racy. 3762 DWARFDIE func_die = GetDIE(func_id.GetID()); 3763 if (func_die.IsValid()) 3764 return CollectCallEdges(GetObjectFile()->GetModule(), func_die); 3765 return {}; 3766 } 3767 3768 // PluginInterface protocol 3769 ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); } 3770 3771 uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; } 3772 3773 void SymbolFileDWARF::Dump(lldb_private::Stream &s) { 3774 SymbolFile::Dump(s); 3775 m_index->Dump(s); 3776 } 3777 3778 void SymbolFileDWARF::DumpClangAST(Stream &s) { 3779 auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus); 3780 if (!ts_or_err) 3781 return; 3782 TypeSystemClang *clang = 3783 llvm::dyn_cast_or_null<TypeSystemClang>(&ts_or_err.get()); 3784 if (!clang) 3785 return; 3786 clang->Dump(s); 3787 } 3788 3789 SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() { 3790 if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) { 3791 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock()); 3792 if (module_sp) { 3793 m_debug_map_symfile = 3794 static_cast<SymbolFileDWARFDebugMap *>(module_sp->GetSymbolFile()); 3795 } 3796 } 3797 return m_debug_map_symfile; 3798 } 3799 3800 const std::shared_ptr<SymbolFileDWARFDwo> &SymbolFileDWARF::GetDwpSymbolFile() { 3801 llvm::call_once(m_dwp_symfile_once_flag, [this]() { 3802 ModuleSpec module_spec; 3803 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec(); 3804 module_spec.GetSymbolFileSpec() = 3805 FileSpec(m_objfile_sp->GetModule()->GetFileSpec().GetPath() + ".dwp"); 3806 3807 FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths(); 3808 FileSpec dwp_filespec = 3809 Symbols::LocateExecutableSymbolFile(module_spec, search_paths); 3810 if (FileSystem::Instance().Exists(dwp_filespec)) { 3811 DataBufferSP dwp_file_data_sp; 3812 lldb::offset_t dwp_file_data_offset = 0; 3813 ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin( 3814 GetObjectFile()->GetModule(), &dwp_filespec, 0, 3815 FileSystem::Instance().GetByteSize(dwp_filespec), dwp_file_data_sp, 3816 dwp_file_data_offset); 3817 if (!dwp_obj_file) 3818 return; 3819 m_dwp_symfile = 3820 std::make_shared<SymbolFileDWARFDwo>(*this, dwp_obj_file, 0x3fffffff); 3821 } 3822 }); 3823 return m_dwp_symfile; 3824 } 3825 3826 llvm::Expected<TypeSystem &> SymbolFileDWARF::GetTypeSystem(DWARFUnit &unit) { 3827 return unit.GetSymbolFileDWARF().GetTypeSystemForLanguage(GetLanguage(unit)); 3828 } 3829 3830 DWARFASTParser *SymbolFileDWARF::GetDWARFParser(DWARFUnit &unit) { 3831 auto type_system_or_err = GetTypeSystem(unit); 3832 if (auto err = type_system_or_err.takeError()) { 3833 LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS), 3834 std::move(err), "Unable to get DWARFASTParser"); 3835 return nullptr; 3836 } 3837 return type_system_or_err->GetDWARFParser(); 3838 } 3839 3840 CompilerDecl SymbolFileDWARF::GetDecl(const DWARFDIE &die) { 3841 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) 3842 return dwarf_ast->GetDeclForUIDFromDWARF(die); 3843 return CompilerDecl(); 3844 } 3845 3846 CompilerDeclContext SymbolFileDWARF::GetDeclContext(const DWARFDIE &die) { 3847 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) 3848 return dwarf_ast->GetDeclContextForUIDFromDWARF(die); 3849 return CompilerDeclContext(); 3850 } 3851 3852 CompilerDeclContext 3853 SymbolFileDWARF::GetContainingDeclContext(const DWARFDIE &die) { 3854 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) 3855 return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die); 3856 return CompilerDeclContext(); 3857 } 3858 3859 DWARFDeclContext SymbolFileDWARF::GetDWARFDeclContext(const DWARFDIE &die) { 3860 if (!die.IsValid()) 3861 return {}; 3862 DWARFDeclContext dwarf_decl_ctx = 3863 die.GetDIE()->GetDWARFDeclContext(die.GetCU()); 3864 dwarf_decl_ctx.SetLanguage(GetLanguage(*die.GetCU())); 3865 return dwarf_decl_ctx; 3866 } 3867 3868 LanguageType SymbolFileDWARF::LanguageTypeFromDWARF(uint64_t val) { 3869 // Note: user languages between lo_user and hi_user must be handled 3870 // explicitly here. 3871 switch (val) { 3872 case DW_LANG_Mips_Assembler: 3873 return eLanguageTypeMipsAssembler; 3874 case DW_LANG_GOOGLE_RenderScript: 3875 return eLanguageTypeExtRenderScript; 3876 default: 3877 return static_cast<LanguageType>(val); 3878 } 3879 } 3880 3881 LanguageType SymbolFileDWARF::GetLanguage(DWARFUnit &unit) { 3882 return LanguageTypeFromDWARF(unit.GetDWARFLanguageType()); 3883 } 3884