DWARFAcceleratorTable.cpp 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905
  1. //===- DWARFAcceleratorTable.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/DWARFAcceleratorTable.h"
  9. #include "llvm/ADT/SmallVector.h"
  10. #include "llvm/BinaryFormat/Dwarf.h"
  11. #include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
  12. #include "llvm/Support/Compiler.h"
  13. #include "llvm/Support/DJB.h"
  14. #include "llvm/Support/Errc.h"
  15. #include "llvm/Support/Format.h"
  16. #include "llvm/Support/FormatVariadic.h"
  17. #include "llvm/Support/ScopedPrinter.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. #include <cstddef>
  20. #include <cstdint>
  21. #include <utility>
  22. using namespace llvm;
  23. namespace {
  24. struct Atom {
  25. unsigned Value;
  26. };
  27. static raw_ostream &operator<<(raw_ostream &OS, const Atom &A) {
  28. StringRef Str = dwarf::AtomTypeString(A.Value);
  29. if (!Str.empty())
  30. return OS << Str;
  31. return OS << "DW_ATOM_unknown_" << format("%x", A.Value);
  32. }
  33. } // namespace
  34. static Atom formatAtom(unsigned Atom) { return {Atom}; }
  35. DWARFAcceleratorTable::~DWARFAcceleratorTable() = default;
  36. Error AppleAcceleratorTable::extract() {
  37. uint64_t Offset = 0;
  38. // Check that we can at least read the header.
  39. if (!AccelSection.isValidOffset(offsetof(Header, HeaderDataLength) + 4))
  40. return createStringError(errc::illegal_byte_sequence,
  41. "Section too small: cannot read header.");
  42. Hdr.Magic = AccelSection.getU32(&Offset);
  43. Hdr.Version = AccelSection.getU16(&Offset);
  44. Hdr.HashFunction = AccelSection.getU16(&Offset);
  45. Hdr.BucketCount = AccelSection.getU32(&Offset);
  46. Hdr.HashCount = AccelSection.getU32(&Offset);
  47. Hdr.HeaderDataLength = AccelSection.getU32(&Offset);
  48. // Check that we can read all the hashes and offsets from the
  49. // section (see SourceLevelDebugging.rst for the structure of the index).
  50. // We need to substract one because we're checking for an *offset* which is
  51. // equal to the size for an empty table and hence pointer after the section.
  52. if (!AccelSection.isValidOffset(sizeof(Hdr) + Hdr.HeaderDataLength +
  53. Hdr.BucketCount * 4 + Hdr.HashCount * 8 - 1))
  54. return createStringError(
  55. errc::illegal_byte_sequence,
  56. "Section too small: cannot read buckets and hashes.");
  57. HdrData.DIEOffsetBase = AccelSection.getU32(&Offset);
  58. uint32_t NumAtoms = AccelSection.getU32(&Offset);
  59. for (unsigned i = 0; i < NumAtoms; ++i) {
  60. uint16_t AtomType = AccelSection.getU16(&Offset);
  61. auto AtomForm = static_cast<dwarf::Form>(AccelSection.getU16(&Offset));
  62. HdrData.Atoms.push_back(std::make_pair(AtomType, AtomForm));
  63. }
  64. IsValid = true;
  65. return Error::success();
  66. }
  67. uint32_t AppleAcceleratorTable::getNumBuckets() { return Hdr.BucketCount; }
  68. uint32_t AppleAcceleratorTable::getNumHashes() { return Hdr.HashCount; }
  69. uint32_t AppleAcceleratorTable::getSizeHdr() { return sizeof(Hdr); }
  70. uint32_t AppleAcceleratorTable::getHeaderDataLength() {
  71. return Hdr.HeaderDataLength;
  72. }
  73. ArrayRef<std::pair<AppleAcceleratorTable::HeaderData::AtomType,
  74. AppleAcceleratorTable::HeaderData::Form>>
  75. AppleAcceleratorTable::getAtomsDesc() {
  76. return HdrData.Atoms;
  77. }
  78. bool AppleAcceleratorTable::validateForms() {
  79. for (auto Atom : getAtomsDesc()) {
  80. DWARFFormValue FormValue(Atom.second);
  81. switch (Atom.first) {
  82. case dwarf::DW_ATOM_die_offset:
  83. case dwarf::DW_ATOM_die_tag:
  84. case dwarf::DW_ATOM_type_flags:
  85. if ((!FormValue.isFormClass(DWARFFormValue::FC_Constant) &&
  86. !FormValue.isFormClass(DWARFFormValue::FC_Flag)) ||
  87. FormValue.getForm() == dwarf::DW_FORM_sdata)
  88. return false;
  89. break;
  90. default:
  91. break;
  92. }
  93. }
  94. return true;
  95. }
  96. std::pair<uint64_t, dwarf::Tag>
  97. AppleAcceleratorTable::readAtoms(uint64_t *HashDataOffset) {
  98. uint64_t DieOffset = dwarf::DW_INVALID_OFFSET;
  99. dwarf::Tag DieTag = dwarf::DW_TAG_null;
  100. dwarf::FormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
  101. for (auto Atom : getAtomsDesc()) {
  102. DWARFFormValue FormValue(Atom.second);
  103. FormValue.extractValue(AccelSection, HashDataOffset, FormParams);
  104. switch (Atom.first) {
  105. case dwarf::DW_ATOM_die_offset:
  106. DieOffset = *FormValue.getAsUnsignedConstant();
  107. break;
  108. case dwarf::DW_ATOM_die_tag:
  109. DieTag = (dwarf::Tag)*FormValue.getAsUnsignedConstant();
  110. break;
  111. default:
  112. break;
  113. }
  114. }
  115. return {DieOffset, DieTag};
  116. }
  117. void AppleAcceleratorTable::Header::dump(ScopedPrinter &W) const {
  118. DictScope HeaderScope(W, "Header");
  119. W.printHex("Magic", Magic);
  120. W.printHex("Version", Version);
  121. W.printHex("Hash function", HashFunction);
  122. W.printNumber("Bucket count", BucketCount);
  123. W.printNumber("Hashes count", HashCount);
  124. W.printNumber("HeaderData length", HeaderDataLength);
  125. }
  126. Optional<uint64_t> AppleAcceleratorTable::HeaderData::extractOffset(
  127. Optional<DWARFFormValue> Value) const {
  128. if (!Value)
  129. return None;
  130. switch (Value->getForm()) {
  131. case dwarf::DW_FORM_ref1:
  132. case dwarf::DW_FORM_ref2:
  133. case dwarf::DW_FORM_ref4:
  134. case dwarf::DW_FORM_ref8:
  135. case dwarf::DW_FORM_ref_udata:
  136. return Value->getRawUValue() + DIEOffsetBase;
  137. default:
  138. return Value->getAsSectionOffset();
  139. }
  140. }
  141. bool AppleAcceleratorTable::dumpName(ScopedPrinter &W,
  142. SmallVectorImpl<DWARFFormValue> &AtomForms,
  143. uint64_t *DataOffset) const {
  144. dwarf::FormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
  145. uint64_t NameOffset = *DataOffset;
  146. if (!AccelSection.isValidOffsetForDataOfSize(*DataOffset, 4)) {
  147. W.printString("Incorrectly terminated list.");
  148. return false;
  149. }
  150. uint64_t StringOffset = AccelSection.getRelocatedValue(4, DataOffset);
  151. if (!StringOffset)
  152. return false; // End of list
  153. DictScope NameScope(W, ("Name@0x" + Twine::utohexstr(NameOffset)).str());
  154. W.startLine() << format("String: 0x%08" PRIx64, StringOffset);
  155. W.getOStream() << " \"" << StringSection.getCStr(&StringOffset) << "\"\n";
  156. unsigned NumData = AccelSection.getU32(DataOffset);
  157. for (unsigned Data = 0; Data < NumData; ++Data) {
  158. ListScope DataScope(W, ("Data " + Twine(Data)).str());
  159. unsigned i = 0;
  160. for (auto &Atom : AtomForms) {
  161. W.startLine() << format("Atom[%d]: ", i);
  162. if (Atom.extractValue(AccelSection, DataOffset, FormParams)) {
  163. Atom.dump(W.getOStream());
  164. if (Optional<uint64_t> Val = Atom.getAsUnsignedConstant()) {
  165. StringRef Str = dwarf::AtomValueString(HdrData.Atoms[i].first, *Val);
  166. if (!Str.empty())
  167. W.getOStream() << " (" << Str << ")";
  168. }
  169. } else
  170. W.getOStream() << "Error extracting the value";
  171. W.getOStream() << "\n";
  172. i++;
  173. }
  174. }
  175. return true; // more entries follow
  176. }
  177. LLVM_DUMP_METHOD void AppleAcceleratorTable::dump(raw_ostream &OS) const {
  178. if (!IsValid)
  179. return;
  180. ScopedPrinter W(OS);
  181. Hdr.dump(W);
  182. W.printNumber("DIE offset base", HdrData.DIEOffsetBase);
  183. W.printNumber("Number of atoms", uint64_t(HdrData.Atoms.size()));
  184. SmallVector<DWARFFormValue, 3> AtomForms;
  185. {
  186. ListScope AtomsScope(W, "Atoms");
  187. unsigned i = 0;
  188. for (const auto &Atom : HdrData.Atoms) {
  189. DictScope AtomScope(W, ("Atom " + Twine(i++)).str());
  190. W.startLine() << "Type: " << formatAtom(Atom.first) << '\n';
  191. W.startLine() << "Form: " << formatv("{0}", Atom.second) << '\n';
  192. AtomForms.push_back(DWARFFormValue(Atom.second));
  193. }
  194. }
  195. // Now go through the actual tables and dump them.
  196. uint64_t Offset = sizeof(Hdr) + Hdr.HeaderDataLength;
  197. uint64_t HashesBase = Offset + Hdr.BucketCount * 4;
  198. uint64_t OffsetsBase = HashesBase + Hdr.HashCount * 4;
  199. for (unsigned Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket) {
  200. unsigned Index = AccelSection.getU32(&Offset);
  201. ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
  202. if (Index == UINT32_MAX) {
  203. W.printString("EMPTY");
  204. continue;
  205. }
  206. for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
  207. uint64_t HashOffset = HashesBase + HashIdx*4;
  208. uint64_t OffsetsOffset = OffsetsBase + HashIdx*4;
  209. uint32_t Hash = AccelSection.getU32(&HashOffset);
  210. if (Hash % Hdr.BucketCount != Bucket)
  211. break;
  212. uint64_t DataOffset = AccelSection.getU32(&OffsetsOffset);
  213. ListScope HashScope(W, ("Hash 0x" + Twine::utohexstr(Hash)).str());
  214. if (!AccelSection.isValidOffset(DataOffset)) {
  215. W.printString("Invalid section offset");
  216. continue;
  217. }
  218. while (dumpName(W, AtomForms, &DataOffset))
  219. /*empty*/;
  220. }
  221. }
  222. }
  223. AppleAcceleratorTable::Entry::Entry(
  224. const AppleAcceleratorTable::HeaderData &HdrData)
  225. : HdrData(&HdrData) {
  226. Values.reserve(HdrData.Atoms.size());
  227. for (const auto &Atom : HdrData.Atoms)
  228. Values.push_back(DWARFFormValue(Atom.second));
  229. }
  230. void AppleAcceleratorTable::Entry::extract(
  231. const AppleAcceleratorTable &AccelTable, uint64_t *Offset) {
  232. dwarf::FormParams FormParams = {AccelTable.Hdr.Version, 0,
  233. dwarf::DwarfFormat::DWARF32};
  234. for (auto &Atom : Values)
  235. Atom.extractValue(AccelTable.AccelSection, Offset, FormParams);
  236. }
  237. Optional<DWARFFormValue>
  238. AppleAcceleratorTable::Entry::lookup(HeaderData::AtomType Atom) const {
  239. assert(HdrData && "Dereferencing end iterator?");
  240. assert(HdrData->Atoms.size() == Values.size());
  241. for (auto Tuple : zip_first(HdrData->Atoms, Values)) {
  242. if (std::get<0>(Tuple).first == Atom)
  243. return std::get<1>(Tuple);
  244. }
  245. return None;
  246. }
  247. Optional<uint64_t> AppleAcceleratorTable::Entry::getDIESectionOffset() const {
  248. return HdrData->extractOffset(lookup(dwarf::DW_ATOM_die_offset));
  249. }
  250. Optional<uint64_t> AppleAcceleratorTable::Entry::getCUOffset() const {
  251. return HdrData->extractOffset(lookup(dwarf::DW_ATOM_cu_offset));
  252. }
  253. Optional<dwarf::Tag> AppleAcceleratorTable::Entry::getTag() const {
  254. Optional<DWARFFormValue> Tag = lookup(dwarf::DW_ATOM_die_tag);
  255. if (!Tag)
  256. return None;
  257. if (Optional<uint64_t> Value = Tag->getAsUnsignedConstant())
  258. return dwarf::Tag(*Value);
  259. return None;
  260. }
  261. AppleAcceleratorTable::ValueIterator::ValueIterator(
  262. const AppleAcceleratorTable &AccelTable, uint64_t Offset)
  263. : AccelTable(&AccelTable), Current(AccelTable.HdrData), DataOffset(Offset) {
  264. if (!AccelTable.AccelSection.isValidOffsetForDataOfSize(DataOffset, 4))
  265. return;
  266. // Read the first entry.
  267. NumData = AccelTable.AccelSection.getU32(&DataOffset);
  268. Next();
  269. }
  270. void AppleAcceleratorTable::ValueIterator::Next() {
  271. assert(NumData > 0 && "attempted to increment iterator past the end");
  272. auto &AccelSection = AccelTable->AccelSection;
  273. if (Data >= NumData ||
  274. !AccelSection.isValidOffsetForDataOfSize(DataOffset, 4)) {
  275. NumData = 0;
  276. DataOffset = 0;
  277. return;
  278. }
  279. Current.extract(*AccelTable, &DataOffset);
  280. ++Data;
  281. }
  282. iterator_range<AppleAcceleratorTable::ValueIterator>
  283. AppleAcceleratorTable::equal_range(StringRef Key) const {
  284. if (!IsValid)
  285. return make_range(ValueIterator(), ValueIterator());
  286. // Find the bucket.
  287. unsigned HashValue = djbHash(Key);
  288. unsigned Bucket = HashValue % Hdr.BucketCount;
  289. uint64_t BucketBase = sizeof(Hdr) + Hdr.HeaderDataLength;
  290. uint64_t HashesBase = BucketBase + Hdr.BucketCount * 4;
  291. uint64_t OffsetsBase = HashesBase + Hdr.HashCount * 4;
  292. uint64_t BucketOffset = BucketBase + Bucket * 4;
  293. unsigned Index = AccelSection.getU32(&BucketOffset);
  294. // Search through all hashes in the bucket.
  295. for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
  296. uint64_t HashOffset = HashesBase + HashIdx * 4;
  297. uint64_t OffsetsOffset = OffsetsBase + HashIdx * 4;
  298. uint32_t Hash = AccelSection.getU32(&HashOffset);
  299. if (Hash % Hdr.BucketCount != Bucket)
  300. // We are already in the next bucket.
  301. break;
  302. uint64_t DataOffset = AccelSection.getU32(&OffsetsOffset);
  303. uint64_t StringOffset = AccelSection.getRelocatedValue(4, &DataOffset);
  304. if (!StringOffset)
  305. break;
  306. // Finally, compare the key.
  307. if (Key == StringSection.getCStr(&StringOffset))
  308. return make_range({*this, DataOffset}, ValueIterator());
  309. }
  310. return make_range(ValueIterator(), ValueIterator());
  311. }
  312. void DWARFDebugNames::Header::dump(ScopedPrinter &W) const {
  313. DictScope HeaderScope(W, "Header");
  314. W.printHex("Length", UnitLength);
  315. W.printString("Format", dwarf::FormatString(Format));
  316. W.printNumber("Version", Version);
  317. W.printNumber("CU count", CompUnitCount);
  318. W.printNumber("Local TU count", LocalTypeUnitCount);
  319. W.printNumber("Foreign TU count", ForeignTypeUnitCount);
  320. W.printNumber("Bucket count", BucketCount);
  321. W.printNumber("Name count", NameCount);
  322. W.printHex("Abbreviations table size", AbbrevTableSize);
  323. W.startLine() << "Augmentation: '" << AugmentationString << "'\n";
  324. }
  325. Error DWARFDebugNames::Header::extract(const DWARFDataExtractor &AS,
  326. uint64_t *Offset) {
  327. auto HeaderError = [Offset = *Offset](Error E) {
  328. return createStringError(errc::illegal_byte_sequence,
  329. "parsing .debug_names header at 0x%" PRIx64 ": %s",
  330. Offset, toString(std::move(E)).c_str());
  331. };
  332. DataExtractor::Cursor C(*Offset);
  333. std::tie(UnitLength, Format) = AS.getInitialLength(C);
  334. Version = AS.getU16(C);
  335. AS.skip(C, 2); // padding
  336. CompUnitCount = AS.getU32(C);
  337. LocalTypeUnitCount = AS.getU32(C);
  338. ForeignTypeUnitCount = AS.getU32(C);
  339. BucketCount = AS.getU32(C);
  340. NameCount = AS.getU32(C);
  341. AbbrevTableSize = AS.getU32(C);
  342. AugmentationStringSize = alignTo(AS.getU32(C), 4);
  343. if (!C)
  344. return HeaderError(C.takeError());
  345. if (!AS.isValidOffsetForDataOfSize(C.tell(), AugmentationStringSize))
  346. return HeaderError(createStringError(errc::illegal_byte_sequence,
  347. "cannot read header augmentation"));
  348. AugmentationString.resize(AugmentationStringSize);
  349. AS.getU8(C, reinterpret_cast<uint8_t *>(AugmentationString.data()),
  350. AugmentationStringSize);
  351. *Offset = C.tell();
  352. return C.takeError();
  353. }
  354. void DWARFDebugNames::Abbrev::dump(ScopedPrinter &W) const {
  355. DictScope AbbrevScope(W, ("Abbreviation 0x" + Twine::utohexstr(Code)).str());
  356. W.startLine() << formatv("Tag: {0}\n", Tag);
  357. for (const auto &Attr : Attributes)
  358. W.startLine() << formatv("{0}: {1}\n", Attr.Index, Attr.Form);
  359. }
  360. static constexpr DWARFDebugNames::AttributeEncoding sentinelAttrEnc() {
  361. return {dwarf::Index(0), dwarf::Form(0)};
  362. }
  363. static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE) {
  364. return AE == sentinelAttrEnc();
  365. }
  366. static DWARFDebugNames::Abbrev sentinelAbbrev() {
  367. return DWARFDebugNames::Abbrev(0, dwarf::Tag(0), {});
  368. }
  369. static bool isSentinel(const DWARFDebugNames::Abbrev &Abbr) {
  370. return Abbr.Code == 0;
  371. }
  372. DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getEmptyKey() {
  373. return sentinelAbbrev();
  374. }
  375. DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getTombstoneKey() {
  376. return DWARFDebugNames::Abbrev(~0, dwarf::Tag(0), {});
  377. }
  378. Expected<DWARFDebugNames::AttributeEncoding>
  379. DWARFDebugNames::NameIndex::extractAttributeEncoding(uint64_t *Offset) {
  380. if (*Offset >= EntriesBase) {
  381. return createStringError(errc::illegal_byte_sequence,
  382. "Incorrectly terminated abbreviation table.");
  383. }
  384. uint32_t Index = Section.AccelSection.getULEB128(Offset);
  385. uint32_t Form = Section.AccelSection.getULEB128(Offset);
  386. return AttributeEncoding(dwarf::Index(Index), dwarf::Form(Form));
  387. }
  388. Expected<std::vector<DWARFDebugNames::AttributeEncoding>>
  389. DWARFDebugNames::NameIndex::extractAttributeEncodings(uint64_t *Offset) {
  390. std::vector<AttributeEncoding> Result;
  391. for (;;) {
  392. auto AttrEncOr = extractAttributeEncoding(Offset);
  393. if (!AttrEncOr)
  394. return AttrEncOr.takeError();
  395. if (isSentinel(*AttrEncOr))
  396. return std::move(Result);
  397. Result.emplace_back(*AttrEncOr);
  398. }
  399. }
  400. Expected<DWARFDebugNames::Abbrev>
  401. DWARFDebugNames::NameIndex::extractAbbrev(uint64_t *Offset) {
  402. if (*Offset >= EntriesBase) {
  403. return createStringError(errc::illegal_byte_sequence,
  404. "Incorrectly terminated abbreviation table.");
  405. }
  406. uint32_t Code = Section.AccelSection.getULEB128(Offset);
  407. if (Code == 0)
  408. return sentinelAbbrev();
  409. uint32_t Tag = Section.AccelSection.getULEB128(Offset);
  410. auto AttrEncOr = extractAttributeEncodings(Offset);
  411. if (!AttrEncOr)
  412. return AttrEncOr.takeError();
  413. return Abbrev(Code, dwarf::Tag(Tag), std::move(*AttrEncOr));
  414. }
  415. Error DWARFDebugNames::NameIndex::extract() {
  416. const DWARFDataExtractor &AS = Section.AccelSection;
  417. uint64_t Offset = Base;
  418. if (Error E = Hdr.extract(AS, &Offset))
  419. return E;
  420. const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Hdr.Format);
  421. CUsBase = Offset;
  422. Offset += Hdr.CompUnitCount * SectionOffsetSize;
  423. Offset += Hdr.LocalTypeUnitCount * SectionOffsetSize;
  424. Offset += Hdr.ForeignTypeUnitCount * 8;
  425. BucketsBase = Offset;
  426. Offset += Hdr.BucketCount * 4;
  427. HashesBase = Offset;
  428. if (Hdr.BucketCount > 0)
  429. Offset += Hdr.NameCount * 4;
  430. StringOffsetsBase = Offset;
  431. Offset += Hdr.NameCount * SectionOffsetSize;
  432. EntryOffsetsBase = Offset;
  433. Offset += Hdr.NameCount * SectionOffsetSize;
  434. if (!AS.isValidOffsetForDataOfSize(Offset, Hdr.AbbrevTableSize))
  435. return createStringError(errc::illegal_byte_sequence,
  436. "Section too small: cannot read abbreviations.");
  437. EntriesBase = Offset + Hdr.AbbrevTableSize;
  438. for (;;) {
  439. auto AbbrevOr = extractAbbrev(&Offset);
  440. if (!AbbrevOr)
  441. return AbbrevOr.takeError();
  442. if (isSentinel(*AbbrevOr))
  443. return Error::success();
  444. if (!Abbrevs.insert(std::move(*AbbrevOr)).second)
  445. return createStringError(errc::invalid_argument,
  446. "Duplicate abbreviation code.");
  447. }
  448. }
  449. DWARFDebugNames::Entry::Entry(const NameIndex &NameIdx, const Abbrev &Abbr)
  450. : NameIdx(&NameIdx), Abbr(&Abbr) {
  451. // This merely creates form values. It is up to the caller
  452. // (NameIndex::getEntry) to populate them.
  453. Values.reserve(Abbr.Attributes.size());
  454. for (const auto &Attr : Abbr.Attributes)
  455. Values.emplace_back(Attr.Form);
  456. }
  457. Optional<DWARFFormValue>
  458. DWARFDebugNames::Entry::lookup(dwarf::Index Index) const {
  459. assert(Abbr->Attributes.size() == Values.size());
  460. for (auto Tuple : zip_first(Abbr->Attributes, Values)) {
  461. if (std::get<0>(Tuple).Index == Index)
  462. return std::get<1>(Tuple);
  463. }
  464. return None;
  465. }
  466. Optional<uint64_t> DWARFDebugNames::Entry::getDIEUnitOffset() const {
  467. if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_die_offset))
  468. return Off->getAsReferenceUVal();
  469. return None;
  470. }
  471. Optional<uint64_t> DWARFDebugNames::Entry::getCUIndex() const {
  472. if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_compile_unit))
  473. return Off->getAsUnsignedConstant();
  474. // In a per-CU index, the entries without a DW_IDX_compile_unit attribute
  475. // implicitly refer to the single CU.
  476. if (NameIdx->getCUCount() == 1)
  477. return 0;
  478. return None;
  479. }
  480. Optional<uint64_t> DWARFDebugNames::Entry::getCUOffset() const {
  481. Optional<uint64_t> Index = getCUIndex();
  482. if (!Index || *Index >= NameIdx->getCUCount())
  483. return None;
  484. return NameIdx->getCUOffset(*Index);
  485. }
  486. void DWARFDebugNames::Entry::dump(ScopedPrinter &W) const {
  487. W.printHex("Abbrev", Abbr->Code);
  488. W.startLine() << formatv("Tag: {0}\n", Abbr->Tag);
  489. assert(Abbr->Attributes.size() == Values.size());
  490. for (auto Tuple : zip_first(Abbr->Attributes, Values)) {
  491. W.startLine() << formatv("{0}: ", std::get<0>(Tuple).Index);
  492. std::get<1>(Tuple).dump(W.getOStream());
  493. W.getOStream() << '\n';
  494. }
  495. }
  496. char DWARFDebugNames::SentinelError::ID;
  497. std::error_code DWARFDebugNames::SentinelError::convertToErrorCode() const {
  498. return inconvertibleErrorCode();
  499. }
  500. uint64_t DWARFDebugNames::NameIndex::getCUOffset(uint32_t CU) const {
  501. assert(CU < Hdr.CompUnitCount);
  502. const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Hdr.Format);
  503. uint64_t Offset = CUsBase + SectionOffsetSize * CU;
  504. return Section.AccelSection.getRelocatedValue(SectionOffsetSize, &Offset);
  505. }
  506. uint64_t DWARFDebugNames::NameIndex::getLocalTUOffset(uint32_t TU) const {
  507. assert(TU < Hdr.LocalTypeUnitCount);
  508. const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Hdr.Format);
  509. uint64_t Offset = CUsBase + SectionOffsetSize * (Hdr.CompUnitCount + TU);
  510. return Section.AccelSection.getRelocatedValue(SectionOffsetSize, &Offset);
  511. }
  512. uint64_t DWARFDebugNames::NameIndex::getForeignTUSignature(uint32_t TU) const {
  513. assert(TU < Hdr.ForeignTypeUnitCount);
  514. const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Hdr.Format);
  515. uint64_t Offset =
  516. CUsBase +
  517. SectionOffsetSize * (Hdr.CompUnitCount + Hdr.LocalTypeUnitCount) + 8 * TU;
  518. return Section.AccelSection.getU64(&Offset);
  519. }
  520. Expected<DWARFDebugNames::Entry>
  521. DWARFDebugNames::NameIndex::getEntry(uint64_t *Offset) const {
  522. const DWARFDataExtractor &AS = Section.AccelSection;
  523. if (!AS.isValidOffset(*Offset))
  524. return createStringError(errc::illegal_byte_sequence,
  525. "Incorrectly terminated entry list.");
  526. uint32_t AbbrevCode = AS.getULEB128(Offset);
  527. if (AbbrevCode == 0)
  528. return make_error<SentinelError>();
  529. const auto AbbrevIt = Abbrevs.find_as(AbbrevCode);
  530. if (AbbrevIt == Abbrevs.end())
  531. return createStringError(errc::invalid_argument, "Invalid abbreviation.");
  532. Entry E(*this, *AbbrevIt);
  533. dwarf::FormParams FormParams = {Hdr.Version, 0, Hdr.Format};
  534. for (auto &Value : E.Values) {
  535. if (!Value.extractValue(AS, Offset, FormParams))
  536. return createStringError(errc::io_error,
  537. "Error extracting index attribute values.");
  538. }
  539. return std::move(E);
  540. }
  541. DWARFDebugNames::NameTableEntry
  542. DWARFDebugNames::NameIndex::getNameTableEntry(uint32_t Index) const {
  543. assert(0 < Index && Index <= Hdr.NameCount);
  544. const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Hdr.Format);
  545. uint64_t StringOffsetOffset =
  546. StringOffsetsBase + SectionOffsetSize * (Index - 1);
  547. uint64_t EntryOffsetOffset =
  548. EntryOffsetsBase + SectionOffsetSize * (Index - 1);
  549. const DWARFDataExtractor &AS = Section.AccelSection;
  550. uint64_t StringOffset =
  551. AS.getRelocatedValue(SectionOffsetSize, &StringOffsetOffset);
  552. uint64_t EntryOffset = AS.getUnsigned(&EntryOffsetOffset, SectionOffsetSize);
  553. EntryOffset += EntriesBase;
  554. return {Section.StringSection, Index, StringOffset, EntryOffset};
  555. }
  556. uint32_t
  557. DWARFDebugNames::NameIndex::getBucketArrayEntry(uint32_t Bucket) const {
  558. assert(Bucket < Hdr.BucketCount);
  559. uint64_t BucketOffset = BucketsBase + 4 * Bucket;
  560. return Section.AccelSection.getU32(&BucketOffset);
  561. }
  562. uint32_t DWARFDebugNames::NameIndex::getHashArrayEntry(uint32_t Index) const {
  563. assert(0 < Index && Index <= Hdr.NameCount);
  564. uint64_t HashOffset = HashesBase + 4 * (Index - 1);
  565. return Section.AccelSection.getU32(&HashOffset);
  566. }
  567. // Returns true if we should continue scanning for entries, false if this is the
  568. // last (sentinel) entry). In case of a parsing error we also return false, as
  569. // it's not possible to recover this entry list (but the other lists may still
  570. // parse OK).
  571. bool DWARFDebugNames::NameIndex::dumpEntry(ScopedPrinter &W,
  572. uint64_t *Offset) const {
  573. uint64_t EntryId = *Offset;
  574. auto EntryOr = getEntry(Offset);
  575. if (!EntryOr) {
  576. handleAllErrors(EntryOr.takeError(), [](const SentinelError &) {},
  577. [&W](const ErrorInfoBase &EI) { EI.log(W.startLine()); });
  578. return false;
  579. }
  580. DictScope EntryScope(W, ("Entry @ 0x" + Twine::utohexstr(EntryId)).str());
  581. EntryOr->dump(W);
  582. return true;
  583. }
  584. void DWARFDebugNames::NameIndex::dumpName(ScopedPrinter &W,
  585. const NameTableEntry &NTE,
  586. Optional<uint32_t> Hash) const {
  587. DictScope NameScope(W, ("Name " + Twine(NTE.getIndex())).str());
  588. if (Hash)
  589. W.printHex("Hash", *Hash);
  590. W.startLine() << format("String: 0x%08" PRIx64, NTE.getStringOffset());
  591. W.getOStream() << " \"" << NTE.getString() << "\"\n";
  592. uint64_t EntryOffset = NTE.getEntryOffset();
  593. while (dumpEntry(W, &EntryOffset))
  594. /*empty*/;
  595. }
  596. void DWARFDebugNames::NameIndex::dumpCUs(ScopedPrinter &W) const {
  597. ListScope CUScope(W, "Compilation Unit offsets");
  598. for (uint32_t CU = 0; CU < Hdr.CompUnitCount; ++CU)
  599. W.startLine() << format("CU[%u]: 0x%08" PRIx64 "\n", CU, getCUOffset(CU));
  600. }
  601. void DWARFDebugNames::NameIndex::dumpLocalTUs(ScopedPrinter &W) const {
  602. if (Hdr.LocalTypeUnitCount == 0)
  603. return;
  604. ListScope TUScope(W, "Local Type Unit offsets");
  605. for (uint32_t TU = 0; TU < Hdr.LocalTypeUnitCount; ++TU)
  606. W.startLine() << format("LocalTU[%u]: 0x%08" PRIx64 "\n", TU,
  607. getLocalTUOffset(TU));
  608. }
  609. void DWARFDebugNames::NameIndex::dumpForeignTUs(ScopedPrinter &W) const {
  610. if (Hdr.ForeignTypeUnitCount == 0)
  611. return;
  612. ListScope TUScope(W, "Foreign Type Unit signatures");
  613. for (uint32_t TU = 0; TU < Hdr.ForeignTypeUnitCount; ++TU) {
  614. W.startLine() << format("ForeignTU[%u]: 0x%016" PRIx64 "\n", TU,
  615. getForeignTUSignature(TU));
  616. }
  617. }
  618. void DWARFDebugNames::NameIndex::dumpAbbreviations(ScopedPrinter &W) const {
  619. ListScope AbbrevsScope(W, "Abbreviations");
  620. for (const auto &Abbr : Abbrevs)
  621. Abbr.dump(W);
  622. }
  623. void DWARFDebugNames::NameIndex::dumpBucket(ScopedPrinter &W,
  624. uint32_t Bucket) const {
  625. ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
  626. uint32_t Index = getBucketArrayEntry(Bucket);
  627. if (Index == 0) {
  628. W.printString("EMPTY");
  629. return;
  630. }
  631. if (Index > Hdr.NameCount) {
  632. W.printString("Name index is invalid");
  633. return;
  634. }
  635. for (; Index <= Hdr.NameCount; ++Index) {
  636. uint32_t Hash = getHashArrayEntry(Index);
  637. if (Hash % Hdr.BucketCount != Bucket)
  638. break;
  639. dumpName(W, getNameTableEntry(Index), Hash);
  640. }
  641. }
  642. LLVM_DUMP_METHOD void DWARFDebugNames::NameIndex::dump(ScopedPrinter &W) const {
  643. DictScope UnitScope(W, ("Name Index @ 0x" + Twine::utohexstr(Base)).str());
  644. Hdr.dump(W);
  645. dumpCUs(W);
  646. dumpLocalTUs(W);
  647. dumpForeignTUs(W);
  648. dumpAbbreviations(W);
  649. if (Hdr.BucketCount > 0) {
  650. for (uint32_t Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket)
  651. dumpBucket(W, Bucket);
  652. return;
  653. }
  654. W.startLine() << "Hash table not present\n";
  655. for (const NameTableEntry &NTE : *this)
  656. dumpName(W, NTE, None);
  657. }
  658. Error DWARFDebugNames::extract() {
  659. uint64_t Offset = 0;
  660. while (AccelSection.isValidOffset(Offset)) {
  661. NameIndex Next(*this, Offset);
  662. if (Error E = Next.extract())
  663. return E;
  664. Offset = Next.getNextUnitOffset();
  665. NameIndices.push_back(std::move(Next));
  666. }
  667. return Error::success();
  668. }
  669. iterator_range<DWARFDebugNames::ValueIterator>
  670. DWARFDebugNames::NameIndex::equal_range(StringRef Key) const {
  671. return make_range(ValueIterator(*this, Key), ValueIterator());
  672. }
  673. LLVM_DUMP_METHOD void DWARFDebugNames::dump(raw_ostream &OS) const {
  674. ScopedPrinter W(OS);
  675. for (const NameIndex &NI : NameIndices)
  676. NI.dump(W);
  677. }
  678. Optional<uint64_t>
  679. DWARFDebugNames::ValueIterator::findEntryOffsetInCurrentIndex() {
  680. const Header &Hdr = CurrentIndex->Hdr;
  681. if (Hdr.BucketCount == 0) {
  682. // No Hash Table, We need to search through all names in the Name Index.
  683. for (const NameTableEntry &NTE : *CurrentIndex) {
  684. if (NTE.getString() == Key)
  685. return NTE.getEntryOffset();
  686. }
  687. return None;
  688. }
  689. // The Name Index has a Hash Table, so use that to speed up the search.
  690. // Compute the Key Hash, if it has not been done already.
  691. if (!Hash)
  692. Hash = caseFoldingDjbHash(Key);
  693. uint32_t Bucket = *Hash % Hdr.BucketCount;
  694. uint32_t Index = CurrentIndex->getBucketArrayEntry(Bucket);
  695. if (Index == 0)
  696. return None; // Empty bucket
  697. for (; Index <= Hdr.NameCount; ++Index) {
  698. uint32_t Hash = CurrentIndex->getHashArrayEntry(Index);
  699. if (Hash % Hdr.BucketCount != Bucket)
  700. return None; // End of bucket
  701. NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
  702. if (NTE.getString() == Key)
  703. return NTE.getEntryOffset();
  704. }
  705. return None;
  706. }
  707. bool DWARFDebugNames::ValueIterator::getEntryAtCurrentOffset() {
  708. auto EntryOr = CurrentIndex->getEntry(&DataOffset);
  709. if (!EntryOr) {
  710. consumeError(EntryOr.takeError());
  711. return false;
  712. }
  713. CurrentEntry = std::move(*EntryOr);
  714. return true;
  715. }
  716. bool DWARFDebugNames::ValueIterator::findInCurrentIndex() {
  717. Optional<uint64_t> Offset = findEntryOffsetInCurrentIndex();
  718. if (!Offset)
  719. return false;
  720. DataOffset = *Offset;
  721. return getEntryAtCurrentOffset();
  722. }
  723. void DWARFDebugNames::ValueIterator::searchFromStartOfCurrentIndex() {
  724. for (const NameIndex *End = CurrentIndex->Section.NameIndices.end();
  725. CurrentIndex != End; ++CurrentIndex) {
  726. if (findInCurrentIndex())
  727. return;
  728. }
  729. setEnd();
  730. }
  731. void DWARFDebugNames::ValueIterator::next() {
  732. assert(CurrentIndex && "Incrementing an end() iterator?");
  733. // First try the next entry in the current Index.
  734. if (getEntryAtCurrentOffset())
  735. return;
  736. // If we're a local iterator or we have reached the last Index, we're done.
  737. if (IsLocal || CurrentIndex == &CurrentIndex->Section.NameIndices.back()) {
  738. setEnd();
  739. return;
  740. }
  741. // Otherwise, try the next index.
  742. ++CurrentIndex;
  743. searchFromStartOfCurrentIndex();
  744. }
  745. DWARFDebugNames::ValueIterator::ValueIterator(const DWARFDebugNames &AccelTable,
  746. StringRef Key)
  747. : CurrentIndex(AccelTable.NameIndices.begin()), IsLocal(false),
  748. Key(std::string(Key)) {
  749. searchFromStartOfCurrentIndex();
  750. }
  751. DWARFDebugNames::ValueIterator::ValueIterator(
  752. const DWARFDebugNames::NameIndex &NI, StringRef Key)
  753. : CurrentIndex(&NI), IsLocal(true), Key(std::string(Key)) {
  754. if (!findInCurrentIndex())
  755. setEnd();
  756. }
  757. iterator_range<DWARFDebugNames::ValueIterator>
  758. DWARFDebugNames::equal_range(StringRef Key) const {
  759. if (NameIndices.empty())
  760. return make_range(ValueIterator(), ValueIterator());
  761. return make_range(ValueIterator(*this, Key), ValueIterator());
  762. }
  763. const DWARFDebugNames::NameIndex *
  764. DWARFDebugNames::getCUNameIndex(uint64_t CUOffset) {
  765. if (CUToNameIndex.size() == 0 && NameIndices.size() > 0) {
  766. for (const auto &NI : *this) {
  767. for (uint32_t CU = 0; CU < NI.getCUCount(); ++CU)
  768. CUToNameIndex.try_emplace(NI.getCUOffset(CU), &NI);
  769. }
  770. }
  771. return CUToNameIndex.lookup(CUOffset);
  772. }