1 //===- DWARFDie.cpp -------------------------------------------------------===//
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 "llvm/DebugInfo/DWARF/DWARFDie.h"
10 #include "llvm/ADT/None.h"
11 #include "llvm/ADT/Optional.h"
12 #include "llvm/ADT/SmallSet.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/BinaryFormat/Dwarf.h"
15 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
16 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDebugLine.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
19 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/DebugInfo/DWARF/DWARFTypePrinter.h"
22 #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
23 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
24 #include "llvm/Object/ObjectFile.h"
25 #include "llvm/Support/DataExtractor.h"
26 #include "llvm/Support/Format.h"
27 #include "llvm/Support/FormatVariadic.h"
28 #include "llvm/Support/MathExtras.h"
29 #include "llvm/Support/ScopedPrinter.h"
30 #include "llvm/Support/WithColor.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <cassert>
33 #include <cinttypes>
34 #include <cstdint>
35 #include <string>
36 #include <utility>
37 
38 using namespace llvm;
39 using namespace dwarf;
40 using namespace object;
41 
42 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
43   OS << " (";
44   do {
45     uint64_t Shift = countTrailingZeros(Val);
46     assert(Shift < 64 && "undefined behavior");
47     uint64_t Bit = 1ULL << Shift;
48     auto PropName = ApplePropertyString(Bit);
49     if (!PropName.empty())
50       OS << PropName;
51     else
52       OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
53     if (!(Val ^= Bit))
54       break;
55     OS << ", ";
56   } while (true);
57   OS << ")";
58 }
59 
60 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
61                        const DWARFAddressRangesVector &Ranges,
62                        unsigned AddressSize, unsigned Indent,
63                        const DIDumpOptions &DumpOpts) {
64   if (!DumpOpts.ShowAddresses)
65     return;
66 
67   for (const DWARFAddressRange &R : Ranges) {
68     OS << '\n';
69     OS.indent(Indent);
70     R.dump(OS, AddressSize, DumpOpts, &Obj);
71   }
72 }
73 
74 static void dumpLocationList(raw_ostream &OS, const DWARFFormValue &FormValue,
75                              DWARFUnit *U, unsigned Indent,
76                              DIDumpOptions DumpOpts) {
77   assert(FormValue.isFormClass(DWARFFormValue::FC_SectionOffset) &&
78          "bad FORM for location list");
79   DWARFContext &Ctx = U->getContext();
80   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
81   uint64_t Offset = *FormValue.getAsSectionOffset();
82 
83   if (FormValue.getForm() == DW_FORM_loclistx) {
84     FormValue.dump(OS, DumpOpts);
85 
86     if (auto LoclistOffset = U->getLoclistOffset(Offset))
87       Offset = *LoclistOffset;
88     else
89       return;
90   }
91   U->getLocationTable().dumpLocationList(&Offset, OS, U->getBaseAddress(), MRI,
92                                          Ctx.getDWARFObj(), U, DumpOpts,
93                                          Indent);
94 }
95 
96 static void dumpLocationExpr(raw_ostream &OS, const DWARFFormValue &FormValue,
97                              DWARFUnit *U, unsigned Indent,
98                              DIDumpOptions DumpOpts) {
99   assert((FormValue.isFormClass(DWARFFormValue::FC_Block) ||
100           FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) &&
101          "bad FORM for location expression");
102   DWARFContext &Ctx = U->getContext();
103   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
104   ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
105   DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
106                      Ctx.isLittleEndian(), 0);
107   DWARFExpression(Data, U->getAddressByteSize(), U->getFormParams().Format)
108       .print(OS, DumpOpts, MRI, U);
109 }
110 
111 static DWARFDie resolveReferencedType(DWARFDie D, DWARFFormValue F) {
112   return D.getAttributeValueAsReferencedDie(F).resolveTypeUnitReference();
113 }
114 
115 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
116                           const DWARFAttribute &AttrValue, unsigned Indent,
117                           DIDumpOptions DumpOpts) {
118   if (!Die.isValid())
119     return;
120   const char BaseIndent[] = "            ";
121   OS << BaseIndent;
122   OS.indent(Indent + 2);
123   dwarf::Attribute Attr = AttrValue.Attr;
124   WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
125 
126   dwarf::Form Form = AttrValue.Value.getForm();
127   if (DumpOpts.Verbose || DumpOpts.ShowForm)
128     OS << formatv(" [{0}]", Form);
129 
130   DWARFUnit *U = Die.getDwarfUnit();
131   const DWARFFormValue &FormValue = AttrValue.Value;
132 
133   OS << "\t(";
134 
135   StringRef Name;
136   std::string File;
137   auto Color = HighlightColor::Enumerator;
138   if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
139     Color = HighlightColor::String;
140     if (const auto *LT = U->getContext().getLineTableForUnit(U))
141       if (LT->getFileNameByIndex(
142               *FormValue.getAsUnsignedConstant(), U->getCompilationDir(),
143               DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
144         File = '"' + File + '"';
145         Name = File;
146       }
147   } else if (Optional<uint64_t> Val = FormValue.getAsUnsignedConstant())
148     Name = AttributeValueString(Attr, *Val);
149 
150   if (!Name.empty())
151     WithColor(OS, Color) << Name;
152   else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
153     OS << *FormValue.getAsUnsignedConstant();
154   else if (Attr == DW_AT_low_pc &&
155            (FormValue.getAsAddress() ==
156             dwarf::computeTombstoneAddress(U->getAddressByteSize()))) {
157     if (DumpOpts.Verbose) {
158       FormValue.dump(OS, DumpOpts);
159       OS << " (";
160     }
161     OS << "dead code";
162     if (DumpOpts.Verbose)
163       OS << ')';
164   } else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
165              FormValue.getAsUnsignedConstant()) {
166     if (DumpOpts.ShowAddresses) {
167       // Print the actual address rather than the offset.
168       uint64_t LowPC, HighPC, Index;
169       if (Die.getLowAndHighPC(LowPC, HighPC, Index))
170         DWARFFormValue::dumpAddress(OS, U->getAddressByteSize(), HighPC);
171       else
172         FormValue.dump(OS, DumpOpts);
173     }
174   } else if (DWARFAttribute::mayHaveLocationList(Attr) &&
175              FormValue.isFormClass(DWARFFormValue::FC_SectionOffset))
176     dumpLocationList(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
177                      DumpOpts);
178   else if (FormValue.isFormClass(DWARFFormValue::FC_Exprloc) ||
179            (DWARFAttribute::mayHaveLocationExpr(Attr) &&
180             FormValue.isFormClass(DWARFFormValue::FC_Block)))
181     dumpLocationExpr(OS, FormValue, U, sizeof(BaseIndent) + Indent + 4,
182                      DumpOpts);
183   else
184     FormValue.dump(OS, DumpOpts);
185 
186   std::string Space = DumpOpts.ShowAddresses ? " " : "";
187 
188   // We have dumped the attribute raw value. For some attributes
189   // having both the raw value and the pretty-printed value is
190   // interesting. These attributes are handled below.
191   if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
192     if (const char *Name =
193             Die.getAttributeValueAsReferencedDie(FormValue).getName(
194                 DINameKind::LinkageName))
195       OS << Space << "\"" << Name << '\"';
196   } else if (Attr == DW_AT_type || Attr == DW_AT_containing_type) {
197     DWARFDie D = resolveReferencedType(Die, FormValue);
198     if (D && !D.isNULL()) {
199       OS << Space << "\"";
200       dumpTypeQualifiedName(D, OS);
201       OS << '"';
202     }
203   } else if (Attr == DW_AT_APPLE_property_attribute) {
204     if (Optional<uint64_t> OptVal = FormValue.getAsUnsignedConstant())
205       dumpApplePropertyAttribute(OS, *OptVal);
206   } else if (Attr == DW_AT_ranges) {
207     const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
208     // For DW_FORM_rnglistx we need to dump the offset separately, since
209     // we have only dumped the index so far.
210     if (FormValue.getForm() == DW_FORM_rnglistx)
211       if (auto RangeListOffset =
212               U->getRnglistOffset(*FormValue.getAsSectionOffset())) {
213         DWARFFormValue FV = DWARFFormValue::createFromUValue(
214             dwarf::DW_FORM_sec_offset, *RangeListOffset);
215         FV.dump(OS, DumpOpts);
216       }
217     if (auto RangesOrError = Die.getAddressRanges())
218       dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
219                  sizeof(BaseIndent) + Indent + 4, DumpOpts);
220     else
221       DumpOpts.RecoverableErrorHandler(createStringError(
222           errc::invalid_argument, "decoding address ranges: %s",
223           toString(RangesOrError.takeError()).c_str()));
224   }
225 
226   OS << ")\n";
227 }
228 
229 void DWARFDie::getFullName(raw_string_ostream &OS,
230                            std::string *OriginalFullName) const {
231   const char *NamePtr = getShortName();
232   if (!NamePtr)
233     return;
234   if (getTag() == DW_TAG_GNU_template_parameter_pack)
235     return;
236   dumpTypeUnqualifiedName(*this, OS, OriginalFullName);
237 }
238 
239 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
240 
241 bool DWARFDie::isSubroutineDIE() const {
242   auto Tag = getTag();
243   return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
244 }
245 
246 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
247   if (!isValid())
248     return None;
249   auto AbbrevDecl = getAbbreviationDeclarationPtr();
250   if (AbbrevDecl)
251     return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
252   return None;
253 }
254 
255 Optional<DWARFFormValue>
256 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
257   if (!isValid())
258     return None;
259   auto AbbrevDecl = getAbbreviationDeclarationPtr();
260   if (AbbrevDecl) {
261     for (auto Attr : Attrs) {
262       if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
263         return Value;
264     }
265   }
266   return None;
267 }
268 
269 Optional<DWARFFormValue>
270 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
271   SmallVector<DWARFDie, 3> Worklist;
272   Worklist.push_back(*this);
273 
274   // Keep track if DIEs already seen to prevent infinite recursion.
275   // Empirically we rarely see a depth of more than 3 when dealing with valid
276   // DWARF. This corresponds to following the DW_AT_abstract_origin and
277   // DW_AT_specification just once.
278   SmallSet<DWARFDie, 3> Seen;
279   Seen.insert(*this);
280 
281   while (!Worklist.empty()) {
282     DWARFDie Die = Worklist.pop_back_val();
283 
284     if (!Die.isValid())
285       continue;
286 
287     if (auto Value = Die.find(Attrs))
288       return Value;
289 
290     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
291       if (Seen.insert(D).second)
292         Worklist.push_back(D);
293 
294     if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
295       if (Seen.insert(D).second)
296         Worklist.push_back(D);
297   }
298 
299   return None;
300 }
301 
302 DWARFDie
303 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
304   if (Optional<DWARFFormValue> F = find(Attr))
305     return getAttributeValueAsReferencedDie(*F);
306   return DWARFDie();
307 }
308 
309 DWARFDie
310 DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
311   DWARFDie Result;
312   if (auto SpecRef = V.getAsRelativeReference()) {
313     if (SpecRef->Unit)
314       Result = SpecRef->Unit->getDIEForOffset(SpecRef->Unit->getOffset() +
315                                               SpecRef->Offset);
316     else if (auto SpecUnit =
317                  U->getUnitVector().getUnitForOffset(SpecRef->Offset))
318       Result = SpecUnit->getDIEForOffset(SpecRef->Offset);
319   }
320   return Result;
321 }
322 
323 DWARFDie DWARFDie::resolveTypeUnitReference() const {
324   if (auto Attr = find(DW_AT_signature)) {
325     if (Optional<uint64_t> Sig = Attr->getAsReferenceUVal()) {
326       if (DWARFTypeUnit *TU = U->getContext().getTypeUnitForHash(
327               U->getVersion(), *Sig, U->isDWOUnit()))
328         return TU->getDIEForOffset(TU->getTypeOffset() + TU->getOffset());
329     }
330   }
331   return *this;
332 }
333 
334 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
335   return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
336 }
337 
338 Optional<uint64_t> DWARFDie::getLocBaseAttribute() const {
339   return toSectionOffset(find(DW_AT_loclists_base));
340 }
341 
342 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
343   uint64_t Tombstone = dwarf::computeTombstoneAddress(U->getAddressByteSize());
344   if (LowPC == Tombstone)
345     return None;
346   if (auto FormValue = find(DW_AT_high_pc)) {
347     if (auto Address = FormValue->getAsAddress()) {
348       // High PC is an address.
349       return Address;
350     }
351     if (auto Offset = FormValue->getAsUnsignedConstant()) {
352       // High PC is an offset from LowPC.
353       return LowPC + *Offset;
354     }
355   }
356   return None;
357 }
358 
359 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
360                                uint64_t &SectionIndex) const {
361   auto F = find(DW_AT_low_pc);
362   auto LowPcAddr = toSectionedAddress(F);
363   if (!LowPcAddr)
364     return false;
365   if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
366     LowPC = LowPcAddr->Address;
367     HighPC = *HighPcAddr;
368     SectionIndex = LowPcAddr->SectionIndex;
369     return true;
370   }
371   return false;
372 }
373 
374 Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
375   if (isNULL())
376     return DWARFAddressRangesVector();
377   // Single range specified by low/high PC.
378   uint64_t LowPC, HighPC, Index;
379   if (getLowAndHighPC(LowPC, HighPC, Index))
380     return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
381 
382   Optional<DWARFFormValue> Value = find(DW_AT_ranges);
383   if (Value) {
384     if (Value->getForm() == DW_FORM_rnglistx)
385       return U->findRnglistFromIndex(*Value->getAsSectionOffset());
386     return U->findRnglistFromOffset(*Value->getAsSectionOffset());
387   }
388   return DWARFAddressRangesVector();
389 }
390 
391 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
392   auto RangesOrError = getAddressRanges();
393   if (!RangesOrError) {
394     llvm::consumeError(RangesOrError.takeError());
395     return false;
396   }
397 
398   for (const auto &R : RangesOrError.get())
399     if (R.LowPC <= Address && Address < R.HighPC)
400       return true;
401   return false;
402 }
403 
404 Expected<DWARFLocationExpressionsVector>
405 DWARFDie::getLocations(dwarf::Attribute Attr) const {
406   Optional<DWARFFormValue> Location = find(Attr);
407   if (!Location)
408     return createStringError(inconvertibleErrorCode(), "No %s",
409                              dwarf::AttributeString(Attr).data());
410 
411   if (Optional<uint64_t> Off = Location->getAsSectionOffset()) {
412     uint64_t Offset = *Off;
413 
414     if (Location->getForm() == DW_FORM_loclistx) {
415       if (auto LoclistOffset = U->getLoclistOffset(Offset))
416         Offset = *LoclistOffset;
417       else
418         return createStringError(inconvertibleErrorCode(),
419                                  "Loclist table not found");
420     }
421     return U->findLoclistFromOffset(Offset);
422   }
423 
424   if (Optional<ArrayRef<uint8_t>> Expr = Location->getAsBlock()) {
425     return DWARFLocationExpressionsVector{
426         DWARFLocationExpression{None, to_vector<4>(*Expr)}};
427   }
428 
429   return createStringError(
430       inconvertibleErrorCode(), "Unsupported %s encoding: %s",
431       dwarf::AttributeString(Attr).data(),
432       dwarf::FormEncodingString(Location->getForm()).data());
433 }
434 
435 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
436   if (!isSubroutineDIE())
437     return nullptr;
438   return getName(Kind);
439 }
440 
441 const char *DWARFDie::getName(DINameKind Kind) const {
442   if (!isValid() || Kind == DINameKind::None)
443     return nullptr;
444   // Try to get mangled name only if it was asked for.
445   if (Kind == DINameKind::LinkageName) {
446     if (auto Name = getLinkageName())
447       return Name;
448   }
449   return getShortName();
450 }
451 
452 const char *DWARFDie::getShortName() const {
453   if (!isValid())
454     return nullptr;
455 
456   return dwarf::toString(findRecursively(dwarf::DW_AT_name), nullptr);
457 }
458 
459 const char *DWARFDie::getLinkageName() const {
460   if (!isValid())
461     return nullptr;
462 
463   return dwarf::toString(findRecursively({dwarf::DW_AT_MIPS_linkage_name,
464                                           dwarf::DW_AT_linkage_name}),
465                          nullptr);
466 }
467 
468 uint64_t DWARFDie::getDeclLine() const {
469   return toUnsigned(findRecursively(DW_AT_decl_line), 0);
470 }
471 
472 std::string
473 DWARFDie::getDeclFile(DILineInfoSpecifier::FileLineInfoKind Kind) const {
474   if (auto FormValue = findRecursively(DW_AT_decl_file))
475     if (auto OptString = FormValue->getAsFile(Kind))
476       return *OptString;
477   return {};
478 }
479 
480 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
481                               uint32_t &CallColumn,
482                               uint32_t &CallDiscriminator) const {
483   CallFile = toUnsigned(find(DW_AT_call_file), 0);
484   CallLine = toUnsigned(find(DW_AT_call_line), 0);
485   CallColumn = toUnsigned(find(DW_AT_call_column), 0);
486   CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
487 }
488 
489 Optional<uint64_t> DWARFDie::getTypeSize(uint64_t PointerSize) {
490   if (auto SizeAttr = find(DW_AT_byte_size))
491     if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
492       return Size;
493 
494   switch (getTag()) {
495   case DW_TAG_pointer_type:
496   case DW_TAG_reference_type:
497   case DW_TAG_rvalue_reference_type:
498     return PointerSize;
499   case DW_TAG_ptr_to_member_type: {
500     if (DWARFDie BaseType = getAttributeValueAsReferencedDie(DW_AT_type))
501       if (BaseType.getTag() == DW_TAG_subroutine_type)
502         return 2 * PointerSize;
503     return PointerSize;
504   }
505   case DW_TAG_const_type:
506   case DW_TAG_immutable_type:
507   case DW_TAG_volatile_type:
508   case DW_TAG_restrict_type:
509   case DW_TAG_typedef: {
510     if (DWARFDie BaseType = getAttributeValueAsReferencedDie(DW_AT_type))
511       return BaseType.getTypeSize(PointerSize);
512     break;
513   }
514   case DW_TAG_array_type: {
515     DWARFDie BaseType = getAttributeValueAsReferencedDie(DW_AT_type);
516     if (!BaseType)
517       return None;
518     Optional<uint64_t> BaseSize = BaseType.getTypeSize(PointerSize);
519     if (!BaseSize)
520       return None;
521     uint64_t Size = *BaseSize;
522     for (DWARFDie Child : *this) {
523       if (Child.getTag() != DW_TAG_subrange_type)
524         continue;
525 
526       if (auto ElemCountAttr = Child.find(DW_AT_count))
527         if (Optional<uint64_t> ElemCount =
528                 ElemCountAttr->getAsUnsignedConstant())
529           Size *= *ElemCount;
530       if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
531         if (Optional<int64_t> UpperBound =
532                 UpperBoundAttr->getAsSignedConstant()) {
533           int64_t LowerBound = 0;
534           if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
535             LowerBound = LowerBoundAttr->getAsSignedConstant().value_or(0);
536           Size *= *UpperBound - LowerBound + 1;
537         }
538     }
539     return Size;
540   }
541   default:
542     if (DWARFDie BaseType = getAttributeValueAsReferencedDie(DW_AT_type))
543       return BaseType.getTypeSize(PointerSize);
544     break;
545   }
546   return None;
547 }
548 
549 /// Helper to dump a DIE with all of its parents, but no siblings.
550 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
551                                 DIDumpOptions DumpOpts, unsigned Depth = 0) {
552   if (!Die)
553     return Indent;
554   if (DumpOpts.ParentRecurseDepth > 0 && Depth >= DumpOpts.ParentRecurseDepth)
555     return Indent;
556   Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts, Depth + 1);
557   Die.dump(OS, Indent, DumpOpts);
558   return Indent + 2;
559 }
560 
561 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
562                     DIDumpOptions DumpOpts) const {
563   if (!isValid())
564     return;
565   DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
566   const uint64_t Offset = getOffset();
567   uint64_t offset = Offset;
568   if (DumpOpts.ShowParents) {
569     DIDumpOptions ParentDumpOpts = DumpOpts;
570     ParentDumpOpts.ShowParents = false;
571     ParentDumpOpts.ShowChildren = false;
572     Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
573   }
574 
575   if (debug_info_data.isValidOffset(offset)) {
576     uint32_t abbrCode = debug_info_data.getULEB128(&offset);
577     if (DumpOpts.ShowAddresses)
578       WithColor(OS, HighlightColor::Address).get()
579           << format("\n0x%8.8" PRIx64 ": ", Offset);
580 
581     if (abbrCode) {
582       auto AbbrevDecl = getAbbreviationDeclarationPtr();
583       if (AbbrevDecl) {
584         WithColor(OS, HighlightColor::Tag).get().indent(Indent)
585             << formatv("{0}", getTag());
586         if (DumpOpts.Verbose) {
587           OS << format(" [%u] %c", abbrCode,
588                        AbbrevDecl->hasChildren() ? '*' : ' ');
589           if (Optional<uint32_t> ParentIdx = Die->getParentIdx())
590             OS << format(" (0x%8.8" PRIx64 ")",
591                          U->getDIEAtIndex(*ParentIdx).getOffset());
592         }
593         OS << '\n';
594 
595         // Dump all data in the DIE for the attributes.
596         for (const DWARFAttribute &AttrValue : attributes())
597           dumpAttribute(OS, *this, AttrValue, Indent, DumpOpts);
598 
599         if (DumpOpts.ShowChildren && DumpOpts.ChildRecurseDepth > 0) {
600           DWARFDie Child = getFirstChild();
601           DumpOpts.ChildRecurseDepth--;
602           DIDumpOptions ChildDumpOpts = DumpOpts;
603           ChildDumpOpts.ShowParents = false;
604           while (Child) {
605             Child.dump(OS, Indent + 2, ChildDumpOpts);
606             Child = Child.getSibling();
607           }
608         }
609       } else {
610         OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
611            << abbrCode << '\n';
612       }
613     } else {
614       OS.indent(Indent) << "NULL\n";
615     }
616   }
617 }
618 
619 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
620 
621 DWARFDie DWARFDie::getParent() const {
622   if (isValid())
623     return U->getParent(Die);
624   return DWARFDie();
625 }
626 
627 DWARFDie DWARFDie::getSibling() const {
628   if (isValid())
629     return U->getSibling(Die);
630   return DWARFDie();
631 }
632 
633 DWARFDie DWARFDie::getPreviousSibling() const {
634   if (isValid())
635     return U->getPreviousSibling(Die);
636   return DWARFDie();
637 }
638 
639 DWARFDie DWARFDie::getFirstChild() const {
640   if (isValid())
641     return U->getFirstChild(Die);
642   return DWARFDie();
643 }
644 
645 DWARFDie DWARFDie::getLastChild() const {
646   if (isValid())
647     return U->getLastChild(Die);
648   return DWARFDie();
649 }
650 
651 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
652   return make_range(attribute_iterator(*this, false),
653                     attribute_iterator(*this, true));
654 }
655 
656 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
657     : Die(D), Index(0) {
658   auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
659   assert(AbbrDecl && "Must have abbreviation declaration");
660   if (End) {
661     // This is the end iterator so we set the index to the attribute count.
662     Index = AbbrDecl->getNumAttributes();
663   } else {
664     // This is the begin iterator so we extract the value for this->Index.
665     AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
666     updateForIndex(*AbbrDecl, 0);
667   }
668 }
669 
670 void DWARFDie::attribute_iterator::updateForIndex(
671     const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
672   Index = I;
673   // AbbrDecl must be valid before calling this function.
674   auto NumAttrs = AbbrDecl.getNumAttributes();
675   if (Index < NumAttrs) {
676     AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
677     // Add the previous byte size of any previous attribute value.
678     AttrValue.Offset += AttrValue.ByteSize;
679     uint64_t ParseOffset = AttrValue.Offset;
680     if (AbbrDecl.getAttrIsImplicitConstByIndex(Index))
681       AttrValue.Value = DWARFFormValue::createFromSValue(
682           AbbrDecl.getFormByIndex(Index),
683           AbbrDecl.getAttrImplicitConstValueByIndex(Index));
684     else {
685       auto U = Die.getDwarfUnit();
686       assert(U && "Die must have valid DWARF unit");
687       AttrValue.Value = DWARFFormValue::createFromUnit(
688           AbbrDecl.getFormByIndex(Index), U, &ParseOffset);
689     }
690     AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
691   } else {
692     assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
693     AttrValue = {};
694   }
695 }
696 
697 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
698   if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
699     updateForIndex(*AbbrDecl, Index + 1);
700   return *this;
701 }
702 
703 bool DWARFAttribute::mayHaveLocationList(dwarf::Attribute Attr) {
704   switch(Attr) {
705   case DW_AT_location:
706   case DW_AT_string_length:
707   case DW_AT_return_addr:
708   case DW_AT_data_member_location:
709   case DW_AT_frame_base:
710   case DW_AT_static_link:
711   case DW_AT_segment:
712   case DW_AT_use_location:
713   case DW_AT_vtable_elem_location:
714     return true;
715   default:
716     return false;
717   }
718 }
719 
720 bool DWARFAttribute::mayHaveLocationExpr(dwarf::Attribute Attr) {
721   switch (Attr) {
722   // From the DWARF v5 specification.
723   case DW_AT_location:
724   case DW_AT_byte_size:
725   case DW_AT_bit_offset:
726   case DW_AT_bit_size:
727   case DW_AT_string_length:
728   case DW_AT_lower_bound:
729   case DW_AT_return_addr:
730   case DW_AT_bit_stride:
731   case DW_AT_upper_bound:
732   case DW_AT_count:
733   case DW_AT_data_member_location:
734   case DW_AT_frame_base:
735   case DW_AT_segment:
736   case DW_AT_static_link:
737   case DW_AT_use_location:
738   case DW_AT_vtable_elem_location:
739   case DW_AT_allocated:
740   case DW_AT_associated:
741   case DW_AT_data_location:
742   case DW_AT_byte_stride:
743   case DW_AT_rank:
744   case DW_AT_call_value:
745   case DW_AT_call_origin:
746   case DW_AT_call_target:
747   case DW_AT_call_target_clobbered:
748   case DW_AT_call_data_location:
749   case DW_AT_call_data_value:
750   // Extensions.
751   case DW_AT_GNU_call_site_value:
752   case DW_AT_GNU_call_site_target:
753     return true;
754   default:
755     return false;
756   }
757 }
758 
759 namespace llvm {
760 
761 void dumpTypeQualifiedName(const DWARFDie &DIE, raw_ostream &OS) {
762   DWARFTypePrinter(OS).appendQualifiedName(DIE);
763 }
764 
765 void dumpTypeUnqualifiedName(const DWARFDie &DIE, raw_ostream &OS,
766                              std::string *OriginalFullName) {
767   DWARFTypePrinter(OS).appendUnqualifiedName(DIE, OriginalFullName);
768 }
769 
770 } // namespace llvm
771