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