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