LLDB mainline
SymbolFileDWARF.cpp
Go to the documentation of this file.
1//===-- SymbolFileDWARF.cpp -----------------------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#include "SymbolFileDWARF.h"
10#include "clang/Basic/ABI.h"
11#include "llvm/ADT/STLExtras.h"
12#include "llvm/ADT/SmallPtrSet.h"
13#include "llvm/ADT/StringExtras.h"
14#include "llvm/ADT/StringRef.h"
15#include "llvm/DebugInfo/DWARF/DWARFAddressRange.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
17#include "llvm/Support/Casting.h"
18#include "llvm/Support/Error.h"
19#include "llvm/Support/ErrorExtras.h"
20#include "llvm/Support/FileUtilities.h"
21#include "llvm/Support/FormatAdapters.h"
22#include "llvm/Support/Threading.h"
23
24#include "lldb/Core/Module.h"
28#include "lldb/Core/Progress.h"
29#include "lldb/Core/Section.h"
30#include "lldb/Core/Value.h"
35#include "lldb/Utility/Scalar.h"
38#include "lldb/Utility/Timer.h"
39
42
43#include "lldb/Host/Config.h"
45#include "lldb/Host/Host.h"
46
49
54#include "lldb/Symbol/Block.h"
62#include "lldb/Symbol/TypeMap.h"
65
67#include "lldb/Target/Target.h"
68
69#include "AppleDWARFIndex.h"
70#include "DWARFASTParser.h"
71#include "DWARFASTParserClang.h"
72#include "DWARFCompileUnit.h"
73#include "DWARFDebugAranges.h"
74#include "DWARFDebugInfo.h"
75#include "DWARFDebugMacro.h"
76#include "DWARFDeclContext.h"
77#include "DWARFFormValue.h"
78#include "DWARFTypeUnit.h"
79#include "DWARFUnit.h"
81#include "LogChannelDWARF.h"
82#include "ManualDWARFIndex.h"
84#include "SymbolFileDWARFDwo.h"
86
87#include "llvm/DebugInfo/DWARF/DWARFContext.h"
88#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
89#include "llvm/Demangle/Demangle.h"
90#include "llvm/Support/FileSystem.h"
91#include "llvm/Support/FormatVariadic.h"
92
93#include <algorithm>
94#include <map>
95#include <memory>
96#include <optional>
97
98#include <cctype>
99#include <cstring>
100
101//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
102
103#ifdef ENABLE_DEBUG_PRINTF
104#include <cstdio>
105#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
106#else
107#define DEBUG_PRINTF(fmt, ...)
108#endif
109
110using namespace lldb;
111using namespace lldb_private;
112using namespace lldb_private::plugin::dwarf;
113using namespace llvm::dwarf;
114
116
118
119namespace {
120
121#define LLDB_PROPERTIES_symbolfiledwarf
122#include "SymbolFileDWARFProperties.inc"
123
124enum {
125#define LLDB_PROPERTIES_symbolfiledwarf
126#include "SymbolFileDWARFPropertiesEnum.inc"
127};
128
129class PluginProperties : public Properties {
130public:
131 static llvm::StringRef GetSettingName() {
133 }
134
135 PluginProperties() {
136 m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
137 m_collection_sp->Initialize(g_symbolfiledwarf_properties_def);
138 }
139
140 bool IgnoreFileIndexes() const {
141 return GetPropertyAtIndexAs<bool>(ePropertyIgnoreIndexes, false);
142 }
143};
144
145} // namespace
146
147bool IsStructOrClassTag(llvm::dwarf::Tag Tag) {
148 return Tag == llvm::dwarf::Tag::DW_TAG_class_type ||
149 Tag == llvm::dwarf::Tag::DW_TAG_structure_type;
150}
151
152static PluginProperties &GetGlobalPluginProperties() {
153 static PluginProperties g_settings;
154 return g_settings;
155}
156
157static const llvm::DWARFDebugLine::LineTable *
158ParseLLVMLineTable(DWARFContext &context, llvm::DWARFDebugLine &line,
159 dw_offset_t line_offset, dw_offset_t unit_offset) {
161
162 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
163 llvm::DWARFContext &ctx = context.GetAsLLVM();
164 llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
165 line.getOrParseLineTable(
166 data, line_offset, ctx, nullptr, [&](llvm::Error e) {
168 log, std::move(e),
169 "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
170 });
171
172 if (!line_table) {
173 LLDB_LOG_ERROR(log, line_table.takeError(),
174 "SymbolFileDWARF::ParseLineTable failed to parse: {0}");
175 return nullptr;
176 }
177 return *line_table;
178}
179
181 llvm::DWARFDebugLine::Prologue &prologue,
182 dw_offset_t line_offset,
183 dw_offset_t unit_offset) {
185 bool success = true;
186 llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVMDWARF();
187 llvm::DWARFContext &ctx = context.GetAsLLVM();
188 uint64_t offset = line_offset;
189 llvm::Error error = prologue.parse(
190 data, &offset,
191 [&](llvm::Error e) {
192 success = false;
193 LLDB_LOG_ERROR(log, std::move(e),
194 "SymbolFileDWARF::ParseSupportFiles failed to parse "
195 "line table prologue: {0}");
196 },
197 ctx, nullptr);
198 if (error) {
199 LLDB_LOG_ERROR(log, std::move(error),
200 "SymbolFileDWARF::ParseSupportFiles failed to parse line "
201 "table prologue: {0}");
202 return false;
203 }
204 return success;
205}
206
207static std::optional<std::string>
208GetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
209 llvm::StringRef compile_dir, FileSpec::Style style) {
210 // Try to get an absolute path first.
211 std::string abs_path;
212 auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
213 if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
214 return std::move(abs_path);
215
216 // Otherwise ask for a relative path.
217 std::string rel_path;
218 auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::RawValue;
219 if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
220 return {};
221 return std::move(rel_path);
222}
223
225 SupportFileList &support_files, const lldb::ModuleSP &module,
226 const llvm::DWARFDebugLine::Prologue &prologue, FileSpec::Style style,
227 llvm::StringRef compile_dir = {}) {
228 // Handle the case where there are no files first to avoid having to special
229 // case this later.
230 if (prologue.FileNames.empty())
231 return;
232
233 // Before DWARF v5, the line table indexes were one based.
234 const bool is_one_based = prologue.getVersion() < 5;
235 const size_t file_names = prologue.FileNames.size();
236 const size_t first_file_idx = is_one_based ? 1 : 0;
237 const size_t last_file_idx = is_one_based ? file_names : file_names - 1;
238
239 // Add a dummy entry to ensure the support file list indices match those we
240 // get from the debug info and line tables.
241 if (is_one_based)
242 support_files.Append(FileSpec());
243
244 for (size_t idx = first_file_idx; idx <= last_file_idx; ++idx) {
245 std::string remapped_file;
246 if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style)) {
247 auto entry = prologue.getFileNameEntry(idx);
248 auto source = entry.Source.getAsCString();
249 if (!source)
250 consumeError(source.takeError());
251 else {
252 llvm::StringRef source_ref(*source);
253 if (!source_ref.empty()) {
254 /// Wrap a path for an in-DWARF source file. Lazily write it
255 /// to disk when Materialize() is called.
256 struct LazyDWARFSourceFile : public SupportFile {
257 LazyDWARFSourceFile(const FileSpec &fs, llvm::StringRef source,
258 FileSpec::Style style)
259 : SupportFile(fs), source(source), style(style) {}
260 FileSpec tmp_file;
261 /// The file contents buffer.
262 llvm::StringRef source;
263 /// Deletes the temporary file at the end.
264 std::unique_ptr<llvm::FileRemover> remover;
265 FileSpec::Style style;
266
267 /// Write the file contents to a temporary file.
268 const FileSpec &Materialize() override {
269 if (tmp_file)
270 return tmp_file;
271 llvm::SmallString<0> name;
272 int fd;
273 auto orig_name = m_file_spec.GetFilename();
274 auto ec = llvm::sys::fs::createTemporaryFile(
275 "", llvm::sys::path::filename(orig_name, style), fd, name);
276 if (ec || fd <= 0) {
277 LLDB_LOG(GetLog(DWARFLog::DebugInfo),
278 "Could not create temporary file");
279 return tmp_file;
280 }
281 remover = std::make_unique<llvm::FileRemover>(name);
283 size_t num_bytes = source.size();
284 file.Write(source.data(), num_bytes);
285 tmp_file.SetPath(name);
286 return tmp_file;
287 }
288 };
289 support_files.Append(std::make_unique<LazyDWARFSourceFile>(
290 FileSpec(*file_path), *source, style));
291 continue;
292 }
293 }
294 if (auto remapped = module->RemapSourceFile(llvm::StringRef(*file_path)))
295 remapped_file = *remapped;
296 else
297 remapped_file = std::move(*file_path);
298 }
299
300 Checksum checksum;
301 if (prologue.ContentTypes.HasMD5) {
302 const llvm::DWARFDebugLine::FileNameEntry &file_name_entry =
303 prologue.getFileNameEntry(idx);
304 checksum = file_name_entry.Checksum;
305 }
306
307 // Unconditionally add an entry, so the indices match up.
308 support_files.EmplaceBack(FileSpec(remapped_file, style), checksum);
309 }
310}
311
315
318 llvm::Expected<llvm::DWARFDebugLine::LineTable> line_table)
319 : line_table(std::move(line_table)) {}
320
321 llvm::Expected<llvm::DWARFDebugLine::LineTable> line_table;
322 };
323
324 // Keep one entry per .debug_line contribution so compile unit indices remain
325 // stable when a contribution cannot be parsed.
326 std::vector<LineTableEntry> line_tables;
327 llvm::once_flag aranges_once_flag;
329
330 bool HasLineTables();
331 uint32_t CalculateNumCompileUnits() const;
332 CompUnitSP ParseCompileUnitAtIndex(uint32_t cu_idx);
333 bool ParseLineTable(CompileUnit &comp_unit);
334 uint32_t ResolveSymbolContext(const Address &so_addr,
335 SymbolContextItem resolve_scope,
336 SymbolContext &sc);
337
338 const llvm::DWARFDebugLine::LineTable *GetLineTable(uint32_t cu_idx);
339 const llvm::DWARFDebugLine::Prologue *GetPrologue(uint32_t cu_idx);
340
341 const DWARFDebugAranges &GetAranges(lldb::addr_t first_code_address);
342
343private:
345};
346
347static std::unique_ptr<LineTable>
349 const llvm::DWARFDebugLine::LineTable &line_table,
350 lldb::addr_t first_code_address) {
351 std::vector<LineTable::Sequence> sequences;
352 // The Sequences view contains only valid line sequences. Don't iterate over
353 // the Rows directly.
354 for (const llvm::DWARFDebugLine::Sequence &seq : line_table.Sequences) {
355 // Ignore line sequences that start before the first code address.
356 // Addresses within a sequence are monotonically increasing, so checking
357 // LowPC is sufficient.
358 if (seq.LowPC < first_code_address)
359 continue;
360 LineTable::Sequence sequence;
361 for (unsigned idx = seq.FirstRowIndex; idx < seq.LastRowIndex; ++idx) {
362 const llvm::DWARFDebugLine::Row &row = line_table.Rows[idx];
364 sequence, row.Address.Address, row.Line, row.Column, row.File,
365 row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
366 row.EndSequence);
367 }
368 sequences.push_back(std::move(sequence));
369 }
370
371 return std::make_unique<LineTable>(&comp_unit, std::move(sequences));
372}
373
375 SymbolFileDWARF &symfile)
376 : m_symfile(symfile) {
377 llvm::DWARFDataExtractor line_data =
378 m_symfile.m_context.getOrLoadLineData().GetAsLLVMDWARF();
379 if (line_data.getData().empty())
380 return;
381
382 llvm::DWARFContext &context = m_symfile.m_context.GetAsLLVM();
383 llvm::DWARFDebugLine::SectionParser parser(line_data, context,
384 context.normal_units());
386 auto recoverable = [&](llvm::Error error) {
387 LLDB_LOG_ERROR(log, std::move(error),
388 "SymbolFileDWARF failed to parse standalone line "
389 "table: {0}");
390 };
391 auto append_error = [&](llvm::Error error) {
392 LLDB_LOG(log, "SymbolFileDWARF failed to parse standalone line table: {0}",
393 llvm::toStringWithoutConsuming(error));
394 line_tables.emplace_back(
395 llvm::Expected<llvm::DWARFDebugLine::LineTable>(std::move(error)));
396 };
397
398 while (!parser.done()) {
399 llvm::Error parse_error = llvm::Error::success();
400 auto unrecoverable = [&](llvm::Error error) {
401 parse_error = llvm::joinErrors(std::move(parse_error), std::move(error));
402 };
403 llvm::DWARFDebugLine::LineTable line_table =
404 parser.parseNext(recoverable, unrecoverable);
405
406 if (parse_error) {
407 append_error(std::move(parse_error));
409 line_table.Prologue.getVersion())) {
410 append_error(llvm::createStringError(
411 llvm::inconvertibleErrorCode(),
412 "unsupported standalone line table version %u",
413 line_table.Prologue.getVersion()));
414 } else if (line_table.Prologue.FileNames.empty()) {
415 append_error(
416 llvm::createStringError(llvm::inconvertibleErrorCode(),
417 "standalone line table has no files"));
418 } else {
419 line_tables.emplace_back(llvm::Expected<llvm::DWARFDebugLine::LineTable>(
420 std::move(line_table)));
421 }
422 }
423}
424
426 for (LineTableEntry &entry : line_tables)
427 llvm::consumeError(entry.line_table.takeError());
428}
429
431 return llvm::any_of(line_tables, [](LineTableEntry &entry) {
432 return static_cast<bool>(entry.line_table);
433 });
434}
435
436const llvm::DWARFDebugLine::Prologue *
438 if (cu_idx >= line_tables.size())
439 return nullptr;
440 LineTableEntry &entry = line_tables[cu_idx];
441 return entry.line_table ? &entry.line_table->Prologue : nullptr;
442}
443
444const llvm::DWARFDebugLine::LineTable *
446 if (cu_idx >= line_tables.size())
447 return nullptr;
448 LineTableEntry &entry = line_tables[cu_idx];
449 return entry.line_table ? &*entry.line_table : nullptr;
450}
451
452const DWARFDebugAranges &
454 llvm::call_once(aranges_once_flag, [&] {
455 for (uint32_t cu_idx = 0; cu_idx < line_tables.size(); ++cu_idx) {
456 const llvm::DWARFDebugLine::LineTable *line_table = GetLineTable(cu_idx);
457 if (!line_table)
458 continue;
459 for (const llvm::DWARFDebugLine::Sequence &seq : line_table->Sequences) {
460 if (seq.isValid() && seq.LowPC >= first_code_address)
461 aranges.AppendRange(cu_idx, seq.LowPC, seq.HighPC);
462 }
463 }
464 aranges.Sort(/*minimize=*/true);
465 });
466 return aranges;
467}
468
472
475 const llvm::DWARFDebugLine::Prologue *prologue = GetPrologue(cu_idx);
476 if (!prologue)
477 return {};
478
479 SupportFileList support_files;
481 support_files, m_symfile.m_objfile_sp->GetModule(), *prologue,
482 m_symfile.m_objfile_sp->GetFileSpec().GetPathStyle());
483
484 // DWARF v5 guarantees that file index zero names the primary source file.
485 // Earlier versions are one-based and have no explicit primary-file field;
486 // use the first file in the table as the best available fallback.
487 const size_t primary_file_idx = prologue->getVersion() < 5 ? 1 : 0;
488 SupportFileNSP primary_file =
489 support_files.GetSupportFileAtIndex(primary_file_idx);
490
491 ModuleSP module_sp = m_symfile.m_objfile_sp->GetModule();
492 if (!module_sp)
493 return {};
494 CompUnitSP cu_sp = std::make_shared<CompileUnit>(
495 module_sp, /*user_data=*/nullptr, primary_file, cu_idx,
496 eLanguageTypeUnknown, eLazyBoolNo, std::move(support_files));
497 m_symfile.SetCompileUnitAtIndex(cu_idx, cu_sp);
498 return cu_sp;
499}
500
502 const llvm::DWARFDebugLine::LineTable *line_table =
503 GetLineTable(comp_unit.GetID());
504 if (!line_table)
505 return false;
506 if (m_symfile.m_first_code_address == LLDB_INVALID_ADDRESS)
507 m_symfile.InitializeFirstCodeAddress();
508 comp_unit.SetLineTable(
509 ConvertLineTable(comp_unit, *line_table, m_symfile.m_first_code_address)
510 .release());
511 return true;
512}
513
515 const Address &so_addr, SymbolContextItem resolve_scope,
516 SymbolContext &sc) {
517 if (m_symfile.m_first_code_address == LLDB_INVALID_ADDRESS)
518 m_symfile.InitializeFirstCodeAddress();
519 const DWARFDebugAranges &aranges = GetAranges(m_symfile.m_first_code_address);
520 const dw_offset_t cu_idx = aranges.FindAddress(so_addr.GetFileAddress());
521 if (cu_idx == DW_INVALID_OFFSET)
522 return 0;
523
524 CompUnitSP cu_sp = m_symfile.GetCompileUnitAtIndex(cu_idx);
525 sc.comp_unit = cu_sp.get();
526 if (!sc.comp_unit)
527 return 0;
528 uint32_t resolved = eSymbolContextCompUnit;
529
530 if (resolve_scope & eSymbolContextLineEntry) {
531 if (LineTable *line_table = sc.comp_unit->GetLineTable()) {
532 Address exe_so_addr(so_addr);
533 if (m_symfile.FixupAddress(exe_so_addr) &&
534 line_table->FindLineEntryByAddress(exe_so_addr, sc.line_entry))
535 resolved |= eSymbolContextLineEntry;
536 }
537 }
538 return resolved;
539}
540
548
551 debugger, PluginProperties::GetSettingName())) {
552 const bool is_global_setting = true;
554 debugger, GetGlobalPluginProperties().GetValueProperties(),
555 "Properties for the dwarf symbol-file plug-in.", is_global_setting);
556 }
557}
558
564
566 return "DWARF and DWARF3 debug symbol file reader.";
567}
568
570 return LLDB_DWO_DIAGNOSTIC_SUFFIX;
571}
572
574 if (objfile_sp->GetArchitecture().GetTriple().isWasm())
575 return new SymbolFileWasm(std::move(objfile_sp),
576 /*dwo_section_list*/ nullptr);
577 return new SymbolFileDWARF(std::move(objfile_sp),
578 /*dwo_section_list*/ nullptr);
579}
580
582 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
583 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
584 return debug_map_symfile->GetTypeList();
586}
587void SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
588 dw_offset_t max_die_offset, uint32_t type_mask,
589 TypeSet &type_set) {
590 if (die) {
591 const dw_offset_t die_offset = die.GetOffset();
592
593 if (die_offset >= max_die_offset)
594 return;
595
596 if (die_offset >= min_die_offset) {
597 const dw_tag_t tag = die.Tag();
598
599 bool add_type = false;
600
601 switch (tag) {
602 case DW_TAG_array_type:
603 add_type = (type_mask & eTypeClassArray) != 0;
604 break;
605 case DW_TAG_unspecified_type:
606 case DW_TAG_base_type:
607 add_type = (type_mask & eTypeClassBuiltin) != 0;
608 break;
609 case DW_TAG_class_type:
610 add_type = (type_mask & eTypeClassClass) != 0;
611 break;
612 case DW_TAG_structure_type:
613 add_type = (type_mask & eTypeClassStruct) != 0;
614 break;
615 case DW_TAG_union_type:
616 add_type = (type_mask & eTypeClassUnion) != 0;
617 break;
618 case DW_TAG_enumeration_type:
619 add_type = (type_mask & eTypeClassEnumeration) != 0;
620 break;
621 case DW_TAG_subroutine_type:
622 case DW_TAG_subprogram:
623 case DW_TAG_inlined_subroutine:
624 add_type = (type_mask & eTypeClassFunction) != 0;
625 break;
626 case DW_TAG_pointer_type:
627 add_type = (type_mask & eTypeClassPointer) != 0;
628 break;
629 case DW_TAG_rvalue_reference_type:
630 case DW_TAG_reference_type:
631 add_type = (type_mask & eTypeClassReference) != 0;
632 break;
633 case DW_TAG_typedef:
634 add_type = (type_mask & eTypeClassTypedef) != 0;
635 break;
636 case DW_TAG_ptr_to_member_type:
637 add_type = (type_mask & eTypeClassMemberPointer) != 0;
638 break;
639 default:
640 break;
641 }
642
643 if (add_type) {
644 const bool assert_not_being_parsed = true;
645 Type *type = ResolveTypeUID(die, assert_not_being_parsed);
646 if (type)
647 type_set.insert(type);
648 }
649 }
650
651 for (DWARFDIE child_die : die.children()) {
652 GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
653 }
654 }
655}
656
658 TypeClass type_mask, TypeList &type_list)
659
660{
661 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
662 TypeSet type_set;
663
664 CompileUnit *comp_unit = nullptr;
665 if (sc_scope)
666 comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
667
668 const auto &get = [&](DWARFUnit *unit) {
669 if (!unit)
670 return;
671 unit = &unit->GetNonSkeletonUnit();
672 GetTypes(unit->DIE(), unit->GetOffset(), unit->GetNextUnitOffset(),
673 type_mask, type_set);
674 };
675 if (comp_unit) {
676 get(GetDWARFCompileUnit(comp_unit));
677 } else {
678 DWARFDebugInfo &info = DebugInfo();
679 const size_t num_cus = info.GetNumUnits();
680 for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx)
681 get(info.GetUnitAtIndex(cu_idx));
682 }
683
684 std::set<CompilerType> compiler_type_set;
685 for (Type *type : type_set) {
686 CompilerType compiler_type = type->GetForwardCompilerType();
687 if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
688 compiler_type_set.insert(compiler_type);
689 type_list.Insert(type->shared_from_this());
690 }
691 }
692}
693
694// Gets the first parent that is a lexical block, function or inlined
695// subroutine, or compile unit.
698 DWARFDIE die;
699 for (die = child_die.GetParent(); die; die = die.GetParent()) {
700 dw_tag_t tag = die.Tag();
701
702 switch (tag) {
703 case DW_TAG_compile_unit:
704 case DW_TAG_partial_unit:
705 case DW_TAG_subprogram:
706 case DW_TAG_inlined_subroutine:
707 case DW_TAG_lexical_block:
708 return die;
709 default:
710 break;
711 }
712 }
713 return DWARFDIE();
714}
715
717 SectionList *dwo_section_list)
718 : SymbolFileCommon(std::move(objfile_sp)), m_debug_map_module_wp(),
719 m_debug_map_symfile(nullptr),
720 m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
722
724
726 static ConstString g_dwarf_section_name("__DWARF");
727 return g_dwarf_section_name;
728}
729
730llvm::DenseMap<const DWARFDebugInfoEntry *, Type *> &
732 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
733 return debug_map_symfile->GetDIEToType();
734 return m_die_to_type;
735}
736
737llvm::DenseMap<lldb::opaque_compiler_type_t, DIERef> &
739 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
740 return debug_map_symfile->GetForwardDeclCompilerTypeToDIE();
742}
743
745 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
746 if (debug_map_symfile)
747 return debug_map_symfile->GetUniqueDWARFASTTypeMap();
748 else
750}
751
752llvm::Expected<lldb::TypeSystemSP>
754 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
755 return debug_map_symfile->GetTypeSystemForLanguage(language);
756
758}
759
762
764
765 if (!GetGlobalPluginProperties().IgnoreFileIndexes()) {
766 StreamString module_desc;
767 GetObjectFile()->GetModule()->GetDescription(module_desc.AsRawOstream(),
769 DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
774
775 if (apple_names.GetByteSize() > 0 || apple_namespaces.GetByteSize() > 0 ||
776 apple_types.GetByteSize() > 0 || apple_objc.GetByteSize() > 0) {
778 *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
779 apple_types, apple_objc, m_context.getOrLoadStrData());
780
781 if (m_index)
782 return;
783 }
784
785 DWARFDataExtractor debug_names;
787 if (debug_names.GetByteSize() > 0) {
788 Progress progress("Loading DWARF5 index", module_desc.GetData());
789 llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
791 debug_names,
792 m_context.getOrLoadStrData(), *this);
793 if (index_or) {
794 m_index = std::move(*index_or);
795 return;
796 }
797 LLDB_LOG_ERROR(log, index_or.takeError(),
798 "Unable to read .debug_names data: {0}");
799 }
800 }
801
802 m_index =
803 std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(), *this);
804}
805
812
814 const lldb_private::SectionList &section_list) {
815 for (SectionSP section_sp : section_list) {
816 if (section_sp->GetChildren().GetSize() > 0) {
817 InitializeFirstCodeAddressRecursive(section_sp->GetChildren());
818 } else if (section_sp->GetType() == eSectionTypeCode) {
820 std::min(m_first_code_address, section_sp->GetFileAddress());
821 }
822 }
823}
824
825bool SymbolFileDWARF::SupportedVersion(uint16_t version) {
826 return version >= 2 && version <= 5;
827}
828
829static std::set<dw_form_t>
830GetUnsupportedForms(llvm::DWARFDebugAbbrev *debug_abbrev) {
831 if (!debug_abbrev)
832 return {};
833
834 std::set<dw_form_t> unsupported_forms;
835 for (const auto &[_, decl_set] : *debug_abbrev)
836 for (const auto &decl : decl_set)
837 for (const auto &attr : decl.attributes())
838 if (!DWARFFormValue::FormIsSupported(attr.Form))
839 unsupported_forms.insert(attr.Form);
840
841 return unsupported_forms;
842}
843
845 uint32_t abilities = 0;
846 if (m_objfile_sp != nullptr) {
847 const Section *section = nullptr;
848 const SectionList *section_list = m_objfile_sp->GetSectionList();
849 if (section_list == nullptr)
850 return 0;
851
852 uint64_t debug_abbrev_file_size = 0;
853 uint64_t debug_info_file_size = 0;
854 uint64_t debug_line_file_size = 0;
855
856 section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
857
858 if (section)
859 section_list = &section->GetChildren();
860
861 section =
862 section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
863 if (section != nullptr) {
864 debug_info_file_size = section->GetFileSize();
865
866 section =
868 .get();
869 if (section)
870 debug_abbrev_file_size = section->GetFileSize();
871
872 llvm::DWARFDebugAbbrev *abbrev = DebugAbbrev();
873 std::set<dw_form_t> unsupported_forms = GetUnsupportedForms(abbrev);
874 if (!unsupported_forms.empty()) {
876 error.Printf("unsupported DW_FORM value%s:",
877 unsupported_forms.size() > 1 ? "s" : "");
878 for (auto form : unsupported_forms)
879 error.Printf(" %#x", form);
880 m_objfile_sp->GetModule()->ReportWarning("{0}", error.GetString());
881 return 0;
882 }
883
884 } else {
885 llvm::StringRef symfile_dir = m_objfile_sp->GetFileSpec().GetDirectory();
886 if (symfile_dir.contains_insensitive(".dsym")) {
887 if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
888 // We have a dSYM file that didn't have a any debug info. If the
889 // string table has a size of 1, then it was made from an
890 // executable with no debug info, or from an executable that was
891 // stripped.
892 section =
894 .get();
895 if (section && section->GetFileSize() == 1) {
896 m_objfile_sp->GetModule()->ReportWarning(
897 "empty dSYM file detected, dSYM was created with an "
898 "executable with no debug info");
899 }
900 }
901 }
902 }
903
904 // .debug_line may exist without .debug_info, so detect it independently.
905 section =
906 section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true).get();
907 if (section)
908 debug_line_file_size = section->GetFileSize();
909
910 constexpr uint64_t MaxDebugInfoSize = (1ull) << DW_DIE_OFFSET_MAX_BITSIZE;
911 if (debug_info_file_size >= MaxDebugInfoSize) {
912 m_objfile_sp->GetModule()->ReportWarning(
913 "SymbolFileDWARF can't load this DWARF. It's larger then {0:x+16}",
914 MaxDebugInfoSize);
915 return 0;
916 }
917
918 if (debug_abbrev_file_size > 0 && debug_info_file_size > 0) {
919 abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
921
922 if (debug_line_file_size > 0)
923 abilities |= LineTables;
924 } else if (debug_line_file_size > 0) {
926 if (info && info->HasLineTables()) {
927 // A standalone line table still supplies enough information to create
928 // compile units, even though there are no DIEs backing them.
929 abilities |= CompileUnits | LineTables;
930 }
931 }
932 }
933 return abilities;
934}
935
937 DWARFDataExtractor &data) {
938 ModuleSP module_sp(m_objfile_sp->GetModule());
939 const SectionList *section_list = module_sp->GetSectionList();
940 if (!section_list)
941 return;
942
943 SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
944 if (!section_sp)
945 return;
946
947 data.Clear();
948 m_objfile_sp->ReadSectionData(section_sp.get(), data);
949}
950
951llvm::DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
952 if (m_abbr)
953 return m_abbr.get();
954
955 const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
956 if (debug_abbrev_data.GetByteSize() == 0)
957 return nullptr;
958
960 auto abbr =
961 std::make_unique<llvm::DWARFDebugAbbrev>(debug_abbrev_data.GetAsLLVM());
962 llvm::Error error = abbr->parse();
963 if (error) {
965 LLDB_LOG_ERROR(log, std::move(error),
966 "Unable to read .debug_abbrev section: {0}");
967 return nullptr;
968 }
969
970 m_abbr = std::move(abbr);
971 return m_abbr.get();
972}
973
975 llvm::call_once(m_info_once_flag, [&] {
977
978 m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
979 });
980 return *m_info;
981}
982
984 return m_context.getOrLoadDebugInfoData().GetByteSize() == 0;
985}
986
988 llvm::call_once(m_standalone_line_table_once_flag, [&] {
989 if (!MissingDebugInfo())
990 return;
991
992 auto info = std::make_unique<StandaloneDWARFLineTableInfo>(*this);
993 if (info->HasLineTables())
994 m_standalone_line_table_info = std::move(info);
995 });
996 // This returns a valid pointer only if there is .debug_line with no
997 // .debug_info.
998 return m_standalone_line_table_info.get();
999}
1000
1002 if (!comp_unit)
1003 return nullptr;
1004 // If we have no debug info then there are no DWARF compile units. This is
1005 // expected when we only have .debug_line and no .debug_info.
1006 if (MissingDebugInfo())
1007 return nullptr;
1008
1009 // The compile unit ID is the index of the DWARF unit.
1010 DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(comp_unit->GetID());
1011 if (dwarf_cu && dwarf_cu->GetLLDBCompUnit() == nullptr)
1012 dwarf_cu->SetLLDBCompUnit(comp_unit);
1013
1014 // It must be DWARFCompileUnit when it created a CompileUnit.
1015 return llvm::cast_or_null<DWARFCompileUnit>(dwarf_cu);
1016}
1017
1018/// Make an absolute path out of \p file_spec and remap it using the
1019/// module's source remapping dictionary.
1020static void MakeAbsoluteAndRemap(FileSpec &file_spec, DWARFUnit &dwarf_cu,
1021 const ModuleSP &module_sp) {
1022 if (!file_spec)
1023 return;
1024 // If we have a full path to the compile unit, we don't need to
1025 // resolve the file. This can be expensive e.g. when the source
1026 // files are NFS mounted.
1027 file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
1028
1029 if (auto remapped_file = module_sp->RemapSourceFile(file_spec.GetPath()))
1030 file_spec.SetFile(*remapped_file, FileSpec::Style::native);
1031}
1032
1033/// Return the DW_AT_(GNU_)dwo_name.
1034static const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
1035 const DWARFDebugInfoEntry &cu_die) {
1036 const char *dwo_name =
1037 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1038 if (!dwo_name)
1039 dwo_name =
1040 cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
1041 return dwo_name;
1042}
1043
1045 CompUnitSP cu_sp;
1046 CompileUnit *comp_unit = dwarf_cu.GetLLDBCompUnit();
1047 if (comp_unit) {
1048 // We already parsed this compile unit, had out a shared pointer to it
1049 cu_sp = comp_unit->shared_from_this();
1050 } else {
1051 if (GetDebugMapSymfile()) {
1052 // Let the debug map create the compile unit
1053 cu_sp = m_debug_map_symfile->GetCompileUnit(this, dwarf_cu);
1054 dwarf_cu.SetLLDBCompUnit(cu_sp.get());
1055 } else {
1056 ModuleSP module_sp(m_objfile_sp->GetModule());
1057 if (module_sp) {
1058 auto initialize_cu = [&](SupportFileNSP support_file_nsp,
1059 LanguageType cu_language,
1060 SupportFileList &&support_files = {}) {
1062 cu_sp = std::make_shared<CompileUnit>(
1063 module_sp, &dwarf_cu, support_file_nsp,
1064 *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
1065 eLazyBoolCalculate, std::move(support_files));
1066
1067 dwarf_cu.SetLLDBCompUnit(cu_sp.get());
1068
1069 SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
1070 };
1071
1072 auto lazy_initialize_cu = [&]() {
1073 // If the version is < 5, we can't do lazy initialization.
1074 if (dwarf_cu.GetVersion() < 5)
1075 return false;
1076
1077 // If there is no DWO, there is no reason to initialize
1078 // lazily; we will do eager initialization in that case.
1079 if (GetDebugMapSymfile())
1080 return false;
1081 const DWARFBaseDIE cu_die = dwarf_cu.GetUnitDIEOnly();
1082 if (!cu_die)
1083 return false;
1084 if (!GetDWOName(dwarf_cu, *cu_die.GetDIE()))
1085 return false;
1086
1087 // With DWARFv5 we can assume that the first support
1088 // file is also the name of the compile unit. This
1089 // allows us to avoid loading the non-skeleton unit,
1090 // which may be in a separate DWO file.
1091 SupportFileList support_files;
1092 if (!ParseSupportFiles(dwarf_cu, module_sp, support_files))
1093 return false;
1094 if (support_files.GetSize() == 0)
1095 return false;
1096 initialize_cu(support_files.GetSupportFileAtIndex(0),
1097 eLanguageTypeUnknown, std::move(support_files));
1098 return true;
1099 };
1100
1101 if (!lazy_initialize_cu()) {
1102 // Eagerly initialize compile unit
1103 const DWARFBaseDIE cu_die =
1105 if (cu_die) {
1107 dwarf_cu.GetDWARFLanguageType());
1108
1109 FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
1110
1111 // Path needs to be remapped in this case. In the support files
1112 // case ParseSupportFiles takes care of the remapping.
1113 MakeAbsoluteAndRemap(cu_file_spec, dwarf_cu, module_sp);
1114
1115 initialize_cu(std::make_shared<SupportFile>(cu_file_spec),
1116 cu_language);
1117 }
1118 }
1119 }
1120 }
1121 }
1122 return cu_sp;
1123}
1124
1126 if (!m_lldb_cu_to_dwarf_unit.empty())
1127 return;
1128
1129 DWARFDebugInfo &info = DebugInfo();
1130 if (!info.ContainsTypeUnits()) {
1131 // We can use a 1-to-1 mapping. No need to build a translation table.
1132 return;
1133 }
1134 for (uint32_t i = 0, num = info.GetNumUnits(); i < num; ++i) {
1135 if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info.GetUnitAtIndex(i))) {
1136 cu->SetID(m_lldb_cu_to_dwarf_unit.size());
1137 m_lldb_cu_to_dwarf_unit.push_back(i);
1138 }
1139 }
1140}
1141
1142std::optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
1144 if (m_lldb_cu_to_dwarf_unit.empty())
1145 return cu_idx;
1146 if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
1147 return std::nullopt;
1148 return m_lldb_cu_to_dwarf_unit[cu_idx];
1149}
1150
1153 return info->CalculateNumCompileUnits();
1154
1156 return m_lldb_cu_to_dwarf_unit.empty() ? DebugInfo().GetNumUnits()
1157 : m_lldb_cu_to_dwarf_unit.size();
1158}
1159
1161 ASSERT_MODULE_LOCK(this);
1163 return info->ParseCompileUnitAtIndex(cu_idx);
1164
1165 if (std::optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
1166 if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
1167 DebugInfo().GetUnitAtIndex(*dwarf_idx)))
1168 return ParseCompileUnit(*dwarf_cu);
1169 }
1170 return {};
1171}
1172
1174 const DWARFDIE &die) {
1175 ASSERT_MODULE_LOCK(this);
1176 Log *log = GetLog(LLDBLog::Symbols);
1177 if (!die.IsValid())
1178 return nullptr;
1179
1180 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
1181 if (auto err = type_system_or_err.takeError()) {
1182 LLDB_LOG_ERROR(log, std::move(err), "Unable to parse function: {0}");
1183 return nullptr;
1184 }
1185 auto ts = *type_system_or_err;
1186 if (!ts)
1187 return nullptr;
1188 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
1189 if (!dwarf_ast)
1190 return nullptr;
1191
1192 AddressRanges ranges;
1193 ModuleSP module_sp(die.GetModule());
1194 if (llvm::Expected<llvm::DWARFAddressRangesVector> die_ranges =
1195 die.GetDIE()->GetAttributeAddressRanges(die.GetCU(),
1196 /*check_hi_lo_pc=*/true)) {
1197 for (const auto &range : *die_ranges) {
1198 if (range.valid() && range.LowPC < m_first_code_address)
1199 continue;
1200 // Require the low PC to resolve to a section. This rejects addresses that
1201 // don't correspond to any real code, such as the "(dead code)" tombstone
1202 // a linker leaves on the DW_AT_low_pc of an eliminated function.
1203 if (Address base_addr(range.LowPC, module_sp->GetSectionList());
1204 base_addr.IsSectionOffset() && FixupAddress(base_addr))
1205 ranges.emplace_back(std::move(base_addr), range.HighPC - range.LowPC);
1206 }
1207 } else {
1208 LLDB_LOG_ERRORV(log, die_ranges.takeError(), "DIE({1:x}): {0}",
1209 die.GetID());
1210 }
1211 if (ranges.empty())
1212 return nullptr;
1213
1214 return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die, std::move(ranges));
1215}
1216
1219 ASSERT_MODULE_LOCK(this);
1220 if (!die.IsValid()) {
1221 return ConstString();
1222 }
1223
1224 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
1225 if (auto err = type_system_or_err.takeError()) {
1226 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
1227 "Unable to construct demangled name for function: {0}");
1228 return ConstString();
1229 }
1230
1231 auto ts = *type_system_or_err;
1232 if (!ts) {
1233 LLDB_LOG(GetLog(LLDBLog::Symbols), "Type system no longer live");
1234 return ConstString();
1235 }
1236 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
1237 if (!dwarf_ast)
1238 return ConstString();
1239
1240 return dwarf_ast->ConstructDemangledNameFromDWARF(die);
1241}
1242
1244 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1245 if (debug_map_symfile)
1246 return debug_map_symfile->LinkOSOFileAddress(this, file_addr);
1247 return file_addr;
1248}
1249
1251 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1252 if (debug_map_symfile) {
1253 return debug_map_symfile->LinkOSOAddress(addr);
1254 }
1255 // This is a normal DWARF file, no address fixups need to happen
1256 return true;
1257}
1259 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1260 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1261 if (dwarf_cu)
1262 return GetLanguage(dwarf_cu->GetNonSkeletonUnit());
1263 else
1264 return eLanguageTypeUnknown;
1265}
1266
1268 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1269 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1270 if (!dwarf_cu)
1271 return {};
1272 const DWARFBaseDIE cu_die = dwarf_cu->GetNonSkeletonUnit().GetUnitDIEOnly();
1273 if (!cu_die)
1274 return {};
1275 const char *sdk = cu_die.GetAttributeValueAsString(DW_AT_APPLE_sdk, nullptr);
1276 if (!sdk)
1277 return {};
1278 llvm::StringRef sysroot =
1279 cu_die.GetAttributeValueAsString(DW_AT_LLVM_sysroot, "");
1280
1281 // RegisterXcodeSDK calls into xcrun which is not aware of CLT, which is
1282 // expensive.
1283 if (!sysroot.starts_with("/Library/Developer/CommandLineTools/SDKs")) {
1284 // Register the sysroot path remapping with the module belonging to
1285 // the CU as well as the one belonging to the symbol file. The two
1286 // would be different if this is an OSO object and module is the
1287 // corresponding debug map, in which case both should be updated.
1288 ModuleSP module_sp = comp_unit.GetModule();
1289 if (module_sp)
1290 module_sp->RegisterXcodeSDK(sdk, sysroot);
1291
1292 ModuleSP local_module_sp = m_objfile_sp->GetModule();
1293 if (local_module_sp && local_module_sp != module_sp)
1294 local_module_sp->RegisterXcodeSDK(sdk, sysroot);
1295 }
1296
1297 return {sdk, FileSpec(sysroot)};
1298}
1299
1302 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1303 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1304 if (!dwarf_cu)
1305 return 0;
1306
1307 size_t functions_added = 0;
1308 dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
1309 for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
1310 if (entry.Tag() != DW_TAG_subprogram)
1311 continue;
1312
1313 DWARFDIE die(dwarf_cu, &entry);
1314 if (comp_unit.FindFunctionByUID(die.GetID()))
1315 continue;
1316 if (ParseFunction(comp_unit, die))
1317 ++functions_added;
1318 }
1319 // FixupTypes();
1320 return functions_added;
1321}
1322
1324 CompileUnit &comp_unit,
1325 llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
1326 llvm::function_ref<bool(Module &)> lambda) {
1327 // Only visit each symbol file once.
1328 if (!visited_symbol_files.insert(this).second)
1329 return false;
1330
1332 for (auto &p : m_external_type_modules) {
1333 ModuleSP module = p.second;
1334 if (!module)
1335 continue;
1336
1337 // Invoke the action and potentially early-exit.
1338 if (lambda(*module))
1339 return true;
1340
1341 for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
1342 auto cu = module->GetCompileUnitAtIndex(i);
1343 bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
1344 if (early_exit)
1345 return true;
1346 }
1347 }
1348 return false;
1349}
1350
1352 SupportFileList &support_files) {
1353 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1354 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1355 if (!dwarf_cu)
1356 return false;
1357
1358 if (!ParseSupportFiles(*dwarf_cu, comp_unit.GetModule(), support_files))
1359 return false;
1360
1361 return true;
1362}
1363
1365 const ModuleSP &module,
1366 SupportFileList &support_files) {
1367
1368 dw_offset_t offset = dwarf_cu.GetLineTableOffset();
1369 if (offset == DW_INVALID_OFFSET)
1370 return false;
1371
1373 llvm::DWARFDebugLine::Prologue prologue;
1374 if (!ParseLLVMLineTablePrologue(m_context, prologue, offset,
1375 dwarf_cu.GetOffset()))
1376 return false;
1377
1378 std::string comp_dir = dwarf_cu.GetCompilationDirectory().GetPath();
1379 ParseSupportFilesFromPrologue(support_files, module, prologue,
1380 dwarf_cu.GetPathStyle(), comp_dir);
1381 return true;
1382}
1383
1385 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
1386 if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
1387 return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
1388 return FileSpec();
1389 }
1390
1391 auto &tu = llvm::cast<DWARFTypeUnit>(unit);
1392 if (const SupportFileList *support_files = GetTypeUnitSupportFiles(tu))
1393 return support_files->GetFileSpecAtIndex(file_idx);
1394 return {};
1395}
1396
1397const SupportFileList *
1399 static SupportFileList empty_list;
1400
1401 dw_offset_t offset = tu.GetLineTableOffset();
1402 if (offset == DW_INVALID_OFFSET)
1403 return nullptr;
1404
1405 // Many type units can share a line table, so parse the support file list
1406 // once, and cache it based on the offset field.
1407 auto iter_bool = m_type_unit_support_files.try_emplace(offset);
1408 std::unique_ptr<SupportFileList> &list = iter_bool.first->second;
1409 if (iter_bool.second) {
1410 list = std::make_unique<SupportFileList>();
1411 uint64_t line_table_offset = offset;
1412 llvm::DWARFDataExtractor data =
1413 m_context.getOrLoadLineData().GetAsLLVMDWARF();
1414 llvm::DWARFContext &ctx = m_context.GetAsLLVM();
1415 llvm::DWARFDebugLine::Prologue prologue;
1416 auto report = [](llvm::Error error) {
1418 LLDB_LOG_ERROR(log, std::move(error),
1419 "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
1420 "the line table prologue: {0}");
1421 };
1423 llvm::Error error = prologue.parse(data, &line_table_offset, report, ctx);
1424 if (error)
1425 report(std::move(error));
1426 else
1427 ParseSupportFilesFromPrologue(*list, GetObjectFile()->GetModule(),
1428 prologue, tu.GetPathStyle());
1429 }
1430 return list.get();
1431}
1432
1434 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1435 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1436 if (dwarf_cu)
1437 return dwarf_cu->GetNonSkeletonUnit().GetIsOptimized();
1438 return false;
1439}
1440
1443 std::vector<SourceModule> &imported_modules) {
1444 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1445 assert(sc.comp_unit);
1446 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1447 if (!dwarf_cu)
1448 return false;
1450 sc.comp_unit->GetLanguage()))
1451 return false;
1453
1454 const DWARFDIE die = dwarf_cu->DIE();
1455 if (!die)
1456 return false;
1457
1458 for (DWARFDIE child_die : die.children()) {
1459 if (child_die.Tag() != DW_TAG_imported_declaration)
1460 continue;
1461
1462 DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
1463 if (module_die.Tag() != DW_TAG_module)
1464 continue;
1465
1466 if (const char *name =
1467 module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
1468 SourceModule module;
1469 module.path.push_back(ConstString(name));
1470
1471 const char *include_path = module_die.GetAttributeValueAsString(
1472 DW_AT_LLVM_include_path, nullptr);
1473 DWARFDIE parent_die = module_die;
1474 while ((parent_die = parent_die.GetParent())) {
1475 if (parent_die.Tag() != DW_TAG_module)
1476 break;
1477 if (const char *name =
1478 parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
1479 module.path.push_back(ConstString(name));
1480
1481 // Inferred submodule declarations may not have a
1482 // DW_AT_LLVM_include_path. Pick the parent (aka umbrella) module's
1483 // include path instead.
1484 if (!include_path)
1485 include_path = parent_die.GetAttributeValueAsString(
1486 DW_AT_LLVM_include_path, nullptr);
1487 }
1488 std::reverse(module.path.begin(), module.path.end());
1489 if (include_path) {
1490 FileSpec include_spec(include_path, dwarf_cu->GetPathStyle());
1491 MakeAbsoluteAndRemap(include_spec, *dwarf_cu,
1492 m_objfile_sp->GetModule());
1493 module.search_path = ConstString(include_spec.GetPath());
1494 }
1495 if (const char *sysroot = dwarf_cu->DIE().GetAttributeValueAsString(
1496 DW_AT_LLVM_sysroot, nullptr))
1497 module.sysroot = ConstString(sysroot);
1498 imported_modules.push_back(module);
1499 }
1500 }
1501 return true;
1502}
1503
1505 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1506 if (comp_unit.GetLineTable() != nullptr)
1507 return true;
1508
1510 return info->ParseLineTable(comp_unit);
1511
1512 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1513 if (!dwarf_cu)
1514 return false;
1515
1516 dw_offset_t offset = dwarf_cu->GetLineTableOffset();
1517 if (offset == DW_INVALID_OFFSET)
1518 return false;
1519
1521 llvm::DWARFDebugLine line;
1522 const llvm::DWARFDebugLine::LineTable *line_table =
1523 ParseLLVMLineTable(m_context, line, offset, dwarf_cu->GetOffset());
1524
1525 if (!line_table)
1526 return false;
1527
1528 std::unique_ptr<LineTable> line_table_up =
1529 ConvertLineTable(comp_unit, *line_table, m_first_code_address);
1530
1531 if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1532 // We have an object file that has a line table with addresses that are not
1533 // linked. We need to link the line table and convert the addresses that
1534 // are relative to the .o file into addresses for the main executable.
1535 comp_unit.SetLineTable(
1536 debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1537 } else {
1538 comp_unit.SetLineTable(line_table_up.release());
1539 }
1540
1541 return true;
1542}
1543
1546 auto iter = m_debug_macros_map.find(*offset);
1547 if (iter != m_debug_macros_map.end())
1548 return iter->second;
1549
1551 const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1552 if (debug_macro_data.GetByteSize() == 0)
1553 return DebugMacrosSP();
1554
1556 m_debug_macros_map[*offset] = debug_macros_sp;
1557
1558 const DWARFDebugMacroHeader &header =
1559 DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1561 debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1562 offset, this, debug_macros_sp);
1563
1564 return debug_macros_sp;
1565}
1566
1568 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1569
1570 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1571 if (dwarf_cu == nullptr)
1572 return false;
1573
1574 const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1575 if (!dwarf_cu_die)
1576 return false;
1577
1578 lldb::offset_t sect_offset =
1579 dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1580 if (sect_offset == DW_INVALID_OFFSET)
1581 sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1583 if (sect_offset == DW_INVALID_OFFSET)
1584 return false;
1585
1586 comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset));
1587
1588 return true;
1589}
1590
1592 Block *parent_block, DWARFDIE die,
1593 addr_t function_file_addr) {
1594 size_t blocks_added = 0;
1595 for (; die; die = die.GetSibling()) {
1596 dw_tag_t tag = die.Tag();
1597
1598 if (tag != DW_TAG_inlined_subroutine && tag != DW_TAG_lexical_block)
1599 continue;
1600
1601 Block *block = parent_block->CreateChild(die.GetID()).get();
1602 llvm::DWARFAddressRangesVector ranges;
1603 const char *name = nullptr;
1604 const char *mangled_name = nullptr;
1605
1606 std::optional<int> decl_file;
1607 std::optional<int> decl_line;
1608 std::optional<int> decl_column;
1609 std::optional<int> call_file;
1610 std::optional<int> call_line;
1611 std::optional<int> call_column;
1612 if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1613 decl_line, decl_column, call_file, call_line,
1614 call_column, nullptr)) {
1615 for (const llvm::DWARFAddressRange &range : ranges) {
1616 if (range.valid() && range.LowPC >= m_first_code_address)
1617 block->AddRange(Block::Range(range.LowPC - function_file_addr,
1618 range.HighPC - range.LowPC));
1619 }
1620 block->FinalizeRanges();
1621
1622 if (tag != DW_TAG_subprogram &&
1623 (name != nullptr || mangled_name != nullptr)) {
1624 std::unique_ptr<Declaration> decl_up;
1625 if (decl_file || decl_line || decl_column)
1626 decl_up = std::make_unique<Declaration>(
1628 decl_file.value_or(0)),
1629 decl_line.value_or(0), decl_column.value_or(0));
1630
1631 std::unique_ptr<Declaration> call_up;
1632 if (call_file || call_line || call_column)
1633 call_up = std::make_unique<Declaration>(
1635 call_file.value_or(0)),
1636 call_line.value_or(0), call_column.value_or(0));
1637
1638 block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1639 call_up.get());
1640 }
1641
1642 ++blocks_added;
1643
1644 if (die.HasChildren()) {
1645 blocks_added += ParseBlocksRecursive(
1646 comp_unit, block, die.GetFirstChild(), function_file_addr);
1647 }
1648 }
1649 }
1650 return blocks_added;
1651}
1652
1654 if (parent_die) {
1655 for (DWARFDIE die : parent_die.children()) {
1656 dw_tag_t tag = die.Tag();
1657 bool check_virtuality = false;
1658 switch (tag) {
1659 case DW_TAG_inheritance:
1660 case DW_TAG_subprogram:
1661 check_virtuality = true;
1662 break;
1663 default:
1664 break;
1665 }
1666 if (check_virtuality) {
1667 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1668 return true;
1669 }
1670 }
1671 }
1672 return false;
1673}
1674
1676 auto *type_system = decl_ctx.GetTypeSystem();
1677 if (type_system != nullptr)
1679 decl_ctx);
1680}
1681
1684
1686 // This method can be called without going through the symbol vendor so we
1687 // need to lock the module.
1688 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1689 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1690 // SymbolFileDWARF::GetDIE(). See comments inside the
1691 // SymbolFileDWARF::GetDIE() for details.
1692 if (DWARFDIE die = GetDIE(type_uid))
1693 return GetDecl(die);
1694 return CompilerDecl();
1695}
1696
1699 // This method can be called without going through the symbol vendor so we
1700 // need to lock the module.
1701 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1702 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1703 // SymbolFileDWARF::GetDIE(). See comments inside the
1704 // SymbolFileDWARF::GetDIE() for details.
1705 if (DWARFDIE die = GetDIE(type_uid))
1706 return GetDeclContext(die);
1707 return CompilerDeclContext();
1708}
1709
1712 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1713 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1714 // SymbolFileDWARF::GetDIE(). See comments inside the
1715 // SymbolFileDWARF::GetDIE() for details.
1716 if (DWARFDIE die = GetDIE(type_uid))
1717 return GetContainingDeclContext(die);
1718 return CompilerDeclContext();
1719}
1720
1721std::vector<CompilerContext>
1723 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1724 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1725 // SymbolFileDWARF::GetDIE(). See comments inside the
1726 // SymbolFileDWARF::GetDIE() for details.
1727 if (DWARFDIE die = GetDIE(type_uid))
1728 return die.GetDeclContext();
1729 return {};
1730}
1731
1733 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1734 // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1735 // SymbolFileDWARF::GetDIE(). See comments inside the
1736 // SymbolFileDWARF::GetDIE() for details.
1737 if (DWARFDIE type_die = GetDIE(type_uid))
1738 return type_die.ResolveType();
1739 else
1740 return nullptr;
1741}
1742
1743std::optional<SymbolFile::ArrayInfo> SymbolFileDWARF::GetDynamicArrayInfoForUID(
1744 lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1745 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1746 if (DWARFDIE type_die = GetDIE(type_uid))
1747 return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1748 else
1749 return std::nullopt;
1750}
1751
1753 return ResolveType(GetDIE(die_ref), true);
1754}
1755
1757 bool assert_not_being_parsed) {
1758 if (die) {
1760 if (log)
1761 GetObjectFile()->GetModule()->LogMessage(
1762 log,
1763 "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) {1} ({2}) '{3}'",
1764 die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1765 die.GetName());
1766
1767 // We might be coming in in the middle of a type tree (a class within a
1768 // class, an enum within a class), so parse any needed parent DIEs before
1769 // we get to this one...
1770 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1771 if (decl_ctx_die) {
1772 if (log) {
1773 switch (decl_ctx_die.Tag()) {
1774 case DW_TAG_structure_type:
1775 case DW_TAG_union_type:
1776 case DW_TAG_class_type: {
1777 // Get the type, which could be a forward declaration
1778 if (log)
1779 GetObjectFile()->GetModule()->LogMessage(
1780 log,
1781 "SymbolFileDWARF::ResolveTypeUID (die = {0:x16}) {1} ({2}) "
1782 "'{3}' resolve parent forward type for {4:x16})",
1783 die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1784 die.GetName(), decl_ctx_die.GetOffset());
1785 } break;
1786
1787 default:
1788 break;
1789 }
1790 }
1791 }
1792 return ResolveType(die);
1793 }
1794 return nullptr;
1795}
1796
1797// This function is used when SymbolFileDWARFDebugMap owns a bunch of
1798// SymbolFileDWARF objects to detect if this DWARF file is the one that can
1799// resolve a compiler_type.
1801 const CompilerType &compiler_type) {
1802 CompilerType compiler_type_no_qualifiers =
1803 ClangUtil::RemoveFastQualifiers(compiler_type);
1805 compiler_type_no_qualifiers.GetOpaqueQualType())) {
1806 return true;
1807 }
1808 auto clang_type_system = compiler_type.GetTypeSystem<TypeSystemClang>();
1809 if (!clang_type_system)
1810 return false;
1811 auto *ast_parser =
1812 llvm::cast<DWARFASTParserClang>(clang_type_system->GetDWARFParser());
1813 return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1814}
1815
1817 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1818 auto clang_type_system = compiler_type.GetTypeSystem<TypeSystemClang>();
1819 if (clang_type_system) {
1820 auto *ast_parser =
1821 llvm::cast<DWARFASTParserClang>(clang_type_system->GetDWARFParser());
1822 if (ast_parser &&
1823 ast_parser->GetClangASTImporter().CanImport(compiler_type))
1824 return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1825 }
1826
1827 // We have a struct/union/class/enum that needs to be fully resolved.
1828 CompilerType compiler_type_no_qualifiers =
1829 ClangUtil::RemoveFastQualifiers(compiler_type);
1830 auto die_it = GetForwardDeclCompilerTypeToDIE().find(
1831 compiler_type_no_qualifiers.GetOpaqueQualType());
1832 if (die_it == GetForwardDeclCompilerTypeToDIE().end()) {
1833 // We have already resolved this type...
1834 return true;
1835 }
1836
1837 DWARFDIE decl_die = GetDIE(die_it->getSecond());
1838 // Once we start resolving this type, remove it from the forward
1839 // declaration map in case anyone's child members or other types require this
1840 // type to get resolved.
1841 GetForwardDeclCompilerTypeToDIE().erase(die_it);
1842 DWARFDIE def_die = FindDefinitionDIE(decl_die);
1843 if (!def_die) {
1844 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1845 if (debug_map_symfile) {
1846 // We weren't able to find a full declaration in this DWARF, see
1847 // if we have a declaration anywhere else...
1848 def_die = debug_map_symfile->FindDefinitionDIE(decl_die);
1849 }
1850 }
1851 if (!def_die) {
1852 // If we don't have definition DIE, CompleteTypeFromDWARF will forcefully
1853 // complete this type.
1854 def_die = decl_die;
1855 }
1856
1857 DWARFASTParser *dwarf_ast = GetDWARFParser(*def_die.GetCU());
1858 if (!dwarf_ast)
1859 return false;
1860 Type *type = GetDIEToType().lookup(decl_die.GetDIE());
1861 assert(type);
1862
1863 if (decl_die != def_die) {
1864 GetDIEToType()[def_die.GetDIE()] = type;
1865 auto *ast_parser = llvm::cast<DWARFASTParserClang>(dwarf_ast);
1866 ast_parser->MapDeclDIEToDefDIE(decl_die, def_die);
1867 }
1868
1870 if (log)
1871 GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1872 log, "{0:x8}: {1} ({2}) '{3}' resolving forward declaration...",
1873 def_die.GetID(), DW_TAG_value_to_name(def_die.Tag()), def_die.Tag(),
1874 type->GetName().GetStringRef());
1875 assert(compiler_type);
1876 return dwarf_ast->CompleteTypeFromDWARF(def_die, type, compiler_type);
1877}
1878
1880 bool assert_not_being_parsed,
1881 bool resolve_function_context) {
1882 if (die) {
1883 Type *type = GetTypeForDIE(die, resolve_function_context).get();
1884
1885 if (assert_not_being_parsed) {
1886 if (type != DIE_IS_BEING_PARSED)
1887 return type;
1888
1889 GetObjectFile()->GetModule()->ReportInternalError(
1890 "Parsing a die that is being parsed die: {0:x16}: {1} ({2}) {3}",
1891 die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
1892 die.GetName());
1893
1894 } else
1895 return type;
1896 }
1897 return nullptr;
1898}
1899
1902
1903 if (dwarf_cu.IsDWOUnit()) {
1904 DWARFCompileUnit *non_dwo_cu = dwarf_cu.GetSkeletonUnit();
1905 assert(non_dwo_cu);
1907 *non_dwo_cu);
1908 }
1909 // Check if the symbol vendor already knows about this compile unit?
1910 CompileUnit *lldb_cu = dwarf_cu.GetLLDBCompUnit();
1911 if (lldb_cu)
1912 return lldb_cu;
1913 // The symbol vendor doesn't know about this compile unit, we need to parse
1914 // and add it to the symbol vendor object.
1915 return ParseCompileUnit(dwarf_cu).get();
1916}
1917
1919 ConstString class_name,
1920 llvm::function_ref<IterationAction(DWARFDIE die)> callback) {
1921 m_index->GetObjCMethods(class_name, callback);
1922}
1923
1925 sc.Clear(false);
1926
1927 if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1928 // Check if the symbol vendor already knows about this compile unit?
1929 sc.comp_unit =
1930 GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1931
1932 sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1933 if (sc.function == nullptr)
1934 sc.function = ParseFunction(*sc.comp_unit, die);
1935
1936 if (sc.function) {
1938 return true;
1939 }
1940 }
1941
1942 return false;
1943}
1944
1947 const auto &pos = m_external_type_modules.find(name);
1948 if (pos == m_external_type_modules.end())
1949 return lldb::ModuleSP();
1950 return pos->second;
1951}
1952
1954 // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1955 // must make sure we use the correct DWARF file when resolving things. On
1956 // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1957 // SymbolFileDWARF classes, one for each .o file. We can often end up with
1958 // references to other DWARF objects and we must be ready to receive a
1959 // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1960 // instance.
1961
1962 std::optional<uint32_t> file_index = die_ref.file_index();
1963
1964 // If the file index matches, then we have the right SymbolFileDWARF already.
1965 // This will work for both .dwo file and DWARF in .o files for mac. Also if
1966 // both the file indexes are invalid, then we have a match.
1967 if (GetFileIndex() == file_index)
1968 return this;
1969
1970 if (file_index) {
1971 // We have a SymbolFileDWARFDebugMap, so let it find the right file
1973 return debug_map->GetSymbolFileByOSOIndex(*file_index);
1974
1975 // Handle the .dwp file case correctly
1976 if (*file_index == DIERef::k_file_index_mask)
1977 return GetDwpSymbolFile().get(); // DWP case
1978
1979 // Handle the .dwo file case correctly
1980 return DebugInfo().GetUnitAtIndex(*die_ref.file_index())
1981 ->GetDwoSymbolFile(); // DWO case
1982 }
1983 return this;
1984}
1985
1988 if (die_ref.die_offset() == DW_INVALID_OFFSET)
1989 return DWARFDIE();
1990
1991 // This method can be called without going through the symbol vendor so we
1992 // need to lock the module.
1993 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1994 SymbolFileDWARF *symbol_file = GetDIERefSymbolFile(die_ref);
1995 if (symbol_file)
1996 return symbol_file->DebugInfo().GetDIE(die_ref.section(),
1997 die_ref.die_offset());
1998 return DWARFDIE();
1999}
2000
2001/// Return the DW_AT_(GNU_)dwo_id.
2002static std::optional<uint64_t> GetDWOId(DWARFCompileUnit &dwarf_cu,
2003 const DWARFDebugInfoEntry &cu_die) {
2004 std::optional<uint64_t> dwo_id =
2005 cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id);
2006 if (dwo_id)
2007 return dwo_id;
2008 return cu_die.GetAttributeValueAsOptionalUnsigned(&dwarf_cu, DW_AT_dwo_id);
2009}
2010
2011std::optional<uint64_t> SymbolFileDWARF::GetDWOId() {
2012 if (GetNumCompileUnits() == 1) {
2013 if (auto comp_unit = GetCompileUnitAtIndex(0))
2014 if (DWARFCompileUnit *cu = GetDWARFCompileUnit(comp_unit.get()))
2015 if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
2016 return ::GetDWOId(*cu, *cu_die);
2017 }
2018 return {};
2019}
2020
2024
2025std::shared_ptr<SymbolFileDWARFDwo>
2027 DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
2028 // If this is a Darwin-style debug map (non-.dSYM) symbol file,
2029 // never attempt to load ELF-style DWO files since the -gmodules
2030 // support uses the same DWO mechanism to specify full debug info
2031 // files for modules. This is handled in
2032 // UpdateExternalModuleListIfNeeded().
2033 if (GetDebugMapSymfile())
2034 return nullptr;
2035
2036 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
2037 // Only compile units can be split into two parts and we should only
2038 // look for a DWO file if there is a valid DWO ID.
2039 if (!dwarf_cu || !dwarf_cu->GetDWOId().has_value())
2040 return nullptr;
2041
2042 const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
2043 if (!dwo_name) {
2045 "missing DWO name in skeleton DIE {0:x16}", cu_die.GetOffset()));
2046 return nullptr;
2047 }
2048
2049 if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile())
2050 return dwp_sp;
2051
2052 FileSpec dwo_file(dwo_name);
2053 FileSystem::Instance().Resolve(dwo_file);
2054 bool found = false;
2055
2056 const FileSpecList &debug_file_search_paths =
2058 size_t num_search_paths = debug_file_search_paths.GetSize();
2059
2060 // It's relative, e.g. "foo.dwo", but we just to happen to be right next to
2061 // it. Or it's absolute.
2062 found = FileSystem::Instance().Exists(dwo_file);
2063
2064 const char *comp_dir =
2065 cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
2066 if (!found) {
2067 // It could be a relative path that also uses DW_AT_COMP_DIR.
2068 if (comp_dir) {
2069 dwo_file.SetFile(comp_dir, FileSpec::Style::native);
2070 if (!dwo_file.IsRelative()) {
2071 FileSystem::Instance().Resolve(dwo_file);
2072 dwo_file.AppendPathComponent(dwo_name);
2073 found = FileSystem::Instance().Exists(dwo_file);
2074 } else {
2075 FileSpecList dwo_paths;
2076
2077 // if DW_AT_comp_dir is relative, it should be relative to the location
2078 // of the executable, not to the location from which the debugger was
2079 // launched.
2080 FileSpec relative_to_binary = dwo_file;
2081 relative_to_binary.PrependPathComponent(
2082 m_objfile_sp->GetFileSpec().GetDirectory());
2083 FileSystem::Instance().Resolve(relative_to_binary);
2084 relative_to_binary.AppendPathComponent(dwo_name);
2085 dwo_paths.Append(relative_to_binary);
2086
2087 // Or it's relative to one of the user specified debug directories.
2088 for (size_t idx = 0; idx < num_search_paths; ++idx) {
2089 FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx);
2090 dirspec.AppendPathComponent(comp_dir);
2091 FileSystem::Instance().Resolve(dirspec);
2092 if (!FileSystem::Instance().IsDirectory(dirspec))
2093 continue;
2094
2095 dirspec.AppendPathComponent(dwo_name);
2096 dwo_paths.Append(dirspec);
2097 }
2098
2099 size_t num_possible = dwo_paths.GetSize();
2100 for (size_t idx = 0; idx < num_possible && !found; ++idx) {
2101 FileSpec dwo_spec = dwo_paths.GetFileSpecAtIndex(idx);
2102 if (FileSystem::Instance().Exists(dwo_spec)) {
2103 dwo_file = dwo_spec;
2104 found = true;
2105 }
2106 }
2107 }
2108 } else {
2109 Log *log = GetLog(LLDBLog::Symbols);
2110 LLDB_LOGF(log,
2111 "unable to locate relative .dwo debug file \"%s\" for "
2112 "skeleton DIE 0x%016" PRIx64 " without valid DW_AT_comp_dir "
2113 "attribute",
2114 dwo_name, cu_die.GetOffset());
2115 }
2116 }
2117
2118 if (!found) {
2119 // Try adding the DW_AT_dwo_name ( e.g. "c/d/main-main.dwo"), and just the
2120 // filename ("main-main.dwo") to binary dir and search paths.
2121 FileSpecList dwo_paths;
2122 FileSpec dwo_name_spec(dwo_name);
2123 llvm::StringRef filename_only = dwo_name_spec.GetFilename();
2124
2125 FileSpec binary_directory(m_objfile_sp->GetFileSpec().GetDirectory());
2126 FileSystem::Instance().Resolve(binary_directory);
2127
2128 if (dwo_name_spec.IsRelative()) {
2129 FileSpec dwo_name_binary_directory(binary_directory);
2130 dwo_name_binary_directory.AppendPathComponent(dwo_name);
2131 dwo_paths.Append(dwo_name_binary_directory);
2132 }
2133
2134 FileSpec filename_binary_directory(binary_directory);
2135 filename_binary_directory.AppendPathComponent(filename_only);
2136 dwo_paths.Append(filename_binary_directory);
2137
2138 for (size_t idx = 0; idx < num_search_paths; ++idx) {
2139 FileSpec dirspec = debug_file_search_paths.GetFileSpecAtIndex(idx);
2140 FileSystem::Instance().Resolve(dirspec);
2141 if (!FileSystem::Instance().IsDirectory(dirspec))
2142 continue;
2143
2144 FileSpec dwo_name_dirspec(dirspec);
2145 dwo_name_dirspec.AppendPathComponent(dwo_name);
2146 dwo_paths.Append(dwo_name_dirspec);
2147
2148 FileSpec filename_dirspec(dirspec);
2149 filename_dirspec.AppendPathComponent(filename_only);
2150 dwo_paths.Append(filename_dirspec);
2151 }
2152
2153 size_t num_possible = dwo_paths.GetSize();
2154 for (size_t idx = 0; idx < num_possible && !found; ++idx) {
2155 FileSpec dwo_spec = dwo_paths.GetFileSpecAtIndex(idx);
2156 if (FileSystem::Instance().Exists(dwo_spec)) {
2157 dwo_file = dwo_spec;
2158 found = true;
2159 }
2160 }
2161 }
2162
2163 if (!found) {
2164 FileSpec error_dwo_path(dwo_name);
2165 FileSystem::Instance().Resolve(error_dwo_path);
2166 if (error_dwo_path.IsRelative() && comp_dir != nullptr) {
2167 error_dwo_path.PrependPathComponent(comp_dir);
2168 FileSystem::Instance().Resolve(error_dwo_path);
2169 }
2171 "unable to locate .dwo debug file \"{0}\" for skeleton DIE "
2172 "{1:x16}. {2}",
2173 error_dwo_path.GetPath().c_str(), cu_die.GetOffset(),
2175
2176 if (m_dwo_warning_issued.test_and_set(std::memory_order_relaxed) == false) {
2177 GetObjectFile()->GetModule()->ReportWarning(
2178 "unable to locate separate debug file (dwo, dwp). {0}",
2180 }
2181 return nullptr;
2182 }
2183
2184 const lldb::offset_t file_offset = 0;
2185 DataExtractorSP dwo_file_extractor_sp;
2186 lldb::offset_t dwo_file_data_offset = 0;
2187 ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
2188 GetObjectFile()->GetModule(), &dwo_file, file_offset,
2189 FileSystem::Instance().GetByteSize(dwo_file), dwo_file_extractor_sp,
2190 dwo_file_data_offset);
2191 if (dwo_obj_file == nullptr) {
2193 "unable to load object file for .dwo debug file \"{0}\" for "
2194 "unit DIE {1:x16}",
2195 dwo_name, cu_die.GetOffset()));
2196 return nullptr;
2197 }
2198
2199 return std::make_shared<SymbolFileDWARFDwo>(*this, dwo_obj_file,
2200 dwarf_cu->GetID());
2201}
2202
2205 return;
2207 DWARFDebugInfo &debug_info = DebugInfo();
2208
2209 // Follow DWO skeleton unit breadcrumbs.
2210 const uint32_t num_compile_units = GetNumCompileUnits();
2211 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2212 auto *dwarf_cu =
2213 llvm::dyn_cast<DWARFCompileUnit>(debug_info.GetUnitAtIndex(cu_idx));
2214 if (!dwarf_cu)
2215 continue;
2216
2217 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
2218 if (!die || die.HasChildren() || !die.GetDIE())
2219 continue;
2220
2221 const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
2222 if (!name)
2223 continue;
2224
2225 ConstString const_name(name);
2226 ModuleSP &module_sp = m_external_type_modules[const_name];
2227 if (module_sp)
2228 continue;
2229
2230 const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
2231 if (!dwo_path)
2232 continue;
2233
2234 ModuleSpec dwo_module_spec;
2235 dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
2236 if (dwo_module_spec.GetFileSpec().IsRelative()) {
2237 const char *comp_dir =
2238 die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
2239 if (comp_dir) {
2240 dwo_module_spec.GetFileSpec().SetFile(comp_dir,
2241 FileSpec::Style::native);
2242 FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
2243 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
2244 }
2245 }
2246 dwo_module_spec.GetArchitecture() =
2247 m_objfile_sp->GetModule()->GetArchitecture();
2248
2249 // When LLDB loads "external" modules it looks at the presence of
2250 // DW_AT_dwo_name. However, when the already created module
2251 // (corresponding to .dwo itself) is being processed, it will see
2252 // the presence of DW_AT_dwo_name (which contains the name of dwo
2253 // file) and will try to call ModuleList::GetSharedModule
2254 // again. In some cases (i.e., for empty files) Clang 4.0
2255 // generates a *.dwo file which has DW_AT_dwo_name, but no
2256 // DW_AT_comp_dir. In this case the method
2257 // ModuleList::GetSharedModule will fail and the warning will be
2258 // printed. However, as one can notice in this case we don't
2259 // actually need to try to load the already loaded module
2260 // (corresponding to .dwo) so we simply skip it.
2261 if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
2262 llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
2263 .ends_with(dwo_module_spec.GetFileSpec().GetPath())) {
2264 continue;
2265 }
2266
2267 Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
2268 nullptr, nullptr);
2269 if (!module_sp) {
2270 // ReportWarning also rate-limits based on the warning string,
2271 // but in a -gmodules build, each object file has a similar DAG
2272 // of module dependencies that would all be listed here.
2273 GetObjectFile()->GetModule()->ReportWarning(
2274 "{0}", error.AsCString("unknown error"));
2275 GetObjectFile()->GetModule()->ReportWarning(
2276 "unable to locate module needed for external types.\n"
2277 "Debugging will be degraded due to missing types. Rebuilding the "
2278 "project will regenerate the needed module files");
2279 continue;
2280 }
2281
2282 // Verify the DWO hash.
2283 // FIXME: Technically "0" is a valid hash.
2284 std::optional<uint64_t> dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
2285 if (!dwo_id)
2286 continue;
2287
2288 auto *dwo_symfile =
2289 llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
2290 if (!dwo_symfile)
2291 continue;
2292 std::optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
2293 if (!dwo_dwo_id)
2294 continue;
2295
2296 if (dwo_id != dwo_dwo_id) {
2297 GetObjectFile()->GetModule()->ReportWarning(
2298 "module {0} is out-of-date (hash mismatch).\n"
2299 "Type information from this module may be incomplete or inconsistent "
2300 "with the rest of the program. Rebuilding the project will "
2301 "regenerate the needed module files",
2302 dwo_module_spec.GetFileSpec().GetPath());
2303 }
2304 }
2305}
2306
2308 if (!m_global_aranges_up) {
2309 m_global_aranges_up = std::make_unique<GlobalVariableMap>();
2310
2311 ModuleSP module_sp = GetObjectFile()->GetModule();
2312 if (module_sp) {
2313 const size_t num_cus = module_sp->GetNumCompileUnits();
2314 for (size_t i = 0; i < num_cus; ++i) {
2315 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
2316 if (cu_sp) {
2317 VariableListSP globals_sp = cu_sp->GetVariableList(true);
2318 if (globals_sp) {
2319 const size_t num_globals = globals_sp->GetSize();
2320 for (size_t g = 0; g < num_globals; ++g) {
2321 VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
2322 if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
2323 const DWARFExpressionList &location =
2324 var_sp->LocationExpressionList();
2325 ExecutionContext exe_ctx;
2326 llvm::Expected<Value> location_result = location.Evaluate(
2327 &exe_ctx, nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr);
2328 if (location_result) {
2329 if (location_result->GetValueType() ==
2331 lldb::addr_t file_addr =
2332 location_result->GetScalar().ULongLong();
2333 lldb::addr_t byte_size = 1;
2334 if (var_sp->GetType())
2335 byte_size = llvm::expectedToOptional(
2336 var_sp->GetType()->GetByteSize(nullptr))
2337 .value_or(0);
2339 file_addr, byte_size, var_sp.get()));
2340 }
2341 } else {
2343 location_result.takeError(),
2344 "location expression failed to execute: {0}");
2345 }
2346 }
2347 }
2348 }
2349 }
2350 }
2351 }
2352 m_global_aranges_up->Sort();
2353 }
2354 return *m_global_aranges_up;
2355}
2356
2358 bool lookup_block,
2359 SymbolContext &sc) {
2360 assert(sc.comp_unit);
2361 DWARFCompileUnit &cu =
2363 DWARFDIE function_die = cu.LookupAddress(file_vm_addr);
2364 DWARFDIE block_die;
2365 if (function_die) {
2366 sc.function = sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
2367 if (sc.function == nullptr)
2368 sc.function = ParseFunction(*sc.comp_unit, function_die);
2369
2370 if (sc.function && lookup_block)
2371 block_die = function_die.LookupDeepestBlock(file_vm_addr);
2372 }
2373
2374 if (!sc.function || !lookup_block)
2375 return;
2376
2377 Block &block = sc.function->GetBlock(true);
2378 if (block_die)
2379 sc.block = block.FindBlockByID(block_die.GetID());
2380 else
2381 sc.block = block.FindBlockByID(function_die.GetID());
2382}
2383
2384uint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
2385 SymbolContextItem resolve_scope,
2386 SymbolContext &sc) {
2387 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2388 LLDB_SCOPED_TIMERF("SymbolFileDWARF::"
2389 "ResolveSymbolContext (so_addr = { "
2390 "section = %p, offset = 0x%" PRIx64
2391 " }, resolve_scope = 0x%8.8x)",
2392 static_cast<void *>(so_addr.GetSection().get()),
2393 so_addr.GetOffset(), resolve_scope);
2394 uint32_t resolved = 0;
2395 if (resolve_scope &
2396 (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
2397 eSymbolContextLineEntry | eSymbolContextVariable)) {
2399 return standalone->ResolveSymbolContext(so_addr, resolve_scope, sc);
2400
2401 lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2402 DWARFDebugInfo &debug_info = DebugInfo();
2403 const DWARFDebugAranges &aranges = debug_info.GetCompileUnitAranges();
2404 const dw_offset_t cu_offset = aranges.FindAddress(file_vm_addr);
2405 if (cu_offset == DW_INVALID_OFFSET) {
2406 // Global variables are not in the compile unit address ranges. The only
2407 // way to currently find global variables is to iterate over the
2408 // .debug_pubnames or the __apple_names table and find all items in there
2409 // that point to DW_TAG_variable DIEs and then find the address that
2410 // matches.
2411 if (resolve_scope & eSymbolContextVariable) {
2413 const GlobalVariableMap::Entry *entry =
2414 map.FindEntryThatContains(file_vm_addr);
2415 if (entry && entry->data) {
2416 Variable *variable = entry->data;
2417 SymbolContextScope *scc = variable->GetSymbolContextScope();
2418 if (scc) {
2419 scc->CalculateSymbolContext(&sc);
2420 sc.variable = variable;
2421 }
2422 return sc.GetResolvedMask();
2423 }
2424 }
2425 } else {
2426 uint32_t cu_idx = DW_INVALID_INDEX;
2427 if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
2428 debug_info.GetUnitAtOffset(DIERef::Section::DebugInfo, cu_offset,
2429 &cu_idx))) {
2430 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2431 if (sc.comp_unit) {
2432 resolved |= eSymbolContextCompUnit;
2433
2434 bool force_check_line_table = false;
2435 if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock)) {
2436 ResolveFunctionAndBlock(file_vm_addr,
2437 resolve_scope & eSymbolContextBlock, sc);
2438 if (sc.function)
2439 resolved |= eSymbolContextFunction;
2440 else {
2441 // We might have had a compile unit that had discontiguous address
2442 // ranges where the gaps are symbols that don't have any debug
2443 // info. Discontiguous compile unit address ranges should only
2444 // happen when there aren't other functions from other compile
2445 // units in these gaps. This helps keep the size of the aranges
2446 // down.
2447 force_check_line_table = true;
2448 }
2449 if (sc.block)
2450 resolved |= eSymbolContextBlock;
2451 }
2452
2453 if ((resolve_scope & eSymbolContextLineEntry) ||
2454 force_check_line_table) {
2455 LineTable *line_table = sc.comp_unit->GetLineTable();
2456 if (line_table != nullptr) {
2457 // And address that makes it into this function should be in terms
2458 // of this debug file if there is no debug map, or it will be an
2459 // address in the .o file which needs to be fixed up to be in
2460 // terms of the debug map executable. Either way, calling
2461 // FixupAddress() will work for us.
2462 Address exe_so_addr(so_addr);
2463 if (FixupAddress(exe_so_addr)) {
2464 if (line_table->FindLineEntryByAddress(exe_so_addr,
2465 sc.line_entry)) {
2466 resolved |= eSymbolContextLineEntry;
2467 }
2468 }
2469 }
2470 }
2471
2472 if (force_check_line_table && !(resolved & eSymbolContextLineEntry)) {
2473 // We might have had a compile unit that had discontiguous address
2474 // ranges where the gaps are symbols that don't have any debug info.
2475 // Discontiguous compile unit address ranges should only happen when
2476 // there aren't other functions from other compile units in these
2477 // gaps. This helps keep the size of the aranges down.
2478 sc.comp_unit = nullptr;
2479 resolved &= ~eSymbolContextCompUnit;
2480 }
2481 } else {
2482 GetObjectFile()->GetModule()->ReportWarning(
2483 "{0:x16}: compile unit {1} failed to create a valid "
2484 "lldb_private::CompileUnit class",
2485 cu_offset, cu_idx);
2486 }
2487 }
2488 }
2489 }
2490 return resolved;
2491}
2492
2494 const SourceLocationSpec &src_location_spec,
2495 SymbolContextItem resolve_scope, SymbolContextList &sc_list) {
2496 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2497 const bool check_inlines = src_location_spec.GetCheckInlines();
2498 const uint32_t prev_size = sc_list.GetSize();
2499 if (resolve_scope & eSymbolContextCompUnit) {
2500 for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
2501 ++cu_idx) {
2502 CompileUnit *dc_cu = GetCompileUnitAtIndex(cu_idx).get();
2503 if (!dc_cu)
2504 continue;
2505
2506 bool file_spec_matches_cu_file_spec = FileSpec::Match(
2507 src_location_spec.GetFileSpec(), dc_cu->GetPrimaryFile());
2508 if (check_inlines || file_spec_matches_cu_file_spec) {
2509 dc_cu->ResolveSymbolContext(src_location_spec, resolve_scope, sc_list);
2510 if (!check_inlines)
2511 break;
2512 }
2513 }
2514 }
2515 return sc_list.GetSize() - prev_size;
2516}
2517
2519 // Get the symbol table for the symbol file prior to taking the module lock
2520 // so that it is available without needing to take the module lock. The DWARF
2521 // indexing might end up needing to relocate items when DWARF sections are
2522 // loaded as they might end up getting the section contents which can call
2523 // ObjectFileELF::RelocateSection() which in turn will ask for the symbol
2524 // table and can cause deadlocks.
2525 GetSymtab();
2526 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2527 m_index->Preload();
2528}
2529
2530std::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2531 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2532 if (module_sp)
2533 return module_sp->GetMutex();
2534 return GetObjectFile()->GetModule()->GetMutex();
2535}
2536
2538 const lldb_private::CompilerDeclContext &decl_ctx) {
2539 if (!decl_ctx.IsValid()) {
2540 // Invalid namespace decl which means we aren't matching only things in
2541 // this symbol file, so return true to indicate it matches this symbol
2542 // file.
2543 return true;
2544 }
2545
2546 TypeSystem *decl_ctx_type_system = decl_ctx.GetTypeSystem();
2547 auto type_system_or_err = GetTypeSystemForLanguage(
2548 decl_ctx_type_system->GetMinimumLanguage(nullptr));
2549 if (auto err = type_system_or_err.takeError()) {
2550 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
2551 "Unable to match namespace decl using TypeSystem: {0}");
2552 return false;
2553 }
2554
2555 if (decl_ctx_type_system == type_system_or_err->get())
2556 return true; // The type systems match, return true
2557
2558 // The namespace AST was valid, and it does not match...
2560
2561 if (log)
2562 GetObjectFile()->GetModule()->LogMessage(
2563 log, "Valid namespace does not match symbol file");
2564
2565 return false;
2566}
2567
2569 ConstString name, const CompilerDeclContext &parent_decl_ctx,
2570 uint32_t max_matches, VariableList &variables) {
2571 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2573
2574 if (log)
2575 GetObjectFile()->GetModule()->LogMessage(
2576 log,
2577 "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2578 "parent_decl_ctx={1:p}, max_matches={2}, variables)",
2579 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2580 max_matches);
2581
2582 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2583 return;
2584
2585 // Remember how many variables are in the list before we search.
2586 const uint32_t original_size = variables.GetSize();
2587
2588 llvm::StringRef basename;
2589 llvm::StringRef context;
2590 bool name_is_mangled = Mangled::GetManglingScheme(name.GetStringRef()) !=
2592
2593 // Technically not a mangled name, but a support variable emitted by clang.
2594 // Regardless, we need an exact lookup
2595 //
2596 // FIXME: Replace this with a constant shared between Clang and LLDB
2597 if (name == "__clang_vtable")
2598 name_is_mangled = true;
2599
2601 context, basename))
2602 basename = name.GetStringRef();
2603
2604 // Loop invariant: Variables up to this index have been checked for context
2605 // matches.
2606 uint32_t pruned_idx = original_size;
2607
2608 SymbolContext sc;
2609 m_index->GetGlobalVariables(ConstString(basename), [&](DWARFDIE die) {
2610 if (!sc.module_sp)
2611 sc.module_sp = m_objfile_sp->GetModule();
2612 assert(sc.module_sp);
2613
2614 if (die.Tag() != DW_TAG_variable && die.Tag() != DW_TAG_member)
2616
2617 auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2618 if (!dwarf_cu)
2620 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2621
2622 if (parent_decl_ctx) {
2623 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2624 CompilerDeclContext actual_parent_decl_ctx =
2625 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2626
2627 /// If the actual namespace is inline (i.e., had a DW_AT_export_symbols)
2628 /// and a child (possibly through other layers of inline namespaces)
2629 /// of the namespace referred to by 'basename', allow the lookup to
2630 /// succeed.
2631 if (!actual_parent_decl_ctx ||
2632 (actual_parent_decl_ctx != parent_decl_ctx &&
2633 !parent_decl_ctx.IsContainedInLookup(actual_parent_decl_ctx)))
2635 }
2636 }
2637
2638 ParseAndAppendGlobalVariable(sc, die, variables);
2639 while (pruned_idx < variables.GetSize()) {
2640 VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2641 if (name_is_mangled ||
2642 var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2643 ++pruned_idx;
2644 else
2645 variables.RemoveVariableAtIndex(pruned_idx);
2646 }
2647
2648 if (variables.GetSize() - original_size < max_matches)
2650
2651 return IterationAction::Stop;
2652 });
2653
2654 // Return the number of variable that were appended to the list
2655 const uint32_t num_matches = variables.GetSize() - original_size;
2656 if (log && num_matches > 0) {
2657 GetObjectFile()->GetModule()->LogMessage(
2658 log,
2659 "SymbolFileDWARF::FindGlobalVariables (name=\"{0}\", "
2660 "parent_decl_ctx={1:p}, max_matches={2}, variables) => {3}",
2661 name.GetCString(), static_cast<const void *>(&parent_decl_ctx),
2662 max_matches, num_matches);
2663 }
2664}
2665
2667 uint32_t max_matches,
2668 VariableList &variables) {
2669 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2671
2672 if (log) {
2673 GetObjectFile()->GetModule()->LogMessage(
2674 log,
2675 "SymbolFileDWARF::FindGlobalVariables (regex=\"{0}\", "
2676 "max_matches={1}, variables)",
2677 regex.GetText().str().c_str(), max_matches);
2678 }
2679
2680 // Remember how many variables are in the list before we search.
2681 const uint32_t original_size = variables.GetSize();
2682
2683 SymbolContext sc;
2684 m_index->GetGlobalVariables(regex, [&](DWARFDIE die) {
2685 if (!sc.module_sp)
2686 sc.module_sp = m_objfile_sp->GetModule();
2687 assert(sc.module_sp);
2688
2689 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2690 if (!dwarf_cu)
2692 sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2693
2694 ParseAndAppendGlobalVariable(sc, die, variables);
2695
2696 if (variables.GetSize() - original_size < max_matches)
2698
2699 return IterationAction::Stop;
2700 });
2701}
2702
2704 bool include_inlines,
2705 SymbolContextList &sc_list) {
2706 SymbolContext sc;
2707
2708 if (!orig_die)
2709 return false;
2710
2711 // If we were passed a die that is not a function, just return false...
2712 if (!(orig_die.Tag() == DW_TAG_subprogram ||
2713 (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2714 return false;
2715
2716 DWARFDIE die = orig_die;
2717 DWARFDIE inlined_die;
2718 if (die.Tag() == DW_TAG_inlined_subroutine) {
2719 inlined_die = die;
2720
2721 while (true) {
2722 die = die.GetParent();
2723
2724 if (die) {
2725 if (die.Tag() == DW_TAG_subprogram)
2726 break;
2727 } else
2728 break;
2729 }
2730 }
2731 assert(die && die.Tag() == DW_TAG_subprogram);
2732 if (GetFunction(die, sc)) {
2733 // Parse all blocks if needed
2734 if (inlined_die) {
2735 Block &function_block = sc.function->GetBlock(true);
2736 sc.block = function_block.FindBlockByID(inlined_die.GetID());
2737 if (sc.block == nullptr)
2738 sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2739 }
2740
2741 sc_list.AppendIfUnique(sc, /*merge_symbol_into_function=*/true);
2742 return true;
2743 }
2744
2745 return false;
2746}
2747
2748static llvm::StringRef ClangToItaniumCtorKind(clang::CXXCtorType kind) {
2749 switch (kind) {
2750 case clang::CXXCtorType::Ctor_Complete:
2751 return "C1";
2752 case clang::CXXCtorType::Ctor_Base:
2753 return "C2";
2754 case clang::CXXCtorType::Ctor_Unified:
2755 return "C4";
2756 case clang::CXXCtorType::Ctor_CopyingClosure:
2757 case clang::CXXCtorType::Ctor_DefaultClosure:
2758 case clang::CXXCtorType::Ctor_Comdat:
2759 llvm_unreachable("Unexpected constructor kind.");
2760 }
2761 llvm_unreachable("Fully covered switch above");
2762}
2763
2764static llvm::StringRef ClangToItaniumDtorKind(clang::CXXDtorType kind) {
2765 switch (kind) {
2766 case clang::CXXDtorType::Dtor_Deleting:
2767 return "D0";
2768 case clang::CXXDtorType::Dtor_Complete:
2769 return "D1";
2770 case clang::CXXDtorType::Dtor_Base:
2771 return "D2";
2772 case clang::CXXDtorType::Dtor_Unified:
2773 return "D4";
2774 case clang::CXXDtorType::Dtor_Comdat:
2775 case clang::CXXDtorType::Dtor_VectorDeleting:
2776 llvm_unreachable("Unexpected destructor kind.");
2777 }
2778 llvm_unreachable("Fully covered switch above");
2779}
2780
2781static llvm::StringRef
2782GetItaniumCtorDtorVariant(llvm::StringRef discriminator) {
2783 const bool is_ctor = discriminator.consume_front("C");
2784 if (!is_ctor && !discriminator.consume_front("D"))
2785 return {};
2786
2787 uint64_t structor_kind;
2788 if (!llvm::to_integer(discriminator, structor_kind))
2789 return {};
2790
2791 if (is_ctor) {
2792 if (structor_kind > clang::CXXCtorType::Ctor_Unified)
2793 return {};
2794
2796 static_cast<clang::CXXCtorType>(structor_kind));
2797 }
2798
2799 if (structor_kind > clang::CXXDtorType::Dtor_Unified)
2800 return {};
2801
2802 return ClangToItaniumDtorKind(static_cast<clang::CXXDtorType>(structor_kind));
2803}
2804
2805llvm::Expected<DWARFDIE>
2807 const DWARFDIE &declaration) {
2808 auto do_lookup = [this](llvm::StringRef lookup_name) -> DWARFDIE {
2809 DWARFDIE found;
2810 auto lookup_infos = Module::LookupInfo::MakeLookupInfos(
2811 ConstString(lookup_name), lldb::eFunctionNameTypeFull,
2813
2814 m_index->GetFunctions(lookup_infos, *this, {}, [&](DWARFDIE entry) {
2815 if (entry.GetAttributeValueAsUnsigned(llvm::dwarf::DW_AT_declaration, 0))
2817
2818 found = entry;
2819 return IterationAction::Stop;
2820 });
2821
2822 return found;
2823 };
2824
2825 DWARFDIE definition = do_lookup(label.lookup_name);
2826 if (definition.IsValid())
2827 return definition;
2828
2829 // This is not a structor lookup. Nothing else to be done here.
2830 if (label.discriminator.empty())
2831 return llvm::createStringError(
2832 "no definition DIE found in this SymbolFile");
2833
2834 // We're doing a structor lookup. Maybe we didn't find the structor variant
2835 // because the complete object structor was aliased to the base object
2836 // structor. Try finding the alias instead.
2837 //
2838 // TODO: there are other reasons for why a subprogram definition might be
2839 // missing. Ideally DWARF would tell us more details about which structor
2840 // variant a DIE corresponds to and whether it's an alias.
2841 auto subst_or_err =
2843 label.lookup_name);
2844 if (!subst_or_err)
2845 return subst_or_err.takeError();
2846
2847 definition = do_lookup(*subst_or_err);
2848
2849 if (!definition.IsValid())
2850 return llvm::createStringError(
2851 "failed to find definition DIE for structor alias in fallback lookup");
2852
2853 return definition;
2854}
2855
2856llvm::Expected<SymbolContext>
2858 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2859
2860 if (!label.discriminator.empty()) {
2861 llvm::StringRef from = label.discriminator[0] == 'C' ? "C4" : "D4";
2862
2863 llvm::StringRef variant = GetItaniumCtorDtorVariant(label.discriminator);
2864 if (variant.empty())
2865 return llvm::createStringError(
2866 "failed to get Itanium variant for discriminator");
2867
2868 if (from == variant)
2869 return llvm::createStringError(
2870 "tried substituting unified structor variant into label");
2871
2872 // If we failed to substitute unified mangled name, don't try to do a lookup
2873 // using the unified name because there may be multiple definitions for it
2874 // in the index, and we wouldn't know which one to choose.
2876 label.lookup_name, from, variant);
2877 if (!subst_or_err)
2878 return llvm::joinErrors(
2879 llvm::createStringErrorV(
2880 "failed to substitute {0} for {1} in mangled name {2}:", from,
2881 variant, label.lookup_name),
2882 subst_or_err.takeError());
2883
2884 if (!*subst_or_err)
2885 return llvm::createStringErrorV(
2886 "got invalid substituted mangled named (substituted "
2887 "{0} for {1} in mangled name {2})",
2888 from, variant, label.lookup_name);
2889
2890 label.lookup_name = subst_or_err->GetStringRef();
2891 }
2892
2893 DWARFDIE die = GetDIE(label.symbol_id);
2894 if (!die.IsValid())
2895 return llvm::createStringErrorV("invalid DIE ID in {0}", label);
2896
2897 // Label was created using a declaration DIE. Need to fetch the definition
2898 // to resolve the function call.
2899 if (die.GetAttributeValueAsUnsigned(llvm::dwarf::DW_AT_declaration, 0)) {
2900 auto die_or_err = FindFunctionDefinition(label, die);
2901 if (!die_or_err)
2902 return llvm::joinErrors(
2903 llvm::createStringError("failed to find definition DIE:"),
2904 die_or_err.takeError());
2905
2906 die = std::move(*die_or_err);
2907 }
2908
2909 SymbolContextList sc_list;
2910 if (!ResolveFunction(die, /*include_inlines=*/false, sc_list))
2911 return llvm::createStringError("failed to resolve function");
2912
2913 if (sc_list.IsEmpty())
2914 return llvm::createStringError("failed to find function");
2915
2916 assert(sc_list.GetSize() == 1);
2917
2918 return sc_list[0];
2919}
2920
2922 const DWARFDIE &die,
2923 bool only_root_namespaces) {
2924 // If we have no parent decl context to match this DIE matches, and if the
2925 // parent decl context isn't valid, we aren't trying to look for any
2926 // particular decl context so any die matches.
2927 if (!decl_ctx.IsValid()) {
2928 // ...But if we are only checking root decl contexts, confirm that the
2929 // 'die' is a top-level context.
2930 if (only_root_namespaces)
2931 return die.GetParent().Tag() == llvm::dwarf::DW_TAG_compile_unit;
2932
2933 return true;
2934 }
2935
2936 if (die) {
2937 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU())) {
2938 if (CompilerDeclContext actual_decl_ctx =
2939 dwarf_ast->GetDeclContextContainingUIDFromDWARF(die))
2940 return decl_ctx.IsContainedInLookup(actual_decl_ctx);
2941 }
2942 }
2943 return false;
2944}
2945
2947 const CompilerDeclContext &parent_decl_ctx,
2948 bool include_inlines,
2949 SymbolContextList &sc_list) {
2950 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2951 ConstString name = lookup_info.GetLookupName();
2952 FunctionNameType name_type_mask = lookup_info.GetNameTypeMask();
2953
2954 // eFunctionNameTypeAuto should be pre-resolved by a call to
2955 // Module::LookupInfo::LookupInfo()
2956 assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2957
2959
2960 if (log) {
2961 GetObjectFile()->GetModule()->LogMessage(
2962 log,
2963 "SymbolFileDWARF::FindFunctions (name=\"{0}\", name_type_mask={1:x}, "
2964 "sc_list)",
2965 name.GetCString(), name_type_mask);
2966 }
2967
2968 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2969 return;
2970
2971 // If name is empty then we won't find anything.
2972 if (name.IsEmpty())
2973 return;
2974
2975 // Remember how many sc_list are in the list before we search in case we are
2976 // appending the results to a variable list.
2977
2978 const uint32_t original_size = sc_list.GetSize();
2979
2980 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2981
2982 m_index->GetFunctions(lookup_info, *this, parent_decl_ctx, [&](DWARFDIE die) {
2983 if (resolved_dies.insert(die.GetDIE()).second)
2984 ResolveFunction(die, include_inlines, sc_list);
2986 });
2987 // With -gsimple-template-names, a templated type's DW_AT_name will not
2988 // contain the template parameters. Try again stripping '<' and anything
2989 // after, filtering out entries with template parameters that don't match.
2990 {
2991 const llvm::StringRef name_ref = name.GetStringRef();
2992 auto it = name_ref.find('<');
2993 if (it != llvm::StringRef::npos) {
2994 const llvm::StringRef name_no_template_params = name_ref.slice(0, it);
2995
2996 Module::LookupInfo no_tp_lookup_info(
2997 lookup_info, ConstString(name_no_template_params));
2998 m_index->GetFunctions(no_tp_lookup_info, *this, parent_decl_ctx,
2999 [&](DWARFDIE die) {
3000 if (resolved_dies.insert(die.GetDIE()).second)
3001 ResolveFunction(die, include_inlines, sc_list);
3003 });
3004 }
3005 }
3006
3007 // Return the number of variable that were appended to the list
3008 const uint32_t num_matches = sc_list.GetSize() - original_size;
3009
3010 if (log && num_matches > 0) {
3011 GetObjectFile()->GetModule()->LogMessage(
3012 log,
3013 "SymbolFileDWARF::FindFunctions (name=\"{0}\", "
3014 "name_type_mask={1:x}, include_inlines={2:d}, sc_list) => {3}",
3015 name.GetCString(), name_type_mask, include_inlines, num_matches);
3016 }
3017}
3018
3020 bool include_inlines,
3021 SymbolContextList &sc_list) {
3022 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3023 LLDB_SCOPED_TIMERF("SymbolFileDWARF::FindFunctions (regex = '%s')",
3024 regex.GetText().str().c_str());
3025
3027
3028 if (log) {
3029 GetObjectFile()->GetModule()->LogMessage(
3030 log, "SymbolFileDWARF::FindFunctions (regex=\"{0}\", sc_list)",
3031 regex.GetText().str().c_str());
3032 }
3033
3034 llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
3035 m_index->GetFunctions(regex, [&](DWARFDIE die) {
3036 if (resolved_dies.insert(die.GetDIE()).second)
3037 ResolveFunction(die, include_inlines, sc_list);
3039 });
3040}
3041
3043 const std::string &scope_qualified_name,
3044 std::vector<ConstString> &mangled_names) {
3045 DWARFDebugInfo &info = DebugInfo();
3046 uint32_t num_comp_units = info.GetNumUnits();
3047 for (uint32_t i = 0; i < num_comp_units; i++) {
3048 DWARFUnit *cu = info.GetUnitAtIndex(i);
3049 if (cu == nullptr)
3050 continue;
3051
3053 if (dwo)
3054 dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
3055 }
3056
3057 for (DIERef die_ref :
3058 m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
3059 DWARFDIE die = GetDIE(die_ref);
3060 mangled_names.push_back(ConstString(die.GetMangledName()));
3061 }
3062}
3063
3064/// Split a name up into a basename and template parameters.
3065static bool SplitTemplateParams(llvm::StringRef fullname,
3066 llvm::StringRef &basename,
3067 llvm::StringRef &template_params) {
3068 auto it = fullname.find('<');
3069 if (it == llvm::StringRef::npos) {
3070 basename = fullname;
3071 template_params = llvm::StringRef();
3072 return false;
3073 }
3074 basename = fullname.slice(0, it);
3075 template_params = fullname.slice(it, fullname.size());
3076 return true;
3077}
3078
3080 // We need to find any names in the context that have template parameters
3081 // and strip them so the context can be matched when -gsimple-template-names
3082 // is being used. Returns true if any of the context items were updated.
3083 bool any_context_updated = false;
3084 for (auto &context : match.GetContextRef()) {
3085 llvm::StringRef basename, params;
3086 if (SplitTemplateParams(context.name.GetStringRef(), basename, params)) {
3087 context.name = ConstString(basename);
3088 any_context_updated = true;
3089 }
3090 }
3091 return any_context_updated;
3092}
3093
3094uint64_t SymbolFileDWARF::GetDebugInfoSize(bool load_all_debug_info) {
3095 DWARFDebugInfo &info = DebugInfo();
3096 uint32_t num_comp_units = info.GetNumUnits();
3097
3098 uint64_t debug_info_size = SymbolFileCommon::GetDebugInfoSize();
3099 // In dwp scenario, debug info == skeleton debug info + dwp debug info.
3100 if (std::shared_ptr<SymbolFileDWARFDwo> dwp_sp = GetDwpSymbolFile())
3101 return debug_info_size + dwp_sp->GetDebugInfoSize();
3102
3103 // In dwo scenario, debug info == skeleton debug info + all dwo debug info.
3104 for (uint32_t i = 0; i < num_comp_units; i++) {
3105 DWARFUnit *cu = info.GetUnitAtIndex(i);
3106 if (cu == nullptr)
3107 continue;
3108
3109 SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile(load_all_debug_info);
3110 if (dwo)
3111 debug_info_size += dwo->GetDebugInfoSize();
3112 }
3113 return debug_info_size;
3114}
3115
3117
3118 // Make sure we haven't already searched this SymbolFile before.
3119 if (results.AlreadySearched(this))
3120 return;
3121
3122 auto type_basename = query.GetTypeBasename();
3123
3125 if (log) {
3126 GetObjectFile()->GetModule()->LogMessage(
3127 log, "SymbolFileDWARF::FindTypes(type_basename=\"{0}\")",
3128 type_basename);
3129 }
3130
3131 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3132
3133 TypeQuery query_full(query);
3134 bool have_index_match = false;
3135 m_index->GetTypesWithQuery(query_full, [&](DWARFDIE die) {
3136 if (Type *matching_type = ResolveType(die, true, true)) {
3137 if (!query.GetSearchByMangledName() && matching_type->IsTemplateType()) {
3138 // We have to watch out for case where we lookup a type by basename and
3139 // it matches a template with simple template names. Like looking up
3140 // "Foo" and if we have simple template names then we will match
3141 // "Foo<int>" and "Foo<double>" because all the DWARF has is "Foo" in
3142 // the accelerator tables. The main case we see this in is when the
3143 // expression parser is trying to parse "Foo<int>" and it will first do
3144 // a lookup on just "Foo". We verify the type basename matches before
3145 // inserting the type in the results.
3146 auto CompilerTypeBasename =
3147 matching_type->GetForwardCompilerType().GetTypeName(true);
3148 if (CompilerTypeBasename != query.GetTypeBasename())
3150 }
3151 have_index_match = true;
3152 results.InsertUnique(matching_type->shared_from_this());
3153 }
3154 if (!results.Done(query))
3156
3157 return IterationAction::Stop;
3158 });
3159
3160 if (results.Done(query)) {
3161 if (log) {
3162 GetObjectFile()->GetModule()->LogMessage(
3163 log, "SymbolFileDWARF::FindTypes(type_basename=\"{0}\") => {1}",
3164 type_basename, results.GetTypeMap().GetSize());
3165 }
3166 return;
3167 }
3168
3169 // With -gsimple-template-names, a templated type's DW_AT_name will not
3170 // contain the template parameters. Try again stripping '<' and anything
3171 // after, filtering out entries with template parameters that don't match.
3172 if (!have_index_match && !query.GetSearchByMangledName()) {
3173 // Create a type matcher with a compiler context that is tuned for
3174 // -gsimple-template-names. We will use this for the index lookup and the
3175 // context matching, but will use the original "match" to insert matches
3176 // into if things match. The "match_simple" has a compiler context with
3177 // all template parameters removed to allow the names and context to match.
3178 // The UpdateCompilerContextForSimpleTemplateNames(...) will return true if
3179 // it trims any context items down by removing template parameter names.
3180 TypeQuery query_simple(query);
3182 auto type_basename_simple = query_simple.GetTypeBasename();
3183 // Copy our match's context and update the basename we are looking for
3184 // so we can use this only to compare the context correctly.
3185 m_index->GetTypesWithQuery(query_simple, [&](DWARFDIE die) {
3186 std::vector<CompilerContext> qualified_context =
3187 query.GetModuleSearch()
3188 ? die.GetDeclContext(/*derive_template_names=*/true)
3189 : die.GetTypeLookupContext(/*derive_template_names=*/true);
3190 if (query.ContextMatches(qualified_context))
3191 if (Type *matching_type = ResolveType(die, true, true))
3192 results.InsertUnique(matching_type->shared_from_this());
3193 if (!results.Done(query))
3195
3196 return IterationAction::Stop;
3197 });
3198 if (results.Done(query)) {
3199 if (log) {
3200 GetObjectFile()->GetModule()->LogMessage(
3201 log,
3202 "SymbolFileDWARF::FindTypes(type_basename=\"{0}\") => {1} "
3203 "(simplified as \"{2}\")",
3204 type_basename, results.GetTypeMap().GetSize(),
3205 type_basename_simple);
3206 }
3207 return;
3208 }
3209 }
3210 }
3211
3212 // Next search through the reachable Clang modules. This only applies for
3213 // DWARF objects compiled with -gmodules that haven't been processed by
3214 // dsymutil.
3216
3217 for (const auto &pair : m_external_type_modules) {
3218 if (ModuleSP external_module_sp = pair.second) {
3219 external_module_sp->FindTypes(query, results);
3220 if (results.Done(query)) {
3221 // We don't log the results here as they are already logged in the
3222 // nested FindTypes call
3223 return;
3224 }
3225 }
3226 }
3227}
3228
3231 const CompilerDeclContext &parent_decl_ctx,
3232 bool only_root_namespaces) {
3233 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3235
3236 if (log) {
3237 GetObjectFile()->GetModule()->LogMessage(
3238 log, "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\")",
3239 name.GetCString());
3240 }
3241
3242 CompilerDeclContext namespace_decl_ctx;
3243
3244 if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
3245 return namespace_decl_ctx;
3246
3247 m_index->GetNamespacesWithParents(name, parent_decl_ctx, [&](DWARFDIE die) {
3248 if (!DIEInDeclContext(parent_decl_ctx, die, only_root_namespaces))
3250
3251 DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU());
3252 if (!dwarf_ast)
3254
3255 namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
3256 if (namespace_decl_ctx.IsValid())
3257 return IterationAction::Stop;
3258
3260 });
3261
3262 if (log && namespace_decl_ctx) {
3263 GetObjectFile()->GetModule()->LogMessage(
3264 log,
3265 "SymbolFileDWARF::FindNamespace (sc, name=\"{0}\") => "
3266 "CompilerDeclContext({1:p}/{2:p}) \"{3}\"",
3267 name.GetCString(),
3268 static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
3269 static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
3270 namespace_decl_ctx.GetName().AsCString("<NULL>"));
3271 }
3272
3273 return namespace_decl_ctx;
3274}
3275
3277 bool resolve_function_context) {
3278 TypeSP type_sp;
3279 if (die) {
3280 Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
3281 if (type_ptr == nullptr) {
3282 SymbolContextScope *scope;
3283 if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
3284 scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
3285 else
3286 scope = GetObjectFile()->GetModule().get();
3287 assert(scope);
3288 SymbolContext sc(scope);
3289 const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
3290 while (parent_die != nullptr) {
3291 if (parent_die->Tag() == DW_TAG_subprogram)
3292 break;
3293 parent_die = parent_die->GetParent();
3294 }
3295 SymbolContext sc_backup = sc;
3296 if (resolve_function_context && parent_die != nullptr &&
3297 !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
3298 sc = sc_backup;
3299
3300 type_sp = ParseType(sc, die, nullptr);
3301 } else if (type_ptr != DIE_IS_BEING_PARSED) {
3302 // Get the original shared pointer for this type
3303 type_sp = type_ptr->shared_from_this();
3304 }
3305 }
3306 return type_sp;
3307}
3308
3311 // Elaborations of the search DIE cannot be its declaration context.
3312 llvm::SmallVector<std::pair<DWARFDIE, bool>, 4> worklist;
3313 if (orig_die)
3314 worklist.emplace_back(orig_die, /*is_elaboration=*/true);
3315
3316 // Bound the search on self-referential DWARF.
3317 llvm::SmallPtrSet<const DWARFDebugInfoEntry *, 4> seen;
3318
3319 while (!worklist.empty()) {
3320 auto [die, is_elaboration] = worklist.pop_back_val();
3321
3322 if (is_elaboration) {
3323 if (!seen.insert(die.GetDIE()).second)
3324 continue;
3325 } else {
3326 switch (die.Tag()) {
3327 case DW_TAG_compile_unit:
3328 case DW_TAG_partial_unit:
3329 case DW_TAG_namespace:
3330 case DW_TAG_structure_type:
3331 case DW_TAG_union_type:
3332 case DW_TAG_class_type:
3333 case DW_TAG_lexical_block:
3334 case DW_TAG_subprogram:
3335 return die;
3336 case DW_TAG_inlined_subroutine:
3337 if (DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin))
3338 return abs_die;
3339 break;
3340 default:
3341 break;
3342 }
3343 }
3344
3345 // Traverse specifications and abstract origins before parent contexts.
3346 if (DWARFDIE parent = die.GetParent())
3347 worklist.emplace_back(parent, /*is_elaboration=*/false);
3348 if (DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin))
3349 worklist.emplace_back(abs_die, /*is_elaboration=*/true);
3350 if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification))
3351 worklist.emplace_back(spec_die, /*is_elaboration=*/true);
3352 }
3353
3354 return DWARFDIE();
3355}
3356
3358 Symbol *objc_class_symbol = nullptr;
3359 if (m_objfile_sp) {
3360 Symtab *symtab = m_objfile_sp->GetSymtab();
3361 if (symtab) {
3362 objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
3363 objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
3365 }
3366 }
3367 return objc_class_symbol;
3368}
3369
3370// This function can be used when a DIE is found that is a forward declaration
3371// DIE and we want to try and find a type that has the complete definition.
3373 const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
3374
3375 TypeSP type_sp;
3376
3377 if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
3378 return type_sp;
3379
3380 m_index->GetCompleteObjCClass(
3381 type_name, must_be_implementation, [&](DWARFDIE type_die) {
3382 // Don't try and resolve the DIE we are looking for with the DIE
3383 // itself!
3384 if (type_die == die || !IsStructOrClassTag(type_die.Tag()))
3386
3387 if (must_be_implementation) {
3388 const bool try_resolving_type = type_die.GetAttributeValueAsUnsigned(
3389 DW_AT_APPLE_objc_complete_type, 0);
3390 if (!try_resolving_type)
3392 }
3393
3394 Type *resolved_type = ResolveType(type_die, false, true);
3395 if (!resolved_type || resolved_type == DIE_IS_BEING_PARSED)
3397
3399 "resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
3400 " (cu 0x%8.8" PRIx64 ")\n",
3401 die.GetID(),
3402 m_objfile_sp->GetFileSpec().GetFilename().AsCString("<Unknown>"),
3403 type_die.GetID(), type_cu->GetID());
3404
3405 if (die)
3406 GetDIEToType()[die.GetDIE()] = resolved_type;
3407 type_sp = resolved_type->shared_from_this();
3408 return IterationAction::Stop;
3409 });
3410 return type_sp;
3411}
3412
3415 const char *name = die.GetName();
3416 if (!name)
3417 return {};
3418 if (!die.GetAttributeValueAsUnsigned(DW_AT_declaration, 0))
3419 return die;
3420
3421 Progress progress(llvm::formatv("Searching definition DIE in {0}: '{1}'",
3422 GetObjectFile()->GetFileSpec().GetFilename(),
3423 name));
3424
3425 const dw_tag_t tag = die.Tag();
3426
3428 if (log) {
3429 GetObjectFile()->GetModule()->LogMessage(
3430 log,
3431 "SymbolFileDWARF::FindDefinitionDIE(tag={0} "
3432 "({1}), name='{2}')",
3433 DW_TAG_value_to_name(tag), tag, name);
3434 }
3435
3436 // Get the type system that we are looking to find a type for. We will
3437 // use this to ensure any matches we find are in a language that this
3438 // type system supports
3439 const LanguageType language = GetLanguage(*die.GetCU());
3440 TypeSystemSP type_system = nullptr;
3441 if (language != eLanguageTypeUnknown) {
3442 auto type_system_or_err = GetTypeSystemForLanguage(language);
3443 if (auto err = type_system_or_err.takeError()) {
3444 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3445 "Cannot get TypeSystem for language {1}: {0}",
3447 } else {
3448 type_system = *type_system_or_err;
3449 }
3450 }
3451
3452 // See comments below about -gsimple-template-names for why we attempt to
3453 // compute missing template parameter names.
3454 std::vector<std::string> template_params;
3455 DWARFDeclContext die_dwarf_decl_ctx;
3456 DWARFASTParser *dwarf_ast =
3457 type_system ? type_system->GetDWARFParser() : nullptr;
3458 for (DWARFDIE ctx_die = die; ctx_die && !isUnitType(ctx_die.Tag());
3459 ctx_die = ctx_die.GetParentDeclContextDIE()) {
3460 die_dwarf_decl_ctx.AppendDeclContext(ctx_die.Tag(), ctx_die.GetName());
3461 template_params.push_back(
3462 (ctx_die.IsStructUnionOrClass() && dwarf_ast)
3463 ? dwarf_ast->GetDIEClassTemplateParams(ctx_die)
3464 : "");
3465 }
3466 const bool any_template_params = llvm::any_of(
3467 template_params, [](llvm::StringRef p) { return !p.empty(); });
3468
3469 auto die_matches = [&](DWARFDIE type_die) {
3470 // Resolve the type if both have the same tag or {class, struct} tags.
3471 const bool tag_matches =
3472 type_die.Tag() == tag ||
3473 (IsStructOrClassTag(type_die.Tag()) && IsStructOrClassTag(tag));
3474 if (!tag_matches)
3475 return false;
3476 if (any_template_params) {
3477 size_t pos = 0;
3478 for (DWARFDIE ctx_die = type_die; ctx_die && !isUnitType(ctx_die.Tag()) &&
3479 pos < template_params.size();
3480 ctx_die = ctx_die.GetParentDeclContextDIE(), ++pos) {
3481 if (template_params[pos].empty())
3482 continue;
3483 if (template_params[pos] !=
3484 dwarf_ast->GetDIEClassTemplateParams(ctx_die))
3485 return false;
3486 }
3487 if (pos != template_params.size())
3488 return false;
3489 }
3490 return true;
3491 };
3492 DWARFDIE result;
3493 m_index->GetFullyQualifiedType(die_dwarf_decl_ctx, [&](DWARFDIE type_die) {
3494 // Make sure type_die's language matches the type system we are
3495 // looking for. We don't want to find a "Foo" type from Java if we
3496 // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
3497 if (type_system &&
3498 !type_system->SupportsLanguage(GetLanguage(*type_die.GetCU())))
3500
3501 if (!die_matches(type_die)) {
3502 if (log) {
3503 GetObjectFile()->GetModule()->LogMessage(
3504 log,
3505 "SymbolFileDWARF::FindDefinitionDIE(tag={0} ({1}), "
3506 "name='{2}') ignoring die={3:x16} ({4})",
3507 DW_TAG_value_to_name(tag), tag, name, type_die.GetOffset(),
3508 type_die.GetName());
3509 }
3511 }
3512
3513 if (log) {
3514 DWARFDeclContext type_dwarf_decl_ctx = type_die.GetDWARFDeclContext();
3515 GetObjectFile()->GetModule()->LogMessage(
3516 log,
3517 "SymbolFileDWARF::FindDefinitionTypeDIE(tag={0} ({1}), name='{2}') "
3518 "trying die={3:x16} ({4})",
3519 DW_TAG_value_to_name(tag), tag, name, type_die.GetOffset(),
3520 type_dwarf_decl_ctx.GetQualifiedName());
3521 }
3522
3523 result = type_die;
3524 return IterationAction::Stop;
3525 });
3526 return result;
3527}
3528
3530 bool *type_is_new_ptr) {
3531 if (!die)
3532 return {};
3533
3534 auto type_system_or_err = GetTypeSystemForLanguage(GetLanguage(*die.GetCU()));
3535 if (auto err = type_system_or_err.takeError()) {
3536 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
3537 "Unable to parse type: {0}");
3538 return {};
3539 }
3540 auto ts = *type_system_or_err;
3541 if (!ts)
3542 return {};
3543
3544 DWARFASTParser *dwarf_ast = ts->GetDWARFParser();
3545 if (!dwarf_ast)
3546 return {};
3547
3548 TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3549 if (type_sp) {
3550 if (die.Tag() == DW_TAG_subprogram) {
3551 std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3553 .AsCString(""));
3554 if (scope_qualified_name.size()) {
3555 m_function_scope_qualified_name_map[scope_qualified_name].insert(
3556 *die.GetDIERef());
3557 }
3558 }
3559 }
3560
3561 return type_sp;
3562}
3563
3565 const DWARFDIE &orig_die,
3566 bool parse_siblings, bool parse_children) {
3567 size_t types_added = 0;
3568 DWARFDIE die = orig_die;
3569
3570 while (die) {
3571 const dw_tag_t tag = die.Tag();
3572 bool type_is_new = false;
3573
3574 Tag dwarf_tag = static_cast<Tag>(tag);
3575
3576 // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3577 // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3578 // not.
3579 if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3580 ParseType(sc, die, &type_is_new);
3581
3582 if (type_is_new)
3583 ++types_added;
3584
3585 if (parse_children && die.HasChildren()) {
3586 if (die.Tag() == DW_TAG_subprogram) {
3587 SymbolContext child_sc(sc);
3588 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3589 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3590 } else
3591 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3592 }
3593
3594 if (parse_siblings)
3595 die = die.GetSibling();
3596 else
3597 die.Clear();
3598 }
3599 return types_added;
3600}
3601
3603 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3604 CompileUnit *comp_unit = func.GetCompileUnit();
3605 lldbassert(comp_unit);
3606
3607 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3608 if (!dwarf_cu)
3609 return 0;
3610
3611 size_t functions_added = 0;
3612 const dw_offset_t function_die_offset = DIERef(func.GetID()).die_offset();
3613 DWARFDIE function_die =
3614 dwarf_cu->GetNonSkeletonUnit().GetDIE(function_die_offset);
3615 if (function_die) {
3616 // We can't use the file address from the Function object as (in the OSO
3617 // case) it will already be remapped to the main module.
3618 if (llvm::Expected<llvm::DWARFAddressRangesVector> ranges =
3619 function_die.GetDIE()->GetAttributeAddressRanges(
3620 function_die.GetCU(),
3621 /*check_hi_lo_pc=*/true)) {
3622 if (ranges->empty())
3623 return 0;
3624 dw_addr_t function_file_addr = ranges->begin()->LowPC;
3625 if (function_file_addr != LLDB_INVALID_ADDRESS)
3626 ParseBlocksRecursive(*comp_unit, &func.GetBlock(false),
3627 function_die.GetFirstChild(), function_file_addr);
3628 } else {
3629 LLDB_LOG_ERRORV(GetLog(DWARFLog::DebugInfo), ranges.takeError(),
3630 "{1:x}: {0}", dwarf_cu->GetOffset());
3631 }
3632 }
3633
3634 return functions_added;
3635}
3636
3638 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3639 size_t types_added = 0;
3640 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3641 if (dwarf_cu) {
3642 DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3643 if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3644 SymbolContext sc;
3645 sc.comp_unit = &comp_unit;
3646 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3647 }
3648 }
3649
3650 return types_added;
3651}
3652
3654 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3655 if (sc.comp_unit != nullptr) {
3656 if (sc.function) {
3657 DWARFDIE function_die = GetDIE(sc.function->GetID());
3658
3659 dw_addr_t func_lo_pc = LLDB_INVALID_ADDRESS;
3660 if (llvm::Expected<llvm::DWARFAddressRangesVector> ranges =
3661 function_die.GetDIE()->GetAttributeAddressRanges(
3662 function_die.GetCU(), /*check_hi_lo_pc=*/true)) {
3663 if (!ranges->empty())
3664 func_lo_pc = ranges->begin()->LowPC;
3665 } else {
3666 LLDB_LOG_ERRORV(GetLog(DWARFLog::DebugInfo), ranges.takeError(),
3667 "DIE({1:x}): {0}", function_die.GetID());
3668 }
3669 if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3670 const size_t num_variables =
3671 ParseVariablesInFunctionContext(sc, function_die, func_lo_pc);
3672
3673 // Let all blocks know they have parse all their variables
3674 sc.function->GetBlock(false).SetDidParseVariables(true, true);
3675 return num_variables;
3676 }
3677 } else if (sc.comp_unit) {
3678 DWARFUnit *dwarf_cu = DebugInfo().GetUnitAtIndex(sc.comp_unit->GetID());
3679
3680 if (dwarf_cu == nullptr)
3681 return 0;
3682
3683 uint32_t vars_added = 0;
3684 VariableListSP variables(sc.comp_unit->GetVariableList(false));
3685
3686 if (variables.get() == nullptr) {
3687 variables = std::make_shared<VariableList>();
3688 sc.comp_unit->SetVariableList(variables);
3689
3690 m_index->GetGlobalVariables(*dwarf_cu, [&](DWARFDIE die) {
3691 VariableSP var_sp(ParseVariableDIECached(sc, die));
3692 if (var_sp) {
3693 variables->AddVariableIfUnique(var_sp);
3694 ++vars_added;
3695 }
3697 });
3698 }
3699 return vars_added;
3700 }
3701 }
3702 return 0;
3703}
3704
3706 const DWARFDIE &die) {
3707 if (!die)
3708 return nullptr;
3709
3710 DIEToVariableSP &die_to_variable = die.GetDWARF()->GetDIEToVariable();
3711
3712 VariableSP var_sp = die_to_variable[die.GetDIE()];
3713 if (var_sp)
3714 return var_sp;
3715
3716 var_sp = ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS);
3717 if (var_sp) {
3718 die_to_variable[die.GetDIE()] = var_sp;
3719 if (DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification))
3720 die_to_variable[spec_die.GetDIE()] = var_sp;
3721 }
3722 return var_sp;
3723}
3724
3725/// Walks transparent type wrappers following DW_AT_type and returns
3726/// the first DW_AT_byte_size encountered along the chain.
3727static std::optional<uint64_t> GetByteSizeFromTypeDIE(DWARFDIE die,
3728 unsigned max_depth = 64) {
3729 // Bound the walk to guard against malformed/cyclic DWARF.
3730 if (!die || !max_depth)
3731 return std::nullopt;
3732
3733 if (std::optional<uint64_t> byte_size =
3734 die.GetAttributeValueAsOptionalUnsigned(DW_AT_byte_size))
3735 return byte_size;
3736
3737 switch (die.Tag()) {
3738 case DW_TAG_const_type:
3739 case DW_TAG_volatile_type:
3740 case DW_TAG_restrict_type:
3741 case DW_TAG_atomic_type:
3742 case DW_TAG_typedef:
3743 if (DWARFDIE next = die.GetAttributeValueAsReferenceDIE(DW_AT_type))
3744 return GetByteSizeFromTypeDIE(next, max_depth - 1);
3745 break;
3746 default:
3747 break;
3748 }
3749 return std::nullopt;
3750}
3751
3752/// Creates a DWARFExpressionList from an DW_AT_location form_value.
3754 ModuleSP module,
3755 const DWARFDIE &die,
3756 const addr_t func_low_pc) {
3757 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3758 const DWARFDataExtractor &data = die.GetData();
3759
3760 uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
3761 uint64_t block_length = form_value.Unsigned();
3762 return DWARFExpressionList(
3763 module, DataExtractor(data, block_offset, block_length), die.GetCU());
3764 }
3765
3766 DWARFExpressionList location_list(module, DWARFExpression(), die.GetCU());
3767 DataExtractor data = die.GetCU()->GetLocationData();
3768 dw_offset_t offset = form_value.Unsigned();
3769 if (form_value.Form() == DW_FORM_loclistx)
3770 offset = die.GetCU()->GetLoclistOffset(offset).value_or(-1);
3771 if (data.ValidOffset(offset)) {
3772 data = DataExtractor(data, offset, data.GetByteSize() - offset);
3773 const DWARFUnit *dwarf_cu = form_value.GetUnit();
3774 if (dwarf_cu->ParseDWARFLocationList(data, location_list))
3775 location_list.SetFuncFileAddress(func_low_pc);
3776 }
3777
3778 return location_list;
3779}
3780
3781/// Creates a DWARFExpressionList from an DW_AT_const_value. This is either a
3782/// block form, or a string, or a data form. For data forms, this returns an
3783/// empty list, as we cannot initialize it properly without a SymbolFileType.
3784static DWARFExpressionList
3786 const DWARFDIE &die) {
3787 const DWARFDataExtractor &debug_info_data = die.GetData();
3788 if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3789 // Retrieve the value as a block expression.
3790 uint64_t block_offset =
3791 form_value.BlockData() - debug_info_data.GetDataStart();
3792 uint64_t block_length = form_value.Unsigned();
3793 return DWARFExpressionList(
3794 module, DataExtractor(debug_info_data, block_offset, block_length),
3795 die.GetCU());
3796 }
3797 if (const char *str = form_value.AsCString())
3798 return DWARFExpressionList(module,
3799 DataExtractor(str, strlen(str) + 1,
3800 die.GetCU()->GetByteOrder(),
3801 die.GetCU()->GetAddressByteSize()),
3802 die.GetCU());
3803 return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3804}
3805
3806/// Global variables that are not initialized may have their address set to
3807/// zero. Since multiple variables may have this address, we cannot apply the
3808/// OSO relink address approach we normally use.
3809/// However, the executable will have a matching symbol with a good address;
3810/// this function attempts to find the correct address by looking into the
3811/// executable's symbol table. If it succeeds, the expr_list is updated with
3812/// the new address and the executable's symbol is returned.
3814 SymbolFileDWARFDebugMap &debug_map_symfile, llvm::StringRef name,
3815 DWARFExpressionList &expr_list, const DWARFDIE &die) {
3816 ObjectFile *debug_map_objfile = debug_map_symfile.GetObjectFile();
3817 if (!debug_map_objfile)
3818 return nullptr;
3819
3820 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3821 if (!debug_map_symtab)
3822 return nullptr;
3823 Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType(
3826 if (!exe_symbol || !exe_symbol->ValueIsAddress())
3827 return nullptr;
3828 const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress();
3829 if (exe_file_addr == LLDB_INVALID_ADDRESS)
3830 return nullptr;
3831
3832 DWARFExpression *location = expr_list.GetMutableExpressionAtAddress();
3833 if (location->Update_DW_OP_addr(die.GetCU(), exe_file_addr))
3834 return exe_symbol;
3835 return nullptr;
3836}
3837
3839 const DWARFDIE &die,
3840 const lldb::addr_t func_low_pc) {
3841 if (die.GetDWARF() != this)
3842 return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3843
3844 if (!die)
3845 return nullptr;
3846
3847 const dw_tag_t tag = die.Tag();
3848 ModuleSP module = GetObjectFile()->GetModule();
3849
3850 if (tag != DW_TAG_variable && tag != DW_TAG_constant &&
3851 tag != DW_TAG_member && (tag != DW_TAG_formal_parameter || !sc.function))
3852 return nullptr;
3853
3854 DWARFAttributes attributes = die.GetAttributes();
3855 const char *name = nullptr;
3856 const char *mangled = nullptr;
3857 Declaration decl;
3858 DWARFFormValue type_die_form;
3859 bool is_external = false;
3860 bool is_artificial = false;
3861 std::optional<uint64_t> tag_offset = std::nullopt;
3862 DWARFFormValue const_value_form, location_form;
3863 Variable::RangeList scope_ranges;
3864
3865 for (size_t i = 0; i < attributes.Size(); ++i) {
3866 dw_attr_t attr = attributes.AttributeAtIndex(i);
3867 DWARFFormValue form_value;
3868
3869 if (!attributes.ExtractFormValueAtIndex(i, form_value))
3870 continue;
3871 switch (attr) {
3872 case DW_AT_LLVM_tag_offset:
3873 tag_offset = form_value.Unsigned();
3874 break;
3875 case DW_AT_decl_file:
3876 decl.SetFile(
3877 attributes.CompileUnitAtIndex(i)->GetFile(form_value.Unsigned()));
3878 break;
3879 case DW_AT_decl_line:
3880 decl.SetLine(form_value.Unsigned());
3881 break;
3882 case DW_AT_decl_column:
3883 decl.SetColumn(form_value.Unsigned());
3884 break;
3885 case DW_AT_name:
3886 name = form_value.AsCString();
3887 break;
3888 case DW_AT_linkage_name:
3889 case DW_AT_MIPS_linkage_name:
3890 mangled = form_value.AsCString();
3891 break;
3892 case DW_AT_type:
3893 // DW_AT_type on declaration may be less accurate than
3894 // that of definition, so don't overwrite it.
3895 if (!type_die_form.IsValid())
3896 type_die_form = form_value;
3897 break;
3898 case DW_AT_external:
3899 is_external = form_value.Boolean();
3900 break;
3901 case DW_AT_const_value:
3902 const_value_form = form_value;
3903 break;
3904 case DW_AT_location:
3905 location_form = form_value;
3906 break;
3907 case DW_AT_start_scope:
3908 // TODO: Implement this.
3909 break;
3910 case DW_AT_artificial:
3911 is_artificial = form_value.Boolean();
3912 break;
3913 case DW_AT_declaration:
3914 case DW_AT_description:
3915 case DW_AT_endianity:
3916 case DW_AT_segment:
3917 case DW_AT_specification:
3918 case DW_AT_visibility:
3919 default:
3920 case DW_AT_abstract_origin:
3921 case DW_AT_sibling:
3922 break;
3923 }
3924 }
3925
3926 // Prefer DW_AT_location over DW_AT_const_value. Both can be emitted e.g.
3927 // for static constexpr member variables -- DW_AT_const_value and
3928 // DW_AT_location will both be present in the DIE defining the member.
3929 bool location_is_const_value_data =
3930 const_value_form.IsValid() && !location_form.IsValid();
3931
3932 DWARFExpressionList location_list = [&] {
3933 if (location_form.IsValid())
3934 return GetExprListFromAtLocation(location_form, module, die, func_low_pc);
3935 if (const_value_form.IsValid())
3936 return GetExprListFromAtConstValue(const_value_form, module, die);
3937 return DWARFExpressionList(module, DWARFExpression(), die.GetCU());
3938 }();
3939
3940 const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3941 const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3942 const dw_tag_t parent_tag = sc_parent_die.Tag();
3943 bool is_static_member = (parent_tag == DW_TAG_compile_unit ||
3944 parent_tag == DW_TAG_partial_unit) &&
3945 (parent_context_die.Tag() == DW_TAG_class_type ||
3946 parent_context_die.Tag() == DW_TAG_structure_type);
3947
3949 SymbolContextScope *symbol_context_scope = nullptr;
3950
3951 bool has_explicit_mangled = mangled != nullptr;
3952 if (!mangled) {
3953 // LLDB relies on the mangled name (DW_TAG_linkage_name or
3954 // DW_AT_MIPS_linkage_name) to generate fully qualified names
3955 // of global variables with commands like "frame var j". For
3956 // example, if j were an int variable holding a value 4 and
3957 // declared in a namespace B which in turn is contained in a
3958 // namespace A, the command "frame var j" returns
3959 // "(int) A::B::j = 4".
3960 // If the compiler does not emit a linkage name, we should be
3961 // able to generate a fully qualified name from the
3962 // declaration context.
3963 if ((parent_tag == DW_TAG_compile_unit ||
3964 parent_tag == DW_TAG_partial_unit) &&
3966 mangled = die.GetDWARFDeclContext()
3968 .GetCString();
3969 }
3970
3971 if (tag == DW_TAG_formal_parameter)
3973 else {
3974 // DWARF doesn't specify if a DW_TAG_variable is a local, global
3975 // or static variable, so we have to do a little digging:
3976 // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3977 // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3978 // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3979 // Clang likes to combine small global variables into the same symbol
3980 // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3981 // so we need to look through the whole expression.
3982 bool has_explicit_location = location_form.IsValid();
3983 bool is_static_lifetime =
3984 has_explicit_mangled ||
3985 (has_explicit_location && !location_list.IsValid());
3986 // Check if the location has a DW_OP_addr with any address value...
3987 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3988 if (!location_is_const_value_data) {
3989 if (const DWARFExpression *location =
3990 location_list.GetAlwaysValidExpr()) {
3991 if (auto maybe_location_DW_OP_addr =
3992 location->GetLocation_DW_OP_addr(location_form.GetUnit())) {
3993 location_DW_OP_addr = *maybe_location_DW_OP_addr;
3994 } else {
3995 StreamString strm;
3996 location->DumpLocation(&strm, eDescriptionLevelFull, nullptr);
3997 GetObjectFile()->GetModule()->ReportError(
3998 "{0:x16}: {1} ({2}) has an invalid location: {3}: {4}",
3999 die.GetOffset(), DW_TAG_value_to_name(die.Tag()), die.Tag(),
4000 llvm::fmt_consume(maybe_location_DW_OP_addr.takeError()),
4001 strm.GetData());
4002 }
4003 }
4004 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
4005 is_static_lifetime = true;
4006 }
4007 SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
4008 if (debug_map_symfile)
4009 // Set the module of the expression to the linked module
4010 // instead of the object file so the relocated address can be
4011 // found there.
4012 location_list.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
4013
4014 if (is_static_lifetime) {
4015 if (is_external)
4017 else
4019
4020 if (debug_map_symfile) {
4021 bool linked_oso_file_addr = false;
4022
4023 if (is_external && location_DW_OP_addr == 0) {
4024 if (Symbol *exe_symbol = fixupExternalAddrZeroVariable(
4025 *debug_map_symfile, mangled ? mangled : name, location_list,
4026 die)) {
4027 linked_oso_file_addr = true;
4028 symbol_context_scope = exe_symbol;
4029 }
4030 }
4031
4032 if (!linked_oso_file_addr) {
4033 // The DW_OP_addr is not zero, but it contains a .o file address
4034 // which needs to be linked up correctly.
4035 const lldb::addr_t exe_file_addr =
4036 debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
4037 if (exe_file_addr != LLDB_INVALID_ADDRESS) {
4038 // Update the file address for this variable
4039 DWARFExpression *location =
4040 location_list.GetMutableExpressionAtAddress();
4041 location->Update_DW_OP_addr(die.GetCU(), exe_file_addr);
4042 } else {
4043 // Variable didn't make it into the final executable
4044 return nullptr;
4045 }
4046 }
4047 }
4048 } else {
4049 if (location_is_const_value_data &&
4050 die.GetDIE()->IsGlobalOrStaticScopeVariable())
4052 else {
4054 if (debug_map_symfile) {
4055 // We need to check for TLS addresses that we need to fixup
4056 if (location_list.ContainsThreadLocalStorage()) {
4057 location_list.LinkThreadLocalStorage(
4058 debug_map_symfile->GetObjectFile()->GetModule(),
4059 [this, debug_map_symfile](
4060 lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
4061 return debug_map_symfile->LinkOSOFileAddress(
4062 this, unlinked_file_addr);
4063 });
4065 }
4066 }
4067 }
4068 }
4069 }
4070
4071 if (symbol_context_scope == nullptr) {
4072 switch (parent_tag) {
4073 case DW_TAG_subprogram:
4074 case DW_TAG_inlined_subroutine:
4075 case DW_TAG_lexical_block:
4076 if (sc.function) {
4077 symbol_context_scope =
4078 sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
4079 if (symbol_context_scope == nullptr)
4080 symbol_context_scope = sc.function;
4081 }
4082 break;
4083
4084 default:
4085 symbol_context_scope = sc.comp_unit;
4086 break;
4087 }
4088 }
4089
4090 if (!symbol_context_scope) {
4091 // Not ready to parse this variable yet. It might be a global or static
4092 // variable that is in a function scope and the function in the symbol
4093 // context wasn't filled in yet
4094 return nullptr;
4095 }
4096
4097 auto type_sp = std::make_shared<SymbolFileType>(
4098 *this, type_die_form.Reference().GetID());
4099
4100 bool use_type_size_for_value =
4101 location_is_const_value_data &&
4102 DWARFFormValue::IsDataForm(const_value_form.Form());
4103 if (use_type_size_for_value) {
4104 std::optional<uint64_t> byte_size;
4105 if (Type *t = type_sp->GetType())
4106 byte_size = llvm::expectedToOptional(t->GetByteSize(nullptr));
4107
4108 // Some TypeSystems (such as Swift) cannot determine a type's byte
4109 // size without an execution context (e.g. types whose layout
4110 // depends on runtime metadata). In those cases the debug info
4111 // might still carry the static size of the value's box, which is
4112 // enough if the value is a constant.
4113 if (!byte_size)
4114 byte_size = GetByteSizeFromTypeDIE(type_die_form.Reference());
4115
4116 if (byte_size) {
4117 DWARFExpression *location = location_list.GetMutableExpressionAtAddress();
4118 location->UpdateValue(const_value_form.Unsigned(), *byte_size,
4119 die.GetCU()->GetAddressByteSize());
4120 }
4121 }
4122
4123 return std::make_shared<Variable>(
4124 die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
4125 scope_ranges, &decl, location_list, is_external, is_artificial,
4126 location_is_const_value_data, is_static_member, tag_offset);
4127}
4128
4131 const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
4132 // Give the concrete function die specified by "func_die_offset", find the
4133 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4134 // to "spec_block_die_offset"
4135 return FindBlockContainingSpecification(GetDIE(func_die_ref),
4136 spec_block_die_offset);
4137}
4138
4141 const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
4142 if (die) {
4143 switch (die.Tag()) {
4144 case DW_TAG_subprogram:
4145 case DW_TAG_inlined_subroutine:
4146 case DW_TAG_lexical_block: {
4147 if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
4148 spec_block_die_offset)
4149 return die;
4150
4151 if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
4152 spec_block_die_offset)
4153 return die;
4154 } break;
4155 default:
4156 break;
4157 }
4158
4159 // Give the concrete function die specified by "func_die_offset", find the
4160 // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4161 // to "spec_block_die_offset"
4162 for (DWARFDIE child_die : die.children()) {
4163 DWARFDIE result_die =
4164 FindBlockContainingSpecification(child_die, spec_block_die_offset);
4165 if (result_die)
4166 return result_die;
4167 }
4168 }
4169
4170 return DWARFDIE();
4171}
4172
4174 const SymbolContext &sc, const DWARFDIE &die,
4175 VariableList &cc_variable_list) {
4176 if (!die)
4177 return;
4178
4179 dw_tag_t tag = die.Tag();
4180 if (tag != DW_TAG_variable && tag != DW_TAG_constant && tag != DW_TAG_member)
4181 return;
4182
4183 // Check to see if we have already parsed this variable or constant?
4184 VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
4185 if (var_sp) {
4186 cc_variable_list.AddVariableIfUnique(var_sp);
4187 return;
4188 }
4189
4190 // We haven't parsed the variable yet, lets do that now. Also, let us include
4191 // the variable in the relevant compilation unit's variable list, if it
4192 // exists.
4193 VariableListSP variable_list_sp;
4194 DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
4195 dw_tag_t parent_tag = sc_parent_die.Tag();
4196 switch (parent_tag) {
4197 case DW_TAG_compile_unit:
4198 case DW_TAG_partial_unit:
4199 if (sc.comp_unit != nullptr) {
4200 variable_list_sp = sc.comp_unit->GetVariableList(false);
4201 } else {
4202 GetObjectFile()->GetModule()->ReportError(
4203 "parent {0:x8} {1} ({2}) with no valid compile unit in "
4204 "symbol context for {3:x8} {4} ({5}).\n",
4205 sc_parent_die.GetID(), DW_TAG_value_to_name(sc_parent_die.Tag()),
4206 sc_parent_die.Tag(), die.GetID(), DW_TAG_value_to_name(die.Tag()),
4207 die.Tag());
4208 return;
4209 }
4210 break;
4211
4212 default:
4214 "{0} '{1}' ({2:x8}) is not a global variable - ignoring", tag,
4215 die.GetName(), die.GetID());
4216 return;
4217 }
4218
4219 var_sp = ParseVariableDIECached(sc, die);
4220 if (!var_sp)
4221 return;
4222
4223 cc_variable_list.AddVariableIfUnique(var_sp);
4224 if (variable_list_sp)
4225 variable_list_sp->AddVariableIfUnique(var_sp);
4226}
4227
4230 DIEArray &&variable_dies) {
4231 // DW_TAG_inline_subroutine objects may omit DW_TAG_formal_parameter in
4232 // instances of the function when they are unused (i.e., the parameter's
4233 // location list would be empty). The current DW_TAG_inline_subroutine may
4234 // refer to another DW_TAG_subprogram that might actually have the definitions
4235 // of the parameters and we need to include these so they show up in the
4236 // variables for this function (for example, in a stack trace). Let us try to
4237 // find the abstract subprogram that might contain the parameter definitions
4238 // and merge with the concrete parameters.
4239
4240 // Nothing to merge if the block is not an inlined function.
4241 if (block_die.Tag() != DW_TAG_inlined_subroutine) {
4242 return std::move(variable_dies);
4243 }
4244
4245 // Nothing to merge if the block does not have abstract parameters.
4246 DWARFDIE abs_die = block_die.GetReferencedDIE(DW_AT_abstract_origin);
4247 if (!abs_die || abs_die.Tag() != DW_TAG_subprogram ||
4248 !abs_die.HasChildren()) {
4249 return std::move(variable_dies);
4250 }
4251
4252 // For each abstract parameter, if we have its concrete counterpart, insert
4253 // it. Otherwise, insert the abstract parameter.
4254 DIEArray::iterator concrete_it = variable_dies.begin();
4255 DWARFDIE abstract_child = abs_die.GetFirstChild();
4256 DIEArray merged;
4257 bool did_merge_abstract = false;
4258 for (; abstract_child; abstract_child = abstract_child.GetSibling()) {
4259 if (abstract_child.Tag() == DW_TAG_formal_parameter) {
4260 if (concrete_it == variable_dies.end() ||
4261 GetDIE(*concrete_it).Tag() != DW_TAG_formal_parameter) {
4262 // We arrived at the end of the concrete parameter list, so all
4263 // the remaining abstract parameters must have been omitted.
4264 // Let us insert them to the merged list here.
4265 merged.push_back(*abstract_child.GetDIERef());
4266 did_merge_abstract = true;
4267 continue;
4268 }
4269
4270 DWARFDIE origin_of_concrete =
4271 GetDIE(*concrete_it).GetReferencedDIE(DW_AT_abstract_origin);
4272 if (origin_of_concrete == abstract_child) {
4273 // The current abstract parameter is the origin of the current
4274 // concrete parameter, just push the concrete parameter.
4275 merged.push_back(*concrete_it);
4276 ++concrete_it;
4277 } else {
4278 // Otherwise, the parameter must have been omitted from the concrete
4279 // function, so insert the abstract one.
4280 merged.push_back(*abstract_child.GetDIERef());
4281 did_merge_abstract = true;
4282 }
4283 }
4284 }
4285
4286 // Shortcut if no merging happened.
4287 if (!did_merge_abstract)
4288 return std::move(variable_dies);
4289
4290 // We inserted all the abstract parameters (or their concrete counterparts).
4291 // Let us insert all the remaining concrete variables to the merged list.
4292 // During the insertion, let us check there are no remaining concrete
4293 // formal parameters. If that's the case, then just bailout from the merge -
4294 // the variable list is malformed.
4295 for (; concrete_it != variable_dies.end(); ++concrete_it) {
4296 if (GetDIE(*concrete_it).Tag() == DW_TAG_formal_parameter) {
4297 return std::move(variable_dies);
4298 }
4299 merged.push_back(*concrete_it);
4300 }
4301 return merged;
4302}
4303
4305 const SymbolContext &sc, const DWARFDIE &die,
4306 const lldb::addr_t func_low_pc) {
4307 if (!die || !sc.function)
4308 return 0;
4309
4310 DIEArray dummy_block_variables; // The recursive call should not add anything
4311 // to this vector because |die| should be a
4312 // subprogram, so all variables will be added
4313 // to the subprogram's list.
4314 return ParseVariablesInFunctionContextRecursive(sc, die, func_low_pc,
4315 dummy_block_variables);
4316}
4317
4318// This method parses all the variables in the blocks in the subtree of |die|,
4319// and inserts them to the variable list for all the nested blocks.
4320// The uninserted variables for the current block are accumulated in
4321// |accumulator|.
4323 const lldb_private::SymbolContext &sc, const DWARFDIE &die,
4324 lldb::addr_t func_low_pc, DIEArray &accumulator) {
4325 size_t vars_added = 0;
4326 dw_tag_t tag = die.Tag();
4327
4328 if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
4329 (tag == DW_TAG_formal_parameter)) {
4330 accumulator.push_back(*die.GetDIERef());
4331 }
4332
4333 switch (tag) {
4334 case DW_TAG_subprogram:
4335 case DW_TAG_inlined_subroutine:
4336 case DW_TAG_lexical_block: {
4337 // If we start a new block, compute a new block variable list and recurse.
4338 Block *block =
4339 sc.function->GetBlock(/*can_create=*/true).FindBlockByID(die.GetID());
4340 if (block == nullptr) {
4341 // This must be a specification or abstract origin with a
4342 // concrete block counterpart in the current function. We need
4343 // to find the concrete block so we can correctly add the
4344 // variable to it.
4345 const DWARFDIE concrete_block_die = FindBlockContainingSpecification(
4346 GetDIE(sc.function->GetID()), die.GetOffset());
4347 if (concrete_block_die)
4348 block = sc.function->GetBlock(/*can_create=*/true)
4349 .FindBlockByID(concrete_block_die.GetID());
4350 }
4351
4352 if (block == nullptr)
4353 return 0;
4354
4355 const bool can_create = false;
4356 VariableListSP block_variable_list_sp =
4357 block->GetBlockVariableList(can_create);
4358 if (block_variable_list_sp.get() == nullptr) {
4359 block_variable_list_sp = std::make_shared<VariableList>();
4360 block->SetVariableList(block_variable_list_sp);
4361 }
4362
4363 DIEArray block_variables;
4364 for (DWARFDIE child = die.GetFirstChild(); child;
4365 child = child.GetSibling()) {
4367 sc, child, func_low_pc, block_variables);
4368 }
4369 block_variables =
4370 MergeBlockAbstractParameters(die, std::move(block_variables));
4371 vars_added += PopulateBlockVariableList(*block_variable_list_sp, sc,
4372 block_variables, func_low_pc);
4373 break;
4374 }
4375
4376 default:
4377 // Recurse to children with the same variable accumulator.
4378 for (DWARFDIE child = die.GetFirstChild(); child;
4379 child = child.GetSibling()) {
4381 sc, child, func_low_pc, accumulator);
4382 }
4383 break;
4384 }
4385
4386 return vars_added;
4387}
4388
4390 VariableList &variable_list, const lldb_private::SymbolContext &sc,
4391 llvm::ArrayRef<DIERef> variable_dies, lldb::addr_t func_low_pc) {
4392 // Parse the variable DIEs and insert them to the list.
4393 for (auto &die : variable_dies) {
4394 if (VariableSP var_sp = ParseVariableDIE(sc, GetDIE(die), func_low_pc)) {
4395 variable_list.AddVariableIfUnique(var_sp);
4396 }
4397 }
4398 return variable_dies.size();
4399}
4400
4401/// Collect call site parameters in a DW_TAG_call_site DIE.
4404 CallSiteParameterArray parameters;
4405 for (DWARFDIE child : call_site_die.children()) {
4406 if (child.Tag() != DW_TAG_call_site_parameter &&
4407 child.Tag() != DW_TAG_GNU_call_site_parameter)
4408 continue;
4409
4410 std::optional<DWARFExpressionList> LocationInCallee;
4411 std::optional<DWARFExpressionList> LocationInCaller;
4412
4413 DWARFAttributes attributes = child.GetAttributes();
4414
4415 // Parse the location at index \p attr_index within this call site parameter
4416 // DIE, or return std::nullopt on failure.
4417 auto parse_simple_location =
4418 [&](int attr_index) -> std::optional<DWARFExpressionList> {
4419 DWARFFormValue form_value;
4420 if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
4421 return {};
4422 if (!DWARFFormValue::IsBlockForm(form_value.Form()))
4423 return {};
4424 auto data = child.GetData();
4425 uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
4426 uint64_t block_length = form_value.Unsigned();
4427 return DWARFExpressionList(
4428 module, DataExtractor(data, block_offset, block_length),
4429 child.GetCU());
4430 };
4431
4432 for (size_t i = 0; i < attributes.Size(); ++i) {
4433 dw_attr_t attr = attributes.AttributeAtIndex(i);
4434 if (attr == DW_AT_location)
4435 LocationInCallee = parse_simple_location(i);
4436 if (attr == DW_AT_call_value || attr == DW_AT_GNU_call_site_value)
4437 LocationInCaller = parse_simple_location(i);
4438 }
4439
4440 if (LocationInCallee && LocationInCaller) {
4441 CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
4442 parameters.push_back(param);
4443 }
4444 }
4445 return parameters;
4446}
4447
4448/// Collect call graph edges present in a function DIE.
4449std::vector<std::unique_ptr<lldb_private::CallEdge>>
4451 // Check if the function has a supported call site-related attribute.
4452 // TODO: In the future it may be worthwhile to support call_all_source_calls.
4453 bool has_call_edges =
4454 function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0) ||
4455 function_die.GetAttributeValueAsUnsigned(DW_AT_GNU_all_call_sites, 0);
4456 if (!has_call_edges)
4457 return {};
4458
4459 Log *log = GetLog(LLDBLog::Step);
4460 LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
4461 function_die.GetPubname());
4462
4463 // Scan the DIE for TAG_call_site entries.
4464 // TODO: A recursive scan of all blocks in the subprogram is needed in order
4465 // to be DWARF5-compliant. This may need to be done lazily to be performant.
4466 // For now, assume that all entries are nested directly under the subprogram
4467 // (this is the kind of DWARF LLVM produces) and parse them eagerly.
4468 std::vector<std::unique_ptr<CallEdge>> call_edges;
4469 for (DWARFDIE child : function_die.children()) {
4470 if (child.Tag() != DW_TAG_call_site && child.Tag() != DW_TAG_GNU_call_site)
4471 continue;
4472
4473 std::optional<DWARFDIE> call_origin;
4474 std::optional<DWARFExpressionList> call_target;
4475 addr_t return_pc = LLDB_INVALID_ADDRESS;
4476 addr_t call_inst_pc = LLDB_INVALID_ADDRESS;
4478 bool tail_call = false;
4479
4480 // Second DW_AT_low_pc may come from DW_TAG_subprogram referenced by
4481 // DW_TAG_GNU_call_site's DW_AT_abstract_origin overwriting our 'low_pc'.
4482 // So do not inherit attributes from DW_AT_abstract_origin.
4483 DWARFAttributes attributes = child.GetAttributes(DWARFDIE::Recurse::no);
4484 for (size_t i = 0; i < attributes.Size(); ++i) {
4485 DWARFFormValue form_value;
4486 if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
4487 LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
4488 break;
4489 }
4490
4491 dw_attr_t attr = attributes.AttributeAtIndex(i);
4492
4493 if (attr == DW_AT_call_tail_call || attr == DW_AT_GNU_tail_call)
4494 tail_call = form_value.Boolean();
4495
4496 // Extract DW_AT_call_origin (the call target's DIE).
4497 if (attr == DW_AT_call_origin || attr == DW_AT_abstract_origin) {
4498 call_origin = form_value.Reference();
4499 if (!call_origin->IsValid()) {
4500 LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
4501 function_die.GetPubname());
4502 break;
4503 }
4504 }
4505
4506 if (attr == DW_AT_low_pc)
4507 low_pc = form_value.Address();
4508
4509 // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
4510 // available. It should only ever be unavailable for tail call edges, in
4511 // which case use LLDB_INVALID_ADDRESS.
4512 if (attr == DW_AT_call_return_pc)
4513 return_pc = form_value.Address();
4514
4515 // Extract DW_AT_call_pc (the PC at the call/branch instruction). It
4516 // should only ever be unavailable for non-tail calls, in which case use
4517 // LLDB_INVALID_ADDRESS.
4518 if (attr == DW_AT_call_pc)
4519 call_inst_pc = form_value.Address();
4520
4521 // Extract DW_AT_call_target (the location of the address of the indirect
4522 // call).
4523 if (attr == DW_AT_call_target || attr == DW_AT_GNU_call_site_target) {
4524 if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
4525 LLDB_LOG(log,
4526 "CollectCallEdges: AT_call_target does not have block form");
4527 break;
4528 }
4529
4530 auto data = child.GetData();
4531 uint64_t block_offset = form_value.BlockData() - data.GetDataStart();
4532 uint64_t block_length = form_value.Unsigned();
4533 call_target = DWARFExpressionList(
4534 module, DataExtractor(data, block_offset, block_length),
4535 child.GetCU());
4536 }
4537 }
4538 if (!call_origin && !call_target) {
4539 LLDB_LOG(log, "CollectCallEdges: call site without any call target");
4540 continue;
4541 }
4542
4543 addr_t caller_address;
4544 CallEdge::AddrType caller_address_type;
4545 if (return_pc != LLDB_INVALID_ADDRESS) {
4546 caller_address = return_pc;
4547 caller_address_type = CallEdge::AddrType::AfterCall;
4548 } else if (low_pc != LLDB_INVALID_ADDRESS) {
4549 caller_address = low_pc;
4550 caller_address_type = CallEdge::AddrType::AfterCall;
4551 } else if (call_inst_pc != LLDB_INVALID_ADDRESS) {
4552 caller_address = call_inst_pc;
4553 caller_address_type = CallEdge::AddrType::Call;
4554 } else {
4555 LLDB_LOG(log, "CollectCallEdges: No caller address");
4556 continue;
4557 }
4558 // Adjust any PC forms. It needs to be fixed up if the main executable
4559 // contains a debug map (i.e. pointers to object files), because we need a
4560 // file address relative to the executable's text section.
4561 caller_address = FixupAddress(caller_address);
4562
4563 // Extract call site parameters.
4564 CallSiteParameterArray parameters =
4565 CollectCallSiteParameters(module, child);
4566
4567 std::unique_ptr<CallEdge> edge;
4568 if (call_origin) {
4569 LLDB_LOG(log,
4570 "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x}) "
4571 "(call-PC: {2:x})",
4572 call_origin->GetPubname(), return_pc, call_inst_pc);
4573 edge = std::make_unique<DirectCallEdge>(
4574 call_origin->GetMangledName(), caller_address_type, caller_address,
4575 tail_call, std::move(parameters));
4576 } else {
4577 if (log) {
4578 StreamString call_target_desc;
4579 call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
4580 nullptr);
4581 LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
4582 call_target_desc.GetString());
4583 }
4584 edge = std::make_unique<IndirectCallEdge>(
4585 *call_target, caller_address_type, caller_address, tail_call,
4586 std::move(parameters));
4587 }
4588
4589 if (log && parameters.size()) {
4590 for (const CallSiteParameter &param : parameters) {
4591 StreamString callee_loc_desc, caller_loc_desc;
4592 param.LocationInCallee.GetDescription(&callee_loc_desc,
4593 eDescriptionLevelBrief, nullptr);
4594 param.LocationInCaller.GetDescription(&caller_loc_desc,
4595 eDescriptionLevelBrief, nullptr);
4596 LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
4597 callee_loc_desc.GetString(), caller_loc_desc.GetString());
4598 }
4599 }
4600
4601 call_edges.push_back(std::move(edge));
4602 }
4603 return call_edges;
4604}
4605
4606std::vector<std::unique_ptr<lldb_private::CallEdge>>
4608 // ParseCallEdgesInFunction must be called at the behest of an exclusively
4609 // locked lldb::Function instance. Storage for parsed call edges is owned by
4610 // the lldb::Function instance: locking at the SymbolFile level would be too
4611 // late, because the act of storing results from ParseCallEdgesInFunction
4612 // would be racy.
4613 DWARFDIE func_die = GetDIE(func_id.GetID());
4614 if (func_die.IsValid())
4615 return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
4616 return {};
4617}
4618
4623
4624void SymbolFileDWARF::DumpClangAST(Stream &s, llvm::StringRef filter,
4625 bool show_color) {
4627 if (!ts_or_err)
4628 return;
4629 auto ts = *ts_or_err;
4630 TypeSystemClang *clang = llvm::dyn_cast_or_null<TypeSystemClang>(ts.get());
4631 if (!clang)
4632 return;
4633 clang->Dump(s.AsRawOstream(), filter, show_color);
4634}
4635
4637 DWARFDebugInfo &info = DebugInfo();
4638 const size_t num_cus = info.GetNumUnits();
4640 // Check if a .dwp file exists, returning it if it does.
4641 if (const auto &dwp_sp = GetDwpSymbolFile()) {
4642 if (ObjectFile *dwp_obj = dwp_sp->GetObjectFile()) {
4643 spec_list.Append(ModuleSpec(dwp_obj->GetFileSpec()));
4644 // Only one .dwp file is expected, so return early.
4645 return spec_list;
4646 }
4647 }
4648
4649 for (uint32_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
4650 DWARFUnit *unit = info.GetUnitAtIndex(cu_idx);
4651 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(unit);
4652 if (dwarf_cu == nullptr || !dwarf_cu->GetDWOId().has_value())
4653 continue;
4654
4655 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
4656 if (!die)
4657 continue;
4658
4659 const char *dwo_name = GetDWOName(*dwarf_cu, *die.GetDIE());
4660 if (!dwo_name)
4661 continue;
4662
4663 lldb_private::FileSpec dwo_file(dwo_name);
4664 if (!dwo_file.IsAbsolute()) {
4665 const char *comp_dir = die.GetDIE()->GetAttributeValueAsString(
4666 dwarf_cu, DW_AT_comp_dir, nullptr);
4667 if (comp_dir)
4668 dwo_file.PrependPathComponent(comp_dir);
4669 }
4670 spec_list.Append(ModuleSpec(dwo_file));
4671 }
4672 return spec_list;
4673}
4674
4676 bool errors_only,
4677 bool load_all_debug_info) {
4678 StructuredData::Array separate_debug_info_files;
4679 DWARFDebugInfo &info = DebugInfo();
4680 const size_t num_cus = info.GetNumUnits();
4681 for (size_t cu_idx = 0; cu_idx < num_cus; cu_idx++) {
4682 DWARFUnit *unit = info.GetUnitAtIndex(cu_idx);
4683 DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(unit);
4684 if (dwarf_cu == nullptr)
4685 continue;
4686
4687 // Check if this is a DWO unit by checking if it has a DWO ID.
4688 // NOTE: it seems that `DWARFUnit::IsDWOUnit` is always false?
4689 if (!dwarf_cu->GetDWOId().has_value())
4690 continue;
4691
4693 std::make_shared<StructuredData::Dictionary>();
4694 const uint64_t dwo_id = dwarf_cu->GetDWOId().value();
4695 dwo_data->AddIntegerItem("dwo_id", dwo_id);
4696
4697 if (const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly()) {
4698 const char *dwo_name = GetDWOName(*dwarf_cu, *die.GetDIE());
4699 if (dwo_name) {
4700 dwo_data->AddStringItem("dwo_name", dwo_name);
4701 } else {
4702 dwo_data->AddStringItem("error", "missing dwo name");
4703 }
4704
4705 const char *comp_dir = die.GetDIE()->GetAttributeValueAsString(
4706 dwarf_cu, DW_AT_comp_dir, nullptr);
4707 if (comp_dir) {
4708 dwo_data->AddStringItem("comp_dir", comp_dir);
4709 }
4710 } else {
4711 dwo_data->AddStringItem(
4712 "error",
4713 llvm::formatv("unable to get unit DIE for DWARFUnit at {0:x}",
4714 dwarf_cu->GetOffset())
4715 .str());
4716 }
4717
4718 // If we have a DWO symbol file, that means we were able to successfully
4719 // load it.
4720 SymbolFile *dwo_symfile = dwarf_cu->GetDwoSymbolFile(load_all_debug_info);
4721 if (dwo_symfile) {
4722 dwo_data->AddStringItem(
4723 "resolved_dwo_path",
4724 dwo_symfile->GetObjectFile()->GetFileSpec().GetPath());
4725 } else {
4726 dwo_data->AddStringItem("error",
4727 dwarf_cu->GetDwoError().AsCString("unknown"));
4728 }
4729 dwo_data->AddBooleanItem("loaded", dwo_symfile != nullptr);
4730 if (!errors_only || dwo_data->HasKey("error"))
4731 separate_debug_info_files.AddItem(dwo_data);
4732 }
4733
4734 d.AddStringItem("type", "dwo");
4735 d.AddStringItem("symfile", GetMainObjectFile()->GetFileSpec().GetPath());
4736 d.AddItem("separate-debug-info-files",
4737 std::make_shared<StructuredData::Array>(
4738 std::move(separate_debug_info_files)));
4739 return true;
4740}
4741
4743 if (m_debug_map_symfile == nullptr) {
4744 lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
4745 if (module_sp) {
4746 m_debug_map_symfile = llvm::cast<SymbolFileDWARFDebugMap>(
4747 module_sp->GetSymbolFile()->GetBackingSymbolFile());
4748 }
4749 }
4750 return m_debug_map_symfile;
4751}
4752
4753const std::shared_ptr<SymbolFileDWARFDwo> &SymbolFileDWARF::GetDwpSymbolFile() {
4754 llvm::call_once(m_dwp_symfile_once_flag, [this]() {
4755 if (m_objfile_sp->GetArchitecture().GetTriple().isAppleMachO())
4756 return;
4757
4758 // Create a list of files to try and append .dwp to.
4759 FileSpecList symfiles;
4760 // Append the module's object file path.
4761 const FileSpec module_fspec = m_objfile_sp->GetModule()->GetFileSpec();
4762 symfiles.Append(module_fspec);
4763 // Append the object file for this SymbolFile only if it is different from
4764 // the module's file path. Our main module could be "a.out", our symbol file
4765 // could be "a.debug" and our ".dwp" file might be "a.debug.dwp" instead of
4766 // "a.out.dwp".
4767 const FileSpec symfile_fspec(m_objfile_sp->GetFileSpec());
4768 if (symfile_fspec != module_fspec) {
4769 symfiles.Append(symfile_fspec);
4770 } else {
4771 // If we don't have a separate debug info file, then try stripping the
4772 // extension. The main module could be "a.debug" and the .dwp file could
4773 // be "a.dwp" instead of "a.debug.dwp".
4774 llvm::StringRef filename_no_ext =
4775 module_fspec.GetFileNameStrippingExtension();
4776 if (filename_no_ext != module_fspec.GetFilename()) {
4777 FileSpec module_spec_no_ext(module_fspec);
4778 module_spec_no_ext.SetFilename(filename_no_ext);
4779 symfiles.Append(module_spec_no_ext);
4780 }
4781 }
4784 ModuleSpec module_spec;
4785 module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
4786 FileSpec dwp_filespec;
4787 for (const auto &symfile : symfiles.files()) {
4788 module_spec.GetSymbolFileSpec() =
4789 FileSpec(symfile.GetPath() + ".dwp", symfile.GetPathStyle());
4790 LLDB_LOG(log, "Searching for DWP using: \"{0}\"",
4791 module_spec.GetSymbolFileSpec());
4793 module_spec, search_paths,
4794 m_objfile_sp->GetModule()->GetSymbolLocatorStatistics());
4795 if (FileSystem::Instance().Exists(dwp_filespec)) {
4796 break;
4797 }
4798 }
4799 if (!FileSystem::Instance().Exists(dwp_filespec)) {
4800 LLDB_LOG(log, "No DWP file found locally");
4801 // Fill in the UUID for the module we're trying to match for, so we can
4802 // find the correct DWP file, as the Debuginfod plugin uses *only* this
4803 // data to correctly match the DWP file with the binary.
4804 module_spec.GetUUID() = m_objfile_sp->GetUUID();
4806 module_spec, search_paths,
4807 m_objfile_sp->GetModule()->GetSymbolLocatorStatistics());
4808 }
4809 if (FileSystem::Instance().Exists(dwp_filespec)) {
4810 LLDB_LOG(log, "Found DWP file: \"{0}\"", dwp_filespec);
4811 DataExtractorSP dwp_file_extractor_sp;
4812 lldb::offset_t dwp_file_data_offset = 0;
4813 ObjectFileSP dwp_obj_file = ObjectFile::FindPlugin(
4814 GetObjectFile()->GetModule(), &dwp_filespec, 0,
4815 FileSystem::Instance().GetByteSize(dwp_filespec),
4816 dwp_file_extractor_sp, dwp_file_data_offset);
4817 if (dwp_obj_file) {
4818 m_dwp_symfile = std::make_shared<SymbolFileDWARFDwo>(
4819 *this, dwp_obj_file, DIERef::k_file_index_mask);
4820 }
4821 }
4822 if (!m_dwp_symfile) {
4823 LLDB_LOG(log, "Unable to locate for DWP file for: \"{0}\"",
4824 m_objfile_sp->GetModule()->GetFileSpec());
4825 }
4826 });
4827 return m_dwp_symfile;
4828}
4829
4830llvm::Expected<lldb::TypeSystemSP>
4834
4836 auto type_system_or_err = GetTypeSystem(unit);
4837 if (auto err = type_system_or_err.takeError()) {
4838 LLDB_LOG_ERROR(GetLog(LLDBLog::Symbols), std::move(err),
4839 "Unable to get DWARFASTParser: {0}");
4840 return nullptr;
4841 }
4842 if (auto ts = *type_system_or_err)
4843 return ts->GetDWARFParser();
4844 return nullptr;
4845}
4846
4848 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4849 return dwarf_ast->GetDeclForUIDFromDWARF(die);
4850 return CompilerDecl();
4851}
4852
4854 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4855 return dwarf_ast->GetDeclContextForUIDFromDWARF(die);
4856 return CompilerDeclContext();
4857}
4858
4861 if (DWARFASTParser *dwarf_ast = GetDWARFParser(*die.GetCU()))
4862 return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
4863 return CompilerDeclContext();
4864}
4865
4868 return static_cast<LanguageType>(val);
4869
4870 // Note: user languages between lo_user and hi_user must be handled
4871 // explicitly here.
4872 switch (val) {
4873 case DW_LANG_Mips_Assembler:
4875 default:
4876 return eLanguageTypeUnknown;
4877 }
4878}
4879
4883
4885 auto lang = (llvm::dwarf::SourceLanguage)unit.GetDWARFLanguageType();
4886 if (llvm::dwarf::isCPlusPlus(lang))
4887 lang = DW_LANG_C_plus_plus;
4888 return LanguageTypeFromDWARF(lang);
4889}
4890
4892 if (m_index)
4893 return m_index->GetIndexTime();
4894 return {};
4895}
4896
4898 m_parse_time.reset();
4899 if (m_index)
4900 return m_index->ResetStatistics();
4901}
4902
4904 std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
4905 CompileUnit *cu = frame.GetSymbolContext(eSymbolContextCompUnit).comp_unit;
4906 if (!cu)
4907 return Status();
4908
4909 DWARFCompileUnit *dwarf_cu = GetDWARFCompileUnit(cu);
4910 if (!dwarf_cu)
4911 return Status();
4912
4913 // Check if we have a skeleton compile unit that had issues trying to load
4914 // its .dwo/.dwp file. First pares the Unit DIE to make sure we see any .dwo
4915 // related errors.
4916 dwarf_cu->ExtractUnitDIEIfNeeded();
4917 const Status &dwo_error = dwarf_cu->GetDwoError();
4918 if (dwo_error.Fail())
4919 return dwo_error.Clone();
4920
4921 // Don't return an error for assembly files as they typically don't have
4922 // varaible information.
4923 if (dwarf_cu->GetDWARFLanguageType() == DW_LANG_Mips_Assembler)
4924 return Status();
4925
4926 // Check if this compile unit has any variable DIEs. If it doesn't then there
4927 // is not variable information for the entire compile unit.
4928 if (dwarf_cu->HasAny({DW_TAG_variable, DW_TAG_formal_parameter}))
4929 return Status();
4930
4932 "no variable information is available in debug info for this "
4933 "compile unit");
4934}
4935
4937 std::unordered_map<lldb::CompUnitSP, lldb_private::Args> &args) {
4938
4939 const uint32_t num_compile_units = GetNumCompileUnits();
4940
4941 for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
4942 lldb::CompUnitSP comp_unit = GetCompileUnitAtIndex(cu_idx);
4943 if (!comp_unit)
4944 continue;
4945
4946 DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit.get());
4947 if (!dwarf_cu)
4948 continue;
4949
4950 const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
4951 if (!die)
4952 continue;
4953
4954 const char *flags = die.GetAttributeValueAsString(DW_AT_APPLE_flags, NULL);
4955
4956 if (!flags)
4957 continue;
4958 args.insert({comp_unit, Args(flags)});
4959 }
4960}
4961
4963 DWOStats stats;
4964
4965 DWARFDebugInfo &info = DebugInfo();
4966 const size_t num_cus = info.GetNumUnits();
4967 for (size_t cu_idx = 0; cu_idx < num_cus; cu_idx++) {
4968 DWARFUnit *dwarf_cu = info.GetUnitAtIndex(cu_idx);
4969 if (dwarf_cu == nullptr)
4970 continue;
4971
4972 // Check if this is a DWO unit by checking if it has a DWO ID.
4973 if (!dwarf_cu->GetDWOId().has_value())
4974 continue;
4975
4976 stats.dwo_file_count++;
4977
4978 // If we have a DWO symbol file, that means we were able to successfully
4979 // load it.
4980 SymbolFile *dwo_symfile =
4981 dwarf_cu->GetDwoSymbolFile(/*load_all_debug_info=*/false);
4982 if (dwo_symfile) {
4983 stats.loaded_dwo_file_count++;
4984 }
4985
4986 // Check if this unit has a DWO load error, false by default.
4987 const Status &dwo_error = dwarf_cu->GetDwoError();
4988 if (dwo_error.Fail())
4989 stats.dwo_error_count++;
4990 }
4991
4992 return stats;
4993}
4994
4996 DWARFDIE die = GetDIE(uid);
4997
4998 if (die.Tag() != DW_TAG_variable)
4999 return nullptr;
5000
5002}
static llvm::raw_ostream & error(Stream &strm)
#define DEBUG_PRINTF(fmt,...)
static PluginProperties & GetGlobalPluginProperties()
#define lldbassert(x)
Definition LLDBAssert.h:16
#define LLDB_LOG(log,...)
The LLDB_LOG* macros defined below are the way to emit log messages.
Definition Log.h:375
#define LLDB_LOG_ERRORV(log, error,...)
Definition Log.h:421
#define LLDB_LOGF(log,...)
Definition Log.h:389
#define LLDB_LOG_ERROR(log, error,...)
Definition Log.h:405
#define LLDB_PLUGIN_DEFINE(PluginName)
static double elapsed(const StatsTimepoint &start, const StatsTimepoint &end)
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 llvm::StringRef ClangToItaniumCtorKind(clang::CXXCtorType kind)
static void ParseSupportFilesFromPrologue(SupportFileList &support_files, const lldb::ModuleSP &module, const llvm::DWARFDebugLine::Prologue &prologue, FileSpec::Style style, llvm::StringRef compile_dir={})
static std::optional< uint64_t > GetByteSizeFromTypeDIE(DWARFDIE die, unsigned max_depth=64)
Walks transparent type wrappers following DW_AT_type and returns the first DW_AT_byte_size encountere...
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 llvm::StringRef GetItaniumCtorDtorVariant(llvm::StringRef discriminator)
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 std::unique_ptr< LineTable > ConvertLineTable(CompileUnit &comp_unit, const llvm::DWARFDebugLine::LineTable &line_table, lldb::addr_t first_code_address)
static llvm::StringRef ClangToItaniumDtorKind(clang::CXXDtorType kind)
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:40
#define LLDB_SCOPED_TIMER()
Definition Timer.h:88
#define LLDB_SCOPED_TIMERF(...)
Definition Timer.h:91
A section + offset based address class.
Definition Address.h:62
lldb::SectionSP GetSection() const
Get const accessor for the section.
Definition Address.h:426
lldb::addr_t GetFileAddress() const
Get the file address.
Definition Address.cpp:283
lldb::addr_t GetOffset() const
Get the section relative offset value.
Definition Address.h:329
bool IsSectionOffset() const
Check if an address is section offset.
Definition Address.h:342
A command line argument class.
Definition Args.h:33
A class that describes a single lexical block.
Definition Block.h:41
RangeList::Entry Range
Definition Block.h:44
lldb::VariableListSP GetBlockVariableList(bool can_create)
Get the variable list for this block only.
Definition Block.cpp:382
lldb::BlockSP CreateChild(lldb::user_id_t uid)
Creates a block with the specified UID uid.
Definition Block.cpp:370
Block * FindBlockByID(lldb::user_id_t block_id)
Definition Block.cpp:113
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
Definition Block.h:310
void SetDidParseVariables(bool b, bool set_children)
Definition Block.cpp:479
void AddRange(const Range &range)
Add a new offset range to this block.
Definition Block.cpp:331
void FinalizeRanges()
Definition Block.cpp:326
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:375
static bool ExtractContextAndIdentifier(llvm::StringRef name, llvm::StringRef &context, llvm::StringRef &identifier)
static llvm::Expected< ConstString > SubstituteStructor_ItaniumMangle(llvm::StringRef mangled_name, llvm::StringRef subst_from, llvm::StringRef subst_to)
Substitutes Itanium structor encoding substrings given by subst_from in mangled_name with subst_to.
static llvm::Expected< ConstString > SubstituteStructorAliases_ItaniumMangle(llvm::StringRef mangled_name)
Tries replacing Itanium structor encoding substrings in mangled_name with potential aliases....
Checksum(llvm::MD5::MD5Result md5=g_sentinel)
Definition Checksum.cpp:15
static bool LanguageSupportsClangModules(lldb::LanguageType language)
Query whether Clang supports modules for a particular language.
A class that describes a compilation unit.
Definition CompileUnit.h:43
void SetVariableList(lldb::VariableListSP &variable_list_sp)
Set accessor for the variable list.
const SupportFileList & GetSupportFiles()
Get the compile unit's support file list.
lldb::VariableListSP GetVariableList(bool can_create)
Get the variable list for a compile unit.
void SetDebugMacros(const DebugMacrosSP &debug_macros)
const FileSpec & GetPrimaryFile() const
Return the primary source spec associated with this compile unit.
void ResolveSymbolContext(const SourceLocationSpec &src_location_spec, lldb::SymbolContextItem resolve_scope, SymbolContextList &sc_list, RealpathPrefixes *realpath_prefixes=nullptr)
Resolve symbol contexts by file and line.
void SetLineTable(LineTable *line_table)
Set the line table for the compile unit.
lldb::FunctionSP FindFunctionByUID(lldb::user_id_t uid)
Finds a function by user ID.
lldb::LanguageType GetLanguage()
LineTable * GetLineTable()
Get the line table for the compile unit.
Represents a generic declaration context in a program.
bool IsContainedInLookup(CompilerDeclContext other) const
Check if the given other decl context is contained in the lookup of this decl context (for example be...
Represents a generic declaration such as a function declaration.
Generic representation of a type in a programming language.
TypeSystemSPWrapper GetTypeSystem() const
Accessors.
lldb::opaque_compiler_type_t GetOpaqueQualType() const
A uniqued constant string class.
Definition ConstString.h:40
bool IsEmpty() const
Test for empty string.
llvm::StringRef GetStringRef() const
Get the string value as a llvm::StringRef.
const char * GetCString() const
Get the string value as a C string.
const char * AsCString(const char *value_if_empty) const
Get the string value as a C string.
llvm::DWARFDataExtractor GetAsLLVMDWARF() 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 UpdateValue(uint64_t const_value, lldb::offset_t const_value_byte_size, uint8_t addr_byte_size)
bool Update_DW_OP_addr(const Delegate *dwarf_cu, lldb::addr_t file_addr)
An data extractor class.
void Clear()
Clears the object state.
virtual uint64_t GetByteSize() const
Get the number of bytes contained in this object.
llvm::DataExtractor GetAsLLVM() const
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:106
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.
void SetColumn(uint16_t column)
Set accessor for the declaration column number.
void SetFile(const FileSpec &file_spec)
Set accessor for the declaration file specification.
A class that measures elapsed time in an exception safe way.
Definition Statistics.h:76
"lldb/Target/ExecutionContext.h" A class that contains an execution context.
A file collection class.
llvm::iterator_range< const_iterator > files() const
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:454
static bool Match(const FileSpec &pattern, const FileSpec &file)
Match FileSpec pattern against FileSpec file.
Definition FileSpec.cpp:317
bool IsRelative() const
Returns true if the filespec represents a relative path.
Definition FileSpec.cpp:514
llvm::StringRef GetFileNameStrippingExtension() const
Return the filename without the extension part.
Definition FileSpec.cpp:414
void SetFilename(llvm::StringRef filename)
Filename string set accessor.
Definition FileSpec.cpp:363
void MakeAbsolute(const FileSpec &dir)
Make the FileSpec absolute by treating it relative to dir.
Definition FileSpec.cpp:537
void SetPath(llvm::StringRef p)
Temporary helper for FileSystem change.
Definition FileSpec.h:286
llvm::StringRef GetFilename() const
Filename string const get accessor.
Definition FileSpec.h:248
bool IsAbsolute() const
Returns true if the filespec represents an absolute path.
Definition FileSpec.cpp:518
void PrependPathComponent(llvm::StringRef component)
Definition FileSpec.cpp:440
size_t GetPath(char *path, size_t max_path_length, bool denormalize=true) const
Extract the full path to the file.
Definition FileSpec.cpp:380
llvm::sys::path::Style Style
Definition FileSpec.h:58
bool Exists(const FileSpec &file_spec) const
Returns whether the given file exists.
static FileSystem & Instance()
void Resolve(llvm::SmallVectorImpl< char > &path, bool force_make_absolute=false)
Resolve path to make it canonical.
A class that describes a function.
Definition Function.h:386
lldb::ModuleSP CalculateSymbolContextModule() override
Definition Function.cpp:474
CompileUnit * GetCompileUnit()
Get accessor for the compile unit that owns this function.
Definition Function.cpp:416
Block & GetBlock(bool can_create)
Get accessor for the block list.
Definition Function.cpp:401
static const char * GetNameForLanguageType(lldb::LanguageType language)
Returns the internal LLDB name for the specified language.
Definition Language.cpp:348
static bool LanguageIsCPlusPlus(lldb::LanguageType language)
Definition Language.cpp:385
A line table class.
Definition LineTable.h:25
static void AppendLineEntryToSequence(Sequence &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:59
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.
static Mangled::ManglingScheme GetManglingScheme(llvm::StringRef name)
Try to identify the mangling scheme used.
Definition Mangled.cpp:182
lldb::ModuleSP GetModule() const
Get const accessor for the module pointer.
static Status GetSharedModule(const ModuleSpec &module_spec, lldb::ModuleSP &module_sp, llvm::SmallVectorImpl< lldb::ModuleSP > *old_modules, bool *did_create_ptr, bool invoke_locate_callback=true, bool invoke_symbol_locators=true)
void Append(const ModuleSpec &spec)
Definition ModuleSpec.h:371
FileSpec & GetFileSpec()
Definition ModuleSpec.h:57
ArchSpec & GetArchitecture()
Definition ModuleSpec.h:93
FileSpec & GetSymbolFileSpec()
Definition ModuleSpec.h:81
A class that encapsulates name lookup information.
Definition Module.h:965
lldb::FunctionNameType GetNameTypeMask() const
Definition Module.h:1007
ConstString GetLookupName() const
Definition Module.h:1005
static std::vector< LookupInfo > MakeLookupInfos(ConstString name, lldb::FunctionNameType name_type_mask, lldb::LanguageType lang_type, ConstString lookup_name_override={})
Creates a vector of lookup infos for function name resolution.
Definition Module.cpp:710
A class that describes an executable image and its associated object and symbol files.
Definition Module.h:92
A plug-in interface definition class for object file parsers.
Definition ObjectFile.h:46
static lldb::ObjectFileSP FindPlugin(const lldb::ModuleSP &module_sp, const FileSpec *file_spec, lldb::offset_t file_offset, lldb::offset_t file_size, lldb::DataExtractorSP extractor_sp, lldb::offset_t &data_offset)
Find a ObjectFile plug-in that can parse file_spec.
Symtab * GetSymtab(bool can_create=true)
Gets the symbol table for the currently selected architecture (and object for archives).
@ eTypeDebugInfo
An object file that contains only debug information.
Definition ObjectFile.h:57
virtual FileSpec & GetFileSpec()
Get accessor to the object file specification.
Definition ObjectFile.h:284
static bool RegisterPlugin(llvm::StringRef name, llvm::StringRef description, ABICreateInstance create_callback)
static FileSpec LocateExecutableSymbolFile(const ModuleSpec &module_spec, const FileSpecList &default_search_paths, StatisticsMap &map)
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 bool UnregisterPlugin(ABICreateInstance create_callback)
A Progress indicator helper class.
Definition Progress.h:60
RangeData< lldb::addr_t, lldb::addr_t, Variable * > Entry
Definition RangeMap.h:462
llvm::StringRef GetText() const
Access the regular expression text.
lldb::SectionSP FindSectionByName(llvm::StringRef section_name) const
Definition Section.cpp:562
lldb::SectionSP FindSectionByType(lldb::SectionType sect_type, bool check_children, size_t start_idx=0) const
Definition Section.cpp:602
SectionList & GetChildren()
Definition Section.h:166
lldb::offset_t GetFileSize() const
Definition Section.h:186
This base class provides an interface to stack frames.
Definition StackFrame.h:44
virtual const SymbolContext & GetSymbolContext(lldb::SymbolContextItem resolve_scope)
Provide a SymbolContext for this StackFrame's current pc value.
std::chrono::duration< double > Duration
Definition Statistics.h:37
An error handling class.
Definition Status.h:118
Status Clone() const
Don't call this function in new code.
Definition Status.h:174
static Status FromErrorString(const char *str)
Definition Status.h:141
bool Fail() const
Test for error condition.
Definition Status.cpp:293
const char * AsCString(const char *default_error_str="unknown error") const
Get the error string associated with the current error.
Definition Status.cpp:194
static Status static Status FromErrorStringWithFormatv(const char *format, Args &&...args)
Definition Status.h:151
const char * GetData() const
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:405
void AddItem(const ObjectSP &item)
void AddStringItem(llvm::StringRef key, llvm::StringRef value)
void AddItem(llvm::StringRef key, ObjectSP value_sp)
std::shared_ptr< Dictionary > DictionarySP
A list of support files for a CompileUnit.
const FileSpec & GetFileSpecAtIndex(size_t idx) const
void Append(const FileSpec &file)
SupportFileNSP GetSupportFileAtIndex(size_t idx) const
void EmplaceBack(Args &&...args)
Wraps a FileSpec and an optional Checksum.
Definition SupportFile.h:22
virtual const FileSpec & Materialize()
Materialize the file to disk and return the path to that temporary file.
Definition SupportFile.h:73
Defines a list of symbol context objects.
uint32_t GetSize() const
Get accessor for a symbol context list size.
bool AppendIfUnique(const SymbolContext &sc, bool merge_symbol_into_function)
"lldb/Symbol/SymbolContextScope.h" Inherit from this if your object is part of a symbol context and c...
virtual CompileUnit * CalculateSymbolContextCompileUnit()
virtual void CalculateSymbolContext(SymbolContext *sc)=0
Reconstruct the object's symbol context into sc.
Defines a symbol context baton that can be handed other debug core functions.
Function * function
The Function for a given query.
Block * block
The Block for a given query.
lldb::ModuleSP module_sp
The Module for a given query.
CompileUnit * comp_unit
The CompileUnit for a given query.
void Clear(bool clear_target)
Clear the object's state.
Variable * variable
The global variable matching the given query.
LineEntry line_entry
The LineEntry for a given query.
lldb::CompUnitSP GetCompileUnitAtIndex(uint32_t idx) override
ObjectFile * GetObjectFile() override
Definition SymbolFile.h:601
virtual TypeList & GetTypeList()
Definition SymbolFile.h:674
lldb::ObjectFileSP m_objfile_sp
Definition SymbolFile.h:677
ObjectFile * GetMainObjectFile() override
void SetCompileUnitAtIndex(uint32_t idx, const lldb::CompUnitSP &cu_sp)
SymbolFileCommon(lldb::ObjectFileSP objfile_sp)
Definition SymbolFile.h:586
Symtab * GetSymtab(bool can_create=true) override
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language) override
uint32_t GetNumCompileUnits() override
void Dump(Stream &s) override
uint64_t GetDebugInfoSize(bool load_all_debug_info=false) override
Metrics gathering functions.
std::unordered_map< lldb::CompUnitSP, Args > GetCompileOptions()
Returns a map of compilation unit to the compile option arguments associated with that compilation un...
Definition SymbolFile.h:545
virtual ObjectFile * GetObjectFile()=0
bool ValueIsAddress() const
Definition Symbol.cpp:192
Address & GetAddressRef()
Definition Symbol.h:78
Symbol * FindFirstSymbolWithNameAndType(ConstString name, lldb::SymbolType symbol_type, Debug symbol_debug_type, Visibility symbol_visibility)
Definition Symtab.cpp:842
static FileSpecList GetDefaultDebugFileSearchPaths()
Definition Target.cpp:2950
void Insert(const lldb::TypeSP &type)
Definition TypeList.cpp:27
uint32_t GetSize() const
Definition TypeMap.cpp:51
A class that contains all state required for type lookups.
bool GetModuleSearch() const
The m_context can be used in two ways: normal types searching with the context containing a stanadard...
std::vector< lldb_private::CompilerContext > & GetContextRef()
Access the internal compiler context array.
ConstString GetTypeBasename() const
Get the type basename to use when searching the type indexes in each SymbolFile object.
bool ContextMatches(llvm::ArrayRef< lldb_private::CompilerContext > context) const
Check of a CompilerContext array from matching type from a symbol file matches the m_context.
bool GetSearchByMangledName() const
Returns true if the type query is supposed to treat the name to be searched as a mangled name.
This class tracks the state and results of a TypeQuery.
bool InsertUnique(const lldb::TypeSP &type_sp)
When types that match a TypeQuery are found, this API is used to insert the matching types.
bool Done(const TypeQuery &query) const
Check if the type matching has found all of the matches that it needs.
bool AlreadySearched(lldb_private::SymbolFile *sym_file)
Check if a SymbolFile object has already been searched by this type match object.
A TypeSystem implementation based on Clang.
Interface for representing a type system.
Definition TypeSystem.h:72
virtual lldb::LanguageType GetMinimumLanguage(lldb::opaque_compiler_type_t type)=0
virtual plugin::dwarf::DWARFASTParser * GetDWARFParser()
Definition TypeSystem.h:95
ConstString GetName()
@ FileAddress
A file address value.
Definition Value.h:48
bool AddVariableIfUnique(const lldb::VariableSP &var_sp)
lldb::VariableSP GetVariableAtIndex(size_t idx) const
lldb::VariableSP RemoveVariableAtIndex(size_t idx)
SymbolContextScope * GetSymbolContextScope() const
Definition Variable.h:52
RangeVector< lldb::addr_t, lldb::addr_t > RangeList
Definition Variable.h:27
An abstraction which groups an XcodeSDK with the sysroot it was used from.
Definition XcodeSDK.h:101
static std::unique_ptr< AppleDWARFIndex > Create(Module &module, DWARFDataExtractor apple_names, DWARFDataExtractor apple_namespaces, DWARFDataExtractor apple_types, DWARFDataExtractor apple_objc, DWARFDataExtractor debug_str)
Identifies a DWARF debug info entry within a given Module.
Definition DIERef.h:31
std::optional< uint32_t > file_index() const
Definition DIERef.h:60
static constexpr uint64_t k_file_index_mask
Definition DIERef.h:120
dw_offset_t die_offset() const
Definition DIERef.h:68
virtual void EnsureAllDIEsInDeclContextHaveBeenParsed(CompilerDeclContext decl_context)=0
virtual bool CompleteTypeFromDWARF(const DWARFDIE &die, Type *type, const CompilerType &compiler_type)=0
virtual std::string GetDIEClassTemplateParams(DWARFDIE die)=0
virtual Function * ParseFunctionFromDWARF(CompileUnit &comp_unit, const DWARFDIE &die, AddressRanges ranges)=0
virtual ConstString ConstructDemangledNameFromDWARF(const DWARFDIE &die)=0
virtual lldb::TypeSP ParseTypeFromDWARF(const SymbolContext &sc, const DWARFDIE &die, bool *type_is_new_ptr)=0
static std::optional< SymbolFile::ArrayInfo > ParseChildArrayInfo(const DWARFDIE &parent_die, const ExecutionContext *exe_ctx=nullptr)
virtual CompilerDeclContext GetDeclContextForUIDFromDWARF(const DWARFDIE &die)=0
DWARFUnit * CompileUnitAtIndex(uint32_t i) const
dw_attr_t AttributeAtIndex(uint32_t i) const
bool ExtractFormValueAtIndex(uint32_t i, DWARFFormValue &form_value) const
DWARFAttributes GetAttributes(Recurse recurse=Recurse::yes) const
std::optional< uint64_t > GetAttributeValueAsOptionalUnsigned(const dw_attr_t attr) const
const DWARFDataExtractor & GetData() const
const char * GetAttributeValueAsString(const dw_attr_t attr, const char *fail_value) const
std::optional< DIERef > GetDIERef() const
DWARFDebugInfoEntry * GetDIE() const
uint64_t GetAttributeValueAsUnsigned(const dw_attr_t attr, uint64_t fail_value) const
DWARFDIE LookupAddress(const dw_addr_t address)
const DWARFDataExtractor & getOrLoadLineData()
const char * GetMangledName(bool substitute_name_allowed=true) const
Definition DWARFDIE.cpp:212
bool GetDIENamesAndRanges(const char *&name, const char *&mangled, llvm::DWARFAddressRangesVector &ranges, std::optional< int > &decl_file, std::optional< int > &decl_line, std::optional< int > &decl_column, std::optional< int > &call_file, std::optional< int > &call_line, std::optional< int > &call_column, DWARFExpressionList *frame_base) const
Definition DWARFDIE.cpp:584
DWARFDIE GetDIE(dw_offset_t die_offset) const
Definition DWARFDIE.cpp:126
llvm::iterator_range< child_iterator > children() const
The range of all the children of this DIE.
Definition DWARFDIE.cpp:601
std::vector< CompilerContext > GetDeclContext(bool derive_template_names=false) const
Return this DIE's decl context as it is needed to look up types in Clang modules.
Definition DWARFDIE.cpp:456
DWARFDIE LookupDeepestBlock(lldb::addr_t file_addr) const
Definition DWARFDIE.cpp:147
DWARFDIE GetAttributeValueAsReferenceDIE(const dw_attr_t attr) const
Definition DWARFDIE.cpp:134
DWARFDeclContext GetDWARFDeclContext() const
Definition DWARFDIE.cpp:526
DWARFDIE GetReferencedDIE(const dw_attr_t attr) const
Definition DWARFDIE.cpp:118
std::vector< CompilerContext > GetTypeLookupContext(bool derive_template_names=false) const
Get a context to a type so it can be looked up.
Definition DWARFDIE.cpp:503
dw_offset_t FindAddress(dw_addr_t address) const
DWARFDebugInfoEntry objects assume that they are living in one big vector and do pointer arithmetic o...
std::optional< uint64_t > GetAttributeValueAsOptionalUnsigned(const DWARFUnit *cu, const dw_attr_t attr, bool check_elaborating_dies=false) const
const char * GetAttributeValueAsString(const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value, bool check_elaborating_dies=false) const
DWARFUnit * GetSkeletonUnit(DWARFUnit *dwo_unit)
DWARFUnit * GetUnitAtOffset(DIERef::Section section, dw_offset_t cu_offset, uint32_t *idx_ptr=nullptr)
const DWARFDebugAranges & GetCompileUnitAranges()
DWARFDIE GetDIE(DIERef::Section section, dw_offset_t die_offset)
static void ReadMacroEntries(const DWARFDataExtractor &debug_macro_data, const DWARFDataExtractor &debug_str_data, const bool offset_is_64_bit, lldb::offset_t *sect_offset, SymbolFileDWARF *sym_file_dwarf, DebugMacrosSP &debug_macros_sp)
static DWARFDebugMacroHeader ParseHeader(const DWARFDataExtractor &debug_macro_data, lldb::offset_t *offset)
void AppendDeclContext(dw_tag_t tag, const char *name)
static bool IsDataForm(const dw_form_t form)
static bool IsBlockForm(const dw_form_t form)
SymbolFileDWARF & GetSymbolFileDWARF() const
Definition DWARFUnit.h:201
DWARFCompileUnit * GetSkeletonUnit()
Get the skeleton compile unit for a DWO file.
const Status & GetDwoError() const
Get the fission .dwo file specific error for this compile unit.
Definition DWARFUnit.h:285
void SetLLDBCompUnit(lldb_private::CompileUnit *cu)
Definition DWARFUnit.h:185
lldb_private::CompileUnit * GetLLDBCompUnit() const
Definition DWARFUnit.h:183
uint8_t GetAddressByteSize() const override
Definition DWARFUnit.h:127
DWARFDataExtractor GetLocationData() const
std::optional< uint64_t > GetLoclistOffset(uint32_t Index)
Definition DWARFUnit.h:250
bool ParseDWARFLocationList(const DataExtractor &data, DWARFExpressionList &loc_list) const
void SetDwoError(Status &&error)
Set the fission .dwo file specific error for this compile unit.
Definition DWARFUnit.h:293
DWARFDIE GetDIE(dw_offset_t die_offset)
lldb::ByteOrder GetByteOrder() const
SymbolFileDWARFDwo * GetDwoSymbolFile(bool load_all_debug_info=true)
uint16_t GetVersion() const override
Definition DWARFUnit.h:121
std::optional< uint64_t > GetDWOId()
Get the DWO ID from the DWARFUnitHeader for DWARF5, or from the unit DIE's DW_AT_dwo_id or DW_AT_GNU_...
bool HasAny(llvm::ArrayRef< dw_tag_t > tags)
Returns true if any DIEs in the unit match any DW_TAG values in tags.
FileSpec GetFile(size_t file_idx)
static llvm::Expected< std::unique_ptr< DebugNamesDWARFIndex > > Create(Module &module, DWARFDataExtractor debug_names, DWARFDataExtractor debug_str, SymbolFileDWARF &dwarf)
lldb::addr_t LinkOSOFileAddress(SymbolFileDWARF *oso_symfile, lldb::addr_t oso_file_addr)
Convert a .o file "file address" to an executable "file address".
bool LinkOSOAddress(Address &addr)
Convert addr from a .o file address, to an executable address.
uint64_t GetDebugInfoSize(bool load_all_debug_info=false) override
Metrics gathering functions.
CompilerDeclContext GetDeclContextContainingUID(lldb::user_id_t uid) override
static CompilerDeclContext GetContainingDeclContext(const DWARFDIE &die)
static bool SupportedVersion(uint16_t version)
std::optional< uint32_t > GetDWARFUnitIndex(uint32_t cu_idx)
CompileUnit * GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu)
lldb::ModuleSP GetExternalModule(ConstString name)
void FindGlobalVariables(ConstString name, const CompilerDeclContext &parent_decl_ctx, uint32_t max_matches, VariableList &variables) override
virtual DWARFDIE FindDefinitionDIE(const DWARFDIE &die)
DWARFDIE FindBlockContainingSpecification(const DIERef &func_die_ref, dw_offset_t spec_block_die_offset)
lldb::VariableSP ParseVariableDIE(const SymbolContext &sc, const DWARFDIE &die, const lldb::addr_t func_low_pc)
static DWARFASTParser * GetDWARFParser(DWARFUnit &unit)
static lldb::LanguageType GetLanguageFamily(DWARFUnit &unit)
Same as GetLanguage() but reports all C++ versions as C++ (no version).
bool ForEachExternalModule(CompileUnit &, llvm::DenseSet< SymbolFile * > &, llvm::function_ref< bool(Module &)>) override
std::unique_ptr< DWARFDebugInfo > m_info
bool DeclContextMatchesThisSymbolFile(const CompilerDeclContext &decl_ctx)
void GetMangledNamesForFunction(const std::string &scope_qualified_name, std::vector< ConstString > &mangled_names) override
size_t PopulateBlockVariableList(VariableList &variable_list, const SymbolContext &sc, llvm::ArrayRef< DIERef > variable_dies, lldb::addr_t func_low_pc)
Type * ResolveType(const DWARFDIE &die, bool assert_not_being_parsed=true, bool resolve_function_context=false)
DWOStats GetDwoStats() override
Gets statistics about dwo files associated with this symbol file.
virtual llvm::DenseMap< lldb::opaque_compiler_type_t, DIERef > & GetForwardDeclCompilerTypeToDIE()
llvm::DenseMap< const DWARFDebugInfoEntry *, lldb::VariableSP > DIEToVariableSP
size_t ParseVariablesInFunctionContextRecursive(const SymbolContext &sc, const DWARFDIE &die, lldb::addr_t func_low_pc, DIEArray &accumulator)
std::unique_ptr< StandaloneDWARFLineTableInfo > m_standalone_line_table_info
virtual lldb::TypeSP FindCompleteObjCDefinitionTypeForDIE(const DWARFDIE &die, ConstString type_name, bool must_be_implementation)
const std::shared_ptr< SymbolFileDWARFDwo > & GetDwpSymbolFile()
StandaloneDWARFLineTableInfo * GetStandaloneLineTableInfo()
Return standalone line-table information when there is a .debug_line section without a ....
std::recursive_mutex & GetModuleMutex() const override
Symbols file subclasses should override this to return the Module that owns the TypeSystem that this ...
bool GetSeparateDebugInfo(StructuredData::Dictionary &d, bool errors_only, bool load_all_debug_info=false) override
List separate dwo files.
llvm::Expected< DWARFDIE > FindFunctionDefinition(const FunctionCallLabel &label, const DWARFDIE &declaration)
Find the definition DIE for the specified label in this SymbolFile.
virtual llvm::DenseMap< const DWARFDebugInfoEntry *, Type * > & GetDIEToType()
virtual DWARFCompileUnit * GetDWARFCompileUnit(CompileUnit *comp_unit)
Function * ParseFunction(CompileUnit &comp_unit, const DWARFDIE &die)
lldb::TypeSP GetTypeForDIE(const DWARFDIE &die, bool resolve_function_context=false)
llvm::Expected< SymbolContext > ResolveFunctionCallLabel(FunctionCallLabel &label) override
Resolves the function corresponding to the specified LLDB function call label.
lldb::addr_t m_first_code_address
DWARF does not provide a good way for traditional (concatenating) linkers to invalidate debug info de...
ConstString ConstructFunctionDemangledName(const DWARFDIE &die)
DWARFUnit * GetSkeletonUnit(DWARFUnit *dwo_unit)
Given a DWO DWARFUnit, find the corresponding skeleton DWARFUnit in the main symbol file.
FileSpec GetFile(DWARFUnit &unit, size_t file_idx)
std::shared_ptr< SymbolFileDWARFDwo > m_dwp_symfile
void DumpClangAST(Stream &s, llvm::StringRef filter, bool show_colors) override
void InitializeFirstCodeAddressRecursive(const SectionList &section_list)
std::unique_ptr< llvm::DWARFDebugAbbrev > m_abbr
llvm::DenseMap< lldb::opaque_compiler_type_t, DIERef > m_forward_decl_compiler_type_to_die
std::vector< CompilerContext > GetCompilerContextForUID(lldb::user_id_t uid) override
virtual DWARFDIE GetDIE(const DIERef &die_ref)
std::unique_ptr< GlobalVariableMap > m_global_aranges_up
uint64_t GetDebugInfoSize(bool load_all_debug_info=false) override
Metrics gathering functions.
void FindTypes(const lldb_private::TypeQuery &match, lldb_private::TypeResults &results) override
Find types using a type-matching object that contains all search parameters.
static CompilerDecl GetDecl(const DWARFDIE &die)
void ResolveFunctionAndBlock(lldb::addr_t file_vm_addr, bool lookup_block, SymbolContext &sc)
Resolve functions and (possibly) blocks for the given file address and a compile unit.
void ResetStatistics() override
Reset the statistics for the symbol file.
size_t ParseVariablesForContext(const SymbolContext &sc) override
std::optional< ArrayInfo > GetDynamicArrayInfoForUID(lldb::user_id_t type_uid, const ExecutionContext *exe_ctx) override
If type_uid points to an array type, return its characteristics.
size_t ParseBlocksRecursive(Function &func) override
Type * ResolveTypeUID(lldb::user_id_t type_uid) override
static lldb::LanguageType GetLanguage(DWARFUnit &unit)
llvm::DenseMap< dw_offset_t, std::unique_ptr< SupportFileList > > m_type_unit_support_files
size_t ParseFunctions(CompileUnit &comp_unit) override
bool ParseDebugMacros(CompileUnit &comp_unit) override
static SymbolFile * CreateInstance(lldb::ObjectFileSP objfile_sp)
bool ParseSupportFiles(CompileUnit &comp_unit, SupportFileList &support_files) override
bool ParseImportedModules(const SymbolContext &sc, std::vector< SourceModule > &imported_modules) override
std::optional< uint64_t > GetDWOId()
If this is a DWARF object with a single CU, return its DW_AT_dwo_id.
void GetTypes(SymbolContextScope *sc_scope, lldb::TypeClass type_mask, TypeList &type_list) override
void ParseDeclsForContext(CompilerDeclContext decl_ctx) override
size_t ParseTypes(CompileUnit &comp_unit) override
std::shared_ptr< SymbolFileDWARFDwo > GetDwoSymbolFileForCompileUnit(DWARFUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die)
SymbolFileDWARF(lldb::ObjectFileSP objfile_sp, SectionList *dwo_section_list)
lldb::VariableSP ParseVariableDIECached(const SymbolContext &sc, const DWARFDIE &die)
lldb_private::ModuleSpecList GetSeparateDebugInfoFiles() override
Return a map of separate debug info files that are loaded.
StatsDuration::Duration GetDebugInfoIndexTime() override
Return the time it took to index the debug information in the object file.
bool CompleteType(CompilerType &compiler_type) override
bool ParseLineTable(CompileUnit &comp_unit) override
lldb::TypeSP GetTypeEnclosingVariableUID(lldb::user_id_t uid) override
Get the semantically innermost non-function type that encloses the provided variable.
bool ResolveFunction(const DWARFDIE &die, bool include_inlines, SymbolContextList &sc_list)
bool ParseIsOptimized(CompileUnit &comp_unit) override
std::vector< std::unique_ptr< CallEdge > > CollectCallEdges(lldb::ModuleSP module, DWARFDIE function_die)
Parse call site entries (DW_TAG_call_site), including any nested call site parameters (DW_TAG_call_si...
DIEArray MergeBlockAbstractParameters(const DWARFDIE &block_die, DIEArray &&variable_dies)
DWARFDIE GetDeclContextDIEContainingDIE(const DWARFDIE &die)
void InitializeObject() override
Initialize the SymbolFile object.
void ParseAndAppendGlobalVariable(const SymbolContext &sc, const DWARFDIE &die, VariableList &cc_variable_list)
static llvm::Expected< lldb::TypeSystemSP > GetTypeSystem(DWARFUnit &unit)
XcodeSDKAndSysroot ParseXcodeSDK(CompileUnit &comp_unit) override
Return the Xcode SDK comp_unit was compiled against.
void FindFunctions(const Module::LookupInfo &lookup_info, const CompilerDeclContext &parent_decl_ctx, bool include_inlines, SymbolContextList &sc_list) override
static bool DIEInDeclContext(const CompilerDeclContext &parent_decl_ctx, const DWARFDIE &die, bool only_root_namespaces=false)
uint32_t ResolveSymbolContext(const Address &so_addr, lldb::SymbolContextItem resolve_scope, SymbolContext &sc) override
bool HasForwardDeclForCompilerType(const CompilerType &compiler_type)
lldb::CompUnitSP ParseCompileUnit(DWARFCompileUnit &dwarf_cu)
CompilerDeclContext FindNamespace(ConstString name, const CompilerDeclContext &parent_decl_ctx, bool only_root_namespaces) override
Finds a namespace of name name and whose parent context is parent_decl_ctx.
lldb::CompUnitSP ParseCompileUnitAtIndex(uint32_t index) override
static lldb::LanguageType LanguageTypeFromDWARF(uint64_t val)
lldb::TypeSP ParseType(const SymbolContext &sc, const DWARFDIE &die, bool *type_is_new)
static DWARFDIE GetParentSymbolContextDIE(const DWARFDIE &die)
std::vector< std::unique_ptr< CallEdge > > ParseCallEdgesInFunction(UserID func_id) override
lldb::addr_t FixupAddress(lldb::addr_t file_addr)
If this symbol file is linked to by a debug map (see SymbolFileDWARFDebugMap), and file_addr is a fil...
virtual void GetObjCMethods(ConstString class_name, llvm::function_ref< IterationAction(DWARFDIE die)> callback)
llvm::Expected< lldb::TypeSystemSP > GetTypeSystemForLanguage(lldb::LanguageType language) override
CompilerDecl GetDeclForUID(lldb::user_id_t uid) override
virtual SymbolFileDWARF * GetDIERefSymbolFile(const DIERef &die_ref)
Given a DIERef, find the correct SymbolFileDWARF.
lldb::LanguageType ParseLanguage(CompileUnit &comp_unit) override
CompilerDeclContext GetDeclContextForUID(lldb::user_id_t uid) override
static void DebuggerInitialize(Debugger &debugger)
RangeDataVector< lldb::addr_t, lldb::addr_t, Variable * > GlobalVariableMap
size_t ParseVariablesInFunctionContext(const SymbolContext &sc, const DWARFDIE &die, const lldb::addr_t func_low_pc)
llvm::DenseMap< const DWARFDebugInfoEntry *, Type * > m_die_to_type
bool GetFunction(const DWARFDIE &die, SymbolContext &sc)
const SupportFileList * GetTypeUnitSupportFiles(DWARFTypeUnit &tu)
std::optional< uint64_t > GetFileIndex() const
Symbol * GetObjCClassSymbol(ConstString objc_class_name)
static CompilerDeclContext GetDeclContext(const DWARFDIE &die)
virtual UniqueDWARFASTTypeMap & GetUniqueDWARFASTTypeMap()
virtual void LoadSectionData(lldb::SectionType sect_type, DWARFDataExtractor &data)
Status CalculateFrameVariableError(StackFrame &frame) override
Subclasses will override this function to for GetFrameVariableError().
uint64_t dw_offset_t
Definition dwarf.h:24
#define DW_INVALID_OFFSET
Definition dwarf.h:29
llvm::dwarf::Tag dw_tag_t
Definition dwarf.h:19
#define DW_DIE_OFFSET_MAX_BITSIZE
Definition dwarf.h:28
llvm::dwarf::Attribute dw_attr_t
Definition dwarf.h:17
uint64_t dw_addr_t
Definition dwarf.h:20
#define DW_INVALID_INDEX
Definition dwarf.h:30
#define LLDB_INVALID_ADDRESS
llvm::StringRef DW_TAG_value_to_name(dw_tag_t tag)
std::vector< DIERef > DIEArray
Definition DIERef.h:136
A class that represents a running process on the host machine.
Log * GetLog(Cat mask)
Retrieve the Log object for the channel associated with the given log enum.
Definition Log.h:338
NonNullSharedPtr< lldb_private::SupportFile > SupportFileNSP
Definition SupportFile.h:80
NativeFilePosix NativeFile
Definition File.h:29
std::shared_ptr< DebugMacros > DebugMacrosSP
Definition DebugMacros.h:22
llvm::SmallVector< CallSiteParameter, 0 > CallSiteParameterArray
A vector of CallSiteParameter.
Definition Function.h:248
IterationAction
Useful for callbacks whose return type indicates whether to continue iteration or short-circuit.
std::shared_ptr< lldb_private::TypeSystem > TypeSystemSP
@ eDescriptionLevelBrief
@ eDescriptionLevelFull
uint64_t offset_t
Definition lldb-types.h:86
std::shared_ptr< lldb_private::ObjectFile > ObjectFileSP
LanguageType
Programming language type.
@ eLanguageTypeMipsAssembler
Mips_Assembler.
@ eLanguageTypeUnknown
Unknown or invalid language value.
@ eLanguageTypeC_plus_plus
ISO C++:1998.
@ eLanguageTypeLastStandardLanguage
std::shared_ptr< lldb_private::Type > TypeSP
@ eSymbolTypeObjCClass
std::shared_ptr< lldb_private::VariableList > VariableListSP
std::shared_ptr< lldb_private::Variable > VariableSP
@ eValueTypeVariableGlobal
globals variable
@ eValueTypeVariableLocal
function local variables
@ eValueTypeVariableArgument
function argument variables
@ eValueTypeVariableStatic
static variable
@ eValueTypeVariableThreadLocal
thread local storage variable
uint64_t user_id_t
Definition lldb-types.h:83
std::shared_ptr< lldb_private::Section > SectionSP
uint64_t addr_t
Definition lldb-types.h:80
@ eSectionTypeDWARFAppleNamespaces
@ eSectionTypeDWARFDebugNames
DWARF v5 .debug_names.
@ eSectionTypeDWARFAppleTypes
@ eSectionTypeDWARFDebugInfo
@ eSectionTypeDWARFDebugLine
@ eSectionTypeDWARFDebugStr
@ eSectionTypeDWARFAppleNames
@ eSectionTypeDWARFAppleObjC
@ eSectionTypeDWARFDebugAbbrev
std::shared_ptr< lldb_private::DataExtractor > DataExtractorSP
std::shared_ptr< lldb_private::Module > ModuleSP
std::shared_ptr< lldb_private::CompileUnit > CompUnitSP
Represent the locations of a parameter at a call site, both in the caller and in the callee.
Definition Function.h:242
static CompilerType RemoveFastQualifiers(const CompilerType &ct)
Definition ClangUtil.cpp:51
Holds statistics about DWO (Debug With Object) files.
Definition Statistics.h:124
uint32_t loaded_dwo_file_count
Definition Statistics.h:125
Holds parsed information about a function call label that LLDB attaches as an AsmLabel to function AS...
Definition Expression.h:110
lldb::user_id_t symbol_id
Unique identifier of the function symbol on which to perform the function call.
Definition Expression.h:122
llvm::StringRef discriminator
Arbitrary string which language plugins can interpret for their own needs.
Definition Expression.h:113
llvm::StringRef lookup_name
Name to use when searching for the function symbol in module_id.
Definition Expression.h:131
Information needed to import a source-language module.
std::vector< ConstString > path
Something like "Module.Submodule".
A mix in class that contains a generic user ID.
Definition UserID.h:31
lldb::user_id_t GetID() const
Get accessor for the user ID.
Definition UserID.h:47
LineTableEntry(llvm::Expected< llvm::DWARFDebugLine::LineTable > line_table)
const llvm::DWARFDebugLine::Prologue * GetPrologue(uint32_t cu_idx)
const llvm::DWARFDebugLine::LineTable * GetLineTable(uint32_t cu_idx)
uint32_t ResolveSymbolContext(const Address &so_addr, SymbolContextItem resolve_scope, SymbolContext &sc)
const DWARFDebugAranges & GetAranges(lldb::addr_t first_code_address)