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