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