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