1//===- DWARFUnit.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/DWARFUnit.h"
10#include "llvm/ADT/SmallString.h"
11#include "llvm/ADT/StringRef.h"
12#include "llvm/BinaryFormat/Dwarf.h"
13#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
14#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
15#include "llvm/DebugInfo/DWARF/DWARFContext.h"
16#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
17#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
18#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
19#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
20#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
21#include "llvm/DebugInfo/DWARF/DWARFDie.h"
22#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
23#include "llvm/DebugInfo/DWARF/DWARFListTable.h"
24#include "llvm/DebugInfo/DWARF/DWARFObject.h"
25#include "llvm/DebugInfo/DWARF/DWARFSection.h"
26#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
27#include "llvm/DebugInfo/DWARF/LowLevel/DWARFExpression.h"
28#include "llvm/Object/ObjectFile.h"
29#include "llvm/Support/DataExtractor.h"
30#include "llvm/Support/Errc.h"
31#include "llvm/Support/Path.h"
32#include <algorithm>
33#include <cassert>
34#include <cstddef>
35#include <cstdint>
36#include <utility>
37#include <vector>
38
39using namespace llvm;
40using namespace dwarf;
41
42void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
43 const DWARFSection &Section,
44 DWARFSectionKind SectionKind) {
45 const DWARFObject &D = C.getDWARFObj();
46 addUnitsImpl(Context&: C, Obj: D, Section, DA: C.getDebugAbbrev(), RS: &D.getRangesSection(),
47 LocSection: &D.getLocSection(), SS: D.getStrSection(),
48 SOS: D.getStrOffsetsSection(), AOS: &D.getAddrSection(),
49 LS: D.getLineSection(), LE: D.isLittleEndian(), IsDWO: false, Lazy: false,
50 SectionKind);
51}
52
53void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
54 const DWARFSection &DWOSection,
55 DWARFSectionKind SectionKind,
56 bool Lazy) {
57 const DWARFObject &D = C.getDWARFObj();
58 addUnitsImpl(Context&: C, Obj: D, Section: DWOSection, DA: C.getDebugAbbrevDWO(), RS: &D.getRangesDWOSection(),
59 LocSection: &D.getLocDWOSection(), SS: D.getStrDWOSection(),
60 SOS: D.getStrOffsetsDWOSection(), AOS: &D.getAddrSection(),
61 LS: D.getLineDWOSection(), LE: C.isLittleEndian(), IsDWO: true, Lazy,
62 SectionKind);
63}
64
65void DWARFUnitVector::addUnitsImpl(
66 DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
67 const DWARFDebugAbbrev *DA, const DWARFSection *RS,
68 const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
69 const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
70 bool Lazy, DWARFSectionKind SectionKind) {
71 DWARFDataExtractor Data(Obj, Section, LE, 0);
72 // Lazy initialization of Parser, now that we have all section info.
73 if (!Parser) {
74 Parser = [=, &Context, &Obj, &Section, &SOS,
75 &LS](uint64_t Offset, DWARFSectionKind SectionKind,
76 const DWARFSection *CurSection,
77 const DWARFUnitIndex::Entry *IndexEntry)
78 -> std::unique_ptr<DWARFUnit> {
79 const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
80 DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
81 if (!Data.isValidOffset(offset: Offset))
82 return nullptr;
83 DWARFUnitHeader Header;
84 if (Error ExtractErr =
85 Header.extract(Context, debug_info: Data, offset_ptr: &Offset, SectionKind)) {
86 Context.getWarningHandler()(std::move(ExtractErr));
87 return nullptr;
88 }
89 if (!IndexEntry && IsDWO) {
90 const DWARFUnitIndex &Index = getDWARFUnitIndex(
91 Context, Kind: Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);
92 if (Index) {
93 if (Header.isTypeUnit())
94 IndexEntry = Index.getFromHash(Offset: Header.getTypeHash());
95 else if (auto DWOId = Header.getDWOId())
96 IndexEntry = Index.getFromHash(Offset: *DWOId);
97 }
98 if (!IndexEntry)
99 IndexEntry = Index.getFromOffset(Offset: Header.getOffset());
100 }
101 if (IndexEntry) {
102 if (Error ApplicationErr = Header.applyIndexEntry(Entry: IndexEntry)) {
103 Context.getWarningHandler()(std::move(ApplicationErr));
104 return nullptr;
105 }
106 }
107 std::unique_ptr<DWARFUnit> U;
108 if (Header.isTypeUnit())
109 U = std::make_unique<DWARFTypeUnit>(args&: Context, args: InfoSection, args&: Header, args: DA,
110 args: RS, args: LocSection, args: SS, args: SOS, args: AOS, args: LS,
111 args: LE, args: IsDWO, args&: *this);
112 else
113 U = std::make_unique<DWARFCompileUnit>(args&: Context, args: InfoSection, args&: Header,
114 args: DA, args: RS, args: LocSection, args: SS, args: SOS,
115 args: AOS, args: LS, args: LE, args: IsDWO, args&: *this);
116 return U;
117 };
118 }
119 if (Lazy)
120 return;
121 // Find a reasonable insertion point within the vector. We skip over
122 // (a) units from a different section, (b) units from the same section
123 // but with lower offset-within-section. This keeps units in order
124 // within a section, although not necessarily within the object file,
125 // even if we do lazy parsing.
126 auto I = this->begin();
127 uint64_t Offset = 0;
128 while (Data.isValidOffset(offset: Offset)) {
129 if (I != this->end() &&
130 (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
131 ++I;
132 continue;
133 }
134 auto U = Parser(Offset, SectionKind, &Section, nullptr);
135 // If parsing failed, we're done with this section.
136 if (!U)
137 break;
138 Offset = U->getNextUnitOffset();
139 I = std::next(x: this->insert(I, Elt: std::move(U)));
140 }
141}
142
143DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {
144 auto I = llvm::upper_bound(Range&: *this, Value&: Unit,
145 C: [](const std::unique_ptr<DWARFUnit> &LHS,
146 const std::unique_ptr<DWARFUnit> &RHS) {
147 return LHS->getOffset() < RHS->getOffset();
148 });
149 return this->insert(I, Elt: std::move(Unit))->get();
150}
151
152DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {
153 auto end = begin() + getNumInfoUnits();
154 auto *CU =
155 std::upper_bound(first: begin(), last: end, val: Offset,
156 comp: [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
157 return LHS < RHS->getNextUnitOffset();
158 });
159 if (CU != end && (*CU)->getOffset() <= Offset)
160 return CU->get();
161 return nullptr;
162}
163
164DWARFUnit *DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E,
165 DWARFSectionKind Sec,
166 const DWARFSection *Section) {
167 const auto *CUOff = E.getContribution(Sec);
168 if (!CUOff)
169 return nullptr;
170
171 uint64_t Offset = CUOff->getOffset();
172 auto begin = this->begin();
173 auto end = begin + getNumInfoUnits();
174
175 if (Sec == DW_SECT_EXT_TYPES) {
176 begin = end;
177 end = this->end();
178 }
179
180 auto *CU =
181 std::upper_bound(first: begin, last: end, val: CUOff->getOffset(),
182 comp: [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
183 return LHS < RHS->getNextUnitOffset();
184 });
185 if (CU != end && (*CU)->getOffset() <= Offset)
186 return CU->get();
187
188 if (!Parser)
189 return nullptr;
190
191 auto U = Parser(Offset, Sec, Section, &E);
192 if (!U)
193 return nullptr;
194
195 auto *NewCU = U.get();
196 this->insert(I: CU, Elt: std::move(U));
197 if (Sec == DW_SECT_INFO)
198 ++NumInfoUnits;
199 return NewCU;
200}
201
202DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
203 const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
204 const DWARFSection *RS, const DWARFSection *LocSection,
205 StringRef SS, const DWARFSection &SOS,
206 const DWARFSection *AOS, const DWARFSection &LS, bool LE,
207 bool IsDWO, const DWARFUnitVector &UnitVector)
208 : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
209 RangeSection(RS), LineSection(LS), StringSection(SS),
210 StringOffsetSection(SOS), AddrOffsetSection(AOS), IsLittleEndian(LE),
211 IsDWO(IsDWO), UnitVector(UnitVector) {
212 clear();
213}
214
215DWARFUnit::~DWARFUnit() = default;
216
217DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
218 return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, IsLittleEndian,
219 getAddressByteSize());
220}
221
222std::optional<object::SectionedAddress>
223DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
224 if (!AddrOffsetSectionBase) {
225 auto R = Context.info_section_units();
226 // Surprising if a DWO file has more than one skeleton unit in it - this
227 // probably shouldn't be valid, but if a use case is found, here's where to
228 // support it (probably have to linearly search for the matching skeleton CU
229 // here)
230 if (IsDWO && hasSingleElement(C&: R))
231 return (*R.begin())->getAddrOffsetSectionItem(Index);
232
233 return std::nullopt;
234 }
235
236 uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
237 if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
238 return std::nullopt;
239 DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
240 IsLittleEndian, getAddressByteSize());
241 uint64_t Section;
242 uint64_t Address = DA.getRelocatedAddress(Off: &Offset, SecIx: &Section);
243 return {{.Address: Address, .SectionIndex: Section}};
244}
245
246Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
247 if (!StringOffsetsTableContribution)
248 return make_error<StringError>(
249 Args: "DW_FORM_strx used without a valid string offsets table",
250 Args: inconvertibleErrorCode());
251 unsigned ItemSize = getDwarfStringOffsetsByteSize();
252 uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
253 if (StringOffsetSection.Data.size() < Offset + ItemSize)
254 return make_error<StringError>(Args: "DW_FORM_strx uses index " + Twine(Index) +
255 ", which is too large",
256 Args: inconvertibleErrorCode());
257 DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
258 IsLittleEndian, 0);
259 return DA.getRelocatedValue(Size: ItemSize, Off: &Offset);
260}
261
262Error DWARFUnitHeader::extract(DWARFContext &Context,
263 const DWARFDataExtractor &debug_info,
264 uint64_t *offset_ptr,
265 DWARFSectionKind SectionKind) {
266 Offset = *offset_ptr;
267 Error Err = Error::success();
268 IndexEntry = nullptr;
269 std::tie(args&: Length, args&: FormParams.Format) =
270 debug_info.getInitialLength(Off: offset_ptr, Err: &Err);
271 FormParams.Version = debug_info.getU16(offset_ptr, Err: &Err);
272 if (FormParams.Version >= 5) {
273 UnitType = debug_info.getU8(offset_ptr, Err: &Err);
274 FormParams.AddrSize = debug_info.getU8(offset_ptr, Err: &Err);
275 AbbrOffset = debug_info.getRelocatedValue(
276 Size: FormParams.getDwarfOffsetByteSize(), Off: offset_ptr, SectionIndex: nullptr, Err: &Err);
277 } else {
278 AbbrOffset = debug_info.getRelocatedValue(
279 Size: FormParams.getDwarfOffsetByteSize(), Off: offset_ptr, SectionIndex: nullptr, Err: &Err);
280 FormParams.AddrSize = debug_info.getU8(offset_ptr, Err: &Err);
281 // Fake a unit type based on the section type. This isn't perfect,
282 // but distinguishing compile and type units is generally enough.
283 if (SectionKind == DW_SECT_EXT_TYPES)
284 UnitType = DW_UT_type;
285 else
286 UnitType = DW_UT_compile;
287 }
288 if (isTypeUnit()) {
289 TypeHash = debug_info.getU64(offset_ptr, Err: &Err);
290 TypeOffset = debug_info.getUnsigned(
291 offset_ptr, byte_size: FormParams.getDwarfOffsetByteSize(), Err: &Err);
292 } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
293 DWOId = debug_info.getU64(offset_ptr, Err: &Err);
294
295 if (Err)
296 return joinErrors(
297 E1: createStringError(
298 EC: errc::invalid_argument,
299 Fmt: "DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Vals: Offset),
300 E2: std::move(Err));
301
302 // Header fields all parsed, capture the size of this unit header.
303 assert(*offset_ptr - Offset <= 255 && "unexpected header size");
304 Size = uint8_t(*offset_ptr - Offset);
305 uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();
306
307 if (!debug_info.isValidOffset(offset: getNextUnitOffset() - 1))
308 return createStringError(EC: errc::invalid_argument,
309 Fmt: "DWARF unit from offset 0x%8.8" PRIx64 " incl. "
310 "to offset 0x%8.8" PRIx64 " excl. "
311 "extends past section size 0x%8.8zx",
312 Vals: Offset, Vals: NextCUOffset, Vals: debug_info.size());
313
314 if (!DWARFContext::isSupportedVersion(version: getVersion()))
315 return createStringError(
316 EC: errc::invalid_argument,
317 Fmt: "DWARF unit at offset 0x%8.8" PRIx64 " "
318 "has unsupported version %" PRIu16 ", supported are 2-%u",
319 Vals: Offset, Vals: getVersion(), Vals: DWARFContext::getMaxSupportedVersion());
320
321 // Type offset is unit-relative; should be after the header and before
322 // the end of the current unit.
323 if (isTypeUnit() && TypeOffset < Size)
324 return createStringError(EC: errc::invalid_argument,
325 Fmt: "DWARF type unit at offset "
326 "0x%8.8" PRIx64 " "
327 "has its relocated type_offset 0x%8.8" PRIx64 " "
328 "pointing inside the header",
329 Vals: Offset, Vals: Offset + TypeOffset);
330
331 if (isTypeUnit() && TypeOffset >= getUnitLengthFieldByteSize() + getLength())
332 return createStringError(
333 EC: errc::invalid_argument,
334 Fmt: "DWARF type unit from offset 0x%8.8" PRIx64 " incl. "
335 "to offset 0x%8.8" PRIx64 " excl. has its "
336 "relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",
337 Vals: Offset, Vals: NextCUOffset, Vals: Offset + TypeOffset);
338
339 if (Error SizeErr = DWARFContext::checkAddressSizeSupported(
340 AddressSize: getAddressByteSize(), EC: errc::invalid_argument,
341 Fmt: "DWARF unit at offset 0x%8.8" PRIx64, Vals: Offset))
342 return SizeErr;
343
344 // Keep track of the highest DWARF version we encounter across all units.
345 Context.setMaxVersionIfGreater(getVersion());
346 return Error::success();
347}
348
349Error DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
350 assert(Entry);
351 assert(!IndexEntry);
352 IndexEntry = Entry;
353 if (AbbrOffset)
354 return createStringError(EC: errc::invalid_argument,
355 Fmt: "DWARF package unit at offset 0x%8.8" PRIx64
356 " has a non-zero abbreviation offset",
357 Vals: Offset);
358
359 auto *UnitContrib = IndexEntry->getContribution();
360 if (!UnitContrib)
361 return createStringError(EC: errc::invalid_argument,
362 Fmt: "DWARF package unit at offset 0x%8.8" PRIx64
363 " has no contribution index",
364 Vals: Offset);
365
366 uint64_t IndexLength = getLength() + getUnitLengthFieldByteSize();
367 if (UnitContrib->getLength() != IndexLength)
368 return createStringError(EC: errc::invalid_argument,
369 Fmt: "DWARF package unit at offset 0x%8.8" PRIx64
370 " has an inconsistent index (expected: %" PRIu64
371 ", actual: %" PRIu64 ")",
372 Vals: Offset, Vals: UnitContrib->getLength(), Vals: IndexLength);
373
374 auto *AbbrEntry = IndexEntry->getContribution(Sec: DW_SECT_ABBREV);
375 if (!AbbrEntry)
376 return createStringError(EC: errc::invalid_argument,
377 Fmt: "DWARF package unit at offset 0x%8.8" PRIx64
378 " missing abbreviation column",
379 Vals: Offset);
380
381 AbbrOffset = AbbrEntry->getOffset();
382 return Error::success();
383}
384
385Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
386 DWARFDebugRangeList &RangeList) const {
387 // Require that compile unit is extracted.
388 assert(!DieArray.empty());
389 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
390 IsLittleEndian, getAddressByteSize());
391 uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
392 return RangeList.extract(data: RangesData, offset_ptr: &ActualRangeListOffset);
393}
394
395void DWARFUnit::clear() {
396 Abbrevs = nullptr;
397 BaseAddr.reset();
398 RangeSectionBase = 0;
399 LocSectionBase = 0;
400 AddrOffsetSectionBase = std::nullopt;
401 SU = nullptr;
402 clearDIEs(KeepCUDie: false);
403 AddrDieMap.clear();
404 if (DWO)
405 DWO->clear();
406 DWO.reset();
407}
408
409const char *DWARFUnit::getCompilationDir() {
410 return dwarf::toString(V: getUnitDIE().find(Attr: DW_AT_comp_dir), Default: nullptr);
411}
412
413void DWARFUnit::extractDIEsToVector(
414 bool AppendCUDie, bool AppendNonCUDies,
415 std::vector<DWARFDebugInfoEntry> &Dies) const {
416 if (!AppendCUDie && !AppendNonCUDies)
417 return;
418
419 // Set the offset to that of the first DIE and calculate the start of the
420 // next compilation unit header.
421 uint64_t DIEOffset = getOffset() + getHeaderSize();
422 uint64_t NextCUOffset = getNextUnitOffset();
423 DWARFDebugInfoEntry DIE;
424 DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
425 // The end offset has been already checked by DWARFUnitHeader::extract.
426 assert(DebugInfoData.isValidOffset(NextCUOffset - 1));
427 std::vector<uint32_t> Parents;
428 std::vector<uint32_t> PrevSiblings;
429 bool IsCUDie = true;
430
431 assert(
432 ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&
433 "Dies array is not empty");
434
435 // Fill Parents and Siblings stacks with initial value.
436 Parents.push_back(UINT32_MAX);
437 if (!AppendCUDie)
438 Parents.push_back(x: 0);
439 PrevSiblings.push_back(x: 0);
440
441 // Start to extract dies.
442 do {
443 assert(Parents.size() > 0 && "Empty parents stack");
444 assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&
445 "Wrong parent index");
446
447 // Extract die. Stop if any error occurred.
448 if (!DIE.extractFast(U: *this, OffsetPtr: &DIEOffset, DebugInfoData, UEndOffset: NextCUOffset,
449 ParentIdx: Parents.back()))
450 break;
451
452 // If previous sibling is remembered then update it`s SiblingIdx field.
453 if (PrevSiblings.back() > 0) {
454 assert(PrevSiblings.back() < Dies.size() &&
455 "Previous sibling index is out of Dies boundaries");
456 Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());
457 }
458
459 // Store die into the Dies vector.
460 if (IsCUDie) {
461 if (AppendCUDie)
462 Dies.push_back(x: DIE);
463 if (!AppendNonCUDies)
464 break;
465 // The average bytes per DIE entry has been seen to be
466 // around 14-20 so let's pre-reserve the needed memory for
467 // our DIE entries accordingly.
468 Dies.reserve(n: Dies.size() + getDebugInfoSize() / 14);
469 } else {
470 // Remember last previous sibling.
471 PrevSiblings.back() = Dies.size();
472
473 Dies.push_back(x: DIE);
474 }
475
476 // Check for new children scope.
477 if (const DWARFAbbreviationDeclaration *AbbrDecl =
478 DIE.getAbbreviationDeclarationPtr()) {
479 if (AbbrDecl->hasChildren()) {
480 if (AppendCUDie || !IsCUDie) {
481 assert(Dies.size() > 0 && "Dies does not contain any die");
482 Parents.push_back(x: Dies.size() - 1);
483 PrevSiblings.push_back(x: 0);
484 }
485 } else if (IsCUDie)
486 // Stop if we have single compile unit die w/o children.
487 break;
488 } else {
489 // NULL DIE: finishes current children scope.
490 Parents.pop_back();
491 PrevSiblings.pop_back();
492 }
493
494 if (IsCUDie)
495 IsCUDie = false;
496
497 // Stop when compile unit die is removed from the parents stack.
498 } while (Parents.size() > 1);
499 Dies.shrink_to_fit();
500}
501
502void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
503 if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
504 Context.getRecoverableErrorHandler()(std::move(e));
505}
506
507Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
508 if ((CUDieOnly && !DieArray.empty()) || DieArray.size() > 1)
509 return Error::success(); // Already parsed.
510
511 bool HasCUDie = !DieArray.empty();
512 extractDIEsToVector(AppendCUDie: !HasCUDie, AppendNonCUDies: !CUDieOnly, Dies&: DieArray);
513
514 if (DieArray.empty())
515 return Error::success();
516
517 // If CU DIE was just parsed, copy several attribute values from it.
518 if (HasCUDie)
519 return Error::success();
520
521 DWARFDie UnitDie(this, &DieArray[0]);
522 if (std::optional<uint64_t> DWOId =
523 toUnsigned(V: UnitDie.find(Attr: DW_AT_GNU_dwo_id)))
524 Header.setDWOId(*DWOId);
525 if (!IsDWO) {
526 assert(AddrOffsetSectionBase == std::nullopt);
527 assert(RangeSectionBase == 0);
528 assert(LocSectionBase == 0);
529 AddrOffsetSectionBase = toSectionOffset(V: UnitDie.find(Attr: DW_AT_addr_base));
530 if (!AddrOffsetSectionBase)
531 AddrOffsetSectionBase =
532 toSectionOffset(V: UnitDie.find(Attr: DW_AT_GNU_addr_base));
533 RangeSectionBase = toSectionOffset(V: UnitDie.find(Attr: DW_AT_rnglists_base), Default: 0);
534 LocSectionBase = toSectionOffset(V: UnitDie.find(Attr: DW_AT_loclists_base), Default: 0);
535 }
536
537 // In general, in DWARF v5 and beyond we derive the start of the unit's
538 // contribution to the string offsets table from the unit DIE's
539 // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
540 // attribute, so we assume that there is a contribution to the string
541 // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
542 // In both cases we need to determine the format of the contribution,
543 // which may differ from the unit's format.
544 DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
545 IsLittleEndian, 0);
546 if (IsDWO || getVersion() >= 5) {
547 auto StringOffsetOrError =
548 IsDWO ? determineStringOffsetsTableContributionDWO(DA)
549 : determineStringOffsetsTableContribution(DA);
550 if (!StringOffsetOrError)
551 return createStringError(EC: errc::invalid_argument,
552 S: "invalid reference to or invalid content in "
553 ".debug_str_offsets[.dwo]: " +
554 toString(E: StringOffsetOrError.takeError()));
555
556 StringOffsetsTableContribution = *StringOffsetOrError;
557 }
558
559 // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
560 // describe address ranges.
561 if (getVersion() >= 5) {
562 // In case of DWP, the base offset from the index has to be added.
563 if (IsDWO) {
564 uint64_t ContributionBaseOffset = 0;
565 if (auto *IndexEntry = Header.getIndexEntry())
566 if (auto *Contrib = IndexEntry->getContribution(Sec: DW_SECT_RNGLISTS))
567 ContributionBaseOffset = Contrib->getOffset();
568 setRangesSection(
569 RS: &Context.getDWARFObj().getRnglistsDWOSection(),
570 Base: ContributionBaseOffset +
571 DWARFListTableHeader::getHeaderSize(Format: Header.getFormat()));
572 } else
573 setRangesSection(RS: &Context.getDWARFObj().getRnglistsSection(),
574 Base: toSectionOffset(V: UnitDie.find(Attr: DW_AT_rnglists_base),
575 Default: DWARFListTableHeader::getHeaderSize(
576 Format: Header.getFormat())));
577 }
578
579 if (IsDWO) {
580 // If we are reading a package file, we need to adjust the location list
581 // data based on the index entries.
582 StringRef Data = Header.getVersion() >= 5
583 ? Context.getDWARFObj().getLoclistsDWOSection().Data
584 : Context.getDWARFObj().getLocDWOSection().Data;
585 if (auto *IndexEntry = Header.getIndexEntry())
586 if (const auto *C = IndexEntry->getContribution(
587 Sec: Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
588 Data = Data.substr(Start: C->getOffset(), N: C->getLength());
589
590 DWARFDataExtractor DWARFData(Data, IsLittleEndian, getAddressByteSize());
591 LocTable =
592 std::make_unique<DWARFDebugLoclists>(args&: DWARFData, args: Header.getVersion());
593 LocSectionBase = DWARFListTableHeader::getHeaderSize(Format: Header.getFormat());
594 } else if (getVersion() >= 5) {
595 LocTable = std::make_unique<DWARFDebugLoclists>(
596 args: DWARFDataExtractor(Context.getDWARFObj(),
597 Context.getDWARFObj().getLoclistsSection(),
598 IsLittleEndian, getAddressByteSize()),
599 args: getVersion());
600 } else {
601 LocTable = std::make_unique<DWARFDebugLoc>(args: DWARFDataExtractor(
602 Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),
603 IsLittleEndian, getAddressByteSize()));
604 }
605
606 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
607 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
608 return Error::success();
609}
610
611bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {
612 if (IsDWO)
613 return false;
614 if (DWO)
615 return false;
616 DWARFDie UnitDie = getUnitDIE();
617 if (!UnitDie)
618 return false;
619 auto DWOFileName = getVersion() >= 5
620 ? dwarf::toString(V: UnitDie.find(Attr: DW_AT_dwo_name))
621 : dwarf::toString(V: UnitDie.find(Attr: DW_AT_GNU_dwo_name));
622 if (!DWOFileName)
623 return false;
624 auto CompilationDir = dwarf::toString(V: UnitDie.find(Attr: DW_AT_comp_dir));
625 SmallString<16> AbsolutePath;
626 if (sys::path::is_relative(path: *DWOFileName) && CompilationDir &&
627 *CompilationDir) {
628 sys::path::append(path&: AbsolutePath, a: *CompilationDir);
629 }
630 sys::path::append(path&: AbsolutePath, a: *DWOFileName);
631 auto DWOId = getDWOId();
632 if (!DWOId)
633 return false;
634 auto DWOContext = Context.getDWOContext(AbsolutePath);
635 if (!DWOContext) {
636 // Use the alternative location to get the DWARF context for the DWO object.
637 if (DWOAlternativeLocation.empty())
638 return false;
639 // If the alternative context does not correspond to the original DWO object
640 // (different hashes), the below 'getDWOCompileUnitForHash' call will catch
641 // the issue, with a returned null context.
642 DWOContext = Context.getDWOContext(AbsolutePath: DWOAlternativeLocation);
643 if (!DWOContext)
644 return false;
645 }
646
647 DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(Hash: *DWOId);
648 if (!DWOCU)
649 return false;
650 DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
651 DWO->setSkeletonUnit(this);
652 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
653 if (AddrOffsetSectionBase)
654 DWO->setAddrOffsetSection(AOS: AddrOffsetSection, Base: *AddrOffsetSectionBase);
655 if (getVersion() == 4) {
656 auto DWORangesBase = UnitDie.getRangesBaseAttribute();
657 DWO->setRangesSection(RS: RangeSection, Base: DWORangesBase.value_or(u: 0));
658 }
659
660 return true;
661}
662
663void DWARFUnit::clearDIEs(bool KeepCUDie) {
664 // Do not use resize() + shrink_to_fit() to free memory occupied by dies.
665 // shrink_to_fit() is a *non-binding* request to reduce capacity() to size().
666 // It depends on the implementation whether the request is fulfilled.
667 // Create a new vector with a small capacity and assign it to the DieArray to
668 // have previous contents freed.
669 DieArray = (KeepCUDie && !DieArray.empty())
670 ? std::vector<DWARFDebugInfoEntry>({DieArray[0]})
671 : std::vector<DWARFDebugInfoEntry>();
672}
673
674Expected<DWARFAddressRangesVector>
675DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
676 if (getVersion() <= 4) {
677 DWARFDebugRangeList RangeList;
678 if (Error E = extractRangeList(RangeListOffset: Offset, RangeList))
679 return std::move(E);
680 return RangeList.getAbsoluteRanges(BaseAddr: getBaseAddress());
681 }
682 DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
683 IsLittleEndian, Header.getAddressByteSize());
684 DWARFDebugRnglistTable RnglistTable;
685 auto RangeListOrError = RnglistTable.findList(Data: RangesData, Offset);
686 if (RangeListOrError)
687 return RangeListOrError.get().getAbsoluteRanges(BaseAddr: getBaseAddress(), U&: *this);
688 return RangeListOrError.takeError();
689}
690
691Expected<DWARFAddressRangesVector>
692DWARFUnit::findRnglistFromIndex(uint32_t Index) {
693 if (auto Offset = getRnglistOffset(Index))
694 return findRnglistFromOffset(Offset: *Offset);
695
696 return createStringError(EC: errc::invalid_argument,
697 Fmt: "invalid range list table index %d (possibly "
698 "missing the entire range list table)",
699 Vals: Index);
700}
701
702Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
703 DWARFDie UnitDie = getUnitDIE();
704 if (!UnitDie)
705 return createStringError(EC: errc::invalid_argument, S: "No unit DIE");
706
707 // First, check if unit DIE describes address ranges for the whole unit.
708 auto CUDIERangesOrError = UnitDie.getAddressRanges();
709 if (!CUDIERangesOrError)
710 return createStringError(EC: errc::invalid_argument,
711 Fmt: "decoding address ranges: %s",
712 Vals: toString(E: CUDIERangesOrError.takeError()).c_str());
713 return *CUDIERangesOrError;
714}
715
716Expected<DWARFLocationExpressionsVector>
717DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
718 DWARFLocationExpressionsVector Result;
719
720 Error InterpretationError = Error::success();
721
722 Error ParseError = getLocationTable().visitAbsoluteLocationList(
723 Offset, BaseAddr: getBaseAddress(),
724 LookupAddr: [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
725 Callback: [&](Expected<DWARFLocationExpression> L) {
726 if (L)
727 Result.push_back(x: std::move(*L));
728 else
729 InterpretationError =
730 joinErrors(E1: L.takeError(), E2: std::move(InterpretationError));
731 return !InterpretationError;
732 });
733
734 if (ParseError || InterpretationError)
735 return joinErrors(E1: std::move(ParseError), E2: std::move(InterpretationError));
736
737 return Result;
738}
739
740void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
741 if (Die.isSubroutineDIE()) {
742 auto DIERangesOrError = Die.getAddressRanges();
743 if (DIERangesOrError) {
744 for (const auto &R : DIERangesOrError.get()) {
745 // Ignore 0-sized ranges.
746 if (R.LowPC == R.HighPC)
747 continue;
748 auto B = AddrDieMap.upper_bound(x: R.LowPC);
749 if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
750 // The range is a sub-range of existing ranges, we need to split the
751 // existing range.
752 if (R.HighPC < B->second.first)
753 AddrDieMap[R.HighPC] = B->second;
754 if (R.LowPC > B->first)
755 AddrDieMap[B->first].first = R.LowPC;
756 }
757 AddrDieMap[R.LowPC] = std::make_pair(x: R.HighPC, y&: Die);
758 }
759 } else
760 llvm::consumeError(Err: DIERangesOrError.takeError());
761 }
762 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
763 // simplify the logic to update AddrDieMap. The child's range will always
764 // be equal or smaller than the parent's range. With this assumption, when
765 // adding one range into the map, it will at most split a range into 3
766 // sub-ranges.
767 for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
768 updateAddressDieMap(Die: Child);
769}
770
771DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
772 extractDIEsIfNeeded(CUDieOnly: false);
773 if (AddrDieMap.empty())
774 updateAddressDieMap(Die: getUnitDIE());
775 auto R = AddrDieMap.upper_bound(x: Address);
776 if (R == AddrDieMap.begin())
777 return DWARFDie();
778 // upper_bound's previous item contains Address.
779 --R;
780 if (Address >= R->second.first)
781 return DWARFDie();
782 return R->second.second;
783}
784
785void DWARFUnit::updateVariableDieMap(DWARFDie Die) {
786 for (DWARFDie Child : Die) {
787 if (isType(T: Child.getTag()))
788 continue;
789 updateVariableDieMap(Die: Child);
790 }
791
792 if (Die.getTag() != DW_TAG_variable)
793 return;
794
795 Expected<DWARFLocationExpressionsVector> Locations =
796 Die.getLocations(Attr: DW_AT_location);
797 if (!Locations) {
798 // Missing DW_AT_location is fine here.
799 consumeError(Err: Locations.takeError());
800 return;
801 }
802
803 uint64_t Address = UINT64_MAX;
804
805 for (const DWARFLocationExpression &Location : *Locations) {
806 uint8_t AddressSize = getAddressByteSize();
807 DataExtractor Data(Location.Expr, isLittleEndian());
808 DWARFExpression Expr(Data, AddressSize);
809 auto It = Expr.begin();
810 if (It == Expr.end())
811 continue;
812
813 // Match exactly the main sequence used to describe global variables:
814 // `DW_OP_addr[x] [+ DW_OP_plus_uconst]`. Currently, this is the sequence
815 // that LLVM produces for DILocalVariables and DIGlobalVariables. If, in
816 // future, the DWARF producer (`DwarfCompileUnit::addLocationAttribute()` is
817 // a good starting point) is extended to use further expressions, this code
818 // needs to be updated.
819 uint64_t LocationAddr;
820 if (It->getCode() == dwarf::DW_OP_addr) {
821 LocationAddr = It->getRawOperand(Idx: 0);
822 } else if (It->getCode() == dwarf::DW_OP_addrx) {
823 uint64_t DebugAddrOffset = It->getRawOperand(Idx: 0);
824 if (auto Pointer = getAddrOffsetSectionItem(Index: DebugAddrOffset)) {
825 LocationAddr = Pointer->Address;
826 }
827 } else {
828 continue;
829 }
830
831 // Read the optional 2nd operand, a DW_OP_plus_uconst.
832 if (++It != Expr.end()) {
833 if (It->getCode() != dwarf::DW_OP_plus_uconst)
834 continue;
835
836 LocationAddr += It->getRawOperand(Idx: 0);
837
838 // Probe for a 3rd operand, if it exists, bail.
839 if (++It != Expr.end())
840 continue;
841 }
842
843 Address = LocationAddr;
844 break;
845 }
846
847 // Get the size of the global variable. If all else fails (i.e. the global has
848 // no type), then we use a size of one to still allow symbolization of the
849 // exact address.
850 uint64_t GVSize = 1;
851 if (Die.getAttributeValueAsReferencedDie(Attr: DW_AT_type))
852 if (std::optional<uint64_t> Size = Die.getTypeSize(PointerSize: getAddressByteSize()))
853 GVSize = *Size;
854
855 if (Address != UINT64_MAX)
856 VariableDieMap[Address] = {Address + GVSize, Die};
857}
858
859DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {
860 extractDIEsIfNeeded(CUDieOnly: false);
861
862 auto RootDie = getUnitDIE();
863
864 auto RootLookup = RootsParsedForVariables.insert(V: RootDie.getOffset());
865 if (RootLookup.second)
866 updateVariableDieMap(Die: RootDie);
867
868 auto R = VariableDieMap.upper_bound(x: Address);
869 if (R == VariableDieMap.begin())
870 return DWARFDie();
871
872 // upper_bound's previous item contains Address.
873 --R;
874 if (Address >= R->second.first)
875 return DWARFDie();
876 return R->second.second;
877}
878
879void
880DWARFUnit::getInlinedChainForAddress(uint64_t Address,
881 SmallVectorImpl<DWARFDie> &InlinedChain) {
882 assert(InlinedChain.empty());
883 // Try to look for subprogram DIEs in the DWO file.
884 parseDWO();
885 // First, find the subroutine that contains the given address (the leaf
886 // of inlined chain).
887 DWARFDie SubroutineDIE =
888 (DWO ? *DWO : *this).getSubroutineForAddress(Address);
889
890 while (SubroutineDIE) {
891 if (SubroutineDIE.isSubprogramDIE()) {
892 InlinedChain.push_back(Elt: SubroutineDIE);
893 return;
894 }
895 if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
896 InlinedChain.push_back(Elt: SubroutineDIE);
897 SubroutineDIE = SubroutineDIE.getParent();
898 }
899}
900
901const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
902 DWARFSectionKind Kind) {
903 if (Kind == DW_SECT_INFO)
904 return Context.getCUIndex();
905 assert(Kind == DW_SECT_EXT_TYPES);
906 return Context.getTUIndex();
907}
908
909DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
910 if (const DWARFDebugInfoEntry *Entry = getParentEntry(Die))
911 return DWARFDie(this, Entry);
912
913 return DWARFDie();
914}
915
916const DWARFDebugInfoEntry *
917DWARFUnit::getParentEntry(const DWARFDebugInfoEntry *Die) const {
918 if (!Die)
919 return nullptr;
920 assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
921
922 if (std::optional<uint32_t> ParentIdx = Die->getParentIdx()) {
923 assert(*ParentIdx < DieArray.size() &&
924 "ParentIdx is out of DieArray boundaries");
925 return getDebugInfoEntry(Index: *ParentIdx);
926 }
927
928 return nullptr;
929}
930
931DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
932 if (const DWARFDebugInfoEntry *Sibling = getSiblingEntry(Die))
933 return DWARFDie(this, Sibling);
934
935 return DWARFDie();
936}
937
938const DWARFDebugInfoEntry *
939DWARFUnit::getSiblingEntry(const DWARFDebugInfoEntry *Die) const {
940 if (!Die)
941 return nullptr;
942 assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
943
944 if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
945 assert(*SiblingIdx < DieArray.size() &&
946 "SiblingIdx is out of DieArray boundaries");
947 return &DieArray[*SiblingIdx];
948 }
949
950 return nullptr;
951}
952
953DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
954 if (const DWARFDebugInfoEntry *Sibling = getPreviousSiblingEntry(Die))
955 return DWARFDie(this, Sibling);
956
957 return DWARFDie();
958}
959
960const DWARFDebugInfoEntry *
961DWARFUnit::getPreviousSiblingEntry(const DWARFDebugInfoEntry *Die) const {
962 if (!Die)
963 return nullptr;
964 assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
965
966 std::optional<uint32_t> ParentIdx = Die->getParentIdx();
967 if (!ParentIdx)
968 // Die is a root die, there is no previous sibling.
969 return nullptr;
970
971 assert(*ParentIdx < DieArray.size() &&
972 "ParentIdx is out of DieArray boundaries");
973 assert(getDIEIndex(Die) > 0 && "Die is a root die");
974
975 uint32_t PrevDieIdx = getDIEIndex(Die) - 1;
976 if (PrevDieIdx == *ParentIdx)
977 // Immediately previous node is parent, there is no previous sibling.
978 return nullptr;
979
980 while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {
981 PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();
982
983 assert(PrevDieIdx < DieArray.size() &&
984 "PrevDieIdx is out of DieArray boundaries");
985 assert(PrevDieIdx >= *ParentIdx &&
986 "PrevDieIdx is not a child of parent of Die");
987 }
988
989 return &DieArray[PrevDieIdx];
990}
991
992DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
993 if (const DWARFDebugInfoEntry *Child = getFirstChildEntry(Die))
994 return DWARFDie(this, Child);
995
996 return DWARFDie();
997}
998
999const DWARFDebugInfoEntry *
1000DWARFUnit::getFirstChildEntry(const DWARFDebugInfoEntry *Die) const {
1001 if (!Die)
1002 return nullptr;
1003 assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
1004
1005 if (!Die->hasChildren())
1006 return nullptr;
1007
1008 // TODO: Instead of checking here for invalid die we might reject
1009 // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
1010 // We do not want access out of bounds when parsing corrupted debug data.
1011 size_t I = getDIEIndex(Die) + 1;
1012 if (I >= DieArray.size())
1013 return nullptr;
1014 return &DieArray[I];
1015}
1016
1017DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
1018 if (const DWARFDebugInfoEntry *Child = getLastChildEntry(Die))
1019 return DWARFDie(this, Child);
1020
1021 return DWARFDie();
1022}
1023
1024const DWARFDebugInfoEntry *
1025DWARFUnit::getLastChildEntry(const DWARFDebugInfoEntry *Die) const {
1026 if (!Die)
1027 return nullptr;
1028 assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
1029
1030 if (!Die->hasChildren())
1031 return nullptr;
1032
1033 if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
1034 assert(*SiblingIdx < DieArray.size() &&
1035 "SiblingIdx is out of DieArray boundaries");
1036 assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&
1037 "Bad end of children marker");
1038 return &DieArray[*SiblingIdx - 1];
1039 }
1040
1041 // If SiblingIdx is set for non-root dies we could be sure that DWARF is
1042 // correct and "end of children marker" must be found. For root die we do not
1043 // have such a guarantee(parsing root die might be stopped if "end of children
1044 // marker" is missing, SiblingIdx is always zero for root die). That is why we
1045 // do not use assertion for checking for "end of children marker" for root
1046 // die.
1047
1048 // TODO: Instead of checking here for invalid die we might reject
1049 // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
1050 if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&
1051 DieArray.back().getTag() == dwarf::DW_TAG_null) {
1052 // For the unit die we might take last item from DieArray.
1053 assert(getDIEIndex(Die) ==
1054 getDIEIndex(const_cast<DWARFUnit *>(this)->getUnitDIE()) &&
1055 "Bad unit die");
1056 return &DieArray.back();
1057 }
1058
1059 return nullptr;
1060}
1061
1062const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
1063 if (!Abbrevs) {
1064 Expected<const DWARFAbbreviationDeclarationSet *> AbbrevsOrError =
1065 Abbrev->getAbbreviationDeclarationSet(CUAbbrOffset: getAbbreviationsOffset());
1066 if (!AbbrevsOrError) {
1067 // FIXME: We should propagate this error upwards.
1068 consumeError(Err: AbbrevsOrError.takeError());
1069 return nullptr;
1070 }
1071 Abbrevs = *AbbrevsOrError;
1072 }
1073 return Abbrevs;
1074}
1075
1076std::optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
1077 if (BaseAddr)
1078 return BaseAddr;
1079
1080 DWARFDie UnitDie = (SU ? SU : this)->getUnitDIE();
1081 std::optional<DWARFFormValue> PC =
1082 UnitDie.find(Attrs: {DW_AT_low_pc, DW_AT_entry_pc});
1083 BaseAddr = toSectionedAddress(V: PC);
1084 return BaseAddr;
1085}
1086
1087Expected<StrOffsetsContributionDescriptor>
1088StrOffsetsContributionDescriptor::validateContributionSize(
1089 DWARFDataExtractor &DA) {
1090 uint8_t EntrySize = getDwarfOffsetByteSize();
1091 // In order to ensure that we don't read a partial record at the end of
1092 // the section we validate for a multiple of the entry size.
1093 uint64_t ValidationSize = alignTo(Value: Size, Align: EntrySize);
1094 // Guard against overflow.
1095 if (ValidationSize >= Size)
1096 if (DA.isValidOffsetForDataOfSize(offset: (uint32_t)Base, length: ValidationSize))
1097 return *this;
1098 return createStringError(EC: errc::invalid_argument, S: "length exceeds section size");
1099}
1100
1101// Look for a DWARF64-formatted contribution to the string offsets table
1102// starting at a given offset and record it in a descriptor.
1103static Expected<StrOffsetsContributionDescriptor>
1104parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
1105 if (!DA.isValidOffsetForDataOfSize(offset: Offset, length: 16))
1106 return createStringError(EC: errc::invalid_argument, S: "section offset exceeds section size");
1107
1108 if (DA.getU32(offset_ptr: &Offset) != dwarf::DW_LENGTH_DWARF64)
1109 return createStringError(EC: errc::invalid_argument, S: "32 bit contribution referenced from a 64 bit unit");
1110
1111 uint64_t Size = DA.getU64(offset_ptr: &Offset);
1112 uint8_t Version = DA.getU16(offset_ptr: &Offset);
1113 (void)DA.getU16(offset_ptr: &Offset); // padding
1114 // The encoded length includes the 2-byte version field and the 2-byte
1115 // padding, so we need to subtract them out when we populate the descriptor.
1116 return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
1117}
1118
1119// Look for a DWARF32-formatted contribution to the string offsets table
1120// starting at a given offset and record it in a descriptor.
1121static Expected<StrOffsetsContributionDescriptor>
1122parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
1123 if (!DA.isValidOffsetForDataOfSize(offset: Offset, length: 8))
1124 return createStringError(EC: errc::invalid_argument, S: "section offset exceeds section size");
1125
1126 uint32_t ContributionSize = DA.getU32(offset_ptr: &Offset);
1127 if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
1128 return createStringError(EC: errc::invalid_argument, S: "invalid length");
1129
1130 uint8_t Version = DA.getU16(offset_ptr: &Offset);
1131 (void)DA.getU16(offset_ptr: &Offset); // padding
1132 // The encoded length includes the 2-byte version field and the 2-byte
1133 // padding, so we need to subtract them out when we populate the descriptor.
1134 return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
1135 DWARF32);
1136}
1137
1138static Expected<StrOffsetsContributionDescriptor>
1139parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
1140 llvm::dwarf::DwarfFormat Format,
1141 uint64_t Offset) {
1142 StrOffsetsContributionDescriptor Desc;
1143 switch (Format) {
1144 case dwarf::DwarfFormat::DWARF64: {
1145 if (Offset < 16)
1146 return createStringError(EC: errc::invalid_argument, S: "insufficient space for 64 bit header prefix");
1147 auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset: Offset - 16);
1148 if (!DescOrError)
1149 return DescOrError.takeError();
1150 Desc = *DescOrError;
1151 break;
1152 }
1153 case dwarf::DwarfFormat::DWARF32: {
1154 if (Offset < 8)
1155 return createStringError(EC: errc::invalid_argument, S: "insufficient space for 32 bit header prefix");
1156 auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset: Offset - 8);
1157 if (!DescOrError)
1158 return DescOrError.takeError();
1159 Desc = *DescOrError;
1160 break;
1161 }
1162 }
1163 return Desc.validateContributionSize(DA);
1164}
1165
1166Expected<std::optional<StrOffsetsContributionDescriptor>>
1167DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
1168 assert(!IsDWO);
1169 auto OptOffset = toSectionOffset(V: getUnitDIE().find(Attr: DW_AT_str_offsets_base));
1170 if (!OptOffset)
1171 return std::nullopt;
1172 auto DescOrError =
1173 parseDWARFStringOffsetsTableHeader(DA, Format: Header.getFormat(), Offset: *OptOffset);
1174 if (!DescOrError)
1175 return DescOrError.takeError();
1176 return *DescOrError;
1177}
1178
1179Expected<std::optional<StrOffsetsContributionDescriptor>>
1180DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA) {
1181 assert(IsDWO);
1182 uint64_t Offset = 0;
1183 auto IndexEntry = Header.getIndexEntry();
1184 const auto *C =
1185 IndexEntry ? IndexEntry->getContribution(Sec: DW_SECT_STR_OFFSETS) : nullptr;
1186 if (C)
1187 Offset = C->getOffset();
1188 if (getVersion() >= 5) {
1189 if (DA.getData().data() == nullptr)
1190 return std::nullopt;
1191 // FYI: The .debug_str_offsets.dwo section may use DWARF64 even when the
1192 // rest of the file uses DWARF32, so respect whichever encoding the
1193 // header/length uses.
1194 uint64_t Length = 0;
1195 DwarfFormat Format = dwarf::DwarfFormat::DWARF32;
1196 std::tie(args&: Length, args&: Format) = DA.getInitialLength(Off: &Offset);
1197 Offset += 4; // Skip the DWARF version uint16_t and the uint16_t padding.
1198 // Look for a valid contribution at the given offset.
1199 auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Format, Offset);
1200 if (!DescOrError)
1201 return DescOrError.takeError();
1202 return *DescOrError;
1203 }
1204 // Prior to DWARF v5, we derive the contribution size from the
1205 // index table (in a package file). In a .dwo file it is simply
1206 // the length of the string offsets section.
1207 StrOffsetsContributionDescriptor Desc;
1208 if (C)
1209 Desc = StrOffsetsContributionDescriptor(C->getOffset(), C->getLength(), 4,
1210 Header.getFormat());
1211 else if (!IndexEntry && !StringOffsetSection.Data.empty())
1212 Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
1213 4, Header.getFormat());
1214 else
1215 return std::nullopt;
1216 auto DescOrError = Desc.validateContributionSize(DA);
1217 if (!DescOrError)
1218 return DescOrError.takeError();
1219 return *DescOrError;
1220}
1221
1222std::optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
1223 DataExtractor RangesData(RangeSection->Data, IsLittleEndian);
1224 DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
1225 IsLittleEndian, 0);
1226 if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1227 Data: RangesData, OffsetTableOffset: RangeSectionBase, Format: getFormat(), Index))
1228 return *Off + RangeSectionBase;
1229 return std::nullopt;
1230}
1231
1232std::optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {
1233 if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1234 Data: LocTable->getData(), OffsetTableOffset: LocSectionBase, Format: getFormat(), Index))
1235 return *Off + LocSectionBase;
1236 return std::nullopt;
1237}
1238