1 //===- DWARFDie.cpp -------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
11 #include "SyntaxHighlighting.h"
12 #include "llvm/ADT/None.h"
13 #include "llvm/ADT/Optional.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/MathExtras.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include <algorithm>
28 #include <cassert>
29 #include <cinttypes>
30 #include <cstdint>
31 #include <string>
32 #include <utility>
33 
34 using namespace llvm;
35 using namespace dwarf;
36 using namespace object;
37 using namespace syntax;
38 
39 static void dumpApplePropertyAttribute(raw_ostream &OS, uint64_t Val) {
40   OS << " (";
41   do {
42     uint64_t Shift = countTrailingZeros(Val);
43     assert(Shift < 64 && "undefined behavior");
44     uint64_t Bit = 1ULL << Shift;
45     auto PropName = ApplePropertyString(Bit);
46     if (!PropName.empty())
47       OS << PropName;
48     else
49       OS << format("DW_APPLE_PROPERTY_0x%" PRIx64, Bit);
50     if (!(Val ^= Bit))
51       break;
52     OS << ", ";
53   } while (true);
54   OS << ")";
55 }
56 
57 static void dumpRanges(const DWARFObject &Obj, raw_ostream &OS,
58                        const DWARFAddressRangesVector &Ranges,
59                        unsigned AddressSize, unsigned Indent,
60                        const DIDumpOptions &DumpOpts) {
61   ArrayRef<SectionName> SectionNames;
62   if (DumpOpts.Verbose)
63     SectionNames = Obj.getSectionNames();
64 
65   for (size_t I = 0; I < Ranges.size(); ++I) {
66     const DWARFAddressRange &R = Ranges[I];
67 
68     OS << '\n';
69     OS.indent(Indent);
70     OS << format("[0x%0*" PRIx64 " - 0x%0*" PRIx64 ")", AddressSize * 2,
71                  R.LowPC, AddressSize * 2, R.HighPC);
72 
73     if (SectionNames.empty() || R.SectionIndex == -1ULL)
74       continue;
75 
76     StringRef Name = SectionNames[R.SectionIndex].Name;
77     OS << " \"" << Name << '\"';
78 
79     // Print section index if name is not unique.
80     if (!SectionNames[R.SectionIndex].IsNameUnique)
81       OS << format(" [%" PRIu64 "]", R.SectionIndex);
82   }
83 }
84 
85 static void dumpLocation(raw_ostream &OS, DWARFFormValue &FormValue,
86                          DWARFUnit *U, unsigned Indent,
87                          DIDumpOptions DumpOpts) {
88   DWARFContext &Ctx = U->getContext();
89   const DWARFObject &Obj = Ctx.getDWARFObj();
90   const MCRegisterInfo *MRI = Ctx.getRegisterInfo();
91   if (FormValue.isFormClass(DWARFFormValue::FC_Block) ||
92       FormValue.isFormClass(DWARFFormValue::FC_Exprloc)) {
93     ArrayRef<uint8_t> Expr = *FormValue.getAsBlock();
94     DataExtractor Data(StringRef((const char *)Expr.data(), Expr.size()),
95                        Ctx.isLittleEndian(), 0);
96     DWARFExpression(Data, U->getVersion(), U->getAddressByteSize())
97         .print(OS, MRI);
98     return;
99   }
100 
101   FormValue.dump(OS, DumpOpts);
102   if (FormValue.isFormClass(DWARFFormValue::FC_SectionOffset)) {
103     const DWARFSection &LocSection = Obj.getLocSection();
104     const DWARFSection &LocDWOSection = Obj.getLocDWOSection();
105     uint32_t Offset = *FormValue.getAsSectionOffset();
106 
107     if (!LocSection.Data.empty()) {
108       DWARFDebugLoc DebugLoc;
109       DWARFDataExtractor Data(Obj, LocSection, Ctx.isLittleEndian(),
110                               Obj.getAddressSize());
111       auto LL = DebugLoc.parseOneLocationList(Data, &Offset);
112       if (LL)
113         LL->dump(OS, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI, Indent);
114       else
115         OS << "error extracting location list.";
116     } else if (!LocDWOSection.Data.empty()) {
117       DataExtractor Data(LocDWOSection.Data, Ctx.isLittleEndian(), 0);
118       auto LL = DWARFDebugLocDWO::parseOneLocationList(Data, &Offset);
119       if (LL)
120         LL->dump(OS, Ctx.isLittleEndian(), Obj.getAddressSize(), MRI, Indent);
121       else
122         OS << "error extracting location list.";
123     }
124   }
125 }
126 
127 static void dumpAttribute(raw_ostream &OS, const DWARFDie &Die,
128                           uint32_t *OffsetPtr, dwarf::Attribute Attr,
129                           dwarf::Form Form, unsigned Indent,
130                           DIDumpOptions DumpOpts) {
131   if (!Die.isValid())
132     return;
133   const char BaseIndent[] = "            ";
134   OS << BaseIndent;
135   OS.indent(Indent + 2);
136   auto attrString = AttributeString(Attr);
137   if (!attrString.empty())
138     WithColor(OS, syntax::Attribute) << attrString;
139   else
140     WithColor(OS, syntax::Attribute).get() << format("DW_AT_Unknown_%x", Attr);
141 
142   if (DumpOpts.Verbose || DumpOpts.ShowForm) {
143     auto formString = FormEncodingString(Form);
144     if (!formString.empty())
145       OS << " [" << formString << ']';
146     else
147       OS << format(" [DW_FORM_Unknown_%x]", Form);
148   }
149 
150   DWARFUnit *U = Die.getDwarfUnit();
151   DWARFFormValue formValue(Form);
152 
153   if (!formValue.extractValue(U->getDebugInfoExtractor(), OffsetPtr, U))
154     return;
155 
156   OS << "\t(";
157 
158   StringRef Name;
159   std::string File;
160   auto Color = syntax::Enumerator;
161   if (Attr == DW_AT_decl_file || Attr == DW_AT_call_file) {
162     Color = syntax::String;
163     if (const auto *LT = U->getContext().getLineTableForUnit(U))
164       if (LT->getFileNameByIndex(
165               formValue.getAsUnsignedConstant().getValue(),
166               U->getCompilationDir(),
167               DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath, File)) {
168         File = '"' + File + '"';
169         Name = File;
170       }
171   } else if (Optional<uint64_t> Val = formValue.getAsUnsignedConstant())
172     Name = AttributeValueString(Attr, *Val);
173 
174   if (!Name.empty())
175     WithColor(OS, Color) << Name;
176   else if (Attr == DW_AT_decl_line || Attr == DW_AT_call_line)
177     OS << *formValue.getAsUnsignedConstant();
178   else if (Attr == DW_AT_location || Attr == DW_AT_frame_base ||
179            Attr == DW_AT_data_member_location)
180     dumpLocation(OS, formValue, U, sizeof(BaseIndent) + Indent + 4, DumpOpts);
181   else
182     formValue.dump(OS, DumpOpts);
183 
184   // We have dumped the attribute raw value. For some attributes
185   // having both the raw value and the pretty-printed value is
186   // interesting. These attributes are handled below.
187   if (Attr == DW_AT_specification || Attr == DW_AT_abstract_origin) {
188     if (const char *Name = Die.getAttributeValueAsReferencedDie(Attr).getName(
189             DINameKind::LinkageName))
190       OS << " \"" << Name << '\"';
191   } else if (Attr == DW_AT_APPLE_property_attribute) {
192     if (Optional<uint64_t> OptVal = formValue.getAsUnsignedConstant())
193       dumpApplePropertyAttribute(OS, *OptVal);
194   } else if (Attr == DW_AT_ranges) {
195     const DWARFObject &Obj = Die.getDwarfUnit()->getContext().getDWARFObj();
196     dumpRanges(Obj, OS, Die.getAddressRanges(), U->getAddressByteSize(),
197                sizeof(BaseIndent) + Indent + 4, DumpOpts);
198   }
199 
200   OS << ")\n";
201 }
202 
203 bool DWARFDie::isSubprogramDIE() const { return getTag() == DW_TAG_subprogram; }
204 
205 bool DWARFDie::isSubroutineDIE() const {
206   auto Tag = getTag();
207   return Tag == DW_TAG_subprogram || Tag == DW_TAG_inlined_subroutine;
208 }
209 
210 Optional<DWARFFormValue> DWARFDie::find(dwarf::Attribute Attr) const {
211   if (!isValid())
212     return None;
213   auto AbbrevDecl = getAbbreviationDeclarationPtr();
214   if (AbbrevDecl)
215     return AbbrevDecl->getAttributeValue(getOffset(), Attr, *U);
216   return None;
217 }
218 
219 Optional<DWARFFormValue>
220 DWARFDie::find(ArrayRef<dwarf::Attribute> Attrs) const {
221   if (!isValid())
222     return None;
223   auto AbbrevDecl = getAbbreviationDeclarationPtr();
224   if (AbbrevDecl) {
225     for (auto Attr : Attrs) {
226       if (auto Value = AbbrevDecl->getAttributeValue(getOffset(), Attr, *U))
227         return Value;
228     }
229   }
230   return None;
231 }
232 
233 Optional<DWARFFormValue>
234 DWARFDie::findRecursively(ArrayRef<dwarf::Attribute> Attrs) const {
235   if (!isValid())
236     return None;
237   auto Die = *this;
238   if (auto Value = Die.find(Attrs))
239     return Value;
240   if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
241     Die = D;
242   if (auto Value = Die.find(Attrs))
243     return Value;
244   if (auto D = Die.getAttributeValueAsReferencedDie(DW_AT_specification))
245     Die = D;
246   if (auto Value = Die.find(Attrs))
247     return Value;
248   return None;
249 }
250 
251 DWARFDie
252 DWARFDie::getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const {
253   auto SpecRef = toReference(find(Attr));
254   if (SpecRef) {
255     auto SpecUnit = U->getUnitSection().getUnitForOffset(*SpecRef);
256     if (SpecUnit)
257       return SpecUnit->getDIEForOffset(*SpecRef);
258   }
259   return DWARFDie();
260 }
261 
262 Optional<uint64_t> DWARFDie::getRangesBaseAttribute() const {
263   return toSectionOffset(find({DW_AT_rnglists_base, DW_AT_GNU_ranges_base}));
264 }
265 
266 Optional<uint64_t> DWARFDie::getHighPC(uint64_t LowPC) const {
267   if (auto FormValue = find(DW_AT_high_pc)) {
268     if (auto Address = FormValue->getAsAddress()) {
269       // High PC is an address.
270       return Address;
271     }
272     if (auto Offset = FormValue->getAsUnsignedConstant()) {
273       // High PC is an offset from LowPC.
274       return LowPC + *Offset;
275     }
276   }
277   return None;
278 }
279 
280 bool DWARFDie::getLowAndHighPC(uint64_t &LowPC, uint64_t &HighPC,
281                                uint64_t &SectionIndex) const {
282   auto F = find(DW_AT_low_pc);
283   auto LowPcAddr = toAddress(F);
284   if (!LowPcAddr)
285     return false;
286   if (auto HighPcAddr = getHighPC(*LowPcAddr)) {
287     LowPC = *LowPcAddr;
288     HighPC = *HighPcAddr;
289     SectionIndex = F->getSectionIndex();
290     return true;
291   }
292   return false;
293 }
294 
295 DWARFAddressRangesVector DWARFDie::getAddressRanges() const {
296   if (isNULL())
297     return DWARFAddressRangesVector();
298   // Single range specified by low/high PC.
299   uint64_t LowPC, HighPC, Index;
300   if (getLowAndHighPC(LowPC, HighPC, Index))
301     return {{LowPC, HighPC, Index}};
302 
303   // Multiple ranges from .debug_ranges section.
304   auto RangesOffset = toSectionOffset(find(DW_AT_ranges));
305   if (RangesOffset) {
306     DWARFDebugRangeList RangeList;
307     if (U->extractRangeList(*RangesOffset, RangeList))
308       return RangeList.getAbsoluteRanges(U->getBaseAddress());
309   }
310   return DWARFAddressRangesVector();
311 }
312 
313 void DWARFDie::collectChildrenAddressRanges(
314     DWARFAddressRangesVector &Ranges) const {
315   if (isNULL())
316     return;
317   if (isSubprogramDIE()) {
318     const auto &DIERanges = getAddressRanges();
319     Ranges.insert(Ranges.end(), DIERanges.begin(), DIERanges.end());
320   }
321 
322   for (auto Child : children())
323     Child.collectChildrenAddressRanges(Ranges);
324 }
325 
326 bool DWARFDie::addressRangeContainsAddress(const uint64_t Address) const {
327   for (const auto &R : getAddressRanges()) {
328     if (R.LowPC <= Address && Address < R.HighPC)
329       return true;
330   }
331   return false;
332 }
333 
334 const char *DWARFDie::getSubroutineName(DINameKind Kind) const {
335   if (!isSubroutineDIE())
336     return nullptr;
337   return getName(Kind);
338 }
339 
340 const char *DWARFDie::getName(DINameKind Kind) const {
341   if (!isValid() || Kind == DINameKind::None)
342     return nullptr;
343   // Try to get mangled name only if it was asked for.
344   if (Kind == DINameKind::LinkageName) {
345     if (auto Name = dwarf::toString(
346             findRecursively({DW_AT_MIPS_linkage_name, DW_AT_linkage_name}),
347             nullptr))
348       return Name;
349   }
350   if (auto Name = dwarf::toString(findRecursively(DW_AT_name), nullptr))
351     return Name;
352   return nullptr;
353 }
354 
355 uint64_t DWARFDie::getDeclLine() const {
356   return toUnsigned(findRecursively(DW_AT_decl_line), 0);
357 }
358 
359 void DWARFDie::getCallerFrame(uint32_t &CallFile, uint32_t &CallLine,
360                               uint32_t &CallColumn,
361                               uint32_t &CallDiscriminator) const {
362   CallFile = toUnsigned(find(DW_AT_call_file), 0);
363   CallLine = toUnsigned(find(DW_AT_call_line), 0);
364   CallColumn = toUnsigned(find(DW_AT_call_column), 0);
365   CallDiscriminator = toUnsigned(find(DW_AT_GNU_discriminator), 0);
366 }
367 
368 /// Helper to dump a DIE with all of its parents, but no siblings.
369 static unsigned dumpParentChain(DWARFDie Die, raw_ostream &OS, unsigned Indent,
370                                 DIDumpOptions DumpOpts) {
371   if (!Die)
372     return Indent;
373   Indent = dumpParentChain(Die.getParent(), OS, Indent, DumpOpts);
374   Die.dump(OS, Indent, DumpOpts);
375   return Indent + 2;
376 }
377 
378 void DWARFDie::dump(raw_ostream &OS, unsigned Indent,
379                     DIDumpOptions DumpOpts) const {
380   if (!isValid())
381     return;
382   DWARFDataExtractor debug_info_data = U->getDebugInfoExtractor();
383   const uint32_t Offset = getOffset();
384   uint32_t offset = Offset;
385   if (DumpOpts.ShowParents) {
386     DumpOpts.ShowParents = false;
387     Indent = dumpParentChain(getParent(), OS, Indent, DumpOpts);
388   }
389 
390   if (debug_info_data.isValidOffset(offset)) {
391     uint32_t abbrCode = debug_info_data.getULEB128(&offset);
392     WithColor(OS, syntax::Address).get() << format("\n0x%8.8x: ", Offset);
393 
394     if (abbrCode) {
395       auto AbbrevDecl = getAbbreviationDeclarationPtr();
396       if (AbbrevDecl) {
397         auto tagString = TagString(getTag());
398         if (!tagString.empty())
399           WithColor(OS, syntax::Tag).get().indent(Indent) << tagString;
400         else
401           WithColor(OS, syntax::Tag).get().indent(Indent)
402               << format("DW_TAG_Unknown_%x", getTag());
403 
404         if (DumpOpts.Verbose)
405           OS << format(" [%u] %c", abbrCode,
406                        AbbrevDecl->hasChildren() ? '*' : ' ');
407         OS << '\n';
408 
409         // Dump all data in the DIE for the attributes.
410         for (const auto &AttrSpec : AbbrevDecl->attributes()) {
411           if (AttrSpec.Form == DW_FORM_implicit_const) {
412             // We are dumping .debug_info section ,
413             // implicit_const attribute values are not really stored here,
414             // but in .debug_abbrev section. So we just skip such attrs.
415             continue;
416           }
417           dumpAttribute(OS, *this, &offset, AttrSpec.Attr, AttrSpec.Form,
418                         Indent, DumpOpts);
419         }
420 
421         DWARFDie child = getFirstChild();
422         if (DumpOpts.RecurseDepth > 0 && child) {
423           DumpOpts.RecurseDepth--;
424           while (child) {
425             child.dump(OS, Indent + 2, DumpOpts);
426             child = child.getSibling();
427           }
428         }
429       } else {
430         OS << "Abbreviation code not found in 'debug_abbrev' class for code: "
431            << abbrCode << '\n';
432       }
433     } else {
434       OS.indent(Indent) << "NULL\n";
435     }
436   }
437 }
438 
439 LLVM_DUMP_METHOD void DWARFDie::dump() const { dump(llvm::errs(), 0); }
440 
441 DWARFDie DWARFDie::getParent() const {
442   if (isValid())
443     return U->getParent(Die);
444   return DWARFDie();
445 }
446 
447 DWARFDie DWARFDie::getSibling() const {
448   if (isValid())
449     return U->getSibling(Die);
450   return DWARFDie();
451 }
452 
453 iterator_range<DWARFDie::attribute_iterator> DWARFDie::attributes() const {
454   return make_range(attribute_iterator(*this, false),
455                     attribute_iterator(*this, true));
456 }
457 
458 DWARFDie::attribute_iterator::attribute_iterator(DWARFDie D, bool End)
459     : Die(D), AttrValue(0), Index(0) {
460   auto AbbrDecl = Die.getAbbreviationDeclarationPtr();
461   assert(AbbrDecl && "Must have abbreviation declaration");
462   if (End) {
463     // This is the end iterator so we set the index to the attribute count.
464     Index = AbbrDecl->getNumAttributes();
465   } else {
466     // This is the begin iterator so we extract the value for this->Index.
467     AttrValue.Offset = D.getOffset() + AbbrDecl->getCodeByteSize();
468     updateForIndex(*AbbrDecl, 0);
469   }
470 }
471 
472 void DWARFDie::attribute_iterator::updateForIndex(
473     const DWARFAbbreviationDeclaration &AbbrDecl, uint32_t I) {
474   Index = I;
475   // AbbrDecl must be valid before calling this function.
476   auto NumAttrs = AbbrDecl.getNumAttributes();
477   if (Index < NumAttrs) {
478     AttrValue.Attr = AbbrDecl.getAttrByIndex(Index);
479     // Add the previous byte size of any previous attribute value.
480     AttrValue.Offset += AttrValue.ByteSize;
481     AttrValue.Value.setForm(AbbrDecl.getFormByIndex(Index));
482     uint32_t ParseOffset = AttrValue.Offset;
483     auto U = Die.getDwarfUnit();
484     assert(U && "Die must have valid DWARF unit");
485     bool b = AttrValue.Value.extractValue(U->getDebugInfoExtractor(),
486                                           &ParseOffset, U);
487     (void)b;
488     assert(b && "extractValue cannot fail on fully parsed DWARF");
489     AttrValue.ByteSize = ParseOffset - AttrValue.Offset;
490   } else {
491     assert(Index == NumAttrs && "Indexes should be [0, NumAttrs) only");
492     AttrValue.clear();
493   }
494 }
495 
496 DWARFDie::attribute_iterator &DWARFDie::attribute_iterator::operator++() {
497   if (auto AbbrDecl = Die.getAbbreviationDeclarationPtr())
498     updateForIndex(*AbbrDecl, Index + 1);
499   return *this;
500 }
501