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