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