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             const dw_offset_t stmt_list = cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list, DW_INVALID_OFFSET);
1067             if (stmt_list != DW_INVALID_OFFSET)
1068             {
1069                 // All file indexes in DWARF are one based and a file of index zero is
1070                 // supposed to be the compile unit itself.
1071                 support_files.Append (*sc.comp_unit);
1072                 return DWARFDebugLine::ParseSupportFiles(sc.comp_unit->GetModule(),
1073                                                          get_debug_line_data(),
1074                                                          cu_comp_dir,
1075                                                          stmt_list,
1076                                                          support_files);
1077             }
1078         }
1079     }
1080     return false;
1081 }
1082 
1083 bool
1084 SymbolFileDWARF::ParseImportedModules (const lldb_private::SymbolContext &sc, std::vector<lldb_private::ConstString> &imported_modules)
1085 {
1086     assert (sc.comp_unit);
1087     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1088     if (dwarf_cu)
1089     {
1090         if (ClangModulesDeclVendor::LanguageSupportsClangModules(sc.comp_unit->GetLanguage()))
1091         {
1092             UpdateExternalModuleListIfNeeded();
1093 
1094             if (sc.comp_unit)
1095             {
1096                 const DWARFDIE die = dwarf_cu->GetCompileUnitDIEOnly();
1097 
1098                 if (die)
1099                 {
1100                     for (DWARFDIE child_die = die.GetFirstChild();
1101                          child_die;
1102                          child_die = child_die.GetSibling())
1103                     {
1104                         if (child_die.Tag() == DW_TAG_imported_declaration)
1105                         {
1106                             if (DWARFDIE module_die = child_die.GetReferencedDIE(DW_AT_import))
1107                             {
1108                                 if (module_die.Tag() == DW_TAG_module)
1109                                 {
1110                                     if (const char *name = module_die.GetAttributeValueAsString(DW_AT_name, nullptr))
1111                                     {
1112                                         ConstString const_name(name);
1113                                         imported_modules.push_back(const_name);
1114                                     }
1115                                 }
1116                             }
1117                         }
1118                     }
1119                 }
1120             }
1121             else
1122             {
1123                 for (const auto &pair : m_external_type_modules)
1124                 {
1125                     imported_modules.push_back(pair.first);
1126                 }
1127             }
1128         }
1129     }
1130     return false;
1131 }
1132 
1133 struct ParseDWARFLineTableCallbackInfo
1134 {
1135     LineTable* line_table;
1136     std::unique_ptr<LineSequence> sequence_ap;
1137     lldb::addr_t addr_mask;
1138 };
1139 
1140 //----------------------------------------------------------------------
1141 // ParseStatementTableCallback
1142 //----------------------------------------------------------------------
1143 static void
1144 ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State& state, void* userData)
1145 {
1146     if (state.row == DWARFDebugLine::State::StartParsingLineTable)
1147     {
1148         // Just started parsing the line table
1149     }
1150     else if (state.row == DWARFDebugLine::State::DoneParsingLineTable)
1151     {
1152         // Done parsing line table, nothing to do for the cleanup
1153     }
1154     else
1155     {
1156         ParseDWARFLineTableCallbackInfo* info = (ParseDWARFLineTableCallbackInfo*)userData;
1157         LineTable* line_table = info->line_table;
1158 
1159         // If this is our first time here, we need to create a
1160         // sequence container.
1161         if (!info->sequence_ap.get())
1162         {
1163             info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1164             assert(info->sequence_ap.get());
1165         }
1166         line_table->AppendLineEntryToSequence (info->sequence_ap.get(),
1167                                                state.address & info->addr_mask,
1168                                                state.line,
1169                                                state.column,
1170                                                state.file,
1171                                                state.is_stmt,
1172                                                state.basic_block,
1173                                                state.prologue_end,
1174                                                state.epilogue_begin,
1175                                                state.end_sequence);
1176         if (state.end_sequence)
1177         {
1178             // First, put the current sequence into the line table.
1179             line_table->InsertSequence(info->sequence_ap.get());
1180             // Then, empty it to prepare for the next sequence.
1181             info->sequence_ap->Clear();
1182         }
1183     }
1184 }
1185 
1186 bool
1187 SymbolFileDWARF::ParseCompileUnitLineTable (const SymbolContext &sc)
1188 {
1189     assert (sc.comp_unit);
1190     if (sc.comp_unit->GetLineTable() != NULL)
1191         return true;
1192 
1193     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1194     if (dwarf_cu)
1195     {
1196         const DWARFDIE dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1197         if (dwarf_cu_die)
1198         {
1199             const dw_offset_t cu_line_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_stmt_list, DW_INVALID_OFFSET);
1200             if (cu_line_offset != DW_INVALID_OFFSET)
1201             {
1202                 std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1203                 if (line_table_ap.get())
1204                 {
1205                     ParseDWARFLineTableCallbackInfo info;
1206                     info.line_table = line_table_ap.get();
1207 
1208                     /*
1209                      * MIPS:
1210                      * The SymbolContext may not have a valid target, thus we may not be able
1211                      * to call Address::GetOpcodeLoadAddress() which would clear the bit #0
1212                      * for MIPS. Use ArchSpec to clear the bit #0.
1213                     */
1214                     ArchSpec arch;
1215                     GetObjectFile()->GetArchitecture(arch);
1216                     switch (arch.GetMachine())
1217                     {
1218                     case llvm::Triple::mips:
1219                     case llvm::Triple::mipsel:
1220                     case llvm::Triple::mips64:
1221                     case llvm::Triple::mips64el:
1222                         info.addr_mask = ~((lldb::addr_t)1);
1223                         break;
1224                     default:
1225                         info.addr_mask = ~((lldb::addr_t)0);
1226                         break;
1227                     }
1228 
1229                     lldb::offset_t offset = cu_line_offset;
1230                     DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info);
1231                     if (m_debug_map_symfile)
1232                     {
1233                         // We have an object file that has a line table with addresses
1234                         // that are not linked. We need to link the line table and convert
1235                         // the addresses that are relative to the .o file into addresses
1236                         // for the main executable.
1237                         sc.comp_unit->SetLineTable (m_debug_map_symfile->LinkOSOLineTable (this, line_table_ap.get()));
1238                     }
1239                     else
1240                     {
1241                         sc.comp_unit->SetLineTable(line_table_ap.release());
1242                         return true;
1243                     }
1244                 }
1245             }
1246         }
1247     }
1248     return false;
1249 }
1250 
1251 lldb_private::DebugMacrosSP
1252 SymbolFileDWARF::ParseDebugMacros(lldb::offset_t *offset)
1253 {
1254     auto iter = m_debug_macros_map.find(*offset);
1255     if (iter != m_debug_macros_map.end())
1256         return iter->second;
1257 
1258     const DWARFDataExtractor &debug_macro_data = get_debug_macro_data();
1259     if (debug_macro_data.GetByteSize() == 0)
1260         return DebugMacrosSP();
1261 
1262     lldb_private::DebugMacrosSP debug_macros_sp(new lldb_private::DebugMacros());
1263     m_debug_macros_map[*offset] = debug_macros_sp;
1264 
1265     const DWARFDebugMacroHeader &header = DWARFDebugMacroHeader::ParseHeader(debug_macro_data, offset);
1266     DWARFDebugMacroEntry::ReadMacroEntries(
1267         debug_macro_data, get_debug_str_data(), header.OffsetIs64Bit(), offset, this, debug_macros_sp);
1268 
1269     return debug_macros_sp;
1270 }
1271 
1272 bool
1273 SymbolFileDWARF::ParseCompileUnitDebugMacros(const SymbolContext& sc)
1274 {
1275     assert (sc.comp_unit);
1276 
1277     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1278     if (dwarf_cu == nullptr)
1279         return false;
1280 
1281     const DWARFDIE dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1282     if (!dwarf_cu_die)
1283         return false;
1284 
1285     lldb::offset_t sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_macros, DW_INVALID_OFFSET);
1286     if (sect_offset == DW_INVALID_OFFSET)
1287         sect_offset = dwarf_cu_die.GetAttributeValueAsUnsigned(DW_AT_GNU_macros, DW_INVALID_OFFSET);
1288     if (sect_offset == DW_INVALID_OFFSET)
1289         return false;
1290 
1291     sc.comp_unit->SetDebugMacros(ParseDebugMacros(&sect_offset));
1292 
1293     return true;
1294 }
1295 
1296 size_t
1297 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext& sc,
1298                                       Block *parent_block,
1299                                       const DWARFDIE &orig_die,
1300                                       addr_t subprogram_low_pc,
1301                                       uint32_t depth)
1302 {
1303     size_t blocks_added = 0;
1304     DWARFDIE die = orig_die;
1305     while (die)
1306     {
1307         dw_tag_t tag = die.Tag();
1308 
1309         switch (tag)
1310         {
1311         case DW_TAG_inlined_subroutine:
1312         case DW_TAG_subprogram:
1313         case DW_TAG_lexical_block:
1314             {
1315                 Block *block = NULL;
1316                 if (tag == DW_TAG_subprogram)
1317                 {
1318                     // Skip any DW_TAG_subprogram DIEs that are inside
1319                     // of a normal or inlined functions. These will be
1320                     // parsed on their own as separate entities.
1321 
1322                     if (depth > 0)
1323                         break;
1324 
1325                     block = parent_block;
1326                 }
1327                 else
1328                 {
1329                     BlockSP block_sp(new Block (die.GetID()));
1330                     parent_block->AddChild(block_sp);
1331                     block = block_sp.get();
1332                 }
1333                 DWARFRangeList ranges;
1334                 const char *name = NULL;
1335                 const char *mangled_name = NULL;
1336 
1337                 int decl_file = 0;
1338                 int decl_line = 0;
1339                 int decl_column = 0;
1340                 int call_file = 0;
1341                 int call_line = 0;
1342                 int call_column = 0;
1343                 if (die.GetDIENamesAndRanges (name,
1344                                               mangled_name,
1345                                               ranges,
1346                                               decl_file, decl_line, decl_column,
1347                                               call_file, call_line, call_column, nullptr))
1348                 {
1349                     if (tag == DW_TAG_subprogram)
1350                     {
1351                         assert (subprogram_low_pc == LLDB_INVALID_ADDRESS);
1352                         subprogram_low_pc = ranges.GetMinRangeBase(0);
1353                     }
1354                     else if (tag == DW_TAG_inlined_subroutine)
1355                     {
1356                         // We get called here for inlined subroutines in two ways.
1357                         // The first time is when we are making the Function object
1358                         // for this inlined concrete instance.  Since we're creating a top level block at
1359                         // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we need to
1360                         // adjust the containing address.
1361                         // The second time is when we are parsing the blocks inside the function that contains
1362                         // the inlined concrete instance.  Since these will be blocks inside the containing "real"
1363                         // function the offset will be for that function.
1364                         if (subprogram_low_pc == LLDB_INVALID_ADDRESS)
1365                         {
1366                             subprogram_low_pc = ranges.GetMinRangeBase(0);
1367                         }
1368                     }
1369 
1370                     const size_t num_ranges = ranges.GetSize();
1371                     for (size_t i = 0; i<num_ranges; ++i)
1372                     {
1373                         const DWARFRangeList::Entry &range = ranges.GetEntryRef (i);
1374                         const addr_t range_base = range.GetRangeBase();
1375                         if (range_base >= subprogram_low_pc)
1376                             block->AddRange(Block::Range (range_base - subprogram_low_pc, range.GetByteSize()));
1377                         else
1378                         {
1379                             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",
1380                                                                        block->GetID(),
1381                                                                        range_base,
1382                                                                        range.GetRangeEnd(),
1383                                                                        subprogram_low_pc);
1384                         }
1385                     }
1386                     block->FinalizeRanges ();
1387 
1388                     if (tag != DW_TAG_subprogram && (name != NULL || mangled_name != NULL))
1389                     {
1390                         std::unique_ptr<Declaration> decl_ap;
1391                         if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1392                             decl_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1393                                                           decl_line, decl_column));
1394 
1395                         std::unique_ptr<Declaration> call_ap;
1396                         if (call_file != 0 || call_line != 0 || call_column != 0)
1397                             call_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1398                                                           call_line, call_column));
1399 
1400                         block->SetInlinedFunctionInfo (name, mangled_name, decl_ap.get(), call_ap.get());
1401                     }
1402 
1403                     ++blocks_added;
1404 
1405                     if (die.HasChildren())
1406                     {
1407                         blocks_added += ParseFunctionBlocks (sc,
1408                                                              block,
1409                                                              die.GetFirstChild(),
1410                                                              subprogram_low_pc,
1411                                                              depth + 1);
1412                     }
1413                 }
1414             }
1415             break;
1416         default:
1417             break;
1418         }
1419 
1420         // Only parse siblings of the block if we are not at depth zero. A depth
1421         // of zero indicates we are currently parsing the top level
1422         // DW_TAG_subprogram DIE
1423 
1424         if (depth == 0)
1425             die.Clear();
1426         else
1427             die = die.GetSibling();
1428     }
1429     return blocks_added;
1430 }
1431 
1432 bool
1433 SymbolFileDWARF::ClassOrStructIsVirtual (const DWARFDIE &parent_die)
1434 {
1435     if (parent_die)
1436     {
1437         for (DWARFDIE die = parent_die.GetFirstChild(); die; die = die.GetSibling())
1438         {
1439             dw_tag_t tag = die.Tag();
1440             bool check_virtuality = false;
1441             switch (tag)
1442             {
1443                 case DW_TAG_inheritance:
1444                 case DW_TAG_subprogram:
1445                     check_virtuality = true;
1446                     break;
1447                 default:
1448                     break;
1449             }
1450             if (check_virtuality)
1451             {
1452                 if (die.GetAttributeValueAsUnsigned(DW_AT_virtuality, 0) != 0)
1453                     return true;
1454             }
1455         }
1456     }
1457     return false;
1458 }
1459 
1460 void
1461 SymbolFileDWARF::ParseDeclsForContext (CompilerDeclContext decl_ctx)
1462 {
1463     TypeSystem *type_system = decl_ctx.GetTypeSystem();
1464     DWARFASTParser *ast_parser = type_system->GetDWARFParser();
1465     std::vector<DWARFDIE> decl_ctx_die_list = ast_parser->GetDIEForDeclContext(decl_ctx);
1466 
1467     for (DWARFDIE decl_ctx_die : decl_ctx_die_list)
1468         for (DWARFDIE decl = decl_ctx_die.GetFirstChild(); decl; decl = decl.GetSibling())
1469             ast_parser->GetDeclForUIDFromDWARF(decl);
1470 }
1471 
1472 CompilerDecl
1473 SymbolFileDWARF::GetDeclForUID (lldb::user_id_t type_uid)
1474 {
1475     if (UserIDMatches(type_uid))
1476     {
1477         DWARFDebugInfo* debug_info = DebugInfo();
1478         if (debug_info)
1479         {
1480             DWARFDIE die = debug_info->GetDIE(DIERef(type_uid));
1481             if (die)
1482             {
1483                 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
1484                 if (dwarf_ast)
1485                     return dwarf_ast->GetDeclForUIDFromDWARF(die);
1486             }
1487         }
1488     }
1489     return CompilerDecl();
1490 }
1491 
1492 CompilerDeclContext
1493 SymbolFileDWARF::GetDeclContextForUID (lldb::user_id_t type_uid)
1494 {
1495     if (UserIDMatches(type_uid))
1496     {
1497         DWARFDebugInfo* debug_info = DebugInfo();
1498         if (debug_info)
1499         {
1500             DWARFDIE die = debug_info->GetDIE(DIERef(type_uid));
1501             if (die)
1502             {
1503                 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
1504                 if (dwarf_ast)
1505                     return dwarf_ast->GetDeclContextForUIDFromDWARF(die);
1506             }
1507         }
1508     }
1509     return CompilerDeclContext();
1510 }
1511 
1512 CompilerDeclContext
1513 SymbolFileDWARF::GetDeclContextContainingUID (lldb::user_id_t type_uid)
1514 {
1515     if (UserIDMatches(type_uid))
1516     {
1517         DWARFDebugInfo* debug_info = DebugInfo();
1518         if (debug_info)
1519         {
1520             DWARFDIE die = debug_info->GetDIE(DIERef(type_uid));
1521             if (die)
1522             {
1523                 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
1524                 if (dwarf_ast)
1525                     return dwarf_ast->GetDeclContextContainingUIDFromDWARF(die);
1526             }
1527         }
1528     }
1529     return CompilerDeclContext();
1530 }
1531 
1532 
1533 Type*
1534 SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
1535 {
1536     if (UserIDMatches(type_uid))
1537     {
1538         DWARFDebugInfo* debug_info = DebugInfo();
1539         if (debug_info)
1540         {
1541             DWARFDIE type_die = debug_info->GetDIE (DIERef(type_uid));
1542             if (type_die)
1543             {
1544                 const bool assert_not_being_parsed = true;
1545                 return ResolveTypeUID (type_die, assert_not_being_parsed);
1546             }
1547         }
1548     }
1549     return NULL;
1550 }
1551 
1552 Type*
1553 SymbolFileDWARF::ResolveTypeUID (const DWARFDIE &die, bool assert_not_being_parsed)
1554 {
1555     if (die)
1556     {
1557         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
1558         if (log)
1559             GetObjectFile()->GetModule()->LogMessage (log,
1560                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
1561                                                       die.GetOffset(),
1562                                                       die.GetTagAsCString(),
1563                                                       die.GetName());
1564 
1565         // We might be coming in in the middle of a type tree (a class
1566         // withing a class, an enum within a class), so parse any needed
1567         // parent DIEs before we get to this one...
1568         DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE (die);
1569         if (decl_ctx_die)
1570         {
1571             if (log)
1572             {
1573                 switch (decl_ctx_die.Tag())
1574                 {
1575                     case DW_TAG_structure_type:
1576                     case DW_TAG_union_type:
1577                     case DW_TAG_class_type:
1578                     {
1579                         // Get the type, which could be a forward declaration
1580                         if (log)
1581                             GetObjectFile()->GetModule()->LogMessage (log,
1582                                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
1583                                                                       die.GetOffset(),
1584                                                                       die.GetTagAsCString(),
1585                                                                       die.GetName(),
1586                                                                       decl_ctx_die.GetOffset());
1587                     }
1588                     break;
1589 
1590                     default:
1591                         break;
1592                 }
1593             }
1594         }
1595         return ResolveType (die);
1596     }
1597     return NULL;
1598 }
1599 
1600 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
1601 // SymbolFileDWARF objects to detect if this DWARF file is the one that
1602 // can resolve a compiler_type.
1603 bool
1604 SymbolFileDWARF::HasForwardDeclForClangType (const CompilerType &compiler_type)
1605 {
1606     CompilerType compiler_type_no_qualifiers = ClangASTContext::RemoveFastQualifiers(compiler_type);
1607     if (GetForwardDeclClangTypeToDie().count (compiler_type_no_qualifiers.GetOpaqueQualType()))
1608     {
1609         return true;
1610     }
1611     TypeSystem *type_system = compiler_type.GetTypeSystem();
1612     if (type_system)
1613     {
1614         DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
1615         if (dwarf_ast)
1616             return dwarf_ast->CanCompleteType(compiler_type);
1617     }
1618     return false;
1619 }
1620 
1621 
1622 bool
1623 SymbolFileDWARF::CompleteType (CompilerType &compiler_type)
1624 {
1625     lldb_private::Mutex::Locker locker(GetObjectFile()->GetModule()->GetMutex());
1626 
1627     TypeSystem *type_system = compiler_type.GetTypeSystem();
1628     if (type_system)
1629     {
1630         DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
1631         if (dwarf_ast && dwarf_ast->CanCompleteType(compiler_type))
1632             return dwarf_ast->CompleteType(compiler_type);
1633     }
1634 
1635     // We have a struct/union/class/enum that needs to be fully resolved.
1636     CompilerType compiler_type_no_qualifiers = ClangASTContext::RemoveFastQualifiers(compiler_type);
1637     auto die_it = GetForwardDeclClangTypeToDie().find (compiler_type_no_qualifiers.GetOpaqueQualType());
1638     if (die_it == GetForwardDeclClangTypeToDie().end())
1639     {
1640         // We have already resolved this type...
1641         return true;
1642     }
1643 
1644     DWARFDebugInfo* debug_info = DebugInfo();
1645     DWARFDIE dwarf_die = debug_info->GetDIE(die_it->getSecond());
1646 
1647     assert(UserIDMatches(die_it->getSecond().GetUID()) && "CompleteType called on the wrong SymbolFile");
1648 
1649     // Once we start resolving this type, remove it from the forward declaration
1650     // map in case anyone child members or other types require this type to get resolved.
1651     // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
1652     // are done.
1653     GetForwardDeclClangTypeToDie().erase (die_it);
1654 
1655     Type *type = GetDIEToType().lookup (dwarf_die.GetDIE());
1656 
1657     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
1658     if (log)
1659         GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
1660                                                                   "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
1661                                                                   dwarf_die.GetID(),
1662                                                                   dwarf_die.GetTagAsCString(),
1663                                                                   type->GetName().AsCString());
1664     assert (compiler_type);
1665     DWARFASTParser *dwarf_ast = dwarf_die.GetDWARFParser();
1666     if (dwarf_ast)
1667         return dwarf_ast->CompleteTypeFromDWARF (dwarf_die, type, compiler_type);
1668     return false;
1669 }
1670 
1671 Type*
1672 SymbolFileDWARF::ResolveType (const DWARFDIE &die, bool assert_not_being_parsed, bool resolve_function_context)
1673 {
1674     if (die)
1675     {
1676         Type *type = GetDIEToType().lookup (die.GetDIE());
1677 
1678         if (type == NULL)
1679             type = GetTypeForDIE (die, resolve_function_context).get();
1680 
1681         if (assert_not_being_parsed)
1682         {
1683             if (type != DIE_IS_BEING_PARSED)
1684                 return type;
1685 
1686             GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
1687                                                        die.GetOffset(),
1688                                                        die.GetTagAsCString(),
1689                                                        die.GetName());
1690 
1691         }
1692         else
1693             return type;
1694     }
1695     return nullptr;
1696 }
1697 
1698 CompileUnit*
1699 SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
1700 {
1701     // Check if the symbol vendor already knows about this compile unit?
1702     if (dwarf_cu->GetUserData() == NULL)
1703     {
1704         // The symbol vendor doesn't know about this compile unit, we
1705         // need to parse and add it to the symbol vendor object.
1706         return ParseCompileUnit(dwarf_cu, cu_idx).get();
1707     }
1708     return (CompileUnit*)dwarf_cu->GetUserData();
1709 }
1710 
1711 size_t
1712 SymbolFileDWARF::GetObjCMethodDIEOffsets (ConstString class_name, DIEArray &method_die_offsets)
1713 {
1714     method_die_offsets.clear();
1715     if (m_using_apple_tables)
1716     {
1717         if (m_apple_objc_ap.get())
1718             m_apple_objc_ap->FindByName(class_name.GetCString(), method_die_offsets);
1719     }
1720     else
1721     {
1722         if (!m_indexed)
1723             Index ();
1724 
1725         m_objc_class_selectors_index.Find (class_name, method_die_offsets);
1726     }
1727     return method_die_offsets.size();
1728 }
1729 
1730 bool
1731 SymbolFileDWARF::GetFunction (const DWARFDIE &die, SymbolContext& sc)
1732 {
1733     sc.Clear(false);
1734 
1735     if (die)
1736     {
1737         // Check if the symbol vendor already knows about this compile unit?
1738         sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
1739 
1740         sc.function = sc.comp_unit->FindFunctionByUID (die.GetID()).get();
1741         if (sc.function == NULL)
1742             sc.function = ParseCompileUnitFunction(sc, die);
1743 
1744         if (sc.function)
1745         {
1746             sc.module_sp = sc.function->CalculateSymbolContextModule();
1747             return true;
1748         }
1749     }
1750 
1751     return false;
1752 }
1753 
1754 lldb::ModuleSP
1755 SymbolFileDWARF::GetDWOModule (ConstString name)
1756 {
1757     UpdateExternalModuleListIfNeeded();
1758     const auto &pos = m_external_type_modules.find(name);
1759     if (pos != m_external_type_modules.end())
1760         return pos->second;
1761     else
1762         return lldb::ModuleSP();
1763 }
1764 
1765 void
1766 SymbolFileDWARF::UpdateExternalModuleListIfNeeded()
1767 {
1768     if (m_fetched_external_modules)
1769         return;
1770     m_fetched_external_modules = true;
1771 
1772     DWARFDebugInfo * debug_info = DebugInfo();
1773 
1774     const uint32_t num_compile_units = GetNumCompileUnits();
1775     for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
1776     {
1777         DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
1778 
1779         const DWARFDIE die = dwarf_cu->GetCompileUnitDIEOnly();
1780         if (die && die.HasChildren() == false)
1781         {
1782             const char *name = die.GetAttributeValueAsString(DW_AT_name, nullptr);
1783 
1784             if (name)
1785             {
1786                 ConstString const_name(name);
1787                 if (m_external_type_modules.find(const_name) == m_external_type_modules.end())
1788                 {
1789                     ModuleSP module_sp;
1790                     const char *dwo_path = die.GetAttributeValueAsString(DW_AT_GNU_dwo_name, nullptr);
1791                     if (dwo_path)
1792                     {
1793                         ModuleSpec dwo_module_spec;
1794                         dwo_module_spec.GetFileSpec().SetFile(dwo_path, false);
1795                         dwo_module_spec.GetArchitecture() = m_obj_file->GetModule()->GetArchitecture();
1796                         //printf ("Loading dwo = '%s'\n", dwo_path);
1797                         Error error = ModuleList::GetSharedModule (dwo_module_spec, module_sp, NULL, NULL, NULL);
1798                     }
1799                     m_external_type_modules[const_name] = module_sp;
1800                 }
1801             }
1802         }
1803     }
1804 }
1805 
1806 SymbolFileDWARF::GlobalVariableMap &
1807 SymbolFileDWARF::GetGlobalAranges()
1808 {
1809     if (!m_global_aranges_ap)
1810     {
1811         m_global_aranges_ap.reset (new GlobalVariableMap());
1812 
1813         ModuleSP module_sp = GetObjectFile()->GetModule();
1814         if (module_sp)
1815         {
1816             const size_t num_cus = module_sp->GetNumCompileUnits();
1817             for (size_t i = 0; i < num_cus; ++i)
1818             {
1819                 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
1820                 if (cu_sp)
1821                 {
1822                     VariableListSP globals_sp = cu_sp->GetVariableList(true);
1823                     if (globals_sp)
1824                     {
1825                         const size_t num_globals = globals_sp->GetSize();
1826                         for (size_t g = 0; g < num_globals; ++g)
1827                         {
1828                             VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
1829                             if (var_sp && !var_sp->GetLocationIsConstantValueData())
1830                             {
1831                                 const DWARFExpression &location = var_sp->LocationExpression();
1832                                 Value location_result;
1833                                 Error error;
1834                                 if (location.Evaluate(nullptr, nullptr, nullptr, LLDB_INVALID_ADDRESS, nullptr, nullptr, location_result, &error))
1835                                 {
1836                                     if (location_result.GetValueType() == Value::eValueTypeFileAddress)
1837                                     {
1838                                         lldb::addr_t file_addr = location_result.GetScalar().ULongLong();
1839                                         lldb::addr_t byte_size = 1;
1840                                         if (var_sp->GetType())
1841                                             byte_size = var_sp->GetType()->GetByteSize();
1842                                         m_global_aranges_ap->Append(GlobalVariableMap::Entry(file_addr, byte_size, var_sp.get()));
1843                                     }
1844                                 }
1845                             }
1846                         }
1847                     }
1848                 }
1849             }
1850         }
1851         m_global_aranges_ap->Sort();
1852     }
1853     return *m_global_aranges_ap;
1854 }
1855 
1856 
1857 uint32_t
1858 SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
1859 {
1860     Timer scoped_timer(__PRETTY_FUNCTION__,
1861                        "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)",
1862                        static_cast<void*>(so_addr.GetSection().get()),
1863                        so_addr.GetOffset(), resolve_scope);
1864     uint32_t resolved = 0;
1865     if (resolve_scope & (   eSymbolContextCompUnit  |
1866                             eSymbolContextFunction  |
1867                             eSymbolContextBlock     |
1868                             eSymbolContextLineEntry |
1869                             eSymbolContextVariable  ))
1870     {
1871         lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
1872 
1873         DWARFDebugInfo* debug_info = DebugInfo();
1874         if (debug_info)
1875         {
1876             const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
1877             if (cu_offset == DW_INVALID_OFFSET)
1878             {
1879                 // Global variables are not in the compile unit address ranges. The only way to
1880                 // currently find global variables is to iterate over the .debug_pubnames or the
1881                 // __apple_names table and find all items in there that point to DW_TAG_variable
1882                 // DIEs and then find the address that matches.
1883                 if (resolve_scope & eSymbolContextVariable)
1884                 {
1885                     GlobalVariableMap &map = GetGlobalAranges();
1886                     const GlobalVariableMap::Entry *entry = map.FindEntryThatContains(file_vm_addr);
1887                     if (entry && entry->data)
1888                     {
1889                         Variable *variable = entry->data;
1890                         SymbolContextScope *scc = variable->GetSymbolContextScope();
1891                         if (scc)
1892                         {
1893                             scc->CalculateSymbolContext(&sc);
1894                             sc.variable = variable;
1895                         }
1896                         return sc.GetResolvedMask();
1897                     }
1898                 }
1899             }
1900             else
1901             {
1902                 uint32_t cu_idx = DW_INVALID_INDEX;
1903                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx);
1904                 if (dwarf_cu)
1905                 {
1906                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
1907                     if (sc.comp_unit)
1908                     {
1909                         resolved |= eSymbolContextCompUnit;
1910 
1911                         bool force_check_line_table = false;
1912                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
1913                         {
1914                             DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
1915                             DWARFDIE block_die;
1916                             if (function_die)
1917                             {
1918                                 sc.function = sc.comp_unit->FindFunctionByUID (function_die.GetID()).get();
1919                                 if (sc.function == NULL)
1920                                     sc.function = ParseCompileUnitFunction(sc, function_die);
1921 
1922                                 if (sc.function && (resolve_scope & eSymbolContextBlock))
1923                                     block_die = function_die.LookupDeepestBlock(file_vm_addr);
1924                             }
1925                             else
1926                             {
1927                                 // We might have had a compile unit that had discontiguous
1928                                 // address ranges where the gaps are symbols that don't have
1929                                 // any debug info. Discontiguous compile unit address ranges
1930                                 // should only happen when there aren't other functions from
1931                                 // other compile units in these gaps. This helps keep the size
1932                                 // of the aranges down.
1933                                 force_check_line_table = true;
1934                             }
1935 
1936                             if (sc.function != NULL)
1937                             {
1938                                 resolved |= eSymbolContextFunction;
1939 
1940                                 if (resolve_scope & eSymbolContextBlock)
1941                                 {
1942                                     Block& block = sc.function->GetBlock (true);
1943 
1944                                     if (block_die)
1945                                         sc.block = block.FindBlockByID (block_die.GetID());
1946                                     else
1947                                         sc.block = block.FindBlockByID (function_die.GetID());
1948                                     if (sc.block)
1949                                         resolved |= eSymbolContextBlock;
1950                                 }
1951                             }
1952                         }
1953 
1954                         if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table)
1955                         {
1956                             LineTable *line_table = sc.comp_unit->GetLineTable();
1957                             if (line_table != NULL)
1958                             {
1959                                 // And address that makes it into this function should be in terms
1960                                 // of this debug file if there is no debug map, or it will be an
1961                                 // address in the .o file which needs to be fixed up to be in terms
1962                                 // of the debug map executable. Either way, calling FixupAddress()
1963                                 // will work for us.
1964                                 Address exe_so_addr (so_addr);
1965                                 if (FixupAddress(exe_so_addr))
1966                                 {
1967                                     if (line_table->FindLineEntryByAddress (exe_so_addr, sc.line_entry))
1968                                     {
1969                                         resolved |= eSymbolContextLineEntry;
1970                                     }
1971                                 }
1972                             }
1973                         }
1974 
1975                         if (force_check_line_table && !(resolved & eSymbolContextLineEntry))
1976                         {
1977                             // We might have had a compile unit that had discontiguous
1978                             // address ranges where the gaps are symbols that don't have
1979                             // any debug info. Discontiguous compile unit address ranges
1980                             // should only happen when there aren't other functions from
1981                             // other compile units in these gaps. This helps keep the size
1982                             // of the aranges down.
1983                             sc.comp_unit = NULL;
1984                             resolved &= ~eSymbolContextCompUnit;
1985                         }
1986                     }
1987                     else
1988                     {
1989                         GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
1990                                                                      cu_offset,
1991                                                                      cu_idx);
1992                     }
1993                 }
1994             }
1995         }
1996     }
1997     return resolved;
1998 }
1999 
2000 
2001 
2002 uint32_t
2003 SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
2004 {
2005     const uint32_t prev_size = sc_list.GetSize();
2006     if (resolve_scope & eSymbolContextCompUnit)
2007     {
2008         DWARFDebugInfo* debug_info = DebugInfo();
2009         if (debug_info)
2010         {
2011             uint32_t cu_idx;
2012             DWARFCompileUnit* dwarf_cu = NULL;
2013 
2014             for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
2015             {
2016                 CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2017                 const bool full_match = (bool)file_spec.GetDirectory();
2018                 bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
2019                 if (check_inlines || file_spec_matches_cu_file_spec)
2020                 {
2021                     SymbolContext sc (m_obj_file->GetModule());
2022                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2023                     if (sc.comp_unit)
2024                     {
2025                         uint32_t file_idx = UINT32_MAX;
2026 
2027                         // If we are looking for inline functions only and we don't
2028                         // find it in the support files, we are done.
2029                         if (check_inlines)
2030                         {
2031                             file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2032                             if (file_idx == UINT32_MAX)
2033                                 continue;
2034                         }
2035 
2036                         if (line != 0)
2037                         {
2038                             LineTable *line_table = sc.comp_unit->GetLineTable();
2039 
2040                             if (line_table != NULL && line != 0)
2041                             {
2042                                 // We will have already looked up the file index if
2043                                 // we are searching for inline entries.
2044                                 if (!check_inlines)
2045                                     file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
2046 
2047                                 if (file_idx != UINT32_MAX)
2048                                 {
2049                                     uint32_t found_line;
2050                                     uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
2051                                     found_line = sc.line_entry.line;
2052 
2053                                     while (line_idx != UINT32_MAX)
2054                                     {
2055                                         sc.function = NULL;
2056                                         sc.block = NULL;
2057                                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2058                                         {
2059                                             const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
2060                                             if (file_vm_addr != LLDB_INVALID_ADDRESS)
2061                                             {
2062                                                 DWARFDIE function_die = dwarf_cu->LookupAddress(file_vm_addr);
2063                                                 DWARFDIE block_die;
2064                                                 if (function_die)
2065                                                 {
2066                                                     sc.function = sc.comp_unit->FindFunctionByUID (function_die.GetID()).get();
2067                                                     if (sc.function == NULL)
2068                                                         sc.function = ParseCompileUnitFunction(sc, function_die);
2069 
2070                                                     if (sc.function && (resolve_scope & eSymbolContextBlock))
2071                                                         block_die = function_die.LookupDeepestBlock(file_vm_addr);
2072                                                 }
2073 
2074                                                 if (sc.function != NULL)
2075                                                 {
2076                                                     Block& block = sc.function->GetBlock (true);
2077 
2078                                                     if (block_die)
2079                                                         sc.block = block.FindBlockByID (block_die.GetID());
2080                                                     else if (function_die)
2081                                                         sc.block = block.FindBlockByID (function_die.GetID());
2082                                                 }
2083                                             }
2084                                         }
2085 
2086                                         sc_list.Append(sc);
2087                                         line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
2088                                     }
2089                                 }
2090                             }
2091                             else if (file_spec_matches_cu_file_spec && !check_inlines)
2092                             {
2093                                 // only append the context if we aren't looking for inline call sites
2094                                 // by file and line and if the file spec matches that of the compile unit
2095                                 sc_list.Append(sc);
2096                             }
2097                         }
2098                         else if (file_spec_matches_cu_file_spec && !check_inlines)
2099                         {
2100                             // only append the context if we aren't looking for inline call sites
2101                             // by file and line and if the file spec matches that of the compile unit
2102                             sc_list.Append(sc);
2103                         }
2104 
2105                         if (!check_inlines)
2106                             break;
2107                     }
2108                 }
2109             }
2110         }
2111     }
2112     return sc_list.GetSize() - prev_size;
2113 }
2114 
2115 void
2116 SymbolFileDWARF::Index ()
2117 {
2118     if (m_indexed)
2119         return;
2120     m_indexed = true;
2121     Timer scoped_timer (__PRETTY_FUNCTION__,
2122                         "SymbolFileDWARF::Index (%s)",
2123                         GetObjectFile()->GetFileSpec().GetFilename().AsCString("<Unknown>"));
2124 
2125     DWARFDebugInfo* debug_info = DebugInfo();
2126     if (debug_info)
2127     {
2128         const uint32_t num_compile_units = GetNumCompileUnits();
2129         std::vector<NameToDIE> function_basename_index(num_compile_units);
2130         std::vector<NameToDIE> function_fullname_index(num_compile_units);
2131         std::vector<NameToDIE> function_method_index(num_compile_units);
2132         std::vector<NameToDIE> function_selector_index(num_compile_units);
2133         std::vector<NameToDIE> objc_class_selectors_index(num_compile_units);
2134         std::vector<NameToDIE> global_index(num_compile_units);
2135         std::vector<NameToDIE> type_index(num_compile_units);
2136         std::vector<NameToDIE> namespace_index(num_compile_units);
2137 
2138         auto parser_fn = [this,
2139                           debug_info,
2140                           &function_basename_index,
2141                           &function_fullname_index,
2142                           &function_method_index,
2143                           &function_selector_index,
2144                           &objc_class_selectors_index,
2145                           &global_index,
2146                           &type_index,
2147                           &namespace_index](uint32_t cu_idx)
2148         {
2149             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
2150             bool clear_dies = dwarf_cu->ExtractDIEsIfNeeded(false) > 1;
2151 
2152             dwarf_cu->Index(function_basename_index[cu_idx],
2153                             function_fullname_index[cu_idx],
2154                             function_method_index[cu_idx],
2155                             function_selector_index[cu_idx],
2156                             objc_class_selectors_index[cu_idx],
2157                             global_index[cu_idx],
2158                             type_index[cu_idx],
2159                             namespace_index[cu_idx]);
2160 
2161             // Keep memory down by clearing DIEs if this generate function
2162             // caused them to be parsed
2163             if (clear_dies)
2164                 dwarf_cu->ClearDIEs(true);
2165 
2166             return cu_idx;
2167         };
2168 
2169         TaskRunner<uint32_t> task_runner;
2170         for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
2171             task_runner.AddTask(parser_fn, cu_idx);
2172 
2173         while (true)
2174         {
2175             std::future<uint32_t> f = task_runner.WaitForNextCompletedTask();
2176             if (!f.valid())
2177                 break;
2178             uint32_t cu_idx = f.get();
2179 
2180             m_function_basename_index.Append(function_basename_index[cu_idx]);
2181             m_function_fullname_index.Append(function_fullname_index[cu_idx]);
2182             m_function_method_index.Append(function_method_index[cu_idx]);
2183             m_function_selector_index.Append(function_selector_index[cu_idx]);
2184             m_objc_class_selectors_index.Append(objc_class_selectors_index[cu_idx]);
2185             m_global_index.Append(global_index[cu_idx]);
2186             m_type_index.Append(type_index[cu_idx]);
2187             m_namespace_index.Append(namespace_index[cu_idx]);
2188         }
2189 
2190         TaskPool::RunTasks(
2191             [&]() { m_function_basename_index.Finalize(); },
2192             [&]() { m_function_fullname_index.Finalize(); },
2193             [&]() { m_function_method_index.Finalize(); },
2194             [&]() { m_function_selector_index.Finalize(); },
2195             [&]() { m_objc_class_selectors_index.Finalize(); },
2196             [&]() { m_global_index.Finalize(); },
2197             [&]() { m_type_index.Finalize(); },
2198             [&]() { m_namespace_index.Finalize(); });
2199 
2200 #if defined (ENABLE_DEBUG_PRINTF)
2201         StreamFile s(stdout, false);
2202         s.Printf ("DWARF index for '%s':",
2203                   GetObjectFile()->GetFileSpec().GetPath().c_str());
2204         s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
2205         s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
2206         s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
2207         s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
2208         s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
2209         s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
2210         s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
2211         s.Printf("\nNamespaces:\n")             m_namespace_index.Dump (&s);
2212 #endif
2213     }
2214 }
2215 
2216 bool
2217 SymbolFileDWARF::DeclContextMatchesThisSymbolFile (const lldb_private::CompilerDeclContext *decl_ctx)
2218 {
2219     if (decl_ctx == nullptr || !decl_ctx->IsValid())
2220     {
2221         // Invalid namespace decl which means we aren't matching only things
2222         // in this symbol file, so return true to indicate it matches this
2223         // symbol file.
2224         return true;
2225     }
2226 
2227     TypeSystem *decl_ctx_type_system = decl_ctx->GetTypeSystem();
2228     TypeSystem *type_system = GetTypeSystemForLanguage(decl_ctx_type_system->GetMinimumLanguage(nullptr));
2229     if (decl_ctx_type_system == type_system)
2230         return true;    // The type systems match, return true
2231 
2232     // The namespace AST was valid, and it does not match...
2233     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2234 
2235     if (log)
2236         GetObjectFile()->GetModule()->LogMessage(log, "Valid namespace does not match symbol file");
2237 
2238     return false;
2239 }
2240 
2241 uint32_t
2242 SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const CompilerDeclContext *parent_decl_ctx, bool append, uint32_t max_matches, VariableList& variables)
2243 {
2244     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2245 
2246     if (log)
2247         GetObjectFile()->GetModule()->LogMessage (log,
2248                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", parent_decl_ctx=%p, append=%u, max_matches=%u, variables)",
2249                                                   name.GetCString(),
2250                                                   static_cast<const void*>(parent_decl_ctx),
2251                                                   append, max_matches);
2252 
2253     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2254         return 0;
2255 
2256     DWARFDebugInfo* info = DebugInfo();
2257     if (info == NULL)
2258         return 0;
2259 
2260     // If we aren't appending the results to this list, then clear the list
2261     if (!append)
2262         variables.Clear();
2263 
2264     // Remember how many variables are in the list before we search in case
2265     // we are appending the results to a variable list.
2266     const uint32_t original_size = variables.GetSize();
2267 
2268     DIEArray die_offsets;
2269 
2270     if (m_using_apple_tables)
2271     {
2272         if (m_apple_names_ap.get())
2273         {
2274             const char *name_cstr = name.GetCString();
2275             llvm::StringRef basename;
2276             llvm::StringRef context;
2277 
2278             if (!CPlusPlusLanguage::ExtractContextAndIdentifier(name_cstr, context, basename))
2279                 basename = name_cstr;
2280 
2281             m_apple_names_ap->FindByName (basename.data(), die_offsets);
2282         }
2283     }
2284     else
2285     {
2286         // Index the DWARF if we haven't already
2287         if (!m_indexed)
2288             Index ();
2289 
2290         m_global_index.Find (name, die_offsets);
2291     }
2292 
2293     const size_t num_die_matches = die_offsets.size();
2294     if (num_die_matches)
2295     {
2296         SymbolContext sc;
2297         sc.module_sp = m_obj_file->GetModule();
2298         assert (sc.module_sp);
2299 
2300         DWARFDebugInfo* debug_info = DebugInfo();
2301         bool done = false;
2302         for (size_t i=0; i<num_die_matches && !done; ++i)
2303         {
2304             const DIERef& die_ref = die_offsets[i];
2305             DWARFDIE die = debug_info->GetDIE (die_ref);
2306 
2307             if (die)
2308             {
2309                 switch (die.Tag())
2310                 {
2311                     default:
2312                     case DW_TAG_subprogram:
2313                     case DW_TAG_inlined_subroutine:
2314                     case DW_TAG_try_block:
2315                     case DW_TAG_catch_block:
2316                         break;
2317 
2318                     case DW_TAG_variable:
2319                         {
2320                             sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2321 
2322                             if (parent_decl_ctx)
2323                             {
2324                                 DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2325                                 if (dwarf_ast)
2326                                 {
2327                                     CompilerDeclContext actual_parent_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF (die);
2328                                     if (!actual_parent_decl_ctx || actual_parent_decl_ctx != *parent_decl_ctx)
2329                                         continue;
2330                                 }
2331                             }
2332 
2333                             ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2334 
2335                             if (variables.GetSize() - original_size >= max_matches)
2336                                 done = true;
2337                         }
2338                         break;
2339                 }
2340             }
2341             else
2342             {
2343                 if (m_using_apple_tables)
2344                 {
2345                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
2346                                                                                die_ref.die_offset, name.GetCString());
2347                 }
2348             }
2349         }
2350     }
2351 
2352     // Return the number of variable that were appended to the list
2353     const uint32_t num_matches = variables.GetSize() - original_size;
2354     if (log && num_matches > 0)
2355     {
2356         GetObjectFile()->GetModule()->LogMessage (log,
2357                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", parent_decl_ctx=%p, append=%u, max_matches=%u, variables) => %u",
2358                                                   name.GetCString(),
2359                                                   static_cast<const void*>(parent_decl_ctx),
2360                                                   append, max_matches,
2361                                                   num_matches);
2362     }
2363     return num_matches;
2364 }
2365 
2366 uint32_t
2367 SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
2368 {
2369     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2370 
2371     if (log)
2372     {
2373         GetObjectFile()->GetModule()->LogMessage (log,
2374                                                   "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
2375                                                   regex.GetText(), append,
2376                                                   max_matches);
2377     }
2378 
2379     DWARFDebugInfo* info = DebugInfo();
2380     if (info == NULL)
2381         return 0;
2382 
2383     // If we aren't appending the results to this list, then clear the list
2384     if (!append)
2385         variables.Clear();
2386 
2387     // Remember how many variables are in the list before we search in case
2388     // we are appending the results to a variable list.
2389     const uint32_t original_size = variables.GetSize();
2390 
2391     DIEArray die_offsets;
2392 
2393     if (m_using_apple_tables)
2394     {
2395         if (m_apple_names_ap.get())
2396         {
2397             DWARFMappedHash::DIEInfoArray hash_data_array;
2398             if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
2399                 DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
2400         }
2401     }
2402     else
2403     {
2404         // Index the DWARF if we haven't already
2405         if (!m_indexed)
2406             Index ();
2407 
2408         m_global_index.Find (regex, die_offsets);
2409     }
2410 
2411     SymbolContext sc;
2412     sc.module_sp = m_obj_file->GetModule();
2413     assert (sc.module_sp);
2414 
2415     const size_t num_matches = die_offsets.size();
2416     if (num_matches)
2417     {
2418         DWARFDebugInfo* debug_info = DebugInfo();
2419         for (size_t i=0; i<num_matches; ++i)
2420         {
2421             const DIERef& die_ref = die_offsets[i];
2422             DWARFDIE die = debug_info->GetDIE (die_ref);
2423 
2424             if (die)
2425             {
2426                 sc.comp_unit = GetCompUnitForDWARFCompUnit(die.GetCU(), UINT32_MAX);
2427 
2428                 ParseVariables(sc, die, LLDB_INVALID_ADDRESS, false, false, &variables);
2429 
2430                 if (variables.GetSize() - original_size >= max_matches)
2431                     break;
2432             }
2433             else
2434             {
2435                 if (m_using_apple_tables)
2436                 {
2437                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
2438                                                                                die_ref.die_offset, regex.GetText());
2439                 }
2440             }
2441         }
2442     }
2443 
2444     // Return the number of variable that were appended to the list
2445     return variables.GetSize() - original_size;
2446 }
2447 
2448 
2449 bool
2450 SymbolFileDWARF::ResolveFunction (const DIERef& die_ref,
2451                                   bool include_inlines,
2452                                   SymbolContextList& sc_list)
2453 {
2454     DWARFDIE die = DebugInfo()->GetDIE (die_ref);
2455     return ResolveFunction (die, include_inlines, sc_list);
2456 }
2457 
2458 
2459 bool
2460 SymbolFileDWARF::ResolveFunction (const DWARFDIE &orig_die,
2461                                   bool include_inlines,
2462                                   SymbolContextList& sc_list)
2463 {
2464     SymbolContext sc;
2465 
2466     if (!orig_die)
2467         return false;
2468 
2469     // If we were passed a die that is not a function, just return false...
2470     if (!(orig_die.Tag() == DW_TAG_subprogram || (include_inlines && orig_die.Tag() == DW_TAG_inlined_subroutine)))
2471         return false;
2472 
2473     DWARFDIE die = orig_die;
2474     DWARFDIE inlined_die;
2475     if (die.Tag() == DW_TAG_inlined_subroutine)
2476     {
2477         inlined_die = die;
2478 
2479         while (1)
2480         {
2481             die = die.GetParent();
2482 
2483             if (die)
2484             {
2485                 if (die.Tag() == DW_TAG_subprogram)
2486                     break;
2487             }
2488             else
2489                 break;
2490         }
2491     }
2492     assert (die && die.Tag() == DW_TAG_subprogram);
2493     if (GetFunction (die, sc))
2494     {
2495         Address addr;
2496         // Parse all blocks if needed
2497         if (inlined_die)
2498         {
2499             Block &function_block = sc.function->GetBlock (true);
2500             sc.block = function_block.FindBlockByID (inlined_die.GetID());
2501             if (sc.block == NULL)
2502                 sc.block = function_block.FindBlockByID (inlined_die.GetOffset());
2503             if (sc.block == NULL || sc.block->GetStartAddress (addr) == false)
2504                 addr.Clear();
2505         }
2506         else
2507         {
2508             sc.block = NULL;
2509             addr = sc.function->GetAddressRange().GetBaseAddress();
2510         }
2511 
2512         if (addr.IsValid())
2513         {
2514             sc_list.Append(sc);
2515             return true;
2516         }
2517     }
2518 
2519     return false;
2520 }
2521 
2522 void
2523 SymbolFileDWARF::FindFunctions (const ConstString &name,
2524                                 const NameToDIE &name_to_die,
2525                                 bool include_inlines,
2526                                 SymbolContextList& sc_list)
2527 {
2528     DIEArray die_offsets;
2529     if (name_to_die.Find (name, die_offsets))
2530     {
2531         ParseFunctions (die_offsets, include_inlines, sc_list);
2532     }
2533 }
2534 
2535 
2536 void
2537 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
2538                                 const NameToDIE &name_to_die,
2539                                 bool include_inlines,
2540                                 SymbolContextList& sc_list)
2541 {
2542     DIEArray die_offsets;
2543     if (name_to_die.Find (regex, die_offsets))
2544     {
2545         ParseFunctions (die_offsets, include_inlines, sc_list);
2546     }
2547 }
2548 
2549 
2550 void
2551 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
2552                                 const DWARFMappedHash::MemoryTable &memory_table,
2553                                 bool include_inlines,
2554                                 SymbolContextList& sc_list)
2555 {
2556     DIEArray die_offsets;
2557     DWARFMappedHash::DIEInfoArray hash_data_array;
2558     if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
2559     {
2560         DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
2561         ParseFunctions (die_offsets, include_inlines, sc_list);
2562     }
2563 }
2564 
2565 void
2566 SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
2567                                  bool include_inlines,
2568                                  SymbolContextList& sc_list)
2569 {
2570     const size_t num_matches = die_offsets.size();
2571     if (num_matches)
2572     {
2573         for (size_t i=0; i<num_matches; ++i)
2574             ResolveFunction (die_offsets[i], include_inlines, sc_list);
2575     }
2576 }
2577 
2578 bool
2579 SymbolFileDWARF::DIEInDeclContext (const CompilerDeclContext *decl_ctx,
2580                                    const DWARFDIE &die)
2581 {
2582     // If we have no parent decl context to match this DIE matches, and if the parent
2583     // decl context isn't valid, we aren't trying to look for any particular decl
2584     // context so any die matches.
2585     if (decl_ctx == nullptr || !decl_ctx->IsValid())
2586         return true;
2587 
2588     if (die)
2589     {
2590         DWARFASTParser *dwarf_ast = die.GetDWARFParser();
2591         if (dwarf_ast)
2592         {
2593             CompilerDeclContext actual_decl_ctx = dwarf_ast->GetDeclContextContainingUIDFromDWARF (die);
2594             if (actual_decl_ctx)
2595                 return actual_decl_ctx == *decl_ctx;
2596         }
2597     }
2598     return false;
2599 }
2600 
2601 uint32_t
2602 SymbolFileDWARF::FindFunctions (const ConstString &name,
2603                                 const CompilerDeclContext *parent_decl_ctx,
2604                                 uint32_t name_type_mask,
2605                                 bool include_inlines,
2606                                 bool append,
2607                                 SymbolContextList& sc_list)
2608 {
2609     Timer scoped_timer (__PRETTY_FUNCTION__,
2610                         "SymbolFileDWARF::FindFunctions (name = '%s')",
2611                         name.AsCString());
2612 
2613     // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup()
2614     assert ((name_type_mask & eFunctionNameTypeAuto) == 0);
2615 
2616     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2617 
2618     if (log)
2619     {
2620         GetObjectFile()->GetModule()->LogMessage (log,
2621                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
2622                                                   name.GetCString(),
2623                                                   name_type_mask,
2624                                                   append);
2625     }
2626 
2627     // If we aren't appending the results to this list, then clear the list
2628     if (!append)
2629         sc_list.Clear();
2630 
2631     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
2632         return 0;
2633 
2634     // If name is empty then we won't find anything.
2635     if (name.IsEmpty())
2636         return 0;
2637 
2638     // Remember how many sc_list are in the list before we search in case
2639     // we are appending the results to a variable list.
2640 
2641     const char *name_cstr = name.GetCString();
2642 
2643     const uint32_t original_size = sc_list.GetSize();
2644 
2645     DWARFDebugInfo* info = DebugInfo();
2646     if (info == NULL)
2647         return 0;
2648 
2649     std::set<const DWARFDebugInfoEntry *> resolved_dies;
2650     if (m_using_apple_tables)
2651     {
2652         if (m_apple_names_ap.get())
2653         {
2654 
2655             DIEArray die_offsets;
2656 
2657             uint32_t num_matches = 0;
2658 
2659             if (name_type_mask & eFunctionNameTypeFull)
2660             {
2661                 // If they asked for the full name, match what they typed.  At some point we may
2662                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
2663                 // dies that we find by exact match.
2664                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2665                 for (uint32_t i = 0; i < num_matches; i++)
2666                 {
2667                     const DIERef& die_ref = die_offsets[i];
2668                     DWARFDIE die = info->GetDIE (die_ref);
2669                     if (die)
2670                     {
2671                         if (!DIEInDeclContext(parent_decl_ctx, die))
2672                             continue; // The containing decl contexts don't match
2673 
2674                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2675                         {
2676                             if (ResolveFunction (die, include_inlines, sc_list))
2677                                 resolved_dies.insert(die.GetDIE());
2678                         }
2679                     }
2680                     else
2681                     {
2682                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2683                                                                                    die_ref.die_offset, name_cstr);
2684                     }
2685                 }
2686             }
2687 
2688             if (name_type_mask & eFunctionNameTypeSelector)
2689             {
2690                 if (parent_decl_ctx && parent_decl_ctx->IsValid())
2691                     return 0; // no selectors in namespaces
2692 
2693                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2694                 // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
2695                 // and if it is an ObjC method name, we're good.
2696 
2697                 for (uint32_t i = 0; i < num_matches; i++)
2698                 {
2699                     const DIERef& die_ref = die_offsets[i];
2700                     DWARFDIE die = info->GetDIE (die_ref);
2701                     if (die)
2702                     {
2703                         const char *die_name = die.GetName();
2704                         if (ObjCLanguage::IsPossibleObjCMethodName(die_name))
2705                         {
2706                             if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2707                             {
2708                                 if (ResolveFunction (die, include_inlines, sc_list))
2709                                     resolved_dies.insert(die.GetDIE());
2710                             }
2711                         }
2712                     }
2713                     else
2714                     {
2715                         GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2716                                                                    die_ref.die_offset, name_cstr);
2717                     }
2718                 }
2719                 die_offsets.clear();
2720             }
2721 
2722             if (((name_type_mask & eFunctionNameTypeMethod) && !parent_decl_ctx) || name_type_mask & eFunctionNameTypeBase)
2723             {
2724                 // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
2725                 // extract the base name, look that up, and if there is any other information in the name we were
2726                 // passed in we have to post-filter based on that.
2727 
2728                 // FIXME: Arrange the logic above so that we don't calculate the base name twice:
2729                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
2730 
2731                 for (uint32_t i = 0; i < num_matches; i++)
2732                 {
2733                     const DIERef& die_ref = die_offsets[i];
2734                     DWARFDIE die = info->GetDIE (die_ref);
2735                     if (die)
2736                     {
2737                         if (!DIEInDeclContext(parent_decl_ctx, die))
2738                             continue; // The containing decl contexts don't match
2739 
2740 
2741                         // If we get to here, the die is good, and we should add it:
2742                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end() && ResolveFunction (die, include_inlines, sc_list))
2743                         {
2744                             bool keep_die = true;
2745                             if ((name_type_mask & (eFunctionNameTypeBase|eFunctionNameTypeMethod)) != (eFunctionNameTypeBase|eFunctionNameTypeMethod))
2746                             {
2747                                 // We are looking for either basenames or methods, so we need to
2748                                 // trim out the ones we won't want by looking at the type
2749                                 SymbolContext sc;
2750                                 if (sc_list.GetLastContext(sc))
2751                                 {
2752                                     if (sc.block)
2753                                     {
2754                                         // We have an inlined function
2755                                     }
2756                                     else if (sc.function)
2757                                     {
2758                                         Type *type = sc.function->GetType();
2759 
2760                                         if (type)
2761                                         {
2762                                             CompilerDeclContext decl_ctx = GetDeclContextContainingUID (type->GetID());
2763                                             if (decl_ctx.IsStructUnionOrClass())
2764                                             {
2765                                                 if (name_type_mask & eFunctionNameTypeBase)
2766                                                 {
2767                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
2768                                                     keep_die = false;
2769                                                 }
2770                                             }
2771                                             else
2772                                             {
2773                                                 if (name_type_mask & eFunctionNameTypeMethod)
2774                                                 {
2775                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
2776                                                     keep_die = false;
2777                                                 }
2778                                             }
2779                                         }
2780                                         else
2781                                         {
2782                                             GetObjectFile()->GetModule()->ReportWarning ("function at die offset 0x%8.8x had no function type",
2783                                                                                          die_ref.die_offset);
2784                                         }
2785                                     }
2786                                 }
2787                             }
2788                             if (keep_die)
2789                                 resolved_dies.insert(die.GetDIE());
2790                         }
2791                     }
2792                     else
2793                     {
2794                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
2795                                                                                    die_ref.die_offset, name_cstr);
2796                     }
2797                 }
2798                 die_offsets.clear();
2799             }
2800         }
2801     }
2802     else
2803     {
2804 
2805         // Index the DWARF if we haven't already
2806         if (!m_indexed)
2807             Index ();
2808 
2809         if (name_type_mask & eFunctionNameTypeFull)
2810         {
2811             FindFunctions (name, m_function_fullname_index, include_inlines, sc_list);
2812 
2813             // FIXME Temporary workaround for global/anonymous namespace
2814             // functions debugging FreeBSD and Linux binaries.
2815             // If we didn't find any functions in the global namespace try
2816             // looking in the basename index but ignore any returned
2817             // functions that have a namespace but keep functions which
2818             // have an anonymous namespace
2819             // TODO: The arch in the object file isn't correct for MSVC
2820             // binaries on windows, we should find a way to make it
2821             // correct and handle those symbols as well.
2822             if (sc_list.GetSize() == original_size)
2823             {
2824                 ArchSpec arch;
2825                 if (!parent_decl_ctx &&
2826                     GetObjectFile()->GetArchitecture(arch) &&
2827                     (arch.GetTriple().isOSFreeBSD() || arch.GetTriple().isOSLinux() ||
2828                      arch.GetMachine() == llvm::Triple::hexagon))
2829                 {
2830                     SymbolContextList temp_sc_list;
2831                     FindFunctions (name, m_function_basename_index, include_inlines, temp_sc_list);
2832                     SymbolContext sc;
2833                     for (uint32_t i = 0; i < temp_sc_list.GetSize(); i++)
2834                     {
2835                         if (temp_sc_list.GetContextAtIndex(i, sc))
2836                         {
2837                             ConstString mangled_name = sc.GetFunctionName(Mangled::ePreferMangled);
2838                             ConstString demangled_name = sc.GetFunctionName(Mangled::ePreferDemangled);
2839                             // Mangled names on Linux and FreeBSD are of the form:
2840                             // _ZN18function_namespace13function_nameEv.
2841                             if (strncmp(mangled_name.GetCString(), "_ZN", 3) ||
2842                                 !strncmp(demangled_name.GetCString(), "(anonymous namespace)", 21))
2843                             {
2844                                 sc_list.Append(sc);
2845                             }
2846                         }
2847                     }
2848                 }
2849             }
2850         }
2851         DIEArray die_offsets;
2852         if (name_type_mask & eFunctionNameTypeBase)
2853         {
2854             uint32_t num_base = m_function_basename_index.Find(name, die_offsets);
2855             for (uint32_t i = 0; i < num_base; i++)
2856             {
2857                 DWARFDIE die = info->GetDIE (die_offsets[i]);
2858                 if (die)
2859                 {
2860                     if (!DIEInDeclContext(parent_decl_ctx, die))
2861                         continue; // The containing decl contexts don't match
2862 
2863                     // If we get to here, the die is good, and we should add it:
2864                     if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2865                     {
2866                         if (ResolveFunction (die, include_inlines, sc_list))
2867                             resolved_dies.insert(die.GetDIE());
2868                     }
2869                 }
2870             }
2871             die_offsets.clear();
2872         }
2873 
2874         if (name_type_mask & eFunctionNameTypeMethod)
2875         {
2876             if (parent_decl_ctx && parent_decl_ctx->IsValid())
2877                 return 0; // no methods in namespaces
2878 
2879             uint32_t num_base = m_function_method_index.Find(name, die_offsets);
2880             {
2881                 for (uint32_t i = 0; i < num_base; i++)
2882                 {
2883                     DWARFDIE die = info->GetDIE (die_offsets[i]);
2884                     if (die)
2885                     {
2886                         // If we get to here, the die is good, and we should add it:
2887                         if (resolved_dies.find(die.GetDIE()) == resolved_dies.end())
2888                         {
2889                             if (ResolveFunction (die, include_inlines, sc_list))
2890                                 resolved_dies.insert(die.GetDIE());
2891                         }
2892                     }
2893                 }
2894             }
2895             die_offsets.clear();
2896         }
2897 
2898         if ((name_type_mask & eFunctionNameTypeSelector) && (!parent_decl_ctx || !parent_decl_ctx->IsValid()))
2899         {
2900             FindFunctions (name, m_function_selector_index, include_inlines, sc_list);
2901         }
2902 
2903     }
2904 
2905     // Return the number of variable that were appended to the list
2906     const uint32_t num_matches = sc_list.GetSize() - original_size;
2907 
2908     if (log && num_matches > 0)
2909     {
2910         GetObjectFile()->GetModule()->LogMessage (log,
2911                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => %u",
2912                                                   name.GetCString(),
2913                                                   name_type_mask,
2914                                                   include_inlines,
2915                                                   append,
2916                                                   num_matches);
2917     }
2918     return num_matches;
2919 }
2920 
2921 uint32_t
2922 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
2923 {
2924     Timer scoped_timer (__PRETTY_FUNCTION__,
2925                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
2926                         regex.GetText());
2927 
2928     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
2929 
2930     if (log)
2931     {
2932         GetObjectFile()->GetModule()->LogMessage (log,
2933                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
2934                                                   regex.GetText(),
2935                                                   append);
2936     }
2937 
2938 
2939     // If we aren't appending the results to this list, then clear the list
2940     if (!append)
2941         sc_list.Clear();
2942 
2943     // Remember how many sc_list are in the list before we search in case
2944     // we are appending the results to a variable list.
2945     uint32_t original_size = sc_list.GetSize();
2946 
2947     if (m_using_apple_tables)
2948     {
2949         if (m_apple_names_ap.get())
2950             FindFunctions (regex, *m_apple_names_ap, include_inlines, sc_list);
2951     }
2952     else
2953     {
2954         // Index the DWARF if we haven't already
2955         if (!m_indexed)
2956             Index ();
2957 
2958         FindFunctions (regex, m_function_basename_index, include_inlines, sc_list);
2959 
2960         FindFunctions (regex, m_function_fullname_index, include_inlines, sc_list);
2961     }
2962 
2963     // Return the number of variable that were appended to the list
2964     return sc_list.GetSize() - original_size;
2965 }
2966 
2967 void
2968 SymbolFileDWARF::GetMangledNamesForFunction (const std::string &scope_qualified_name,
2969                                              std::vector<ConstString> &mangled_names)
2970 {
2971     DWARFDebugInfo* info = DebugInfo();
2972     uint32_t num_comp_units = 0;
2973     if (info)
2974         num_comp_units = info->GetNumCompileUnits();
2975 
2976     for (uint32_t i = 0; i < num_comp_units; i++)
2977     {
2978         DWARFCompileUnit *cu = info->GetCompileUnitAtIndex(i);
2979         if (cu == nullptr)
2980             continue;
2981 
2982         SymbolFileDWARFDwo *dwo = cu->GetDwoSymbolFile();
2983         if (dwo)
2984             dwo->GetMangledNamesForFunction(scope_qualified_name, mangled_names);
2985     }
2986 
2987     NameToOffsetMap::iterator iter = m_function_scope_qualified_name_map.find(scope_qualified_name);
2988     if (iter == m_function_scope_qualified_name_map.end())
2989         return;
2990 
2991     DIERefSetSP set_sp = (*iter).second;
2992     std::set<DIERef>::iterator set_iter;
2993     for (set_iter = set_sp->begin(); set_iter != set_sp->end(); set_iter++)
2994     {
2995         DWARFDIE die = DebugInfo()->GetDIE (*set_iter);
2996         mangled_names.push_back(ConstString(die.GetMangledName()));
2997     }
2998 }
2999 
3000 
3001 uint32_t
3002 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
3003                             const ConstString &name,
3004                             const CompilerDeclContext *parent_decl_ctx,
3005                             bool append,
3006                             uint32_t max_matches,
3007                             llvm::DenseSet<lldb_private::SymbolFile *> &searched_symbol_files,
3008                             TypeMap& types)
3009 {
3010     // If we aren't appending the results to this list, then clear the list
3011     if (!append)
3012         types.Clear();
3013 
3014     // Make sure we haven't already searched this SymbolFile before...
3015     if (searched_symbol_files.count(this))
3016         return 0;
3017     else
3018         searched_symbol_files.insert(this);
3019 
3020     DWARFDebugInfo* info = DebugInfo();
3021     if (info == NULL)
3022         return 0;
3023 
3024     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3025 
3026     if (log)
3027     {
3028         if (parent_decl_ctx)
3029             GetObjectFile()->GetModule()->LogMessage (log,
3030                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = %p (\"%s\"), append=%u, max_matches=%u, type_list)",
3031                                                       name.GetCString(),
3032                                                       static_cast<const void*>(parent_decl_ctx),
3033                                                       parent_decl_ctx->GetName().AsCString("<NULL>"),
3034                                                       append, max_matches);
3035         else
3036             GetObjectFile()->GetModule()->LogMessage (log,
3037                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = NULL, append=%u, max_matches=%u, type_list)",
3038                                                       name.GetCString(), append,
3039                                                       max_matches);
3040     }
3041 
3042     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
3043         return 0;
3044 
3045     DIEArray die_offsets;
3046 
3047     if (m_using_apple_tables)
3048     {
3049         if (m_apple_types_ap.get())
3050         {
3051             const char *name_cstr = name.GetCString();
3052             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3053         }
3054     }
3055     else
3056     {
3057         if (!m_indexed)
3058             Index ();
3059 
3060         m_type_index.Find (name, die_offsets);
3061     }
3062 
3063     const size_t num_die_matches = die_offsets.size();
3064 
3065     if (num_die_matches)
3066     {
3067         const uint32_t initial_types_size = types.GetSize();
3068         DWARFDebugInfo* debug_info = DebugInfo();
3069         for (size_t i=0; i<num_die_matches; ++i)
3070         {
3071             const DIERef& die_ref = die_offsets[i];
3072             DWARFDIE die = debug_info->GetDIE (die_ref);
3073 
3074             if (die)
3075             {
3076                 if (!DIEInDeclContext(parent_decl_ctx, die))
3077                     continue; // The containing decl contexts don't match
3078 
3079                 Type *matching_type = ResolveType (die, true, true);
3080                 if (matching_type)
3081                 {
3082                     // We found a type pointer, now find the shared pointer form our type list
3083                     types.InsertUnique (matching_type->shared_from_this());
3084                     if (types.GetSize() >= max_matches)
3085                         break;
3086                 }
3087             }
3088             else
3089             {
3090                 if (m_using_apple_tables)
3091                 {
3092                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3093                                                                                die_ref.die_offset, name.GetCString());
3094                 }
3095             }
3096 
3097         }
3098         const uint32_t num_matches = types.GetSize() - initial_types_size;
3099         if (log && num_matches)
3100         {
3101             if (parent_decl_ctx)
3102             {
3103                 GetObjectFile()->GetModule()->LogMessage (log,
3104                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = %p (\"%s\"), append=%u, max_matches=%u, type_list) => %u",
3105                                                           name.GetCString(),
3106                                                           static_cast<const void*>(parent_decl_ctx),
3107                                                           parent_decl_ctx->GetName().AsCString("<NULL>"),
3108                                                           append, max_matches,
3109                                                           num_matches);
3110             }
3111             else
3112             {
3113                 GetObjectFile()->GetModule()->LogMessage (log,
3114                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", parent_decl_ctx = NULL, append=%u, max_matches=%u, type_list) => %u",
3115                                                           name.GetCString(),
3116                                                           append, max_matches,
3117                                                           num_matches);
3118             }
3119         }
3120         return num_matches;
3121     }
3122     else
3123     {
3124         UpdateExternalModuleListIfNeeded();
3125 
3126         for (const auto &pair : m_external_type_modules)
3127         {
3128             ModuleSP external_module_sp = pair.second;
3129             if (external_module_sp)
3130             {
3131                 SymbolVendor *sym_vendor = external_module_sp->GetSymbolVendor();
3132                 if (sym_vendor)
3133                 {
3134                     const uint32_t num_external_matches = sym_vendor->FindTypes (sc,
3135                                                                                  name,
3136                                                                                  parent_decl_ctx,
3137                                                                                  append,
3138                                                                                  max_matches,
3139                                                                                  searched_symbol_files,
3140                                                                                  types);
3141                     if (num_external_matches)
3142                         return num_external_matches;
3143                 }
3144             }
3145         }
3146     }
3147 
3148     return 0;
3149 }
3150 
3151 
3152 size_t
3153 SymbolFileDWARF::FindTypes (const std::vector<CompilerContext> &context,
3154                             bool append,
3155                             TypeMap& types)
3156 {
3157     if (!append)
3158         types.Clear();
3159 
3160     if (context.empty())
3161         return 0;
3162 
3163     DIEArray die_offsets;
3164 
3165     ConstString name = context.back().name;
3166 
3167     if (!name)
3168         return 0;
3169 
3170     if (m_using_apple_tables)
3171     {
3172         if (m_apple_types_ap.get())
3173         {
3174             const char *name_cstr = name.GetCString();
3175             m_apple_types_ap->FindByName (name_cstr, die_offsets);
3176         }
3177     }
3178     else
3179     {
3180         if (!m_indexed)
3181             Index ();
3182 
3183         m_type_index.Find (name, die_offsets);
3184     }
3185 
3186     const size_t num_die_matches = die_offsets.size();
3187 
3188     if (num_die_matches)
3189     {
3190         size_t num_matches = 0;
3191         DWARFDebugInfo* debug_info = DebugInfo();
3192         for (size_t i=0; i<num_die_matches; ++i)
3193         {
3194             const DIERef& die_ref = die_offsets[i];
3195             DWARFDIE die = debug_info->GetDIE (die_ref);
3196 
3197             if (die)
3198             {
3199                 std::vector<CompilerContext> die_context;
3200                 die.GetDWOContext(die_context);
3201                 if (die_context != context)
3202                     continue;
3203 
3204                 Type *matching_type = ResolveType (die, true, true);
3205                 if (matching_type)
3206                 {
3207                     // We found a type pointer, now find the shared pointer form our type list
3208                     types.InsertUnique (matching_type->shared_from_this());
3209                     ++num_matches;
3210                 }
3211             }
3212             else
3213             {
3214                 if (m_using_apple_tables)
3215                 {
3216                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3217                                                                                die_ref.die_offset, name.GetCString());
3218                 }
3219             }
3220 
3221         }
3222         return num_matches;
3223     }
3224     return 0;
3225 }
3226 
3227 
3228 CompilerDeclContext
3229 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
3230                                 const ConstString &name,
3231                                 const CompilerDeclContext *parent_decl_ctx)
3232 {
3233     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3234 
3235     if (log)
3236     {
3237         GetObjectFile()->GetModule()->LogMessage (log,
3238                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
3239                                                   name.GetCString());
3240     }
3241 
3242     CompilerDeclContext namespace_decl_ctx;
3243 
3244     if (!DeclContextMatchesThisSymbolFile(parent_decl_ctx))
3245         return namespace_decl_ctx;
3246 
3247 
3248     DWARFDebugInfo* info = DebugInfo();
3249     if (info)
3250     {
3251         DIEArray die_offsets;
3252 
3253         // Index if we already haven't to make sure the compile units
3254         // get indexed and make their global DIE index list
3255         if (m_using_apple_tables)
3256         {
3257             if (m_apple_namespaces_ap.get())
3258             {
3259                 const char *name_cstr = name.GetCString();
3260                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
3261             }
3262         }
3263         else
3264         {
3265             if (!m_indexed)
3266                 Index ();
3267 
3268             m_namespace_index.Find (name, die_offsets);
3269         }
3270 
3271         const size_t num_matches = die_offsets.size();
3272         if (num_matches)
3273         {
3274             DWARFDebugInfo* debug_info = DebugInfo();
3275             for (size_t i=0; i<num_matches; ++i)
3276             {
3277                 const DIERef& die_ref = die_offsets[i];
3278                 DWARFDIE die = debug_info->GetDIE (die_ref);
3279 
3280                 if (die)
3281                 {
3282                     if (!DIEInDeclContext (parent_decl_ctx, die))
3283                         continue; // The containing decl contexts don't match
3284 
3285                     DWARFASTParser *dwarf_ast = die.GetDWARFParser();
3286                     if (dwarf_ast)
3287                     {
3288                         namespace_decl_ctx = dwarf_ast->GetDeclContextForUIDFromDWARF (die);
3289                         if (namespace_decl_ctx)
3290                             break;
3291                     }
3292                 }
3293                 else
3294                 {
3295                     if (m_using_apple_tables)
3296                     {
3297                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
3298                                                                    die_ref.die_offset, name.GetCString());
3299                     }
3300                 }
3301 
3302             }
3303         }
3304     }
3305     if (log && namespace_decl_ctx)
3306     {
3307         GetObjectFile()->GetModule()->LogMessage (log,
3308                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => CompilerDeclContext(%p/%p) \"%s\"",
3309                                                   name.GetCString(),
3310                                                   static_cast<const void*>(namespace_decl_ctx.GetTypeSystem()),
3311                                                   static_cast<const void*>(namespace_decl_ctx.GetOpaqueDeclContext()),
3312                                                   namespace_decl_ctx.GetName().AsCString("<NULL>"));
3313     }
3314 
3315     return namespace_decl_ctx;
3316 }
3317 
3318 TypeSP
3319 SymbolFileDWARF::GetTypeForDIE (const DWARFDIE &die, bool resolve_function_context)
3320 {
3321     TypeSP type_sp;
3322     if (die)
3323     {
3324         Type *type_ptr = GetDIEToType().lookup (die.GetDIE());
3325         if (type_ptr == NULL)
3326         {
3327             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(die.GetCU());
3328             assert (lldb_cu);
3329             SymbolContext sc(lldb_cu);
3330             const DWARFDebugInfoEntry* parent_die = die.GetParent().GetDIE();
3331             while (parent_die != nullptr)
3332                 {
3333                     if (parent_die->Tag() == DW_TAG_subprogram)
3334                         break;
3335                     parent_die = parent_die->GetParent();
3336                 }
3337             SymbolContext sc_backup = sc;
3338             if (resolve_function_context && parent_die != nullptr && !GetFunction(DWARFDIE(die.GetCU(),parent_die), sc))
3339                 sc = sc_backup;
3340 
3341             type_sp = ParseType(sc, die, NULL);
3342         }
3343         else if (type_ptr != DIE_IS_BEING_PARSED)
3344         {
3345             // Grab the existing type from the master types lists
3346             type_sp = type_ptr->shared_from_this();
3347         }
3348 
3349     }
3350     return type_sp;
3351 }
3352 
3353 
3354 DWARFDIE
3355 SymbolFileDWARF::GetDeclContextDIEContainingDIE (const DWARFDIE &orig_die)
3356 {
3357     if (orig_die)
3358     {
3359         DWARFDIE die = orig_die;
3360 
3361         while (die)
3362         {
3363             // If this is the original DIE that we are searching for a declaration
3364             // for, then don't look in the cache as we don't want our own decl
3365             // context to be our decl context...
3366             if (orig_die != die)
3367             {
3368                 switch (die.Tag())
3369                 {
3370                     case DW_TAG_compile_unit:
3371                     case DW_TAG_namespace:
3372                     case DW_TAG_structure_type:
3373                     case DW_TAG_union_type:
3374                     case DW_TAG_class_type:
3375                     case DW_TAG_lexical_block:
3376                     case DW_TAG_subprogram:
3377                         return die;
3378 
3379                     default:
3380                         break;
3381                 }
3382             }
3383 
3384             DWARFDIE spec_die = die.GetReferencedDIE(DW_AT_specification);
3385             if (spec_die)
3386             {
3387                 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(spec_die);
3388                 if (decl_ctx_die)
3389                     return decl_ctx_die;
3390             }
3391 
3392             DWARFDIE abs_die = die.GetReferencedDIE(DW_AT_abstract_origin);
3393             if (abs_die)
3394             {
3395                 DWARFDIE decl_ctx_die = GetDeclContextDIEContainingDIE(abs_die);
3396                 if (decl_ctx_die)
3397                     return decl_ctx_die;
3398             }
3399 
3400             die = die.GetParent();
3401         }
3402     }
3403     return DWARFDIE();
3404 }
3405 
3406 
3407 Symbol *
3408 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
3409 {
3410     Symbol *objc_class_symbol = NULL;
3411     if (m_obj_file)
3412     {
3413         Symtab *symtab = m_obj_file->GetSymtab ();
3414         if (symtab)
3415         {
3416             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
3417                                                                         eSymbolTypeObjCClass,
3418                                                                         Symtab::eDebugNo,
3419                                                                         Symtab::eVisibilityAny);
3420         }
3421     }
3422     return objc_class_symbol;
3423 }
3424 
3425 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
3426 // then we can end up looking through all class types for a complete type and never find
3427 // the full definition. We need to know if this attribute is supported, so we determine
3428 // this here and cache th result. We also need to worry about the debug map DWARF file
3429 // if we are doing darwin DWARF in .o file debugging.
3430 bool
3431 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
3432 {
3433     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
3434     {
3435         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
3436         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
3437             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3438         else
3439         {
3440             DWARFDebugInfo* debug_info = DebugInfo();
3441             const uint32_t num_compile_units = GetNumCompileUnits();
3442             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
3443             {
3444                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
3445                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
3446                 {
3447                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
3448                     break;
3449                 }
3450             }
3451         }
3452         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
3453             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
3454     }
3455     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
3456 }
3457 
3458 // This function can be used when a DIE is found that is a forward declaration
3459 // DIE and we want to try and find a type that has the complete definition.
3460 TypeSP
3461 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDIE &die,
3462                                                        const ConstString &type_name,
3463                                                        bool must_be_implementation)
3464 {
3465 
3466     TypeSP type_sp;
3467 
3468     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
3469         return type_sp;
3470 
3471     DIEArray die_offsets;
3472 
3473     if (m_using_apple_tables)
3474     {
3475         if (m_apple_types_ap.get())
3476         {
3477             const char *name_cstr = type_name.GetCString();
3478             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
3479         }
3480     }
3481     else
3482     {
3483         if (!m_indexed)
3484             Index ();
3485 
3486         m_type_index.Find (type_name, die_offsets);
3487     }
3488 
3489     const size_t num_matches = die_offsets.size();
3490 
3491     if (num_matches)
3492     {
3493         DWARFDebugInfo* debug_info = DebugInfo();
3494         for (size_t i=0; i<num_matches; ++i)
3495         {
3496             const DIERef& die_ref = die_offsets[i];
3497             DWARFDIE type_die = debug_info->GetDIE (die_ref);
3498 
3499             if (type_die)
3500             {
3501                 bool try_resolving_type = false;
3502 
3503                 // Don't try and resolve the DIE we are looking for with the DIE itself!
3504                 if (type_die != die)
3505                 {
3506                     switch (type_die.Tag())
3507                     {
3508                         case DW_TAG_class_type:
3509                         case DW_TAG_structure_type:
3510                             try_resolving_type = true;
3511                             break;
3512                         default:
3513                             break;
3514                     }
3515                 }
3516 
3517                 if (try_resolving_type)
3518                 {
3519                     if (must_be_implementation && type_die.Supports_DW_AT_APPLE_objc_complete_type())
3520                         try_resolving_type = type_die.GetAttributeValueAsUnsigned (DW_AT_APPLE_objc_complete_type, 0);
3521 
3522                     if (try_resolving_type)
3523                     {
3524                         Type *resolved_type = ResolveType (type_die, false, true);
3525                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
3526                         {
3527                             DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
3528                                           die.GetID(),
3529                                           m_obj_file->GetFileSpec().GetFilename().AsCString("<Unknown>"),
3530                                           type_die.GetID(),
3531                                           type_cu->GetID());
3532 
3533                             if (die)
3534                                 GetDIEToType()[die.GetDIE()] = resolved_type;
3535                             type_sp = resolved_type->shared_from_this();
3536                             break;
3537                         }
3538                     }
3539                 }
3540             }
3541             else
3542             {
3543                 if (m_using_apple_tables)
3544                 {
3545                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3546                                                                die_ref.die_offset, type_name.GetCString());
3547                 }
3548             }
3549 
3550         }
3551     }
3552     return type_sp;
3553 }
3554 
3555 
3556 //----------------------------------------------------------------------
3557 // This function helps to ensure that the declaration contexts match for
3558 // two different DIEs. Often times debug information will refer to a
3559 // forward declaration of a type (the equivalent of "struct my_struct;".
3560 // There will often be a declaration of that type elsewhere that has the
3561 // full definition. When we go looking for the full type "my_struct", we
3562 // will find one or more matches in the accelerator tables and we will
3563 // then need to make sure the type was in the same declaration context
3564 // as the original DIE. This function can efficiently compare two DIEs
3565 // and will return true when the declaration context matches, and false
3566 // when they don't.
3567 //----------------------------------------------------------------------
3568 bool
3569 SymbolFileDWARF::DIEDeclContextsMatch (const DWARFDIE &die1,
3570                                        const DWARFDIE &die2)
3571 {
3572     if (die1 == die2)
3573         return true;
3574 
3575     DWARFDIECollection decl_ctx_1;
3576     DWARFDIECollection decl_ctx_2;
3577     //The declaration DIE stack is a stack of the declaration context
3578     // DIEs all the way back to the compile unit. If a type "T" is
3579     // declared inside a class "B", and class "B" is declared inside
3580     // a class "A" and class "A" is in a namespace "lldb", and the
3581     // namespace is in a compile unit, there will be a stack of DIEs:
3582     //
3583     //   [0] DW_TAG_class_type for "B"
3584     //   [1] DW_TAG_class_type for "A"
3585     //   [2] DW_TAG_namespace  for "lldb"
3586     //   [3] DW_TAG_compile_unit for the source file.
3587     //
3588     // We grab both contexts and make sure that everything matches
3589     // all the way back to the compiler unit.
3590 
3591     // First lets grab the decl contexts for both DIEs
3592     die1.GetDeclContextDIEs (decl_ctx_1);
3593     die2.GetDeclContextDIEs (decl_ctx_2);
3594     // Make sure the context arrays have the same size, otherwise
3595     // we are done
3596     const size_t count1 = decl_ctx_1.Size();
3597     const size_t count2 = decl_ctx_2.Size();
3598     if (count1 != count2)
3599         return false;
3600 
3601     // Make sure the DW_TAG values match all the way back up the
3602     // compile unit. If they don't, then we are done.
3603     DWARFDIE decl_ctx_die1;
3604     DWARFDIE decl_ctx_die2;
3605     size_t i;
3606     for (i=0; i<count1; i++)
3607     {
3608         decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex (i);
3609         decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex (i);
3610         if (decl_ctx_die1.Tag() != decl_ctx_die2.Tag())
3611             return false;
3612     }
3613 #if defined LLDB_CONFIGURATION_DEBUG
3614 
3615     // Make sure the top item in the decl context die array is always
3616     // DW_TAG_compile_unit. If it isn't then something went wrong in
3617     // the DWARFDIE::GetDeclContextDIEs() function...
3618     assert (decl_ctx_1.GetDIEAtIndex (count1 - 1).Tag() == DW_TAG_compile_unit);
3619 
3620 #endif
3621     // Always skip the compile unit when comparing by only iterating up to
3622     // "count - 1". Here we compare the names as we go.
3623     for (i=0; i<count1 - 1; i++)
3624     {
3625         decl_ctx_die1 = decl_ctx_1.GetDIEAtIndex (i);
3626         decl_ctx_die2 = decl_ctx_2.GetDIEAtIndex (i);
3627         const char *name1 = decl_ctx_die1.GetName();
3628         const char *name2 = decl_ctx_die2.GetName();
3629         // If the string was from a DW_FORM_strp, then the pointer will often
3630         // be the same!
3631         if (name1 == name2)
3632             continue;
3633 
3634         // Name pointers are not equal, so only compare the strings
3635         // if both are not NULL.
3636         if (name1 && name2)
3637         {
3638             // If the strings don't compare, we are done...
3639             if (strcmp(name1, name2) != 0)
3640                 return false;
3641         }
3642         else
3643         {
3644             // One name was NULL while the other wasn't
3645             return false;
3646         }
3647     }
3648     // We made it through all of the checks and the declaration contexts
3649     // are equal.
3650     return true;
3651 }
3652 
3653 
3654 TypeSP
3655 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
3656 {
3657     TypeSP type_sp;
3658 
3659     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
3660     if (dwarf_decl_ctx_count > 0)
3661     {
3662         const ConstString type_name(dwarf_decl_ctx[0].name);
3663         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
3664 
3665         if (type_name)
3666         {
3667             Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
3668             if (log)
3669             {
3670                 GetObjectFile()->GetModule()->LogMessage (log,
3671                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
3672                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3673                                                           dwarf_decl_ctx.GetQualifiedName());
3674             }
3675 
3676             DIEArray die_offsets;
3677 
3678             if (m_using_apple_tables)
3679             {
3680                 if (m_apple_types_ap.get())
3681                 {
3682                     const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
3683                     const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
3684                     if (has_tag && has_qualified_name_hash)
3685                     {
3686                         const char *qualified_name = dwarf_decl_ctx.GetQualifiedName();
3687                         const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name);
3688                         if (log)
3689                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
3690                         m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), tag, qualified_name_hash, die_offsets);
3691                     }
3692                     else if (has_tag)
3693                     {
3694                         if (log)
3695                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
3696                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
3697                     }
3698                     else
3699                     {
3700                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
3701                     }
3702                 }
3703             }
3704             else
3705             {
3706                 if (!m_indexed)
3707                     Index ();
3708 
3709                 m_type_index.Find (type_name, die_offsets);
3710             }
3711 
3712             const size_t num_matches = die_offsets.size();
3713 
3714 
3715             if (num_matches)
3716             {
3717                 DWARFDebugInfo* debug_info = DebugInfo();
3718                 for (size_t i=0; i<num_matches; ++i)
3719                 {
3720                     const DIERef& die_ref = die_offsets[i];
3721                     DWARFDIE type_die = debug_info->GetDIE (die_ref);
3722 
3723                     if (type_die)
3724                     {
3725                         bool try_resolving_type = false;
3726 
3727                         // Don't try and resolve the DIE we are looking for with the DIE itself!
3728                         const dw_tag_t type_tag = type_die.Tag();
3729                         // Make sure the tags match
3730                         if (type_tag == tag)
3731                         {
3732                             // The tags match, lets try resolving this type
3733                             try_resolving_type = true;
3734                         }
3735                         else
3736                         {
3737                             // The tags don't match, but we need to watch our for a
3738                             // forward declaration for a struct and ("struct foo")
3739                             // ends up being a class ("class foo { ... };") or
3740                             // vice versa.
3741                             switch (type_tag)
3742                             {
3743                                 case DW_TAG_class_type:
3744                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
3745                                     try_resolving_type = (tag == DW_TAG_structure_type);
3746                                     break;
3747                                 case DW_TAG_structure_type:
3748                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
3749                                     try_resolving_type = (tag == DW_TAG_class_type);
3750                                     break;
3751                                 default:
3752                                     // Tags don't match, don't event try to resolve
3753                                     // using this type whose name matches....
3754                                     break;
3755                             }
3756                         }
3757 
3758                         if (try_resolving_type)
3759                         {
3760                             DWARFDeclContext type_dwarf_decl_ctx;
3761                             type_die.GetDWARFDeclContext (type_dwarf_decl_ctx);
3762 
3763                             if (log)
3764                             {
3765                                 GetObjectFile()->GetModule()->LogMessage (log,
3766                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
3767                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3768                                                                           dwarf_decl_ctx.GetQualifiedName(),
3769                                                                           type_die.GetOffset(),
3770                                                                           type_dwarf_decl_ctx.GetQualifiedName());
3771                             }
3772 
3773                             // Make sure the decl contexts match all the way up
3774                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
3775                             {
3776                                 Type *resolved_type = ResolveType (type_die, false);
3777                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
3778                                 {
3779                                     type_sp = resolved_type->shared_from_this();
3780                                     break;
3781                                 }
3782                             }
3783                         }
3784                         else
3785                         {
3786                             if (log)
3787                             {
3788                                 std::string qualified_name;
3789                                 type_die.GetQualifiedName(qualified_name);
3790                                 GetObjectFile()->GetModule()->LogMessage (log,
3791                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
3792                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
3793                                                                           dwarf_decl_ctx.GetQualifiedName(),
3794                                                                           type_die.GetOffset(),
3795                                                                           qualified_name.c_str());
3796                             }
3797                         }
3798                     }
3799                     else
3800                     {
3801                         if (m_using_apple_tables)
3802                         {
3803                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
3804                                                                                        die_ref.die_offset, type_name.GetCString());
3805                         }
3806                     }
3807 
3808                 }
3809             }
3810         }
3811     }
3812     return type_sp;
3813 }
3814 
3815 TypeSP
3816 SymbolFileDWARF::ParseType (const SymbolContext& sc, const DWARFDIE &die, bool *type_is_new_ptr)
3817 {
3818     TypeSP type_sp;
3819 
3820     if (die)
3821     {
3822         TypeSystem *type_system = GetTypeSystemForLanguage(die.GetCU()->GetLanguageType());
3823 
3824         if (type_system)
3825         {
3826             DWARFASTParser *dwarf_ast = type_system->GetDWARFParser();
3827             if (dwarf_ast)
3828             {
3829                 Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
3830                 type_sp = dwarf_ast->ParseTypeFromDWARF (sc, die, log, type_is_new_ptr);
3831                 if (type_sp)
3832                 {
3833                     TypeList* type_list = GetTypeList();
3834                     if (type_list)
3835                         type_list->Insert(type_sp);
3836 
3837                     if (die.Tag() == DW_TAG_subprogram)
3838                     {
3839                         DIERef die_ref = die.GetDIERef();
3840                         std::string scope_qualified_name(GetDeclContextForUID(die.GetID()).GetScopeQualifiedName().AsCString(""));
3841                         if (scope_qualified_name.size())
3842                         {
3843                             NameToOffsetMap::iterator iter = m_function_scope_qualified_name_map.find(scope_qualified_name);
3844                             if (iter != m_function_scope_qualified_name_map.end())
3845                                 (*iter).second->insert(die_ref);
3846                             else
3847                             {
3848                                 DIERefSetSP new_set(new std::set<DIERef>);
3849                                 new_set->insert(die_ref);
3850                                 m_function_scope_qualified_name_map.emplace(std::make_pair(scope_qualified_name, new_set));
3851                             }
3852                         }
3853                     }
3854                 }
3855             }
3856         }
3857     }
3858 
3859     return type_sp;
3860 }
3861 
3862 size_t
3863 SymbolFileDWARF::ParseTypes
3864 (
3865     const SymbolContext& sc,
3866     const DWARFDIE &orig_die,
3867     bool parse_siblings,
3868     bool parse_children
3869 )
3870 {
3871     size_t types_added = 0;
3872     DWARFDIE die = orig_die;
3873     while (die)
3874     {
3875         bool type_is_new = false;
3876         if (ParseType(sc, die, &type_is_new).get())
3877         {
3878             if (type_is_new)
3879                 ++types_added;
3880         }
3881 
3882         if (parse_children && die.HasChildren())
3883         {
3884             if (die.Tag() == DW_TAG_subprogram)
3885             {
3886                 SymbolContext child_sc(sc);
3887                 child_sc.function = sc.comp_unit->FindFunctionByUID(die.GetID()).get();
3888                 types_added += ParseTypes(child_sc, die.GetFirstChild(), true, true);
3889             }
3890             else
3891                 types_added += ParseTypes(sc, die.GetFirstChild(), true, true);
3892         }
3893 
3894         if (parse_siblings)
3895             die = die.GetSibling();
3896         else
3897             die.Clear();
3898     }
3899     return types_added;
3900 }
3901 
3902 
3903 size_t
3904 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
3905 {
3906     assert(sc.comp_unit && sc.function);
3907     size_t functions_added = 0;
3908     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3909     if (dwarf_cu)
3910     {
3911         const dw_offset_t function_die_offset = sc.function->GetID();
3912         DWARFDIE function_die = dwarf_cu->GetDIE (function_die_offset);
3913         if (function_die)
3914         {
3915             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), function_die, LLDB_INVALID_ADDRESS, 0);
3916         }
3917     }
3918 
3919     return functions_added;
3920 }
3921 
3922 
3923 size_t
3924 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
3925 {
3926     // At least a compile unit must be valid
3927     assert(sc.comp_unit);
3928     size_t types_added = 0;
3929     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
3930     if (dwarf_cu)
3931     {
3932         if (sc.function)
3933         {
3934             dw_offset_t function_die_offset = sc.function->GetID();
3935             DWARFDIE func_die = dwarf_cu->GetDIE(function_die_offset);
3936             if (func_die && func_die.HasChildren())
3937             {
3938                 types_added = ParseTypes(sc, func_die.GetFirstChild(), true, true);
3939             }
3940         }
3941         else
3942         {
3943             DWARFDIE dwarf_cu_die = dwarf_cu->DIE();
3944             if (dwarf_cu_die && dwarf_cu_die.HasChildren())
3945             {
3946                 types_added = ParseTypes(sc, dwarf_cu_die.GetFirstChild(), true, true);
3947             }
3948         }
3949     }
3950 
3951     return types_added;
3952 }
3953 
3954 size_t
3955 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
3956 {
3957     if (sc.comp_unit != NULL)
3958     {
3959         DWARFDebugInfo* info = DebugInfo();
3960         if (info == NULL)
3961             return 0;
3962 
3963         if (sc.function)
3964         {
3965             DWARFDIE function_die = info->GetDIE(DIERef(sc.function->GetID()));
3966 
3967             const dw_addr_t func_lo_pc = function_die.GetAttributeValueAsAddress (DW_AT_low_pc, LLDB_INVALID_ADDRESS);
3968             if (func_lo_pc != LLDB_INVALID_ADDRESS)
3969             {
3970                 const size_t num_variables = ParseVariables(sc, function_die.GetFirstChild(), func_lo_pc, true, true);
3971 
3972                 // Let all blocks know they have parse all their variables
3973                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
3974                 return num_variables;
3975             }
3976         }
3977         else if (sc.comp_unit)
3978         {
3979             DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID());
3980 
3981             if (dwarf_cu == NULL)
3982                 return 0;
3983 
3984             uint32_t vars_added = 0;
3985             VariableListSP variables (sc.comp_unit->GetVariableList(false));
3986 
3987             if (variables.get() == NULL)
3988             {
3989                 variables.reset(new VariableList());
3990                 sc.comp_unit->SetVariableList(variables);
3991 
3992                 DIEArray die_offsets;
3993                 if (m_using_apple_tables)
3994                 {
3995                     if (m_apple_names_ap.get())
3996                     {
3997                         DWARFMappedHash::DIEInfoArray hash_data_array;
3998                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
3999                                                                     dwarf_cu->GetNextCompileUnitOffset(),
4000                                                                     hash_data_array))
4001                         {
4002                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
4003                         }
4004                     }
4005                 }
4006                 else
4007                 {
4008                     // Index if we already haven't to make sure the compile units
4009                     // get indexed and make their global DIE index list
4010                     if (!m_indexed)
4011                         Index ();
4012 
4013                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
4014                                                                  die_offsets);
4015                 }
4016 
4017                 const size_t num_matches = die_offsets.size();
4018                 if (num_matches)
4019                 {
4020                     DWARFDebugInfo* debug_info = DebugInfo();
4021                     for (size_t i=0; i<num_matches; ++i)
4022                     {
4023                         const DIERef& die_ref = die_offsets[i];
4024                         DWARFDIE die = debug_info->GetDIE (die_ref);
4025                         if (die)
4026                         {
4027                             VariableSP var_sp (ParseVariableDIE(sc, die, LLDB_INVALID_ADDRESS));
4028                             if (var_sp)
4029                             {
4030                                 variables->AddVariableIfUnique (var_sp);
4031                                 ++vars_added;
4032                             }
4033                         }
4034                         else
4035                         {
4036                             if (m_using_apple_tables)
4037                             {
4038                                 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);
4039                             }
4040                         }
4041 
4042                     }
4043                 }
4044             }
4045             return vars_added;
4046         }
4047     }
4048     return 0;
4049 }
4050 
4051 VariableSP
4052 SymbolFileDWARF::ParseVariableDIE
4053 (
4054     const SymbolContext& sc,
4055     const DWARFDIE &die,
4056     const lldb::addr_t func_low_pc
4057 )
4058 {
4059     if (die.GetDWARF() != this)
4060         return die.GetDWARF()->ParseVariableDIE(sc, die, func_low_pc);
4061 
4062     VariableSP var_sp;
4063     if (!die)
4064         return var_sp;
4065 
4066     var_sp = GetDIEToVariable()[die.GetDIE()];
4067     if (var_sp)
4068         return var_sp;  // Already been parsed!
4069 
4070     const dw_tag_t tag = die.Tag();
4071     ModuleSP module = GetObjectFile()->GetModule();
4072 
4073     if ((tag == DW_TAG_variable) ||
4074         (tag == DW_TAG_constant) ||
4075         (tag == DW_TAG_formal_parameter && sc.function))
4076     {
4077         DWARFAttributes attributes;
4078         const size_t num_attributes = die.GetAttributes(attributes);
4079         DWARFDIE spec_die;
4080         if (num_attributes > 0)
4081         {
4082             const char *name = NULL;
4083             const char *mangled = NULL;
4084             Declaration decl;
4085             uint32_t i;
4086             DWARFFormValue type_die_form;
4087             DWARFExpression location(die.GetCU());
4088             bool is_external = false;
4089             bool is_artificial = false;
4090             bool location_is_const_value_data = false;
4091             bool has_explicit_location = false;
4092             DWARFFormValue const_value;
4093             Variable::RangeList scope_ranges;
4094             //AccessType accessibility = eAccessNone;
4095 
4096             for (i=0; i<num_attributes; ++i)
4097             {
4098                 dw_attr_t attr = attributes.AttributeAtIndex(i);
4099                 DWARFFormValue form_value;
4100 
4101                 if (attributes.ExtractFormValueAtIndex(i, form_value))
4102                 {
4103                     switch (attr)
4104                     {
4105                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4106                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4107                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4108                     case DW_AT_name:        name = form_value.AsCString(); break;
4109                     case DW_AT_linkage_name:
4110                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(); break;
4111                     case DW_AT_type:        type_die_form = form_value; break;
4112                     case DW_AT_external:    is_external = form_value.Boolean(); break;
4113                     case DW_AT_const_value:
4114                         // If we have already found a DW_AT_location attribute, ignore this attribute.
4115                         if (!has_explicit_location)
4116                         {
4117                             location_is_const_value_data = true;
4118                             // The constant value will be either a block, a data value or a string.
4119                             const DWARFDataExtractor& debug_info_data = get_debug_info_data();
4120                             if (DWARFFormValue::IsBlockForm(form_value.Form()))
4121                             {
4122                                 // Retrieve the value as a block expression.
4123                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
4124                                 uint32_t block_length = form_value.Unsigned();
4125                                 location.CopyOpcodeData(module, debug_info_data, block_offset, block_length);
4126                             }
4127                             else if (DWARFFormValue::IsDataForm(form_value.Form()))
4128                             {
4129                                 // Retrieve the value as a data expression.
4130                                 DWARFFormValue::FixedFormSizes fixed_form_sizes =
4131                                     DWARFFormValue::GetFixedFormSizesForAddressSize (
4132                                             attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
4133                                             attributes.CompileUnitAtIndex(i)->IsDWARF64());
4134                                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
4135                                 uint32_t data_length = fixed_form_sizes.GetSize(form_value.Form());
4136                                 if (data_length == 0)
4137                                 {
4138                                     const uint8_t *data_pointer = form_value.BlockData();
4139                                     if (data_pointer)
4140                                     {
4141                                         form_value.Unsigned();
4142                                     }
4143                                     else if (DWARFFormValue::IsDataForm(form_value.Form()))
4144                                     {
4145                                         // we need to get the byte size of the type later after we create the variable
4146                                         const_value = form_value;
4147                                     }
4148                                 }
4149                                 else
4150                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
4151                             }
4152                             else
4153                             {
4154                                 // Retrieve the value as a string expression.
4155                                 if (form_value.Form() == DW_FORM_strp)
4156                                 {
4157                                     DWARFFormValue::FixedFormSizes fixed_form_sizes =
4158                                         DWARFFormValue::GetFixedFormSizesForAddressSize (
4159                                                 attributes.CompileUnitAtIndex(i)->GetAddressByteSize(),
4160                                                 attributes.CompileUnitAtIndex(i)->IsDWARF64());
4161                                     uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
4162                                     uint32_t data_length = fixed_form_sizes.GetSize(form_value.Form());
4163                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
4164                                 }
4165                                 else
4166                                 {
4167                                     const char *str = form_value.AsCString();
4168                                     uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart();
4169                                     uint32_t string_length = strlen(str) + 1;
4170                                     location.CopyOpcodeData(module, debug_info_data, string_offset, string_length);
4171                                 }
4172                             }
4173                         }
4174                         break;
4175                     case DW_AT_location:
4176                         {
4177                             location_is_const_value_data = false;
4178                             has_explicit_location = true;
4179                             if (form_value.BlockData())
4180                             {
4181                                 const DWARFDataExtractor& debug_info_data = get_debug_info_data();
4182 
4183                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
4184                                 uint32_t block_length = form_value.Unsigned();
4185                                 location.CopyOpcodeData(module, get_debug_info_data(), block_offset, block_length);
4186                             }
4187                             else
4188                             {
4189                                 const DWARFDataExtractor& debug_loc_data = get_debug_loc_data();
4190                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
4191 
4192                                 size_t loc_list_length = DWARFExpression::LocationListSize(die.GetCU(), debug_loc_data, debug_loc_offset);
4193                                 if (loc_list_length > 0)
4194                                 {
4195                                     location.CopyOpcodeData(module, debug_loc_data, debug_loc_offset, loc_list_length);
4196                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
4197                                     location.SetLocationListSlide (func_low_pc - attributes.CompileUnitAtIndex(i)->GetBaseAddress());
4198                                 }
4199                             }
4200                         }
4201                         break;
4202                     case DW_AT_specification:
4203                     {
4204                         DWARFDebugInfo* debug_info = DebugInfo();
4205                         if (debug_info)
4206                             spec_die = debug_info->GetDIE(DIERef(form_value));
4207                         break;
4208                     }
4209                     case DW_AT_start_scope:
4210                     {
4211                         if (form_value.Form() == DW_FORM_sec_offset)
4212                         {
4213                             DWARFRangeList dwarf_scope_ranges;
4214                             const DWARFDebugRanges* debug_ranges = DebugRanges();
4215                             debug_ranges->FindRanges(form_value.Unsigned(), dwarf_scope_ranges);
4216 
4217                             // All DW_AT_start_scope are relative to the base address of the
4218                             // compile unit. We add the compile unit base address to make
4219                             // sure all the addresses are properly fixed up.
4220                             for (size_t i = 0, count = dwarf_scope_ranges.GetSize(); i < count; ++i)
4221                             {
4222                                 const DWARFRangeList::Entry& range = dwarf_scope_ranges.GetEntryRef(i);
4223                                 scope_ranges.Append(range.GetRangeBase() + die.GetCU()->GetBaseAddress(),
4224                                                     range.GetByteSize());
4225                             }
4226                         }
4227                         else
4228                         {
4229                             // TODO: Handle the case when DW_AT_start_scope have form constant. The
4230                             // dwarf spec is a bit ambiguous about what is the expected behavior in
4231                             // case the enclosing block have a non coninious address range and the
4232                             // DW_AT_start_scope entry have a form constant.
4233                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_start_scope has unsupported form type (0x%x)\n",
4234                                                                          die.GetID(),
4235                                                                          form_value.Form());
4236                         }
4237 
4238                         scope_ranges.Sort();
4239                         scope_ranges.CombineConsecutiveRanges();
4240                     }
4241                     case DW_AT_artificial:      is_artificial = form_value.Boolean(); break;
4242                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
4243                     case DW_AT_declaration:
4244                     case DW_AT_description:
4245                     case DW_AT_endianity:
4246                     case DW_AT_segment:
4247                     case DW_AT_visibility:
4248                     default:
4249                     case DW_AT_abstract_origin:
4250                     case DW_AT_sibling:
4251                         break;
4252                     }
4253                 }
4254             }
4255 
4256             const DWARFDIE parent_context_die = GetDeclContextDIEContainingDIE(die);
4257             const dw_tag_t parent_tag = die.GetParent().Tag();
4258             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);
4259 
4260             ValueType scope = eValueTypeInvalid;
4261 
4262             const DWARFDIE sc_parent_die = GetParentSymbolContextDIE(die);
4263             SymbolContextScope * symbol_context_scope = NULL;
4264 
4265             if (!mangled)
4266             {
4267                 // LLDB relies on the mangled name (DW_TAG_linkage_name or DW_AT_MIPS_linkage_name) to
4268                 // generate fully qualified names of global variables with commands like "frame var j".
4269                 // For example, if j were an int variable holding a value 4 and declared in a namespace
4270                 // B which in turn is contained in a namespace A, the command "frame var j" returns
4271                 // "(int) A::B::j = 4". If the compiler does not emit a linkage name, we should be able
4272                 // to generate a fully qualified name from the declaration context.
4273                 if (parent_tag == DW_TAG_compile_unit &&
4274                     Language::LanguageIsCPlusPlus(die.GetLanguage()))
4275                 {
4276                     DWARFDeclContext decl_ctx;
4277 
4278                     die.GetDWARFDeclContext(decl_ctx);
4279                     mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
4280                 }
4281             }
4282 
4283             // DWARF doesn't specify if a DW_TAG_variable is a local, global
4284             // or static variable, so we have to do a little digging by
4285             // looking at the location of a variable to see if it contains
4286             // a DW_OP_addr opcode _somewhere_ in the definition. I say
4287             // somewhere because clang likes to combine small global variables
4288             // into the same symbol and have locations like:
4289             // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
4290             // So if we don't have a DW_TAG_formal_parameter, we can look at
4291             // the location to see if it contains a DW_OP_addr opcode, and
4292             // then we can correctly classify  our variables.
4293             if (tag == DW_TAG_formal_parameter)
4294                 scope = eValueTypeVariableArgument;
4295             else
4296             {
4297                 bool op_error = false;
4298                 // Check if the location has a DW_OP_addr with any address value...
4299                 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
4300                 if (!location_is_const_value_data)
4301                 {
4302                     location_DW_OP_addr = location.GetLocation_DW_OP_addr (0, op_error);
4303                     if (op_error)
4304                     {
4305                         StreamString strm;
4306                         location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
4307                         GetObjectFile()->GetModule()->ReportError ("0x%8.8x: %s has an invalid location: %s", die.GetOffset(), die.GetTagAsCString(), strm.GetString().c_str());
4308                     }
4309                 }
4310 
4311                 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
4312                 {
4313                     if (is_external)
4314                         scope = eValueTypeVariableGlobal;
4315                     else
4316                         scope = eValueTypeVariableStatic;
4317 
4318 
4319                     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile ();
4320 
4321                     if (debug_map_symfile)
4322                     {
4323                         // When leaving the DWARF in the .o files on darwin,
4324                         // when we have a global variable that wasn't initialized,
4325                         // the .o file might not have allocated a virtual
4326                         // address for the global variable. In this case it will
4327                         // have created a symbol for the global variable
4328                         // that is undefined/data and external and the value will
4329                         // be the byte size of the variable. When we do the
4330                         // address map in SymbolFileDWARFDebugMap we rely on
4331                         // having an address, we need to do some magic here
4332                         // so we can get the correct address for our global
4333                         // variable. The address for all of these entries
4334                         // will be zero, and there will be an undefined symbol
4335                         // in this object file, and the executable will have
4336                         // a matching symbol with a good address. So here we
4337                         // dig up the correct address and replace it in the
4338                         // location for the variable, and set the variable's
4339                         // symbol context scope to be that of the main executable
4340                         // so the file address will resolve correctly.
4341                         bool linked_oso_file_addr = false;
4342                         if (is_external && location_DW_OP_addr == 0)
4343                         {
4344                             // we have a possible uninitialized extern global
4345                             ConstString const_name(mangled ? mangled : name);
4346                             ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile();
4347                             if (debug_map_objfile)
4348                             {
4349                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
4350                                 if (debug_map_symtab)
4351                                 {
4352                                     Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
4353                                                                                                            eSymbolTypeData,
4354                                                                                                            Symtab::eDebugYes,
4355                                                                                                            Symtab::eVisibilityExtern);
4356                                     if (exe_symbol)
4357                                     {
4358                                         if (exe_symbol->ValueIsAddress())
4359                                         {
4360                                             const addr_t exe_file_addr = exe_symbol->GetAddressRef().GetFileAddress();
4361                                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
4362                                             {
4363                                                 if (location.Update_DW_OP_addr (exe_file_addr))
4364                                                 {
4365                                                     linked_oso_file_addr = true;
4366                                                     symbol_context_scope = exe_symbol;
4367                                                 }
4368                                             }
4369                                         }
4370                                     }
4371                                 }
4372                             }
4373                         }
4374 
4375                         if (!linked_oso_file_addr)
4376                         {
4377                             // The DW_OP_addr is not zero, but it contains a .o file address which
4378                             // needs to be linked up correctly.
4379                             const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
4380                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
4381                             {
4382                                 // Update the file address for this variable
4383                                 location.Update_DW_OP_addr (exe_file_addr);
4384                             }
4385                             else
4386                             {
4387                                 // Variable didn't make it into the final executable
4388                                 return var_sp;
4389                             }
4390                         }
4391                     }
4392                 }
4393                 else
4394                 {
4395                     if (location_is_const_value_data)
4396                         scope = eValueTypeVariableStatic;
4397                     else
4398                         scope = eValueTypeVariableLocal;
4399                 }
4400             }
4401 
4402             if (symbol_context_scope == NULL)
4403             {
4404                 switch (parent_tag)
4405                 {
4406                 case DW_TAG_subprogram:
4407                 case DW_TAG_inlined_subroutine:
4408                 case DW_TAG_lexical_block:
4409                     if (sc.function)
4410                     {
4411                         symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
4412                         if (symbol_context_scope == NULL)
4413                             symbol_context_scope = sc.function;
4414                     }
4415                     break;
4416 
4417                 default:
4418                     symbol_context_scope = sc.comp_unit;
4419                     break;
4420                 }
4421             }
4422 
4423             if (symbol_context_scope)
4424             {
4425                 SymbolFileTypeSP type_sp(new SymbolFileType(*this, DIERef(type_die_form).GetUID()));
4426 
4427                 if (const_value.Form() && type_sp && type_sp->GetType())
4428                     location.CopyOpcodeData(const_value.Unsigned(), type_sp->GetType()->GetByteSize(), die.GetCU()->GetAddressByteSize());
4429 
4430                 var_sp.reset (new Variable (die.GetID(),
4431                                             name,
4432                                             mangled,
4433                                             type_sp,
4434                                             scope,
4435                                             symbol_context_scope,
4436                                             scope_ranges,
4437                                             &decl,
4438                                             location,
4439                                             is_external,
4440                                             is_artificial,
4441                                             is_static_member));
4442 
4443                 var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
4444             }
4445             else
4446             {
4447                 // Not ready to parse this variable yet. It might be a global
4448                 // or static variable that is in a function scope and the function
4449                 // in the symbol context wasn't filled in yet
4450                 return var_sp;
4451             }
4452         }
4453         // Cache var_sp even if NULL (the variable was just a specification or
4454         // was missing vital information to be able to be displayed in the debugger
4455         // (missing location due to optimization, etc)) so we don't re-parse
4456         // this DIE over and over later...
4457         GetDIEToVariable()[die.GetDIE()] = var_sp;
4458         if (spec_die)
4459             GetDIEToVariable()[spec_die.GetDIE()] = var_sp;
4460     }
4461     return var_sp;
4462 }
4463 
4464 
4465 DWARFDIE
4466 SymbolFileDWARF::FindBlockContainingSpecification (const DIERef& func_die_ref,
4467                                                    dw_offset_t spec_block_die_offset)
4468 {
4469     // Give the concrete function die specified by "func_die_offset", find the
4470     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4471     // to "spec_block_die_offset"
4472     return FindBlockContainingSpecification (DebugInfo()->GetDIE (func_die_ref), spec_block_die_offset);
4473 }
4474 
4475 
4476 DWARFDIE
4477 SymbolFileDWARF::FindBlockContainingSpecification(const DWARFDIE &die,
4478                                                   dw_offset_t spec_block_die_offset)
4479 {
4480     if (die)
4481     {
4482         switch (die.Tag())
4483         {
4484         case DW_TAG_subprogram:
4485         case DW_TAG_inlined_subroutine:
4486         case DW_TAG_lexical_block:
4487             {
4488                 if (die.GetAttributeValueAsReference (DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
4489                     return die;
4490 
4491                 if (die.GetAttributeValueAsReference (DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
4492                     return die;
4493             }
4494             break;
4495         }
4496 
4497         // Give the concrete function die specified by "func_die_offset", find the
4498         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
4499         // to "spec_block_die_offset"
4500         for (DWARFDIE child_die = die.GetFirstChild(); child_die; child_die = child_die.GetSibling())
4501         {
4502             DWARFDIE result_die = FindBlockContainingSpecification (child_die, spec_block_die_offset);
4503             if (result_die)
4504                 return result_die;
4505         }
4506     }
4507 
4508     return DWARFDIE();
4509 }
4510 
4511 size_t
4512 SymbolFileDWARF::ParseVariables (const SymbolContext& sc,
4513                                  const DWARFDIE &orig_die,
4514                                  const lldb::addr_t func_low_pc,
4515                                  bool parse_siblings,
4516                                  bool parse_children,
4517                                  VariableList* cc_variable_list)
4518 {
4519     if (!orig_die)
4520         return 0;
4521 
4522     VariableListSP variable_list_sp;
4523 
4524     size_t vars_added = 0;
4525     DWARFDIE die = orig_die;
4526     while (die)
4527     {
4528         dw_tag_t tag = die.Tag();
4529 
4530         // Check to see if we have already parsed this variable or constant?
4531         VariableSP var_sp = GetDIEToVariable()[die.GetDIE()];
4532         if (var_sp)
4533         {
4534             if (cc_variable_list)
4535                 cc_variable_list->AddVariableIfUnique (var_sp);
4536         }
4537         else
4538         {
4539             // We haven't already parsed it, lets do that now.
4540             if ((tag == DW_TAG_variable) ||
4541                 (tag == DW_TAG_constant) ||
4542                 (tag == DW_TAG_formal_parameter && sc.function))
4543             {
4544                 if (variable_list_sp.get() == NULL)
4545                 {
4546                     DWARFDIE sc_parent_die = GetParentSymbolContextDIE(orig_die);
4547                     dw_tag_t parent_tag = sc_parent_die.Tag();
4548                     switch (parent_tag)
4549                     {
4550                         case DW_TAG_compile_unit:
4551                             if (sc.comp_unit != NULL)
4552                             {
4553                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
4554                                 if (variable_list_sp.get() == NULL)
4555                                 {
4556                                     variable_list_sp.reset(new VariableList());
4557                                     sc.comp_unit->SetVariableList(variable_list_sp);
4558                                 }
4559                             }
4560                             else
4561                             {
4562                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
4563                                                                            sc_parent_die.GetID(),
4564                                                                            sc_parent_die.GetTagAsCString(),
4565                                                                            orig_die.GetID(),
4566                                                                            orig_die.GetTagAsCString());
4567                             }
4568                             break;
4569 
4570                         case DW_TAG_subprogram:
4571                         case DW_TAG_inlined_subroutine:
4572                         case DW_TAG_lexical_block:
4573                             if (sc.function != NULL)
4574                             {
4575                                 // Check to see if we already have parsed the variables for the given scope
4576 
4577                                 Block *block = sc.function->GetBlock(true).FindBlockByID(sc_parent_die.GetID());
4578                                 if (block == NULL)
4579                                 {
4580                                     // This must be a specification or abstract origin with
4581                                     // a concrete block counterpart in the current function. We need
4582                                     // to find the concrete block so we can correctly add the
4583                                     // variable to it
4584                                     const DWARFDIE concrete_block_die = FindBlockContainingSpecification (DIERef(sc.function->GetID()),
4585                                                                                                           sc_parent_die.GetOffset());
4586                                     if (concrete_block_die)
4587                                         block = sc.function->GetBlock(true).FindBlockByID(concrete_block_die.GetID());
4588                                 }
4589 
4590                                 if (block != NULL)
4591                                 {
4592                                     const bool can_create = false;
4593                                     variable_list_sp = block->GetBlockVariableList (can_create);
4594                                     if (variable_list_sp.get() == NULL)
4595                                     {
4596                                         variable_list_sp.reset(new VariableList());
4597                                         block->SetVariableList(variable_list_sp);
4598                                     }
4599                                 }
4600                             }
4601                             break;
4602 
4603                         default:
4604                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
4605                                                                         orig_die.GetID(),
4606                                                                         orig_die.GetTagAsCString());
4607                             break;
4608                     }
4609                 }
4610 
4611                 if (variable_list_sp)
4612                 {
4613                     VariableSP var_sp (ParseVariableDIE(sc, die, func_low_pc));
4614                     if (var_sp)
4615                     {
4616                         variable_list_sp->AddVariableIfUnique (var_sp);
4617                         if (cc_variable_list)
4618                             cc_variable_list->AddVariableIfUnique (var_sp);
4619                         ++vars_added;
4620                     }
4621                 }
4622             }
4623         }
4624 
4625         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
4626 
4627         if (!skip_children && parse_children && die.HasChildren())
4628         {
4629             vars_added += ParseVariables(sc, die.GetFirstChild(), func_low_pc, true, true, cc_variable_list);
4630         }
4631 
4632         if (parse_siblings)
4633             die = die.GetSibling();
4634         else
4635             die.Clear();
4636     }
4637     return vars_added;
4638 }
4639 
4640 //------------------------------------------------------------------
4641 // PluginInterface protocol
4642 //------------------------------------------------------------------
4643 ConstString
4644 SymbolFileDWARF::GetPluginName()
4645 {
4646     return GetPluginNameStatic();
4647 }
4648 
4649 uint32_t
4650 SymbolFileDWARF::GetPluginVersion()
4651 {
4652     return 1;
4653 }
4654 
4655 void
4656 SymbolFileDWARF::DumpIndexes ()
4657 {
4658     StreamFile s(stdout, false);
4659 
4660     s.Printf ("DWARF index for (%s) '%s':",
4661               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
4662               GetObjectFile()->GetFileSpec().GetPath().c_str());
4663     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
4664     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
4665     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
4666     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
4667     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
4668     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
4669     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
4670     s.Printf("\nNamespaces:\n");            m_namespace_index.Dump (&s);
4671 }
4672 
4673 
4674 SymbolFileDWARFDebugMap *
4675 SymbolFileDWARF::GetDebugMapSymfile ()
4676 {
4677     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
4678     {
4679         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
4680         if (module_sp)
4681         {
4682             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
4683             if (sym_vendor)
4684                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
4685         }
4686     }
4687     return m_debug_map_symfile;
4688 }
4689 
4690 DWARFExpression::LocationListFormat
4691 SymbolFileDWARF::GetLocationListFormat() const
4692 {
4693     return DWARFExpression::RegularLocationList;
4694 }
4695