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 
649   // If we're a unit DIE, also check the attributes of the dwo unit (if any).
650   if (GetParent())
651     return 0;
652   SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile();
653   if (!dwo_symbol_file)
654     return 0;
655 
656   DWARFCompileUnit *dwo_cu = dwo_symbol_file->GetCompileUnit();
657   if (!dwo_cu)
658     return 0;
659 
660   DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
661   if (!dwo_cu_die.IsValid())
662     return 0;
663 
664   return dwo_cu_die.GetDIE()->GetAttributeValue(
665       dwo_cu, attr, form_value, end_attr_offset_ptr,
666       check_specification_or_abstract_origin);
667 }
668 
669 // GetAttributeValueAsString
670 //
671 // Get the value of an attribute as a string return it. The resulting pointer
672 // to the string data exists within the supplied SymbolFileDWARF and will only
673 // be available as long as the SymbolFileDWARF is still around and it's content
674 // doesn't change.
675 const char *DWARFDebugInfoEntry::GetAttributeValueAsString(
676     const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value,
677     bool check_specification_or_abstract_origin) const {
678   DWARFFormValue form_value;
679   if (GetAttributeValue(cu, attr, form_value, nullptr,
680                         check_specification_or_abstract_origin))
681     return form_value.AsCString();
682   return fail_value;
683 }
684 
685 // GetAttributeValueAsUnsigned
686 //
687 // Get the value of an attribute as unsigned and return it.
688 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsUnsigned(
689     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
690     bool check_specification_or_abstract_origin) const {
691   DWARFFormValue form_value;
692   if (GetAttributeValue(cu, attr, form_value, nullptr,
693                         check_specification_or_abstract_origin))
694     return form_value.Unsigned();
695   return fail_value;
696 }
697 
698 // GetAttributeValueAsReference
699 //
700 // Get the value of an attribute as reference and fix up and compile unit
701 // relative offsets as needed.
702 DWARFDIE DWARFDebugInfoEntry::GetAttributeValueAsReference(
703     const DWARFUnit *cu, const dw_attr_t attr,
704     bool check_specification_or_abstract_origin) const {
705   DWARFFormValue form_value;
706   if (GetAttributeValue(cu, attr, form_value, nullptr,
707                         check_specification_or_abstract_origin))
708     return form_value.Reference();
709   return {};
710 }
711 
712 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsAddress(
713     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
714     bool check_specification_or_abstract_origin) const {
715   DWARFFormValue form_value;
716   if (GetAttributeValue(cu, attr, form_value, nullptr,
717                         check_specification_or_abstract_origin))
718     return form_value.Address();
719   return fail_value;
720 }
721 
722 // GetAttributeHighPC
723 //
724 // Get the hi_pc, adding hi_pc to lo_pc when specified as an <offset-from-low-
725 // pc>.
726 //
727 // Returns the hi_pc or fail_value.
728 dw_addr_t DWARFDebugInfoEntry::GetAttributeHighPC(
729     const DWARFUnit *cu, dw_addr_t lo_pc, uint64_t fail_value,
730     bool check_specification_or_abstract_origin) const {
731   DWARFFormValue form_value;
732   if (GetAttributeValue(cu, DW_AT_high_pc, form_value, nullptr,
733                         check_specification_or_abstract_origin)) {
734     dw_form_t form = form_value.Form();
735     if (form == DW_FORM_addr || form == DW_FORM_addrx ||
736         form == DW_FORM_GNU_addr_index)
737       return form_value.Address();
738 
739     // DWARF4 can specify the hi_pc as an <offset-from-lowpc>
740     return lo_pc + form_value.Unsigned();
741   }
742   return fail_value;
743 }
744 
745 // GetAttributeAddressRange
746 //
747 // Get the lo_pc and hi_pc, adding hi_pc to lo_pc when specified as an <offset-
748 // from-low-pc>.
749 //
750 // Returns true or sets lo_pc and hi_pc to fail_value.
751 bool DWARFDebugInfoEntry::GetAttributeAddressRange(
752     const DWARFUnit *cu, dw_addr_t &lo_pc, dw_addr_t &hi_pc,
753     uint64_t fail_value, bool check_specification_or_abstract_origin) const {
754   lo_pc = GetAttributeValueAsAddress(cu, DW_AT_low_pc, fail_value,
755                                      check_specification_or_abstract_origin);
756   if (lo_pc != fail_value) {
757     hi_pc = GetAttributeHighPC(cu, lo_pc, fail_value,
758                                check_specification_or_abstract_origin);
759     if (hi_pc != fail_value)
760       return true;
761   }
762   lo_pc = fail_value;
763   hi_pc = fail_value;
764   return false;
765 }
766 
767 size_t DWARFDebugInfoEntry::GetAttributeAddressRanges(
768     DWARFUnit *cu, DWARFRangeList &ranges, bool check_hi_lo_pc,
769     bool check_specification_or_abstract_origin) const {
770   ranges.Clear();
771 
772   DWARFFormValue form_value;
773   if (GetAttributeValue(cu, DW_AT_ranges, form_value)) {
774     ranges = GetRangesOrReportError(*cu, *this, form_value);
775   } else if (check_hi_lo_pc) {
776     dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
777     dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
778     if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS,
779                                  check_specification_or_abstract_origin)) {
780       if (lo_pc < hi_pc)
781         ranges.Append(DWARFRangeList::Entry(lo_pc, hi_pc - lo_pc));
782     }
783   }
784   return ranges.GetSize();
785 }
786 
787 // GetName
788 //
789 // Get value of the DW_AT_name attribute and return it if one exists, else
790 // return NULL.
791 const char *DWARFDebugInfoEntry::GetName(const DWARFUnit *cu) const {
792   return GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
793 }
794 
795 // GetMangledName
796 //
797 // Get value of the DW_AT_MIPS_linkage_name attribute and return it if one
798 // exists, else return the value of the DW_AT_name attribute
799 const char *
800 DWARFDebugInfoEntry::GetMangledName(const DWARFUnit *cu,
801                                     bool substitute_name_allowed) const {
802   const char *name = nullptr;
803 
804   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
805   if (name)
806     return name;
807 
808   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
809   if (name)
810     return name;
811 
812   if (!substitute_name_allowed)
813     return nullptr;
814 
815   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
816   return name;
817 }
818 
819 // GetPubname
820 //
821 // Get value the name for a DIE as it should appear for a .debug_pubnames or
822 // .debug_pubtypes section.
823 const char *DWARFDebugInfoEntry::GetPubname(const DWARFUnit *cu) const {
824   const char *name = nullptr;
825   if (!cu)
826     return name;
827 
828   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
829   if (name)
830     return name;
831 
832   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
833   if (name)
834     return name;
835 
836   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
837   return name;
838 }
839 
840 // BuildAddressRangeTable
841 void DWARFDebugInfoEntry::BuildAddressRangeTable(
842     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
843   if (m_tag) {
844     if (m_tag == DW_TAG_subprogram) {
845       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
846       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
847       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
848         /// printf("BuildAddressRangeTable() 0x%8.8x: %30s: [0x%8.8x -
849         /// 0x%8.8x)\n", m_offset, DW_TAG_value_to_name(tag), lo_pc, hi_pc);
850         debug_aranges->AppendRange(cu->GetOffset(), lo_pc, hi_pc);
851       }
852     }
853 
854     const DWARFDebugInfoEntry *child = GetFirstChild();
855     while (child) {
856       child->BuildAddressRangeTable(cu, debug_aranges);
857       child = child->GetSibling();
858     }
859   }
860 }
861 
862 // BuildFunctionAddressRangeTable
863 //
864 // This function is very similar to the BuildAddressRangeTable function except
865 // that the actual DIE offset for the function is placed in the table instead
866 // of the compile unit offset (which is the way the standard .debug_aranges
867 // section does it).
868 void DWARFDebugInfoEntry::BuildFunctionAddressRangeTable(
869     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
870   if (m_tag) {
871     if (m_tag == DW_TAG_subprogram) {
872       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
873       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
874       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
875         //  printf("BuildAddressRangeTable() 0x%8.8x: [0x%16.16" PRIx64 " -
876         //  0x%16.16" PRIx64 ")\n", m_offset, lo_pc, hi_pc); // DEBUG ONLY
877         debug_aranges->AppendRange(GetOffset(), lo_pc, hi_pc);
878       }
879     }
880 
881     const DWARFDebugInfoEntry *child = GetFirstChild();
882     while (child) {
883       child->BuildFunctionAddressRangeTable(cu, debug_aranges);
884       child = child->GetSibling();
885     }
886   }
887 }
888 
889 void DWARFDebugInfoEntry::GetDWARFDeclContext(
890     DWARFUnit *cu, DWARFDeclContext &dwarf_decl_ctx) const {
891   const dw_tag_t tag = Tag();
892   if (tag != DW_TAG_compile_unit && tag != DW_TAG_partial_unit) {
893     dwarf_decl_ctx.AppendDeclContext(tag, GetName(cu));
894     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
895     if (parent_decl_ctx_die && parent_decl_ctx_die.GetDIE() != this) {
896       if (parent_decl_ctx_die.Tag() != DW_TAG_compile_unit &&
897           parent_decl_ctx_die.Tag() != DW_TAG_partial_unit)
898         parent_decl_ctx_die.GetDIE()->GetDWARFDeclContext(
899             parent_decl_ctx_die.GetCU(), dwarf_decl_ctx);
900     }
901   }
902 }
903 
904 DWARFDIE
905 DWARFDebugInfoEntry::GetParentDeclContextDIE(DWARFUnit *cu) const {
906   DWARFAttributes attributes;
907   GetAttributes(cu, attributes);
908   return GetParentDeclContextDIE(cu, attributes);
909 }
910 
911 DWARFDIE
912 DWARFDebugInfoEntry::GetParentDeclContextDIE(
913     DWARFUnit *cu, const DWARFAttributes &attributes) const {
914   DWARFDIE die(cu, const_cast<DWARFDebugInfoEntry *>(this));
915 
916   while (die) {
917     // If this is the original DIE that we are searching for a declaration for,
918     // then don't look in the cache as we don't want our own decl context to be
919     // our decl context...
920     if (die.GetDIE() != this) {
921       switch (die.Tag()) {
922       case DW_TAG_compile_unit:
923       case DW_TAG_partial_unit:
924       case DW_TAG_namespace:
925       case DW_TAG_structure_type:
926       case DW_TAG_union_type:
927       case DW_TAG_class_type:
928         return die;
929 
930       default:
931         break;
932       }
933     }
934 
935     DWARFDIE spec_die = attributes.FormValueAsReference(DW_AT_specification);
936     if (spec_die) {
937       DWARFDIE decl_ctx_die = spec_die.GetParentDeclContextDIE();
938       if (decl_ctx_die)
939         return decl_ctx_die;
940     }
941 
942     DWARFDIE abs_die = attributes.FormValueAsReference(DW_AT_abstract_origin);
943     if (abs_die) {
944       DWARFDIE decl_ctx_die = abs_die.GetParentDeclContextDIE();
945       if (decl_ctx_die)
946         return decl_ctx_die;
947     }
948 
949     die = die.GetParent();
950   }
951   return DWARFDIE();
952 }
953 
954 const char *DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
955                                                   std::string &storage) const {
956   DWARFAttributes attributes;
957   GetAttributes(cu, attributes);
958   return GetQualifiedName(cu, attributes, storage);
959 }
960 
961 const char *
962 DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
963                                       const DWARFAttributes &attributes,
964                                       std::string &storage) const {
965 
966   const char *name = GetName(cu);
967 
968   if (name) {
969     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
970     storage.clear();
971     // TODO: change this to get the correct decl context parent....
972     while (parent_decl_ctx_die) {
973       const dw_tag_t parent_tag = parent_decl_ctx_die.Tag();
974       switch (parent_tag) {
975       case DW_TAG_namespace: {
976         const char *namespace_name = parent_decl_ctx_die.GetName();
977         if (namespace_name) {
978           storage.insert(0, "::");
979           storage.insert(0, namespace_name);
980         } else {
981           storage.insert(0, "(anonymous namespace)::");
982         }
983         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
984       } break;
985 
986       case DW_TAG_class_type:
987       case DW_TAG_structure_type:
988       case DW_TAG_union_type: {
989         const char *class_union_struct_name = parent_decl_ctx_die.GetName();
990 
991         if (class_union_struct_name) {
992           storage.insert(0, "::");
993           storage.insert(0, class_union_struct_name);
994         }
995         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
996       } break;
997 
998       default:
999         parent_decl_ctx_die.Clear();
1000         break;
1001       }
1002     }
1003 
1004     if (storage.empty())
1005       storage.append("::");
1006 
1007     storage.append(name);
1008   }
1009   if (storage.empty())
1010     return nullptr;
1011   return storage.c_str();
1012 }
1013 
1014 bool DWARFDebugInfoEntry::LookupAddress(const dw_addr_t address, DWARFUnit *cu,
1015                                         DWARFDebugInfoEntry **function_die,
1016                                         DWARFDebugInfoEntry **block_die) {
1017   bool found_address = false;
1018   if (m_tag) {
1019     bool check_children = false;
1020     bool match_addr_range = false;
1021     //  printf("0x%8.8x: %30s: address = 0x%8.8x - ", m_offset,
1022     //  DW_TAG_value_to_name(tag), address);
1023     switch (m_tag) {
1024     case DW_TAG_array_type:
1025       break;
1026     case DW_TAG_class_type:
1027       check_children = true;
1028       break;
1029     case DW_TAG_entry_point:
1030     case DW_TAG_enumeration_type:
1031     case DW_TAG_formal_parameter:
1032     case DW_TAG_imported_declaration:
1033     case DW_TAG_label:
1034       break;
1035     case DW_TAG_lexical_block:
1036       check_children = true;
1037       match_addr_range = true;
1038       break;
1039     case DW_TAG_member:
1040     case DW_TAG_pointer_type:
1041     case DW_TAG_reference_type:
1042       break;
1043     case DW_TAG_compile_unit:
1044       match_addr_range = true;
1045       break;
1046     case DW_TAG_string_type:
1047       break;
1048     case DW_TAG_structure_type:
1049       check_children = true;
1050       break;
1051     case DW_TAG_subroutine_type:
1052     case DW_TAG_typedef:
1053     case DW_TAG_union_type:
1054     case DW_TAG_unspecified_parameters:
1055     case DW_TAG_variant:
1056       break;
1057     case DW_TAG_common_block:
1058       check_children = true;
1059       break;
1060     case DW_TAG_common_inclusion:
1061     case DW_TAG_inheritance:
1062       break;
1063     case DW_TAG_inlined_subroutine:
1064       check_children = true;
1065       match_addr_range = true;
1066       break;
1067     case DW_TAG_module:
1068       match_addr_range = true;
1069       break;
1070     case DW_TAG_ptr_to_member_type:
1071     case DW_TAG_set_type:
1072     case DW_TAG_subrange_type:
1073     case DW_TAG_with_stmt:
1074     case DW_TAG_access_declaration:
1075     case DW_TAG_base_type:
1076       break;
1077     case DW_TAG_catch_block:
1078       match_addr_range = true;
1079       break;
1080     case DW_TAG_const_type:
1081     case DW_TAG_constant:
1082     case DW_TAG_enumerator:
1083     case DW_TAG_file_type:
1084     case DW_TAG_friend:
1085     case DW_TAG_namelist:
1086     case DW_TAG_namelist_item:
1087     case DW_TAG_packed_type:
1088       break;
1089     case DW_TAG_subprogram:
1090       match_addr_range = true;
1091       break;
1092     case DW_TAG_template_type_parameter:
1093     case DW_TAG_template_value_parameter:
1094     case DW_TAG_GNU_template_parameter_pack:
1095     case DW_TAG_thrown_type:
1096       break;
1097     case DW_TAG_try_block:
1098       match_addr_range = true;
1099       break;
1100     case DW_TAG_variant_part:
1101     case DW_TAG_variable:
1102     case DW_TAG_volatile_type:
1103     case DW_TAG_dwarf_procedure:
1104     case DW_TAG_restrict_type:
1105     case DW_TAG_interface_type:
1106       break;
1107     case DW_TAG_namespace:
1108       check_children = true;
1109       break;
1110     case DW_TAG_imported_module:
1111     case DW_TAG_unspecified_type:
1112       break;
1113     case DW_TAG_partial_unit:
1114       match_addr_range = true;
1115       break;
1116     case DW_TAG_imported_unit:
1117     case DW_TAG_shared_type:
1118     default:
1119       break;
1120     }
1121 
1122     if (match_addr_range) {
1123       dw_addr_t lo_pc =
1124           GetAttributeValueAsAddress(cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
1125       if (lo_pc != LLDB_INVALID_ADDRESS) {
1126         dw_addr_t hi_pc = GetAttributeHighPC(cu, lo_pc, LLDB_INVALID_ADDRESS);
1127         if (hi_pc != LLDB_INVALID_ADDRESS) {
1128           //  printf("\n0x%8.8x: %30s: address = 0x%8.8x  [0x%8.8x - 0x%8.8x) ",
1129           //  m_offset, DW_TAG_value_to_name(tag), address, lo_pc, hi_pc);
1130           if ((lo_pc <= address) && (address < hi_pc)) {
1131             found_address = true;
1132             //  puts("***MATCH***");
1133             switch (m_tag) {
1134             case DW_TAG_compile_unit: // File
1135             case DW_TAG_partial_unit: // File
1136               check_children =
1137                   ((function_die != nullptr) || (block_die != nullptr));
1138               break;
1139 
1140             case DW_TAG_subprogram: // Function
1141               if (function_die)
1142                 *function_die = this;
1143               check_children = (block_die != nullptr);
1144               break;
1145 
1146             case DW_TAG_inlined_subroutine: // Inlined Function
1147             case DW_TAG_lexical_block:      // Block { } in code
1148               if (block_die) {
1149                 *block_die = this;
1150                 check_children = true;
1151               }
1152               break;
1153 
1154             default:
1155               check_children = true;
1156               break;
1157             }
1158           }
1159         } else {
1160           // Compile units may not have a valid high/low pc when there
1161           // are address gaps in subroutines so we must always search
1162           // if there is no valid high and low PC.
1163           check_children =
1164               (m_tag == DW_TAG_compile_unit || m_tag == DW_TAG_partial_unit) &&
1165               ((function_die != nullptr) || (block_die != nullptr));
1166         }
1167       } else {
1168         DWARFRangeList ranges;
1169         if (GetAttributeAddressRanges(cu, ranges, /*check_hi_lo_pc*/ false) &&
1170             ranges.FindEntryThatContains(address)) {
1171           found_address = true;
1172           //  puts("***MATCH***");
1173           switch (m_tag) {
1174           case DW_TAG_compile_unit: // File
1175           case DW_TAG_partial_unit: // File
1176               check_children =
1177                   ((function_die != nullptr) || (block_die != nullptr));
1178               break;
1179 
1180           case DW_TAG_subprogram: // Function
1181             if (function_die)
1182               *function_die = this;
1183             check_children = (block_die != nullptr);
1184             break;
1185 
1186           case DW_TAG_inlined_subroutine: // Inlined Function
1187           case DW_TAG_lexical_block:      // Block { } in code
1188             if (block_die) {
1189               *block_die = this;
1190               check_children = true;
1191             }
1192             break;
1193 
1194           default:
1195             check_children = true;
1196             break;
1197           }
1198         } else {
1199           check_children = false;
1200         }
1201       }
1202     }
1203 
1204     if (check_children) {
1205       //  printf("checking children\n");
1206       DWARFDebugInfoEntry *child = GetFirstChild();
1207       while (child) {
1208         if (child->LookupAddress(address, cu, function_die, block_die))
1209           return true;
1210         child = child->GetSibling();
1211       }
1212     }
1213   }
1214   return found_address;
1215 }
1216 
1217 lldb::offset_t DWARFDebugInfoEntry::GetFirstAttributeOffset() const {
1218   return GetOffset() + llvm::getULEB128Size(m_abbr_idx);
1219 }
1220 
1221 const DWARFAbbreviationDeclaration *
1222 DWARFDebugInfoEntry::GetAbbreviationDeclarationPtr(const DWARFUnit *cu) const {
1223   if (cu) {
1224     const DWARFAbbreviationDeclarationSet *abbrev_set = cu->GetAbbreviations();
1225     if (abbrev_set)
1226       return abbrev_set->GetAbbreviationDeclaration(m_abbr_idx);
1227   }
1228   return nullptr;
1229 }
1230 
1231 bool DWARFDebugInfoEntry::operator==(const DWARFDebugInfoEntry &rhs) const {
1232   return m_offset == rhs.m_offset && m_parent_idx == rhs.m_parent_idx &&
1233          m_sibling_idx == rhs.m_sibling_idx &&
1234          m_abbr_idx == rhs.m_abbr_idx && m_has_children == rhs.m_has_children &&
1235          m_tag == rhs.m_tag;
1236 }
1237 
1238 bool DWARFDebugInfoEntry::operator!=(const DWARFDebugInfoEntry &rhs) const {
1239   return !(*this == rhs);
1240 }
1241