DWARFDie.cpp 25 KB

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