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
9#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
10
11#include "llvm/ADT/SmallVector.h"
12#include "llvm/BinaryFormat/Dwarf.h"
13#include "llvm/Support/Compiler.h"
14#include "llvm/Support/DJB.h"
15#include "llvm/Support/Errc.h"
16#include "llvm/Support/Format.h"
17#include "llvm/Support/FormatVariadic.h"
18#include "llvm/Support/ScopedPrinter.h"
19#include "llvm/Support/raw_ostream.h"
20#include <cstddef>
21#include <cstdint>
22#include <utility>
23
24using namespace llvm;
25
26namespace {
27struct Atom {
28 unsigned Value;
29};
30
31static raw_ostream &operator<<(raw_ostream &OS, const Atom &A) {
32 StringRef Str = dwarf::AtomTypeString(Atom: A.Value);
33 if (!Str.empty())
34 return OS << Str;
35 return OS << "DW_ATOM_unknown_" << formatv(Fmt: "{0:x-}", Vals: A.Value);
36}
37} // namespace
38
39static Atom formatAtom(unsigned Atom) { return {.Value: Atom}; }
40
41DWARFAcceleratorTable::~DWARFAcceleratorTable() = default;
42
43Error AppleAcceleratorTable::extract() {
44 uint64_t Offset = 0;
45
46 // Check that we can at least read the header.
47 if (!AccelSection.isValidOffset(offsetof(Header, HeaderDataLength) + 4))
48 return createStringError(EC: errc::illegal_byte_sequence,
49 S: "Section too small: cannot read header.");
50
51 Hdr.Magic = AccelSection.getU32(offset_ptr: &Offset);
52 Hdr.Version = AccelSection.getU16(offset_ptr: &Offset);
53 Hdr.HashFunction = AccelSection.getU16(offset_ptr: &Offset);
54 Hdr.BucketCount = AccelSection.getU32(offset_ptr: &Offset);
55 Hdr.HashCount = AccelSection.getU32(offset_ptr: &Offset);
56 Hdr.HeaderDataLength = AccelSection.getU32(offset_ptr: &Offset);
57 FormParams = {.Version: Hdr.Version, .AddrSize: 0, .Format: dwarf::DwarfFormat::DWARF32};
58
59 // Check that we can read all the hashes and offsets from the
60 // section (see SourceLevelDebugging.md for the structure of the index).
61 if (!AccelSection.isValidOffset(offset: getIthBucketBase(I: Hdr.BucketCount - 1)))
62 return createStringError(
63 EC: errc::illegal_byte_sequence,
64 S: "Section too small: cannot read buckets and hashes.");
65
66 HdrData.DIEOffsetBase = AccelSection.getU32(offset_ptr: &Offset);
67 uint32_t NumAtoms = AccelSection.getU32(offset_ptr: &Offset);
68
69 HashDataEntryLength = 0;
70 auto MakeUnsupportedFormError = [](dwarf::Form Form) {
71 return createStringError(EC: errc::not_supported,
72 S: "Unsupported form:" +
73 dwarf::FormEncodingString(Encoding: Form));
74 };
75
76 for (unsigned i = 0; i < NumAtoms; ++i) {
77 uint16_t AtomType = AccelSection.getU16(offset_ptr: &Offset);
78 auto AtomForm = static_cast<dwarf::Form>(AccelSection.getU16(offset_ptr: &Offset));
79 HdrData.Atoms.push_back(Elt: std::make_pair(x&: AtomType, y&: AtomForm));
80
81 std::optional<uint8_t> FormSize =
82 dwarf::getFixedFormByteSize(Form: AtomForm, Params: FormParams);
83 if (!FormSize)
84 return MakeUnsupportedFormError(AtomForm);
85 HashDataEntryLength += *FormSize;
86 }
87
88 IsValid = true;
89 return Error::success();
90}
91
92uint32_t AppleAcceleratorTable::getNumBuckets() const {
93 return Hdr.BucketCount;
94}
95uint32_t AppleAcceleratorTable::getNumHashes() const { return Hdr.HashCount; }
96uint32_t AppleAcceleratorTable::getSizeHdr() const { return sizeof(Hdr); }
97uint32_t AppleAcceleratorTable::getHeaderDataLength() const {
98 return Hdr.HeaderDataLength;
99}
100
101ArrayRef<std::pair<AppleAcceleratorTable::HeaderData::AtomType,
102 AppleAcceleratorTable::HeaderData::Form>>
103AppleAcceleratorTable::getAtomsDesc() {
104 return HdrData.Atoms;
105}
106
107bool AppleAcceleratorTable::validateForms() {
108 for (auto Atom : getAtomsDesc()) {
109 DWARFFormValue FormValue(Atom.second);
110 switch (Atom.first) {
111 case dwarf::DW_ATOM_die_offset:
112 case dwarf::DW_ATOM_die_tag:
113 case dwarf::DW_ATOM_type_flags:
114 if ((!FormValue.isFormClass(FC: DWARFFormValue::FC_Constant) &&
115 !FormValue.isFormClass(FC: DWARFFormValue::FC_Flag)) ||
116 FormValue.getForm() == dwarf::DW_FORM_sdata)
117 return false;
118 break;
119 default:
120 break;
121 }
122 }
123 return true;
124}
125
126std::pair<uint64_t, dwarf::Tag>
127AppleAcceleratorTable::readAtoms(uint64_t *HashDataOffset) {
128 uint64_t DieOffset = dwarf::DW_INVALID_OFFSET;
129 dwarf::Tag DieTag = dwarf::DW_TAG_null;
130
131 for (auto Atom : getAtomsDesc()) {
132 DWARFFormValue FormValue(Atom.second);
133 FormValue.extractValue(Data: AccelSection, OffsetPtr: HashDataOffset, FormParams);
134 switch (Atom.first) {
135 case dwarf::DW_ATOM_die_offset:
136 DieOffset = *FormValue.getAsUnsignedConstant();
137 break;
138 case dwarf::DW_ATOM_die_tag:
139 DieTag = (dwarf::Tag)*FormValue.getAsUnsignedConstant();
140 break;
141 default:
142 break;
143 }
144 }
145 return {DieOffset, DieTag};
146}
147
148void AppleAcceleratorTable::Header::dump(ScopedPrinter &W) const {
149 DictScope HeaderScope(W, "Header");
150 W.printHex(Label: "Magic", Value: Magic);
151 W.printHex(Label: "Version", Value: Version);
152 W.printHex(Label: "Hash function", Value: HashFunction);
153 W.printNumber(Label: "Bucket count", Value: BucketCount);
154 W.printNumber(Label: "Hashes count", Value: HashCount);
155 W.printNumber(Label: "HeaderData length", Value: HeaderDataLength);
156}
157
158std::optional<uint64_t> AppleAcceleratorTable::HeaderData::extractOffset(
159 std::optional<DWARFFormValue> Value) const {
160 if (!Value)
161 return std::nullopt;
162
163 switch (Value->getForm()) {
164 case dwarf::DW_FORM_ref1:
165 case dwarf::DW_FORM_ref2:
166 case dwarf::DW_FORM_ref4:
167 case dwarf::DW_FORM_ref8:
168 case dwarf::DW_FORM_ref_udata:
169 return Value->getRawUValue() + DIEOffsetBase;
170 default:
171 return Value->getAsSectionOffset();
172 }
173}
174
175bool AppleAcceleratorTable::dumpName(ScopedPrinter &W,
176 SmallVectorImpl<DWARFFormValue> &AtomForms,
177 uint64_t *DataOffset) const {
178 uint64_t NameOffset = *DataOffset;
179 if (!AccelSection.isValidOffsetForDataOfSize(offset: *DataOffset, length: 4)) {
180 W.printString(Value: "Incorrectly terminated list.");
181 return false;
182 }
183 uint64_t StringOffset = AccelSection.getRelocatedValue(Size: 4, Off: DataOffset);
184 if (!StringOffset)
185 return false; // End of list
186
187 DictScope NameScope(W, ("Name@0x" + Twine::utohexstr(Val: NameOffset)).str());
188 W.startLine() << formatv(Fmt: "String: {0:x8}", Vals&: StringOffset);
189 W.getOStream() << " \"" << StringSection.getCStr(OffsetPtr: &StringOffset) << "\"\n";
190
191 unsigned NumData = AccelSection.getU32(offset_ptr: DataOffset);
192 for (unsigned Data = 0; Data < NumData; ++Data) {
193 ListScope DataScope(W, ("Data " + Twine(Data)).str());
194 unsigned i = 0;
195 for (auto &Atom : AtomForms) {
196 W.startLine() << formatv(Fmt: "Atom[{0}]: ", Vals&: i);
197 if (Atom.extractValue(Data: AccelSection, OffsetPtr: DataOffset, FormParams)) {
198 Atom.dump(OS&: W.getOStream());
199 if (std::optional<uint64_t> Val = Atom.getAsUnsignedConstant()) {
200 StringRef Str = dwarf::AtomValueString(Atom: HdrData.Atoms[i].first, Val: *Val);
201 if (!Str.empty())
202 W.getOStream() << " (" << Str << ")";
203 }
204 } else
205 W.getOStream() << "Error extracting the value";
206 W.getOStream() << "\n";
207 i++;
208 }
209 }
210 return true; // more entries follow
211}
212
213LLVM_DUMP_METHOD void AppleAcceleratorTable::dump(raw_ostream &OS) const {
214 if (!IsValid)
215 return;
216
217 ScopedPrinter W(OS);
218
219 Hdr.dump(W);
220
221 W.printNumber(Label: "DIE offset base", Value: HdrData.DIEOffsetBase);
222 W.printNumber(Label: "Number of atoms", Value: uint64_t(HdrData.Atoms.size()));
223 W.printNumber(Label: "Size of each hash data entry", Value: getHashDataEntryLength());
224 SmallVector<DWARFFormValue, 3> AtomForms;
225 {
226 ListScope AtomsScope(W, "Atoms");
227 unsigned i = 0;
228 for (const auto &Atom : HdrData.Atoms) {
229 DictScope AtomScope(W, ("Atom " + Twine(i++)).str());
230 W.startLine() << "Type: " << formatAtom(Atom: Atom.first) << '\n';
231 W.startLine() << "Form: " << formatv(Fmt: "{0}", Vals: Atom.second) << '\n';
232 AtomForms.push_back(Elt: DWARFFormValue(Atom.second));
233 }
234 }
235
236 // Now go through the actual tables and dump them.
237 uint64_t Offset = sizeof(Hdr) + Hdr.HeaderDataLength;
238 uint64_t HashesBase = Offset + Hdr.BucketCount * 4;
239 uint64_t OffsetsBase = HashesBase + Hdr.HashCount * 4;
240
241 for (unsigned Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket) {
242 unsigned Index = AccelSection.getU32(offset_ptr: &Offset);
243
244 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
245 if (Index == UINT32_MAX) {
246 W.printString(Value: "EMPTY");
247 continue;
248 }
249
250 for (unsigned HashIdx = Index; HashIdx < Hdr.HashCount; ++HashIdx) {
251 uint64_t HashOffset = HashesBase + HashIdx*4;
252 uint64_t OffsetsOffset = OffsetsBase + HashIdx*4;
253 uint32_t Hash = AccelSection.getU32(offset_ptr: &HashOffset);
254
255 if (Hash % Hdr.BucketCount != Bucket)
256 break;
257
258 uint64_t DataOffset = AccelSection.getU32(offset_ptr: &OffsetsOffset);
259 ListScope HashScope(W, ("Hash 0x" + Twine::utohexstr(Val: Hash)).str());
260 if (!AccelSection.isValidOffset(offset: DataOffset)) {
261 W.printString(Value: "Invalid section offset");
262 continue;
263 }
264 while (dumpName(W, AtomForms, DataOffset: &DataOffset))
265 /*empty*/;
266 }
267 }
268}
269
270AppleAcceleratorTable::Entry::Entry(const AppleAcceleratorTable &Table)
271 : Table(Table) {
272 Values.reserve(N: Table.HdrData.Atoms.size());
273 for (const auto &Atom : Table.HdrData.Atoms)
274 Values.push_back(Elt: DWARFFormValue(Atom.second));
275}
276
277void AppleAcceleratorTable::Entry::extract(uint64_t *Offset) {
278 for (auto &FormValue : Values)
279 FormValue.extractValue(Data: Table.AccelSection, OffsetPtr: Offset, FormParams: Table.FormParams);
280}
281
282std::optional<DWARFFormValue>
283AppleAcceleratorTable::Entry::lookup(HeaderData::AtomType AtomToFind) const {
284 for (auto [Atom, FormValue] : zip_equal(t: Table.HdrData.Atoms, u: Values))
285 if (Atom.first == AtomToFind)
286 return FormValue;
287 return std::nullopt;
288}
289
290std::optional<uint64_t>
291AppleAcceleratorTable::Entry::getDIESectionOffset() const {
292 return Table.HdrData.extractOffset(Value: lookup(AtomToFind: dwarf::DW_ATOM_die_offset));
293}
294
295std::optional<uint64_t> AppleAcceleratorTable::Entry::getCUOffset() const {
296 return Table.HdrData.extractOffset(Value: lookup(AtomToFind: dwarf::DW_ATOM_cu_offset));
297}
298
299std::optional<dwarf::Tag> AppleAcceleratorTable::Entry::getTag() const {
300 std::optional<DWARFFormValue> Tag = lookup(AtomToFind: dwarf::DW_ATOM_die_tag);
301 if (!Tag)
302 return std::nullopt;
303 if (std::optional<uint64_t> Value = Tag->getAsUnsignedConstant())
304 return dwarf::Tag(*Value);
305 return std::nullopt;
306}
307
308AppleAcceleratorTable::SameNameIterator::SameNameIterator(
309 const AppleAcceleratorTable &AccelTable, uint64_t DataOffset)
310 : Current(AccelTable), Offset(DataOffset) {}
311
312void AppleAcceleratorTable::Iterator::prepareNextEntryOrEnd() {
313 if (NumEntriesToCome == 0)
314 prepareNextStringOrEnd();
315 if (isEnd())
316 return;
317 uint64_t OffsetCopy = Offset;
318 Current.BaseEntry.extract(Offset: &OffsetCopy);
319 NumEntriesToCome--;
320 Offset += getTable().getHashDataEntryLength();
321}
322
323void AppleAcceleratorTable::Iterator::prepareNextStringOrEnd() {
324 const AppleAcceleratorTable &Table = getTable();
325 if (Offset == 0) {
326 // Always start looking for strings using a valid offset from the Offsets
327 // table. Entries are not always consecutive.
328 std::optional<uint64_t> OptOffset = Table.readIthOffset(I: OffsetIdx++);
329 if (!OptOffset)
330 return setToEnd();
331 Offset = *OptOffset;
332 }
333 std::optional<uint32_t> StrOffset = Table.readStringOffsetAt(Offset);
334 if (!StrOffset)
335 return setToEnd();
336
337 // A zero denotes the end of the collision list. Skip to the next offset
338 // in the offsets table by setting the Offset to zero so we will grab the
339 // next offset from the offsets table.
340 if (*StrOffset == 0) {
341 Offset = 0;
342 return prepareNextStringOrEnd();
343 }
344 Current.StrOffset = *StrOffset;
345
346 std::optional<uint32_t> MaybeNumEntries = Table.readU32FromAccel(Offset);
347 if (!MaybeNumEntries || *MaybeNumEntries == 0)
348 return setToEnd();
349 NumEntriesToCome = *MaybeNumEntries;
350}
351
352AppleAcceleratorTable::Iterator::Iterator(const AppleAcceleratorTable &Table,
353 bool SetEnd)
354 : Current(Table), Offset(0), NumEntriesToCome(0) {
355 if (SetEnd)
356 setToEnd();
357 else
358 prepareNextEntryOrEnd();
359}
360
361iterator_range<AppleAcceleratorTable::SameNameIterator>
362AppleAcceleratorTable::equal_range(StringRef Key) const {
363 const auto EmptyRange =
364 make_range(x: SameNameIterator(*this, 0), y: SameNameIterator(*this, 0));
365 if (!IsValid)
366 return EmptyRange;
367
368 // Find the bucket.
369 uint32_t SearchHash = djbHash(Buffer: Key);
370 uint32_t BucketIdx = hashToBucketIdx(Hash: SearchHash);
371 std::optional<uint32_t> HashIdx = idxOfHashInBucket(HashToFind: SearchHash, BucketIdx);
372 if (!HashIdx)
373 return EmptyRange;
374
375 std::optional<uint64_t> MaybeDataOffset = readIthOffset(I: *HashIdx);
376 if (!MaybeDataOffset)
377 return EmptyRange;
378
379 uint64_t DataOffset = *MaybeDataOffset;
380 if (DataOffset >= AccelSection.size())
381 return EmptyRange;
382
383 std::optional<uint32_t> StrOffset = readStringOffsetAt(Offset&: DataOffset);
384 // Valid input and still have strings in this hash.
385 while (StrOffset && *StrOffset) {
386 std::optional<StringRef> MaybeStr = readStringFromStrSection(StringSectionOffset: *StrOffset);
387 std::optional<uint32_t> NumEntries = this->readU32FromAccel(Offset&: DataOffset);
388 if (!MaybeStr || !NumEntries)
389 return EmptyRange;
390 uint64_t EndOffset = DataOffset + *NumEntries * getHashDataEntryLength();
391 if (Key == *MaybeStr)
392 return make_range(x: {*this, DataOffset},
393 y: SameNameIterator{*this, EndOffset});
394 DataOffset = EndOffset;
395 StrOffset = readStringOffsetAt(Offset&: DataOffset);
396 }
397
398 return EmptyRange;
399}
400
401std::optional<uint32_t>
402AppleAcceleratorTable::idxOfHashInBucket(uint32_t HashToFind,
403 uint32_t BucketIdx) const {
404 std::optional<uint32_t> HashStartIdx = readIthBucket(I: BucketIdx);
405 if (!HashStartIdx)
406 return std::nullopt;
407
408 for (uint32_t HashIdx = *HashStartIdx; HashIdx < getNumHashes(); HashIdx++) {
409 std::optional<uint32_t> MaybeHash = readIthHash(I: HashIdx);
410 if (!MaybeHash || !wouldHashBeInBucket(Hash: *MaybeHash, BucketIdx))
411 break;
412 if (*MaybeHash == HashToFind)
413 return HashIdx;
414 }
415 return std::nullopt;
416}
417
418std::optional<StringRef> AppleAcceleratorTable::readStringFromStrSection(
419 uint64_t StringSectionOffset) const {
420 Error E = Error::success();
421 StringRef Str = StringSection.getCStrRef(OffsetPtr: &StringSectionOffset, Err: &E);
422 if (E) {
423 consumeError(Err: std::move(E));
424 return std::nullopt;
425 }
426 return Str;
427}
428
429std::optional<uint32_t>
430AppleAcceleratorTable::readU32FromAccel(uint64_t &Offset,
431 bool UseRelocation) const {
432 Error E = Error::success();
433 uint32_t Data = UseRelocation
434 ? AccelSection.getRelocatedValue(Size: 4, Off: &Offset, SectionIndex: nullptr, Err: &E)
435 : AccelSection.getU32(offset_ptr: &Offset, Err: &E);
436 if (E) {
437 consumeError(Err: std::move(E));
438 return std::nullopt;
439 }
440 return Data;
441}
442
443void DWARFDebugNames::Header::dump(ScopedPrinter &W) const {
444 DictScope HeaderScope(W, "Header");
445 W.printHex(Label: "Length", Value: UnitLength);
446 W.printString(Label: "Format", Value: dwarf::FormatString(Format));
447 W.printNumber(Label: "Version", Value: Version);
448 W.printNumber(Label: "CU count", Value: CompUnitCount);
449 W.printNumber(Label: "Local TU count", Value: LocalTypeUnitCount);
450 W.printNumber(Label: "Foreign TU count", Value: ForeignTypeUnitCount);
451 W.printNumber(Label: "Bucket count", Value: BucketCount);
452 W.printNumber(Label: "Name count", Value: NameCount);
453 W.printHex(Label: "Abbreviations table size", Value: AbbrevTableSize);
454 W.startLine() << "Augmentation: '" << AugmentationString << "'\n";
455}
456
457Error DWARFDebugNames::Header::extract(const DWARFDataExtractor &AS,
458 uint64_t *Offset) {
459 auto HeaderError = [Offset = *Offset](Error E) {
460 return createStringError(EC: errc::illegal_byte_sequence,
461 Fmt: "parsing .debug_names header at 0x%" PRIx64 ": %s",
462 Vals: Offset, Vals: toString(E: std::move(E)).c_str());
463 };
464
465 DataExtractor::Cursor C(*Offset);
466 std::tie(args&: UnitLength, args&: Format) = AS.getInitialLength(C);
467
468 Version = AS.getU16(C);
469 AS.skip(C, Length: 2); // padding
470 CompUnitCount = AS.getU32(C);
471 LocalTypeUnitCount = AS.getU32(C);
472 ForeignTypeUnitCount = AS.getU32(C);
473 BucketCount = AS.getU32(C);
474 NameCount = AS.getU32(C);
475 AbbrevTableSize = AS.getU32(C);
476 AugmentationStringSize = alignTo(Value: AS.getU32(C), Align: 4);
477
478 if (!C)
479 return HeaderError(C.takeError());
480
481 if (!AS.isValidOffsetForDataOfSize(offset: C.tell(), length: AugmentationStringSize))
482 return HeaderError(createStringError(EC: errc::illegal_byte_sequence,
483 S: "cannot read header augmentation"));
484 AugmentationString.resize(N: AugmentationStringSize);
485 AS.getU8(C, Dst: reinterpret_cast<uint8_t *>(AugmentationString.data()),
486 Count: AugmentationStringSize);
487 *Offset = C.tell();
488 return C.takeError();
489}
490
491void DWARFDebugNames::Abbrev::dump(ScopedPrinter &W) const {
492 DictScope AbbrevScope(W, ("Abbreviation 0x" + Twine::utohexstr(Val: Code)).str());
493 W.startLine() << formatv(Fmt: "Tag: {0}\n", Vals: Tag);
494
495 for (const auto &Attr : Attributes)
496 W.startLine() << formatv(Fmt: "{0}: {1}\n", Vals: Attr.Index, Vals: Attr.Form);
497}
498
499static constexpr DWARFDebugNames::AttributeEncoding sentinelAttrEnc() {
500 return {dwarf::Index(0), dwarf::Form(0)};
501}
502
503static bool isSentinel(const DWARFDebugNames::AttributeEncoding &AE) {
504 return AE == sentinelAttrEnc();
505}
506
507static DWARFDebugNames::Abbrev sentinelAbbrev() {
508 return DWARFDebugNames::Abbrev(0, dwarf::Tag(0), 0, {});
509}
510
511static bool isSentinel(const DWARFDebugNames::Abbrev &Abbr) {
512 return Abbr.Code == 0;
513}
514
515Expected<DWARFDebugNames::AttributeEncoding>
516DWARFDebugNames::NameIndex::extractAttributeEncoding(uint64_t *Offset) {
517 if (*Offset >= Offsets.EntriesBase) {
518 return createStringError(EC: errc::illegal_byte_sequence,
519 S: "Incorrectly terminated abbreviation table.");
520 }
521
522 uint32_t Index = Section.AccelSection.getULEB128(offset_ptr: Offset);
523 uint32_t Form = Section.AccelSection.getULEB128(offset_ptr: Offset);
524 return AttributeEncoding(dwarf::Index(Index), dwarf::Form(Form));
525}
526
527Expected<std::vector<DWARFDebugNames::AttributeEncoding>>
528DWARFDebugNames::NameIndex::extractAttributeEncodings(uint64_t *Offset) {
529 std::vector<AttributeEncoding> Result;
530 for (;;) {
531 auto AttrEncOr = extractAttributeEncoding(Offset);
532 if (!AttrEncOr)
533 return AttrEncOr.takeError();
534 if (isSentinel(AE: *AttrEncOr))
535 return std::move(Result);
536
537 Result.emplace_back(args&: *AttrEncOr);
538 }
539}
540
541Expected<DWARFDebugNames::Abbrev>
542DWARFDebugNames::NameIndex::extractAbbrev(uint64_t *Offset) {
543 if (*Offset >= Offsets.EntriesBase) {
544 return createStringError(EC: errc::illegal_byte_sequence,
545 S: "Incorrectly terminated abbreviation table.");
546 }
547 const uint64_t AbbrevOffset = *Offset;
548 uint32_t Code = Section.AccelSection.getULEB128(offset_ptr: Offset);
549 if (Code == 0)
550 return sentinelAbbrev();
551
552 uint32_t Tag = Section.AccelSection.getULEB128(offset_ptr: Offset);
553 auto AttrEncOr = extractAttributeEncodings(Offset);
554 if (!AttrEncOr)
555 return AttrEncOr.takeError();
556 return Abbrev(Code, dwarf::Tag(Tag), AbbrevOffset, std::move(*AttrEncOr));
557}
558
559DWARFDebugNames::DWARFDebugNamesOffsets
560dwarf::findDebugNamesOffsets(uint64_t EndOfHeaderOffset,
561 const DWARFDebugNames::Header &Hdr) {
562 uint64_t DwarfSize = getDwarfOffsetByteSize(Format: Hdr.Format);
563 DWARFDebugNames::DWARFDebugNamesOffsets Ret;
564 Ret.CUsBase = EndOfHeaderOffset;
565 Ret.BucketsBase = Ret.CUsBase + Hdr.CompUnitCount * DwarfSize +
566 Hdr.LocalTypeUnitCount * DwarfSize +
567 Hdr.ForeignTypeUnitCount * 8;
568 Ret.HashesBase = Ret.BucketsBase + Hdr.BucketCount * 4;
569 Ret.StringOffsetsBase =
570 Ret.HashesBase + (Hdr.BucketCount > 0 ? Hdr.NameCount * 4 : 0);
571 Ret.EntryOffsetsBase = Ret.StringOffsetsBase + Hdr.NameCount * DwarfSize;
572 Ret.EntriesBase =
573 Ret.EntryOffsetsBase + Hdr.NameCount * DwarfSize + Hdr.AbbrevTableSize;
574 return Ret;
575}
576
577Error DWARFDebugNames::NameIndex::extract() {
578 const DWARFDataExtractor &AS = Section.AccelSection;
579 uint64_t EndOfHeaderOffset = Base;
580 if (Error E = Hdr.extract(AS, Offset: &EndOfHeaderOffset))
581 return E;
582
583 const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Format: Hdr.Format);
584 Offsets = dwarf::findDebugNamesOffsets(EndOfHeaderOffset, Hdr);
585
586 uint64_t Offset =
587 Offsets.EntryOffsetsBase + (Hdr.NameCount * SectionOffsetSize);
588
589 if (!AS.isValidOffsetForDataOfSize(offset: Offset, length: Hdr.AbbrevTableSize))
590 return createStringError(EC: errc::illegal_byte_sequence,
591 S: "Section too small: cannot read abbreviations.");
592
593 Offsets.EntriesBase = Offset + Hdr.AbbrevTableSize;
594
595 for (;;) {
596 auto AbbrevOr = extractAbbrev(Offset: &Offset);
597 if (!AbbrevOr)
598 return AbbrevOr.takeError();
599 if (isSentinel(Abbr: *AbbrevOr))
600 return Error::success();
601
602 if (!Abbrevs.insert(V: std::move(*AbbrevOr)).second)
603 return createStringError(EC: errc::invalid_argument,
604 S: "Duplicate abbreviation code.");
605 }
606}
607
608DWARFDebugNames::Entry::Entry(const NameIndex &NameIdx, const Abbrev &Abbr)
609 : NameIdx(&NameIdx), Abbr(&Abbr) {
610 // This merely creates form values. It is up to the caller
611 // (NameIndex::getEntry) to populate them.
612 Values.reserve(N: Abbr.Attributes.size());
613 for (const auto &Attr : Abbr.Attributes)
614 Values.emplace_back(Args: Attr.Form);
615}
616
617std::optional<DWARFFormValue>
618DWARFDebugNames::Entry::lookup(dwarf::Index Index) const {
619 assert(Abbr->Attributes.size() == Values.size());
620 for (auto Tuple : zip_first(t: Abbr->Attributes, u: Values)) {
621 if (std::get<0>(t&: Tuple).Index == Index)
622 return std::get<1>(t&: Tuple);
623 }
624 return std::nullopt;
625}
626
627bool DWARFDebugNames::Entry::hasParentInformation() const {
628 return lookup(Index: dwarf::DW_IDX_parent).has_value();
629}
630
631std::optional<uint64_t> DWARFDebugNames::Entry::getDIEUnitOffset() const {
632 if (std::optional<DWARFFormValue> Off = lookup(Index: dwarf::DW_IDX_die_offset))
633 return Off->getAsReferenceUVal();
634 return std::nullopt;
635}
636
637std::optional<uint64_t> DWARFDebugNames::Entry::getRelatedCUIndex() const {
638 // Return the DW_IDX_compile_unit attribute value if it is specified.
639 if (std::optional<DWARFFormValue> Off = lookup(Index: dwarf::DW_IDX_compile_unit))
640 return Off->getAsUnsignedConstant();
641 // In a per-CU index, the entries without a DW_IDX_compile_unit attribute
642 // implicitly refer to the single CU.
643 if (NameIdx->getCUCount() == 1)
644 return 0;
645 return std::nullopt;
646}
647
648std::optional<uint64_t> DWARFDebugNames::Entry::getCUIndex() const {
649 // Return the DW_IDX_compile_unit attribute value but only if we don't have a
650 // DW_IDX_type_unit attribute. Use Entry::getRelatedCUIndex() to get the
651 // associated CU index if this behaviour is not desired.
652 if (lookup(Index: dwarf::DW_IDX_type_unit).has_value())
653 return std::nullopt;
654 return getRelatedCUIndex();
655}
656
657std::optional<uint64_t> DWARFDebugNames::Entry::getCUOffset() const {
658 std::optional<uint64_t> Index = getCUIndex();
659 if (!Index || *Index >= NameIdx->getCUCount())
660 return std::nullopt;
661 return NameIdx->getCUOffset(CU: *Index);
662}
663
664std::optional<uint64_t> DWARFDebugNames::Entry::getRelatedCUOffset() const {
665 std::optional<uint64_t> Index = getRelatedCUIndex();
666 if (!Index || *Index >= NameIdx->getCUCount())
667 return std::nullopt;
668 return NameIdx->getCUOffset(CU: *Index);
669}
670
671std::optional<uint64_t> DWARFDebugNames::Entry::getLocalTUOffset() const {
672 std::optional<uint64_t> Index = getTUIndex();
673 if (!Index || *Index >= NameIdx->getLocalTUCount())
674 return std::nullopt;
675 return NameIdx->getLocalTUOffset(TU: *Index);
676}
677
678std::optional<uint64_t>
679DWARFDebugNames::Entry::getForeignTUTypeSignature() const {
680 std::optional<uint64_t> Index = getTUIndex();
681 const uint32_t NumLocalTUs = NameIdx->getLocalTUCount();
682 if (!Index || *Index < NumLocalTUs)
683 return std::nullopt; // Invalid TU index or TU index is for a local TU
684 // The foreign TU index is the TU index minus the number of local TUs.
685 const uint64_t ForeignTUIndex = *Index - NumLocalTUs;
686 if (ForeignTUIndex >= NameIdx->getForeignTUCount())
687 return std::nullopt; // Invalid foreign TU index.
688 return NameIdx->getForeignTUSignature(TU: ForeignTUIndex);
689}
690
691std::optional<uint64_t> DWARFDebugNames::Entry::getTUIndex() const {
692 if (std::optional<DWARFFormValue> Off = lookup(Index: dwarf::DW_IDX_type_unit))
693 return Off->getAsUnsignedConstant();
694 return std::nullopt;
695}
696
697Expected<std::optional<DWARFDebugNames::Entry>>
698DWARFDebugNames::Entry::getParentDIEEntry() const {
699 // The offset of the accelerator table entry for the parent.
700 std::optional<DWARFFormValue> ParentEntryOff = lookup(Index: dwarf::DW_IDX_parent);
701 assert(ParentEntryOff.has_value() && "hasParentInformation() must be called");
702
703 if (ParentEntryOff->getForm() == dwarf::Form::DW_FORM_flag_present)
704 return std::nullopt;
705 return NameIdx->getEntryAtRelativeOffset(Offset: ParentEntryOff->getRawUValue());
706}
707
708void DWARFDebugNames::Entry::dumpParentIdx(
709 ScopedPrinter &W, const DWARFFormValue &FormValue) const {
710 Expected<std::optional<Entry>> ParentEntry = getParentDIEEntry();
711 if (!ParentEntry) {
712 W.getOStream() << "<invalid offset data>";
713 consumeError(Err: ParentEntry.takeError());
714 return;
715 }
716
717 if (!ParentEntry->has_value()) {
718 W.getOStream() << "<parent not indexed>";
719 return;
720 }
721
722 auto AbsoluteOffset = NameIdx->Offsets.EntriesBase + FormValue.getRawUValue();
723 W.getOStream() << "Entry @ 0x" + Twine::utohexstr(Val: AbsoluteOffset);
724}
725
726void DWARFDebugNames::Entry::dump(ScopedPrinter &W) const {
727 W.startLine() << formatv(Fmt: "Abbrev: {0:x}\n", Vals: Abbr->Code);
728 W.startLine() << formatv(Fmt: "Tag: {0}\n", Vals: Abbr->Tag);
729 assert(Abbr->Attributes.size() == Values.size());
730 for (auto Tuple : zip_first(t: Abbr->Attributes, u: Values)) {
731 auto Index = std::get<0>(t&: Tuple).Index;
732 W.startLine() << formatv(Fmt: "{0}: ", Vals&: Index);
733
734 auto FormValue = std::get<1>(t&: Tuple);
735 if (Index == dwarf::Index::DW_IDX_parent)
736 dumpParentIdx(W, FormValue);
737 else
738 FormValue.dump(OS&: W.getOStream());
739 W.getOStream() << '\n';
740 }
741}
742
743char DWARFDebugNames::SentinelError::ID;
744std::error_code DWARFDebugNames::SentinelError::convertToErrorCode() const {
745 return inconvertibleErrorCode();
746}
747
748uint64_t DWARFDebugNames::NameIndex::getCUOffset(uint32_t CU) const {
749 assert(CU < Hdr.CompUnitCount);
750 const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Format: Hdr.Format);
751 uint64_t Offset = Offsets.CUsBase + SectionOffsetSize * CU;
752 return Section.AccelSection.getRelocatedValue(Size: SectionOffsetSize, Off: &Offset);
753}
754
755uint64_t DWARFDebugNames::NameIndex::getLocalTUOffset(uint32_t TU) const {
756 assert(TU < Hdr.LocalTypeUnitCount);
757 const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Format: Hdr.Format);
758 uint64_t Offset =
759 Offsets.CUsBase + SectionOffsetSize * (Hdr.CompUnitCount + TU);
760 return Section.AccelSection.getRelocatedValue(Size: SectionOffsetSize, Off: &Offset);
761}
762
763uint64_t DWARFDebugNames::NameIndex::getForeignTUSignature(uint32_t TU) const {
764 assert(TU < Hdr.ForeignTypeUnitCount);
765 const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Format: Hdr.Format);
766 uint64_t Offset =
767 Offsets.CUsBase +
768 SectionOffsetSize * (Hdr.CompUnitCount + Hdr.LocalTypeUnitCount) + 8 * TU;
769 return Section.AccelSection.getU64(offset_ptr: &Offset);
770}
771
772Expected<DWARFDebugNames::Entry>
773DWARFDebugNames::NameIndex::getEntry(uint64_t *Offset) const {
774 const DWARFDataExtractor &AS = Section.AccelSection;
775 if (!AS.isValidOffset(offset: *Offset))
776 return createStringError(EC: errc::illegal_byte_sequence,
777 S: "Incorrectly terminated entry list.");
778
779 uint32_t AbbrevCode = AS.getULEB128(offset_ptr: Offset);
780 if (AbbrevCode == 0)
781 return make_error<SentinelError>();
782
783 const auto AbbrevIt = Abbrevs.find_as(Val: AbbrevCode);
784 if (AbbrevIt == Abbrevs.end())
785 return createStringError(EC: errc::invalid_argument, S: "Invalid abbreviation.");
786
787 Entry E(*this, *AbbrevIt);
788
789 dwarf::FormParams FormParams = {.Version: Hdr.Version, .AddrSize: 0, .Format: Hdr.Format};
790 for (auto &Value : E.Values) {
791 if (!Value.extractValue(Data: AS, OffsetPtr: Offset, FormParams))
792 return createStringError(EC: errc::io_error,
793 S: "Error extracting index attribute values.");
794 }
795 return std::move(E);
796}
797
798DWARFDebugNames::NameTableEntry
799DWARFDebugNames::NameIndex::getNameTableEntry(uint32_t Index) const {
800 assert(0 < Index && Index <= Hdr.NameCount);
801 const unsigned SectionOffsetSize = dwarf::getDwarfOffsetByteSize(Format: Hdr.Format);
802 uint64_t StringOffsetOffset =
803 Offsets.StringOffsetsBase + SectionOffsetSize * (Index - 1);
804 uint64_t EntryOffsetOffset =
805 Offsets.EntryOffsetsBase + SectionOffsetSize * (Index - 1);
806 const DWARFDataExtractor &AS = Section.AccelSection;
807
808 uint64_t StringOffset =
809 AS.getRelocatedValue(Size: SectionOffsetSize, Off: &StringOffsetOffset);
810 uint64_t EntryOffset = AS.getUnsigned(offset_ptr: &EntryOffsetOffset, byte_size: SectionOffsetSize);
811 EntryOffset += Offsets.EntriesBase;
812 return {Section.StringSection, Index, StringOffset, EntryOffset};
813}
814
815uint32_t
816DWARFDebugNames::NameIndex::getBucketArrayEntry(uint32_t Bucket) const {
817 assert(Bucket < Hdr.BucketCount);
818 uint64_t BucketOffset = Offsets.BucketsBase + 4 * Bucket;
819 return Section.AccelSection.getU32(offset_ptr: &BucketOffset);
820}
821
822uint32_t DWARFDebugNames::NameIndex::getHashArrayEntry(uint32_t Index) const {
823 assert(0 < Index && Index <= Hdr.NameCount);
824 uint64_t HashOffset = Offsets.HashesBase + 4 * (Index - 1);
825 return Section.AccelSection.getU32(offset_ptr: &HashOffset);
826}
827
828// Returns true if we should continue scanning for entries, false if this is the
829// last (sentinel) entry). In case of a parsing error we also return false, as
830// it's not possible to recover this entry list (but the other lists may still
831// parse OK).
832bool DWARFDebugNames::NameIndex::dumpEntry(ScopedPrinter &W,
833 uint64_t *Offset) const {
834 uint64_t EntryId = *Offset;
835 auto EntryOr = getEntry(Offset);
836 if (!EntryOr) {
837 handleAllErrors(E: EntryOr.takeError(), Handlers: [](const SentinelError &) {},
838 Handlers: [&W](const ErrorInfoBase &EI) { EI.log(OS&: W.startLine()); });
839 return false;
840 }
841
842 DictScope EntryScope(W, ("Entry @ 0x" + Twine::utohexstr(Val: EntryId)).str());
843 EntryOr->dump(W);
844 return true;
845}
846
847void DWARFDebugNames::NameIndex::dumpName(ScopedPrinter &W,
848 const NameTableEntry &NTE,
849 std::optional<uint32_t> Hash) const {
850 DictScope NameScope(W, ("Name " + Twine(NTE.getIndex())).str());
851 if (Hash)
852 W.printHex(Label: "Hash", Value: *Hash);
853
854 W.startLine() << formatv(Fmt: "String: {0:x8}", Vals: NTE.getStringOffset());
855 W.getOStream() << " \"" << NTE.getString() << "\"\n";
856
857 uint64_t EntryOffset = NTE.getEntryOffset();
858 while (dumpEntry(W, Offset: &EntryOffset))
859 /*empty*/;
860}
861
862void DWARFDebugNames::NameIndex::dumpCUs(ScopedPrinter &W) const {
863 ListScope CUScope(W, "Compilation Unit offsets");
864 for (uint32_t CU = 0; CU < Hdr.CompUnitCount; ++CU)
865 W.startLine() << formatv(Fmt: "CU[{0}]: {1:x8}\n", Vals&: CU, Vals: getCUOffset(CU));
866}
867
868void DWARFDebugNames::NameIndex::dumpLocalTUs(ScopedPrinter &W) const {
869 if (Hdr.LocalTypeUnitCount == 0)
870 return;
871
872 ListScope TUScope(W, "Local Type Unit offsets");
873 for (uint32_t TU = 0; TU < Hdr.LocalTypeUnitCount; ++TU)
874 W.startLine() << formatv(Fmt: "LocalTU[{0}]: {1:x8}\n", Vals&: TU,
875 Vals: getLocalTUOffset(TU));
876}
877
878void DWARFDebugNames::NameIndex::dumpForeignTUs(ScopedPrinter &W) const {
879 if (Hdr.ForeignTypeUnitCount == 0)
880 return;
881
882 ListScope TUScope(W, "Foreign Type Unit signatures");
883 for (uint32_t TU = 0; TU < Hdr.ForeignTypeUnitCount; ++TU) {
884 W.startLine() << formatv(Fmt: "ForeignTU[{0}]: {1:x16}\n", Vals&: TU,
885 Vals: getForeignTUSignature(TU));
886 }
887}
888
889void DWARFDebugNames::NameIndex::dumpAbbreviations(ScopedPrinter &W) const {
890 ListScope AbbrevsScope(W, "Abbreviations");
891 std::vector<const Abbrev *> AbbrevsVect;
892 for (const DWARFDebugNames::Abbrev &Abbr : Abbrevs)
893 AbbrevsVect.push_back(x: &Abbr);
894 llvm::sort(C&: AbbrevsVect, Comp: [](const Abbrev *LHS, const Abbrev *RHS) {
895 return LHS->AbbrevOffset < RHS->AbbrevOffset;
896 });
897 for (const DWARFDebugNames::Abbrev *Abbr : AbbrevsVect)
898 Abbr->dump(W);
899}
900
901void DWARFDebugNames::NameIndex::dumpBucket(ScopedPrinter &W,
902 uint32_t Bucket) const {
903 ListScope BucketScope(W, ("Bucket " + Twine(Bucket)).str());
904 uint32_t Index = getBucketArrayEntry(Bucket);
905 if (Index == 0) {
906 W.printString(Value: "EMPTY");
907 return;
908 }
909 if (Index > Hdr.NameCount) {
910 W.printString(Value: "Name index is invalid");
911 return;
912 }
913
914 for (; Index <= Hdr.NameCount; ++Index) {
915 uint32_t Hash = getHashArrayEntry(Index);
916 if (Hash % Hdr.BucketCount != Bucket)
917 break;
918
919 dumpName(W, NTE: getNameTableEntry(Index), Hash);
920 }
921}
922
923LLVM_DUMP_METHOD void DWARFDebugNames::NameIndex::dump(ScopedPrinter &W) const {
924 DictScope UnitScope(W, ("Name Index @ 0x" + Twine::utohexstr(Val: Base)).str());
925 Hdr.dump(W);
926 dumpCUs(W);
927 dumpLocalTUs(W);
928 dumpForeignTUs(W);
929 dumpAbbreviations(W);
930
931 if (Hdr.BucketCount > 0) {
932 for (uint32_t Bucket = 0; Bucket < Hdr.BucketCount; ++Bucket)
933 dumpBucket(W, Bucket);
934 return;
935 }
936
937 W.startLine() << "Hash table not present\n";
938 for (const NameTableEntry &NTE : *this)
939 dumpName(W, NTE, Hash: std::nullopt);
940}
941
942Error DWARFDebugNames::extract() {
943 uint64_t Offset = 0;
944 while (AccelSection.isValidOffset(offset: Offset)) {
945 NameIndex Next(*this, Offset);
946 if (Error E = Next.extract())
947 return E;
948 Offset = Next.getNextUnitOffset();
949 NameIndices.push_back(Elt: std::move(Next));
950 }
951 return Error::success();
952}
953
954iterator_range<DWARFDebugNames::ValueIterator>
955DWARFDebugNames::NameIndex::equal_range(StringRef Key) const {
956 return make_range(x: ValueIterator(*this, Key), y: ValueIterator());
957}
958
959LLVM_DUMP_METHOD void DWARFDebugNames::dump(raw_ostream &OS) const {
960 ScopedPrinter W(OS);
961 for (const NameIndex &NI : NameIndices)
962 NI.dump(W);
963}
964
965std::optional<uint64_t>
966DWARFDebugNames::ValueIterator::findEntryOffsetInCurrentIndex() {
967 const Header &Hdr = CurrentIndex->Hdr;
968 if (Hdr.BucketCount == 0) {
969 // No Hash Table, We need to search through all names in the Name Index.
970 for (const NameTableEntry &NTE : *CurrentIndex) {
971 if (NTE.sameNameAs(Target: Key))
972 return NTE.getEntryOffset();
973 }
974 return std::nullopt;
975 }
976
977 // The Name Index has a Hash Table, so use that to speed up the search.
978 // Compute the Key Hash, if it has not been done already.
979 if (!Hash)
980 Hash = caseFoldingDjbHash(Buffer: Key);
981 uint32_t Bucket = *Hash % Hdr.BucketCount;
982 uint32_t Index = CurrentIndex->getBucketArrayEntry(Bucket);
983 if (Index == 0)
984 return std::nullopt; // Empty bucket
985
986 for (; Index <= Hdr.NameCount; ++Index) {
987 uint32_t HashAtIndex = CurrentIndex->getHashArrayEntry(Index);
988 if (HashAtIndex % Hdr.BucketCount != Bucket)
989 return std::nullopt; // End of bucket
990 // Only compare names if the hashes match.
991 if (HashAtIndex != Hash)
992 continue;
993
994 NameTableEntry NTE = CurrentIndex->getNameTableEntry(Index);
995 if (NTE.sameNameAs(Target: Key))
996 return NTE.getEntryOffset();
997 }
998 return std::nullopt;
999}
1000
1001bool DWARFDebugNames::ValueIterator::getEntryAtCurrentOffset() {
1002 auto EntryOr = CurrentIndex->getEntry(Offset: &DataOffset);
1003 if (!EntryOr) {
1004 consumeError(Err: EntryOr.takeError());
1005 return false;
1006 }
1007 CurrentEntry = std::move(*EntryOr);
1008 return true;
1009}
1010
1011bool DWARFDebugNames::ValueIterator::findInCurrentIndex() {
1012 std::optional<uint64_t> Offset = findEntryOffsetInCurrentIndex();
1013 if (!Offset)
1014 return false;
1015 DataOffset = *Offset;
1016 return getEntryAtCurrentOffset();
1017}
1018
1019void DWARFDebugNames::ValueIterator::searchFromStartOfCurrentIndex() {
1020 for (const NameIndex *End = CurrentIndex->Section.NameIndices.end();
1021 CurrentIndex != End; ++CurrentIndex) {
1022 if (findInCurrentIndex())
1023 return;
1024 }
1025 setEnd();
1026}
1027
1028void DWARFDebugNames::ValueIterator::next() {
1029 assert(CurrentIndex && "Incrementing an end() iterator?");
1030
1031 // First try the next entry in the current Index.
1032 if (getEntryAtCurrentOffset())
1033 return;
1034
1035 // If we're a local iterator or we have reached the last Index, we're done.
1036 if (IsLocal || CurrentIndex == &CurrentIndex->Section.NameIndices.back()) {
1037 setEnd();
1038 return;
1039 }
1040
1041 // Otherwise, try the next index.
1042 ++CurrentIndex;
1043 searchFromStartOfCurrentIndex();
1044}
1045
1046DWARFDebugNames::ValueIterator::ValueIterator(const DWARFDebugNames &AccelTable,
1047 StringRef Key)
1048 : CurrentIndex(AccelTable.NameIndices.begin()), IsLocal(false),
1049 Key(std::string(Key)) {
1050 searchFromStartOfCurrentIndex();
1051}
1052
1053DWARFDebugNames::ValueIterator::ValueIterator(
1054 const DWARFDebugNames::NameIndex &NI, StringRef Key)
1055 : CurrentIndex(&NI), IsLocal(true), Key(std::string(Key)) {
1056 if (!findInCurrentIndex())
1057 setEnd();
1058}
1059
1060iterator_range<DWARFDebugNames::ValueIterator>
1061DWARFDebugNames::equal_range(StringRef Key) const {
1062 if (NameIndices.empty())
1063 return make_range(x: ValueIterator(), y: ValueIterator());
1064 return make_range(x: ValueIterator(*this, Key), y: ValueIterator());
1065}
1066
1067const DWARFDebugNames::NameIndex *
1068DWARFDebugNames::getCUOrTUNameIndex(uint64_t UnitOffset) {
1069 if (UnitOffsetToNameIndex.size() == 0 && NameIndices.size() > 0) {
1070 for (const auto &NI : *this) {
1071 for (uint32_t CU = 0; CU < NI.getCUCount(); ++CU)
1072 UnitOffsetToNameIndex.try_emplace(Key: NI.getCUOffset(CU), Args: &NI);
1073 for (uint32_t TU = 0; TU < NI.getLocalTUCount(); ++TU)
1074 UnitOffsetToNameIndex.try_emplace(Key: NI.getLocalTUOffset(TU), Args: &NI);
1075 }
1076 }
1077 return UnitOffsetToNameIndex.lookup(Val: UnitOffset);
1078}
1079
1080static bool isObjCSelector(StringRef Name) {
1081 return Name.size() > 2 && (Name[0] == '-' || Name[0] == '+') &&
1082 (Name[1] == '[');
1083}
1084
1085std::optional<ObjCSelectorNames> llvm::getObjCNamesIfSelector(StringRef Name) {
1086 if (!isObjCSelector(Name))
1087 return std::nullopt;
1088 // "-[Atom setMass:]"
1089 StringRef ClassNameStart(Name.drop_front(N: 2));
1090 size_t FirstSpace = ClassNameStart.find(C: ' ');
1091 if (FirstSpace == StringRef::npos)
1092 return std::nullopt;
1093
1094 StringRef SelectorStart = ClassNameStart.drop_front(N: FirstSpace + 1);
1095 if (!SelectorStart.size())
1096 return std::nullopt;
1097
1098 ObjCSelectorNames Ans;
1099 Ans.ClassName = ClassNameStart.take_front(N: FirstSpace);
1100 Ans.Selector = SelectorStart.drop_back(); // drop ']';
1101
1102 // "-[Class(Category) selector :withArg ...]"
1103 if (Ans.ClassName.back() == ')') {
1104 size_t OpenParens = Ans.ClassName.find(C: '(');
1105 if (OpenParens != StringRef::npos) {
1106 Ans.ClassNameNoCategory = Ans.ClassName.take_front(N: OpenParens);
1107
1108 Ans.MethodNameNoCategory = Name.take_front(N: OpenParens + 2);
1109 // FIXME: The missing space here may be a bug, but dsymutil-classic also
1110 // does it this way.
1111 append_range(C&: *Ans.MethodNameNoCategory, R&: SelectorStart);
1112 }
1113 }
1114 return Ans;
1115}
1116
1117std::optional<StringRef> llvm::StripTemplateParameters(StringRef Name) {
1118 // We are looking for template parameters to strip from Name. e.g.
1119 //
1120 // operator<<B>
1121 //
1122 // We look for > at the end but if it does not contain any < then we
1123 // have something like operator>>. We check for the operator<=> case.
1124 if (!Name.ends_with(Suffix: ">") || Name.count(Str: "<") == 0 || Name.ends_with(Suffix: "<=>"))
1125 return {};
1126
1127 // How many < until we have the start of the template parameters.
1128 size_t NumLeftAnglesToSkip = 1;
1129
1130 // If we have operator<=> then we need to skip its < as well.
1131 NumLeftAnglesToSkip += Name.count(Str: "<=>");
1132
1133 size_t RightAngleCount = Name.count(C: '>');
1134 size_t LeftAngleCount = Name.count(C: '<');
1135
1136 // If we have more < than > we have operator< or operator<<
1137 // we to account for their < as well.
1138 if (LeftAngleCount > RightAngleCount)
1139 NumLeftAnglesToSkip += LeftAngleCount - RightAngleCount;
1140
1141 size_t StartOfTemplate = 0;
1142 while (NumLeftAnglesToSkip--)
1143 StartOfTemplate = Name.find(C: '<', From: StartOfTemplate) + 1;
1144
1145 StringRef Result = Name.substr(Start: 0, N: StartOfTemplate - 1);
1146 if (Result.empty())
1147 return std::nullopt;
1148 return Result;
1149}
1150