blob: 3d26cf69b9469a2d5746f73aadcd7ff667afe0ce [file] [log] [blame]
Eugene Zelenkoe94042c2017-02-27 23:43:14 +00001//===- DWARFAcceleratorTable.cpp ------------------------------------------===//
Frederic Riss7c41c642014-11-20 16:21:06 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Zachary Turner82af9432015-01-30 18:07:45 +000010#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000011
Chandler Carruth6bda14b2017-06-06 11:49:48 +000012#include "llvm/ADT/SmallVector.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000013#include "llvm/BinaryFormat/Dwarf.h"
Eugene Zelenkoe94042c2017-02-27 23:43:14 +000014#include "llvm/DebugInfo/DWARF/DWARFRelocMap.h"
Eugene Zelenkoe94042c2017-02-27 23:43:14 +000015#include "llvm/Support/Compiler.h"
Jonas Devlieghere92ac9d32018-01-28 11:05:10 +000016#include "llvm/Support/DJB.h"
Frederic Risse837ec22014-11-14 16:15:53 +000017#include "llvm/Support/Format.h"
Pavel Labath3c9a9182018-01-29 11:08:32 +000018#include "llvm/Support/ScopedPrinter.h"
Frederic Risse837ec22014-11-14 16:15:53 +000019#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe94042c2017-02-27 23:43:14 +000020#include <cstddef>
21#include <cstdint>
22#include <utility>
Frederic Risse837ec22014-11-14 16:15:53 +000023
Eugene Zelenkoe94042c2017-02-27 23:43:14 +000024using namespace llvm;
Frederic Risse837ec22014-11-14 16:15:53 +000025
Pavel Labath3c9a9182018-01-29 11:08:32 +000026namespace {
27struct DwarfConstant {
28 StringRef (*StringFn)(unsigned);
29 StringRef Type;
30 unsigned Value;
31};
32
33static raw_ostream &operator<<(raw_ostream &OS, const DwarfConstant &C) {
34 StringRef Str = C.StringFn(C.Value);
35 if (!Str.empty())
36 return OS << Str;
37 return OS << "DW_" << C.Type << "_Unknown_0x" << format("%x", C.Value);
38}
39} // namespace
40
41static DwarfConstant formatTag(unsigned Tag) {
42 return {dwarf::TagString, "TAG", Tag};
43}
44
45static DwarfConstant formatForm(unsigned Form) {
46 return {dwarf::FormEncodingString, "FORM", Form};
47}
48
49static DwarfConstant formatIndex(unsigned Idx) {
50 return {dwarf::IndexString, "IDX", Idx};
51}
52
53static DwarfConstant formatAtom(unsigned Atom) {
54 return {dwarf::AtomTypeString, "ATOM", Atom};
55}
56
57DWARFAcceleratorTable::~DWARFAcceleratorTable() = default;
58
Pavel Labath9b36fd22018-01-22 13:17:23 +000059llvm::Error AppleAcceleratorTable::extract() {
Frederic Risse837ec22014-11-14 16:15:53 +000060 uint32_t Offset = 0;
61
62 // Check that we can at least read the header.
63 if (!AccelSection.isValidOffset(offsetof(Header, HeaderDataLength)+4))
Jonas Devlieghereba915892017-12-11 18:22:47 +000064 return make_error<StringError>("Section too small: cannot read header.",
65 inconvertibleErrorCode());
Frederic Risse837ec22014-11-14 16:15:53 +000066
67 Hdr.Magic = AccelSection.getU32(&Offset);
68 Hdr.Version = AccelSection.getU16(&Offset);
69 Hdr.HashFunction = AccelSection.getU16(&Offset);
Pavel Labath394e8052018-01-29 11:33:17 +000070 Hdr.BucketCount = AccelSection.getU32(&Offset);
71 Hdr.HashCount = AccelSection.getU32(&Offset);
Frederic Risse837ec22014-11-14 16:15:53 +000072 Hdr.HeaderDataLength = AccelSection.getU32(&Offset);
73
74 // Check that we can read all the hashes and offsets from the
75 // section (see SourceLevelDebugging.rst for the structure of the index).
Jonas Devlieghereba915892017-12-11 18:22:47 +000076 // We need to substract one because we're checking for an *offset* which is
77 // equal to the size for an empty table and hence pointer after the section.
Frederic Risse837ec22014-11-14 16:15:53 +000078 if (!AccelSection.isValidOffset(sizeof(Hdr) + Hdr.HeaderDataLength +
Pavel Labath394e8052018-01-29 11:33:17 +000079 Hdr.BucketCount * 4 + Hdr.HashCount * 8 - 1))
Jonas Devlieghereba915892017-12-11 18:22:47 +000080 return make_error<StringError>(
81 "Section too small: cannot read buckets and hashes.",
82 inconvertibleErrorCode());
Frederic Risse837ec22014-11-14 16:15:53 +000083
84 HdrData.DIEOffsetBase = AccelSection.getU32(&Offset);
85 uint32_t NumAtoms = AccelSection.getU32(&Offset);
86
87 for (unsigned i = 0; i < NumAtoms; ++i) {
88 uint16_t AtomType = AccelSection.getU16(&Offset);
Greg Clayton6c273762016-10-27 16:32:04 +000089 auto AtomForm = static_cast<dwarf::Form>(AccelSection.getU16(&Offset));
Frederic Risse837ec22014-11-14 16:15:53 +000090 HdrData.Atoms.push_back(std::make_pair(AtomType, AtomForm));
91 }
92
Adrian Prantl99fdb9d2017-09-28 18:10:52 +000093 IsValid = true;
Jonas Devlieghereba915892017-12-11 18:22:47 +000094 return Error::success();
Frederic Risse837ec22014-11-14 16:15:53 +000095}
96
Pavel Labath394e8052018-01-29 11:33:17 +000097uint32_t AppleAcceleratorTable::getNumBuckets() { return Hdr.BucketCount; }
98uint32_t AppleAcceleratorTable::getNumHashes() { return Hdr.HashCount; }
Pavel Labath9b36fd22018-01-22 13:17:23 +000099uint32_t AppleAcceleratorTable::getSizeHdr() { return sizeof(Hdr); }
100uint32_t AppleAcceleratorTable::getHeaderDataLength() {
Spyridoula Gravanie41823b2017-06-14 00:17:55 +0000101 return Hdr.HeaderDataLength;
102}
103
Pavel Labath9b36fd22018-01-22 13:17:23 +0000104ArrayRef<std::pair<AppleAcceleratorTable::HeaderData::AtomType,
105 AppleAcceleratorTable::HeaderData::Form>>
106AppleAcceleratorTable::getAtomsDesc() {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000107 return HdrData.Atoms;
108}
109
Pavel Labath9b36fd22018-01-22 13:17:23 +0000110bool AppleAcceleratorTable::validateForms() {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000111 for (auto Atom : getAtomsDesc()) {
112 DWARFFormValue FormValue(Atom.second);
113 switch (Atom.first) {
114 case dwarf::DW_ATOM_die_offset:
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000115 case dwarf::DW_ATOM_die_tag:
116 case dwarf::DW_ATOM_type_flags:
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000117 if ((!FormValue.isFormClass(DWARFFormValue::FC_Constant) &&
118 !FormValue.isFormClass(DWARFFormValue::FC_Flag)) ||
119 FormValue.getForm() == dwarf::DW_FORM_sdata)
120 return false;
Adrian Prantl0e6694d2017-12-19 22:05:25 +0000121 break;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000122 default:
123 break;
124 }
125 }
126 return true;
127}
128
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000129std::pair<uint32_t, dwarf::Tag>
Pavel Labath9b36fd22018-01-22 13:17:23 +0000130AppleAcceleratorTable::readAtoms(uint32_t &HashDataOffset) {
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000131 uint32_t DieOffset = dwarf::DW_INVALID_OFFSET;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000132 dwarf::Tag DieTag = dwarf::DW_TAG_null;
Paul Robinsone5400f82017-11-07 19:57:12 +0000133 DWARFFormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000134
135 for (auto Atom : getAtomsDesc()) {
136 DWARFFormValue FormValue(Atom.second);
Paul Robinsone5400f82017-11-07 19:57:12 +0000137 FormValue.extractValue(AccelSection, &HashDataOffset, FormParams);
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000138 switch (Atom.first) {
139 case dwarf::DW_ATOM_die_offset:
140 DieOffset = *FormValue.getAsUnsignedConstant();
141 break;
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000142 case dwarf::DW_ATOM_die_tag:
143 DieTag = (dwarf::Tag)*FormValue.getAsUnsignedConstant();
144 break;
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000145 default:
146 break;
147 }
148 }
Spyridoula Gravani70d35e12017-07-31 18:01:16 +0000149 return {DieOffset, DieTag};
Spyridoula Gravani837c1102017-06-29 20:13:05 +0000150}
151
Pavel Labath394e8052018-01-29 11:33:17 +0000152void AppleAcceleratorTable::Header::dump(ScopedPrinter &W) const {
153 DictScope HeaderScope(W, "Header");
154 W.printHex("Magic", Magic);
155 W.printHex("Version", Version);
156 W.printHex("Hash function", HashFunction);
157 W.printNumber("Bucket count", BucketCount);
158 W.printNumber("Hashes count", HashCount);
159 W.printNumber("HeaderData length", HeaderDataLength);
160}
161
162bool AppleAcceleratorTable::dumpName(ScopedPrinter &W,
163 SmallVectorImpl<DWARFFormValue> &AtomForms,
164 uint32_t *DataOffset) const {
165 DWARFFormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
166 uint32_t NameOffset = *DataOffset;
167 if (!AccelSection.isValidOffsetForDataOfSize(*DataOffset, 4)) {
168 W.printString("Incorrectly terminated list.");
169 return false;
170 }
171 unsigned StringOffset = AccelSection.getRelocatedValue(4, DataOffset);
172 if (!StringOffset)
173 return false; // End of list
174
175 DictScope NameScope(W, ("Name@0x" + Twine::utohexstr(NameOffset)).str());
176 W.startLine() << format("String: 0x%08x", StringOffset);
177 W.getOStream() << " \"" << StringSection.getCStr(&StringOffset) << "\"\n";
178
179 unsigned NumData = AccelSection.getU32(DataOffset);
180 for (unsigned Data = 0; Data < NumData; ++Data) {
181 ListScope DataScope(W, ("Data " + Twine(Data)).str());
182 unsigned i = 0;
183 for (auto &Atom : AtomForms) {
184 W.startLine() << format("Atom[%d]: ", i++);
185 if (Atom.extractValue(AccelSection, DataOffset, FormParams))
186 Atom.dump(W.getOStream());
187 else
188 W.getOStream() << "Error extracting the value";
189 W.getOStream() << "\n";
190 }
191 }
192 return true; // more entries follow
193}
194
Pavel Labath9b36fd22018-01-22 13:17:23 +0000195LLVM_DUMP_METHOD void AppleAcceleratorTable::dump(raw_ostream &OS) const {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000196 if (!IsValid)
197 return;
198
Pavel Labath394e8052018-01-29 11:33:17 +0000199 ScopedPrinter W(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000200
Pavel Labath394e8052018-01-29 11:33:17 +0000201 Hdr.dump(W);
202
203 W.printNumber("DIE offset base", HdrData.DIEOffsetBase);
Pavel Labath34609572018-01-29 11:53:46 +0000204 W.printNumber("Number of atoms", uint64_t(HdrData.Atoms.size()));
Frederic Riss77a07432014-11-20 16:21:11 +0000205 SmallVector<DWARFFormValue, 3> AtomForms;
Pavel Labath394e8052018-01-29 11:33:17 +0000206 {
207 ListScope AtomsScope(W, "Atoms");
208 unsigned i = 0;
209 for (const auto &Atom : HdrData.Atoms) {
210 DictScope AtomScope(W, ("Atom " + Twine(i++)).str());
211 W.startLine() << "Type: " << formatAtom(Atom.first) << '\n';
212 W.startLine() << "Form: " << formatForm(Atom.second) << '\n';
213 AtomForms.push_back(DWARFFormValue(Atom.second));
214 }
Frederic Risse837ec22014-11-14 16:15:53 +0000215 }
216
217 // Now go through the actual tables and dump them.
218 uint32_t Offset = sizeof(Hdr) + Hdr.HeaderDataLength;
Pavel Labath394e8052018-01-29 11:33:17 +0000219 unsigned HashesBase = Offset + Hdr.BucketCount * 4;
220 unsigned OffsetsBase = HashesBase + Hdr.HashCount * 4;
Frederic Risse837ec22014-11-14 16:15:53 +0000221
Pavel Labath394e8052018-01-29 11:33:17 +0000222 for (unsigned Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket) {
Frederic Risse837ec22014-11-14 16:15:53 +0000223 unsigned Index = AccelSection.getU32(&Offset);
224
Pavel Labath394e8052018-01-29 11:33:17 +0000225 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
Frederic Risse837ec22014-11-14 16:15:53 +0000226 if (Index == UINT32_MAX) {
Pavel Labath394e8052018-01-29 11:33:17 +0000227 W.printString("EMPTY");
Frederic Risse837ec22014-11-14 16:15:53 +0000228 continue;
229 }
230
Pavel Labath394e8052018-01-29 11:33:17 +0000231 for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
Frederic Risse837ec22014-11-14 16:15:53 +0000232 unsigned HashOffset = HashesBase + HashIdx*4;
233 unsigned OffsetsOffset = OffsetsBase + HashIdx*4;
234 uint32_t Hash = AccelSection.getU32(&HashOffset);
235
Pavel Labath394e8052018-01-29 11:33:17 +0000236 if (Hash % Hdr.BucketCount != Bucket)
Frederic Risse837ec22014-11-14 16:15:53 +0000237 break;
238
239 unsigned DataOffset = AccelSection.getU32(&OffsetsOffset);
Pavel Labath394e8052018-01-29 11:33:17 +0000240 ListScope HashScope(W, ("Hash 0x" + Twine::utohexstr(Hash)).str());
Frederic Risse837ec22014-11-14 16:15:53 +0000241 if (!AccelSection.isValidOffset(DataOffset)) {
Pavel Labath394e8052018-01-29 11:33:17 +0000242 W.printString("Invalid section offset");
Frederic Risse837ec22014-11-14 16:15:53 +0000243 continue;
244 }
Pavel Labath394e8052018-01-29 11:33:17 +0000245 while (dumpName(W, AtomForms, &DataOffset))
246 /*empty*/;
Frederic Risse837ec22014-11-14 16:15:53 +0000247 }
248 }
249}
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000250
Pavel Labathd99072b2018-02-24 00:35:21 +0000251AppleAcceleratorTable::Entry::Entry(
252 const AppleAcceleratorTable::HeaderData &HdrData)
253 : HdrData(&HdrData) {
254 Values.reserve(HdrData.Atoms.size());
255 for (const auto &Atom : HdrData.Atoms)
256 Values.push_back(DWARFFormValue(Atom.second));
257}
258
259void AppleAcceleratorTable::Entry::extract(
260 const AppleAcceleratorTable &AccelTable, uint32_t *Offset) {
261
262 DWARFFormParams FormParams = {AccelTable.Hdr.Version, 0,
263 dwarf::DwarfFormat::DWARF32};
264 for (auto &Atom : Values)
265 Atom.extractValue(AccelTable.AccelSection, Offset, FormParams);
266}
267
268Optional<DWARFFormValue>
269AppleAcceleratorTable::Entry::lookup(HeaderData::AtomType Atom) const {
270 assert(HdrData && "Dereferencing end iterator?");
271 assert(HdrData->Atoms.size() == Values.size());
272 for (const auto &Tuple : zip_first(HdrData->Atoms, Values)) {
273 if (std::get<0>(Tuple).first == Atom)
274 return std::get<1>(Tuple);
275 }
276 return None;
277}
278
279Optional<uint64_t> AppleAcceleratorTable::Entry::getDIEOffset() const {
280 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_ATOM_die_offset))
281 return Off->getAsSectionOffset();
282 return None;
283}
284
285Optional<uint64_t> AppleAcceleratorTable::Entry::getCUOffset() const {
286 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_ATOM_cu_offset))
287 return Off->getAsSectionOffset();
288 return None;
289}
290
291Optional<dwarf::Tag> AppleAcceleratorTable::Entry::getTag() const {
292 Optional<DWARFFormValue> Tag = lookup(dwarf::DW_ATOM_die_tag);
293 if (!Tag)
294 return None;
295 if (Optional<uint64_t> Value = Tag->getAsUnsignedConstant())
296 return dwarf::Tag(*Value);
297 return None;
298}
299
Pavel Labath9b36fd22018-01-22 13:17:23 +0000300AppleAcceleratorTable::ValueIterator::ValueIterator(
301 const AppleAcceleratorTable &AccelTable, unsigned Offset)
Pavel Labathd99072b2018-02-24 00:35:21 +0000302 : AccelTable(&AccelTable), Current(AccelTable.HdrData), DataOffset(Offset) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000303 if (!AccelTable.AccelSection.isValidOffsetForDataOfSize(DataOffset, 4))
304 return;
305
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000306 // Read the first entry.
307 NumData = AccelTable.AccelSection.getU32(&DataOffset);
308 Next();
309}
310
Pavel Labath9b36fd22018-01-22 13:17:23 +0000311void AppleAcceleratorTable::ValueIterator::Next() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000312 assert(NumData > 0 && "attempted to increment iterator past the end");
313 auto &AccelSection = AccelTable->AccelSection;
314 if (Data >= NumData ||
315 !AccelSection.isValidOffsetForDataOfSize(DataOffset, 4)) {
316 NumData = 0;
317 return;
318 }
Pavel Labathd99072b2018-02-24 00:35:21 +0000319 Current.extract(*AccelTable, &DataOffset);
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000320 ++Data;
321}
322
Pavel Labath9b36fd22018-01-22 13:17:23 +0000323iterator_range<AppleAcceleratorTable::ValueIterator>
324AppleAcceleratorTable::equal_range(StringRef Key) const {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000325 if (!IsValid)
326 return make_range(ValueIterator(), ValueIterator());
327
328 // Find the bucket.
Jonas Devlieghere92ac9d32018-01-28 11:05:10 +0000329 unsigned HashValue = djbHash(Key);
Pavel Labath394e8052018-01-29 11:33:17 +0000330 unsigned Bucket = HashValue % Hdr.BucketCount;
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000331 unsigned BucketBase = sizeof(Hdr) + Hdr.HeaderDataLength;
Pavel Labath394e8052018-01-29 11:33:17 +0000332 unsigned HashesBase = BucketBase + Hdr.BucketCount * 4;
333 unsigned OffsetsBase = HashesBase + Hdr.HashCount * 4;
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000334
335 unsigned BucketOffset = BucketBase + Bucket * 4;
336 unsigned Index = AccelSection.getU32(&BucketOffset);
337
338 // Search through all hashes in the bucket.
Pavel Labath394e8052018-01-29 11:33:17 +0000339 for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000340 unsigned HashOffset = HashesBase + HashIdx * 4;
341 unsigned OffsetsOffset = OffsetsBase + HashIdx * 4;
342 uint32_t Hash = AccelSection.getU32(&HashOffset);
343
Pavel Labath394e8052018-01-29 11:33:17 +0000344 if (Hash % Hdr.BucketCount != Bucket)
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000345 // We are already in the next bucket.
346 break;
347
348 unsigned DataOffset = AccelSection.getU32(&OffsetsOffset);
349 unsigned StringOffset = AccelSection.getRelocatedValue(4, &DataOffset);
350 if (!StringOffset)
351 break;
352
353 // Finally, compare the key.
354 if (Key == StringSection.getCStr(&StringOffset))
355 return make_range({*this, DataOffset}, ValueIterator());
356 }
357 return make_range(ValueIterator(), ValueIterator());
358}
Pavel Labath3c9a9182018-01-29 11:08:32 +0000359
360void DWARFDebugNames::Header::dump(ScopedPrinter &W) const {
361 DictScope HeaderScope(W, "Header");
362 W.printHex("Length", UnitLength);
363 W.printNumber("Version", Version);
364 W.printHex("Padding", Padding);
365 W.printNumber("CU count", CompUnitCount);
366 W.printNumber("Local TU count", LocalTypeUnitCount);
367 W.printNumber("Foreign TU count", ForeignTypeUnitCount);
368 W.printNumber("Bucket count", BucketCount);
369 W.printNumber("Name count", NameCount);
370 W.printHex("Abbreviations table size", AbbrevTableSize);
371 W.startLine() << "Augmentation: '" << AugmentationString << "'\n";
372}
373
374llvm::Error DWARFDebugNames::Header::extract(const DWARFDataExtractor &AS,
375 uint32_t *Offset) {
376 // Check that we can read the fixed-size part.
Pavel Labathe7264102018-01-29 13:53:48 +0000377 if (!AS.isValidOffset(*Offset + sizeof(HeaderPOD) - 1))
Pavel Labath3c9a9182018-01-29 11:08:32 +0000378 return make_error<StringError>("Section too small: cannot read header.",
379 inconvertibleErrorCode());
380
381 UnitLength = AS.getU32(Offset);
382 Version = AS.getU16(Offset);
383 Padding = AS.getU16(Offset);
384 CompUnitCount = AS.getU32(Offset);
385 LocalTypeUnitCount = AS.getU32(Offset);
386 ForeignTypeUnitCount = AS.getU32(Offset);
387 BucketCount = AS.getU32(Offset);
388 NameCount = AS.getU32(Offset);
389 AbbrevTableSize = AS.getU32(Offset);
390 AugmentationStringSize = AS.getU32(Offset);
391
392 if (!AS.isValidOffsetForDataOfSize(*Offset, AugmentationStringSize))
393 return make_error<StringError>(
394 "Section too small: cannot read header augmentation.",
395 inconvertibleErrorCode());
396 AugmentationString.resize(AugmentationStringSize);
397 AS.getU8(Offset, reinterpret_cast<uint8_t *>(AugmentationString.data()),
398 AugmentationStringSize);
399 *Offset = alignTo(*Offset, 4);
400 return Error::success();
401}
402
403void DWARFDebugNames::Abbrev::dump(ScopedPrinter &W) const {
404 DictScope AbbrevScope(W, ("Abbreviation 0x" + Twine::utohexstr(Code)).str());
405 W.startLine() << "Tag: " << formatTag(Tag) << '\n';
406
407 for (const auto &Attr : Attributes) {
408 W.startLine() << formatIndex(Attr.Index) << ": " << formatForm(Attr.Form)
409 << '\n';
410 }
411}
412
413static constexpr DWARFDebugNames::AttributeEncoding sentinelAttrEnc() {
414 return {dwarf::Index(0), dwarf::Form(0)};
415}
416
417static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE) {
418 return AE == sentinelAttrEnc();
419}
420
421static DWARFDebugNames::Abbrev sentinelAbbrev() {
422 return DWARFDebugNames::Abbrev(0, dwarf::Tag(0), {});
423}
424
425static bool isSentinel(const DWARFDebugNames::Abbrev &Abbr) {
426 return Abbr.Code == 0;
427}
428
429DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getEmptyKey() {
430 return sentinelAbbrev();
431}
432
433DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getTombstoneKey() {
434 return DWARFDebugNames::Abbrev(~0, dwarf::Tag(0), {});
435}
436
437Expected<DWARFDebugNames::AttributeEncoding>
438DWARFDebugNames::NameIndex::extractAttributeEncoding(uint32_t *Offset) {
439 if (*Offset >= EntriesBase) {
440 return make_error<StringError>("Incorrectly terminated abbreviation table.",
441 inconvertibleErrorCode());
442 }
443
444 uint32_t Index = Section.AccelSection.getULEB128(Offset);
445 uint32_t Form = Section.AccelSection.getULEB128(Offset);
446 return AttributeEncoding(dwarf::Index(Index), dwarf::Form(Form));
447}
448
449Expected<std::vector<DWARFDebugNames::AttributeEncoding>>
450DWARFDebugNames::NameIndex::extractAttributeEncodings(uint32_t *Offset) {
451 std::vector<AttributeEncoding> Result;
452 for (;;) {
453 auto AttrEncOr = extractAttributeEncoding(Offset);
454 if (!AttrEncOr)
455 return AttrEncOr.takeError();
456 if (isSentinel(*AttrEncOr))
457 return std::move(Result);
458
459 Result.emplace_back(*AttrEncOr);
460 }
461}
462
463Expected<DWARFDebugNames::Abbrev>
464DWARFDebugNames::NameIndex::extractAbbrev(uint32_t *Offset) {
465 if (*Offset >= EntriesBase) {
466 return make_error<StringError>("Incorrectly terminated abbreviation table.",
467 inconvertibleErrorCode());
468 }
469
470 uint32_t Code = Section.AccelSection.getULEB128(Offset);
471 if (Code == 0)
472 return sentinelAbbrev();
473
474 uint32_t Tag = Section.AccelSection.getULEB128(Offset);
475 auto AttrEncOr = extractAttributeEncodings(Offset);
476 if (!AttrEncOr)
477 return AttrEncOr.takeError();
478 return Abbrev(Code, dwarf::Tag(Tag), std::move(*AttrEncOr));
479}
480
481Error DWARFDebugNames::NameIndex::extract() {
482 const DWARFDataExtractor &AS = Section.AccelSection;
483 uint32_t Offset = Base;
484 if (Error E = Hdr.extract(AS, &Offset))
485 return E;
486
487 CUsBase = Offset;
488 Offset += Hdr.CompUnitCount * 4;
489 Offset += Hdr.LocalTypeUnitCount * 4;
490 Offset += Hdr.ForeignTypeUnitCount * 8;
491 BucketsBase = Offset;
492 Offset += Hdr.BucketCount * 4;
493 HashesBase = Offset;
494 if (Hdr.BucketCount > 0)
495 Offset += Hdr.NameCount * 4;
496 StringOffsetsBase = Offset;
497 Offset += Hdr.NameCount * 4;
498 EntryOffsetsBase = Offset;
499 Offset += Hdr.NameCount * 4;
500
501 if (!AS.isValidOffsetForDataOfSize(Offset, Hdr.AbbrevTableSize))
502 return make_error<StringError>(
503 "Section too small: cannot read abbreviations.",
504 inconvertibleErrorCode());
505
506 EntriesBase = Offset + Hdr.AbbrevTableSize;
507
508 for (;;) {
509 auto AbbrevOr = extractAbbrev(&Offset);
510 if (!AbbrevOr)
511 return AbbrevOr.takeError();
512 if (isSentinel(*AbbrevOr))
513 return Error::success();
514
515 if (!Abbrevs.insert(std::move(*AbbrevOr)).second) {
516 return make_error<StringError>("Duplicate abbreviation code.",
517 inconvertibleErrorCode());
518 }
519 }
520}
Pavel Labathd99072b2018-02-24 00:35:21 +0000521DWARFDebugNames::Entry::Entry(const NameIndex &NameIdx, const Abbrev &Abbr)
522 : NameIdx(&NameIdx), Abbr(&Abbr) {
Pavel Labath3c9a9182018-01-29 11:08:32 +0000523 // This merely creates form values. It is up to the caller
524 // (NameIndex::getEntry) to populate them.
525 Values.reserve(Abbr.Attributes.size());
526 for (const auto &Attr : Abbr.Attributes)
527 Values.emplace_back(Attr.Form);
528}
529
Pavel Labathd99072b2018-02-24 00:35:21 +0000530Optional<DWARFFormValue>
531DWARFDebugNames::Entry::lookup(dwarf::Index Index) const {
532 assert(Abbr->Attributes.size() == Values.size());
533 for (const auto &Tuple : zip_first(Abbr->Attributes, Values)) {
534 if (std::get<0>(Tuple).Index == Index)
535 return std::get<1>(Tuple);
536 }
537 return None;
538}
Pavel Labath3c9a9182018-01-29 11:08:32 +0000539
Pavel Labathd99072b2018-02-24 00:35:21 +0000540Optional<uint64_t> DWARFDebugNames::Entry::getDIEOffset() const {
541 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_die_offset))
542 return Off->getAsSectionOffset();
543 return None;
544}
545
546Optional<uint64_t> DWARFDebugNames::Entry::getCUIndex() const {
547 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_compile_unit))
548 return Off->getAsUnsignedConstant();
549 return None;
550}
551
552Optional<uint64_t> DWARFDebugNames::Entry::getCUOffset() const {
553 Optional<uint64_t> Index = getCUIndex();
554 if (!Index || *Index >= NameIdx->getCUCount())
555 return None;
556 return NameIdx->getCUOffset(*Index);
557}
558
559void DWARFDebugNames::Entry::dump(ScopedPrinter &W) const {
560 W.printHex("Abbrev", Abbr->Code);
561 W.startLine() << "Tag: " << formatTag(Abbr->Tag) << "\n";
562
563 assert(Abbr->Attributes.size() == Values.size());
564 for (const auto &Tuple : zip_first(Abbr->Attributes, Values)) {
565 W.startLine() << formatIndex(std::get<0>(Tuple).Index) << ": ";
566 std::get<1>(Tuple).dump(W.getOStream());
Pavel Labath3c9a9182018-01-29 11:08:32 +0000567 W.getOStream() << '\n';
568 }
569}
570
571char DWARFDebugNames::SentinelError::ID;
572std::error_code DWARFDebugNames::SentinelError::convertToErrorCode() const {
573 return inconvertibleErrorCode();
574}
575
576uint32_t DWARFDebugNames::NameIndex::getCUOffset(uint32_t CU) const {
577 assert(CU < Hdr.CompUnitCount);
578 uint32_t Offset = CUsBase + 4 * CU;
579 return Section.AccelSection.getRelocatedValue(4, &Offset);
580}
581
582uint32_t DWARFDebugNames::NameIndex::getLocalTUOffset(uint32_t TU) const {
583 assert(TU < Hdr.LocalTypeUnitCount);
584 uint32_t Offset = CUsBase + Hdr.CompUnitCount * 4;
585 return Section.AccelSection.getRelocatedValue(4, &Offset);
586}
587
Pavel Labathd99072b2018-02-24 00:35:21 +0000588uint64_t DWARFDebugNames::NameIndex::getForeignTUSignature(uint32_t TU) const {
Pavel Labath3c9a9182018-01-29 11:08:32 +0000589 assert(TU < Hdr.ForeignTypeUnitCount);
590 uint32_t Offset = CUsBase + (Hdr.CompUnitCount + Hdr.LocalTypeUnitCount) * 4;
591 return Section.AccelSection.getU64(&Offset);
592}
593
594Expected<DWARFDebugNames::Entry>
595DWARFDebugNames::NameIndex::getEntry(uint32_t *Offset) const {
596 const DWARFDataExtractor &AS = Section.AccelSection;
597 if (!AS.isValidOffset(*Offset))
598 return make_error<StringError>("Incorrectly terminated entry list",
599 inconvertibleErrorCode());
600
601 uint32_t AbbrevCode = AS.getULEB128(Offset);
602 if (AbbrevCode == 0)
603 return make_error<SentinelError>();
604
605 const auto AbbrevIt = Abbrevs.find_as(AbbrevCode);
606 if (AbbrevIt == Abbrevs.end())
607 return make_error<StringError>("Invalid abbreviation",
608 inconvertibleErrorCode());
609
Pavel Labathd99072b2018-02-24 00:35:21 +0000610 Entry E(*this, *AbbrevIt);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000611
612 DWARFFormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
613 for (auto &Value : E.Values) {
614 if (!Value.extractValue(AS, Offset, FormParams))
615 return make_error<StringError>("Error extracting index attribute values",
616 inconvertibleErrorCode());
617 }
618 return std::move(E);
619}
620
621DWARFDebugNames::NameTableEntry
622DWARFDebugNames::NameIndex::getNameTableEntry(uint32_t Index) const {
623 assert(0 < Index && Index <= Hdr.NameCount);
624 uint32_t StringOffsetOffset = StringOffsetsBase + 4 * (Index - 1);
625 uint32_t EntryOffsetOffset = EntryOffsetsBase + 4 * (Index - 1);
626 const DWARFDataExtractor &AS = Section.AccelSection;
627
628 uint32_t StringOffset = AS.getRelocatedValue(4, &StringOffsetOffset);
629 uint32_t EntryOffset = AS.getU32(&EntryOffsetOffset);
630 EntryOffset += EntriesBase;
631 return {StringOffset, EntryOffset};
632}
633
634uint32_t
635DWARFDebugNames::NameIndex::getBucketArrayEntry(uint32_t Bucket) const {
636 assert(Bucket < Hdr.BucketCount);
637 uint32_t BucketOffset = BucketsBase + 4 * Bucket;
638 return Section.AccelSection.getU32(&BucketOffset);
639}
640
641uint32_t DWARFDebugNames::NameIndex::getHashArrayEntry(uint32_t Index) const {
642 assert(0 < Index && Index <= Hdr.NameCount);
643 uint32_t HashOffset = HashesBase + 4 * (Index - 1);
644 return Section.AccelSection.getU32(&HashOffset);
645}
646
647// Returns true if we should continue scanning for entries, false if this is the
648// last (sentinel) entry). In case of a parsing error we also return false, as
649// it's not possible to recover this entry list (but the other lists may still
650// parse OK).
651bool DWARFDebugNames::NameIndex::dumpEntry(ScopedPrinter &W,
652 uint32_t *Offset) const {
653 uint32_t EntryId = *Offset;
654 auto EntryOr = getEntry(Offset);
655 if (!EntryOr) {
656 handleAllErrors(EntryOr.takeError(), [](const SentinelError &) {},
657 [&W](const ErrorInfoBase &EI) { EI.log(W.startLine()); });
658 return false;
659 }
660
661 DictScope EntryScope(W, ("Entry @ 0x" + Twine::utohexstr(EntryId)).str());
662 EntryOr->dump(W);
663 return true;
664}
665
666void DWARFDebugNames::NameIndex::dumpName(ScopedPrinter &W, uint32_t Index,
667 Optional<uint32_t> Hash) const {
668 const DataExtractor &SS = Section.StringSection;
669 NameTableEntry NTE = getNameTableEntry(Index);
670
671 DictScope NameScope(W, ("Name " + Twine(Index)).str());
672 if (Hash)
673 W.printHex("Hash", *Hash);
674
675 W.startLine() << format("String: 0x%08x", NTE.StringOffset);
676 W.getOStream() << " \"" << SS.getCStr(&NTE.StringOffset) << "\"\n";
677
678 while (dumpEntry(W, &NTE.EntryOffset))
679 /*empty*/;
680}
681
682void DWARFDebugNames::NameIndex::dumpCUs(ScopedPrinter &W) const {
683 ListScope CUScope(W, "Compilation Unit offsets");
684 for (uint32_t CU = 0; CU < Hdr.CompUnitCount; ++CU)
685 W.startLine() << format("CU[%u]: 0x%08x\n", CU, getCUOffset(CU));
686}
687
688void DWARFDebugNames::NameIndex::dumpLocalTUs(ScopedPrinter &W) const {
689 if (Hdr.LocalTypeUnitCount == 0)
690 return;
691
692 ListScope TUScope(W, "Local Type Unit offsets");
693 for (uint32_t TU = 0; TU < Hdr.LocalTypeUnitCount; ++TU)
694 W.startLine() << format("LocalTU[%u]: 0x%08x\n", TU, getLocalTUOffset(TU));
695}
696
697void DWARFDebugNames::NameIndex::dumpForeignTUs(ScopedPrinter &W) const {
698 if (Hdr.ForeignTypeUnitCount == 0)
699 return;
700
701 ListScope TUScope(W, "Foreign Type Unit signatures");
702 for (uint32_t TU = 0; TU < Hdr.ForeignTypeUnitCount; ++TU) {
703 W.startLine() << format("ForeignTU[%u]: 0x%016" PRIx64 "\n", TU,
Pavel Labathd99072b2018-02-24 00:35:21 +0000704 getForeignTUSignature(TU));
Pavel Labath3c9a9182018-01-29 11:08:32 +0000705 }
706}
707
708void DWARFDebugNames::NameIndex::dumpAbbreviations(ScopedPrinter &W) const {
709 ListScope AbbrevsScope(W, "Abbreviations");
710 for (const auto &Abbr : Abbrevs)
711 Abbr.dump(W);
712}
713
714void DWARFDebugNames::NameIndex::dumpBucket(ScopedPrinter &W,
715 uint32_t Bucket) const {
716 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
717 uint32_t Index = getBucketArrayEntry(Bucket);
718 if (Index == 0) {
719 W.printString("EMPTY");
720 return;
721 }
722 if (Index > Hdr.NameCount) {
723 W.printString("Name index is invalid");
724 return;
725 }
726
727 for (; Index <= Hdr.NameCount; ++Index) {
728 uint32_t Hash = getHashArrayEntry(Index);
729 if (Hash % Hdr.BucketCount != Bucket)
730 break;
731
732 dumpName(W, Index, Hash);
733 }
734}
735
736LLVM_DUMP_METHOD void DWARFDebugNames::NameIndex::dump(ScopedPrinter &W) const {
737 DictScope UnitScope(W, ("Name Index @ 0x" + Twine::utohexstr(Base)).str());
738 Hdr.dump(W);
739 dumpCUs(W);
740 dumpLocalTUs(W);
741 dumpForeignTUs(W);
742 dumpAbbreviations(W);
743
744 if (Hdr.BucketCount > 0) {
745 for (uint32_t Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket)
746 dumpBucket(W, Bucket);
747 return;
748 }
749
750 W.startLine() << "Hash table not present\n";
751 for (uint32_t Index = 1; Index <= Hdr.NameCount; ++Index)
752 dumpName(W, Index, None);
753}
754
755llvm::Error DWARFDebugNames::extract() {
756 uint32_t Offset = 0;
757 while (AccelSection.isValidOffset(Offset)) {
758 NameIndex Next(*this, Offset);
759 if (llvm::Error E = Next.extract())
760 return E;
761 Offset = Next.getNextUnitOffset();
762 NameIndices.push_back(std::move(Next));
763 }
764 return Error::success();
765}
766
767LLVM_DUMP_METHOD void DWARFDebugNames::dump(raw_ostream &OS) const {
768 ScopedPrinter W(OS);
769 for (const NameIndex &NI : NameIndices)
770 NI.dump(W);
771}
Pavel Labathd99072b2018-02-24 00:35:21 +0000772
773Optional<uint32_t>
774DWARFDebugNames::ValueIterator::findEntryOffsetInCurrentIndex() {
775 const Header &Hdr = CurrentIndex->Hdr;
776 if (Hdr.BucketCount == 0) {
777 // No Hash Table, We need to search through all names in the Name Index.
778 for (uint32_t Index = 1; Index <= Hdr.NameCount; ++Index) {
779 NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
780 if (CurrentIndex->Section.StringSection.getCStr(&NTE.StringOffset) == Key)
781 return NTE.EntryOffset;
782 }
783 return None;
784 }
785
786 // The Name Index has a Hash Table, so use that to speed up the search.
787 // Compute the Key Hash, if it has not been done already.
788 if (!Hash)
789 Hash = caseFoldingDjbHash(Key);
790 uint32_t Bucket = *Hash % Hdr.BucketCount;
791 uint32_t Index = CurrentIndex->getBucketArrayEntry(Bucket);
792 if (Index == 0)
793 return None; // Empty bucket
794
795 for (; Index <= Hdr.NameCount; ++Index) {
796 uint32_t Hash = CurrentIndex->getHashArrayEntry(Index);
797 if (Hash % Hdr.BucketCount != Bucket)
798 return None; // End of bucket
799
800 NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
801 if (CurrentIndex->Section.StringSection.getCStr(&NTE.StringOffset) == Key)
802 return NTE.EntryOffset;
803 }
804 return None;
805}
806
807bool DWARFDebugNames::ValueIterator::getEntryAtCurrentOffset() {
808 auto EntryOr = CurrentIndex->getEntry(&DataOffset);
809 if (!EntryOr) {
810 consumeError(EntryOr.takeError());
811 return false;
812 }
813 CurrentEntry = std::move(*EntryOr);
814 return true;
815}
816
817bool DWARFDebugNames::ValueIterator::findInCurrentIndex() {
818 Optional<uint32_t> Offset = findEntryOffsetInCurrentIndex();
819 if (!Offset)
820 return false;
821 DataOffset = *Offset;
822 return getEntryAtCurrentOffset();
823}
824
825void DWARFDebugNames::ValueIterator::searchFromStartOfCurrentIndex() {
826 for (const NameIndex *End = CurrentIndex->Section.NameIndices.end();
827 CurrentIndex != End; ++CurrentIndex) {
828 if (findInCurrentIndex())
829 return;
830 }
831 setEnd();
832}
833
834void DWARFDebugNames::ValueIterator::next() {
835 assert(CurrentIndex && "Incrementing an end() iterator?");
836
837 // First try the next entry in the current Index.
838 if (getEntryAtCurrentOffset())
839 return;
840
841 // Try the next Name Index.
842 ++CurrentIndex;
843 searchFromStartOfCurrentIndex();
844}
845
846DWARFDebugNames::ValueIterator::ValueIterator(const DWARFDebugNames &AccelTable,
847 StringRef Key)
848 : CurrentIndex(AccelTable.NameIndices.begin()), Key(Key) {
849 searchFromStartOfCurrentIndex();
850}
851
852iterator_range<DWARFDebugNames::ValueIterator>
853DWARFDebugNames::equal_range(StringRef Key) const {
854 if (NameIndices.empty())
855 return make_range(ValueIterator(), ValueIterator());
856 return make_range(ValueIterator(*this, Key), ValueIterator());
857}