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