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