1289550Szbb//===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
2289550Szbb//
3289550Szbb// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4289550Szbb// See https://llvm.org/LICENSE.txt for license information.
5289550Szbb// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6289550Szbb//
7289550Szbb//===----------------------------------------------------------------------===//
8289550Szbb
9289550Szbb#include "SymbolFileDWARF.h"
10289550Szbb
11289550Szbb#include "llvm/ADT/Optional.h"
12289550Szbb#include "llvm/Support/Casting.h"
13289550Szbb#include "llvm/Support/Threading.h"
14289550Szbb
15289550Szbb#include "lldb/Core/Module.h"
16289550Szbb#include "lldb/Core/ModuleList.h"
17289550Szbb#include "lldb/Core/ModuleSpec.h"
18289550Szbb#include "lldb/Core/PluginManager.h"
19289550Szbb#include "lldb/Core/Section.h"
20289550Szbb#include "lldb/Core/StreamFile.h"
21289550Szbb#include "lldb/Core/Value.h"
22289550Szbb#include "lldb/Utility/ArchSpec.h"
23289550Szbb#include "lldb/Utility/RegularExpression.h"
24289550Szbb#include "lldb/Utility/Scalar.h"
25289550Szbb#include "lldb/Utility/StreamString.h"
26289550Szbb#include "lldb/Utility/Timer.h"
27289550Szbb
28289550Szbb#include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
29289551Szbb#include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
30289551Szbb
31289550Szbb#include "lldb/Host/FileSystem.h"
32296030Szbb#include "lldb/Host/Host.h"
33296030Szbb
34296030Szbb#include "lldb/Interpreter/OptionValueFileSpecList.h"
35289551Szbb#include "lldb/Interpreter/OptionValueProperties.h"
36289551Szbb
37289551Szbb#include "lldb/Symbol/Block.h"
38289551Szbb#include "lldb/Symbol/ClangASTContext.h"
39289551Szbb#include "lldb/Symbol/ClangUtil.h"
40289551Szbb#include "lldb/Symbol/CompileUnit.h"
41289551Szbb#include "lldb/Symbol/CompilerDecl.h"
42289551Szbb#include "lldb/Symbol/CompilerDeclContext.h"
43289551Szbb#include "lldb/Symbol/DebugMacros.h"
44289551Szbb#include "lldb/Symbol/LineTable.h"
45289551Szbb#include "lldb/Symbol/LocateSymbolFile.h"
46289551Szbb#include "lldb/Symbol/ObjectFile.h"
47289551Szbb#include "lldb/Symbol/SymbolFile.h"
48289551Szbb#include "lldb/Symbol/TypeMap.h"
49289551Szbb#include "lldb/Symbol/TypeSystem.h"
50289551Szbb#include "lldb/Symbol/VariableList.h"
51289551Szbb
52289551Szbb#include "lldb/Target/Language.h"
53289551Szbb#include "lldb/Target/Target.h"
54289551Szbb
55289551Szbb#include "AppleDWARFIndex.h"
56289550Szbb#include "DWARFASTParser.h"
57289551Szbb#include "DWARFASTParserClang.h"
58289551Szbb#include "DWARFCompileUnit.h"
59289551Szbb#include "DWARFDebugAbbrev.h"
60289551Szbb#include "DWARFDebugAranges.h"
61289551Szbb#include "DWARFDebugInfo.h"
62289551Szbb#include "DWARFDebugMacro.h"
63289551Szbb#include "DWARFDebugRanges.h"
64289551Szbb#include "DWARFDeclContext.h"
65289551Szbb#include "DWARFFormValue.h"
66289551Szbb#include "DWARFTypeUnit.h"
67297450Szbb#include "DWARFUnit.h"
68297450Szbb#include "DebugNamesDWARFIndex.h"
69289551Szbb#include "LogChannelDWARF.h"
70296030Szbb#include "ManualDWARFIndex.h"
71296030Szbb#include "SymbolFileDWARFDebugMap.h"
72296030Szbb#include "SymbolFileDWARFDwo.h"
73296030Szbb#include "SymbolFileDWARFDwp.h"
74296030Szbb
75296030Szbb#include "llvm/DebugInfo/DWARF/DWARFContext.h"
76296030Szbb#include "llvm/Support/FileSystem.h"
77296030Szbb
78296030Szbb#include <algorithm>
79296030Szbb#include <map>
80289551Szbb#include <memory>
81289551Szbb
82289551Szbb#include <ctype.h>
83289551Szbb#include <string.h>
84289550Szbb
85289550Szbb//#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
86289550Szbb
87289550Szbb#ifdef ENABLE_DEBUG_PRINTF
88289550Szbb#include <stdio.h>
89289551Szbb#define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
90289551Szbb#else
91289551Szbb#define DEBUG_PRINTF(fmt, ...)
92289551Szbb#endif
93289551Szbb
94289551Szbbusing namespace lldb;
95289551Szbbusing namespace lldb_private;
96289551Szbb
97289551Szbbchar SymbolFileDWARF::ID;
98289551Szbb
99289551Szbb// static inline bool
100289551Szbb// child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
101289551Szbb//{
102289551Szbb//    switch (tag)
103289551Szbb//    {
104289551Szbb//    default:
105289551Szbb//        break;
106289551Szbb//    case DW_TAG_subprogram:
107289551Szbb//    case DW_TAG_inlined_subroutine:
108289551Szbb//    case DW_TAG_class_type:
109297450Szbb//    case DW_TAG_structure_type:
110297450Szbb//    case DW_TAG_union_type:
111289551Szbb//        return true;
112289551Szbb//    }
113289551Szbb//    return false;
114289550Szbb//}
115289551Szbb//
116289551Szbb
117289551Szbbnamespace {
118289550Szbb
119289550Szbb#define LLDB_PROPERTIES_symbolfiledwarf
120289551Szbb#include "SymbolFileDWARFProperties.inc"
121289550Szbb
122289550Szbbenum {
123289550Szbb#define LLDB_PROPERTIES_symbolfiledwarf
124289551Szbb#include "SymbolFileDWARFPropertiesEnum.inc"
125289550Szbb};
126289551Szbb
127289551Szbbclass PluginProperties : public Properties {
128289550Szbbpublic:
129289550Szbb  static ConstString GetSettingName() {
130289551Szbb    return SymbolFileDWARF::GetPluginNameStatic();
131289550Szbb  }
132289550Szbb
133289550Szbb  PluginProperties() {
134289550Szbb    m_collection_sp = std::make_shared<OptionValueProperties>(GetSettingName());
135289550Szbb    m_collection_sp->Initialize(g_symbolfiledwarf_properties);
136289551Szbb  }
137289551Szbb
138289551Szbb  FileSpecList GetSymLinkPaths() {
139289550Szbb    const OptionValueFileSpecList *option_value =
140289550Szbb        m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(
141289551Szbb            nullptr, true, ePropertySymLinkPaths);
142289551Szbb    assert(option_value);
143289550Szbb    return option_value->GetCurrentValue();
144289550Szbb  }
145289551Szbb
146289551Szbb  bool IgnoreFileIndexes() const {
147289551Szbb    return m_collection_sp->GetPropertyAtIndexAsBoolean(
148289551Szbb        nullptr, ePropertyIgnoreIndexes, false);
149289551Szbb  }
150289551Szbb};
151289551Szbb
152289551Szbbtypedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
153289551Szbb
154289551Szbbstatic const SymbolFileDWARFPropertiesSP &GetGlobalPluginProperties() {
155289551Szbb  static const auto g_settings_sp(std::make_shared<PluginProperties>());
156289550Szbb  return g_settings_sp;
157289551Szbb}
158289551Szbb
159289551Szbb} // namespace
160289550Szbb
161289551Szbbstatic const llvm::DWARFDebugLine::LineTable *
162289551SzbbParseLLVMLineTable(lldb_private::DWARFContext &context,
163289551Szbb                   llvm::DWARFDebugLine &line, dw_offset_t line_offset,
164289551Szbb                   dw_offset_t unit_offset) {
165289551Szbb  Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
166289551Szbb
167289551Szbb  llvm::DWARFDataExtractor data = context.getOrLoadLineData().GetAsLLVM();
168289551Szbb  llvm::DWARFContext &ctx = context.GetAsLLVM();
169289551Szbb  llvm::Expected<const llvm::DWARFDebugLine::LineTable *> line_table =
170289551Szbb      line.getOrParseLineTable(
171289551Szbb          data, line_offset, ctx, nullptr, [&](llvm::Error e) {
172289551Szbb            LLDB_LOG_ERROR(log, std::move(e),
173289551Szbb                           "SymbolFileDWARF::ParseLineTable failed to parse");
174289551Szbb          });
175289551Szbb
176289551Szbb  if (!line_table) {
177289551Szbb    LLDB_LOG_ERROR(log, line_table.takeError(),
178289551Szbb                   "SymbolFileDWARF::ParseLineTable failed to parse");
179289551Szbb    return nullptr;
180289551Szbb  }
181289551Szbb  return *line_table;
182289551Szbb}
183289551Szbb
184289551Szbbstatic llvm::Optional<std::string>
185289551SzbbGetFileByIndex(const llvm::DWARFDebugLine::Prologue &prologue, size_t idx,
186289551Szbb               llvm::StringRef compile_dir, FileSpec::Style style) {
187289551Szbb  // Try to get an absolute path first.
188289551Szbb  std::string abs_path;
189289551Szbb  auto absolute = llvm::DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath;
190289551Szbb  if (prologue.getFileNameByIndex(idx, compile_dir, absolute, abs_path, style))
191289551Szbb    return std::move(abs_path);
192289551Szbb
193289551Szbb  // Otherwise ask for a relative path.
194289551Szbb  std::string rel_path;
195289551Szbb  auto relative = llvm::DILineInfoSpecifier::FileLineInfoKind::Default;
196289551Szbb  if (!prologue.getFileNameByIndex(idx, compile_dir, relative, rel_path, style))
197289551Szbb    return {};
198289551Szbb  return std::move(rel_path);
199289551Szbb}
200289551Szbb
201289551Szbbstatic FileSpecList
202289551SzbbParseSupportFilesFromPrologue(const lldb::ModuleSP &module,
203289551Szbb                              const llvm::DWARFDebugLine::Prologue &prologue,
204289551Szbb                              FileSpec::Style style,
205289551Szbb                              llvm::StringRef compile_dir = {}) {
206289551Szbb  FileSpecList support_files;
207289551Szbb  size_t first_file = 0;
208289551Szbb  if (prologue.getVersion() <= 4) {
209289551Szbb    // File index 0 is not valid before DWARF v5. Add a dummy entry to ensure
210289550Szbb    // support file list indices match those we get from the debug info and line
211289551Szbb    // tables.
212289550Szbb    support_files.Append(FileSpec());
213289551Szbb    first_file = 1;
214289551Szbb  }
215289551Szbb
216289551Szbb  const size_t number_of_files = prologue.FileNames.size();
217289551Szbb  for (size_t idx = first_file; idx <= number_of_files; ++idx) {
218289551Szbb    std::string remapped_file;
219289551Szbb    if (auto file_path = GetFileByIndex(prologue, idx, compile_dir, style))
220289551Szbb      if (!module->RemapSourceFile(llvm::StringRef(*file_path), remapped_file))
221289551Szbb        remapped_file = std::move(*file_path);
222289551Szbb
223289551Szbb    // Unconditionally add an entry, so the indices match up.
224289551Szbb    support_files.EmplaceBack(remapped_file, style);
225289550Szbb  }
226289550Szbb
227289550Szbb  return support_files;
228289551Szbb}
229289551Szbb
230289550SzbbFileSpecList SymbolFileDWARF::GetSymlinkPaths() {
231289551Szbb  return GetGlobalPluginProperties()->GetSymLinkPaths();
232289551Szbb}
233289551Szbb
234289550Szbbvoid SymbolFileDWARF::Initialize() {
235289550Szbb  LogChannelDWARF::Initialize();
236289551Szbb  PluginManager::RegisterPlugin(GetPluginNameStatic(),
237289551Szbb                                GetPluginDescriptionStatic(), CreateInstance,
238289551Szbb                                DebuggerInitialize);
239289551Szbb}
240289551Szbb
241289551Szbbvoid SymbolFileDWARF::DebuggerInitialize(Debugger &debugger) {
242289551Szbb  if (!PluginManager::GetSettingForSymbolFilePlugin(
243289551Szbb          debugger, PluginProperties::GetSettingName())) {
244289551Szbb    const bool is_global_setting = true;
245289551Szbb    PluginManager::CreateSettingForSymbolFilePlugin(
246289551Szbb        debugger, GetGlobalPluginProperties()->GetValueProperties(),
247289551Szbb        ConstString("Properties for the dwarf symbol-file plug-in."),
248289550Szbb        is_global_setting);
249289550Szbb  }
250289550Szbb}
251289551Szbb
252289551Szbbvoid SymbolFileDWARF::Terminate() {
253289550Szbb  PluginManager::UnregisterPlugin(CreateInstance);
254289550Szbb  LogChannelDWARF::Terminate();
255289550Szbb}
256289550Szbb
257289551Szbblldb_private::ConstString SymbolFileDWARF::GetPluginNameStatic() {
258289551Szbb  static ConstString g_name("dwarf");
259289551Szbb  return g_name;
260289550Szbb}
261289551Szbb
262289550Szbbconst char *SymbolFileDWARF::GetPluginDescriptionStatic() {
263289551Szbb  return "DWARF and DWARF3 debug symbol file reader.";
264289551Szbb}
265289551Szbb
266289550SzbbSymbolFile *SymbolFileDWARF::CreateInstance(ObjectFileSP objfile_sp) {
267289551Szbb  return new SymbolFileDWARF(std::move(objfile_sp),
268289551Szbb                             /*dwo_section_list*/ nullptr);
269289551Szbb}
270289550Szbb
271289551SzbbTypeList &SymbolFileDWARF::GetTypeList() {
272289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
273289551Szbb  if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
274289551Szbb    return debug_map_symfile->GetTypeList();
275289551Szbb  return SymbolFile::GetTypeList();
276289551Szbb}
277289551Szbbvoid SymbolFileDWARF::GetTypes(const DWARFDIE &die, dw_offset_t min_die_offset,
278289551Szbb                               dw_offset_t max_die_offset, uint32_t type_mask,
279289551Szbb                               TypeSet &type_set) {
280289551Szbb  if (die) {
281289551Szbb    const dw_offset_t die_offset = die.GetOffset();
282289551Szbb
283289551Szbb    if (die_offset >= max_die_offset)
284289551Szbb      return;
285289551Szbb
286289550Szbb    if (die_offset >= min_die_offset) {
287289551Szbb      const dw_tag_t tag = die.Tag();
288289551Szbb
289289551Szbb      bool add_type = false;
290289551Szbb
291289551Szbb      switch (tag) {
292289551Szbb      case DW_TAG_array_type:
293289551Szbb        add_type = (type_mask & eTypeClassArray) != 0;
294289551Szbb        break;
295289550Szbb      case DW_TAG_unspecified_type:
296289551Szbb      case DW_TAG_base_type:
297289551Szbb        add_type = (type_mask & eTypeClassBuiltin) != 0;
298289551Szbb        break;
299289550Szbb      case DW_TAG_class_type:
300289551Szbb        add_type = (type_mask & eTypeClassClass) != 0;
301289550Szbb        break;
302289551Szbb      case DW_TAG_structure_type:
303289550Szbb        add_type = (type_mask & eTypeClassStruct) != 0;
304289550Szbb        break;
305289551Szbb      case DW_TAG_union_type:
306289551Szbb        add_type = (type_mask & eTypeClassUnion) != 0;
307289551Szbb        break;
308289550Szbb      case DW_TAG_enumeration_type:
309289551Szbb        add_type = (type_mask & eTypeClassEnumeration) != 0;
310289550Szbb        break;
311289550Szbb      case DW_TAG_subroutine_type:
312289550Szbb      case DW_TAG_subprogram:
313289551Szbb      case DW_TAG_inlined_subroutine:
314289550Szbb        add_type = (type_mask & eTypeClassFunction) != 0;
315289551Szbb        break;
316289551Szbb      case DW_TAG_pointer_type:
317289551Szbb        add_type = (type_mask & eTypeClassPointer) != 0;
318289551Szbb        break;
319289551Szbb      case DW_TAG_rvalue_reference_type:
320289550Szbb      case DW_TAG_reference_type:
321289551Szbb        add_type = (type_mask & eTypeClassReference) != 0;
322289551Szbb        break;
323289551Szbb      case DW_TAG_typedef:
324289551Szbb        add_type = (type_mask & eTypeClassTypedef) != 0;
325289551Szbb        break;
326289550Szbb      case DW_TAG_ptr_to_member_type:
327289551Szbb        add_type = (type_mask & eTypeClassMemberPointer) != 0;
328289551Szbb        break;
329289550Szbb      default:
330289551Szbb        break;
331289550Szbb      }
332289550Szbb
333289550Szbb      if (add_type) {
334289551Szbb        const bool assert_not_being_parsed = true;
335289551Szbb        Type *type = ResolveTypeUID(die, assert_not_being_parsed);
336289551Szbb        if (type) {
337289550Szbb          if (type_set.find(type) == type_set.end())
338289551Szbb            type_set.insert(type);
339289551Szbb        }
340289551Szbb      }
341289550Szbb    }
342289550Szbb
343289550Szbb    for (DWARFDIE child_die = die.GetFirstChild(); child_die.IsValid();
344289551Szbb         child_die = child_die.GetSibling()) {
345289550Szbb      GetTypes(child_die, min_die_offset, max_die_offset, type_mask, type_set);
346289551Szbb    }
347289551Szbb  }
348289551Szbb}
349289551Szbb
350289551Szbbvoid SymbolFileDWARF::GetTypes(SymbolContextScope *sc_scope,
351289551Szbb                               TypeClass type_mask, TypeList &type_list)
352289550Szbb
353289550Szbb{
354289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
355289551Szbb  TypeSet type_set;
356289551Szbb
357289551Szbb  CompileUnit *comp_unit = nullptr;
358289551Szbb  DWARFUnit *dwarf_cu = nullptr;
359289551Szbb  if (sc_scope)
360289550Szbb    comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
361289551Szbb
362289551Szbb  if (comp_unit) {
363289550Szbb    dwarf_cu = GetDWARFCompileUnit(comp_unit);
364289551Szbb    if (!dwarf_cu)
365289551Szbb      return;
366289551Szbb    GetTypes(dwarf_cu->DIE(), dwarf_cu->GetOffset(),
367289551Szbb             dwarf_cu->GetNextUnitOffset(), type_mask, type_set);
368289551Szbb  } else {
369289551Szbb    DWARFDebugInfo *info = DebugInfo();
370289551Szbb    if (info) {
371289551Szbb      const size_t num_cus = info->GetNumUnits();
372289551Szbb      for (size_t cu_idx = 0; cu_idx < num_cus; ++cu_idx) {
373289551Szbb        dwarf_cu = info->GetUnitAtIndex(cu_idx);
374289551Szbb        if (dwarf_cu) {
375289551Szbb          GetTypes(dwarf_cu->DIE(), 0, UINT32_MAX, type_mask, type_set);
376289551Szbb        }
377289551Szbb      }
378289551Szbb    }
379289551Szbb  }
380289551Szbb
381289551Szbb  std::set<CompilerType> compiler_type_set;
382289551Szbb  for (Type *type : type_set) {
383289551Szbb    CompilerType compiler_type = type->GetForwardCompilerType();
384289551Szbb    if (compiler_type_set.find(compiler_type) == compiler_type_set.end()) {
385289551Szbb      compiler_type_set.insert(compiler_type);
386289551Szbb      type_list.Insert(type->shared_from_this());
387289551Szbb    }
388289551Szbb  }
389289551Szbb}
390289551Szbb
391289551Szbb// Gets the first parent that is a lexical block, function or inlined
392289551Szbb// subroutine, or compile unit.
393289551SzbbDWARFDIE
394289551SzbbSymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die) {
395289551Szbb  DWARFDIE die;
396289551Szbb  for (die = child_die.GetParent(); die; die = die.GetParent()) {
397289551Szbb    dw_tag_t tag = die.Tag();
398289551Szbb
399289550Szbb    switch (tag) {
400289551Szbb    case DW_TAG_compile_unit:
401289551Szbb    case DW_TAG_partial_unit:
402289551Szbb    case DW_TAG_subprogram:
403289551Szbb    case DW_TAG_inlined_subroutine:
404289551Szbb    case DW_TAG_lexical_block:
405289551Szbb      return die;
406289551Szbb    default:
407289550Szbb      break;
408289551Szbb    }
409289551Szbb  }
410289551Szbb  return DWARFDIE();
411289551Szbb}
412289551Szbb
413289550SzbbSymbolFileDWARF::SymbolFileDWARF(ObjectFileSP objfile_sp,
414289551Szbb                                 SectionList *dwo_section_list)
415289550Szbb    : SymbolFile(std::move(objfile_sp)),
416289551Szbb      UserID(0x7fffffff00000000), // Used by SymbolFileDWARFDebugMap to
417289551Szbb                                  // when this class parses .o files to
418289551Szbb                                  // contain the .o file index/ID
419289551Szbb      m_debug_map_module_wp(), m_debug_map_symfile(nullptr),
420289551Szbb      m_context(m_objfile_sp->GetModule()->GetSectionList(), dwo_section_list),
421289551Szbb      m_data_debug_loc(), m_abbr(), m_info(), m_fetched_external_modules(false),
422289551Szbb      m_supports_DW_AT_APPLE_objc_complete_type(eLazyBoolCalculate),
423289551Szbb      m_unique_ast_type_map() {}
424289551Szbb
425289551SzbbSymbolFileDWARF::~SymbolFileDWARF() {}
426289550Szbb
427289550Szbbstatic ConstString GetDWARFMachOSegmentName() {
428289550Szbb  static ConstString g_dwarf_section_name("__DWARF");
429289551Szbb  return g_dwarf_section_name;
430289551Szbb}
431289550Szbb
432289551SzbbUniqueDWARFASTTypeMap &SymbolFileDWARF::GetUniqueDWARFASTTypeMap() {
433289551Szbb  SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
434289550Szbb  if (debug_map_symfile)
435289550Szbb    return debug_map_symfile->GetUniqueDWARFASTTypeMap();
436289551Szbb  else
437289551Szbb    return m_unique_ast_type_map;
438289551Szbb}
439289550Szbb
440289551Szbbllvm::Expected<TypeSystem &>
441289550SzbbSymbolFileDWARF::GetTypeSystemForLanguage(LanguageType language) {
442289551Szbb  if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile())
443289550Szbb    return debug_map_symfile->GetTypeSystemForLanguage(language);
444289550Szbb
445289551Szbb  auto type_system_or_err =
446289551Szbb      m_objfile_sp->GetModule()->GetTypeSystemForLanguage(language);
447289551Szbb  if (type_system_or_err) {
448289551Szbb    type_system_or_err->SetSymbolFile(this);
449289551Szbb  }
450289551Szbb  return type_system_or_err;
451289551Szbb}
452289551Szbb
453289551Szbbvoid SymbolFileDWARF::InitializeObject() {
454289551Szbb  Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
455289551Szbb
456289550Szbb  if (!GetGlobalPluginProperties()->IgnoreFileIndexes()) {
457289551Szbb    DWARFDataExtractor apple_names, apple_namespaces, apple_types, apple_objc;
458289551Szbb    LoadSectionData(eSectionTypeDWARFAppleNames, apple_names);
459289551Szbb    LoadSectionData(eSectionTypeDWARFAppleNamespaces, apple_namespaces);
460289551Szbb    LoadSectionData(eSectionTypeDWARFAppleTypes, apple_types);
461289551Szbb    LoadSectionData(eSectionTypeDWARFAppleObjC, apple_objc);
462289551Szbb
463289551Szbb    m_index = AppleDWARFIndex::Create(
464289551Szbb        *GetObjectFile()->GetModule(), apple_names, apple_namespaces,
465289551Szbb        apple_types, apple_objc, m_context.getOrLoadStrData());
466289551Szbb
467289551Szbb    if (m_index)
468289551Szbb      return;
469289551Szbb
470289551Szbb    DWARFDataExtractor debug_names;
471289551Szbb    LoadSectionData(eSectionTypeDWARFDebugNames, debug_names);
472289551Szbb    if (debug_names.GetByteSize() > 0) {
473289551Szbb      llvm::Expected<std::unique_ptr<DebugNamesDWARFIndex>> index_or =
474289551Szbb          DebugNamesDWARFIndex::Create(
475289551Szbb              *GetObjectFile()->GetModule(), debug_names,
476289551Szbb              m_context.getOrLoadStrData(), DebugInfo());
477289551Szbb      if (index_or) {
478289551Szbb        m_index = std::move(*index_or);
479289551Szbb        return;
480289551Szbb      }
481289551Szbb      LLDB_LOG_ERROR(log, index_or.takeError(),
482289551Szbb                     "Unable to read .debug_names data: {0}");
483289551Szbb    }
484289551Szbb  }
485289551Szbb
486289551Szbb  m_index = std::make_unique<ManualDWARFIndex>(*GetObjectFile()->GetModule(),
487289551Szbb                                                DebugInfo());
488289551Szbb}
489289551Szbb
490289550Szbbbool SymbolFileDWARF::SupportedVersion(uint16_t version) {
491289551Szbb  return version >= 2 && version <= 5;
492289551Szbb}
493289551Szbb
494289551Szbbuint32_t SymbolFileDWARF::CalculateAbilities() {
495289551Szbb  uint32_t abilities = 0;
496289551Szbb  if (m_objfile_sp != nullptr) {
497289551Szbb    const Section *section = nullptr;
498289551Szbb    const SectionList *section_list = m_objfile_sp->GetSectionList();
499289551Szbb    if (section_list == nullptr)
500289551Szbb      return 0;
501289551Szbb
502289551Szbb    uint64_t debug_abbrev_file_size = 0;
503289551Szbb    uint64_t debug_info_file_size = 0;
504289551Szbb    uint64_t debug_line_file_size = 0;
505289551Szbb
506289551Szbb    section = section_list->FindSectionByName(GetDWARFMachOSegmentName()).get();
507289551Szbb
508289551Szbb    if (section)
509289551Szbb      section_list = &section->GetChildren();
510289551Szbb
511289551Szbb    section =
512289551Szbb        section_list->FindSectionByType(eSectionTypeDWARFDebugInfo, true).get();
513289551Szbb    if (section != nullptr) {
514289551Szbb      debug_info_file_size = section->GetFileSize();
515289551Szbb
516289550Szbb      section =
517289550Szbb          section_list->FindSectionByType(eSectionTypeDWARFDebugAbbrev, true)
518289550Szbb              .get();
519289550Szbb      if (section)
520289550Szbb        debug_abbrev_file_size = section->GetFileSize();
521289550Szbb
522289551Szbb      DWARFDebugAbbrev *abbrev = DebugAbbrev();
523289551Szbb      if (abbrev) {
524289550Szbb        std::set<dw_form_t> invalid_forms;
525289551Szbb        abbrev->GetUnsupportedForms(invalid_forms);
526289551Szbb        if (!invalid_forms.empty()) {
527289550Szbb          StreamString error;
528289551Szbb          error.Printf("unsupported DW_FORM value%s:",
529289551Szbb                       invalid_forms.size() > 1 ? "s" : "");
530289551Szbb          for (auto form : invalid_forms)
531289550Szbb            error.Printf(" %#x", form);
532289550Szbb          m_objfile_sp->GetModule()->ReportWarning(
533289550Szbb              "%s", error.GetString().str().c_str());
534289551Szbb          return 0;
535289551Szbb        }
536289551Szbb      }
537289551Szbb
538289550Szbb      section =
539289551Szbb          section_list->FindSectionByType(eSectionTypeDWARFDebugLine, true)
540289551Szbb              .get();
541289551Szbb      if (section)
542289551Szbb        debug_line_file_size = section->GetFileSize();
543289551Szbb    } else {
544289551Szbb      const char *symfile_dir_cstr =
545289550Szbb          m_objfile_sp->GetFileSpec().GetDirectory().GetCString();
546289550Szbb      if (symfile_dir_cstr) {
547289551Szbb        if (strcasestr(symfile_dir_cstr, ".dsym")) {
548289550Szbb          if (m_objfile_sp->GetType() == ObjectFile::eTypeDebugInfo) {
549289550Szbb            // We have a dSYM file that didn't have a any debug info. If the
550289550Szbb            // string table has a size of 1, then it was made from an
551289550Szbb            // executable with no debug info, or from an executable that was
552289550Szbb            // stripped.
553289551Szbb            section =
554289551Szbb                section_list->FindSectionByType(eSectionTypeDWARFDebugStr, true)
555289551Szbb                    .get();
556289551Szbb            if (section && section->GetFileSize() == 1) {
557289550Szbb              m_objfile_sp->GetModule()->ReportWarning(
558289550Szbb                  "empty dSYM file detected, dSYM was created with an "
559289550Szbb                  "executable with no debug info.");
560289550Szbb            }
561289550Szbb          }
562289550Szbb        }
563289550Szbb      }
564289550Szbb    }
565289551Szbb
566289551Szbb    if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
567289551Szbb      abilities |= CompileUnits | Functions | Blocks | GlobalVariables |
568289551Szbb                   LocalVariables | VariableTypes;
569289550Szbb
570289551Szbb    if (debug_line_file_size > 0)
571289550Szbb      abilities |= LineTables;
572289551Szbb  }
573289550Szbb  return abilities;
574289550Szbb}
575289550Szbb
576289550Szbbconst DWARFDataExtractor &
577289550SzbbSymbolFileDWARF::GetCachedSectionData(lldb::SectionType sect_type,
578289551Szbb                                      DWARFDataSegment &data_segment) {
579289550Szbb  llvm::call_once(data_segment.m_flag, [this, sect_type, &data_segment] {
580289550Szbb    this->LoadSectionData(sect_type, std::ref(data_segment.m_data));
581289551Szbb  });
582289551Szbb  return data_segment.m_data;
583289550Szbb}
584289550Szbb
585289550Szbbvoid SymbolFileDWARF::LoadSectionData(lldb::SectionType sect_type,
586289550Szbb                                      DWARFDataExtractor &data) {
587289551Szbb  ModuleSP module_sp(m_objfile_sp->GetModule());
588289551Szbb  const SectionList *section_list = module_sp->GetSectionList();
589289551Szbb  if (!section_list)
590289551Szbb    return;
591289551Szbb
592289551Szbb  SectionSP section_sp(section_list->FindSectionByType(sect_type, true));
593289550Szbb  if (!section_sp)
594289550Szbb    return;
595289551Szbb
596289551Szbb  data.Clear();
597289551Szbb  m_objfile_sp->ReadSectionData(section_sp.get(), data);
598289551Szbb}
599289550Szbb
600289550SzbbDWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() {
601289551Szbb  if (m_abbr)
602289551Szbb    return m_abbr.get();
603289551Szbb
604289550Szbb  const DWARFDataExtractor &debug_abbrev_data = m_context.getOrLoadAbbrevData();
605289551Szbb  if (debug_abbrev_data.GetByteSize() == 0)
606289551Szbb    return nullptr;
607289550Szbb
608289551Szbb  auto abbr = std::make_unique<DWARFDebugAbbrev>();
609289551Szbb  llvm::Error error = abbr->parse(debug_abbrev_data);
610289551Szbb  if (error) {
611289551Szbb    Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
612289551Szbb    LLDB_LOG_ERROR(log, std::move(error),
613289551Szbb                   "Unable to read .debug_abbrev section: {0}");
614289551Szbb    return nullptr;
615289550Szbb  }
616289550Szbb
617289551Szbb  m_abbr = std::move(abbr);
618289551Szbb  return m_abbr.get();
619289551Szbb}
620289550Szbb
621289551Szbbconst DWARFDebugAbbrev *SymbolFileDWARF::DebugAbbrev() const {
622289551Szbb  return m_abbr.get();
623289550Szbb}
624289551Szbb
625289551SzbbDWARFDebugInfo *SymbolFileDWARF::DebugInfo() {
626289551Szbb  if (m_info == nullptr) {
627289551Szbb    static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
628289551Szbb    Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
629289551Szbb                       static_cast<void *>(this));
630289551Szbb    if (m_context.getOrLoadDebugInfoData().GetByteSize() > 0)
631289551Szbb      m_info = std::make_unique<DWARFDebugInfo>(*this, m_context);
632289551Szbb  }
633289550Szbb  return m_info.get();
634289550Szbb}
635289550Szbb
636289551Szbbconst DWARFDebugInfo *SymbolFileDWARF::DebugInfo() const {
637289551Szbb  return m_info.get();
638289551Szbb}
639289551Szbb
640289551SzbbDWARFUnit *
641296031SzbbSymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit) {
642289551Szbb  if (!comp_unit)
643289551Szbb    return nullptr;
644289551Szbb
645289551Szbb  DWARFDebugInfo *info = DebugInfo();
646296031Szbb  if (info) {
647289551Szbb    // The compile unit ID is the index of the DWARF unit.
648289551Szbb    DWARFUnit *dwarf_cu = info->GetUnitAtIndex(comp_unit->GetID());
649289551Szbb    if (dwarf_cu && dwarf_cu->GetUserData() == nullptr)
650289551Szbb      dwarf_cu->SetUserData(comp_unit);
651289551Szbb    return dwarf_cu;
652289551Szbb  }
653289551Szbb  return nullptr;
654289551Szbb}
655289551Szbb
656289551SzbbDWARFDebugRanges *SymbolFileDWARF::GetDebugRanges() {
657289551Szbb  if (!m_ranges) {
658289551Szbb    static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
659289551Szbb    Timer scoped_timer(func_cat, "%s this = %p", LLVM_PRETTY_FUNCTION,
660289551Szbb                       static_cast<void *>(this));
661289551Szbb
662289551Szbb    if (m_context.getOrLoadRangesData().GetByteSize() > 0)
663289551Szbb      m_ranges.reset(new DWARFDebugRanges());
664289551Szbb
665296031Szbb    if (m_ranges)
666296031Szbb      m_ranges->Extract(m_context);
667296031Szbb  }
668296031Szbb  return m_ranges.get();
669296031Szbb}
670296031Szbb
671296031Szbblldb::CompUnitSP SymbolFileDWARF::ParseCompileUnit(DWARFCompileUnit &dwarf_cu) {
672296031Szbb  CompUnitSP cu_sp;
673296031Szbb  CompileUnit *comp_unit = (CompileUnit *)dwarf_cu.GetUserData();
674296031Szbb  if (comp_unit) {
675296031Szbb    // We already parsed this compile unit, had out a shared pointer to it
676296031Szbb    cu_sp = comp_unit->shared_from_this();
677296031Szbb  } else {
678289551Szbb    if (&dwarf_cu.GetSymbolFileDWARF() != this) {
679289551Szbb      return dwarf_cu.GetSymbolFileDWARF().ParseCompileUnit(dwarf_cu);
680289551Szbb    } else if (dwarf_cu.GetOffset() == 0 && GetDebugMapSymfile()) {
681289551Szbb      // Let the debug map create the compile unit
682289551Szbb      cu_sp = m_debug_map_symfile->GetCompileUnit(this);
683289551Szbb      dwarf_cu.SetUserData(cu_sp.get());
684289551Szbb    } else {
685289551Szbb      ModuleSP module_sp(m_objfile_sp->GetModule());
686289551Szbb      if (module_sp) {
687289551Szbb        const DWARFBaseDIE cu_die =
688289551Szbb            dwarf_cu.GetNonSkeletonUnit().GetUnitDIEOnly();
689289551Szbb        if (cu_die) {
690289551Szbb          FileSpec cu_file_spec(cu_die.GetName(), dwarf_cu.GetPathStyle());
691289551Szbb          if (cu_file_spec) {
692289551Szbb            // If we have a full path to the compile unit, we don't need to
693289551Szbb            // resolve the file.  This can be expensive e.g. when the source
694289551Szbb            // files are NFS mounted.
695289551Szbb            cu_file_spec.MakeAbsolute(dwarf_cu.GetCompilationDirectory());
696289551Szbb
697289551Szbb            std::string remapped_file;
698289551Szbb            if (module_sp->RemapSourceFile(cu_file_spec.GetPath(),
699289551Szbb                                           remapped_file))
700289551Szbb              cu_file_spec.SetFile(remapped_file, FileSpec::Style::native);
701289551Szbb          }
702289551Szbb
703289551Szbb          LanguageType cu_language = DWARFUnit::LanguageTypeFromDWARF(
704289551Szbb              cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
705289551Szbb
706289551Szbb          bool is_optimized = dwarf_cu.GetNonSkeletonUnit().GetIsOptimized();
707289551Szbb          BuildCuTranslationTable();
708289551Szbb          cu_sp = std::make_shared<CompileUnit>(
709289551Szbb              module_sp, &dwarf_cu, cu_file_spec,
710289551Szbb              *GetDWARFUnitIndex(dwarf_cu.GetID()), cu_language,
711289551Szbb              is_optimized ? eLazyBoolYes : eLazyBoolNo);
712289551Szbb
713289551Szbb          dwarf_cu.SetUserData(cu_sp.get());
714289551Szbb
715289551Szbb          SetCompileUnitAtIndex(dwarf_cu.GetID(), cu_sp);
716289551Szbb        }
717289551Szbb      }
718289551Szbb    }
719289551Szbb  }
720289551Szbb  return cu_sp;
721289551Szbb}
722289551Szbb
723289551Szbbvoid SymbolFileDWARF::BuildCuTranslationTable() {
724289551Szbb  if (!m_lldb_cu_to_dwarf_unit.empty())
725289551Szbb    return;
726289551Szbb
727296602Szbb  DWARFDebugInfo *info = DebugInfo();
728289551Szbb  if (!info)
729289551Szbb    return;
730289551Szbb
731289551Szbb  if (!info->ContainsTypeUnits()) {
732289551Szbb    // We can use a 1-to-1 mapping. No need to build a translation table.
733289551Szbb    return;
734289551Szbb  }
735289551Szbb  for (uint32_t i = 0, num = info->GetNumUnits(); i < num; ++i) {
736289551Szbb    if (auto *cu = llvm::dyn_cast<DWARFCompileUnit>(info->GetUnitAtIndex(i))) {
737289551Szbb      cu->SetID(m_lldb_cu_to_dwarf_unit.size());
738289551Szbb      m_lldb_cu_to_dwarf_unit.push_back(i);
739289551Szbb    }
740289551Szbb  }
741289551Szbb}
742289551Szbb
743289551Szbbllvm::Optional<uint32_t> SymbolFileDWARF::GetDWARFUnitIndex(uint32_t cu_idx) {
744289551Szbb  BuildCuTranslationTable();
745297450Szbb  if (m_lldb_cu_to_dwarf_unit.empty())
746296031Szbb    return cu_idx;
747289551Szbb  if (cu_idx >= m_lldb_cu_to_dwarf_unit.size())
748296031Szbb    return llvm::None;
749296031Szbb  return m_lldb_cu_to_dwarf_unit[cu_idx];
750289551Szbb}
751289551Szbb
752289551Szbbuint32_t SymbolFileDWARF::CalculateNumCompileUnits() {
753289551Szbb  DWARFDebugInfo *info = DebugInfo();
754289551Szbb  if (!info)
755289551Szbb    return 0;
756289551Szbb  BuildCuTranslationTable();
757289551Szbb  return m_lldb_cu_to_dwarf_unit.empty() ? info->GetNumUnits()
758289551Szbb                                         : m_lldb_cu_to_dwarf_unit.size();
759289551Szbb}
760289551Szbb
761289551SzbbCompUnitSP SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx) {
762289551Szbb  ASSERT_MODULE_LOCK(this);
763289551Szbb  DWARFDebugInfo *info = DebugInfo();
764289551Szbb  if (!info)
765289551Szbb    return {};
766289551Szbb
767289551Szbb  if (llvm::Optional<uint32_t> dwarf_idx = GetDWARFUnitIndex(cu_idx)) {
768289551Szbb    if (auto *dwarf_cu = llvm::cast_or_null<DWARFCompileUnit>(
769289551Szbb            info->GetUnitAtIndex(*dwarf_idx)))
770289551Szbb      return ParseCompileUnit(*dwarf_cu);
771289551Szbb  }
772296032Szbb  return {};
773296032Szbb}
774289551Szbb
775289551SzbbFunction *SymbolFileDWARF::ParseFunction(CompileUnit &comp_unit,
776289551Szbb                                         const DWARFDIE &die) {
777289551Szbb  ASSERT_MODULE_LOCK(this);
778289551Szbb  if (!die.IsValid())
779289551Szbb    return nullptr;
780289551Szbb
781289551Szbb  auto type_system_or_err =
782289551Szbb      GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
783289551Szbb  if (auto err = type_system_or_err.takeError()) {
784289551Szbb    LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
785289551Szbb                   std::move(err), "Unable to parse function");
786289551Szbb    return nullptr;
787289551Szbb  }
788289551Szbb  DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
789289551Szbb  if (!dwarf_ast)
790289551Szbb    return nullptr;
791289551Szbb
792289551Szbb  return dwarf_ast->ParseFunctionFromDWARF(comp_unit, die);
793289551Szbb}
794289551Szbb
795289551Szbbbool SymbolFileDWARF::FixupAddress(Address &addr) {
796289551Szbb  SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
797289551Szbb  if (debug_map_symfile) {
798289551Szbb    return debug_map_symfile->LinkOSOAddress(addr);
799289551Szbb  }
800289551Szbb  // This is a normal DWARF file, no address fixups need to happen
801289551Szbb  return true;
802289551Szbb}
803289551Szbblldb::LanguageType SymbolFileDWARF::ParseLanguage(CompileUnit &comp_unit) {
804289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
805289551Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
806289551Szbb  if (dwarf_cu)
807289551Szbb    return dwarf_cu->GetLanguageType();
808289551Szbb  else
809289551Szbb    return eLanguageTypeUnknown;
810289551Szbb}
811289551Szbb
812289551Szbbsize_t SymbolFileDWARF::ParseFunctions(CompileUnit &comp_unit) {
813289551Szbb  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
814289551Szbb  Timer scoped_timer(func_cat, "SymbolFileDWARF::ParseFunctions");
815289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
816289551Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
817289551Szbb  if (!dwarf_cu)
818289551Szbb    return 0;
819289551Szbb
820289551Szbb  size_t functions_added = 0;
821289551Szbb  dwarf_cu = &dwarf_cu->GetNonSkeletonUnit();
822289551Szbb  for (DWARFDebugInfoEntry &entry : dwarf_cu->dies()) {
823289551Szbb    if (entry.Tag() != DW_TAG_subprogram)
824297450Szbb      continue;
825289551Szbb
826289551Szbb    DWARFDIE die(dwarf_cu, &entry);
827296031Szbb    if (comp_unit.FindFunctionByUID(die.GetID()))
828296031Szbb      continue;
829296031Szbb    if (ParseFunction(comp_unit, die))
830296031Szbb      ++functions_added;
831296031Szbb  }
832296031Szbb  // FixupTypes();
833297482Ssephe  return functions_added;
834296031Szbb}
835289551Szbb
836289551Szbbbool SymbolFileDWARF::ForEachExternalModule(
837289551Szbb    CompileUnit &comp_unit,
838289551Szbb    llvm::DenseSet<lldb_private::SymbolFile *> &visited_symbol_files,
839289551Szbb    llvm::function_ref<bool(Module &)> lambda) {
840289551Szbb  // Only visit each symbol file once.
841289551Szbb  if (!visited_symbol_files.insert(this).second)
842289551Szbb    return false;
843289551Szbb
844289551Szbb  UpdateExternalModuleListIfNeeded();
845289551Szbb  for (auto &p : m_external_type_modules) {
846289551Szbb    ModuleSP module = p.second;
847289551Szbb    if (!module)
848289551Szbb      continue;
849289551Szbb
850289551Szbb    // Invoke the action and potentially early-exit.
851289551Szbb    if (lambda(*module))
852289551Szbb      return true;
853289551Szbb
854289551Szbb    for (std::size_t i = 0; i < module->GetNumCompileUnits(); ++i) {
855289551Szbb      auto cu = module->GetCompileUnitAtIndex(i);
856289551Szbb      bool early_exit = cu->ForEachExternalModule(visited_symbol_files, lambda);
857289551Szbb      if (early_exit)
858289551Szbb        return true;
859289551Szbb    }
860289551Szbb  }
861289551Szbb  return false;
862289551Szbb}
863289551Szbb
864289551Szbbbool SymbolFileDWARF::ParseSupportFiles(CompileUnit &comp_unit,
865289551Szbb                                        FileSpecList &support_files) {
866289551Szbb  if (!comp_unit.GetLineTable())
867289551Szbb    ParseLineTable(comp_unit);
868289551Szbb  return true;
869289551Szbb}
870289551Szbb
871289551SzbbFileSpec SymbolFileDWARF::GetFile(DWARFUnit &unit, size_t file_idx) {
872289551Szbb  if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit)) {
873289551Szbb    if (CompileUnit *lldb_cu = GetCompUnitForDWARFCompUnit(*dwarf_cu))
874289551Szbb      return lldb_cu->GetSupportFiles().GetFileSpecAtIndex(file_idx);
875289551Szbb    return FileSpec();
876289551Szbb  }
877289551Szbb
878289551Szbb  auto &tu = llvm::cast<DWARFTypeUnit>(unit);
879289551Szbb  return GetTypeUnitSupportFiles(tu).GetFileSpecAtIndex(file_idx);
880289551Szbb}
881289551Szbb
882289551Szbbconst FileSpecList &
883289551SzbbSymbolFileDWARF::GetTypeUnitSupportFiles(DWARFTypeUnit &tu) {
884289551Szbb  static FileSpecList empty_list;
885289551Szbb
886289551Szbb  dw_offset_t offset = tu.GetLineTableOffset();
887289551Szbb  if (offset == DW_INVALID_OFFSET ||
888289551Szbb      offset == llvm::DenseMapInfo<dw_offset_t>::getEmptyKey() ||
889289551Szbb      offset == llvm::DenseMapInfo<dw_offset_t>::getTombstoneKey())
890289551Szbb    return empty_list;
891289551Szbb
892289551Szbb  // Many type units can share a line table, so parse the support file list
893289551Szbb  // once, and cache it based on the offset field.
894289551Szbb  auto iter_bool = m_type_unit_support_files.try_emplace(offset);
895289551Szbb  FileSpecList &list = iter_bool.first->second;
896289551Szbb  if (iter_bool.second) {
897289551Szbb    uint64_t line_table_offset = offset;
898289551Szbb    llvm::DWARFDataExtractor data = m_context.getOrLoadLineData().GetAsLLVM();
899289551Szbb    llvm::DWARFContext &ctx = m_context.GetAsLLVM();
900289551Szbb    llvm::DWARFDebugLine::Prologue prologue;
901289551Szbb    llvm::Error error = prologue.parse(data, &line_table_offset, ctx);
902289551Szbb    if (error) {
903289551Szbb      Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
904289551Szbb      LLDB_LOG_ERROR(log, std::move(error),
905289551Szbb                     "SymbolFileDWARF::GetTypeUnitSupportFiles failed to parse "
906289551Szbb                     "the line table prologue");
907289551Szbb    } else {
908289551Szbb      list = ParseSupportFilesFromPrologue(GetObjectFile()->GetModule(),
909289551Szbb                                           prologue, tu.GetPathStyle());
910296601Szbb    }
911289551Szbb  }
912289551Szbb  return list;
913289551Szbb}
914289551Szbb
915289551Szbbbool SymbolFileDWARF::ParseIsOptimized(CompileUnit &comp_unit) {
916289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
917289551Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
918289551Szbb  if (dwarf_cu)
919289551Szbb    return dwarf_cu->GetIsOptimized();
920289550Szbb  return false;
921289550Szbb}
922289550Szbb
923289551Szbbbool SymbolFileDWARF::ParseImportedModules(
924289551Szbb    const lldb_private::SymbolContext &sc,
925289551Szbb    std::vector<SourceModule> &imported_modules) {
926289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
927289551Szbb  assert(sc.comp_unit);
928289550Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
929289550Szbb  if (!dwarf_cu)
930289550Szbb    return false;
931289551Szbb  if (!ClangModulesDeclVendor::LanguageSupportsClangModules(
932289551Szbb          sc.comp_unit->GetLanguage()))
933289551Szbb    return false;
934289551Szbb  UpdateExternalModuleListIfNeeded();
935289551Szbb
936289551Szbb  const DWARFDIE die = dwarf_cu->DIE();
937289550Szbb  if (!die)
938296038Szbb    return false;
939289551Szbb
940289551Szbb  for (DWARFDIE child_die = die.GetFirstChild(); child_die;
941289550Szbb       child_die = child_die.GetSibling()) {
942289550Szbb    if (child_die.Tag() != DW_TAG_imported_declaration)
943289551Szbb      continue;
944289551Szbb
945289551Szbb    DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import);
946289551Szbb    if (module_die.Tag() != DW_TAG_module)
947289551Szbb      continue;
948289551Szbb
949289551Szbb    if (const char *name =
950289551Szbb            module_die.GetAttributeValueAsString(DW_AT_name, nullptr)) {
951289551Szbb      SourceModule module;
952289551Szbb      module.path.push_back(ConstString(name));
953289551Szbb
954289550Szbb      DWARFDIE parent_die = module_die;
955289550Szbb      while ((parent_die = parent_die.GetParent())) {
956289551Szbb        if (parent_die.Tag() != DW_TAG_module)
957289551Szbb          break;
958289550Szbb        if (const char *name =
959289551Szbb                parent_die.GetAttributeValueAsString(DW_AT_name, nullptr))
960289551Szbb          module.path.push_back(ConstString(name));
961289550Szbb      }
962289551Szbb      std::reverse(module.path.begin(), module.path.end());
963289551Szbb      if (const char *include_path = module_die.GetAttributeValueAsString(
964289551Szbb              DW_AT_LLVM_include_path, nullptr))
965289551Szbb        module.search_path = ConstString(include_path);
966289551Szbb      if (const char *sysroot = module_die.GetAttributeValueAsString(
967289551Szbb              DW_AT_LLVM_sysroot, nullptr))
968289551Szbb        module.sysroot = ConstString(sysroot);
969289550Szbb      imported_modules.push_back(module);
970289551Szbb    }
971289551Szbb  }
972289551Szbb  return true;
973289551Szbb}
974289551Szbb
975289551Szbbbool SymbolFileDWARF::ParseLineTable(CompileUnit &comp_unit) {
976289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
977289551Szbb  if (comp_unit.GetLineTable() != nullptr)
978289551Szbb    return true;
979289551Szbb
980289551Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
981289551Szbb  if (!dwarf_cu)
982289551Szbb    return false;
983289551Szbb
984289551Szbb  const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
985289551Szbb  if (!dwarf_cu_die)
986289551Szbb    return false;
987289551Szbb
988289550Szbb  const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(
989289551Szbb      DW_AT_stmt_list, DW_INVALID_OFFSET);
990289551Szbb  if (cu_line_offset == DW_INVALID_OFFSET)
991289551Szbb    return false;
992289551Szbb
993289550Szbb  llvm::DWARFDebugLine line;
994289550Szbb  const llvm::DWARFDebugLine::LineTable *line_table = ParseLLVMLineTable(
995297450Szbb      m_context, line, cu_line_offset, dwarf_cu->GetOffset());
996297450Szbb
997297450Szbb  if (!line_table)
998297450Szbb    return false;
999297450Szbb
1000297450Szbb  // FIXME: Rather than parsing the whole line table and then copying it over
1001297450Szbb  // into LLDB, we should explore using a callback to populate the line table
1002297450Szbb  // while we parse to reduce memory usage.
1003297450Szbb  std::unique_ptr<LineTable> line_table_up =
1004297450Szbb      std::make_unique<LineTable>(&comp_unit);
1005297450Szbb  LineSequence *sequence = line_table_up->CreateLineSequenceContainer();
1006297450Szbb  for (auto &row : line_table->Rows) {
1007297450Szbb    line_table_up->AppendLineEntryToSequence(
1008297450Szbb        sequence, row.Address.Address, row.Line, row.Column, row.File,
1009297450Szbb        row.IsStmt, row.BasicBlock, row.PrologueEnd, row.EpilogueBegin,
1010297450Szbb        row.EndSequence);
1011297450Szbb    if (row.EndSequence) {
1012297450Szbb      line_table_up->InsertSequence(sequence);
1013297450Szbb      sequence = line_table_up->CreateLineSequenceContainer();
1014297450Szbb    }
1015297450Szbb  }
1016297450Szbb
1017297450Szbb  if (SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile()) {
1018297450Szbb    // We have an object file that has a line table with addresses that are not
1019297450Szbb    // linked. We need to link the line table and convert the addresses that
1020297450Szbb    // are relative to the .o file into addresses for the main executable.
1021297450Szbb    comp_unit.SetLineTable(
1022297450Szbb        debug_map_symfile->LinkOSOLineTable(this, line_table_up.get()));
1023297450Szbb  } else {
1024297450Szbb    comp_unit.SetLineTable(line_table_up.release());
1025297450Szbb  }
1026289551Szbb
1027289551Szbb  comp_unit.SetSupportFiles(ParseSupportFilesFromPrologue(
1028289551Szbb      comp_unit.GetModule(), line_table->Prologue, dwarf_cu->GetPathStyle(),
1029289551Szbb      dwarf_cu->GetCompilationDirectory().GetCString()));
1030297450Szbb
1031297450Szbb  return true;
1032297450Szbb}
1033289551Szbb
1034297450Szbblldb_private::DebugMacrosSP
1035297450SzbbSymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset) {
1036297450Szbb  auto iter = m_debug_macros_map.find(*offset);
1037297450Szbb  if (iter != m_debug_macros_map.end())
1038297450Szbb    return iter->second;
1039297450Szbb
1040297450Szbb  const DWARFDataExtractor &debug_macro_data = m_context.getOrLoadMacroData();
1041297450Szbb  if (debug_macro_data.GetByteSize() == 0)
1042297450Szbb    return DebugMacrosSP();
1043297450Szbb
1044297450Szbb  lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1045289551Szbb  m_debug_macros_map[*offset] = debug_macros_sp;
1046297450Szbb
1047289551Szbb  const DWARFDebugMacroHeader &header =
1048297450Szbb      DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1049297450Szbb  DWARFDebugMacroEntry::ReadMacroEntries(
1050297450Szbb      debug_macro_data, m_context.getOrLoadStrData(), header.OffsetIs64Bit(),
1051289551Szbb      offset, this, debug_macros_sp);
1052289551Szbb
1053289550Szbb  return debug_macros_sp;
1054289551Szbb}
1055289551Szbb
1056289551Szbbbool SymbolFileDWARF::ParseDebugMacros(CompileUnit &comp_unit) {
1057289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1058289551Szbb
1059289550Szbb  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
1060289550Szbb  if (dwarf_cu == nullptr)
1061289551Szbb    return false;
1062289551Szbb
1063289551Szbb  const DWARFBaseDIE dwarf_cu_die = dwarf_cu->GetUnitDIEOnly();
1064289551Szbb  if (!dwarf_cu_die)
1065289551Szbb    return false;
1066289551Szbb
1067289551Szbb  lldb::offset_t sect_offset =
1068289551Szbb      dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1069289551Szbb  if (sect_offset == DW_INVALID_OFFSET)
1070289551Szbb    sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros,
1071289551Szbb                                                           DW_INVALID_OFFSET);
1072289551Szbb  if (sect_offset == DW_INVALID_OFFSET)
1073289551Szbb    return false;
1074289551Szbb
1075289551Szbb  comp_unit.SetDebugMacros(ParseDebugMacros(&sect_offset));
1076289551Szbb
1077289551Szbb  return true;
1078289550Szbb}
1079289550Szbb
1080289551Szbbsize_t SymbolFileDWARF::ParseBlocksRecursive(
1081289551Szbb    lldb_private::CompileUnit &comp_unit, Block *parent_block,
1082289551Szbb    const DWARFDIE &orig_die, addr_t subprogram_low_pc, uint32_t depth) {
1083289551Szbb  size_t blocks_added = 0;
1084289551Szbb  DWARFDIE die = orig_die;
1085289550Szbb  while (die) {
1086289550Szbb    dw_tag_t tag = die.Tag();
1087289551Szbb
1088297388Szbb    switch (tag) {
1089289550Szbb    case DW_TAG_inlined_subroutine:
1090289551Szbb    case DW_TAG_subprogram:
1091289551Szbb    case DW_TAG_lexical_block: {
1092289550Szbb      Block *block = nullptr;
1093289551Szbb      if (tag == DW_TAG_subprogram) {
1094289551Szbb        // Skip any DW_TAG_subprogram DIEs that are inside of a normal or
1095289551Szbb        // inlined functions. These will be parsed on their own as separate
1096289550Szbb        // entities.
1097289551Szbb
1098289551Szbb        if (depth > 0)
1099289551Szbb          break;
1100289551Szbb
1101289551Szbb        block = parent_block;
1102289551Szbb      } else {
1103289551Szbb        BlockSP block_sp(new Block(die.GetID()));
1104289551Szbb        parent_block->AddChild(block_sp);
1105296039Szbb        block = block_sp.get();
1106296039Szbb      }
1107289551Szbb      DWARFRangeList ranges;
1108289551Szbb      const char *name = nullptr;
1109289551Szbb      const char *mangled_name = nullptr;
1110289551Szbb
1111289551Szbb      int decl_file = 0;
1112289551Szbb      int decl_line = 0;
1113289551Szbb      int decl_column = 0;
1114289551Szbb      int call_file = 0;
1115289551Szbb      int call_line = 0;
1116289551Szbb      int call_column = 0;
1117289551Szbb      if (die.GetDIENamesAndRanges(name, mangled_name, ranges, decl_file,
1118289551Szbb                                   decl_line, decl_column, call_file, call_line,
1119289551Szbb                                   call_column, nullptr)) {
1120289551Szbb        if (tag == DW_TAG_subprogram) {
1121289551Szbb          assert(subprogram_low_pc == LLDB_INVALID_ADDRESS);
1122289551Szbb          subprogram_low_pc = ranges.GetMinRangeBase(0);
1123289551Szbb        } else if (tag == DW_TAG_inlined_subroutine) {
1124289551Szbb          // We get called here for inlined subroutines in two ways. The first
1125289551Szbb          // time is when we are making the Function object for this inlined
1126289551Szbb          // concrete instance.  Since we're creating a top level block at
1127289551Szbb          // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we
1128289551Szbb          // need to adjust the containing address. The second time is when we
1129289551Szbb          // are parsing the blocks inside the function that contains the
1130289551Szbb          // inlined concrete instance.  Since these will be blocks inside the
1131289551Szbb          // containing "real" function the offset will be for that function.
1132289551Szbb          if (subprogram_low_pc == LLDB_INVALID_ADDRESS) {
1133289551Szbb            subprogram_low_pc = ranges.GetMinRangeBase(0);
1134289551Szbb          }
1135289551Szbb        }
1136289551Szbb
1137289551Szbb        const size_t num_ranges = ranges.GetSize();
1138289551Szbb        for (size_t i = 0; i < num_ranges; ++i) {
1139289551Szbb          const DWARFRangeList::Entry &range = ranges.GetEntryRef(i);
1140289551Szbb          const addr_t range_base = range.GetRangeBase();
1141289551Szbb          if (range_base >= subprogram_low_pc)
1142289551Szbb            block->AddRange(Block::Range(range_base - subprogram_low_pc,
1143289551Szbb                                         range.GetByteSize()));
1144289551Szbb          else {
1145289551Szbb            GetObjectFile()->GetModule()->ReportError(
1146289551Szbb                "0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64
1147289551Szbb                ") which has a base that is less than the function's low PC "
1148289551Szbb                "0x%" PRIx64 ". Please file a bug and attach the file at the "
1149289551Szbb                "start of this error message",
1150289551Szbb                block->GetID(), range_base, range.GetRangeEnd(),
1151289550Szbb                subprogram_low_pc);
1152289550Szbb          }
1153289551Szbb        }
1154289551Szbb        block->FinalizeRanges();
1155289550Szbb
1156289551Szbb        if (tag != DW_TAG_subprogram &&
1157289551Szbb            (name != nullptr || mangled_name != nullptr)) {
1158289551Szbb          std::unique_ptr<Declaration> decl_up;
1159289551Szbb          if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1160289551Szbb            decl_up.reset(new Declaration(
1161289550Szbb                comp_unit.GetSupportFiles().GetFileSpecAtIndex(decl_file),
1162289550Szbb                decl_line, decl_column));
1163289551Szbb
1164289551Szbb          std::unique_ptr<Declaration> call_up;
1165289551Szbb          if (call_file != 0 || call_line != 0 || call_column != 0)
1166289551Szbb            call_up.reset(new Declaration(
1167289550Szbb                comp_unit.GetSupportFiles().GetFileSpecAtIndex(call_file),
1168289551Szbb                call_line, call_column));
1169289551Szbb
1170289551Szbb          block->SetInlinedFunctionInfo(name, mangled_name, decl_up.get(),
1171289551Szbb                                        call_up.get());
1172289551Szbb        }
1173289551Szbb
1174289551Szbb        ++blocks_added;
1175289551Szbb
1176289551Szbb        if (die.HasChildren()) {
1177289551Szbb          blocks_added +=
1178289551Szbb              ParseBlocksRecursive(comp_unit, block, die.GetFirstChild(),
1179289551Szbb                                   subprogram_low_pc, depth + 1);
1180289551Szbb        }
1181289551Szbb      }
1182289551Szbb    } break;
1183289551Szbb    default:
1184289551Szbb      break;
1185289551Szbb    }
1186289551Szbb
1187289551Szbb    // Only parse siblings of the block if we are not at depth zero. A depth of
1188289551Szbb    // zero indicates we are currently parsing the top level DW_TAG_subprogram
1189289551Szbb    // DIE
1190289551Szbb
1191289551Szbb    if (depth == 0)
1192289551Szbb      die.Clear();
1193289551Szbb    else
1194289551Szbb      die = die.GetSibling();
1195289551Szbb  }
1196289551Szbb  return blocks_added;
1197289551Szbb}
1198289551Szbb
1199289551Szbbbool SymbolFileDWARF::ClassOrStructIsVirtual(const DWARFDIE &parent_die) {
1200289551Szbb  if (parent_die) {
1201289551Szbb    for (DWARFDIE die = parent_die.GetFirstChild(); die;
1202289551Szbb         die = die.GetSibling()) {
1203289551Szbb      dw_tag_t tag = die.Tag();
1204289551Szbb      bool check_virtuality = false;
1205289551Szbb      switch (tag) {
1206289551Szbb      case DW_TAG_inheritance:
1207289551Szbb      case DW_TAG_subprogram:
1208289551Szbb        check_virtuality = true;
1209289551Szbb        break;
1210289551Szbb      default:
1211289551Szbb        break;
1212289550Szbb      }
1213289550Szbb      if (check_virtuality) {
1214289551Szbb        if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1215289551Szbb          return true;
1216289550Szbb      }
1217289551Szbb    }
1218289550Szbb  }
1219289550Szbb  return false;
1220289550Szbb}
1221289550Szbb
1222289550Szbbvoid SymbolFileDWARF::ParseDeclsForContext(CompilerDeclContext decl_ctx) {
1223289550Szbb  auto *type_system = decl_ctx.GetTypeSystem();
1224289550Szbb  if (type_system != nullptr)
1225289550Szbb    type_system->GetDWARFParser()->EnsureAllDIEsInDeclContextHaveBeenParsed(
1226289550Szbb        decl_ctx);
1227289551Szbb}
1228289551Szbb
1229289550Szbbuser_id_t SymbolFileDWARF::GetUID(DIERef ref) {
1230289550Szbb  if (GetDebugMapSymfile())
1231289550Szbb    return GetID() | ref.die_offset();
1232289550Szbb
1233289550Szbb  return user_id_t(GetDwoNum().getValueOr(0x7fffffff)) << 32 |
1234289550Szbb         ref.die_offset() |
1235289550Szbb         (lldb::user_id_t(ref.section() == DIERef::Section::DebugTypes) << 63);
1236289550Szbb}
1237289551Szbb
1238289551Szbbllvm::Optional<SymbolFileDWARF::DecodedUID>
1239289550SzbbSymbolFileDWARF::DecodeUID(lldb::user_id_t uid) {
1240289551Szbb  // This method can be called without going through the symbol vendor so we
1241289550Szbb  // need to lock the module.
1242289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1243289550Szbb  // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API we
1244289550Szbb  // must make sure we use the correct DWARF file when resolving things. On
1245289550Szbb  // MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1246289550Szbb  // SymbolFileDWARF classes, one for each .o file. We can often end up with
1247289550Szbb  // references to other DWARF objects and we must be ready to receive a
1248289550Szbb  // "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1249289551Szbb  // instance.
1250289551Szbb  if (SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile()) {
1251289550Szbb    SymbolFileDWARF *dwarf = debug_map->GetSymbolFileByOSOIndex(
1252289551Szbb        debug_map->GetOSOIndexFromUserID(uid));
1253289550Szbb    return DecodedUID{
1254289550Szbb        *dwarf, {llvm::None, DIERef::Section::DebugInfo, dw_offset_t(uid)}};
1255289550Szbb  }
1256289551Szbb  dw_offset_t die_offset = uid;
1257289551Szbb  if (die_offset == DW_INVALID_OFFSET)
1258289551Szbb    return llvm::None;
1259289551Szbb
1260289550Szbb  DIERef::Section section =
1261289551Szbb      uid >> 63 ? DIERef::Section::DebugTypes : DIERef::Section::DebugInfo;
1262289551Szbb
1263289550Szbb  llvm::Optional<uint32_t> dwo_num = uid >> 32 & 0x7fffffff;
1264289550Szbb  if (*dwo_num == 0x7fffffff)
1265289550Szbb    dwo_num = llvm::None;
1266289551Szbb
1267289550Szbb  return DecodedUID{*this, {dwo_num, section, die_offset}};
1268289551Szbb}
1269289551Szbb
1270289550SzbbDWARFDIE
1271289550SzbbSymbolFileDWARF::GetDIE(lldb::user_id_t uid) {
1272289550Szbb  // This method can be called without going through the symbol vendor so we
1273289550Szbb  // need to lock the module.
1274289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1275289550Szbb
1276289550Szbb  llvm::Optional<DecodedUID> decoded = DecodeUID(uid);
1277289551Szbb
1278289550Szbb  if (decoded)
1279289550Szbb    return decoded->dwarf.GetDIE(decoded->ref);
1280289551Szbb
1281289551Szbb  return DWARFDIE();
1282289550Szbb}
1283289550Szbb
1284289551SzbbCompilerDecl SymbolFileDWARF::GetDeclForUID(lldb::user_id_t type_uid) {
1285289551Szbb  // This method can be called without going through the symbol vendor so we
1286289550Szbb  // need to lock the module.
1287289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1288289550Szbb  // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1289289551Szbb  // SymbolFileDWARF::GetDIE(). See comments inside the
1290289551Szbb  // SymbolFileDWARF::GetDIE() for details.
1291289550Szbb  if (DWARFDIE die = GetDIE(type_uid))
1292289550Szbb    return die.GetDecl();
1293289550Szbb  return CompilerDecl();
1294289550Szbb}
1295289550Szbb
1296289550SzbbCompilerDeclContext
1297289550SzbbSymbolFileDWARF::GetDeclContextForUID(lldb::user_id_t type_uid) {
1298289550Szbb  // This method can be called without going through the symbol vendor so we
1299289550Szbb  // need to lock the module.
1300289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1301289551Szbb  // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1302289551Szbb  // SymbolFileDWARF::GetDIE(). See comments inside the
1303289550Szbb  // SymbolFileDWARF::GetDIE() for details.
1304289550Szbb  if (DWARFDIE die = GetDIE(type_uid))
1305289550Szbb    return die.GetDeclContext();
1306289550Szbb  return CompilerDeclContext();
1307296031Szbb}
1308296031Szbb
1309289550SzbbCompilerDeclContext
1310296031SzbbSymbolFileDWARF::GetDeclContextContainingUID(lldb::user_id_t type_uid) {
1311296031Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1312289550Szbb  // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1313289550Szbb  // SymbolFileDWARF::GetDIE(). See comments inside the
1314289550Szbb  // SymbolFileDWARF::GetDIE() for details.
1315296031Szbb  if (DWARFDIE die = GetDIE(type_uid))
1316296031Szbb    return die.GetContainingDeclContext();
1317289550Szbb  return CompilerDeclContext();
1318289550Szbb}
1319289550Szbb
1320289550SzbbType *SymbolFileDWARF::ResolveTypeUID(lldb::user_id_t type_uid) {
1321289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1322296031Szbb  // Anytime we have a lldb::user_id_t, we must get the DIE by calling
1323296031Szbb  // SymbolFileDWARF::GetDIE(). See comments inside the
1324296031Szbb  // SymbolFileDWARF::GetDIE() for details.
1325289550Szbb  if (DWARFDIE type_die = GetDIE(type_uid))
1326289550Szbb    return type_die.ResolveType();
1327289550Szbb  else
1328296031Szbb    return nullptr;
1329296031Szbb}
1330296031Szbb
1331296031Szbbllvm::Optional<SymbolFile::ArrayInfo>
1332296031SzbbSymbolFileDWARF::GetDynamicArrayInfoForUID(
1333296031Szbb    lldb::user_id_t type_uid, const lldb_private::ExecutionContext *exe_ctx) {
1334296031Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1335296031Szbb  if (DWARFDIE type_die = GetDIE(type_uid))
1336296031Szbb    return DWARFASTParser::ParseChildArrayInfo(type_die, exe_ctx);
1337296031Szbb  else
1338296031Szbb    return llvm::None;
1339296031Szbb}
1340289550Szbb
1341289550SzbbType *SymbolFileDWARF::ResolveTypeUID(const DIERef &die_ref) {
1342289550Szbb  return ResolveType(GetDIE(die_ref), true);
1343289550Szbb}
1344289550Szbb
1345289550SzbbType *SymbolFileDWARF::ResolveTypeUID(const DWARFDIE &die,
1346289550Szbb                                      bool assert_not_being_parsed) {
1347289550Szbb  if (die) {
1348289550Szbb    Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1349289550Szbb    if (log)
1350289550Szbb      GetObjectFile()->GetModule()->LogMessage(
1351289550Szbb          log, "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1352289550Szbb          die.GetOffset(), die.GetTagAsCString(), die.GetName());
1353289550Szbb
1354289551Szbb    // We might be coming in in the middle of a type tree (a class within a
1355289551Szbb    // class, an enum within a class), so parse any needed parent DIEs before
1356289551Szbb    // we get to this one...
1357289550Szbb    DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(die);
1358289550Szbb    if (decl_ctx_die) {
1359289550Szbb      if (log) {
1360289551Szbb        switch (decl_ctx_die.Tag()) {
1361289550Szbb        case DW_TAG_structure_type:
1362289550Szbb        case DW_TAG_union_type:
1363289551Szbb        case DW_TAG_class_type: {
1364289551Szbb          // Get the type, which could be a forward declaration
1365289550Szbb          if (log)
1366289550Szbb            GetObjectFile()->GetModule()->LogMessage(
1367289550Szbb                log,
1368289551Szbb                "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' "
1369289550Szbb                "resolve parent forward type for 0x%8.8x",
1370289550Szbb                die.GetOffset(), die.GetTagAsCString(), die.GetName(),
1371289550Szbb                decl_ctx_die.GetOffset());
1372289550Szbb        } break;
1373289550Szbb
1374289550Szbb        default:
1375289550Szbb          break;
1376289551Szbb        }
1377289551Szbb      }
1378289550Szbb    }
1379289550Szbb    return ResolveType(die);
1380289550Szbb  }
1381289551Szbb  return nullptr;
1382289551Szbb}
1383289551Szbb
1384289550Szbb// This function is used when SymbolFileDWARFDebugMap owns a bunch of
1385289550Szbb// SymbolFileDWARF objects to detect if this DWARF file is the one that can
1386289550Szbb// resolve a compiler_type.
1387289550Szbbbool SymbolFileDWARF::HasForwardDeclForClangType(
1388289550Szbb    const CompilerType &compiler_type) {
1389289550Szbb  CompilerType compiler_type_no_qualifiers =
1390289550Szbb      ClangUtil::RemoveFastQualifiers(compiler_type);
1391289550Szbb  if (GetForwardDeclClangTypeToDie().count(
1392289550Szbb          compiler_type_no_qualifiers.GetOpaqueQualType())) {
1393289550Szbb    return true;
1394289550Szbb  }
1395289550Szbb  TypeSystem *type_system = compiler_type.GetTypeSystem();
1396289550Szbb
1397289550Szbb  ClangASTContext *clang_type_system =
1398289550Szbb      llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1399289550Szbb  if (!clang_type_system)
1400289551Szbb    return false;
1401289551Szbb  DWARFASTParserClang *ast_parser =
1402289550Szbb      static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1403289550Szbb  return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1404289550Szbb}
1405289550Szbb
1406289550Szbbbool SymbolFileDWARF::CompleteType(CompilerType &compiler_type) {
1407289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1408289550Szbb
1409289551Szbb  ClangASTContext *clang_type_system =
1410289550Szbb      llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1411289550Szbb  if (clang_type_system) {
1412289550Szbb    DWARFASTParserClang *ast_parser =
1413289551Szbb        static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1414289551Szbb    if (ast_parser &&
1415289550Szbb        ast_parser->GetClangASTImporter().CanImport(compiler_type))
1416289550Szbb      return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1417289550Szbb  }
1418289551Szbb
1419289551Szbb  // We have a struct/union/class/enum that needs to be fully resolved.
1420289551Szbb  CompilerType compiler_type_no_qualifiers =
1421289550Szbb      ClangUtil::RemoveFastQualifiers(compiler_type);
1422289550Szbb  auto die_it = GetForwardDeclClangTypeToDie().find(
1423289550Szbb      compiler_type_no_qualifiers.GetOpaqueQualType());
1424289550Szbb  if (die_it == GetForwardDeclClangTypeToDie().end()) {
1425289550Szbb    // We have already resolved this type...
1426289550Szbb    return true;
1427289550Szbb  }
1428289550Szbb
1429289550Szbb  DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1430289550Szbb  if (dwarf_die) {
1431289550Szbb    // Once we start resolving this type, remove it from the forward
1432289550Szbb    // declaration map in case anyone child members or other types require this
1433289550Szbb    // type to get resolved. The type will get resolved when all of the calls
1434289550Szbb    // to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition are done.
1435289550Szbb    GetForwardDeclClangTypeToDie().erase(die_it);
1436289550Szbb
1437289550Szbb    Type *type = GetDIEToType().lookup(dwarf_die.GetDIE());
1438289550Szbb
1439289550Szbb    Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO |
1440289550Szbb                                          DWARF_LOG_TYPE_COMPLETION));
1441289550Szbb    if (log)
1442289550Szbb      GetObjectFile()->GetModule()->LogMessageVerboseBacktrace(
1443289550Szbb          log, "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1444289550Szbb          dwarf_die.GetID(), dwarf_die.GetTagAsCString(),
1445289550Szbb          type->GetName().AsCString());
1446289550Szbb    assert(compiler_type);
1447289550Szbb    DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1448289550Szbb    if (dwarf_ast)
1449289551Szbb      return dwarf_ast->CompleteTypeFromDWARF(dwarf_die, type, compiler_type);
1450289551Szbb  }
1451289550Szbb  return false;
1452289550Szbb}
1453289550Szbb
1454289550SzbbType *SymbolFileDWARF::ResolveType(const DWARFDIE &die,
1455289550Szbb                                   bool assert_not_being_parsed,
1456289550Szbb                                   bool resolve_function_context) {
1457289550Szbb  if (die) {
1458289551Szbb    Type *type = GetTypeForDIE(die, resolve_function_context).get();
1459289550Szbb
1460289550Szbb    if (assert_not_being_parsed) {
1461289550Szbb      if (type != DIE_IS_BEING_PARSED)
1462289550Szbb        return type;
1463289550Szbb
1464289550Szbb      GetObjectFile()->GetModule()->ReportError(
1465289551Szbb          "Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1466289551Szbb          die.GetOffset(), die.GetTagAsCString(), die.GetName());
1467289551Szbb
1468289550Szbb    } else
1469289550Szbb      return type;
1470289550Szbb  }
1471289550Szbb  return nullptr;
1472289550Szbb}
1473289550Szbb
1474289550SzbbCompileUnit *
1475289550SzbbSymbolFileDWARF::GetCompUnitForDWARFCompUnit(DWARFCompileUnit &dwarf_cu) {
1476289550Szbb  // Check if the symbol vendor already knows about this compile unit?
1477289550Szbb  if (dwarf_cu.GetUserData() == nullptr) {
1478289551Szbb    // The symbol vendor doesn't know about this compile unit, we need to parse
1479289551Szbb    // and add it to the symbol vendor object.
1480289550Szbb    return ParseCompileUnit(dwarf_cu).get();
1481289550Szbb  }
1482289550Szbb  return (CompileUnit *)dwarf_cu.GetUserData();
1483289550Szbb}
1484289550Szbb
1485289550Szbbsize_t SymbolFileDWARF::GetObjCMethodDIEOffsets(ConstString class_name,
1486289550Szbb                                                DIEArray &method_die_offsets) {
1487289550Szbb  method_die_offsets.clear();
1488289550Szbb  m_index->GetObjCMethods(class_name, method_die_offsets);
1489289551Szbb  return method_die_offsets.size();
1490289551Szbb}
1491289550Szbb
1492289550Szbbbool SymbolFileDWARF::GetFunction(const DWARFDIE &die, SymbolContext &sc) {
1493289551Szbb  sc.Clear(false);
1494289551Szbb
1495289550Szbb  if (die && llvm::isa<DWARFCompileUnit>(die.GetCU())) {
1496289550Szbb    // Check if the symbol vendor already knows about this compile unit?
1497289551Szbb    sc.comp_unit =
1498289551Szbb        GetCompUnitForDWARFCompUnit(llvm::cast<DWARFCompileUnit>(*die.GetCU()));
1499289550Szbb
1500289550Szbb    sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
1501289550Szbb    if (sc.function == nullptr)
1502289551Szbb      sc.function = ParseFunction(*sc.comp_unit, die);
1503289551Szbb
1504289550Szbb    if (sc.function) {
1505289550Szbb      sc.module_sp = sc.function->CalculateSymbolContextModule();
1506289551Szbb      return true;
1507289550Szbb    }
1508289550Szbb  }
1509289551Szbb
1510289551Szbb  return false;
1511289551Szbb}
1512289551Szbb
1513289550Szbblldb::ModuleSP SymbolFileDWARF::GetExternalModule(ConstString name) {
1514289550Szbb  UpdateExternalModuleListIfNeeded();
1515289550Szbb  const auto &pos = m_external_type_modules.find(name);
1516289550Szbb  if (pos != m_external_type_modules.end())
1517289550Szbb    return pos->second;
1518289550Szbb  else
1519289550Szbb    return lldb::ModuleSP();
1520289550Szbb}
1521289550Szbb
1522289550SzbbDWARFDIE
1523289550SzbbSymbolFileDWARF::GetDIE(const DIERef &die_ref) {
1524289550Szbb  if (die_ref.dwo_num()) {
1525289550Szbb    return DebugInfo()
1526289550Szbb        ->GetUnitAtIndex(*die_ref.dwo_num())
1527289550Szbb        ->GetDwoSymbolFile()
1528289550Szbb        ->GetDIE(die_ref);
1529289550Szbb  }
1530289550Szbb
1531289550Szbb  DWARFDebugInfo *debug_info = DebugInfo();
1532289551Szbb  if (debug_info)
1533289551Szbb    return debug_info->GetDIE(die_ref);
1534289550Szbb  else
1535289550Szbb    return DWARFDIE();
1536289551Szbb}
1537289550Szbb
1538289551Szbb/// Return the DW_AT_(GNU_)dwo_name.
1539289551Szbbstatic const char *GetDWOName(DWARFCompileUnit &dwarf_cu,
1540289551Szbb                              const DWARFDebugInfoEntry &cu_die) {
1541289551Szbb  const char *dwo_name =
1542289551Szbb      cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1543289551Szbb  if (!dwo_name)
1544289551Szbb    dwo_name =
1545289551Szbb        cu_die.GetAttributeValueAsString(&dwarf_cu, DW_AT_dwo_name, nullptr);
1546289551Szbb  return dwo_name;
1547289551Szbb}
1548289551Szbb
1549289551Szbb/// Return the DW_AT_(GNU_)dwo_id.
1550289551Szbb/// FIXME: Technically 0 is a valid hash.
1551289551Szbbstatic uint64_t GetDWOId(DWARFCompileUnit &dwarf_cu,
1552289551Szbb                         const DWARFDebugInfoEntry &cu_die) {
1553289550Szbb  uint64_t dwo_id =
1554289550Szbb      cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_GNU_dwo_id, 0);
1555289550Szbb  if (!dwo_id)
1556289550Szbb    dwo_id = cu_die.GetAttributeValueAsUnsigned(&dwarf_cu, DW_AT_dwo_id, 0);
1557289550Szbb  return dwo_id;
1558289550Szbb}
1559289550Szbb
1560289550Szbbllvm::Optional<uint64_t> SymbolFileDWARF::GetDWOId() {
1561289550Szbb  if (GetNumCompileUnits() == 1) {
1562289550Szbb    if (auto comp_unit = GetCompileUnitAtIndex(0))
1563289550Szbb      if (DWARFCompileUnit *cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1564289550Szbb              GetDWARFCompileUnit(comp_unit.get())))
1565289550Szbb        if (DWARFDebugInfoEntry *cu_die = cu->DIE().GetDIE())
1566289551Szbb          if (uint64_t dwo_id = ::GetDWOId(*cu, *cu_die))
1567289551Szbb            return dwo_id;
1568289550Szbb  }
1569289551Szbb  return {};
1570289550Szbb}
1571289550Szbb
1572289550Szbbstd::unique_ptr<SymbolFileDWARFDwo>
1573289550SzbbSymbolFileDWARF::GetDwoSymbolFileForCompileUnit(
1574289550Szbb    DWARFUnit &unit, const DWARFDebugInfoEntry &cu_die) {
1575289551Szbb  // If this is a Darwin-style debug map (non-.dSYM) symbol file,
1576289550Szbb  // never attempt to load ELF-style DWO files since the -gmodules
1577289550Szbb  // support uses the same DWO machanism to specify full debug info
1578289550Szbb  // files for modules. This is handled in
1579289550Szbb  // UpdateExternalModuleListIfNeeded().
1580289550Szbb  if (GetDebugMapSymfile())
1581289551Szbb    return nullptr;
1582289550Szbb
1583289550Szbb  DWARFCompileUnit *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(&unit);
1584289550Szbb  // Only compile units can be split into two parts.
1585289550Szbb  if (!dwarf_cu)
1586289550Szbb    return nullptr;
1587289551Szbb
1588289550Szbb  const char *dwo_name = GetDWOName(*dwarf_cu, cu_die);
1589289550Szbb  if (!dwo_name)
1590289550Szbb    return nullptr;
1591289551Szbb
1592289551Szbb  SymbolFileDWARFDwp *dwp_symfile = GetDwpSymbolFile();
1593289551Szbb  if (dwp_symfile) {
1594289551Szbb    uint64_t dwo_id = ::GetDWOId(*dwarf_cu, cu_die);
1595289551Szbb    std::unique_ptr<SymbolFileDWARFDwo> dwo_symfile =
1596289551Szbb        dwp_symfile->GetSymbolFileForDwoId(*dwarf_cu, dwo_id);
1597289551Szbb    if (dwo_symfile)
1598289551Szbb      return dwo_symfile;
1599289550Szbb  }
1600289550Szbb
1601289551Szbb  FileSpec dwo_file(dwo_name);
1602289550Szbb  FileSystem::Instance().Resolve(dwo_file);
1603289550Szbb  if (dwo_file.IsRelative()) {
1604289551Szbb    const char *comp_dir =
1605289551Szbb        cu_die.GetAttributeValueAsString(dwarf_cu, DW_AT_comp_dir, nullptr);
1606289550Szbb    if (!comp_dir)
1607289550Szbb      return nullptr;
1608289550Szbb
1609289551Szbb    dwo_file.SetFile(comp_dir, FileSpec::Style::native);
1610289550Szbb    FileSystem::Instance().Resolve(dwo_file);
1611289550Szbb    dwo_file.AppendPathComponent(dwo_name);
1612289550Szbb  }
1613289550Szbb
1614289551Szbb  if (!FileSystem::Instance().Exists(dwo_file))
1615289550Szbb    return nullptr;
1616289551Szbb
1617289550Szbb  const lldb::offset_t file_offset = 0;
1618289550Szbb  DataBufferSP dwo_file_data_sp;
1619289550Szbb  lldb::offset_t dwo_file_data_offset = 0;
1620289550Szbb  ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(
1621289550Szbb      GetObjectFile()->GetModule(), &dwo_file, file_offset,
1622289550Szbb      FileSystem::Instance().GetByteSize(dwo_file), dwo_file_data_sp,
1623289550Szbb      dwo_file_data_offset);
1624289550Szbb  if (dwo_obj_file == nullptr)
1625289550Szbb    return nullptr;
1626289550Szbb
1627289550Szbb  return std::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, *dwarf_cu);
1628289551Szbb}
1629289550Szbb
1630289550Szbbvoid SymbolFileDWARF::UpdateExternalModuleListIfNeeded() {
1631289551Szbb  if (m_fetched_external_modules)
1632289551Szbb    return;
1633289550Szbb  m_fetched_external_modules = true;
1634289551Szbb  DWARFDebugInfo *debug_info = DebugInfo();
1635289551Szbb
1636289550Szbb  // Follow DWO skeleton unit breadcrumbs.
1637289550Szbb  const uint32_t num_compile_units = GetNumCompileUnits();
1638289551Szbb  for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
1639289551Szbb    auto *dwarf_cu =
1640289551Szbb        llvm::dyn_cast<DWARFCompileUnit>(debug_info->GetUnitAtIndex(cu_idx));
1641289550Szbb    if (!dwarf_cu)
1642289550Szbb      continue;
1643289551Szbb
1644289551Szbb    const DWARFBaseDIE die = dwarf_cu->GetUnitDIEOnly();
1645289550Szbb    if (!die || die.HasChildren() || !die.GetDIE())
1646289550Szbb      continue;
1647289550Szbb
1648289550Szbb    const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1649289550Szbb    if (!name)
1650289550Szbb      continue;
1651289550Szbb
1652289550Szbb    ConstString const_name(name);
1653289550Szbb    ModuleSP &module_sp = m_external_type_modules[const_name];
1654289550Szbb    if (module_sp)
1655289550Szbb      continue;
1656289550Szbb
1657289550Szbb    const char *dwo_path = GetDWOName(*dwarf_cu, *die.GetDIE());
1658289550Szbb    if (!dwo_path)
1659289550Szbb      continue;
1660289550Szbb
1661289550Szbb    ModuleSpec dwo_module_spec;
1662289550Szbb    dwo_module_spec.GetFileSpec().SetFile(dwo_path, FileSpec::Style::native);
1663289550Szbb    if (dwo_module_spec.GetFileSpec().IsRelative()) {
1664289550Szbb      const char *comp_dir =
1665289550Szbb          die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1666289550Szbb      if (comp_dir) {
1667289551Szbb        dwo_module_spec.GetFileSpec().SetFile(comp_dir,
1668289550Szbb                                              FileSpec::Style::native);
1669289550Szbb        FileSystem::Instance().Resolve(dwo_module_spec.GetFileSpec());
1670289551Szbb        dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1671289551Szbb      }
1672289550Szbb    }
1673289550Szbb    dwo_module_spec.GetArchitecture() =
1674289551Szbb        m_objfile_sp->GetModule()->GetArchitecture();
1675289551Szbb
1676289550Szbb    // When LLDB loads "external" modules it looks at the presence of
1677289550Szbb    // DW_AT_dwo_name. However, when the already created module
1678289550Szbb    // (corresponding to .dwo itself) is being processed, it will see
1679289550Szbb    // the presence of DW_AT_dwo_name (which contains the name of dwo
1680297388Szbb    // file) and will try to call ModuleList::GetSharedModule
1681289550Szbb    // again. In some cases (i.e., for empty files) Clang 4.0
1682289550Szbb    // generates a *.dwo file which has DW_AT_dwo_name, but no
1683289550Szbb    // DW_AT_comp_dir. In this case the method
1684289551Szbb    // ModuleList::GetSharedModule will fail and the warning will be
1685289550Szbb    // printed. However, as one can notice in this case we don't
1686289550Szbb    // actually need to try to load the already loaded module
1687289550Szbb    // (corresponding to .dwo) so we simply skip it.
1688289551Szbb    if (m_objfile_sp->GetFileSpec().GetFileNameExtension() == ".dwo" &&
1689289551Szbb        llvm::StringRef(m_objfile_sp->GetFileSpec().GetPath())
1690289550Szbb            .endswith(dwo_module_spec.GetFileSpec().GetPath())) {
1691289551Szbb      continue;
1692297388Szbb    }
1693289550Szbb
1694289550Szbb    Status error = ModuleList::GetSharedModule(dwo_module_spec, module_sp,
1695289550Szbb                                               nullptr, nullptr, nullptr);
1696289550Szbb    if (!module_sp) {
1697289551Szbb      GetObjectFile()->GetModule()->ReportWarning(
1698289551Szbb          "0x%8.8x: unable to locate module needed for external types: "
1699289550Szbb          "%s\nerror: %s\nDebugging will be degraded due to missing "
1700289550Szbb          "types. Rebuilding the project will regenerate the needed "
1701289550Szbb          "module files.",
1702289551Szbb          die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str(),
1703289550Szbb          error.AsCString("unknown error"));
1704289550Szbb      continue;
1705289551Szbb    }
1706289551Szbb
1707289550Szbb    // Verify the DWO hash.
1708289551Szbb    // FIXME: Technically "0" is a valid hash.
1709289550Szbb    uint64_t dwo_id = ::GetDWOId(*dwarf_cu, *die.GetDIE());
1710289550Szbb    if (!dwo_id)
1711289550Szbb      continue;
1712289550Szbb
1713289550Szbb    auto *dwo_symfile =
1714289550Szbb        llvm::dyn_cast_or_null<SymbolFileDWARF>(module_sp->GetSymbolFile());
1715289550Szbb    if (!dwo_symfile)
1716289550Szbb      continue;
1717289551Szbb    llvm::Optional<uint64_t> dwo_dwo_id = dwo_symfile->GetDWOId();
1718289551Szbb    if (!dwo_dwo_id)
1719289550Szbb      continue;
1720289551Szbb
1721289550Szbb    if (dwo_id != dwo_dwo_id) {
1722289550Szbb      GetObjectFile()->GetModule()->ReportWarning(
1723289550Szbb          "0x%8.8x: Module %s is out-of-date (hash mismatch). Type information "
1724289550Szbb          "from this module may be incomplete or inconsistent with the rest of "
1725289550Szbb          "the program. Rebuilding the project will regenerate the needed "
1726289550Szbb          "module files.",
1727289551Szbb          die.GetOffset(), dwo_module_spec.GetFileSpec().GetPath().c_str());
1728289551Szbb    }
1729289550Szbb  }
1730289551Szbb}
1731289551Szbb
1732289550SzbbSymbolFileDWARF::GlobalVariableMap &SymbolFileDWARF::GetGlobalAranges() {
1733289550Szbb  if (!m_global_aranges_up) {
1734289551Szbb    m_global_aranges_up.reset(new GlobalVariableMap());
1735289550Szbb
1736289550Szbb    ModuleSP module_sp = GetObjectFile()->GetModule();
1737289550Szbb    if (module_sp) {
1738289550Szbb      const size_t num_cus = module_sp->GetNumCompileUnits();
1739289550Szbb      for (size_t i = 0; i < num_cus; ++i) {
1740289550Szbb        CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1741289550Szbb        if (cu_sp) {
1742289550Szbb          VariableListSP globals_sp = cu_sp->GetVariableList(true);
1743289551Szbb          if (globals_sp) {
1744289551Szbb            const size_t num_globals = globals_sp->GetSize();
1745289551Szbb            for (size_t g = 0; g < num_globals; ++g) {
1746289551Szbb              VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1747289551Szbb              if (var_sp && !var_sp->GetLocationIsConstantValueData()) {
1748289551Szbb                const DWARFExpression &location = var_sp->LocationExpression();
1749289550Szbb                Value location_result;
1750289550Szbb                Status error;
1751289551Szbb                if (location.Evaluate(nullptr, LLDB_INVALID_ADDRESS, nullptr,
1752289550Szbb                                      nullptr, location_result, &error)) {
1753289550Szbb                  if (location_result.GetValueType() ==
1754289551Szbb                      Value::eValueTypeFileAddress) {
1755289551Szbb                    lldb::addr_t file_addr =
1756289550Szbb                        location_result.GetScalar().ULongLong();
1757289550Szbb                    lldb::addr_t byte_size = 1;
1758296030Szbb                    if (var_sp->GetType())
1759289550Szbb                      byte_size =
1760289551Szbb                          var_sp->GetType()->GetByteSize().getValueOr(0);
1761289550Szbb                    m_global_aranges_up->Append(GlobalVariableMap::Entry(
1762296039Szbb                        file_addr, byte_size, var_sp.get()));
1763289550Szbb                  }
1764296030Szbb                }
1765296030Szbb              }
1766296030Szbb            }
1767296039Szbb          }
1768296030Szbb        }
1769296030Szbb      }
1770296030Szbb    }
1771289550Szbb    m_global_aranges_up->Sort();
1772296039Szbb  }
1773296039Szbb  return *m_global_aranges_up;
1774289550Szbb}
1775289551Szbb
1776289550Szbbuint32_t SymbolFileDWARF::ResolveSymbolContext(const Address &so_addr,
1777289550Szbb                                               SymbolContextItem resolve_scope,
1778289550Szbb                                               SymbolContext &sc) {
1779289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1780289550Szbb  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
1781289550Szbb  Timer scoped_timer(func_cat,
1782289550Szbb                     "SymbolFileDWARF::"
1783289550Szbb                     "ResolveSymbolContext (so_addr = { "
1784289550Szbb                     "section = %p, offset = 0x%" PRIx64
1785296039Szbb                     " }, resolve_scope = 0x%8.8x)",
1786296039Szbb                     static_cast<void *>(so_addr.GetSection().get()),
1787296039Szbb                     so_addr.GetOffset(), resolve_scope);
1788296039Szbb  uint32_t resolved = 0;
1789296039Szbb  if (resolve_scope &
1790296039Szbb      (eSymbolContextCompUnit | eSymbolContextFunction | eSymbolContextBlock |
1791296039Szbb       eSymbolContextLineEntry | eSymbolContextVariable)) {
1792296039Szbb    lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1793296030Szbb
1794296039Szbb    DWARFDebugInfo *debug_info = DebugInfo();
1795296039Szbb    if (debug_info) {
1796296039Szbb      llvm::Expected<DWARFDebugAranges &> aranges =
1797296039Szbb          debug_info->GetCompileUnitAranges();
1798296039Szbb      if (!aranges) {
1799296039Szbb        Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
1800296039Szbb        LLDB_LOG_ERROR(log, aranges.takeError(),
1801296039Szbb                       "SymbolFileDWARF::ResolveSymbolContext failed to get cu "
1802296039Szbb                       "aranges.  {0}");
1803296039Szbb        return 0;
1804296030Szbb      }
1805296030Szbb
1806296030Szbb      const dw_offset_t cu_offset = aranges->FindAddress(file_vm_addr);
1807296030Szbb      if (cu_offset == DW_INVALID_OFFSET) {
1808296030Szbb        // Global variables are not in the compile unit address ranges. The
1809296030Szbb        // only way to currently find global variables is to iterate over the
1810296030Szbb        // .debug_pubnames or the __apple_names table and find all items in
1811296039Szbb        // there that point to DW_TAG_variable DIEs and then find the address
1812296039Szbb        // that matches.
1813296039Szbb        if (resolve_scope & eSymbolContextVariable) {
1814296030Szbb          GlobalVariableMap &map = GetGlobalAranges();
1815296039Szbb          const GlobalVariableMap::Entry *entry =
1816296039Szbb              map.FindEntryThatContains(file_vm_addr);
1817296030Szbb          if (entry && entry->data) {
1818296030Szbb            Variable *variable = entry->data;
1819296030Szbb            SymbolContextScope *scc = variable->GetSymbolContextScope();
1820296030Szbb            if (scc) {
1821296030Szbb              scc->CalculateSymbolContext(&sc);
1822296030Szbb              sc.variable = variable;
1823296030Szbb            }
1824296030Szbb            return sc.GetResolvedMask();
1825296030Szbb          }
1826296030Szbb        }
1827296030Szbb      } else {
1828296030Szbb        uint32_t cu_idx = DW_INVALID_INDEX;
1829296030Szbb        if (auto *dwarf_cu = llvm::dyn_cast_or_null<DWARFCompileUnit>(
1830296030Szbb                debug_info->GetUnitAtOffset(DIERef::Section::DebugInfo,
1831296030Szbb                                            cu_offset, &cu_idx))) {
1832296030Szbb          sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
1833296030Szbb          if (sc.comp_unit) {
1834296030Szbb            resolved |= eSymbolContextCompUnit;
1835296030Szbb
1836296030Szbb            bool force_check_line_table = false;
1837296030Szbb            if (resolve_scope &
1838296030Szbb                (eSymbolContextFunction | eSymbolContextBlock)) {
1839296030Szbb              DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1840296030Szbb              DWARFDIE block_die;
1841296030Szbb              if (function_die) {
1842296030Szbb                sc.function =
1843296030Szbb                    sc.comp_unit->FindFunctionByUID(function_die.GetID()).get();
1844296030Szbb                if (sc.function == nullptr)
1845296030Szbb                  sc.function = ParseFunction(*sc.comp_unit, function_die);
1846296030Szbb
1847296030Szbb                if (sc.function && (resolve_scope & eSymbolContextBlock))
1848296030Szbb                  block_die = function_die.LookupDeepestBlock(file_vm_addr);
1849296030Szbb              } else {
1850296030Szbb                // We might have had a compile unit that had discontiguous
1851296030Szbb                // address ranges where the gaps are symbols that don't have
1852296030Szbb                // any debug info. Discontiguous compile unit address ranges
1853296030Szbb                // should only happen when there aren't other functions from
1854296030Szbb                // other compile units in these gaps. This helps keep the size
1855296030Szbb                // of the aranges down.
1856296030Szbb                force_check_line_table = true;
1857296039Szbb              }
1858296039Szbb
1859296030Szbb              if (sc.function != nullptr) {
1860296030Szbb                resolved |= eSymbolContextFunction;
1861296039Szbb
1862296039Szbb                if (resolve_scope & eSymbolContextBlock) {
1863296039Szbb                  Block &block = sc.function->GetBlock(true);
1864296039Szbb
1865296039Szbb                  if (block_die)
1866296039Szbb                    sc.block = block.FindBlockByID(block_die.GetID());
1867296039Szbb                  else
1868296039Szbb                    sc.block = block.FindBlockByID(function_die.GetID());
1869296039Szbb                  if (sc.block)
1870296039Szbb                    resolved |= eSymbolContextBlock;
1871296039Szbb                }
1872296039Szbb              }
1873296039Szbb            }
1874296039Szbb
1875296039Szbb            if ((resolve_scope & eSymbolContextLineEntry) ||
1876296039Szbb                force_check_line_table) {
1877296030Szbb              LineTable *line_table = sc.comp_unit->GetLineTable();
1878296039Szbb              if (line_table != nullptr) {
1879296030Szbb                // And address that makes it into this function should be in
1880296030Szbb                // terms of this debug file if there is no debug map, or it
1881289550Szbb                // will be an address in the .o file which needs to be fixed up
1882289550Szbb                // to be in terms of the debug map executable. Either way,
1883289551Szbb                // calling FixupAddress() will work for us.
1884289551Szbb                Address exe_so_addr(so_addr);
1885289550Szbb                if (FixupAddress(exe_so_addr)) {
1886289550Szbb                  if (line_table->FindLineEntryByAddress(exe_so_addr,
1887289550Szbb                                                         sc.line_entry)) {
1888289551Szbb                    resolved |= eSymbolContextLineEntry;
1889289550Szbb                  }
1890289550Szbb                }
1891289550Szbb              }
1892289550Szbb            }
1893289550Szbb
1894289550Szbb            if (force_check_line_table &&
1895289550Szbb                !(resolved & eSymbolContextLineEntry)) {
1896289550Szbb              // We might have had a compile unit that had discontiguous
1897289550Szbb              // address ranges where the gaps are symbols that don't have any
1898289550Szbb              // debug info. Discontiguous compile unit address ranges should
1899289550Szbb              // only happen when there aren't other functions from other
1900289550Szbb              // compile units in these gaps. This helps keep the size of the
1901289550Szbb              // aranges down.
1902289551Szbb              sc.comp_unit = nullptr;
1903297450Szbb              resolved &= ~eSymbolContextCompUnit;
1904297450Szbb            }
1905289550Szbb          } else {
1906289551Szbb            GetObjectFile()->GetModule()->ReportWarning(
1907296039Szbb                "0x%8.8x: compile unit %u failed to create a valid "
1908289551Szbb                "lldb_private::CompileUnit class.",
1909289551Szbb                cu_offset, cu_idx);
1910289551Szbb          }
1911296039Szbb        }
1912289551Szbb      }
1913289550Szbb    }
1914289551Szbb  }
1915289551Szbb  return resolved;
1916289551Szbb}
1917289551Szbb
1918289551Szbbuint32_t SymbolFileDWARF::ResolveSymbolContext(const FileSpec &file_spec,
1919289551Szbb                                               uint32_t line,
1920289551Szbb                                               bool check_inlines,
1921289551Szbb                                               SymbolContextItem resolve_scope,
1922297450Szbb                                               SymbolContextList &sc_list) {
1923297450Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
1924289551Szbb  const uint32_t prev_size = sc_list.GetSize();
1925297450Szbb  if (resolve_scope & eSymbolContextCompUnit) {
1926297450Szbb    for (uint32_t cu_idx = 0, num_cus = GetNumCompileUnits(); cu_idx < num_cus;
1927289551Szbb         ++cu_idx) {
1928289550Szbb      CompileUnit *dc_cu = ParseCompileUnitAtIndex(cu_idx).get();
1929289550Szbb      if (!dc_cu)
1930289551Szbb        continue;
1931296039Szbb
1932297450Szbb      bool file_spec_matches_cu_file_spec =
1933296039Szbb          FileSpec::Match(file_spec, dc_cu->GetPrimaryFile());
1934296039Szbb      if (check_inlines || file_spec_matches_cu_file_spec) {
1935296039Szbb        SymbolContext sc(m_objfile_sp->GetModule());
1936289550Szbb        sc.comp_unit = dc_cu;
1937289551Szbb        uint32_t file_idx = UINT32_MAX;
1938289551Szbb
1939289551Szbb        // If we are looking for inline functions only and we don't find it
1940289551Szbb        // in the support files, we are done.
1941289551Szbb        if (check_inlines) {
1942289550Szbb          file_idx =
1943289550Szbb              sc.comp_unit->GetSupportFiles().FindFileIndex(1, file_spec, true);
1944289550Szbb          if (file_idx == UINT32_MAX)
1945289550Szbb            continue;
1946297450Szbb        }
1947297450Szbb
1948296030Szbb        if (line != 0) {
1949297450Szbb          LineTable *line_table = sc.comp_unit->GetLineTable();
1950296030Szbb
1951297450Szbb          if (line_table != nullptr && line != 0) {
1952297450Szbb            // We will have already looked up the file index if we are
1953297450Szbb            // searching for inline entries.
1954297450Szbb            if (!check_inlines)
1955296030Szbb              file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex(
1956296030Szbb                  1, file_spec, true);
1957289550Szbb
1958289550Szbb            if (file_idx != UINT32_MAX) {
1959289551Szbb              uint32_t found_line;
1960289550Szbb              uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex(
1961289551Szbb                  0, file_idx, line, false, &sc.line_entry);
1962289551Szbb              found_line = sc.line_entry.line;
1963289550Szbb
1964289550Szbb              while (line_idx != UINT32_MAX) {
1965289550Szbb                sc.function = nullptr;
1966289551Szbb                sc.block = nullptr;
1967289550Szbb                if (resolve_scope &
1968289551Szbb                    (eSymbolContextFunction | eSymbolContextBlock)) {
1969289551Szbb                  const lldb::addr_t file_vm_addr =
1970289550Szbb                      sc.line_entry.range.GetBaseAddress().GetFileAddress();
1971289551Szbb                  if (file_vm_addr != LLDB_INVALID_ADDRESS) {
1972289551Szbb                    DWARFDIE function_die =
1973289551Szbb                        GetDWARFCompileUnit(dc_cu)->LookupAddress(file_vm_addr);
1974289550Szbb                    DWARFDIE block_die;
1975289550Szbb                    if (function_die) {
1976289551Szbb                      sc.function =
1977289551Szbb                          sc.comp_unit->FindFunctionByUID(function_die.GetID())
1978289550Szbb                              .get();
1979289551Szbb                      if (sc.function == nullptr)
1980289551Szbb                        sc.function =
1981289550Szbb                            ParseFunction(*sc.comp_unit, function_die);
1982289551Szbb
1983289550Szbb                      if (sc.function && (resolve_scope & eSymbolContextBlock))
1984289550Szbb                        block_die =
1985289550Szbb                            function_die.LookupDeepestBlock(file_vm_addr);
1986289551Szbb                    }
1987289551Szbb
1988289551Szbb                    if (sc.function != nullptr) {
1989289550Szbb                      Block &block = sc.function->GetBlock(true);
1990289550Szbb
1991289550Szbb                      if (block_die)
1992289551Szbb                        sc.block = block.FindBlockByID(block_die.GetID());
1993289551Szbb                      else if (function_die)
1994289551Szbb                        sc.block = block.FindBlockByID(function_die.GetID());
1995289551Szbb                    }
1996289550Szbb                  }
1997289551Szbb                }
1998289551Szbb
1999289551Szbb                sc_list.Append(sc);
2000289550Szbb                line_idx = line_table->FindLineEntryIndexByFileIndex(
2001289551Szbb                    line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2002289551Szbb              }
2003289550Szbb            }
2004289550Szbb          } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2005289550Szbb            // only append the context if we aren't looking for inline call
2006289551Szbb            // sites by file and line and if the file spec matches that of
2007289550Szbb            // the compile unit
2008289551Szbb            sc_list.Append(sc);
2009289551Szbb          }
2010289551Szbb        } else if (file_spec_matches_cu_file_spec && !check_inlines) {
2011289551Szbb          // only append the context if we aren't looking for inline call
2012289551Szbb          // sites by file and line and if the file spec matches that of
2013289550Szbb          // the compile unit
2014289550Szbb          sc_list.Append(sc);
2015289551Szbb        }
2016289551Szbb
2017289551Szbb        if (!check_inlines)
2018289550Szbb          break;
2019289550Szbb      }
2020289550Szbb    }
2021289550Szbb  }
2022289551Szbb  return sc_list.GetSize() - prev_size;
2023289551Szbb}
2024289551Szbb
2025289551Szbbvoid SymbolFileDWARF::PreloadSymbols() {
2026289551Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2027296030Szbb  m_index->Preload();
2028296030Szbb}
2029296030Szbb
2030296030Szbbstd::recursive_mutex &SymbolFileDWARF::GetModuleMutex() const {
2031297389Szbb  lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
2032296030Szbb  if (module_sp)
2033296030Szbb    return module_sp->GetMutex();
2034296030Szbb  return GetObjectFile()->GetModule()->GetMutex();
2035297389Szbb}
2036297389Szbb
2037297389Szbbbool SymbolFileDWARF::DeclContextMatchesThisSymbolFile(
2038297389Szbb    const lldb_private::CompilerDeclContext *decl_ctx) {
2039296030Szbb  if (decl_ctx == nullptr || !decl_ctx->IsValid()) {
2040296030Szbb    // Invalid namespace decl which means we aren't matching only things in
2041297389Szbb    // this symbol file, so return true to indicate it matches this symbol
2042297389Szbb    // file.
2043297389Szbb    return true;
2044297389Szbb  }
2045297389Szbb
2046297389Szbb  TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
2047297389Szbb  auto type_system_or_err = GetTypeSystemForLanguage(
2048296030Szbb      decl_ctx_type_system->GetMinimumLanguage(nullptr));
2049296030Szbb  if (auto err = type_system_or_err.takeError()) {
2050289551Szbb    LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2051289551Szbb                   std::move(err),
2052289551Szbb                   "Unable to match namespace decl using TypeSystem");
2053289550Szbb    return false;
2054289550Szbb  }
2055289550Szbb
2056289551Szbb  if (decl_ctx_type_system == &type_system_or_err.get())
2057289551Szbb    return true; // The type systems match, return true
2058289550Szbb
2059289551Szbb  // The namespace AST was valid, and it does not match...
2060289550Szbb  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2061289550Szbb
2062289550Szbb  if (log)
2063289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2064289550Szbb        log, "Valid namespace does not match symbol file");
2065289551Szbb
2066289550Szbb  return false;
2067289550Szbb}
2068289551Szbb
2069289550Szbbvoid SymbolFileDWARF::FindGlobalVariables(
2070289550Szbb    ConstString name, const CompilerDeclContext *parent_decl_ctx,
2071289551Szbb    uint32_t max_matches, VariableList &variables) {
2072289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2073289550Szbb  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2074289551Szbb
2075289550Szbb  if (log)
2076289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2077289551Szbb        log,
2078289550Szbb        "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2079289550Szbb        "parent_decl_ctx=%p, max_matches=%u, variables)",
2080289551Szbb        name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2081289550Szbb        max_matches);
2082289550Szbb
2083289551Szbb  if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2084289550Szbb    return;
2085289550Szbb
2086289551Szbb  DWARFDebugInfo *info = DebugInfo();
2087289550Szbb  if (!info)
2088289550Szbb    return;
2089289550Szbb
2090289550Szbb  // Remember how many variables are in the list before we search.
2091289550Szbb  const uint32_t original_size = variables.GetSize();
2092289550Szbb
2093289550Szbb  llvm::StringRef basename;
2094289550Szbb  llvm::StringRef context;
2095289551Szbb  bool name_is_mangled = (bool)Mangled(name);
2096289551Szbb
2097289550Szbb  if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name.GetCString(),
2098289551Szbb                                                      context, basename))
2099289550Szbb    basename = name.GetStringRef();
2100289550Szbb
2101289550Szbb  DIEArray die_offsets;
2102289551Szbb  m_index->GetGlobalVariables(ConstString(basename), die_offsets);
2103289550Szbb  const size_t num_die_matches = die_offsets.size();
2104289550Szbb  if (num_die_matches) {
2105289551Szbb    SymbolContext sc;
2106289550Szbb    sc.module_sp = m_objfile_sp->GetModule();
2107289550Szbb    assert(sc.module_sp);
2108289551Szbb
2109289550Szbb    // Loop invariant: Variables up to this index have been checked for context
2110289550Szbb    // matches.
2111289551Szbb    uint32_t pruned_idx = original_size;
2112289550Szbb
2113289550Szbb    bool done = false;
2114289551Szbb    for (size_t i = 0; i < num_die_matches && !done; ++i) {
2115289550Szbb      const DIERef &die_ref = die_offsets[i];
2116289550Szbb      DWARFDIE die = GetDIE(die_ref);
2117289551Szbb
2118289550Szbb      if (die) {
2119289550Szbb        switch (die.Tag()) {
2120289551Szbb        default:
2121289550Szbb        case DW_TAG_subprogram:
2122289550Szbb        case DW_TAG_inlined_subroutine:
2123289551Szbb        case DW_TAG_try_block:
2124289550Szbb        case DW_TAG_catch_block:
2125289550Szbb          break;
2126289550Szbb
2127289550Szbb        case DW_TAG_variable: {
2128289550Szbb          auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2129289550Szbb          if (!dwarf_cu)
2130289550Szbb            continue;
2131289550Szbb          sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2132289551Szbb
2133289551Szbb          if (parent_decl_ctx) {
2134289550Szbb            DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2135289551Szbb            if (dwarf_ast) {
2136289550Szbb              CompilerDeclContext actual_parent_decl_ctx =
2137289550Szbb                  dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2138289550Szbb              if (!actual_parent_decl_ctx ||
2139289551Szbb                  actual_parent_decl_ctx != *parent_decl_ctx)
2140289550Szbb                continue;
2141289550Szbb            }
2142289551Szbb          }
2143289550Szbb
2144289550Szbb          ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false,
2145289551Szbb                         &variables);
2146289550Szbb          while (pruned_idx < variables.GetSize()) {
2147289550Szbb            VariableSP var_sp = variables.GetVariableAtIndex(pruned_idx);
2148289551Szbb            if (name_is_mangled ||
2149289550Szbb                var_sp->GetName().GetStringRef().contains(name.GetStringRef()))
2150289550Szbb              ++pruned_idx;
2151289551Szbb            else
2152289550Szbb              variables.RemoveVariableAtIndex(pruned_idx);
2153289550Szbb          }
2154289551Szbb
2155289550Szbb          if (variables.GetSize() - original_size >= max_matches)
2156289550Szbb            done = true;
2157289551Szbb        } break;
2158289550Szbb        }
2159289550Szbb      } else {
2160289551Szbb        m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2161289550Szbb      }
2162289550Szbb    }
2163289550Szbb  }
2164289550Szbb
2165289550Szbb  // Return the number of variable that were appended to the list
2166289550Szbb  const uint32_t num_matches = variables.GetSize() - original_size;
2167289550Szbb  if (log && num_matches > 0) {
2168289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2169289551Szbb        log,
2170289551Szbb        "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", "
2171289550Szbb        "parent_decl_ctx=%p, max_matches=%u, variables) => %u",
2172289551Szbb        name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2173289551Szbb        max_matches, num_matches);
2174289550Szbb  }
2175289550Szbb}
2176289550Szbb
2177289550Szbbvoid SymbolFileDWARF::FindGlobalVariables(const RegularExpression &regex,
2178289550Szbb                                          uint32_t max_matches,
2179289551Szbb                                          VariableList &variables) {
2180289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2181289550Szbb  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2182289551Szbb
2183289550Szbb  if (log) {
2184289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2185289551Szbb        log,
2186289550Szbb        "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", "
2187289550Szbb        "max_matches=%u, variables)",
2188289550Szbb        regex.GetText().str().c_str(), max_matches);
2189289550Szbb  }
2190289550Szbb
2191289550Szbb  DWARFDebugInfo *info = DebugInfo();
2192289550Szbb  if (!info)
2193289550Szbb    return;
2194289550Szbb
2195289550Szbb  // Remember how many variables are in the list before we search.
2196289550Szbb  const uint32_t original_size = variables.GetSize();
2197289550Szbb
2198289550Szbb  DIEArray die_offsets;
2199289550Szbb  m_index->GetGlobalVariables(regex, die_offsets);
2200289551Szbb
2201289550Szbb  SymbolContext sc;
2202289550Szbb  sc.module_sp = m_objfile_sp->GetModule();
2203289550Szbb  assert(sc.module_sp);
2204289550Szbb
2205289550Szbb  const size_t num_matches = die_offsets.size();
2206289550Szbb  if (num_matches) {
2207289550Szbb    for (size_t i = 0; i < num_matches; ++i) {
2208289551Szbb      const DIERef &die_ref = die_offsets[i];
2209289551Szbb      DWARFDIE die = GetDIE(die_ref);
2210289550Szbb
2211289550Szbb      if (die) {
2212289550Szbb        DWARFCompileUnit *dwarf_cu =
2213289550Szbb            llvm::dyn_cast<DWARFCompileUnit>(die.GetCU());
2214289550Szbb        if (!dwarf_cu)
2215289550Szbb          continue;
2216289550Szbb        sc.comp_unit = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2217289550Szbb
2218289550Szbb        ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2219289550Szbb
2220289550Szbb        if (variables.GetSize() - original_size >= max_matches)
2221289550Szbb          break;
2222289551Szbb      } else
2223289551Szbb        m_index->ReportInvalidDIERef(die_ref, regex.GetText());
2224289550Szbb    }
2225289550Szbb  }
2226289550Szbb}
2227289550Szbb
2228289550Szbbbool SymbolFileDWARF::ResolveFunction(const DWARFDIE &orig_die,
2229289550Szbb                                      bool include_inlines,
2230289550Szbb                                      SymbolContextList &sc_list) {
2231289550Szbb  SymbolContext sc;
2232289550Szbb
2233289550Szbb  if (!orig_die)
2234289550Szbb    return false;
2235289550Szbb
2236289550Szbb  // If we were passed a die that is not a function, just return false...
2237289551Szbb  if (!(orig_die.Tag() == DW_TAG_subprogram ||
2238289551Szbb        (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2239289551Szbb    return false;
2240289550Szbb
2241289550Szbb  DWARFDIE die = orig_die;
2242289550Szbb  DWARFDIE inlined_die;
2243289550Szbb  if (die.Tag() == DW_TAG_inlined_subroutine) {
2244289550Szbb    inlined_die = die;
2245289550Szbb
2246289551Szbb    while (true) {
2247289550Szbb      die = die.GetParent();
2248289550Szbb
2249289550Szbb      if (die) {
2250289550Szbb        if (die.Tag() == DW_TAG_subprogram)
2251289550Szbb          break;
2252289550Szbb      } else
2253289550Szbb        break;
2254289550Szbb    }
2255289550Szbb  }
2256289550Szbb  assert(die && die.Tag() == DW_TAG_subprogram);
2257289550Szbb  if (GetFunction(die, sc)) {
2258289550Szbb    Address addr;
2259289550Szbb    // Parse all blocks if needed
2260289550Szbb    if (inlined_die) {
2261289550Szbb      Block &function_block = sc.function->GetBlock(true);
2262289550Szbb      sc.block = function_block.FindBlockByID(inlined_die.GetID());
2263289550Szbb      if (sc.block == nullptr)
2264289550Szbb        sc.block = function_block.FindBlockByID(inlined_die.GetOffset());
2265289550Szbb      if (sc.block == nullptr || !sc.block->GetStartAddress(addr))
2266289550Szbb        addr.Clear();
2267289550Szbb    } else {
2268289550Szbb      sc.block = nullptr;
2269289550Szbb      addr = sc.function->GetAddressRange().GetBaseAddress();
2270289550Szbb    }
2271289550Szbb
2272289550Szbb
2273289550Szbb    if (auto section_sp = addr.GetSection()) {
2274289550Szbb      if (section_sp->GetPermissions() & ePermissionsExecutable) {
2275289550Szbb        sc_list.Append(sc);
2276289550Szbb        return true;
2277289550Szbb      }
2278289550Szbb    }
2279289550Szbb  }
2280289550Szbb
2281289550Szbb  return false;
2282289550Szbb}
2283289550Szbb
2284289550Szbbbool SymbolFileDWARF::DIEInDeclContext(const CompilerDeclContext *decl_ctx,
2285289550Szbb                                       const DWARFDIE &die) {
2286289550Szbb  // If we have no parent decl context to match this DIE matches, and if the
2287289550Szbb  // parent decl context isn't valid, we aren't trying to look for any
2288289550Szbb  // particular decl context so any die matches.
2289289550Szbb  if (decl_ctx == nullptr || !decl_ctx->IsValid())
2290289550Szbb    return true;
2291289550Szbb
2292289550Szbb  if (die) {
2293289550Szbb    DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2294289550Szbb    if (dwarf_ast) {
2295289550Szbb      CompilerDeclContext actual_decl_ctx =
2296289550Szbb          dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
2297289550Szbb      if (actual_decl_ctx)
2298289550Szbb        return decl_ctx->IsContainedInLookup(actual_decl_ctx);
2299289550Szbb    }
2300289550Szbb  }
2301289550Szbb  return false;
2302289550Szbb}
2303289550Szbb
2304289550Szbbvoid SymbolFileDWARF::FindFunctions(ConstString name,
2305289550Szbb                                    const CompilerDeclContext *parent_decl_ctx,
2306289550Szbb                                    FunctionNameType name_type_mask,
2307289550Szbb                                    bool include_inlines,
2308289550Szbb                                    SymbolContextList &sc_list) {
2309289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2310289550Szbb  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2311289550Szbb  Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (name = '%s')",
2312289550Szbb                     name.AsCString());
2313289550Szbb
2314289550Szbb  // eFunctionNameTypeAuto should be pre-resolved by a call to
2315289550Szbb  // Module::LookupInfo::LookupInfo()
2316289550Szbb  assert((name_type_mask & eFunctionNameTypeAuto) == 0);
2317289550Szbb
2318289550Szbb  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2319289550Szbb
2320289550Szbb  if (log) {
2321289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2322289550Szbb        log,
2323289550Szbb        "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, sc_list)",
2324289551Szbb        name.GetCString(), name_type_mask);
2325289550Szbb  }
2326289550Szbb
2327289550Szbb  if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2328289551Szbb    return;
2329289551Szbb
2330289551Szbb  // If name is empty then we won't find anything.
2331289550Szbb  if (name.IsEmpty())
2332289550Szbb    return;
2333289550Szbb
2334289550Szbb  // Remember how many sc_list are in the list before we search in case we are
2335289550Szbb  // appending the results to a variable list.
2336289550Szbb
2337289551Szbb  const uint32_t original_size = sc_list.GetSize();
2338289550Szbb
2339289550Szbb  llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2340289550Szbb  DIEArray offsets;
2341289550Szbb  CompilerDeclContext empty_decl_ctx;
2342289550Szbb  if (!parent_decl_ctx)
2343289550Szbb    parent_decl_ctx = &empty_decl_ctx;
2344289550Szbb
2345289550Szbb  std::vector<DWARFDIE> dies;
2346289550Szbb  m_index->GetFunctions(name, *this, *parent_decl_ctx, name_type_mask, dies);
2347289550Szbb  for (const DWARFDIE &die : dies) {
2348289550Szbb    if (resolved_dies.insert(die.GetDIE()).second)
2349289550Szbb      ResolveFunction(die, include_inlines, sc_list);
2350289550Szbb  }
2351289550Szbb
2352289550Szbb  // Return the number of variable that were appended to the list
2353289550Szbb  const uint32_t num_matches = sc_list.GetSize() - original_size;
2354289550Szbb
2355289550Szbb  if (log && num_matches > 0) {
2356289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2357289550Szbb        log,
2358289550Szbb        "SymbolFileDWARF::FindFunctions (name=\"%s\", "
2359289550Szbb        "name_type_mask=0x%x, include_inlines=%d, sc_list) => %u",
2360289550Szbb        name.GetCString(), name_type_mask, include_inlines,
2361289550Szbb        num_matches);
2362289550Szbb  }
2363289550Szbb}
2364289550Szbb
2365289550Szbbvoid SymbolFileDWARF::FindFunctions(const RegularExpression &regex,
2366289550Szbb                                    bool include_inlines,
2367289550Szbb                                    SymbolContextList &sc_list) {
2368289550Szbb  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2369289550Szbb  static Timer::Category func_cat(LLVM_PRETTY_FUNCTION);
2370289550Szbb  Timer scoped_timer(func_cat, "SymbolFileDWARF::FindFunctions (regex = '%s')",
2371289550Szbb                     regex.GetText().str().c_str());
2372289550Szbb
2373289550Szbb  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2374289550Szbb
2375289550Szbb  if (log) {
2376289550Szbb    GetObjectFile()->GetModule()->LogMessage(
2377289550Szbb        log, "SymbolFileDWARF::FindFunctions (regex=\"%s\", sc_list)",
2378289550Szbb        regex.GetText().str().c_str());
2379289551Szbb  }
2380289550Szbb
2381  DWARFDebugInfo *info = DebugInfo();
2382  if (!info)
2383    return;
2384
2385  DIEArray offsets;
2386  m_index->GetFunctions(regex, offsets);
2387
2388  llvm::DenseSet<const DWARFDebugInfoEntry *> resolved_dies;
2389  for (DIERef ref : offsets) {
2390    DWARFDIE die = info->GetDIE(ref);
2391    if (!die) {
2392      m_index->ReportInvalidDIERef(ref, regex.GetText());
2393      continue;
2394    }
2395    if (resolved_dies.insert(die.GetDIE()).second)
2396      ResolveFunction(die, include_inlines, sc_list);
2397  }
2398}
2399
2400void SymbolFileDWARF::GetMangledNamesForFunction(
2401    const std::string &scope_qualified_name,
2402    std::vector<ConstString> &mangled_names) {
2403  DWARFDebugInfo *info = DebugInfo();
2404  uint32_t num_comp_units = 0;
2405  if (info)
2406    num_comp_units = info->GetNumUnits();
2407
2408  for (uint32_t i = 0; i < num_comp_units; i++) {
2409    DWARFUnit *cu = info->GetUnitAtIndex(i);
2410    if (cu == nullptr)
2411      continue;
2412
2413    SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2414    if (dwo)
2415      dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2416  }
2417
2418  for (lldb::user_id_t uid :
2419       m_function_scope_qualified_name_map.lookup(scope_qualified_name)) {
2420    DWARFDIE die = GetDIE(uid);
2421    mangled_names.push_back(ConstString(die.GetMangledName()));
2422  }
2423}
2424
2425void SymbolFileDWARF::FindTypes(
2426    ConstString name, const CompilerDeclContext *parent_decl_ctx,
2427    uint32_t max_matches,
2428    llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
2429    TypeMap &types) {
2430  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2431  // Make sure we haven't already searched this SymbolFile before.
2432  if (!searched_symbol_files.insert(this).second)
2433    return;
2434
2435  DWARFDebugInfo *info = DebugInfo();
2436  if (!info)
2437    return;
2438
2439  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2440
2441  if (log) {
2442    if (parent_decl_ctx)
2443      GetObjectFile()->GetModule()->LogMessage(
2444          log,
2445          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2446          "%p (\"%s\"), max_matches=%u, type_list)",
2447          name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2448          parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches);
2449    else
2450      GetObjectFile()->GetModule()->LogMessage(
2451          log,
2452          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = "
2453          "NULL, max_matches=%u, type_list)",
2454          name.GetCString(), max_matches);
2455  }
2456
2457  if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2458    return;
2459
2460  DIEArray die_offsets;
2461  m_index->GetTypes(name, die_offsets);
2462  const size_t num_die_matches = die_offsets.size();
2463
2464  for (size_t i = 0; i < num_die_matches; ++i) {
2465    const DIERef &die_ref = die_offsets[i];
2466    DWARFDIE die = GetDIE(die_ref);
2467    if (die) {
2468      if (!DIEInDeclContext(parent_decl_ctx, die))
2469        continue; // The containing decl contexts don't match
2470
2471      Type *matching_type = ResolveType(die, true, true);
2472      if (matching_type) {
2473        // We found a type pointer, now find the shared pointer form our type
2474        // list
2475        types.InsertUnique(matching_type->shared_from_this());
2476        if (types.GetSize() >= max_matches)
2477          break;
2478      }
2479    } else {
2480      m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2481    }
2482  }
2483
2484  // Next search through the reachable Clang modules. This only applies for
2485  // DWARF objects compiled with -gmodules that haven't been processed by
2486  // dsymutil.
2487  if (num_die_matches < max_matches) {
2488    UpdateExternalModuleListIfNeeded();
2489
2490    for (const auto &pair : m_external_type_modules)
2491      if (ModuleSP external_module_sp = pair.second)
2492        if (SymbolFile *sym_file = external_module_sp->GetSymbolFile())
2493          sym_file->FindTypes(name, parent_decl_ctx, max_matches,
2494                              searched_symbol_files, types);
2495  }
2496
2497  if (log && types.GetSize()) {
2498    if (parent_decl_ctx) {
2499      GetObjectFile()->GetModule()->LogMessage(
2500          log,
2501          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2502          "= %p (\"%s\"), max_matches=%u, type_list) => %u",
2503          name.GetCString(), static_cast<const void *>(parent_decl_ctx),
2504          parent_decl_ctx->GetName().AsCString("<NULL>"), max_matches,
2505          types.GetSize());
2506    } else {
2507      GetObjectFile()->GetModule()->LogMessage(
2508          log,
2509          "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx "
2510          "= NULL, max_matches=%u, type_list) => %u",
2511          name.GetCString(), max_matches, types.GetSize());
2512    }
2513  }
2514}
2515
2516void SymbolFileDWARF::FindTypes(
2517    llvm::ArrayRef<CompilerContext> pattern, LanguageSet languages,
2518    llvm::DenseSet<SymbolFile *> &searched_symbol_files, TypeMap &types) {
2519  // Make sure we haven't already searched this SymbolFile before.
2520  if (!searched_symbol_files.insert(this).second)
2521    return;
2522
2523  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2524  if (pattern.empty())
2525    return;
2526
2527  ConstString name = pattern.back().name;
2528
2529  if (!name)
2530    return;
2531
2532  DIEArray die_offsets;
2533  m_index->GetTypes(name, die_offsets);
2534  const size_t num_die_matches = die_offsets.size();
2535
2536  for (size_t i = 0; i < num_die_matches; ++i) {
2537    const DIERef &die_ref = die_offsets[i];
2538    DWARFDIE die = GetDIE(die_ref);
2539
2540    if (!die) {
2541      m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2542      continue;
2543    }
2544    if (!languages[die.GetCU()->GetLanguageType()])
2545      continue;
2546
2547    llvm::SmallVector<CompilerContext, 4> die_context;
2548    die.GetDeclContext(die_context);
2549    if (!contextMatches(die_context, pattern))
2550      continue;
2551
2552    if (Type *matching_type = ResolveType(die, true, true)) {
2553      // We found a type pointer, now find the shared pointer form our type
2554      // list.
2555      types.InsertUnique(matching_type->shared_from_this());
2556    }
2557  }
2558
2559  // Next search through the reachable Clang modules. This only applies for
2560  // DWARF objects compiled with -gmodules that haven't been processed by
2561  // dsymutil.
2562  UpdateExternalModuleListIfNeeded();
2563
2564  for (const auto &pair : m_external_type_modules)
2565    if (ModuleSP external_module_sp = pair.second)
2566      external_module_sp->FindTypes(pattern, languages, searched_symbol_files,
2567                                    types);
2568}
2569
2570CompilerDeclContext
2571SymbolFileDWARF::FindNamespace(ConstString name,
2572                               const CompilerDeclContext *parent_decl_ctx) {
2573  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
2574  Log *log(LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2575
2576  if (log) {
2577    GetObjectFile()->GetModule()->LogMessage(
2578        log, "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
2579        name.GetCString());
2580  }
2581
2582  CompilerDeclContext namespace_decl_ctx;
2583
2584  if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2585    return namespace_decl_ctx;
2586
2587  DWARFDebugInfo *info = DebugInfo();
2588  if (info) {
2589    DIEArray die_offsets;
2590    m_index->GetNamespaces(name, die_offsets);
2591    const size_t num_matches = die_offsets.size();
2592    if (num_matches) {
2593      for (size_t i = 0; i < num_matches; ++i) {
2594        const DIERef &die_ref = die_offsets[i];
2595        DWARFDIE die = GetDIE(die_ref);
2596
2597        if (die) {
2598          if (!DIEInDeclContext(parent_decl_ctx, die))
2599            continue; // The containing decl contexts don't match
2600
2601          DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2602          if (dwarf_ast) {
2603            namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF(die);
2604            if (namespace_decl_ctx)
2605              break;
2606          }
2607        } else {
2608          m_index->ReportInvalidDIERef(die_ref, name.GetStringRef());
2609        }
2610      }
2611    }
2612  }
2613  if (log && namespace_decl_ctx) {
2614    GetObjectFile()->GetModule()->LogMessage(
2615        log,
2616        "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => "
2617        "CompilerDeclContext(%p/%p) \"%s\"",
2618        name.GetCString(),
2619        static_cast<const void *>(namespace_decl_ctx.GetTypeSystem()),
2620        static_cast<const void *>(namespace_decl_ctx.GetOpaqueDeclContext()),
2621        namespace_decl_ctx.GetName().AsCString("<NULL>"));
2622  }
2623
2624  return namespace_decl_ctx;
2625}
2626
2627TypeSP SymbolFileDWARF::GetTypeForDIE(const DWARFDIE &die,
2628                                      bool resolve_function_context) {
2629  TypeSP type_sp;
2630  if (die) {
2631    Type *type_ptr = GetDIEToType().lookup(die.GetDIE());
2632    if (type_ptr == nullptr) {
2633      SymbolContextScope *scope;
2634      if (auto *dwarf_cu = llvm::dyn_cast<DWARFCompileUnit>(die.GetCU()))
2635        scope = GetCompUnitForDWARFCompUnit(*dwarf_cu);
2636      else
2637        scope = GetObjectFile()->GetModule().get();
2638      assert(scope);
2639      SymbolContext sc(scope);
2640      const DWARFDebugInfoEntry *parent_die = die.GetParent().GetDIE();
2641      while (parent_die != nullptr) {
2642        if (parent_die->Tag() == DW_TAG_subprogram)
2643          break;
2644        parent_die = parent_die->GetParent();
2645      }
2646      SymbolContext sc_backup = sc;
2647      if (resolve_function_context && parent_die != nullptr &&
2648          !GetFunction(DWARFDIE(die.GetCU(), parent_die), sc))
2649        sc = sc_backup;
2650
2651      type_sp = ParseType(sc, die, nullptr);
2652    } else if (type_ptr != DIE_IS_BEING_PARSED) {
2653      // Grab the existing type from the master types lists
2654      type_sp = type_ptr->shared_from_this();
2655    }
2656  }
2657  return type_sp;
2658}
2659
2660DWARFDIE
2661SymbolFileDWARF::GetDeclContextDIEContainingDIE(const DWARFDIE &orig_die) {
2662  if (orig_die) {
2663    DWARFDIE die = orig_die;
2664
2665    while (die) {
2666      // If this is the original DIE that we are searching for a declaration
2667      // for, then don't look in the cache as we don't want our own decl
2668      // context to be our decl context...
2669      if (orig_die != die) {
2670        switch (die.Tag()) {
2671        case DW_TAG_compile_unit:
2672        case DW_TAG_partial_unit:
2673        case DW_TAG_namespace:
2674        case DW_TAG_structure_type:
2675        case DW_TAG_union_type:
2676        case DW_TAG_class_type:
2677        case DW_TAG_lexical_block:
2678        case DW_TAG_subprogram:
2679          return die;
2680        case DW_TAG_inlined_subroutine: {
2681          DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2682          if (abs_die) {
2683            return abs_die;
2684          }
2685          break;
2686        }
2687        default:
2688          break;
2689        }
2690      }
2691
2692      DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
2693      if (spec_die) {
2694        DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
2695        if (decl_ctx_die)
2696          return decl_ctx_die;
2697      }
2698
2699      DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
2700      if (abs_die) {
2701        DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
2702        if (decl_ctx_die)
2703          return decl_ctx_die;
2704      }
2705
2706      die = die.GetParent();
2707    }
2708  }
2709  return DWARFDIE();
2710}
2711
2712Symbol *SymbolFileDWARF::GetObjCClassSymbol(ConstString objc_class_name) {
2713  Symbol *objc_class_symbol = nullptr;
2714  if (m_objfile_sp) {
2715    Symtab *symtab = m_objfile_sp->GetSymtab();
2716    if (symtab) {
2717      objc_class_symbol = symtab->FindFirstSymbolWithNameAndType(
2718          objc_class_name, eSymbolTypeObjCClass, Symtab::eDebugNo,
2719          Symtab::eVisibilityAny);
2720    }
2721  }
2722  return objc_class_symbol;
2723}
2724
2725// Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If
2726// they don't then we can end up looking through all class types for a complete
2727// type and never find the full definition. We need to know if this attribute
2728// is supported, so we determine this here and cache th result. We also need to
2729// worry about the debug map
2730// DWARF file
2731// if we are doing darwin DWARF in .o file debugging.
2732bool SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type(DWARFUnit *cu) {
2733  if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate) {
2734    m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
2735    if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
2736      m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2737    else {
2738      DWARFDebugInfo *debug_info = DebugInfo();
2739      const uint32_t num_compile_units = GetNumCompileUnits();
2740      for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx) {
2741        DWARFUnit *dwarf_cu = debug_info->GetUnitAtIndex(cu_idx);
2742        if (dwarf_cu != cu &&
2743            dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type()) {
2744          m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
2745          break;
2746        }
2747      }
2748    }
2749    if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo &&
2750        GetDebugMapSymfile())
2751      return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type(this);
2752  }
2753  return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
2754}
2755
2756// This function can be used when a DIE is found that is a forward declaration
2757// DIE and we want to try and find a type that has the complete definition.
2758TypeSP SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE(
2759    const DWARFDIE &die, ConstString type_name, bool must_be_implementation) {
2760
2761  TypeSP type_sp;
2762
2763  if (!type_name || (must_be_implementation && !GetObjCClassSymbol(type_name)))
2764    return type_sp;
2765
2766  DIEArray die_offsets;
2767  m_index->GetCompleteObjCClass(type_name, must_be_implementation, die_offsets);
2768
2769  const size_t num_matches = die_offsets.size();
2770
2771  if (num_matches) {
2772    for (size_t i = 0; i < num_matches; ++i) {
2773      const DIERef &die_ref = die_offsets[i];
2774      DWARFDIE type_die = GetDIE(die_ref);
2775
2776      if (type_die) {
2777        bool try_resolving_type = false;
2778
2779        // Don't try and resolve the DIE we are looking for with the DIE
2780        // itself!
2781        if (type_die != die) {
2782          switch (type_die.Tag()) {
2783          case DW_TAG_class_type:
2784          case DW_TAG_structure_type:
2785            try_resolving_type = true;
2786            break;
2787          default:
2788            break;
2789          }
2790        }
2791
2792        if (try_resolving_type) {
2793          if (must_be_implementation &&
2794              type_die.Supports_DW_AT_APPLE_objc_complete_type())
2795            try_resolving_type = type_die.GetAttributeValueAsUnsigned(
2796                DW_AT_APPLE_objc_complete_type, 0);
2797
2798          if (try_resolving_type) {
2799            Type *resolved_type = ResolveType(type_die, false, true);
2800            if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
2801              DEBUG_PRINTF("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64
2802                           " (cu 0x%8.8" PRIx64 ")\n",
2803                           die.GetID(),
2804                           m_objfile_sp->GetFileSpec().GetFilename().AsCString(
2805                               "<Unknown>"),
2806                           type_die.GetID(), type_cu->GetID());
2807
2808              if (die)
2809                GetDIEToType()[die.GetDIE()] = resolved_type;
2810              type_sp = resolved_type->shared_from_this();
2811              break;
2812            }
2813          }
2814        }
2815      } else {
2816        m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
2817      }
2818    }
2819  }
2820  return type_sp;
2821}
2822
2823// This function helps to ensure that the declaration contexts match for two
2824// different DIEs. Often times debug information will refer to a forward
2825// declaration of a type (the equivalent of "struct my_struct;". There will
2826// often be a declaration of that type elsewhere that has the full definition.
2827// When we go looking for the full type "my_struct", we will find one or more
2828// matches in the accelerator tables and we will then need to make sure the
2829// type was in the same declaration context as the original DIE. This function
2830// can efficiently compare two DIEs and will return true when the declaration
2831// context matches, and false when they don't.
2832bool SymbolFileDWARF::DIEDeclContextsMatch(const DWARFDIE &die1,
2833                                           const DWARFDIE &die2) {
2834  if (die1 == die2)
2835    return true;
2836
2837  std::vector<DWARFDIE> decl_ctx_1;
2838  std::vector<DWARFDIE> decl_ctx_2;
2839  // The declaration DIE stack is a stack of the declaration context DIEs all
2840  // the way back to the compile unit. If a type "T" is declared inside a class
2841  // "B", and class "B" is declared inside a class "A" and class "A" is in a
2842  // namespace "lldb", and the namespace is in a compile unit, there will be a
2843  // stack of DIEs:
2844  //
2845  //   [0] DW_TAG_class_type for "B"
2846  //   [1] DW_TAG_class_type for "A"
2847  //   [2] DW_TAG_namespace  for "lldb"
2848  //   [3] DW_TAG_compile_unit or DW_TAG_partial_unit for the source file.
2849  //
2850  // We grab both contexts and make sure that everything matches all the way
2851  // back to the compiler unit.
2852
2853  // First lets grab the decl contexts for both DIEs
2854  decl_ctx_1 = die1.GetDeclContextDIEs();
2855  decl_ctx_2 = die2.GetDeclContextDIEs();
2856  // Make sure the context arrays have the same size, otherwise we are done
2857  const size_t count1 = decl_ctx_1.size();
2858  const size_t count2 = decl_ctx_2.size();
2859  if (count1 != count2)
2860    return false;
2861
2862  // Make sure the DW_TAG values match all the way back up the compile unit. If
2863  // they don't, then we are done.
2864  DWARFDIE decl_ctx_die1;
2865  DWARFDIE decl_ctx_die2;
2866  size_t i;
2867  for (i = 0; i < count1; i++) {
2868    decl_ctx_die1 = decl_ctx_1[i];
2869    decl_ctx_die2 = decl_ctx_2[i];
2870    if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
2871      return false;
2872  }
2873#ifndef NDEBUG
2874
2875  // Make sure the top item in the decl context die array is always
2876  // DW_TAG_compile_unit or DW_TAG_partial_unit. If it isn't then
2877  // something went wrong in the DWARFDIE::GetDeclContextDIEs()
2878  // function.
2879  dw_tag_t cu_tag = decl_ctx_1[count1 - 1].Tag();
2880  UNUSED_IF_ASSERT_DISABLED(cu_tag);
2881  assert(cu_tag == DW_TAG_compile_unit || cu_tag == DW_TAG_partial_unit);
2882
2883#endif
2884  // Always skip the compile unit when comparing by only iterating up to "count
2885  // - 1". Here we compare the names as we go.
2886  for (i = 0; i < count1 - 1; i++) {
2887    decl_ctx_die1 = decl_ctx_1[i];
2888    decl_ctx_die2 = decl_ctx_2[i];
2889    const char *name1 = decl_ctx_die1.GetName();
2890    const char *name2 = decl_ctx_die2.GetName();
2891    // If the string was from a DW_FORM_strp, then the pointer will often be
2892    // the same!
2893    if (name1 == name2)
2894      continue;
2895
2896    // Name pointers are not equal, so only compare the strings if both are not
2897    // NULL.
2898    if (name1 && name2) {
2899      // If the strings don't compare, we are done...
2900      if (strcmp(name1, name2) != 0)
2901        return false;
2902    } else {
2903      // One name was NULL while the other wasn't
2904      return false;
2905    }
2906  }
2907  // We made it through all of the checks and the declaration contexts are
2908  // equal.
2909  return true;
2910}
2911
2912TypeSP SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(
2913    const DWARFDeclContext &dwarf_decl_ctx) {
2914  TypeSP type_sp;
2915
2916  const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
2917  if (dwarf_decl_ctx_count > 0) {
2918    const ConstString type_name(dwarf_decl_ctx[0].name);
2919    const dw_tag_t tag = dwarf_decl_ctx[0].tag;
2920
2921    if (type_name) {
2922      Log *log(LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION |
2923                                            DWARF_LOG_LOOKUPS));
2924      if (log) {
2925        GetObjectFile()->GetModule()->LogMessage(
2926            log,
2927            "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%"
2928            "s, qualified-name='%s')",
2929            DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
2930            dwarf_decl_ctx.GetQualifiedName());
2931      }
2932
2933      DIEArray die_offsets;
2934      m_index->GetTypes(dwarf_decl_ctx, die_offsets);
2935      const size_t num_matches = die_offsets.size();
2936
2937      // Get the type system that we are looking to find a type for. We will
2938      // use this to ensure any matches we find are in a language that this
2939      // type system supports
2940      const LanguageType language = dwarf_decl_ctx.GetLanguage();
2941      TypeSystem *type_system = nullptr;
2942      if (language != eLanguageTypeUnknown) {
2943        auto type_system_or_err = GetTypeSystemForLanguage(language);
2944        if (auto err = type_system_or_err.takeError()) {
2945          LLDB_LOG_ERROR(
2946              lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
2947              std::move(err), "Cannot get TypeSystem for language {}",
2948              Language::GetNameForLanguageType(language));
2949        } else {
2950          type_system = &type_system_or_err.get();
2951        }
2952      }
2953      if (num_matches) {
2954        for (size_t i = 0; i < num_matches; ++i) {
2955          const DIERef &die_ref = die_offsets[i];
2956          DWARFDIE type_die = GetDIE(die_ref);
2957
2958          if (type_die) {
2959            // Make sure type_die's langauge matches the type system we are
2960            // looking for. We don't want to find a "Foo" type from Java if we
2961            // are looking for a "Foo" type for C, C++, ObjC, or ObjC++.
2962            if (type_system &&
2963                !type_system->SupportsLanguage(type_die.GetLanguage()))
2964              continue;
2965            bool try_resolving_type = false;
2966
2967            // Don't try and resolve the DIE we are looking for with the DIE
2968            // itself!
2969            const dw_tag_t type_tag = type_die.Tag();
2970            // Make sure the tags match
2971            if (type_tag == tag) {
2972              // The tags match, lets try resolving this type
2973              try_resolving_type = true;
2974            } else {
2975              // The tags don't match, but we need to watch our for a forward
2976              // declaration for a struct and ("struct foo") ends up being a
2977              // class ("class foo { ... };") or vice versa.
2978              switch (type_tag) {
2979              case DW_TAG_class_type:
2980                // We had a "class foo", see if we ended up with a "struct foo
2981                // { ... };"
2982                try_resolving_type = (tag == DW_TAG_structure_type);
2983                break;
2984              case DW_TAG_structure_type:
2985                // We had a "struct foo", see if we ended up with a "class foo
2986                // { ... };"
2987                try_resolving_type = (tag == DW_TAG_class_type);
2988                break;
2989              default:
2990                // Tags don't match, don't event try to resolve using this type
2991                // whose name matches....
2992                break;
2993              }
2994            }
2995
2996            if (try_resolving_type) {
2997              DWARFDeclContext type_dwarf_decl_ctx;
2998              type_die.GetDWARFDeclContext(type_dwarf_decl_ctx);
2999
3000              if (log) {
3001                GetObjectFile()->GetModule()->LogMessage(
3002                    log,
3003                    "SymbolFileDWARF::"
3004                    "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3005                    "qualified-name='%s') trying die=0x%8.8x (%s)",
3006                    DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3007                    dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3008                    type_dwarf_decl_ctx.GetQualifiedName());
3009              }
3010
3011              // Make sure the decl contexts match all the way up
3012              if (dwarf_decl_ctx == type_dwarf_decl_ctx) {
3013                Type *resolved_type = ResolveType(type_die, false);
3014                if (resolved_type && resolved_type != DIE_IS_BEING_PARSED) {
3015                  type_sp = resolved_type->shared_from_this();
3016                  break;
3017                }
3018              }
3019            } else {
3020              if (log) {
3021                std::string qualified_name;
3022                type_die.GetQualifiedName(qualified_name);
3023                GetObjectFile()->GetModule()->LogMessage(
3024                    log,
3025                    "SymbolFileDWARF::"
3026                    "FindDefinitionTypeForDWARFDeclContext(tag=%s, "
3027                    "qualified-name='%s') ignoring die=0x%8.8x (%s)",
3028                    DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3029                    dwarf_decl_ctx.GetQualifiedName(), type_die.GetOffset(),
3030                    qualified_name.c_str());
3031              }
3032            }
3033          } else {
3034            m_index->ReportInvalidDIERef(die_ref, type_name.GetStringRef());
3035          }
3036        }
3037      }
3038    }
3039  }
3040  return type_sp;
3041}
3042
3043TypeSP SymbolFileDWARF::ParseType(const SymbolContext &sc, const DWARFDIE &die,
3044                                  bool *type_is_new_ptr) {
3045  if (!die)
3046    return {};
3047
3048  auto type_system_or_err =
3049      GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3050  if (auto err = type_system_or_err.takeError()) {
3051    LLDB_LOG_ERROR(lldb_private::GetLogIfAnyCategoriesSet(LIBLLDB_LOG_SYMBOLS),
3052                   std::move(err), "Unable to parse type");
3053    return {};
3054  }
3055
3056  DWARFASTParser *dwarf_ast = type_system_or_err->GetDWARFParser();
3057  if (!dwarf_ast)
3058    return {};
3059
3060  TypeSP type_sp = dwarf_ast->ParseTypeFromDWARF(sc, die, type_is_new_ptr);
3061  if (type_sp) {
3062    GetTypeList().Insert(type_sp);
3063
3064    if (die.Tag() == DW_TAG_subprogram) {
3065      std::string scope_qualified_name(GetDeclContextForUID(die.GetID())
3066                                           .GetScopeQualifiedName()
3067                                           .AsCString(""));
3068      if (scope_qualified_name.size()) {
3069        m_function_scope_qualified_name_map[scope_qualified_name].insert(
3070            die.GetID());
3071      }
3072    }
3073  }
3074
3075  return type_sp;
3076}
3077
3078size_t SymbolFileDWARF::ParseTypes(const SymbolContext &sc,
3079                                   const DWARFDIE &orig_die,
3080                                   bool parse_siblings, bool parse_children) {
3081  size_t types_added = 0;
3082  DWARFDIE die = orig_die;
3083
3084  while (die) {
3085    const dw_tag_t tag = die.Tag();
3086    bool type_is_new = false;
3087
3088    Tag dwarf_tag = static_cast<Tag>(tag);
3089
3090    // TODO: Currently ParseTypeFromDWARF(...) which is called by ParseType(...)
3091    // does not handle DW_TAG_subrange_type. It is not clear if this is a bug or
3092    // not.
3093    if (isType(dwarf_tag) && tag != DW_TAG_subrange_type)
3094      ParseType(sc, die, &type_is_new);
3095
3096    if (type_is_new)
3097      ++types_added;
3098
3099    if (parse_children && die.HasChildren()) {
3100      if (die.Tag() == DW_TAG_subprogram) {
3101        SymbolContext child_sc(sc);
3102        child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3103        types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3104      } else
3105        types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3106    }
3107
3108    if (parse_siblings)
3109      die = die.GetSibling();
3110    else
3111      die.Clear();
3112  }
3113  return types_added;
3114}
3115
3116size_t SymbolFileDWARF::ParseBlocksRecursive(Function &func) {
3117  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3118  CompileUnit *comp_unit = func.GetCompileUnit();
3119  lldbassert(comp_unit);
3120
3121  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(comp_unit);
3122  if (!dwarf_cu)
3123    return 0;
3124
3125  size_t functions_added = 0;
3126  const dw_offset_t function_die_offset = func.GetID();
3127  DWARFDIE function_die = dwarf_cu->GetDIE(function_die_offset);
3128  if (function_die) {
3129    ParseBlocksRecursive(*comp_unit, &func.GetBlock(false), function_die,
3130                         LLDB_INVALID_ADDRESS, 0);
3131  }
3132
3133  return functions_added;
3134}
3135
3136size_t SymbolFileDWARF::ParseTypes(CompileUnit &comp_unit) {
3137  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3138  size_t types_added = 0;
3139  DWARFUnit *dwarf_cu = GetDWARFCompileUnit(&comp_unit);
3140  if (dwarf_cu) {
3141    DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3142    if (dwarf_cu_die && dwarf_cu_die.HasChildren()) {
3143      SymbolContext sc;
3144      sc.comp_unit = &comp_unit;
3145      types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3146    }
3147  }
3148
3149  return types_added;
3150}
3151
3152size_t SymbolFileDWARF::ParseVariablesForContext(const SymbolContext &sc) {
3153  std::lock_guard<std::recursive_mutex> guard(GetModuleMutex());
3154  if (sc.comp_unit != nullptr) {
3155    DWARFDebugInfo *info = DebugInfo();
3156    if (info == nullptr)
3157      return 0;
3158
3159    if (sc.function) {
3160      DWARFDIE function_die = GetDIE(sc.function->GetID());
3161
3162      const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress(
3163          DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3164      if (func_lo_pc != LLDB_INVALID_ADDRESS) {
3165        const size_t num_variables = ParseVariables(
3166            sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3167
3168        // Let all blocks know they have parse all their variables
3169        sc.function->GetBlock(false).SetDidParseVariables(true, true);
3170        return num_variables;
3171      }
3172    } else if (sc.comp_unit) {
3173      DWARFUnit *dwarf_cu = info->GetUnitAtIndex(sc.comp_unit->GetID());
3174
3175      if (dwarf_cu == nullptr)
3176        return 0;
3177
3178      uint32_t vars_added = 0;
3179      VariableListSP variables(sc.comp_unit->GetVariableList(false));
3180
3181      if (variables.get() == nullptr) {
3182        variables = std::make_shared<VariableList>();
3183        sc.comp_unit->SetVariableList(variables);
3184
3185        DIEArray die_offsets;
3186        m_index->GetGlobalVariables(dwarf_cu->GetNonSkeletonUnit(),
3187                                    die_offsets);
3188        const size_t num_matches = die_offsets.size();
3189        if (num_matches) {
3190          for (size_t i = 0; i < num_matches; ++i) {
3191            const DIERef &die_ref = die_offsets[i];
3192            DWARFDIE die = GetDIE(die_ref);
3193            if (die) {
3194              VariableSP var_sp(
3195                  ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
3196              if (var_sp) {
3197                variables->AddVariableIfUnique(var_sp);
3198                ++vars_added;
3199              }
3200            } else
3201              m_index->ReportInvalidDIERef(die_ref, "");
3202          }
3203        }
3204      }
3205      return vars_added;
3206    }
3207  }
3208  return 0;
3209}
3210
3211VariableSP SymbolFileDWARF::ParseVariableDIE(const SymbolContext &sc,
3212                                             const DWARFDIE &die,
3213                                             const lldb::addr_t func_low_pc) {
3214  if (die.GetDWARF() != this)
3215    return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
3216
3217  VariableSP var_sp;
3218  if (!die)
3219    return var_sp;
3220
3221  var_sp = GetDIEToVariable()[die.GetDIE()];
3222  if (var_sp)
3223    return var_sp; // Already been parsed!
3224
3225  const dw_tag_t tag = die.Tag();
3226  ModuleSP module = GetObjectFile()->GetModule();
3227
3228  if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3229      (tag == DW_TAG_formal_parameter && sc.function)) {
3230    DWARFAttributes attributes;
3231    const size_t num_attributes = die.GetAttributes(attributes);
3232    DWARFDIE spec_die;
3233    if (num_attributes > 0) {
3234      const char *name = nullptr;
3235      const char *mangled = nullptr;
3236      Declaration decl;
3237      uint32_t i;
3238      DWARFFormValue type_die_form;
3239      DWARFExpression location;
3240      bool is_external = false;
3241      bool is_artificial = false;
3242      bool location_is_const_value_data = false;
3243      bool has_explicit_location = false;
3244      DWARFFormValue const_value;
3245      Variable::RangeList scope_ranges;
3246      // AccessType accessibility = eAccessNone;
3247
3248      for (i = 0; i < num_attributes; ++i) {
3249        dw_attr_t attr = attributes.AttributeAtIndex(i);
3250        DWARFFormValue form_value;
3251
3252        if (attributes.ExtractFormValueAtIndex(i, form_value)) {
3253          switch (attr) {
3254          case DW_AT_decl_file:
3255            decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(
3256                form_value.Unsigned()));
3257            break;
3258          case DW_AT_decl_line:
3259            decl.SetLine(form_value.Unsigned());
3260            break;
3261          case DW_AT_decl_column:
3262            decl.SetColumn(form_value.Unsigned());
3263            break;
3264          case DW_AT_name:
3265            name = form_value.AsCString();
3266            break;
3267          case DW_AT_linkage_name:
3268          case DW_AT_MIPS_linkage_name:
3269            mangled = form_value.AsCString();
3270            break;
3271          case DW_AT_type:
3272            type_die_form = form_value;
3273            break;
3274          case DW_AT_external:
3275            is_external = form_value.Boolean();
3276            break;
3277          case DW_AT_const_value:
3278            // If we have already found a DW_AT_location attribute, ignore this
3279            // attribute.
3280            if (!has_explicit_location) {
3281              location_is_const_value_data = true;
3282              // The constant value will be either a block, a data value or a
3283              // string.
3284              auto debug_info_data = die.GetData();
3285              if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3286                // Retrieve the value as a block expression.
3287                uint32_t block_offset =
3288                    form_value.BlockData() - debug_info_data.GetDataStart();
3289                uint32_t block_length = form_value.Unsigned();
3290                location = DWARFExpression(
3291                    module,
3292                    DataExtractor(debug_info_data, block_offset, block_length),
3293                    die.GetCU());
3294              } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3295                // Retrieve the value as a data expression.
3296                uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3297                if (auto data_length = form_value.GetFixedSize())
3298                  location = DWARFExpression(
3299                      module,
3300                      DataExtractor(debug_info_data, data_offset, *data_length),
3301                      die.GetCU());
3302                else {
3303                  const uint8_t *data_pointer = form_value.BlockData();
3304                  if (data_pointer) {
3305                    form_value.Unsigned();
3306                  } else if (DWARFFormValue::IsDataForm(form_value.Form())) {
3307                    // we need to get the byte size of the type later after we
3308                    // create the variable
3309                    const_value = form_value;
3310                  }
3311                }
3312              } else {
3313                // Retrieve the value as a string expression.
3314                if (form_value.Form() == DW_FORM_strp) {
3315                  uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
3316                  if (auto data_length = form_value.GetFixedSize())
3317                    location = DWARFExpression(module,
3318                                               DataExtractor(debug_info_data,
3319                                                             data_offset,
3320                                                             *data_length),
3321                                               die.GetCU());
3322                } else {
3323                  const char *str = form_value.AsCString();
3324                  uint32_t string_offset =
3325                      str - (const char *)debug_info_data.GetDataStart();
3326                  uint32_t string_length = strlen(str) + 1;
3327                  location = DWARFExpression(module,
3328                                             DataExtractor(debug_info_data,
3329                                                           string_offset,
3330                                                           string_length),
3331                                             die.GetCU());
3332                }
3333              }
3334            }
3335            break;
3336          case DW_AT_location: {
3337            location_is_const_value_data = false;
3338            has_explicit_location = true;
3339            if (DWARFFormValue::IsBlockForm(form_value.Form())) {
3340              auto data = die.GetData();
3341
3342              uint32_t block_offset =
3343                  form_value.BlockData() - data.GetDataStart();
3344              uint32_t block_length = form_value.Unsigned();
3345              location = DWARFExpression(
3346                  module, DataExtractor(data, block_offset, block_length),
3347                  die.GetCU());
3348            } else {
3349              DataExtractor data = die.GetCU()->GetLocationData();
3350              dw_offset_t offset = form_value.Unsigned();
3351              if (form_value.Form() == DW_FORM_loclistx)
3352                offset = die.GetCU()->GetLoclistOffset(offset).getValueOr(-1);
3353              if (data.ValidOffset(offset)) {
3354                data = DataExtractor(data, offset, data.GetByteSize() - offset);
3355                location = DWARFExpression(module, data, die.GetCU());
3356                assert(func_low_pc != LLDB_INVALID_ADDRESS);
3357                location.SetLocationListAddresses(
3358                    attributes.CompileUnitAtIndex(i)->GetBaseAddress(),
3359                    func_low_pc);
3360              }
3361            }
3362          } break;
3363          case DW_AT_specification:
3364            spec_die = form_value.Reference();
3365            break;
3366          case DW_AT_start_scope:
3367            // TODO: Implement this.
3368            break;
3369          case DW_AT_artificial:
3370            is_artificial = form_value.Boolean();
3371            break;
3372          case DW_AT_accessibility:
3373            break; // accessibility =
3374                   // DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
3375          case DW_AT_declaration:
3376          case DW_AT_description:
3377          case DW_AT_endianity:
3378          case DW_AT_segment:
3379          case DW_AT_visibility:
3380          default:
3381          case DW_AT_abstract_origin:
3382          case DW_AT_sibling:
3383            break;
3384          }
3385        }
3386      }
3387
3388      const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
3389      const dw_tag_t parent_tag = die.GetParent().Tag();
3390      bool is_static_member =
3391          (parent_tag == DW_TAG_compile_unit ||
3392           parent_tag == DW_TAG_partial_unit) &&
3393          (parent_context_die.Tag() == DW_TAG_class_type ||
3394           parent_context_die.Tag() == DW_TAG_structure_type);
3395
3396      ValueType scope = eValueTypeInvalid;
3397
3398      const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
3399      SymbolContextScope *symbol_context_scope = nullptr;
3400
3401      bool has_explicit_mangled = mangled != nullptr;
3402      if (!mangled) {
3403        // LLDB relies on the mangled name (DW_TAG_linkage_name or
3404        // DW_AT_MIPS_linkage_name) to generate fully qualified names
3405        // of global variables with commands like "frame var j". For
3406        // example, if j were an int variable holding a value 4 and
3407        // declared in a namespace B which in turn is contained in a
3408        // namespace A, the command "frame var j" returns
3409        //   "(int) A::B::j = 4".
3410        // If the compiler does not emit a linkage name, we should be
3411        // able to generate a fully qualified name from the
3412        // declaration context.
3413        if ((parent_tag == DW_TAG_compile_unit ||
3414             parent_tag == DW_TAG_partial_unit) &&
3415            Language::LanguageIsCPlusPlus(die.GetLanguage())) {
3416          DWARFDeclContext decl_ctx;
3417
3418          die.GetDWARFDeclContext(decl_ctx);
3419          mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
3420        }
3421      }
3422
3423      if (tag == DW_TAG_formal_parameter)
3424        scope = eValueTypeVariableArgument;
3425      else {
3426        // DWARF doesn't specify if a DW_TAG_variable is a local, global
3427        // or static variable, so we have to do a little digging:
3428        // 1) DW_AT_linkage_name implies static lifetime (but may be missing)
3429        // 2) An empty DW_AT_location is an (optimized-out) static lifetime var.
3430        // 3) DW_AT_location containing a DW_OP_addr implies static lifetime.
3431        // Clang likes to combine small global variables into the same symbol
3432        // with locations like: DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
3433        // so we need to look through the whole expression.
3434        bool is_static_lifetime =
3435            has_explicit_mangled ||
3436            (has_explicit_location && !location.IsValid());
3437        // Check if the location has a DW_OP_addr with any address value...
3438        lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
3439        if (!location_is_const_value_data) {
3440          bool op_error = false;
3441          location_DW_OP_addr = location.GetLocation_DW_OP_addr(0, op_error);
3442          if (op_error) {
3443            StreamString strm;
3444            location.DumpLocationForAddress(&strm, eDescriptionLevelFull, 0, 0,
3445                                            nullptr);
3446            GetObjectFile()->GetModule()->ReportError(
3447                "0x%8.8x: %s has an invalid location: %s", die.GetOffset(),
3448                die.GetTagAsCString(), strm.GetData());
3449          }
3450          if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
3451            is_static_lifetime = true;
3452        }
3453        SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
3454        if (debug_map_symfile)
3455          // Set the module of the expression to the linked module
3456          // instead of the oject file so the relocated address can be
3457          // found there.
3458          location.SetModule(debug_map_symfile->GetObjectFile()->GetModule());
3459
3460        if (is_static_lifetime) {
3461          if (is_external)
3462            scope = eValueTypeVariableGlobal;
3463          else
3464            scope = eValueTypeVariableStatic;
3465
3466          if (debug_map_symfile) {
3467            // When leaving the DWARF in the .o files on darwin, when we have a
3468            // global variable that wasn't initialized, the .o file might not
3469            // have allocated a virtual address for the global variable. In
3470            // this case it will have created a symbol for the global variable
3471            // that is undefined/data and external and the value will be the
3472            // byte size of the variable. When we do the address map in
3473            // SymbolFileDWARFDebugMap we rely on having an address, we need to
3474            // do some magic here so we can get the correct address for our
3475            // global variable. The address for all of these entries will be
3476            // zero, and there will be an undefined symbol in this object file,
3477            // and the executable will have a matching symbol with a good
3478            // address. So here we dig up the correct address and replace it in
3479            // the location for the variable, and set the variable's symbol
3480            // context scope to be that of the main executable so the file
3481            // address will resolve correctly.
3482            bool linked_oso_file_addr = false;
3483            if (is_external && location_DW_OP_addr == 0) {
3484              // we have a possible uninitialized extern global
3485              ConstString const_name(mangled ? mangled : name);
3486              ObjectFile *debug_map_objfile =
3487                  debug_map_symfile->GetObjectFile();
3488              if (debug_map_objfile) {
3489                Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
3490                if (debug_map_symtab) {
3491                  Symbol *exe_symbol =
3492                      debug_map_symtab->FindFirstSymbolWithNameAndType(
3493                          const_name, eSymbolTypeData, Symtab::eDebugYes,
3494                          Symtab::eVisibilityExtern);
3495                  if (exe_symbol) {
3496                    if (exe_symbol->ValueIsAddress()) {
3497                      const addr_t exe_file_addr =
3498                          exe_symbol->GetAddressRef().GetFileAddress();
3499                      if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3500                        if (location.Update_DW_OP_addr(exe_file_addr)) {
3501                          linked_oso_file_addr = true;
3502                          symbol_context_scope = exe_symbol;
3503                        }
3504                      }
3505                    }
3506                  }
3507                }
3508              }
3509            }
3510
3511            if (!linked_oso_file_addr) {
3512              // The DW_OP_addr is not zero, but it contains a .o file address
3513              // which needs to be linked up correctly.
3514              const lldb::addr_t exe_file_addr =
3515                  debug_map_symfile->LinkOSOFileAddress(this,
3516                                                        location_DW_OP_addr);
3517              if (exe_file_addr != LLDB_INVALID_ADDRESS) {
3518                // Update the file address for this variable
3519                location.Update_DW_OP_addr(exe_file_addr);
3520              } else {
3521                // Variable didn't make it into the final executable
3522                return var_sp;
3523              }
3524            }
3525          }
3526        } else {
3527          if (location_is_const_value_data)
3528            scope = eValueTypeVariableStatic;
3529          else {
3530            scope = eValueTypeVariableLocal;
3531            if (debug_map_symfile) {
3532              // We need to check for TLS addresses that we need to fixup
3533              if (location.ContainsThreadLocalStorage()) {
3534                location.LinkThreadLocalStorage(
3535                    debug_map_symfile->GetObjectFile()->GetModule(),
3536                    [this, debug_map_symfile](
3537                        lldb::addr_t unlinked_file_addr) -> lldb::addr_t {
3538                      return debug_map_symfile->LinkOSOFileAddress(
3539                          this, unlinked_file_addr);
3540                    });
3541                scope = eValueTypeVariableThreadLocal;
3542              }
3543            }
3544          }
3545        }
3546      }
3547
3548      if (symbol_context_scope == nullptr) {
3549        switch (parent_tag) {
3550        case DW_TAG_subprogram:
3551        case DW_TAG_inlined_subroutine:
3552        case DW_TAG_lexical_block:
3553          if (sc.function) {
3554            symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(
3555                sc_parent_die.GetID());
3556            if (symbol_context_scope == nullptr)
3557              symbol_context_scope = sc.function;
3558          }
3559          break;
3560
3561        default:
3562          symbol_context_scope = sc.comp_unit;
3563          break;
3564        }
3565      }
3566
3567      if (symbol_context_scope) {
3568        SymbolFileTypeSP type_sp(
3569            new SymbolFileType(*this, GetUID(type_die_form.Reference())));
3570
3571        if (const_value.Form() && type_sp && type_sp->GetType())
3572          location.UpdateValue(const_value.Unsigned(),
3573                               type_sp->GetType()->GetByteSize().getValueOr(0),
3574                               die.GetCU()->GetAddressByteSize());
3575
3576        var_sp = std::make_shared<Variable>(
3577            die.GetID(), name, mangled, type_sp, scope, symbol_context_scope,
3578            scope_ranges, &decl, location, is_external, is_artificial,
3579            is_static_member);
3580
3581        var_sp->SetLocationIsConstantValueData(location_is_const_value_data);
3582      } else {
3583        // Not ready to parse this variable yet. It might be a global or static
3584        // variable that is in a function scope and the function in the symbol
3585        // context wasn't filled in yet
3586        return var_sp;
3587      }
3588    }
3589    // Cache var_sp even if NULL (the variable was just a specification or was
3590    // missing vital information to be able to be displayed in the debugger
3591    // (missing location due to optimization, etc)) so we don't re-parse this
3592    // DIE over and over later...
3593    GetDIEToVariable()[die.GetDIE()] = var_sp;
3594    if (spec_die)
3595      GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
3596  }
3597  return var_sp;
3598}
3599
3600DWARFDIE
3601SymbolFileDWARF::FindBlockContainingSpecification(
3602    const DIERef &func_die_ref, dw_offset_t spec_block_die_offset) {
3603  // Give the concrete function die specified by "func_die_offset", find the
3604  // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3605  // to "spec_block_die_offset"
3606  return FindBlockContainingSpecification(DebugInfo()->GetDIE(func_die_ref),
3607                                          spec_block_die_offset);
3608}
3609
3610DWARFDIE
3611SymbolFileDWARF::FindBlockContainingSpecification(
3612    const DWARFDIE &die, dw_offset_t spec_block_die_offset) {
3613  if (die) {
3614    switch (die.Tag()) {
3615    case DW_TAG_subprogram:
3616    case DW_TAG_inlined_subroutine:
3617    case DW_TAG_lexical_block: {
3618      if (die.GetReferencedDIE(DW_AT_specification).GetOffset() ==
3619          spec_block_die_offset)
3620        return die;
3621
3622      if (die.GetReferencedDIE(DW_AT_abstract_origin).GetOffset() ==
3623          spec_block_die_offset)
3624        return die;
3625    } break;
3626    default:
3627      break;
3628    }
3629
3630    // Give the concrete function die specified by "func_die_offset", find the
3631    // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
3632    // to "spec_block_die_offset"
3633    for (DWARFDIE child_die = die.GetFirstChild(); child_die;
3634         child_die = child_die.GetSibling()) {
3635      DWARFDIE result_die =
3636          FindBlockContainingSpecification(child_die, spec_block_die_offset);
3637      if (result_die)
3638        return result_die;
3639    }
3640  }
3641
3642  return DWARFDIE();
3643}
3644
3645size_t SymbolFileDWARF::ParseVariables(const SymbolContext &sc,
3646                                       const DWARFDIE &orig_die,
3647                                       const lldb::addr_t func_low_pc,
3648                                       bool parse_siblings, bool parse_children,
3649                                       VariableList *cc_variable_list) {
3650  if (!orig_die)
3651    return 0;
3652
3653  VariableListSP variable_list_sp;
3654
3655  size_t vars_added = 0;
3656  DWARFDIE die = orig_die;
3657  while (die) {
3658    dw_tag_t tag = die.Tag();
3659
3660    // Check to see if we have already parsed this variable or constant?
3661    VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
3662    if (var_sp) {
3663      if (cc_variable_list)
3664        cc_variable_list->AddVariableIfUnique(var_sp);
3665    } else {
3666      // We haven't already parsed it, lets do that now.
3667      if ((tag == DW_TAG_variable) || (tag == DW_TAG_constant) ||
3668          (tag == DW_TAG_formal_parameter && sc.function)) {
3669        if (variable_list_sp.get() == nullptr) {
3670          DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
3671          dw_tag_t parent_tag = sc_parent_die.Tag();
3672          switch (parent_tag) {
3673          case DW_TAG_compile_unit:
3674          case DW_TAG_partial_unit:
3675            if (sc.comp_unit != nullptr) {
3676              variable_list_sp = sc.comp_unit->GetVariableList(false);
3677              if (variable_list_sp.get() == nullptr) {
3678                variable_list_sp = std::make_shared<VariableList>();
3679              }
3680            } else {
3681              GetObjectFile()->GetModule()->ReportError(
3682                  "parent 0x%8.8" PRIx64 " %s with no valid compile unit in "
3683                  "symbol context for 0x%8.8" PRIx64 " %s.\n",
3684                  sc_parent_die.GetID(), sc_parent_die.GetTagAsCString(),
3685                  orig_die.GetID(), orig_die.GetTagAsCString());
3686            }
3687            break;
3688
3689          case DW_TAG_subprogram:
3690          case DW_TAG_inlined_subroutine:
3691          case DW_TAG_lexical_block:
3692            if (sc.function != nullptr) {
3693              // Check to see if we already have parsed the variables for the
3694              // given scope
3695
3696              Block *block = sc.function->GetBlock(true).FindBlockByID(
3697                  sc_parent_die.GetID());
3698              if (block == nullptr) {
3699                // This must be a specification or abstract origin with a
3700                // concrete block counterpart in the current function. We need
3701                // to find the concrete block so we can correctly add the
3702                // variable to it
3703                const DWARFDIE concrete_block_die =
3704                    FindBlockContainingSpecification(
3705                        GetDIE(sc.function->GetID()),
3706                        sc_parent_die.GetOffset());
3707                if (concrete_block_die)
3708                  block = sc.function->GetBlock(true).FindBlockByID(
3709                      concrete_block_die.GetID());
3710              }
3711
3712              if (block != nullptr) {
3713                const bool can_create = false;
3714                variable_list_sp = block->GetBlockVariableList(can_create);
3715                if (variable_list_sp.get() == nullptr) {
3716                  variable_list_sp = std::make_shared<VariableList>();
3717                  block->SetVariableList(variable_list_sp);
3718                }
3719              }
3720            }
3721            break;
3722
3723          default:
3724            GetObjectFile()->GetModule()->ReportError(
3725                "didn't find appropriate parent DIE for variable list for "
3726                "0x%8.8" PRIx64 " %s.\n",
3727                orig_die.GetID(), orig_die.GetTagAsCString());
3728            break;
3729          }
3730        }
3731
3732        if (variable_list_sp) {
3733          VariableSP var_sp(ParseVariableDIE(sc, die, func_low_pc));
3734          if (var_sp) {
3735            variable_list_sp->AddVariableIfUnique(var_sp);
3736            if (cc_variable_list)
3737              cc_variable_list->AddVariableIfUnique(var_sp);
3738            ++vars_added;
3739          }
3740        }
3741      }
3742    }
3743
3744    bool skip_children = (sc.function == nullptr && tag == DW_TAG_subprogram);
3745
3746    if (!skip_children && parse_children && die.HasChildren()) {
3747      vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true,
3748                                   true, cc_variable_list);
3749    }
3750
3751    if (parse_siblings)
3752      die = die.GetSibling();
3753    else
3754      die.Clear();
3755  }
3756  return vars_added;
3757}
3758
3759/// Collect call site parameters in a DW_TAG_call_site DIE.
3760static CallSiteParameterArray
3761CollectCallSiteParameters(ModuleSP module, DWARFDIE call_site_die) {
3762  CallSiteParameterArray parameters;
3763  for (DWARFDIE child = call_site_die.GetFirstChild(); child.IsValid();
3764       child = child.GetSibling()) {
3765    if (child.Tag() != DW_TAG_call_site_parameter)
3766      continue;
3767
3768    llvm::Optional<DWARFExpression> LocationInCallee;
3769    llvm::Optional<DWARFExpression> LocationInCaller;
3770
3771    DWARFAttributes attributes;
3772    const size_t num_attributes = child.GetAttributes(attributes);
3773
3774    // Parse the location at index \p attr_index within this call site parameter
3775    // DIE, or return None on failure.
3776    auto parse_simple_location =
3777        [&](int attr_index) -> llvm::Optional<DWARFExpression> {
3778      DWARFFormValue form_value;
3779      if (!attributes.ExtractFormValueAtIndex(attr_index, form_value))
3780        return {};
3781      if (!DWARFFormValue::IsBlockForm(form_value.Form()))
3782        return {};
3783      auto data = child.GetData();
3784      uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3785      uint32_t block_length = form_value.Unsigned();
3786      return DWARFExpression(module,
3787                             DataExtractor(data, block_offset, block_length),
3788                             child.GetCU());
3789    };
3790
3791    for (size_t i = 0; i < num_attributes; ++i) {
3792      dw_attr_t attr = attributes.AttributeAtIndex(i);
3793      if (attr == DW_AT_location)
3794        LocationInCallee = parse_simple_location(i);
3795      if (attr == DW_AT_call_value)
3796        LocationInCaller = parse_simple_location(i);
3797    }
3798
3799    if (LocationInCallee && LocationInCaller) {
3800      CallSiteParameter param = {*LocationInCallee, *LocationInCaller};
3801      parameters.push_back(param);
3802    }
3803  }
3804  return parameters;
3805}
3806
3807/// Collect call graph edges present in a function DIE.
3808static std::vector<std::unique_ptr<lldb_private::CallEdge>>
3809CollectCallEdges(ModuleSP module, DWARFDIE function_die) {
3810  // Check if the function has a supported call site-related attribute.
3811  // TODO: In the future it may be worthwhile to support call_all_source_calls.
3812  uint64_t has_call_edges =
3813      function_die.GetAttributeValueAsUnsigned(DW_AT_call_all_calls, 0);
3814  if (!has_call_edges)
3815    return {};
3816
3817  Log *log(lldb_private::GetLogIfAllCategoriesSet(LIBLLDB_LOG_STEP));
3818  LLDB_LOG(log, "CollectCallEdges: Found call site info in {0}",
3819           function_die.GetPubname());
3820
3821  // Scan the DIE for TAG_call_site entries.
3822  // TODO: A recursive scan of all blocks in the subprogram is needed in order
3823  // to be DWARF5-compliant. This may need to be done lazily to be performant.
3824  // For now, assume that all entries are nested directly under the subprogram
3825  // (this is the kind of DWARF LLVM produces) and parse them eagerly.
3826  std::vector<std::unique_ptr<CallEdge>> call_edges;
3827  for (DWARFDIE child = function_die.GetFirstChild(); child.IsValid();
3828       child = child.GetSibling()) {
3829    if (child.Tag() != DW_TAG_call_site)
3830      continue;
3831
3832    llvm::Optional<DWARFDIE> call_origin;
3833    llvm::Optional<DWARFExpression> call_target;
3834    addr_t return_pc = LLDB_INVALID_ADDRESS;
3835
3836    DWARFAttributes attributes;
3837    const size_t num_attributes = child.GetAttributes(attributes);
3838    for (size_t i = 0; i < num_attributes; ++i) {
3839      DWARFFormValue form_value;
3840      if (!attributes.ExtractFormValueAtIndex(i, form_value)) {
3841        LLDB_LOG(log, "CollectCallEdges: Could not extract TAG_call_site form");
3842        break;
3843      }
3844
3845      dw_attr_t attr = attributes.AttributeAtIndex(i);
3846
3847      // Extract DW_AT_call_origin (the call target's DIE).
3848      if (attr == DW_AT_call_origin) {
3849        call_origin = form_value.Reference();
3850        if (!call_origin->IsValid()) {
3851          LLDB_LOG(log, "CollectCallEdges: Invalid call origin in {0}",
3852                   function_die.GetPubname());
3853          break;
3854        }
3855      }
3856
3857      // Extract DW_AT_call_return_pc (the PC the call returns to) if it's
3858      // available. It should only ever be unavailable for tail call edges, in
3859      // which case use LLDB_INVALID_ADDRESS.
3860      if (attr == DW_AT_call_return_pc)
3861        return_pc = form_value.Address();
3862
3863      // Extract DW_AT_call_target (the location of the address of the indirect
3864      // call).
3865      if (attr == DW_AT_call_target) {
3866        if (!DWARFFormValue::IsBlockForm(form_value.Form())) {
3867          LLDB_LOG(log,
3868                   "CollectCallEdges: AT_call_target does not have block form");
3869          break;
3870        }
3871
3872        auto data = child.GetData();
3873        uint32_t block_offset = form_value.BlockData() - data.GetDataStart();
3874        uint32_t block_length = form_value.Unsigned();
3875        call_target = DWARFExpression(
3876            module, DataExtractor(data, block_offset, block_length),
3877            child.GetCU());
3878      }
3879    }
3880    if (!call_origin && !call_target) {
3881      LLDB_LOG(log, "CollectCallEdges: call site without any call target");
3882      continue;
3883    }
3884
3885    // Extract call site parameters.
3886    CallSiteParameterArray parameters =
3887        CollectCallSiteParameters(module, child);
3888
3889    std::unique_ptr<CallEdge> edge;
3890    if (call_origin) {
3891      LLDB_LOG(log, "CollectCallEdges: Found call origin: {0} (retn-PC: {1:x})",
3892               call_origin->GetPubname(), return_pc);
3893      edge = std::make_unique<DirectCallEdge>(call_origin->GetMangledName(),
3894                                              return_pc, std::move(parameters));
3895    } else {
3896      if (log) {
3897        StreamString call_target_desc;
3898        call_target->GetDescription(&call_target_desc, eDescriptionLevelBrief,
3899                                    LLDB_INVALID_ADDRESS, nullptr);
3900        LLDB_LOG(log, "CollectCallEdges: Found indirect call target: {0}",
3901                 call_target_desc.GetString());
3902      }
3903      edge = std::make_unique<IndirectCallEdge>(*call_target, return_pc,
3904                                                std::move(parameters));
3905    }
3906
3907    if (log && parameters.size()) {
3908      for (const CallSiteParameter &param : parameters) {
3909        StreamString callee_loc_desc, caller_loc_desc;
3910        param.LocationInCallee.GetDescription(&callee_loc_desc,
3911                                              eDescriptionLevelBrief,
3912                                              LLDB_INVALID_ADDRESS, nullptr);
3913        param.LocationInCaller.GetDescription(&caller_loc_desc,
3914                                              eDescriptionLevelBrief,
3915                                              LLDB_INVALID_ADDRESS, nullptr);
3916        LLDB_LOG(log, "CollectCallEdges: \tparam: {0} => {1}",
3917                 callee_loc_desc.GetString(), caller_loc_desc.GetString());
3918      }
3919    }
3920
3921    call_edges.push_back(std::move(edge));
3922  }
3923  return call_edges;
3924}
3925
3926std::vector<std::unique_ptr<lldb_private::CallEdge>>
3927SymbolFileDWARF::ParseCallEdgesInFunction(UserID func_id) {
3928  DWARFDIE func_die = GetDIE(func_id.GetID());
3929  if (func_die.IsValid())
3930    return CollectCallEdges(GetObjectFile()->GetModule(), func_die);
3931  return {};
3932}
3933
3934// PluginInterface protocol
3935ConstString SymbolFileDWARF::GetPluginName() { return GetPluginNameStatic(); }
3936
3937uint32_t SymbolFileDWARF::GetPluginVersion() { return 1; }
3938
3939void SymbolFileDWARF::Dump(lldb_private::Stream &s) {
3940  SymbolFile::Dump(s);
3941  m_index->Dump(s);
3942}
3943
3944void SymbolFileDWARF::DumpClangAST(Stream &s) {
3945  auto ts_or_err = GetTypeSystemForLanguage(eLanguageTypeC_plus_plus);
3946  if (!ts_or_err)
3947    return;
3948  ClangASTContext *clang =
3949      llvm::dyn_cast_or_null<ClangASTContext>(&ts_or_err.get());
3950  if (!clang)
3951    return;
3952  clang->Dump(s);
3953}
3954
3955SymbolFileDWARFDebugMap *SymbolFileDWARF::GetDebugMapSymfile() {
3956  if (m_debug_map_symfile == nullptr && !m_debug_map_module_wp.expired()) {
3957    lldb::ModuleSP module_sp(m_debug_map_module_wp.lock());
3958    if (module_sp) {
3959      m_debug_map_symfile =
3960          (SymbolFileDWARFDebugMap *)module_sp->GetSymbolFile();
3961    }
3962  }
3963  return m_debug_map_symfile;
3964}
3965
3966SymbolFileDWARFDwp *SymbolFileDWARF::GetDwpSymbolFile() {
3967  llvm::call_once(m_dwp_symfile_once_flag, [this]() {
3968    ModuleSpec module_spec;
3969    module_spec.GetFileSpec() = m_objfile_sp->GetFileSpec();
3970    module_spec.GetSymbolFileSpec() =
3971        FileSpec(m_objfile_sp->GetFileSpec().GetPath() + ".dwp");
3972
3973    FileSpecList search_paths = Target::GetDefaultDebugFileSearchPaths();
3974    FileSpec dwp_filespec =
3975        Symbols::LocateExecutableSymbolFile(module_spec, search_paths);
3976    if (FileSystem::Instance().Exists(dwp_filespec)) {
3977      m_dwp_symfile = SymbolFileDWARFDwp::Create(GetObjectFile()->GetModule(),
3978                                                 dwp_filespec);
3979    }
3980  });
3981  return m_dwp_symfile.get();
3982}
3983