1 //===-- DWARFDebugInfoEntry.cpp ---------------------------------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "DWARFDebugInfoEntry.h"
10 
11 #include <assert.h>
12 
13 #include <algorithm>
14 
15 #include "llvm/Support/LEB128.h"
16 
17 #include "lldb/Core/Module.h"
18 #include "lldb/Expression/DWARFExpression.h"
19 #include "lldb/Symbol/ObjectFile.h"
20 #include "lldb/Utility/Stream.h"
21 
22 #include "DWARFCompileUnit.h"
23 #include "DWARFDebugAbbrev.h"
24 #include "DWARFDebugAranges.h"
25 #include "DWARFDebugInfo.h"
26 #include "DWARFDebugRanges.h"
27 #include "DWARFDeclContext.h"
28 #include "DWARFFormValue.h"
29 #include "DWARFUnit.h"
30 #include "SymbolFileDWARF.h"
31 #include "SymbolFileDWARFDwo.h"
32 
33 using namespace lldb_private;
34 using namespace std;
35 extern int g_verbose;
36 
37 // Extract a debug info entry for a given DWARFUnit from the data
38 // starting at the offset in offset_ptr
39 bool DWARFDebugInfoEntry::Extract(const DWARFDataExtractor &data,
40                                   const DWARFUnit *cu,
41                                   lldb::offset_t *offset_ptr) {
42   m_offset = *offset_ptr;
43   m_parent_idx = 0;
44   m_sibling_idx = 0;
45   const uint64_t abbr_idx = data.GetULEB128(offset_ptr);
46   lldbassert(abbr_idx <= UINT16_MAX);
47   m_abbr_idx = abbr_idx;
48 
49   // assert (fixed_form_sizes);  // For best performance this should be
50   // specified!
51 
52   if (m_abbr_idx) {
53     lldb::offset_t offset = *offset_ptr;
54     const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu);
55     if (abbrevDecl == nullptr) {
56       cu->GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
57           "{0x%8.8x}: invalid abbreviation code %u, please file a bug and "
58           "attach the file at the start of this error message",
59           m_offset, (unsigned)abbr_idx);
60       // WE can't parse anymore if the DWARF is borked...
61       *offset_ptr = UINT32_MAX;
62       return false;
63     }
64     m_tag = abbrevDecl->Tag();
65     m_has_children = abbrevDecl->HasChildren();
66     // Skip all data in the .debug_info or .debug_types for the attributes
67     const uint32_t numAttributes = abbrevDecl->NumAttributes();
68     uint32_t i;
69     dw_form_t form;
70     for (i = 0; i < numAttributes; ++i) {
71       form = abbrevDecl->GetFormByIndexUnchecked(i);
72       llvm::Optional<uint8_t> fixed_skip_size =
73           DWARFFormValue::GetFixedSize(form, cu);
74       if (fixed_skip_size)
75         offset += *fixed_skip_size;
76       else {
77         bool form_is_indirect = false;
78         do {
79           form_is_indirect = false;
80           uint32_t form_size = 0;
81           switch (form) {
82           // Blocks if inlined data that have a length field and the data bytes
83           // inlined in the .debug_info/.debug_types
84           case DW_FORM_exprloc:
85           case DW_FORM_block:
86             form_size = data.GetULEB128(&offset);
87             break;
88           case DW_FORM_block1:
89             form_size = data.GetU8_unchecked(&offset);
90             break;
91           case DW_FORM_block2:
92             form_size = data.GetU16_unchecked(&offset);
93             break;
94           case DW_FORM_block4:
95             form_size = data.GetU32_unchecked(&offset);
96             break;
97 
98           // Inlined NULL terminated C-strings
99           case DW_FORM_string:
100             data.GetCStr(&offset);
101             break;
102 
103           // Compile unit address sized values
104           case DW_FORM_addr:
105             form_size = cu->GetAddressByteSize();
106             break;
107           case DW_FORM_ref_addr:
108             if (cu->GetVersion() <= 2)
109               form_size = cu->GetAddressByteSize();
110             else
111               form_size = 4;
112             break;
113 
114           // 0 sized form
115           case DW_FORM_flag_present:
116             form_size = 0;
117             break;
118 
119           // 1 byte values
120           case DW_FORM_addrx1:
121           case DW_FORM_data1:
122           case DW_FORM_flag:
123           case DW_FORM_ref1:
124           case DW_FORM_strx1:
125             form_size = 1;
126             break;
127 
128           // 2 byte values
129           case DW_FORM_addrx2:
130           case DW_FORM_data2:
131           case DW_FORM_ref2:
132           case DW_FORM_strx2:
133             form_size = 2;
134             break;
135 
136           // 3 byte values
137           case DW_FORM_addrx3:
138           case DW_FORM_strx3:
139             form_size = 3;
140             break;
141 
142           // 4 byte values
143           case DW_FORM_addrx4:
144           case DW_FORM_data4:
145           case DW_FORM_ref4:
146           case DW_FORM_strx4:
147             form_size = 4;
148             break;
149 
150           // 8 byte values
151           case DW_FORM_data8:
152           case DW_FORM_ref8:
153           case DW_FORM_ref_sig8:
154             form_size = 8;
155             break;
156 
157           // signed or unsigned LEB 128 values
158           case DW_FORM_addrx:
159           case DW_FORM_loclistx:
160           case DW_FORM_rnglistx:
161           case DW_FORM_sdata:
162           case DW_FORM_udata:
163           case DW_FORM_ref_udata:
164           case DW_FORM_GNU_addr_index:
165           case DW_FORM_GNU_str_index:
166           case DW_FORM_strx:
167             data.Skip_LEB128(&offset);
168             break;
169 
170           case DW_FORM_indirect:
171             form_is_indirect = true;
172             form = data.GetULEB128(&offset);
173             break;
174 
175           case DW_FORM_strp:
176           case DW_FORM_sec_offset:
177             data.GetU32(&offset);
178             break;
179 
180           case DW_FORM_implicit_const:
181             form_size = 0;
182             break;
183 
184           default:
185             *offset_ptr = m_offset;
186             return false;
187           }
188           offset += form_size;
189 
190         } while (form_is_indirect);
191       }
192     }
193     *offset_ptr = offset;
194     return true;
195   } else {
196     m_tag = llvm::dwarf::DW_TAG_null;
197     m_has_children = false;
198     return true; // NULL debug tag entry
199   }
200 
201   return false;
202 }
203 
204 static DWARFRangeList GetRangesOrReportError(DWARFUnit &unit,
205                                              const DWARFDebugInfoEntry &die,
206                                              const DWARFFormValue &value) {
207   llvm::Expected<DWARFRangeList> expected_ranges =
208       (value.Form() == DW_FORM_rnglistx)
209           ? unit.FindRnglistFromIndex(value.Unsigned())
210           : unit.FindRnglistFromOffset(value.Unsigned());
211   if (expected_ranges)
212     return std::move(*expected_ranges);
213   unit.GetSymbolFileDWARF().GetObjectFile()->GetModule()->ReportError(
214       "{0x%8.8x}: DIE has DW_AT_ranges(0x%" PRIx64 ") attribute, but "
215       "range extraction failed (%s), please file a bug "
216       "and attach the file at the start of this error message",
217       die.GetOffset(), value.Unsigned(),
218       toString(expected_ranges.takeError()).c_str());
219   return DWARFRangeList();
220 }
221 
222 // GetDIENamesAndRanges
223 //
224 // Gets the valid address ranges for a given DIE by looking for a
225 // DW_AT_low_pc/DW_AT_high_pc pair, DW_AT_entry_pc, or DW_AT_ranges attributes.
226 bool DWARFDebugInfoEntry::GetDIENamesAndRanges(
227     DWARFUnit *cu, const char *&name, const char *&mangled,
228     DWARFRangeList &ranges, int &decl_file, int &decl_line, int &decl_column,
229     int &call_file, int &call_line, int &call_column,
230     DWARFExpression *frame_base) const {
231   dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
232   dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
233   std::vector<DWARFDIE> dies;
234   bool set_frame_base_loclist_addr = false;
235 
236   const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu);
237 
238   SymbolFileDWARF &dwarf = cu->GetSymbolFileDWARF();
239   lldb::ModuleSP module = dwarf.GetObjectFile()->GetModule();
240 
241   if (abbrevDecl) {
242     const DWARFDataExtractor &data = cu->GetData();
243     lldb::offset_t offset = GetFirstAttributeOffset();
244 
245     if (!data.ValidOffset(offset))
246       return false;
247 
248     const uint32_t numAttributes = abbrevDecl->NumAttributes();
249     bool do_offset = false;
250 
251     for (uint32_t i = 0; i < numAttributes; ++i) {
252       DWARFFormValue form_value(cu);
253       dw_attr_t attr;
254       abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value);
255 
256       if (form_value.ExtractValue(data, &offset)) {
257         switch (attr) {
258         case DW_AT_low_pc:
259           lo_pc = form_value.Address();
260 
261           if (do_offset)
262             hi_pc += lo_pc;
263           do_offset = false;
264           break;
265 
266         case DW_AT_entry_pc:
267           lo_pc = form_value.Address();
268           break;
269 
270         case DW_AT_high_pc:
271           if (form_value.Form() == DW_FORM_addr ||
272               form_value.Form() == DW_FORM_addrx ||
273               form_value.Form() == DW_FORM_GNU_addr_index) {
274             hi_pc = form_value.Address();
275           } else {
276             hi_pc = form_value.Unsigned();
277             if (lo_pc == LLDB_INVALID_ADDRESS)
278               do_offset = hi_pc != LLDB_INVALID_ADDRESS;
279             else
280               hi_pc += lo_pc; // DWARF 4 introduces <offset-from-lo-pc> to save
281                               // on relocations
282           }
283           break;
284 
285         case DW_AT_ranges:
286           ranges = GetRangesOrReportError(*cu, *this, form_value);
287           break;
288 
289         case DW_AT_name:
290           if (name == nullptr)
291             name = form_value.AsCString();
292           break;
293 
294         case DW_AT_MIPS_linkage_name:
295         case DW_AT_linkage_name:
296           if (mangled == nullptr)
297             mangled = form_value.AsCString();
298           break;
299 
300         case DW_AT_abstract_origin:
301           dies.push_back(form_value.Reference());
302           break;
303 
304         case DW_AT_specification:
305           dies.push_back(form_value.Reference());
306           break;
307 
308         case DW_AT_decl_file:
309           if (decl_file == 0)
310             decl_file = form_value.Unsigned();
311           break;
312 
313         case DW_AT_decl_line:
314           if (decl_line == 0)
315             decl_line = form_value.Unsigned();
316           break;
317 
318         case DW_AT_decl_column:
319           if (decl_column == 0)
320             decl_column = form_value.Unsigned();
321           break;
322 
323         case DW_AT_call_file:
324           if (call_file == 0)
325             call_file = form_value.Unsigned();
326           break;
327 
328         case DW_AT_call_line:
329           if (call_line == 0)
330             call_line = form_value.Unsigned();
331           break;
332 
333         case DW_AT_call_column:
334           if (call_column == 0)
335             call_column = form_value.Unsigned();
336           break;
337 
338         case DW_AT_frame_base:
339           if (frame_base) {
340             if (form_value.BlockData()) {
341               uint32_t block_offset =
342                   form_value.BlockData() - data.GetDataStart();
343               uint32_t block_length = form_value.Unsigned();
344               *frame_base = DWARFExpression(
345                   module, DataExtractor(data, block_offset, block_length), cu);
346             } else {
347               DataExtractor data = cu->GetLocationData();
348               const dw_offset_t offset = form_value.Unsigned();
349               if (data.ValidOffset(offset)) {
350                 data = DataExtractor(data, offset, data.GetByteSize() - offset);
351                 *frame_base = DWARFExpression(module, data, cu);
352                 if (lo_pc != LLDB_INVALID_ADDRESS) {
353                   assert(lo_pc >= cu->GetBaseAddress());
354                   frame_base->SetLocationListAddresses(cu->GetBaseAddress(),
355                                                        lo_pc);
356                 } else {
357                   set_frame_base_loclist_addr = true;
358                 }
359               }
360             }
361           }
362           break;
363 
364         default:
365           break;
366         }
367       }
368     }
369   }
370 
371   if (ranges.IsEmpty()) {
372     if (lo_pc != LLDB_INVALID_ADDRESS) {
373       if (hi_pc != LLDB_INVALID_ADDRESS && hi_pc > lo_pc)
374         ranges.Append(DWARFRangeList::Entry(lo_pc, hi_pc - lo_pc));
375       else
376         ranges.Append(DWARFRangeList::Entry(lo_pc, 0));
377     }
378   }
379 
380   if (set_frame_base_loclist_addr) {
381     dw_addr_t lowest_range_pc = ranges.GetMinRangeBase(0);
382     assert(lowest_range_pc >= cu->GetBaseAddress());
383     frame_base->SetLocationListAddresses(cu->GetBaseAddress(), lowest_range_pc);
384   }
385 
386   if (ranges.IsEmpty() || name == nullptr || mangled == nullptr) {
387     for (const DWARFDIE &die : dies) {
388       if (die) {
389         die.GetDIE()->GetDIENamesAndRanges(die.GetCU(), name, mangled, ranges,
390                                            decl_file, decl_line, decl_column,
391                                            call_file, call_line, call_column);
392       }
393     }
394   }
395   return !ranges.IsEmpty();
396 }
397 
398 // Dump
399 //
400 // Dumps a debug information entry and all of it's attributes to the specified
401 // stream.
402 void DWARFDebugInfoEntry::Dump(const DWARFUnit *cu, Stream &s,
403                                uint32_t recurse_depth) const {
404   const DWARFDataExtractor &data = cu->GetData();
405   lldb::offset_t offset = m_offset;
406 
407   if (data.ValidOffset(offset)) {
408     dw_uleb128_t abbrCode = data.GetULEB128(&offset);
409 
410     s.Printf("\n0x%8.8x: ", m_offset);
411     s.Indent();
412     if (abbrCode != m_abbr_idx) {
413       s.Printf("error: DWARF has been modified\n");
414     } else if (abbrCode) {
415       const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu);
416       if (abbrevDecl) {
417         s.PutCString(DW_TAG_value_to_name(abbrevDecl->Tag()));
418         s.Printf(" [%u] %c\n", abbrCode, abbrevDecl->HasChildren() ? '*' : ' ');
419 
420         // Dump all data in the .debug_info/.debug_types for the attributes
421         const uint32_t numAttributes = abbrevDecl->NumAttributes();
422         for (uint32_t i = 0; i < numAttributes; ++i) {
423           DWARFFormValue form_value(cu);
424           dw_attr_t attr;
425           abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value);
426 
427           DumpAttribute(cu, data, &offset, s, attr, form_value);
428         }
429 
430         const DWARFDebugInfoEntry *child = GetFirstChild();
431         if (recurse_depth > 0 && child) {
432           s.IndentMore();
433 
434           while (child) {
435             child->Dump(cu, s, recurse_depth - 1);
436             child = child->GetSibling();
437           }
438           s.IndentLess();
439         }
440       } else
441         s.Printf("Abbreviation code note found in 'debug_abbrev' class for "
442                  "code: %u\n",
443                  abbrCode);
444     } else {
445       s.Printf("NULL\n");
446     }
447   }
448 }
449 
450 // DumpAttribute
451 //
452 // Dumps a debug information entry attribute along with it's form. Any special
453 // display of attributes is done (disassemble location lists, show enumeration
454 // values for attributes, etc).
455 void DWARFDebugInfoEntry::DumpAttribute(
456     const DWARFUnit *cu, const DWARFDataExtractor &data,
457     lldb::offset_t *offset_ptr, Stream &s, dw_attr_t attr,
458     DWARFFormValue &form_value) {
459   bool show_form = s.GetFlags().Test(DWARFDebugInfo::eDumpFlag_ShowForm);
460 
461   s.Printf("            ");
462   s.Indent(DW_AT_value_to_name(attr));
463 
464   if (show_form) {
465     s.Printf("[%s", DW_FORM_value_to_name(form_value.Form()));
466   }
467 
468   if (!form_value.ExtractValue(data, offset_ptr))
469     return;
470 
471   if (show_form) {
472     if (form_value.Form() == DW_FORM_indirect) {
473       s.Printf(" [%s]", DW_FORM_value_to_name(form_value.Form()));
474     }
475 
476     s.PutCString("] ");
477   }
478 
479   s.PutCString("( ");
480 
481   // Check to see if we have any special attribute formatters
482   switch (attr) {
483   case DW_AT_stmt_list:
484     s.Printf("0x%8.8" PRIx64, form_value.Unsigned());
485     break;
486 
487   case DW_AT_language:
488     s.PutCString(DW_LANG_value_to_name(form_value.Unsigned()));
489     break;
490 
491   case DW_AT_encoding:
492     s.PutCString(DW_ATE_value_to_name(form_value.Unsigned()));
493     break;
494 
495   case DW_AT_frame_base:
496   case DW_AT_location:
497   case DW_AT_data_member_location: {
498     const uint8_t *blockData = form_value.BlockData();
499     if (blockData) {
500       // Location description is inlined in data in the form value
501       DWARFDataExtractor locationData(data,
502                                       (*offset_ptr) - form_value.Unsigned(),
503                                       form_value.Unsigned());
504       DWARFExpression::PrintDWARFExpression(
505           s, locationData, DWARFUnit::GetAddressByteSize(cu), 4, false);
506     } else {
507       // We have a location list offset as the value that is the offset into
508       // the .debug_loc section that describes the value over it's lifetime
509       uint64_t debug_loc_offset = form_value.Unsigned();
510       DWARFExpression::PrintDWARFLocationList(s, cu, cu->GetLocationData(),
511                                               debug_loc_offset);
512     }
513   } break;
514 
515   case DW_AT_abstract_origin:
516   case DW_AT_specification: {
517     DWARFDIE abstract_die = form_value.Reference();
518     form_value.Dump(s);
519     //  *ostrm_ptr << HEX32 << abstract_die.GetOffset() << " ( ";
520     abstract_die.GetName(s);
521   } break;
522 
523   case DW_AT_type: {
524     DWARFDIE type_die = form_value.Reference();
525     s.PutCString(" ( ");
526     type_die.AppendTypeName(s);
527     s.PutCString(" )");
528   } break;
529 
530   default:
531     break;
532   }
533 
534   s.PutCString(" )\n");
535 }
536 
537 // Get all attribute values for a given DIE, including following any
538 // specification or abstract origin attributes and including those in the
539 // results. Any duplicate attributes will have the first instance take
540 // precedence (this can happen for declaration attributes).
541 size_t DWARFDebugInfoEntry::GetAttributes(
542     const DWARFUnit *cu, DWARFAttributes &attributes,
543     uint32_t curr_depth) const {
544   const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu);
545   if (abbrevDecl) {
546     const DWARFDataExtractor &data = cu->GetData();
547     lldb::offset_t offset = GetFirstAttributeOffset();
548 
549     const uint32_t num_attributes = abbrevDecl->NumAttributes();
550     for (uint32_t i = 0; i < num_attributes; ++i) {
551       DWARFFormValue form_value(cu);
552       dw_attr_t attr;
553       abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value);
554       const dw_form_t form = form_value.Form();
555 
556       // If we are tracking down DW_AT_specification or DW_AT_abstract_origin
557       // attributes, the depth will be non-zero. We need to omit certain
558       // attributes that don't make sense.
559       switch (attr) {
560       case DW_AT_sibling:
561       case DW_AT_declaration:
562         if (curr_depth > 0) {
563           // This attribute doesn't make sense when combined with the DIE that
564           // references this DIE. We know a DIE is referencing this DIE because
565           // curr_depth is not zero
566           break;
567         }
568         LLVM_FALLTHROUGH;
569       default:
570         attributes.Append(cu, offset, attr, form);
571         break;
572       }
573 
574       if ((attr == DW_AT_specification) || (attr == DW_AT_abstract_origin)) {
575         if (form_value.ExtractValue(data, &offset)) {
576           DWARFDIE spec_die = form_value.Reference();
577           if (spec_die)
578             spec_die.GetAttributes(attributes, curr_depth + 1);
579         }
580       } else {
581         llvm::Optional<uint8_t> fixed_skip_size = DWARFFormValue::GetFixedSize(form, cu);
582         if (fixed_skip_size)
583           offset += *fixed_skip_size;
584         else
585           DWARFFormValue::SkipValue(form, data, &offset, cu);
586       }
587     }
588   } else {
589     attributes.Clear();
590   }
591   return attributes.Size();
592 }
593 
594 // GetAttributeValue
595 //
596 // Get the value of an attribute and return the .debug_info or .debug_types
597 // offset of the attribute if it was properly extracted into form_value,
598 // or zero if we fail since an offset of zero is invalid for an attribute (it
599 // would be a compile unit header).
600 dw_offset_t DWARFDebugInfoEntry::GetAttributeValue(
601     const DWARFUnit *cu, const dw_attr_t attr, DWARFFormValue &form_value,
602     dw_offset_t *end_attr_offset_ptr,
603     bool check_specification_or_abstract_origin) const {
604   if (const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu)) {
605     uint32_t attr_idx = abbrevDecl->FindAttributeIndex(attr);
606 
607     if (attr_idx != DW_INVALID_INDEX) {
608       const DWARFDataExtractor &data = cu->GetData();
609       lldb::offset_t offset = GetFirstAttributeOffset();
610 
611       uint32_t idx = 0;
612       while (idx < attr_idx)
613         DWARFFormValue::SkipValue(abbrevDecl->GetFormByIndex(idx++),
614                                   data, &offset, cu);
615 
616       const dw_offset_t attr_offset = offset;
617       form_value.SetUnit(cu);
618       form_value.SetForm(abbrevDecl->GetFormByIndex(idx));
619       if (form_value.ExtractValue(data, &offset)) {
620         if (end_attr_offset_ptr)
621           *end_attr_offset_ptr = offset;
622         return attr_offset;
623       }
624     }
625   }
626 
627   if (check_specification_or_abstract_origin) {
628     if (GetAttributeValue(cu, DW_AT_specification, form_value)) {
629       DWARFDIE die = form_value.Reference();
630       if (die) {
631         dw_offset_t die_offset = die.GetDIE()->GetAttributeValue(
632             die.GetCU(), attr, form_value, end_attr_offset_ptr, false);
633         if (die_offset)
634           return die_offset;
635       }
636     }
637 
638     if (GetAttributeValue(cu, DW_AT_abstract_origin, form_value)) {
639       DWARFDIE die = form_value.Reference();
640       if (die) {
641         dw_offset_t die_offset = die.GetDIE()->GetAttributeValue(
642             die.GetCU(), attr, form_value, end_attr_offset_ptr, false);
643         if (die_offset)
644           return die_offset;
645       }
646     }
647   }
648   return 0;
649 }
650 
651 // GetAttributeValueAsString
652 //
653 // Get the value of an attribute as a string return it. The resulting pointer
654 // to the string data exists within the supplied SymbolFileDWARF and will only
655 // be available as long as the SymbolFileDWARF is still around and it's content
656 // doesn't change.
657 const char *DWARFDebugInfoEntry::GetAttributeValueAsString(
658     const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value,
659     bool check_specification_or_abstract_origin) const {
660   DWARFFormValue form_value;
661   if (GetAttributeValue(cu, attr, form_value, nullptr,
662                         check_specification_or_abstract_origin))
663     return form_value.AsCString();
664   return fail_value;
665 }
666 
667 // GetAttributeValueAsUnsigned
668 //
669 // Get the value of an attribute as unsigned and return it.
670 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsUnsigned(
671     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
672     bool check_specification_or_abstract_origin) const {
673   DWARFFormValue form_value;
674   if (GetAttributeValue(cu, attr, form_value, nullptr,
675                         check_specification_or_abstract_origin))
676     return form_value.Unsigned();
677   return fail_value;
678 }
679 
680 // GetAttributeValueAsReference
681 //
682 // Get the value of an attribute as reference and fix up and compile unit
683 // relative offsets as needed.
684 DWARFDIE DWARFDebugInfoEntry::GetAttributeValueAsReference(
685     const DWARFUnit *cu, const dw_attr_t attr,
686     bool check_specification_or_abstract_origin) const {
687   DWARFFormValue form_value;
688   if (GetAttributeValue(cu, attr, form_value, nullptr,
689                         check_specification_or_abstract_origin))
690     return form_value.Reference();
691   return {};
692 }
693 
694 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsAddress(
695     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
696     bool check_specification_or_abstract_origin) const {
697   DWARFFormValue form_value;
698   if (GetAttributeValue(cu, attr, form_value, nullptr,
699                         check_specification_or_abstract_origin))
700     return form_value.Address();
701   return fail_value;
702 }
703 
704 // GetAttributeHighPC
705 //
706 // Get the hi_pc, adding hi_pc to lo_pc when specified as an <offset-from-low-
707 // pc>.
708 //
709 // Returns the hi_pc or fail_value.
710 dw_addr_t DWARFDebugInfoEntry::GetAttributeHighPC(
711     const DWARFUnit *cu, dw_addr_t lo_pc, uint64_t fail_value,
712     bool check_specification_or_abstract_origin) const {
713   DWARFFormValue form_value;
714   if (GetAttributeValue(cu, DW_AT_high_pc, form_value, nullptr,
715                         check_specification_or_abstract_origin)) {
716     dw_form_t form = form_value.Form();
717     if (form == DW_FORM_addr || form == DW_FORM_addrx ||
718         form == DW_FORM_GNU_addr_index)
719       return form_value.Address();
720 
721     // DWARF4 can specify the hi_pc as an <offset-from-lowpc>
722     return lo_pc + form_value.Unsigned();
723   }
724   return fail_value;
725 }
726 
727 // GetAttributeAddressRange
728 //
729 // Get the lo_pc and hi_pc, adding hi_pc to lo_pc when specified as an <offset-
730 // from-low-pc>.
731 //
732 // Returns true or sets lo_pc and hi_pc to fail_value.
733 bool DWARFDebugInfoEntry::GetAttributeAddressRange(
734     const DWARFUnit *cu, dw_addr_t &lo_pc, dw_addr_t &hi_pc,
735     uint64_t fail_value, bool check_specification_or_abstract_origin) const {
736   lo_pc = GetAttributeValueAsAddress(cu, DW_AT_low_pc, fail_value,
737                                      check_specification_or_abstract_origin);
738   if (lo_pc != fail_value) {
739     hi_pc = GetAttributeHighPC(cu, lo_pc, fail_value,
740                                check_specification_or_abstract_origin);
741     if (hi_pc != fail_value)
742       return true;
743   }
744   lo_pc = fail_value;
745   hi_pc = fail_value;
746   return false;
747 }
748 
749 size_t DWARFDebugInfoEntry::GetAttributeAddressRanges(
750     DWARFUnit *cu, DWARFRangeList &ranges, bool check_hi_lo_pc,
751     bool check_specification_or_abstract_origin) const {
752   ranges.Clear();
753 
754   DWARFFormValue form_value;
755   if (GetAttributeValue(cu, DW_AT_ranges, form_value)) {
756     ranges = GetRangesOrReportError(*cu, *this, form_value);
757   } else if (check_hi_lo_pc) {
758     dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
759     dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
760     if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS,
761                                  check_specification_or_abstract_origin)) {
762       if (lo_pc < hi_pc)
763         ranges.Append(DWARFRangeList::Entry(lo_pc, hi_pc - lo_pc));
764     }
765   }
766   return ranges.GetSize();
767 }
768 
769 // GetName
770 //
771 // Get value of the DW_AT_name attribute and return it if one exists, else
772 // return NULL.
773 const char *DWARFDebugInfoEntry::GetName(const DWARFUnit *cu) const {
774   return GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
775 }
776 
777 // GetMangledName
778 //
779 // Get value of the DW_AT_MIPS_linkage_name attribute and return it if one
780 // exists, else return the value of the DW_AT_name attribute
781 const char *
782 DWARFDebugInfoEntry::GetMangledName(const DWARFUnit *cu,
783                                     bool substitute_name_allowed) const {
784   const char *name = nullptr;
785 
786   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
787   if (name)
788     return name;
789 
790   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
791   if (name)
792     return name;
793 
794   if (!substitute_name_allowed)
795     return nullptr;
796 
797   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
798   return name;
799 }
800 
801 // GetPubname
802 //
803 // Get value the name for a DIE as it should appear for a .debug_pubnames or
804 // .debug_pubtypes section.
805 const char *DWARFDebugInfoEntry::GetPubname(const DWARFUnit *cu) const {
806   const char *name = nullptr;
807   if (!cu)
808     return name;
809 
810   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
811   if (name)
812     return name;
813 
814   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
815   if (name)
816     return name;
817 
818   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
819   return name;
820 }
821 
822 // BuildAddressRangeTable
823 void DWARFDebugInfoEntry::BuildAddressRangeTable(
824     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
825   if (m_tag) {
826     if (m_tag == DW_TAG_subprogram) {
827       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
828       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
829       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
830         /// printf("BuildAddressRangeTable() 0x%8.8x: %30s: [0x%8.8x -
831         /// 0x%8.8x)\n", m_offset, DW_TAG_value_to_name(tag), lo_pc, hi_pc);
832         debug_aranges->AppendRange(cu->GetOffset(), lo_pc, hi_pc);
833       }
834     }
835 
836     const DWARFDebugInfoEntry *child = GetFirstChild();
837     while (child) {
838       child->BuildAddressRangeTable(cu, debug_aranges);
839       child = child->GetSibling();
840     }
841   }
842 }
843 
844 // BuildFunctionAddressRangeTable
845 //
846 // This function is very similar to the BuildAddressRangeTable function except
847 // that the actual DIE offset for the function is placed in the table instead
848 // of the compile unit offset (which is the way the standard .debug_aranges
849 // section does it).
850 void DWARFDebugInfoEntry::BuildFunctionAddressRangeTable(
851     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
852   if (m_tag) {
853     if (m_tag == DW_TAG_subprogram) {
854       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
855       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
856       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
857         //  printf("BuildAddressRangeTable() 0x%8.8x: [0x%16.16" PRIx64 " -
858         //  0x%16.16" PRIx64 ")\n", m_offset, lo_pc, hi_pc); // DEBUG ONLY
859         debug_aranges->AppendRange(GetOffset(), lo_pc, hi_pc);
860       }
861     }
862 
863     const DWARFDebugInfoEntry *child = GetFirstChild();
864     while (child) {
865       child->BuildFunctionAddressRangeTable(cu, debug_aranges);
866       child = child->GetSibling();
867     }
868   }
869 }
870 
871 void DWARFDebugInfoEntry::GetDWARFDeclContext(
872     DWARFUnit *cu, DWARFDeclContext &dwarf_decl_ctx) const {
873   const dw_tag_t tag = Tag();
874   if (tag != DW_TAG_compile_unit && tag != DW_TAG_partial_unit) {
875     dwarf_decl_ctx.AppendDeclContext(tag, GetName(cu));
876     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
877     if (parent_decl_ctx_die && parent_decl_ctx_die.GetDIE() != this) {
878       if (parent_decl_ctx_die.Tag() != DW_TAG_compile_unit &&
879           parent_decl_ctx_die.Tag() != DW_TAG_partial_unit)
880         parent_decl_ctx_die.GetDIE()->GetDWARFDeclContext(
881             parent_decl_ctx_die.GetCU(), dwarf_decl_ctx);
882     }
883   }
884 }
885 
886 DWARFDIE
887 DWARFDebugInfoEntry::GetParentDeclContextDIE(DWARFUnit *cu) const {
888   DWARFAttributes attributes;
889   GetAttributes(cu, attributes);
890   return GetParentDeclContextDIE(cu, attributes);
891 }
892 
893 DWARFDIE
894 DWARFDebugInfoEntry::GetParentDeclContextDIE(
895     DWARFUnit *cu, const DWARFAttributes &attributes) const {
896   DWARFDIE die(cu, const_cast<DWARFDebugInfoEntry *>(this));
897 
898   while (die) {
899     // If this is the original DIE that we are searching for a declaration for,
900     // then don't look in the cache as we don't want our own decl context to be
901     // our decl context...
902     if (die.GetDIE() != this) {
903       switch (die.Tag()) {
904       case DW_TAG_compile_unit:
905       case DW_TAG_partial_unit:
906       case DW_TAG_namespace:
907       case DW_TAG_structure_type:
908       case DW_TAG_union_type:
909       case DW_TAG_class_type:
910         return die;
911 
912       default:
913         break;
914       }
915     }
916 
917     DWARFDIE spec_die = attributes.FormValueAsReference(DW_AT_specification);
918     if (spec_die) {
919       DWARFDIE decl_ctx_die = spec_die.GetParentDeclContextDIE();
920       if (decl_ctx_die)
921         return decl_ctx_die;
922     }
923 
924     DWARFDIE abs_die = attributes.FormValueAsReference(DW_AT_abstract_origin);
925     if (abs_die) {
926       DWARFDIE decl_ctx_die = abs_die.GetParentDeclContextDIE();
927       if (decl_ctx_die)
928         return decl_ctx_die;
929     }
930 
931     die = die.GetParent();
932   }
933   return DWARFDIE();
934 }
935 
936 const char *DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
937                                                   std::string &storage) const {
938   DWARFAttributes attributes;
939   GetAttributes(cu, attributes);
940   return GetQualifiedName(cu, attributes, storage);
941 }
942 
943 const char *
944 DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
945                                       const DWARFAttributes &attributes,
946                                       std::string &storage) const {
947 
948   const char *name = GetName(cu);
949 
950   if (name) {
951     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
952     storage.clear();
953     // TODO: change this to get the correct decl context parent....
954     while (parent_decl_ctx_die) {
955       const dw_tag_t parent_tag = parent_decl_ctx_die.Tag();
956       switch (parent_tag) {
957       case DW_TAG_namespace: {
958         const char *namespace_name = parent_decl_ctx_die.GetName();
959         if (namespace_name) {
960           storage.insert(0, "::");
961           storage.insert(0, namespace_name);
962         } else {
963           storage.insert(0, "(anonymous namespace)::");
964         }
965         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
966       } break;
967 
968       case DW_TAG_class_type:
969       case DW_TAG_structure_type:
970       case DW_TAG_union_type: {
971         const char *class_union_struct_name = parent_decl_ctx_die.GetName();
972 
973         if (class_union_struct_name) {
974           storage.insert(0, "::");
975           storage.insert(0, class_union_struct_name);
976         }
977         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
978       } break;
979 
980       default:
981         parent_decl_ctx_die.Clear();
982         break;
983       }
984     }
985 
986     if (storage.empty())
987       storage.append("::");
988 
989     storage.append(name);
990   }
991   if (storage.empty())
992     return nullptr;
993   return storage.c_str();
994 }
995 
996 bool DWARFDebugInfoEntry::LookupAddress(const dw_addr_t address, DWARFUnit *cu,
997                                         DWARFDebugInfoEntry **function_die,
998                                         DWARFDebugInfoEntry **block_die) {
999   bool found_address = false;
1000   if (m_tag) {
1001     bool check_children = false;
1002     bool match_addr_range = false;
1003     //  printf("0x%8.8x: %30s: address = 0x%8.8x - ", m_offset,
1004     //  DW_TAG_value_to_name(tag), address);
1005     switch (m_tag) {
1006     case DW_TAG_array_type:
1007       break;
1008     case DW_TAG_class_type:
1009       check_children = true;
1010       break;
1011     case DW_TAG_entry_point:
1012     case DW_TAG_enumeration_type:
1013     case DW_TAG_formal_parameter:
1014     case DW_TAG_imported_declaration:
1015     case DW_TAG_label:
1016       break;
1017     case DW_TAG_lexical_block:
1018       check_children = true;
1019       match_addr_range = true;
1020       break;
1021     case DW_TAG_member:
1022     case DW_TAG_pointer_type:
1023     case DW_TAG_reference_type:
1024       break;
1025     case DW_TAG_compile_unit:
1026       match_addr_range = true;
1027       break;
1028     case DW_TAG_string_type:
1029       break;
1030     case DW_TAG_structure_type:
1031       check_children = true;
1032       break;
1033     case DW_TAG_subroutine_type:
1034     case DW_TAG_typedef:
1035     case DW_TAG_union_type:
1036     case DW_TAG_unspecified_parameters:
1037     case DW_TAG_variant:
1038       break;
1039     case DW_TAG_common_block:
1040       check_children = true;
1041       break;
1042     case DW_TAG_common_inclusion:
1043     case DW_TAG_inheritance:
1044       break;
1045     case DW_TAG_inlined_subroutine:
1046       check_children = true;
1047       match_addr_range = true;
1048       break;
1049     case DW_TAG_module:
1050       match_addr_range = true;
1051       break;
1052     case DW_TAG_ptr_to_member_type:
1053     case DW_TAG_set_type:
1054     case DW_TAG_subrange_type:
1055     case DW_TAG_with_stmt:
1056     case DW_TAG_access_declaration:
1057     case DW_TAG_base_type:
1058       break;
1059     case DW_TAG_catch_block:
1060       match_addr_range = true;
1061       break;
1062     case DW_TAG_const_type:
1063     case DW_TAG_constant:
1064     case DW_TAG_enumerator:
1065     case DW_TAG_file_type:
1066     case DW_TAG_friend:
1067     case DW_TAG_namelist:
1068     case DW_TAG_namelist_item:
1069     case DW_TAG_packed_type:
1070       break;
1071     case DW_TAG_subprogram:
1072       match_addr_range = true;
1073       break;
1074     case DW_TAG_template_type_parameter:
1075     case DW_TAG_template_value_parameter:
1076     case DW_TAG_GNU_template_parameter_pack:
1077     case DW_TAG_thrown_type:
1078       break;
1079     case DW_TAG_try_block:
1080       match_addr_range = true;
1081       break;
1082     case DW_TAG_variant_part:
1083     case DW_TAG_variable:
1084     case DW_TAG_volatile_type:
1085     case DW_TAG_dwarf_procedure:
1086     case DW_TAG_restrict_type:
1087     case DW_TAG_interface_type:
1088       break;
1089     case DW_TAG_namespace:
1090       check_children = true;
1091       break;
1092     case DW_TAG_imported_module:
1093     case DW_TAG_unspecified_type:
1094       break;
1095     case DW_TAG_partial_unit:
1096       match_addr_range = true;
1097       break;
1098     case DW_TAG_imported_unit:
1099     case DW_TAG_shared_type:
1100     default:
1101       break;
1102     }
1103 
1104     if (match_addr_range) {
1105       dw_addr_t lo_pc =
1106           GetAttributeValueAsAddress(cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
1107       if (lo_pc != LLDB_INVALID_ADDRESS) {
1108         dw_addr_t hi_pc = GetAttributeHighPC(cu, lo_pc, LLDB_INVALID_ADDRESS);
1109         if (hi_pc != LLDB_INVALID_ADDRESS) {
1110           //  printf("\n0x%8.8x: %30s: address = 0x%8.8x  [0x%8.8x - 0x%8.8x) ",
1111           //  m_offset, DW_TAG_value_to_name(tag), address, lo_pc, hi_pc);
1112           if ((lo_pc <= address) && (address < hi_pc)) {
1113             found_address = true;
1114             //  puts("***MATCH***");
1115             switch (m_tag) {
1116             case DW_TAG_compile_unit: // File
1117             case DW_TAG_partial_unit: // File
1118               check_children =
1119                   ((function_die != nullptr) || (block_die != nullptr));
1120               break;
1121 
1122             case DW_TAG_subprogram: // Function
1123               if (function_die)
1124                 *function_die = this;
1125               check_children = (block_die != nullptr);
1126               break;
1127 
1128             case DW_TAG_inlined_subroutine: // Inlined Function
1129             case DW_TAG_lexical_block:      // Block { } in code
1130               if (block_die) {
1131                 *block_die = this;
1132                 check_children = true;
1133               }
1134               break;
1135 
1136             default:
1137               check_children = true;
1138               break;
1139             }
1140           }
1141         } else {
1142           // Compile units may not have a valid high/low pc when there
1143           // are address gaps in subroutines so we must always search
1144           // if there is no valid high and low PC.
1145           check_children =
1146               (m_tag == DW_TAG_compile_unit || m_tag == DW_TAG_partial_unit) &&
1147               ((function_die != nullptr) || (block_die != nullptr));
1148         }
1149       } else {
1150         DWARFRangeList ranges;
1151         if (GetAttributeAddressRanges(cu, ranges, /*check_hi_lo_pc*/ false) &&
1152             ranges.FindEntryThatContains(address)) {
1153           found_address = true;
1154           //  puts("***MATCH***");
1155           switch (m_tag) {
1156           case DW_TAG_compile_unit: // File
1157           case DW_TAG_partial_unit: // File
1158               check_children =
1159                   ((function_die != nullptr) || (block_die != nullptr));
1160               break;
1161 
1162           case DW_TAG_subprogram: // Function
1163             if (function_die)
1164               *function_die = this;
1165             check_children = (block_die != nullptr);
1166             break;
1167 
1168           case DW_TAG_inlined_subroutine: // Inlined Function
1169           case DW_TAG_lexical_block:      // Block { } in code
1170             if (block_die) {
1171               *block_die = this;
1172               check_children = true;
1173             }
1174             break;
1175 
1176           default:
1177             check_children = true;
1178             break;
1179           }
1180         } else {
1181           check_children = false;
1182         }
1183       }
1184     }
1185 
1186     if (check_children) {
1187       //  printf("checking children\n");
1188       DWARFDebugInfoEntry *child = GetFirstChild();
1189       while (child) {
1190         if (child->LookupAddress(address, cu, function_die, block_die))
1191           return true;
1192         child = child->GetSibling();
1193       }
1194     }
1195   }
1196   return found_address;
1197 }
1198 
1199 lldb::offset_t DWARFDebugInfoEntry::GetFirstAttributeOffset() const {
1200   return GetOffset() + llvm::getULEB128Size(m_abbr_idx);
1201 }
1202 
1203 const DWARFAbbreviationDeclaration *
1204 DWARFDebugInfoEntry::GetAbbreviationDeclarationPtr(const DWARFUnit *cu) const {
1205   if (cu) {
1206     const DWARFAbbreviationDeclarationSet *abbrev_set = cu->GetAbbreviations();
1207     if (abbrev_set)
1208       return abbrev_set->GetAbbreviationDeclaration(m_abbr_idx);
1209   }
1210   return nullptr;
1211 }
1212 
1213 bool DWARFDebugInfoEntry::operator==(const DWARFDebugInfoEntry &rhs) const {
1214   return m_offset == rhs.m_offset && m_parent_idx == rhs.m_parent_idx &&
1215          m_sibling_idx == rhs.m_sibling_idx &&
1216          m_abbr_idx == rhs.m_abbr_idx && m_has_children == rhs.m_has_children &&
1217          m_tag == rhs.m_tag;
1218 }
1219 
1220 bool DWARFDebugInfoEntry::operator!=(const DWARFDebugInfoEntry &rhs) const {
1221   return !(*this == rhs);
1222 }
1223