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