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