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