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