1 //===- DWARFUnit.cpp ------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/ADT/StringRef.h"
12 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
13 #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
14 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
15 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
16 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/Path.h"
24 #include "llvm/Support/WithColor.h"
34 using namespace dwarf
;
36 void DWARFUnitVector::addUnitsForSection(DWARFContext
&C
,
37 const DWARFSection
&Section
,
38 DWARFSectionKind SectionKind
) {
39 const DWARFObject
&D
= C
.getDWARFObj();
40 addUnitsImpl(C
, D
, Section
, C
.getDebugAbbrev(), &D
.getRangesSection(),
41 &D
.getLocSection(), D
.getStrSection(),
42 D
.getStrOffsetsSection(), &D
.getAddrSection(),
43 D
.getLineSection(), D
.isLittleEndian(), false, false,
47 void DWARFUnitVector::addUnitsForDWOSection(DWARFContext
&C
,
48 const DWARFSection
&DWOSection
,
49 DWARFSectionKind SectionKind
,
51 const DWARFObject
&D
= C
.getDWARFObj();
52 addUnitsImpl(C
, D
, DWOSection
, C
.getDebugAbbrevDWO(), &D
.getRangesDWOSection(),
53 &D
.getLocDWOSection(), D
.getStrDWOSection(),
54 D
.getStrOffsetsDWOSection(), &D
.getAddrSection(),
55 D
.getLineDWOSection(), C
.isLittleEndian(), true, Lazy
,
59 void DWARFUnitVector::addUnitsImpl(
60 DWARFContext
&Context
, const DWARFObject
&Obj
, const DWARFSection
&Section
,
61 const DWARFDebugAbbrev
*DA
, const DWARFSection
*RS
,
62 const DWARFSection
*LocSection
, StringRef SS
, const DWARFSection
&SOS
,
63 const DWARFSection
*AOS
, const DWARFSection
&LS
, bool LE
, bool IsDWO
,
64 bool Lazy
, DWARFSectionKind SectionKind
) {
65 DWARFDataExtractor
Data(Obj
, Section
, LE
, 0);
66 // Lazy initialization of Parser, now that we have all section info.
68 Parser
= [=, &Context
, &Obj
, &Section
, &SOS
,
69 &LS
](uint64_t Offset
, DWARFSectionKind SectionKind
,
70 const DWARFSection
*CurSection
,
71 const DWARFUnitIndex::Entry
*IndexEntry
)
72 -> std::unique_ptr
<DWARFUnit
> {
73 const DWARFSection
&InfoSection
= CurSection
? *CurSection
: Section
;
74 DWARFDataExtractor
Data(Obj
, InfoSection
, LE
, 0);
75 if (!Data
.isValidOffset(Offset
))
77 const DWARFUnitIndex
*Index
= nullptr;
79 Index
= &getDWARFUnitIndex(Context
, SectionKind
);
80 DWARFUnitHeader Header
;
81 if (!Header
.extract(Context
, Data
, &Offset
, SectionKind
, Index
,
84 std::unique_ptr
<DWARFUnit
> U
;
85 if (Header
.isTypeUnit())
86 U
= std::make_unique
<DWARFTypeUnit
>(Context
, InfoSection
, Header
, DA
,
87 RS
, LocSection
, SS
, SOS
, AOS
, LS
,
90 U
= std::make_unique
<DWARFCompileUnit
>(Context
, InfoSection
, Header
,
91 DA
, RS
, LocSection
, SS
, SOS
,
92 AOS
, LS
, LE
, IsDWO
, *this);
98 // Find a reasonable insertion point within the vector. We skip over
99 // (a) units from a different section, (b) units from the same section
100 // but with lower offset-within-section. This keeps units in order
101 // within a section, although not necessarily within the object file,
102 // even if we do lazy parsing.
103 auto I
= this->begin();
105 while (Data
.isValidOffset(Offset
)) {
106 if (I
!= this->end() &&
107 (&(*I
)->getInfoSection() != &Section
|| (*I
)->getOffset() == Offset
)) {
111 auto U
= Parser(Offset
, SectionKind
, &Section
, nullptr);
112 // If parsing failed, we're done with this section.
115 Offset
= U
->getNextUnitOffset();
116 I
= std::next(this->insert(I
, std::move(U
)));
120 DWARFUnit
*DWARFUnitVector::addUnit(std::unique_ptr
<DWARFUnit
> Unit
) {
121 auto I
= std::upper_bound(begin(), end(), Unit
,
122 [](const std::unique_ptr
<DWARFUnit
> &LHS
,
123 const std::unique_ptr
<DWARFUnit
> &RHS
) {
124 return LHS
->getOffset() < RHS
->getOffset();
126 return this->insert(I
, std::move(Unit
))->get();
129 DWARFUnit
*DWARFUnitVector::getUnitForOffset(uint64_t Offset
) const {
130 auto end
= begin() + getNumInfoUnits();
132 std::upper_bound(begin(), end
, Offset
,
133 [](uint64_t LHS
, const std::unique_ptr
<DWARFUnit
> &RHS
) {
134 return LHS
< RHS
->getNextUnitOffset();
136 if (CU
!= end
&& (*CU
)->getOffset() <= Offset
)
142 DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry
&E
) {
143 const auto *CUOff
= E
.getOffset(DW_SECT_INFO
);
147 auto Offset
= CUOff
->Offset
;
148 auto end
= begin() + getNumInfoUnits();
151 std::upper_bound(begin(), end
, CUOff
->Offset
,
152 [](uint64_t LHS
, const std::unique_ptr
<DWARFUnit
> &RHS
) {
153 return LHS
< RHS
->getNextUnitOffset();
155 if (CU
!= end
&& (*CU
)->getOffset() <= Offset
)
161 auto U
= Parser(Offset
, DW_SECT_INFO
, nullptr, &E
);
165 auto *NewCU
= U
.get();
166 this->insert(CU
, std::move(U
));
171 DWARFUnit::DWARFUnit(DWARFContext
&DC
, const DWARFSection
&Section
,
172 const DWARFUnitHeader
&Header
, const DWARFDebugAbbrev
*DA
,
173 const DWARFSection
*RS
, const DWARFSection
*LocSection
,
174 StringRef SS
, const DWARFSection
&SOS
,
175 const DWARFSection
*AOS
, const DWARFSection
&LS
, bool LE
,
176 bool IsDWO
, const DWARFUnitVector
&UnitVector
)
177 : Context(DC
), InfoSection(Section
), Header(Header
), Abbrev(DA
),
178 RangeSection(RS
), LocSection(LocSection
), LineSection(LS
),
179 StringSection(SS
), StringOffsetSection(SOS
), AddrOffsetSection(AOS
),
180 isLittleEndian(LE
), IsDWO(IsDWO
), UnitVector(UnitVector
) {
182 // For split DWARF we only need to keep track of the location list section's
183 // data (no relocations), and if we are reading a package file, we need to
184 // adjust the location list data based on the index entries.
186 LocSectionData
= LocSection
->Data
;
187 if (auto *IndexEntry
= Header
.getIndexEntry())
188 if (const auto *C
= IndexEntry
->getOffset(DW_SECT_LOC
))
189 LocSectionData
= LocSectionData
.substr(C
->Offset
, C
->Length
);
193 DWARFUnit::~DWARFUnit() = default;
195 DWARFDataExtractor
DWARFUnit::getDebugInfoExtractor() const {
196 return DWARFDataExtractor(Context
.getDWARFObj(), InfoSection
, isLittleEndian
,
197 getAddressByteSize());
200 Optional
<object::SectionedAddress
>
201 DWARFUnit::getAddrOffsetSectionItem(uint32_t Index
) const {
203 auto R
= Context
.info_section_units();
205 // Surprising if a DWO file has more than one skeleton unit in it - this
206 // probably shouldn't be valid, but if a use case is found, here's where to
207 // support it (probably have to linearly search for the matching skeleton CU
209 if (I
!= R
.end() && std::next(I
) == R
.end())
210 return (*I
)->getAddrOffsetSectionItem(Index
);
212 uint64_t Offset
= AddrOffsetSectionBase
+ Index
* getAddressByteSize();
213 if (AddrOffsetSection
->Data
.size() < Offset
+ getAddressByteSize())
215 DWARFDataExtractor
DA(Context
.getDWARFObj(), *AddrOffsetSection
,
216 isLittleEndian
, getAddressByteSize());
218 uint64_t Address
= DA
.getRelocatedAddress(&Offset
, &Section
);
219 return {{Address
, Section
}};
222 Optional
<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index
) const {
223 if (!StringOffsetsTableContribution
)
225 unsigned ItemSize
= getDwarfStringOffsetsByteSize();
226 uint64_t Offset
= getStringOffsetsBase() + Index
* ItemSize
;
227 if (StringOffsetSection
.Data
.size() < Offset
+ ItemSize
)
229 DWARFDataExtractor
DA(Context
.getDWARFObj(), StringOffsetSection
,
231 return DA
.getRelocatedValue(ItemSize
, &Offset
);
234 bool DWARFUnitHeader::extract(DWARFContext
&Context
,
235 const DWARFDataExtractor
&debug_info
,
236 uint64_t *offset_ptr
,
237 DWARFSectionKind SectionKind
,
238 const DWARFUnitIndex
*Index
,
239 const DWARFUnitIndex::Entry
*Entry
) {
240 Offset
= *offset_ptr
;
242 if (!IndexEntry
&& Index
)
243 IndexEntry
= Index
->getFromOffset(*offset_ptr
);
244 Length
= debug_info
.getRelocatedValue(4, offset_ptr
);
245 FormParams
.Format
= DWARF32
;
246 if (Length
== dwarf::DW_LENGTH_DWARF64
) {
247 Length
= debug_info
.getU64(offset_ptr
);
248 FormParams
.Format
= DWARF64
;
250 FormParams
.Version
= debug_info
.getU16(offset_ptr
);
251 if (FormParams
.Version
>= 5) {
252 UnitType
= debug_info
.getU8(offset_ptr
);
253 FormParams
.AddrSize
= debug_info
.getU8(offset_ptr
);
254 AbbrOffset
= debug_info
.getRelocatedValue(FormParams
.getDwarfOffsetByteSize(), offset_ptr
);
256 AbbrOffset
= debug_info
.getRelocatedValue(FormParams
.getDwarfOffsetByteSize(), offset_ptr
);
257 FormParams
.AddrSize
= debug_info
.getU8(offset_ptr
);
258 // Fake a unit type based on the section type. This isn't perfect,
259 // but distinguishing compile and type units is generally enough.
260 if (SectionKind
== DW_SECT_TYPES
)
261 UnitType
= DW_UT_type
;
263 UnitType
= DW_UT_compile
;
268 auto *UnitContrib
= IndexEntry
->getOffset();
269 if (!UnitContrib
|| UnitContrib
->Length
!= (Length
+ 4))
271 auto *AbbrEntry
= IndexEntry
->getOffset(DW_SECT_ABBREV
);
274 AbbrOffset
= AbbrEntry
->Offset
;
277 TypeHash
= debug_info
.getU64(offset_ptr
);
279 debug_info
.getUnsigned(offset_ptr
, FormParams
.getDwarfOffsetByteSize());
280 } else if (UnitType
== DW_UT_split_compile
|| UnitType
== DW_UT_skeleton
)
281 DWOId
= debug_info
.getU64(offset_ptr
);
283 // Header fields all parsed, capture the size of this unit header.
284 assert(*offset_ptr
- Offset
<= 255 && "unexpected header size");
285 Size
= uint8_t(*offset_ptr
- Offset
);
287 // Type offset is unit-relative; should be after the header and before
288 // the end of the current unit.
292 : TypeOffset
>= Size
&&
293 TypeOffset
< getLength() + getUnitLengthFieldByteSize();
294 bool LengthOK
= debug_info
.isValidOffset(getNextUnitOffset() - 1);
295 bool VersionOK
= DWARFContext::isSupportedVersion(getVersion());
296 bool AddrSizeOK
= getAddressByteSize() == 4 || getAddressByteSize() == 8;
298 if (!LengthOK
|| !VersionOK
|| !AddrSizeOK
|| !TypeOffsetOK
)
301 // Keep track of the highest DWARF version we encounter across all units.
302 Context
.setMaxVersionIfGreater(getVersion());
306 // Parse the rangelist table header, including the optional array of offsets
307 // following it (DWARF v5 and later).
308 static Expected
<DWARFDebugRnglistTable
>
309 parseRngListTableHeader(DWARFDataExtractor
&DA
, uint64_t Offset
,
310 DwarfFormat Format
) {
311 // We are expected to be called with Offset 0 or pointing just past the table
312 // header. Correct Offset in the latter case so that it points to the start
315 uint64_t HeaderSize
= DWARFListTableHeader::getHeaderSize(Format
);
316 if (Offset
< HeaderSize
)
317 return createStringError(errc::invalid_argument
, "Did not detect a valid"
318 " range list table with base = 0x%" PRIx64
"\n",
320 Offset
-= HeaderSize
;
322 llvm::DWARFDebugRnglistTable Table
;
323 if (Error E
= Table
.extractHeaderAndOffsets(DA
, &Offset
))
328 Error
DWARFUnit::extractRangeList(uint64_t RangeListOffset
,
329 DWARFDebugRangeList
&RangeList
) const {
330 // Require that compile unit is extracted.
331 assert(!DieArray
.empty());
332 DWARFDataExtractor
RangesData(Context
.getDWARFObj(), *RangeSection
,
333 isLittleEndian
, getAddressByteSize());
334 uint64_t ActualRangeListOffset
= RangeSectionBase
+ RangeListOffset
;
335 return RangeList
.extract(RangesData
, &ActualRangeListOffset
);
338 void DWARFUnit::clear() {
341 RangeSectionBase
= 0;
342 AddrOffsetSectionBase
= 0;
347 const char *DWARFUnit::getCompilationDir() {
348 return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir
), nullptr);
351 void DWARFUnit::extractDIEsToVector(
352 bool AppendCUDie
, bool AppendNonCUDies
,
353 std::vector
<DWARFDebugInfoEntry
> &Dies
) const {
354 if (!AppendCUDie
&& !AppendNonCUDies
)
357 // Set the offset to that of the first DIE and calculate the start of the
358 // next compilation unit header.
359 uint64_t DIEOffset
= getOffset() + getHeaderSize();
360 uint64_t NextCUOffset
= getNextUnitOffset();
361 DWARFDebugInfoEntry DIE
;
362 DWARFDataExtractor DebugInfoData
= getDebugInfoExtractor();
366 while (DIE
.extractFast(*this, &DIEOffset
, DebugInfoData
, NextCUOffset
,
371 if (!AppendNonCUDies
)
373 // The average bytes per DIE entry has been seen to be
374 // around 14-20 so let's pre-reserve the needed memory for
375 // our DIE entries accordingly.
376 Dies
.reserve(Dies
.size() + getDebugInfoSize() / 14);
382 if (const DWARFAbbreviationDeclaration
*AbbrDecl
=
383 DIE
.getAbbreviationDeclarationPtr()) {
385 if (AbbrDecl
->hasChildren())
392 break; // We are done with this compile unit!
396 // Give a little bit of info if we encounter corrupt DWARF (our offset
397 // should always terminate at or before the start of the next compilation
399 if (DIEOffset
> NextCUOffset
)
400 WithColor::warning() << format("DWARF compile unit extends beyond its "
401 "bounds cu 0x%8.8" PRIx64
" "
402 "at 0x%8.8" PRIx64
"\n",
403 getOffset(), DIEOffset
);
406 void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly
) {
407 if (Error e
= tryExtractDIEsIfNeeded(CUDieOnly
))
408 WithColor::error() << toString(std::move(e
));
411 Error
DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly
) {
412 if ((CUDieOnly
&& !DieArray
.empty()) ||
414 return Error::success(); // Already parsed.
416 bool HasCUDie
= !DieArray
.empty();
417 extractDIEsToVector(!HasCUDie
, !CUDieOnly
, DieArray
);
419 if (DieArray
.empty())
420 return Error::success();
422 // If CU DIE was just parsed, copy several attribute values from it.
424 return Error::success();
426 DWARFDie
UnitDie(this, &DieArray
[0]);
427 if (Optional
<uint64_t> DWOId
= toUnsigned(UnitDie
.find(DW_AT_GNU_dwo_id
)))
428 Header
.setDWOId(*DWOId
);
430 assert(AddrOffsetSectionBase
== 0);
431 assert(RangeSectionBase
== 0);
432 AddrOffsetSectionBase
= toSectionOffset(UnitDie
.find(DW_AT_addr_base
), 0);
433 if (!AddrOffsetSectionBase
)
434 AddrOffsetSectionBase
=
435 toSectionOffset(UnitDie
.find(DW_AT_GNU_addr_base
), 0);
436 RangeSectionBase
= toSectionOffset(UnitDie
.find(DW_AT_rnglists_base
), 0);
439 // In general, in DWARF v5 and beyond we derive the start of the unit's
440 // contribution to the string offsets table from the unit DIE's
441 // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
442 // attribute, so we assume that there is a contribution to the string
443 // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
444 // In both cases we need to determine the format of the contribution,
445 // which may differ from the unit's format.
446 DWARFDataExtractor
DA(Context
.getDWARFObj(), StringOffsetSection
,
448 if (IsDWO
|| getVersion() >= 5) {
449 auto StringOffsetOrError
=
450 IsDWO
? determineStringOffsetsTableContributionDWO(DA
)
451 : determineStringOffsetsTableContribution(DA
);
452 if (!StringOffsetOrError
)
453 return createStringError(errc::invalid_argument
,
454 "invalid reference to or invalid content in "
455 ".debug_str_offsets[.dwo]: " +
456 toString(StringOffsetOrError
.takeError()));
458 StringOffsetsTableContribution
= *StringOffsetOrError
;
461 // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
462 // describe address ranges.
463 if (getVersion() >= 5) {
465 setRangesSection(&Context
.getDWARFObj().getRnglistsDWOSection(), 0);
467 setRangesSection(&Context
.getDWARFObj().getRnglistsSection(),
468 toSectionOffset(UnitDie
.find(DW_AT_rnglists_base
), 0));
469 if (RangeSection
->Data
.size()) {
470 // Parse the range list table header. Individual range lists are
472 DWARFDataExtractor
RangesDA(Context
.getDWARFObj(), *RangeSection
,
474 auto TableOrError
= parseRngListTableHeader(RangesDA
, RangeSectionBase
,
477 return createStringError(errc::invalid_argument
,
478 "parsing a range list table: " +
479 toString(TableOrError
.takeError()));
481 RngListTable
= TableOrError
.get();
483 // In a split dwarf unit, there is no DW_AT_rnglists_base attribute.
484 // Adjust RangeSectionBase to point past the table header.
485 if (IsDWO
&& RngListTable
)
486 RangeSectionBase
= RngListTable
->getHeaderSize();
490 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
491 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
492 return Error::success();
495 bool DWARFUnit::parseDWO() {
500 DWARFDie UnitDie
= getUnitDIE();
503 auto DWOFileName
= dwarf::toString(UnitDie
.find(DW_AT_GNU_dwo_name
));
506 auto CompilationDir
= dwarf::toString(UnitDie
.find(DW_AT_comp_dir
));
507 SmallString
<16> AbsolutePath
;
508 if (sys::path::is_relative(*DWOFileName
) && CompilationDir
&&
510 sys::path::append(AbsolutePath
, *CompilationDir
);
512 sys::path::append(AbsolutePath
, *DWOFileName
);
513 auto DWOId
= getDWOId();
516 auto DWOContext
= Context
.getDWOContext(AbsolutePath
);
520 DWARFCompileUnit
*DWOCU
= DWOContext
->getDWOCompileUnitForHash(*DWOId
);
523 DWO
= std::shared_ptr
<DWARFCompileUnit
>(std::move(DWOContext
), DWOCU
);
524 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
525 DWO
->setAddrOffsetSection(AddrOffsetSection
, AddrOffsetSectionBase
);
526 if (getVersion() >= 5) {
527 DWO
->setRangesSection(&Context
.getDWARFObj().getRnglistsDWOSection(), 0);
528 DWARFDataExtractor
RangesDA(Context
.getDWARFObj(), *RangeSection
,
530 if (auto TableOrError
= parseRngListTableHeader(RangesDA
, RangeSectionBase
,
532 DWO
->RngListTable
= TableOrError
.get();
534 WithColor::error() << "parsing a range list table: "
535 << toString(TableOrError
.takeError())
537 if (DWO
->RngListTable
)
538 DWO
->RangeSectionBase
= DWO
->RngListTable
->getHeaderSize();
540 auto DWORangesBase
= UnitDie
.getRangesBaseAttribute();
541 DWO
->setRangesSection(RangeSection
, DWORangesBase
? *DWORangesBase
: 0);
547 void DWARFUnit::clearDIEs(bool KeepCUDie
) {
548 if (DieArray
.size() > (unsigned)KeepCUDie
) {
549 DieArray
.resize((unsigned)KeepCUDie
);
550 DieArray
.shrink_to_fit();
554 Expected
<DWARFAddressRangesVector
>
555 DWARFUnit::findRnglistFromOffset(uint64_t Offset
) {
556 if (getVersion() <= 4) {
557 DWARFDebugRangeList RangeList
;
558 if (Error E
= extractRangeList(Offset
, RangeList
))
560 return RangeList
.getAbsoluteRanges(getBaseAddress());
563 DWARFDataExtractor
RangesData(Context
.getDWARFObj(), *RangeSection
,
564 isLittleEndian
, RngListTable
->getAddrSize());
565 auto RangeListOrError
= RngListTable
->findList(RangesData
, Offset
);
566 if (RangeListOrError
)
567 return RangeListOrError
.get().getAbsoluteRanges(getBaseAddress(), *this);
568 return RangeListOrError
.takeError();
571 return createStringError(errc::invalid_argument
,
572 "missing or invalid range list table");
575 Expected
<DWARFAddressRangesVector
>
576 DWARFUnit::findRnglistFromIndex(uint32_t Index
) {
577 if (auto Offset
= getRnglistOffset(Index
))
578 return findRnglistFromOffset(*Offset
+ RangeSectionBase
);
581 return createStringError(errc::invalid_argument
,
582 "invalid range list table index %d", Index
);
584 return createStringError(errc::invalid_argument
,
585 "missing or invalid range list table");
588 Expected
<DWARFAddressRangesVector
> DWARFUnit::collectAddressRanges() {
589 DWARFDie UnitDie
= getUnitDIE();
591 return createStringError(errc::invalid_argument
, "No unit DIE");
593 // First, check if unit DIE describes address ranges for the whole unit.
594 auto CUDIERangesOrError
= UnitDie
.getAddressRanges();
595 if (!CUDIERangesOrError
)
596 return createStringError(errc::invalid_argument
,
597 "decoding address ranges: %s",
598 toString(CUDIERangesOrError
.takeError()).c_str());
599 return *CUDIERangesOrError
;
602 void DWARFUnit::updateAddressDieMap(DWARFDie Die
) {
603 if (Die
.isSubroutineDIE()) {
604 auto DIERangesOrError
= Die
.getAddressRanges();
605 if (DIERangesOrError
) {
606 for (const auto &R
: DIERangesOrError
.get()) {
607 // Ignore 0-sized ranges.
608 if (R
.LowPC
== R
.HighPC
)
610 auto B
= AddrDieMap
.upper_bound(R
.LowPC
);
611 if (B
!= AddrDieMap
.begin() && R
.LowPC
< (--B
)->second
.first
) {
612 // The range is a sub-range of existing ranges, we need to split the
614 if (R
.HighPC
< B
->second
.first
)
615 AddrDieMap
[R
.HighPC
] = B
->second
;
616 if (R
.LowPC
> B
->first
)
617 AddrDieMap
[B
->first
].first
= R
.LowPC
;
619 AddrDieMap
[R
.LowPC
] = std::make_pair(R
.HighPC
, Die
);
622 llvm::consumeError(DIERangesOrError
.takeError());
624 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
625 // simplify the logic to update AddrDieMap. The child's range will always
626 // be equal or smaller than the parent's range. With this assumption, when
627 // adding one range into the map, it will at most split a range into 3
629 for (DWARFDie Child
= Die
.getFirstChild(); Child
; Child
= Child
.getSibling())
630 updateAddressDieMap(Child
);
633 DWARFDie
DWARFUnit::getSubroutineForAddress(uint64_t Address
) {
634 extractDIEsIfNeeded(false);
635 if (AddrDieMap
.empty())
636 updateAddressDieMap(getUnitDIE());
637 auto R
= AddrDieMap
.upper_bound(Address
);
638 if (R
== AddrDieMap
.begin())
640 // upper_bound's previous item contains Address.
642 if (Address
>= R
->second
.first
)
644 return R
->second
.second
;
648 DWARFUnit::getInlinedChainForAddress(uint64_t Address
,
649 SmallVectorImpl
<DWARFDie
> &InlinedChain
) {
650 assert(InlinedChain
.empty());
651 // Try to look for subprogram DIEs in the DWO file.
653 // First, find the subroutine that contains the given address (the leaf
654 // of inlined chain).
655 DWARFDie SubroutineDIE
=
656 (DWO
? *DWO
: *this).getSubroutineForAddress(Address
);
661 while (!SubroutineDIE
.isSubprogramDIE()) {
662 if (SubroutineDIE
.getTag() == DW_TAG_inlined_subroutine
)
663 InlinedChain
.push_back(SubroutineDIE
);
664 SubroutineDIE
= SubroutineDIE
.getParent();
666 InlinedChain
.push_back(SubroutineDIE
);
669 const DWARFUnitIndex
&llvm::getDWARFUnitIndex(DWARFContext
&Context
,
670 DWARFSectionKind Kind
) {
671 if (Kind
== DW_SECT_INFO
)
672 return Context
.getCUIndex();
673 assert(Kind
== DW_SECT_TYPES
);
674 return Context
.getTUIndex();
677 DWARFDie
DWARFUnit::getParent(const DWARFDebugInfoEntry
*Die
) {
680 const uint32_t Depth
= Die
->getDepth();
681 // Unit DIEs always have a depth of zero and never have parents.
684 // Depth of 1 always means parent is the compile/type unit.
687 // Look for previous DIE with a depth that is one less than the Die's depth.
688 const uint32_t ParentDepth
= Depth
- 1;
689 for (uint32_t I
= getDIEIndex(Die
) - 1; I
> 0; --I
) {
690 if (DieArray
[I
].getDepth() == ParentDepth
)
691 return DWARFDie(this, &DieArray
[I
]);
696 DWARFDie
DWARFUnit::getSibling(const DWARFDebugInfoEntry
*Die
) {
699 uint32_t Depth
= Die
->getDepth();
700 // Unit DIEs always have a depth of zero and never have siblings.
703 // NULL DIEs don't have siblings.
704 if (Die
->getAbbreviationDeclarationPtr() == nullptr)
707 // Find the next DIE whose depth is the same as the Die's depth.
708 for (size_t I
= getDIEIndex(Die
) + 1, EndIdx
= DieArray
.size(); I
< EndIdx
;
710 if (DieArray
[I
].getDepth() == Depth
)
711 return DWARFDie(this, &DieArray
[I
]);
716 DWARFDie
DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry
*Die
) {
719 uint32_t Depth
= Die
->getDepth();
720 // Unit DIEs always have a depth of zero and never have siblings.
724 // Find the previous DIE whose depth is the same as the Die's depth.
725 for (size_t I
= getDIEIndex(Die
); I
> 0;) {
727 if (DieArray
[I
].getDepth() == Depth
- 1)
729 if (DieArray
[I
].getDepth() == Depth
)
730 return DWARFDie(this, &DieArray
[I
]);
735 DWARFDie
DWARFUnit::getFirstChild(const DWARFDebugInfoEntry
*Die
) {
736 if (!Die
->hasChildren())
739 // We do not want access out of bounds when parsing corrupted debug data.
740 size_t I
= getDIEIndex(Die
) + 1;
741 if (I
>= DieArray
.size())
743 return DWARFDie(this, &DieArray
[I
]);
746 DWARFDie
DWARFUnit::getLastChild(const DWARFDebugInfoEntry
*Die
) {
747 if (!Die
->hasChildren())
750 uint32_t Depth
= Die
->getDepth();
751 for (size_t I
= getDIEIndex(Die
) + 1, EndIdx
= DieArray
.size(); I
< EndIdx
;
753 if (DieArray
[I
].getDepth() == Depth
+ 1 &&
754 DieArray
[I
].getTag() == dwarf::DW_TAG_null
)
755 return DWARFDie(this, &DieArray
[I
]);
756 assert(DieArray
[I
].getDepth() > Depth
&& "Not processing children?");
761 const DWARFAbbreviationDeclarationSet
*DWARFUnit::getAbbreviations() const {
763 Abbrevs
= Abbrev
->getAbbreviationDeclarationSet(Header
.getAbbrOffset());
767 llvm::Optional
<object::SectionedAddress
> DWARFUnit::getBaseAddress() {
771 DWARFDie UnitDie
= getUnitDIE();
772 Optional
<DWARFFormValue
> PC
= UnitDie
.find({DW_AT_low_pc
, DW_AT_entry_pc
});
773 BaseAddr
= toSectionedAddress(PC
);
777 Expected
<StrOffsetsContributionDescriptor
>
778 StrOffsetsContributionDescriptor::validateContributionSize(
779 DWARFDataExtractor
&DA
) {
780 uint8_t EntrySize
= getDwarfOffsetByteSize();
781 // In order to ensure that we don't read a partial record at the end of
782 // the section we validate for a multiple of the entry size.
783 uint64_t ValidationSize
= alignTo(Size
, EntrySize
);
784 // Guard against overflow.
785 if (ValidationSize
>= Size
)
786 if (DA
.isValidOffsetForDataOfSize((uint32_t)Base
, ValidationSize
))
788 return createStringError(errc::invalid_argument
, "length exceeds section size");
791 // Look for a DWARF64-formatted contribution to the string offsets table
792 // starting at a given offset and record it in a descriptor.
793 static Expected
<StrOffsetsContributionDescriptor
>
794 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor
&DA
, uint64_t Offset
) {
795 if (!DA
.isValidOffsetForDataOfSize(Offset
, 16))
796 return createStringError(errc::invalid_argument
, "section offset exceeds section size");
798 if (DA
.getU32(&Offset
) != dwarf::DW_LENGTH_DWARF64
)
799 return createStringError(errc::invalid_argument
, "32 bit contribution referenced from a 64 bit unit");
801 uint64_t Size
= DA
.getU64(&Offset
);
802 uint8_t Version
= DA
.getU16(&Offset
);
803 (void)DA
.getU16(&Offset
); // padding
804 // The encoded length includes the 2-byte version field and the 2-byte
805 // padding, so we need to subtract them out when we populate the descriptor.
806 return StrOffsetsContributionDescriptor(Offset
, Size
- 4, Version
, DWARF64
);
809 // Look for a DWARF32-formatted contribution to the string offsets table
810 // starting at a given offset and record it in a descriptor.
811 static Expected
<StrOffsetsContributionDescriptor
>
812 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor
&DA
, uint64_t Offset
) {
813 if (!DA
.isValidOffsetForDataOfSize(Offset
, 8))
814 return createStringError(errc::invalid_argument
, "section offset exceeds section size");
816 uint32_t ContributionSize
= DA
.getU32(&Offset
);
817 if (ContributionSize
>= dwarf::DW_LENGTH_lo_reserved
)
818 return createStringError(errc::invalid_argument
, "invalid length");
820 uint8_t Version
= DA
.getU16(&Offset
);
821 (void)DA
.getU16(&Offset
); // padding
822 // The encoded length includes the 2-byte version field and the 2-byte
823 // padding, so we need to subtract them out when we populate the descriptor.
824 return StrOffsetsContributionDescriptor(Offset
, ContributionSize
- 4, Version
,
828 static Expected
<StrOffsetsContributionDescriptor
>
829 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor
&DA
,
830 llvm::dwarf::DwarfFormat Format
,
832 StrOffsetsContributionDescriptor Desc
;
834 case dwarf::DwarfFormat::DWARF64
: {
836 return createStringError(errc::invalid_argument
, "insufficient space for 64 bit header prefix");
837 auto DescOrError
= parseDWARF64StringOffsetsTableHeader(DA
, Offset
- 16);
839 return DescOrError
.takeError();
843 case dwarf::DwarfFormat::DWARF32
: {
845 return createStringError(errc::invalid_argument
, "insufficient space for 32 bit header prefix");
846 auto DescOrError
= parseDWARF32StringOffsetsTableHeader(DA
, Offset
- 8);
848 return DescOrError
.takeError();
853 return Desc
.validateContributionSize(DA
);
856 Expected
<Optional
<StrOffsetsContributionDescriptor
>>
857 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor
&DA
) {
861 if (DA
.getData().data() == nullptr)
864 auto OptOffset
= toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base
));
869 auto DescOrError
= parseDWARFStringOffsetsTableHeader(DA
, Header
.getFormat(), Offset
);
871 return DescOrError
.takeError();
875 Expected
<Optional
<StrOffsetsContributionDescriptor
>>
876 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor
& DA
) {
878 auto IndexEntry
= Header
.getIndexEntry();
880 IndexEntry
? IndexEntry
->getOffset(DW_SECT_STR_OFFSETS
) : nullptr;
883 if (getVersion() >= 5) {
884 if (DA
.getData().data() == nullptr)
886 Offset
+= Header
.getFormat() == dwarf::DwarfFormat::DWARF32
? 8 : 16;
887 // Look for a valid contribution at the given offset.
888 auto DescOrError
= parseDWARFStringOffsetsTableHeader(DA
, Header
.getFormat(), Offset
);
890 return DescOrError
.takeError();
893 // Prior to DWARF v5, we derive the contribution size from the
894 // index table (in a package file). In a .dwo file it is simply
895 // the length of the string offsets section.
898 Optional
<StrOffsetsContributionDescriptor
>(
899 {0, StringOffsetSection
.Data
.size(), 4, DWARF32
})};
901 return {Optional
<StrOffsetsContributionDescriptor
>(
902 {C
->Offset
, C
->Length
, 4, DWARF32
})};