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