1 //===-- DWARFCompileUnit.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 "DWARFCompileUnit.h"
11 
12 #include "lldb/Core/Mangled.h"
13 #include "lldb/Core/Stream.h"
14 #include "lldb/Core/Timer.h"
15 #include "lldb/Symbol/ObjectFile.h"
16 
17 #include "DWARFDebugAbbrev.h"
18 #include "DWARFDebugAranges.h"
19 #include "DWARFDebugInfo.h"
20 #include "DWARFDIECollection.h"
21 #include "DWARFFormValue.h"
22 #include "LogChannelDWARF.h"
23 #include "NameToDIE.h"
24 #include "SymbolFileDWARF.h"
25 
26 using namespace lldb_private;
27 using namespace std;
28 
29 extern int g_verbose;
30 
31 DWARFCompileUnit::DWARFCompileUnit(SymbolFileDWARF* dwarf2Data) :
32     m_dwarf2Data    ( dwarf2Data ),
33     m_offset        ( DW_INVALID_OFFSET ),
34     m_length        ( 0 ),
35     m_version       ( 0 ),
36     m_abbrevs       ( NULL ),
37     m_addr_size     ( DWARFCompileUnit::GetDefaultAddressSize() ),
38     m_base_addr     ( 0 ),
39     m_die_array     (),
40     m_aranges_ap    (),
41     m_user_data     ( NULL )
42 {
43 }
44 
45 void
46 DWARFCompileUnit::Clear()
47 {
48     m_offset        = DW_INVALID_OFFSET;
49     m_length        = 0;
50     m_version       = 0;
51     m_abbrevs       = NULL;
52     m_addr_size     = DWARFCompileUnit::GetDefaultAddressSize();
53     m_base_addr     = 0;
54     m_die_array.clear();
55     m_aranges_ap.reset();
56     m_user_data     = NULL;
57 }
58 
59 bool
60 DWARFCompileUnit::Extract(const DataExtractor &debug_info, uint32_t* offset_ptr)
61 {
62     Clear();
63 
64     m_offset = *offset_ptr;
65 
66     if (debug_info.ValidOffset(*offset_ptr))
67     {
68         dw_offset_t abbr_offset;
69         const DWARFDebugAbbrev *abbr = m_dwarf2Data->DebugAbbrev();
70         m_length        = debug_info.GetU32(offset_ptr);
71         m_version       = debug_info.GetU16(offset_ptr);
72         abbr_offset     = debug_info.GetU32(offset_ptr);
73         m_addr_size     = debug_info.GetU8 (offset_ptr);
74 
75         bool length_OK = debug_info.ValidOffset(GetNextCompileUnitOffset()-1);
76         bool version_OK = SymbolFileDWARF::SupportedVersion(m_version);
77         bool abbr_offset_OK = m_dwarf2Data->get_debug_abbrev_data().ValidOffset(abbr_offset);
78         bool addr_size_OK = ((m_addr_size == 4) || (m_addr_size == 8));
79 
80         if (length_OK && version_OK && addr_size_OK && abbr_offset_OK && abbr != NULL)
81         {
82             m_abbrevs = abbr->GetAbbreviationDeclarationSet(abbr_offset);
83             return true;
84         }
85 
86         // reset the offset to where we tried to parse from if anything went wrong
87         *offset_ptr = m_offset;
88     }
89 
90     return false;
91 }
92 
93 
94 dw_offset_t
95 DWARFCompileUnit::Extract(dw_offset_t offset, const DataExtractor& debug_info_data, const DWARFAbbreviationDeclarationSet* abbrevs)
96 {
97     Clear();
98 
99     m_offset = offset;
100 
101     if (debug_info_data.ValidOffset(offset))
102     {
103         m_length        = debug_info_data.GetU32(&offset);
104         m_version       = debug_info_data.GetU16(&offset);
105         bool abbrevs_OK = debug_info_data.GetU32(&offset) == abbrevs->GetOffset();
106         m_abbrevs       = abbrevs;
107         m_addr_size     = debug_info_data.GetU8 (&offset);
108 
109         bool version_OK = SymbolFileDWARF::SupportedVersion(m_version);
110         bool addr_size_OK = ((m_addr_size == 4) || (m_addr_size == 8));
111 
112         if (version_OK && addr_size_OK && abbrevs_OK && debug_info_data.ValidOffset(offset))
113             return offset;
114     }
115     return DW_INVALID_OFFSET;
116 }
117 
118 void
119 DWARFCompileUnit::ClearDIEs(bool keep_compile_unit_die)
120 {
121     if (m_die_array.size() > 1)
122     {
123         // std::vectors never get any smaller when resized to a smaller size,
124         // or when clear() or erase() are called, the size will report that it
125         // is smaller, but the memory allocated remains intact (call capacity()
126         // to see this). So we need to create a temporary vector and swap the
127         // contents which will cause just the internal pointers to be swapped
128         // so that when "tmp_array" goes out of scope, it will destroy the
129         // contents.
130 
131         // Save at least the compile unit DIE
132         DWARFDebugInfoEntry::collection tmp_array;
133         m_die_array.swap(tmp_array);
134         if (keep_compile_unit_die)
135             m_die_array.push_back(tmp_array.front());
136     }
137 }
138 
139 //----------------------------------------------------------------------
140 // ParseCompileUnitDIEsIfNeeded
141 //
142 // Parses a compile unit and indexes its DIEs if it hasn't already been
143 // done.
144 //----------------------------------------------------------------------
145 size_t
146 DWARFCompileUnit::ExtractDIEsIfNeeded (bool cu_die_only)
147 {
148     const size_t initial_die_array_size = m_die_array.size();
149     if ((cu_die_only && initial_die_array_size > 0) || initial_die_array_size > 1)
150         return 0; // Already parsed
151 
152     Timer scoped_timer (__PRETTY_FUNCTION__,
153                         "%8.8x: DWARFCompileUnit::ExtractDIEsIfNeeded( cu_die_only = %i )",
154                         m_offset,
155                         cu_die_only);
156 
157     // Set the offset to that of the first DIE
158     uint32_t offset = GetFirstDIEOffset();
159     DWARFDebugInfoEntry die;
160         // Keep a flat array of the DIE for binary lookup by DIE offset
161 //    Log *log = LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_INFO);
162 //        if (log)
163 //            log->Printf("0x%8.8x: Compile Unit: length = 0x%8.8x, version = 0x%4.4x, abbr_offset = 0x%8.8x, addr_size = 0x%2.2x",
164 //                        cu->GetOffset(),
165 //                        cu->GetLength(),
166 //                        cu->GetVersion(),
167 //                        cu->GetAbbrevOffset(),
168 //                        cu->GetAddressByteSize());
169 
170     uint32_t depth = 0;
171     // We are in our compile unit, parse starting at the offset
172     // we were told to parse
173     const DataExtractor& debug_info_data = m_dwarf2Data->get_debug_info_data();
174 
175     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (GetAddressByteSize());
176     while (die.FastExtract (debug_info_data, this, fixed_form_sizes, &offset))
177     {
178 //        if (log)
179 //            log->Printf("0x%8.8x: %*.*s%s%s",
180 //                        die.GetOffset(),
181 //                        depth * 2, depth * 2, "",
182 //                        DW_TAG_value_to_name (die.Tag()),
183 //                        die.HasChildren() ? " *" : "");
184 
185         if (depth == 0)
186         {
187             uint64_t base_addr = die.GetAttributeValueAsUnsigned(m_dwarf2Data, this, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
188             if (base_addr == LLDB_INVALID_ADDRESS)
189                 base_addr = die.GetAttributeValueAsUnsigned(m_dwarf2Data, this, DW_AT_entry_pc, 0);
190             SetBaseAddress (base_addr);
191         }
192 
193         if (cu_die_only)
194         {
195             AddDIE (die);
196             return 1;
197         }
198         else if (depth == 0 && initial_die_array_size == 1)
199         {
200             // Don't append the CU die as we already did that
201         }
202         else
203         {
204             AddDIE (die);
205         }
206 
207         const DWARFAbbreviationDeclaration* abbrDecl = die.GetAbbreviationDeclarationPtr();
208         if (abbrDecl)
209         {
210             // Normal DIE
211             if (abbrDecl->HasChildren())
212                 ++depth;
213         }
214         else
215         {
216             // NULL DIE.
217             if (depth > 0)
218                 --depth;
219             if (depth == 0)
220                 break;  // We are done with this compile unit!
221         }
222 
223         if (offset > GetNextCompileUnitOffset())
224         {
225             char path[PATH_MAX];
226             ObjectFile *objfile = m_dwarf2Data->GetObjectFile();
227             if (objfile)
228             {
229                 objfile->GetFileSpec().GetPath(path, sizeof(path));
230             }
231             fprintf (stderr, "warning: DWARF compile unit extends beyond its bounds cu 0x%8.8x at 0x%8.8x in '%s'\n", GetOffset(), offset, path);
232             break;
233         }
234     }
235     SetDIERelations();
236     return m_die_array.size();
237 }
238 
239 
240 dw_offset_t
241 DWARFCompileUnit::GetAbbrevOffset() const
242 {
243     return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
244 }
245 
246 
247 
248 bool
249 DWARFCompileUnit::Verify(Stream *s) const
250 {
251     const DataExtractor& debug_info = m_dwarf2Data->get_debug_info_data();
252     bool valid_offset = debug_info.ValidOffset(m_offset);
253     bool length_OK = debug_info.ValidOffset(GetNextCompileUnitOffset()-1);
254     bool version_OK = SymbolFileDWARF::SupportedVersion(m_version);
255     bool abbr_offset_OK = m_dwarf2Data->get_debug_abbrev_data().ValidOffset(GetAbbrevOffset());
256     bool addr_size_OK = ((m_addr_size == 4) || (m_addr_size == 8));
257     bool verbose = s->GetVerbose();
258     if (valid_offset && length_OK && version_OK && addr_size_OK && abbr_offset_OK)
259     {
260         if (verbose)
261             s->Printf("    0x%8.8x: OK\n", m_offset);
262         return true;
263     }
264     else
265     {
266         s->Printf("    0x%8.8x: ", m_offset);
267 
268         m_dwarf2Data->get_debug_info_data().Dump (s, m_offset, lldb::eFormatHex, 1, Size(), 32, LLDB_INVALID_ADDRESS, 0, 0);
269         s->EOL();
270         if (valid_offset)
271         {
272             if (!length_OK)
273                 s->Printf("        The length (0x%8.8x) for this compile unit is too large for the .debug_info provided.\n", m_length);
274             if (!version_OK)
275                 s->Printf("        The 16 bit compile unit header version is not supported.\n");
276             if (!abbr_offset_OK)
277                 s->Printf("        The offset into the .debug_abbrev section (0x%8.8x) is not valid.\n", GetAbbrevOffset());
278             if (!addr_size_OK)
279                 s->Printf("        The address size is unsupported: 0x%2.2x\n", m_addr_size);
280         }
281         else
282             s->Printf("        The start offset of the compile unit header in the .debug_info is invalid.\n");
283     }
284     return false;
285 }
286 
287 
288 void
289 DWARFCompileUnit::Dump(Stream *s) const
290 {
291     s->Printf("0x%8.8x: Compile Unit: length = 0x%8.8x, version = 0x%4.4x, abbr_offset = 0x%8.8x, addr_size = 0x%2.2x (next CU at {0x%8.8x})\n",
292                 m_offset, m_length, m_version, GetAbbrevOffset(), m_addr_size, GetNextCompileUnitOffset());
293 }
294 
295 
296 static uint8_t g_default_addr_size = 4;
297 
298 uint8_t
299 DWARFCompileUnit::GetAddressByteSize(const DWARFCompileUnit* cu)
300 {
301     if (cu)
302         return cu->GetAddressByteSize();
303     return DWARFCompileUnit::GetDefaultAddressSize();
304 }
305 
306 uint8_t
307 DWARFCompileUnit::GetDefaultAddressSize()
308 {
309     return g_default_addr_size;
310 }
311 
312 void
313 DWARFCompileUnit::SetDefaultAddressSize(uint8_t addr_size)
314 {
315     g_default_addr_size = addr_size;
316 }
317 
318 bool
319 DWARFCompileUnit::LookupAddress
320 (
321     const dw_addr_t address,
322     DWARFDebugInfoEntry** function_die_handle,
323     DWARFDebugInfoEntry** block_die_handle
324 )
325 {
326     bool success = false;
327 
328     if (function_die_handle != NULL && DIE())
329     {
330         if (m_aranges_ap.get() == NULL)
331         {
332             m_aranges_ap.reset(new DWARFDebugAranges());
333             m_die_array.front().BuildFunctionAddressRangeTable(m_dwarf2Data, this, m_aranges_ap.get());
334         }
335 
336         // Re-check the aranges auto pointer contents in case it was created above
337         if (m_aranges_ap.get() != NULL)
338         {
339             *function_die_handle = GetDIEPtr(m_aranges_ap->FindAddress(address));
340             if (*function_die_handle != NULL)
341             {
342                 success = true;
343                 if (block_die_handle != NULL)
344                 {
345                     DWARFDebugInfoEntry* child = (*function_die_handle)->GetFirstChild();
346                     while (child)
347                     {
348                         if (child->LookupAddress(address, m_dwarf2Data, this, NULL, block_die_handle))
349                             break;
350                         child = child->GetSibling();
351                     }
352                 }
353             }
354         }
355     }
356     return success;
357 }
358 
359 //----------------------------------------------------------------------
360 // SetDIERelations()
361 //
362 // We read in all of the DIE entries into our flat list of DIE entries
363 // and now we need to go back through all of them and set the parent,
364 // sibling and child pointers for quick DIE navigation.
365 //----------------------------------------------------------------------
366 void
367 DWARFCompileUnit::SetDIERelations()
368 {
369 #if 0
370     // Compute average bytes per DIE
371     //
372     // We can figure out what the average number of bytes per DIE is
373     // to help us pre-allocate the correct number of m_die_array
374     // entries so we don't end up doing a lot of memory copies as we
375     // are creating our DIE array when parsing
376     //
377     // Enable this code by changing "#if 0" above to "#if 1" and running
378     // the dsymutil or dwarfdump with a bunch of dwarf files and see what
379     // the running average ends up being in the stdout log.
380     static size_t g_total_cu_debug_info_size = 0;
381     static size_t g_total_num_dies = 0;
382     static size_t g_min_bytes_per_die = UINT32_MAX;
383     static size_t g_max_bytes_per_die = 0;
384     const size_t num_dies = m_die_array.size();
385     const size_t cu_debug_info_size = GetDebugInfoSize();
386     const size_t bytes_per_die = cu_debug_info_size / num_dies;
387     if (g_min_bytes_per_die > bytes_per_die)
388         g_min_bytes_per_die = bytes_per_die;
389     if (g_max_bytes_per_die < bytes_per_die)
390         g_max_bytes_per_die = bytes_per_die;
391     if (g_total_cu_debug_info_size == 0)
392     {
393         cout << "                    min max avg" << endl
394              << "n dies cu size  bpd bpd bpd bpd" << endl
395              << "------ -------- --- === === ===" << endl;
396     }
397     g_total_cu_debug_info_size += cu_debug_info_size;
398     g_total_num_dies += num_dies;
399     const size_t avg_bytes_per_die = g_total_cu_debug_info_size / g_total_num_dies;
400     cout
401         << DECIMAL_WIDTH(6) << num_dies << ' '
402         << DECIMAL_WIDTH(8) << cu_debug_info_size  << ' '
403         << DECIMAL_WIDTH(3) << bytes_per_die << ' '
404         << DECIMAL_WIDTH(3) << g_min_bytes_per_die << ' '
405         << DECIMAL_WIDTH(3) << g_max_bytes_per_die << ' '
406         << DECIMAL_WIDTH(3) << avg_bytes_per_die
407         << endl;
408 #endif
409     if (m_die_array.empty())
410         return;
411     DWARFDebugInfoEntry* die_array_begin = &m_die_array.front();
412     DWARFDebugInfoEntry* die_array_end = &m_die_array.back();
413     DWARFDebugInfoEntry* curr_die;
414     // We purposely are skipping the last element in the array in the loop below
415     // so that we can always have a valid next item
416     for (curr_die = die_array_begin;  curr_die < die_array_end;  ++curr_die)
417     {
418         // Since our loop doesn't include the last element, we can always
419         // safely access the next die in the array.
420         DWARFDebugInfoEntry* next_die = curr_die + 1;
421 
422         const DWARFAbbreviationDeclaration* curr_die_abbrev = curr_die->GetAbbreviationDeclarationPtr();
423 
424         if (curr_die_abbrev)
425         {
426             // Normal DIE
427             if (curr_die_abbrev->HasChildren())
428                 next_die->SetParent(curr_die);
429             else
430                 curr_die->SetSibling(next_die);
431         }
432         else
433         {
434             // NULL DIE that terminates a sibling chain
435             DWARFDebugInfoEntry* parent = curr_die->GetParent();
436             if (parent)
437                 parent->SetSibling(next_die);
438         }
439     }
440 
441     // Since we skipped the last element, we need to fix it up!
442     if (die_array_begin < die_array_end)
443         curr_die->SetParent(die_array_begin);
444 
445 #if 0
446     // The code below will dump the DIE relations in case any modification
447     // is done to the above code. This dump can be used in a diff to make
448     // sure that no functionality is lost.
449     {
450         DWARFDebugInfoEntry::const_iterator pos;
451         DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
452         puts("offset    parent   sibling  child");
453         puts("--------  -------- -------- --------");
454         for (pos = m_die_array.begin(); pos != end; ++pos)
455         {
456             const DWARFDebugInfoEntry& die_ref = *pos;
457             const DWARFDebugInfoEntry* p = die_ref.GetParent();
458             const DWARFDebugInfoEntry* s = die_ref.GetSibling();
459             const DWARFDebugInfoEntry* c = die_ref.GetFirstChild();
460             printf("%.8x: %.8x %.8x %.8x\n", die_ref.GetOffset(),
461                 p ? p->GetOffset() : 0,
462                 s ? s->GetOffset() : 0,
463                 c ? c->GetOffset() : 0);
464         }
465     }
466 #endif
467 
468 }
469 //----------------------------------------------------------------------
470 // Compare function DWARFDebugAranges::Range structures
471 //----------------------------------------------------------------------
472 static bool CompareDIEOffset (const DWARFDebugInfoEntry& die1, const DWARFDebugInfoEntry& die2)
473 {
474     return die1.GetOffset() < die2.GetOffset();
475 }
476 
477 //----------------------------------------------------------------------
478 // GetDIEPtr()
479 //
480 // Get the DIE (Debug Information Entry) with the specified offset.
481 //----------------------------------------------------------------------
482 DWARFDebugInfoEntry*
483 DWARFCompileUnit::GetDIEPtr(dw_offset_t die_offset)
484 {
485     if (die_offset != DW_INVALID_OFFSET)
486     {
487         ExtractDIEsIfNeeded (false);
488         DWARFDebugInfoEntry compare_die;
489         compare_die.SetOffset(die_offset);
490         DWARFDebugInfoEntry::iterator end = m_die_array.end();
491         DWARFDebugInfoEntry::iterator pos = lower_bound(m_die_array.begin(), end, compare_die, CompareDIEOffset);
492         if (pos != end)
493         {
494             if (die_offset == (*pos).GetOffset())
495                 return &(*pos);
496         }
497     }
498     return NULL;    // Not found in any compile units
499 }
500 
501 //----------------------------------------------------------------------
502 // GetDIEPtrContainingOffset()
503 //
504 // Get the DIE (Debug Information Entry) that contains the specified
505 // .debug_info offset.
506 //----------------------------------------------------------------------
507 const DWARFDebugInfoEntry*
508 DWARFCompileUnit::GetDIEPtrContainingOffset(dw_offset_t die_offset)
509 {
510     if (die_offset != DW_INVALID_OFFSET)
511     {
512         ExtractDIEsIfNeeded (false);
513         DWARFDebugInfoEntry compare_die;
514         compare_die.SetOffset(die_offset);
515         DWARFDebugInfoEntry::iterator end = m_die_array.end();
516         DWARFDebugInfoEntry::iterator pos = lower_bound(m_die_array.begin(), end, compare_die, CompareDIEOffset);
517         if (pos != end)
518         {
519             if (die_offset >= (*pos).GetOffset())
520             {
521                 DWARFDebugInfoEntry::iterator next = pos + 1;
522                 if (next != end)
523                 {
524                     if (die_offset < (*next).GetOffset())
525                         return &(*pos);
526                 }
527             }
528         }
529     }
530     return NULL;    // Not found in any compile units
531 }
532 
533 
534 
535 size_t
536 DWARFCompileUnit::AppendDIEsWithTag (const dw_tag_t tag, DWARFDIECollection& dies, uint32_t depth) const
537 {
538     size_t old_size = dies.Size();
539     DWARFDebugInfoEntry::const_iterator pos;
540     DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
541     for (pos = m_die_array.begin(); pos != end; ++pos)
542     {
543         if (pos->Tag() == tag)
544             dies.Append (&(*pos));
545     }
546 
547     // Return the number of DIEs added to the collection
548     return dies.Size() - old_size;
549 }
550 
551 //void
552 //DWARFCompileUnit::AddGlobalDIEByIndex (uint32_t die_idx)
553 //{
554 //    m_global_die_indexes.push_back (die_idx);
555 //}
556 //
557 //
558 //void
559 //DWARFCompileUnit::AddGlobal (const DWARFDebugInfoEntry* die)
560 //{
561 //    // Indexes to all file level global and static variables
562 //    m_global_die_indexes;
563 //
564 //    if (m_die_array.empty())
565 //        return;
566 //
567 //    const DWARFDebugInfoEntry* first_die = &m_die_array[0];
568 //    const DWARFDebugInfoEntry* end = first_die + m_die_array.size();
569 //    if (first_die <= die && die < end)
570 //        m_global_die_indexes.push_back (die - first_die);
571 //}
572 
573 
574 void
575 DWARFCompileUnit::Index
576 (
577     const uint32_t cu_idx,
578     NameToDIE& func_basenames,
579     NameToDIE& func_fullnames,
580     NameToDIE& func_methods,
581     NameToDIE& func_selectors,
582     NameToDIE& objc_class_selectors,
583     NameToDIE& globals,
584     NameToDIE& types,
585     NameToDIE& namespaces,
586     const DWARFDebugRanges *debug_ranges,
587     DWARFDebugAranges *aranges
588 )
589 {
590     const DataExtractor* debug_str = &m_dwarf2Data->get_debug_str_data();
591 
592     const uint8_t *fixed_form_sizes = DWARFFormValue::GetFixedFormSizesForAddressSize (GetAddressByteSize());
593 
594     NameToDIE::Info die_info = { cu_idx, 0 };
595     DWARFDebugInfoEntry::const_iterator pos;
596     DWARFDebugInfoEntry::const_iterator begin = m_die_array.begin();
597     DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
598     for (pos = begin; pos != end; ++pos)
599     {
600         const DWARFDebugInfoEntry &die = *pos;
601 
602         const dw_tag_t tag = die.Tag();
603 
604         switch (tag)
605         {
606         case DW_TAG_subprogram:
607         case DW_TAG_inlined_subroutine:
608         case DW_TAG_base_type:
609         case DW_TAG_class_type:
610         case DW_TAG_constant:
611         case DW_TAG_enumeration_type:
612         case DW_TAG_string_type:
613         case DW_TAG_subroutine_type:
614         case DW_TAG_structure_type:
615         case DW_TAG_union_type:
616         case DW_TAG_typedef:
617         case DW_TAG_namespace:
618         case DW_TAG_variable:
619             break;
620 
621         default:
622             continue;
623         }
624 
625         DWARFDebugInfoEntry::Attributes attributes;
626         const char *name = NULL;
627         Mangled mangled;
628         bool is_variable = false;
629         bool is_declaration = false;
630         bool is_artificial = false;
631         bool has_address = false;
632         bool has_location = false;
633         bool is_global_or_static_variable = false;
634         dw_addr_t lo_pc = DW_INVALID_ADDRESS;
635         dw_addr_t hi_pc = DW_INVALID_ADDRESS;
636         DWARFDebugRanges::RangeList ranges;
637 
638         dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
639         const size_t num_attributes = die.GetAttributes(m_dwarf2Data, this, fixed_form_sizes, attributes);
640         if (num_attributes > 0)
641         {
642             is_variable = tag == DW_TAG_variable;
643 
644             for (uint32_t i=0; i<num_attributes; ++i)
645             {
646                 dw_attr_t attr = attributes.AttributeAtIndex(i);
647                 DWARFFormValue form_value;
648                 switch (attr)
649                 {
650                 case DW_AT_name:
651                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
652                         name = form_value.AsCString(debug_str);
653                     break;
654 
655                 case DW_AT_declaration:
656                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
657                         is_declaration = form_value.Unsigned() != 0;
658                     break;
659 
660                 case DW_AT_artificial:
661                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
662                         is_artificial = form_value.Unsigned() != 0;
663                     break;
664 
665                 case DW_AT_MIPS_linkage_name:
666                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
667                         mangled.GetMangledName().SetCString(form_value.AsCString(debug_str));
668                     break;
669 
670                 case DW_AT_low_pc:
671                     has_address = true;
672                     if (tag == DW_TAG_subprogram && attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
673                     {
674                         lo_pc = form_value.Unsigned();
675                     }
676                     break;
677 
678                 case DW_AT_high_pc:
679                     has_address = true;
680                     if (tag == DW_TAG_subprogram && attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
681                     {
682                         hi_pc = form_value.Unsigned();
683                     }
684                     break;
685 
686                 case DW_AT_ranges:
687                     if (tag == DW_TAG_subprogram && attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
688                     {
689                         if (debug_ranges)
690                         {
691                             debug_ranges->FindRanges(form_value.Unsigned(), ranges);
692                             // All DW_AT_ranges are relative to the base address of the
693                             // compile unit. We add the compile unit base address to make
694                             // sure all the addresses are properly fixed up.
695                             ranges.AddOffset(GetBaseAddress());
696                         }
697                     }
698                     has_address = true;
699                     break;
700 
701                 case DW_AT_entry_pc:
702                     has_address = true;
703                     break;
704 
705                 case DW_AT_location:
706                     has_location = true;
707                     if (tag == DW_TAG_variable)
708                     {
709                         const DWARFDebugInfoEntry* parent_die = die.GetParent();
710                         while ( parent_die != NULL )
711                         {
712                             switch (parent_die->Tag())
713                             {
714                             case DW_TAG_subprogram:
715                             case DW_TAG_lexical_block:
716                             case DW_TAG_inlined_subroutine:
717                                 // Even if this is a function level static, we don't add it. We could theoretically
718                                 // add these if we wanted to by introspecting into the DW_AT_location and seeing
719                                 // if the location describes a hard coded address, but we dont want the performance
720                                 // penalty of that right now.
721                                 is_global_or_static_variable = false;
722 //                              if (attributes.ExtractFormValueAtIndex(dwarf2Data, i, form_value))
723 //                              {
724 //                                  // If we have valid block data, then we have location expression bytes
725 //                                  // that are fixed (not a location list).
726 //                                  const uint8_t *block_data = form_value.BlockData();
727 //                                  if (block_data)
728 //                                  {
729 //                                      uint32_t block_length = form_value.Unsigned();
730 //                                      if (block_length == 1 + attributes.CompileUnitAtIndex(i)->GetAddressByteSize())
731 //                                      {
732 //                                          if (block_data[0] == DW_OP_addr)
733 //                                              add_die = true;
734 //                                      }
735 //                                  }
736 //                              }
737                                 parent_die = NULL;  // Terminate the while loop.
738                                 break;
739 
740                             case DW_TAG_compile_unit:
741                                 is_global_or_static_variable = true;
742                                 parent_die = NULL;  // Terminate the while loop.
743                                 break;
744 
745                             default:
746                                 parent_die = parent_die->GetParent();   // Keep going in the while loop.
747                                 break;
748                             }
749                         }
750                     }
751                     break;
752 
753                 case DW_AT_specification:
754                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
755                         specification_die_offset = form_value.Reference(this);
756                     break;
757                 }
758             }
759 
760             if (tag == DW_TAG_subprogram)
761             {
762                 if (lo_pc != DW_INVALID_ADDRESS && hi_pc != DW_INVALID_ADDRESS)
763                 {
764                     aranges->AppendRange (m_offset, lo_pc, hi_pc);
765                 }
766                 else
767                 {
768                     for (uint32_t i=0, num_ranges = ranges.Size(); i<num_ranges; ++i)
769                     {
770                         const DWARFDebugRanges::Range *range = ranges.RangeAtIndex (i);
771                         aranges->AppendRange (m_offset, range->begin_offset, range->end_offset);
772                     }
773                 }
774             }
775         }
776 
777         die_info.die_idx = std::distance (begin, pos);
778 
779         switch (tag)
780         {
781         case DW_TAG_subprogram:
782             if (has_address)
783             {
784                 if (name)
785                 {
786                     if ((name[0] == '-' || name[0] == '+') && name[1] == '[')
787                     {
788                         int name_len = strlen (name);
789                         // Objective C methods must have at least:
790                         //      "-[" or "+[" prefix
791                         //      One character for a class name
792                         //      One character for the space between the class name
793                         //      One character for the method name
794                         //      "]" suffix
795                         if (name_len >= 6 && name[name_len - 1] == ']')
796                         {
797                             const char *method_name = strchr (name, ' ');
798                             if (method_name)
799                             {
800                                 ConstString class_name (name + 2, method_name - name - 2);
801 
802                                 // Keep a map of the objective C class name to all selector
803                                 // DIEs
804                                 objc_class_selectors.Insert(class_name, die_info);
805 
806                                 // Skip the space
807                                 ++method_name;
808                                 // Extract the objective C basename and add it to the
809                                 // accelerator tables
810                                 size_t method_name_len = name_len - (method_name - name) - 1;
811                                 func_selectors.Insert (ConstString (method_name, method_name_len), die_info);
812                             }
813                         }
814                     }
815                     // If we have a mangled name, then the DW_AT_name attribute
816                     // is usually the method name without the class or any parameters
817                     const DWARFDebugInfoEntry *parent = die.GetParent();
818                     bool is_method = false;
819                     if (parent)
820                     {
821                         dw_tag_t parent_tag = parent->Tag();
822                         if (parent_tag == DW_TAG_class_type || parent_tag == DW_TAG_structure_type)
823                         {
824                             is_method = true;
825                         }
826                         else
827                         {
828                             if (mangled && specification_die_offset != DW_INVALID_OFFSET)
829                             {
830                                 const DWARFDebugInfoEntry *specification_die = m_dwarf2Data->DebugInfo()->GetDIEPtr (specification_die_offset, NULL);
831                                 if (specification_die)
832                                 {
833                                     parent = specification_die->GetParent();
834                                     if (parent)
835                                     {
836                                         parent_tag = parent->Tag();
837 
838                                         if (parent_tag == DW_TAG_class_type || parent_tag == DW_TAG_structure_type)
839                                             is_method = true;
840                                     }
841                                 }
842                             }
843                         }
844                     }
845 
846 
847                     if (is_method)
848                         func_methods.Insert (ConstString(name), die_info);
849                     else
850                         func_basenames.Insert (ConstString(name), die_info);
851                 }
852                 if (mangled.GetMangledName())
853                     func_fullnames.Insert (mangled.GetMangledName(), die_info);
854                 if (mangled.GetDemangledName())
855                     func_fullnames.Insert (mangled.GetDemangledName(), die_info);
856             }
857             break;
858 
859         case DW_TAG_inlined_subroutine:
860             if (has_address)
861             {
862                 if (name)
863                     func_basenames.Insert (ConstString(name), die_info);
864                 if (mangled.GetMangledName())
865                     func_fullnames.Insert (mangled.GetMangledName(), die_info);
866                 if (mangled.GetDemangledName())
867                     func_fullnames.Insert (mangled.GetDemangledName(), die_info);
868             }
869             break;
870 
871         case DW_TAG_base_type:
872         case DW_TAG_class_type:
873         case DW_TAG_constant:
874         case DW_TAG_enumeration_type:
875         case DW_TAG_string_type:
876         case DW_TAG_subroutine_type:
877         case DW_TAG_structure_type:
878         case DW_TAG_union_type:
879         case DW_TAG_typedef:
880             if (name && is_declaration == false)
881             {
882                 types.Insert (ConstString(name), die_info);
883             }
884             break;
885 
886         case DW_TAG_namespace:
887             if (name)
888                 namespaces.Insert (ConstString(name), die_info);
889             break;
890 
891         case DW_TAG_variable:
892             if (name && has_location && is_global_or_static_variable)
893             {
894                 globals.Insert (ConstString(name), die_info);
895                 // Be sure to include variables by their mangled and demangled
896                 // names if they have any since a variable can have a basename
897                 // "i", a mangled named "_ZN12_GLOBAL__N_11iE" and a demangled
898                 // mangled name "(anonymous namespace)::i"...
899                 if (mangled.GetMangledName())
900                     globals.Insert (mangled.GetMangledName(), die_info);
901                 if (mangled.GetDemangledName())
902                     globals.Insert (mangled.GetDemangledName(), die_info);
903             }
904             break;
905 
906         default:
907             continue;
908         }
909     }
910 }
911 
912 
913