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

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