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