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