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