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