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