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