1 //===-- SymbolFileDWARF.cpp ------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "SymbolFileDWARF.h"
11 
12 // Other libraries and framework includes
13 #include "clang/AST/ASTConsumer.h"
14 #include "clang/AST/ASTContext.h"
15 #include "clang/AST/Decl.h"
16 #include "clang/AST/DeclGroup.h"
17 #include "clang/AST/DeclObjC.h"
18 #include "clang/AST/DeclTemplate.h"
19 #include "clang/Basic/Builtins.h"
20 #include "clang/Basic/IdentifierTable.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Basic/Specifiers.h"
25 #include "clang/Sema/DeclSpec.h"
26 
27 #include "llvm/Support/Casting.h"
28 
29 #include "lldb/Core/Module.h"
30 #include "lldb/Core/PluginManager.h"
31 #include "lldb/Core/RegularExpression.h"
32 #include "lldb/Core/Scalar.h"
33 #include "lldb/Core/Section.h"
34 #include "lldb/Core/StreamFile.h"
35 #include "lldb/Core/StreamString.h"
36 #include "lldb/Core/Timer.h"
37 #include "lldb/Core/Value.h"
38 
39 #include "lldb/Host/Host.h"
40 
41 #include "lldb/Symbol/Block.h"
42 #include "lldb/Symbol/ClangExternalASTSourceCallbacks.h"
43 #include "lldb/Symbol/CompileUnit.h"
44 #include "lldb/Symbol/LineTable.h"
45 #include "lldb/Symbol/ObjectFile.h"
46 #include "lldb/Symbol/SymbolVendor.h"
47 #include "lldb/Symbol/VariableList.h"
48 
49 #include "lldb/Target/ObjCLanguageRuntime.h"
50 #include "lldb/Target/CPPLanguageRuntime.h"
51 
52 #include "DWARFCompileUnit.h"
53 #include "DWARFDebugAbbrev.h"
54 #include "DWARFDebugAranges.h"
55 #include "DWARFDebugInfo.h"
56 #include "DWARFDebugInfoEntry.h"
57 #include "DWARFDebugLine.h"
58 #include "DWARFDebugPubnames.h"
59 #include "DWARFDebugRanges.h"
60 #include "DWARFDeclContext.h"
61 #include "DWARFDIECollection.h"
62 #include "DWARFFormValue.h"
63 #include "DWARFLocationList.h"
64 #include "LogChannelDWARF.h"
65 #include "SymbolFileDWARFDebugMap.h"
66 
67 #include <map>
68 
69 #include <ctype.h>
70 #include <string.h>
71 
72 //#define ENABLE_DEBUG_PRINTF // COMMENT OUT THIS LINE PRIOR TO CHECKIN
73 
74 #ifdef ENABLE_DEBUG_PRINTF
75 #include <stdio.h>
76 #define DEBUG_PRINTF(fmt, ...) printf(fmt, __VA_ARGS__)
77 #else
78 #define DEBUG_PRINTF(fmt, ...)
79 #endif
80 
81 #define DIE_IS_BEING_PARSED ((lldb_private::Type*)1)
82 
83 using namespace lldb;
84 using namespace lldb_private;
85 
86 //static inline bool
87 //child_requires_parent_class_union_or_struct_to_be_completed (dw_tag_t tag)
88 //{
89 //    switch (tag)
90 //    {
91 //    default:
92 //        break;
93 //    case DW_TAG_subprogram:
94 //    case DW_TAG_inlined_subroutine:
95 //    case DW_TAG_class_type:
96 //    case DW_TAG_structure_type:
97 //    case DW_TAG_union_type:
98 //        return true;
99 //    }
100 //    return false;
101 //}
102 //
103 static AccessType
104 DW_ACCESS_to_AccessType (uint32_t dwarf_accessibility)
105 {
106     switch (dwarf_accessibility)
107     {
108         case DW_ACCESS_public:      return eAccessPublic;
109         case DW_ACCESS_private:     return eAccessPrivate;
110         case DW_ACCESS_protected:   return eAccessProtected;
111         default:                    break;
112     }
113     return eAccessNone;
114 }
115 
116 static const char*
117 removeHostnameFromPathname(const char* path_from_dwarf)
118 {
119     if (!path_from_dwarf || !path_from_dwarf[0])
120     {
121         return path_from_dwarf;
122     }
123 
124     const char *colon_pos = strchr(path_from_dwarf, ':');
125     if (!colon_pos)
126     {
127         return path_from_dwarf;
128     }
129 
130     // check whether we have a windows path, and so the first character
131     // is a drive-letter not a hostname.
132     if (
133         colon_pos == path_from_dwarf + 1 &&
134         isalpha(*path_from_dwarf) &&
135         strlen(path_from_dwarf) > 2 &&
136         '\\' == path_from_dwarf[2])
137     {
138         return path_from_dwarf;
139     }
140 
141     return colon_pos + 1;
142 }
143 
144 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
145 
146 class DIEStack
147 {
148 public:
149 
150     void Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
151     {
152         m_dies.push_back (DIEInfo(cu, die));
153     }
154 
155 
156     void LogDIEs (Log *log, SymbolFileDWARF *dwarf)
157     {
158         StreamString log_strm;
159         const size_t n = m_dies.size();
160         log_strm.Printf("DIEStack[%" PRIu64 "]:\n", (uint64_t)n);
161         for (size_t i=0; i<n; i++)
162         {
163             DWARFCompileUnit *cu = m_dies[i].cu;
164             const DWARFDebugInfoEntry *die = m_dies[i].die;
165             std::string qualified_name;
166             die->GetQualifiedName(dwarf, cu, qualified_name);
167             log_strm.Printf ("[%" PRIu64 "] 0x%8.8x: %s name='%s'\n",
168                              (uint64_t)i,
169                              die->GetOffset(),
170                              DW_TAG_value_to_name(die->Tag()),
171                              qualified_name.c_str());
172         }
173         log->PutCString(log_strm.GetData());
174     }
175     void Pop ()
176     {
177         m_dies.pop_back();
178     }
179 
180     class ScopedPopper
181     {
182     public:
183         ScopedPopper (DIEStack &die_stack) :
184             m_die_stack (die_stack),
185             m_valid (false)
186         {
187         }
188 
189         void
190         Push (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
191         {
192             m_valid = true;
193             m_die_stack.Push (cu, die);
194         }
195 
196         ~ScopedPopper ()
197         {
198             if (m_valid)
199                 m_die_stack.Pop();
200         }
201 
202 
203 
204     protected:
205         DIEStack &m_die_stack;
206         bool m_valid;
207     };
208 
209 protected:
210     struct DIEInfo {
211         DIEInfo (DWARFCompileUnit *c, const DWARFDebugInfoEntry *d) :
212             cu(c),
213             die(d)
214         {
215         }
216         DWARFCompileUnit *cu;
217         const DWARFDebugInfoEntry *die;
218     };
219     typedef std::vector<DIEInfo> Stack;
220     Stack m_dies;
221 };
222 #endif
223 
224 void
225 SymbolFileDWARF::Initialize()
226 {
227     LogChannelDWARF::Initialize();
228     PluginManager::RegisterPlugin (GetPluginNameStatic(),
229                                    GetPluginDescriptionStatic(),
230                                    CreateInstance);
231 }
232 
233 void
234 SymbolFileDWARF::Terminate()
235 {
236     PluginManager::UnregisterPlugin (CreateInstance);
237     LogChannelDWARF::Initialize();
238 }
239 
240 
241 lldb_private::ConstString
242 SymbolFileDWARF::GetPluginNameStatic()
243 {
244     static ConstString g_name("dwarf");
245     return g_name;
246 }
247 
248 const char *
249 SymbolFileDWARF::GetPluginDescriptionStatic()
250 {
251     return "DWARF and DWARF3 debug symbol file reader.";
252 }
253 
254 
255 SymbolFile*
256 SymbolFileDWARF::CreateInstance (ObjectFile* obj_file)
257 {
258     return new SymbolFileDWARF(obj_file);
259 }
260 
261 TypeList *
262 SymbolFileDWARF::GetTypeList ()
263 {
264     if (GetDebugMapSymfile ())
265         return m_debug_map_symfile->GetTypeList();
266     return m_obj_file->GetModule()->GetTypeList();
267 
268 }
269 void
270 SymbolFileDWARF::GetTypes (DWARFCompileUnit* cu,
271                            const DWARFDebugInfoEntry *die,
272                            dw_offset_t min_die_offset,
273                            dw_offset_t max_die_offset,
274                            uint32_t type_mask,
275                            TypeSet &type_set)
276 {
277     if (cu)
278     {
279         if (die)
280         {
281             const dw_offset_t die_offset = die->GetOffset();
282 
283             if (die_offset >= max_die_offset)
284                 return;
285 
286             if (die_offset >= min_die_offset)
287             {
288                 const dw_tag_t tag = die->Tag();
289 
290                 bool add_type = false;
291 
292                 switch (tag)
293                 {
294                     case DW_TAG_array_type:         add_type = (type_mask & eTypeClassArray         ) != 0; break;
295                     case DW_TAG_unspecified_type:
296                     case DW_TAG_base_type:          add_type = (type_mask & eTypeClassBuiltin       ) != 0; break;
297                     case DW_TAG_class_type:         add_type = (type_mask & eTypeClassClass         ) != 0; break;
298                     case DW_TAG_structure_type:     add_type = (type_mask & eTypeClassStruct        ) != 0; break;
299                     case DW_TAG_union_type:         add_type = (type_mask & eTypeClassUnion         ) != 0; break;
300                     case DW_TAG_enumeration_type:   add_type = (type_mask & eTypeClassEnumeration   ) != 0; break;
301                     case DW_TAG_subroutine_type:
302                     case DW_TAG_subprogram:
303                     case DW_TAG_inlined_subroutine: add_type = (type_mask & eTypeClassFunction      ) != 0; break;
304                     case DW_TAG_pointer_type:       add_type = (type_mask & eTypeClassPointer       ) != 0; break;
305                     case DW_TAG_rvalue_reference_type:
306                     case DW_TAG_reference_type:     add_type = (type_mask & eTypeClassReference     ) != 0; break;
307                     case DW_TAG_typedef:            add_type = (type_mask & eTypeClassTypedef       ) != 0; break;
308                     case DW_TAG_ptr_to_member_type: add_type = (type_mask & eTypeClassMemberPointer ) != 0; break;
309                 }
310 
311                 if (add_type)
312                 {
313                     const bool assert_not_being_parsed = true;
314                     Type *type = ResolveTypeUID (cu, die, assert_not_being_parsed);
315                     if (type)
316                     {
317                         if (type_set.find(type) == type_set.end())
318                             type_set.insert(type);
319                     }
320                 }
321             }
322 
323             for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild();
324                  child_die != NULL;
325                  child_die = child_die->GetSibling())
326             {
327                 GetTypes (cu, child_die, min_die_offset, max_die_offset, type_mask, type_set);
328             }
329         }
330     }
331 }
332 
333 size_t
334 SymbolFileDWARF::GetTypes (SymbolContextScope *sc_scope,
335                            uint32_t type_mask,
336                            TypeList &type_list)
337 
338 {
339     TypeSet type_set;
340 
341     CompileUnit *comp_unit = NULL;
342     DWARFCompileUnit* dwarf_cu = NULL;
343     if (sc_scope)
344         comp_unit = sc_scope->CalculateSymbolContextCompileUnit();
345 
346     if (comp_unit)
347     {
348         dwarf_cu = GetDWARFCompileUnit(comp_unit);
349         if (dwarf_cu == 0)
350             return 0;
351         GetTypes (dwarf_cu,
352                   dwarf_cu->DIE(),
353                   dwarf_cu->GetOffset(),
354                   dwarf_cu->GetNextCompileUnitOffset(),
355                   type_mask,
356                   type_set);
357     }
358     else
359     {
360         DWARFDebugInfo* info = DebugInfo();
361         if (info)
362         {
363             const size_t num_cus = info->GetNumCompileUnits();
364             for (size_t cu_idx=0; cu_idx<num_cus; ++cu_idx)
365             {
366                 dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
367                 if (dwarf_cu)
368                 {
369                     GetTypes (dwarf_cu,
370                               dwarf_cu->DIE(),
371                               0,
372                               UINT32_MAX,
373                               type_mask,
374                               type_set);
375                 }
376             }
377         }
378     }
379 //    if (m_using_apple_tables)
380 //    {
381 //        DWARFMappedHash::MemoryTable *apple_types = m_apple_types_ap.get();
382 //        if (apple_types)
383 //        {
384 //            apple_types->ForEach([this, &type_set, apple_types, type_mask](const DWARFMappedHash::DIEInfoArray &die_info_array) -> bool {
385 //
386 //                for (auto die_info: die_info_array)
387 //                {
388 //                    bool add_type = TagMatchesTypeMask (type_mask, 0);
389 //                    if (!add_type)
390 //                    {
391 //                        dw_tag_t tag = die_info.tag;
392 //                        if (tag == 0)
393 //                        {
394 //                            const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtr(die_info.offset, NULL);
395 //                            tag = die->Tag();
396 //                        }
397 //                        add_type = TagMatchesTypeMask (type_mask, tag);
398 //                    }
399 //                    if (add_type)
400 //                    {
401 //                        Type *type = ResolveTypeUID(die_info.offset);
402 //
403 //                        if (type_set.find(type) == type_set.end())
404 //                            type_set.insert(type);
405 //                    }
406 //                }
407 //                return true; // Keep iterating
408 //            });
409 //        }
410 //    }
411 //    else
412 //    {
413 //        if (!m_indexed)
414 //            Index ();
415 //
416 //        m_type_index.ForEach([this, &type_set, type_mask](const char *name, uint32_t die_offset) -> bool {
417 //
418 //            bool add_type = TagMatchesTypeMask (type_mask, 0);
419 //
420 //            if (!add_type)
421 //            {
422 //                const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtr(die_offset, NULL);
423 //                if (die)
424 //                {
425 //                    const dw_tag_t tag = die->Tag();
426 //                    add_type = TagMatchesTypeMask (type_mask, tag);
427 //                }
428 //            }
429 //
430 //            if (add_type)
431 //            {
432 //                Type *type = ResolveTypeUID(die_offset);
433 //
434 //                if (type_set.find(type) == type_set.end())
435 //                    type_set.insert(type);
436 //            }
437 //            return true; // Keep iterating
438 //        });
439 //    }
440 
441     std::set<ClangASTType> clang_type_set;
442     size_t num_types_added = 0;
443     for (Type *type : type_set)
444     {
445         ClangASTType clang_type = type->GetClangForwardType();
446         if (clang_type_set.find(clang_type) == clang_type_set.end())
447         {
448             clang_type_set.insert(clang_type);
449             type_list.Insert (type->shared_from_this());
450             ++num_types_added;
451         }
452     }
453     return num_types_added;
454 }
455 
456 
457 //----------------------------------------------------------------------
458 // Gets the first parent that is a lexical block, function or inlined
459 // subroutine, or compile unit.
460 //----------------------------------------------------------------------
461 static const DWARFDebugInfoEntry *
462 GetParentSymbolContextDIE(const DWARFDebugInfoEntry *child_die)
463 {
464     const DWARFDebugInfoEntry *die;
465     for (die = child_die->GetParent(); die != NULL; die = die->GetParent())
466     {
467         dw_tag_t tag = die->Tag();
468 
469         switch (tag)
470         {
471         case DW_TAG_compile_unit:
472         case DW_TAG_subprogram:
473         case DW_TAG_inlined_subroutine:
474         case DW_TAG_lexical_block:
475             return die;
476         }
477     }
478     return NULL;
479 }
480 
481 
482 SymbolFileDWARF::SymbolFileDWARF(ObjectFile* objfile) :
483     SymbolFile (objfile),
484     UserID (0),  // Used by SymbolFileDWARFDebugMap to when this class parses .o files to contain the .o file index/ID
485     m_debug_map_module_wp (),
486     m_debug_map_symfile (NULL),
487     m_clang_tu_decl (NULL),
488     m_flags(),
489     m_data_debug_abbrev (),
490     m_data_debug_aranges (),
491     m_data_debug_frame (),
492     m_data_debug_info (),
493     m_data_debug_line (),
494     m_data_debug_loc (),
495     m_data_debug_ranges (),
496     m_data_debug_str (),
497     m_data_apple_names (),
498     m_data_apple_types (),
499     m_data_apple_namespaces (),
500     m_abbr(),
501     m_info(),
502     m_line(),
503     m_apple_names_ap (),
504     m_apple_types_ap (),
505     m_apple_namespaces_ap (),
506     m_apple_objc_ap (),
507     m_function_basename_index(),
508     m_function_fullname_index(),
509     m_function_method_index(),
510     m_function_selector_index(),
511     m_objc_class_selectors_index(),
512     m_global_index(),
513     m_type_index(),
514     m_namespace_index(),
515     m_indexed (false),
516     m_is_external_ast_source (false),
517     m_using_apple_tables (false),
518     m_supports_DW_AT_APPLE_objc_complete_type (eLazyBoolCalculate),
519     m_ranges(),
520     m_unique_ast_type_map ()
521 {
522 }
523 
524 SymbolFileDWARF::~SymbolFileDWARF()
525 {
526     if (m_is_external_ast_source)
527     {
528         ModuleSP module_sp (m_obj_file->GetModule());
529         if (module_sp)
530             module_sp->GetClangASTContext().RemoveExternalSource ();
531     }
532 }
533 
534 static const ConstString &
535 GetDWARFMachOSegmentName ()
536 {
537     static ConstString g_dwarf_section_name ("__DWARF");
538     return g_dwarf_section_name;
539 }
540 
541 UniqueDWARFASTTypeMap &
542 SymbolFileDWARF::GetUniqueDWARFASTTypeMap ()
543 {
544     if (GetDebugMapSymfile ())
545         return m_debug_map_symfile->GetUniqueDWARFASTTypeMap ();
546     return m_unique_ast_type_map;
547 }
548 
549 ClangASTContext &
550 SymbolFileDWARF::GetClangASTContext ()
551 {
552     if (GetDebugMapSymfile ())
553         return m_debug_map_symfile->GetClangASTContext ();
554 
555     ClangASTContext &ast = m_obj_file->GetModule()->GetClangASTContext();
556     if (!m_is_external_ast_source)
557     {
558         m_is_external_ast_source = true;
559         llvm::IntrusiveRefCntPtr<clang::ExternalASTSource> ast_source_ap (
560             new ClangExternalASTSourceCallbacks (SymbolFileDWARF::CompleteTagDecl,
561                                                  SymbolFileDWARF::CompleteObjCInterfaceDecl,
562                                                  SymbolFileDWARF::FindExternalVisibleDeclsByName,
563                                                  SymbolFileDWARF::LayoutRecordType,
564                                                  this));
565         ast.SetExternalSource (ast_source_ap);
566     }
567     return ast;
568 }
569 
570 void
571 SymbolFileDWARF::InitializeObject()
572 {
573     // Install our external AST source callbacks so we can complete Clang types.
574     ModuleSP module_sp (m_obj_file->GetModule());
575     if (module_sp)
576     {
577         const SectionList *section_list = module_sp->GetSectionList();
578 
579         const Section* section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
580 
581         // Memory map the DWARF mach-o segment so we have everything mmap'ed
582         // to keep our heap memory usage down.
583         if (section)
584             m_obj_file->MemoryMapSectionData(section, m_dwarf_data);
585     }
586     get_apple_names_data();
587     if (m_data_apple_names.GetByteSize() > 0)
588     {
589         m_apple_names_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_names, get_debug_str_data(), ".apple_names"));
590         if (m_apple_names_ap->IsValid())
591             m_using_apple_tables = true;
592         else
593             m_apple_names_ap.reset();
594     }
595     get_apple_types_data();
596     if (m_data_apple_types.GetByteSize() > 0)
597     {
598         m_apple_types_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_types, get_debug_str_data(), ".apple_types"));
599         if (m_apple_types_ap->IsValid())
600             m_using_apple_tables = true;
601         else
602             m_apple_types_ap.reset();
603     }
604 
605     get_apple_namespaces_data();
606     if (m_data_apple_namespaces.GetByteSize() > 0)
607     {
608         m_apple_namespaces_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_namespaces, get_debug_str_data(), ".apple_namespaces"));
609         if (m_apple_namespaces_ap->IsValid())
610             m_using_apple_tables = true;
611         else
612             m_apple_namespaces_ap.reset();
613     }
614 
615     get_apple_objc_data();
616     if (m_data_apple_objc.GetByteSize() > 0)
617     {
618         m_apple_objc_ap.reset (new DWARFMappedHash::MemoryTable (m_data_apple_objc, get_debug_str_data(), ".apple_objc"));
619         if (m_apple_objc_ap->IsValid())
620             m_using_apple_tables = true;
621         else
622             m_apple_objc_ap.reset();
623     }
624 }
625 
626 bool
627 SymbolFileDWARF::SupportedVersion(uint16_t version)
628 {
629     return version == 2 || version == 3 || version == 4;
630 }
631 
632 uint32_t
633 SymbolFileDWARF::CalculateAbilities ()
634 {
635     uint32_t abilities = 0;
636     if (m_obj_file != NULL)
637     {
638         const Section* section = NULL;
639         const SectionList *section_list = m_obj_file->GetSectionList();
640         if (section_list == NULL)
641             return 0;
642 
643         uint64_t debug_abbrev_file_size = 0;
644         uint64_t debug_info_file_size = 0;
645         uint64_t debug_line_file_size = 0;
646 
647         section = section_list->FindSectionByName(GetDWARFMachOSegmentName ()).get();
648 
649         if (section)
650             section_list = &section->GetChildren ();
651 
652         section = section_list->FindSectionByType (eSectionTypeDWARFDebugInfo, true).get();
653         if (section != NULL)
654         {
655             debug_info_file_size = section->GetFileSize();
656 
657             section = section_list->FindSectionByType (eSectionTypeDWARFDebugAbbrev, true).get();
658             if (section)
659                 debug_abbrev_file_size = section->GetFileSize();
660             else
661                 m_flags.Set (flagsGotDebugAbbrevData);
662 
663             section = section_list->FindSectionByType (eSectionTypeDWARFDebugAranges, true).get();
664             if (!section)
665                 m_flags.Set (flagsGotDebugArangesData);
666 
667             section = section_list->FindSectionByType (eSectionTypeDWARFDebugFrame, true).get();
668             if (!section)
669                 m_flags.Set (flagsGotDebugFrameData);
670 
671             section = section_list->FindSectionByType (eSectionTypeDWARFDebugLine, true).get();
672             if (section)
673                 debug_line_file_size = section->GetFileSize();
674             else
675                 m_flags.Set (flagsGotDebugLineData);
676 
677             section = section_list->FindSectionByType (eSectionTypeDWARFDebugLoc, true).get();
678             if (!section)
679                 m_flags.Set (flagsGotDebugLocData);
680 
681             section = section_list->FindSectionByType (eSectionTypeDWARFDebugMacInfo, true).get();
682             if (!section)
683                 m_flags.Set (flagsGotDebugMacInfoData);
684 
685             section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubNames, true).get();
686             if (!section)
687                 m_flags.Set (flagsGotDebugPubNamesData);
688 
689             section = section_list->FindSectionByType (eSectionTypeDWARFDebugPubTypes, true).get();
690             if (!section)
691                 m_flags.Set (flagsGotDebugPubTypesData);
692 
693             section = section_list->FindSectionByType (eSectionTypeDWARFDebugRanges, true).get();
694             if (!section)
695                 m_flags.Set (flagsGotDebugRangesData);
696 
697             section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
698             if (!section)
699                 m_flags.Set (flagsGotDebugStrData);
700         }
701         else
702         {
703             const char *symfile_dir_cstr = m_obj_file->GetFileSpec().GetDirectory().GetCString();
704             if (symfile_dir_cstr)
705             {
706                 if (strcasestr(symfile_dir_cstr, ".dsym"))
707                 {
708                     if (m_obj_file->GetType() == ObjectFile::eTypeDebugInfo)
709                     {
710                         // We have a dSYM file that didn't have a any debug info.
711                         // If the string table has a size of 1, then it was made from
712                         // an executable with no debug info, or from an executable that
713                         // was stripped.
714                         section = section_list->FindSectionByType (eSectionTypeDWARFDebugStr, true).get();
715                         if (section && section->GetFileSize() == 1)
716                         {
717                             m_obj_file->GetModule()->ReportWarning ("empty dSYM file detected, dSYM was created with an executable with no debug info.");
718                         }
719                     }
720                 }
721             }
722         }
723 
724         if (debug_abbrev_file_size > 0 && debug_info_file_size > 0)
725             abilities |= CompileUnits | Functions | Blocks | GlobalVariables | LocalVariables | VariableTypes;
726 
727         if (debug_line_file_size > 0)
728             abilities |= LineTables;
729     }
730     return abilities;
731 }
732 
733 const DWARFDataExtractor&
734 SymbolFileDWARF::GetCachedSectionData (uint32_t got_flag, SectionType sect_type, DWARFDataExtractor &data)
735 {
736     if (m_flags.IsClear (got_flag))
737     {
738         ModuleSP module_sp (m_obj_file->GetModule());
739         m_flags.Set (got_flag);
740         const SectionList *section_list = module_sp->GetSectionList();
741         if (section_list)
742         {
743             SectionSP section_sp (section_list->FindSectionByType(sect_type, true));
744             if (section_sp)
745             {
746                 // See if we memory mapped the DWARF segment?
747                 if (m_dwarf_data.GetByteSize())
748                 {
749                     data.SetData(m_dwarf_data, section_sp->GetOffset (), section_sp->GetFileSize());
750                 }
751                 else
752                 {
753                     if (m_obj_file->ReadSectionData (section_sp.get(), data) == 0)
754                         data.Clear();
755                 }
756             }
757         }
758     }
759     return data;
760 }
761 
762 const DWARFDataExtractor&
763 SymbolFileDWARF::get_debug_abbrev_data()
764 {
765     return GetCachedSectionData (flagsGotDebugAbbrevData, eSectionTypeDWARFDebugAbbrev, m_data_debug_abbrev);
766 }
767 
768 const DWARFDataExtractor&
769 SymbolFileDWARF::get_debug_aranges_data()
770 {
771     return GetCachedSectionData (flagsGotDebugArangesData, eSectionTypeDWARFDebugAranges, m_data_debug_aranges);
772 }
773 
774 const DWARFDataExtractor&
775 SymbolFileDWARF::get_debug_frame_data()
776 {
777     return GetCachedSectionData (flagsGotDebugFrameData, eSectionTypeDWARFDebugFrame, m_data_debug_frame);
778 }
779 
780 const DWARFDataExtractor&
781 SymbolFileDWARF::get_debug_info_data()
782 {
783     return GetCachedSectionData (flagsGotDebugInfoData, eSectionTypeDWARFDebugInfo, m_data_debug_info);
784 }
785 
786 const DWARFDataExtractor&
787 SymbolFileDWARF::get_debug_line_data()
788 {
789     return GetCachedSectionData (flagsGotDebugLineData, eSectionTypeDWARFDebugLine, m_data_debug_line);
790 }
791 
792 const DWARFDataExtractor&
793 SymbolFileDWARF::get_debug_loc_data()
794 {
795     return GetCachedSectionData (flagsGotDebugLocData, eSectionTypeDWARFDebugLoc, m_data_debug_loc);
796 }
797 
798 const DWARFDataExtractor&
799 SymbolFileDWARF::get_debug_ranges_data()
800 {
801     return GetCachedSectionData (flagsGotDebugRangesData, eSectionTypeDWARFDebugRanges, m_data_debug_ranges);
802 }
803 
804 const DWARFDataExtractor&
805 SymbolFileDWARF::get_debug_str_data()
806 {
807     return GetCachedSectionData (flagsGotDebugStrData, eSectionTypeDWARFDebugStr, m_data_debug_str);
808 }
809 
810 const DWARFDataExtractor&
811 SymbolFileDWARF::get_apple_names_data()
812 {
813     return GetCachedSectionData (flagsGotAppleNamesData, eSectionTypeDWARFAppleNames, m_data_apple_names);
814 }
815 
816 const DWARFDataExtractor&
817 SymbolFileDWARF::get_apple_types_data()
818 {
819     return GetCachedSectionData (flagsGotAppleTypesData, eSectionTypeDWARFAppleTypes, m_data_apple_types);
820 }
821 
822 const DWARFDataExtractor&
823 SymbolFileDWARF::get_apple_namespaces_data()
824 {
825     return GetCachedSectionData (flagsGotAppleNamespacesData, eSectionTypeDWARFAppleNamespaces, m_data_apple_namespaces);
826 }
827 
828 const DWARFDataExtractor&
829 SymbolFileDWARF::get_apple_objc_data()
830 {
831     return GetCachedSectionData (flagsGotAppleObjCData, eSectionTypeDWARFAppleObjC, m_data_apple_objc);
832 }
833 
834 
835 DWARFDebugAbbrev*
836 SymbolFileDWARF::DebugAbbrev()
837 {
838     if (m_abbr.get() == NULL)
839     {
840         const DWARFDataExtractor &debug_abbrev_data = get_debug_abbrev_data();
841         if (debug_abbrev_data.GetByteSize() > 0)
842         {
843             m_abbr.reset(new DWARFDebugAbbrev());
844             if (m_abbr.get())
845                 m_abbr->Parse(debug_abbrev_data);
846         }
847     }
848     return m_abbr.get();
849 }
850 
851 const DWARFDebugAbbrev*
852 SymbolFileDWARF::DebugAbbrev() const
853 {
854     return m_abbr.get();
855 }
856 
857 
858 DWARFDebugInfo*
859 SymbolFileDWARF::DebugInfo()
860 {
861     if (m_info.get() == NULL)
862     {
863         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
864                            __PRETTY_FUNCTION__, static_cast<void*>(this));
865         if (get_debug_info_data().GetByteSize() > 0)
866         {
867             m_info.reset(new DWARFDebugInfo());
868             if (m_info.get())
869             {
870                 m_info->SetDwarfData(this);
871             }
872         }
873     }
874     return m_info.get();
875 }
876 
877 const DWARFDebugInfo*
878 SymbolFileDWARF::DebugInfo() const
879 {
880     return m_info.get();
881 }
882 
883 DWARFCompileUnit*
884 SymbolFileDWARF::GetDWARFCompileUnit(lldb_private::CompileUnit *comp_unit)
885 {
886     DWARFDebugInfo* info = DebugInfo();
887     if (info)
888     {
889         if (GetDebugMapSymfile ())
890         {
891             // The debug map symbol file made the compile units for this DWARF
892             // file which is .o file with DWARF in it, and we should have
893             // only 1 compile unit which is at offset zero in the DWARF.
894             // TODO: modify to support LTO .o files where each .o file might
895             // have multiple DW_TAG_compile_unit tags.
896 
897             DWARFCompileUnit *dwarf_cu = info->GetCompileUnit(0).get();
898             if (dwarf_cu && dwarf_cu->GetUserData() == NULL)
899                 dwarf_cu->SetUserData(comp_unit);
900             return dwarf_cu;
901         }
902         else
903         {
904             // Just a normal DWARF file whose user ID for the compile unit is
905             // the DWARF offset itself
906 
907             DWARFCompileUnit *dwarf_cu = info->GetCompileUnit((dw_offset_t)comp_unit->GetID()).get();
908             if (dwarf_cu && dwarf_cu->GetUserData() == NULL)
909                 dwarf_cu->SetUserData(comp_unit);
910             return dwarf_cu;
911 
912         }
913     }
914     return NULL;
915 }
916 
917 
918 DWARFDebugRanges*
919 SymbolFileDWARF::DebugRanges()
920 {
921     if (m_ranges.get() == NULL)
922     {
923         Timer scoped_timer(__PRETTY_FUNCTION__, "%s this = %p",
924                            __PRETTY_FUNCTION__, static_cast<void*>(this));
925         if (get_debug_ranges_data().GetByteSize() > 0)
926         {
927             m_ranges.reset(new DWARFDebugRanges());
928             if (m_ranges.get())
929                 m_ranges->Extract(this);
930         }
931     }
932     return m_ranges.get();
933 }
934 
935 const DWARFDebugRanges*
936 SymbolFileDWARF::DebugRanges() const
937 {
938     return m_ranges.get();
939 }
940 
941 lldb::CompUnitSP
942 SymbolFileDWARF::ParseCompileUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
943 {
944     CompUnitSP cu_sp;
945     if (dwarf_cu)
946     {
947         CompileUnit *comp_unit = (CompileUnit*)dwarf_cu->GetUserData();
948         if (comp_unit)
949         {
950             // We already parsed this compile unit, had out a shared pointer to it
951             cu_sp = comp_unit->shared_from_this();
952         }
953         else
954         {
955             if (GetDebugMapSymfile ())
956             {
957                 // Let the debug map create the compile unit
958                 cu_sp = m_debug_map_symfile->GetCompileUnit(this);
959                 dwarf_cu->SetUserData(cu_sp.get());
960             }
961             else
962             {
963                 ModuleSP module_sp (m_obj_file->GetModule());
964                 if (module_sp)
965                 {
966                     const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly ();
967                     if (cu_die)
968                     {
969                         const char * cu_die_name = cu_die->GetName(this, dwarf_cu);
970                         const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
971                         LanguageType cu_language = (LanguageType)cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
972                         if (cu_die_name)
973                         {
974                             std::string ramapped_file;
975                             FileSpec cu_file_spec;
976 
977                             if (cu_die_name[0] == '/' || cu_comp_dir == NULL || cu_comp_dir[0] == '\0')
978                             {
979                                 // If we have a full path to the compile unit, we don't need to resolve
980                                 // the file.  This can be expensive e.g. when the source files are NFS mounted.
981                                 if (module_sp->RemapSourceFile(cu_die_name, ramapped_file))
982                                     cu_file_spec.SetFile (ramapped_file.c_str(), false);
983                                 else
984                                     cu_file_spec.SetFile (cu_die_name, false);
985                             }
986                             else
987                             {
988                                 // DWARF2/3 suggests the form hostname:pathname for compilation directory.
989                                 // Remove the host part if present.
990                                 cu_comp_dir = removeHostnameFromPathname(cu_comp_dir);
991                                 std::string fullpath(cu_comp_dir);
992 
993                                 if (*fullpath.rbegin() != '/')
994                                     fullpath += '/';
995                                 fullpath += cu_die_name;
996                                 if (module_sp->RemapSourceFile (fullpath.c_str(), ramapped_file))
997                                     cu_file_spec.SetFile (ramapped_file.c_str(), false);
998                                 else
999                                     cu_file_spec.SetFile (fullpath.c_str(), false);
1000                             }
1001 
1002                             cu_sp.reset(new CompileUnit (module_sp,
1003                                                          dwarf_cu,
1004                                                          cu_file_spec,
1005                                                          MakeUserID(dwarf_cu->GetOffset()),
1006                                                          cu_language));
1007                             if (cu_sp)
1008                             {
1009                                 dwarf_cu->SetUserData(cu_sp.get());
1010 
1011                                 // Figure out the compile unit index if we weren't given one
1012                                 if (cu_idx == UINT32_MAX)
1013                                     DebugInfo()->GetCompileUnit(dwarf_cu->GetOffset(), &cu_idx);
1014 
1015                                 m_obj_file->GetModule()->GetSymbolVendor()->SetCompileUnitAtIndex(cu_idx, cu_sp);
1016                             }
1017                         }
1018                     }
1019                 }
1020             }
1021         }
1022     }
1023     return cu_sp;
1024 }
1025 
1026 uint32_t
1027 SymbolFileDWARF::GetNumCompileUnits()
1028 {
1029     DWARFDebugInfo* info = DebugInfo();
1030     if (info)
1031         return info->GetNumCompileUnits();
1032     return 0;
1033 }
1034 
1035 CompUnitSP
1036 SymbolFileDWARF::ParseCompileUnitAtIndex(uint32_t cu_idx)
1037 {
1038     CompUnitSP cu_sp;
1039     DWARFDebugInfo* info = DebugInfo();
1040     if (info)
1041     {
1042         DWARFCompileUnit* dwarf_cu = info->GetCompileUnitAtIndex(cu_idx);
1043         if (dwarf_cu)
1044             cu_sp = ParseCompileUnit(dwarf_cu, cu_idx);
1045     }
1046     return cu_sp;
1047 }
1048 
1049 Function *
1050 SymbolFileDWARF::ParseCompileUnitFunction (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die)
1051 {
1052     DWARFDebugRanges::RangeList func_ranges;
1053     const char *name = NULL;
1054     const char *mangled = NULL;
1055     int decl_file = 0;
1056     int decl_line = 0;
1057     int decl_column = 0;
1058     int call_file = 0;
1059     int call_line = 0;
1060     int call_column = 0;
1061     DWARFExpression frame_base;
1062 
1063     assert (die->Tag() == DW_TAG_subprogram);
1064 
1065     if (die->Tag() != DW_TAG_subprogram)
1066         return NULL;
1067 
1068     if (die->GetDIENamesAndRanges (this,
1069                                    dwarf_cu,
1070                                    name,
1071                                    mangled,
1072                                    func_ranges,
1073                                    decl_file,
1074                                    decl_line,
1075                                    decl_column,
1076                                    call_file,
1077                                    call_line,
1078                                    call_column,
1079                                    &frame_base))
1080     {
1081         // Union of all ranges in the function DIE (if the function is discontiguous)
1082         AddressRange func_range;
1083         lldb::addr_t lowest_func_addr = func_ranges.GetMinRangeBase (0);
1084         lldb::addr_t highest_func_addr = func_ranges.GetMaxRangeEnd (0);
1085         if (lowest_func_addr != LLDB_INVALID_ADDRESS && lowest_func_addr <= highest_func_addr)
1086         {
1087             ModuleSP module_sp (m_obj_file->GetModule());
1088             func_range.GetBaseAddress().ResolveAddressUsingFileSections (lowest_func_addr, module_sp->GetSectionList());
1089             if (func_range.GetBaseAddress().IsValid())
1090                 func_range.SetByteSize(highest_func_addr - lowest_func_addr);
1091         }
1092 
1093         if (func_range.GetBaseAddress().IsValid())
1094         {
1095             Mangled func_name;
1096             if (mangled)
1097                 func_name.SetValue(ConstString(mangled), true);
1098             else if (die->GetParent()->Tag() == DW_TAG_compile_unit &&
1099                      LanguageRuntime::LanguageIsCPlusPlus(dwarf_cu->GetLanguageType()) &&
1100                      strcmp(name, "main") != 0)
1101             {
1102                 // If the mangled name is not present in the DWARF, generate the demangled name
1103                 // using the decl context. We skip if the function is "main" as its name is
1104                 // never mangled.
1105                 bool is_static = false;
1106                 bool is_variadic = false;
1107                 unsigned type_quals = 0;
1108                 std::vector<ClangASTType> param_types;
1109                 std::vector<clang::ParmVarDecl*> param_decls;
1110                 const DWARFDebugInfoEntry *decl_ctx_die = NULL;
1111                 DWARFDeclContext decl_ctx;
1112                 StreamString sstr;
1113 
1114                 die->GetDWARFDeclContext(this, dwarf_cu, decl_ctx);
1115                 sstr << decl_ctx.GetQualifiedName();
1116 
1117                 clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE(dwarf_cu,
1118                                                                                            die,
1119                                                                                            &decl_ctx_die);
1120                 ParseChildParameters(sc,
1121                                      containing_decl_ctx,
1122                                      dwarf_cu,
1123                                      die,
1124                                      true,
1125                                      is_static,
1126                                      is_variadic,
1127                                      param_types,
1128                                      param_decls,
1129                                      type_quals);
1130                 sstr << "(";
1131                 for (size_t i = 0; i < param_types.size(); i++)
1132                 {
1133                     if (i > 0)
1134                         sstr << ", ";
1135                     sstr << param_types[i].GetTypeName();
1136                 }
1137                 if (is_variadic)
1138                     sstr << ", ...";
1139                 sstr << ")";
1140                 if (type_quals & clang::Qualifiers::Const)
1141                     sstr << " const";
1142 
1143                 func_name.SetValue(ConstString(sstr.GetData()), false);
1144             }
1145             else
1146                 func_name.SetValue(ConstString(name), false);
1147 
1148             FunctionSP func_sp;
1149             std::unique_ptr<Declaration> decl_ap;
1150             if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1151                 decl_ap.reset(new Declaration (sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1152                                                decl_line,
1153                                                decl_column));
1154 
1155             // Supply the type _only_ if it has already been parsed
1156             Type *func_type = m_die_to_type.lookup (die);
1157 
1158             assert(func_type == NULL || func_type != DIE_IS_BEING_PARSED);
1159 
1160             if (FixupAddress (func_range.GetBaseAddress()))
1161             {
1162                 const user_id_t func_user_id = MakeUserID(die->GetOffset());
1163                 func_sp.reset(new Function (sc.comp_unit,
1164                                             MakeUserID(func_user_id),       // UserID is the DIE offset
1165                                             MakeUserID(func_user_id),
1166                                             func_name,
1167                                             func_type,
1168                                             func_range));           // first address range
1169 
1170                 if (func_sp.get() != NULL)
1171                 {
1172                     if (frame_base.IsValid())
1173                         func_sp->GetFrameBaseExpression() = frame_base;
1174                     sc.comp_unit->AddFunction(func_sp);
1175                     return func_sp.get();
1176                 }
1177             }
1178         }
1179     }
1180     return NULL;
1181 }
1182 
1183 bool
1184 SymbolFileDWARF::FixupAddress (Address &addr)
1185 {
1186     SymbolFileDWARFDebugMap * debug_map_symfile = GetDebugMapSymfile ();
1187     if (debug_map_symfile)
1188     {
1189         return debug_map_symfile->LinkOSOAddress(addr);
1190     }
1191     // This is a normal DWARF file, no address fixups need to happen
1192     return true;
1193 }
1194 lldb::LanguageType
1195 SymbolFileDWARF::ParseCompileUnitLanguage (const SymbolContext& sc)
1196 {
1197     assert (sc.comp_unit);
1198     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1199     if (dwarf_cu)
1200     {
1201         const DWARFDebugInfoEntry *die = dwarf_cu->GetCompileUnitDIEOnly();
1202         if (die)
1203         {
1204             const uint32_t language = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_language, 0);
1205             if (language)
1206                 return (lldb::LanguageType)language;
1207         }
1208     }
1209     return eLanguageTypeUnknown;
1210 }
1211 
1212 size_t
1213 SymbolFileDWARF::ParseCompileUnitFunctions(const SymbolContext &sc)
1214 {
1215     assert (sc.comp_unit);
1216     size_t functions_added = 0;
1217     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1218     if (dwarf_cu)
1219     {
1220         DWARFDIECollection function_dies;
1221         const size_t num_functions = dwarf_cu->AppendDIEsWithTag (DW_TAG_subprogram, function_dies);
1222         size_t func_idx;
1223         for (func_idx = 0; func_idx < num_functions; ++func_idx)
1224         {
1225             const DWARFDebugInfoEntry *die = function_dies.GetDIEPtrAtIndex(func_idx);
1226             if (sc.comp_unit->FindFunctionByUID (MakeUserID(die->GetOffset())).get() == NULL)
1227             {
1228                 if (ParseCompileUnitFunction(sc, dwarf_cu, die))
1229                     ++functions_added;
1230             }
1231         }
1232         //FixupTypes();
1233     }
1234     return functions_added;
1235 }
1236 
1237 bool
1238 SymbolFileDWARF::ParseCompileUnitSupportFiles (const SymbolContext& sc, FileSpecList& support_files)
1239 {
1240     assert (sc.comp_unit);
1241     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1242     if (dwarf_cu)
1243     {
1244         const DWARFDebugInfoEntry * cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1245 
1246         if (cu_die)
1247         {
1248             const char * cu_comp_dir = cu_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_comp_dir, NULL);
1249 
1250             // DWARF2/3 suggests the form hostname:pathname for compilation directory.
1251             // Remove the host part if present.
1252             cu_comp_dir = removeHostnameFromPathname(cu_comp_dir);
1253 
1254             dw_offset_t stmt_list = cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
1255 
1256             // All file indexes in DWARF are one based and a file of index zero is
1257             // supposed to be the compile unit itself.
1258             support_files.Append (*sc.comp_unit);
1259 
1260             return DWARFDebugLine::ParseSupportFiles(sc.comp_unit->GetModule(), get_debug_line_data(), cu_comp_dir, stmt_list, support_files);
1261         }
1262     }
1263     return false;
1264 }
1265 
1266 struct ParseDWARFLineTableCallbackInfo
1267 {
1268     LineTable* line_table;
1269     std::unique_ptr<LineSequence> sequence_ap;
1270 };
1271 
1272 //----------------------------------------------------------------------
1273 // ParseStatementTableCallback
1274 //----------------------------------------------------------------------
1275 static void
1276 ParseDWARFLineTableCallback(dw_offset_t offset, const DWARFDebugLine::State& state, void* userData)
1277 {
1278     if (state.row == DWARFDebugLine::State::StartParsingLineTable)
1279     {
1280         // Just started parsing the line table
1281     }
1282     else if (state.row == DWARFDebugLine::State::DoneParsingLineTable)
1283     {
1284         // Done parsing line table, nothing to do for the cleanup
1285     }
1286     else
1287     {
1288         ParseDWARFLineTableCallbackInfo* info = (ParseDWARFLineTableCallbackInfo*)userData;
1289         LineTable* line_table = info->line_table;
1290 
1291         // If this is our first time here, we need to create a
1292         // sequence container.
1293         if (!info->sequence_ap.get())
1294         {
1295             info->sequence_ap.reset(line_table->CreateLineSequenceContainer());
1296             assert(info->sequence_ap.get());
1297         }
1298         line_table->AppendLineEntryToSequence (info->sequence_ap.get(),
1299                                                state.address,
1300                                                state.line,
1301                                                state.column,
1302                                                state.file,
1303                                                state.is_stmt,
1304                                                state.basic_block,
1305                                                state.prologue_end,
1306                                                state.epilogue_begin,
1307                                                state.end_sequence);
1308         if (state.end_sequence)
1309         {
1310             // First, put the current sequence into the line table.
1311             line_table->InsertSequence(info->sequence_ap.get());
1312             // Then, empty it to prepare for the next sequence.
1313             info->sequence_ap->Clear();
1314         }
1315     }
1316 }
1317 
1318 bool
1319 SymbolFileDWARF::ParseCompileUnitLineTable (const SymbolContext &sc)
1320 {
1321     assert (sc.comp_unit);
1322     if (sc.comp_unit->GetLineTable() != NULL)
1323         return true;
1324 
1325     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
1326     if (dwarf_cu)
1327     {
1328         const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->GetCompileUnitDIEOnly();
1329         if (dwarf_cu_die)
1330         {
1331             const dw_offset_t cu_line_offset = dwarf_cu_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_stmt_list, DW_INVALID_OFFSET);
1332             if (cu_line_offset != DW_INVALID_OFFSET)
1333             {
1334                 std::unique_ptr<LineTable> line_table_ap(new LineTable(sc.comp_unit));
1335                 if (line_table_ap.get())
1336                 {
1337                     ParseDWARFLineTableCallbackInfo info;
1338                     info.line_table = line_table_ap.get();
1339                     lldb::offset_t offset = cu_line_offset;
1340                     DWARFDebugLine::ParseStatementTable(get_debug_line_data(), &offset, ParseDWARFLineTableCallback, &info);
1341                     if (m_debug_map_symfile)
1342                     {
1343                         // We have an object file that has a line table with addresses
1344                         // that are not linked. We need to link the line table and convert
1345                         // the addresses that are relative to the .o file into addresses
1346                         // for the main executable.
1347                         sc.comp_unit->SetLineTable (m_debug_map_symfile->LinkOSOLineTable (this, line_table_ap.get()));
1348                     }
1349                     else
1350                     {
1351                         sc.comp_unit->SetLineTable(line_table_ap.release());
1352                         return true;
1353                     }
1354                 }
1355             }
1356         }
1357     }
1358     return false;
1359 }
1360 
1361 size_t
1362 SymbolFileDWARF::ParseFunctionBlocks
1363 (
1364     const SymbolContext& sc,
1365     Block *parent_block,
1366     DWARFCompileUnit* dwarf_cu,
1367     const DWARFDebugInfoEntry *die,
1368     addr_t subprogram_low_pc,
1369     uint32_t depth
1370 )
1371 {
1372     size_t blocks_added = 0;
1373     while (die != NULL)
1374     {
1375         dw_tag_t tag = die->Tag();
1376 
1377         switch (tag)
1378         {
1379         case DW_TAG_inlined_subroutine:
1380         case DW_TAG_subprogram:
1381         case DW_TAG_lexical_block:
1382             {
1383                 Block *block = NULL;
1384                 if (tag == DW_TAG_subprogram)
1385                 {
1386                     // Skip any DW_TAG_subprogram DIEs that are inside
1387                     // of a normal or inlined functions. These will be
1388                     // parsed on their own as separate entities.
1389 
1390                     if (depth > 0)
1391                         break;
1392 
1393                     block = parent_block;
1394                 }
1395                 else
1396                 {
1397                     BlockSP block_sp(new Block (MakeUserID(die->GetOffset())));
1398                     parent_block->AddChild(block_sp);
1399                     block = block_sp.get();
1400                 }
1401                 DWARFDebugRanges::RangeList ranges;
1402                 const char *name = NULL;
1403                 const char *mangled_name = NULL;
1404 
1405                 int decl_file = 0;
1406                 int decl_line = 0;
1407                 int decl_column = 0;
1408                 int call_file = 0;
1409                 int call_line = 0;
1410                 int call_column = 0;
1411                 if (die->GetDIENamesAndRanges (this,
1412                                                dwarf_cu,
1413                                                name,
1414                                                mangled_name,
1415                                                ranges,
1416                                                decl_file, decl_line, decl_column,
1417                                                call_file, call_line, call_column))
1418                 {
1419                     if (tag == DW_TAG_subprogram)
1420                     {
1421                         assert (subprogram_low_pc == LLDB_INVALID_ADDRESS);
1422                         subprogram_low_pc = ranges.GetMinRangeBase(0);
1423                     }
1424                     else if (tag == DW_TAG_inlined_subroutine)
1425                     {
1426                         // We get called here for inlined subroutines in two ways.
1427                         // The first time is when we are making the Function object
1428                         // for this inlined concrete instance.  Since we're creating a top level block at
1429                         // here, the subprogram_low_pc will be LLDB_INVALID_ADDRESS.  So we need to
1430                         // adjust the containing address.
1431                         // The second time is when we are parsing the blocks inside the function that contains
1432                         // the inlined concrete instance.  Since these will be blocks inside the containing "real"
1433                         // function the offset will be for that function.
1434                         if (subprogram_low_pc == LLDB_INVALID_ADDRESS)
1435                         {
1436                             subprogram_low_pc = ranges.GetMinRangeBase(0);
1437                         }
1438                     }
1439 
1440                     const size_t num_ranges = ranges.GetSize();
1441                     for (size_t i = 0; i<num_ranges; ++i)
1442                     {
1443                         const DWARFDebugRanges::Range &range = ranges.GetEntryRef (i);
1444                         const addr_t range_base = range.GetRangeBase();
1445                         if (range_base >= subprogram_low_pc)
1446                             block->AddRange(Block::Range (range_base - subprogram_low_pc, range.GetByteSize()));
1447                         else
1448                         {
1449                             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",
1450                                                                        block->GetID(),
1451                                                                        range_base,
1452                                                                        range.GetRangeEnd(),
1453                                                                        subprogram_low_pc);
1454                         }
1455                     }
1456                     block->FinalizeRanges ();
1457 
1458                     if (tag != DW_TAG_subprogram && (name != NULL || mangled_name != NULL))
1459                     {
1460                         std::unique_ptr<Declaration> decl_ap;
1461                         if (decl_file != 0 || decl_line != 0 || decl_column != 0)
1462                             decl_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(decl_file),
1463                                                           decl_line, decl_column));
1464 
1465                         std::unique_ptr<Declaration> call_ap;
1466                         if (call_file != 0 || call_line != 0 || call_column != 0)
1467                             call_ap.reset(new Declaration(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(call_file),
1468                                                           call_line, call_column));
1469 
1470                         block->SetInlinedFunctionInfo (name, mangled_name, decl_ap.get(), call_ap.get());
1471                     }
1472 
1473                     ++blocks_added;
1474 
1475                     if (die->HasChildren())
1476                     {
1477                         blocks_added += ParseFunctionBlocks (sc,
1478                                                              block,
1479                                                              dwarf_cu,
1480                                                              die->GetFirstChild(),
1481                                                              subprogram_low_pc,
1482                                                              depth + 1);
1483                     }
1484                 }
1485             }
1486             break;
1487         default:
1488             break;
1489         }
1490 
1491         // Only parse siblings of the block if we are not at depth zero. A depth
1492         // of zero indicates we are currently parsing the top level
1493         // DW_TAG_subprogram DIE
1494 
1495         if (depth == 0)
1496             die = NULL;
1497         else
1498             die = die->GetSibling();
1499     }
1500     return blocks_added;
1501 }
1502 
1503 bool
1504 SymbolFileDWARF::ParseTemplateDIE (DWARFCompileUnit* dwarf_cu,
1505                                    const DWARFDebugInfoEntry *die,
1506                                    ClangASTContext::TemplateParameterInfos &template_param_infos)
1507 {
1508     const dw_tag_t tag = die->Tag();
1509 
1510     switch (tag)
1511     {
1512     case DW_TAG_template_type_parameter:
1513     case DW_TAG_template_value_parameter:
1514         {
1515             const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize(), dwarf_cu->IsDWARF64());
1516 
1517             DWARFDebugInfoEntry::Attributes attributes;
1518             const size_t num_attributes = die->GetAttributes (this,
1519                                                               dwarf_cu,
1520                                                               fixed_form_sizes,
1521                                                               attributes);
1522             const char *name = NULL;
1523             Type *lldb_type = NULL;
1524             ClangASTType clang_type;
1525             uint64_t uval64 = 0;
1526             bool uval64_valid = false;
1527             if (num_attributes > 0)
1528             {
1529                 DWARFFormValue form_value;
1530                 for (size_t i=0; i<num_attributes; ++i)
1531                 {
1532                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
1533 
1534                     switch (attr)
1535                     {
1536                         case DW_AT_name:
1537                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1538                                 name = form_value.AsCString(&get_debug_str_data());
1539                             break;
1540 
1541                         case DW_AT_type:
1542                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1543                             {
1544                                 const dw_offset_t type_die_offset = form_value.Reference();
1545                                 lldb_type = ResolveTypeUID(type_die_offset);
1546                                 if (lldb_type)
1547                                     clang_type = lldb_type->GetClangForwardType();
1548                             }
1549                             break;
1550 
1551                         case DW_AT_const_value:
1552                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1553                             {
1554                                 uval64_valid = true;
1555                                 uval64 = form_value.Unsigned();
1556                             }
1557                             break;
1558                         default:
1559                             break;
1560                     }
1561                 }
1562 
1563                 clang::ASTContext *ast = GetClangASTContext().getASTContext();
1564                 if (!clang_type)
1565                     clang_type = GetClangASTContext().GetBasicType(eBasicTypeVoid);
1566 
1567                 if (clang_type)
1568                 {
1569                     bool is_signed = false;
1570                     if (name && name[0])
1571                         template_param_infos.names.push_back(name);
1572                     else
1573                         template_param_infos.names.push_back(NULL);
1574 
1575                     if (tag == DW_TAG_template_value_parameter &&
1576                         lldb_type != NULL &&
1577                         clang_type.IsIntegerType (is_signed) &&
1578                         uval64_valid)
1579                     {
1580                         llvm::APInt apint (lldb_type->GetByteSize() * 8, uval64, is_signed);
1581                         template_param_infos.args.push_back (clang::TemplateArgument (*ast,
1582                                                                                       llvm::APSInt(apint),
1583                                                                                       clang_type.GetQualType()));
1584                     }
1585                     else
1586                     {
1587                         template_param_infos.args.push_back (clang::TemplateArgument (clang_type.GetQualType()));
1588                     }
1589                 }
1590                 else
1591                 {
1592                     return false;
1593                 }
1594 
1595             }
1596         }
1597         return true;
1598 
1599     default:
1600         break;
1601     }
1602     return false;
1603 }
1604 
1605 bool
1606 SymbolFileDWARF::ParseTemplateParameterInfos (DWARFCompileUnit* dwarf_cu,
1607                                               const DWARFDebugInfoEntry *parent_die,
1608                                               ClangASTContext::TemplateParameterInfos &template_param_infos)
1609 {
1610 
1611     if (parent_die == NULL)
1612         return false;
1613 
1614     Args template_parameter_names;
1615     for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild();
1616          die != NULL;
1617          die = die->GetSibling())
1618     {
1619         const dw_tag_t tag = die->Tag();
1620 
1621         switch (tag)
1622         {
1623             case DW_TAG_template_type_parameter:
1624             case DW_TAG_template_value_parameter:
1625                 ParseTemplateDIE (dwarf_cu, die, template_param_infos);
1626             break;
1627 
1628         default:
1629             break;
1630         }
1631     }
1632     if (template_param_infos.args.empty())
1633         return false;
1634     return template_param_infos.args.size() == template_param_infos.names.size();
1635 }
1636 
1637 clang::ClassTemplateDecl *
1638 SymbolFileDWARF::ParseClassTemplateDecl (clang::DeclContext *decl_ctx,
1639                                          lldb::AccessType access_type,
1640                                          const char *parent_name,
1641                                          int tag_decl_kind,
1642                                          const ClangASTContext::TemplateParameterInfos &template_param_infos)
1643 {
1644     if (template_param_infos.IsValid())
1645     {
1646         std::string template_basename(parent_name);
1647         template_basename.erase (template_basename.find('<'));
1648         ClangASTContext &ast = GetClangASTContext();
1649 
1650         return ast.CreateClassTemplateDecl (decl_ctx,
1651                                             access_type,
1652                                             template_basename.c_str(),
1653                                             tag_decl_kind,
1654                                             template_param_infos);
1655     }
1656     return NULL;
1657 }
1658 
1659 class SymbolFileDWARF::DelayedAddObjCClassProperty
1660 {
1661 public:
1662     DelayedAddObjCClassProperty
1663     (
1664         const ClangASTType     &class_opaque_type,
1665         const char             *property_name,
1666         const ClangASTType     &property_opaque_type,  // The property type is only required if you don't have an ivar decl
1667         clang::ObjCIvarDecl    *ivar_decl,
1668         const char             *property_setter_name,
1669         const char             *property_getter_name,
1670         uint32_t                property_attributes,
1671         const ClangASTMetadata *metadata
1672     ) :
1673         m_class_opaque_type     (class_opaque_type),
1674         m_property_name         (property_name),
1675         m_property_opaque_type  (property_opaque_type),
1676         m_ivar_decl             (ivar_decl),
1677         m_property_setter_name  (property_setter_name),
1678         m_property_getter_name  (property_getter_name),
1679         m_property_attributes   (property_attributes)
1680     {
1681         if (metadata != NULL)
1682         {
1683             m_metadata_ap.reset(new ClangASTMetadata());
1684             *m_metadata_ap = *metadata;
1685         }
1686     }
1687 
1688     DelayedAddObjCClassProperty (const DelayedAddObjCClassProperty &rhs)
1689     {
1690         *this = rhs;
1691     }
1692 
1693     DelayedAddObjCClassProperty& operator= (const DelayedAddObjCClassProperty &rhs)
1694     {
1695         m_class_opaque_type    = rhs.m_class_opaque_type;
1696         m_property_name        = rhs.m_property_name;
1697         m_property_opaque_type = rhs.m_property_opaque_type;
1698         m_ivar_decl            = rhs.m_ivar_decl;
1699         m_property_setter_name = rhs.m_property_setter_name;
1700         m_property_getter_name = rhs.m_property_getter_name;
1701         m_property_attributes  = rhs.m_property_attributes;
1702 
1703         if (rhs.m_metadata_ap.get())
1704         {
1705             m_metadata_ap.reset (new ClangASTMetadata());
1706             *m_metadata_ap = *rhs.m_metadata_ap;
1707         }
1708         return *this;
1709     }
1710 
1711     bool
1712     Finalize()
1713     {
1714         return m_class_opaque_type.AddObjCClassProperty (m_property_name,
1715                                                          m_property_opaque_type,
1716                                                          m_ivar_decl,
1717                                                          m_property_setter_name,
1718                                                          m_property_getter_name,
1719                                                          m_property_attributes,
1720                                                          m_metadata_ap.get());
1721     }
1722 private:
1723     ClangASTType            m_class_opaque_type;
1724     const char             *m_property_name;
1725     ClangASTType            m_property_opaque_type;
1726     clang::ObjCIvarDecl    *m_ivar_decl;
1727     const char             *m_property_setter_name;
1728     const char             *m_property_getter_name;
1729     uint32_t                m_property_attributes;
1730     std::unique_ptr<ClangASTMetadata> m_metadata_ap;
1731 };
1732 
1733 struct BitfieldInfo
1734 {
1735     uint64_t bit_size;
1736     uint64_t bit_offset;
1737 
1738     BitfieldInfo () :
1739         bit_size (LLDB_INVALID_ADDRESS),
1740         bit_offset (LLDB_INVALID_ADDRESS)
1741     {
1742     }
1743 
1744     void
1745     Clear()
1746     {
1747         bit_size = LLDB_INVALID_ADDRESS;
1748         bit_offset = LLDB_INVALID_ADDRESS;
1749     }
1750 
1751     bool IsValid ()
1752     {
1753         return (bit_size != LLDB_INVALID_ADDRESS) &&
1754                (bit_offset != LLDB_INVALID_ADDRESS);
1755     }
1756 };
1757 
1758 
1759 bool
1760 SymbolFileDWARF::ClassOrStructIsVirtual (DWARFCompileUnit* dwarf_cu,
1761                                          const DWARFDebugInfoEntry *parent_die)
1762 {
1763     if (parent_die)
1764     {
1765         for (const DWARFDebugInfoEntry *die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1766         {
1767             dw_tag_t tag = die->Tag();
1768             bool check_virtuality = false;
1769             switch (tag)
1770             {
1771                 case DW_TAG_inheritance:
1772                 case DW_TAG_subprogram:
1773                     check_virtuality = true;
1774                     break;
1775                 default:
1776                     break;
1777             }
1778             if (check_virtuality)
1779             {
1780                 if (die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_virtuality, 0) != 0)
1781                     return true;
1782             }
1783         }
1784     }
1785     return false;
1786 }
1787 
1788 size_t
1789 SymbolFileDWARF::ParseChildMembers
1790 (
1791     const SymbolContext& sc,
1792     DWARFCompileUnit* dwarf_cu,
1793     const DWARFDebugInfoEntry *parent_die,
1794     ClangASTType &class_clang_type,
1795     const LanguageType class_language,
1796     std::vector<clang::CXXBaseSpecifier *>& base_classes,
1797     std::vector<int>& member_accessibilities,
1798     DWARFDIECollection& member_function_dies,
1799     DelayedPropertyList& delayed_properties,
1800     AccessType& default_accessibility,
1801     bool &is_a_class,
1802     LayoutInfo &layout_info
1803 )
1804 {
1805     if (parent_die == NULL)
1806         return 0;
1807 
1808     size_t count = 0;
1809     const DWARFDebugInfoEntry *die;
1810     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize(), dwarf_cu->IsDWARF64());
1811     uint32_t member_idx = 0;
1812     BitfieldInfo last_field_info;
1813     ModuleSP module = GetObjectFile()->GetModule();
1814 
1815     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
1816     {
1817         dw_tag_t tag = die->Tag();
1818 
1819         switch (tag)
1820         {
1821         case DW_TAG_member:
1822         case DW_TAG_APPLE_property:
1823             {
1824                 DWARFDebugInfoEntry::Attributes attributes;
1825                 const size_t num_attributes = die->GetAttributes (this,
1826                                                                   dwarf_cu,
1827                                                                   fixed_form_sizes,
1828                                                                   attributes);
1829                 if (num_attributes > 0)
1830                 {
1831                     Declaration decl;
1832                     //DWARFExpression location;
1833                     const char *name = NULL;
1834                     const char *prop_name = NULL;
1835                     const char *prop_getter_name = NULL;
1836                     const char *prop_setter_name = NULL;
1837                     uint32_t prop_attributes = 0;
1838 
1839 
1840                     bool is_artificial = false;
1841                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
1842                     AccessType accessibility = eAccessNone;
1843                     uint32_t member_byte_offset = UINT32_MAX;
1844                     size_t byte_size = 0;
1845                     size_t bit_offset = 0;
1846                     size_t bit_size = 0;
1847                     bool is_external = false; // On DW_TAG_members, this means the member is static
1848                     uint32_t i;
1849                     for (i=0; i<num_attributes && !is_artificial; ++i)
1850                     {
1851                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
1852                         DWARFFormValue form_value;
1853                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
1854                         {
1855                             switch (attr)
1856                             {
1857                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
1858                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
1859                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
1860                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
1861                             case DW_AT_type:        encoding_uid = form_value.Reference(); break;
1862                             case DW_AT_bit_offset:  bit_offset = form_value.Unsigned(); break;
1863                             case DW_AT_bit_size:    bit_size = form_value.Unsigned(); break;
1864                             case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
1865                             case DW_AT_data_member_location:
1866                                 if (form_value.BlockData())
1867                                 {
1868                                     Value initialValue(0);
1869                                     Value memberOffset(0);
1870                                     const DWARFDataExtractor& debug_info_data = get_debug_info_data();
1871                                     uint32_t block_length = form_value.Unsigned();
1872                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
1873                                     if (DWARFExpression::Evaluate(NULL, // ExecutionContext *
1874                                                                   NULL, // ClangExpressionVariableList *
1875                                                                   NULL, // ClangExpressionDeclMap *
1876                                                                   NULL, // RegisterContext *
1877                                                                   module,
1878                                                                   debug_info_data,
1879                                                                   block_offset,
1880                                                                   block_length,
1881                                                                   eRegisterKindDWARF,
1882                                                                   &initialValue,
1883                                                                   memberOffset,
1884                                                                   NULL))
1885                                     {
1886                                         member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
1887                                     }
1888                                 }
1889                                 else
1890                                 {
1891                                     // With DWARF 3 and later, if the value is an integer constant,
1892                                     // this form value is the offset in bytes from the beginning
1893                                     // of the containing entity.
1894                                     member_byte_offset = form_value.Unsigned();
1895                                 }
1896                                 break;
1897 
1898                             case DW_AT_accessibility: accessibility = DW_ACCESS_to_AccessType (form_value.Unsigned()); break;
1899                             case DW_AT_artificial: is_artificial = form_value.Boolean(); break;
1900                             case DW_AT_APPLE_property_name:      prop_name = form_value.AsCString(&get_debug_str_data()); break;
1901                             case DW_AT_APPLE_property_getter:    prop_getter_name = form_value.AsCString(&get_debug_str_data()); break;
1902                             case DW_AT_APPLE_property_setter:    prop_setter_name = form_value.AsCString(&get_debug_str_data()); break;
1903                             case DW_AT_APPLE_property_attribute: prop_attributes = form_value.Unsigned(); break;
1904                             case DW_AT_external:                 is_external = form_value.Boolean(); break;
1905 
1906                             default:
1907                             case DW_AT_declaration:
1908                             case DW_AT_description:
1909                             case DW_AT_mutable:
1910                             case DW_AT_visibility:
1911                             case DW_AT_sibling:
1912                                 break;
1913                             }
1914                         }
1915                     }
1916 
1917                     if (prop_name)
1918                     {
1919                         ConstString fixed_getter;
1920                         ConstString fixed_setter;
1921 
1922                         // Check if the property getter/setter were provided as full
1923                         // names.  We want basenames, so we extract them.
1924 
1925                         if (prop_getter_name && prop_getter_name[0] == '-')
1926                         {
1927                             ObjCLanguageRuntime::MethodName prop_getter_method(prop_getter_name, true);
1928                             prop_getter_name = prop_getter_method.GetSelector().GetCString();
1929                         }
1930 
1931                         if (prop_setter_name && prop_setter_name[0] == '-')
1932                         {
1933                             ObjCLanguageRuntime::MethodName prop_setter_method(prop_setter_name, true);
1934                             prop_setter_name = prop_setter_method.GetSelector().GetCString();
1935                         }
1936 
1937                         // If the names haven't been provided, they need to be
1938                         // filled in.
1939 
1940                         if (!prop_getter_name)
1941                         {
1942                             prop_getter_name = prop_name;
1943                         }
1944                         if (!prop_setter_name && prop_name[0] && !(prop_attributes & DW_APPLE_PROPERTY_readonly))
1945                         {
1946                             StreamString ss;
1947 
1948                             ss.Printf("set%c%s:",
1949                                       toupper(prop_name[0]),
1950                                       &prop_name[1]);
1951 
1952                             fixed_setter.SetCString(ss.GetData());
1953                             prop_setter_name = fixed_setter.GetCString();
1954                         }
1955                     }
1956 
1957                     // Clang has a DWARF generation bug where sometimes it
1958                     // represents fields that are references with bad byte size
1959                     // and bit size/offset information such as:
1960                     //
1961                     //  DW_AT_byte_size( 0x00 )
1962                     //  DW_AT_bit_size( 0x40 )
1963                     //  DW_AT_bit_offset( 0xffffffffffffffc0 )
1964                     //
1965                     // So check the bit offset to make sure it is sane, and if
1966                     // the values are not sane, remove them. If we don't do this
1967                     // then we will end up with a crash if we try to use this
1968                     // type in an expression when clang becomes unhappy with its
1969                     // recycled debug info.
1970 
1971                     if (bit_offset > 128)
1972                     {
1973                         bit_size = 0;
1974                         bit_offset = 0;
1975                     }
1976 
1977                     // FIXME: Make Clang ignore Objective-C accessibility for expressions
1978                     if (class_language == eLanguageTypeObjC ||
1979                         class_language == eLanguageTypeObjC_plus_plus)
1980                         accessibility = eAccessNone;
1981 
1982                     if (member_idx == 0 && !is_artificial && name && (strstr (name, "_vptr$") == name))
1983                     {
1984                         // Not all compilers will mark the vtable pointer
1985                         // member as artificial (llvm-gcc). We can't have
1986                         // the virtual members in our classes otherwise it
1987                         // throws off all child offsets since we end up
1988                         // having and extra pointer sized member in our
1989                         // class layouts.
1990                         is_artificial = true;
1991                     }
1992 
1993                     // Handle static members
1994                     if (is_external && member_byte_offset == UINT32_MAX)
1995                     {
1996                         Type *var_type = ResolveTypeUID(encoding_uid);
1997 
1998                         if (var_type)
1999                         {
2000                             if (accessibility == eAccessNone)
2001                                 accessibility = eAccessPublic;
2002                             class_clang_type.AddVariableToRecordType (name,
2003                                                                       var_type->GetClangLayoutType(),
2004                                                                       accessibility);
2005                         }
2006                         break;
2007                     }
2008 
2009                     if (is_artificial == false)
2010                     {
2011                         Type *member_type = ResolveTypeUID(encoding_uid);
2012 
2013                         clang::FieldDecl *field_decl = NULL;
2014                         if (tag == DW_TAG_member)
2015                         {
2016                             if (member_type)
2017                             {
2018                                 if (accessibility == eAccessNone)
2019                                     accessibility = default_accessibility;
2020                                 member_accessibilities.push_back(accessibility);
2021 
2022                                 uint64_t field_bit_offset = (member_byte_offset == UINT32_MAX ? 0 : (member_byte_offset * 8));
2023                                 if (bit_size > 0)
2024                                 {
2025 
2026                                     BitfieldInfo this_field_info;
2027                                     this_field_info.bit_offset = field_bit_offset;
2028                                     this_field_info.bit_size = bit_size;
2029 
2030                                     /////////////////////////////////////////////////////////////
2031                                     // How to locate a field given the DWARF debug information
2032                                     //
2033                                     // AT_byte_size indicates the size of the word in which the
2034                                     // bit offset must be interpreted.
2035                                     //
2036                                     // AT_data_member_location indicates the byte offset of the
2037                                     // word from the base address of the structure.
2038                                     //
2039                                     // AT_bit_offset indicates how many bits into the word
2040                                     // (according to the host endianness) the low-order bit of
2041                                     // the field starts.  AT_bit_offset can be negative.
2042                                     //
2043                                     // AT_bit_size indicates the size of the field in bits.
2044                                     /////////////////////////////////////////////////////////////
2045 
2046                                     if (byte_size == 0)
2047                                         byte_size = member_type->GetByteSize();
2048 
2049                                     if (GetObjectFile()->GetByteOrder() == eByteOrderLittle)
2050                                     {
2051                                         this_field_info.bit_offset += byte_size * 8;
2052                                         this_field_info.bit_offset -= (bit_offset + bit_size);
2053                                     }
2054                                     else
2055                                     {
2056                                         this_field_info.bit_offset += bit_offset;
2057                                     }
2058 
2059                                     // Update the field bit offset we will report for layout
2060                                     field_bit_offset = this_field_info.bit_offset;
2061 
2062                                     // If the member to be emitted did not start on a character boundary and there is
2063                                     // empty space between the last field and this one, then we need to emit an
2064                                     // anonymous member filling up the space up to its start.  There are three cases
2065                                     // here:
2066                                     //
2067                                     // 1 If the previous member ended on a character boundary, then we can emit an
2068                                     //   anonymous member starting at the most recent character boundary.
2069                                     //
2070                                     // 2 If the previous member did not end on a character boundary and the distance
2071                                     //   from the end of the previous member to the current member is less than a
2072                                     //   word width, then we can emit an anonymous member starting right after the
2073                                     //   previous member and right before this member.
2074                                     //
2075                                     // 3 If the previous member did not end on a character boundary and the distance
2076                                     //   from the end of the previous member to the current member is greater than
2077                                     //   or equal a word width, then we act as in Case 1.
2078 
2079                                     const uint64_t character_width = 8;
2080                                     const uint64_t word_width = 32;
2081 
2082                                     // Objective-C has invalid DW_AT_bit_offset values in older versions
2083                                     // of clang, so we have to be careful and only insert unnamed bitfields
2084                                     // if we have a new enough clang.
2085                                     bool detect_unnamed_bitfields = true;
2086 
2087                                     if (class_language == eLanguageTypeObjC || class_language == eLanguageTypeObjC_plus_plus)
2088                                         detect_unnamed_bitfields = dwarf_cu->Supports_unnamed_objc_bitfields ();
2089 
2090                                     if (detect_unnamed_bitfields)
2091                                     {
2092                                         BitfieldInfo anon_field_info;
2093 
2094                                         if ((this_field_info.bit_offset % character_width) != 0) // not char aligned
2095                                         {
2096                                             uint64_t last_field_end = 0;
2097 
2098                                             if (last_field_info.IsValid())
2099                                                 last_field_end = last_field_info.bit_offset + last_field_info.bit_size;
2100 
2101                                             if (this_field_info.bit_offset != last_field_end)
2102                                             {
2103                                                 if (((last_field_end % character_width) == 0) ||                    // case 1
2104                                                     (this_field_info.bit_offset - last_field_end >= word_width))    // case 3
2105                                                 {
2106                                                     anon_field_info.bit_size = this_field_info.bit_offset % character_width;
2107                                                     anon_field_info.bit_offset = this_field_info.bit_offset - anon_field_info.bit_size;
2108                                                 }
2109                                                 else                                                                // case 2
2110                                                 {
2111                                                     anon_field_info.bit_size = this_field_info.bit_offset - last_field_end;
2112                                                     anon_field_info.bit_offset = last_field_end;
2113                                                 }
2114                                             }
2115                                         }
2116 
2117                                         if (anon_field_info.IsValid())
2118                                         {
2119                                             clang::FieldDecl *unnamed_bitfield_decl = class_clang_type.AddFieldToRecordType (NULL,
2120                                                                                                                              GetClangASTContext().GetBuiltinTypeForEncodingAndBitSize(eEncodingSint, word_width),
2121                                                                                                                              accessibility,
2122                                                                                                                              anon_field_info.bit_size);
2123 
2124                                             layout_info.field_offsets.insert(
2125                                                 std::make_pair(unnamed_bitfield_decl, anon_field_info.bit_offset));
2126                                         }
2127                                     }
2128                                     last_field_info = this_field_info;
2129                                 }
2130                                 else
2131                                 {
2132                                     last_field_info.Clear();
2133                                 }
2134 
2135                                 ClangASTType member_clang_type = member_type->GetClangLayoutType();
2136 
2137                                 {
2138                                     // Older versions of clang emit array[0] and array[1] in the same way (<rdar://problem/12566646>).
2139                                     // If the current field is at the end of the structure, then there is definitely no room for extra
2140                                     // elements and we override the type to array[0].
2141 
2142                                     ClangASTType member_array_element_type;
2143                                     uint64_t member_array_size;
2144                                     bool member_array_is_incomplete;
2145 
2146                                     if (member_clang_type.IsArrayType(&member_array_element_type,
2147                                                                       &member_array_size,
2148                                                                       &member_array_is_incomplete) &&
2149                                         !member_array_is_incomplete)
2150                                     {
2151                                         uint64_t parent_byte_size = parent_die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, UINT64_MAX);
2152 
2153                                         if (member_byte_offset >= parent_byte_size)
2154                                         {
2155                                             if (member_array_size != 1)
2156                                             {
2157                                                 GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 " which extends beyond the bounds of 0x%8.8" PRIx64,
2158                                                                                            MakeUserID(die->GetOffset()),
2159                                                                                            name,
2160                                                                                            encoding_uid,
2161                                                                                            MakeUserID(parent_die->GetOffset()));
2162                                             }
2163 
2164                                             member_clang_type = GetClangASTContext().CreateArrayType(member_array_element_type, 0, false);
2165                                         }
2166                                     }
2167                                 }
2168 
2169                                 field_decl = class_clang_type.AddFieldToRecordType (name,
2170                                                                                     member_clang_type,
2171                                                                                     accessibility,
2172                                                                                     bit_size);
2173 
2174                                 GetClangASTContext().SetMetadataAsUserID (field_decl, MakeUserID(die->GetOffset()));
2175 
2176                                 layout_info.field_offsets.insert(std::make_pair(field_decl, field_bit_offset));
2177                             }
2178                             else
2179                             {
2180                                 if (name)
2181                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member '%s' refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
2182                                                                                MakeUserID(die->GetOffset()),
2183                                                                                name,
2184                                                                                encoding_uid);
2185                                 else
2186                                     GetObjectFile()->GetModule()->ReportError ("0x%8.8" PRIx64 ": DW_TAG_member refers to type 0x%8.8" PRIx64 " which was unable to be parsed",
2187                                                                                MakeUserID(die->GetOffset()),
2188                                                                                encoding_uid);
2189                             }
2190                         }
2191 
2192                         if (prop_name != NULL)
2193                         {
2194                             clang::ObjCIvarDecl *ivar_decl = NULL;
2195 
2196                             if (field_decl)
2197                             {
2198                                 ivar_decl = clang::dyn_cast<clang::ObjCIvarDecl>(field_decl);
2199                                 assert (ivar_decl != NULL);
2200                             }
2201 
2202                             ClangASTMetadata metadata;
2203                             metadata.SetUserID (MakeUserID(die->GetOffset()));
2204                             delayed_properties.push_back(DelayedAddObjCClassProperty(class_clang_type,
2205                                                                                      prop_name,
2206                                                                                      member_type->GetClangLayoutType(),
2207                                                                                      ivar_decl,
2208                                                                                      prop_setter_name,
2209                                                                                      prop_getter_name,
2210                                                                                      prop_attributes,
2211                                                                                      &metadata));
2212 
2213                             if (ivar_decl)
2214                                 GetClangASTContext().SetMetadataAsUserID (ivar_decl, MakeUserID(die->GetOffset()));
2215                         }
2216                     }
2217                 }
2218                 ++member_idx;
2219             }
2220             break;
2221 
2222         case DW_TAG_subprogram:
2223             // Let the type parsing code handle this one for us.
2224             member_function_dies.Append (die);
2225             break;
2226 
2227         case DW_TAG_inheritance:
2228             {
2229                 is_a_class = true;
2230                 if (default_accessibility == eAccessNone)
2231                     default_accessibility = eAccessPrivate;
2232                 // TODO: implement DW_TAG_inheritance type parsing
2233                 DWARFDebugInfoEntry::Attributes attributes;
2234                 const size_t num_attributes = die->GetAttributes (this,
2235                                                                   dwarf_cu,
2236                                                                   fixed_form_sizes,
2237                                                                   attributes);
2238                 if (num_attributes > 0)
2239                 {
2240                     Declaration decl;
2241                     DWARFExpression location;
2242                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
2243                     AccessType accessibility = default_accessibility;
2244                     bool is_virtual = false;
2245                     bool is_base_of_class = true;
2246                     off_t member_byte_offset = 0;
2247                     uint32_t i;
2248                     for (i=0; i<num_attributes; ++i)
2249                     {
2250                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
2251                         DWARFFormValue form_value;
2252                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
2253                         {
2254                             switch (attr)
2255                             {
2256                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
2257                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
2258                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
2259                             case DW_AT_type:        encoding_uid = form_value.Reference(); break;
2260                             case DW_AT_data_member_location:
2261                                 if (form_value.BlockData())
2262                                 {
2263                                     Value initialValue(0);
2264                                     Value memberOffset(0);
2265                                     const DWARFDataExtractor& debug_info_data = get_debug_info_data();
2266                                     uint32_t block_length = form_value.Unsigned();
2267                                     uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
2268                                     if (DWARFExpression::Evaluate (NULL,
2269                                                                    NULL,
2270                                                                    NULL,
2271                                                                    NULL,
2272                                                                    module,
2273                                                                    debug_info_data,
2274                                                                    block_offset,
2275                                                                    block_length,
2276                                                                    eRegisterKindDWARF,
2277                                                                    &initialValue,
2278                                                                    memberOffset,
2279                                                                    NULL))
2280                                     {
2281                                         member_byte_offset = memberOffset.ResolveValue(NULL).UInt();
2282                                     }
2283                                 }
2284                                 else
2285                                 {
2286                                     // With DWARF 3 and later, if the value is an integer constant,
2287                                     // this form value is the offset in bytes from the beginning
2288                                     // of the containing entity.
2289                                     member_byte_offset = form_value.Unsigned();
2290                                 }
2291                                 break;
2292 
2293                             case DW_AT_accessibility:
2294                                 accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
2295                                 break;
2296 
2297                             case DW_AT_virtuality:
2298                                 is_virtual = form_value.Boolean();
2299                                 break;
2300 
2301                             case DW_AT_sibling:
2302                                 break;
2303 
2304                             default:
2305                                 break;
2306                             }
2307                         }
2308                     }
2309 
2310                     Type *base_class_type = ResolveTypeUID(encoding_uid);
2311                     assert(base_class_type);
2312 
2313                     ClangASTType base_class_clang_type = base_class_type->GetClangFullType();
2314                     assert (base_class_clang_type);
2315                     if (class_language == eLanguageTypeObjC)
2316                     {
2317                         class_clang_type.SetObjCSuperClass(base_class_clang_type);
2318                     }
2319                     else
2320                     {
2321                         base_classes.push_back (base_class_clang_type.CreateBaseClassSpecifier (accessibility,
2322                                                                                                is_virtual,
2323                                                                                                is_base_of_class));
2324 
2325                         if (is_virtual)
2326                         {
2327                             // Do not specify any offset for virtual inheritance. The DWARF produced by clang doesn't
2328                             // give us a constant offset, but gives us a DWARF expressions that requires an actual object
2329                             // in memory. the DW_AT_data_member_location for a virtual base class looks like:
2330                             //      DW_AT_data_member_location( DW_OP_dup, DW_OP_deref, DW_OP_constu(0x00000018), DW_OP_minus, DW_OP_deref, DW_OP_plus )
2331                             // Given this, there is really no valid response we can give to clang for virtual base
2332                             // class offsets, and this should eventually be removed from LayoutRecordType() in the external
2333                             // AST source in clang.
2334                         }
2335                         else
2336                         {
2337                             layout_info.base_offsets.insert(
2338                                 std::make_pair(base_class_clang_type.GetAsCXXRecordDecl(),
2339                                                clang::CharUnits::fromQuantity(member_byte_offset)));
2340                         }
2341                     }
2342                 }
2343             }
2344             break;
2345 
2346         default:
2347             break;
2348         }
2349     }
2350 
2351     return count;
2352 }
2353 
2354 
2355 clang::DeclContext*
2356 SymbolFileDWARF::GetClangDeclContextContainingTypeUID (lldb::user_id_t type_uid)
2357 {
2358     DWARFDebugInfo* debug_info = DebugInfo();
2359     if (debug_info && UserIDMatches(type_uid))
2360     {
2361         DWARFCompileUnitSP cu_sp;
2362         const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2363         if (die)
2364             return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
2365     }
2366     return NULL;
2367 }
2368 
2369 clang::DeclContext*
2370 SymbolFileDWARF::GetClangDeclContextForTypeUID (const lldb_private::SymbolContext &sc, lldb::user_id_t type_uid)
2371 {
2372     if (UserIDMatches(type_uid))
2373         return GetClangDeclContextForDIEOffset (sc, type_uid);
2374     return NULL;
2375 }
2376 
2377 Type*
2378 SymbolFileDWARF::ResolveTypeUID (lldb::user_id_t type_uid)
2379 {
2380     if (UserIDMatches(type_uid))
2381     {
2382         DWARFDebugInfo* debug_info = DebugInfo();
2383         if (debug_info)
2384         {
2385             DWARFCompileUnitSP cu_sp;
2386             const DWARFDebugInfoEntry* type_die = debug_info->GetDIEPtr(type_uid, &cu_sp);
2387             const bool assert_not_being_parsed = true;
2388             return ResolveTypeUID (cu_sp.get(), type_die, assert_not_being_parsed);
2389         }
2390     }
2391     return NULL;
2392 }
2393 
2394 Type*
2395 SymbolFileDWARF::ResolveTypeUID (DWARFCompileUnit* cu, const DWARFDebugInfoEntry* die, bool assert_not_being_parsed)
2396 {
2397     if (die != NULL)
2398     {
2399         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
2400         if (log)
2401             GetObjectFile()->GetModule()->LogMessage (log,
2402                                                       "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s'",
2403                                                       die->GetOffset(),
2404                                                       DW_TAG_value_to_name(die->Tag()),
2405                                                       die->GetName(this, cu));
2406 
2407         // We might be coming in in the middle of a type tree (a class
2408         // withing a class, an enum within a class), so parse any needed
2409         // parent DIEs before we get to this one...
2410         const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
2411         switch (decl_ctx_die->Tag())
2412         {
2413             case DW_TAG_structure_type:
2414             case DW_TAG_union_type:
2415             case DW_TAG_class_type:
2416             {
2417                 // Get the type, which could be a forward declaration
2418                 if (log)
2419                     GetObjectFile()->GetModule()->LogMessage (log,
2420                                                               "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent forward type for 0x%8.8x",
2421                                                               die->GetOffset(),
2422                                                               DW_TAG_value_to_name(die->Tag()),
2423                                                               die->GetName(this, cu),
2424                                                               decl_ctx_die->GetOffset());
2425 //
2426 //                Type *parent_type = ResolveTypeUID (cu, decl_ctx_die, assert_not_being_parsed);
2427 //                if (child_requires_parent_class_union_or_struct_to_be_completed(die->Tag()))
2428 //                {
2429 //                    if (log)
2430 //                        GetObjectFile()->GetModule()->LogMessage (log,
2431 //                                                                  "SymbolFileDWARF::ResolveTypeUID (die = 0x%8.8x) %s '%s' resolve parent full type for 0x%8.8x since die is a function",
2432 //                                                                  die->GetOffset(),
2433 //                                                                  DW_TAG_value_to_name(die->Tag()),
2434 //                                                                  die->GetName(this, cu),
2435 //                                                                  decl_ctx_die->GetOffset());
2436 //                    // Ask the type to complete itself if it already hasn't since if we
2437 //                    // want a function (method or static) from a class, the class must
2438 //                    // create itself and add it's own methods and class functions.
2439 //                    if (parent_type)
2440 //                        parent_type->GetClangFullType();
2441 //                }
2442             }
2443             break;
2444 
2445             default:
2446                 break;
2447         }
2448         return ResolveType (cu, die);
2449     }
2450     return NULL;
2451 }
2452 
2453 // This function is used when SymbolFileDWARFDebugMap owns a bunch of
2454 // SymbolFileDWARF objects to detect if this DWARF file is the one that
2455 // can resolve a clang_type.
2456 bool
2457 SymbolFileDWARF::HasForwardDeclForClangType (const ClangASTType &clang_type)
2458 {
2459     ClangASTType clang_type_no_qualifiers = clang_type.RemoveFastQualifiers();
2460     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers.GetOpaqueQualType());
2461     return die != NULL;
2462 }
2463 
2464 
2465 bool
2466 SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (ClangASTType &clang_type)
2467 {
2468     // We have a struct/union/class/enum that needs to be fully resolved.
2469     ClangASTType clang_type_no_qualifiers = clang_type.RemoveFastQualifiers();
2470     const DWARFDebugInfoEntry* die = m_forward_decl_clang_type_to_die.lookup (clang_type_no_qualifiers.GetOpaqueQualType());
2471     if (die == NULL)
2472     {
2473         // We have already resolved this type...
2474         return true;
2475     }
2476     // Once we start resolving this type, remove it from the forward declaration
2477     // map in case anyone child members or other types require this type to get resolved.
2478     // The type will get resolved when all of the calls to SymbolFileDWARF::ResolveClangOpaqueTypeDefinition
2479     // are done.
2480     m_forward_decl_clang_type_to_die.erase (clang_type_no_qualifiers.GetOpaqueQualType());
2481 
2482     // Disable external storage for this type so we don't get anymore
2483     // clang::ExternalASTSource queries for this type.
2484     clang_type.SetHasExternalStorage (false);
2485 
2486     DWARFDebugInfo* debug_info = DebugInfo();
2487 
2488     DWARFCompileUnit *dwarf_cu = debug_info->GetCompileUnitContainingDIE (die->GetOffset()).get();
2489     Type *type = m_die_to_type.lookup (die);
2490 
2491     const dw_tag_t tag = die->Tag();
2492 
2493     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO|DWARF_LOG_TYPE_COMPLETION));
2494     if (log)
2495         GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
2496                                                                   "0x%8.8" PRIx64 ": %s '%s' resolving forward declaration...",
2497                                                                   MakeUserID(die->GetOffset()),
2498                                                                   DW_TAG_value_to_name(tag),
2499                                                                   type->GetName().AsCString());
2500     assert (clang_type);
2501     DWARFDebugInfoEntry::Attributes attributes;
2502 
2503     switch (tag)
2504     {
2505     case DW_TAG_structure_type:
2506     case DW_TAG_union_type:
2507     case DW_TAG_class_type:
2508         {
2509             LayoutInfo layout_info;
2510 
2511             {
2512                 if (die->HasChildren())
2513                 {
2514                     LanguageType class_language = eLanguageTypeUnknown;
2515                     if (clang_type.IsObjCObjectOrInterfaceType())
2516                     {
2517                         class_language = eLanguageTypeObjC;
2518                         // For objective C we don't start the definition when
2519                         // the class is created.
2520                         clang_type.StartTagDeclarationDefinition ();
2521                     }
2522 
2523                     int tag_decl_kind = -1;
2524                     AccessType default_accessibility = eAccessNone;
2525                     if (tag == DW_TAG_structure_type)
2526                     {
2527                         tag_decl_kind = clang::TTK_Struct;
2528                         default_accessibility = eAccessPublic;
2529                     }
2530                     else if (tag == DW_TAG_union_type)
2531                     {
2532                         tag_decl_kind = clang::TTK_Union;
2533                         default_accessibility = eAccessPublic;
2534                     }
2535                     else if (tag == DW_TAG_class_type)
2536                     {
2537                         tag_decl_kind = clang::TTK_Class;
2538                         default_accessibility = eAccessPrivate;
2539                     }
2540 
2541                     SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2542                     std::vector<clang::CXXBaseSpecifier *> base_classes;
2543                     std::vector<int> member_accessibilities;
2544                     bool is_a_class = false;
2545                     // Parse members and base classes first
2546                     DWARFDIECollection member_function_dies;
2547 
2548                     DelayedPropertyList delayed_properties;
2549                     ParseChildMembers (sc,
2550                                        dwarf_cu,
2551                                        die,
2552                                        clang_type,
2553                                        class_language,
2554                                        base_classes,
2555                                        member_accessibilities,
2556                                        member_function_dies,
2557                                        delayed_properties,
2558                                        default_accessibility,
2559                                        is_a_class,
2560                                        layout_info);
2561 
2562                     // Now parse any methods if there were any...
2563                     size_t num_functions = member_function_dies.Size();
2564                     if (num_functions > 0)
2565                     {
2566                         for (size_t i=0; i<num_functions; ++i)
2567                         {
2568                             ResolveType(dwarf_cu, member_function_dies.GetDIEPtrAtIndex(i));
2569                         }
2570                     }
2571 
2572                     if (class_language == eLanguageTypeObjC)
2573                     {
2574                         ConstString class_name (clang_type.GetTypeName());
2575                         if (class_name)
2576                         {
2577                             DIEArray method_die_offsets;
2578                             if (m_using_apple_tables)
2579                             {
2580                                 if (m_apple_objc_ap.get())
2581                                     m_apple_objc_ap->FindByName(class_name.GetCString(), method_die_offsets);
2582                             }
2583                             else
2584                             {
2585                                 if (!m_indexed)
2586                                     Index ();
2587 
2588                                 m_objc_class_selectors_index.Find (class_name, method_die_offsets);
2589                             }
2590 
2591                             if (!method_die_offsets.empty())
2592                             {
2593                                 DWARFDebugInfo* debug_info = DebugInfo();
2594 
2595                                 DWARFCompileUnit* method_cu = NULL;
2596                                 const size_t num_matches = method_die_offsets.size();
2597                                 for (size_t i=0; i<num_matches; ++i)
2598                                 {
2599                                     const dw_offset_t die_offset = method_die_offsets[i];
2600                                     DWARFDebugInfoEntry *method_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &method_cu);
2601 
2602                                     if (method_die)
2603                                         ResolveType (method_cu, method_die);
2604                                     else
2605                                     {
2606                                         if (m_using_apple_tables)
2607                                         {
2608                                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_objc accelerator table had bad die 0x%8.8x for '%s')\n",
2609                                                                                                        die_offset, class_name.GetCString());
2610                                         }
2611                                     }
2612                                 }
2613                             }
2614 
2615                             for (DelayedPropertyList::iterator pi = delayed_properties.begin(), pe = delayed_properties.end();
2616                                  pi != pe;
2617                                  ++pi)
2618                                 pi->Finalize();
2619                         }
2620                     }
2621 
2622                     // If we have a DW_TAG_structure_type instead of a DW_TAG_class_type we
2623                     // need to tell the clang type it is actually a class.
2624                     if (class_language != eLanguageTypeObjC)
2625                     {
2626                         if (is_a_class && tag_decl_kind != clang::TTK_Class)
2627                             clang_type.SetTagTypeKind (clang::TTK_Class);
2628                     }
2629 
2630                     // Since DW_TAG_structure_type gets used for both classes
2631                     // and structures, we may need to set any DW_TAG_member
2632                     // fields to have a "private" access if none was specified.
2633                     // When we parsed the child members we tracked that actual
2634                     // accessibility value for each DW_TAG_member in the
2635                     // "member_accessibilities" array. If the value for the
2636                     // member is zero, then it was set to the "default_accessibility"
2637                     // which for structs was "public". Below we correct this
2638                     // by setting any fields to "private" that weren't correctly
2639                     // set.
2640                     if (is_a_class && !member_accessibilities.empty())
2641                     {
2642                         // This is a class and all members that didn't have
2643                         // their access specified are private.
2644                         clang_type.SetDefaultAccessForRecordFields (eAccessPrivate,
2645                                                                     &member_accessibilities.front(),
2646                                                                     member_accessibilities.size());
2647                     }
2648 
2649                     if (!base_classes.empty())
2650                     {
2651                         // Make sure all base classes refer to complete types and not
2652                         // forward declarations. If we don't do this, clang will crash
2653                         // with an assertion in the call to clang_type.SetBaseClassesForClassType()
2654                         bool base_class_error = false;
2655                         for (auto &base_class : base_classes)
2656                         {
2657                             clang::TypeSourceInfo *type_source_info = base_class->getTypeSourceInfo();
2658                             if (type_source_info)
2659                             {
2660                                 ClangASTType base_class_type (GetClangASTContext().getASTContext(), type_source_info->getType());
2661                                 if (base_class_type.GetCompleteType() == false)
2662                                 {
2663                                     if (!base_class_error)
2664                                     {
2665                                         GetObjectFile()->GetModule()->ReportError ("DWARF DIE at 0x%8.8x for class '%s' has a base class '%s' that is a forward declaration, not a complete definition.\nPlease file a bug against the compiler and include the preprocessed output for %s",
2666                                                                                    die->GetOffset(),
2667                                                                                    die->GetName(this, dwarf_cu),
2668                                                                                    base_class_type.GetTypeName().GetCString(),
2669                                                                                    sc.comp_unit ? sc.comp_unit->GetPath().c_str() : "the source file");
2670                                     }
2671                                     // We have no choice other than to pretend that the base class
2672                                     // is complete. If we don't do this, clang will crash when we
2673                                     // call setBases() inside of "clang_type.SetBaseClassesForClassType()"
2674                                     // below. Since we provide layout assistance, all ivars in this
2675                                     // class and other classes will be fine, this is the best we can do
2676                                     // short of crashing.
2677                                     base_class_type.StartTagDeclarationDefinition ();
2678                                     base_class_type.CompleteTagDeclarationDefinition ();
2679                                 }
2680                             }
2681                         }
2682                         clang_type.SetBaseClassesForClassType (&base_classes.front(),
2683                                                                base_classes.size());
2684 
2685                         // Clang will copy each CXXBaseSpecifier in "base_classes"
2686                         // so we have to free them all.
2687                         ClangASTType::DeleteBaseClassSpecifiers (&base_classes.front(),
2688                                                                  base_classes.size());
2689                     }
2690                 }
2691             }
2692 
2693             clang_type.BuildIndirectFields ();
2694             clang_type.CompleteTagDeclarationDefinition ();
2695 
2696             if (!layout_info.field_offsets.empty() ||
2697                 !layout_info.base_offsets.empty()  ||
2698                 !layout_info.vbase_offsets.empty() )
2699             {
2700                 if (type)
2701                     layout_info.bit_size = type->GetByteSize() * 8;
2702                 if (layout_info.bit_size == 0)
2703                     layout_info.bit_size = die->GetAttributeValueAsUnsigned(this, dwarf_cu, DW_AT_byte_size, 0) * 8;
2704 
2705                 clang::CXXRecordDecl *record_decl = clang_type.GetAsCXXRecordDecl();
2706                 if (record_decl)
2707                 {
2708                     if (log)
2709                     {
2710                         GetObjectFile()->GetModule()->LogMessage (log,
2711                                                                   "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) caching layout info for record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u], base_offsets[%u], vbase_offsets[%u])",
2712                                                                   static_cast<void*>(clang_type.GetOpaqueQualType()),
2713                                                                   static_cast<void*>(record_decl),
2714                                                                   layout_info.bit_size,
2715                                                                   layout_info.alignment,
2716                                                                   static_cast<uint32_t>(layout_info.field_offsets.size()),
2717                                                                   static_cast<uint32_t>(layout_info.base_offsets.size()),
2718                                                                   static_cast<uint32_t>(layout_info.vbase_offsets.size()));
2719 
2720                         uint32_t idx;
2721                         {
2722                             llvm::DenseMap<const clang::FieldDecl *, uint64_t>::const_iterator pos,
2723                                 end = layout_info.field_offsets.end();
2724                             for (idx = 0, pos = layout_info.field_offsets.begin(); pos != end; ++pos, ++idx)
2725                         {
2726                             GetObjectFile()->GetModule()->LogMessage(
2727                                 log, "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) field[%u] = "
2728                                      "{ bit_offset=%u, name='%s' }",
2729                                 static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2730                                 static_cast<uint32_t>(pos->second), pos->first->getNameAsString().c_str());
2731                         }
2732                         }
2733 
2734                         {
2735                             llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator base_pos,
2736                                 base_end = layout_info.base_offsets.end();
2737                             for (idx = 0, base_pos = layout_info.base_offsets.begin(); base_pos != base_end;
2738                                  ++base_pos, ++idx)
2739                             {
2740                                 GetObjectFile()->GetModule()->LogMessage(
2741                                     log, "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) base[%u] "
2742                                          "= { byte_offset=%u, name='%s' }",
2743                                     clang_type.GetOpaqueQualType(), idx, (uint32_t)base_pos->second.getQuantity(),
2744                                     base_pos->first->getNameAsString().c_str());
2745                             }
2746                         }
2747                         {
2748                             llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits>::const_iterator vbase_pos,
2749                                 vbase_end = layout_info.vbase_offsets.end();
2750                             for (idx = 0, vbase_pos = layout_info.vbase_offsets.begin(); vbase_pos != vbase_end;
2751                                  ++vbase_pos, ++idx)
2752                             {
2753                                 GetObjectFile()->GetModule()->LogMessage(
2754                                     log, "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition (clang_type = %p) "
2755                                          "vbase[%u] = { byte_offset=%u, name='%s' }",
2756                                     static_cast<void *>(clang_type.GetOpaqueQualType()), idx,
2757                                     static_cast<uint32_t>(vbase_pos->second.getQuantity()),
2758                                     vbase_pos->first->getNameAsString().c_str());
2759                             }
2760                         }
2761                     }
2762                     m_record_decl_to_layout_map.insert(std::make_pair(record_decl, layout_info));
2763                 }
2764             }
2765         }
2766 
2767         return (bool)clang_type;
2768 
2769     case DW_TAG_enumeration_type:
2770         clang_type.StartTagDeclarationDefinition ();
2771         if (die->HasChildren())
2772         {
2773             SymbolContext sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
2774             bool is_signed = false;
2775             clang_type.IsIntegerType(is_signed);
2776             ParseChildEnumerators(sc, clang_type, is_signed, type->GetByteSize(), dwarf_cu, die);
2777         }
2778         clang_type.CompleteTagDeclarationDefinition ();
2779         return (bool)clang_type;
2780 
2781     default:
2782         assert(false && "not a forward clang type decl!");
2783         break;
2784     }
2785     return false;
2786 }
2787 
2788 Type*
2789 SymbolFileDWARF::ResolveType (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* type_die, bool assert_not_being_parsed)
2790 {
2791     if (type_die != NULL)
2792     {
2793         Type *type = m_die_to_type.lookup (type_die);
2794 
2795         if (type == NULL)
2796             type = GetTypeForDIE (dwarf_cu, type_die).get();
2797 
2798         if (assert_not_being_parsed)
2799         {
2800             if (type != DIE_IS_BEING_PARSED)
2801                 return type;
2802 
2803             GetObjectFile()->GetModule()->ReportError ("Parsing a die that is being parsed die: 0x%8.8x: %s %s",
2804                                                        type_die->GetOffset(),
2805                                                        DW_TAG_value_to_name(type_die->Tag()),
2806                                                        type_die->GetName(this, dwarf_cu));
2807 
2808         }
2809         else
2810             return type;
2811     }
2812     return NULL;
2813 }
2814 
2815 CompileUnit*
2816 SymbolFileDWARF::GetCompUnitForDWARFCompUnit (DWARFCompileUnit* dwarf_cu, uint32_t cu_idx)
2817 {
2818     // Check if the symbol vendor already knows about this compile unit?
2819     if (dwarf_cu->GetUserData() == NULL)
2820     {
2821         // The symbol vendor doesn't know about this compile unit, we
2822         // need to parse and add it to the symbol vendor object.
2823         return ParseCompileUnit(dwarf_cu, cu_idx).get();
2824     }
2825     return (CompileUnit*)dwarf_cu->GetUserData();
2826 }
2827 
2828 bool
2829 SymbolFileDWARF::GetFunction (DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry* func_die, SymbolContext& sc)
2830 {
2831     sc.Clear(false);
2832     // Check if the symbol vendor already knows about this compile unit?
2833     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
2834 
2835     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(func_die->GetOffset())).get();
2836     if (sc.function == NULL)
2837         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, func_die);
2838 
2839     if (sc.function)
2840     {
2841         sc.module_sp = sc.function->CalculateSymbolContextModule();
2842         return true;
2843     }
2844 
2845     return false;
2846 }
2847 
2848 
2849 
2850 SymbolFileDWARF::GlobalVariableMap &
2851 SymbolFileDWARF::GetGlobalAranges()
2852 {
2853     if (!m_global_aranges_ap)
2854     {
2855         m_global_aranges_ap.reset (new GlobalVariableMap());
2856 
2857         ModuleSP module_sp = GetObjectFile()->GetModule();
2858         if (module_sp)
2859         {
2860             const size_t num_cus = module_sp->GetNumCompileUnits();
2861             for (size_t i = 0; i < num_cus; ++i)
2862             {
2863                 CompUnitSP cu_sp = module_sp->GetCompileUnitAtIndex(i);
2864                 if (cu_sp)
2865                 {
2866                     VariableListSP globals_sp = cu_sp->GetVariableList(true);
2867                     if (globals_sp)
2868                     {
2869                         const size_t num_globals = globals_sp->GetSize();
2870                         for (size_t g = 0; g < num_globals; ++g)
2871                         {
2872                             VariableSP var_sp = globals_sp->GetVariableAtIndex(g);
2873                             if (var_sp && !var_sp->GetLocationIsConstantValueData())
2874                             {
2875                                 const DWARFExpression &location = var_sp->LocationExpression();
2876                                 Value location_result;
2877                                 Error error;
2878                                 if (location.Evaluate(NULL, NULL, NULL, LLDB_INVALID_ADDRESS, NULL, location_result, &error))
2879                                 {
2880                                     if (location_result.GetValueType() == Value::eValueTypeFileAddress)
2881                                     {
2882                                         lldb::addr_t file_addr = location_result.GetScalar().ULongLong();
2883                                         lldb::addr_t byte_size = 1;
2884                                         if (var_sp->GetType())
2885                                             byte_size = var_sp->GetType()->GetByteSize();
2886                                         m_global_aranges_ap->Append(GlobalVariableMap::Entry(file_addr, byte_size, var_sp.get()));
2887                                     }
2888                                 }
2889                             }
2890                         }
2891                     }
2892                 }
2893             }
2894         }
2895         m_global_aranges_ap->Sort();
2896     }
2897     return *m_global_aranges_ap;
2898 }
2899 
2900 
2901 uint32_t
2902 SymbolFileDWARF::ResolveSymbolContext (const Address& so_addr, uint32_t resolve_scope, SymbolContext& sc)
2903 {
2904     Timer scoped_timer(__PRETTY_FUNCTION__,
2905                        "SymbolFileDWARF::ResolveSymbolContext (so_addr = { section = %p, offset = 0x%" PRIx64 " }, resolve_scope = 0x%8.8x)",
2906                        static_cast<void*>(so_addr.GetSection().get()),
2907                        so_addr.GetOffset(), resolve_scope);
2908     uint32_t resolved = 0;
2909     if (resolve_scope & (   eSymbolContextCompUnit  |
2910                             eSymbolContextFunction  |
2911                             eSymbolContextBlock     |
2912                             eSymbolContextLineEntry |
2913                             eSymbolContextVariable  ))
2914     {
2915         lldb::addr_t file_vm_addr = so_addr.GetFileAddress();
2916 
2917         DWARFDebugInfo* debug_info = DebugInfo();
2918         if (debug_info)
2919         {
2920             const dw_offset_t cu_offset = debug_info->GetCompileUnitAranges().FindAddress(file_vm_addr);
2921             if (cu_offset == DW_INVALID_OFFSET)
2922             {
2923                 // Global variables are not in the compile unit address ranges. The only way to
2924                 // currently find global variables is to iterate over the .debug_pubnames or the
2925                 // __apple_names table and find all items in there that point to DW_TAG_variable
2926                 // DIEs and then find the address that matches.
2927                 if (resolve_scope & eSymbolContextVariable)
2928                 {
2929                     GlobalVariableMap &map = GetGlobalAranges();
2930                     const GlobalVariableMap::Entry *entry = map.FindEntryThatContains(file_vm_addr);
2931                     if (entry && entry->data)
2932                     {
2933                         Variable *variable = entry->data;
2934                         SymbolContextScope *scc = variable->GetSymbolContextScope();
2935                         if (scc)
2936                         {
2937                             scc->CalculateSymbolContext(&sc);
2938                             sc.variable = variable;
2939                         }
2940                         return sc.GetResolvedMask();
2941                     }
2942                 }
2943             }
2944             else
2945             {
2946                 uint32_t cu_idx = DW_INVALID_INDEX;
2947                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnit(cu_offset, &cu_idx).get();
2948                 if (dwarf_cu)
2949                 {
2950                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
2951                     if (sc.comp_unit)
2952                     {
2953                         resolved |= eSymbolContextCompUnit;
2954 
2955                         bool force_check_line_table = false;
2956                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
2957                         {
2958                             DWARFDebugInfoEntry *function_die = NULL;
2959                             DWARFDebugInfoEntry *block_die = NULL;
2960                             if (resolve_scope & eSymbolContextBlock)
2961                             {
2962                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, &block_die);
2963                             }
2964                             else
2965                             {
2966                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, NULL);
2967                             }
2968 
2969                             if (function_die != NULL)
2970                             {
2971                                 sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
2972                                 if (sc.function == NULL)
2973                                     sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
2974                             }
2975                             else
2976                             {
2977                                 // We might have had a compile unit that had discontiguous
2978                                 // address ranges where the gaps are symbols that don't have
2979                                 // any debug info. Discontiguous compile unit address ranges
2980                                 // should only happen when there aren't other functions from
2981                                 // other compile units in these gaps. This helps keep the size
2982                                 // of the aranges down.
2983                                 force_check_line_table = true;
2984                             }
2985 
2986                             if (sc.function != NULL)
2987                             {
2988                                 resolved |= eSymbolContextFunction;
2989 
2990                                 if (resolve_scope & eSymbolContextBlock)
2991                                 {
2992                                     Block& block = sc.function->GetBlock (true);
2993 
2994                                     if (block_die != NULL)
2995                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
2996                                     else
2997                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
2998                                     if (sc.block)
2999                                         resolved |= eSymbolContextBlock;
3000                                 }
3001                             }
3002                         }
3003 
3004                         if ((resolve_scope & eSymbolContextLineEntry) || force_check_line_table)
3005                         {
3006                             LineTable *line_table = sc.comp_unit->GetLineTable();
3007                             if (line_table != NULL)
3008                             {
3009                                 // And address that makes it into this function should be in terms
3010                                 // of this debug file if there is no debug map, or it will be an
3011                                 // address in the .o file which needs to be fixed up to be in terms
3012                                 // of the debug map executable. Either way, calling FixupAddress()
3013                                 // will work for us.
3014                                 Address exe_so_addr (so_addr);
3015                                 if (FixupAddress(exe_so_addr))
3016                                 {
3017                                     if (line_table->FindLineEntryByAddress (exe_so_addr, sc.line_entry))
3018                                     {
3019                                         resolved |= eSymbolContextLineEntry;
3020                                     }
3021                                 }
3022                             }
3023                         }
3024 
3025                         if (force_check_line_table && !(resolved & eSymbolContextLineEntry))
3026                         {
3027                             // We might have had a compile unit that had discontiguous
3028                             // address ranges where the gaps are symbols that don't have
3029                             // any debug info. Discontiguous compile unit address ranges
3030                             // should only happen when there aren't other functions from
3031                             // other compile units in these gaps. This helps keep the size
3032                             // of the aranges down.
3033                             sc.comp_unit = NULL;
3034                             resolved &= ~eSymbolContextCompUnit;
3035                         }
3036                     }
3037                     else
3038                     {
3039                         GetObjectFile()->GetModule()->ReportWarning ("0x%8.8x: compile unit %u failed to create a valid lldb_private::CompileUnit class.",
3040                                                                      cu_offset,
3041                                                                      cu_idx);
3042                     }
3043                 }
3044             }
3045         }
3046     }
3047     return resolved;
3048 }
3049 
3050 
3051 
3052 uint32_t
3053 SymbolFileDWARF::ResolveSymbolContext(const FileSpec& file_spec, uint32_t line, bool check_inlines, uint32_t resolve_scope, SymbolContextList& sc_list)
3054 {
3055     const uint32_t prev_size = sc_list.GetSize();
3056     if (resolve_scope & eSymbolContextCompUnit)
3057     {
3058         DWARFDebugInfo* debug_info = DebugInfo();
3059         if (debug_info)
3060         {
3061             uint32_t cu_idx;
3062             DWARFCompileUnit* dwarf_cu = NULL;
3063 
3064             for (cu_idx = 0; (dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx)) != NULL; ++cu_idx)
3065             {
3066                 CompileUnit *dc_cu = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
3067                 const bool full_match = (bool)file_spec.GetDirectory();
3068                 bool file_spec_matches_cu_file_spec = dc_cu != NULL && FileSpec::Equal(file_spec, *dc_cu, full_match);
3069                 if (check_inlines || file_spec_matches_cu_file_spec)
3070                 {
3071                     SymbolContext sc (m_obj_file->GetModule());
3072                     sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, cu_idx);
3073                     if (sc.comp_unit)
3074                     {
3075                         uint32_t file_idx = UINT32_MAX;
3076 
3077                         // If we are looking for inline functions only and we don't
3078                         // find it in the support files, we are done.
3079                         if (check_inlines)
3080                         {
3081                             file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
3082                             if (file_idx == UINT32_MAX)
3083                                 continue;
3084                         }
3085 
3086                         if (line != 0)
3087                         {
3088                             LineTable *line_table = sc.comp_unit->GetLineTable();
3089 
3090                             if (line_table != NULL && line != 0)
3091                             {
3092                                 // We will have already looked up the file index if
3093                                 // we are searching for inline entries.
3094                                 if (!check_inlines)
3095                                     file_idx = sc.comp_unit->GetSupportFiles().FindFileIndex (1, file_spec, true);
3096 
3097                                 if (file_idx != UINT32_MAX)
3098                                 {
3099                                     uint32_t found_line;
3100                                     uint32_t line_idx = line_table->FindLineEntryIndexByFileIndex (0, file_idx, line, false, &sc.line_entry);
3101                                     found_line = sc.line_entry.line;
3102 
3103                                     while (line_idx != UINT32_MAX)
3104                                     {
3105                                         sc.function = NULL;
3106                                         sc.block = NULL;
3107                                         if (resolve_scope & (eSymbolContextFunction | eSymbolContextBlock))
3108                                         {
3109                                             const lldb::addr_t file_vm_addr = sc.line_entry.range.GetBaseAddress().GetFileAddress();
3110                                             if (file_vm_addr != LLDB_INVALID_ADDRESS)
3111                                             {
3112                                                 DWARFDebugInfoEntry *function_die = NULL;
3113                                                 DWARFDebugInfoEntry *block_die = NULL;
3114                                                 dwarf_cu->LookupAddress(file_vm_addr, &function_die, resolve_scope & eSymbolContextBlock ? &block_die : NULL);
3115 
3116                                                 if (function_die != NULL)
3117                                                 {
3118                                                     sc.function = sc.comp_unit->FindFunctionByUID (MakeUserID(function_die->GetOffset())).get();
3119                                                     if (sc.function == NULL)
3120                                                         sc.function = ParseCompileUnitFunction(sc, dwarf_cu, function_die);
3121                                                 }
3122 
3123                                                 if (sc.function != NULL)
3124                                                 {
3125                                                     Block& block = sc.function->GetBlock (true);
3126 
3127                                                     if (block_die != NULL)
3128                                                         sc.block = block.FindBlockByID (MakeUserID(block_die->GetOffset()));
3129                                                     else if (function_die != NULL)
3130                                                         sc.block = block.FindBlockByID (MakeUserID(function_die->GetOffset()));
3131                                                 }
3132                                             }
3133                                         }
3134 
3135                                         sc_list.Append(sc);
3136                                         line_idx = line_table->FindLineEntryIndexByFileIndex (line_idx + 1, file_idx, found_line, true, &sc.line_entry);
3137                                     }
3138                                 }
3139                             }
3140                             else if (file_spec_matches_cu_file_spec && !check_inlines)
3141                             {
3142                                 // only append the context if we aren't looking for inline call sites
3143                                 // by file and line and if the file spec matches that of the compile unit
3144                                 sc_list.Append(sc);
3145                             }
3146                         }
3147                         else if (file_spec_matches_cu_file_spec && !check_inlines)
3148                         {
3149                             // only append the context if we aren't looking for inline call sites
3150                             // by file and line and if the file spec matches that of the compile unit
3151                             sc_list.Append(sc);
3152                         }
3153 
3154                         if (!check_inlines)
3155                             break;
3156                     }
3157                 }
3158             }
3159         }
3160     }
3161     return sc_list.GetSize() - prev_size;
3162 }
3163 
3164 void
3165 SymbolFileDWARF::Index ()
3166 {
3167     if (m_indexed)
3168         return;
3169     m_indexed = true;
3170     Timer scoped_timer (__PRETTY_FUNCTION__,
3171                         "SymbolFileDWARF::Index (%s)",
3172                         GetObjectFile()->GetFileSpec().GetFilename().AsCString("<Unknown>"));
3173 
3174     DWARFDebugInfo* debug_info = DebugInfo();
3175     if (debug_info)
3176     {
3177         uint32_t cu_idx = 0;
3178         const uint32_t num_compile_units = GetNumCompileUnits();
3179         for (cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
3180         {
3181             DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
3182 
3183             bool clear_dies = dwarf_cu->ExtractDIEsIfNeeded (false) > 1;
3184 
3185             dwarf_cu->Index (cu_idx,
3186                              m_function_basename_index,
3187                              m_function_fullname_index,
3188                              m_function_method_index,
3189                              m_function_selector_index,
3190                              m_objc_class_selectors_index,
3191                              m_global_index,
3192                              m_type_index,
3193                              m_namespace_index);
3194 
3195             // Keep memory down by clearing DIEs if this generate function
3196             // caused them to be parsed
3197             if (clear_dies)
3198                 dwarf_cu->ClearDIEs (true);
3199         }
3200 
3201         m_function_basename_index.Finalize();
3202         m_function_fullname_index.Finalize();
3203         m_function_method_index.Finalize();
3204         m_function_selector_index.Finalize();
3205         m_objc_class_selectors_index.Finalize();
3206         m_global_index.Finalize();
3207         m_type_index.Finalize();
3208         m_namespace_index.Finalize();
3209 
3210 #if defined (ENABLE_DEBUG_PRINTF)
3211         StreamFile s(stdout, false);
3212         s.Printf ("DWARF index for '%s':",
3213                   GetObjectFile()->GetFileSpec().GetPath().c_str());
3214         s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
3215         s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
3216         s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
3217         s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
3218         s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
3219         s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
3220         s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
3221         s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
3222 #endif
3223     }
3224 }
3225 
3226 bool
3227 SymbolFileDWARF::NamespaceDeclMatchesThisSymbolFile (const ClangNamespaceDecl *namespace_decl)
3228 {
3229     if (namespace_decl == NULL)
3230     {
3231         // Invalid namespace decl which means we aren't matching only things
3232         // in this symbol file, so return true to indicate it matches this
3233         // symbol file.
3234         return true;
3235     }
3236 
3237     clang::ASTContext *namespace_ast = namespace_decl->GetASTContext();
3238 
3239     if (namespace_ast == NULL)
3240         return true;    // No AST in the "namespace_decl", return true since it
3241                         // could then match any symbol file, including this one
3242 
3243     if (namespace_ast == GetClangASTContext().getASTContext())
3244         return true;    // The ASTs match, return true
3245 
3246     // The namespace AST was valid, and it does not match...
3247     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3248 
3249     if (log)
3250         GetObjectFile()->GetModule()->LogMessage(log, "Valid namespace does not match symbol file");
3251 
3252     return false;
3253 }
3254 
3255 bool
3256 SymbolFileDWARF::DIEIsInNamespace (const ClangNamespaceDecl *namespace_decl,
3257                                    DWARFCompileUnit* cu,
3258                                    const DWARFDebugInfoEntry* die)
3259 {
3260     // No namespace specified, so the answer is
3261     if (namespace_decl == NULL)
3262         return true;
3263 
3264     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3265 
3266     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
3267     clang::DeclContext *die_clang_decl_ctx = GetClangDeclContextContainingDIE (cu, die, &decl_ctx_die);
3268     if (decl_ctx_die)
3269     {
3270         clang::NamespaceDecl *clang_namespace_decl = namespace_decl->GetNamespaceDecl();
3271 
3272         if (clang_namespace_decl)
3273         {
3274             if (decl_ctx_die->Tag() != DW_TAG_namespace)
3275             {
3276                 if (log)
3277                     GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent is not a namespace");
3278                 return false;
3279             }
3280 
3281             if (clang_namespace_decl == die_clang_decl_ctx)
3282                 return true;
3283             else
3284                 return false;
3285         }
3286         else
3287         {
3288             // We have a namespace_decl that was not NULL but it contained
3289             // a NULL "clang::NamespaceDecl", so this means the global namespace
3290             // So as long the contained decl context DIE isn't a namespace
3291             // we should be ok.
3292             if (decl_ctx_die->Tag() != DW_TAG_namespace)
3293                 return true;
3294         }
3295     }
3296 
3297     if (log)
3298         GetObjectFile()->GetModule()->LogMessage(log, "Found a match, but its parent doesn't exist");
3299 
3300     return false;
3301 }
3302 uint32_t
3303 SymbolFileDWARF::FindGlobalVariables (const ConstString &name, const lldb_private::ClangNamespaceDecl *namespace_decl, bool append, uint32_t max_matches, VariableList& variables)
3304 {
3305     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3306 
3307     if (log)
3308         GetObjectFile()->GetModule()->LogMessage (log,
3309                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables)",
3310                                                   name.GetCString(),
3311                                                   static_cast<const void*>(namespace_decl),
3312                                                   append, max_matches);
3313 
3314     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3315         return 0;
3316 
3317     DWARFDebugInfo* info = DebugInfo();
3318     if (info == NULL)
3319         return 0;
3320 
3321     // If we aren't appending the results to this list, then clear the list
3322     if (!append)
3323         variables.Clear();
3324 
3325     // Remember how many variables are in the list before we search in case
3326     // we are appending the results to a variable list.
3327     const uint32_t original_size = variables.GetSize();
3328 
3329     DIEArray die_offsets;
3330 
3331     if (m_using_apple_tables)
3332     {
3333         if (m_apple_names_ap.get())
3334         {
3335             const char *name_cstr = name.GetCString();
3336             llvm::StringRef basename;
3337             llvm::StringRef context;
3338 
3339             if (!CPPLanguageRuntime::ExtractContextAndIdentifier(name_cstr, context, basename))
3340                 basename = name_cstr;
3341 
3342             m_apple_names_ap->FindByName (basename.data(), die_offsets);
3343         }
3344     }
3345     else
3346     {
3347         // Index the DWARF if we haven't already
3348         if (!m_indexed)
3349             Index ();
3350 
3351         m_global_index.Find (name, die_offsets);
3352     }
3353 
3354     const size_t num_die_matches = die_offsets.size();
3355     if (num_die_matches)
3356     {
3357         SymbolContext sc;
3358         sc.module_sp = m_obj_file->GetModule();
3359         assert (sc.module_sp);
3360 
3361         DWARFDebugInfo* debug_info = DebugInfo();
3362         DWARFCompileUnit* dwarf_cu = NULL;
3363         const DWARFDebugInfoEntry* die = NULL;
3364         bool done = false;
3365         for (size_t i=0; i<num_die_matches && !done; ++i)
3366         {
3367             const dw_offset_t die_offset = die_offsets[i];
3368             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3369 
3370             if (die)
3371             {
3372                 switch (die->Tag())
3373                 {
3374                     default:
3375                     case DW_TAG_subprogram:
3376                     case DW_TAG_inlined_subroutine:
3377                     case DW_TAG_try_block:
3378                     case DW_TAG_catch_block:
3379                         break;
3380 
3381                     case DW_TAG_variable:
3382                         {
3383                             sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3384 
3385                             if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3386                                 continue;
3387 
3388                             ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3389 
3390                             if (variables.GetSize() - original_size >= max_matches)
3391                                 done = true;
3392                         }
3393                         break;
3394                 }
3395             }
3396             else
3397             {
3398                 if (m_using_apple_tables)
3399                 {
3400                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')\n",
3401                                                                                die_offset, name.GetCString());
3402                 }
3403             }
3404         }
3405     }
3406 
3407     // Return the number of variable that were appended to the list
3408     const uint32_t num_matches = variables.GetSize() - original_size;
3409     if (log && num_matches > 0)
3410     {
3411         GetObjectFile()->GetModule()->LogMessage (log,
3412                                                   "SymbolFileDWARF::FindGlobalVariables (name=\"%s\", namespace_decl=%p, append=%u, max_matches=%u, variables) => %u",
3413                                                   name.GetCString(),
3414                                                   static_cast<const void*>(namespace_decl),
3415                                                   append, max_matches,
3416                                                   num_matches);
3417     }
3418     return num_matches;
3419 }
3420 
3421 uint32_t
3422 SymbolFileDWARF::FindGlobalVariables(const RegularExpression& regex, bool append, uint32_t max_matches, VariableList& variables)
3423 {
3424     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3425 
3426     if (log)
3427     {
3428         GetObjectFile()->GetModule()->LogMessage (log,
3429                                                   "SymbolFileDWARF::FindGlobalVariables (regex=\"%s\", append=%u, max_matches=%u, variables)",
3430                                                   regex.GetText(), append,
3431                                                   max_matches);
3432     }
3433 
3434     DWARFDebugInfo* info = DebugInfo();
3435     if (info == NULL)
3436         return 0;
3437 
3438     // If we aren't appending the results to this list, then clear the list
3439     if (!append)
3440         variables.Clear();
3441 
3442     // Remember how many variables are in the list before we search in case
3443     // we are appending the results to a variable list.
3444     const uint32_t original_size = variables.GetSize();
3445 
3446     DIEArray die_offsets;
3447 
3448     if (m_using_apple_tables)
3449     {
3450         if (m_apple_names_ap.get())
3451         {
3452             DWARFMappedHash::DIEInfoArray hash_data_array;
3453             if (m_apple_names_ap->AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3454                 DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3455         }
3456     }
3457     else
3458     {
3459         // Index the DWARF if we haven't already
3460         if (!m_indexed)
3461             Index ();
3462 
3463         m_global_index.Find (regex, die_offsets);
3464     }
3465 
3466     SymbolContext sc;
3467     sc.module_sp = m_obj_file->GetModule();
3468     assert (sc.module_sp);
3469 
3470     DWARFCompileUnit* dwarf_cu = NULL;
3471     const DWARFDebugInfoEntry* die = NULL;
3472     const size_t num_matches = die_offsets.size();
3473     if (num_matches)
3474     {
3475         DWARFDebugInfo* debug_info = DebugInfo();
3476         for (size_t i=0; i<num_matches; ++i)
3477         {
3478             const dw_offset_t die_offset = die_offsets[i];
3479             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3480 
3481             if (die)
3482             {
3483                 sc.comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
3484 
3485                 ParseVariables(sc, dwarf_cu, LLDB_INVALID_ADDRESS, die, false, false, &variables);
3486 
3487                 if (variables.GetSize() - original_size >= max_matches)
3488                     break;
3489             }
3490             else
3491             {
3492                 if (m_using_apple_tables)
3493                 {
3494                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for regex '%s')\n",
3495                                                                                die_offset, regex.GetText());
3496                 }
3497             }
3498         }
3499     }
3500 
3501     // Return the number of variable that were appended to the list
3502     return variables.GetSize() - original_size;
3503 }
3504 
3505 
3506 bool
3507 SymbolFileDWARF::ResolveFunction (dw_offset_t die_offset,
3508                                   DWARFCompileUnit *&dwarf_cu,
3509                                   bool include_inlines,
3510                                   SymbolContextList& sc_list)
3511 {
3512     const DWARFDebugInfoEntry *die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3513     return ResolveFunction (dwarf_cu, die, include_inlines, sc_list);
3514 }
3515 
3516 
3517 bool
3518 SymbolFileDWARF::ResolveFunction (DWARFCompileUnit *cu,
3519                                   const DWARFDebugInfoEntry *die,
3520                                   bool include_inlines,
3521                                   SymbolContextList& sc_list)
3522 {
3523     SymbolContext sc;
3524 
3525     if (die == NULL)
3526         return false;
3527 
3528     // If we were passed a die that is not a function, just return false...
3529     if (! (die->Tag() == DW_TAG_subprogram || (include_inlines && die->Tag() == DW_TAG_inlined_subroutine)))
3530         return false;
3531 
3532     const DWARFDebugInfoEntry* inlined_die = NULL;
3533     if (die->Tag() == DW_TAG_inlined_subroutine)
3534     {
3535         inlined_die = die;
3536 
3537         while ((die = die->GetParent()) != NULL)
3538         {
3539             if (die->Tag() == DW_TAG_subprogram)
3540                 break;
3541         }
3542     }
3543     assert (die && die->Tag() == DW_TAG_subprogram);
3544     if (GetFunction (cu, die, sc))
3545     {
3546         Address addr;
3547         // Parse all blocks if needed
3548         if (inlined_die)
3549         {
3550             Block &function_block = sc.function->GetBlock (true);
3551             sc.block = function_block.FindBlockByID (MakeUserID(inlined_die->GetOffset()));
3552             if (sc.block == NULL)
3553                 sc.block = function_block.FindBlockByID (inlined_die->GetOffset());
3554             if (sc.block == NULL || sc.block->GetStartAddress (addr) == false)
3555                 addr.Clear();
3556         }
3557         else
3558         {
3559             sc.block = NULL;
3560             addr = sc.function->GetAddressRange().GetBaseAddress();
3561         }
3562 
3563         if (addr.IsValid())
3564         {
3565             sc_list.Append(sc);
3566             return true;
3567         }
3568     }
3569 
3570     return false;
3571 }
3572 
3573 void
3574 SymbolFileDWARF::FindFunctions (const ConstString &name,
3575                                 const NameToDIE &name_to_die,
3576                                 bool include_inlines,
3577                                 SymbolContextList& sc_list)
3578 {
3579     DIEArray die_offsets;
3580     if (name_to_die.Find (name, die_offsets))
3581     {
3582         ParseFunctions (die_offsets, include_inlines, sc_list);
3583     }
3584 }
3585 
3586 
3587 void
3588 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3589                                 const NameToDIE &name_to_die,
3590                                 bool include_inlines,
3591                                 SymbolContextList& sc_list)
3592 {
3593     DIEArray die_offsets;
3594     if (name_to_die.Find (regex, die_offsets))
3595     {
3596         ParseFunctions (die_offsets, include_inlines, sc_list);
3597     }
3598 }
3599 
3600 
3601 void
3602 SymbolFileDWARF::FindFunctions (const RegularExpression &regex,
3603                                 const DWARFMappedHash::MemoryTable &memory_table,
3604                                 bool include_inlines,
3605                                 SymbolContextList& sc_list)
3606 {
3607     DIEArray die_offsets;
3608     DWARFMappedHash::DIEInfoArray hash_data_array;
3609     if (memory_table.AppendAllDIEsThatMatchingRegex (regex, hash_data_array))
3610     {
3611         DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
3612         ParseFunctions (die_offsets, include_inlines, sc_list);
3613     }
3614 }
3615 
3616 void
3617 SymbolFileDWARF::ParseFunctions (const DIEArray &die_offsets,
3618                                  bool include_inlines,
3619                                  SymbolContextList& sc_list)
3620 {
3621     const size_t num_matches = die_offsets.size();
3622     if (num_matches)
3623     {
3624         DWARFCompileUnit* dwarf_cu = NULL;
3625         for (size_t i=0; i<num_matches; ++i)
3626         {
3627             const dw_offset_t die_offset = die_offsets[i];
3628             ResolveFunction (die_offset, dwarf_cu, include_inlines, sc_list);
3629         }
3630     }
3631 }
3632 
3633 bool
3634 SymbolFileDWARF::FunctionDieMatchesPartialName (const DWARFDebugInfoEntry* die,
3635                                                 const DWARFCompileUnit *dwarf_cu,
3636                                                 uint32_t name_type_mask,
3637                                                 const char *partial_name,
3638                                                 const char *base_name_start,
3639                                                 const char *base_name_end)
3640 {
3641     // If we are looking only for methods, throw away all the ones that are or aren't in C++ classes:
3642     if (name_type_mask == eFunctionNameTypeMethod || name_type_mask == eFunctionNameTypeBase)
3643     {
3644         clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIEOffset(die->GetOffset());
3645         if (!containing_decl_ctx)
3646             return false;
3647 
3648         bool is_cxx_method = DeclKindIsCXXClass(containing_decl_ctx->getDeclKind());
3649 
3650         if (name_type_mask == eFunctionNameTypeMethod)
3651         {
3652             if (is_cxx_method == false)
3653                 return false;
3654         }
3655 
3656         if (name_type_mask == eFunctionNameTypeBase)
3657         {
3658             if (is_cxx_method == true)
3659                 return false;
3660         }
3661     }
3662 
3663     // Now we need to check whether the name we got back for this type matches the extra specifications
3664     // that were in the name we're looking up:
3665     if (base_name_start != partial_name || *base_name_end != '\0')
3666     {
3667         // First see if the stuff to the left matches the full name.  To do that let's see if
3668         // we can pull out the mips linkage name attribute:
3669 
3670         Mangled best_name;
3671         DWARFDebugInfoEntry::Attributes attributes;
3672         DWARFFormValue form_value;
3673         die->GetAttributes(this, dwarf_cu, NULL, attributes);
3674         uint32_t idx = attributes.FindAttributeIndex(DW_AT_MIPS_linkage_name);
3675         if (idx == UINT32_MAX)
3676             idx = attributes.FindAttributeIndex(DW_AT_linkage_name);
3677         if (idx != UINT32_MAX)
3678         {
3679             if (attributes.ExtractFormValueAtIndex(this, idx, form_value))
3680             {
3681                 const char *mangled_name = form_value.AsCString(&get_debug_str_data());
3682                 if (mangled_name)
3683                     best_name.SetValue (ConstString(mangled_name), true);
3684             }
3685         }
3686 
3687         if (!best_name)
3688         {
3689             idx = attributes.FindAttributeIndex(DW_AT_name);
3690             if (idx != UINT32_MAX && attributes.ExtractFormValueAtIndex(this, idx, form_value))
3691             {
3692                 const char *name = form_value.AsCString(&get_debug_str_data());
3693                 best_name.SetValue (ConstString(name), false);
3694             }
3695         }
3696 
3697         if (best_name.GetDemangledName())
3698         {
3699             const char *demangled = best_name.GetDemangledName().GetCString();
3700             if (demangled)
3701             {
3702                 std::string name_no_parens(partial_name, base_name_end - partial_name);
3703                 const char *partial_in_demangled = strstr (demangled, name_no_parens.c_str());
3704                 if (partial_in_demangled == NULL)
3705                     return false;
3706                 else
3707                 {
3708                     // Sort out the case where our name is something like "Process::Destroy" and the match is
3709                     // "SBProcess::Destroy" - that shouldn't be a match.  We should really always match on
3710                     // namespace boundaries...
3711 
3712                     if (partial_name[0] == ':'  && partial_name[1] == ':')
3713                     {
3714                         // The partial name was already on a namespace boundary so all matches are good.
3715                         return true;
3716                     }
3717                     else if (partial_in_demangled == demangled)
3718                     {
3719                         // They both start the same, so this is an good match.
3720                         return true;
3721                     }
3722                     else
3723                     {
3724                         if (partial_in_demangled - demangled == 1)
3725                         {
3726                             // Only one character difference, can't be a namespace boundary...
3727                             return false;
3728                         }
3729                         else if (*(partial_in_demangled - 1) == ':' && *(partial_in_demangled - 2) == ':')
3730                         {
3731                             // We are on a namespace boundary, so this is also good.
3732                             return true;
3733                         }
3734                         else
3735                             return false;
3736                     }
3737                 }
3738             }
3739         }
3740     }
3741 
3742     return true;
3743 }
3744 
3745 uint32_t
3746 SymbolFileDWARF::FindFunctions (const ConstString &name,
3747                                 const lldb_private::ClangNamespaceDecl *namespace_decl,
3748                                 uint32_t name_type_mask,
3749                                 bool include_inlines,
3750                                 bool append,
3751                                 SymbolContextList& sc_list)
3752 {
3753     Timer scoped_timer (__PRETTY_FUNCTION__,
3754                         "SymbolFileDWARF::FindFunctions (name = '%s')",
3755                         name.AsCString());
3756 
3757     // eFunctionNameTypeAuto should be pre-resolved by a call to Module::PrepareForFunctionNameLookup()
3758     assert ((name_type_mask & eFunctionNameTypeAuto) == 0);
3759 
3760     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
3761 
3762     if (log)
3763     {
3764         GetObjectFile()->GetModule()->LogMessage (log,
3765                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, append=%u, sc_list)",
3766                                                   name.GetCString(),
3767                                                   name_type_mask,
3768                                                   append);
3769     }
3770 
3771     // If we aren't appending the results to this list, then clear the list
3772     if (!append)
3773         sc_list.Clear();
3774 
3775     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
3776         return 0;
3777 
3778     // If name is empty then we won't find anything.
3779     if (name.IsEmpty())
3780         return 0;
3781 
3782     // Remember how many sc_list are in the list before we search in case
3783     // we are appending the results to a variable list.
3784 
3785     const char *name_cstr = name.GetCString();
3786 
3787     const uint32_t original_size = sc_list.GetSize();
3788 
3789     DWARFDebugInfo* info = DebugInfo();
3790     if (info == NULL)
3791         return 0;
3792 
3793     DWARFCompileUnit *dwarf_cu = NULL;
3794     std::set<const DWARFDebugInfoEntry *> resolved_dies;
3795     if (m_using_apple_tables)
3796     {
3797         if (m_apple_names_ap.get())
3798         {
3799 
3800             DIEArray die_offsets;
3801 
3802             uint32_t num_matches = 0;
3803 
3804             if (name_type_mask & eFunctionNameTypeFull)
3805             {
3806                 // If they asked for the full name, match what they typed.  At some point we may
3807                 // want to canonicalize this (strip double spaces, etc.  For now, we just add all the
3808                 // dies that we find by exact match.
3809                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3810                 for (uint32_t i = 0; i < num_matches; i++)
3811                 {
3812                     const dw_offset_t die_offset = die_offsets[i];
3813                     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3814                     if (die)
3815                     {
3816                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3817                             continue;
3818 
3819                         if (resolved_dies.find(die) == resolved_dies.end())
3820                         {
3821                             if (ResolveFunction (dwarf_cu, die, include_inlines, sc_list))
3822                                 resolved_dies.insert(die);
3823                         }
3824                     }
3825                     else
3826                     {
3827                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3828                                                                                    die_offset, name_cstr);
3829                     }
3830                 }
3831             }
3832 
3833             if (name_type_mask & eFunctionNameTypeSelector)
3834             {
3835                 if (namespace_decl && *namespace_decl)
3836                     return 0; // no selectors in namespaces
3837 
3838                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3839                 // Now make sure these are actually ObjC methods.  In this case we can simply look up the name,
3840                 // and if it is an ObjC method name, we're good.
3841 
3842                 for (uint32_t i = 0; i < num_matches; i++)
3843                 {
3844                     const dw_offset_t die_offset = die_offsets[i];
3845                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3846                     if (die)
3847                     {
3848                         const char *die_name = die->GetName(this, dwarf_cu);
3849                         if (ObjCLanguageRuntime::IsPossibleObjCMethodName(die_name))
3850                         {
3851                             if (resolved_dies.find(die) == resolved_dies.end())
3852                             {
3853                                 if (ResolveFunction (dwarf_cu, die, include_inlines, sc_list))
3854                                     resolved_dies.insert(die);
3855                             }
3856                         }
3857                     }
3858                     else
3859                     {
3860                         GetObjectFile()->GetModule()->ReportError ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3861                                                                    die_offset, name_cstr);
3862                     }
3863                 }
3864                 die_offsets.clear();
3865             }
3866 
3867             if (((name_type_mask & eFunctionNameTypeMethod) && !namespace_decl) || name_type_mask & eFunctionNameTypeBase)
3868             {
3869                 // The apple_names table stores just the "base name" of C++ methods in the table.  So we have to
3870                 // extract the base name, look that up, and if there is any other information in the name we were
3871                 // passed in we have to post-filter based on that.
3872 
3873                 // FIXME: Arrange the logic above so that we don't calculate the base name twice:
3874                 num_matches = m_apple_names_ap->FindByName (name_cstr, die_offsets);
3875 
3876                 for (uint32_t i = 0; i < num_matches; i++)
3877                 {
3878                     const dw_offset_t die_offset = die_offsets[i];
3879                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
3880                     if (die)
3881                     {
3882                         if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
3883                             continue;
3884 
3885                         // If we get to here, the die is good, and we should add it:
3886                         if (resolved_dies.find(die) == resolved_dies.end())
3887                         if (ResolveFunction (dwarf_cu, die, include_inlines, sc_list))
3888                         {
3889                             bool keep_die = true;
3890                             if ((name_type_mask & (eFunctionNameTypeBase|eFunctionNameTypeMethod)) != (eFunctionNameTypeBase|eFunctionNameTypeMethod))
3891                             {
3892                                 // We are looking for either basenames or methods, so we need to
3893                                 // trim out the ones we won't want by looking at the type
3894                                 SymbolContext sc;
3895                                 if (sc_list.GetLastContext(sc))
3896                                 {
3897                                     if (sc.block)
3898                                     {
3899                                         // We have an inlined function
3900                                     }
3901                                     else if (sc.function)
3902                                     {
3903                                         Type *type = sc.function->GetType();
3904 
3905                                         if (type)
3906                                         {
3907                                             clang::DeclContext* decl_ctx = GetClangDeclContextContainingTypeUID (type->GetID());
3908                                             if (decl_ctx->isRecord())
3909                                             {
3910                                                 if (name_type_mask & eFunctionNameTypeBase)
3911                                                 {
3912                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3913                                                     keep_die = false;
3914                                                 }
3915                                             }
3916                                             else
3917                                             {
3918                                                 if (name_type_mask & eFunctionNameTypeMethod)
3919                                                 {
3920                                                     sc_list.RemoveContextAtIndex(sc_list.GetSize()-1);
3921                                                     keep_die = false;
3922                                                 }
3923                                             }
3924                                         }
3925                                         else
3926                                         {
3927                                             GetObjectFile()->GetModule()->ReportWarning ("function at die offset 0x%8.8x had no function type",
3928                                                                                          die_offset);
3929                                         }
3930                                     }
3931                                 }
3932                             }
3933                             if (keep_die)
3934                                 resolved_dies.insert(die);
3935                         }
3936                     }
3937                     else
3938                     {
3939                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x for '%s')",
3940                                                                                    die_offset, name_cstr);
3941                     }
3942                 }
3943                 die_offsets.clear();
3944             }
3945         }
3946     }
3947     else
3948     {
3949 
3950         // Index the DWARF if we haven't already
3951         if (!m_indexed)
3952             Index ();
3953 
3954         if (name_type_mask & eFunctionNameTypeFull)
3955         {
3956             FindFunctions (name, m_function_fullname_index, include_inlines, sc_list);
3957 
3958             // FIXME Temporary workaround for global/anonymous namespace
3959             // functions on FreeBSD and Linux
3960 #if defined (__FreeBSD__) || defined (__linux__)
3961             // If we didn't find any functions in the global namespace try
3962             // looking in the basename index but ignore any returned
3963             // functions that have a namespace (ie. mangled names starting with
3964             // '_ZN') but keep functions which have an anonymous namespace
3965             if (sc_list.GetSize() == 0)
3966             {
3967                 SymbolContextList temp_sc_list;
3968                 FindFunctions (name, m_function_basename_index, include_inlines, temp_sc_list);
3969                 if (!namespace_decl)
3970                 {
3971                     SymbolContext sc;
3972                     for (uint32_t i = 0; i < temp_sc_list.GetSize(); i++)
3973                     {
3974                         if (temp_sc_list.GetContextAtIndex(i, sc))
3975                         {
3976                             ConstString mangled_name = sc.GetFunctionName(Mangled::ePreferMangled);
3977                             ConstString demangled_name = sc.GetFunctionName(Mangled::ePreferDemangled);
3978                             if (strncmp(mangled_name.GetCString(), "_ZN", 3) ||
3979                                 !strncmp(demangled_name.GetCString(), "(anonymous namespace)", 21))
3980                             {
3981                                 sc_list.Append(sc);
3982                             }
3983                         }
3984                     }
3985                 }
3986             }
3987 #endif
3988         }
3989         DIEArray die_offsets;
3990         DWARFCompileUnit *dwarf_cu = NULL;
3991 
3992         if (name_type_mask & eFunctionNameTypeBase)
3993         {
3994             uint32_t num_base = m_function_basename_index.Find(name, die_offsets);
3995             for (uint32_t i = 0; i < num_base; i++)
3996             {
3997                 const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
3998                 if (die)
3999                 {
4000                     if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
4001                         continue;
4002 
4003                     // If we get to here, the die is good, and we should add it:
4004                     if (resolved_dies.find(die) == resolved_dies.end())
4005                     {
4006                         if (ResolveFunction (dwarf_cu, die, include_inlines, sc_list))
4007                             resolved_dies.insert(die);
4008                     }
4009                 }
4010             }
4011             die_offsets.clear();
4012         }
4013 
4014         if (name_type_mask & eFunctionNameTypeMethod)
4015         {
4016             if (namespace_decl && *namespace_decl)
4017                 return 0; // no methods in namespaces
4018 
4019             uint32_t num_base = m_function_method_index.Find(name, die_offsets);
4020             {
4021                 for (uint32_t i = 0; i < num_base; i++)
4022                 {
4023                     const DWARFDebugInfoEntry* die = info->GetDIEPtrWithCompileUnitHint (die_offsets[i], &dwarf_cu);
4024                     if (die)
4025                     {
4026                         // If we get to here, the die is good, and we should add it:
4027                         if (resolved_dies.find(die) == resolved_dies.end())
4028                         {
4029                             if (ResolveFunction (dwarf_cu, die, include_inlines, sc_list))
4030                                 resolved_dies.insert(die);
4031                         }
4032                     }
4033                 }
4034             }
4035             die_offsets.clear();
4036         }
4037 
4038         if ((name_type_mask & eFunctionNameTypeSelector) && (!namespace_decl || !*namespace_decl))
4039         {
4040             FindFunctions (name, m_function_selector_index, include_inlines, sc_list);
4041         }
4042 
4043     }
4044 
4045     // Return the number of variable that were appended to the list
4046     const uint32_t num_matches = sc_list.GetSize() - original_size;
4047 
4048     if (log && num_matches > 0)
4049     {
4050         GetObjectFile()->GetModule()->LogMessage (log,
4051                                                   "SymbolFileDWARF::FindFunctions (name=\"%s\", name_type_mask=0x%x, include_inlines=%d, append=%u, sc_list) => %u",
4052                                                   name.GetCString(),
4053                                                   name_type_mask,
4054                                                   include_inlines,
4055                                                   append,
4056                                                   num_matches);
4057     }
4058     return num_matches;
4059 }
4060 
4061 uint32_t
4062 SymbolFileDWARF::FindFunctions(const RegularExpression& regex, bool include_inlines, bool append, SymbolContextList& sc_list)
4063 {
4064     Timer scoped_timer (__PRETTY_FUNCTION__,
4065                         "SymbolFileDWARF::FindFunctions (regex = '%s')",
4066                         regex.GetText());
4067 
4068     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
4069 
4070     if (log)
4071     {
4072         GetObjectFile()->GetModule()->LogMessage (log,
4073                                                   "SymbolFileDWARF::FindFunctions (regex=\"%s\", append=%u, sc_list)",
4074                                                   regex.GetText(),
4075                                                   append);
4076     }
4077 
4078 
4079     // If we aren't appending the results to this list, then clear the list
4080     if (!append)
4081         sc_list.Clear();
4082 
4083     // Remember how many sc_list are in the list before we search in case
4084     // we are appending the results to a variable list.
4085     uint32_t original_size = sc_list.GetSize();
4086 
4087     if (m_using_apple_tables)
4088     {
4089         if (m_apple_names_ap.get())
4090             FindFunctions (regex, *m_apple_names_ap, include_inlines, sc_list);
4091     }
4092     else
4093     {
4094         // Index the DWARF if we haven't already
4095         if (!m_indexed)
4096             Index ();
4097 
4098         FindFunctions (regex, m_function_basename_index, include_inlines, sc_list);
4099 
4100         FindFunctions (regex, m_function_fullname_index, include_inlines, sc_list);
4101     }
4102 
4103     // Return the number of variable that were appended to the list
4104     return sc_list.GetSize() - original_size;
4105 }
4106 
4107 uint32_t
4108 SymbolFileDWARF::FindTypes (const SymbolContext& sc,
4109                             const ConstString &name,
4110                             const lldb_private::ClangNamespaceDecl *namespace_decl,
4111                             bool append,
4112                             uint32_t max_matches,
4113                             TypeList& types)
4114 {
4115     DWARFDebugInfo* info = DebugInfo();
4116     if (info == NULL)
4117         return 0;
4118 
4119     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
4120 
4121     if (log)
4122     {
4123         if (namespace_decl)
4124             GetObjectFile()->GetModule()->LogMessage (log,
4125                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list)",
4126                                                       name.GetCString(),
4127                                                       static_cast<void*>(namespace_decl->GetNamespaceDecl()),
4128                                                       namespace_decl->GetQualifiedName().c_str(),
4129                                                       append, max_matches);
4130         else
4131             GetObjectFile()->GetModule()->LogMessage (log,
4132                                                       "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list)",
4133                                                       name.GetCString(), append,
4134                                                       max_matches);
4135     }
4136 
4137     // If we aren't appending the results to this list, then clear the list
4138     if (!append)
4139         types.Clear();
4140 
4141     if (!NamespaceDeclMatchesThisSymbolFile(namespace_decl))
4142         return 0;
4143 
4144     DIEArray die_offsets;
4145 
4146     if (m_using_apple_tables)
4147     {
4148         if (m_apple_types_ap.get())
4149         {
4150             const char *name_cstr = name.GetCString();
4151             m_apple_types_ap->FindByName (name_cstr, die_offsets);
4152         }
4153     }
4154     else
4155     {
4156         if (!m_indexed)
4157             Index ();
4158 
4159         m_type_index.Find (name, die_offsets);
4160     }
4161 
4162     const size_t num_die_matches = die_offsets.size();
4163 
4164     if (num_die_matches)
4165     {
4166         const uint32_t initial_types_size = types.GetSize();
4167         DWARFCompileUnit* dwarf_cu = NULL;
4168         const DWARFDebugInfoEntry* die = NULL;
4169         DWARFDebugInfo* debug_info = DebugInfo();
4170         for (size_t i=0; i<num_die_matches; ++i)
4171         {
4172             const dw_offset_t die_offset = die_offsets[i];
4173             die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
4174 
4175             if (die)
4176             {
4177                 if (namespace_decl && !DIEIsInNamespace (namespace_decl, dwarf_cu, die))
4178                     continue;
4179 
4180                 Type *matching_type = ResolveType (dwarf_cu, die);
4181                 if (matching_type)
4182                 {
4183                     // We found a type pointer, now find the shared pointer form our type list
4184                     types.InsertUnique (matching_type->shared_from_this());
4185                     if (types.GetSize() >= max_matches)
4186                         break;
4187                 }
4188             }
4189             else
4190             {
4191                 if (m_using_apple_tables)
4192                 {
4193                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
4194                                                                                die_offset, name.GetCString());
4195                 }
4196             }
4197 
4198         }
4199         const uint32_t num_matches = types.GetSize() - initial_types_size;
4200         if (log && num_matches)
4201         {
4202             if (namespace_decl)
4203             {
4204                 GetObjectFile()->GetModule()->LogMessage (log,
4205                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(%p) \"%s\", append=%u, max_matches=%u, type_list) => %u",
4206                                                           name.GetCString(),
4207                                                           static_cast<void*>(namespace_decl->GetNamespaceDecl()),
4208                                                           namespace_decl->GetQualifiedName().c_str(),
4209                                                           append, max_matches,
4210                                                           num_matches);
4211             }
4212             else
4213             {
4214                 GetObjectFile()->GetModule()->LogMessage (log,
4215                                                           "SymbolFileDWARF::FindTypes (sc, name=\"%s\", clang::NamespaceDecl(NULL), append=%u, max_matches=%u, type_list) => %u",
4216                                                           name.GetCString(),
4217                                                           append, max_matches,
4218                                                           num_matches);
4219             }
4220         }
4221         return num_matches;
4222     }
4223     return 0;
4224 }
4225 
4226 
4227 ClangNamespaceDecl
4228 SymbolFileDWARF::FindNamespace (const SymbolContext& sc,
4229                                 const ConstString &name,
4230                                 const lldb_private::ClangNamespaceDecl *parent_namespace_decl)
4231 {
4232     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_LOOKUPS));
4233 
4234     if (log)
4235     {
4236         GetObjectFile()->GetModule()->LogMessage (log,
4237                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\")",
4238                                                   name.GetCString());
4239     }
4240 
4241     if (!NamespaceDeclMatchesThisSymbolFile(parent_namespace_decl))
4242         return ClangNamespaceDecl();
4243 
4244     ClangNamespaceDecl namespace_decl;
4245     DWARFDebugInfo* info = DebugInfo();
4246     if (info)
4247     {
4248         DIEArray die_offsets;
4249 
4250         // Index if we already haven't to make sure the compile units
4251         // get indexed and make their global DIE index list
4252         if (m_using_apple_tables)
4253         {
4254             if (m_apple_namespaces_ap.get())
4255             {
4256                 const char *name_cstr = name.GetCString();
4257                 m_apple_namespaces_ap->FindByName (name_cstr, die_offsets);
4258             }
4259         }
4260         else
4261         {
4262             if (!m_indexed)
4263                 Index ();
4264 
4265             m_namespace_index.Find (name, die_offsets);
4266         }
4267 
4268         DWARFCompileUnit* dwarf_cu = NULL;
4269         const DWARFDebugInfoEntry* die = NULL;
4270         const size_t num_matches = die_offsets.size();
4271         if (num_matches)
4272         {
4273             DWARFDebugInfo* debug_info = DebugInfo();
4274             for (size_t i=0; i<num_matches; ++i)
4275             {
4276                 const dw_offset_t die_offset = die_offsets[i];
4277                 die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
4278 
4279                 if (die)
4280                 {
4281                     if (parent_namespace_decl && !DIEIsInNamespace (parent_namespace_decl, dwarf_cu, die))
4282                         continue;
4283 
4284                     clang::NamespaceDecl *clang_namespace_decl = ResolveNamespaceDIE (dwarf_cu, die);
4285                     if (clang_namespace_decl)
4286                     {
4287                         namespace_decl.SetASTContext (GetClangASTContext().getASTContext());
4288                         namespace_decl.SetNamespaceDecl (clang_namespace_decl);
4289                         break;
4290                     }
4291                 }
4292                 else
4293                 {
4294                     if (m_using_apple_tables)
4295                     {
4296                         GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_namespaces accelerator table had bad die 0x%8.8x for '%s')\n",
4297                                                                    die_offset, name.GetCString());
4298                     }
4299                 }
4300 
4301             }
4302         }
4303     }
4304     if (log && namespace_decl.GetNamespaceDecl())
4305     {
4306         GetObjectFile()->GetModule()->LogMessage (log,
4307                                                   "SymbolFileDWARF::FindNamespace (sc, name=\"%s\") => clang::NamespaceDecl(%p) \"%s\"",
4308                                                   name.GetCString(),
4309                                                   static_cast<const void*>(namespace_decl.GetNamespaceDecl()),
4310                                                   namespace_decl.GetQualifiedName().c_str());
4311     }
4312 
4313     return namespace_decl;
4314 }
4315 
4316 uint32_t
4317 SymbolFileDWARF::FindTypes(std::vector<dw_offset_t> die_offsets, uint32_t max_matches, TypeList& types)
4318 {
4319     // Remember how many sc_list are in the list before we search in case
4320     // we are appending the results to a variable list.
4321     uint32_t original_size = types.GetSize();
4322 
4323     const uint32_t num_die_offsets = die_offsets.size();
4324     // Parse all of the types we found from the pubtypes matches
4325     uint32_t i;
4326     uint32_t num_matches = 0;
4327     for (i = 0; i < num_die_offsets; ++i)
4328     {
4329         Type *matching_type = ResolveTypeUID (die_offsets[i]);
4330         if (matching_type)
4331         {
4332             // We found a type pointer, now find the shared pointer form our type list
4333             types.InsertUnique (matching_type->shared_from_this());
4334             ++num_matches;
4335             if (num_matches >= max_matches)
4336                 break;
4337         }
4338     }
4339 
4340     // Return the number of variable that were appended to the list
4341     return types.GetSize() - original_size;
4342 }
4343 
4344 
4345 size_t
4346 SymbolFileDWARF::ParseChildParameters (const SymbolContext& sc,
4347                                        clang::DeclContext *containing_decl_ctx,
4348                                        DWARFCompileUnit* dwarf_cu,
4349                                        const DWARFDebugInfoEntry *parent_die,
4350                                        bool skip_artificial,
4351                                        bool &is_static,
4352                                        bool &is_variadic,
4353                                        std::vector<ClangASTType>& function_param_types,
4354                                        std::vector<clang::ParmVarDecl*>& function_param_decls,
4355                                        unsigned &type_quals) // ,
4356                                        // ClangASTContext::TemplateParameterInfos &template_param_infos))
4357 {
4358     if (parent_die == NULL)
4359         return 0;
4360 
4361     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize(), dwarf_cu->IsDWARF64());
4362 
4363     size_t arg_idx = 0;
4364     const DWARFDebugInfoEntry *die;
4365     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4366     {
4367         dw_tag_t tag = die->Tag();
4368         switch (tag)
4369         {
4370         case DW_TAG_formal_parameter:
4371             {
4372                 DWARFDebugInfoEntry::Attributes attributes;
4373                 const size_t num_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4374                 if (num_attributes > 0)
4375                 {
4376                     const char *name = NULL;
4377                     Declaration decl;
4378                     dw_offset_t param_type_die_offset = DW_INVALID_OFFSET;
4379                     bool is_artificial = false;
4380                     // one of None, Auto, Register, Extern, Static, PrivateExtern
4381 
4382                     clang::StorageClass storage = clang::SC_None;
4383                     uint32_t i;
4384                     for (i=0; i<num_attributes; ++i)
4385                     {
4386                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4387                         DWARFFormValue form_value;
4388                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4389                         {
4390                             switch (attr)
4391                             {
4392                             case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4393                             case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4394                             case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4395                             case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
4396                             case DW_AT_type:        param_type_die_offset = form_value.Reference(); break;
4397                             case DW_AT_artificial:  is_artificial = form_value.Boolean(); break;
4398                             case DW_AT_location:
4399     //                          if (form_value.BlockData())
4400     //                          {
4401     //                              const DWARFDataExtractor& debug_info_data = debug_info();
4402     //                              uint32_t block_length = form_value.Unsigned();
4403     //                              DWARFDataExtractor location(debug_info_data, form_value.BlockData() - debug_info_data.GetDataStart(), block_length);
4404     //                          }
4405     //                          else
4406     //                          {
4407     //                          }
4408     //                          break;
4409                             case DW_AT_const_value:
4410                             case DW_AT_default_value:
4411                             case DW_AT_description:
4412                             case DW_AT_endianity:
4413                             case DW_AT_is_optional:
4414                             case DW_AT_segment:
4415                             case DW_AT_variable_parameter:
4416                             default:
4417                             case DW_AT_abstract_origin:
4418                             case DW_AT_sibling:
4419                                 break;
4420                             }
4421                         }
4422                     }
4423 
4424                     bool skip = false;
4425                     if (skip_artificial)
4426                     {
4427                         if (is_artificial)
4428                         {
4429                             // In order to determine if a C++ member function is
4430                             // "const" we have to look at the const-ness of "this"...
4431                             // Ugly, but that
4432                             if (arg_idx == 0)
4433                             {
4434                                 if (DeclKindIsCXXClass(containing_decl_ctx->getDeclKind()))
4435                                 {
4436                                     // Often times compilers omit the "this" name for the
4437                                     // specification DIEs, so we can't rely upon the name
4438                                     // being in the formal parameter DIE...
4439                                     if (name == NULL || ::strcmp(name, "this")==0)
4440                                     {
4441                                         Type *this_type = ResolveTypeUID (param_type_die_offset);
4442                                         if (this_type)
4443                                         {
4444                                             uint32_t encoding_mask = this_type->GetEncodingMask();
4445                                             if (encoding_mask & Type::eEncodingIsPointerUID)
4446                                             {
4447                                                 is_static = false;
4448 
4449                                                 if (encoding_mask & (1u << Type::eEncodingIsConstUID))
4450                                                     type_quals |= clang::Qualifiers::Const;
4451                                                 if (encoding_mask & (1u << Type::eEncodingIsVolatileUID))
4452                                                     type_quals |= clang::Qualifiers::Volatile;
4453                                             }
4454                                         }
4455                                     }
4456                                 }
4457                             }
4458                             skip = true;
4459                         }
4460                         else
4461                         {
4462 
4463                             // HACK: Objective C formal parameters "self" and "_cmd"
4464                             // are not marked as artificial in the DWARF...
4465                             CompileUnit *comp_unit = GetCompUnitForDWARFCompUnit(dwarf_cu, UINT32_MAX);
4466                             if (comp_unit)
4467                             {
4468                                 switch (comp_unit->GetLanguage())
4469                                 {
4470                                     case eLanguageTypeObjC:
4471                                     case eLanguageTypeObjC_plus_plus:
4472                                         if (name && name[0] && (strcmp (name, "self") == 0 || strcmp (name, "_cmd") == 0))
4473                                             skip = true;
4474                                         break;
4475                                     default:
4476                                         break;
4477                                 }
4478                             }
4479                         }
4480                     }
4481 
4482                     if (!skip)
4483                     {
4484                         Type *type = ResolveTypeUID(param_type_die_offset);
4485                         if (type)
4486                         {
4487                             function_param_types.push_back (type->GetClangForwardType());
4488 
4489                             clang::ParmVarDecl *param_var_decl = GetClangASTContext().CreateParameterDeclaration (name,
4490                                                                                                                   type->GetClangForwardType(),
4491                                                                                                                   storage);
4492                             assert(param_var_decl);
4493                             function_param_decls.push_back(param_var_decl);
4494 
4495                             GetClangASTContext().SetMetadataAsUserID (param_var_decl, MakeUserID(die->GetOffset()));
4496                         }
4497                     }
4498                 }
4499                 arg_idx++;
4500             }
4501             break;
4502 
4503         case DW_TAG_unspecified_parameters:
4504             is_variadic = true;
4505             break;
4506 
4507         case DW_TAG_template_type_parameter:
4508         case DW_TAG_template_value_parameter:
4509             // The one caller of this was never using the template_param_infos,
4510             // and the local variable was taking up a large amount of stack space
4511             // in SymbolFileDWARF::ParseType() so this was removed. If we ever need
4512             // the template params back, we can add them back.
4513             // ParseTemplateDIE (dwarf_cu, die, template_param_infos);
4514             break;
4515 
4516         default:
4517             break;
4518         }
4519     }
4520     return arg_idx;
4521 }
4522 
4523 size_t
4524 SymbolFileDWARF::ParseChildEnumerators
4525 (
4526     const SymbolContext& sc,
4527     lldb_private::ClangASTType &clang_type,
4528     bool is_signed,
4529     uint32_t enumerator_byte_size,
4530     DWARFCompileUnit* dwarf_cu,
4531     const DWARFDebugInfoEntry *parent_die
4532 )
4533 {
4534     if (parent_die == NULL)
4535         return 0;
4536 
4537     size_t enumerators_added = 0;
4538     const DWARFDebugInfoEntry *die;
4539     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize(), dwarf_cu->IsDWARF64());
4540 
4541     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4542     {
4543         const dw_tag_t tag = die->Tag();
4544         if (tag == DW_TAG_enumerator)
4545         {
4546             DWARFDebugInfoEntry::Attributes attributes;
4547             const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4548             if (num_child_attributes > 0)
4549             {
4550                 const char *name = NULL;
4551                 bool got_value = false;
4552                 int64_t enum_value = 0;
4553                 Declaration decl;
4554 
4555                 uint32_t i;
4556                 for (i=0; i<num_child_attributes; ++i)
4557                 {
4558                     const dw_attr_t attr = attributes.AttributeAtIndex(i);
4559                     DWARFFormValue form_value;
4560                     if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4561                     {
4562                         switch (attr)
4563                         {
4564                         case DW_AT_const_value:
4565                             got_value = true;
4566                             if (is_signed)
4567                                 enum_value = form_value.Signed();
4568                             else
4569                                 enum_value = form_value.Unsigned();
4570                             break;
4571 
4572                         case DW_AT_name:
4573                             name = form_value.AsCString(&get_debug_str_data());
4574                             break;
4575 
4576                         case DW_AT_description:
4577                         default:
4578                         case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
4579                         case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
4580                         case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
4581                         case DW_AT_sibling:
4582                             break;
4583                         }
4584                     }
4585                 }
4586 
4587                 if (name && name[0] && got_value)
4588                 {
4589                     clang_type.AddEnumerationValueToEnumerationType (clang_type.GetEnumerationIntegerType(),
4590                                                                      decl,
4591                                                                      name,
4592                                                                      enum_value,
4593                                                                      enumerator_byte_size * 8);
4594                     ++enumerators_added;
4595                 }
4596             }
4597         }
4598     }
4599     return enumerators_added;
4600 }
4601 
4602 void
4603 SymbolFileDWARF::ParseChildArrayInfo
4604 (
4605     const SymbolContext& sc,
4606     DWARFCompileUnit* dwarf_cu,
4607     const DWARFDebugInfoEntry *parent_die,
4608     int64_t& first_index,
4609     std::vector<uint64_t>& element_orders,
4610     uint32_t& byte_stride,
4611     uint32_t& bit_stride
4612 )
4613 {
4614     if (parent_die == NULL)
4615         return;
4616 
4617     const DWARFDebugInfoEntry *die;
4618     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (dwarf_cu->GetAddressByteSize(), dwarf_cu->IsDWARF64());
4619     for (die = parent_die->GetFirstChild(); die != NULL; die = die->GetSibling())
4620     {
4621         const dw_tag_t tag = die->Tag();
4622         switch (tag)
4623         {
4624         case DW_TAG_subrange_type:
4625             {
4626                 DWARFDebugInfoEntry::Attributes attributes;
4627                 const size_t num_child_attributes = die->GetAttributes(this, dwarf_cu, fixed_form_sizes, attributes);
4628                 if (num_child_attributes > 0)
4629                 {
4630                     uint64_t num_elements = 0;
4631                     uint64_t lower_bound = 0;
4632                     uint64_t upper_bound = 0;
4633                     bool upper_bound_valid = false;
4634                     uint32_t i;
4635                     for (i=0; i<num_child_attributes; ++i)
4636                     {
4637                         const dw_attr_t attr = attributes.AttributeAtIndex(i);
4638                         DWARFFormValue form_value;
4639                         if (attributes.ExtractFormValueAtIndex(this, i, form_value))
4640                         {
4641                             switch (attr)
4642                             {
4643                             case DW_AT_name:
4644                                 break;
4645 
4646                             case DW_AT_count:
4647                                 num_elements = form_value.Unsigned();
4648                                 break;
4649 
4650                             case DW_AT_bit_stride:
4651                                 bit_stride = form_value.Unsigned();
4652                                 break;
4653 
4654                             case DW_AT_byte_stride:
4655                                 byte_stride = form_value.Unsigned();
4656                                 break;
4657 
4658                             case DW_AT_lower_bound:
4659                                 lower_bound = form_value.Unsigned();
4660                                 break;
4661 
4662                             case DW_AT_upper_bound:
4663                                 upper_bound_valid = true;
4664                                 upper_bound = form_value.Unsigned();
4665                                 break;
4666 
4667                             default:
4668                             case DW_AT_abstract_origin:
4669                             case DW_AT_accessibility:
4670                             case DW_AT_allocated:
4671                             case DW_AT_associated:
4672                             case DW_AT_data_location:
4673                             case DW_AT_declaration:
4674                             case DW_AT_description:
4675                             case DW_AT_sibling:
4676                             case DW_AT_threads_scaled:
4677                             case DW_AT_type:
4678                             case DW_AT_visibility:
4679                                 break;
4680                             }
4681                         }
4682                     }
4683 
4684                     if (num_elements == 0)
4685                     {
4686                         if (upper_bound_valid && upper_bound >= lower_bound)
4687                             num_elements = upper_bound - lower_bound + 1;
4688                     }
4689 
4690                     element_orders.push_back (num_elements);
4691                 }
4692             }
4693             break;
4694         }
4695     }
4696 }
4697 
4698 TypeSP
4699 SymbolFileDWARF::GetTypeForDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry* die)
4700 {
4701     TypeSP type_sp;
4702     if (die != NULL)
4703     {
4704         assert(dwarf_cu != NULL);
4705         Type *type_ptr = m_die_to_type.lookup (die);
4706         if (type_ptr == NULL)
4707         {
4708             CompileUnit* lldb_cu = GetCompUnitForDWARFCompUnit(dwarf_cu);
4709             assert (lldb_cu);
4710             SymbolContext sc(lldb_cu);
4711             type_sp = ParseType(sc, dwarf_cu, die, NULL);
4712         }
4713         else if (type_ptr != DIE_IS_BEING_PARSED)
4714         {
4715             // Grab the existing type from the master types lists
4716             type_sp = type_ptr->shared_from_this();
4717         }
4718 
4719     }
4720     return type_sp;
4721 }
4722 
4723 clang::DeclContext *
4724 SymbolFileDWARF::GetClangDeclContextContainingDIEOffset (dw_offset_t die_offset)
4725 {
4726     if (die_offset != DW_INVALID_OFFSET)
4727     {
4728         DWARFCompileUnitSP cu_sp;
4729         const DWARFDebugInfoEntry* die = DebugInfo()->GetDIEPtr(die_offset, &cu_sp);
4730         return GetClangDeclContextContainingDIE (cu_sp.get(), die, NULL);
4731     }
4732     return NULL;
4733 }
4734 
4735 clang::DeclContext *
4736 SymbolFileDWARF::GetClangDeclContextForDIEOffset (const SymbolContext &sc, dw_offset_t die_offset)
4737 {
4738     if (die_offset != DW_INVALID_OFFSET)
4739     {
4740         DWARFDebugInfo* debug_info = DebugInfo();
4741         if (debug_info)
4742         {
4743             DWARFCompileUnitSP cu_sp;
4744             const DWARFDebugInfoEntry* die = debug_info->GetDIEPtr(die_offset, &cu_sp);
4745             if (die)
4746                 return GetClangDeclContextForDIE (sc, cu_sp.get(), die);
4747         }
4748     }
4749     return NULL;
4750 }
4751 
4752 clang::NamespaceDecl *
4753 SymbolFileDWARF::ResolveNamespaceDIE (DWARFCompileUnit *dwarf_cu, const DWARFDebugInfoEntry *die)
4754 {
4755     if (die && die->Tag() == DW_TAG_namespace)
4756     {
4757         // See if we already parsed this namespace DIE and associated it with a
4758         // uniqued namespace declaration
4759         clang::NamespaceDecl *namespace_decl = static_cast<clang::NamespaceDecl *>(m_die_to_decl_ctx[die]);
4760         if (namespace_decl)
4761             return namespace_decl;
4762         else
4763         {
4764             const char *namespace_name = die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL);
4765             clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, NULL);
4766             namespace_decl = GetClangASTContext().GetUniqueNamespaceDeclaration (namespace_name, containing_decl_ctx);
4767             Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4768             if (log)
4769             {
4770                 if (namespace_name)
4771                 {
4772                     GetObjectFile()->GetModule()->LogMessage (log,
4773                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace with DW_AT_name(\"%s\") => clang::NamespaceDecl *%p (original = %p)",
4774                                                               static_cast<void*>(GetClangASTContext().getASTContext()),
4775                                                               MakeUserID(die->GetOffset()),
4776                                                               namespace_name,
4777                                                               static_cast<void*>(namespace_decl),
4778                                                               static_cast<void*>(namespace_decl->getOriginalNamespace()));
4779                 }
4780                 else
4781                 {
4782                     GetObjectFile()->GetModule()->LogMessage (log,
4783                                                               "ASTContext => %p: 0x%8.8" PRIx64 ": DW_TAG_namespace (anonymous) => clang::NamespaceDecl *%p (original = %p)",
4784                                                               static_cast<void*>(GetClangASTContext().getASTContext()),
4785                                                               MakeUserID(die->GetOffset()),
4786                                                               static_cast<void*>(namespace_decl),
4787                                                               static_cast<void*>(namespace_decl->getOriginalNamespace()));
4788                 }
4789             }
4790 
4791             if (namespace_decl)
4792                 LinkDeclContextToDIE((clang::DeclContext*)namespace_decl, die);
4793             return namespace_decl;
4794         }
4795     }
4796     return NULL;
4797 }
4798 
4799 clang::DeclContext *
4800 SymbolFileDWARF::GetClangDeclContextForDIE (const SymbolContext &sc, DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4801 {
4802     clang::DeclContext *clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4803     if (clang_decl_ctx)
4804         return clang_decl_ctx;
4805     // If this DIE has a specification, or an abstract origin, then trace to those.
4806 
4807     dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4808     if (die_offset != DW_INVALID_OFFSET)
4809         return GetClangDeclContextForDIEOffset (sc, die_offset);
4810 
4811     die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4812     if (die_offset != DW_INVALID_OFFSET)
4813         return GetClangDeclContextForDIEOffset (sc, die_offset);
4814 
4815     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
4816     if (log)
4817         GetObjectFile()->GetModule()->LogMessage(log, "SymbolFileDWARF::GetClangDeclContextForDIE (die = 0x%8.8x) %s '%s'", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), die->GetName(this, cu));
4818     // This is the DIE we want.  Parse it, then query our map.
4819     bool assert_not_being_parsed = true;
4820     ResolveTypeUID (cu, die, assert_not_being_parsed);
4821 
4822     clang_decl_ctx = GetCachedClangDeclContextForDIE (die);
4823 
4824     return clang_decl_ctx;
4825 }
4826 
4827 clang::DeclContext *
4828 SymbolFileDWARF::GetClangDeclContextContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die, const DWARFDebugInfoEntry **decl_ctx_die_copy)
4829 {
4830     if (m_clang_tu_decl == NULL)
4831         m_clang_tu_decl = GetClangASTContext().getASTContext()->getTranslationUnitDecl();
4832 
4833     const DWARFDebugInfoEntry *decl_ctx_die = GetDeclContextDIEContainingDIE (cu, die);
4834 
4835     if (decl_ctx_die_copy)
4836         *decl_ctx_die_copy = decl_ctx_die;
4837 
4838     if (decl_ctx_die)
4839     {
4840 
4841         DIEToDeclContextMap::iterator pos = m_die_to_decl_ctx.find (decl_ctx_die);
4842         if (pos != m_die_to_decl_ctx.end())
4843             return pos->second;
4844 
4845         switch (decl_ctx_die->Tag())
4846         {
4847         case DW_TAG_compile_unit:
4848             return m_clang_tu_decl;
4849 
4850         case DW_TAG_namespace:
4851             return ResolveNamespaceDIE (cu, decl_ctx_die);
4852             break;
4853 
4854         case DW_TAG_structure_type:
4855         case DW_TAG_union_type:
4856         case DW_TAG_class_type:
4857             {
4858                 Type* type = ResolveType (cu, decl_ctx_die);
4859                 if (type)
4860                 {
4861                     clang::DeclContext *decl_ctx = type->GetClangForwardType().GetDeclContextForType ();
4862                     if (decl_ctx)
4863                     {
4864                         LinkDeclContextToDIE (decl_ctx, decl_ctx_die);
4865                         if (decl_ctx)
4866                             return decl_ctx;
4867                     }
4868                 }
4869             }
4870             break;
4871 
4872         default:
4873             break;
4874         }
4875     }
4876     return m_clang_tu_decl;
4877 }
4878 
4879 
4880 const DWARFDebugInfoEntry *
4881 SymbolFileDWARF::GetDeclContextDIEContainingDIE (DWARFCompileUnit *cu, const DWARFDebugInfoEntry *die)
4882 {
4883     if (cu && die)
4884     {
4885         const DWARFDebugInfoEntry * const decl_die = die;
4886 
4887         while (die != NULL)
4888         {
4889             // If this is the original DIE that we are searching for a declaration
4890             // for, then don't look in the cache as we don't want our own decl
4891             // context to be our decl context...
4892             if (decl_die != die)
4893             {
4894                 switch (die->Tag())
4895                 {
4896                     case DW_TAG_compile_unit:
4897                     case DW_TAG_namespace:
4898                     case DW_TAG_structure_type:
4899                     case DW_TAG_union_type:
4900                     case DW_TAG_class_type:
4901                         return die;
4902 
4903                     default:
4904                         break;
4905                 }
4906             }
4907 
4908             dw_offset_t die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_specification, DW_INVALID_OFFSET);
4909             if (die_offset != DW_INVALID_OFFSET)
4910             {
4911                 DWARFCompileUnit *spec_cu = cu;
4912                 const DWARFDebugInfoEntry *spec_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &spec_cu);
4913                 const DWARFDebugInfoEntry *spec_die_decl_ctx_die = GetDeclContextDIEContainingDIE (spec_cu, spec_die);
4914                 if (spec_die_decl_ctx_die)
4915                     return spec_die_decl_ctx_die;
4916             }
4917 
4918             die_offset = die->GetAttributeValueAsReference(this, cu, DW_AT_abstract_origin, DW_INVALID_OFFSET);
4919             if (die_offset != DW_INVALID_OFFSET)
4920             {
4921                 DWARFCompileUnit *abs_cu = cu;
4922                 const DWARFDebugInfoEntry *abs_die = DebugInfo()->GetDIEPtrWithCompileUnitHint (die_offset, &abs_cu);
4923                 const DWARFDebugInfoEntry *abs_die_decl_ctx_die = GetDeclContextDIEContainingDIE (abs_cu, abs_die);
4924                 if (abs_die_decl_ctx_die)
4925                     return abs_die_decl_ctx_die;
4926             }
4927 
4928             die = die->GetParent();
4929         }
4930     }
4931     return NULL;
4932 }
4933 
4934 
4935 Symbol *
4936 SymbolFileDWARF::GetObjCClassSymbol (const ConstString &objc_class_name)
4937 {
4938     Symbol *objc_class_symbol = NULL;
4939     if (m_obj_file)
4940     {
4941         Symtab *symtab = m_obj_file->GetSymtab ();
4942         if (symtab)
4943         {
4944             objc_class_symbol = symtab->FindFirstSymbolWithNameAndType (objc_class_name,
4945                                                                         eSymbolTypeObjCClass,
4946                                                                         Symtab::eDebugNo,
4947                                                                         Symtab::eVisibilityAny);
4948         }
4949     }
4950     return objc_class_symbol;
4951 }
4952 
4953 // Some compilers don't emit the DW_AT_APPLE_objc_complete_type attribute. If they don't
4954 // then we can end up looking through all class types for a complete type and never find
4955 // the full definition. We need to know if this attribute is supported, so we determine
4956 // this here and cache th result. We also need to worry about the debug map DWARF file
4957 // if we are doing darwin DWARF in .o file debugging.
4958 bool
4959 SymbolFileDWARF::Supports_DW_AT_APPLE_objc_complete_type (DWARFCompileUnit *cu)
4960 {
4961     if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolCalculate)
4962     {
4963         m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolNo;
4964         if (cu && cu->Supports_DW_AT_APPLE_objc_complete_type())
4965             m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4966         else
4967         {
4968             DWARFDebugInfo* debug_info = DebugInfo();
4969             const uint32_t num_compile_units = GetNumCompileUnits();
4970             for (uint32_t cu_idx = 0; cu_idx < num_compile_units; ++cu_idx)
4971             {
4972                 DWARFCompileUnit* dwarf_cu = debug_info->GetCompileUnitAtIndex(cu_idx);
4973                 if (dwarf_cu != cu && dwarf_cu->Supports_DW_AT_APPLE_objc_complete_type())
4974                 {
4975                     m_supports_DW_AT_APPLE_objc_complete_type = eLazyBoolYes;
4976                     break;
4977                 }
4978             }
4979         }
4980         if (m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolNo && GetDebugMapSymfile ())
4981             return m_debug_map_symfile->Supports_DW_AT_APPLE_objc_complete_type (this);
4982     }
4983     return m_supports_DW_AT_APPLE_objc_complete_type == eLazyBoolYes;
4984 }
4985 
4986 // This function can be used when a DIE is found that is a forward declaration
4987 // DIE and we want to try and find a type that has the complete definition.
4988 TypeSP
4989 SymbolFileDWARF::FindCompleteObjCDefinitionTypeForDIE (const DWARFDebugInfoEntry *die,
4990                                                        const ConstString &type_name,
4991                                                        bool must_be_implementation)
4992 {
4993 
4994     TypeSP type_sp;
4995 
4996     if (!type_name || (must_be_implementation && !GetObjCClassSymbol (type_name)))
4997         return type_sp;
4998 
4999     DIEArray die_offsets;
5000 
5001     if (m_using_apple_tables)
5002     {
5003         if (m_apple_types_ap.get())
5004         {
5005             const char *name_cstr = type_name.GetCString();
5006             m_apple_types_ap->FindCompleteObjCClassByName (name_cstr, die_offsets, must_be_implementation);
5007         }
5008     }
5009     else
5010     {
5011         if (!m_indexed)
5012             Index ();
5013 
5014         m_type_index.Find (type_name, die_offsets);
5015     }
5016 
5017     const size_t num_matches = die_offsets.size();
5018 
5019     DWARFCompileUnit* type_cu = NULL;
5020     const DWARFDebugInfoEntry* type_die = NULL;
5021     if (num_matches)
5022     {
5023         DWARFDebugInfo* debug_info = DebugInfo();
5024         for (size_t i=0; i<num_matches; ++i)
5025         {
5026             const dw_offset_t die_offset = die_offsets[i];
5027             type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5028 
5029             if (type_die)
5030             {
5031                 bool try_resolving_type = false;
5032 
5033                 // Don't try and resolve the DIE we are looking for with the DIE itself!
5034                 if (type_die != die)
5035                 {
5036                     switch (type_die->Tag())
5037                     {
5038                         case DW_TAG_class_type:
5039                         case DW_TAG_structure_type:
5040                             try_resolving_type = true;
5041                             break;
5042                         default:
5043                             break;
5044                     }
5045                 }
5046 
5047                 if (try_resolving_type)
5048                 {
5049                     if (must_be_implementation && type_cu->Supports_DW_AT_APPLE_objc_complete_type())
5050                         try_resolving_type = type_die->GetAttributeValueAsUnsigned (this, type_cu, DW_AT_APPLE_objc_complete_type, 0);
5051 
5052                     if (try_resolving_type)
5053                     {
5054                         Type *resolved_type = ResolveType (type_cu, type_die, false);
5055                         if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5056                         {
5057                             DEBUG_PRINTF ("resolved 0x%8.8" PRIx64 " from %s to 0x%8.8" PRIx64 " (cu 0x%8.8" PRIx64 ")\n",
5058                                           MakeUserID(die->GetOffset()),
5059                                           m_obj_file->GetFileSpec().GetFilename().AsCString("<Unknown>"),
5060                                           MakeUserID(type_die->GetOffset()),
5061                                           MakeUserID(type_cu->GetOffset()));
5062 
5063                             if (die)
5064                                 m_die_to_type[die] = resolved_type;
5065                             type_sp = resolved_type->shared_from_this();
5066                             break;
5067                         }
5068                     }
5069                 }
5070             }
5071             else
5072             {
5073                 if (m_using_apple_tables)
5074                 {
5075                     GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5076                                                                die_offset, type_name.GetCString());
5077                 }
5078             }
5079 
5080         }
5081     }
5082     return type_sp;
5083 }
5084 
5085 
5086 //----------------------------------------------------------------------
5087 // This function helps to ensure that the declaration contexts match for
5088 // two different DIEs. Often times debug information will refer to a
5089 // forward declaration of a type (the equivalent of "struct my_struct;".
5090 // There will often be a declaration of that type elsewhere that has the
5091 // full definition. When we go looking for the full type "my_struct", we
5092 // will find one or more matches in the accelerator tables and we will
5093 // then need to make sure the type was in the same declaration context
5094 // as the original DIE. This function can efficiently compare two DIEs
5095 // and will return true when the declaration context matches, and false
5096 // when they don't.
5097 //----------------------------------------------------------------------
5098 bool
5099 SymbolFileDWARF::DIEDeclContextsMatch (DWARFCompileUnit* cu1, const DWARFDebugInfoEntry *die1,
5100                                        DWARFCompileUnit* cu2, const DWARFDebugInfoEntry *die2)
5101 {
5102     if (die1 == die2)
5103         return true;
5104 
5105 #if defined (LLDB_CONFIGURATION_DEBUG)
5106     // You can't and shouldn't call this function with a compile unit from
5107     // two different SymbolFileDWARF instances.
5108     assert (DebugInfo()->ContainsCompileUnit (cu1));
5109     assert (DebugInfo()->ContainsCompileUnit (cu2));
5110 #endif
5111 
5112     DWARFDIECollection decl_ctx_1;
5113     DWARFDIECollection decl_ctx_2;
5114     //The declaration DIE stack is a stack of the declaration context
5115     // DIEs all the way back to the compile unit. If a type "T" is
5116     // declared inside a class "B", and class "B" is declared inside
5117     // a class "A" and class "A" is in a namespace "lldb", and the
5118     // namespace is in a compile unit, there will be a stack of DIEs:
5119     //
5120     //   [0] DW_TAG_class_type for "B"
5121     //   [1] DW_TAG_class_type for "A"
5122     //   [2] DW_TAG_namespace  for "lldb"
5123     //   [3] DW_TAG_compile_unit for the source file.
5124     //
5125     // We grab both contexts and make sure that everything matches
5126     // all the way back to the compiler unit.
5127 
5128     // First lets grab the decl contexts for both DIEs
5129     die1->GetDeclContextDIEs (this, cu1, decl_ctx_1);
5130     die2->GetDeclContextDIEs (this, cu2, decl_ctx_2);
5131     // Make sure the context arrays have the same size, otherwise
5132     // we are done
5133     const size_t count1 = decl_ctx_1.Size();
5134     const size_t count2 = decl_ctx_2.Size();
5135     if (count1 != count2)
5136         return false;
5137 
5138     // Make sure the DW_TAG values match all the way back up the
5139     // compile unit. If they don't, then we are done.
5140     const DWARFDebugInfoEntry *decl_ctx_die1;
5141     const DWARFDebugInfoEntry *decl_ctx_die2;
5142     size_t i;
5143     for (i=0; i<count1; i++)
5144     {
5145         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
5146         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
5147         if (decl_ctx_die1->Tag() != decl_ctx_die2->Tag())
5148             return false;
5149     }
5150 #if defined LLDB_CONFIGURATION_DEBUG
5151 
5152     // Make sure the top item in the decl context die array is always
5153     // DW_TAG_compile_unit. If it isn't then something went wrong in
5154     // the DWARFDebugInfoEntry::GetDeclContextDIEs() function...
5155     assert (decl_ctx_1.GetDIEPtrAtIndex (count1 - 1)->Tag() == DW_TAG_compile_unit);
5156 
5157 #endif
5158     // Always skip the compile unit when comparing by only iterating up to
5159     // "count - 1". Here we compare the names as we go.
5160     for (i=0; i<count1 - 1; i++)
5161     {
5162         decl_ctx_die1 = decl_ctx_1.GetDIEPtrAtIndex (i);
5163         decl_ctx_die2 = decl_ctx_2.GetDIEPtrAtIndex (i);
5164         const char *name1 = decl_ctx_die1->GetName(this, cu1);
5165         const char *name2 = decl_ctx_die2->GetName(this, cu2);
5166         // If the string was from a DW_FORM_strp, then the pointer will often
5167         // be the same!
5168         if (name1 == name2)
5169             continue;
5170 
5171         // Name pointers are not equal, so only compare the strings
5172         // if both are not NULL.
5173         if (name1 && name2)
5174         {
5175             // If the strings don't compare, we are done...
5176             if (strcmp(name1, name2) != 0)
5177                 return false;
5178         }
5179         else
5180         {
5181             // One name was NULL while the other wasn't
5182             return false;
5183         }
5184     }
5185     // We made it through all of the checks and the declaration contexts
5186     // are equal.
5187     return true;
5188 }
5189 
5190 
5191 TypeSP
5192 SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext (const DWARFDeclContext &dwarf_decl_ctx)
5193 {
5194     TypeSP type_sp;
5195 
5196     const uint32_t dwarf_decl_ctx_count = dwarf_decl_ctx.GetSize();
5197     if (dwarf_decl_ctx_count > 0)
5198     {
5199         const ConstString type_name(dwarf_decl_ctx[0].name);
5200         const dw_tag_t tag = dwarf_decl_ctx[0].tag;
5201 
5202         if (type_name)
5203         {
5204             Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_TYPE_COMPLETION|DWARF_LOG_LOOKUPS));
5205             if (log)
5206             {
5207                 GetObjectFile()->GetModule()->LogMessage (log,
5208                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s')",
5209                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5210                                                           dwarf_decl_ctx.GetQualifiedName());
5211             }
5212 
5213             DIEArray die_offsets;
5214 
5215             if (m_using_apple_tables)
5216             {
5217                 if (m_apple_types_ap.get())
5218                 {
5219                     const bool has_tag = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeTag);
5220                     const bool has_qualified_name_hash = m_apple_types_ap->GetHeader().header_data.ContainsAtom (DWARFMappedHash::eAtomTypeQualNameHash);
5221                     if (has_tag && has_qualified_name_hash)
5222                     {
5223                         const char *qualified_name = dwarf_decl_ctx.GetQualifiedName();
5224                         const uint32_t qualified_name_hash = MappedHash::HashStringUsingDJB (qualified_name);
5225                         if (log)
5226                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTagAndQualifiedNameHash()");
5227                         m_apple_types_ap->FindByNameAndTagAndQualifiedNameHash (type_name.GetCString(), tag, qualified_name_hash, die_offsets);
5228                     }
5229                     else if (has_tag)
5230                     {
5231                         if (log)
5232                             GetObjectFile()->GetModule()->LogMessage (log,"FindByNameAndTag()");
5233                         m_apple_types_ap->FindByNameAndTag (type_name.GetCString(), tag, die_offsets);
5234                     }
5235                     else
5236                     {
5237                         m_apple_types_ap->FindByName (type_name.GetCString(), die_offsets);
5238                     }
5239                 }
5240             }
5241             else
5242             {
5243                 if (!m_indexed)
5244                     Index ();
5245 
5246                 m_type_index.Find (type_name, die_offsets);
5247             }
5248 
5249             const size_t num_matches = die_offsets.size();
5250 
5251 
5252             DWARFCompileUnit* type_cu = NULL;
5253             const DWARFDebugInfoEntry* type_die = NULL;
5254             if (num_matches)
5255             {
5256                 DWARFDebugInfo* debug_info = DebugInfo();
5257                 for (size_t i=0; i<num_matches; ++i)
5258                 {
5259                     const dw_offset_t die_offset = die_offsets[i];
5260                     type_die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &type_cu);
5261 
5262                     if (type_die)
5263                     {
5264                         bool try_resolving_type = false;
5265 
5266                         // Don't try and resolve the DIE we are looking for with the DIE itself!
5267                         const dw_tag_t type_tag = type_die->Tag();
5268                         // Make sure the tags match
5269                         if (type_tag == tag)
5270                         {
5271                             // The tags match, lets try resolving this type
5272                             try_resolving_type = true;
5273                         }
5274                         else
5275                         {
5276                             // The tags don't match, but we need to watch our for a
5277                             // forward declaration for a struct and ("struct foo")
5278                             // ends up being a class ("class foo { ... };") or
5279                             // vice versa.
5280                             switch (type_tag)
5281                             {
5282                                 case DW_TAG_class_type:
5283                                     // We had a "class foo", see if we ended up with a "struct foo { ... };"
5284                                     try_resolving_type = (tag == DW_TAG_structure_type);
5285                                     break;
5286                                 case DW_TAG_structure_type:
5287                                     // We had a "struct foo", see if we ended up with a "class foo { ... };"
5288                                     try_resolving_type = (tag == DW_TAG_class_type);
5289                                     break;
5290                                 default:
5291                                     // Tags don't match, don't event try to resolve
5292                                     // using this type whose name matches....
5293                                     break;
5294                             }
5295                         }
5296 
5297                         if (try_resolving_type)
5298                         {
5299                             DWARFDeclContext type_dwarf_decl_ctx;
5300                             type_die->GetDWARFDeclContext (this, type_cu, type_dwarf_decl_ctx);
5301 
5302                             if (log)
5303                             {
5304                                 GetObjectFile()->GetModule()->LogMessage (log,
5305                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') trying die=0x%8.8x (%s)",
5306                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5307                                                                           dwarf_decl_ctx.GetQualifiedName(),
5308                                                                           type_die->GetOffset(),
5309                                                                           type_dwarf_decl_ctx.GetQualifiedName());
5310                             }
5311 
5312                             // Make sure the decl contexts match all the way up
5313                             if (dwarf_decl_ctx == type_dwarf_decl_ctx)
5314                             {
5315                                 Type *resolved_type = ResolveType (type_cu, type_die, false);
5316                                 if (resolved_type && resolved_type != DIE_IS_BEING_PARSED)
5317                                 {
5318                                     type_sp = resolved_type->shared_from_this();
5319                                     break;
5320                                 }
5321                             }
5322                         }
5323                         else
5324                         {
5325                             if (log)
5326                             {
5327                                 std::string qualified_name;
5328                                 type_die->GetQualifiedName(this, type_cu, qualified_name);
5329                                 GetObjectFile()->GetModule()->LogMessage (log,
5330                                                                           "SymbolFileDWARF::FindDefinitionTypeForDWARFDeclContext(tag=%s, qualified-name='%s') ignoring die=0x%8.8x (%s)",
5331                                                                           DW_TAG_value_to_name(dwarf_decl_ctx[0].tag),
5332                                                                           dwarf_decl_ctx.GetQualifiedName(),
5333                                                                           type_die->GetOffset(),
5334                                                                           qualified_name.c_str());
5335                             }
5336                         }
5337                     }
5338                     else
5339                     {
5340                         if (m_using_apple_tables)
5341                         {
5342                             GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_types accelerator table had bad die 0x%8.8x for '%s')\n",
5343                                                                                        die_offset, type_name.GetCString());
5344                         }
5345                     }
5346 
5347                 }
5348             }
5349         }
5350     }
5351     return type_sp;
5352 }
5353 
5354 bool
5355 SymbolFileDWARF::CopyUniqueClassMethodTypes (SymbolFileDWARF *src_symfile,
5356                                              Type *class_type,
5357                                              DWARFCompileUnit* src_cu,
5358                                              const DWARFDebugInfoEntry *src_class_die,
5359                                              DWARFCompileUnit* dst_cu,
5360                                              const DWARFDebugInfoEntry *dst_class_die,
5361                                              DWARFDIECollection &failures)
5362 {
5363     if (!class_type || !src_cu || !src_class_die || !dst_cu || !dst_class_die)
5364         return false;
5365     if (src_class_die->Tag() != dst_class_die->Tag())
5366         return false;
5367 
5368     // We need to complete the class type so we can get all of the method types
5369     // parsed so we can then unique those types to their equivalent counterparts
5370     // in "dst_cu" and "dst_class_die"
5371     class_type->GetClangFullType();
5372 
5373     const DWARFDebugInfoEntry *src_die;
5374     const DWARFDebugInfoEntry *dst_die;
5375     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die;
5376     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die;
5377     UniqueCStringMap<const DWARFDebugInfoEntry *> src_name_to_die_artificial;
5378     UniqueCStringMap<const DWARFDebugInfoEntry *> dst_name_to_die_artificial;
5379     for (src_die = src_class_die->GetFirstChild(); src_die != NULL; src_die = src_die->GetSibling())
5380     {
5381         if (src_die->Tag() == DW_TAG_subprogram)
5382         {
5383             // Make sure this is a declaration and not a concrete instance by looking
5384             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5385             // are placed inside the class definitions and shouldn't be included in
5386             // the list of things are are tracking here.
5387             if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_declaration, 0) == 1)
5388             {
5389                 const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5390                 if (src_name)
5391                 {
5392                     ConstString src_const_name(src_name);
5393                     if (src_die->GetAttributeValueAsUnsigned(src_symfile, src_cu, DW_AT_artificial, 0))
5394                         src_name_to_die_artificial.Append(src_const_name.GetCString(), src_die);
5395                     else
5396                         src_name_to_die.Append(src_const_name.GetCString(), src_die);
5397                 }
5398             }
5399         }
5400     }
5401     for (dst_die = dst_class_die->GetFirstChild(); dst_die != NULL; dst_die = dst_die->GetSibling())
5402     {
5403         if (dst_die->Tag() == DW_TAG_subprogram)
5404         {
5405             // Make sure this is a declaration and not a concrete instance by looking
5406             // for DW_AT_declaration set to 1. Sometimes concrete function instances
5407             // are placed inside the class definitions and shouldn't be included in
5408             // the list of things are are tracking here.
5409             if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_declaration, 0) == 1)
5410             {
5411                 const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5412                 if (dst_name)
5413                 {
5414                     ConstString dst_const_name(dst_name);
5415                     if (dst_die->GetAttributeValueAsUnsigned(this, dst_cu, DW_AT_artificial, 0))
5416                         dst_name_to_die_artificial.Append(dst_const_name.GetCString(), dst_die);
5417                     else
5418                         dst_name_to_die.Append(dst_const_name.GetCString(), dst_die);
5419                 }
5420             }
5421         }
5422     }
5423     const uint32_t src_size = src_name_to_die.GetSize ();
5424     const uint32_t dst_size = dst_name_to_die.GetSize ();
5425     Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_TYPE_COMPLETION));
5426 
5427     // Is everything kosher so we can go through the members at top speed?
5428     bool fast_path = true;
5429 
5430     if (src_size != dst_size)
5431     {
5432         if (src_size != 0 && dst_size != 0)
5433         {
5434             if (log)
5435                 log->Printf("warning: trying to unique class DIE 0x%8.8x to 0x%8.8x, but they didn't have the same size (src=%d, dst=%d)",
5436                             src_class_die->GetOffset(),
5437                             dst_class_die->GetOffset(),
5438                             src_size,
5439                             dst_size);
5440         }
5441 
5442         fast_path = false;
5443     }
5444 
5445     uint32_t idx;
5446 
5447     if (fast_path)
5448     {
5449         for (idx = 0; idx < src_size; ++idx)
5450         {
5451             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5452             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5453 
5454             if (src_die->Tag() != dst_die->Tag())
5455             {
5456                 if (log)
5457                     log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, but 0x%8.8x (%s) tags didn't match 0x%8.8x (%s)",
5458                                 src_class_die->GetOffset(),
5459                                 dst_class_die->GetOffset(),
5460                                 src_die->GetOffset(),
5461                                 DW_TAG_value_to_name(src_die->Tag()),
5462                                 dst_die->GetOffset(),
5463                                 DW_TAG_value_to_name(src_die->Tag()));
5464                 fast_path = false;
5465             }
5466 
5467             const char *src_name = src_die->GetMangledName (src_symfile, src_cu);
5468             const char *dst_name = dst_die->GetMangledName (this, dst_cu);
5469 
5470             // Make sure the names match
5471             if (src_name == dst_name || (strcmp (src_name, dst_name) == 0))
5472                 continue;
5473 
5474             if (log)
5475                 log->Printf("warning: tried to unique class DIE 0x%8.8x to 0x%8.8x, but 0x%8.8x (%s) names didn't match 0x%8.8x (%s)",
5476                             src_class_die->GetOffset(),
5477                             dst_class_die->GetOffset(),
5478                             src_die->GetOffset(),
5479                             src_name,
5480                             dst_die->GetOffset(),
5481                             dst_name);
5482 
5483             fast_path = false;
5484         }
5485     }
5486 
5487     // Now do the work of linking the DeclContexts and Types.
5488     if (fast_path)
5489     {
5490         // We can do this quickly.  Just run across the tables index-for-index since
5491         // we know each node has matching names and tags.
5492         for (idx = 0; idx < src_size; ++idx)
5493         {
5494             src_die = src_name_to_die.GetValueAtIndexUnchecked (idx);
5495             dst_die = dst_name_to_die.GetValueAtIndexUnchecked (idx);
5496 
5497             clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5498             if (src_decl_ctx)
5499             {
5500                 if (log)
5501                     log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5502                                  static_cast<void*>(src_decl_ctx),
5503                                  src_die->GetOffset(), dst_die->GetOffset());
5504                 LinkDeclContextToDIE (src_decl_ctx, dst_die);
5505             }
5506             else
5507             {
5508                 if (log)
5509                     log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found",
5510                                  src_die->GetOffset(), dst_die->GetOffset());
5511             }
5512 
5513             Type *src_child_type = m_die_to_type[src_die];
5514             if (src_child_type)
5515             {
5516                 if (log)
5517                     log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5518                                  static_cast<void*>(src_child_type),
5519                                  src_child_type->GetID(),
5520                                  src_die->GetOffset(), dst_die->GetOffset());
5521                 m_die_to_type[dst_die] = src_child_type;
5522             }
5523             else
5524             {
5525                 if (log)
5526                     log->Printf ("warning: tried to unique lldb_private::Type from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5527             }
5528         }
5529     }
5530     else
5531     {
5532         // We must do this slowly.  For each member of the destination, look
5533         // up a member in the source with the same name, check its tag, and
5534         // unique them if everything matches up.  Report failures.
5535 
5536         if (!src_name_to_die.IsEmpty() && !dst_name_to_die.IsEmpty())
5537         {
5538             src_name_to_die.Sort();
5539 
5540             for (idx = 0; idx < dst_size; ++idx)
5541             {
5542                 const char *dst_name = dst_name_to_die.GetCStringAtIndex(idx);
5543                 dst_die = dst_name_to_die.GetValueAtIndexUnchecked(idx);
5544                 src_die = src_name_to_die.Find(dst_name, NULL);
5545 
5546                 if (src_die && (src_die->Tag() == dst_die->Tag()))
5547                 {
5548                     clang::DeclContext *src_decl_ctx = src_symfile->m_die_to_decl_ctx[src_die];
5549                     if (src_decl_ctx)
5550                     {
5551                         if (log)
5552                             log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5553                                          static_cast<void*>(src_decl_ctx),
5554                                          src_die->GetOffset(),
5555                                          dst_die->GetOffset());
5556                         LinkDeclContextToDIE (src_decl_ctx, dst_die);
5557                     }
5558                     else
5559                     {
5560                         if (log)
5561                             log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5562                     }
5563 
5564                     Type *src_child_type = m_die_to_type[src_die];
5565                     if (src_child_type)
5566                     {
5567                         if (log)
5568                             log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5569                                          static_cast<void*>(src_child_type),
5570                                          src_child_type->GetID(),
5571                                          src_die->GetOffset(),
5572                                          dst_die->GetOffset());
5573                         m_die_to_type[dst_die] = src_child_type;
5574                     }
5575                     else
5576                     {
5577                         if (log)
5578                             log->Printf ("warning: tried to unique lldb_private::Type from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5579                     }
5580                 }
5581                 else
5582                 {
5583                     if (log)
5584                         log->Printf ("warning: couldn't find a match for 0x%8.8x", dst_die->GetOffset());
5585 
5586                     failures.Append(dst_die);
5587                 }
5588             }
5589         }
5590     }
5591 
5592     const uint32_t src_size_artificial = src_name_to_die_artificial.GetSize ();
5593     const uint32_t dst_size_artificial = dst_name_to_die_artificial.GetSize ();
5594 
5595     UniqueCStringMap<const DWARFDebugInfoEntry *> name_to_die_artificial_not_in_src;
5596 
5597     if (src_size_artificial && dst_size_artificial)
5598     {
5599         dst_name_to_die_artificial.Sort();
5600 
5601         for (idx = 0; idx < src_size_artificial; ++idx)
5602         {
5603             const char *src_name_artificial = src_name_to_die_artificial.GetCStringAtIndex(idx);
5604             src_die = src_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5605             dst_die = dst_name_to_die_artificial.Find(src_name_artificial, NULL);
5606 
5607             if (dst_die)
5608             {
5609                 // Both classes have the artificial types, link them
5610                 clang::DeclContext *src_decl_ctx = m_die_to_decl_ctx[src_die];
5611                 if (src_decl_ctx)
5612                 {
5613                     if (log)
5614                         log->Printf ("uniquing decl context %p from 0x%8.8x for 0x%8.8x",
5615                                      static_cast<void*>(src_decl_ctx),
5616                                      src_die->GetOffset(), dst_die->GetOffset());
5617                     LinkDeclContextToDIE (src_decl_ctx, dst_die);
5618                 }
5619                 else
5620                 {
5621                     if (log)
5622                         log->Printf ("warning: tried to unique decl context from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5623                 }
5624 
5625                 Type *src_child_type = m_die_to_type[src_die];
5626                 if (src_child_type)
5627                 {
5628                     if (log)
5629                         log->Printf ("uniquing type %p (uid=0x%" PRIx64 ") from 0x%8.8x for 0x%8.8x",
5630                                      static_cast<void*>(src_child_type),
5631                                      src_child_type->GetID(),
5632                                      src_die->GetOffset(), dst_die->GetOffset());
5633                     m_die_to_type[dst_die] = src_child_type;
5634                 }
5635                 else
5636                 {
5637                     if (log)
5638                         log->Printf ("warning: tried to unique lldb_private::Type from 0x%8.8x for 0x%8.8x, but none was found", src_die->GetOffset(), dst_die->GetOffset());
5639                 }
5640             }
5641         }
5642     }
5643 
5644     if (dst_size_artificial)
5645     {
5646         for (idx = 0; idx < dst_size_artificial; ++idx)
5647         {
5648             const char *dst_name_artificial = dst_name_to_die_artificial.GetCStringAtIndex(idx);
5649             dst_die = dst_name_to_die_artificial.GetValueAtIndexUnchecked (idx);
5650             if (log)
5651                 log->Printf ("warning: need to create artificial method for 0x%8.8x for method '%s'", dst_die->GetOffset(), dst_name_artificial);
5652 
5653             failures.Append(dst_die);
5654         }
5655     }
5656 
5657     return (failures.Size() != 0);
5658 }
5659 
5660 TypeSP
5661 SymbolFileDWARF::ParseType (const SymbolContext& sc, DWARFCompileUnit* dwarf_cu, const DWARFDebugInfoEntry *die, bool *type_is_new_ptr)
5662 {
5663     TypeSP type_sp;
5664 
5665     if (type_is_new_ptr)
5666         *type_is_new_ptr = false;
5667 
5668 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
5669     static DIEStack g_die_stack;
5670     DIEStack::ScopedPopper scoped_die_logger(g_die_stack);
5671 #endif
5672 
5673     AccessType accessibility = eAccessNone;
5674     if (die != NULL)
5675     {
5676         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5677         if (log)
5678         {
5679             const DWARFDebugInfoEntry *context_die;
5680             clang::DeclContext *context = GetClangDeclContextContainingDIE (dwarf_cu, die, &context_die);
5681 
5682             GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x, decl_ctx = %p (die 0x%8.8x)) %s name = '%s')",
5683                                                       die->GetOffset(),
5684                                                       static_cast<void*>(context),
5685                                                       context_die->GetOffset(),
5686                                                       DW_TAG_value_to_name(die->Tag()),
5687                                                       die->GetName(this, dwarf_cu));
5688 
5689 #if defined(LLDB_CONFIGURATION_DEBUG) || defined(LLDB_CONFIGURATION_RELEASE)
5690             scoped_die_logger.Push (dwarf_cu, die);
5691             g_die_stack.LogDIEs(log, this);
5692 #endif
5693         }
5694 //
5695 //        Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
5696 //        if (log && dwarf_cu)
5697 //        {
5698 //            StreamString s;
5699 //            die->DumpLocation (this, dwarf_cu, s);
5700 //            GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDwarf::%s %s", __FUNCTION__, s.GetData());
5701 //
5702 //        }
5703 
5704         Type *type_ptr = m_die_to_type.lookup (die);
5705         TypeList* type_list = GetTypeList();
5706         if (type_ptr == NULL)
5707         {
5708             ClangASTContext &ast = GetClangASTContext();
5709             if (type_is_new_ptr)
5710                 *type_is_new_ptr = true;
5711 
5712             const dw_tag_t tag = die->Tag();
5713 
5714             bool is_forward_declaration = false;
5715             DWARFDebugInfoEntry::Attributes attributes;
5716             const char *type_name_cstr = NULL;
5717             ConstString type_name_const_str;
5718             Type::ResolveState resolve_state = Type::eResolveStateUnresolved;
5719             uint64_t byte_size = 0;
5720             Declaration decl;
5721 
5722             Type::EncodingDataType encoding_data_type = Type::eEncodingIsUID;
5723             ClangASTType clang_type;
5724             DWARFFormValue form_value;
5725 
5726             dw_attr_t attr;
5727 
5728             switch (tag)
5729             {
5730             case DW_TAG_base_type:
5731             case DW_TAG_pointer_type:
5732             case DW_TAG_reference_type:
5733             case DW_TAG_rvalue_reference_type:
5734             case DW_TAG_typedef:
5735             case DW_TAG_const_type:
5736             case DW_TAG_restrict_type:
5737             case DW_TAG_volatile_type:
5738             case DW_TAG_unspecified_type:
5739                 {
5740                     // Set a bit that lets us know that we are currently parsing this
5741                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5742 
5743                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5744                     uint32_t encoding = 0;
5745                     lldb::user_id_t encoding_uid = LLDB_INVALID_UID;
5746 
5747                     if (num_attributes > 0)
5748                     {
5749                         uint32_t i;
5750                         for (i=0; i<num_attributes; ++i)
5751                         {
5752                             attr = attributes.AttributeAtIndex(i);
5753                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5754                             {
5755                                 switch (attr)
5756                                 {
5757                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
5758                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
5759                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
5760                                 case DW_AT_name:
5761 
5762                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5763                                     // Work around a bug in llvm-gcc where they give a name to a reference type which doesn't
5764                                     // include the "&"...
5765                                     if (tag == DW_TAG_reference_type)
5766                                     {
5767                                         if (strchr (type_name_cstr, '&') == NULL)
5768                                             type_name_cstr = NULL;
5769                                     }
5770                                     if (type_name_cstr)
5771                                         type_name_const_str.SetCString(type_name_cstr);
5772                                     break;
5773                                 case DW_AT_byte_size:   byte_size = form_value.Unsigned(); break;
5774                                 case DW_AT_encoding:    encoding = form_value.Unsigned(); break;
5775                                 case DW_AT_type:        encoding_uid = form_value.Reference(); break;
5776                                 default:
5777                                 case DW_AT_sibling:
5778                                     break;
5779                                 }
5780                             }
5781                         }
5782                     }
5783 
5784                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\") type => 0x%8.8lx\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr, encoding_uid);
5785 
5786                     switch (tag)
5787                     {
5788                     default:
5789                         break;
5790 
5791                     case DW_TAG_unspecified_type:
5792                         if (strcmp(type_name_cstr, "nullptr_t") == 0 ||
5793                             strcmp(type_name_cstr, "decltype(nullptr)") == 0 )
5794                         {
5795                             resolve_state = Type::eResolveStateFull;
5796                             clang_type = ast.GetBasicType(eBasicTypeNullPtr);
5797                             break;
5798                         }
5799                         // Fall through to base type below in case we can handle the type there...
5800 
5801                     case DW_TAG_base_type:
5802                         resolve_state = Type::eResolveStateFull;
5803                         clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (type_name_cstr,
5804                                                                                    encoding,
5805                                                                                    byte_size * 8);
5806                         break;
5807 
5808                     case DW_TAG_pointer_type:           encoding_data_type = Type::eEncodingIsPointerUID;           break;
5809                     case DW_TAG_reference_type:         encoding_data_type = Type::eEncodingIsLValueReferenceUID;   break;
5810                     case DW_TAG_rvalue_reference_type:  encoding_data_type = Type::eEncodingIsRValueReferenceUID;   break;
5811                     case DW_TAG_typedef:                encoding_data_type = Type::eEncodingIsTypedefUID;           break;
5812                     case DW_TAG_const_type:             encoding_data_type = Type::eEncodingIsConstUID;             break;
5813                     case DW_TAG_restrict_type:          encoding_data_type = Type::eEncodingIsRestrictUID;          break;
5814                     case DW_TAG_volatile_type:          encoding_data_type = Type::eEncodingIsVolatileUID;          break;
5815                     }
5816 
5817                     if (!clang_type && (encoding_data_type == Type::eEncodingIsPointerUID || encoding_data_type == Type::eEncodingIsTypedefUID) && sc.comp_unit != NULL)
5818                     {
5819                         bool translation_unit_is_objc = (sc.comp_unit->GetLanguage() == eLanguageTypeObjC || sc.comp_unit->GetLanguage() == eLanguageTypeObjC_plus_plus);
5820 
5821                         if (translation_unit_is_objc)
5822                         {
5823                             if (type_name_cstr != NULL)
5824                             {
5825                                 static ConstString g_objc_type_name_id("id");
5826                                 static ConstString g_objc_type_name_Class("Class");
5827                                 static ConstString g_objc_type_name_selector("SEL");
5828 
5829                                 if (type_name_const_str == g_objc_type_name_id)
5830                                 {
5831                                     if (log)
5832                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'id' built-in type.",
5833                                                                                   die->GetOffset(),
5834                                                                                   DW_TAG_value_to_name(die->Tag()),
5835                                                                                   die->GetName(this, dwarf_cu));
5836                                     clang_type = ast.GetBasicType(eBasicTypeObjCID);
5837                                     encoding_data_type = Type::eEncodingIsUID;
5838                                     encoding_uid = LLDB_INVALID_UID;
5839                                     resolve_state = Type::eResolveStateFull;
5840 
5841                                 }
5842                                 else if (type_name_const_str == g_objc_type_name_Class)
5843                                 {
5844                                     if (log)
5845                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'Class' built-in type.",
5846                                                                                   die->GetOffset(),
5847                                                                                   DW_TAG_value_to_name(die->Tag()),
5848                                                                                   die->GetName(this, dwarf_cu));
5849                                     clang_type = ast.GetBasicType(eBasicTypeObjCClass);
5850                                     encoding_data_type = Type::eEncodingIsUID;
5851                                     encoding_uid = LLDB_INVALID_UID;
5852                                     resolve_state = Type::eResolveStateFull;
5853                                 }
5854                                 else if (type_name_const_str == g_objc_type_name_selector)
5855                                 {
5856                                     if (log)
5857                                         GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is Objective C 'selector' built-in type.",
5858                                                                                   die->GetOffset(),
5859                                                                                   DW_TAG_value_to_name(die->Tag()),
5860                                                                                   die->GetName(this, dwarf_cu));
5861                                     clang_type = ast.GetBasicType(eBasicTypeObjCSel);
5862                                     encoding_data_type = Type::eEncodingIsUID;
5863                                     encoding_uid = LLDB_INVALID_UID;
5864                                     resolve_state = Type::eResolveStateFull;
5865                                 }
5866                             }
5867                             else if (encoding_data_type == Type::eEncodingIsPointerUID && encoding_uid != LLDB_INVALID_UID)
5868                             {
5869                                 // Clang sometimes erroneously emits id as objc_object*.  In that case we fix up the type to "id".
5870 
5871                                 DWARFDebugInfoEntry* encoding_die = dwarf_cu->GetDIEPtr(encoding_uid);
5872 
5873                                 if (encoding_die && encoding_die->Tag() == DW_TAG_structure_type)
5874                                 {
5875                                     if (const char *struct_name = encoding_die->GetAttributeValueAsString(this, dwarf_cu, DW_AT_name, NULL))
5876                                     {
5877                                         if (!strcmp(struct_name, "objc_object"))
5878                                         {
5879                                             if (log)
5880                                                 GetObjectFile()->GetModule()->LogMessage (log, "SymbolFileDWARF::ParseType (die = 0x%8.8x) %s '%s' is 'objc_object*', which we overrode to 'id'.",
5881                                                                                           die->GetOffset(),
5882                                                                                           DW_TAG_value_to_name(die->Tag()),
5883                                                                                           die->GetName(this, dwarf_cu));
5884                                             clang_type = ast.GetBasicType(eBasicTypeObjCID);
5885                                             encoding_data_type = Type::eEncodingIsUID;
5886                                             encoding_uid = LLDB_INVALID_UID;
5887                                             resolve_state = Type::eResolveStateFull;
5888                                         }
5889                                     }
5890                                 }
5891                             }
5892                         }
5893                     }
5894 
5895                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
5896                                              this,
5897                                              type_name_const_str,
5898                                              byte_size,
5899                                              NULL,
5900                                              encoding_uid,
5901                                              encoding_data_type,
5902                                              &decl,
5903                                              clang_type,
5904                                              resolve_state));
5905 
5906                     m_die_to_type[die] = type_sp.get();
5907 
5908 //                  Type* encoding_type = GetUniquedTypeForDIEOffset(encoding_uid, type_sp, NULL, 0, 0, false);
5909 //                  if (encoding_type != NULL)
5910 //                  {
5911 //                      if (encoding_type != DIE_IS_BEING_PARSED)
5912 //                          type_sp->SetEncodingType(encoding_type);
5913 //                      else
5914 //                          m_indirect_fixups.push_back(type_sp.get());
5915 //                  }
5916                 }
5917                 break;
5918 
5919             case DW_TAG_structure_type:
5920             case DW_TAG_union_type:
5921             case DW_TAG_class_type:
5922                 {
5923                     // Set a bit that lets us know that we are currently parsing this
5924                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
5925                     bool byte_size_valid = false;
5926 
5927                     LanguageType class_language = eLanguageTypeUnknown;
5928                     bool is_complete_objc_class = false;
5929                     //bool struct_is_class = false;
5930                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
5931                     if (num_attributes > 0)
5932                     {
5933                         uint32_t i;
5934                         for (i=0; i<num_attributes; ++i)
5935                         {
5936                             attr = attributes.AttributeAtIndex(i);
5937                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
5938                             {
5939                                 switch (attr)
5940                                 {
5941                                 case DW_AT_decl_file:
5942                                     if (dwarf_cu->DW_AT_decl_file_attributes_are_invalid())
5943                                     {
5944                                         // llvm-gcc outputs invalid DW_AT_decl_file attributes that always
5945                                         // point to the compile unit file, so we clear this invalid value
5946                                         // so that we can still unique types efficiently.
5947                                         decl.SetFile(FileSpec ("<invalid>", false));
5948                                     }
5949                                     else
5950                                         decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned()));
5951                                     break;
5952 
5953                                 case DW_AT_decl_line:
5954                                     decl.SetLine(form_value.Unsigned());
5955                                     break;
5956 
5957                                 case DW_AT_decl_column:
5958                                     decl.SetColumn(form_value.Unsigned());
5959                                     break;
5960 
5961                                 case DW_AT_name:
5962                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
5963                                     type_name_const_str.SetCString(type_name_cstr);
5964                                     break;
5965 
5966                                 case DW_AT_byte_size:
5967                                     byte_size = form_value.Unsigned();
5968                                     byte_size_valid = true;
5969                                     break;
5970 
5971                                 case DW_AT_accessibility:
5972                                     accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned());
5973                                     break;
5974 
5975                                 case DW_AT_declaration:
5976                                     is_forward_declaration = form_value.Boolean();
5977                                     break;
5978 
5979                                 case DW_AT_APPLE_runtime_class:
5980                                     class_language = (LanguageType)form_value.Signed();
5981                                     break;
5982 
5983                                 case DW_AT_APPLE_objc_complete_type:
5984                                     is_complete_objc_class = form_value.Signed();
5985                                     break;
5986 
5987                                 case DW_AT_allocated:
5988                                 case DW_AT_associated:
5989                                 case DW_AT_data_location:
5990                                 case DW_AT_description:
5991                                 case DW_AT_start_scope:
5992                                 case DW_AT_visibility:
5993                                 default:
5994                                 case DW_AT_sibling:
5995                                     break;
5996                                 }
5997                             }
5998                         }
5999                     }
6000 
6001                     // UniqueDWARFASTType is large, so don't create a local variables on the
6002                     // stack, put it on the heap. This function is often called recursively
6003                     // and clang isn't good and sharing the stack space for variables in different blocks.
6004                     std::unique_ptr<UniqueDWARFASTType> unique_ast_entry_ap(new UniqueDWARFASTType());
6005 
6006                     // Only try and unique the type if it has a name.
6007                     if (type_name_const_str &&
6008                         GetUniqueDWARFASTTypeMap().Find (type_name_const_str,
6009                                                          this,
6010                                                          dwarf_cu,
6011                                                          die,
6012                                                          decl,
6013                                                          byte_size_valid ? byte_size : -1,
6014                                                          *unique_ast_entry_ap))
6015                     {
6016                         // We have already parsed this type or from another
6017                         // compile unit. GCC loves to use the "one definition
6018                         // rule" which can result in multiple definitions
6019                         // of the same class over and over in each compile
6020                         // unit.
6021                         type_sp = unique_ast_entry_ap->m_type_sp;
6022                         if (type_sp)
6023                         {
6024                             m_die_to_type[die] = type_sp.get();
6025                             return type_sp;
6026                         }
6027                     }
6028 
6029                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6030 
6031                     int tag_decl_kind = -1;
6032                     AccessType default_accessibility = eAccessNone;
6033                     if (tag == DW_TAG_structure_type)
6034                     {
6035                         tag_decl_kind = clang::TTK_Struct;
6036                         default_accessibility = eAccessPublic;
6037                     }
6038                     else if (tag == DW_TAG_union_type)
6039                     {
6040                         tag_decl_kind = clang::TTK_Union;
6041                         default_accessibility = eAccessPublic;
6042                     }
6043                     else if (tag == DW_TAG_class_type)
6044                     {
6045                         tag_decl_kind = clang::TTK_Class;
6046                         default_accessibility = eAccessPrivate;
6047                     }
6048 
6049                     if (byte_size_valid && byte_size == 0 && type_name_cstr &&
6050                         die->HasChildren() == false &&
6051                         sc.comp_unit->GetLanguage() == eLanguageTypeObjC)
6052                     {
6053                         // Work around an issue with clang at the moment where
6054                         // forward declarations for objective C classes are emitted
6055                         // as:
6056                         //  DW_TAG_structure_type [2]
6057                         //  DW_AT_name( "ForwardObjcClass" )
6058                         //  DW_AT_byte_size( 0x00 )
6059                         //  DW_AT_decl_file( "..." )
6060                         //  DW_AT_decl_line( 1 )
6061                         //
6062                         // Note that there is no DW_AT_declaration and there are
6063                         // no children, and the byte size is zero.
6064                         is_forward_declaration = true;
6065                     }
6066 
6067                     if (class_language == eLanguageTypeObjC ||
6068                         class_language == eLanguageTypeObjC_plus_plus)
6069                     {
6070                         if (!is_complete_objc_class && Supports_DW_AT_APPLE_objc_complete_type(dwarf_cu))
6071                         {
6072                             // We have a valid eSymbolTypeObjCClass class symbol whose
6073                             // name matches the current objective C class that we
6074                             // are trying to find and this DIE isn't the complete
6075                             // definition (we checked is_complete_objc_class above and
6076                             // know it is false), so the real definition is in here somewhere
6077                             type_sp = FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
6078 
6079                             if (!type_sp && GetDebugMapSymfile ())
6080                             {
6081                                 // We weren't able to find a full declaration in
6082                                 // this DWARF, see if we have a declaration anywhere
6083                                 // else...
6084                                 type_sp = m_debug_map_symfile->FindCompleteObjCDefinitionTypeForDIE (die, type_name_const_str, true);
6085                             }
6086 
6087                             if (type_sp)
6088                             {
6089                                 if (log)
6090                                 {
6091                                     GetObjectFile()->GetModule()->LogMessage (log,
6092                                                                               "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is an incomplete objc type, complete type is 0x%8.8" PRIx64,
6093                                                                               static_cast<void*>(this),
6094                                                                               die->GetOffset(),
6095                                                                               DW_TAG_value_to_name(tag),
6096                                                                               type_name_cstr,
6097                                                                               type_sp->GetID());
6098                                 }
6099 
6100                                 // We found a real definition for this type elsewhere
6101                                 // so lets use it and cache the fact that we found
6102                                 // a complete type for this die
6103                                 m_die_to_type[die] = type_sp.get();
6104                                 return type_sp;
6105                             }
6106                         }
6107                     }
6108 
6109 
6110                     if (is_forward_declaration)
6111                     {
6112                         // We have a forward declaration to a type and we need
6113                         // to try and find a full declaration. We look in the
6114                         // current type index just in case we have a forward
6115                         // declaration followed by an actual declarations in the
6116                         // DWARF. If this fails, we need to look elsewhere...
6117                         if (log)
6118                         {
6119                             GetObjectFile()->GetModule()->LogMessage (log,
6120                                                                       "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, trying to find complete type",
6121                                                                       static_cast<void*>(this),
6122                                                                       die->GetOffset(),
6123                                                                       DW_TAG_value_to_name(tag),
6124                                                                       type_name_cstr);
6125                         }
6126 
6127                         DWARFDeclContext die_decl_ctx;
6128                         die->GetDWARFDeclContext(this, dwarf_cu, die_decl_ctx);
6129 
6130                         //type_sp = FindDefinitionTypeForDIE (dwarf_cu, die, type_name_const_str);
6131                         type_sp = FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
6132 
6133                         if (!type_sp && GetDebugMapSymfile ())
6134                         {
6135                             // We weren't able to find a full declaration in
6136                             // this DWARF, see if we have a declaration anywhere
6137                             // else...
6138                             type_sp = m_debug_map_symfile->FindDefinitionTypeForDWARFDeclContext (die_decl_ctx);
6139                         }
6140 
6141                         if (type_sp)
6142                         {
6143                             if (log)
6144                             {
6145                                 GetObjectFile()->GetModule()->LogMessage (log,
6146                                                                           "SymbolFileDWARF(%p) - 0x%8.8x: %s type \"%s\" is a forward declaration, complete type is 0x%8.8" PRIx64,
6147                                                                           static_cast<void*>(this),
6148                                                                           die->GetOffset(),
6149                                                                           DW_TAG_value_to_name(tag),
6150                                                                           type_name_cstr,
6151                                                                           type_sp->GetID());
6152                             }
6153 
6154                             // We found a real definition for this type elsewhere
6155                             // so lets use it and cache the fact that we found
6156                             // a complete type for this die
6157                             m_die_to_type[die] = type_sp.get();
6158                             return type_sp;
6159                         }
6160                     }
6161                     assert (tag_decl_kind != -1);
6162                     bool clang_type_was_created = false;
6163                     clang_type.SetClangType(ast.getASTContext(), m_forward_decl_die_to_clang_type.lookup (die));
6164                     if (!clang_type)
6165                     {
6166                         const DWARFDebugInfoEntry *decl_ctx_die;
6167 
6168                         clang::DeclContext *decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6169                         if (accessibility == eAccessNone && decl_ctx)
6170                         {
6171                             // Check the decl context that contains this class/struct/union.
6172                             // If it is a class we must give it an accessibility.
6173                             const clang::Decl::Kind containing_decl_kind = decl_ctx->getDeclKind();
6174                             if (DeclKindIsCXXClass (containing_decl_kind))
6175                                 accessibility = default_accessibility;
6176                         }
6177 
6178                         ClangASTMetadata metadata;
6179                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6180                         metadata.SetIsDynamicCXXType(ClassOrStructIsVirtual (dwarf_cu, die));
6181 
6182                         if (type_name_cstr && strchr (type_name_cstr, '<'))
6183                         {
6184                             ClangASTContext::TemplateParameterInfos template_param_infos;
6185                             if (ParseTemplateParameterInfos (dwarf_cu, die, template_param_infos))
6186                             {
6187                                 clang::ClassTemplateDecl *class_template_decl = ParseClassTemplateDecl (decl_ctx,
6188                                                                                                         accessibility,
6189                                                                                                         type_name_cstr,
6190                                                                                                         tag_decl_kind,
6191                                                                                                         template_param_infos);
6192 
6193                                 clang::ClassTemplateSpecializationDecl *class_specialization_decl = ast.CreateClassTemplateSpecializationDecl (decl_ctx,
6194                                                                                                                                                class_template_decl,
6195                                                                                                                                                tag_decl_kind,
6196                                                                                                                                                template_param_infos);
6197                                 clang_type = ast.CreateClassTemplateSpecializationType (class_specialization_decl);
6198                                 clang_type_was_created = true;
6199 
6200                                 GetClangASTContext().SetMetadata (class_template_decl, metadata);
6201                                 GetClangASTContext().SetMetadata (class_specialization_decl, metadata);
6202                             }
6203                         }
6204 
6205                         if (!clang_type_was_created)
6206                         {
6207                             clang_type_was_created = true;
6208                             clang_type = ast.CreateRecordType (decl_ctx,
6209                                                                accessibility,
6210                                                                type_name_cstr,
6211                                                                tag_decl_kind,
6212                                                                class_language,
6213                                                                &metadata);
6214                         }
6215                     }
6216 
6217                     // Store a forward declaration to this class type in case any
6218                     // parameters in any class methods need it for the clang
6219                     // types for function prototypes.
6220                     LinkDeclContextToDIE(clang_type.GetDeclContextForType(), die);
6221                     type_sp.reset (new Type (MakeUserID(die->GetOffset()),
6222                                              this,
6223                                              type_name_const_str,
6224                                              byte_size,
6225                                              NULL,
6226                                              LLDB_INVALID_UID,
6227                                              Type::eEncodingIsUID,
6228                                              &decl,
6229                                              clang_type,
6230                                              Type::eResolveStateForward));
6231 
6232                     type_sp->SetIsCompleteObjCClass(is_complete_objc_class);
6233 
6234 
6235                     // Add our type to the unique type map so we don't
6236                     // end up creating many copies of the same type over
6237                     // and over in the ASTContext for our module
6238                     unique_ast_entry_ap->m_type_sp = type_sp;
6239                     unique_ast_entry_ap->m_symfile = this;
6240                     unique_ast_entry_ap->m_cu = dwarf_cu;
6241                     unique_ast_entry_ap->m_die = die;
6242                     unique_ast_entry_ap->m_declaration = decl;
6243                     unique_ast_entry_ap->m_byte_size = byte_size;
6244                     GetUniqueDWARFASTTypeMap().Insert (type_name_const_str,
6245                                                        *unique_ast_entry_ap);
6246 
6247                     if (is_forward_declaration && die->HasChildren())
6248                     {
6249                         // Check to see if the DIE actually has a definition, some version of GCC will
6250                         // emit DIEs with DW_AT_declaration set to true, but yet still have subprogram,
6251                         // members, or inheritance, so we can't trust it
6252                         const DWARFDebugInfoEntry *child_die = die->GetFirstChild();
6253                         while (child_die)
6254                         {
6255                             switch (child_die->Tag())
6256                             {
6257                                 case DW_TAG_inheritance:
6258                                 case DW_TAG_subprogram:
6259                                 case DW_TAG_member:
6260                                 case DW_TAG_APPLE_property:
6261                                 case DW_TAG_class_type:
6262                                 case DW_TAG_structure_type:
6263                                 case DW_TAG_enumeration_type:
6264                                 case DW_TAG_typedef:
6265                                 case DW_TAG_union_type:
6266                                     child_die = NULL;
6267                                     is_forward_declaration = false;
6268                                     break;
6269                                 default:
6270                                     child_die = child_die->GetSibling();
6271                                     break;
6272                             }
6273                         }
6274                     }
6275 
6276                     if (!is_forward_declaration)
6277                     {
6278                         // Always start the definition for a class type so that
6279                         // if the class has child classes or types that require
6280                         // the class to be created for use as their decl contexts
6281                         // the class will be ready to accept these child definitions.
6282                         if (die->HasChildren() == false)
6283                         {
6284                             // No children for this struct/union/class, lets finish it
6285                             clang_type.StartTagDeclarationDefinition ();
6286                             clang_type.CompleteTagDeclarationDefinition ();
6287 
6288                             if (tag == DW_TAG_structure_type) // this only applies in C
6289                             {
6290                                 clang::RecordDecl *record_decl = clang_type.GetAsRecordDecl();
6291 
6292                                 if (record_decl)
6293                                     m_record_decl_to_layout_map.insert(std::make_pair(record_decl, LayoutInfo()));
6294                             }
6295                         }
6296                         else if (clang_type_was_created)
6297                         {
6298                             // Start the definition if the class is not objective C since
6299                             // the underlying decls respond to isCompleteDefinition(). Objective
6300                             // C decls don't respond to isCompleteDefinition() so we can't
6301                             // start the declaration definition right away. For C++ class/union/structs
6302                             // we want to start the definition in case the class is needed as the
6303                             // declaration context for a contained class or type without the need
6304                             // to complete that type..
6305 
6306                             if (class_language != eLanguageTypeObjC &&
6307                                 class_language != eLanguageTypeObjC_plus_plus)
6308                                 clang_type.StartTagDeclarationDefinition ();
6309 
6310                             // Leave this as a forward declaration until we need
6311                             // to know the details of the type. lldb_private::Type
6312                             // will automatically call the SymbolFile virtual function
6313                             // "SymbolFileDWARF::ResolveClangOpaqueTypeDefinition(Type *)"
6314                             // When the definition needs to be defined.
6315                             m_forward_decl_die_to_clang_type[die] = clang_type.GetOpaqueQualType();
6316                             m_forward_decl_clang_type_to_die[clang_type.RemoveFastQualifiers().GetOpaqueQualType()] = die;
6317                             clang_type.SetHasExternalStorage (true);
6318                         }
6319                     }
6320 
6321                 }
6322                 break;
6323 
6324             case DW_TAG_enumeration_type:
6325                 {
6326                     // Set a bit that lets us know that we are currently parsing this
6327                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6328 
6329                     lldb::user_id_t encoding_uid = DW_INVALID_OFFSET;
6330 
6331                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6332                     if (num_attributes > 0)
6333                     {
6334                         uint32_t i;
6335 
6336                         for (i=0; i<num_attributes; ++i)
6337                         {
6338                             attr = attributes.AttributeAtIndex(i);
6339                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6340                             {
6341                                 switch (attr)
6342                                 {
6343                                 case DW_AT_decl_file:       decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6344                                 case DW_AT_decl_line:       decl.SetLine(form_value.Unsigned()); break;
6345                                 case DW_AT_decl_column:     decl.SetColumn(form_value.Unsigned()); break;
6346                                 case DW_AT_name:
6347                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6348                                     type_name_const_str.SetCString(type_name_cstr);
6349                                     break;
6350                                 case DW_AT_type:            encoding_uid = form_value.Reference(); break;
6351                                 case DW_AT_byte_size:       byte_size = form_value.Unsigned(); break;
6352                                 case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6353                                 case DW_AT_declaration:     break; //is_forward_declaration = form_value.Boolean(); break;
6354                                 case DW_AT_allocated:
6355                                 case DW_AT_associated:
6356                                 case DW_AT_bit_stride:
6357                                 case DW_AT_byte_stride:
6358                                 case DW_AT_data_location:
6359                                 case DW_AT_description:
6360                                 case DW_AT_start_scope:
6361                                 case DW_AT_visibility:
6362                                 case DW_AT_specification:
6363                                 case DW_AT_abstract_origin:
6364                                 case DW_AT_sibling:
6365                                     break;
6366                                 }
6367                             }
6368                         }
6369 
6370                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6371 
6372                         ClangASTType enumerator_clang_type;
6373                         clang_type.SetClangType (ast.getASTContext(), m_forward_decl_die_to_clang_type.lookup (die));
6374                         if (!clang_type)
6375                         {
6376                             if (encoding_uid != DW_INVALID_OFFSET)
6377                             {
6378                                 Type *enumerator_type = ResolveTypeUID(encoding_uid);
6379                                 if (enumerator_type)
6380                                     enumerator_clang_type = enumerator_type->GetClangFullType();
6381                             }
6382 
6383                             if (!enumerator_clang_type)
6384                                 enumerator_clang_type = ast.GetBuiltinTypeForDWARFEncodingAndBitSize (NULL,
6385                                                                                                       DW_ATE_signed,
6386                                                                                                       byte_size * 8);
6387 
6388                             clang_type = ast.CreateEnumerationType (type_name_cstr,
6389                                                                     GetClangDeclContextContainingDIE (dwarf_cu, die, NULL),
6390                                                                     decl,
6391                                                                     enumerator_clang_type);
6392                         }
6393                         else
6394                         {
6395                             enumerator_clang_type = clang_type.GetEnumerationIntegerType ();
6396                         }
6397 
6398                         LinkDeclContextToDIE(clang_type.GetDeclContextForType(), die);
6399 
6400                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6401                                                  this,
6402                                                  type_name_const_str,
6403                                                  byte_size,
6404                                                  NULL,
6405                                                  encoding_uid,
6406                                                  Type::eEncodingIsUID,
6407                                                  &decl,
6408                                                  clang_type,
6409                                                  Type::eResolveStateForward));
6410 
6411                         clang_type.StartTagDeclarationDefinition ();
6412                         if (die->HasChildren())
6413                         {
6414                             SymbolContext cu_sc(GetCompUnitForDWARFCompUnit(dwarf_cu));
6415                             bool is_signed = false;
6416                             enumerator_clang_type.IsIntegerType(is_signed);
6417                             ParseChildEnumerators(cu_sc, clang_type, is_signed, type_sp->GetByteSize(), dwarf_cu, die);
6418                         }
6419                         clang_type.CompleteTagDeclarationDefinition ();
6420                     }
6421                 }
6422                 break;
6423 
6424             case DW_TAG_inlined_subroutine:
6425             case DW_TAG_subprogram:
6426             case DW_TAG_subroutine_type:
6427                 {
6428                     // Set a bit that lets us know that we are currently parsing this
6429                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6430 
6431                     //const char *mangled = NULL;
6432                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
6433                     bool is_variadic = false;
6434                     bool is_inline = false;
6435                     bool is_static = false;
6436                     bool is_virtual = false;
6437                     bool is_explicit = false;
6438                     bool is_artificial = false;
6439                     dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
6440                     dw_offset_t abstract_origin_die_offset = DW_INVALID_OFFSET;
6441                     dw_offset_t object_pointer_die_offset = DW_INVALID_OFFSET;
6442 
6443                     unsigned type_quals = 0;
6444                     clang::StorageClass storage = clang::SC_None;//, Extern, Static, PrivateExtern
6445 
6446 
6447                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6448                     if (num_attributes > 0)
6449                     {
6450                         uint32_t i;
6451                         for (i=0; i<num_attributes; ++i)
6452                         {
6453                             attr = attributes.AttributeAtIndex(i);
6454                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6455                             {
6456                                 switch (attr)
6457                                 {
6458                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6459                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6460                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6461                                 case DW_AT_name:
6462                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6463                                     type_name_const_str.SetCString(type_name_cstr);
6464                                     break;
6465 
6466                                 case DW_AT_linkage_name:
6467                                 case DW_AT_MIPS_linkage_name:   break; // mangled = form_value.AsCString(&get_debug_str_data()); break;
6468                                 case DW_AT_type:                type_die_offset = form_value.Reference(); break;
6469                                 case DW_AT_accessibility:       accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6470                                 case DW_AT_declaration:         break; // is_forward_declaration = form_value.Boolean(); break;
6471                                 case DW_AT_inline:              is_inline = form_value.Boolean(); break;
6472                                 case DW_AT_virtuality:          is_virtual = form_value.Boolean();  break;
6473                                 case DW_AT_explicit:            is_explicit = form_value.Boolean();  break;
6474                                 case DW_AT_artificial:          is_artificial = form_value.Boolean();  break;
6475 
6476 
6477                                 case DW_AT_external:
6478                                     if (form_value.Unsigned())
6479                                     {
6480                                         if (storage == clang::SC_None)
6481                                             storage = clang::SC_Extern;
6482                                         else
6483                                             storage = clang::SC_PrivateExtern;
6484                                     }
6485                                     break;
6486 
6487                                 case DW_AT_specification:
6488                                     specification_die_offset = form_value.Reference();
6489                                     break;
6490 
6491                                 case DW_AT_abstract_origin:
6492                                     abstract_origin_die_offset = form_value.Reference();
6493                                     break;
6494 
6495                                 case DW_AT_object_pointer:
6496                                     object_pointer_die_offset = form_value.Reference();
6497                                     break;
6498 
6499                                 case DW_AT_allocated:
6500                                 case DW_AT_associated:
6501                                 case DW_AT_address_class:
6502                                 case DW_AT_calling_convention:
6503                                 case DW_AT_data_location:
6504                                 case DW_AT_elemental:
6505                                 case DW_AT_entry_pc:
6506                                 case DW_AT_frame_base:
6507                                 case DW_AT_high_pc:
6508                                 case DW_AT_low_pc:
6509                                 case DW_AT_prototyped:
6510                                 case DW_AT_pure:
6511                                 case DW_AT_ranges:
6512                                 case DW_AT_recursive:
6513                                 case DW_AT_return_addr:
6514                                 case DW_AT_segment:
6515                                 case DW_AT_start_scope:
6516                                 case DW_AT_static_link:
6517                                 case DW_AT_trampoline:
6518                                 case DW_AT_visibility:
6519                                 case DW_AT_vtable_elem_location:
6520                                 case DW_AT_description:
6521                                 case DW_AT_sibling:
6522                                     break;
6523                                 }
6524                             }
6525                         }
6526                     }
6527 
6528                     std::string object_pointer_name;
6529                     if (object_pointer_die_offset != DW_INVALID_OFFSET)
6530                     {
6531                         // Get the name from the object pointer die
6532                         StreamString s;
6533                         if (DWARFDebugInfoEntry::GetName (this, dwarf_cu, object_pointer_die_offset, s))
6534                         {
6535                             object_pointer_name.assign(s.GetData());
6536                         }
6537                     }
6538 
6539                     DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6540 
6541                     ClangASTType return_clang_type;
6542                     Type *func_type = NULL;
6543 
6544                     if (type_die_offset != DW_INVALID_OFFSET)
6545                         func_type = ResolveTypeUID(type_die_offset);
6546 
6547                     if (func_type)
6548                         return_clang_type = func_type->GetClangForwardType();
6549                     else
6550                         return_clang_type = ast.GetBasicType(eBasicTypeVoid);
6551 
6552 
6553                     std::vector<ClangASTType> function_param_types;
6554                     std::vector<clang::ParmVarDecl*> function_param_decls;
6555 
6556                     // Parse the function children for the parameters
6557 
6558                     const DWARFDebugInfoEntry *decl_ctx_die = NULL;
6559                     clang::DeclContext *containing_decl_ctx = GetClangDeclContextContainingDIE (dwarf_cu, die, &decl_ctx_die);
6560                     const clang::Decl::Kind containing_decl_kind = containing_decl_ctx->getDeclKind();
6561 
6562                     const bool is_cxx_method = DeclKindIsCXXClass (containing_decl_kind);
6563                     // Start off static. This will be set to false in ParseChildParameters(...)
6564                     // if we find a "this" parameters as the first parameter
6565                     if (is_cxx_method)
6566                         is_static = true;
6567 
6568                     if (die->HasChildren())
6569                     {
6570                         bool skip_artificial = true;
6571                         ParseChildParameters (sc,
6572                                               containing_decl_ctx,
6573                                               dwarf_cu,
6574                                               die,
6575                                               skip_artificial,
6576                                               is_static,
6577                                               is_variadic,
6578                                               function_param_types,
6579                                               function_param_decls,
6580                                               type_quals);
6581                     }
6582 
6583                     // clang_type will get the function prototype clang type after this call
6584                     clang_type = ast.CreateFunctionType (return_clang_type,
6585                                                          function_param_types.data(),
6586                                                          function_param_types.size(),
6587                                                          is_variadic,
6588                                                          type_quals);
6589 
6590                     bool ignore_containing_context = false;
6591 
6592                     if (type_name_cstr)
6593                     {
6594                         bool type_handled = false;
6595                         if (tag == DW_TAG_subprogram)
6596                         {
6597                             ObjCLanguageRuntime::MethodName objc_method (type_name_cstr, true);
6598                             if (objc_method.IsValid(true))
6599                             {
6600                                 ClangASTType class_opaque_type;
6601                                 ConstString class_name(objc_method.GetClassName());
6602                                 if (class_name)
6603                                 {
6604                                     TypeSP complete_objc_class_type_sp (FindCompleteObjCDefinitionTypeForDIE (NULL, class_name, false));
6605 
6606                                     if (complete_objc_class_type_sp)
6607                                     {
6608                                         ClangASTType type_clang_forward_type = complete_objc_class_type_sp->GetClangForwardType();
6609                                         if (type_clang_forward_type.IsObjCObjectOrInterfaceType ())
6610                                             class_opaque_type = type_clang_forward_type;
6611                                     }
6612                                 }
6613 
6614                                 if (class_opaque_type)
6615                                 {
6616                                     // If accessibility isn't set to anything valid, assume public for
6617                                     // now...
6618                                     if (accessibility == eAccessNone)
6619                                         accessibility = eAccessPublic;
6620 
6621                                     clang::ObjCMethodDecl *objc_method_decl = class_opaque_type.AddMethodToObjCObjectType (type_name_cstr,
6622                                                                                                                            clang_type,
6623                                                                                                                            accessibility,
6624                                                                                                                            is_artificial);
6625                                     type_handled = objc_method_decl != NULL;
6626                                     if (type_handled)
6627                                     {
6628                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(objc_method_decl), die);
6629                                         GetClangASTContext().SetMetadataAsUserID (objc_method_decl, MakeUserID(die->GetOffset()));
6630                                     }
6631                                     else
6632                                     {
6633                                         GetObjectFile()->GetModule()->ReportError ("{0x%8.8x}: invalid Objective-C method 0x%4.4x (%s), please file a bug and attach the file at the start of this error message",
6634                                                                                    die->GetOffset(),
6635                                                                                    tag,
6636                                                                                    DW_TAG_value_to_name(tag));
6637                                     }
6638                                 }
6639                             }
6640                             else if (is_cxx_method)
6641                             {
6642                                 // Look at the parent of this DIE and see if is is
6643                                 // a class or struct and see if this is actually a
6644                                 // C++ method
6645                                 Type *class_type = ResolveType (dwarf_cu, decl_ctx_die);
6646                                 if (class_type)
6647                                 {
6648                                     if (class_type->GetID() != MakeUserID(decl_ctx_die->GetOffset()))
6649                                     {
6650                                         // We uniqued the parent class of this function to another class
6651                                         // so we now need to associate all dies under "decl_ctx_die" to
6652                                         // DIEs in the DIE for "class_type"...
6653                                         SymbolFileDWARF *class_symfile = NULL;
6654                                         DWARFCompileUnitSP class_type_cu_sp;
6655                                         const DWARFDebugInfoEntry *class_type_die = NULL;
6656 
6657                                         SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile();
6658                                         if (debug_map_symfile)
6659                                         {
6660                                             class_symfile = debug_map_symfile->GetSymbolFileByOSOIndex(SymbolFileDWARFDebugMap::GetOSOIndexFromUserID(class_type->GetID()));
6661                                             class_type_die = class_symfile->DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6662                                         }
6663                                         else
6664                                         {
6665                                             class_symfile = this;
6666                                             class_type_die = DebugInfo()->GetDIEPtr(class_type->GetID(), &class_type_cu_sp);
6667                                         }
6668                                         if (class_type_die)
6669                                         {
6670                                             DWARFDIECollection failures;
6671 
6672                                             CopyUniqueClassMethodTypes (class_symfile,
6673                                                                         class_type,
6674                                                                         class_type_cu_sp.get(),
6675                                                                         class_type_die,
6676                                                                         dwarf_cu,
6677                                                                         decl_ctx_die,
6678                                                                         failures);
6679 
6680                                             // FIXME do something with these failures that's smarter than
6681                                             // just dropping them on the ground.  Unfortunately classes don't
6682                                             // like having stuff added to them after their definitions are
6683                                             // complete...
6684 
6685                                             type_ptr = m_die_to_type[die];
6686                                             if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6687                                             {
6688                                                 type_sp = type_ptr->shared_from_this();
6689                                                 break;
6690                                             }
6691                                         }
6692                                     }
6693 
6694                                     if (specification_die_offset != DW_INVALID_OFFSET)
6695                                     {
6696                                         // We have a specification which we are going to base our function
6697                                         // prototype off of, so we need this type to be completed so that the
6698                                         // m_die_to_decl_ctx for the method in the specification has a valid
6699                                         // clang decl context.
6700                                         class_type->GetClangForwardType();
6701                                         // If we have a specification, then the function type should have been
6702                                         // made with the specification and not with this die.
6703                                         DWARFCompileUnitSP spec_cu_sp;
6704                                         const DWARFDebugInfoEntry* spec_die = DebugInfo()->GetDIEPtr(specification_die_offset, &spec_cu_sp);
6705                                         clang::DeclContext *spec_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, spec_die);
6706                                         if (spec_clang_decl_ctx)
6707                                         {
6708                                             LinkDeclContextToDIE(spec_clang_decl_ctx, die);
6709                                         }
6710                                         else
6711                                         {
6712                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_specification(0x%8.8x) has no decl\n",
6713                                                                                          MakeUserID(die->GetOffset()),
6714                                                                                          specification_die_offset);
6715                                         }
6716                                         type_handled = true;
6717                                     }
6718                                     else if (abstract_origin_die_offset != DW_INVALID_OFFSET)
6719                                     {
6720                                         // We have a specification which we are going to base our function
6721                                         // prototype off of, so we need this type to be completed so that the
6722                                         // m_die_to_decl_ctx for the method in the abstract origin has a valid
6723                                         // clang decl context.
6724                                         class_type->GetClangForwardType();
6725 
6726                                         DWARFCompileUnitSP abs_cu_sp;
6727                                         const DWARFDebugInfoEntry* abs_die = DebugInfo()->GetDIEPtr(abstract_origin_die_offset, &abs_cu_sp);
6728                                         clang::DeclContext *abs_clang_decl_ctx = GetClangDeclContextForDIE (sc, dwarf_cu, abs_die);
6729                                         if (abs_clang_decl_ctx)
6730                                         {
6731                                             LinkDeclContextToDIE (abs_clang_decl_ctx, die);
6732                                         }
6733                                         else
6734                                         {
6735                                             GetObjectFile()->GetModule()->ReportWarning ("0x%8.8" PRIx64 ": DW_AT_abstract_origin(0x%8.8x) has no decl\n",
6736                                                                                          MakeUserID(die->GetOffset()),
6737                                                                                          abstract_origin_die_offset);
6738                                         }
6739                                         type_handled = true;
6740                                     }
6741                                     else
6742                                     {
6743                                         ClangASTType class_opaque_type = class_type->GetClangForwardType();
6744                                         if (class_opaque_type.IsCXXClassType ())
6745                                         {
6746                                             if (class_opaque_type.IsBeingDefined ())
6747                                             {
6748                                                 // Neither GCC 4.2 nor clang++ currently set a valid accessibility
6749                                                 // in the DWARF for C++ methods... Default to public for now...
6750                                                 if (accessibility == eAccessNone)
6751                                                     accessibility = eAccessPublic;
6752 
6753                                                 if (!is_static && !die->HasChildren())
6754                                                 {
6755                                                     // We have a C++ member function with no children (this pointer!)
6756                                                     // and clang will get mad if we try and make a function that isn't
6757                                                     // well formed in the DWARF, so we will just skip it...
6758                                                     type_handled = true;
6759                                                 }
6760                                                 else
6761                                                 {
6762                                                     clang::CXXMethodDecl *cxx_method_decl;
6763                                                     // REMOVE THE CRASH DESCRIPTION BELOW
6764                                                     Host::SetCrashDescriptionWithFormat ("SymbolFileDWARF::ParseType() is adding a method %s to class %s in DIE 0x%8.8" PRIx64 " from %s",
6765                                                                                          type_name_cstr,
6766                                                                                          class_type->GetName().GetCString(),
6767                                                                                          MakeUserID(die->GetOffset()),
6768                                                                                          m_obj_file->GetFileSpec().GetPath().c_str());
6769 
6770                                                     const bool is_attr_used = false;
6771 
6772                                                     cxx_method_decl = class_opaque_type.AddMethodToCXXRecordType (type_name_cstr,
6773                                                                                                                   clang_type,
6774                                                                                                                   accessibility,
6775                                                                                                                   is_virtual,
6776                                                                                                                   is_static,
6777                                                                                                                   is_inline,
6778                                                                                                                   is_explicit,
6779                                                                                                                   is_attr_used,
6780                                                                                                                   is_artificial);
6781 
6782                                                     type_handled = cxx_method_decl != NULL;
6783 
6784                                                     if (type_handled)
6785                                                     {
6786                                                         LinkDeclContextToDIE(ClangASTContext::GetAsDeclContext(cxx_method_decl), die);
6787 
6788                                                         Host::SetCrashDescription (NULL);
6789 
6790 
6791                                                         ClangASTMetadata metadata;
6792                                                         metadata.SetUserID(MakeUserID(die->GetOffset()));
6793 
6794                                                         if (!object_pointer_name.empty())
6795                                                         {
6796                                                             metadata.SetObjectPtrName(object_pointer_name.c_str());
6797                                                             if (log)
6798                                                                 log->Printf ("Setting object pointer name: %s on method object %p.\n",
6799                                                                              object_pointer_name.c_str(),
6800                                                                              static_cast<void*>(cxx_method_decl));
6801                                                         }
6802                                                         GetClangASTContext().SetMetadata (cxx_method_decl, metadata);
6803                                                     }
6804                                                     else
6805                                                     {
6806                                                         ignore_containing_context = true;
6807                                                     }
6808                                                 }
6809                                             }
6810                                             else
6811                                             {
6812                                                 // We were asked to parse the type for a method in a class, yet the
6813                                                 // class hasn't been asked to complete itself through the
6814                                                 // clang::ExternalASTSource protocol, so we need to just have the
6815                                                 // class complete itself and do things the right way, then our
6816                                                 // DIE should then have an entry in the m_die_to_type map. First
6817                                                 // we need to modify the m_die_to_type so it doesn't think we are
6818                                                 // trying to parse this DIE anymore...
6819                                                 m_die_to_type[die] = NULL;
6820 
6821                                                 // Now we get the full type to force our class type to complete itself
6822                                                 // using the clang::ExternalASTSource protocol which will parse all
6823                                                 // base classes and all methods (including the method for this DIE).
6824                                                 class_type->GetClangFullType();
6825 
6826                                                 // The type for this DIE should have been filled in the function call above
6827                                                 type_ptr = m_die_to_type[die];
6828                                                 if (type_ptr && type_ptr != DIE_IS_BEING_PARSED)
6829                                                 {
6830                                                     type_sp = type_ptr->shared_from_this();
6831                                                     break;
6832                                                 }
6833 
6834                                                 // FIXME This is fixing some even uglier behavior but we really need to
6835                                                 // uniq the methods of each class as well as the class itself.
6836                                                 // <rdar://problem/11240464>
6837                                                 type_handled = true;
6838                                             }
6839                                         }
6840                                     }
6841                                 }
6842                             }
6843                         }
6844 
6845                         if (!type_handled)
6846                         {
6847                             // We just have a function that isn't part of a class
6848                             clang::FunctionDecl *function_decl = ast.CreateFunctionDeclaration (ignore_containing_context ? GetClangASTContext().GetTranslationUnitDecl() : containing_decl_ctx,
6849                                                                                                 type_name_cstr,
6850                                                                                                 clang_type,
6851                                                                                                 storage,
6852                                                                                                 is_inline);
6853 
6854 //                            if (template_param_infos.GetSize() > 0)
6855 //                            {
6856 //                                clang::FunctionTemplateDecl *func_template_decl = ast.CreateFunctionTemplateDecl (containing_decl_ctx,
6857 //                                                                                                                  function_decl,
6858 //                                                                                                                  type_name_cstr,
6859 //                                                                                                                  template_param_infos);
6860 //
6861 //                                ast.CreateFunctionTemplateSpecializationInfo (function_decl,
6862 //                                                                              func_template_decl,
6863 //                                                                              template_param_infos);
6864 //                            }
6865                             // Add the decl to our DIE to decl context map
6866                             assert (function_decl);
6867                             LinkDeclContextToDIE(function_decl, die);
6868                             if (!function_param_decls.empty())
6869                                 ast.SetFunctionParameters (function_decl,
6870                                                            &function_param_decls.front(),
6871                                                            function_param_decls.size());
6872 
6873                             ClangASTMetadata metadata;
6874                             metadata.SetUserID(MakeUserID(die->GetOffset()));
6875 
6876                             if (!object_pointer_name.empty())
6877                             {
6878                                 metadata.SetObjectPtrName(object_pointer_name.c_str());
6879                                 if (log)
6880                                     log->Printf ("Setting object pointer name: %s on function object %p.",
6881                                                  object_pointer_name.c_str(),
6882                                                  static_cast<void*>(function_decl));
6883                             }
6884                             GetClangASTContext().SetMetadata (function_decl, metadata);
6885                         }
6886                     }
6887                     type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6888                                              this,
6889                                              type_name_const_str,
6890                                              0,
6891                                              NULL,
6892                                              LLDB_INVALID_UID,
6893                                              Type::eEncodingIsUID,
6894                                              &decl,
6895                                              clang_type,
6896                                              Type::eResolveStateFull));
6897                     assert(type_sp.get());
6898                 }
6899                 break;
6900 
6901             case DW_TAG_array_type:
6902                 {
6903                     // Set a bit that lets us know that we are currently parsing this
6904                     m_die_to_type[die] = DIE_IS_BEING_PARSED;
6905 
6906                     lldb::user_id_t type_die_offset = DW_INVALID_OFFSET;
6907                     int64_t first_index = 0;
6908                     uint32_t byte_stride = 0;
6909                     uint32_t bit_stride = 0;
6910                     bool is_vector = false;
6911                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
6912 
6913                     if (num_attributes > 0)
6914                     {
6915                         uint32_t i;
6916                         for (i=0; i<num_attributes; ++i)
6917                         {
6918                             attr = attributes.AttributeAtIndex(i);
6919                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
6920                             {
6921                                 switch (attr)
6922                                 {
6923                                 case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
6924                                 case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
6925                                 case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
6926                                 case DW_AT_name:
6927                                     type_name_cstr = form_value.AsCString(&get_debug_str_data());
6928                                     type_name_const_str.SetCString(type_name_cstr);
6929                                     break;
6930 
6931                                 case DW_AT_type:            type_die_offset = form_value.Reference(); break;
6932                                 case DW_AT_byte_size:       break; // byte_size = form_value.Unsigned(); break;
6933                                 case DW_AT_byte_stride:     byte_stride = form_value.Unsigned(); break;
6934                                 case DW_AT_bit_stride:      bit_stride = form_value.Unsigned(); break;
6935                                 case DW_AT_GNU_vector:      is_vector = form_value.Boolean(); break;
6936                                 case DW_AT_accessibility:   break; // accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
6937                                 case DW_AT_declaration:     break; // is_forward_declaration = form_value.Boolean(); break;
6938                                 case DW_AT_allocated:
6939                                 case DW_AT_associated:
6940                                 case DW_AT_data_location:
6941                                 case DW_AT_description:
6942                                 case DW_AT_ordering:
6943                                 case DW_AT_start_scope:
6944                                 case DW_AT_visibility:
6945                                 case DW_AT_specification:
6946                                 case DW_AT_abstract_origin:
6947                                 case DW_AT_sibling:
6948                                     break;
6949                                 }
6950                             }
6951                         }
6952 
6953                         DEBUG_PRINTF ("0x%8.8" PRIx64 ": %s (\"%s\")\n", MakeUserID(die->GetOffset()), DW_TAG_value_to_name(tag), type_name_cstr);
6954 
6955                         Type *element_type = ResolveTypeUID(type_die_offset);
6956 
6957                         if (element_type)
6958                         {
6959                             std::vector<uint64_t> element_orders;
6960                             ParseChildArrayInfo(sc, dwarf_cu, die, first_index, element_orders, byte_stride, bit_stride);
6961                             if (byte_stride == 0 && bit_stride == 0)
6962                                 byte_stride = element_type->GetByteSize();
6963                             ClangASTType array_element_type = element_type->GetClangForwardType();
6964                             uint64_t array_element_bit_stride = byte_stride * 8 + bit_stride;
6965                             if (element_orders.size() > 0)
6966                             {
6967                                 uint64_t num_elements = 0;
6968                                 std::vector<uint64_t>::const_reverse_iterator pos;
6969                                 std::vector<uint64_t>::const_reverse_iterator end = element_orders.rend();
6970                                 for (pos = element_orders.rbegin(); pos != end; ++pos)
6971                                 {
6972                                     num_elements = *pos;
6973                                     clang_type = ast.CreateArrayType (array_element_type,
6974                                                                       num_elements,
6975                                                                       is_vector);
6976                                     array_element_type = clang_type;
6977                                     array_element_bit_stride = num_elements ?
6978                                                                array_element_bit_stride * num_elements :
6979                                                                array_element_bit_stride;
6980                                 }
6981                             }
6982                             else
6983                             {
6984                                 clang_type = ast.CreateArrayType (array_element_type, 0, is_vector);
6985                             }
6986                             ConstString empty_name;
6987                             type_sp.reset( new Type (MakeUserID(die->GetOffset()),
6988                                                      this,
6989                                                      empty_name,
6990                                                      array_element_bit_stride / 8,
6991                                                      NULL,
6992                                                      type_die_offset,
6993                                                      Type::eEncodingIsUID,
6994                                                      &decl,
6995                                                      clang_type,
6996                                                      Type::eResolveStateFull));
6997                             type_sp->SetEncodingType (element_type);
6998                         }
6999                     }
7000                 }
7001                 break;
7002 
7003             case DW_TAG_ptr_to_member_type:
7004                 {
7005                     dw_offset_t type_die_offset = DW_INVALID_OFFSET;
7006                     dw_offset_t containing_type_die_offset = DW_INVALID_OFFSET;
7007 
7008                     const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
7009 
7010                     if (num_attributes > 0) {
7011                         uint32_t i;
7012                         for (i=0; i<num_attributes; ++i)
7013                         {
7014                             attr = attributes.AttributeAtIndex(i);
7015                             if (attributes.ExtractFormValueAtIndex(this, i, form_value))
7016                             {
7017                                 switch (attr)
7018                                 {
7019                                     case DW_AT_type:
7020                                         type_die_offset = form_value.Reference(); break;
7021                                     case DW_AT_containing_type:
7022                                         containing_type_die_offset = form_value.Reference(); break;
7023                                 }
7024                             }
7025                         }
7026 
7027                         Type *pointee_type = ResolveTypeUID(type_die_offset);
7028                         Type *class_type = ResolveTypeUID(containing_type_die_offset);
7029 
7030                         ClangASTType pointee_clang_type = pointee_type->GetClangForwardType();
7031                         ClangASTType class_clang_type = class_type->GetClangLayoutType();
7032 
7033                         clang_type = pointee_clang_type.CreateMemberPointerType(class_clang_type);
7034 
7035                         byte_size = clang_type.GetByteSize(nullptr);
7036 
7037                         type_sp.reset( new Type (MakeUserID(die->GetOffset()),
7038                                                  this,
7039                                                  type_name_const_str,
7040                                                  byte_size,
7041                                                  NULL,
7042                                                  LLDB_INVALID_UID,
7043                                                  Type::eEncodingIsUID,
7044                                                  NULL,
7045                                                  clang_type,
7046                                                  Type::eResolveStateForward));
7047                     }
7048 
7049                     break;
7050                 }
7051             default:
7052                 GetObjectFile()->GetModule()->ReportError ("{0x%8.8x}: unhandled type tag 0x%4.4x (%s), please file a bug and attach the file at the start of this error message",
7053                                                            die->GetOffset(),
7054                                                            tag,
7055                                                            DW_TAG_value_to_name(tag));
7056                 break;
7057             }
7058 
7059             if (type_sp.get())
7060             {
7061                 const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
7062                 dw_tag_t sc_parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7063 
7064                 SymbolContextScope * symbol_context_scope = NULL;
7065                 if (sc_parent_tag == DW_TAG_compile_unit)
7066                 {
7067                     symbol_context_scope = sc.comp_unit;
7068                 }
7069                 else if (sc.function != NULL && sc_parent_die)
7070                 {
7071                     symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7072                     if (symbol_context_scope == NULL)
7073                         symbol_context_scope = sc.function;
7074                 }
7075 
7076                 if (symbol_context_scope != NULL)
7077                 {
7078                     type_sp->SetSymbolContextScope(symbol_context_scope);
7079                 }
7080 
7081                 // We are ready to put this type into the uniqued list up at the module level
7082                 type_list->Insert (type_sp);
7083 
7084                 m_die_to_type[die] = type_sp.get();
7085             }
7086         }
7087         else if (type_ptr != DIE_IS_BEING_PARSED)
7088         {
7089             type_sp = type_ptr->shared_from_this();
7090         }
7091     }
7092     return type_sp;
7093 }
7094 
7095 size_t
7096 SymbolFileDWARF::ParseTypes
7097 (
7098     const SymbolContext& sc,
7099     DWARFCompileUnit* dwarf_cu,
7100     const DWARFDebugInfoEntry *die,
7101     bool parse_siblings,
7102     bool parse_children
7103 )
7104 {
7105     size_t types_added = 0;
7106     while (die != NULL)
7107     {
7108         bool type_is_new = false;
7109         if (ParseType(sc, dwarf_cu, die, &type_is_new).get())
7110         {
7111             if (type_is_new)
7112                 ++types_added;
7113         }
7114 
7115         if (parse_children && die->HasChildren())
7116         {
7117             if (die->Tag() == DW_TAG_subprogram)
7118             {
7119                 SymbolContext child_sc(sc);
7120                 child_sc.function = sc.comp_unit->FindFunctionByUID(MakeUserID(die->GetOffset())).get();
7121                 types_added += ParseTypes(child_sc, dwarf_cu, die->GetFirstChild(), true, true);
7122             }
7123             else
7124                 types_added += ParseTypes(sc, dwarf_cu, die->GetFirstChild(), true, true);
7125         }
7126 
7127         if (parse_siblings)
7128             die = die->GetSibling();
7129         else
7130             die = NULL;
7131     }
7132     return types_added;
7133 }
7134 
7135 
7136 size_t
7137 SymbolFileDWARF::ParseFunctionBlocks (const SymbolContext &sc)
7138 {
7139     assert(sc.comp_unit && sc.function);
7140     size_t functions_added = 0;
7141     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
7142     if (dwarf_cu)
7143     {
7144         dw_offset_t function_die_offset = sc.function->GetID();
7145         const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(function_die_offset);
7146         if (function_die)
7147         {
7148             ParseFunctionBlocks(sc, &sc.function->GetBlock (false), dwarf_cu, function_die, LLDB_INVALID_ADDRESS, 0);
7149         }
7150     }
7151 
7152     return functions_added;
7153 }
7154 
7155 
7156 size_t
7157 SymbolFileDWARF::ParseTypes (const SymbolContext &sc)
7158 {
7159     // At least a compile unit must be valid
7160     assert(sc.comp_unit);
7161     size_t types_added = 0;
7162     DWARFCompileUnit* dwarf_cu = GetDWARFCompileUnit(sc.comp_unit);
7163     if (dwarf_cu)
7164     {
7165         if (sc.function)
7166         {
7167             dw_offset_t function_die_offset = sc.function->GetID();
7168             const DWARFDebugInfoEntry *func_die = dwarf_cu->GetDIEPtr(function_die_offset);
7169             if (func_die && func_die->HasChildren())
7170             {
7171                 types_added = ParseTypes(sc, dwarf_cu, func_die->GetFirstChild(), true, true);
7172             }
7173         }
7174         else
7175         {
7176             const DWARFDebugInfoEntry *dwarf_cu_die = dwarf_cu->DIE();
7177             if (dwarf_cu_die && dwarf_cu_die->HasChildren())
7178             {
7179                 types_added = ParseTypes(sc, dwarf_cu, dwarf_cu_die->GetFirstChild(), true, true);
7180             }
7181         }
7182     }
7183 
7184     return types_added;
7185 }
7186 
7187 size_t
7188 SymbolFileDWARF::ParseVariablesForContext (const SymbolContext& sc)
7189 {
7190     if (sc.comp_unit != NULL)
7191     {
7192         DWARFDebugInfo* info = DebugInfo();
7193         if (info == NULL)
7194             return 0;
7195 
7196         if (sc.function)
7197         {
7198             DWARFCompileUnit* dwarf_cu = info->GetCompileUnitContainingDIE(sc.function->GetID()).get();
7199 
7200             if (dwarf_cu == NULL)
7201                 return 0;
7202 
7203             const DWARFDebugInfoEntry *function_die = dwarf_cu->GetDIEPtr(sc.function->GetID());
7204 
7205             dw_addr_t func_lo_pc = function_die->GetAttributeValueAsUnsigned (this, dwarf_cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
7206             if (func_lo_pc != LLDB_INVALID_ADDRESS)
7207             {
7208                 const size_t num_variables = ParseVariables(sc, dwarf_cu, func_lo_pc, function_die->GetFirstChild(), true, true);
7209 
7210                 // Let all blocks know they have parse all their variables
7211                 sc.function->GetBlock (false).SetDidParseVariables (true, true);
7212                 return num_variables;
7213             }
7214         }
7215         else if (sc.comp_unit)
7216         {
7217             DWARFCompileUnit* dwarf_cu = info->GetCompileUnit(sc.comp_unit->GetID()).get();
7218 
7219             if (dwarf_cu == NULL)
7220                 return 0;
7221 
7222             uint32_t vars_added = 0;
7223             VariableListSP variables (sc.comp_unit->GetVariableList(false));
7224 
7225             if (variables.get() == NULL)
7226             {
7227                 variables.reset(new VariableList());
7228                 sc.comp_unit->SetVariableList(variables);
7229 
7230                 DWARFCompileUnit* match_dwarf_cu = NULL;
7231                 const DWARFDebugInfoEntry* die = NULL;
7232                 DIEArray die_offsets;
7233                 if (m_using_apple_tables)
7234                 {
7235                     if (m_apple_names_ap.get())
7236                     {
7237                         DWARFMappedHash::DIEInfoArray hash_data_array;
7238                         if (m_apple_names_ap->AppendAllDIEsInRange (dwarf_cu->GetOffset(),
7239                                                                     dwarf_cu->GetNextCompileUnitOffset(),
7240                                                                     hash_data_array))
7241                         {
7242                             DWARFMappedHash::ExtractDIEArray (hash_data_array, die_offsets);
7243                         }
7244                     }
7245                 }
7246                 else
7247                 {
7248                     // Index if we already haven't to make sure the compile units
7249                     // get indexed and make their global DIE index list
7250                     if (!m_indexed)
7251                         Index ();
7252 
7253                     m_global_index.FindAllEntriesForCompileUnit (dwarf_cu->GetOffset(),
7254                                                                  dwarf_cu->GetNextCompileUnitOffset(),
7255                                                                  die_offsets);
7256                 }
7257 
7258                 const size_t num_matches = die_offsets.size();
7259                 if (num_matches)
7260                 {
7261                     DWARFDebugInfo* debug_info = DebugInfo();
7262                     for (size_t i=0; i<num_matches; ++i)
7263                     {
7264                         const dw_offset_t die_offset = die_offsets[i];
7265                         die = debug_info->GetDIEPtrWithCompileUnitHint (die_offset, &match_dwarf_cu);
7266                         if (die)
7267                         {
7268                             VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, LLDB_INVALID_ADDRESS));
7269                             if (var_sp)
7270                             {
7271                                 variables->AddVariableIfUnique (var_sp);
7272                                 ++vars_added;
7273                             }
7274                         }
7275                         else
7276                         {
7277                             if (m_using_apple_tables)
7278                             {
7279                                 GetObjectFile()->GetModule()->ReportErrorIfModifyDetected ("the DWARF debug information has been modified (.apple_names accelerator table had bad die 0x%8.8x)\n", die_offset);
7280                             }
7281                         }
7282 
7283                     }
7284                 }
7285             }
7286             return vars_added;
7287         }
7288     }
7289     return 0;
7290 }
7291 
7292 
7293 VariableSP
7294 SymbolFileDWARF::ParseVariableDIE
7295 (
7296     const SymbolContext& sc,
7297     DWARFCompileUnit* dwarf_cu,
7298     const DWARFDebugInfoEntry *die,
7299     const lldb::addr_t func_low_pc
7300 )
7301 {
7302     VariableSP var_sp (m_die_to_variable_sp[die]);
7303     if (var_sp)
7304         return var_sp;  // Already been parsed!
7305 
7306     const dw_tag_t tag = die->Tag();
7307     ModuleSP module = GetObjectFile()->GetModule();
7308 
7309     if ((tag == DW_TAG_variable) ||
7310         (tag == DW_TAG_constant) ||
7311         (tag == DW_TAG_formal_parameter && sc.function))
7312     {
7313         DWARFDebugInfoEntry::Attributes attributes;
7314         const size_t num_attributes = die->GetAttributes(this, dwarf_cu, NULL, attributes);
7315         if (num_attributes > 0)
7316         {
7317             const char *name = NULL;
7318             const char *mangled = NULL;
7319             Declaration decl;
7320             uint32_t i;
7321             lldb::user_id_t type_uid = LLDB_INVALID_UID;
7322             DWARFExpression location;
7323             bool is_external = false;
7324             bool is_artificial = false;
7325             bool location_is_const_value_data = false;
7326             bool has_explicit_location = false;
7327             DWARFFormValue const_value;
7328             //AccessType accessibility = eAccessNone;
7329 
7330             for (i=0; i<num_attributes; ++i)
7331             {
7332                 dw_attr_t attr = attributes.AttributeAtIndex(i);
7333                 DWARFFormValue form_value;
7334 
7335                 if (attributes.ExtractFormValueAtIndex(this, i, form_value))
7336                 {
7337                     switch (attr)
7338                     {
7339                     case DW_AT_decl_file:   decl.SetFile(sc.comp_unit->GetSupportFiles().GetFileSpecAtIndex(form_value.Unsigned())); break;
7340                     case DW_AT_decl_line:   decl.SetLine(form_value.Unsigned()); break;
7341                     case DW_AT_decl_column: decl.SetColumn(form_value.Unsigned()); break;
7342                     case DW_AT_name:        name = form_value.AsCString(&get_debug_str_data()); break;
7343                     case DW_AT_linkage_name:
7344                     case DW_AT_MIPS_linkage_name: mangled = form_value.AsCString(&get_debug_str_data()); break;
7345                     case DW_AT_type:        type_uid = form_value.Reference(); break;
7346                     case DW_AT_external:    is_external = form_value.Boolean(); break;
7347                     case DW_AT_const_value:
7348                         // If we have already found a DW_AT_location attribute, ignore this attribute.
7349                         if (!has_explicit_location)
7350                         {
7351                             location_is_const_value_data = true;
7352                             // The constant value will be either a block, a data value or a string.
7353                             const DWARFDataExtractor& debug_info_data = get_debug_info_data();
7354                             if (DWARFFormValue::IsBlockForm(form_value.Form()))
7355                             {
7356                                 // Retrieve the value as a block expression.
7357                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7358                                 uint32_t block_length = form_value.Unsigned();
7359                                 location.CopyOpcodeData(module, debug_info_data, block_offset, block_length);
7360                             }
7361                             else if (DWARFFormValue::IsDataForm(form_value.Form()))
7362                             {
7363                                 // Retrieve the value as a data expression.
7364                                 const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (attributes.CompileUnitAtIndex(i)->GetAddressByteSize(), attributes.CompileUnitAtIndex(i)->IsDWARF64());
7365                                 uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7366                                 uint32_t data_length = fixed_form_sizes[form_value.Form()];
7367                                 if (data_length == 0)
7368                                 {
7369                                     const uint8_t *data_pointer = form_value.BlockData();
7370                                     if (data_pointer)
7371                                     {
7372                                         form_value.Unsigned();
7373                                     }
7374                                     else if (DWARFFormValue::IsDataForm(form_value.Form()))
7375                                     {
7376                                         // we need to get the byte size of the type later after we create the variable
7377                                         const_value = form_value;
7378                                     }
7379                                 }
7380                                 else
7381                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
7382                             }
7383                             else
7384                             {
7385                                 // Retrieve the value as a string expression.
7386                                 if (form_value.Form() == DW_FORM_strp)
7387                                 {
7388                                     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (attributes.CompileUnitAtIndex(i)->GetAddressByteSize(), attributes.CompileUnitAtIndex(i)->IsDWARF64());
7389                                     uint32_t data_offset = attributes.DIEOffsetAtIndex(i);
7390                                     uint32_t data_length = fixed_form_sizes[form_value.Form()];
7391                                     location.CopyOpcodeData(module, debug_info_data, data_offset, data_length);
7392                                 }
7393                                 else
7394                                 {
7395                                     const char *str = form_value.AsCString(&debug_info_data);
7396                                     uint32_t string_offset = str - (const char *)debug_info_data.GetDataStart();
7397                                     uint32_t string_length = strlen(str) + 1;
7398                                     location.CopyOpcodeData(module, debug_info_data, string_offset, string_length);
7399                                 }
7400                             }
7401                         }
7402                         break;
7403                     case DW_AT_location:
7404                         {
7405                             location_is_const_value_data = false;
7406                             has_explicit_location = true;
7407                             if (form_value.BlockData())
7408                             {
7409                                 const DWARFDataExtractor& debug_info_data = get_debug_info_data();
7410 
7411                                 uint32_t block_offset = form_value.BlockData() - debug_info_data.GetDataStart();
7412                                 uint32_t block_length = form_value.Unsigned();
7413                                 location.CopyOpcodeData(module, get_debug_info_data(), block_offset, block_length);
7414                             }
7415                             else
7416                             {
7417                                 const DWARFDataExtractor&    debug_loc_data = get_debug_loc_data();
7418                                 const dw_offset_t debug_loc_offset = form_value.Unsigned();
7419 
7420                                 size_t loc_list_length = DWARFLocationList::Size(debug_loc_data, debug_loc_offset);
7421                                 if (loc_list_length > 0)
7422                                 {
7423                                     location.CopyOpcodeData(module, debug_loc_data, debug_loc_offset, loc_list_length);
7424                                     assert (func_low_pc != LLDB_INVALID_ADDRESS);
7425                                     location.SetLocationListSlide (func_low_pc - attributes.CompileUnitAtIndex(i)->GetBaseAddress());
7426                                 }
7427                             }
7428                         }
7429                         break;
7430 
7431                     case DW_AT_artificial:      is_artificial = form_value.Boolean(); break;
7432                     case DW_AT_accessibility:   break; //accessibility = DW_ACCESS_to_AccessType(form_value.Unsigned()); break;
7433                     case DW_AT_declaration:
7434                     case DW_AT_description:
7435                     case DW_AT_endianity:
7436                     case DW_AT_segment:
7437                     case DW_AT_start_scope:
7438                     case DW_AT_visibility:
7439                     default:
7440                     case DW_AT_abstract_origin:
7441                     case DW_AT_sibling:
7442                     case DW_AT_specification:
7443                         break;
7444                     }
7445                 }
7446             }
7447 
7448             ValueType scope = eValueTypeInvalid;
7449 
7450             const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(die);
7451             dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7452             SymbolContextScope * symbol_context_scope = NULL;
7453 
7454             if (!mangled)
7455             {
7456                 // LLDB relies on the mangled name (DW_TAG_linkage_name or DW_AT_MIPS_linkage_name) to
7457                 // generate fully qualified names of global variables with commands like "frame var j".
7458                 // For example, if j were an int variable holding a value 4 and declared in a namespace
7459                 // B which in turn is contained in a namespace A, the command "frame var j" returns
7460                 // "(int) A::B::j = 4". If the compiler does not emit a linkage name, we should be able
7461                 // to generate a fully qualified name from the declaration context.
7462                 if (die->GetParent()->Tag() == DW_TAG_compile_unit &&
7463                     LanguageRuntime::LanguageIsCPlusPlus(dwarf_cu->GetLanguageType()))
7464                 {
7465                     DWARFDeclContext decl_ctx;
7466 
7467                     die->GetDWARFDeclContext(this, dwarf_cu, decl_ctx);
7468                     mangled = decl_ctx.GetQualifiedNameAsConstString().GetCString();
7469                 }
7470             }
7471 
7472             // DWARF doesn't specify if a DW_TAG_variable is a local, global
7473             // or static variable, so we have to do a little digging by
7474             // looking at the location of a variable to see if it contains
7475             // a DW_OP_addr opcode _somewhere_ in the definition. I say
7476             // somewhere because clang likes to combine small global variables
7477             // into the same symbol and have locations like:
7478             // DW_OP_addr(0x1000), DW_OP_constu(2), DW_OP_plus
7479             // So if we don't have a DW_TAG_formal_parameter, we can look at
7480             // the location to see if it contains a DW_OP_addr opcode, and
7481             // then we can correctly classify  our variables.
7482             if (tag == DW_TAG_formal_parameter)
7483                 scope = eValueTypeVariableArgument;
7484             else
7485             {
7486                 bool op_error = false;
7487                 // Check if the location has a DW_OP_addr with any address value...
7488                 lldb::addr_t location_DW_OP_addr = LLDB_INVALID_ADDRESS;
7489                 if (!location_is_const_value_data)
7490                 {
7491                     location_DW_OP_addr = location.GetLocation_DW_OP_addr (0, op_error);
7492                     if (op_error)
7493                     {
7494                         StreamString strm;
7495                         location.DumpLocationForAddress (&strm, eDescriptionLevelFull, 0, 0, NULL);
7496                         GetObjectFile()->GetModule()->ReportError ("0x%8.8x: %s has an invalid location: %s", die->GetOffset(), DW_TAG_value_to_name(die->Tag()), strm.GetString().c_str());
7497                     }
7498                 }
7499 
7500                 if (location_DW_OP_addr != LLDB_INVALID_ADDRESS)
7501                 {
7502                     if (is_external)
7503                         scope = eValueTypeVariableGlobal;
7504                     else
7505                         scope = eValueTypeVariableStatic;
7506 
7507 
7508                     SymbolFileDWARFDebugMap *debug_map_symfile = GetDebugMapSymfile ();
7509 
7510                     if (debug_map_symfile)
7511                     {
7512                         // When leaving the DWARF in the .o files on darwin,
7513                         // when we have a global variable that wasn't initialized,
7514                         // the .o file might not have allocated a virtual
7515                         // address for the global variable. In this case it will
7516                         // have created a symbol for the global variable
7517                         // that is undefined/data and external and the value will
7518                         // be the byte size of the variable. When we do the
7519                         // address map in SymbolFileDWARFDebugMap we rely on
7520                         // having an address, we need to do some magic here
7521                         // so we can get the correct address for our global
7522                         // variable. The address for all of these entries
7523                         // will be zero, and there will be an undefined symbol
7524                         // in this object file, and the executable will have
7525                         // a matching symbol with a good address. So here we
7526                         // dig up the correct address and replace it in the
7527                         // location for the variable, and set the variable's
7528                         // symbol context scope to be that of the main executable
7529                         // so the file address will resolve correctly.
7530                         bool linked_oso_file_addr = false;
7531                         if (is_external && location_DW_OP_addr == 0)
7532                         {
7533                             // we have a possible uninitialized extern global
7534                             ConstString const_name(mangled ? mangled : name);
7535                             ObjectFile *debug_map_objfile = debug_map_symfile->GetObjectFile();
7536                             if (debug_map_objfile)
7537                             {
7538                                 Symtab *debug_map_symtab = debug_map_objfile->GetSymtab();
7539                                 if (debug_map_symtab)
7540                                 {
7541                                     Symbol *exe_symbol = debug_map_symtab->FindFirstSymbolWithNameAndType (const_name,
7542                                                                                                            eSymbolTypeData,
7543                                                                                                            Symtab::eDebugYes,
7544                                                                                                            Symtab::eVisibilityExtern);
7545                                     if (exe_symbol)
7546                                     {
7547                                         if (exe_symbol->ValueIsAddress())
7548                                         {
7549                                             const addr_t exe_file_addr = exe_symbol->GetAddress().GetFileAddress();
7550                                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
7551                                             {
7552                                                 if (location.Update_DW_OP_addr (exe_file_addr))
7553                                                 {
7554                                                     linked_oso_file_addr = true;
7555                                                     symbol_context_scope = exe_symbol;
7556                                                 }
7557                                             }
7558                                         }
7559                                     }
7560                                 }
7561                             }
7562                         }
7563 
7564                         if (!linked_oso_file_addr)
7565                         {
7566                             // The DW_OP_addr is not zero, but it contains a .o file address which
7567                             // needs to be linked up correctly.
7568                             const lldb::addr_t exe_file_addr = debug_map_symfile->LinkOSOFileAddress(this, location_DW_OP_addr);
7569                             if (exe_file_addr != LLDB_INVALID_ADDRESS)
7570                             {
7571                                 // Update the file address for this variable
7572                                 location.Update_DW_OP_addr (exe_file_addr);
7573                             }
7574                             else
7575                             {
7576                                 // Variable didn't make it into the final executable
7577                                 return var_sp;
7578                             }
7579                         }
7580                     }
7581                 }
7582                 else
7583                 {
7584                     scope = eValueTypeVariableLocal;
7585                 }
7586             }
7587 
7588             if (symbol_context_scope == NULL)
7589             {
7590                 switch (parent_tag)
7591                 {
7592                 case DW_TAG_subprogram:
7593                 case DW_TAG_inlined_subroutine:
7594                 case DW_TAG_lexical_block:
7595                     if (sc.function)
7596                     {
7597                         symbol_context_scope = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7598                         if (symbol_context_scope == NULL)
7599                             symbol_context_scope = sc.function;
7600                     }
7601                     break;
7602 
7603                 default:
7604                     symbol_context_scope = sc.comp_unit;
7605                     break;
7606                 }
7607             }
7608 
7609             if (symbol_context_scope)
7610             {
7611                 SymbolFileTypeSP type_sp(new SymbolFileType(*this, type_uid));
7612 
7613                 if (const_value.Form() && type_sp && type_sp->GetType())
7614                     location.CopyOpcodeData(const_value.Unsigned(), type_sp->GetType()->GetByteSize(), dwarf_cu->GetAddressByteSize());
7615 
7616                 var_sp.reset (new Variable (MakeUserID(die->GetOffset()),
7617                                             name,
7618                                             mangled,
7619                                             type_sp,
7620                                             scope,
7621                                             symbol_context_scope,
7622                                             &decl,
7623                                             location,
7624                                             is_external,
7625                                             is_artificial));
7626 
7627                 var_sp->SetLocationIsConstantValueData (location_is_const_value_data);
7628             }
7629             else
7630             {
7631                 // Not ready to parse this variable yet. It might be a global
7632                 // or static variable that is in a function scope and the function
7633                 // in the symbol context wasn't filled in yet
7634                 return var_sp;
7635             }
7636         }
7637         // Cache var_sp even if NULL (the variable was just a specification or
7638         // was missing vital information to be able to be displayed in the debugger
7639         // (missing location due to optimization, etc)) so we don't re-parse
7640         // this DIE over and over later...
7641         m_die_to_variable_sp[die] = var_sp;
7642     }
7643     return var_sp;
7644 }
7645 
7646 
7647 const DWARFDebugInfoEntry *
7648 SymbolFileDWARF::FindBlockContainingSpecification (dw_offset_t func_die_offset,
7649                                                    dw_offset_t spec_block_die_offset,
7650                                                    DWARFCompileUnit **result_die_cu_handle)
7651 {
7652     // Give the concrete function die specified by "func_die_offset", find the
7653     // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7654     // to "spec_block_die_offset"
7655     DWARFDebugInfo* info = DebugInfo();
7656 
7657     const DWARFDebugInfoEntry *die = info->GetDIEPtrWithCompileUnitHint(func_die_offset, result_die_cu_handle);
7658     if (die)
7659     {
7660         assert (*result_die_cu_handle);
7661         return FindBlockContainingSpecification (*result_die_cu_handle, die, spec_block_die_offset, result_die_cu_handle);
7662     }
7663     return NULL;
7664 }
7665 
7666 
7667 const DWARFDebugInfoEntry *
7668 SymbolFileDWARF::FindBlockContainingSpecification(DWARFCompileUnit* dwarf_cu,
7669                                                   const DWARFDebugInfoEntry *die,
7670                                                   dw_offset_t spec_block_die_offset,
7671                                                   DWARFCompileUnit **result_die_cu_handle)
7672 {
7673     if (die)
7674     {
7675         switch (die->Tag())
7676         {
7677         case DW_TAG_subprogram:
7678         case DW_TAG_inlined_subroutine:
7679         case DW_TAG_lexical_block:
7680             {
7681                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_specification, DW_INVALID_OFFSET) == spec_block_die_offset)
7682                 {
7683                     *result_die_cu_handle = dwarf_cu;
7684                     return die;
7685                 }
7686 
7687                 if (die->GetAttributeValueAsReference (this, dwarf_cu, DW_AT_abstract_origin, DW_INVALID_OFFSET) == spec_block_die_offset)
7688                 {
7689                     *result_die_cu_handle = dwarf_cu;
7690                     return die;
7691                 }
7692             }
7693             break;
7694         }
7695 
7696         // Give the concrete function die specified by "func_die_offset", find the
7697         // concrete block whose DW_AT_specification or DW_AT_abstract_origin points
7698         // to "spec_block_die_offset"
7699         for (const DWARFDebugInfoEntry *child_die = die->GetFirstChild(); child_die != NULL; child_die = child_die->GetSibling())
7700         {
7701             const DWARFDebugInfoEntry *result_die = FindBlockContainingSpecification (dwarf_cu,
7702                                                                                       child_die,
7703                                                                                       spec_block_die_offset,
7704                                                                                       result_die_cu_handle);
7705             if (result_die)
7706                 return result_die;
7707         }
7708     }
7709 
7710     *result_die_cu_handle = NULL;
7711     return NULL;
7712 }
7713 
7714 size_t
7715 SymbolFileDWARF::ParseVariables
7716 (
7717     const SymbolContext& sc,
7718     DWARFCompileUnit* dwarf_cu,
7719     const lldb::addr_t func_low_pc,
7720     const DWARFDebugInfoEntry *orig_die,
7721     bool parse_siblings,
7722     bool parse_children,
7723     VariableList* cc_variable_list
7724 )
7725 {
7726     if (orig_die == NULL)
7727         return 0;
7728 
7729     VariableListSP variable_list_sp;
7730 
7731     size_t vars_added = 0;
7732     const DWARFDebugInfoEntry *die = orig_die;
7733     while (die != NULL)
7734     {
7735         dw_tag_t tag = die->Tag();
7736 
7737         // Check to see if we have already parsed this variable or constant?
7738         if (m_die_to_variable_sp[die])
7739         {
7740             if (cc_variable_list)
7741                 cc_variable_list->AddVariableIfUnique (m_die_to_variable_sp[die]);
7742         }
7743         else
7744         {
7745             // We haven't already parsed it, lets do that now.
7746             if ((tag == DW_TAG_variable) ||
7747                 (tag == DW_TAG_constant) ||
7748                 (tag == DW_TAG_formal_parameter && sc.function))
7749             {
7750                 if (variable_list_sp.get() == NULL)
7751                 {
7752                     const DWARFDebugInfoEntry *sc_parent_die = GetParentSymbolContextDIE(orig_die);
7753                     dw_tag_t parent_tag = sc_parent_die ? sc_parent_die->Tag() : 0;
7754                     switch (parent_tag)
7755                     {
7756                         case DW_TAG_compile_unit:
7757                             if (sc.comp_unit != NULL)
7758                             {
7759                                 variable_list_sp = sc.comp_unit->GetVariableList(false);
7760                                 if (variable_list_sp.get() == NULL)
7761                                 {
7762                                     variable_list_sp.reset(new VariableList());
7763                                     sc.comp_unit->SetVariableList(variable_list_sp);
7764                                 }
7765                             }
7766                             else
7767                             {
7768                                 GetObjectFile()->GetModule()->ReportError ("parent 0x%8.8" PRIx64 " %s with no valid compile unit in symbol context for 0x%8.8" PRIx64 " %s.\n",
7769                                                                            MakeUserID(sc_parent_die->GetOffset()),
7770                                                                            DW_TAG_value_to_name (parent_tag),
7771                                                                            MakeUserID(orig_die->GetOffset()),
7772                                                                            DW_TAG_value_to_name (orig_die->Tag()));
7773                             }
7774                             break;
7775 
7776                         case DW_TAG_subprogram:
7777                         case DW_TAG_inlined_subroutine:
7778                         case DW_TAG_lexical_block:
7779                             if (sc.function != NULL)
7780                             {
7781                                 // Check to see if we already have parsed the variables for the given scope
7782 
7783                                 Block *block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(sc_parent_die->GetOffset()));
7784                                 if (block == NULL)
7785                                 {
7786                                     // This must be a specification or abstract origin with
7787                                     // a concrete block counterpart in the current function. We need
7788                                     // to find the concrete block so we can correctly add the
7789                                     // variable to it
7790                                     DWARFCompileUnit *concrete_block_die_cu = dwarf_cu;
7791                                     const DWARFDebugInfoEntry *concrete_block_die = FindBlockContainingSpecification (sc.function->GetID(),
7792                                                                                                                       sc_parent_die->GetOffset(),
7793                                                                                                                       &concrete_block_die_cu);
7794                                     if (concrete_block_die)
7795                                         block = sc.function->GetBlock(true).FindBlockByID(MakeUserID(concrete_block_die->GetOffset()));
7796                                 }
7797 
7798                                 if (block != NULL)
7799                                 {
7800                                     const bool can_create = false;
7801                                     variable_list_sp = block->GetBlockVariableList (can_create);
7802                                     if (variable_list_sp.get() == NULL)
7803                                     {
7804                                         variable_list_sp.reset(new VariableList());
7805                                         block->SetVariableList(variable_list_sp);
7806                                     }
7807                                 }
7808                             }
7809                             break;
7810 
7811                         default:
7812                              GetObjectFile()->GetModule()->ReportError ("didn't find appropriate parent DIE for variable list for 0x%8.8" PRIx64 " %s.\n",
7813                                                                         MakeUserID(orig_die->GetOffset()),
7814                                                                         DW_TAG_value_to_name (orig_die->Tag()));
7815                             break;
7816                     }
7817                 }
7818 
7819                 if (variable_list_sp)
7820                 {
7821                     VariableSP var_sp (ParseVariableDIE(sc, dwarf_cu, die, func_low_pc));
7822                     if (var_sp)
7823                     {
7824                         variable_list_sp->AddVariableIfUnique (var_sp);
7825                         if (cc_variable_list)
7826                             cc_variable_list->AddVariableIfUnique (var_sp);
7827                         ++vars_added;
7828                     }
7829                 }
7830             }
7831         }
7832 
7833         bool skip_children = (sc.function == NULL && tag == DW_TAG_subprogram);
7834 
7835         if (!skip_children && parse_children && die->HasChildren())
7836         {
7837             vars_added += ParseVariables(sc, dwarf_cu, func_low_pc, die->GetFirstChild(), true, true, cc_variable_list);
7838         }
7839 
7840         if (parse_siblings)
7841             die = die->GetSibling();
7842         else
7843             die = NULL;
7844     }
7845     return vars_added;
7846 }
7847 
7848 //------------------------------------------------------------------
7849 // PluginInterface protocol
7850 //------------------------------------------------------------------
7851 ConstString
7852 SymbolFileDWARF::GetPluginName()
7853 {
7854     return GetPluginNameStatic();
7855 }
7856 
7857 uint32_t
7858 SymbolFileDWARF::GetPluginVersion()
7859 {
7860     return 1;
7861 }
7862 
7863 void
7864 SymbolFileDWARF::CompleteTagDecl (void *baton, clang::TagDecl *decl)
7865 {
7866     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7867     ClangASTType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7868     if (clang_type)
7869         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7870 }
7871 
7872 void
7873 SymbolFileDWARF::CompleteObjCInterfaceDecl (void *baton, clang::ObjCInterfaceDecl *decl)
7874 {
7875     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7876     ClangASTType clang_type = symbol_file_dwarf->GetClangASTContext().GetTypeForDecl (decl);
7877     if (clang_type)
7878         symbol_file_dwarf->ResolveClangOpaqueTypeDefinition (clang_type);
7879 }
7880 
7881 void
7882 SymbolFileDWARF::DumpIndexes ()
7883 {
7884     StreamFile s(stdout, false);
7885 
7886     s.Printf ("DWARF index for (%s) '%s':",
7887               GetObjectFile()->GetModule()->GetArchitecture().GetArchitectureName(),
7888               GetObjectFile()->GetFileSpec().GetPath().c_str());
7889     s.Printf("\nFunction basenames:\n");    m_function_basename_index.Dump (&s);
7890     s.Printf("\nFunction fullnames:\n");    m_function_fullname_index.Dump (&s);
7891     s.Printf("\nFunction methods:\n");      m_function_method_index.Dump (&s);
7892     s.Printf("\nFunction selectors:\n");    m_function_selector_index.Dump (&s);
7893     s.Printf("\nObjective C class selectors:\n");    m_objc_class_selectors_index.Dump (&s);
7894     s.Printf("\nGlobals and statics:\n");   m_global_index.Dump (&s);
7895     s.Printf("\nTypes:\n");                 m_type_index.Dump (&s);
7896     s.Printf("\nNamepaces:\n");             m_namespace_index.Dump (&s);
7897 }
7898 
7899 void
7900 SymbolFileDWARF::SearchDeclContext (const clang::DeclContext *decl_context,
7901                                     const char *name,
7902                                     llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7903 {
7904     DeclContextToDIEMap::iterator iter = m_decl_ctx_to_die.find(decl_context);
7905 
7906     if (iter == m_decl_ctx_to_die.end())
7907         return;
7908 
7909     for (DIEPointerSet::iterator pos = iter->second.begin(), end = iter->second.end(); pos != end; ++pos)
7910     {
7911         const DWARFDebugInfoEntry *context_die = *pos;
7912 
7913         if (!results)
7914             return;
7915 
7916         DWARFDebugInfo* info = DebugInfo();
7917 
7918         DIEArray die_offsets;
7919 
7920         DWARFCompileUnit* dwarf_cu = NULL;
7921         const DWARFDebugInfoEntry* die = NULL;
7922 
7923         if (m_using_apple_tables)
7924         {
7925             if (m_apple_types_ap.get())
7926                 m_apple_types_ap->FindByName (name, die_offsets);
7927         }
7928         else
7929         {
7930             if (!m_indexed)
7931                 Index ();
7932 
7933             m_type_index.Find (ConstString(name), die_offsets);
7934         }
7935 
7936         const size_t num_matches = die_offsets.size();
7937 
7938         if (num_matches)
7939         {
7940             for (size_t i = 0; i < num_matches; ++i)
7941             {
7942                 const dw_offset_t die_offset = die_offsets[i];
7943                 die = info->GetDIEPtrWithCompileUnitHint (die_offset, &dwarf_cu);
7944 
7945                 if (die->GetParent() != context_die)
7946                     continue;
7947 
7948                 Type *matching_type = ResolveType (dwarf_cu, die);
7949 
7950                 clang::QualType qual_type = matching_type->GetClangForwardType().GetQualType();
7951 
7952                 if (const clang::TagType *tag_type = llvm::dyn_cast<clang::TagType>(qual_type.getTypePtr()))
7953                 {
7954                     clang::TagDecl *tag_decl = tag_type->getDecl();
7955                     results->push_back(tag_decl);
7956                 }
7957                 else if (const clang::TypedefType *typedef_type = llvm::dyn_cast<clang::TypedefType>(qual_type.getTypePtr()))
7958                 {
7959                     clang::TypedefNameDecl *typedef_decl = typedef_type->getDecl();
7960                     results->push_back(typedef_decl);
7961                 }
7962             }
7963         }
7964     }
7965 }
7966 
7967 void
7968 SymbolFileDWARF::FindExternalVisibleDeclsByName (void *baton,
7969                                                  const clang::DeclContext *decl_context,
7970                                                  clang::DeclarationName decl_name,
7971                                                  llvm::SmallVectorImpl <clang::NamedDecl *> *results)
7972 {
7973 
7974     switch (decl_context->getDeclKind())
7975     {
7976     case clang::Decl::Namespace:
7977     case clang::Decl::TranslationUnit:
7978         {
7979             SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7980             symbol_file_dwarf->SearchDeclContext (decl_context, decl_name.getAsString().c_str(), results);
7981         }
7982         break;
7983     default:
7984         break;
7985     }
7986 }
7987 
7988 bool
7989 SymbolFileDWARF::LayoutRecordType(void *baton, const clang::RecordDecl *record_decl, uint64_t &size,
7990                                   uint64_t &alignment,
7991                                   llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
7992                                   llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
7993                                   llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
7994 {
7995     SymbolFileDWARF *symbol_file_dwarf = (SymbolFileDWARF *)baton;
7996     return symbol_file_dwarf->LayoutRecordType (record_decl, size, alignment, field_offsets, base_offsets, vbase_offsets);
7997 }
7998 
7999 bool
8000 SymbolFileDWARF::LayoutRecordType(const clang::RecordDecl *record_decl, uint64_t &bit_size, uint64_t &alignment,
8001                                   llvm::DenseMap<const clang::FieldDecl *, uint64_t> &field_offsets,
8002                                   llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &base_offsets,
8003                                   llvm::DenseMap<const clang::CXXRecordDecl *, clang::CharUnits> &vbase_offsets)
8004 {
8005     Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO));
8006     RecordDeclToLayoutMap::iterator pos = m_record_decl_to_layout_map.find (record_decl);
8007     bool success = false;
8008     base_offsets.clear();
8009     vbase_offsets.clear();
8010     if (pos != m_record_decl_to_layout_map.end())
8011     {
8012         bit_size = pos->second.bit_size;
8013         alignment = pos->second.alignment;
8014         field_offsets.swap(pos->second.field_offsets);
8015         base_offsets.swap (pos->second.base_offsets);
8016         vbase_offsets.swap (pos->second.vbase_offsets);
8017         m_record_decl_to_layout_map.erase(pos);
8018         success = true;
8019     }
8020     else
8021     {
8022         bit_size = 0;
8023         alignment = 0;
8024         field_offsets.clear();
8025     }
8026 
8027     if (log)
8028         GetObjectFile()->GetModule()->LogMessage (log,
8029                                                   "SymbolFileDWARF::LayoutRecordType (record_decl = %p, bit_size = %" PRIu64 ", alignment = %" PRIu64 ", field_offsets[%u],base_offsets[%u], vbase_offsets[%u]) success = %i",
8030                                                   static_cast<const void*>(record_decl),
8031                                                   bit_size, alignment,
8032                                                   static_cast<uint32_t>(field_offsets.size()),
8033                                                   static_cast<uint32_t>(base_offsets.size()),
8034                                                   static_cast<uint32_t>(vbase_offsets.size()),
8035                                                   success);
8036     return success;
8037 }
8038 
8039 
8040 SymbolFileDWARFDebugMap *
8041 SymbolFileDWARF::GetDebugMapSymfile ()
8042 {
8043     if (m_debug_map_symfile == NULL && !m_debug_map_module_wp.expired())
8044     {
8045         lldb::ModuleSP module_sp (m_debug_map_module_wp.lock());
8046         if (module_sp)
8047         {
8048             SymbolVendor *sym_vendor = module_sp->GetSymbolVendor();
8049             if (sym_vendor)
8050                 m_debug_map_symfile = (SymbolFileDWARFDebugMap *)sym_vendor->GetSymbolFile();
8051         }
8052     }
8053     return m_debug_map_symfile;
8054 }
8055 
8056 
8057