1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFileDWARF.h"
11 
12 // Other libraries and framework includes
13 #include "llvm/Support/Casting.h"
14 
15 #include "lldb/Core/ArchSpec.h"
16 #include "lldb/Core/Module.h"
17 #include "lldb/Core/ModuleList.h"
18 #include "lldb/Core/ModuleSpec.h"
19 #include "lldb/Core/PluginManager.h"
20 #include "lldb/Core/RegularExpression.h"
21 #include "lldb/Core/Scalar.h"
22 #include "lldb/Core/Section.h"
23 #include "lldb/Core/StreamFile.h"
24 #include "lldb/Core/StreamString.h"
25 #include "lldb/Core/Timer.h"
26 #include "lldb/Core/Value.h"
27 
28 #include "Plugins/ExpressionParser/Clang/ClangModulesDeclVendor.h"
29 
30 #include "lldb/Host/FileSystem.h"
31 #include "lldb/Host/Host.h"
32 
33 #include "lldb/Interpreter/OptionValueFileSpecList.h"
34 #include "lldb/Interpreter/OptionValueProperties.h"
35 
36 #include "lldb/Symbol/Block.h"
37 #include "lldb/Symbol/ClangASTContext.h"
38 #include "lldb/Symbol/ClangUtil.h"
39 #include "lldb/Symbol/CompileUnit.h"
40 #include "lldb/Symbol/CompilerDecl.h"
41 #include "lldb/Symbol/CompilerDeclContext.h"
42 #include "lldb/Symbol/DebugMacros.h"
43 #include "lldb/Symbol/LineTable.h"
44 #include "lldb/Symbol/ObjectFile.h"
45 #include "lldb/Symbol/SymbolVendor.h"
46 #include "lldb/Symbol/TypeMap.h"
47 #include "lldb/Symbol/TypeSystem.h"
48 #include "lldb/Symbol/VariableList.h"
49 
50 #include "Plugins/Language/CPlusPlus/CPlusPlusLanguage.h"
51 #include "Plugins/Language/ObjC/ObjCLanguage.h"
52 
53 #include "lldb/Target/Language.h"
54 
55 #include "lldb/Utility/TaskPool.h"
56 
57 #include "DWARFASTParser.h"
58 #include "DWARFASTParserClang.h"
59 #include "DWARFCompileUnit.h"
60 #include "DWARFDIECollection.h"
61 #include "DWARFDebugAbbrev.h"
62 #include "DWARFDebugAranges.h"
63 #include "DWARFDebugInfo.h"
64 #include "DWARFDebugLine.h"
65 #include "DWARFDebugMacro.h"
66 #include "DWARFDebugPubnames.h"
67 #include "DWARFDebugRanges.h"
68 #include "DWARFDeclContext.h"
69 #include "DWARFFormValue.h"
70 #include "LogChannelDWARF.h"
71 #include "SymbolFileDWARFDebugMap.h"
72 #include "SymbolFileDWARFDwo.h"
73 
74 #include <map>
75 
76 #include <ctype.h>
77 #include <string.h>
78 
79 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
80 
81 #ifdef ENABLE_DEBUG_PRINTF
82 #include <stdio.h>
83 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
84 #else
85 #define DEBUG_PRINTF(fmt, ...)
86 #endif
87 
88 using namespace lldb;
89 using namespace lldb_private;
90 
91 //static inline bool
92 //child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
93 //{
94 //    switch (tag)
95 //    {
96 //    default:
97 //        break;
98 //    case DW_TAG_subprogram:
99 //    case DW_TAG_inlined_subroutine:
100 //    case DW_TAG_class_type:
101 //    case DW_TAG_structure_type:
102 //    case DW_TAG_union_type:
103 //        return true;
104 //    }
105 //    return false;
106 //}
107 //
108 
109 namespace {
110 
111     PropertyDefinition
112     g_properties[] =
113     {
114         { "comp-dir-symlink-paths" , OptionValue::eTypeFileSpecList, true,  0 ,   nullptr, nullptr, "If the DW_AT_comp_dir matches any of these paths the symbolic links will be resolved at DWARF parse time." },
115         {  nullptr                 , OptionValue::eTypeInvalid     , false, 0,    nullptr, nullptr, nullptr }
116     };
117 
118     enum
119     {
120         ePropertySymLinkPaths
121     };
122 
123 
124     class PluginProperties : public Properties
125     {
126     public:
127         static ConstString
128         GetSettingName()
129         {
130             return SymbolFileDWARF::GetPluginNameStatic();
131         }
132 
133         PluginProperties()
134         {
135             m_collection_sp.reset (new OptionValueProperties(GetSettingName()));
136             m_collection_sp->Initialize(g_properties);
137         }
138 
139         FileSpecList&
140         GetSymLinkPaths()
141         {
142             OptionValueFileSpecList *option_value = m_collection_sp->GetPropertyAtIndexAsOptionValueFileSpecList(nullptr, true, ePropertySymLinkPaths);
143             assert(option_value);
144             return option_value->GetCurrentValue();
145         }
146 
147     };
148 
149     typedef std::shared_ptr<PluginProperties> SymbolFileDWARFPropertiesSP;
150 
151     static const SymbolFileDWARFPropertiesSP&
152     GetGlobalPluginProperties()
153     {
154         static const auto g_settings_sp(std::make_shared<PluginProperties>());
155         return g_settings_sp;
156     }
157 
158 }  // anonymous namespace end
159 
160 
161 static const char*
162 removeHostnameFromPathname(const char* path_from_dwarf)
163 {
164     if (!path_from_dwarf || !path_from_dwarf[0])
165     {
166         return path_from_dwarf;
167     }
168 
169     const char *colon_pos = strchr(path_from_dwarf, ':');
170     if (nullptr == colon_pos)
171     {
172         return path_from_dwarf;
173     }
174 
175     const char *slash_pos = strchr(path_from_dwarf, '/');
176     if (slash_pos && (slash_pos < colon_pos))
177     {
178         return path_from_dwarf;
179     }
180 
181     // check whether we have a windows path, and so the first character
182     // is a drive-letter not a hostname.
183     if (
184         colon_pos == path_from_dwarf + 1 &&
185         isalpha(*path_from_dwarf) &&
186         strlen(path_from_dwarf) > 2 &&
187         '\\' == path_from_dwarf[2])
188     {
189         return path_from_dwarf;
190     }
191 
192     return colon_pos + 1;
193 }
194 
195 static const char*
196 resolveCompDir(const char* path_from_dwarf)
197 {
198     if (!path_from_dwarf)
199         return nullptr;
200 
201     // DWARF2/3 suggests the form hostname:pathname for compilation directory.
202     // Remove the host part if present.
203     const char* local_path = removeHostnameFromPathname(path_from_dwarf);
204     if (!local_path)
205         return nullptr;
206 
207     bool is_symlink = false;
208     FileSpec local_path_spec(local_path, false);
209     const auto& file_specs = GetGlobalPluginProperties()->GetSymLinkPaths();
210     for (size_t i = 0; i < file_specs.GetSize() && !is_symlink; ++i)
211         is_symlink = FileSpec::Equal(file_specs.GetFileSpecAtIndex(i), local_path_spec, true);
212 
213     if (!is_symlink)
214         return local_path;
215 
216     if (!local_path_spec.IsSymbolicLink())
217         return local_path;
218 
219     FileSpec resolved_local_path_spec;
220     const auto error = FileSystem::Readlink(local_path_spec, resolved_local_path_spec);
221     if (error.Success())
222         return resolved_local_path_spec.GetCString();
223 
224     return nullptr;
225 }
226 
227 
228 void
229 SymbolFileDWARF::Initialize()
230 {
231     LogChannelDWARF::Initialize();
232     PluginManager::RegisterPlugin (GetPluginNameStatic(),
233                                    GetPluginDescriptionStatic(),
234                                    CreateInstance,
235                                    DebuggerInitialize);
236 }
237 
238 void
239 SymbolFileDWARF::DebuggerInitialize(Debugger &debugger)
240 {
241     if (!PluginManager::GetSettingForSymbolFilePlugin(debugger, PluginProperties::GetSettingName()))
242     {
243         const bool is_global_setting = true;
244         PluginManager::CreateSettingForSymbolFilePlugin(debugger,
245                                                         GetGlobalPluginProperties()->GetValueProperties(),
246                                                         ConstString ("Properties for the dwarf symbol-file plug-in."),
247                                                         is_global_setting);
248     }
249 }
250 
251 void
252 SymbolFileDWARF::Terminate()
253 {
254     PluginManager::UnregisterPlugin (CreateInstance);
255     LogChannelDWARF::Initialize();
256 }
257 
258 
259 lldb_private::ConstString
260 SymbolFileDWARF::GetPluginNameStatic()
261 {
262     static ConstString g_name("dwarf");
263     return g_name;
264 }
265 
266 const char *
267 SymbolFileDWARF::GetPluginDescriptionStatic()
268 {
269     return "DWARF and DWARF3 debug symbol file reader.";
270 }
271 
272 
273 SymbolFile*
274 SymbolFileDWARF::CreateInstance (ObjectFile* obj_file)
275 {
276     return new SymbolFileDWARF(obj_file);
277 }
278 
279 TypeList *
280 SymbolFileDWARF::GetTypeList ()
281 {
282     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
283     if (debug_map_symfile)
284         return debug_map_symfile->GetTypeList();
285     else
286         return m_obj_file->GetModule()->GetTypeList();
287 
288 }
289 void
290 SymbolFileDWARF::GetTypes (const DWARFDIE &die,
291                            dw_offset_t min_die_offset,
292                            dw_offset_t max_die_offset,
293                            uint32_t type_mask,
294                            TypeSet &type_set)
295 {
296     if (die)
297     {
298         const dw_offset_t die_offset = die.GetOffset();
299 
300         if (die_offset >= max_die_offset)
301             return;
302 
303         if (die_offset >= min_die_offset)
304         {
305             const dw_tag_t tag = die.Tag();
306 
307             bool add_type = false;
308 
309             switch (tag)
310             {
311                 case DW_TAG_array_type:         add_type = (type_mask & eTypeClassArray         ) != 0; break;
312                 case DW_TAG_unspecified_type:
313                 case DW_TAG_base_type:          add_type = (type_mask & eTypeClassBuiltin       ) != 0; break;
314                 case DW_TAG_class_type:         add_type = (type_mask & eTypeClassClass         ) != 0; break;
315                 case DW_TAG_structure_type:     add_type = (type_mask & eTypeClassStruct        ) != 0; break;
316                 case DW_TAG_union_type:         add_type = (type_mask & eTypeClassUnion         ) != 0; break;
317                 case DW_TAG_enumeration_type:   add_type = (type_mask & eTypeClassEnumeration   ) != 0; break;
318                 case DW_TAG_subroutine_type:
319                 case DW_TAG_subprogram:
320                 case DW_TAG_inlined_subroutine: add_type = (type_mask & eTypeClassFunction      ) != 0; break;
321                 case DW_TAG_pointer_type:       add_type = (type_mask & eTypeClassPointer       ) != 0; break;
322                 case DW_TAG_rvalue_reference_type:
323                 case DW_TAG_reference_type:     add_type = (type_mask & eTypeClassReference     ) != 0; break;
324                 case DW_TAG_typedef:            add_type = (type_mask & eTypeClassTypedef       ) != 0; break;
325                 case DW_TAG_ptr_to_member_type: add_type = (type_mask & eTypeClassMemberPointer ) != 0; break;
326             }
327 
328             if (add_type)
329             {
330                 const bool assert_not_being_parsed = true;
331                 Type *type = ResolveTypeUID (die, assert_not_being_parsed);
332                 if (type)
333                 {
334                     if (type_set.find(type) == type_set.end())
335                         type_set.insert(type);
336                 }
337             }
338         }
339 
340         for (DWARFDIE child_die = die.GetFirstChild();
341              child_die.IsValid();
342              child_die = child_die.GetSibling())
343         {
344             GetTypes (child_die, min_die_offset, max_die_offset, type_mask, type_set);
345         }
346     }
347 }
348 
349 size_t
350 SymbolFileDWARF::GetTypes (SymbolContextScope *sc_scope,
351                            uint32_t type_mask,
352                            TypeList &type_list)
353 
354 {
355     TypeSet type_set;
356 
357     CompileUnit *comp_unit = NULL;
358     DWARFCompileUnit* dwarf_cu = NULL;
359     if (sc_scope)
360         comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
361 
362     if (comp_unit)
363     {
364         dwarf_cu = GetDWARFCompileUnit(comp_unit);
365         if (dwarf_cu == 0)
366             return 0;
367         GetTypes (dwarf_cu->DIE(),
368                   dwarf_cu->GetOffset(),
369                   dwarf_cu->GetNextCompileUnitOffset(),
370                   type_mask,
371                   type_set);
372     }
373     else
374     {
375         DWARFDebugInfo* info = DebugInfo();
376         if (info)
377         {
378             const size_t num_cus = info->GetNumCompileUnits();
379             for (size_t cu_idx=0; cu_idx<num_cus; ++cu_idx)
380             {
381                 dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
382                 if (dwarf_cu)
383                 {
384                     GetTypes (dwarf_cu->DIE(),
385                               0,
386                               UINT32_MAX,
387                               type_mask,
388                               type_set);
389                 }
390             }
391         }
392     }
393 
394     std::set<CompilerType> compiler_type_set;
395     size_t num_types_added = 0;
396     for (Type *type : type_set)
397     {
398         CompilerType compiler_type = type->GetForwardCompilerType ();
399         if (compiler_type_set.find(compiler_type) == compiler_type_set.end())
400         {
401             compiler_type_set.insert(compiler_type);
402             type_list.Insert (type->shared_from_this());
403             ++num_types_added;
404         }
405     }
406     return num_types_added;
407 }
408 
409 
410 //----------------------------------------------------------------------
411 // Gets the first parent that is a lexical block, function or inlined
412 // subroutine, or compile unit.
413 //----------------------------------------------------------------------
414 DWARFDIE
415 SymbolFileDWARF::GetParentSymbolContextDIE(const DWARFDIE &child_die)
416 {
417     DWARFDIE die;
418     for (die = child_die.GetParent(); die; die = die.GetParent())
419     {
420         dw_tag_t tag = die.Tag();
421 
422         switch (tag)
423         {
424         case DW_TAG_compile_unit:
425         case DW_TAG_subprogram:
426         case DW_TAG_inlined_subroutine:
427         case DW_TAG_lexical_block:
428             return die;
429         }
430     }
431     return DWARFDIE();
432 }
433 
434 
435 SymbolFileDWARF::SymbolFileDWARF(ObjectFile* objfile) :
436     SymbolFile (objfile),
437     UserID (0),  // Used by SymbolFileDWARFDebugMap to when this class parses .o files to contain the .o file index/ID
438     m_debug_map_module_wp (),
439     m_debug_map_symfile (NULL),
440     m_data_debug_abbrev (),
441     m_data_debug_aranges (),
442     m_data_debug_frame (),
443     m_data_debug_info (),
444     m_data_debug_line (),
445     m_data_debug_macro (),
446     m_data_debug_loc (),
447     m_data_debug_ranges (),
448     m_data_debug_str (),
449     m_data_apple_names (),
450     m_data_apple_types (),
451     m_data_apple_namespaces (),
452     m_abbr(),
453     m_info(),
454     m_line(),
455     m_apple_names_ap (),
456     m_apple_types_ap (),
457     m_apple_namespaces_ap (),
458     m_apple_objc_ap (),
459     m_function_basename_index(),
460     m_function_fullname_index(),
461     m_function_method_index(),
462     m_function_selector_index(),
463     m_objc_class_selectors_index(),
464     m_global_index(),
465     m_type_index(),
466     m_namespace_index(),
467     m_indexed (false),
468     m_using_apple_tables (false),
469     m_fetched_external_modules (false),
470     m_supports_DW_AT_APPLE_objc_complete_type (eLazyBoolCalculate),
471     m_ranges(),
472     m_unique_ast_type_map ()
473 {
474 }
475 
476 SymbolFileDWARF::~SymbolFileDWARF()
477 {
478 }
479 
480 static const ConstString &
481 GetDWARFMachOSegmentName ()
482 {
483     static ConstString g_dwarf_section_name ("__DWARF");
484     return g_dwarf_section_name;
485 }
486 
487 UniqueDWARFASTTypeMap &
488 SymbolFileDWARF::GetUniqueDWARFASTTypeMap ()
489 {
490     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
491     if (debug_map_symfile)
492         return debug_map_symfile->GetUniqueDWARFASTTypeMap ();
493     else
494         return m_unique_ast_type_map;
495 }
496 
497 TypeSystem *
498 SymbolFileDWARF::GetTypeSystemForLanguage (LanguageType language)
499 {
500     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
501     TypeSystem *type_system;
502     if (debug_map_symfile)
503     {
504         type_system = debug_map_symfile->GetTypeSystemForLanguage(language);
505     }
506     else
507     {
508         type_system = m_obj_file->GetModule()->GetTypeSystemForLanguage(language);
509         if (type_system)
510             type_system->SetSymbolFile(this);
511     }
512     return type_system;
513 }
514 
515 void
516 SymbolFileDWARF::InitializeObject()
517 {
518     ModuleSP module_sp (m_obj_file->GetModule());
519     if (module_sp)
520     {
521         const SectionList *section_list = module_sp->GetSectionList();
522         const Section* section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
523 
524         // Memory map the DWARF mach-o segment so we have everything mmap'ed
525         // to keep our heap memory usage down.
526         if (section)
527             m_obj_file->MemoryMapSectionData(section, m_dwarf_data);
528     }
529 
530     get_apple_names_data();
531     if (m_data_apple_names.m_data.GetByteSize() > 0)
532     {
533         m_apple_names_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_names.m_data,
534                                                                   get_debug_str_data(),
535                                                                   ".apple_names"));
536         if (m_apple_names_ap->IsValid())
537             m_using_apple_tables = true;
538         else
539             m_apple_names_ap.reset();
540     }
541     get_apple_types_data();
542     if (m_data_apple_types.m_data.GetByteSize() > 0)
543     {
544         m_apple_types_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_types.m_data,
545                                                                   get_debug_str_data(),
546                                                                   ".apple_types"));
547         if (m_apple_types_ap->IsValid())
548             m_using_apple_tables = true;
549         else
550             m_apple_types_ap.reset();
551     }
552 
553     get_apple_namespaces_data();
554     if (m_data_apple_namespaces.m_data.GetByteSize() > 0)
555     {
556         m_apple_namespaces_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_namespaces.m_data,
557                                                                        get_debug_str_data(),
558                                                                        ".apple_namespaces"));
559         if (m_apple_namespaces_ap->IsValid())
560             m_using_apple_tables = true;
561         else
562             m_apple_namespaces_ap.reset();
563     }
564 
565     get_apple_objc_data();
566     if (m_data_apple_objc.m_data.GetByteSize() > 0)
567     {
568         m_apple_objc_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_objc.m_data,
569                                                                  get_debug_str_data(),
570                                                                  ".apple_objc"));
571         if (m_apple_objc_ap->IsValid())
572             m_using_apple_tables = true;
573         else
574             m_apple_objc_ap.reset();
575     }
576 }
577 
578 bool
579 SymbolFileDWARF::SupportedVersion(uint16_t version)
580 {
581     return version == 2 || version == 3 || version == 4;
582 }
583 
584 uint32_t
585 SymbolFileDWARF::CalculateAbilities ()
586 {
587     uint32_t abilities = 0;
588     if (m_obj_file != NULL)
589     {
590         const Section* section = NULL;
591         const SectionList *section_list = m_obj_file->GetSectionList();
592         if (section_list == NULL)
593             return 0;
594 
595         uint64_t debug_abbrev_file_size = 0;
596         uint64_t debug_info_file_size = 0;
597         uint64_t debug_line_file_size = 0;
598 
599         section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
600 
601         if (section)
602             section_list = &section->GetChildren ();
603 
604         section = section_list->FindSectionByType (eSectionTypeDWARFDebugInfo, true).get();
605         if (section != NULL)
606         {
607             debug_info_file_size = section->GetFileSize();
608 
609             section = section_list->FindSectionByType (eSectionTypeDWARFDebugAbbrev, true).get();
610             if (section)
611                 debug_abbrev_file_size = section->GetFileSize();
612 
613             section = section_list->FindSectionByType (eSectionTypeDWARFDebugLine, true).get();
614             if (section)
615                 debug_line_file_size = section->GetFileSize();
616         }
617         else
618         {
619             const char *symfile_dir_cstr = m_obj_file->GetFileSpec().GetDirectory().GetCString();
620             if (symfile_dir_cstr)
621             {
622                 if (strcasestr(symfile_dir_cstr, ".dsym"))
623                 {
624                     if (m_obj_file->GetType() == ObjectFile::eTypeDebugInfo)
625                     {
626                         // We have a dSYM file that didn't have a any debug info.
627                         // If the string table has a size of 1, then it was made from
628                         // an executable with no debug info, or from an executable that
629                         // was stripped.
630                         section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
631                         if (section && section->GetFileSize() == 1)
632                         {
633                             m_obj_file->GetModule()->ReportWarning ("empty dSYM file detected, dSYM was created with an executable with no debug info.");
634                         }
635                     }
636                 }
637             }
638         }
639 
640         if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
641             abilities |= CompileUnits | Functions | Blocks | GlobalVariables | LocalVariables | VariableTypes;
642 
643         if (debug_line_file_size > 0)
644             abilities |= LineTables;
645     }
646     return abilities;
647 }
648 
649 const DWARFDataExtractor&
650 SymbolFileDWARF::GetCachedSectionData (lldb::SectionType sect_type, DWARFDataSegment& data_segment)
651 {
652     std::call_once(data_segment.m_flag,
653                    &SymbolFileDWARF::LoadSectionData,
654                    this,
655                    sect_type,
656                    std::ref(data_segment.m_data));
657     return data_segment.m_data;
658 }
659 
660 void
661 SymbolFileDWARF::LoadSectionData (lldb::SectionType sect_type, DWARFDataExtractor& data)
662 {
663     ModuleSP module_sp (m_obj_file->GetModule());
664     const SectionList *section_list = module_sp->GetSectionList();
665     if (section_list)
666     {
667         SectionSP section_sp (section_list->FindSectionByType(sect_type, true));
668         if (section_sp)
669         {
670             // See if we memory mapped the DWARF segment?
671             if (m_dwarf_data.GetByteSize())
672             {
673                 data.SetData(m_dwarf_data, section_sp->GetOffset(), section_sp->GetFileSize());
674             }
675             else
676             {
677                 if (m_obj_file->ReadSectionData(section_sp.get(), data) == 0)
678                     data.Clear();
679             }
680         }
681     }
682 }
683 
684 const DWARFDataExtractor&
685 SymbolFileDWARF::get_debug_abbrev_data()
686 {
687     return GetCachedSectionData (eSectionTypeDWARFDebugAbbrev, m_data_debug_abbrev);
688 }
689 
690 const DWARFDataExtractor&
691 SymbolFileDWARF::get_debug_addr_data()
692 {
693     return GetCachedSectionData (eSectionTypeDWARFDebugAddr, m_data_debug_addr);
694 }
695 
696 const DWARFDataExtractor&
697 SymbolFileDWARF::get_debug_aranges_data()
698 {
699     return GetCachedSectionData (eSectionTypeDWARFDebugAranges, m_data_debug_aranges);
700 }
701 
702 const DWARFDataExtractor&
703 SymbolFileDWARF::get_debug_frame_data()
704 {
705     return GetCachedSectionData (eSectionTypeDWARFDebugFrame, m_data_debug_frame);
706 }
707 
708 const DWARFDataExtractor&
709 SymbolFileDWARF::get_debug_info_data()
710 {
711     return GetCachedSectionData (eSectionTypeDWARFDebugInfo, m_data_debug_info);
712 }
713 
714 const DWARFDataExtractor&
715 SymbolFileDWARF::get_debug_line_data()
716 {
717     return GetCachedSectionData (eSectionTypeDWARFDebugLine, m_data_debug_line);
718 }
719 
720 const DWARFDataExtractor&
721 SymbolFileDWARF::get_debug_macro_data()
722 {
723     return GetCachedSectionData (eSectionTypeDWARFDebugMacro, m_data_debug_macro);
724 }
725 
726 const DWARFDataExtractor&
727 SymbolFileDWARF::get_debug_loc_data()
728 {
729     return GetCachedSectionData (eSectionTypeDWARFDebugLoc, m_data_debug_loc);
730 }
731 
732 const DWARFDataExtractor&
733 SymbolFileDWARF::get_debug_ranges_data()
734 {
735     return GetCachedSectionData (eSectionTypeDWARFDebugRanges, m_data_debug_ranges);
736 }
737 
738 const DWARFDataExtractor&
739 SymbolFileDWARF::get_debug_str_data()
740 {
741     return GetCachedSectionData (eSectionTypeDWARFDebugStr, m_data_debug_str);
742 }
743 
744 const DWARFDataExtractor&
745 SymbolFileDWARF::get_debug_str_offsets_data()
746 {
747     return GetCachedSectionData (eSectionTypeDWARFDebugStrOffsets, m_data_debug_str_offsets);
748 }
749 
750 const DWARFDataExtractor&
751 SymbolFileDWARF::get_apple_names_data()
752 {
753     return GetCachedSectionData (eSectionTypeDWARFAppleNames, m_data_apple_names);
754 }
755 
756 const DWARFDataExtractor&
757 SymbolFileDWARF::get_apple_types_data()
758 {
759     return GetCachedSectionData (eSectionTypeDWARFAppleTypes, m_data_apple_types);
760 }
761 
762 const DWARFDataExtractor&
763 SymbolFileDWARF::get_apple_namespaces_data()
764 {
765     return GetCachedSectionData (eSectionTypeDWARFAppleNamespaces, m_data_apple_namespaces);
766 }
767 
768 const DWARFDataExtractor&
769 SymbolFileDWARF::get_apple_objc_data()
770 {
771     return GetCachedSectionData (eSectionTypeDWARFAppleObjC, m_data_apple_objc);
772 }
773 
774 
775 DWARFDebugAbbrev*
776 SymbolFileDWARF::DebugAbbrev()
777 {
778     if (m_abbr.get() == NULL)
779     {
780         const DWARFDataExtractor &debug_abbrev_data = get_debug_abbrev_data();
781         if (debug_abbrev_data.GetByteSize() > 0)
782         {
783             m_abbr.reset(new DWARFDebugAbbrev());
784             if (m_abbr.get())
785                 m_abbr->Parse(debug_abbrev_data);
786         }
787     }
788     return m_abbr.get();
789 }
790 
791 const DWARFDebugAbbrev*
792 SymbolFileDWARF::DebugAbbrev() const
793 {
794     return m_abbr.get();
795 }
796 
797 
798 DWARFDebugInfo*
799 SymbolFileDWARF::DebugInfo()
800 {
801     if (m_info.get() == NULL)
802     {
803         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
804                            __PRETTY_FUNCTION__, static_cast<void*>(this));
805         if (get_debug_info_data().GetByteSize() > 0)
806         {
807             m_info.reset(new DWARFDebugInfo());
808             if (m_info.get())
809             {
810                 m_info->SetDwarfData(this);
811             }
812         }
813     }
814     return m_info.get();
815 }
816 
817 const DWARFDebugInfo*
818 SymbolFileDWARF::DebugInfo() const
819 {
820     return m_info.get();
821 }
822 
823 DWARFCompileUnit*
824 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit)
825 {
826     if (!comp_unit)
827         return nullptr;
828 
829     DWARFDebugInfo* info = DebugInfo();
830     if (info)
831     {
832         // Just a normal DWARF file whose user ID for the compile unit is
833         // the DWARF offset itself
834 
835         DWARFCompileUnit *dwarf_cu = info->GetCompileUnit((dw_offset_t)comp_unit->GetID());
836         if (dwarf_cu && dwarf_cu->GetUserData() == NULL)
837             dwarf_cu->SetUserData(comp_unit);
838         return dwarf_cu;
839     }
840     return NULL;
841 }
842 
843 
844 DWARFDebugRanges*
845 SymbolFileDWARF::DebugRanges()
846 {
847     if (m_ranges.get() == NULL)
848     {
849         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
850                            __PRETTY_FUNCTION__, static_cast<void*>(this));
851         if (get_debug_ranges_data().GetByteSize() > 0)
852         {
853             m_ranges.reset(new DWARFDebugRanges());
854             if (m_ranges.get())
855                 m_ranges->Extract(this);
856         }
857     }
858     return m_ranges.get();
859 }
860 
861 const DWARFDebugRanges*
862 SymbolFileDWARF::DebugRanges() const
863 {
864     return m_ranges.get();
865 }
866 
867 lldb::CompUnitSP
868 SymbolFileDWARF::ParseCompileUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
869 {
870     CompUnitSP cu_sp;
871     if (dwarf_cu)
872     {
873         CompileUnit *comp_unit = (CompileUnit*)dwarf_cu->GetUserData();
874         if (comp_unit)
875         {
876             // We already parsed this compile unit, had out a shared pointer to it
877             cu_sp = comp_unit->shared_from_this();
878         }
879         else
880         {
881             if (dwarf_cu->GetSymbolFileDWARF() != this)
882             {
883                 return dwarf_cu->GetSymbolFileDWARF()->ParseCompileUnit(dwarf_cu, cu_idx);
884             }
885             else if (dwarf_cu->GetOffset() == 0 && GetDebugMapSymfile ())
886             {
887                 // Let the debug map create the compile unit
888                 cu_sp = m_debug_map_symfile->GetCompileUnit(this);
889                 dwarf_cu->SetUserData(cu_sp.get());
890             }
891             else
892             {
893                 ModuleSP module_sp (m_obj_file->GetModule());
894                 if (module_sp)
895                 {
896                     const DWARFDIE cu_die = dwarf_cu->GetCompileUnitDIEOnly ();
897                     if (cu_die)
898                     {
899                         FileSpec cu_file_spec{cu_die.GetName(), false};
900                         if (cu_file_spec)
901                         {
902                             // If we have a full path to the compile unit, we don't need to resolve
903                             // the file.  This can be expensive e.g. when the source files are NFS mounted.
904                             if (cu_file_spec.IsRelative())
905                             {
906                                 const char *cu_comp_dir{cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr)};
907                                 cu_file_spec.PrependPathComponent(resolveCompDir(cu_comp_dir));
908                             }
909 
910                             std::string remapped_file;
911                             if (module_sp->RemapSourceFile(cu_file_spec.GetCString(), remapped_file))
912                                 cu_file_spec.SetFile(remapped_file, false);
913                         }
914 
915                         LanguageType cu_language = DWARFCompileUnit::LanguageTypeFromDWARF(cu_die.GetAttributeValueAsUnsigned(DW_AT_language, 0));
916 
917                         bool is_optimized = dwarf_cu->GetIsOptimized ();
918                         cu_sp.reset(new CompileUnit (module_sp,
919                                                      dwarf_cu,
920                                                      cu_file_spec,
921                                                      dwarf_cu->GetID(),
922                                                      cu_language,
923                                                      is_optimized));
924                         if (cu_sp)
925                         {
926                             // If we just created a compile unit with an invalid file spec, try and get the
927                             // first entry in the supports files from the line table as that should be the
928                             // compile unit.
929                             if (!cu_file_spec)
930                             {
931                                 cu_file_spec = cu_sp->GetSupportFiles().GetFileSpecAtIndex(1);
932                                 if (cu_file_spec)
933                                 {
934                                     (FileSpec &)(*cu_sp) = cu_file_spec;
935                                     // Also fix the invalid file spec which was copied from the compile unit.
936                                     cu_sp->GetSupportFiles().Replace(0, cu_file_spec);
937                                 }
938                             }
939 
940                             dwarf_cu->SetUserData(cu_sp.get());
941 
942                             // Figure out the compile unit index if we weren't given one
943                             if (cu_idx == UINT32_MAX)
944                                 DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx);
945 
946                             m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cu_idx, cu_sp);
947                         }
948                     }
949                 }
950             }
951         }
952     }
953     return cu_sp;
954 }
955 
956 uint32_t
957 SymbolFileDWARF::GetNumCompileUnits()
958 {
959     DWARFDebugInfo* info = DebugInfo();
960     if (info)
961         return info->GetNumCompileUnits();
962     return 0;
963 }
964 
965 CompUnitSP
966 SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx)
967 {
968     CompUnitSP cu_sp;
969     DWARFDebugInfo* info = DebugInfo();
970     if (info)
971     {
972         DWARFCompileUnit* dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
973         if (dwarf_cu)
974             cu_sp = ParseCompileUnit(dwarf_cu, cu_idx);
975     }
976     return cu_sp;
977 }
978 
979 Function *
980 SymbolFileDWARF::ParseCompileUnitFunction (const SymbolContext& sc, const DWARFDIE &die)
981 {
982     if (die.IsValid())
983     {
984         TypeSystem *type_system = GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
985 
986         if (type_system)
987         {
988             DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
989             if (dwarf_ast)
990                 return dwarf_ast->ParseFunctionFromDWARF(sc, die);
991         }
992     }
993     return nullptr;
994 }
995 
996 bool
997 SymbolFileDWARF::FixupAddress (Address &addr)
998 {
999     SymbolFileDWARFDebugMap * debug_map_symfile = GetDebugMapSymfile();
1000     if (debug_map_symfile)
1001     {
1002         return debug_map_symfile->LinkOSOAddress(addr);
1003     }
1004     // This is a normal DWARF file, no address fixups need to happen
1005     return true;
1006 }
1007 lldb::LanguageType
1008 SymbolFileDWARF::ParseCompileUnitLanguage (const SymbolContext& sc)
1009 {
1010     assert (sc.comp_unit);
1011     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1012     if (dwarf_cu)
1013         return dwarf_cu->GetLanguageType();
1014     else
1015         return eLanguageTypeUnknown;
1016 }
1017 
1018 size_t
1019 SymbolFileDWARF::ParseCompileUnitFunctions(const SymbolContext &sc)
1020 {
1021     assert (sc.comp_unit);
1022     size_t functions_added = 0;
1023     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1024     if (dwarf_cu)
1025     {
1026         DWARFDIECollection function_dies;
1027         const size_t num_functions = dwarf_cu->AppendDIEsWithTag (DW_TAG_subprogram, function_dies);
1028         size_t func_idx;
1029         for (func_idx = 0; func_idx < num_functions; ++func_idx)
1030         {
1031             DWARFDIE die = function_dies.GetDIEAtIndex(func_idx);
1032             if (sc.comp_unit->FindFunctionByUID (die.GetID()).get() == NULL)
1033             {
1034                 if (ParseCompileUnitFunction(sc, die))
1035                     ++functions_added;
1036             }
1037         }
1038         //FixupTypes();
1039     }
1040     return functions_added;
1041 }
1042 
1043 bool
1044 SymbolFileDWARF::ParseCompileUnitSupportFiles (const SymbolContext& sc, FileSpecList& support_files)
1045 {
1046     assert (sc.comp_unit);
1047     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1048     if (dwarf_cu)
1049     {
1050         const DWARFDIE cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1051 
1052         if (cu_die)
1053         {
1054             const char * cu_comp_dir = resolveCompDir(cu_die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr));
1055             const dw_offset_t stmt_list = cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list, DW_INVALID_OFFSET);
1056             if (stmt_list != DW_INVALID_OFFSET)
1057             {
1058                 // All file indexes in DWARF are one based and a file of index zero is
1059                 // supposed to be the compile unit itself.
1060                 support_files.Append (*sc.comp_unit);
1061                 return DWARFDebugLine::ParseSupportFiles(sc.comp_unit->GetModule(),
1062                                                          get_debug_line_data(),
1063                                                          cu_comp_dir,
1064                                                          stmt_list,
1065                                                          support_files);
1066             }
1067         }
1068     }
1069     return false;
1070 }
1071 
1072 bool
1073 SymbolFileDWARF::ParseImportedModules (const lldb_private::SymbolContext &sc, std::vector<lldb_private::ConstString> &imported_modules)
1074 {
1075     assert (sc.comp_unit);
1076     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1077     if (dwarf_cu)
1078     {
1079         if (ClangModulesDeclVendor::LanguageSupportsClangModules(sc.comp_unit->GetLanguage()))
1080         {
1081             UpdateExternalModuleListIfNeeded();
1082 
1083             if (sc.comp_unit)
1084             {
1085                 const DWARFDIE die = dwarf_cu->GetCompileUnitDIEOnly();
1086 
1087                 if (die)
1088                 {
1089                     for (DWARFDIE child_die = die.GetFirstChild();
1090                          child_die;
1091                          child_die = child_die.GetSibling())
1092                     {
1093                         if (child_die.Tag() == DW_TAG_imported_declaration)
1094                         {
1095                             if (DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import))
1096                             {
1097                                 if (module_die.Tag() == DW_TAG_module)
1098                                 {
1099                                     if (const char *name = module_die.GetAttributeValueAsString(DW_AT_name, nullptr))
1100                                     {
1101                                         ConstString const_name(name);
1102                                         imported_modules.push_back(const_name);
1103                                     }
1104                                 }
1105                             }
1106                         }
1107                     }
1108                 }
1109             }
1110             else
1111             {
1112                 for (const auto &pair : m_external_type_modules)
1113                 {
1114                     imported_modules.push_back(pair.first);
1115                 }
1116             }
1117         }
1118     }
1119     return false;
1120 }
1121 
1122 struct ParseDWARFLineTableCallbackInfo
1123 {
1124     LineTable* line_table;
1125     std::unique_ptr<LineSequence> sequence_ap;
1126     lldb::addr_t addr_mask;
1127 };
1128 
1129 //----------------------------------------------------------------------
1130 // ParseStatementTableCallback
1131 //----------------------------------------------------------------------
1132 static void
1133 ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State& state, void* userData)
1134 {
1135     if (state.row == DWARFDebugLine::State::StartParsingLineTable)
1136     {
1137         // Just started parsing the line table
1138     }
1139     else if (state.row == DWARFDebugLine::State::DoneParsingLineTable)
1140     {
1141         // Done parsing line table, nothing to do for the cleanup
1142     }
1143     else
1144     {
1145         ParseDWARFLineTableCallbackInfo* info = (ParseDWARFLineTableCallbackInfo*)userData;
1146         LineTable* line_table = info->line_table;
1147 
1148         // If this is our first time here, we need to create a
1149         // sequence container.
1150         if (!info->sequence_ap.get())
1151         {
1152             info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1153             assert(info->sequence_ap.get());
1154         }
1155         line_table->AppendLineEntryToSequence (info->sequence_ap.get(),
1156                                                state.address & info->addr_mask,
1157                                                state.line,
1158                                                state.column,
1159                                                state.file,
1160                                                state.is_stmt,
1161                                                state.basic_block,
1162                                                state.prologue_end,
1163                                                state.epilogue_begin,
1164                                                state.end_sequence);
1165         if (state.end_sequence)
1166         {
1167             // First, put the current sequence into the line table.
1168             line_table->InsertSequence(info->sequence_ap.get());
1169             // Then, empty it to prepare for the next sequence.
1170             info->sequence_ap->Clear();
1171         }
1172     }
1173 }
1174 
1175 bool
1176 SymbolFileDWARF::ParseCompileUnitLineTable (const SymbolContext &sc)
1177 {
1178     assert (sc.comp_unit);
1179     if (sc.comp_unit->GetLineTable() != NULL)
1180         return true;
1181 
1182     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1183     if (dwarf_cu)
1184     {
1185         const DWARFDIE dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1186         if (dwarf_cu_die)
1187         {
1188             const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list, DW_INVALID_OFFSET);
1189             if (cu_line_offset != DW_INVALID_OFFSET)
1190             {
1191                 std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1192                 if (line_table_ap.get())
1193                 {
1194                     ParseDWARFLineTableCallbackInfo info;
1195                     info.line_table = line_table_ap.get();
1196 
1197                     /*
1198                      * MIPS:
1199                      * The SymbolContext may not have a valid target, thus we may not be able
1200                      * to call Address::GetOpcodeLoadAddress() which would clear the bit #0
1201                      * for MIPS. Use ArchSpec to clear the bit #0.
1202                     */
1203                     ArchSpec arch;
1204                     GetObjectFile()->GetArchitecture(arch);
1205                     switch (arch.GetMachine())
1206                     {
1207                     case llvm::Triple::mips:
1208                     case llvm::Triple::mipsel:
1209                     case llvm::Triple::mips64:
1210                     case llvm::Triple::mips64el:
1211                         info.addr_mask = ~((lldb::addr_t)1);
1212                         break;
1213                     default:
1214                         info.addr_mask = ~((lldb::addr_t)0);
1215                         break;
1216                     }
1217 
1218                     lldb::offset_t offset = cu_line_offset;
1219                     DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info);
1220                     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
1221                     if (debug_map_symfile)
1222                     {
1223                         // We have an object file that has a line table with addresses
1224                         // that are not linked. We need to link the line table and convert
1225                         // the addresses that are relative to the .o file into addresses
1226                         // for the main executable.
1227                         sc.comp_unit->SetLineTable (debug_map_symfile->LinkOSOLineTable (this, line_table_ap.get()));
1228                     }
1229                     else
1230                     {
1231                         sc.comp_unit->SetLineTable(line_table_ap.release());
1232                         return true;
1233                     }
1234                 }
1235             }
1236         }
1237     }
1238     return false;
1239 }
1240 
1241 lldb_private::DebugMacrosSP
1242 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset)
1243 {
1244     auto iter = m_debug_macros_map.find(*offset);
1245     if (iter != m_debug_macros_map.end())
1246         return iter->second;
1247 
1248     const DWARFDataExtractor &debug_macro_data = get_debug_macro_data();
1249     if (debug_macro_data.GetByteSize() == 0)
1250         return DebugMacrosSP();
1251 
1252     lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1253     m_debug_macros_map[*offset] = debug_macros_sp;
1254 
1255     const DWARFDebugMacroHeader &header = DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1256     DWARFDebugMacroEntry::ReadMacroEntries(
1257         debug_macro_data, get_debug_str_data(), header.OffsetIs64Bit(), offset, this, debug_macros_sp);
1258 
1259     return debug_macros_sp;
1260 }
1261 
1262 bool
1263 SymbolFileDWARF::ParseCompileUnitDebugMacros(const SymbolContext& sc)
1264 {
1265     assert (sc.comp_unit);
1266 
1267     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1268     if (dwarf_cu == nullptr)
1269         return false;
1270 
1271     const DWARFDIE dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1272     if (!dwarf_cu_die)
1273         return false;
1274 
1275     lldb::offset_t sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1276     if (sect_offset == DW_INVALID_OFFSET)
1277         sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros, DW_INVALID_OFFSET);
1278     if (sect_offset == DW_INVALID_OFFSET)
1279         return false;
1280 
1281     sc.comp_unit->SetDebugMacros(ParseDebugMacros(&sect_offset));
1282 
1283     return true;
1284 }
1285 
1286 size_t
1287 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext& sc,
1288                                       Block *parent_block,
1289                                       const DWARFDIE &orig_die,
1290                                       addr_t subprogram_low_pc,
1291                                       uint32_t depth)
1292 {
1293     size_t blocks_added = 0;
1294     DWARFDIE die = orig_die;
1295     while (die)
1296     {
1297         dw_tag_t tag = die.Tag();
1298 
1299         switch (tag)
1300         {
1301         case DW_TAG_inlined_subroutine:
1302         case DW_TAG_subprogram:
1303         case DW_TAG_lexical_block:
1304             {
1305                 Block *block = NULL;
1306                 if (tag == DW_TAG_subprogram)
1307                 {
1308                     // Skip any DW_TAG_subprogram DIEs that are inside
1309                     // of a normal or inlined functions. These will be
1310                     // parsed on their own as separate entities.
1311 
1312                     if (depth > 0)
1313                         break;
1314 
1315                     block = parent_block;
1316                 }
1317                 else
1318                 {
1319                     BlockSP block_sp(new Block (die.GetID()));
1320                     parent_block->AddChild(block_sp);
1321                     block = block_sp.get();
1322                 }
1323                 DWARFRangeList ranges;
1324                 const char *name = NULL;
1325                 const char *mangled_name = NULL;
1326 
1327                 int decl_file = 0;
1328                 int decl_line = 0;
1329                 int decl_column = 0;
1330                 int call_file = 0;
1331                 int call_line = 0;
1332                 int call_column = 0;
1333                 if (die.GetDIENamesAndRanges (name,
1334                                               mangled_name,
1335                                               ranges,
1336                                               decl_file, decl_line, decl_column,
1337                                               call_file, call_line, call_column, nullptr))
1338                 {
1339                     if (tag == DW_TAG_subprogram)
1340                     {
1341                         assert (subprogram_low_pc == LLDB_INVALID_ADDRESS);
1342                         subprogram_low_pc = ranges.GetMinRangeBase(0);
1343                     }
1344                     else if (tag == DW_TAG_inlined_subroutine)
1345                     {
1346                         // We get called here for inlined subroutines in two ways.
1347                         // The first time is when we are making the Function object
1348                         // for this inlined concrete instance.  Since we're creating a top level block at
1349                         // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we need to
1350                         // adjust the containing address.
1351                         // The second time is when we are parsing the blocks inside the function that contains
1352                         // the inlined concrete instance.  Since these will be blocks inside the containing "real"
1353                         // function the offset will be for that function.
1354                         if (subprogram_low_pc == LLDB_INVALID_ADDRESS)
1355                         {
1356                             subprogram_low_pc = ranges.GetMinRangeBase(0);
1357                         }
1358                     }
1359 
1360                     const size_t num_ranges = ranges.GetSize();
1361                     for (size_t i = 0; i<num_ranges; ++i)
1362                     {
1363                         const DWARFRangeList::Entry &range = ranges.GetEntryRef (i);
1364                         const addr_t range_base = range.GetRangeBase();
1365                         if (range_base >= subprogram_low_pc)
1366                             block->AddRange(Block::Range (range_base - subprogram_low_pc, range.GetByteSize()));
1367                         else
1368                         {
1369                             GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": adding range [0x%" PRIx64 "-0x%" PRIx64 ") which has a base that is less than the function's low PC 0x%" PRIx64 ". Please file a bug and attach the file at the start of this error message",
1370                                                                        block->GetID(),
1371                                                                        range_base,
1372                                                                        range.GetRangeEnd(),
1373                                                                        subprogram_low_pc);
1374                         }
1375                     }
1376                     block->FinalizeRanges ();
1377 
1378                     if (tag != DW_TAG_subprogram && (name != NULL || mangled_name != NULL))
1379                     {
1380                         std::unique_ptr<Declaration> decl_ap;
1381                         if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1382                             decl_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1383                                                           decl_line, decl_column));
1384 
1385                         std::unique_ptr<Declaration> call_ap;
1386                         if (call_file != 0 || call_line != 0 || call_column != 0)
1387                             call_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1388                                                           call_line, call_column));
1389 
1390                         block->SetInlinedFunctionInfo (name, mangled_name, decl_ap.get(), call_ap.get());
1391                     }
1392 
1393                     ++blocks_added;
1394 
1395                     if (die.HasChildren())
1396                     {
1397                         blocks_added += ParseFunctionBlocks (sc,
1398                                                              block,
1399                                                              die.GetFirstChild(),
1400                                                              subprogram_low_pc,
1401                                                              depth + 1);
1402                     }
1403                 }
1404             }
1405             break;
1406         default:
1407             break;
1408         }
1409 
1410         // Only parse siblings of the block if we are not at depth zero. A depth
1411         // of zero indicates we are currently parsing the top level
1412         // DW_TAG_subprogram DIE
1413 
1414         if (depth == 0)
1415             die.Clear();
1416         else
1417             die = die.GetSibling();
1418     }
1419     return blocks_added;
1420 }
1421 
1422 bool
1423 SymbolFileDWARF::ClassOrStructIsVirtual (const DWARFDIE &parent_die)
1424 {
1425     if (parent_die)
1426     {
1427         for (DWARFDIE die = parent_die.GetFirstChild(); die; die = die.GetSibling())
1428         {
1429             dw_tag_t tag = die.Tag();
1430             bool check_virtuality = false;
1431             switch (tag)
1432             {
1433                 case DW_TAG_inheritance:
1434                 case DW_TAG_subprogram:
1435                     check_virtuality = true;
1436                     break;
1437                 default:
1438                     break;
1439             }
1440             if (check_virtuality)
1441             {
1442                 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1443                     return true;
1444             }
1445         }
1446     }
1447     return false;
1448 }
1449 
1450 void
1451 SymbolFileDWARF::ParseDeclsForContext (CompilerDeclContext decl_ctx)
1452 {
1453     TypeSystem *type_system = decl_ctx.GetTypeSystem();
1454     DWARFASTParser *ast_parser = type_system->GetDWARFParser();
1455     std::vector<DWARFDIE> decl_ctx_die_list = ast_parser->GetDIEForDeclContext(decl_ctx);
1456 
1457     for (DWARFDIE decl_ctx_die : decl_ctx_die_list)
1458         for (DWARFDIE decl = decl_ctx_die.GetFirstChild(); decl; decl = decl.GetSibling())
1459             ast_parser->GetDeclForUIDFromDWARF(decl);
1460 }
1461 
1462 SymbolFileDWARF *
1463 SymbolFileDWARF::GetDWARFForUID (lldb::user_id_t uid)
1464 {
1465     // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API
1466     // we must make sure we use the correct DWARF file when resolving things.
1467     // On MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1468     // SymbolFileDWARF classes, one for each .o file. We can often end up
1469     // with references to other DWARF objects and we must be ready to receive
1470     // a "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1471     // instance.
1472     SymbolFileDWARFDebugMap *debug_map = GetDebugMapSymfile();
1473     if (debug_map)
1474         return debug_map->GetSymbolFileByOSOIndex(debug_map->GetOSOIndexFromUserID(uid));
1475     return this;
1476 }
1477 
1478 DWARFDIE
1479 SymbolFileDWARF::GetDIEFromUID (lldb::user_id_t uid)
1480 {
1481     // Anytime we get a "lldb::user_id_t" from an lldb_private::SymbolFile API
1482     // we must make sure we use the correct DWARF file when resolving things.
1483     // On MacOSX, when using SymbolFileDWARFDebugMap, we will use multiple
1484     // SymbolFileDWARF classes, one for each .o file. We can often end up
1485     // with references to other DWARF objects and we must be ready to receive
1486     // a "lldb::user_id_t" that specifies a DIE from another SymbolFileDWARF
1487     // instance.
1488     SymbolFileDWARF *dwarf = GetDWARFForUID(uid);
1489     if (dwarf)
1490         return dwarf->GetDIE(DIERef(uid, dwarf));
1491     return DWARFDIE();
1492 }
1493 
1494 CompilerDecl
1495 SymbolFileDWARF::GetDeclForUID (lldb::user_id_t type_uid)
1496 {
1497     // Anytime we have a lldb::user_id_t, we must get the DIE by
1498     // calling SymbolFileDWARF::GetDIEFromUID(). See comments inside
1499     // the SymbolFileDWARF::GetDIEFromUID() for details.
1500     DWARFDIE die = GetDIEFromUID(type_uid);
1501     if (die)
1502         return die.GetDecl();
1503     return CompilerDecl();
1504 }
1505 
1506 CompilerDeclContext
1507 SymbolFileDWARF::GetDeclContextForUID (lldb::user_id_t type_uid)
1508 {
1509     // Anytime we have a lldb::user_id_t, we must get the DIE by
1510     // calling SymbolFileDWARF::GetDIEFromUID(). See comments inside
1511     // the SymbolFileDWARF::GetDIEFromUID() for details.
1512     DWARFDIE die = GetDIEFromUID(type_uid);
1513     if (die)
1514         return die.GetDeclContext();
1515     return CompilerDeclContext();
1516 }
1517 
1518 CompilerDeclContext
1519 SymbolFileDWARF::GetDeclContextContainingUID (lldb::user_id_t type_uid)
1520 {
1521     // Anytime we have a lldb::user_id_t, we must get the DIE by
1522     // calling SymbolFileDWARF::GetDIEFromUID(). See comments inside
1523     // the SymbolFileDWARF::GetDIEFromUID() for details.
1524     DWARFDIE die = GetDIEFromUID(type_uid);
1525     if (die)
1526         return die.GetContainingDeclContext();
1527     return CompilerDeclContext();
1528 }
1529 
1530 
1531 Type*
1532 SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
1533 {
1534     // Anytime we have a lldb::user_id_t, we must get the DIE by
1535     // calling SymbolFileDWARF::GetDIEFromUID(). See comments inside
1536     // the SymbolFileDWARF::GetDIEFromUID() for details.
1537     DWARFDIE type_die = GetDIEFromUID(type_uid);
1538     if (type_die)
1539         return type_die.ResolveType();
1540     else
1541         return nullptr;
1542 }
1543 
1544 Type*
1545 SymbolFileDWARF::ResolveTypeUID (const DIERef &die_ref)
1546 {
1547     return ResolveType (GetDIE(die_ref), true);
1548 }
1549 
1550 Type*
1551 SymbolFileDWARF::ResolveTypeUID (const DWARFDIE &die, bool assert_not_being_parsed)
1552 {
1553     if (die)
1554     {
1555         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1556         if (log)
1557             GetObjectFile()->GetModule()->LogMessage (log,
1558                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1559                                                       die.GetOffset(),
1560                                                       die.GetTagAsCString(),
1561                                                       die.GetName());
1562 
1563         // We might be coming in in the middle of a type tree (a class
1564         // withing a class, an enum within a class), so parse any needed
1565         // parent DIEs before we get to this one...
1566         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE (die);
1567         if (decl_ctx_die)
1568         {
1569             if (log)
1570             {
1571                 switch (decl_ctx_die.Tag())
1572                 {
1573                     case DW_TAG_structure_type:
1574                     case DW_TAG_union_type:
1575                     case DW_TAG_class_type:
1576                     {
1577                         // Get the type, which could be a forward declaration
1578                         if (log)
1579                             GetObjectFile()->GetModule()->LogMessage (log,
1580                                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
1581                                                                       die.GetOffset(),
1582                                                                       die.GetTagAsCString(),
1583                                                                       die.GetName(),
1584                                                                       decl_ctx_die.GetOffset());
1585                     }
1586                     break;
1587 
1588                     default:
1589                         break;
1590                 }
1591             }
1592         }
1593         return ResolveType (die);
1594     }
1595     return NULL;
1596 }
1597 
1598 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1599 // SymbolFileDWARF objects to detect if this DWARF file is the one that
1600 // can resolve a compiler_type.
1601 bool
1602 SymbolFileDWARF::HasForwardDeclForClangType (const CompilerType &compiler_type)
1603 {
1604     CompilerType compiler_type_no_qualifiers = ClangUtil::RemoveFastQualifiers(compiler_type);
1605     if (GetForwardDeclClangTypeToDie().count (compiler_type_no_qualifiers.GetOpaqueQualType()))
1606     {
1607         return true;
1608     }
1609     TypeSystem *type_system = compiler_type.GetTypeSystem();
1610 
1611     ClangASTContext *clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(type_system);
1612     if (!clang_type_system)
1613         return false;
1614     DWARFASTParserClang *ast_parser = static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1615     return ast_parser->GetClangASTImporter().CanImport(compiler_type);
1616 }
1617 
1618 
1619 bool
1620 SymbolFileDWARF::CompleteType (CompilerType &compiler_type)
1621 {
1622     std::lock_guard<std::recursive_mutex> guard(GetObjectFile()->GetModule()->GetMutex());
1623 
1624     ClangASTContext *clang_type_system = llvm::dyn_cast_or_null<ClangASTContext>(compiler_type.GetTypeSystem());
1625     if (clang_type_system)
1626     {
1627         DWARFASTParserClang *ast_parser = static_cast<DWARFASTParserClang *>(clang_type_system->GetDWARFParser());
1628         if (ast_parser && ast_parser->GetClangASTImporter().CanImport(compiler_type))
1629             return ast_parser->GetClangASTImporter().CompleteType(compiler_type);
1630     }
1631 
1632     // We have a struct/union/class/enum that needs to be fully resolved.
1633     CompilerType compiler_type_no_qualifiers = ClangUtil::RemoveFastQualifiers(compiler_type);
1634     auto die_it = GetForwardDeclClangTypeToDie().find (compiler_type_no_qualifiers.GetOpaqueQualType());
1635     if (die_it == GetForwardDeclClangTypeToDie().end())
1636     {
1637         // We have already resolved this type...
1638         return true;
1639     }
1640 
1641     DWARFDIE dwarf_die = GetDIE(die_it->getSecond());
1642     if (dwarf_die)
1643     {
1644         // Once we start resolving this type, remove it from the forward declaration
1645         // map in case anyone child members or other types require this type to get resolved.
1646         // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
1647         // are done.
1648         GetForwardDeclClangTypeToDie().erase (die_it);
1649 
1650         Type *type = GetDIEToType().lookup (dwarf_die.GetDIE());
1651 
1652         Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
1653         if (log)
1654             GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
1655                                                                       "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1656                                                                       dwarf_die.GetID(),
1657                                                                       dwarf_die.GetTagAsCString(),
1658                                                                       type->GetName().AsCString());
1659         assert (compiler_type);
1660         DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1661         if (dwarf_ast)
1662             return dwarf_ast->CompleteTypeFromDWARF (dwarf_die, type, compiler_type);
1663     }
1664     return false;
1665 }
1666 
1667 Type*
1668 SymbolFileDWARF::ResolveType (const DWARFDIE &die, bool assert_not_being_parsed, bool resolve_function_context)
1669 {
1670     if (die)
1671     {
1672         Type *type = GetTypeForDIE (die, resolve_function_context).get();
1673 
1674         if (assert_not_being_parsed)
1675         {
1676             if (type != DIE_IS_BEING_PARSED)
1677                 return type;
1678 
1679             GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1680                                                        die.GetOffset(),
1681                                                        die.GetTagAsCString(),
1682                                                        die.GetName());
1683 
1684         }
1685         else
1686             return type;
1687     }
1688     return nullptr;
1689 }
1690 
1691 CompileUnit*
1692 SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
1693 {
1694     // Check if the symbol vendor already knows about this compile unit?
1695     if (dwarf_cu->GetUserData() == NULL)
1696     {
1697         // The symbol vendor doesn't know about this compile unit, we
1698         // need to parse and add it to the symbol vendor object.
1699         return ParseCompileUnit(dwarf_cu, cu_idx).get();
1700     }
1701     return (CompileUnit*)dwarf_cu->GetUserData();
1702 }
1703 
1704 size_t
1705 SymbolFileDWARF::GetObjCMethodDIEOffsets (ConstString class_name, DIEArray &method_die_offsets)
1706 {
1707     method_die_offsets.clear();
1708     if (m_using_apple_tables)
1709     {
1710         if (m_apple_objc_ap.get())
1711             m_apple_objc_ap->FindByName(class_name.GetCString(), method_die_offsets);
1712     }
1713     else
1714     {
1715         if (!m_indexed)
1716             Index ();
1717 
1718         m_objc_class_selectors_index.Find (class_name, method_die_offsets);
1719     }
1720     return method_die_offsets.size();
1721 }
1722 
1723 bool
1724 SymbolFileDWARF::GetFunction (const DWARFDIE &die, SymbolContext& sc)
1725 {
1726     sc.Clear(false);
1727 
1728     if (die)
1729     {
1730         // Check if the symbol vendor already knows about this compile unit?
1731         sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
1732 
1733         sc.function = sc.comp_unit->FindFunctionByUID (die.GetID()).get();
1734         if (sc.function == NULL)
1735             sc.function = ParseCompileUnitFunction(sc, die);
1736 
1737         if (sc.function)
1738         {
1739             sc.module_sp = sc.function->CalculateSymbolContextModule();
1740             return true;
1741         }
1742     }
1743 
1744     return false;
1745 }
1746 
1747 lldb::ModuleSP
1748 SymbolFileDWARF::GetDWOModule (ConstString name)
1749 {
1750     UpdateExternalModuleListIfNeeded();
1751     const auto &pos = m_external_type_modules.find(name);
1752     if (pos != m_external_type_modules.end())
1753         return pos->second;
1754     else
1755         return lldb::ModuleSP();
1756 }
1757 
1758 DWARFDIE
1759 SymbolFileDWARF::GetDIE (const DIERef &die_ref)
1760 {
1761     DWARFDebugInfo * debug_info = DebugInfo();
1762     if (debug_info)
1763         return debug_info->GetDIE(die_ref);
1764     else
1765         return DWARFDIE();
1766 }
1767 
1768 
1769 std::unique_ptr<SymbolFileDWARFDwo>
1770 SymbolFileDWARF::GetDwoSymbolFileForCompileUnit(DWARFCompileUnit &dwarf_cu, const DWARFDebugInfoEntry &cu_die)
1771 {
1772     // If we are using a dSYM file, we never want the standard DWO files since
1773     // the -gmodule support uses the same DWO machanism to specify full debug
1774     // info files for modules.
1775     if (GetDebugMapSymfile())
1776         return nullptr;
1777 
1778     const char *dwo_name = cu_die.GetAttributeValueAsString(this, &dwarf_cu, DW_AT_GNU_dwo_name, nullptr);
1779     if (!dwo_name)
1780         return nullptr;
1781 
1782     FileSpec dwo_file(dwo_name, true);
1783     if (dwo_file.IsRelative())
1784     {
1785         const char *comp_dir = cu_die.GetAttributeValueAsString(this, &dwarf_cu, DW_AT_comp_dir, nullptr);
1786         if (!comp_dir)
1787             return nullptr;
1788 
1789         dwo_file.SetFile(comp_dir, true);
1790         dwo_file.AppendPathComponent(dwo_name);
1791     }
1792 
1793     if (!dwo_file.Exists())
1794         return nullptr;
1795 
1796     const lldb::offset_t file_offset = 0;
1797     DataBufferSP dwo_file_data_sp;
1798     lldb::offset_t dwo_file_data_offset = 0;
1799     ObjectFileSP dwo_obj_file = ObjectFile::FindPlugin(GetObjectFile()->GetModule(), &dwo_file, file_offset,
1800                                                        dwo_file.GetByteSize(), dwo_file_data_sp, dwo_file_data_offset);
1801     if (dwo_obj_file == nullptr)
1802         return nullptr;
1803 
1804     return llvm::make_unique<SymbolFileDWARFDwo>(dwo_obj_file, &dwarf_cu);
1805 }
1806 
1807 void
1808 SymbolFileDWARF::UpdateExternalModuleListIfNeeded()
1809 {
1810     if (m_fetched_external_modules)
1811         return;
1812     m_fetched_external_modules = true;
1813 
1814     DWARFDebugInfo * debug_info = DebugInfo();
1815 
1816     const uint32_t num_compile_units = GetNumCompileUnits();
1817     for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
1818     {
1819         DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
1820 
1821         const DWARFDIE die = dwarf_cu->GetCompileUnitDIEOnly();
1822         if (die && die.HasChildren() == false)
1823         {
1824             const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1825 
1826             if (name)
1827             {
1828                 ConstString const_name(name);
1829                 if (m_external_type_modules.find(const_name) == m_external_type_modules.end())
1830                 {
1831                     ModuleSP module_sp;
1832                     const char *dwo_path = die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1833                     if (dwo_path)
1834                     {
1835                         ModuleSpec dwo_module_spec;
1836                         dwo_module_spec.GetFileSpec().SetFile(dwo_path, false);
1837                         if (dwo_module_spec.GetFileSpec().IsRelative())
1838                         {
1839                             const char *comp_dir = die.GetAttributeValueAsString(DW_AT_comp_dir, nullptr);
1840                             if (comp_dir)
1841                             {
1842                                 dwo_module_spec.GetFileSpec().SetFile(comp_dir, true);
1843                                 dwo_module_spec.GetFileSpec().AppendPathComponent(dwo_path);
1844                             }
1845                         }
1846                         dwo_module_spec.GetArchitecture() = m_obj_file->GetModule()->GetArchitecture();
1847                         //printf ("Loading dwo = '%s'\n", dwo_path);
1848                         Error error = ModuleList::GetSharedModule (dwo_module_spec, module_sp, NULL, NULL, NULL);
1849                         if (!module_sp)
1850                         {
1851                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: unable to locate module needed for external types: %s\nerror: %s\nDebugging will be degraded due to missing types. Rebuilding your project will regenerate the needed module files.",
1852                                                                          die.GetOffset(),
1853                                                                          dwo_module_spec.GetFileSpec().GetPath().c_str(),
1854                                                                          error.AsCString("unknown error"));
1855                         }
1856                     }
1857                     m_external_type_modules[const_name] = module_sp;
1858                 }
1859             }
1860         }
1861     }
1862 }
1863 
1864 SymbolFileDWARF::GlobalVariableMap &
1865 SymbolFileDWARF::GetGlobalAranges()
1866 {
1867     if (!m_global_aranges_ap)
1868     {
1869         m_global_aranges_ap.reset (new GlobalVariableMap());
1870 
1871         ModuleSP module_sp = GetObjectFile()->GetModule();
1872         if (module_sp)
1873         {
1874             const size_t num_cus = module_sp->GetNumCompileUnits();
1875             for (size_t i = 0; i < num_cus; ++i)
1876             {
1877                 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1878                 if (cu_sp)
1879                 {
1880                     VariableListSP globals_sp = cu_sp->GetVariableList(true);
1881                     if (globals_sp)
1882                     {
1883                         const size_t num_globals = globals_sp->GetSize();
1884                         for (size_t g = 0; g < num_globals; ++g)
1885                         {
1886                             VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1887                             if (var_sp && !var_sp->GetLocationIsConstantValueData())
1888                             {
1889                                 const DWARFExpression &location = var_sp->LocationExpression();
1890                                 Value location_result;
1891                                 Error error;
1892                                 if (location.Evaluate(nullptr, nullptr, nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr, location_result, &error))
1893                                 {
1894                                     if (location_result.GetValueType() == Value::eValueTypeFileAddress)
1895                                     {
1896                                         lldb::addr_t file_addr = location_result.GetScalar().ULongLong();
1897                                         lldb::addr_t byte_size = 1;
1898                                         if (var_sp->GetType())
1899                                             byte_size = var_sp->GetType()->GetByteSize();
1900                                         m_global_aranges_ap->Append(GlobalVariableMap::Entry(file_addr, byte_size, var_sp.get()));
1901                                     }
1902                                 }
1903                             }
1904                         }
1905                     }
1906                 }
1907             }
1908         }
1909         m_global_aranges_ap->Sort();
1910     }
1911     return *m_global_aranges_ap;
1912 }
1913 
1914 
1915 uint32_t
1916 SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
1917 {
1918     Timer scoped_timer(__PRETTY_FUNCTION__,
1919                        "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)",
1920                        static_cast<void*>(so_addr.GetSection().get()),
1921                        so_addr.GetOffset(), resolve_scope);
1922     uint32_t resolved = 0;
1923     if (resolve_scope & (   eSymbolContextCompUnit  |
1924                             eSymbolContextFunction  |
1925                             eSymbolContextBlock     |
1926                             eSymbolContextLineEntry |
1927                             eSymbolContextVariable  ))
1928     {
1929         lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1930 
1931         DWARFDebugInfo* debug_info = DebugInfo();
1932         if (debug_info)
1933         {
1934             const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
1935             if (cu_offset == DW_INVALID_OFFSET)
1936             {
1937                 // Global variables are not in the compile unit address ranges. The only way to
1938                 // currently find global variables is to iterate over the .debug_pubnames or the
1939                 // __apple_names table and find all items in there that point to DW_TAG_variable
1940                 // DIEs and then find the address that matches.
1941                 if (resolve_scope & eSymbolContextVariable)
1942                 {
1943                     GlobalVariableMap &map = GetGlobalAranges();
1944                     const GlobalVariableMap::Entry *entry = map.FindEntryThatContains(file_vm_addr);
1945                     if (entry && entry->data)
1946                     {
1947                         Variable *variable = entry->data;
1948                         SymbolContextScope *scc = variable->GetSymbolContextScope();
1949                         if (scc)
1950                         {
1951                             scc->CalculateSymbolContext(&sc);
1952                             sc.variable = variable;
1953                         }
1954                         return sc.GetResolvedMask();
1955                     }
1956                 }
1957             }
1958             else
1959             {
1960                 uint32_t cu_idx = DW_INVALID_INDEX;
1961                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx);
1962                 if (dwarf_cu)
1963                 {
1964                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1965                     if (sc.comp_unit)
1966                     {
1967                         resolved |= eSymbolContextCompUnit;
1968 
1969                         bool force_check_line_table = false;
1970                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
1971                         {
1972                             DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1973                             DWARFDIE block_die;
1974                             if (function_die)
1975                             {
1976                                 sc.function = sc.comp_unit->FindFunctionByUID (function_die.GetID()).get();
1977                                 if (sc.function == NULL)
1978                                     sc.function = ParseCompileUnitFunction(sc, function_die);
1979 
1980                                 if (sc.function && (resolve_scope & eSymbolContextBlock))
1981                                     block_die = function_die.LookupDeepestBlock(file_vm_addr);
1982                             }
1983                             else
1984                             {
1985                                 // We might have had a compile unit that had discontiguous
1986                                 // address ranges where the gaps are symbols that don't have
1987                                 // any debug info. Discontiguous compile unit address ranges
1988                                 // should only happen when there aren't other functions from
1989                                 // other compile units in these gaps. This helps keep the size
1990                                 // of the aranges down.
1991                                 force_check_line_table = true;
1992                             }
1993 
1994                             if (sc.function != NULL)
1995                             {
1996                                 resolved |= eSymbolContextFunction;
1997 
1998                                 if (resolve_scope & eSymbolContextBlock)
1999                                 {
2000                                     Block& block = sc.function->GetBlock (true);
2001 
2002                                     if (block_die)
2003                                         sc.block = block.FindBlockByID (block_die.GetID());
2004                                     else
2005                                         sc.block = block.FindBlockByID (function_die.GetID());
2006                                     if (sc.block)
2007                                         resolved |= eSymbolContextBlock;
2008                                 }
2009                             }
2010                         }
2011 
2012                         if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table)
2013                         {
2014                             LineTable *line_table = sc.comp_unit->GetLineTable();
2015                             if (line_table != NULL)
2016                             {
2017                                 // And address that makes it into this function should be in terms
2018                                 // of this debug file if there is no debug map, or it will be an
2019                                 // address in the .o file which needs to be fixed up to be in terms
2020                                 // of the debug map executable. Either way, calling FixupAddress()
2021                                 // will work for us.
2022                                 Address exe_so_addr (so_addr);
2023                                 if (FixupAddress(exe_so_addr))
2024                                 {
2025                                     if (line_table->FindLineEntryByAddress (exe_so_addr, sc.line_entry))
2026                                     {
2027                                         resolved |= eSymbolContextLineEntry;
2028                                     }
2029                                 }
2030                             }
2031                         }
2032 
2033                         if (force_check_line_table && !(resolved & eSymbolContextLineEntry))
2034                         {
2035                             // We might have had a compile unit that had discontiguous
2036                             // address ranges where the gaps are symbols that don't have
2037                             // any debug info. Discontiguous compile unit address ranges
2038                             // should only happen when there aren't other functions from
2039                             // other compile units in these gaps. This helps keep the size
2040                             // of the aranges down.
2041                             sc.comp_unit = NULL;
2042                             resolved &= ~eSymbolContextCompUnit;
2043                         }
2044                     }
2045                     else
2046                     {
2047                         GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
2048                                                                      cu_offset,
2049                                                                      cu_idx);
2050                     }
2051                 }
2052             }
2053         }
2054     }
2055     return resolved;
2056 }
2057 
2058 
2059 
2060 uint32_t
2061 SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
2062 {
2063     const uint32_t prev_size = sc_list.GetSize();
2064     if (resolve_scope & eSymbolContextCompUnit)
2065     {
2066         DWARFDebugInfo* debug_info = DebugInfo();
2067         if (debug_info)
2068         {
2069             uint32_t cu_idx;
2070             DWARFCompileUnit* dwarf_cu = NULL;
2071 
2072             for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
2073             {
2074                 CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2075                 const bool full_match = (bool)file_spec.GetDirectory();
2076                 bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
2077                 if (check_inlines || file_spec_matches_cu_file_spec)
2078                 {
2079                     SymbolContext sc (m_obj_file->GetModule());
2080                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2081                     if (sc.comp_unit)
2082                     {
2083                         uint32_t file_idx = UINT32_MAX;
2084 
2085                         // If we are looking for inline functions only and we don't
2086                         // find it in the support files, we are done.
2087                         if (check_inlines)
2088                         {
2089                             file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2090                             if (file_idx == UINT32_MAX)
2091                                 continue;
2092                         }
2093 
2094                         if (line != 0)
2095                         {
2096                             LineTable *line_table = sc.comp_unit->GetLineTable();
2097 
2098                             if (line_table != NULL && line != 0)
2099                             {
2100                                 // We will have already looked up the file index if
2101                                 // we are searching for inline entries.
2102                                 if (!check_inlines)
2103                                     file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2104 
2105                                 if (file_idx != UINT32_MAX)
2106                                 {
2107                                     uint32_t found_line;
2108                                     uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
2109                                     found_line = sc.line_entry.line;
2110 
2111                                     while (line_idx != UINT32_MAX)
2112                                     {
2113                                         sc.function = NULL;
2114                                         sc.block = NULL;
2115                                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2116                                         {
2117                                             const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
2118                                             if (file_vm_addr != LLDB_INVALID_ADDRESS)
2119                                             {
2120                                                 DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
2121                                                 DWARFDIE block_die;
2122                                                 if (function_die)
2123                                                 {
2124                                                     sc.function = sc.comp_unit->FindFunctionByUID (function_die.GetID()).get();
2125                                                     if (sc.function == NULL)
2126                                                         sc.function = ParseCompileUnitFunction(sc, function_die);
2127 
2128                                                     if (sc.function && (resolve_scope & eSymbolContextBlock))
2129                                                         block_die = function_die.LookupDeepestBlock(file_vm_addr);
2130                                                 }
2131 
2132                                                 if (sc.function != NULL)
2133                                                 {
2134                                                     Block& block = sc.function->GetBlock (true);
2135 
2136                                                     if (block_die)
2137                                                         sc.block = block.FindBlockByID (block_die.GetID());
2138                                                     else if (function_die)
2139                                                         sc.block = block.FindBlockByID (function_die.GetID());
2140                                                 }
2141                                             }
2142                                         }
2143 
2144                                         sc_list.Append(sc);
2145                                         line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2146                                     }
2147                                 }
2148                             }
2149                             else if (file_spec_matches_cu_file_spec && !check_inlines)
2150                             {
2151                                 // only append the context if we aren't looking for inline call sites
2152                                 // by file and line and if the file spec matches that of the compile unit
2153                                 sc_list.Append(sc);
2154                             }
2155                         }
2156                         else if (file_spec_matches_cu_file_spec && !check_inlines)
2157                         {
2158                             // only append the context if we aren't looking for inline call sites
2159                             // by file and line and if the file spec matches that of the compile unit
2160                             sc_list.Append(sc);
2161                         }
2162 
2163                         if (!check_inlines)
2164                             break;
2165                     }
2166                 }
2167             }
2168         }
2169     }
2170     return sc_list.GetSize() - prev_size;
2171 }
2172 
2173 void
2174 SymbolFileDWARF::Index ()
2175 {
2176     if (m_indexed)
2177         return;
2178     m_indexed = true;
2179     Timer scoped_timer (__PRETTY_FUNCTION__,
2180                         "SymbolFileDWARF::Index (%s)",
2181                         GetObjectFile()->GetFileSpec().GetFilename().AsCString("<Unknown>"));
2182 
2183     DWARFDebugInfo* debug_info = DebugInfo();
2184     if (debug_info)
2185     {
2186         const uint32_t num_compile_units = GetNumCompileUnits();
2187         if (num_compile_units == 0)
2188             return;
2189 
2190         std::vector<NameToDIE> function_basename_index(num_compile_units);
2191         std::vector<NameToDIE> function_fullname_index(num_compile_units);
2192         std::vector<NameToDIE> function_method_index(num_compile_units);
2193         std::vector<NameToDIE> function_selector_index(num_compile_units);
2194         std::vector<NameToDIE> objc_class_selectors_index(num_compile_units);
2195         std::vector<NameToDIE> global_index(num_compile_units);
2196         std::vector<NameToDIE> type_index(num_compile_units);
2197         std::vector<NameToDIE> namespace_index(num_compile_units);
2198 
2199         std::vector<bool> clear_cu_dies(num_compile_units, false);
2200         auto parser_fn = [this,
2201                           debug_info,
2202                           &function_basename_index,
2203                           &function_fullname_index,
2204                           &function_method_index,
2205                           &function_selector_index,
2206                           &objc_class_selectors_index,
2207                           &global_index,
2208                           &type_index,
2209                           &namespace_index](uint32_t cu_idx)
2210         {
2211             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2212             if (dwarf_cu)
2213             {
2214                 dwarf_cu->Index(function_basename_index[cu_idx],
2215                                 function_fullname_index[cu_idx],
2216                                 function_method_index[cu_idx],
2217                                 function_selector_index[cu_idx],
2218                                 objc_class_selectors_index[cu_idx],
2219                                 global_index[cu_idx],
2220                                 type_index[cu_idx],
2221                                 namespace_index[cu_idx]);
2222             }
2223             return cu_idx;
2224         };
2225 
2226         auto extract_fn = [this,
2227                            debug_info,
2228                            num_compile_units](uint32_t cu_idx)
2229         {
2230             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2231             if (dwarf_cu)
2232             {
2233                 // dwarf_cu->ExtractDIEsIfNeeded(false) will return zero if the
2234                 // DIEs for a compile unit have already been parsed.
2235                 return std::make_pair(cu_idx, dwarf_cu->ExtractDIEsIfNeeded(false) > 1);
2236             }
2237             return std::make_pair(cu_idx, false);
2238         };
2239 
2240         // Create a task runner that extracts dies for each DWARF compile unit in a separate thread
2241         TaskRunner<std::pair<uint32_t, bool>> task_runner_extract;
2242         for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2243             task_runner_extract.AddTask(extract_fn, cu_idx);
2244 
2245         //----------------------------------------------------------------------
2246         // First figure out which compile units didn't have their DIEs already
2247         // parsed and remember this.  If no DIEs were parsed prior to this index
2248         // function call, we are going to want to clear the CU dies after we
2249         // are done indexing to make sure we don't pull in all DWARF dies, but
2250         // we need to wait until all compile units have been indexed in case
2251         // a DIE in one compile unit refers to another and the indexes accesses
2252         // those DIEs.
2253         //----------------------------------------------------------------------
2254         while (true)
2255         {
2256             auto f = task_runner_extract.WaitForNextCompletedTask();
2257             if (!f.valid())
2258                 break;
2259             unsigned cu_idx;
2260             bool clear;
2261             std::tie(cu_idx, clear) = f.get();
2262             clear_cu_dies[cu_idx] = clear;
2263         }
2264 
2265         // Now create a task runner that can index each DWARF compile unit in a separate
2266         // thread so we can index quickly.
2267 
2268         TaskRunner<uint32_t> task_runner;
2269         for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2270             task_runner.AddTask(parser_fn, cu_idx);
2271 
2272         while (true)
2273         {
2274             std::future<uint32_t> f = task_runner.WaitForNextCompletedTask();
2275             if (!f.valid())
2276                 break;
2277             uint32_t cu_idx = f.get();
2278 
2279             m_function_basename_index.Append(function_basename_index[cu_idx]);
2280             m_function_fullname_index.Append(function_fullname_index[cu_idx]);
2281             m_function_method_index.Append(function_method_index[cu_idx]);
2282             m_function_selector_index.Append(function_selector_index[cu_idx]);
2283             m_objc_class_selectors_index.Append(objc_class_selectors_index[cu_idx]);
2284             m_global_index.Append(global_index[cu_idx]);
2285             m_type_index.Append(type_index[cu_idx]);
2286             m_namespace_index.Append(namespace_index[cu_idx]);
2287         }
2288 
2289         TaskPool::RunTasks(
2290             [&]() { m_function_basename_index.Finalize(); },
2291             [&]() { m_function_fullname_index.Finalize(); },
2292             [&]() { m_function_method_index.Finalize(); },
2293             [&]() { m_function_selector_index.Finalize(); },
2294             [&]() { m_objc_class_selectors_index.Finalize(); },
2295             [&]() { m_global_index.Finalize(); },
2296             [&]() { m_type_index.Finalize(); },
2297             [&]() { m_namespace_index.Finalize(); });
2298 
2299         //----------------------------------------------------------------------
2300         // Keep memory down by clearing DIEs for any compile units if indexing
2301         // caused us to load the compile unit's DIEs.
2302         //----------------------------------------------------------------------
2303         for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2304         {
2305             if (clear_cu_dies[cu_idx])
2306                 debug_info->GetCompileUnitAtIndex(cu_idx)->ClearDIEs(true);
2307         }
2308 
2309 #if defined (ENABLE_DEBUG_PRINTF)
2310         StreamFile s(stdout, false);
2311         s.Printf ("DWARF index for '%s':",
2312                   GetObjectFile()->GetFileSpec().GetPath().c_str());
2313         s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
2314         s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
2315         s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
2316         s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
2317         s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
2318         s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
2319         s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
2320         s.Printf("\nNamespaces:\n")             m_namespace_index.Dump (&s);
2321 #endif
2322     }
2323 }
2324 
2325 bool
2326 SymbolFileDWARF::DeclContextMatchesThisSymbolFile (const lldb_private::CompilerDeclContext *decl_ctx)
2327 {
2328     if (decl_ctx == nullptr || !decl_ctx->IsValid())
2329     {
2330         // Invalid namespace decl which means we aren't matching only things
2331         // in this symbol file, so return true to indicate it matches this
2332         // symbol file.
2333         return true;
2334     }
2335 
2336     TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
2337     TypeSystem *type_system = GetTypeSystemForLanguage(decl_ctx_type_system->GetMinimumLanguage(nullptr));
2338     if (decl_ctx_type_system == type_system)
2339         return true;    // The type systems match, return true
2340 
2341     // The namespace AST was valid, and it does not match...
2342     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2343 
2344     if (log)
2345         GetObjectFile()->GetModule()->LogMessage(log, "Valid namespace does not match symbol file");
2346 
2347     return false;
2348 }
2349 
2350 uint32_t
2351 SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, VariableList& variables)
2352 {
2353     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2354 
2355     if (log)
2356         GetObjectFile()->GetModule()->LogMessage (log,
2357                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", parent_decl_ctx=%p, append=%u, max_matches=%u, variables)",
2358                                                   name.GetCString(),
2359                                                   static_cast<const void*>(parent_decl_ctx),
2360                                                   append, max_matches);
2361 
2362     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2363         return 0;
2364 
2365     DWARFDebugInfo* info = DebugInfo();
2366     if (info == NULL)
2367         return 0;
2368 
2369     // If we aren't appending the results to this list, then clear the list
2370     if (!append)
2371         variables.Clear();
2372 
2373     // Remember how many variables are in the list before we search in case
2374     // we are appending the results to a variable list.
2375     const uint32_t original_size = variables.GetSize();
2376 
2377     DIEArray die_offsets;
2378 
2379     if (m_using_apple_tables)
2380     {
2381         if (m_apple_names_ap.get())
2382         {
2383             const char *name_cstr = name.GetCString();
2384             llvm::StringRef basename;
2385             llvm::StringRef context;
2386 
2387             if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, basename))
2388                 basename = name_cstr;
2389 
2390             m_apple_names_ap->FindByName (basename.data(), die_offsets);
2391         }
2392     }
2393     else
2394     {
2395         // Index the DWARF if we haven't already
2396         if (!m_indexed)
2397             Index ();
2398 
2399         m_global_index.Find (name, die_offsets);
2400     }
2401 
2402     const size_t num_die_matches = die_offsets.size();
2403     if (num_die_matches)
2404     {
2405         SymbolContext sc;
2406         sc.module_sp = m_obj_file->GetModule();
2407         assert (sc.module_sp);
2408 
2409         bool done = false;
2410         for (size_t i=0; i<num_die_matches && !done; ++i)
2411         {
2412             const DIERef& die_ref = die_offsets[i];
2413             DWARFDIE die = GetDIE (die_ref);
2414 
2415             if (die)
2416             {
2417                 switch (die.Tag())
2418                 {
2419                     default:
2420                     case DW_TAG_subprogram:
2421                     case DW_TAG_inlined_subroutine:
2422                     case DW_TAG_try_block:
2423                     case DW_TAG_catch_block:
2424                         break;
2425 
2426                     case DW_TAG_variable:
2427                         {
2428                             sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2429 
2430                             if (parent_decl_ctx)
2431                             {
2432                                 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2433                                 if (dwarf_ast)
2434                                 {
2435                                     CompilerDeclContext actual_parent_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF (die);
2436                                     if (!actual_parent_decl_ctx || actual_parent_decl_ctx != *parent_decl_ctx)
2437                                         continue;
2438                                 }
2439                             }
2440 
2441                             ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2442 
2443                             if (variables.GetSize() - original_size >= max_matches)
2444                                 done = true;
2445                         }
2446                         break;
2447                 }
2448             }
2449             else
2450             {
2451                 if (m_using_apple_tables)
2452                 {
2453                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
2454                                                                                die_ref.die_offset, name.GetCString());
2455                 }
2456             }
2457         }
2458     }
2459 
2460     // Return the number of variable that were appended to the list
2461     const uint32_t num_matches = variables.GetSize() - original_size;
2462     if (log && num_matches > 0)
2463     {
2464         GetObjectFile()->GetModule()->LogMessage (log,
2465                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", parent_decl_ctx=%p, append=%u, max_matches=%u, variables) => %u",
2466                                                   name.GetCString(),
2467                                                   static_cast<const void*>(parent_decl_ctx),
2468                                                   append, max_matches,
2469                                                   num_matches);
2470     }
2471     return num_matches;
2472 }
2473 
2474 uint32_t
2475 SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
2476 {
2477     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2478 
2479     if (log)
2480     {
2481         GetObjectFile()->GetModule()->LogMessage (log,
2482                                                   "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
2483                                                   regex.GetText(), append,
2484                                                   max_matches);
2485     }
2486 
2487     DWARFDebugInfo* info = DebugInfo();
2488     if (info == NULL)
2489         return 0;
2490 
2491     // If we aren't appending the results to this list, then clear the list
2492     if (!append)
2493         variables.Clear();
2494 
2495     // Remember how many variables are in the list before we search in case
2496     // we are appending the results to a variable list.
2497     const uint32_t original_size = variables.GetSize();
2498 
2499     DIEArray die_offsets;
2500 
2501     if (m_using_apple_tables)
2502     {
2503         if (m_apple_names_ap.get())
2504         {
2505             DWARFMappedHash::DIEInfoArray hash_data_array;
2506             if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
2507                 DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
2508         }
2509     }
2510     else
2511     {
2512         // Index the DWARF if we haven't already
2513         if (!m_indexed)
2514             Index ();
2515 
2516         m_global_index.Find (regex, die_offsets);
2517     }
2518 
2519     SymbolContext sc;
2520     sc.module_sp = m_obj_file->GetModule();
2521     assert (sc.module_sp);
2522 
2523     const size_t num_matches = die_offsets.size();
2524     if (num_matches)
2525     {
2526         for (size_t i=0; i<num_matches; ++i)
2527         {
2528             const DIERef& die_ref = die_offsets[i];
2529             DWARFDIE die = GetDIE (die_ref);
2530 
2531             if (die)
2532             {
2533                 sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2534 
2535                 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2536 
2537                 if (variables.GetSize() - original_size >= max_matches)
2538                     break;
2539             }
2540             else
2541             {
2542                 if (m_using_apple_tables)
2543                 {
2544                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
2545                                                                                die_ref.die_offset, regex.GetText());
2546                 }
2547             }
2548         }
2549     }
2550 
2551     // Return the number of variable that were appended to the list
2552     return variables.GetSize() - original_size;
2553 }
2554 
2555 
2556 bool
2557 SymbolFileDWARF::ResolveFunction (const DIERef& die_ref,
2558                                   bool include_inlines,
2559                                   SymbolContextList& sc_list)
2560 {
2561     DWARFDIE die = DebugInfo()->GetDIE (die_ref);
2562     return ResolveFunction (die, include_inlines, sc_list);
2563 }
2564 
2565 
2566 bool
2567 SymbolFileDWARF::ResolveFunction (const DWARFDIE &orig_die,
2568                                   bool include_inlines,
2569                                   SymbolContextList& sc_list)
2570 {
2571     SymbolContext sc;
2572 
2573     if (!orig_die)
2574         return false;
2575 
2576     // If we were passed a die that is not a function, just return false...
2577     if (!(orig_die.Tag() == DW_TAG_subprogram || (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2578         return false;
2579 
2580     DWARFDIE die = orig_die;
2581     DWARFDIE inlined_die;
2582     if (die.Tag() == DW_TAG_inlined_subroutine)
2583     {
2584         inlined_die = die;
2585 
2586         while (1)
2587         {
2588             die = die.GetParent();
2589 
2590             if (die)
2591             {
2592                 if (die.Tag() == DW_TAG_subprogram)
2593                     break;
2594             }
2595             else
2596                 break;
2597         }
2598     }
2599     assert (die && die.Tag() == DW_TAG_subprogram);
2600     if (GetFunction (die, sc))
2601     {
2602         Address addr;
2603         // Parse all blocks if needed
2604         if (inlined_die)
2605         {
2606             Block &function_block = sc.function->GetBlock (true);
2607             sc.block = function_block.FindBlockByID (inlined_die.GetID());
2608             if (sc.block == NULL)
2609                 sc.block = function_block.FindBlockByID (inlined_die.GetOffset());
2610             if (sc.block == NULL || sc.block->GetStartAddress (addr) == false)
2611                 addr.Clear();
2612         }
2613         else
2614         {
2615             sc.block = NULL;
2616             addr = sc.function->GetAddressRange().GetBaseAddress();
2617         }
2618 
2619         if (addr.IsValid())
2620         {
2621             sc_list.Append(sc);
2622             return true;
2623         }
2624     }
2625 
2626     return false;
2627 }
2628 
2629 void
2630 SymbolFileDWARF::FindFunctions (const ConstString &name,
2631                                 const NameToDIE &name_to_die,
2632                                 bool include_inlines,
2633                                 SymbolContextList& sc_list)
2634 {
2635     DIEArray die_offsets;
2636     if (name_to_die.Find (name, die_offsets))
2637     {
2638         ParseFunctions (die_offsets, include_inlines, sc_list);
2639     }
2640 }
2641 
2642 
2643 void
2644 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
2645                                 const NameToDIE &name_to_die,
2646                                 bool include_inlines,
2647                                 SymbolContextList& sc_list)
2648 {
2649     DIEArray die_offsets;
2650     if (name_to_die.Find (regex, die_offsets))
2651     {
2652         ParseFunctions (die_offsets, include_inlines, sc_list);
2653     }
2654 }
2655 
2656 
2657 void
2658 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
2659                                 const DWARFMappedHash::MemoryTable &memory_table,
2660                                 bool include_inlines,
2661                                 SymbolContextList& sc_list)
2662 {
2663     DIEArray die_offsets;
2664     DWARFMappedHash::DIEInfoArray hash_data_array;
2665     if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
2666     {
2667         DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
2668         ParseFunctions (die_offsets, include_inlines, sc_list);
2669     }
2670 }
2671 
2672 void
2673 SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
2674                                  bool include_inlines,
2675                                  SymbolContextList& sc_list)
2676 {
2677     const size_t num_matches = die_offsets.size();
2678     if (num_matches)
2679     {
2680         for (size_t i=0; i<num_matches; ++i)
2681             ResolveFunction (die_offsets[i], include_inlines, sc_list);
2682     }
2683 }
2684 
2685 bool
2686 SymbolFileDWARF::DIEInDeclContext (const CompilerDeclContext *decl_ctx,
2687                                    const DWARFDIE &die)
2688 {
2689     // If we have no parent decl context to match this DIE matches, and if the parent
2690     // decl context isn't valid, we aren't trying to look for any particular decl
2691     // context so any die matches.
2692     if (decl_ctx == nullptr || !decl_ctx->IsValid())
2693         return true;
2694 
2695     if (die)
2696     {
2697         DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2698         if (dwarf_ast)
2699         {
2700             CompilerDeclContext actual_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF (die);
2701             if (actual_decl_ctx)
2702                 return actual_decl_ctx == *decl_ctx;
2703         }
2704     }
2705     return false;
2706 }
2707 
2708 uint32_t
2709 SymbolFileDWARF::FindFunctions (const ConstString &name,
2710                                 const CompilerDeclContext *parent_decl_ctx,
2711                                 uint32_t name_type_mask,
2712                                 bool include_inlines,
2713                                 bool append,
2714                                 SymbolContextList& sc_list)
2715 {
2716     Timer scoped_timer (__PRETTY_FUNCTION__,
2717                         "SymbolFileDWARF::FindFunctions (name = '%s')",
2718                         name.AsCString());
2719 
2720     // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup()
2721     assert ((name_type_mask & eFunctionNameTypeAuto) == 0);
2722 
2723     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2724 
2725     if (log)
2726     {
2727         GetObjectFile()->GetModule()->LogMessage (log,
2728                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
2729                                                   name.GetCString(),
2730                                                   name_type_mask,
2731                                                   append);
2732     }
2733 
2734     // If we aren't appending the results to this list, then clear the list
2735     if (!append)
2736         sc_list.Clear();
2737 
2738     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2739         return 0;
2740 
2741     // If name is empty then we won't find anything.
2742     if (name.IsEmpty())
2743         return 0;
2744 
2745     // Remember how many sc_list are in the list before we search in case
2746     // we are appending the results to a variable list.
2747 
2748     const char *name_cstr = name.GetCString();
2749 
2750     const uint32_t original_size = sc_list.GetSize();
2751 
2752     DWARFDebugInfo* info = DebugInfo();
2753     if (info == NULL)
2754         return 0;
2755 
2756     std::set<const DWARFDebugInfoEntry *> resolved_dies;
2757     if (m_using_apple_tables)
2758     {
2759         if (m_apple_names_ap.get())
2760         {
2761 
2762             DIEArray die_offsets;
2763 
2764             uint32_t num_matches = 0;
2765 
2766             if (name_type_mask & eFunctionNameTypeFull)
2767             {
2768                 // If they asked for the full name, match what they typed.  At some point we may
2769                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
2770                 // dies that we find by exact match.
2771                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2772                 for (uint32_t i = 0; i < num_matches; i++)
2773                 {
2774                     const DIERef& die_ref = die_offsets[i];
2775                     DWARFDIE die = info->GetDIE (die_ref);
2776                     if (die)
2777                     {
2778                         if (!DIEInDeclContext(parent_decl_ctx, die))
2779                             continue; // The containing decl contexts don't match
2780 
2781                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2782                         {
2783                             if (ResolveFunction (die, include_inlines, sc_list))
2784                                 resolved_dies.insert(die.GetDIE());
2785                         }
2786                     }
2787                     else
2788                     {
2789                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2790                                                                                    die_ref.die_offset, name_cstr);
2791                     }
2792                 }
2793             }
2794 
2795             if (name_type_mask & eFunctionNameTypeSelector)
2796             {
2797                 if (parent_decl_ctx && parent_decl_ctx->IsValid())
2798                     return 0; // no selectors in namespaces
2799 
2800                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2801                 // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
2802                 // and if it is an ObjC method name, we're good.
2803 
2804                 for (uint32_t i = 0; i < num_matches; i++)
2805                 {
2806                     const DIERef& die_ref = die_offsets[i];
2807                     DWARFDIE die = info->GetDIE (die_ref);
2808                     if (die)
2809                     {
2810                         const char *die_name = die.GetName();
2811                         if (ObjCLanguage::IsPossibleObjCMethodName(die_name))
2812                         {
2813                             if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2814                             {
2815                                 if (ResolveFunction (die, include_inlines, sc_list))
2816                                     resolved_dies.insert(die.GetDIE());
2817                             }
2818                         }
2819                     }
2820                     else
2821                     {
2822                         GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2823                                                                    die_ref.die_offset, name_cstr);
2824                     }
2825                 }
2826                 die_offsets.clear();
2827             }
2828 
2829             if (((name_type_mask & eFunctionNameTypeMethod) && !parent_decl_ctx) || name_type_mask & eFunctionNameTypeBase)
2830             {
2831                 // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
2832                 // extract the base name, look that up, and if there is any other information in the name we were
2833                 // passed in we have to post-filter based on that.
2834 
2835                 // FIXME: Arrange the logic above so that we don't calculate the base name twice:
2836                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2837 
2838                 for (uint32_t i = 0; i < num_matches; i++)
2839                 {
2840                     const DIERef& die_ref = die_offsets[i];
2841                     DWARFDIE die = info->GetDIE (die_ref);
2842                     if (die)
2843                     {
2844                         if (!DIEInDeclContext(parent_decl_ctx, die))
2845                             continue; // The containing decl contexts don't match
2846 
2847 
2848                         // If we get to here, the die is good, and we should add it:
2849                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end() && ResolveFunction (die, include_inlines, sc_list))
2850                         {
2851                             bool keep_die = true;
2852                             if ((name_type_mask & (eFunctionNameTypeBase|eFunctionNameTypeMethod)) != (eFunctionNameTypeBase|eFunctionNameTypeMethod))
2853                             {
2854                                 // We are looking for either basenames or methods, so we need to
2855                                 // trim out the ones we won't want by looking at the type
2856                                 SymbolContext sc;
2857                                 if (sc_list.GetLastContext(sc))
2858                                 {
2859                                     if (sc.block)
2860                                     {
2861                                         // We have an inlined function
2862                                     }
2863                                     else if (sc.function)
2864                                     {
2865                                         Type *type = sc.function->GetType();
2866 
2867                                         if (type)
2868                                         {
2869                                             CompilerDeclContext decl_ctx = GetDeclContextContainingUID (type->GetID());
2870                                             if (decl_ctx.IsStructUnionOrClass())
2871                                             {
2872                                                 if (name_type_mask & eFunctionNameTypeBase)
2873                                                 {
2874                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
2875                                                     keep_die = false;
2876                                                 }
2877                                             }
2878                                             else
2879                                             {
2880                                                 if (name_type_mask & eFunctionNameTypeMethod)
2881                                                 {
2882                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
2883                                                     keep_die = false;
2884                                                 }
2885                                             }
2886                                         }
2887                                         else
2888                                         {
2889                                             GetObjectFile()->GetModule()->ReportWarning ("function at die offset 0x%8.8x had no function type",
2890                                                                                          die_ref.die_offset);
2891                                         }
2892                                     }
2893                                 }
2894                             }
2895                             if (keep_die)
2896                                 resolved_dies.insert(die.GetDIE());
2897                         }
2898                     }
2899                     else
2900                     {
2901                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2902                                                                                    die_ref.die_offset, name_cstr);
2903                     }
2904                 }
2905                 die_offsets.clear();
2906             }
2907         }
2908     }
2909     else
2910     {
2911 
2912         // Index the DWARF if we haven't already
2913         if (!m_indexed)
2914             Index ();
2915 
2916         if (name_type_mask & eFunctionNameTypeFull)
2917         {
2918             FindFunctions (name, m_function_fullname_index, include_inlines, sc_list);
2919 
2920             // FIXME Temporary workaround for global/anonymous namespace
2921             // functions debugging FreeBSD and Linux binaries.
2922             // If we didn't find any functions in the global namespace try
2923             // looking in the basename index but ignore any returned
2924             // functions that have a namespace but keep functions which
2925             // have an anonymous namespace
2926             // TODO: The arch in the object file isn't correct for MSVC
2927             // binaries on windows, we should find a way to make it
2928             // correct and handle those symbols as well.
2929             if (sc_list.GetSize() == original_size)
2930             {
2931                 ArchSpec arch;
2932                 if (!parent_decl_ctx &&
2933                     GetObjectFile()->GetArchitecture(arch) &&
2934                     (arch.GetTriple().isOSFreeBSD() || arch.GetTriple().isOSLinux() ||
2935                      arch.GetMachine() == llvm::Triple::hexagon))
2936                 {
2937                     SymbolContextList temp_sc_list;
2938                     FindFunctions (name, m_function_basename_index, include_inlines, temp_sc_list);
2939                     SymbolContext sc;
2940                     for (uint32_t i = 0; i < temp_sc_list.GetSize(); i++)
2941                     {
2942                         if (temp_sc_list.GetContextAtIndex(i, sc))
2943                         {
2944                             ConstString mangled_name = sc.GetFunctionName(Mangled::ePreferMangled);
2945                             ConstString demangled_name = sc.GetFunctionName(Mangled::ePreferDemangled);
2946                             // Mangled names on Linux and FreeBSD are of the form:
2947                             // _ZN18function_namespace13function_nameEv.
2948                             if (strncmp(mangled_name.GetCString(), "_ZN", 3) ||
2949                                 !strncmp(demangled_name.GetCString(), "(anonymous namespace)", 21))
2950                             {
2951                                 sc_list.Append(sc);
2952                             }
2953                         }
2954                     }
2955                 }
2956             }
2957         }
2958         DIEArray die_offsets;
2959         if (name_type_mask & eFunctionNameTypeBase)
2960         {
2961             uint32_t num_base = m_function_basename_index.Find(name, die_offsets);
2962             for (uint32_t i = 0; i < num_base; i++)
2963             {
2964                 DWARFDIE die = info->GetDIE (die_offsets[i]);
2965                 if (die)
2966                 {
2967                     if (!DIEInDeclContext(parent_decl_ctx, die))
2968                         continue; // The containing decl contexts don't match
2969 
2970                     // If we get to here, the die is good, and we should add it:
2971                     if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2972                     {
2973                         if (ResolveFunction (die, include_inlines, sc_list))
2974                             resolved_dies.insert(die.GetDIE());
2975                     }
2976                 }
2977             }
2978             die_offsets.clear();
2979         }
2980 
2981         if (name_type_mask & eFunctionNameTypeMethod)
2982         {
2983             if (parent_decl_ctx && parent_decl_ctx->IsValid())
2984                 return 0; // no methods in namespaces
2985 
2986             uint32_t num_base = m_function_method_index.Find(name, die_offsets);
2987             {
2988                 for (uint32_t i = 0; i < num_base; i++)
2989                 {
2990                     DWARFDIE die = info->GetDIE (die_offsets[i]);
2991                     if (die)
2992                     {
2993                         // If we get to here, the die is good, and we should add it:
2994                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2995                         {
2996                             if (ResolveFunction (die, include_inlines, sc_list))
2997                                 resolved_dies.insert(die.GetDIE());
2998                         }
2999                     }
3000                 }
3001             }
3002             die_offsets.clear();
3003         }
3004 
3005         if ((name_type_mask & eFunctionNameTypeSelector) && (!parent_decl_ctx || !parent_decl_ctx->IsValid()))
3006         {
3007             FindFunctions (name, m_function_selector_index, include_inlines, sc_list);
3008         }
3009 
3010     }
3011 
3012     // Return the number of variable that were appended to the list
3013     const uint32_t num_matches = sc_list.GetSize() - original_size;
3014 
3015     if (log && num_matches > 0)
3016     {
3017         GetObjectFile()->GetModule()->LogMessage (log,
3018                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => %u",
3019                                                   name.GetCString(),
3020                                                   name_type_mask,
3021                                                   include_inlines,
3022                                                   append,
3023                                                   num_matches);
3024     }
3025     return num_matches;
3026 }
3027 
3028 uint32_t
3029 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
3030 {
3031     Timer scoped_timer (__PRETTY_FUNCTION__,
3032                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
3033                         regex.GetText());
3034 
3035     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3036 
3037     if (log)
3038     {
3039         GetObjectFile()->GetModule()->LogMessage (log,
3040                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
3041                                                   regex.GetText(),
3042                                                   append);
3043     }
3044 
3045 
3046     // If we aren't appending the results to this list, then clear the list
3047     if (!append)
3048         sc_list.Clear();
3049 
3050     // Remember how many sc_list are in the list before we search in case
3051     // we are appending the results to a variable list.
3052     uint32_t original_size = sc_list.GetSize();
3053 
3054     if (m_using_apple_tables)
3055     {
3056         if (m_apple_names_ap.get())
3057             FindFunctions (regex, *m_apple_names_ap, include_inlines, sc_list);
3058     }
3059     else
3060     {
3061         // Index the DWARF if we haven't already
3062         if (!m_indexed)
3063             Index ();
3064 
3065         FindFunctions (regex, m_function_basename_index, include_inlines, sc_list);
3066 
3067         FindFunctions (regex, m_function_fullname_index, include_inlines, sc_list);
3068     }
3069 
3070     // Return the number of variable that were appended to the list
3071     return sc_list.GetSize() - original_size;
3072 }
3073 
3074 void
3075 SymbolFileDWARF::GetMangledNamesForFunction (const std::string &scope_qualified_name,
3076                                              std::vector<ConstString> &mangled_names)
3077 {
3078     DWARFDebugInfo* info = DebugInfo();
3079     uint32_t num_comp_units = 0;
3080     if (info)
3081         num_comp_units = info->GetNumCompileUnits();
3082 
3083     for (uint32_t i = 0; i < num_comp_units; i++)
3084     {
3085         DWARFCompileUnit *cu = info->GetCompileUnitAtIndex(i);
3086         if (cu == nullptr)
3087             continue;
3088 
3089         SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
3090         if (dwo)
3091             dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
3092     }
3093 
3094     NameToOffsetMap::iterator iter = m_function_scope_qualified_name_map.find(scope_qualified_name);
3095     if (iter == m_function_scope_qualified_name_map.end())
3096         return;
3097 
3098     DIERefSetSP set_sp = (*iter).second;
3099     std::set<DIERef>::iterator set_iter;
3100     for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++)
3101     {
3102         DWARFDIE die = DebugInfo()->GetDIE (*set_iter);
3103         mangled_names.push_back(ConstString(die.GetMangledName()));
3104     }
3105 }
3106 
3107 
3108 uint32_t
3109 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3110                             const ConstString &name,
3111                             const CompilerDeclContext *parent_decl_ctx,
3112                             bool append,
3113                             uint32_t max_matches,
3114                             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
3115                             TypeMap& types)
3116 {
3117     // If we aren't appending the results to this list, then clear the list
3118     if (!append)
3119         types.Clear();
3120 
3121     // Make sure we haven't already searched this SymbolFile before...
3122     if (searched_symbol_files.count(this))
3123         return 0;
3124     else
3125         searched_symbol_files.insert(this);
3126 
3127     DWARFDebugInfo* info = DebugInfo();
3128     if (info == NULL)
3129         return 0;
3130 
3131     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3132 
3133     if (log)
3134     {
3135         if (parent_decl_ctx)
3136             GetObjectFile()->GetModule()->LogMessage (log,
3137                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = %p (\"%s\"), append=%u, max_matches=%u, type_list)",
3138                                                       name.GetCString(),
3139                                                       static_cast<const void*>(parent_decl_ctx),
3140                                                       parent_decl_ctx->GetName().AsCString("<NULL>"),
3141                                                       append, max_matches);
3142         else
3143             GetObjectFile()->GetModule()->LogMessage (log,
3144                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = NULL, append=%u, max_matches=%u, type_list)",
3145                                                       name.GetCString(), append,
3146                                                       max_matches);
3147     }
3148 
3149     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
3150         return 0;
3151 
3152     DIEArray die_offsets;
3153 
3154     if (m_using_apple_tables)
3155     {
3156         if (m_apple_types_ap.get())
3157         {
3158             const char *name_cstr = name.GetCString();
3159             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3160         }
3161     }
3162     else
3163     {
3164         if (!m_indexed)
3165             Index ();
3166 
3167         m_type_index.Find (name, die_offsets);
3168     }
3169 
3170     const size_t num_die_matches = die_offsets.size();
3171 
3172     if (num_die_matches)
3173     {
3174         const uint32_t initial_types_size = types.GetSize();
3175         for (size_t i=0; i<num_die_matches; ++i)
3176         {
3177             const DIERef& die_ref = die_offsets[i];
3178             DWARFDIE die = GetDIE (die_ref);
3179 
3180             if (die)
3181             {
3182                 if (!DIEInDeclContext(parent_decl_ctx, die))
3183                     continue; // The containing decl contexts don't match
3184 
3185                 Type *matching_type = ResolveType (die, true, true);
3186                 if (matching_type)
3187                 {
3188                     // We found a type pointer, now find the shared pointer form our type list
3189                     types.InsertUnique (matching_type->shared_from_this());
3190                     if (types.GetSize() >= max_matches)
3191                         break;
3192                 }
3193             }
3194             else
3195             {
3196                 if (m_using_apple_tables)
3197                 {
3198                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3199                                                                                die_ref.die_offset, name.GetCString());
3200                 }
3201             }
3202 
3203         }
3204         const uint32_t num_matches = types.GetSize() - initial_types_size;
3205         if (log && num_matches)
3206         {
3207             if (parent_decl_ctx)
3208             {
3209                 GetObjectFile()->GetModule()->LogMessage (log,
3210                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
3211                                                           name.GetCString(),
3212                                                           static_cast<const void*>(parent_decl_ctx),
3213                                                           parent_decl_ctx->GetName().AsCString("<NULL>"),
3214                                                           append, max_matches,
3215                                                           num_matches);
3216             }
3217             else
3218             {
3219                 GetObjectFile()->GetModule()->LogMessage (log,
3220                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = NULL, append=%u, max_matches=%u, type_list) => %u",
3221                                                           name.GetCString(),
3222                                                           append, max_matches,
3223                                                           num_matches);
3224             }
3225         }
3226         return num_matches;
3227     }
3228     else
3229     {
3230         UpdateExternalModuleListIfNeeded();
3231 
3232         for (const auto &pair : m_external_type_modules)
3233         {
3234             ModuleSP external_module_sp = pair.second;
3235             if (external_module_sp)
3236             {
3237                 SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
3238                 if (sym_vendor)
3239                 {
3240                     const uint32_t num_external_matches = sym_vendor->FindTypes (sc,
3241                                                                                  name,
3242                                                                                  parent_decl_ctx,
3243                                                                                  append,
3244                                                                                  max_matches,
3245                                                                                  searched_symbol_files,
3246                                                                                  types);
3247                     if (num_external_matches)
3248                         return num_external_matches;
3249                 }
3250             }
3251         }
3252     }
3253 
3254     return 0;
3255 }
3256 
3257 
3258 size_t
3259 SymbolFileDWARF::FindTypes (const std::vector<CompilerContext> &context,
3260                             bool append,
3261                             TypeMap& types)
3262 {
3263     if (!append)
3264         types.Clear();
3265 
3266     if (context.empty())
3267         return 0;
3268 
3269     DIEArray die_offsets;
3270 
3271     ConstString name = context.back().name;
3272 
3273     if (!name)
3274         return 0;
3275 
3276     if (m_using_apple_tables)
3277     {
3278         if (m_apple_types_ap.get())
3279         {
3280             const char *name_cstr = name.GetCString();
3281             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3282         }
3283     }
3284     else
3285     {
3286         if (!m_indexed)
3287             Index ();
3288 
3289         m_type_index.Find (name, die_offsets);
3290     }
3291 
3292     const size_t num_die_matches = die_offsets.size();
3293 
3294     if (num_die_matches)
3295     {
3296         size_t num_matches = 0;
3297         for (size_t i=0; i<num_die_matches; ++i)
3298         {
3299             const DIERef& die_ref = die_offsets[i];
3300             DWARFDIE die = GetDIE (die_ref);
3301 
3302             if (die)
3303             {
3304                 std::vector<CompilerContext> die_context;
3305                 die.GetDWOContext(die_context);
3306                 if (die_context != context)
3307                     continue;
3308 
3309                 Type *matching_type = ResolveType (die, true, true);
3310                 if (matching_type)
3311                 {
3312                     // We found a type pointer, now find the shared pointer form our type list
3313                     types.InsertUnique (matching_type->shared_from_this());
3314                     ++num_matches;
3315                 }
3316             }
3317             else
3318             {
3319                 if (m_using_apple_tables)
3320                 {
3321                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3322                                                                                die_ref.die_offset, name.GetCString());
3323                 }
3324             }
3325 
3326         }
3327         return num_matches;
3328     }
3329     return 0;
3330 }
3331 
3332 
3333 CompilerDeclContext
3334 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
3335                                 const ConstString &name,
3336                                 const CompilerDeclContext *parent_decl_ctx)
3337 {
3338     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3339 
3340     if (log)
3341     {
3342         GetObjectFile()->GetModule()->LogMessage (log,
3343                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
3344                                                   name.GetCString());
3345     }
3346 
3347     CompilerDeclContext namespace_decl_ctx;
3348 
3349     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
3350         return namespace_decl_ctx;
3351 
3352 
3353     DWARFDebugInfo* info = DebugInfo();
3354     if (info)
3355     {
3356         DIEArray die_offsets;
3357 
3358         // Index if we already haven't to make sure the compile units
3359         // get indexed and make their global DIE index list
3360         if (m_using_apple_tables)
3361         {
3362             if (m_apple_namespaces_ap.get())
3363             {
3364                 const char *name_cstr = name.GetCString();
3365                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
3366             }
3367         }
3368         else
3369         {
3370             if (!m_indexed)
3371                 Index ();
3372 
3373             m_namespace_index.Find (name, die_offsets);
3374         }
3375 
3376         const size_t num_matches = die_offsets.size();
3377         if (num_matches)
3378         {
3379             for (size_t i=0; i<num_matches; ++i)
3380             {
3381                 const DIERef& die_ref = die_offsets[i];
3382                 DWARFDIE die = GetDIE (die_ref);
3383 
3384                 if (die)
3385                 {
3386                     if (!DIEInDeclContext (parent_decl_ctx, die))
3387                         continue; // The containing decl contexts don't match
3388 
3389                     DWARFASTParser *dwarf_ast = die.GetDWARFParser();
3390                     if (dwarf_ast)
3391                     {
3392                         namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF (die);
3393                         if (namespace_decl_ctx)
3394                             break;
3395                     }
3396                 }
3397                 else
3398                 {
3399                     if (m_using_apple_tables)
3400                     {
3401                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
3402                                                                    die_ref.die_offset, name.GetCString());
3403                     }
3404                 }
3405 
3406             }
3407         }
3408     }
3409     if (log && namespace_decl_ctx)
3410     {
3411         GetObjectFile()->GetModule()->LogMessage (log,
3412                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => CompilerDeclContext(%p/%p) \"%s\"",
3413                                                   name.GetCString(),
3414                                                   static_cast<const void*>(namespace_decl_ctx.GetTypeSystem()),
3415                                                   static_cast<const void*>(namespace_decl_ctx.GetOpaqueDeclContext()),
3416                                                   namespace_decl_ctx.GetName().AsCString("<NULL>"));
3417     }
3418 
3419     return namespace_decl_ctx;
3420 }
3421 
3422 TypeSP
3423 SymbolFileDWARF::GetTypeForDIE (const DWARFDIE &die, bool resolve_function_context)
3424 {
3425     TypeSP type_sp;
3426     if (die)
3427     {
3428         Type *type_ptr = GetDIEToType().lookup (die.GetDIE());
3429         if (type_ptr == NULL)
3430         {
3431             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU());
3432             assert (lldb_cu);
3433             SymbolContext sc(lldb_cu);
3434             const DWARFDebugInfoEntry* parent_die = die.GetParent().GetDIE();
3435             while (parent_die != nullptr)
3436                 {
3437                     if (parent_die->Tag() == DW_TAG_subprogram)
3438                         break;
3439                     parent_die = parent_die->GetParent();
3440                 }
3441             SymbolContext sc_backup = sc;
3442             if (resolve_function_context && parent_die != nullptr && !GetFunction(DWARFDIE(die.GetCU(),parent_die), sc))
3443                 sc = sc_backup;
3444 
3445             type_sp = ParseType(sc, die, NULL);
3446         }
3447         else if (type_ptr != DIE_IS_BEING_PARSED)
3448         {
3449             // Grab the existing type from the master types lists
3450             type_sp = type_ptr->shared_from_this();
3451         }
3452 
3453     }
3454     return type_sp;
3455 }
3456 
3457 
3458 DWARFDIE
3459 SymbolFileDWARF::GetDeclContextDIEContainingDIE (const DWARFDIE &orig_die)
3460 {
3461     if (orig_die)
3462     {
3463         DWARFDIE die = orig_die;
3464 
3465         while (die)
3466         {
3467             // If this is the original DIE that we are searching for a declaration
3468             // for, then don't look in the cache as we don't want our own decl
3469             // context to be our decl context...
3470             if (orig_die != die)
3471             {
3472                 switch (die.Tag())
3473                 {
3474                     case DW_TAG_compile_unit:
3475                     case DW_TAG_namespace:
3476                     case DW_TAG_structure_type:
3477                     case DW_TAG_union_type:
3478                     case DW_TAG_class_type:
3479                     case DW_TAG_lexical_block:
3480                     case DW_TAG_subprogram:
3481                         return die;
3482 
3483                     default:
3484                         break;
3485                 }
3486             }
3487 
3488             DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
3489             if (spec_die)
3490             {
3491                 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
3492                 if (decl_ctx_die)
3493                     return decl_ctx_die;
3494             }
3495 
3496             DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
3497             if (abs_die)
3498             {
3499                 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
3500                 if (decl_ctx_die)
3501                     return decl_ctx_die;
3502             }
3503 
3504             die = die.GetParent();
3505         }
3506     }
3507     return DWARFDIE();
3508 }
3509 
3510 
3511 Symbol *
3512 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
3513 {
3514     Symbol *objc_class_symbol = NULL;
3515     if (m_obj_file)
3516     {
3517         Symtab *symtab = m_obj_file->GetSymtab ();
3518         if (symtab)
3519         {
3520             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
3521                                                                         eSymbolTypeObjCClass,
3522                                                                         Symtab::eDebugNo,
3523                                                                         Symtab::eVisibilityAny);
3524         }
3525     }
3526     return objc_class_symbol;
3527 }
3528 
3529 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
3530 // then we can end up looking through all class types for a complete type and never find
3531 // the full definition. We need to know if this attribute is supported, so we determine
3532 // this here and cache th result. We also need to worry about the debug map DWARF file
3533 // if we are doing darwin DWARF in .o file debugging.
3534 bool
3535 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
3536 {
3537     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
3538     {
3539         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
3540         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
3541             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3542         else
3543         {
3544             DWARFDebugInfo* debug_info = DebugInfo();
3545             const uint32_t num_compile_units = GetNumCompileUnits();
3546             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
3547             {
3548                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
3549                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
3550                 {
3551                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3552                     break;
3553                 }
3554             }
3555         }
3556         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
3557             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
3558     }
3559     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
3560 }
3561 
3562 // This function can be used when a DIE is found that is a forward declaration
3563 // DIE and we want to try and find a type that has the complete definition.
3564 TypeSP
3565 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDIE &die,
3566                                                        const ConstString &type_name,
3567                                                        bool must_be_implementation)
3568 {
3569 
3570     TypeSP type_sp;
3571 
3572     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
3573         return type_sp;
3574 
3575     DIEArray die_offsets;
3576 
3577     if (m_using_apple_tables)
3578     {
3579         if (m_apple_types_ap.get())
3580         {
3581             const char *name_cstr = type_name.GetCString();
3582             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
3583         }
3584     }
3585     else
3586     {
3587         if (!m_indexed)
3588             Index ();
3589 
3590         m_type_index.Find (type_name, die_offsets);
3591     }
3592 
3593     const size_t num_matches = die_offsets.size();
3594 
3595     if (num_matches)
3596     {
3597         for (size_t i=0; i<num_matches; ++i)
3598         {
3599             const DIERef& die_ref = die_offsets[i];
3600             DWARFDIE type_die = GetDIE (die_ref);
3601 
3602             if (type_die)
3603             {
3604                 bool try_resolving_type = false;
3605 
3606                 // Don't try and resolve the DIE we are looking for with the DIE itself!
3607                 if (type_die != die)
3608                 {
3609                     switch (type_die.Tag())
3610                     {
3611                         case DW_TAG_class_type:
3612                         case DW_TAG_structure_type:
3613                             try_resolving_type = true;
3614                             break;
3615                         default:
3616                             break;
3617                     }
3618                 }
3619 
3620                 if (try_resolving_type)
3621                 {
3622                     if (must_be_implementation && type_die.Supports_DW_AT_APPLE_objc_complete_type())
3623                         try_resolving_type = type_die.GetAttributeValueAsUnsigned (DW_AT_APPLE_objc_complete_type, 0);
3624 
3625                     if (try_resolving_type)
3626                     {
3627                         Type *resolved_type = ResolveType (type_die, false, true);
3628                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
3629                         {
3630                             DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
3631                                           die.GetID(),
3632                                           m_obj_file->GetFileSpec().GetFilename().AsCString("<Unknown>"),
3633                                           type_die.GetID(),
3634                                           type_cu->GetID());
3635 
3636                             if (die)
3637                                 GetDIEToType()[die.GetDIE()] = resolved_type;
3638                             type_sp = resolved_type->shared_from_this();
3639                             break;
3640                         }
3641                     }
3642                 }
3643             }
3644             else
3645             {
3646                 if (m_using_apple_tables)
3647                 {
3648                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3649                                                                die_ref.die_offset, type_name.GetCString());
3650                 }
3651             }
3652 
3653         }
3654     }
3655     return type_sp;
3656 }
3657 
3658 
3659 //----------------------------------------------------------------------
3660 // This function helps to ensure that the declaration contexts match for
3661 // two different DIEs. Often times debug information will refer to a
3662 // forward declaration of a type (the equivalent of "struct my_struct;".
3663 // There will often be a declaration of that type elsewhere that has the
3664 // full definition. When we go looking for the full type "my_struct", we
3665 // will find one or more matches in the accelerator tables and we will
3666 // then need to make sure the type was in the same declaration context
3667 // as the original DIE. This function can efficiently compare two DIEs
3668 // and will return true when the declaration context matches, and false
3669 // when they don't.
3670 //----------------------------------------------------------------------
3671 bool
3672 SymbolFileDWARF::DIEDeclContextsMatch (const DWARFDIE &die1,
3673                                        const DWARFDIE &die2)
3674 {
3675     if (die1 == die2)
3676         return true;
3677 
3678     DWARFDIECollection decl_ctx_1;
3679     DWARFDIECollection decl_ctx_2;
3680     //The declaration DIE stack is a stack of the declaration context
3681     // DIEs all the way back to the compile unit. If a type "T" is
3682     // declared inside a class "B", and class "B" is declared inside
3683     // a class "A" and class "A" is in a namespace "lldb", and the
3684     // namespace is in a compile unit, there will be a stack of DIEs:
3685     //
3686     //   [0] DW_TAG_class_type for "B"
3687     //   [1] DW_TAG_class_type for "A"
3688     //   [2] DW_TAG_namespace  for "lldb"
3689     //   [3] DW_TAG_compile_unit for the source file.
3690     //
3691     // We grab both contexts and make sure that everything matches
3692     // all the way back to the compiler unit.
3693 
3694     // First lets grab the decl contexts for both DIEs
3695     die1.GetDeclContextDIEs (decl_ctx_1);
3696     die2.GetDeclContextDIEs (decl_ctx_2);
3697     // Make sure the context arrays have the same size, otherwise
3698     // we are done
3699     const size_t count1 = decl_ctx_1.Size();
3700     const size_t count2 = decl_ctx_2.Size();
3701     if (count1 != count2)
3702         return false;
3703 
3704     // Make sure the DW_TAG values match all the way back up the
3705     // compile unit. If they don't, then we are done.
3706     DWARFDIE decl_ctx_die1;
3707     DWARFDIE decl_ctx_die2;
3708     size_t i;
3709     for (i=0; i<count1; i++)
3710     {
3711         decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex (i);
3712         decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex (i);
3713         if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
3714             return false;
3715     }
3716 #if defined LLDB_CONFIGURATION_DEBUG
3717 
3718     // Make sure the top item in the decl context die array is always
3719     // DW_TAG_compile_unit. If it isn't then something went wrong in
3720     // the DWARFDIE::GetDeclContextDIEs() function...
3721     assert (decl_ctx_1.GetDIEAtIndex (count1 - 1).Tag() == DW_TAG_compile_unit);
3722 
3723 #endif
3724     // Always skip the compile unit when comparing by only iterating up to
3725     // "count - 1". Here we compare the names as we go.
3726     for (i=0; i<count1 - 1; i++)
3727     {
3728         decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex (i);
3729         decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex (i);
3730         const char *name1 = decl_ctx_die1.GetName();
3731         const char *name2 = decl_ctx_die2.GetName();
3732         // If the string was from a DW_FORM_strp, then the pointer will often
3733         // be the same!
3734         if (name1 == name2)
3735             continue;
3736 
3737         // Name pointers are not equal, so only compare the strings
3738         // if both are not NULL.
3739         if (name1 && name2)
3740         {
3741             // If the strings don't compare, we are done...
3742             if (strcmp(name1, name2) != 0)
3743                 return false;
3744         }
3745         else
3746         {
3747             // One name was NULL while the other wasn't
3748             return false;
3749         }
3750     }
3751     // We made it through all of the checks and the declaration contexts
3752     // are equal.
3753     return true;
3754 }
3755 
3756 
3757 TypeSP
3758 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
3759 {
3760     TypeSP type_sp;
3761 
3762     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
3763     if (dwarf_decl_ctx_count > 0)
3764     {
3765         const ConstString type_name(dwarf_decl_ctx[0].name);
3766         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
3767 
3768         if (type_name)
3769         {
3770             Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
3771             if (log)
3772             {
3773                 GetObjectFile()->GetModule()->LogMessage (log,
3774                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
3775                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3776                                                           dwarf_decl_ctx.GetQualifiedName());
3777             }
3778 
3779             DIEArray die_offsets;
3780 
3781             if (m_using_apple_tables)
3782             {
3783                 if (m_apple_types_ap.get())
3784                 {
3785                     const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
3786                     const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
3787                     if (has_tag && has_qualified_name_hash)
3788                     {
3789                         const char *qualified_name = dwarf_decl_ctx.GetQualifiedName();
3790                         const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name);
3791                         if (log)
3792                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
3793                         m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), tag, qualified_name_hash, die_offsets);
3794                     }
3795                     else if (has_tag)
3796                     {
3797                         if (log)
3798                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
3799                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
3800                     }
3801                     else
3802                     {
3803                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
3804                     }
3805                 }
3806             }
3807             else
3808             {
3809                 if (!m_indexed)
3810                     Index ();
3811 
3812                 m_type_index.Find (type_name, die_offsets);
3813             }
3814 
3815             const size_t num_matches = die_offsets.size();
3816 
3817             // Get the type system that we are looking to find a type for. We will use this
3818             // to ensure any matches we find are in a language that this type system supports
3819             const LanguageType language = dwarf_decl_ctx.GetLanguage();
3820             TypeSystem *type_system = (language == eLanguageTypeUnknown) ? nullptr : GetTypeSystemForLanguage(language);
3821 
3822             if (num_matches)
3823             {
3824                 for (size_t i=0; i<num_matches; ++i)
3825                 {
3826                     const DIERef& die_ref = die_offsets[i];
3827                     DWARFDIE type_die = GetDIE (die_ref);
3828 
3829                     if (type_die)
3830                     {
3831                         // Make sure type_die's langauge matches the type system we are looking for.
3832                         // We don't want to find a "Foo" type from Java if we are looking for a "Foo"
3833                         // type for C, C++, ObjC, or ObjC++.
3834                         if (type_system && !type_system->SupportsLanguage(type_die.GetLanguage()))
3835                             continue;
3836                         bool try_resolving_type = false;
3837 
3838                         // Don't try and resolve the DIE we are looking for with the DIE itself!
3839                         const dw_tag_t type_tag = type_die.Tag();
3840                         // Make sure the tags match
3841                         if (type_tag == tag)
3842                         {
3843                             // The tags match, lets try resolving this type
3844                             try_resolving_type = true;
3845                         }
3846                         else
3847                         {
3848                             // The tags don't match, but we need to watch our for a
3849                             // forward declaration for a struct and ("struct foo")
3850                             // ends up being a class ("class foo { ... };") or
3851                             // vice versa.
3852                             switch (type_tag)
3853                             {
3854                                 case DW_TAG_class_type:
3855                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
3856                                     try_resolving_type = (tag == DW_TAG_structure_type);
3857                                     break;
3858                                 case DW_TAG_structure_type:
3859                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
3860                                     try_resolving_type = (tag == DW_TAG_class_type);
3861                                     break;
3862                                 default:
3863                                     // Tags don't match, don't event try to resolve
3864                                     // using this type whose name matches....
3865                                     break;
3866                             }
3867                         }
3868 
3869                         if (try_resolving_type)
3870                         {
3871                             DWARFDeclContext type_dwarf_decl_ctx;
3872                             type_die.GetDWARFDeclContext (type_dwarf_decl_ctx);
3873 
3874                             if (log)
3875                             {
3876                                 GetObjectFile()->GetModule()->LogMessage (log,
3877                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
3878                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3879                                                                           dwarf_decl_ctx.GetQualifiedName(),
3880                                                                           type_die.GetOffset(),
3881                                                                           type_dwarf_decl_ctx.GetQualifiedName());
3882                             }
3883 
3884                             // Make sure the decl contexts match all the way up
3885                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
3886                             {
3887                                 Type *resolved_type = ResolveType (type_die, false);
3888                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
3889                                 {
3890                                     type_sp = resolved_type->shared_from_this();
3891                                     break;
3892                                 }
3893                             }
3894                         }
3895                         else
3896                         {
3897                             if (log)
3898                             {
3899                                 std::string qualified_name;
3900                                 type_die.GetQualifiedName(qualified_name);
3901                                 GetObjectFile()->GetModule()->LogMessage (log,
3902                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
3903                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3904                                                                           dwarf_decl_ctx.GetQualifiedName(),
3905                                                                           type_die.GetOffset(),
3906                                                                           qualified_name.c_str());
3907                             }
3908                         }
3909                     }
3910                     else
3911                     {
3912                         if (m_using_apple_tables)
3913                         {
3914                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3915                                                                                        die_ref.die_offset, type_name.GetCString());
3916                         }
3917                     }
3918 
3919                 }
3920             }
3921         }
3922     }
3923     return type_sp;
3924 }
3925 
3926 TypeSP
3927 SymbolFileDWARF::ParseType (const SymbolContext& sc, const DWARFDIE &die, bool *type_is_new_ptr)
3928 {
3929     TypeSP type_sp;
3930 
3931     if (die)
3932     {
3933         TypeSystem *type_system = GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3934 
3935         if (type_system)
3936         {
3937             DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
3938             if (dwarf_ast)
3939             {
3940                 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
3941                 type_sp = dwarf_ast->ParseTypeFromDWARF (sc, die, log, type_is_new_ptr);
3942                 if (type_sp)
3943                 {
3944                     TypeList* type_list = GetTypeList();
3945                     if (type_list)
3946                         type_list->Insert(type_sp);
3947 
3948                     if (die.Tag() == DW_TAG_subprogram)
3949                     {
3950                         DIERef die_ref = die.GetDIERef();
3951                         std::string scope_qualified_name(GetDeclContextForUID(die.GetID()).GetScopeQualifiedName().AsCString(""));
3952                         if (scope_qualified_name.size())
3953                         {
3954                             NameToOffsetMap::iterator iter = m_function_scope_qualified_name_map.find(scope_qualified_name);
3955                             if (iter != m_function_scope_qualified_name_map.end())
3956                                 (*iter).second->insert(die_ref);
3957                             else
3958                             {
3959                                 DIERefSetSP new_set(new std::set<DIERef>);
3960                                 new_set->insert(die_ref);
3961                                 m_function_scope_qualified_name_map.emplace(std::make_pair(scope_qualified_name, new_set));
3962                             }
3963                         }
3964                     }
3965                 }
3966             }
3967         }
3968     }
3969 
3970     return type_sp;
3971 }
3972 
3973 size_t
3974 SymbolFileDWARF::ParseTypes
3975 (
3976     const SymbolContext& sc,
3977     const DWARFDIE &orig_die,
3978     bool parse_siblings,
3979     bool parse_children
3980 )
3981 {
3982     size_t types_added = 0;
3983     DWARFDIE die = orig_die;
3984     while (die)
3985     {
3986         bool type_is_new = false;
3987         if (ParseType(sc, die, &type_is_new).get())
3988         {
3989             if (type_is_new)
3990                 ++types_added;
3991         }
3992 
3993         if (parse_children && die.HasChildren())
3994         {
3995             if (die.Tag() == DW_TAG_subprogram)
3996             {
3997                 SymbolContext child_sc(sc);
3998                 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3999                 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
4000             }
4001             else
4002                 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
4003         }
4004 
4005         if (parse_siblings)
4006             die = die.GetSibling();
4007         else
4008             die.Clear();
4009     }
4010     return types_added;
4011 }
4012 
4013 
4014 size_t
4015 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
4016 {
4017     assert(sc.comp_unit && sc.function);
4018     size_t functions_added = 0;
4019     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
4020     if (dwarf_cu)
4021     {
4022         const dw_offset_t function_die_offset = sc.function->GetID();
4023         DWARFDIE function_die = dwarf_cu->GetDIE (function_die_offset);
4024         if (function_die)
4025         {
4026             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), function_die, LLDB_INVALID_ADDRESS, 0);
4027         }
4028     }
4029 
4030     return functions_added;
4031 }
4032 
4033 
4034 size_t
4035 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
4036 {
4037     // At least a compile unit must be valid
4038     assert(sc.comp_unit);
4039     size_t types_added = 0;
4040     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
4041     if (dwarf_cu)
4042     {
4043         if (sc.function)
4044         {
4045             dw_offset_t function_die_offset = sc.function->GetID();
4046             DWARFDIE func_die = dwarf_cu->GetDIE(function_die_offset);
4047             if (func_die && func_die.HasChildren())
4048             {
4049                 types_added = ParseTypes(sc, func_die.GetFirstChild(), true, true);
4050             }
4051         }
4052         else
4053         {
4054             DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
4055             if (dwarf_cu_die && dwarf_cu_die.HasChildren())
4056             {
4057                 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
4058             }
4059         }
4060     }
4061 
4062     return types_added;
4063 }
4064 
4065 size_t
4066 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
4067 {
4068     if (sc.comp_unit != NULL)
4069     {
4070         DWARFDebugInfo* info = DebugInfo();
4071         if (info == NULL)
4072             return 0;
4073 
4074         if (sc.function)
4075         {
4076             DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID(), this));
4077 
4078             const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress (DW_AT_low_pc, LLDB_INVALID_ADDRESS);
4079             if (func_lo_pc != LLDB_INVALID_ADDRESS)
4080             {
4081                 const size_t num_variables = ParseVariables(sc, function_die.GetFirstChild(), func_lo_pc, true, true);
4082 
4083                 // Let all blocks know they have parse all their variables
4084                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
4085                 return num_variables;
4086             }
4087         }
4088         else if (sc.comp_unit)
4089         {
4090             DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID());
4091 
4092             if (dwarf_cu == NULL)
4093                 return 0;
4094 
4095             uint32_t vars_added = 0;
4096             VariableListSP variables (sc.comp_unit->GetVariableList(false));
4097 
4098             if (variables.get() == NULL)
4099             {
4100                 variables.reset(new VariableList());
4101                 sc.comp_unit->SetVariableList(variables);
4102 
4103                 DIEArray die_offsets;
4104                 if (m_using_apple_tables)
4105                 {
4106                     if (m_apple_names_ap.get())
4107                     {
4108                         DWARFMappedHash::DIEInfoArray hash_data_array;
4109                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
4110                                                                     dwarf_cu->GetNextCompileUnitOffset(),
4111                                                                     hash_data_array))
4112                         {
4113                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
4114                         }
4115                     }
4116                 }
4117                 else
4118                 {
4119                     // Index if we already haven't to make sure the compile units
4120                     // get indexed and make their global DIE index list
4121                     if (!m_indexed)
4122                         Index ();
4123 
4124                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
4125                                                                  die_offsets);
4126                 }
4127 
4128                 const size_t num_matches = die_offsets.size();
4129                 if (num_matches)
4130                 {
4131                     for (size_t i=0; i<num_matches; ++i)
4132                     {
4133                         const DIERef& die_ref = die_offsets[i];
4134                         DWARFDIE die = GetDIE (die_ref);
4135                         if (die)
4136                         {
4137                             VariableSP var_sp (ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
4138                             if (var_sp)
4139                             {
4140                                 variables->AddVariableIfUnique (var_sp);
4141                                 ++vars_added;
4142                             }
4143                         }
4144                         else
4145                         {
4146                             if (m_using_apple_tables)
4147                             {
4148                                 GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_ref.die_offset);
4149                             }
4150                         }
4151 
4152                     }
4153                 }
4154             }
4155             return vars_added;
4156         }
4157     }
4158     return 0;
4159 }
4160 
4161 VariableSP
4162 SymbolFileDWARF::ParseVariableDIE
4163 (
4164     const SymbolContext& sc,
4165     const DWARFDIE &die,
4166     const lldb::addr_t func_low_pc
4167 )
4168 {
4169     if (die.GetDWARF() != this)
4170         return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
4171 
4172     VariableSP var_sp;
4173     if (!die)
4174         return var_sp;
4175 
4176     var_sp = GetDIEToVariable()[die.GetDIE()];
4177     if (var_sp)
4178         return var_sp;  // Already been parsed!
4179 
4180     const dw_tag_t tag = die.Tag();
4181     ModuleSP module = GetObjectFile()->GetModule();
4182 
4183     if ((tag == DW_TAG_variable) ||
4184         (tag == DW_TAG_constant) ||
4185         (tag == DW_TAG_formal_parameter && sc.function))
4186     {
4187         DWARFAttributes attributes;
4188         const size_t num_attributes = die.GetAttributes(attributes);
4189         DWARFDIE spec_die;
4190         if (num_attributes > 0)
4191         {
4192             const char *name = NULL;
4193             const char *mangled = NULL;
4194             Declaration decl;
4195             uint32_t i;
4196             DWARFFormValue type_die_form;
4197             DWARFExpression location(die.GetCU());
4198             bool is_external = false;
4199             bool is_artificial = false;
4200             bool location_is_const_value_data = false;
4201             bool has_explicit_location = false;
4202             DWARFFormValue const_value;
4203             Variable::RangeList scope_ranges;
4204             //AccessType accessibility = eAccessNone;
4205 
4206             for (i=0; i<num_attributes; ++i)
4207             {
4208                 dw_attr_t attr = attributes.AttributeAtIndex(i);
4209                 DWARFFormValue form_value;
4210 
4211                 if (attributes.ExtractFormValueAtIndex(i, form_value))
4212                 {
4213                     switch (attr)
4214                     {
4215                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4216                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4217                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4218                     case DW_AT_name:        name = form_value.AsCString(); break;
4219                     case DW_AT_linkage_name:
4220                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(); break;
4221                     case DW_AT_type:        type_die_form = form_value; break;
4222                     case DW_AT_external:    is_external = form_value.Boolean(); break;
4223                     case DW_AT_const_value:
4224                         // If we have already found a DW_AT_location attribute, ignore this attribute.
4225                         if (!has_explicit_location)
4226                         {
4227                             location_is_const_value_data = true;
4228                             // The constant value will be either a block, a data value or a string.
4229                             const DWARFDataExtractor& debug_info_data = get_debug_info_data();
4230                             if (DWARFFormValue::IsBlockForm(form_value.Form()))
4231                             {
4232                                 // Retrieve the value as a block expression.
4233                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
4234                                 uint32_t block_length = form_value.Unsigned();
4235                                 location.CopyOpcodeData(module, debug_info_data, block_offset, block_length);
4236                             }
4237                             else if (DWARFFormValue::IsDataForm(form_value.Form()))
4238                             {
4239                                 // Retrieve the value as a data expression.
4240                                 DWARFFormValue::FixedFormSizes fixed_form_sizes =
4241                                     DWARFFormValue::GetFixedFormSizesForAddressSize (
4242                                             attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
4243                                             attributes.CompileUnitAtIndex(i)->IsDWARF64());
4244                                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
4245                                 uint32_t data_length = fixed_form_sizes.GetSize(form_value.Form());
4246                                 if (data_length == 0)
4247                                 {
4248                                     const uint8_t *data_pointer = form_value.BlockData();
4249                                     if (data_pointer)
4250                                     {
4251                                         form_value.Unsigned();
4252                                     }
4253                                     else if (DWARFFormValue::IsDataForm(form_value.Form()))
4254                                     {
4255                                         // we need to get the byte size of the type later after we create the variable
4256                                         const_value = form_value;
4257                                     }
4258                                 }
4259                                 else
4260                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
4261                             }
4262                             else
4263                             {
4264                                 // Retrieve the value as a string expression.
4265                                 if (form_value.Form() == DW_FORM_strp)
4266                                 {
4267                                     DWARFFormValue::FixedFormSizes fixed_form_sizes =
4268                                         DWARFFormValue::GetFixedFormSizesForAddressSize (
4269                                                 attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
4270                                                 attributes.CompileUnitAtIndex(i)->IsDWARF64());
4271                                     uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
4272                                     uint32_t data_length = fixed_form_sizes.GetSize(form_value.Form());
4273                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
4274                                 }
4275                                 else
4276                                 {
4277                                     const char *str = form_value.AsCString();
4278                                     uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart();
4279                                     uint32_t string_length = strlen(str) + 1;
4280                                     location.CopyOpcodeData(module, debug_info_data, string_offset, string_length);
4281                                 }
4282                             }
4283                         }
4284                         break;
4285                     case DW_AT_location:
4286                         {
4287                             location_is_const_value_data = false;
4288                             has_explicit_location = true;
4289                             if (form_value.BlockData())
4290                             {
4291                                 const DWARFDataExtractor& debug_info_data = get_debug_info_data();
4292 
4293                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
4294                                 uint32_t block_length = form_value.Unsigned();
4295                                 location.CopyOpcodeData(module, get_debug_info_data(), block_offset, block_length);
4296                             }
4297                             else
4298                             {
4299                                 const DWARFDataExtractor& debug_loc_data = get_debug_loc_data();
4300                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
4301 
4302                                 size_t loc_list_length = DWARFExpression::LocationListSize(die.GetCU(), debug_loc_data, debug_loc_offset);
4303                                 if (loc_list_length > 0)
4304                                 {
4305                                     location.CopyOpcodeData(module, debug_loc_data, debug_loc_offset, loc_list_length);
4306                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
4307                                     location.SetLocationListSlide (func_low_pc - attributes.CompileUnitAtIndex(i)->GetBaseAddress());
4308                                 }
4309                             }
4310                         }
4311                         break;
4312                     case DW_AT_specification:
4313                         spec_die = GetDIE(DIERef(form_value));
4314                         break;
4315                     case DW_AT_start_scope:
4316                         {
4317                             if (form_value.Form() == DW_FORM_sec_offset)
4318                             {
4319                                 DWARFRangeList dwarf_scope_ranges;
4320                                 const DWARFDebugRanges* debug_ranges = DebugRanges();
4321                                 debug_ranges->FindRanges(form_value.Unsigned(), dwarf_scope_ranges);
4322 
4323                                 // All DW_AT_start_scope are relative to the base address of the
4324                                 // compile unit. We add the compile unit base address to make
4325                                 // sure all the addresses are properly fixed up.
4326                                 for (size_t i = 0, count = dwarf_scope_ranges.GetSize(); i < count; ++i)
4327                                 {
4328                                     const DWARFRangeList::Entry& range = dwarf_scope_ranges.GetEntryRef(i);
4329                                     scope_ranges.Append(range.GetRangeBase() + die.GetCU()->GetBaseAddress(),
4330                                                         range.GetByteSize());
4331                                 }
4332                             }
4333                             else
4334                             {
4335                                 // TODO: Handle the case when DW_AT_start_scope have form constant. The
4336                                 // dwarf spec is a bit ambiguous about what is the expected behavior in
4337                                 // case the enclosing block have a non coninious address range and the
4338                                 // DW_AT_start_scope entry have a form constant.
4339                                 GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_start_scope has unsupported form type (0x%x)\n",
4340                                                                              die.GetID(),
4341                                                                              form_value.Form());
4342                             }
4343 
4344                             scope_ranges.Sort();
4345                             scope_ranges.CombineConsecutiveRanges();
4346                         }
4347                         break;
4348                     case DW_AT_artificial:      is_artificial = form_value.Boolean(); break;
4349                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
4350                     case DW_AT_declaration:
4351                     case DW_AT_description:
4352                     case DW_AT_endianity:
4353                     case DW_AT_segment:
4354                     case DW_AT_visibility:
4355                     default:
4356                     case DW_AT_abstract_origin:
4357                     case DW_AT_sibling:
4358                         break;
4359                     }
4360                 }
4361             }
4362 
4363             const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
4364             const dw_tag_t parent_tag = die.GetParent().Tag();
4365             bool is_static_member = parent_tag == DW_TAG_compile_unit && (parent_context_die.Tag() == DW_TAG_class_type || parent_context_die.Tag() == DW_TAG_structure_type);
4366 
4367             ValueType scope = eValueTypeInvalid;
4368 
4369             const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
4370             SymbolContextScope * symbol_context_scope = NULL;
4371 
4372             if (!mangled)
4373             {
4374                 // LLDB relies on the mangled name (DW_TAG_linkage_name or DW_AT_MIPS_linkage_name) to
4375                 // generate fully qualified names of global variables with commands like "frame var j".
4376                 // For example, if j were an int variable holding a value 4 and declared in a namespace
4377                 // B which in turn is contained in a namespace A, the command "frame var j" returns
4378                 // "(int) A::B::j = 4". If the compiler does not emit a linkage name, we should be able
4379                 // to generate a fully qualified name from the declaration context.
4380                 if (parent_tag == DW_TAG_compile_unit &&
4381                     Language::LanguageIsCPlusPlus(die.GetLanguage()))
4382                 {
4383                     DWARFDeclContext decl_ctx;
4384 
4385                     die.GetDWARFDeclContext(decl_ctx);
4386                     mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
4387                 }
4388             }
4389 
4390             // DWARF doesn't specify if a DW_TAG_variable is a local, global
4391             // or static variable, so we have to do a little digging by
4392             // looking at the location of a variable to see if it contains
4393             // a DW_OP_addr opcode _somewhere_ in the definition. I say
4394             // somewhere because clang likes to combine small global variables
4395             // into the same symbol and have locations like:
4396             // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
4397             // So if we don't have a DW_TAG_formal_parameter, we can look at
4398             // the location to see if it contains a DW_OP_addr opcode, and
4399             // then we can correctly classify  our variables.
4400             if (tag == DW_TAG_formal_parameter)
4401                 scope = eValueTypeVariableArgument;
4402             else
4403             {
4404                 bool op_error = false;
4405                 // Check if the location has a DW_OP_addr with any address value...
4406                 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
4407                 if (!location_is_const_value_data)
4408                 {
4409                     location_DW_OP_addr = location.GetLocation_DW_OP_addr (0, op_error);
4410                     if (op_error)
4411                     {
4412                         StreamString strm;
4413                         location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
4414                         GetObjectFile()->GetModule()->ReportError ("0x%8.8x: %s has an invalid location: %s", die.GetOffset(), die.GetTagAsCString(), strm.GetString().c_str());
4415                     }
4416                 }
4417 
4418                 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
4419                 {
4420                     if (is_external)
4421                         scope = eValueTypeVariableGlobal;
4422                     else
4423                         scope = eValueTypeVariableStatic;
4424 
4425 
4426                     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
4427 
4428                     if (debug_map_symfile)
4429                     {
4430                         // When leaving the DWARF in the .o files on darwin,
4431                         // when we have a global variable that wasn't initialized,
4432                         // the .o file might not have allocated a virtual
4433                         // address for the global variable. In this case it will
4434                         // have created a symbol for the global variable
4435                         // that is undefined/data and external and the value will
4436                         // be the byte size of the variable. When we do the
4437                         // address map in SymbolFileDWARFDebugMap we rely on
4438                         // having an address, we need to do some magic here
4439                         // so we can get the correct address for our global
4440                         // variable. The address for all of these entries
4441                         // will be zero, and there will be an undefined symbol
4442                         // in this object file, and the executable will have
4443                         // a matching symbol with a good address. So here we
4444                         // dig up the correct address and replace it in the
4445                         // location for the variable, and set the variable's
4446                         // symbol context scope to be that of the main executable
4447                         // so the file address will resolve correctly.
4448                         bool linked_oso_file_addr = false;
4449                         if (is_external && location_DW_OP_addr == 0)
4450                         {
4451                             // we have a possible uninitialized extern global
4452                             ConstString const_name(mangled ? mangled : name);
4453                             ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile();
4454                             if (debug_map_objfile)
4455                             {
4456                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
4457                                 if (debug_map_symtab)
4458                                 {
4459                                     Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
4460                                                                                                            eSymbolTypeData,
4461                                                                                                            Symtab::eDebugYes,
4462                                                                                                            Symtab::eVisibilityExtern);
4463                                     if (exe_symbol)
4464                                     {
4465                                         if (exe_symbol->ValueIsAddress())
4466                                         {
4467                                             const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress();
4468                                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
4469                                             {
4470                                                 if (location.Update_DW_OP_addr (exe_file_addr))
4471                                                 {
4472                                                     linked_oso_file_addr = true;
4473                                                     symbol_context_scope = exe_symbol;
4474                                                 }
4475                                             }
4476                                         }
4477                                     }
4478                                 }
4479                             }
4480                         }
4481 
4482                         if (!linked_oso_file_addr)
4483                         {
4484                             // The DW_OP_addr is not zero, but it contains a .o file address which
4485                             // needs to be linked up correctly.
4486                             const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
4487                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
4488                             {
4489                                 // Update the file address for this variable
4490                                 location.Update_DW_OP_addr (exe_file_addr);
4491                             }
4492                             else
4493                             {
4494                                 // Variable didn't make it into the final executable
4495                                 return var_sp;
4496                             }
4497                         }
4498                     }
4499                 }
4500                 else
4501                 {
4502                     if (location_is_const_value_data)
4503                         scope = eValueTypeVariableStatic;
4504                     else
4505                         scope = eValueTypeVariableLocal;
4506                 }
4507             }
4508 
4509             if (symbol_context_scope == NULL)
4510             {
4511                 switch (parent_tag)
4512                 {
4513                 case DW_TAG_subprogram:
4514                 case DW_TAG_inlined_subroutine:
4515                 case DW_TAG_lexical_block:
4516                     if (sc.function)
4517                     {
4518                         symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
4519                         if (symbol_context_scope == NULL)
4520                             symbol_context_scope = sc.function;
4521                     }
4522                     break;
4523 
4524                 default:
4525                     symbol_context_scope = sc.comp_unit;
4526                     break;
4527                 }
4528             }
4529 
4530             if (symbol_context_scope)
4531             {
4532                 SymbolFileTypeSP type_sp(new SymbolFileType(*this, DIERef(type_die_form).GetUID(this)));
4533 
4534                 if (const_value.Form() && type_sp && type_sp->GetType())
4535                     location.CopyOpcodeData(const_value.Unsigned(), type_sp->GetType()->GetByteSize(), die.GetCU()->GetAddressByteSize());
4536 
4537                 var_sp.reset (new Variable (die.GetID(),
4538                                             name,
4539                                             mangled,
4540                                             type_sp,
4541                                             scope,
4542                                             symbol_context_scope,
4543                                             scope_ranges,
4544                                             &decl,
4545                                             location,
4546                                             is_external,
4547                                             is_artificial,
4548                                             is_static_member));
4549 
4550                 var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
4551             }
4552             else
4553             {
4554                 // Not ready to parse this variable yet. It might be a global
4555                 // or static variable that is in a function scope and the function
4556                 // in the symbol context wasn't filled in yet
4557                 return var_sp;
4558             }
4559         }
4560         // Cache var_sp even if NULL (the variable was just a specification or
4561         // was missing vital information to be able to be displayed in the debugger
4562         // (missing location due to optimization, etc)) so we don't re-parse
4563         // this DIE over and over later...
4564         GetDIEToVariable()[die.GetDIE()] = var_sp;
4565         if (spec_die)
4566             GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
4567     }
4568     return var_sp;
4569 }
4570 
4571 
4572 DWARFDIE
4573 SymbolFileDWARF::FindBlockContainingSpecification (const DIERef& func_die_ref,
4574                                                    dw_offset_t spec_block_die_offset)
4575 {
4576     // Give the concrete function die specified by "func_die_offset", find the
4577     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4578     // to "spec_block_die_offset"
4579     return FindBlockContainingSpecification (DebugInfo()->GetDIE (func_die_ref), spec_block_die_offset);
4580 }
4581 
4582 
4583 DWARFDIE
4584 SymbolFileDWARF::FindBlockContainingSpecification(const DWARFDIE &die,
4585                                                   dw_offset_t spec_block_die_offset)
4586 {
4587     if (die)
4588     {
4589         switch (die.Tag())
4590         {
4591         case DW_TAG_subprogram:
4592         case DW_TAG_inlined_subroutine:
4593         case DW_TAG_lexical_block:
4594             {
4595                 if (die.GetAttributeValueAsReference (DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
4596                     return die;
4597 
4598                 if (die.GetAttributeValueAsReference (DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
4599                     return die;
4600             }
4601             break;
4602         }
4603 
4604         // Give the concrete function die specified by "func_die_offset", find the
4605         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4606         // to "spec_block_die_offset"
4607         for (DWARFDIE child_die = die.GetFirstChild(); child_die; child_die = child_die.GetSibling())
4608         {
4609             DWARFDIE result_die = FindBlockContainingSpecification (child_die, spec_block_die_offset);
4610             if (result_die)
4611                 return result_die;
4612         }
4613     }
4614 
4615     return DWARFDIE();
4616 }
4617 
4618 size_t
4619 SymbolFileDWARF::ParseVariables (const SymbolContext& sc,
4620                                  const DWARFDIE &orig_die,
4621                                  const lldb::addr_t func_low_pc,
4622                                  bool parse_siblings,
4623                                  bool parse_children,
4624                                  VariableList* cc_variable_list)
4625 {
4626     if (!orig_die)
4627         return 0;
4628 
4629     VariableListSP variable_list_sp;
4630 
4631     size_t vars_added = 0;
4632     DWARFDIE die = orig_die;
4633     while (die)
4634     {
4635         dw_tag_t tag = die.Tag();
4636 
4637         // Check to see if we have already parsed this variable or constant?
4638         VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
4639         if (var_sp)
4640         {
4641             if (cc_variable_list)
4642                 cc_variable_list->AddVariableIfUnique (var_sp);
4643         }
4644         else
4645         {
4646             // We haven't already parsed it, lets do that now.
4647             if ((tag == DW_TAG_variable) ||
4648                 (tag == DW_TAG_constant) ||
4649                 (tag == DW_TAG_formal_parameter && sc.function))
4650             {
4651                 if (variable_list_sp.get() == NULL)
4652                 {
4653                     DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
4654                     dw_tag_t parent_tag = sc_parent_die.Tag();
4655                     switch (parent_tag)
4656                     {
4657                         case DW_TAG_compile_unit:
4658                             if (sc.comp_unit != NULL)
4659                             {
4660                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
4661                                 if (variable_list_sp.get() == NULL)
4662                                 {
4663                                     variable_list_sp.reset(new VariableList());
4664                                     sc.comp_unit->SetVariableList(variable_list_sp);
4665                                 }
4666                             }
4667                             else
4668                             {
4669                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
4670                                                                            sc_parent_die.GetID(),
4671                                                                            sc_parent_die.GetTagAsCString(),
4672                                                                            orig_die.GetID(),
4673                                                                            orig_die.GetTagAsCString());
4674                             }
4675                             break;
4676 
4677                         case DW_TAG_subprogram:
4678                         case DW_TAG_inlined_subroutine:
4679                         case DW_TAG_lexical_block:
4680                             if (sc.function != NULL)
4681                             {
4682                                 // Check to see if we already have parsed the variables for the given scope
4683 
4684                                 Block *block = sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
4685                                 if (block == NULL)
4686                                 {
4687                                     // This must be a specification or abstract origin with
4688                                     // a concrete block counterpart in the current function. We need
4689                                     // to find the concrete block so we can correctly add the
4690                                     // variable to it
4691                                     const DWARFDIE concrete_block_die = FindBlockContainingSpecification (DIERef(sc.function->GetID(), this),
4692                                                                                                           sc_parent_die.GetOffset());
4693                                     if (concrete_block_die)
4694                                         block = sc.function->GetBlock(true).FindBlockByID(concrete_block_die.GetID());
4695                                 }
4696 
4697                                 if (block != NULL)
4698                                 {
4699                                     const bool can_create = false;
4700                                     variable_list_sp = block->GetBlockVariableList (can_create);
4701                                     if (variable_list_sp.get() == NULL)
4702                                     {
4703                                         variable_list_sp.reset(new VariableList());
4704                                         block->SetVariableList(variable_list_sp);
4705                                     }
4706                                 }
4707                             }
4708                             break;
4709 
4710                         default:
4711                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
4712                                                                         orig_die.GetID(),
4713                                                                         orig_die.GetTagAsCString());
4714                             break;
4715                     }
4716                 }
4717 
4718                 if (variable_list_sp)
4719                 {
4720                     VariableSP var_sp (ParseVariableDIE(sc, die, func_low_pc));
4721                     if (var_sp)
4722                     {
4723                         variable_list_sp->AddVariableIfUnique (var_sp);
4724                         if (cc_variable_list)
4725                             cc_variable_list->AddVariableIfUnique (var_sp);
4726                         ++vars_added;
4727                     }
4728                 }
4729             }
4730         }
4731 
4732         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
4733 
4734         if (!skip_children && parse_children && die.HasChildren())
4735         {
4736             vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, true, cc_variable_list);
4737         }
4738 
4739         if (parse_siblings)
4740             die = die.GetSibling();
4741         else
4742             die.Clear();
4743     }
4744     return vars_added;
4745 }
4746 
4747 //------------------------------------------------------------------
4748 // PluginInterface protocol
4749 //------------------------------------------------------------------
4750 ConstString
4751 SymbolFileDWARF::GetPluginName()
4752 {
4753     return GetPluginNameStatic();
4754 }
4755 
4756 uint32_t
4757 SymbolFileDWARF::GetPluginVersion()
4758 {
4759     return 1;
4760 }
4761 
4762 void
4763 SymbolFileDWARF::DumpIndexes ()
4764 {
4765     StreamFile s(stdout, false);
4766 
4767     s.Printf ("DWARF index for (%s) '%s':",
4768               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
4769               GetObjectFile()->GetFileSpec().GetPath().c_str());
4770     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
4771     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
4772     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
4773     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
4774     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
4775     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
4776     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
4777     s.Printf("\nNamespaces:\n");            m_namespace_index.Dump (&s);
4778 }
4779 
4780 
4781 SymbolFileDWARFDebugMap *
4782 SymbolFileDWARF::GetDebugMapSymfile()
4783 {
4784     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
4785     {
4786         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
4787         if (module_sp)
4788         {
4789             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
4790             if (sym_vendor)
4791                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
4792         }
4793     }
4794     return m_debug_map_symfile;
4795 }
4796 
4797 DWARFExpression::LocationListFormat
4798 SymbolFileDWARF::GetLocationListFormat() const
4799 {
4800     return DWARFExpression::RegularLocationList;
4801 }
4802