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 = dwarf.DebugLocData();
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   SymbolFileDWARF &dwarf = cu->GetSymbolFileDWARF();
482 
483   // Check to see if we have any special attribute formatters
484   switch (attr) {
485   case DW_AT_stmt_list:
486     s.Printf("0x%8.8" PRIx64, form_value.Unsigned());
487     break;
488 
489   case DW_AT_language:
490     s.PutCString(DW_LANG_value_to_name(form_value.Unsigned()));
491     break;
492 
493   case DW_AT_encoding:
494     s.PutCString(DW_ATE_value_to_name(form_value.Unsigned()));
495     break;
496 
497   case DW_AT_frame_base:
498   case DW_AT_location:
499   case DW_AT_data_member_location: {
500     const uint8_t *blockData = form_value.BlockData();
501     if (blockData) {
502       // Location description is inlined in data in the form value
503       DWARFDataExtractor locationData(data,
504                                       (*offset_ptr) - form_value.Unsigned(),
505                                       form_value.Unsigned());
506       DWARFExpression::PrintDWARFExpression(
507           s, locationData, DWARFUnit::GetAddressByteSize(cu), 4, false);
508     } else {
509       // We have a location list offset as the value that is the offset into
510       // the .debug_loc section that describes the value over it's lifetime
511       uint64_t debug_loc_offset = form_value.Unsigned();
512       DWARFExpression::PrintDWARFLocationList(s, cu, dwarf.DebugLocData(),
513                                               debug_loc_offset);
514     }
515   } break;
516 
517   case DW_AT_abstract_origin:
518   case DW_AT_specification: {
519     DWARFDIE abstract_die = form_value.Reference();
520     form_value.Dump(s);
521     //  *ostrm_ptr << HEX32 << abstract_die.GetOffset() << " ( ";
522     abstract_die.GetName(s);
523   } break;
524 
525   case DW_AT_type: {
526     DWARFDIE type_die = form_value.Reference();
527     s.PutCString(" ( ");
528     type_die.AppendTypeName(s);
529     s.PutCString(" )");
530   } break;
531 
532   default:
533     break;
534   }
535 
536   s.PutCString(" )\n");
537 }
538 
539 // Get all attribute values for a given DIE, including following any
540 // specification or abstract origin attributes and including those in the
541 // results. Any duplicate attributes will have the first instance take
542 // precedence (this can happen for declaration attributes).
543 size_t DWARFDebugInfoEntry::GetAttributes(
544     const DWARFUnit *cu, DWARFAttributes &attributes,
545     uint32_t curr_depth) const {
546   const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu);
547   if (abbrevDecl) {
548     const DWARFDataExtractor &data = cu->GetData();
549     lldb::offset_t offset = GetFirstAttributeOffset();
550 
551     const uint32_t num_attributes = abbrevDecl->NumAttributes();
552     for (uint32_t i = 0; i < num_attributes; ++i) {
553       DWARFFormValue form_value(cu);
554       dw_attr_t attr;
555       abbrevDecl->GetAttrAndFormValueByIndex(i, attr, form_value);
556       const dw_form_t form = form_value.Form();
557 
558       // If we are tracking down DW_AT_specification or DW_AT_abstract_origin
559       // attributes, the depth will be non-zero. We need to omit certain
560       // attributes that don't make sense.
561       switch (attr) {
562       case DW_AT_sibling:
563       case DW_AT_declaration:
564         if (curr_depth > 0) {
565           // This attribute doesn't make sense when combined with the DIE that
566           // references this DIE. We know a DIE is referencing this DIE because
567           // curr_depth is not zero
568           break;
569         }
570         LLVM_FALLTHROUGH;
571       default:
572         attributes.Append(cu, offset, attr, form);
573         break;
574       }
575 
576       if ((attr == DW_AT_specification) || (attr == DW_AT_abstract_origin)) {
577         if (form_value.ExtractValue(data, &offset)) {
578           DWARFDIE spec_die = form_value.Reference();
579           if (spec_die)
580             spec_die.GetAttributes(attributes, curr_depth + 1);
581         }
582       } else {
583         llvm::Optional<uint8_t> fixed_skip_size = DWARFFormValue::GetFixedSize(form, cu);
584         if (fixed_skip_size)
585           offset += *fixed_skip_size;
586         else
587           DWARFFormValue::SkipValue(form, data, &offset, cu);
588       }
589     }
590   } else {
591     attributes.Clear();
592   }
593   return attributes.Size();
594 }
595 
596 // GetAttributeValue
597 //
598 // Get the value of an attribute and return the .debug_info or .debug_types
599 // offset of the attribute if it was properly extracted into form_value,
600 // or zero if we fail since an offset of zero is invalid for an attribute (it
601 // would be a compile unit header).
602 dw_offset_t DWARFDebugInfoEntry::GetAttributeValue(
603     const DWARFUnit *cu, const dw_attr_t attr, DWARFFormValue &form_value,
604     dw_offset_t *end_attr_offset_ptr,
605     bool check_specification_or_abstract_origin) const {
606   if (const auto *abbrevDecl = GetAbbreviationDeclarationPtr(cu)) {
607     uint32_t attr_idx = abbrevDecl->FindAttributeIndex(attr);
608 
609     if (attr_idx != DW_INVALID_INDEX) {
610       const DWARFDataExtractor &data = cu->GetData();
611       lldb::offset_t offset = GetFirstAttributeOffset();
612 
613       uint32_t idx = 0;
614       while (idx < attr_idx)
615         DWARFFormValue::SkipValue(abbrevDecl->GetFormByIndex(idx++),
616                                   data, &offset, cu);
617 
618       const dw_offset_t attr_offset = offset;
619       form_value.SetUnit(cu);
620       form_value.SetForm(abbrevDecl->GetFormByIndex(idx));
621       if (form_value.ExtractValue(data, &offset)) {
622         if (end_attr_offset_ptr)
623           *end_attr_offset_ptr = offset;
624         return attr_offset;
625       }
626     }
627   }
628 
629   if (check_specification_or_abstract_origin) {
630     if (GetAttributeValue(cu, DW_AT_specification, form_value)) {
631       DWARFDIE die = form_value.Reference();
632       if (die) {
633         dw_offset_t die_offset = die.GetDIE()->GetAttributeValue(
634             die.GetCU(), attr, form_value, end_attr_offset_ptr, false);
635         if (die_offset)
636           return die_offset;
637       }
638     }
639 
640     if (GetAttributeValue(cu, DW_AT_abstract_origin, form_value)) {
641       DWARFDIE die = form_value.Reference();
642       if (die) {
643         dw_offset_t die_offset = die.GetDIE()->GetAttributeValue(
644             die.GetCU(), attr, form_value, end_attr_offset_ptr, false);
645         if (die_offset)
646           return die_offset;
647       }
648     }
649   }
650 
651   // If we're a unit DIE, also check the attributes of the dwo unit (if any).
652   if (GetParent())
653     return 0;
654   SymbolFileDWARFDwo *dwo_symbol_file = cu->GetDwoSymbolFile();
655   if (!dwo_symbol_file)
656     return 0;
657 
658   DWARFCompileUnit *dwo_cu = dwo_symbol_file->GetCompileUnit();
659   if (!dwo_cu)
660     return 0;
661 
662   DWARFBaseDIE dwo_cu_die = dwo_cu->GetUnitDIEOnly();
663   if (!dwo_cu_die.IsValid())
664     return 0;
665 
666   return dwo_cu_die.GetDIE()->GetAttributeValue(
667       dwo_cu, attr, form_value, end_attr_offset_ptr,
668       check_specification_or_abstract_origin);
669 }
670 
671 // GetAttributeValueAsString
672 //
673 // Get the value of an attribute as a string return it. The resulting pointer
674 // to the string data exists within the supplied SymbolFileDWARF and will only
675 // be available as long as the SymbolFileDWARF is still around and it's content
676 // doesn't change.
677 const char *DWARFDebugInfoEntry::GetAttributeValueAsString(
678     const DWARFUnit *cu, const dw_attr_t attr, const char *fail_value,
679     bool check_specification_or_abstract_origin) const {
680   DWARFFormValue form_value;
681   if (GetAttributeValue(cu, attr, form_value, nullptr,
682                         check_specification_or_abstract_origin))
683     return form_value.AsCString();
684   return fail_value;
685 }
686 
687 // GetAttributeValueAsUnsigned
688 //
689 // Get the value of an attribute as unsigned and return it.
690 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsUnsigned(
691     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
692     bool check_specification_or_abstract_origin) const {
693   DWARFFormValue form_value;
694   if (GetAttributeValue(cu, attr, form_value, nullptr,
695                         check_specification_or_abstract_origin))
696     return form_value.Unsigned();
697   return fail_value;
698 }
699 
700 // GetAttributeValueAsReference
701 //
702 // Get the value of an attribute as reference and fix up and compile unit
703 // relative offsets as needed.
704 DWARFDIE DWARFDebugInfoEntry::GetAttributeValueAsReference(
705     const DWARFUnit *cu, const dw_attr_t attr,
706     bool check_specification_or_abstract_origin) const {
707   DWARFFormValue form_value;
708   if (GetAttributeValue(cu, attr, form_value, nullptr,
709                         check_specification_or_abstract_origin))
710     return form_value.Reference();
711   return {};
712 }
713 
714 uint64_t DWARFDebugInfoEntry::GetAttributeValueAsAddress(
715     const DWARFUnit *cu, const dw_attr_t attr, uint64_t fail_value,
716     bool check_specification_or_abstract_origin) const {
717   DWARFFormValue form_value;
718   if (GetAttributeValue(cu, attr, form_value, nullptr,
719                         check_specification_or_abstract_origin))
720     return form_value.Address();
721   return fail_value;
722 }
723 
724 // GetAttributeHighPC
725 //
726 // Get the hi_pc, adding hi_pc to lo_pc when specified as an <offset-from-low-
727 // pc>.
728 //
729 // Returns the hi_pc or fail_value.
730 dw_addr_t DWARFDebugInfoEntry::GetAttributeHighPC(
731     const DWARFUnit *cu, dw_addr_t lo_pc, uint64_t fail_value,
732     bool check_specification_or_abstract_origin) const {
733   DWARFFormValue form_value;
734   if (GetAttributeValue(cu, DW_AT_high_pc, form_value, nullptr,
735                         check_specification_or_abstract_origin)) {
736     dw_form_t form = form_value.Form();
737     if (form == DW_FORM_addr || form == DW_FORM_addrx ||
738         form == DW_FORM_GNU_addr_index)
739       return form_value.Address();
740 
741     // DWARF4 can specify the hi_pc as an <offset-from-lowpc>
742     return lo_pc + form_value.Unsigned();
743   }
744   return fail_value;
745 }
746 
747 // GetAttributeAddressRange
748 //
749 // Get the lo_pc and hi_pc, adding hi_pc to lo_pc when specified as an <offset-
750 // from-low-pc>.
751 //
752 // Returns true or sets lo_pc and hi_pc to fail_value.
753 bool DWARFDebugInfoEntry::GetAttributeAddressRange(
754     const DWARFUnit *cu, dw_addr_t &lo_pc, dw_addr_t &hi_pc,
755     uint64_t fail_value, bool check_specification_or_abstract_origin) const {
756   lo_pc = GetAttributeValueAsAddress(cu, DW_AT_low_pc, fail_value,
757                                      check_specification_or_abstract_origin);
758   if (lo_pc != fail_value) {
759     hi_pc = GetAttributeHighPC(cu, lo_pc, fail_value,
760                                check_specification_or_abstract_origin);
761     if (hi_pc != fail_value)
762       return true;
763   }
764   lo_pc = fail_value;
765   hi_pc = fail_value;
766   return false;
767 }
768 
769 size_t DWARFDebugInfoEntry::GetAttributeAddressRanges(
770     DWARFUnit *cu, DWARFRangeList &ranges, bool check_hi_lo_pc,
771     bool check_specification_or_abstract_origin) const {
772   ranges.Clear();
773 
774   DWARFFormValue form_value;
775   if (GetAttributeValue(cu, DW_AT_ranges, form_value)) {
776     ranges = GetRangesOrReportError(*cu, *this, form_value);
777   } else if (check_hi_lo_pc) {
778     dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
779     dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
780     if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS,
781                                  check_specification_or_abstract_origin)) {
782       if (lo_pc < hi_pc)
783         ranges.Append(DWARFRangeList::Entry(lo_pc, hi_pc - lo_pc));
784     }
785   }
786   return ranges.GetSize();
787 }
788 
789 // GetName
790 //
791 // Get value of the DW_AT_name attribute and return it if one exists, else
792 // return NULL.
793 const char *DWARFDebugInfoEntry::GetName(const DWARFUnit *cu) const {
794   return GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
795 }
796 
797 // GetMangledName
798 //
799 // Get value of the DW_AT_MIPS_linkage_name attribute and return it if one
800 // exists, else return the value of the DW_AT_name attribute
801 const char *
802 DWARFDebugInfoEntry::GetMangledName(const DWARFUnit *cu,
803                                     bool substitute_name_allowed) const {
804   const char *name = nullptr;
805 
806   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
807   if (name)
808     return name;
809 
810   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
811   if (name)
812     return name;
813 
814   if (!substitute_name_allowed)
815     return nullptr;
816 
817   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
818   return name;
819 }
820 
821 // GetPubname
822 //
823 // Get value the name for a DIE as it should appear for a .debug_pubnames or
824 // .debug_pubtypes section.
825 const char *DWARFDebugInfoEntry::GetPubname(const DWARFUnit *cu) const {
826   const char *name = nullptr;
827   if (!cu)
828     return name;
829 
830   name = GetAttributeValueAsString(cu, DW_AT_MIPS_linkage_name, nullptr, true);
831   if (name)
832     return name;
833 
834   name = GetAttributeValueAsString(cu, DW_AT_linkage_name, nullptr, true);
835   if (name)
836     return name;
837 
838   name = GetAttributeValueAsString(cu, DW_AT_name, nullptr, true);
839   return name;
840 }
841 
842 // BuildAddressRangeTable
843 void DWARFDebugInfoEntry::BuildAddressRangeTable(
844     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
845   if (m_tag) {
846     if (m_tag == DW_TAG_subprogram) {
847       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
848       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
849       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
850         /// printf("BuildAddressRangeTable() 0x%8.8x: %30s: [0x%8.8x -
851         /// 0x%8.8x)\n", m_offset, DW_TAG_value_to_name(tag), lo_pc, hi_pc);
852         debug_aranges->AppendRange(cu->GetOffset(), lo_pc, hi_pc);
853       }
854     }
855 
856     const DWARFDebugInfoEntry *child = GetFirstChild();
857     while (child) {
858       child->BuildAddressRangeTable(cu, debug_aranges);
859       child = child->GetSibling();
860     }
861   }
862 }
863 
864 // BuildFunctionAddressRangeTable
865 //
866 // This function is very similar to the BuildAddressRangeTable function except
867 // that the actual DIE offset for the function is placed in the table instead
868 // of the compile unit offset (which is the way the standard .debug_aranges
869 // section does it).
870 void DWARFDebugInfoEntry::BuildFunctionAddressRangeTable(
871     const DWARFUnit *cu, DWARFDebugAranges *debug_aranges) const {
872   if (m_tag) {
873     if (m_tag == DW_TAG_subprogram) {
874       dw_addr_t lo_pc = LLDB_INVALID_ADDRESS;
875       dw_addr_t hi_pc = LLDB_INVALID_ADDRESS;
876       if (GetAttributeAddressRange(cu, lo_pc, hi_pc, LLDB_INVALID_ADDRESS)) {
877         //  printf("BuildAddressRangeTable() 0x%8.8x: [0x%16.16" PRIx64 " -
878         //  0x%16.16" PRIx64 ")\n", m_offset, lo_pc, hi_pc); // DEBUG ONLY
879         debug_aranges->AppendRange(GetOffset(), lo_pc, hi_pc);
880       }
881     }
882 
883     const DWARFDebugInfoEntry *child = GetFirstChild();
884     while (child) {
885       child->BuildFunctionAddressRangeTable(cu, debug_aranges);
886       child = child->GetSibling();
887     }
888   }
889 }
890 
891 void DWARFDebugInfoEntry::GetDWARFDeclContext(
892     DWARFUnit *cu, DWARFDeclContext &dwarf_decl_ctx) const {
893   const dw_tag_t tag = Tag();
894   if (tag != DW_TAG_compile_unit && tag != DW_TAG_partial_unit) {
895     dwarf_decl_ctx.AppendDeclContext(tag, GetName(cu));
896     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
897     if (parent_decl_ctx_die && parent_decl_ctx_die.GetDIE() != this) {
898       if (parent_decl_ctx_die.Tag() != DW_TAG_compile_unit &&
899           parent_decl_ctx_die.Tag() != DW_TAG_partial_unit)
900         parent_decl_ctx_die.GetDIE()->GetDWARFDeclContext(
901             parent_decl_ctx_die.GetCU(), dwarf_decl_ctx);
902     }
903   }
904 }
905 
906 DWARFDIE
907 DWARFDebugInfoEntry::GetParentDeclContextDIE(DWARFUnit *cu) const {
908   DWARFAttributes attributes;
909   GetAttributes(cu, attributes);
910   return GetParentDeclContextDIE(cu, attributes);
911 }
912 
913 DWARFDIE
914 DWARFDebugInfoEntry::GetParentDeclContextDIE(
915     DWARFUnit *cu, const DWARFAttributes &attributes) const {
916   DWARFDIE die(cu, const_cast<DWARFDebugInfoEntry *>(this));
917 
918   while (die) {
919     // If this is the original DIE that we are searching for a declaration for,
920     // then don't look in the cache as we don't want our own decl context to be
921     // our decl context...
922     if (die.GetDIE() != this) {
923       switch (die.Tag()) {
924       case DW_TAG_compile_unit:
925       case DW_TAG_partial_unit:
926       case DW_TAG_namespace:
927       case DW_TAG_structure_type:
928       case DW_TAG_union_type:
929       case DW_TAG_class_type:
930         return die;
931 
932       default:
933         break;
934       }
935     }
936 
937     DWARFDIE spec_die = attributes.FormValueAsReference(DW_AT_specification);
938     if (spec_die) {
939       DWARFDIE decl_ctx_die = spec_die.GetParentDeclContextDIE();
940       if (decl_ctx_die)
941         return decl_ctx_die;
942     }
943 
944     DWARFDIE abs_die = attributes.FormValueAsReference(DW_AT_abstract_origin);
945     if (abs_die) {
946       DWARFDIE decl_ctx_die = abs_die.GetParentDeclContextDIE();
947       if (decl_ctx_die)
948         return decl_ctx_die;
949     }
950 
951     die = die.GetParent();
952   }
953   return DWARFDIE();
954 }
955 
956 const char *DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
957                                                   std::string &storage) const {
958   DWARFAttributes attributes;
959   GetAttributes(cu, attributes);
960   return GetQualifiedName(cu, attributes, storage);
961 }
962 
963 const char *
964 DWARFDebugInfoEntry::GetQualifiedName(DWARFUnit *cu,
965                                       const DWARFAttributes &attributes,
966                                       std::string &storage) const {
967 
968   const char *name = GetName(cu);
969 
970   if (name) {
971     DWARFDIE parent_decl_ctx_die = GetParentDeclContextDIE(cu);
972     storage.clear();
973     // TODO: change this to get the correct decl context parent....
974     while (parent_decl_ctx_die) {
975       const dw_tag_t parent_tag = parent_decl_ctx_die.Tag();
976       switch (parent_tag) {
977       case DW_TAG_namespace: {
978         const char *namespace_name = parent_decl_ctx_die.GetName();
979         if (namespace_name) {
980           storage.insert(0, "::");
981           storage.insert(0, namespace_name);
982         } else {
983           storage.insert(0, "(anonymous namespace)::");
984         }
985         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
986       } break;
987 
988       case DW_TAG_class_type:
989       case DW_TAG_structure_type:
990       case DW_TAG_union_type: {
991         const char *class_union_struct_name = parent_decl_ctx_die.GetName();
992 
993         if (class_union_struct_name) {
994           storage.insert(0, "::");
995           storage.insert(0, class_union_struct_name);
996         }
997         parent_decl_ctx_die = parent_decl_ctx_die.GetParentDeclContextDIE();
998       } break;
999 
1000       default:
1001         parent_decl_ctx_die.Clear();
1002         break;
1003       }
1004     }
1005 
1006     if (storage.empty())
1007       storage.append("::");
1008 
1009     storage.append(name);
1010   }
1011   if (storage.empty())
1012     return nullptr;
1013   return storage.c_str();
1014 }
1015 
1016 bool DWARFDebugInfoEntry::LookupAddress(const dw_addr_t address, DWARFUnit *cu,
1017                                         DWARFDebugInfoEntry **function_die,
1018                                         DWARFDebugInfoEntry **block_die) {
1019   bool found_address = false;
1020   if (m_tag) {
1021     bool check_children = false;
1022     bool match_addr_range = false;
1023     //  printf("0x%8.8x: %30s: address = 0x%8.8x - ", m_offset,
1024     //  DW_TAG_value_to_name(tag), address);
1025     switch (m_tag) {
1026     case DW_TAG_array_type:
1027       break;
1028     case DW_TAG_class_type:
1029       check_children = true;
1030       break;
1031     case DW_TAG_entry_point:
1032     case DW_TAG_enumeration_type:
1033     case DW_TAG_formal_parameter:
1034     case DW_TAG_imported_declaration:
1035     case DW_TAG_label:
1036       break;
1037     case DW_TAG_lexical_block:
1038       check_children = true;
1039       match_addr_range = true;
1040       break;
1041     case DW_TAG_member:
1042     case DW_TAG_pointer_type:
1043     case DW_TAG_reference_type:
1044       break;
1045     case DW_TAG_compile_unit:
1046       match_addr_range = true;
1047       break;
1048     case DW_TAG_string_type:
1049       break;
1050     case DW_TAG_structure_type:
1051       check_children = true;
1052       break;
1053     case DW_TAG_subroutine_type:
1054     case DW_TAG_typedef:
1055     case DW_TAG_union_type:
1056     case DW_TAG_unspecified_parameters:
1057     case DW_TAG_variant:
1058       break;
1059     case DW_TAG_common_block:
1060       check_children = true;
1061       break;
1062     case DW_TAG_common_inclusion:
1063     case DW_TAG_inheritance:
1064       break;
1065     case DW_TAG_inlined_subroutine:
1066       check_children = true;
1067       match_addr_range = true;
1068       break;
1069     case DW_TAG_module:
1070       match_addr_range = true;
1071       break;
1072     case DW_TAG_ptr_to_member_type:
1073     case DW_TAG_set_type:
1074     case DW_TAG_subrange_type:
1075     case DW_TAG_with_stmt:
1076     case DW_TAG_access_declaration:
1077     case DW_TAG_base_type:
1078       break;
1079     case DW_TAG_catch_block:
1080       match_addr_range = true;
1081       break;
1082     case DW_TAG_const_type:
1083     case DW_TAG_constant:
1084     case DW_TAG_enumerator:
1085     case DW_TAG_file_type:
1086     case DW_TAG_friend:
1087     case DW_TAG_namelist:
1088     case DW_TAG_namelist_item:
1089     case DW_TAG_packed_type:
1090       break;
1091     case DW_TAG_subprogram:
1092       match_addr_range = true;
1093       break;
1094     case DW_TAG_template_type_parameter:
1095     case DW_TAG_template_value_parameter:
1096     case DW_TAG_GNU_template_parameter_pack:
1097     case DW_TAG_thrown_type:
1098       break;
1099     case DW_TAG_try_block:
1100       match_addr_range = true;
1101       break;
1102     case DW_TAG_variant_part:
1103     case DW_TAG_variable:
1104     case DW_TAG_volatile_type:
1105     case DW_TAG_dwarf_procedure:
1106     case DW_TAG_restrict_type:
1107     case DW_TAG_interface_type:
1108       break;
1109     case DW_TAG_namespace:
1110       check_children = true;
1111       break;
1112     case DW_TAG_imported_module:
1113     case DW_TAG_unspecified_type:
1114       break;
1115     case DW_TAG_partial_unit:
1116       match_addr_range = true;
1117       break;
1118     case DW_TAG_imported_unit:
1119     case DW_TAG_shared_type:
1120     default:
1121       break;
1122     }
1123 
1124     if (match_addr_range) {
1125       dw_addr_t lo_pc =
1126           GetAttributeValueAsAddress(cu, DW_AT_low_pc, LLDB_INVALID_ADDRESS);
1127       if (lo_pc != LLDB_INVALID_ADDRESS) {
1128         dw_addr_t hi_pc = GetAttributeHighPC(cu, lo_pc, LLDB_INVALID_ADDRESS);
1129         if (hi_pc != LLDB_INVALID_ADDRESS) {
1130           //  printf("\n0x%8.8x: %30s: address = 0x%8.8x  [0x%8.8x - 0x%8.8x) ",
1131           //  m_offset, DW_TAG_value_to_name(tag), address, lo_pc, hi_pc);
1132           if ((lo_pc <= address) && (address < hi_pc)) {
1133             found_address = true;
1134             //  puts("***MATCH***");
1135             switch (m_tag) {
1136             case DW_TAG_compile_unit: // File
1137             case DW_TAG_partial_unit: // File
1138               check_children =
1139                   ((function_die != nullptr) || (block_die != nullptr));
1140               break;
1141 
1142             case DW_TAG_subprogram: // Function
1143               if (function_die)
1144                 *function_die = this;
1145               check_children = (block_die != nullptr);
1146               break;
1147 
1148             case DW_TAG_inlined_subroutine: // Inlined Function
1149             case DW_TAG_lexical_block:      // Block { } in code
1150               if (block_die) {
1151                 *block_die = this;
1152                 check_children = true;
1153               }
1154               break;
1155 
1156             default:
1157               check_children = true;
1158               break;
1159             }
1160           }
1161         } else {
1162           // Compile units may not have a valid high/low pc when there
1163           // are address gaps in subroutines so we must always search
1164           // if there is no valid high and low PC.
1165           check_children =
1166               (m_tag == DW_TAG_compile_unit || m_tag == DW_TAG_partial_unit) &&
1167               ((function_die != nullptr) || (block_die != nullptr));
1168         }
1169       } else {
1170         DWARFRangeList ranges;
1171         if (GetAttributeAddressRanges(cu, ranges, /*check_hi_lo_pc*/ false) &&
1172             ranges.FindEntryThatContains(address)) {
1173           found_address = true;
1174           //  puts("***MATCH***");
1175           switch (m_tag) {
1176           case DW_TAG_compile_unit: // File
1177           case DW_TAG_partial_unit: // File
1178               check_children =
1179                   ((function_die != nullptr) || (block_die != nullptr));
1180               break;
1181 
1182           case DW_TAG_subprogram: // Function
1183             if (function_die)
1184               *function_die = this;
1185             check_children = (block_die != nullptr);
1186             break;
1187 
1188           case DW_TAG_inlined_subroutine: // Inlined Function
1189           case DW_TAG_lexical_block:      // Block { } in code
1190             if (block_die) {
1191               *block_die = this;
1192               check_children = true;
1193             }
1194             break;
1195 
1196           default:
1197             check_children = true;
1198             break;
1199           }
1200         } else {
1201           check_children = false;
1202         }
1203       }
1204     }
1205 
1206     if (check_children) {
1207       //  printf("checking children\n");
1208       DWARFDebugInfoEntry *child = GetFirstChild();
1209       while (child) {
1210         if (child->LookupAddress(address, cu, function_die, block_die))
1211           return true;
1212         child = child->GetSibling();
1213       }
1214     }
1215   }
1216   return found_address;
1217 }
1218 
1219 lldb::offset_t DWARFDebugInfoEntry::GetFirstAttributeOffset() const {
1220   return GetOffset() + llvm::getULEB128Size(m_abbr_idx);
1221 }
1222 
1223 const DWARFAbbreviationDeclaration *
1224 DWARFDebugInfoEntry::GetAbbreviationDeclarationPtr(const DWARFUnit *cu) const {
1225   if (cu) {
1226     const DWARFAbbreviationDeclarationSet *abbrev_set = cu->GetAbbreviations();
1227     if (abbrev_set)
1228       return abbrev_set->GetAbbreviationDeclaration(m_abbr_idx);
1229   }
1230   return nullptr;
1231 }
1232 
1233 bool DWARFDebugInfoEntry::operator==(const DWARFDebugInfoEntry &rhs) const {
1234   return m_offset == rhs.m_offset && m_parent_idx == rhs.m_parent_idx &&
1235          m_sibling_idx == rhs.m_sibling_idx &&
1236          m_abbr_idx == rhs.m_abbr_idx && m_has_children == rhs.m_has_children &&
1237          m_tag == rhs.m_tag;
1238 }
1239 
1240 bool DWARFDebugInfoEntry::operator!=(const DWARFDebugInfoEntry &rhs) const {
1241   return !(*this == rhs);
1242 }
1243