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