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/Module.h"
14 #include "lldb/Core/Stream.h"
15 #include "lldb/Core/Timer.h"
16 #include "lldb/Host/StringConvert.h"
17 #include "lldb/Symbol/CompileUnit.h"
18 #include "lldb/Symbol/LineTable.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Target/ObjCLanguageRuntime.h"
21 
22 #include "DWARFDebugAbbrev.h"
23 #include "DWARFDebugAranges.h"
24 #include "DWARFDebugInfo.h"
25 #include "DWARFDIECollection.h"
26 #include "DWARFFormValue.h"
27 #include "LogChannelDWARF.h"
28 #include "NameToDIE.h"
29 #include "SymbolFileDWARF.h"
30 #include "SymbolFileDWARFDebugMap.h"
31 
32 using namespace lldb;
33 using namespace lldb_private;
34 using namespace std;
35 
36 
37 extern int g_verbose;
38 
39 DWARFCompileUnit::DWARFCompileUnit(SymbolFileDWARF* dwarf2Data) :
40     m_dwarf2Data    (dwarf2Data),
41     m_abbrevs       (NULL),
42     m_user_data     (NULL),
43     m_die_array     (),
44     m_func_aranges_ap (),
45     m_base_addr     (0),
46     m_offset        (DW_INVALID_OFFSET),
47     m_length        (0),
48     m_version       (0),
49     m_addr_size     (DWARFCompileUnit::GetDefaultAddressSize()),
50     m_producer      (eProducerInvalid),
51     m_producer_version_major (0),
52     m_producer_version_minor (0),
53     m_producer_version_update (0),
54     m_language_type (eLanguageTypeUnknown),
55     m_is_dwarf64    (false),
56     m_is_optimized  (eLazyBoolCalculate)
57 {
58 }
59 
60 void
61 DWARFCompileUnit::Clear()
62 {
63     m_offset        = DW_INVALID_OFFSET;
64     m_length        = 0;
65     m_version       = 0;
66     m_abbrevs       = NULL;
67     m_addr_size     = DWARFCompileUnit::GetDefaultAddressSize();
68     m_base_addr     = 0;
69     m_die_array.clear();
70     m_func_aranges_ap.reset();
71     m_user_data     = NULL;
72     m_producer      = eProducerInvalid;
73     m_language_type = eLanguageTypeUnknown;
74     m_is_dwarf64    = false;
75     m_is_optimized  = eLazyBoolCalculate;
76 }
77 
78 bool
79 DWARFCompileUnit::Extract(const DWARFDataExtractor &debug_info, lldb::offset_t *offset_ptr)
80 {
81     Clear();
82 
83     m_offset = *offset_ptr;
84 
85     if (debug_info.ValidOffset(*offset_ptr))
86     {
87         dw_offset_t abbr_offset;
88         const DWARFDebugAbbrev *abbr = m_dwarf2Data->DebugAbbrev();
89         m_length        = debug_info.GetDWARFInitialLength(offset_ptr);
90         m_is_dwarf64    = debug_info.IsDWARF64();
91         m_version       = debug_info.GetU16(offset_ptr);
92         abbr_offset     = debug_info.GetDWARFOffset(offset_ptr);
93         m_addr_size     = debug_info.GetU8 (offset_ptr);
94 
95         bool length_OK = debug_info.ValidOffset(GetNextCompileUnitOffset()-1);
96         bool version_OK = SymbolFileDWARF::SupportedVersion(m_version);
97         bool abbr_offset_OK = m_dwarf2Data->get_debug_abbrev_data().ValidOffset(abbr_offset);
98         bool addr_size_OK = ((m_addr_size == 4) || (m_addr_size == 8));
99 
100         if (length_OK && version_OK && addr_size_OK && abbr_offset_OK && abbr != NULL)
101         {
102             m_abbrevs = abbr->GetAbbreviationDeclarationSet(abbr_offset);
103             return true;
104         }
105 
106         // reset the offset to where we tried to parse from if anything went wrong
107         *offset_ptr = m_offset;
108     }
109 
110     return false;
111 }
112 
113 
114 void
115 DWARFCompileUnit::ClearDIEs(bool keep_compile_unit_die)
116 {
117     if (m_die_array.size() > 1)
118     {
119         // std::vectors never get any smaller when resized to a smaller size,
120         // or when clear() or erase() are called, the size will report that it
121         // is smaller, but the memory allocated remains intact (call capacity()
122         // to see this). So we need to create a temporary vector and swap the
123         // contents which will cause just the internal pointers to be swapped
124         // so that when "tmp_array" goes out of scope, it will destroy the
125         // contents.
126 
127         // Save at least the compile unit DIE
128         DWARFDebugInfoEntry::collection tmp_array;
129         m_die_array.swap(tmp_array);
130         if (keep_compile_unit_die)
131             m_die_array.push_back(tmp_array.front());
132     }
133 }
134 
135 //----------------------------------------------------------------------
136 // ParseCompileUnitDIEsIfNeeded
137 //
138 // Parses a compile unit and indexes its DIEs if it hasn't already been
139 // done.
140 //----------------------------------------------------------------------
141 size_t
142 DWARFCompileUnit::ExtractDIEsIfNeeded (bool cu_die_only)
143 {
144     const size_t initial_die_array_size = m_die_array.size();
145     if ((cu_die_only && initial_die_array_size > 0) || initial_die_array_size > 1)
146         return 0; // Already parsed
147 
148     Timer scoped_timer (__PRETTY_FUNCTION__,
149                         "%8.8x: DWARFCompileUnit::ExtractDIEsIfNeeded( cu_die_only = %i )",
150                         m_offset,
151                         cu_die_only);
152 
153     // Set the offset to that of the first DIE and calculate the start of the
154     // next compilation unit header.
155     lldb::offset_t offset = GetFirstDIEOffset();
156     lldb::offset_t next_cu_offset = GetNextCompileUnitOffset();
157 
158     DWARFDebugInfoEntry die;
159         // Keep a flat array of the DIE for binary lookup by DIE offset
160     if (!cu_die_only)
161     {
162         Log *log (LogChannelDWARF::GetLogIfAny(DWARF_LOG_DEBUG_INFO | DWARF_LOG_LOOKUPS));
163         if (log)
164         {
165             m_dwarf2Data->GetObjectFile()->GetModule()->LogMessageVerboseBacktrace (log,
166                                                                                     "DWARFCompileUnit::ExtractDIEsIfNeeded () for compile unit at .debug_info[0x%8.8x]",
167                                                                                     GetOffset());
168         }
169     }
170 
171     uint32_t depth = 0;
172     // We are in our compile unit, parse starting at the offset
173     // we were told to parse
174     const DWARFDataExtractor& debug_info_data = m_dwarf2Data->get_debug_info_data();
175     std::vector<uint32_t> die_index_stack;
176     die_index_stack.reserve(32);
177     die_index_stack.push_back(0);
178     bool prev_die_had_children = false;
179     DWARFFormValue::FixedFormSizes fixed_form_sizes =
180         DWARFFormValue::GetFixedFormSizesForAddressSize (GetAddressByteSize(), m_is_dwarf64);
181     while (offset < next_cu_offset &&
182            die.FastExtract (debug_info_data, this, fixed_form_sizes, &offset))
183     {
184 //        if (log)
185 //            log->Printf("0x%8.8x: %*.*s%s%s",
186 //                        die.GetOffset(),
187 //                        depth * 2, depth * 2, "",
188 //                        DW_TAG_value_to_name (die.Tag()),
189 //                        die.HasChildren() ? " *" : "");
190 
191         const bool null_die = die.IsNULL();
192         if (depth == 0)
193         {
194             uint64_t base_addr = die.GetAttributeValueAsUnsigned(m_dwarf2Data, this, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
195             if (base_addr == LLDB_INVALID_ADDRESS)
196                 base_addr = die.GetAttributeValueAsUnsigned(m_dwarf2Data, this, DW_AT_entry_pc, 0);
197             SetBaseAddress (base_addr);
198             if (initial_die_array_size == 0)
199                 AddDIE (die);
200             if (cu_die_only)
201                 return 1;
202         }
203         else
204         {
205             if (null_die)
206             {
207                 if (prev_die_had_children)
208                 {
209                     // This will only happen if a DIE says is has children
210                     // but all it contains is a NULL tag. Since we are removing
211                     // the NULL DIEs from the list (saves up to 25% in C++ code),
212                     // we need a way to let the DIE know that it actually doesn't
213                     // have children.
214                     if (!m_die_array.empty())
215                         m_die_array.back().SetEmptyChildren(true);
216                 }
217             }
218             else
219             {
220                 die.SetParentIndex(m_die_array.size() - die_index_stack[depth-1]);
221 
222                 if (die_index_stack.back())
223                     m_die_array[die_index_stack.back()].SetSiblingIndex(m_die_array.size()-die_index_stack.back());
224 
225                 // Only push the DIE if it isn't a NULL DIE
226                     m_die_array.push_back(die);
227             }
228         }
229 
230         if (null_die)
231         {
232             // NULL DIE.
233             if (!die_index_stack.empty())
234                 die_index_stack.pop_back();
235 
236             if (depth > 0)
237                 --depth;
238             if (depth == 0)
239                 break;  // We are done with this compile unit!
240 
241             prev_die_had_children = false;
242         }
243         else
244         {
245             die_index_stack.back() = m_die_array.size() - 1;
246             // Normal DIE
247             const bool die_has_children = die.HasChildren();
248             if (die_has_children)
249             {
250                 die_index_stack.push_back(0);
251                 ++depth;
252             }
253             prev_die_had_children = die_has_children;
254         }
255     }
256 
257     // Give a little bit of info if we encounter corrupt DWARF (our offset
258     // should always terminate at or before the start of the next compilation
259     // unit header).
260     if (offset > next_cu_offset)
261     {
262         m_dwarf2Data->GetObjectFile()->GetModule()->ReportWarning ("DWARF compile unit extends beyond its bounds cu 0x%8.8x at 0x%8.8" PRIx64 "\n",
263                                                                    GetOffset(),
264                                                                    offset);
265     }
266 
267     // Since std::vector objects will double their size, we really need to
268     // make a new array with the perfect size so we don't end up wasting
269     // space. So here we copy and swap to make sure we don't have any extra
270     // memory taken up.
271 
272     if (m_die_array.size () < m_die_array.capacity())
273     {
274         DWARFDebugInfoEntry::collection exact_size_die_array (m_die_array.begin(), m_die_array.end());
275         exact_size_die_array.swap (m_die_array);
276     }
277     Log *verbose_log (LogChannelDWARF::GetLogIfAll (DWARF_LOG_DEBUG_INFO | DWARF_LOG_VERBOSE));
278     if (verbose_log)
279     {
280         StreamString strm;
281         Dump(&strm);
282         if (m_die_array.empty())
283             strm.Printf("error: no DIE for compile unit");
284         else
285             m_die_array[0].Dump(m_dwarf2Data, this, strm, UINT32_MAX);
286         verbose_log->PutCString (strm.GetString().c_str());
287     }
288 
289     return m_die_array.size();
290 }
291 
292 
293 dw_offset_t
294 DWARFCompileUnit::GetAbbrevOffset() const
295 {
296     return m_abbrevs ? m_abbrevs->GetOffset() : DW_INVALID_OFFSET;
297 }
298 
299 
300 
301 bool
302 DWARFCompileUnit::Verify(Stream *s) const
303 {
304     const DWARFDataExtractor& debug_info = m_dwarf2Data->get_debug_info_data();
305     bool valid_offset = debug_info.ValidOffset(m_offset);
306     bool length_OK = debug_info.ValidOffset(GetNextCompileUnitOffset()-1);
307     bool version_OK = SymbolFileDWARF::SupportedVersion(m_version);
308     bool abbr_offset_OK = m_dwarf2Data->get_debug_abbrev_data().ValidOffset(GetAbbrevOffset());
309     bool addr_size_OK = ((m_addr_size == 4) || (m_addr_size == 8));
310     bool verbose = s->GetVerbose();
311     if (valid_offset && length_OK && version_OK && addr_size_OK && abbr_offset_OK)
312     {
313         if (verbose)
314             s->Printf("    0x%8.8x: OK\n", m_offset);
315         return true;
316     }
317     else
318     {
319         s->Printf("    0x%8.8x: ", m_offset);
320 
321         m_dwarf2Data->get_debug_info_data().Dump (s, m_offset, lldb::eFormatHex, 1, Size(), 32, LLDB_INVALID_ADDRESS, 0, 0);
322         s->EOL();
323         if (valid_offset)
324         {
325             if (!length_OK)
326                 s->Printf("        The length (0x%8.8x) for this compile unit is too large for the .debug_info provided.\n", m_length);
327             if (!version_OK)
328                 s->Printf("        The 16 bit compile unit header version is not supported.\n");
329             if (!abbr_offset_OK)
330                 s->Printf("        The offset into the .debug_abbrev section (0x%8.8x) is not valid.\n", GetAbbrevOffset());
331             if (!addr_size_OK)
332                 s->Printf("        The address size is unsupported: 0x%2.2x\n", m_addr_size);
333         }
334         else
335             s->Printf("        The start offset of the compile unit header in the .debug_info is invalid.\n");
336     }
337     return false;
338 }
339 
340 
341 void
342 DWARFCompileUnit::Dump(Stream *s) const
343 {
344     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",
345                 m_offset, m_length, m_version, GetAbbrevOffset(), m_addr_size, GetNextCompileUnitOffset());
346 }
347 
348 
349 static uint8_t g_default_addr_size = 4;
350 
351 uint8_t
352 DWARFCompileUnit::GetAddressByteSize(const DWARFCompileUnit* cu)
353 {
354     if (cu)
355         return cu->GetAddressByteSize();
356     return DWARFCompileUnit::GetDefaultAddressSize();
357 }
358 
359 bool
360 DWARFCompileUnit::IsDWARF64(const DWARFCompileUnit* cu)
361 {
362     if (cu)
363         return cu->IsDWARF64();
364     return false;
365 }
366 
367 uint8_t
368 DWARFCompileUnit::GetDefaultAddressSize()
369 {
370     return g_default_addr_size;
371 }
372 
373 void
374 DWARFCompileUnit::SetDefaultAddressSize(uint8_t addr_size)
375 {
376     g_default_addr_size = addr_size;
377 }
378 
379 void
380 DWARFCompileUnit::BuildAddressRangeTable (SymbolFileDWARF* dwarf2Data,
381                                           DWARFDebugAranges* debug_aranges)
382 {
383     // This function is usually called if there in no .debug_aranges section
384     // in order to produce a compile unit level set of address ranges that
385     // is accurate.
386 
387     size_t num_debug_aranges = debug_aranges->GetNumRanges();
388 
389     // First get the compile unit DIE only and check if it has a DW_AT_ranges
390     const DWARFDebugInfoEntry* die = GetCompileUnitDIEOnly();
391 
392     const dw_offset_t cu_offset = GetOffset();
393     if (die)
394     {
395         DWARFDebugRanges::RangeList ranges;
396         const size_t num_ranges = die->GetAttributeAddressRanges(dwarf2Data, this, ranges, false);
397         if (num_ranges > 0)
398         {
399             // This compile unit has DW_AT_ranges, assume this is correct if it
400             // is present since clang no longer makes .debug_aranges by default
401             // and it emits DW_AT_ranges for DW_TAG_compile_units. GCC also does
402             // this with recent GCC builds.
403             for (size_t i=0; i<num_ranges; ++i)
404             {
405                 const DWARFDebugRanges::RangeList::Entry &range = ranges.GetEntryRef(i);
406                 debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), range.GetRangeEnd());
407             }
408 
409             return; // We got all of our ranges from the DW_AT_ranges attribute
410         }
411     }
412     // We don't have a DW_AT_ranges attribute, so we need to parse the DWARF
413 
414     // If the DIEs weren't parsed, then we don't want all dies for all compile units
415     // to stay loaded when they weren't needed. So we can end up parsing the DWARF
416     // and then throwing them all away to keep memory usage down.
417     const bool clear_dies = ExtractDIEsIfNeeded (false) > 1;
418 
419     die = DIE();
420     if (die)
421         die->BuildAddressRangeTable(dwarf2Data, this, debug_aranges);
422 
423     if (debug_aranges->GetNumRanges() == num_debug_aranges)
424     {
425         // We got nothing from the functions, maybe we have a line tables only
426         // situation. Check the line tables and build the arange table from this.
427         SymbolContext sc;
428         sc.comp_unit = dwarf2Data->GetCompUnitForDWARFCompUnit(this);
429         if (sc.comp_unit)
430         {
431             SymbolFileDWARFDebugMap *debug_map_sym_file = m_dwarf2Data->GetDebugMapSymfile();
432             if (debug_map_sym_file == NULL)
433             {
434                 LineTable *line_table = sc.comp_unit->GetLineTable();
435 
436                 if (line_table)
437                 {
438                     LineTable::FileAddressRanges file_ranges;
439                     const bool append = true;
440                     const size_t num_ranges = line_table->GetContiguousFileAddressRanges (file_ranges, append);
441                     for (uint32_t idx=0; idx<num_ranges; ++idx)
442                     {
443                         const LineTable::FileAddressRanges::Entry &range = file_ranges.GetEntryRef(idx);
444                         debug_aranges->AppendRange(cu_offset, range.GetRangeBase(), range.GetRangeEnd());
445                         printf ("0x%8.8x: [0x%16.16" PRIx64 " - 0x%16.16" PRIx64 ")\n", GetOffset(), range.GetRangeBase(), range.GetRangeEnd());
446                     }
447                 }
448             }
449             else
450                 debug_map_sym_file->AddOSOARanges(dwarf2Data,debug_aranges);
451         }
452     }
453 
454     if (debug_aranges->GetNumRanges() == num_debug_aranges)
455     {
456         // We got nothing from the functions, maybe we have a line tables only
457         // situation. Check the line tables and build the arange table from this.
458         SymbolContext sc;
459         sc.comp_unit = dwarf2Data->GetCompUnitForDWARFCompUnit(this);
460         if (sc.comp_unit)
461         {
462             LineTable *line_table = sc.comp_unit->GetLineTable();
463 
464             if (line_table)
465             {
466                 LineTable::FileAddressRanges file_ranges;
467                 const bool append = true;
468                 const size_t num_ranges = line_table->GetContiguousFileAddressRanges (file_ranges, append);
469                 for (uint32_t idx=0; idx<num_ranges; ++idx)
470                 {
471                     const LineTable::FileAddressRanges::Entry &range = file_ranges.GetEntryRef(idx);
472                     debug_aranges->AppendRange(GetOffset(), range.GetRangeBase(), range.GetRangeEnd());
473                 }
474             }
475         }
476     }
477 
478     // Keep memory down by clearing DIEs if this generate function
479     // caused them to be parsed
480     if (clear_dies)
481         ClearDIEs (true);
482 
483 }
484 
485 
486 const DWARFDebugAranges &
487 DWARFCompileUnit::GetFunctionAranges ()
488 {
489     if (m_func_aranges_ap.get() == NULL)
490     {
491         m_func_aranges_ap.reset (new DWARFDebugAranges());
492         Log *log (LogChannelDWARF::GetLogIfAll(DWARF_LOG_DEBUG_ARANGES));
493 
494         if (log)
495         {
496             m_dwarf2Data->GetObjectFile()->GetModule()->LogMessage (log,
497                                                                     "DWARFCompileUnit::GetFunctionAranges() for compile unit at .debug_info[0x%8.8x]",
498                                                                     GetOffset());
499         }
500         const DWARFDebugInfoEntry* die = DIE();
501         if (die)
502             die->BuildFunctionAddressRangeTable (m_dwarf2Data, this, m_func_aranges_ap.get());
503         const bool minimize = false;
504         m_func_aranges_ap->Sort(minimize);
505     }
506     return *m_func_aranges_ap.get();
507 }
508 
509 bool
510 DWARFCompileUnit::LookupAddress
511 (
512     const dw_addr_t address,
513     DWARFDebugInfoEntry** function_die_handle,
514     DWARFDebugInfoEntry** block_die_handle
515 )
516 {
517     bool success = false;
518 
519     if (function_die_handle != NULL && DIE())
520     {
521 
522         const DWARFDebugAranges &func_aranges = GetFunctionAranges ();
523 
524         // Re-check the aranges auto pointer contents in case it was created above
525         if (!func_aranges.IsEmpty())
526         {
527             *function_die_handle = GetDIEPtr(func_aranges.FindAddress(address));
528             if (*function_die_handle != NULL)
529             {
530                 success = true;
531                 if (block_die_handle != NULL)
532                 {
533                     DWARFDebugInfoEntry* child = (*function_die_handle)->GetFirstChild();
534                     while (child)
535                     {
536                         if (child->LookupAddress(address, m_dwarf2Data, this, NULL, block_die_handle))
537                             break;
538                         child = child->GetSibling();
539                     }
540                 }
541             }
542         }
543     }
544     return success;
545 }
546 
547 //----------------------------------------------------------------------
548 // Compare function DWARFDebugAranges::Range structures
549 //----------------------------------------------------------------------
550 static bool CompareDIEOffset (const DWARFDebugInfoEntry& die1, const DWARFDebugInfoEntry& die2)
551 {
552     return die1.GetOffset() < die2.GetOffset();
553 }
554 
555 //----------------------------------------------------------------------
556 // GetDIEPtr()
557 //
558 // Get the DIE (Debug Information Entry) with the specified offset.
559 //----------------------------------------------------------------------
560 DWARFDebugInfoEntry*
561 DWARFCompileUnit::GetDIEPtr(dw_offset_t die_offset)
562 {
563     if (die_offset != DW_INVALID_OFFSET)
564     {
565         ExtractDIEsIfNeeded (false);
566         DWARFDebugInfoEntry compare_die;
567         compare_die.SetOffset(die_offset);
568         DWARFDebugInfoEntry::iterator end = m_die_array.end();
569         DWARFDebugInfoEntry::iterator pos = lower_bound(m_die_array.begin(), end, compare_die, CompareDIEOffset);
570         if (pos != end)
571         {
572             if (die_offset == (*pos).GetOffset())
573                 return &(*pos);
574         }
575     }
576     return NULL;    // Not found in any compile units
577 }
578 
579 //----------------------------------------------------------------------
580 // GetDIEPtrContainingOffset()
581 //
582 // Get the DIE (Debug Information Entry) that contains the specified
583 // .debug_info offset.
584 //----------------------------------------------------------------------
585 const DWARFDebugInfoEntry*
586 DWARFCompileUnit::GetDIEPtrContainingOffset(dw_offset_t die_offset)
587 {
588     if (die_offset != DW_INVALID_OFFSET)
589     {
590         ExtractDIEsIfNeeded (false);
591         DWARFDebugInfoEntry compare_die;
592         compare_die.SetOffset(die_offset);
593         DWARFDebugInfoEntry::iterator end = m_die_array.end();
594         DWARFDebugInfoEntry::iterator pos = lower_bound(m_die_array.begin(), end, compare_die, CompareDIEOffset);
595         if (pos != end)
596         {
597             if (die_offset >= (*pos).GetOffset())
598             {
599                 DWARFDebugInfoEntry::iterator next = pos + 1;
600                 if (next != end)
601                 {
602                     if (die_offset < (*next).GetOffset())
603                         return &(*pos);
604                 }
605             }
606         }
607     }
608     return NULL;    // Not found in any compile units
609 }
610 
611 
612 
613 size_t
614 DWARFCompileUnit::AppendDIEsWithTag (const dw_tag_t tag, DWARFDIECollection& dies, uint32_t depth) const
615 {
616     size_t old_size = dies.Size();
617     DWARFDebugInfoEntry::const_iterator pos;
618     DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
619     for (pos = m_die_array.begin(); pos != end; ++pos)
620     {
621         if (pos->Tag() == tag)
622             dies.Append (&(*pos));
623     }
624 
625     // Return the number of DIEs added to the collection
626     return dies.Size() - old_size;
627 }
628 
629 //void
630 //DWARFCompileUnit::AddGlobalDIEByIndex (uint32_t die_idx)
631 //{
632 //    m_global_die_indexes.push_back (die_idx);
633 //}
634 //
635 //
636 //void
637 //DWARFCompileUnit::AddGlobal (const DWARFDebugInfoEntry* die)
638 //{
639 //    // Indexes to all file level global and static variables
640 //    m_global_die_indexes;
641 //
642 //    if (m_die_array.empty())
643 //        return;
644 //
645 //    const DWARFDebugInfoEntry* first_die = &m_die_array[0];
646 //    const DWARFDebugInfoEntry* end = first_die + m_die_array.size();
647 //    if (first_die <= die && die < end)
648 //        m_global_die_indexes.push_back (die - first_die);
649 //}
650 
651 
652 void
653 DWARFCompileUnit::Index (const uint32_t cu_idx,
654                          NameToDIE& func_basenames,
655                          NameToDIE& func_fullnames,
656                          NameToDIE& func_methods,
657                          NameToDIE& func_selectors,
658                          NameToDIE& objc_class_selectors,
659                          NameToDIE& globals,
660                          NameToDIE& types,
661                          NameToDIE& namespaces)
662 {
663     DWARFFormValue::FixedFormSizes fixed_form_sizes =
664         DWARFFormValue::GetFixedFormSizesForAddressSize (GetAddressByteSize(), m_is_dwarf64);
665 
666     Log *log (LogChannelDWARF::GetLogIfAll (DWARF_LOG_LOOKUPS));
667 
668     if (log)
669     {
670         m_dwarf2Data->GetObjectFile()->GetModule()->LogMessage (log,
671                                                                 "DWARFCompileUnit::Index() for compile unit at .debug_info[0x%8.8x]",
672                                                                 GetOffset());
673     }
674 
675     const LanguageType cu_language = GetLanguageType();
676     DWARFDebugInfoEntry::const_iterator pos;
677     DWARFDebugInfoEntry::const_iterator begin = m_die_array.begin();
678     DWARFDebugInfoEntry::const_iterator end = m_die_array.end();
679     for (pos = begin; pos != end; ++pos)
680     {
681         const DWARFDebugInfoEntry &die = *pos;
682 
683         const dw_tag_t tag = die.Tag();
684 
685         switch (tag)
686         {
687         case DW_TAG_subprogram:
688         case DW_TAG_inlined_subroutine:
689         case DW_TAG_base_type:
690         case DW_TAG_class_type:
691         case DW_TAG_constant:
692         case DW_TAG_enumeration_type:
693         case DW_TAG_string_type:
694         case DW_TAG_subroutine_type:
695         case DW_TAG_structure_type:
696         case DW_TAG_union_type:
697         case DW_TAG_typedef:
698         case DW_TAG_namespace:
699         case DW_TAG_variable:
700         case DW_TAG_unspecified_type:
701             break;
702 
703         default:
704             continue;
705         }
706 
707         DWARFDebugInfoEntry::Attributes attributes;
708         const char *name = NULL;
709         const char *mangled_cstr = NULL;
710         bool is_declaration = false;
711         //bool is_artificial = false;
712         bool has_address = false;
713         bool has_location = false;
714         bool is_global_or_static_variable = false;
715 
716         dw_offset_t specification_die_offset = DW_INVALID_OFFSET;
717         const size_t num_attributes = die.GetAttributes(m_dwarf2Data, this, fixed_form_sizes, attributes);
718         if (num_attributes > 0)
719         {
720             for (uint32_t i=0; i<num_attributes; ++i)
721             {
722                 dw_attr_t attr = attributes.AttributeAtIndex(i);
723                 DWARFFormValue form_value;
724                 switch (attr)
725                 {
726                 case DW_AT_name:
727                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
728                         name = form_value.AsCString(m_dwarf2Data);
729                     break;
730 
731                 case DW_AT_declaration:
732                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
733                         is_declaration = form_value.Unsigned() != 0;
734                     break;
735 
736 //                case DW_AT_artificial:
737 //                    if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
738 //                        is_artificial = form_value.Unsigned() != 0;
739 //                    break;
740 
741                 case DW_AT_MIPS_linkage_name:
742                 case DW_AT_linkage_name:
743                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
744                         mangled_cstr = form_value.AsCString(m_dwarf2Data);
745                     break;
746 
747                 case DW_AT_low_pc:
748                 case DW_AT_high_pc:
749                 case DW_AT_ranges:
750                     has_address = true;
751                     break;
752 
753                 case DW_AT_entry_pc:
754                     has_address = true;
755                     break;
756 
757                 case DW_AT_location:
758                     has_location = true;
759                     if (tag == DW_TAG_variable)
760                     {
761                         const DWARFDebugInfoEntry* parent_die = die.GetParent();
762                         while ( parent_die != NULL )
763                         {
764                             switch (parent_die->Tag())
765                             {
766                             case DW_TAG_subprogram:
767                             case DW_TAG_lexical_block:
768                             case DW_TAG_inlined_subroutine:
769                                 // Even if this is a function level static, we don't add it. We could theoretically
770                                 // add these if we wanted to by introspecting into the DW_AT_location and seeing
771                                 // if the location describes a hard coded address, but we dont want the performance
772                                 // penalty of that right now.
773                                 is_global_or_static_variable = false;
774 //                              if (attributes.ExtractFormValueAtIndex(dwarf2Data, i, form_value))
775 //                              {
776 //                                  // If we have valid block data, then we have location expression bytes
777 //                                  // that are fixed (not a location list).
778 //                                  const uint8_t *block_data = form_value.BlockData();
779 //                                  if (block_data)
780 //                                  {
781 //                                      uint32_t block_length = form_value.Unsigned();
782 //                                      if (block_length == 1 + attributes.CompileUnitAtIndex(i)->GetAddressByteSize())
783 //                                      {
784 //                                          if (block_data[0] == DW_OP_addr)
785 //                                              add_die = true;
786 //                                      }
787 //                                  }
788 //                              }
789                                 parent_die = NULL;  // Terminate the while loop.
790                                 break;
791 
792                             case DW_TAG_compile_unit:
793                                 is_global_or_static_variable = true;
794                                 parent_die = NULL;  // Terminate the while loop.
795                                 break;
796 
797                             default:
798                                 parent_die = parent_die->GetParent();   // Keep going in the while loop.
799                                 break;
800                             }
801                         }
802                     }
803                     break;
804 
805                 case DW_AT_specification:
806                     if (attributes.ExtractFormValueAtIndex(m_dwarf2Data, i, form_value))
807                         specification_die_offset = form_value.Reference();
808                     break;
809                 }
810             }
811         }
812 
813         switch (tag)
814         {
815         case DW_TAG_subprogram:
816             if (has_address)
817             {
818                 if (name)
819                 {
820                     // Note, this check is also done in ParseMethodName, but since this is a hot loop, we do the
821                     // simple inlined check outside the call.
822                     ObjCLanguageRuntime::MethodName objc_method(name, true);
823                     if (objc_method.IsValid(true))
824                     {
825                         ConstString objc_class_name_with_category (objc_method.GetClassNameWithCategory());
826                         ConstString objc_selector_name (objc_method.GetSelector());
827                         ConstString objc_fullname_no_category_name (objc_method.GetFullNameWithoutCategory(true));
828                         ConstString objc_class_name_no_category (objc_method.GetClassName());
829                         func_fullnames.Insert (ConstString(name), die.GetOffset());
830                         if (objc_class_name_with_category)
831                             objc_class_selectors.Insert(objc_class_name_with_category, die.GetOffset());
832                         if (objc_class_name_no_category && objc_class_name_no_category != objc_class_name_with_category)
833                             objc_class_selectors.Insert(objc_class_name_no_category, die.GetOffset());
834                         if (objc_selector_name)
835                             func_selectors.Insert (objc_selector_name, die.GetOffset());
836                         if (objc_fullname_no_category_name)
837                             func_fullnames.Insert (objc_fullname_no_category_name, die.GetOffset());
838                     }
839                     // If we have a mangled name, then the DW_AT_name attribute
840                     // is usually the method name without the class or any parameters
841                     const DWARFDebugInfoEntry *parent = die.GetParent();
842                     bool is_method = false;
843                     if (parent)
844                     {
845                         dw_tag_t parent_tag = parent->Tag();
846                         if (parent_tag == DW_TAG_class_type || parent_tag == DW_TAG_structure_type)
847                         {
848                             is_method = true;
849                         }
850                         else
851                         {
852                             if (specification_die_offset != DW_INVALID_OFFSET)
853                             {
854                                 const DWARFDebugInfoEntry *specification_die = m_dwarf2Data->DebugInfo()->GetDIEPtr (specification_die_offset, NULL);
855                                 if (specification_die)
856                                 {
857                                     parent = specification_die->GetParent();
858                                     if (parent)
859                                     {
860                                         parent_tag = parent->Tag();
861 
862                                         if (parent_tag == DW_TAG_class_type || parent_tag == DW_TAG_structure_type)
863                                             is_method = true;
864                                     }
865                                 }
866                             }
867                         }
868                     }
869 
870 
871                     if (is_method)
872                         func_methods.Insert (ConstString(name), die.GetOffset());
873                     else
874                         func_basenames.Insert (ConstString(name), die.GetOffset());
875 
876                     if (!is_method && !mangled_cstr && !objc_method.IsValid(true))
877                         func_fullnames.Insert (ConstString(name), die.GetOffset());
878                 }
879                 if (mangled_cstr)
880                 {
881                     // Make sure our mangled name isn't the same string table entry
882                     // as our name. If it starts with '_', then it is ok, else compare
883                     // the string to make sure it isn't the same and we don't end up
884                     // with duplicate entries
885                     if (name != mangled_cstr && ((mangled_cstr[0] == '_') || (name && ::strcmp(name, mangled_cstr) != 0)))
886                     {
887                         Mangled mangled (ConstString(mangled_cstr), true);
888                         func_fullnames.Insert (mangled.GetMangledName(), die.GetOffset());
889                         ConstString demangled = mangled.GetDemangledName(cu_language);
890                         if (demangled)
891                             func_fullnames.Insert (demangled, die.GetOffset());
892                     }
893                 }
894             }
895             break;
896 
897         case DW_TAG_inlined_subroutine:
898             if (has_address)
899             {
900                 if (name)
901                     func_basenames.Insert (ConstString(name), die.GetOffset());
902                 if (mangled_cstr)
903                 {
904                     // Make sure our mangled name isn't the same string table entry
905                     // as our name. If it starts with '_', then it is ok, else compare
906                     // the string to make sure it isn't the same and we don't end up
907                     // with duplicate entries
908                     if (name != mangled_cstr && ((mangled_cstr[0] == '_') || (::strcmp(name, mangled_cstr) != 0)))
909                     {
910                         Mangled mangled (ConstString(mangled_cstr), true);
911                         func_fullnames.Insert (mangled.GetMangledName(), die.GetOffset());
912                         ConstString demangled = mangled.GetDemangledName(cu_language);
913                         if (demangled)
914                             func_fullnames.Insert (demangled, die.GetOffset());
915                     }
916                 }
917                 else
918                     func_fullnames.Insert (ConstString(name), die.GetOffset());
919             }
920             break;
921 
922         case DW_TAG_base_type:
923         case DW_TAG_class_type:
924         case DW_TAG_constant:
925         case DW_TAG_enumeration_type:
926         case DW_TAG_string_type:
927         case DW_TAG_subroutine_type:
928         case DW_TAG_structure_type:
929         case DW_TAG_union_type:
930         case DW_TAG_typedef:
931         case DW_TAG_unspecified_type:
932             if (name && is_declaration == false)
933             {
934                 types.Insert (ConstString(name), die.GetOffset());
935             }
936             break;
937 
938         case DW_TAG_namespace:
939             if (name)
940                 namespaces.Insert (ConstString(name), die.GetOffset());
941             break;
942 
943         case DW_TAG_variable:
944             if (name && has_location && is_global_or_static_variable)
945             {
946                 globals.Insert (ConstString(name), die.GetOffset());
947                 // Be sure to include variables by their mangled and demangled
948                 // names if they have any since a variable can have a basename
949                 // "i", a mangled named "_ZN12_GLOBAL__N_11iE" and a demangled
950                 // mangled name "(anonymous namespace)::i"...
951 
952                 // Make sure our mangled name isn't the same string table entry
953                 // as our name. If it starts with '_', then it is ok, else compare
954                 // the string to make sure it isn't the same and we don't end up
955                 // with duplicate entries
956                 if (mangled_cstr && name != mangled_cstr && ((mangled_cstr[0] == '_') || (::strcmp(name, mangled_cstr) != 0)))
957                 {
958                     Mangled mangled (ConstString(mangled_cstr), true);
959                     globals.Insert (mangled.GetMangledName(), die.GetOffset());
960                     ConstString demangled = mangled.GetDemangledName(cu_language);
961                     if (demangled)
962                         globals.Insert (demangled, die.GetOffset());
963                 }
964             }
965             break;
966 
967         default:
968             continue;
969         }
970     }
971 }
972 
973 bool
974 DWARFCompileUnit::Supports_unnamed_objc_bitfields ()
975 {
976     if (GetProducer() == eProducerClang)
977     {
978         const uint32_t major_version = GetProducerVersionMajor();
979         if (major_version > 425 || (major_version == 425 && GetProducerVersionUpdate() >= 13))
980             return true;
981         else
982             return false;
983     }
984     return true; // Assume all other compilers didn't have incorrect ObjC bitfield info
985 }
986 
987 bool
988 DWARFCompileUnit::Supports_DW_AT_APPLE_objc_complete_type ()
989 {
990     if (GetProducer() == eProducerLLVMGCC)
991         return false;
992     return true;
993 }
994 
995 bool
996 DWARFCompileUnit::DW_AT_decl_file_attributes_are_invalid()
997 {
998     // llvm-gcc makes completely invalid decl file attributes and won't ever
999     // be fixed, so we need to know to ignore these.
1000     return GetProducer() == eProducerLLVMGCC;
1001 }
1002 
1003 void
1004 DWARFCompileUnit::ParseProducerInfo ()
1005 {
1006     m_producer_version_major = UINT32_MAX;
1007     m_producer_version_minor = UINT32_MAX;
1008     m_producer_version_update = UINT32_MAX;
1009 
1010     const DWARFDebugInfoEntry *die = GetCompileUnitDIEOnly();
1011     if (die)
1012     {
1013 
1014         const char *producer_cstr = die->GetAttributeValueAsString(m_dwarf2Data, this, DW_AT_producer, NULL);
1015         if (producer_cstr)
1016         {
1017             RegularExpression llvm_gcc_regex("^4\\.[012]\\.[01] \\(Based on Apple Inc\\. build [0-9]+\\) \\(LLVM build [\\.0-9]+\\)$");
1018             if (llvm_gcc_regex.Execute (producer_cstr))
1019             {
1020                 m_producer = eProducerLLVMGCC;
1021             }
1022             else if (strstr(producer_cstr, "clang"))
1023             {
1024                 static RegularExpression g_clang_version_regex("clang-([0-9]+)\\.([0-9]+)\\.([0-9]+)");
1025                 RegularExpression::Match regex_match(3);
1026                 if (g_clang_version_regex.Execute (producer_cstr, &regex_match))
1027                 {
1028                     std::string str;
1029                     if (regex_match.GetMatchAtIndex (producer_cstr, 1, str))
1030                         m_producer_version_major = StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
1031                     if (regex_match.GetMatchAtIndex (producer_cstr, 2, str))
1032                         m_producer_version_minor = StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
1033                     if (regex_match.GetMatchAtIndex (producer_cstr, 3, str))
1034                         m_producer_version_update = StringConvert::ToUInt32(str.c_str(), UINT32_MAX, 10);
1035                 }
1036                 m_producer = eProducerClang;
1037             }
1038             else if (strstr(producer_cstr, "GNU"))
1039                 m_producer = eProducerGCC;
1040         }
1041     }
1042     if (m_producer == eProducerInvalid)
1043         m_producer = eProcucerOther;
1044 }
1045 
1046 DWARFCompileUnit::Producer
1047 DWARFCompileUnit::GetProducer ()
1048 {
1049     if (m_producer == eProducerInvalid)
1050         ParseProducerInfo ();
1051     return m_producer;
1052 }
1053 
1054 
1055 uint32_t
1056 DWARFCompileUnit::GetProducerVersionMajor()
1057 {
1058     if (m_producer_version_major == 0)
1059         ParseProducerInfo ();
1060     return m_producer_version_major;
1061 }
1062 
1063 uint32_t
1064 DWARFCompileUnit::GetProducerVersionMinor()
1065 {
1066     if (m_producer_version_minor == 0)
1067         ParseProducerInfo ();
1068     return m_producer_version_minor;
1069 }
1070 
1071 uint32_t
1072 DWARFCompileUnit::GetProducerVersionUpdate()
1073 {
1074     if (m_producer_version_update == 0)
1075         ParseProducerInfo ();
1076     return m_producer_version_update;
1077 }
1078 
1079 LanguageType
1080 DWARFCompileUnit::LanguageTypeFromDWARF(uint64_t val)
1081 {
1082     // Note: user languages between lo_user and hi_user
1083     // must be handled explicitly here.
1084     switch (val)
1085     {
1086     case DW_LANG_Mips_Assembler:
1087         return eLanguageTypeMipsAssembler;
1088     case 0x8e57: // FIXME: needs to be added to llvm
1089         return eLanguageTypeExtRenderScript;
1090     default:
1091         return static_cast<LanguageType>(val);
1092     }
1093 }
1094 
1095 LanguageType
1096 DWARFCompileUnit::GetLanguageType()
1097 {
1098     if (m_language_type != eLanguageTypeUnknown)
1099         return m_language_type;
1100 
1101     const DWARFDebugInfoEntry *die = GetCompileUnitDIEOnly();
1102     if (die)
1103         m_language_type = LanguageTypeFromDWARF(die->GetAttributeValueAsUnsigned(m_dwarf2Data, this, DW_AT_language, 0));
1104     return m_language_type;
1105 }
1106 
1107 bool
1108 DWARFCompileUnit::IsDWARF64() const
1109 {
1110     return m_is_dwarf64;
1111 }
1112 
1113 bool
1114 DWARFCompileUnit::GetIsOptimized ()
1115 {
1116     if (m_is_optimized == eLazyBoolCalculate)
1117     {
1118         const DWARFDebugInfoEntry *die = GetCompileUnitDIEOnly();
1119         if (die)
1120         {
1121             m_is_optimized = eLazyBoolNo;
1122             if (die->GetAttributeValueAsUnsigned (m_dwarf2Data, this, DW_AT_APPLE_optimized, 0) == 1)
1123             {
1124                 m_is_optimized = eLazyBoolYes;
1125             }
1126         }
1127     }
1128     if (m_is_optimized == eLazyBoolYes)
1129     {
1130         return true;
1131     }
1132     else
1133     {
1134         return false;
1135     }
1136 }
1137