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