blob: 4771d213741547031ce33aa6e3280ae96d4aef08 [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
Pavel Labath47c34722018-03-09 11:58:59 +0000162Optional<uint64_t> AppleAcceleratorTable::HeaderData::extractOffset(
163 Optional<DWARFFormValue> Value) const {
164 if (!Value)
165 return None;
166
167 switch (Value->getForm()) {
168 case dwarf::DW_FORM_ref1:
169 case dwarf::DW_FORM_ref2:
170 case dwarf::DW_FORM_ref4:
171 case dwarf::DW_FORM_ref8:
172 case dwarf::DW_FORM_ref_udata:
173 return Value->getRawUValue() + DIEOffsetBase;
174 default:
175 return Value->getAsSectionOffset();
176 }
177}
178
Pavel Labath394e8052018-01-29 11:33:17 +0000179bool AppleAcceleratorTable::dumpName(ScopedPrinter &W,
180 SmallVectorImpl<DWARFFormValue> &AtomForms,
181 uint32_t *DataOffset) const {
182 DWARFFormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
183 uint32_t NameOffset = *DataOffset;
184 if (!AccelSection.isValidOffsetForDataOfSize(*DataOffset, 4)) {
185 W.printString("Incorrectly terminated list.");
186 return false;
187 }
188 unsigned StringOffset = AccelSection.getRelocatedValue(4, DataOffset);
189 if (!StringOffset)
190 return false; // End of list
191
192 DictScope NameScope(W, ("Name@0x" + Twine::utohexstr(NameOffset)).str());
193 W.startLine() << format("String: 0x%08x", StringOffset);
194 W.getOStream() << " \"" << StringSection.getCStr(&StringOffset) << "\"\n";
195
196 unsigned NumData = AccelSection.getU32(DataOffset);
197 for (unsigned Data = 0; Data < NumData; ++Data) {
198 ListScope DataScope(W, ("Data " + Twine(Data)).str());
199 unsigned i = 0;
200 for (auto &Atom : AtomForms) {
201 W.startLine() << format("Atom[%d]: ", i++);
202 if (Atom.extractValue(AccelSection, DataOffset, FormParams))
203 Atom.dump(W.getOStream());
204 else
205 W.getOStream() << "Error extracting the value";
206 W.getOStream() << "\n";
207 }
208 }
209 return true; // more entries follow
210}
211
Pavel Labath9b36fd22018-01-22 13:17:23 +0000212LLVM_DUMP_METHOD void AppleAcceleratorTable::dump(raw_ostream &OS) const {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000213 if (!IsValid)
214 return;
215
Pavel Labath394e8052018-01-29 11:33:17 +0000216 ScopedPrinter W(OS);
Frederic Risse837ec22014-11-14 16:15:53 +0000217
Pavel Labath394e8052018-01-29 11:33:17 +0000218 Hdr.dump(W);
219
220 W.printNumber("DIE offset base", HdrData.DIEOffsetBase);
Pavel Labath34609572018-01-29 11:53:46 +0000221 W.printNumber("Number of atoms", uint64_t(HdrData.Atoms.size()));
Frederic Riss77a07432014-11-20 16:21:11 +0000222 SmallVector<DWARFFormValue, 3> AtomForms;
Pavel Labath394e8052018-01-29 11:33:17 +0000223 {
224 ListScope AtomsScope(W, "Atoms");
225 unsigned i = 0;
226 for (const auto &Atom : HdrData.Atoms) {
227 DictScope AtomScope(W, ("Atom " + Twine(i++)).str());
228 W.startLine() << "Type: " << formatAtom(Atom.first) << '\n';
229 W.startLine() << "Form: " << formatForm(Atom.second) << '\n';
230 AtomForms.push_back(DWARFFormValue(Atom.second));
231 }
Frederic Risse837ec22014-11-14 16:15:53 +0000232 }
233
234 // Now go through the actual tables and dump them.
235 uint32_t Offset = sizeof(Hdr) + Hdr.HeaderDataLength;
Pavel Labath394e8052018-01-29 11:33:17 +0000236 unsigned HashesBase = Offset + Hdr.BucketCount * 4;
237 unsigned OffsetsBase = HashesBase + Hdr.HashCount * 4;
Frederic Risse837ec22014-11-14 16:15:53 +0000238
Pavel Labath394e8052018-01-29 11:33:17 +0000239 for (unsigned Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket) {
Frederic Risse837ec22014-11-14 16:15:53 +0000240 unsigned Index = AccelSection.getU32(&Offset);
241
Pavel Labath394e8052018-01-29 11:33:17 +0000242 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
Frederic Risse837ec22014-11-14 16:15:53 +0000243 if (Index == UINT32_MAX) {
Pavel Labath394e8052018-01-29 11:33:17 +0000244 W.printString("EMPTY");
Frederic Risse837ec22014-11-14 16:15:53 +0000245 continue;
246 }
247
Pavel Labath394e8052018-01-29 11:33:17 +0000248 for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
Frederic Risse837ec22014-11-14 16:15:53 +0000249 unsigned HashOffset = HashesBase + HashIdx*4;
250 unsigned OffsetsOffset = OffsetsBase + HashIdx*4;
251 uint32_t Hash = AccelSection.getU32(&HashOffset);
252
Pavel Labath394e8052018-01-29 11:33:17 +0000253 if (Hash % Hdr.BucketCount != Bucket)
Frederic Risse837ec22014-11-14 16:15:53 +0000254 break;
255
256 unsigned DataOffset = AccelSection.getU32(&OffsetsOffset);
Pavel Labath394e8052018-01-29 11:33:17 +0000257 ListScope HashScope(W, ("Hash 0x" + Twine::utohexstr(Hash)).str());
Frederic Risse837ec22014-11-14 16:15:53 +0000258 if (!AccelSection.isValidOffset(DataOffset)) {
Pavel Labath394e8052018-01-29 11:33:17 +0000259 W.printString("Invalid section offset");
Frederic Risse837ec22014-11-14 16:15:53 +0000260 continue;
261 }
Pavel Labath394e8052018-01-29 11:33:17 +0000262 while (dumpName(W, AtomForms, &DataOffset))
263 /*empty*/;
Frederic Risse837ec22014-11-14 16:15:53 +0000264 }
265 }
266}
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000267
Pavel Labathd99072b2018-02-24 00:35:21 +0000268AppleAcceleratorTable::Entry::Entry(
269 const AppleAcceleratorTable::HeaderData &HdrData)
270 : HdrData(&HdrData) {
271 Values.reserve(HdrData.Atoms.size());
272 for (const auto &Atom : HdrData.Atoms)
273 Values.push_back(DWARFFormValue(Atom.second));
274}
275
276void AppleAcceleratorTable::Entry::extract(
277 const AppleAcceleratorTable &AccelTable, uint32_t *Offset) {
278
279 DWARFFormParams FormParams = {AccelTable.Hdr.Version, 0,
280 dwarf::DwarfFormat::DWARF32};
281 for (auto &Atom : Values)
282 Atom.extractValue(AccelTable.AccelSection, Offset, FormParams);
283}
284
285Optional<DWARFFormValue>
286AppleAcceleratorTable::Entry::lookup(HeaderData::AtomType Atom) const {
287 assert(HdrData && "Dereferencing end iterator?");
288 assert(HdrData->Atoms.size() == Values.size());
289 for (const auto &Tuple : zip_first(HdrData->Atoms, Values)) {
290 if (std::get<0>(Tuple).first == Atom)
291 return std::get<1>(Tuple);
292 }
293 return None;
294}
295
Pavel Labath47c34722018-03-09 11:58:59 +0000296Optional<uint64_t> AppleAcceleratorTable::Entry::getDIESectionOffset() const {
297 return HdrData->extractOffset(lookup(dwarf::DW_ATOM_die_offset));
Pavel Labathd99072b2018-02-24 00:35:21 +0000298}
299
300Optional<uint64_t> AppleAcceleratorTable::Entry::getCUOffset() const {
Pavel Labath47c34722018-03-09 11:58:59 +0000301 return HdrData->extractOffset(lookup(dwarf::DW_ATOM_cu_offset));
Pavel Labathd99072b2018-02-24 00:35:21 +0000302}
303
304Optional<dwarf::Tag> AppleAcceleratorTable::Entry::getTag() const {
305 Optional<DWARFFormValue> Tag = lookup(dwarf::DW_ATOM_die_tag);
306 if (!Tag)
307 return None;
308 if (Optional<uint64_t> Value = Tag->getAsUnsignedConstant())
309 return dwarf::Tag(*Value);
310 return None;
311}
312
Pavel Labath9b36fd22018-01-22 13:17:23 +0000313AppleAcceleratorTable::ValueIterator::ValueIterator(
314 const AppleAcceleratorTable &AccelTable, unsigned Offset)
Pavel Labathd99072b2018-02-24 00:35:21 +0000315 : AccelTable(&AccelTable), Current(AccelTable.HdrData), DataOffset(Offset) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000316 if (!AccelTable.AccelSection.isValidOffsetForDataOfSize(DataOffset, 4))
317 return;
318
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000319 // Read the first entry.
320 NumData = AccelTable.AccelSection.getU32(&DataOffset);
321 Next();
322}
323
Pavel Labath9b36fd22018-01-22 13:17:23 +0000324void AppleAcceleratorTable::ValueIterator::Next() {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000325 assert(NumData > 0 && "attempted to increment iterator past the end");
326 auto &AccelSection = AccelTable->AccelSection;
327 if (Data >= NumData ||
328 !AccelSection.isValidOffsetForDataOfSize(DataOffset, 4)) {
329 NumData = 0;
330 return;
331 }
Pavel Labathd99072b2018-02-24 00:35:21 +0000332 Current.extract(*AccelTable, &DataOffset);
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000333 ++Data;
334}
335
Pavel Labath9b36fd22018-01-22 13:17:23 +0000336iterator_range<AppleAcceleratorTable::ValueIterator>
337AppleAcceleratorTable::equal_range(StringRef Key) const {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000338 if (!IsValid)
339 return make_range(ValueIterator(), ValueIterator());
340
341 // Find the bucket.
Jonas Devlieghere92ac9d32018-01-28 11:05:10 +0000342 unsigned HashValue = djbHash(Key);
Pavel Labath394e8052018-01-29 11:33:17 +0000343 unsigned Bucket = HashValue % Hdr.BucketCount;
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000344 unsigned BucketBase = sizeof(Hdr) + Hdr.HeaderDataLength;
Pavel Labath394e8052018-01-29 11:33:17 +0000345 unsigned HashesBase = BucketBase + Hdr.BucketCount * 4;
346 unsigned OffsetsBase = HashesBase + Hdr.HashCount * 4;
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000347
348 unsigned BucketOffset = BucketBase + Bucket * 4;
349 unsigned Index = AccelSection.getU32(&BucketOffset);
350
351 // Search through all hashes in the bucket.
Pavel Labath394e8052018-01-29 11:33:17 +0000352 for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000353 unsigned HashOffset = HashesBase + HashIdx * 4;
354 unsigned OffsetsOffset = OffsetsBase + HashIdx * 4;
355 uint32_t Hash = AccelSection.getU32(&HashOffset);
356
Pavel Labath394e8052018-01-29 11:33:17 +0000357 if (Hash % Hdr.BucketCount != Bucket)
Adrian Prantl99fdb9d2017-09-28 18:10:52 +0000358 // We are already in the next bucket.
359 break;
360
361 unsigned DataOffset = AccelSection.getU32(&OffsetsOffset);
362 unsigned StringOffset = AccelSection.getRelocatedValue(4, &DataOffset);
363 if (!StringOffset)
364 break;
365
366 // Finally, compare the key.
367 if (Key == StringSection.getCStr(&StringOffset))
368 return make_range({*this, DataOffset}, ValueIterator());
369 }
370 return make_range(ValueIterator(), ValueIterator());
371}
Pavel Labath3c9a9182018-01-29 11:08:32 +0000372
373void DWARFDebugNames::Header::dump(ScopedPrinter &W) const {
374 DictScope HeaderScope(W, "Header");
375 W.printHex("Length", UnitLength);
376 W.printNumber("Version", Version);
377 W.printHex("Padding", Padding);
378 W.printNumber("CU count", CompUnitCount);
379 W.printNumber("Local TU count", LocalTypeUnitCount);
380 W.printNumber("Foreign TU count", ForeignTypeUnitCount);
381 W.printNumber("Bucket count", BucketCount);
382 W.printNumber("Name count", NameCount);
383 W.printHex("Abbreviations table size", AbbrevTableSize);
384 W.startLine() << "Augmentation: '" << AugmentationString << "'\n";
385}
386
387llvm::Error DWARFDebugNames::Header::extract(const DWARFDataExtractor &AS,
388 uint32_t *Offset) {
389 // Check that we can read the fixed-size part.
Pavel Labathe7264102018-01-29 13:53:48 +0000390 if (!AS.isValidOffset(*Offset + sizeof(HeaderPOD) - 1))
Pavel Labath3c9a9182018-01-29 11:08:32 +0000391 return make_error<StringError>("Section too small: cannot read header.",
392 inconvertibleErrorCode());
393
394 UnitLength = AS.getU32(Offset);
395 Version = AS.getU16(Offset);
396 Padding = AS.getU16(Offset);
397 CompUnitCount = AS.getU32(Offset);
398 LocalTypeUnitCount = AS.getU32(Offset);
399 ForeignTypeUnitCount = AS.getU32(Offset);
400 BucketCount = AS.getU32(Offset);
401 NameCount = AS.getU32(Offset);
402 AbbrevTableSize = AS.getU32(Offset);
403 AugmentationStringSize = AS.getU32(Offset);
404
405 if (!AS.isValidOffsetForDataOfSize(*Offset, AugmentationStringSize))
406 return make_error<StringError>(
407 "Section too small: cannot read header augmentation.",
408 inconvertibleErrorCode());
409 AugmentationString.resize(AugmentationStringSize);
410 AS.getU8(Offset, reinterpret_cast<uint8_t *>(AugmentationString.data()),
411 AugmentationStringSize);
412 *Offset = alignTo(*Offset, 4);
413 return Error::success();
414}
415
416void DWARFDebugNames::Abbrev::dump(ScopedPrinter &W) const {
417 DictScope AbbrevScope(W, ("Abbreviation 0x" + Twine::utohexstr(Code)).str());
418 W.startLine() << "Tag: " << formatTag(Tag) << '\n';
419
420 for (const auto &Attr : Attributes) {
421 W.startLine() << formatIndex(Attr.Index) << ": " << formatForm(Attr.Form)
422 << '\n';
423 }
424}
425
426static constexpr DWARFDebugNames::AttributeEncoding sentinelAttrEnc() {
427 return {dwarf::Index(0), dwarf::Form(0)};
428}
429
430static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE) {
431 return AE == sentinelAttrEnc();
432}
433
434static DWARFDebugNames::Abbrev sentinelAbbrev() {
435 return DWARFDebugNames::Abbrev(0, dwarf::Tag(0), {});
436}
437
438static bool isSentinel(const DWARFDebugNames::Abbrev &Abbr) {
439 return Abbr.Code == 0;
440}
441
442DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getEmptyKey() {
443 return sentinelAbbrev();
444}
445
446DWARFDebugNames::Abbrev DWARFDebugNames::AbbrevMapInfo::getTombstoneKey() {
447 return DWARFDebugNames::Abbrev(~0, dwarf::Tag(0), {});
448}
449
450Expected<DWARFDebugNames::AttributeEncoding>
451DWARFDebugNames::NameIndex::extractAttributeEncoding(uint32_t *Offset) {
452 if (*Offset >= EntriesBase) {
453 return make_error<StringError>("Incorrectly terminated abbreviation table.",
454 inconvertibleErrorCode());
455 }
456
457 uint32_t Index = Section.AccelSection.getULEB128(Offset);
458 uint32_t Form = Section.AccelSection.getULEB128(Offset);
459 return AttributeEncoding(dwarf::Index(Index), dwarf::Form(Form));
460}
461
462Expected<std::vector<DWARFDebugNames::AttributeEncoding>>
463DWARFDebugNames::NameIndex::extractAttributeEncodings(uint32_t *Offset) {
464 std::vector<AttributeEncoding> Result;
465 for (;;) {
466 auto AttrEncOr = extractAttributeEncoding(Offset);
467 if (!AttrEncOr)
468 return AttrEncOr.takeError();
469 if (isSentinel(*AttrEncOr))
470 return std::move(Result);
471
472 Result.emplace_back(*AttrEncOr);
473 }
474}
475
476Expected<DWARFDebugNames::Abbrev>
477DWARFDebugNames::NameIndex::extractAbbrev(uint32_t *Offset) {
478 if (*Offset >= EntriesBase) {
479 return make_error<StringError>("Incorrectly terminated abbreviation table.",
480 inconvertibleErrorCode());
481 }
482
483 uint32_t Code = Section.AccelSection.getULEB128(Offset);
484 if (Code == 0)
485 return sentinelAbbrev();
486
487 uint32_t Tag = Section.AccelSection.getULEB128(Offset);
488 auto AttrEncOr = extractAttributeEncodings(Offset);
489 if (!AttrEncOr)
490 return AttrEncOr.takeError();
491 return Abbrev(Code, dwarf::Tag(Tag), std::move(*AttrEncOr));
492}
493
494Error DWARFDebugNames::NameIndex::extract() {
495 const DWARFDataExtractor &AS = Section.AccelSection;
496 uint32_t Offset = Base;
497 if (Error E = Hdr.extract(AS, &Offset))
498 return E;
499
500 CUsBase = Offset;
501 Offset += Hdr.CompUnitCount * 4;
502 Offset += Hdr.LocalTypeUnitCount * 4;
503 Offset += Hdr.ForeignTypeUnitCount * 8;
504 BucketsBase = Offset;
505 Offset += Hdr.BucketCount * 4;
506 HashesBase = Offset;
507 if (Hdr.BucketCount > 0)
508 Offset += Hdr.NameCount * 4;
509 StringOffsetsBase = Offset;
510 Offset += Hdr.NameCount * 4;
511 EntryOffsetsBase = Offset;
512 Offset += Hdr.NameCount * 4;
513
514 if (!AS.isValidOffsetForDataOfSize(Offset, Hdr.AbbrevTableSize))
515 return make_error<StringError>(
516 "Section too small: cannot read abbreviations.",
517 inconvertibleErrorCode());
518
519 EntriesBase = Offset + Hdr.AbbrevTableSize;
520
521 for (;;) {
522 auto AbbrevOr = extractAbbrev(&Offset);
523 if (!AbbrevOr)
524 return AbbrevOr.takeError();
525 if (isSentinel(*AbbrevOr))
526 return Error::success();
527
528 if (!Abbrevs.insert(std::move(*AbbrevOr)).second) {
529 return make_error<StringError>("Duplicate abbreviation code.",
530 inconvertibleErrorCode());
531 }
532 }
533}
Pavel Labathd99072b2018-02-24 00:35:21 +0000534DWARFDebugNames::Entry::Entry(const NameIndex &NameIdx, const Abbrev &Abbr)
535 : NameIdx(&NameIdx), Abbr(&Abbr) {
Pavel Labath3c9a9182018-01-29 11:08:32 +0000536 // This merely creates form values. It is up to the caller
537 // (NameIndex::getEntry) to populate them.
538 Values.reserve(Abbr.Attributes.size());
539 for (const auto &Attr : Abbr.Attributes)
540 Values.emplace_back(Attr.Form);
541}
542
Pavel Labathd99072b2018-02-24 00:35:21 +0000543Optional<DWARFFormValue>
544DWARFDebugNames::Entry::lookup(dwarf::Index Index) const {
545 assert(Abbr->Attributes.size() == Values.size());
546 for (const auto &Tuple : zip_first(Abbr->Attributes, Values)) {
547 if (std::get<0>(Tuple).Index == Index)
548 return std::get<1>(Tuple);
549 }
550 return None;
551}
Pavel Labath3c9a9182018-01-29 11:08:32 +0000552
Pavel Labath47c34722018-03-09 11:58:59 +0000553Optional<uint64_t> DWARFDebugNames::Entry::getDIEUnitOffset() const {
Pavel Labathd99072b2018-02-24 00:35:21 +0000554 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_die_offset))
555 return Off->getAsSectionOffset();
556 return None;
557}
558
559Optional<uint64_t> DWARFDebugNames::Entry::getCUIndex() const {
560 if (Optional<DWARFFormValue> Off = lookup(dwarf::DW_IDX_compile_unit))
561 return Off->getAsUnsignedConstant();
Pavel Labath47c34722018-03-09 11:58:59 +0000562 // In a per-CU index, the entries without a DW_IDX_compile_unit attribute
563 // implicitly refer to the single CU.
564 if (NameIdx->getCUCount() == 1)
565 return 0;
Pavel Labathd99072b2018-02-24 00:35:21 +0000566 return None;
567}
568
569Optional<uint64_t> DWARFDebugNames::Entry::getCUOffset() const {
570 Optional<uint64_t> Index = getCUIndex();
571 if (!Index || *Index >= NameIdx->getCUCount())
572 return None;
573 return NameIdx->getCUOffset(*Index);
574}
575
Pavel Labath47c34722018-03-09 11:58:59 +0000576Optional<uint64_t> DWARFDebugNames::Entry::getDIESectionOffset() const {
577 Optional<uint64_t> CUOff = getCUOffset();
578 Optional<uint64_t> DIEOff = getDIEUnitOffset();
579 if (CUOff && DIEOff)
580 return *CUOff + *DIEOff;
581 return None;
582}
583
Pavel Labathd99072b2018-02-24 00:35:21 +0000584void DWARFDebugNames::Entry::dump(ScopedPrinter &W) const {
585 W.printHex("Abbrev", Abbr->Code);
586 W.startLine() << "Tag: " << formatTag(Abbr->Tag) << "\n";
587
588 assert(Abbr->Attributes.size() == Values.size());
589 for (const auto &Tuple : zip_first(Abbr->Attributes, Values)) {
590 W.startLine() << formatIndex(std::get<0>(Tuple).Index) << ": ";
591 std::get<1>(Tuple).dump(W.getOStream());
Pavel Labath3c9a9182018-01-29 11:08:32 +0000592 W.getOStream() << '\n';
593 }
594}
595
596char DWARFDebugNames::SentinelError::ID;
597std::error_code DWARFDebugNames::SentinelError::convertToErrorCode() const {
598 return inconvertibleErrorCode();
599}
600
601uint32_t DWARFDebugNames::NameIndex::getCUOffset(uint32_t CU) const {
602 assert(CU < Hdr.CompUnitCount);
603 uint32_t Offset = CUsBase + 4 * CU;
604 return Section.AccelSection.getRelocatedValue(4, &Offset);
605}
606
607uint32_t DWARFDebugNames::NameIndex::getLocalTUOffset(uint32_t TU) const {
608 assert(TU < Hdr.LocalTypeUnitCount);
609 uint32_t Offset = CUsBase + Hdr.CompUnitCount * 4;
610 return Section.AccelSection.getRelocatedValue(4, &Offset);
611}
612
Pavel Labathd99072b2018-02-24 00:35:21 +0000613uint64_t DWARFDebugNames::NameIndex::getForeignTUSignature(uint32_t TU) const {
Pavel Labath3c9a9182018-01-29 11:08:32 +0000614 assert(TU < Hdr.ForeignTypeUnitCount);
615 uint32_t Offset = CUsBase + (Hdr.CompUnitCount + Hdr.LocalTypeUnitCount) * 4;
616 return Section.AccelSection.getU64(&Offset);
617}
618
619Expected<DWARFDebugNames::Entry>
620DWARFDebugNames::NameIndex::getEntry(uint32_t *Offset) const {
621 const DWARFDataExtractor &AS = Section.AccelSection;
622 if (!AS.isValidOffset(*Offset))
623 return make_error<StringError>("Incorrectly terminated entry list",
624 inconvertibleErrorCode());
625
626 uint32_t AbbrevCode = AS.getULEB128(Offset);
627 if (AbbrevCode == 0)
628 return make_error<SentinelError>();
629
630 const auto AbbrevIt = Abbrevs.find_as(AbbrevCode);
631 if (AbbrevIt == Abbrevs.end())
632 return make_error<StringError>("Invalid abbreviation",
633 inconvertibleErrorCode());
634
Pavel Labathd99072b2018-02-24 00:35:21 +0000635 Entry E(*this, *AbbrevIt);
Pavel Labath3c9a9182018-01-29 11:08:32 +0000636
637 DWARFFormParams FormParams = {Hdr.Version, 0, dwarf::DwarfFormat::DWARF32};
638 for (auto &Value : E.Values) {
639 if (!Value.extractValue(AS, Offset, FormParams))
640 return make_error<StringError>("Error extracting index attribute values",
641 inconvertibleErrorCode());
642 }
643 return std::move(E);
644}
645
646DWARFDebugNames::NameTableEntry
647DWARFDebugNames::NameIndex::getNameTableEntry(uint32_t Index) const {
648 assert(0 < Index && Index <= Hdr.NameCount);
649 uint32_t StringOffsetOffset = StringOffsetsBase + 4 * (Index - 1);
650 uint32_t EntryOffsetOffset = EntryOffsetsBase + 4 * (Index - 1);
651 const DWARFDataExtractor &AS = Section.AccelSection;
652
653 uint32_t StringOffset = AS.getRelocatedValue(4, &StringOffsetOffset);
654 uint32_t EntryOffset = AS.getU32(&EntryOffsetOffset);
655 EntryOffset += EntriesBase;
656 return {StringOffset, EntryOffset};
657}
658
659uint32_t
660DWARFDebugNames::NameIndex::getBucketArrayEntry(uint32_t Bucket) const {
661 assert(Bucket < Hdr.BucketCount);
662 uint32_t BucketOffset = BucketsBase + 4 * Bucket;
663 return Section.AccelSection.getU32(&BucketOffset);
664}
665
666uint32_t DWARFDebugNames::NameIndex::getHashArrayEntry(uint32_t Index) const {
667 assert(0 < Index && Index <= Hdr.NameCount);
668 uint32_t HashOffset = HashesBase + 4 * (Index - 1);
669 return Section.AccelSection.getU32(&HashOffset);
670}
671
672// Returns true if we should continue scanning for entries, false if this is the
673// last (sentinel) entry). In case of a parsing error we also return false, as
674// it's not possible to recover this entry list (but the other lists may still
675// parse OK).
676bool DWARFDebugNames::NameIndex::dumpEntry(ScopedPrinter &W,
677 uint32_t *Offset) const {
678 uint32_t EntryId = *Offset;
679 auto EntryOr = getEntry(Offset);
680 if (!EntryOr) {
681 handleAllErrors(EntryOr.takeError(), [](const SentinelError &) {},
682 [&W](const ErrorInfoBase &EI) { EI.log(W.startLine()); });
683 return false;
684 }
685
686 DictScope EntryScope(W, ("Entry @ 0x" + Twine::utohexstr(EntryId)).str());
687 EntryOr->dump(W);
688 return true;
689}
690
691void DWARFDebugNames::NameIndex::dumpName(ScopedPrinter &W, uint32_t Index,
692 Optional<uint32_t> Hash) const {
693 const DataExtractor &SS = Section.StringSection;
694 NameTableEntry NTE = getNameTableEntry(Index);
695
696 DictScope NameScope(W, ("Name " + Twine(Index)).str());
697 if (Hash)
698 W.printHex("Hash", *Hash);
699
700 W.startLine() << format("String: 0x%08x", NTE.StringOffset);
701 W.getOStream() << " \"" << SS.getCStr(&NTE.StringOffset) << "\"\n";
702
703 while (dumpEntry(W, &NTE.EntryOffset))
704 /*empty*/;
705}
706
707void DWARFDebugNames::NameIndex::dumpCUs(ScopedPrinter &W) const {
708 ListScope CUScope(W, "Compilation Unit offsets");
709 for (uint32_t CU = 0; CU < Hdr.CompUnitCount; ++CU)
710 W.startLine() << format("CU[%u]: 0x%08x\n", CU, getCUOffset(CU));
711}
712
713void DWARFDebugNames::NameIndex::dumpLocalTUs(ScopedPrinter &W) const {
714 if (Hdr.LocalTypeUnitCount == 0)
715 return;
716
717 ListScope TUScope(W, "Local Type Unit offsets");
718 for (uint32_t TU = 0; TU < Hdr.LocalTypeUnitCount; ++TU)
719 W.startLine() << format("LocalTU[%u]: 0x%08x\n", TU, getLocalTUOffset(TU));
720}
721
722void DWARFDebugNames::NameIndex::dumpForeignTUs(ScopedPrinter &W) const {
723 if (Hdr.ForeignTypeUnitCount == 0)
724 return;
725
726 ListScope TUScope(W, "Foreign Type Unit signatures");
727 for (uint32_t TU = 0; TU < Hdr.ForeignTypeUnitCount; ++TU) {
728 W.startLine() << format("ForeignTU[%u]: 0x%016" PRIx64 "\n", TU,
Pavel Labathd99072b2018-02-24 00:35:21 +0000729 getForeignTUSignature(TU));
Pavel Labath3c9a9182018-01-29 11:08:32 +0000730 }
731}
732
733void DWARFDebugNames::NameIndex::dumpAbbreviations(ScopedPrinter &W) const {
734 ListScope AbbrevsScope(W, "Abbreviations");
735 for (const auto &Abbr : Abbrevs)
736 Abbr.dump(W);
737}
738
739void DWARFDebugNames::NameIndex::dumpBucket(ScopedPrinter &W,
740 uint32_t Bucket) const {
741 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
742 uint32_t Index = getBucketArrayEntry(Bucket);
743 if (Index == 0) {
744 W.printString("EMPTY");
745 return;
746 }
747 if (Index > Hdr.NameCount) {
748 W.printString("Name index is invalid");
749 return;
750 }
751
752 for (; Index <= Hdr.NameCount; ++Index) {
753 uint32_t Hash = getHashArrayEntry(Index);
754 if (Hash % Hdr.BucketCount != Bucket)
755 break;
756
757 dumpName(W, Index, Hash);
758 }
759}
760
761LLVM_DUMP_METHOD void DWARFDebugNames::NameIndex::dump(ScopedPrinter &W) const {
762 DictScope UnitScope(W, ("Name Index @ 0x" + Twine::utohexstr(Base)).str());
763 Hdr.dump(W);
764 dumpCUs(W);
765 dumpLocalTUs(W);
766 dumpForeignTUs(W);
767 dumpAbbreviations(W);
768
769 if (Hdr.BucketCount > 0) {
770 for (uint32_t Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket)
771 dumpBucket(W, Bucket);
772 return;
773 }
774
775 W.startLine() << "Hash table not present\n";
776 for (uint32_t Index = 1; Index <= Hdr.NameCount; ++Index)
777 dumpName(W, Index, None);
778}
779
780llvm::Error DWARFDebugNames::extract() {
781 uint32_t Offset = 0;
782 while (AccelSection.isValidOffset(Offset)) {
783 NameIndex Next(*this, Offset);
784 if (llvm::Error E = Next.extract())
785 return E;
786 Offset = Next.getNextUnitOffset();
787 NameIndices.push_back(std::move(Next));
788 }
789 return Error::success();
790}
791
792LLVM_DUMP_METHOD void DWARFDebugNames::dump(raw_ostream &OS) const {
793 ScopedPrinter W(OS);
794 for (const NameIndex &NI : NameIndices)
795 NI.dump(W);
796}
Pavel Labathd99072b2018-02-24 00:35:21 +0000797
798Optional<uint32_t>
799DWARFDebugNames::ValueIterator::findEntryOffsetInCurrentIndex() {
800 const Header &Hdr = CurrentIndex->Hdr;
801 if (Hdr.BucketCount == 0) {
802 // No Hash Table, We need to search through all names in the Name Index.
803 for (uint32_t Index = 1; Index <= Hdr.NameCount; ++Index) {
804 NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
805 if (CurrentIndex->Section.StringSection.getCStr(&NTE.StringOffset) == Key)
806 return NTE.EntryOffset;
807 }
808 return None;
809 }
810
811 // The Name Index has a Hash Table, so use that to speed up the search.
812 // Compute the Key Hash, if it has not been done already.
813 if (!Hash)
814 Hash = caseFoldingDjbHash(Key);
815 uint32_t Bucket = *Hash % Hdr.BucketCount;
816 uint32_t Index = CurrentIndex->getBucketArrayEntry(Bucket);
817 if (Index == 0)
818 return None; // Empty bucket
819
820 for (; Index <= Hdr.NameCount; ++Index) {
821 uint32_t Hash = CurrentIndex->getHashArrayEntry(Index);
822 if (Hash % Hdr.BucketCount != Bucket)
823 return None; // End of bucket
824
825 NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
826 if (CurrentIndex->Section.StringSection.getCStr(&NTE.StringOffset) == Key)
827 return NTE.EntryOffset;
828 }
829 return None;
830}
831
832bool DWARFDebugNames::ValueIterator::getEntryAtCurrentOffset() {
833 auto EntryOr = CurrentIndex->getEntry(&DataOffset);
834 if (!EntryOr) {
835 consumeError(EntryOr.takeError());
836 return false;
837 }
838 CurrentEntry = std::move(*EntryOr);
839 return true;
840}
841
842bool DWARFDebugNames::ValueIterator::findInCurrentIndex() {
843 Optional<uint32_t> Offset = findEntryOffsetInCurrentIndex();
844 if (!Offset)
845 return false;
846 DataOffset = *Offset;
847 return getEntryAtCurrentOffset();
848}
849
850void DWARFDebugNames::ValueIterator::searchFromStartOfCurrentIndex() {
851 for (const NameIndex *End = CurrentIndex->Section.NameIndices.end();
852 CurrentIndex != End; ++CurrentIndex) {
853 if (findInCurrentIndex())
854 return;
855 }
856 setEnd();
857}
858
859void DWARFDebugNames::ValueIterator::next() {
860 assert(CurrentIndex && "Incrementing an end() iterator?");
861
862 // First try the next entry in the current Index.
863 if (getEntryAtCurrentOffset())
864 return;
865
866 // Try the next Name Index.
867 ++CurrentIndex;
868 searchFromStartOfCurrentIndex();
869}
870
871DWARFDebugNames::ValueIterator::ValueIterator(const DWARFDebugNames &AccelTable,
872 StringRef Key)
873 : CurrentIndex(AccelTable.NameIndices.begin()), Key(Key) {
874 searchFromStartOfCurrentIndex();
875}
876
877iterator_range<DWARFDebugNames::ValueIterator>
878DWARFDebugNames::equal_range(StringRef Key) const {
879 if (NameIndices.empty())
880 return make_range(ValueIterator(), ValueIterator());
881 return make_range(ValueIterator(*this, Key), ValueIterator());
882}