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