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