1 //===- DWARFDie.cpp -------------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
11 #include "llvm/ADT/None.h"
12 #include "llvm/ADT/Optional.h"
13 #include "llvm/ADT/SmallSet.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/BinaryFormat/Dwarf.h"
16 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
17 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
19 #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
20 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
21 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
22 #include "llvm/Object/ObjectFile.h"
23 #include "llvm/Support/DataExtractor.h"
24 #include "llvm/Support/Format.h"
25 #include "llvm/Support/FormatVariadic.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/WithColor.h"
28 #include "llvm/Support/raw_ostream.h"
37 using namespace dwarf;
38 using namespace object;
40 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
43 uint64_t Shift = countTrailingZeros(Val);
44 assert(Shift < 64 && "undefined behavior");
45 uint64_t Bit = 1ULL << Shift;
46 auto PropName = ApplePropertyString(Bit);
47 if (!PropName.empty())
50 OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
58 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
59 const DWARFAddressRangesVector &Ranges,
60 unsigned AddressSize, unsigned Indent,
61 const DIDumpOptions &DumpOpts) {
62 if (!DumpOpts.ShowAddresses)
65 ArrayRef<SectionName> SectionNames;
67 SectionNames = Obj.getSectionNames();
69 for (const DWARFAddressRange &R : Ranges) {
72 R.dump(OS, AddressSize);
74 DWARFFormValue::dumpAddressSection(Obj, OS, DumpOpts, R.SectionIndex);
78 static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue,
79 DWARFUnit *U, unsigned Indent,
80 DIDumpOptions DumpOpts) {
81 DWARFContext &Ctx = U->getContext();
82 const DWARFObject &Obj = Ctx.getDWARFObj();
83 const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
84 if (FormValue.isFormClass(DWARFFormValue::FC_Block) ||
85 FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) {
86 ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
87 DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
88 Ctx.isLittleEndian(), 0);
89 DWARFExpression(Data, U->getVersion(), U->getAddressByteSize())
94 FormValue.dump(OS, DumpOpts);
95 if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) {
96 uint32_t Offset = *FormValue.getAsSectionOffset();
97 if (!U->isDWOUnit() && !U->getLocSection()->Data.empty()) {
98 DWARFDebugLoc DebugLoc;
99 DWARFDataExtractor Data(Obj, *U->getLocSection(), Ctx.isLittleEndian(),
100 Obj.getAddressSize());
101 auto LL = DebugLoc.parseOneLocationList(Data, &Offset);
103 uint64_t BaseAddr = 0;
104 if (Optional<SectionedAddress> BA = U->getBaseAddress())
105 BaseAddr = BA->Address;
106 LL->dump(OS, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI, BaseAddr,
109 OS << "error extracting location list.";
113 bool UseLocLists = !U->isDWOUnit();
114 StringRef LoclistsSectionData =
115 UseLocLists ? Obj.getLoclistsSection().Data : U->getLocSectionData();
117 if (!LoclistsSectionData.empty()) {
118 DataExtractor Data(LoclistsSectionData, Ctx.isLittleEndian(),
119 Obj.getAddressSize());
121 // Old-style location list were used in DWARF v4 (.debug_loc.dwo section).
122 // Modern locations list (.debug_loclists) are used starting from v5.
123 // Ideally we should take the version from the .debug_loclists section
124 // header, but using CU's version for simplicity.
125 auto LL = DWARFDebugLoclists::parseOneLocationList(
126 Data, &Offset, UseLocLists ? U->getVersion() : 4);
128 uint64_t BaseAddr = 0;
129 if (Optional<SectionedAddress> BA = U->getBaseAddress())
130 BaseAddr = BA->Address;
133 LL->dump(OS, BaseAddr, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI,
136 OS << "error extracting location list.";
141 /// Dump the name encoded in the type tag.
142 static void dumpTypeTagName(raw_ostream &OS, dwarf::Tag T) {
143 StringRef TagStr = TagString(T);
144 if (!TagStr.startswith("DW_TAG_") || !TagStr.endswith("_type"))
146 OS << TagStr.substr(7, TagStr.size() - 12) << " ";
149 static void dumpArrayType(raw_ostream &OS, const DWARFDie &D) {
150 Optional<uint64_t> Bound;
151 for (const DWARFDie &C : D.children())
152 if (C.getTag() == DW_TAG_subrange_type) {
153 Optional<uint64_t> LB;
154 Optional<uint64_t> Count;
155 Optional<uint64_t> UB;
156 Optional<unsigned> DefaultLB;
157 if (Optional<DWARFFormValue> L = C.find(DW_AT_lower_bound))
158 LB = L->getAsUnsignedConstant();
159 if (Optional<DWARFFormValue> CountV = C.find(DW_AT_count))
160 Count = CountV->getAsUnsignedConstant();
161 if (Optional<DWARFFormValue> UpperV = C.find(DW_AT_upper_bound))
162 UB = UpperV->getAsUnsignedConstant();
163 if (Optional<DWARFFormValue> LV =
164 D.getDwarfUnit()->getUnitDIE().find(DW_AT_language))
165 if (Optional<uint64_t> LC = LV->getAsUnsignedConstant())
167 LanguageLowerBound(static_cast<dwarf::SourceLanguage>(*LC))))
168 if (LB && *LB == *DefaultLB)
170 if (!LB && !Count && !UB)
172 else if (!LB && (Count || UB) && DefaultLB)
173 OS << '[' << (Count ? *Count : *UB - *DefaultLB + 1) << ']';
185 OS << "? + " << *Count;
195 /// Recursively dump the DIE type name when applicable.
196 static void dumpTypeName(raw_ostream &OS, const DWARFDie &D) {
200 if (const char *Name = D.getName(DINameKind::LinkageName)) {
205 // FIXME: We should have pretty printers per language. Currently we print
206 // everything as if it was C++ and fall back to the TAG type name.
207 const dwarf::Tag T = D.getTag();
209 case DW_TAG_array_type:
210 case DW_TAG_pointer_type:
211 case DW_TAG_ptr_to_member_type:
212 case DW_TAG_reference_type:
213 case DW_TAG_rvalue_reference_type:
214 case DW_TAG_subroutine_type:
217 dumpTypeTagName(OS, T);
220 // Follow the DW_AT_type if possible.
221 DWARFDie TypeDie = D.getAttributeValueAsReferencedDie(DW_AT_type);
222 dumpTypeName(OS, TypeDie);
225 case DW_TAG_subroutine_type: {
230 for (const DWARFDie &C : D.children()) {
231 if (C.getTag() == DW_TAG_formal_parameter) {
235 dumpTypeName(OS, C.getAttributeValueAsReferencedDie(DW_AT_type));
241 case DW_TAG_array_type: {
242 dumpArrayType(OS, D);
245 case DW_TAG_pointer_type:
248 case DW_TAG_ptr_to_member_type:
250 D.getAttributeValueAsReferencedDie(DW_AT_containing_type)) {
251 dumpTypeName(OS << ' ', Cont);
256 case DW_TAG_reference_type:
259 case DW_TAG_rvalue_reference_type:
267 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
268 uint32_t *OffsetPtr, dwarf::Attribute Attr,
269 dwarf::Form Form, unsigned Indent,
270 DIDumpOptions DumpOpts) {
273 const char BaseIndent[] = " ";
275 OS.indent(Indent + 2);
276 WithColor(OS, HighlightColor::Attribute) << formatv("{0}", Attr);
278 if (DumpOpts.Verbose || DumpOpts.ShowForm)
279 OS << formatv(" [{0}]", Form);
281 DWARFUnit *U = Die.getDwarfUnit();
282 DWARFFormValue formValue(Form);
284 if (!formValue.extractValue(U->getDebugInfoExtractor(), OffsetPtr,
285 U->getFormParams(), U))
292 auto Color = HighlightColor::Enumerator;
293 if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
294 Color = HighlightColor::String;
295 if (const auto *LT = U->getContext().getLineTableForUnit(U))
296 if (LT->getFileNameByIndex(
297 formValue.getAsUnsignedConstant().getValue(),
298 U->getCompilationDir(),
299 DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
300 File = '"' + File + '"';
303 } else if (Optional<uint64_t> Val = formValue.getAsUnsignedConstant())
304 Name = AttributeValueString(Attr, *Val);
307 WithColor(OS, Color) << Name;
308 else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
309 OS << *formValue.getAsUnsignedConstant();
310 else if (Attr == DW_AT_high_pc && !DumpOpts.ShowForm && !DumpOpts.Verbose &&
311 formValue.getAsUnsignedConstant()) {
312 if (DumpOpts.ShowAddresses) {
313 // Print the actual address rather than the offset.
314 uint64_t LowPC, HighPC, Index;
315 if (Die.getLowAndHighPC(LowPC, HighPC, Index))
316 OS << format("0x%016" PRIx64, HighPC);
318 formValue.dump(OS, DumpOpts);
320 } else if (Attr == DW_AT_location || Attr == DW_AT_frame_base ||
321 Attr == DW_AT_data_member_location ||
322 Attr == DW_AT_GNU_call_site_value)
323 dumpLocation(OS, formValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts);
325 formValue.dump(OS, DumpOpts);
327 std::string Space = DumpOpts.ShowAddresses ? " " : "";
329 // We have dumped the attribute raw value. For some attributes
330 // having both the raw value and the pretty-printed value is
331 // interesting. These attributes are handled below.
332 if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
333 if (const char *Name =
334 Die.getAttributeValueAsReferencedDie(formValue).getName(
335 DINameKind::LinkageName))
336 OS << Space << "\"" << Name << '\"';
337 } else if (Attr == DW_AT_type) {
339 dumpTypeName(OS, Die.getAttributeValueAsReferencedDie(formValue));
341 } else if (Attr == DW_AT_APPLE_property_attribute) {
342 if (Optional<uint64_t> OptVal = formValue.getAsUnsignedConstant())
343 dumpApplePropertyAttribute(OS, *OptVal);
344 } else if (Attr == DW_AT_ranges) {
345 const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
346 // For DW_FORM_rnglistx we need to dump the offset separately, since
347 // we have only dumped the index so far.
348 if (formValue.getForm() == DW_FORM_rnglistx)
349 if (auto RangeListOffset =
350 U->getRnglistOffset(*formValue.getAsSectionOffset())) {
351 DWARFFormValue FV(dwarf::DW_FORM_sec_offset);
352 FV.setUValue(*RangeListOffset);
353 FV.dump(OS, DumpOpts);
355 if (auto RangesOrError = Die.getAddressRanges())
356 dumpRanges(Obj, OS, RangesOrError.get(), U->getAddressByteSize(),
357 sizeof(BaseIndent) + Indent + 4, DumpOpts);
359 WithColor::error() << "decoding address ranges: "
360 << toString(RangesOrError.takeError()) << '\n';
366 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
368 bool DWARFDie::isSubroutineDIE() const {
370 return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
373 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
376 auto AbbrevDecl = getAbbreviationDeclarationPtr();
378 return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
382 Optional<DWARFFormValue>
383 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
386 auto AbbrevDecl = getAbbreviationDeclarationPtr();
388 for (auto Attr : Attrs) {
389 if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
396 Optional<DWARFFormValue>
397 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
398 std::vector<DWARFDie> Worklist;
399 Worklist.push_back(*this);
401 // Keep track if DIEs already seen to prevent infinite recursion.
402 // Empirically we rarely see a depth of more than 3 when dealing with valid
403 // DWARF. This corresponds to following the DW_AT_abstract_origin and
404 // DW_AT_specification just once.
405 SmallSet<DWARFDie, 3> Seen;
407 while (!Worklist.empty()) {
408 DWARFDie Die = Worklist.back();
419 if (auto Value = Die.find(Attrs))
422 if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
423 Worklist.push_back(D);
425 if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
426 Worklist.push_back(D);
433 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
434 if (Optional<DWARFFormValue> F = find(Attr))
435 return getAttributeValueAsReferencedDie(*F);
440 DWARFDie::getAttributeValueAsReferencedDie(const DWARFFormValue &V) const {
441 if (auto SpecRef = toReference(V)) {
442 if (auto SpecUnit = U->getUnitVector().getUnitForOffset(*SpecRef))
443 return SpecUnit->getDIEForOffset(*SpecRef);
448 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
449 return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
452 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
453 if (auto FormValue = find(DW_AT_high_pc)) {
454 if (auto Address = FormValue->getAsAddress()) {
455 // High PC is an address.
458 if (auto Offset = FormValue->getAsUnsignedConstant()) {
459 // High PC is an offset from LowPC.
460 return LowPC + *Offset;
466 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
467 uint64_t &SectionIndex) const {
468 auto F = find(DW_AT_low_pc);
469 auto LowPcAddr = toSectionedAddress(F);
472 if (auto HighPcAddr = getHighPC(LowPcAddr->Address)) {
473 LowPC = LowPcAddr->Address;
474 HighPC = *HighPcAddr;
475 SectionIndex = LowPcAddr->SectionIndex;
481 Expected<DWARFAddressRangesVector> DWARFDie::getAddressRanges() const {
483 return DWARFAddressRangesVector();
484 // Single range specified by low/high PC.
485 uint64_t LowPC, HighPC, Index;
486 if (getLowAndHighPC(LowPC, HighPC, Index))
487 return DWARFAddressRangesVector{{LowPC, HighPC, Index}};
489 Optional<DWARFFormValue> Value = find(DW_AT_ranges);
491 if (Value->getForm() == DW_FORM_rnglistx)
492 return U->findRnglistFromIndex(*Value->getAsSectionOffset());
493 return U->findRnglistFromOffset(*Value->getAsSectionOffset());
495 return DWARFAddressRangesVector();
498 void DWARFDie::collectChildrenAddressRanges(
499 DWARFAddressRangesVector &Ranges) const {
502 if (isSubprogramDIE()) {
503 if (auto DIERangesOrError = getAddressRanges())
504 Ranges.insert(Ranges.end(), DIERangesOrError.get().begin(),
505 DIERangesOrError.get().end());
507 llvm::consumeError(DIERangesOrError.takeError());
510 for (auto Child : children())
511 Child.collectChildrenAddressRanges(Ranges);
514 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
515 auto RangesOrError = getAddressRanges();
516 if (!RangesOrError) {
517 llvm::consumeError(RangesOrError.takeError());
521 for (const auto &R : RangesOrError.get())
522 if (R.LowPC <= Address && Address < R.HighPC)
527 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
528 if (!isSubroutineDIE())
530 return getName(Kind);
533 const char *DWARFDie::getName(DINameKind Kind) const {
534 if (!isValid() || Kind == DINameKind::None)
536 // Try to get mangled name only if it was asked for.
537 if (Kind == DINameKind::LinkageName) {
538 if (auto Name = dwarf::toString(
539 findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}),
543 if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr))
548 uint64_t DWARFDie::getDeclLine() const {
549 return toUnsigned(findRecursively(DW_AT_decl_line), 0);
552 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
553 uint32_t &CallColumn,
554 uint32_t &CallDiscriminator) const {
555 CallFile = toUnsigned(find(DW_AT_call_file), 0);
556 CallLine = toUnsigned(find(DW_AT_call_line), 0);
557 CallColumn = toUnsigned(find(DW_AT_call_column), 0);
558 CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
561 /// Helper to dump a DIE with all of its parents, but no siblings.
562 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
563 DIDumpOptions DumpOpts) {
566 Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts);
567 Die.dump(OS, Indent, DumpOpts);
571 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
572 DIDumpOptions DumpOpts) const {
575 DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
576 const uint32_t Offset = getOffset();
577 uint32_t offset = Offset;
578 if (DumpOpts.ShowParents) {
579 DIDumpOptions ParentDumpOpts = DumpOpts;
580 ParentDumpOpts.ShowParents = false;
581 ParentDumpOpts.ShowChildren = false;
582 Indent = dumpParentChain(getParent(), OS, Indent, ParentDumpOpts);
585 if (debug_info_data.isValidOffset(offset)) {
586 uint32_t abbrCode = debug_info_data.getULEB128(&offset);
587 if (DumpOpts.ShowAddresses)
588 WithColor(OS, HighlightColor::Address).get()
589 << format("\n0x%8.8x: ", Offset);
592 auto AbbrevDecl = getAbbreviationDeclarationPtr();
594 WithColor(OS, HighlightColor::Tag).get().indent(Indent)
595 << formatv("{0}", getTag());
596 if (DumpOpts.Verbose)
597 OS << format(" [%u] %c", abbrCode,
598 AbbrevDecl->hasChildren() ? '*' : ' ');
601 // Dump all data in the DIE for the attributes.
602 for (const auto &AttrSpec : AbbrevDecl->attributes()) {
603 if (AttrSpec.Form == DW_FORM_implicit_const) {
604 // We are dumping .debug_info section ,
605 // implicit_const attribute values are not really stored here,
606 // but in .debug_abbrev section. So we just skip such attrs.
609 dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form,
613 DWARFDie child = getFirstChild();
614 if (DumpOpts.ShowChildren && DumpOpts.RecurseDepth > 0 && child) {
615 DumpOpts.RecurseDepth--;
616 DIDumpOptions ChildDumpOpts = DumpOpts;
617 ChildDumpOpts.ShowParents = false;
619 child.dump(OS, Indent + 2, ChildDumpOpts);
620 child = child.getSibling();
624 OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
628 OS.indent(Indent) << "NULL\n";
633 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
635 DWARFDie DWARFDie::getParent() const {
637 return U->getParent(Die);
641 DWARFDie DWARFDie::getSibling() const {
643 return U->getSibling(Die);
647 DWARFDie DWARFDie::getPreviousSibling() const {
649 return U->getPreviousSibling(Die);
653 DWARFDie DWARFDie::getFirstChild() const {
655 return U->getFirstChild(Die);
659 DWARFDie DWARFDie::getLastChild() const {
661 return U->getLastChild(Die);
665 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
666 return make_range(attribute_iterator(*this, false),
667 attribute_iterator(*this, true));
670 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
671 : Die(D), AttrValue(0), Index(0) {
672 auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
673 assert(AbbrDecl && "Must have abbreviation declaration");
675 // This is the end iterator so we set the index to the attribute count.
676 Index = AbbrDecl->getNumAttributes();
678 // This is the begin iterator so we extract the value for this->Index.
679 AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
680 updateForIndex(*AbbrDecl, 0);
684 void DWARFDie::attribute_iterator::updateForIndex(
685 const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
687 // AbbrDecl must be valid before calling this function.
688 auto NumAttrs = AbbrDecl.getNumAttributes();
689 if (Index < NumAttrs) {
690 AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
691 // Add the previous byte size of any previous attribute value.
692 AttrValue.Offset += AttrValue.ByteSize;
693 AttrValue.Value.setForm(AbbrDecl.getFormByIndex(Index));
694 uint32_t ParseOffset = AttrValue.Offset;
695 auto U = Die.getDwarfUnit();
696 assert(U && "Die must have valid DWARF unit");
697 bool b = AttrValue.Value.extractValue(U->getDebugInfoExtractor(),
698 &ParseOffset, U->getFormParams(), U);
700 assert(b && "extractValue cannot fail on fully parsed DWARF");
701 AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
703 assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
708 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
709 if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
710 updateForIndex(*AbbrDecl, Index + 1);