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

source code of lldb/source/Plugins/SymbolFile/DWARF/SymbolFileDWARF.cpp