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