12db0cfa6SEugene Zelenko //===- DWARFUnit.cpp ------------------------------------------------------===//
282af9438SZachary Turner //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
682af9438SZachary Turner //
782af9438SZachary Turner //===----------------------------------------------------------------------===//
882af9438SZachary Turner
96bda14b3SChandler Carruth #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
106bda14b3SChandler Carruth #include "llvm/ADT/SmallString.h"
11570e39a2SEugene Zelenko #include "llvm/ADT/StringRef.h"
12cead4eceSMitch Phillips #include "llvm/BinaryFormat/Dwarf.h"
13570e39a2SEugene Zelenko #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
14143eaeabSPaul Robinson #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
1582af9438SZachary Turner #include "llvm/DebugInfo/DWARF/DWARFContext.h"
16570e39a2SEugene Zelenko #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
1728db7e65SEugene Zelenko #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
18290e4823Sserge-sans-paille #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
19290e4823Sserge-sans-paille #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
20ad60559bSWolfgang Pieb #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
2128db7e65SEugene Zelenko #include "llvm/DebugInfo/DWARF/DWARFDie.h"
22cead4eceSMitch Phillips #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
2397d22187SGreg Clayton #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
24290e4823Sserge-sans-paille #include "llvm/DebugInfo/DWARF/DWARFListTable.h"
25290e4823Sserge-sans-paille #include "llvm/DebugInfo/DWARF/DWARFObject.h"
26290e4823Sserge-sans-paille #include "llvm/DebugInfo/DWARF/DWARFSection.h"
27143eaeabSPaul Robinson #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
28cead4eceSMitch Phillips #include "llvm/Object/ObjectFile.h"
29570e39a2SEugene Zelenko #include "llvm/Support/DataExtractor.h"
30cba595daSVictor Leschuk #include "llvm/Support/Errc.h"
3182af9438SZachary Turner #include "llvm/Support/Path.h"
32570e39a2SEugene Zelenko #include <algorithm>
33570e39a2SEugene Zelenko #include <cassert>
3428db7e65SEugene Zelenko #include <cstddef>
35570e39a2SEugene Zelenko #include <cstdint>
362db0cfa6SEugene Zelenko #include <utility>
37570e39a2SEugene Zelenko #include <vector>
3882af9438SZachary Turner
3928db7e65SEugene Zelenko using namespace llvm;
4082af9438SZachary Turner using namespace dwarf;
4182af9438SZachary Turner
addUnitsForSection(DWARFContext & C,const DWARFSection & Section,DWARFSectionKind SectionKind)4211307fabSPaul Robinson void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
437f330944SPaul Robinson const DWARFSection &Section,
44143eaeabSPaul Robinson DWARFSectionKind SectionKind) {
45c398e67fSRafael Espindola const DWARFObject &D = C.getDWARFObj();
4690146cd8SDavid Blaikie addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
4790146cd8SDavid Blaikie &D.getLocSection(), D.getStrSection(),
4890146cd8SDavid Blaikie D.getStrOffsetsSection(), &D.getAddrSection(),
496214c11cSWolfgang Pieb D.getLineSection(), D.isLittleEndian(), false, false,
506214c11cSWolfgang Pieb SectionKind);
5182af9438SZachary Turner }
5282af9438SZachary Turner
addUnitsForDWOSection(DWARFContext & C,const DWARFSection & DWOSection,DWARFSectionKind SectionKind,bool Lazy)5311307fabSPaul Robinson void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
54143eaeabSPaul Robinson const DWARFSection &DWOSection,
557f330944SPaul Robinson DWARFSectionKind SectionKind,
567f330944SPaul Robinson bool Lazy) {
57c398e67fSRafael Espindola const DWARFObject &D = C.getDWARFObj();
5890146cd8SDavid Blaikie addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
5990146cd8SDavid Blaikie &D.getLocDWOSection(), D.getStrDWOSection(),
6090146cd8SDavid Blaikie D.getStrOffsetsDWOSection(), &D.getAddrSection(),
616214c11cSWolfgang Pieb D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
626214c11cSWolfgang Pieb SectionKind);
63143eaeabSPaul Robinson }
64143eaeabSPaul Robinson
addUnitsImpl(DWARFContext & Context,const DWARFObject & Obj,const DWARFSection & Section,const DWARFDebugAbbrev * DA,const DWARFSection * RS,const DWARFSection * LocSection,StringRef SS,const DWARFSection & SOS,const DWARFSection * AOS,const DWARFSection & LS,bool LE,bool IsDWO,bool Lazy,DWARFSectionKind SectionKind)6511307fabSPaul Robinson void DWARFUnitVector::addUnitsImpl(
667f330944SPaul Robinson DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
676214c11cSWolfgang Pieb const DWARFDebugAbbrev *DA, const DWARFSection *RS,
686214c11cSWolfgang Pieb const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
696214c11cSWolfgang Pieb const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
706214c11cSWolfgang Pieb bool Lazy, DWARFSectionKind SectionKind) {
71143eaeabSPaul Robinson DWARFDataExtractor Data(Obj, Section, LE, 0);
72143eaeabSPaul Robinson // Lazy initialization of Parser, now that we have all section info.
73143eaeabSPaul Robinson if (!Parser) {
7481959a27SDavid Blaikie Parser = [=, &Context, &Obj, &Section, &SOS,
75f26a70a5SIgor Kudrin &LS](uint64_t Offset, DWARFSectionKind SectionKind,
7681959a27SDavid Blaikie const DWARFSection *CurSection,
7781959a27SDavid Blaikie const DWARFUnitIndex::Entry *IndexEntry)
7881959a27SDavid Blaikie -> std::unique_ptr<DWARFUnit> {
797f330944SPaul Robinson const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
807f330944SPaul Robinson DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
81143eaeabSPaul Robinson if (!Data.isValidOffset(Offset))
82143eaeabSPaul Robinson return nullptr;
83143eaeabSPaul Robinson DWARFUnitHeader Header;
84af11c556SIgor Kudrin if (!Header.extract(Context, Data, &Offset, SectionKind))
85af11c556SIgor Kudrin return nullptr;
86af11c556SIgor Kudrin if (!IndexEntry && IsDWO) {
87af11c556SIgor Kudrin const DWARFUnitIndex &Index = getDWARFUnitIndex(
88af11c556SIgor Kudrin Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);
89727c590fSDavid Blaikie if (Index) {
90727c590fSDavid Blaikie if (Header.isTypeUnit())
91727c590fSDavid Blaikie IndexEntry = Index.getFromHash(Header.getTypeHash());
92727c590fSDavid Blaikie else if (auto DWOId = Header.getDWOId())
93727c590fSDavid Blaikie IndexEntry = Index.getFromHash(*DWOId);
94727c590fSDavid Blaikie }
95727c590fSDavid Blaikie if (!IndexEntry)
96af11c556SIgor Kudrin IndexEntry = Index.getFromOffset(Header.getOffset());
97af11c556SIgor Kudrin }
98af11c556SIgor Kudrin if (IndexEntry && !Header.applyIndexEntry(IndexEntry))
99143eaeabSPaul Robinson return nullptr;
100143eaeabSPaul Robinson std::unique_ptr<DWARFUnit> U;
101143eaeabSPaul Robinson if (Header.isTypeUnit())
1020eaee545SJonas Devlieghere U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
1036214c11cSWolfgang Pieb RS, LocSection, SS, SOS, AOS, LS,
1046214c11cSWolfgang Pieb LE, IsDWO, *this);
105143eaeabSPaul Robinson else
1060eaee545SJonas Devlieghere U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
1076214c11cSWolfgang Pieb DA, RS, LocSection, SS, SOS,
1086214c11cSWolfgang Pieb AOS, LS, LE, IsDWO, *this);
109143eaeabSPaul Robinson return U;
110143eaeabSPaul Robinson };
111143eaeabSPaul Robinson }
112143eaeabSPaul Robinson if (Lazy)
113143eaeabSPaul Robinson return;
1142c25f345SPaul Robinson // Find a reasonable insertion point within the vector. We skip over
1152c25f345SPaul Robinson // (a) units from a different section, (b) units from the same section
1162c25f345SPaul Robinson // but with lower offset-within-section. This keeps units in order
1172c25f345SPaul Robinson // within a section, although not necessarily within the object file,
1182c25f345SPaul Robinson // even if we do lazy parsing.
119143eaeabSPaul Robinson auto I = this->begin();
120f26a70a5SIgor Kudrin uint64_t Offset = 0;
121143eaeabSPaul Robinson while (Data.isValidOffset(Offset)) {
1222c25f345SPaul Robinson if (I != this->end() &&
1232c25f345SPaul Robinson (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
124143eaeabSPaul Robinson ++I;
125143eaeabSPaul Robinson continue;
126143eaeabSPaul Robinson }
12781959a27SDavid Blaikie auto U = Parser(Offset, SectionKind, &Section, nullptr);
1282c25f345SPaul Robinson // If parsing failed, we're done with this section.
129143eaeabSPaul Robinson if (!U)
130143eaeabSPaul Robinson break;
131143eaeabSPaul Robinson Offset = U->getNextUnitOffset();
132143eaeabSPaul Robinson I = std::next(this->insert(I, std::move(U)));
133143eaeabSPaul Robinson }
134143eaeabSPaul Robinson }
135143eaeabSPaul Robinson
addUnit(std::unique_ptr<DWARFUnit> Unit)1367ef2c202SJonas Devlieghere DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {
1377ef2c202SJonas Devlieghere auto I = std::upper_bound(begin(), end(), Unit,
1387ef2c202SJonas Devlieghere [](const std::unique_ptr<DWARFUnit> &LHS,
1397ef2c202SJonas Devlieghere const std::unique_ptr<DWARFUnit> &RHS) {
1407ef2c202SJonas Devlieghere return LHS->getOffset() < RHS->getOffset();
1417ef2c202SJonas Devlieghere });
1427ef2c202SJonas Devlieghere return this->insert(I, std::move(Unit))->get();
1437ef2c202SJonas Devlieghere }
1447ef2c202SJonas Devlieghere
getUnitForOffset(uint64_t Offset) const145f26a70a5SIgor Kudrin DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {
1464ec5a915SDavid Blaikie auto end = begin() + getNumInfoUnits();
1474ec5a915SDavid Blaikie auto *CU =
1484ec5a915SDavid Blaikie std::upper_bound(begin(), end, Offset,
149f26a70a5SIgor Kudrin [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
150143eaeabSPaul Robinson return LHS < RHS->getNextUnitOffset();
151143eaeabSPaul Robinson });
1524ec5a915SDavid Blaikie if (CU != end && (*CU)->getOffset() <= Offset)
153143eaeabSPaul Robinson return CU->get();
154143eaeabSPaul Robinson return nullptr;
155143eaeabSPaul Robinson }
156143eaeabSPaul Robinson
157143eaeabSPaul Robinson DWARFUnit *
getUnitForIndexEntry(const DWARFUnitIndex::Entry & E)15811307fabSPaul Robinson DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) {
159f13ce15dSIgor Kudrin const auto *CUOff = E.getContribution(DW_SECT_INFO);
160143eaeabSPaul Robinson if (!CUOff)
161143eaeabSPaul Robinson return nullptr;
162143eaeabSPaul Robinson
163143eaeabSPaul Robinson auto Offset = CUOff->Offset;
1644ec5a915SDavid Blaikie auto end = begin() + getNumInfoUnits();
165143eaeabSPaul Robinson
1664ec5a915SDavid Blaikie auto *CU =
1674ec5a915SDavid Blaikie std::upper_bound(begin(), end, CUOff->Offset,
168f26a70a5SIgor Kudrin [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
169143eaeabSPaul Robinson return LHS < RHS->getNextUnitOffset();
170143eaeabSPaul Robinson });
1714ec5a915SDavid Blaikie if (CU != end && (*CU)->getOffset() <= Offset)
172143eaeabSPaul Robinson return CU->get();
173143eaeabSPaul Robinson
174143eaeabSPaul Robinson if (!Parser)
175143eaeabSPaul Robinson return nullptr;
176143eaeabSPaul Robinson
17781959a27SDavid Blaikie auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E);
178143eaeabSPaul Robinson if (!U)
179143eaeabSPaul Robinson U = nullptr;
180143eaeabSPaul Robinson
181143eaeabSPaul Robinson auto *NewCU = U.get();
182143eaeabSPaul Robinson this->insert(CU, std::move(U));
1834ec5a915SDavid Blaikie ++NumInfoUnits;
184143eaeabSPaul Robinson return NewCU;
18582af9438SZachary Turner }
18682af9438SZachary Turner
DWARFUnit(DWARFContext & DC,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)18782af9438SZachary Turner DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
1886214c11cSWolfgang Pieb const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
1896214c11cSWolfgang Pieb const DWARFSection *RS, const DWARFSection *LocSection,
19077d3e938SWolfgang Pieb StringRef SS, const DWARFSection &SOS,
191d0c89f85SPaul Robinson const DWARFSection *AOS, const DWARFSection &LS, bool LE,
19211307fabSPaul Robinson bool IsDWO, const DWARFUnitVector &UnitVector)
1935f53f07bSPaul Robinson : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
19409080939SPavel Labath RangeSection(RS), LineSection(LS), StringSection(SS),
19509080939SPavel Labath StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE),
19609080939SPavel Labath IsDWO(IsDWO), UnitVector(UnitVector) {
19782af9438SZachary Turner clear();
19882af9438SZachary Turner }
19982af9438SZachary Turner
200570e39a2SEugene Zelenko DWARFUnit::~DWARFUnit() = default;
20182af9438SZachary Turner
getDebugInfoExtractor() const202c398e67fSRafael Espindola DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
203c398e67fSRafael Espindola return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
204c398e67fSRafael Espindola getAddressByteSize());
205c398e67fSRafael Espindola }
206c398e67fSRafael Espindola
20777fc1f60SAlexey Lapshin Optional<object::SectionedAddress>
getAddrOffsetSectionItem(uint32_t Index) const208161dd3c1SDavid Blaikie DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
20951504bc1SAlexander Yermolovich if (!AddrOffsetSectionBase) {
210c8ae0967SDavid Blaikie auto R = Context.info_section_units();
211c8ae0967SDavid Blaikie // Surprising if a DWO file has more than one skeleton unit in it - this
212c8ae0967SDavid Blaikie // probably shouldn't be valid, but if a use case is found, here's where to
213c8ae0967SDavid Blaikie // support it (probably have to linearly search for the matching skeleton CU
214c8ae0967SDavid Blaikie // here)
21551504bc1SAlexander Yermolovich if (IsDWO && hasSingleElement(R))
2166de48655SKazu Hirata return (*R.begin())->getAddrOffsetSectionItem(Index);
21751504bc1SAlexander Yermolovich
218eed02423SDavid Blaikie return None;
21951504bc1SAlexander Yermolovich }
22051504bc1SAlexander Yermolovich
221eed02423SDavid Blaikie uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
22275c068c5SPaul Robinson if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
223161dd3c1SDavid Blaikie return None;
224c398e67fSRafael Espindola DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
225c398e67fSRafael Espindola isLittleEndian, getAddressByteSize());
226161dd3c1SDavid Blaikie uint64_t Section;
227161dd3c1SDavid Blaikie uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
228161dd3c1SDavid Blaikie return {{Address, Section}};
22982af9438SZachary Turner }
23082af9438SZachary Turner
getStringOffsetSectionItem(uint32_t Index) const23192f2d02bSDavid Blaikie Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
2326ecd6a80SWolfgang Pieb if (!StringOffsetsTableContribution)
23392f2d02bSDavid Blaikie return make_error<StringError>(
23492f2d02bSDavid Blaikie "DW_FORM_strx used without a valid string offsets table",
23592f2d02bSDavid Blaikie inconvertibleErrorCode());
2366ecd6a80SWolfgang Pieb unsigned ItemSize = getDwarfStringOffsetsByteSize();
237f26a70a5SIgor Kudrin uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
23877d3e938SWolfgang Pieb if (StringOffsetSection.Data.size() < Offset + ItemSize)
23992f2d02bSDavid Blaikie return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +
24092f2d02bSDavid Blaikie ", which is too large",
24192f2d02bSDavid Blaikie inconvertibleErrorCode());
242c398e67fSRafael Espindola DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
243c398e67fSRafael Espindola isLittleEndian, 0);
2448eb3c814SWolfgang Pieb return DA.getRelocatedValue(ItemSize, &Offset);
24582af9438SZachary Turner }
24682af9438SZachary Turner
extract(DWARFContext & Context,const DWARFDataExtractor & debug_info,uint64_t * offset_ptr,DWARFSectionKind SectionKind)2475f53f07bSPaul Robinson bool DWARFUnitHeader::extract(DWARFContext &Context,
2485f53f07bSPaul Robinson const DWARFDataExtractor &debug_info,
249f26a70a5SIgor Kudrin uint64_t *offset_ptr,
250af11c556SIgor Kudrin DWARFSectionKind SectionKind) {
2515f53f07bSPaul Robinson Offset = *offset_ptr;
2526f635f90SIgor Kudrin Error Err = Error::success();
253af11c556SIgor Kudrin IndexEntry = nullptr;
254c9579271SPavel Labath std::tie(Length, FormParams.Format) =
255c9579271SPavel Labath debug_info.getInitialLength(offset_ptr, &Err);
2566f635f90SIgor Kudrin FormParams.Version = debug_info.getU16(offset_ptr, &Err);
25775c068c5SPaul Robinson if (FormParams.Version >= 5) {
2586f635f90SIgor Kudrin UnitType = debug_info.getU8(offset_ptr, &Err);
2596f635f90SIgor Kudrin FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
2606f635f90SIgor Kudrin AbbrOffset = debug_info.getRelocatedValue(
2616f635f90SIgor Kudrin FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
262cddd6044SPaul Robinson } else {
2636f635f90SIgor Kudrin AbbrOffset = debug_info.getRelocatedValue(
2646f635f90SIgor Kudrin FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
2656f635f90SIgor Kudrin FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
2665f53f07bSPaul Robinson // Fake a unit type based on the section type. This isn't perfect,
2675f53f07bSPaul Robinson // but distinguishing compile and type units is generally enough.
268a0249fe9SIgor Kudrin if (SectionKind == DW_SECT_EXT_TYPES)
2695f53f07bSPaul Robinson UnitType = DW_UT_type;
2705f53f07bSPaul Robinson else
2715f53f07bSPaul Robinson UnitType = DW_UT_compile;
272cddd6044SPaul Robinson }
273044308e9SIgor Kudrin if (isTypeUnit()) {
274044308e9SIgor Kudrin TypeHash = debug_info.getU64(offset_ptr, &Err);
275044308e9SIgor Kudrin TypeOffset = debug_info.getUnsigned(
276044308e9SIgor Kudrin offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);
277044308e9SIgor Kudrin } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
278044308e9SIgor Kudrin DWOId = debug_info.getU64(offset_ptr, &Err);
279044308e9SIgor Kudrin
280c19a2891SJan Kratochvil if (Err) {
281c19a2891SJan Kratochvil Context.getWarningHandler()(joinErrors(
282c19a2891SJan Kratochvil createStringError(
283c19a2891SJan Kratochvil errc::invalid_argument,
284c19a2891SJan Kratochvil "DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Offset),
285c19a2891SJan Kratochvil std::move(Err)));
286044308e9SIgor Kudrin return false;
287c19a2891SJan Kratochvil }
288044308e9SIgor Kudrin
289543c0e1dSPaul Robinson // Header fields all parsed, capture the size of this unit header.
290543c0e1dSPaul Robinson assert(*offset_ptr - Offset <= 255 && "unexpected header size");
291543c0e1dSPaul Robinson Size = uint8_t(*offset_ptr - Offset);
292c19a2891SJan Kratochvil uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();
293c19a2891SJan Kratochvil
294c19a2891SJan Kratochvil if (!debug_info.isValidOffset(getNextUnitOffset() - 1)) {
295c19a2891SJan Kratochvil Context.getWarningHandler()(
296c19a2891SJan Kratochvil createStringError(errc::invalid_argument,
297c19a2891SJan Kratochvil "DWARF unit from offset 0x%8.8" PRIx64 " incl. "
298c19a2891SJan Kratochvil "to offset 0x%8.8" PRIx64 " excl. "
299c19a2891SJan Kratochvil "extends past section size 0x%8.8zx",
300c19a2891SJan Kratochvil Offset, NextCUOffset, debug_info.size()));
301c19a2891SJan Kratochvil return false;
302c19a2891SJan Kratochvil }
303c19a2891SJan Kratochvil
304c19a2891SJan Kratochvil if (!DWARFContext::isSupportedVersion(getVersion())) {
305c19a2891SJan Kratochvil Context.getWarningHandler()(createStringError(
306c19a2891SJan Kratochvil errc::invalid_argument,
307c19a2891SJan Kratochvil "DWARF unit at offset 0x%8.8" PRIx64 " "
308c19a2891SJan Kratochvil "has unsupported version %" PRIu16 ", supported are 2-%u",
309c19a2891SJan Kratochvil Offset, getVersion(), DWARFContext::getMaxSupportedVersion()));
310c19a2891SJan Kratochvil return false;
311c19a2891SJan Kratochvil }
312543c0e1dSPaul Robinson
3135f53f07bSPaul Robinson // Type offset is unit-relative; should be after the header and before
3145f53f07bSPaul Robinson // the end of the current unit.
315c19a2891SJan Kratochvil if (isTypeUnit() && TypeOffset < Size) {
316c19a2891SJan Kratochvil Context.getWarningHandler()(
317c19a2891SJan Kratochvil createStringError(errc::invalid_argument,
318c19a2891SJan Kratochvil "DWARF type unit at offset "
319c19a2891SJan Kratochvil "0x%8.8" PRIx64 " "
320c19a2891SJan Kratochvil "has its relocated type_offset 0x%8.8" PRIx64 " "
321c19a2891SJan Kratochvil "pointing inside the header",
322c19a2891SJan Kratochvil Offset, Offset + TypeOffset));
32382af9438SZachary Turner return false;
324c19a2891SJan Kratochvil }
325c19a2891SJan Kratochvil if (isTypeUnit() &&
326c19a2891SJan Kratochvil TypeOffset >= getUnitLengthFieldByteSize() + getLength()) {
327c19a2891SJan Kratochvil Context.getWarningHandler()(createStringError(
328c19a2891SJan Kratochvil errc::invalid_argument,
329c19a2891SJan Kratochvil "DWARF type unit from offset 0x%8.8" PRIx64 " incl. "
330c19a2891SJan Kratochvil "to offset 0x%8.8" PRIx64 " excl. has its "
331c19a2891SJan Kratochvil "relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",
332c19a2891SJan Kratochvil Offset, NextCUOffset, Offset + TypeOffset));
333c19a2891SJan Kratochvil return false;
334c19a2891SJan Kratochvil }
335c19a2891SJan Kratochvil
336d7733f84SJack Anderson if (Error SizeErr = DWARFContext::checkAddressSizeSupported(
337d7733f84SJack Anderson getAddressByteSize(), errc::invalid_argument,
338d7733f84SJack Anderson "DWARF unit at offset 0x%8.8" PRIx64, Offset)) {
339d7733f84SJack Anderson Context.getWarningHandler()(std::move(SizeErr));
340c19a2891SJan Kratochvil return false;
341c19a2891SJan Kratochvil }
34282af9438SZachary Turner
34377d3e938SWolfgang Pieb // Keep track of the highest DWARF version we encounter across all units.
34475c068c5SPaul Robinson Context.setMaxVersionIfGreater(getVersion());
345485e01beSDavid Blaikie return true;
34682af9438SZachary Turner }
34782af9438SZachary Turner
applyIndexEntry(const DWARFUnitIndex::Entry * Entry)348af11c556SIgor Kudrin bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
349af11c556SIgor Kudrin assert(Entry);
350af11c556SIgor Kudrin assert(!IndexEntry);
351af11c556SIgor Kudrin IndexEntry = Entry;
352af11c556SIgor Kudrin if (AbbrOffset)
353af11c556SIgor Kudrin return false;
354af11c556SIgor Kudrin auto *UnitContrib = IndexEntry->getContribution();
355af11c556SIgor Kudrin if (!UnitContrib ||
356af11c556SIgor Kudrin UnitContrib->Length != (getLength() + getUnitLengthFieldByteSize()))
357af11c556SIgor Kudrin return false;
358af11c556SIgor Kudrin auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);
359af11c556SIgor Kudrin if (!AbbrEntry)
360af11c556SIgor Kudrin return false;
361af11c556SIgor Kudrin AbbrOffset = AbbrEntry->Offset;
362af11c556SIgor Kudrin return true;
363af11c556SIgor Kudrin }
364af11c556SIgor Kudrin
extractRangeList(uint64_t RangeListOffset,DWARFDebugRangeList & RangeList) const365f26a70a5SIgor Kudrin Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
366f39a9bbeSWolfgang Pieb DWARFDebugRangeList &RangeList) const {
367f39a9bbeSWolfgang Pieb // Require that compile unit is extracted.
368f39a9bbeSWolfgang Pieb assert(!DieArray.empty());
369f39a9bbeSWolfgang Pieb DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
370f39a9bbeSWolfgang Pieb isLittleEndian, getAddressByteSize());
371f26a70a5SIgor Kudrin uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
372f39a9bbeSWolfgang Pieb return RangeList.extract(RangesData, &ActualRangeListOffset);
37382af9438SZachary Turner }
37482af9438SZachary Turner
clear()37582af9438SZachary Turner void DWARFUnit::clear() {
37682af9438SZachary Turner Abbrevs = nullptr;
3772f95c8bcSGeorge Rimar BaseAddr.reset();
37882af9438SZachary Turner RangeSectionBase = 0;
37977cfcd75SDavid Blaikie LocSectionBase = 0;
380eed02423SDavid Blaikie AddrOffsetSectionBase = None;
381b447b9dcSDavid Blaikie SU = nullptr;
38282af9438SZachary Turner clearDIEs(false);
3836c12ae81SHyoun Kyu Cho AddrDieMap.clear();
3846c12ae81SHyoun Kyu Cho if (DWO)
3856c12ae81SHyoun Kyu Cho DWO->clear();
38682af9438SZachary Turner DWO.reset();
38782af9438SZachary Turner }
38882af9438SZachary Turner
getCompilationDir()38982af9438SZachary Turner const char *DWARFUnit::getCompilationDir() {
39028db7e65SEugene Zelenko return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
39182af9438SZachary Turner }
39282af9438SZachary Turner
extractDIEsToVector(bool AppendCUDie,bool AppendNonCUDies,std::vector<DWARFDebugInfoEntry> & Dies) const39382af9438SZachary Turner void DWARFUnit::extractDIEsToVector(
39482af9438SZachary Turner bool AppendCUDie, bool AppendNonCUDies,
395c8c1032cSGreg Clayton std::vector<DWARFDebugInfoEntry> &Dies) const {
39682af9438SZachary Turner if (!AppendCUDie && !AppendNonCUDies)
39782af9438SZachary Turner return;
39882af9438SZachary Turner
39982af9438SZachary Turner // Set the offset to that of the first DIE and calculate the start of the
40082af9438SZachary Turner // next compilation unit header.
401f26a70a5SIgor Kudrin uint64_t DIEOffset = getOffset() + getHeaderSize();
402f26a70a5SIgor Kudrin uint64_t NextCUOffset = getNextUnitOffset();
403c8c1032cSGreg Clayton DWARFDebugInfoEntry DIE;
40417536b93SPaul Robinson DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
405c19a2891SJan Kratochvil // The end offset has been already checked by DWARFUnitHeader::extract.
406c19a2891SJan Kratochvil assert(DebugInfoData.isValidOffset(NextCUOffset - 1));
4070b8c5081SAlexey Lapshin std::vector<uint32_t> Parents;
4080b8c5081SAlexey Lapshin std::vector<uint32_t> PrevSiblings;
40982af9438SZachary Turner bool IsCUDie = true;
41082af9438SZachary Turner
4110b8c5081SAlexey Lapshin assert(
4120b8c5081SAlexey Lapshin ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&
4130b8c5081SAlexey Lapshin "Dies array is not empty");
4140b8c5081SAlexey Lapshin
4150b8c5081SAlexey Lapshin // Fill Parents and Siblings stacks with initial value.
4160b8c5081SAlexey Lapshin Parents.push_back(UINT32_MAX);
4170b8c5081SAlexey Lapshin if (!AppendCUDie)
4180b8c5081SAlexey Lapshin Parents.push_back(0);
4190b8c5081SAlexey Lapshin PrevSiblings.push_back(0);
4200b8c5081SAlexey Lapshin
4210b8c5081SAlexey Lapshin // Start to extract dies.
4220b8c5081SAlexey Lapshin do {
4230b8c5081SAlexey Lapshin assert(Parents.size() > 0 && "Empty parents stack");
4240b8c5081SAlexey Lapshin assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&
4250b8c5081SAlexey Lapshin "Wrong parent index");
4260b8c5081SAlexey Lapshin
427f2c2e924SSylvestre Ledru // Extract die. Stop if any error occurred.
4280b8c5081SAlexey Lapshin if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
4290b8c5081SAlexey Lapshin Parents.back()))
4300b8c5081SAlexey Lapshin break;
4310b8c5081SAlexey Lapshin
4320b8c5081SAlexey Lapshin // If previous sibling is remembered then update it`s SiblingIdx field.
4330b8c5081SAlexey Lapshin if (PrevSiblings.back() > 0) {
4340b8c5081SAlexey Lapshin assert(PrevSiblings.back() < Dies.size() &&
4350b8c5081SAlexey Lapshin "Previous sibling index is out of Dies boundaries");
4360b8c5081SAlexey Lapshin Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());
4370b8c5081SAlexey Lapshin }
4380b8c5081SAlexey Lapshin
4390b8c5081SAlexey Lapshin // Store die into the Dies vector.
44082af9438SZachary Turner if (IsCUDie) {
44182af9438SZachary Turner if (AppendCUDie)
44282af9438SZachary Turner Dies.push_back(DIE);
44382af9438SZachary Turner if (!AppendNonCUDies)
44482af9438SZachary Turner break;
44582af9438SZachary Turner // The average bytes per DIE entry has been seen to be
44682af9438SZachary Turner // around 14-20 so let's pre-reserve the needed memory for
44782af9438SZachary Turner // our DIE entries accordingly.
44882af9438SZachary Turner Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
44982af9438SZachary Turner } else {
4500b8c5081SAlexey Lapshin // Remember last previous sibling.
4510b8c5081SAlexey Lapshin PrevSiblings.back() = Dies.size();
4520b8c5081SAlexey Lapshin
45382af9438SZachary Turner Dies.push_back(DIE);
45482af9438SZachary Turner }
45582af9438SZachary Turner
4560b8c5081SAlexey Lapshin // Check for new children scope.
45782af9438SZachary Turner if (const DWARFAbbreviationDeclaration *AbbrDecl =
45882af9438SZachary Turner DIE.getAbbreviationDeclarationPtr()) {
4590b8c5081SAlexey Lapshin if (AbbrDecl->hasChildren()) {
4600b8c5081SAlexey Lapshin if (AppendCUDie || !IsCUDie) {
4610b8c5081SAlexey Lapshin assert(Dies.size() > 0 && "Dies does not contain any die");
4620b8c5081SAlexey Lapshin Parents.push_back(Dies.size() - 1);
4630b8c5081SAlexey Lapshin PrevSiblings.push_back(0);
4640b8c5081SAlexey Lapshin }
4650b8c5081SAlexey Lapshin } else if (IsCUDie)
4660b8c5081SAlexey Lapshin // Stop if we have single compile unit die w/o children.
4670b8c5081SAlexey Lapshin break;
46882af9438SZachary Turner } else {
4690b8c5081SAlexey Lapshin // NULL DIE: finishes current children scope.
4700b8c5081SAlexey Lapshin Parents.pop_back();
4710b8c5081SAlexey Lapshin PrevSiblings.pop_back();
47282af9438SZachary Turner }
4730b8c5081SAlexey Lapshin
4740b8c5081SAlexey Lapshin if (IsCUDie)
4750b8c5081SAlexey Lapshin IsCUDie = false;
4760b8c5081SAlexey Lapshin
4770b8c5081SAlexey Lapshin // Stop when compile unit die is removed from the parents stack.
4780b8c5081SAlexey Lapshin } while (Parents.size() > 1);
47982af9438SZachary Turner }
48082af9438SZachary Turner
extractDIEsIfNeeded(bool CUDieOnly)4811b1f1d66SDavid Blaikie void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
4820fcc1f7bSDavid Blaikie if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
48398e3f19bSAlexey Lapshin Context.getRecoverableErrorHandler()(std::move(e));
4840fcc1f7bSDavid Blaikie }
4850fcc1f7bSDavid Blaikie
tryExtractDIEsIfNeeded(bool CUDieOnly)4860fcc1f7bSDavid Blaikie Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
487570e39a2SEugene Zelenko if ((CUDieOnly && !DieArray.empty()) ||
48882af9438SZachary Turner DieArray.size() > 1)
4890fcc1f7bSDavid Blaikie return Error::success(); // Already parsed.
49082af9438SZachary Turner
491570e39a2SEugene Zelenko bool HasCUDie = !DieArray.empty();
49282af9438SZachary Turner extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
49382af9438SZachary Turner
49482af9438SZachary Turner if (DieArray.empty())
4950fcc1f7bSDavid Blaikie return Error::success();
49682af9438SZachary Turner
49782af9438SZachary Turner // If CU DIE was just parsed, copy several attribute values from it.
4981b1f1d66SDavid Blaikie if (HasCUDie)
4990fcc1f7bSDavid Blaikie return Error::success();
5001b1f1d66SDavid Blaikie
5010fcc1f7bSDavid Blaikie DWARFDie UnitDie(this, &DieArray[0]);
502543c0e1dSPaul Robinson if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
503543c0e1dSPaul Robinson Header.setDWOId(*DWOId);
504d57b5251SWolfgang Pieb if (!IsDWO) {
505eed02423SDavid Blaikie assert(AddrOffsetSectionBase == None);
50622dc4474SDavid Blaikie assert(RangeSectionBase == 0);
50777cfcd75SDavid Blaikie assert(LocSectionBase == 0);
508eed02423SDavid Blaikie AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));
509161dd3c1SDavid Blaikie if (!AddrOffsetSectionBase)
51022dc4474SDavid Blaikie AddrOffsetSectionBase =
511eed02423SDavid Blaikie toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));
51222dc4474SDavid Blaikie RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
51377cfcd75SDavid Blaikie LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);
51422dc4474SDavid Blaikie }
51577d3e938SWolfgang Pieb
5166ecd6a80SWolfgang Pieb // In general, in DWARF v5 and beyond we derive the start of the unit's
5176ecd6a80SWolfgang Pieb // contribution to the string offsets table from the unit DIE's
5186ecd6a80SWolfgang Pieb // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
5196ecd6a80SWolfgang Pieb // attribute, so we assume that there is a contribution to the string
5206ecd6a80SWolfgang Pieb // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
5216ecd6a80SWolfgang Pieb // In both cases we need to determine the format of the contribution,
5226ecd6a80SWolfgang Pieb // which may differ from the unit's format.
5236ecd6a80SWolfgang Pieb DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
5246ecd6a80SWolfgang Pieb isLittleEndian, 0);
525a17564c2SDavid Blaikie if (IsDWO || getVersion() >= 5) {
526a17564c2SDavid Blaikie auto StringOffsetOrError =
527a17564c2SDavid Blaikie IsDWO ? determineStringOffsetsTableContributionDWO(DA)
528a17564c2SDavid Blaikie : determineStringOffsetsTableContribution(DA);
5290fcc1f7bSDavid Blaikie if (!StringOffsetOrError)
5300fcc1f7bSDavid Blaikie return createStringError(errc::invalid_argument,
5310fcc1f7bSDavid Blaikie "invalid reference to or invalid content in "
5320fcc1f7bSDavid Blaikie ".debug_str_offsets[.dwo]: " +
5330fcc1f7bSDavid Blaikie toString(StringOffsetOrError.takeError()));
5340fcc1f7bSDavid Blaikie
535a17564c2SDavid Blaikie StringOffsetsTableContribution = *StringOffsetOrError;
536a17564c2SDavid Blaikie }
53777d3e938SWolfgang Pieb
538ad60559bSWolfgang Pieb // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
539ad60559bSWolfgang Pieb // describe address ranges.
540ad60559bSWolfgang Pieb if (getVersion() >= 5) {
54135819ff3SIgor Kudrin // In case of DWP, the base offset from the index has to be added.
54235819ff3SIgor Kudrin if (IsDWO) {
5439670a45cSDavid Blaikie uint64_t ContributionBaseOffset = 0;
54435819ff3SIgor Kudrin if (auto *IndexEntry = Header.getIndexEntry())
54535819ff3SIgor Kudrin if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))
54635819ff3SIgor Kudrin ContributionBaseOffset = Contrib->Offset;
54735819ff3SIgor Kudrin setRangesSection(
54835819ff3SIgor Kudrin &Context.getDWARFObj().getRnglistsDWOSection(),
54935819ff3SIgor Kudrin ContributionBaseOffset +
55035819ff3SIgor Kudrin DWARFListTableHeader::getHeaderSize(Header.getFormat()));
55135819ff3SIgor Kudrin } else
552ad60559bSWolfgang Pieb setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
5536d0be74aSDavid Blaikie toSectionOffset(UnitDie.find(DW_AT_rnglists_base),
5546d0be74aSDavid Blaikie DWARFListTableHeader::getHeaderSize(
5556d0be74aSDavid Blaikie Header.getFormat())));
5569670a45cSDavid Blaikie }
55777cfcd75SDavid Blaikie
558467c2514SDavid Blaikie if (IsDWO) {
5599670a45cSDavid Blaikie // If we are reading a package file, we need to adjust the location list
5609670a45cSDavid Blaikie // data based on the index entries.
5619670a45cSDavid Blaikie StringRef Data = Header.getVersion() >= 5
5629670a45cSDavid Blaikie ? Context.getDWARFObj().getLoclistsDWOSection().Data
5639670a45cSDavid Blaikie : Context.getDWARFObj().getLocDWOSection().Data;
5649670a45cSDavid Blaikie if (auto *IndexEntry = Header.getIndexEntry())
5659670a45cSDavid Blaikie if (const auto *C = IndexEntry->getContribution(
5669670a45cSDavid Blaikie Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
5679670a45cSDavid Blaikie Data = Data.substr(C->Offset, C->Length);
5689670a45cSDavid Blaikie
5699670a45cSDavid Blaikie DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize());
5709670a45cSDavid Blaikie LocTable =
5719670a45cSDavid Blaikie std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());
5729670a45cSDavid Blaikie LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());
5739670a45cSDavid Blaikie } else if (getVersion() >= 5) {
5749670a45cSDavid Blaikie LocTable = std::make_unique<DWARFDebugLoclists>(
5759670a45cSDavid Blaikie DWARFDataExtractor(Context.getDWARFObj(),
5769670a45cSDavid Blaikie Context.getDWARFObj().getLoclistsSection(),
5779670a45cSDavid Blaikie isLittleEndian, getAddressByteSize()),
5789670a45cSDavid Blaikie getVersion());
579467c2514SDavid Blaikie } else {
5809670a45cSDavid Blaikie LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(
5819670a45cSDavid Blaikie Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),
5829670a45cSDavid Blaikie isLittleEndian, getAddressByteSize()));
5831d56b4aeSWolfgang Pieb }
584ad60559bSWolfgang Pieb
58582af9438SZachary Turner // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
58682af9438SZachary Turner // skeleton CU DIE, so that DWARF users not aware of it are not broken.
5870fcc1f7bSDavid Blaikie return Error::success();
58882af9438SZachary Turner }
58982af9438SZachary Turner
parseDWO()59082af9438SZachary Turner bool DWARFUnit::parseDWO() {
591d57b5251SWolfgang Pieb if (IsDWO)
592e438cff4SDavid Blaikie return false;
59382af9438SZachary Turner if (DWO.get())
59482af9438SZachary Turner return false;
595c8c1032cSGreg Clayton DWARFDie UnitDie = getUnitDIE();
596c8c1032cSGreg Clayton if (!UnitDie)
59782af9438SZachary Turner return false;
598fb4d8fe1SSourabh Singh Tomar auto DWOFileName = getVersion() >= 5
599fb4d8fe1SSourabh Singh Tomar ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
600fb4d8fe1SSourabh Singh Tomar : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
60182af9438SZachary Turner if (!DWOFileName)
60282af9438SZachary Turner return false;
60328db7e65SEugene Zelenko auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
60482af9438SZachary Turner SmallString<16> AbsolutePath;
60597d22187SGreg Clayton if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
60697d22187SGreg Clayton *CompilationDir) {
60797d22187SGreg Clayton sys::path::append(AbsolutePath, *CompilationDir);
60882af9438SZachary Turner }
60997d22187SGreg Clayton sys::path::append(AbsolutePath, *DWOFileName);
6108d039d40SDavid Blaikie auto DWOId = getDWOId();
6118d039d40SDavid Blaikie if (!DWOId)
6128d039d40SDavid Blaikie return false;
613f9803fb4SDavid Blaikie auto DWOContext = Context.getDWOContext(AbsolutePath);
614f9803fb4SDavid Blaikie if (!DWOContext)
61582af9438SZachary Turner return false;
616f9803fb4SDavid Blaikie
61715d85fc5SDavid Blaikie DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
61815d85fc5SDavid Blaikie if (!DWOCU)
619f9803fb4SDavid Blaikie return false;
62015d85fc5SDavid Blaikie DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
621b447b9dcSDavid Blaikie DWO->setSkeletonUnit(this);
62282af9438SZachary Turner // Share .debug_addr and .debug_ranges section with compile unit in .dwo
623eed02423SDavid Blaikie if (AddrOffsetSectionBase)
624eed02423SDavid Blaikie DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
625ea91749fSDavid Blaikie if (getVersion() == 4) {
62652fe1f68SGreg Clayton auto DWORangesBase = UnitDie.getRangesBaseAttribute();
627*129b531cSKazu Hirata DWO->setRangesSection(RangeSection, DWORangesBase.value_or(0));
628ad60559bSWolfgang Pieb }
629ad60559bSWolfgang Pieb
63082af9438SZachary Turner return true;
63182af9438SZachary Turner }
63282af9438SZachary Turner
clearDIEs(bool KeepCUDie)63382af9438SZachary Turner void DWARFUnit::clearDIEs(bool KeepCUDie) {
63434935408SAlexey Lapshin // Do not use resize() + shrink_to_fit() to free memory occupied by dies.
63534935408SAlexey Lapshin // shrink_to_fit() is a *non-binding* request to reduce capacity() to size().
63634935408SAlexey Lapshin // It depends on the implementation whether the request is fulfilled.
63734935408SAlexey Lapshin // Create a new vector with a small capacity and assign it to the DieArray to
63834935408SAlexey Lapshin // have previous contents freed.
63934935408SAlexey Lapshin DieArray = (KeepCUDie && !DieArray.empty())
64034935408SAlexey Lapshin ? std::vector<DWARFDebugInfoEntry>({DieArray[0]})
64134935408SAlexey Lapshin : std::vector<DWARFDebugInfoEntry>();
64282af9438SZachary Turner }
64382af9438SZachary Turner
64461d8c8d9SWolfgang Pieb Expected<DWARFAddressRangesVector>
findRnglistFromOffset(uint64_t Offset)645f26a70a5SIgor Kudrin DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
646f39a9bbeSWolfgang Pieb if (getVersion() <= 4) {
647f39a9bbeSWolfgang Pieb DWARFDebugRangeList RangeList;
648f39a9bbeSWolfgang Pieb if (Error E = extractRangeList(Offset, RangeList))
649c55cf4afSBill Wendling return std::move(E);
650f39a9bbeSWolfgang Pieb return RangeList.getAbsoluteRanges(getBaseAddress());
651f39a9bbeSWolfgang Pieb }
652ad60559bSWolfgang Pieb DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
6536d0be74aSDavid Blaikie isLittleEndian, Header.getAddressByteSize());
6546d0be74aSDavid Blaikie DWARFDebugRnglistTable RnglistTable;
6556d0be74aSDavid Blaikie auto RangeListOrError = RnglistTable.findList(RangesData, Offset);
65661d8c8d9SWolfgang Pieb if (RangeListOrError)
65759ac2064SDavid Blaikie return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
65861d8c8d9SWolfgang Pieb return RangeListOrError.takeError();
659ad60559bSWolfgang Pieb }
660ad60559bSWolfgang Pieb
66161d8c8d9SWolfgang Pieb Expected<DWARFAddressRangesVector>
findRnglistFromIndex(uint32_t Index)66261d8c8d9SWolfgang Pieb DWARFUnit::findRnglistFromIndex(uint32_t Index) {
663ad60559bSWolfgang Pieb if (auto Offset = getRnglistOffset(Index))
6644ee76a92SPavel Labath return findRnglistFromOffset(*Offset);
66561d8c8d9SWolfgang Pieb
666cba595daSVictor Leschuk return createStringError(errc::invalid_argument,
6676d0be74aSDavid Blaikie "invalid range list table index %d (possibly "
6686d0be74aSDavid Blaikie "missing the entire range list table)",
6696d0be74aSDavid Blaikie Index);
670ad60559bSWolfgang Pieb }
671ad60559bSWolfgang Pieb
collectAddressRanges()672219c6bd3SDavid Blaikie Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
673c8c1032cSGreg Clayton DWARFDie UnitDie = getUnitDIE();
674c8c1032cSGreg Clayton if (!UnitDie)
675219c6bd3SDavid Blaikie return createStringError(errc::invalid_argument, "No unit DIE");
676219c6bd3SDavid Blaikie
6777a18c061SAlexey Samsonov // First, check if unit DIE describes address ranges for the whole unit.
67861d8c8d9SWolfgang Pieb auto CUDIERangesOrError = UnitDie.getAddressRanges();
679219c6bd3SDavid Blaikie if (!CUDIERangesOrError)
680219c6bd3SDavid Blaikie return createStringError(errc::invalid_argument,
681219c6bd3SDavid Blaikie "decoding address ranges: %s",
682219c6bd3SDavid Blaikie toString(CUDIERangesOrError.takeError()).c_str());
683219c6bd3SDavid Blaikie return *CUDIERangesOrError;
68482af9438SZachary Turner }
68582af9438SZachary Turner
686a03435ecSPavel Labath Expected<DWARFLocationExpressionsVector>
findLoclistFromOffset(uint64_t Offset)687a03435ecSPavel Labath DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
688a03435ecSPavel Labath DWARFLocationExpressionsVector Result;
689a03435ecSPavel Labath
690a03435ecSPavel Labath Error InterpretationError = Error::success();
691a03435ecSPavel Labath
692a03435ecSPavel Labath Error ParseError = getLocationTable().visitAbsoluteLocationList(
693a03435ecSPavel Labath Offset, getBaseAddress(),
694a03435ecSPavel Labath [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
695a03435ecSPavel Labath [&](Expected<DWARFLocationExpression> L) {
696a03435ecSPavel Labath if (L)
697a03435ecSPavel Labath Result.push_back(std::move(*L));
698a03435ecSPavel Labath else
699a03435ecSPavel Labath InterpretationError =
700a03435ecSPavel Labath joinErrors(L.takeError(), std::move(InterpretationError));
701a03435ecSPavel Labath return !InterpretationError;
702a03435ecSPavel Labath });
703a03435ecSPavel Labath
704a03435ecSPavel Labath if (ParseError || InterpretationError)
705a03435ecSPavel Labath return joinErrors(std::move(ParseError), std::move(InterpretationError));
706a03435ecSPavel Labath
707a03435ecSPavel Labath return Result;
708a03435ecSPavel Labath }
709a03435ecSPavel Labath
updateAddressDieMap(DWARFDie Die)7103b6de6feSDavid Blaikie void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
7113b6de6feSDavid Blaikie if (Die.isSubroutineDIE()) {
71261d8c8d9SWolfgang Pieb auto DIERangesOrError = Die.getAddressRanges();
71361d8c8d9SWolfgang Pieb if (DIERangesOrError) {
71461d8c8d9SWolfgang Pieb for (const auto &R : DIERangesOrError.get()) {
715a364f09fSDehao Chen // Ignore 0-sized ranges.
7164671f2e0SGeorge Rimar if (R.LowPC == R.HighPC)
717a364f09fSDehao Chen continue;
7183b6de6feSDavid Blaikie auto B = AddrDieMap.upper_bound(R.LowPC);
7193b6de6feSDavid Blaikie if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
7203b6de6feSDavid Blaikie // The range is a sub-range of existing ranges, we need to split the
7213b6de6feSDavid Blaikie // existing range.
7223b6de6feSDavid Blaikie if (R.HighPC < B->second.first)
7233b6de6feSDavid Blaikie AddrDieMap[R.HighPC] = B->second;
7243b6de6feSDavid Blaikie if (R.LowPC > B->first)
7253b6de6feSDavid Blaikie AddrDieMap[B->first].first = R.LowPC;
726a364f09fSDehao Chen }
7273b6de6feSDavid Blaikie AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
728a364f09fSDehao Chen }
72961d8c8d9SWolfgang Pieb } else
73061d8c8d9SWolfgang Pieb llvm::consumeError(DIERangesOrError.takeError());
731a364f09fSDehao Chen }
7323b6de6feSDavid Blaikie // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
7333b6de6feSDavid Blaikie // simplify the logic to update AddrDieMap. The child's range will always
7343b6de6feSDavid Blaikie // be equal or smaller than the parent's range. With this assumption, when
7353b6de6feSDavid Blaikie // adding one range into the map, it will at most split a range into 3
7363b6de6feSDavid Blaikie // sub-ranges.
7373b6de6feSDavid Blaikie for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
7383b6de6feSDavid Blaikie updateAddressDieMap(Child);
739a364f09fSDehao Chen }
740a364f09fSDehao Chen
getSubroutineForAddress(uint64_t Address)741a364f09fSDehao Chen DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
74282af9438SZachary Turner extractDIEsIfNeeded(false);
7433b6de6feSDavid Blaikie if (AddrDieMap.empty())
7443b6de6feSDavid Blaikie updateAddressDieMap(getUnitDIE());
7453b6de6feSDavid Blaikie auto R = AddrDieMap.upper_bound(Address);
7463b6de6feSDavid Blaikie if (R == AddrDieMap.begin())
747c8c1032cSGreg Clayton return DWARFDie();
7483b6de6feSDavid Blaikie // upper_bound's previous item contains Address.
7493b6de6feSDavid Blaikie --R;
7503b6de6feSDavid Blaikie if (Address >= R->second.first)
751a364f09fSDehao Chen return DWARFDie();
7523b6de6feSDavid Blaikie return R->second.second;
75382af9438SZachary Turner }
75482af9438SZachary Turner
updateVariableDieMap(DWARFDie Die)755cead4eceSMitch Phillips void DWARFUnit::updateVariableDieMap(DWARFDie Die) {
756cead4eceSMitch Phillips for (DWARFDie Child : Die) {
757cead4eceSMitch Phillips if (isType(Child.getTag()))
758cead4eceSMitch Phillips continue;
759cead4eceSMitch Phillips updateVariableDieMap(Child);
760cead4eceSMitch Phillips }
761cead4eceSMitch Phillips
762cead4eceSMitch Phillips if (Die.getTag() != DW_TAG_variable)
763cead4eceSMitch Phillips return;
764cead4eceSMitch Phillips
765cead4eceSMitch Phillips Expected<DWARFLocationExpressionsVector> Locations =
766cead4eceSMitch Phillips Die.getLocations(DW_AT_location);
767cead4eceSMitch Phillips if (!Locations) {
768cead4eceSMitch Phillips // Missing DW_AT_location is fine here.
769cead4eceSMitch Phillips consumeError(Locations.takeError());
770cead4eceSMitch Phillips return;
771cead4eceSMitch Phillips }
772cead4eceSMitch Phillips
773cead4eceSMitch Phillips uint64_t Address = UINT64_MAX;
774cead4eceSMitch Phillips
775cead4eceSMitch Phillips for (const DWARFLocationExpression &Location : *Locations) {
776cead4eceSMitch Phillips uint8_t AddressSize = getAddressByteSize();
777cead4eceSMitch Phillips DataExtractor Data(Location.Expr, /*IsLittleEndian=*/true, AddressSize);
778cead4eceSMitch Phillips DWARFExpression Expr(Data, AddressSize);
779cead4eceSMitch Phillips auto It = Expr.begin();
780cead4eceSMitch Phillips if (It == Expr.end())
781cead4eceSMitch Phillips continue;
782cead4eceSMitch Phillips
783cead4eceSMitch Phillips // Match exactly the main sequence used to describe global variables:
784cead4eceSMitch Phillips // `DW_OP_addr[x] [+ DW_OP_plus_uconst]`. Currently, this is the sequence
785cead4eceSMitch Phillips // that LLVM produces for DILocalVariables and DIGlobalVariables. If, in
786cead4eceSMitch Phillips // future, the DWARF producer (`DwarfCompileUnit::addLocationAttribute()` is
787cead4eceSMitch Phillips // a good starting point) is extended to use further expressions, this code
788cead4eceSMitch Phillips // needs to be updated.
789cead4eceSMitch Phillips uint64_t LocationAddr;
790cead4eceSMitch Phillips if (It->getCode() == dwarf::DW_OP_addr) {
791cead4eceSMitch Phillips LocationAddr = It->getRawOperand(0);
792cead4eceSMitch Phillips } else if (It->getCode() == dwarf::DW_OP_addrx) {
793cead4eceSMitch Phillips uint64_t DebugAddrOffset = It->getRawOperand(0);
794cead4eceSMitch Phillips if (auto Pointer = getAddrOffsetSectionItem(DebugAddrOffset)) {
795cead4eceSMitch Phillips LocationAddr = Pointer->Address;
796cead4eceSMitch Phillips }
797cead4eceSMitch Phillips } else {
798cead4eceSMitch Phillips continue;
799cead4eceSMitch Phillips }
800cead4eceSMitch Phillips
801cead4eceSMitch Phillips // Read the optional 2nd operand, a DW_OP_plus_uconst.
802cead4eceSMitch Phillips if (++It != Expr.end()) {
803cead4eceSMitch Phillips if (It->getCode() != dwarf::DW_OP_plus_uconst)
804cead4eceSMitch Phillips continue;
805cead4eceSMitch Phillips
806cead4eceSMitch Phillips LocationAddr += It->getRawOperand(0);
807cead4eceSMitch Phillips
808cead4eceSMitch Phillips // Probe for a 3rd operand, if it exists, bail.
809cead4eceSMitch Phillips if (++It != Expr.end())
810cead4eceSMitch Phillips continue;
811cead4eceSMitch Phillips }
812cead4eceSMitch Phillips
813cead4eceSMitch Phillips Address = LocationAddr;
814cead4eceSMitch Phillips break;
815cead4eceSMitch Phillips }
816cead4eceSMitch Phillips
817cead4eceSMitch Phillips // Get the size of the global variable. If all else fails (i.e. the global has
818cead4eceSMitch Phillips // no type), then we use a size of one to still allow symbolization of the
819cead4eceSMitch Phillips // exact address.
820cead4eceSMitch Phillips uint64_t GVSize = 1;
821cead4eceSMitch Phillips if (DWARFDie BaseType = Die.getAttributeValueAsReferencedDie(DW_AT_type))
822cead4eceSMitch Phillips if (Optional<uint64_t> Size = Die.getTypeSize(getAddressByteSize()))
823cead4eceSMitch Phillips GVSize = *Size;
824cead4eceSMitch Phillips
825cead4eceSMitch Phillips if (Address != UINT64_MAX)
826cead4eceSMitch Phillips VariableDieMap[Address] = {Address + GVSize, Die};
827cead4eceSMitch Phillips }
828cead4eceSMitch Phillips
getVariableForAddress(uint64_t Address)829cead4eceSMitch Phillips DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {
830cead4eceSMitch Phillips extractDIEsIfNeeded(false);
831cead4eceSMitch Phillips
832cead4eceSMitch Phillips auto RootDie = getUnitDIE();
833cead4eceSMitch Phillips
834cead4eceSMitch Phillips auto RootLookup = RootsParsedForVariables.insert(RootDie.getOffset());
835cead4eceSMitch Phillips if (RootLookup.second)
836cead4eceSMitch Phillips updateVariableDieMap(RootDie);
837cead4eceSMitch Phillips
838cead4eceSMitch Phillips auto R = VariableDieMap.upper_bound(Address);
839cead4eceSMitch Phillips if (R == VariableDieMap.begin())
840cead4eceSMitch Phillips return DWARFDie();
841cead4eceSMitch Phillips
842cead4eceSMitch Phillips // upper_bound's previous item contains Address.
843cead4eceSMitch Phillips --R;
844cead4eceSMitch Phillips if (Address >= R->second.first)
845cead4eceSMitch Phillips return DWARFDie();
846cead4eceSMitch Phillips return R->second.second;
847cead4eceSMitch Phillips }
848cead4eceSMitch Phillips
849c8c1032cSGreg Clayton void
getInlinedChainForAddress(uint64_t Address,SmallVectorImpl<DWARFDie> & InlinedChain)850c8c1032cSGreg Clayton DWARFUnit::getInlinedChainForAddress(uint64_t Address,
851c8c1032cSGreg Clayton SmallVectorImpl<DWARFDie> &InlinedChain) {
852db569baeSDehao Chen assert(InlinedChain.empty());
85382af9438SZachary Turner // Try to look for subprogram DIEs in the DWO file.
85482af9438SZachary Turner parseDWO();
855db569baeSDehao Chen // First, find the subroutine that contains the given address (the leaf
856db569baeSDehao Chen // of inlined chain).
857db569baeSDehao Chen DWARFDie SubroutineDIE =
85812faa0d4SDavid Blaikie (DWO ? *DWO : *this).getSubroutineForAddress(Address);
85982af9438SZachary Turner
860df6d0579SAlex Orlov while (SubroutineDIE) {
861df6d0579SAlex Orlov if (SubroutineDIE.isSubprogramDIE()) {
862df6d0579SAlex Orlov InlinedChain.push_back(SubroutineDIE);
863aa537da8SDavid Blaikie return;
864df6d0579SAlex Orlov }
865aa537da8SDavid Blaikie if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
866a364f09fSDehao Chen InlinedChain.push_back(SubroutineDIE);
867a364f09fSDehao Chen SubroutineDIE = SubroutineDIE.getParent();
868a364f09fSDehao Chen }
86982af9438SZachary Turner }
87082641be4SDavid Blaikie
getDWARFUnitIndex(DWARFContext & Context,DWARFSectionKind Kind)87128db7e65SEugene Zelenko const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
87282641be4SDavid Blaikie DWARFSectionKind Kind) {
87382641be4SDavid Blaikie if (Kind == DW_SECT_INFO)
87482641be4SDavid Blaikie return Context.getCUIndex();
875a0249fe9SIgor Kudrin assert(Kind == DW_SECT_EXT_TYPES);
87682641be4SDavid Blaikie return Context.getTUIndex();
87782641be4SDavid Blaikie }
878570e39a2SEugene Zelenko
getParent(const DWARFDebugInfoEntry * Die)87978a07bfaSGreg Clayton DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
88078a07bfaSGreg Clayton if (!Die)
88178a07bfaSGreg Clayton return DWARFDie();
8820b8c5081SAlexey Lapshin
8830b8c5081SAlexey Lapshin if (Optional<uint32_t> ParentIdx = Die->getParentIdx()) {
8840b8c5081SAlexey Lapshin assert(*ParentIdx < DieArray.size() &&
8850b8c5081SAlexey Lapshin "ParentIdx is out of DieArray boundaries");
8860b8c5081SAlexey Lapshin return DWARFDie(this, &DieArray[*ParentIdx]);
88778a07bfaSGreg Clayton }
8880b8c5081SAlexey Lapshin
88978a07bfaSGreg Clayton return DWARFDie();
89078a07bfaSGreg Clayton }
89178a07bfaSGreg Clayton
getSibling(const DWARFDebugInfoEntry * Die)89278a07bfaSGreg Clayton DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
89378a07bfaSGreg Clayton if (!Die)
89478a07bfaSGreg Clayton return DWARFDie();
89578a07bfaSGreg Clayton
8960b8c5081SAlexey Lapshin if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
8970b8c5081SAlexey Lapshin assert(*SiblingIdx < DieArray.size() &&
8980b8c5081SAlexey Lapshin "SiblingIdx is out of DieArray boundaries");
8990b8c5081SAlexey Lapshin return DWARFDie(this, &DieArray[*SiblingIdx]);
90078a07bfaSGreg Clayton }
9010b8c5081SAlexey Lapshin
90278a07bfaSGreg Clayton return DWARFDie();
90378a07bfaSGreg Clayton }
904485e01beSDavid Blaikie
getPreviousSibling(const DWARFDebugInfoEntry * Die)9053f27e57aSJonas Devlieghere DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
9063f27e57aSJonas Devlieghere if (!Die)
9073f27e57aSJonas Devlieghere return DWARFDie();
9080b8c5081SAlexey Lapshin
9090b8c5081SAlexey Lapshin Optional<uint32_t> ParentIdx = Die->getParentIdx();
9100b8c5081SAlexey Lapshin if (!ParentIdx)
9110b8c5081SAlexey Lapshin // Die is a root die, there is no previous sibling.
9123f27e57aSJonas Devlieghere return DWARFDie();
9133f27e57aSJonas Devlieghere
9140b8c5081SAlexey Lapshin assert(*ParentIdx < DieArray.size() &&
9150b8c5081SAlexey Lapshin "ParentIdx is out of DieArray boundaries");
9160b8c5081SAlexey Lapshin assert(getDIEIndex(Die) > 0 && "Die is a root die");
9170b8c5081SAlexey Lapshin
9180b8c5081SAlexey Lapshin uint32_t PrevDieIdx = getDIEIndex(Die) - 1;
9190b8c5081SAlexey Lapshin if (PrevDieIdx == *ParentIdx)
9200b8c5081SAlexey Lapshin // Immediately previous node is parent, there is no previous sibling.
9213f27e57aSJonas Devlieghere return DWARFDie();
9220b8c5081SAlexey Lapshin
9230b8c5081SAlexey Lapshin while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {
9240b8c5081SAlexey Lapshin PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();
9250b8c5081SAlexey Lapshin
9260b8c5081SAlexey Lapshin assert(PrevDieIdx < DieArray.size() &&
9270b8c5081SAlexey Lapshin "PrevDieIdx is out of DieArray boundaries");
9280b8c5081SAlexey Lapshin assert(PrevDieIdx >= *ParentIdx &&
9290b8c5081SAlexey Lapshin "PrevDieIdx is not a child of parent of Die");
9303f27e57aSJonas Devlieghere }
9310b8c5081SAlexey Lapshin
9320b8c5081SAlexey Lapshin return DWARFDie(this, &DieArray[PrevDieIdx]);
9333f27e57aSJonas Devlieghere }
9343f27e57aSJonas Devlieghere
getFirstChild(const DWARFDebugInfoEntry * Die)9350be860f6SGeorge Rimar DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
9360be860f6SGeorge Rimar if (!Die->hasChildren())
9370be860f6SGeorge Rimar return DWARFDie();
9380be860f6SGeorge Rimar
9390b8c5081SAlexey Lapshin // TODO: Instead of checking here for invalid die we might reject
9400b8c5081SAlexey Lapshin // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
9410be860f6SGeorge Rimar // We do not want access out of bounds when parsing corrupted debug data.
9420be860f6SGeorge Rimar size_t I = getDIEIndex(Die) + 1;
9430be860f6SGeorge Rimar if (I >= DieArray.size())
9440be860f6SGeorge Rimar return DWARFDie();
9450be860f6SGeorge Rimar return DWARFDie(this, &DieArray[I]);
9460be860f6SGeorge Rimar }
9470be860f6SGeorge Rimar
getLastChild(const DWARFDebugInfoEntry * Die)9483f27e57aSJonas Devlieghere DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
9493f27e57aSJonas Devlieghere if (!Die->hasChildren())
9503f27e57aSJonas Devlieghere return DWARFDie();
9513f27e57aSJonas Devlieghere
9520b8c5081SAlexey Lapshin if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
9530b8c5081SAlexey Lapshin assert(*SiblingIdx < DieArray.size() &&
9540b8c5081SAlexey Lapshin "SiblingIdx is out of DieArray boundaries");
9550b8c5081SAlexey Lapshin assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&
9560b8c5081SAlexey Lapshin "Bad end of children marker");
9570b8c5081SAlexey Lapshin return DWARFDie(this, &DieArray[*SiblingIdx - 1]);
9583f27e57aSJonas Devlieghere }
9590b8c5081SAlexey Lapshin
9600b8c5081SAlexey Lapshin // If SiblingIdx is set for non-root dies we could be sure that DWARF is
9610b8c5081SAlexey Lapshin // correct and "end of children marker" must be found. For root die we do not
9620b8c5081SAlexey Lapshin // have such a guarantee(parsing root die might be stopped if "end of children
9630b8c5081SAlexey Lapshin // marker" is missing, SiblingIdx is always zero for root die). That is why we
9640b8c5081SAlexey Lapshin // do not use assertion for checking for "end of children marker" for root
9650b8c5081SAlexey Lapshin // die.
9660b8c5081SAlexey Lapshin
9670b8c5081SAlexey Lapshin // TODO: Instead of checking here for invalid die we might reject
9680b8c5081SAlexey Lapshin // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
9690b8c5081SAlexey Lapshin if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&
9700b8c5081SAlexey Lapshin DieArray.back().getTag() == dwarf::DW_TAG_null) {
9710b8c5081SAlexey Lapshin // For the unit die we might take last item from DieArray.
9720b8c5081SAlexey Lapshin assert(getDIEIndex(Die) == getDIEIndex(getUnitDIE()) && "Bad unit die");
9730b8c5081SAlexey Lapshin return DWARFDie(this, &DieArray.back());
9740b8c5081SAlexey Lapshin }
9750b8c5081SAlexey Lapshin
9763f27e57aSJonas Devlieghere return DWARFDie();
9773f27e57aSJonas Devlieghere }
9783f27e57aSJonas Devlieghere
getAbbreviations() const979485e01beSDavid Blaikie const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
980485e01beSDavid Blaikie if (!Abbrevs)
981c19a2891SJan Kratochvil Abbrevs = Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset());
982485e01beSDavid Blaikie return Abbrevs;
983485e01beSDavid Blaikie }
9846ecd6a80SWolfgang Pieb
getBaseAddress()98577fc1f60SAlexey Lapshin llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
986c111382aSJonas Devlieghere if (BaseAddr)
987c111382aSJonas Devlieghere return BaseAddr;
988c111382aSJonas Devlieghere
989c111382aSJonas Devlieghere DWARFDie UnitDie = getUnitDIE();
990c111382aSJonas Devlieghere Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
991161dd3c1SDavid Blaikie BaseAddr = toSectionedAddress(PC);
992c111382aSJonas Devlieghere return BaseAddr;
993c111382aSJonas Devlieghere }
994c111382aSJonas Devlieghere
995a17564c2SDavid Blaikie Expected<StrOffsetsContributionDescriptor>
validateContributionSize(DWARFDataExtractor & DA)9966ecd6a80SWolfgang Pieb StrOffsetsContributionDescriptor::validateContributionSize(
9976ecd6a80SWolfgang Pieb DWARFDataExtractor &DA) {
9986ecd6a80SWolfgang Pieb uint8_t EntrySize = getDwarfOffsetByteSize();
9996ecd6a80SWolfgang Pieb // In order to ensure that we don't read a partial record at the end of
10006ecd6a80SWolfgang Pieb // the section we validate for a multiple of the entry size.
10016ecd6a80SWolfgang Pieb uint64_t ValidationSize = alignTo(Size, EntrySize);
10026ecd6a80SWolfgang Pieb // Guard against overflow.
10036ecd6a80SWolfgang Pieb if (ValidationSize >= Size)
10046ecd6a80SWolfgang Pieb if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
10056ecd6a80SWolfgang Pieb return *this;
1006a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "length exceeds section size");
10076ecd6a80SWolfgang Pieb }
10086ecd6a80SWolfgang Pieb
10096ecd6a80SWolfgang Pieb // Look for a DWARF64-formatted contribution to the string offsets table
10106ecd6a80SWolfgang Pieb // starting at a given offset and record it in a descriptor.
1011a17564c2SDavid Blaikie static Expected<StrOffsetsContributionDescriptor>
parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor & DA,uint64_t Offset)1012f26a70a5SIgor Kudrin parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
10136ecd6a80SWolfgang Pieb if (!DA.isValidOffsetForDataOfSize(Offset, 16))
1014a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "section offset exceeds section size");
10156ecd6a80SWolfgang Pieb
10163daefb07SIgor Kudrin if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
1017a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
10186ecd6a80SWolfgang Pieb
10196ecd6a80SWolfgang Pieb uint64_t Size = DA.getU64(&Offset);
10206ecd6a80SWolfgang Pieb uint8_t Version = DA.getU16(&Offset);
10216ecd6a80SWolfgang Pieb (void)DA.getU16(&Offset); // padding
1022f2b6915eSWolfgang Pieb // The encoded length includes the 2-byte version field and the 2-byte
1023f2b6915eSWolfgang Pieb // padding, so we need to subtract them out when we populate the descriptor.
1024a17564c2SDavid Blaikie return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
10256ecd6a80SWolfgang Pieb }
10266ecd6a80SWolfgang Pieb
10276ecd6a80SWolfgang Pieb // Look for a DWARF32-formatted contribution to the string offsets table
10286ecd6a80SWolfgang Pieb // starting at a given offset and record it in a descriptor.
1029a17564c2SDavid Blaikie static Expected<StrOffsetsContributionDescriptor>
parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor & DA,uint64_t Offset)1030f26a70a5SIgor Kudrin parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
10316ecd6a80SWolfgang Pieb if (!DA.isValidOffsetForDataOfSize(Offset, 8))
1032a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "section offset exceeds section size");
1033a17564c2SDavid Blaikie
10346ecd6a80SWolfgang Pieb uint32_t ContributionSize = DA.getU32(&Offset);
10353daefb07SIgor Kudrin if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
1036a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "invalid length");
1037a17564c2SDavid Blaikie
10386ecd6a80SWolfgang Pieb uint8_t Version = DA.getU16(&Offset);
10396ecd6a80SWolfgang Pieb (void)DA.getU16(&Offset); // padding
1040f2b6915eSWolfgang Pieb // The encoded length includes the 2-byte version field and the 2-byte
1041f2b6915eSWolfgang Pieb // padding, so we need to subtract them out when we populate the descriptor.
1042a17564c2SDavid Blaikie return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
1043a17564c2SDavid Blaikie DWARF32);
10446ecd6a80SWolfgang Pieb }
10456ecd6a80SWolfgang Pieb
1046a17564c2SDavid Blaikie static Expected<StrOffsetsContributionDescriptor>
parseDWARFStringOffsetsTableHeader(DWARFDataExtractor & DA,llvm::dwarf::DwarfFormat Format,uint64_t Offset)1047a17564c2SDavid Blaikie parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
1048a17564c2SDavid Blaikie llvm::dwarf::DwarfFormat Format,
1049a17564c2SDavid Blaikie uint64_t Offset) {
1050a17564c2SDavid Blaikie StrOffsetsContributionDescriptor Desc;
1051a17564c2SDavid Blaikie switch (Format) {
1052a17564c2SDavid Blaikie case dwarf::DwarfFormat::DWARF64: {
1053fc302c2bSDavid Blaikie if (Offset < 16)
1054a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
1055f26a70a5SIgor Kudrin auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
1056a17564c2SDavid Blaikie if (!DescOrError)
1057a17564c2SDavid Blaikie return DescOrError.takeError();
1058a17564c2SDavid Blaikie Desc = *DescOrError;
1059fc302c2bSDavid Blaikie break;
1060fc302c2bSDavid Blaikie }
1061a17564c2SDavid Blaikie case dwarf::DwarfFormat::DWARF32: {
1062a17564c2SDavid Blaikie if (Offset < 8)
1063a17564c2SDavid Blaikie return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
1064f26a70a5SIgor Kudrin auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
1065a17564c2SDavid Blaikie if (!DescOrError)
1066a17564c2SDavid Blaikie return DescOrError.takeError();
1067a17564c2SDavid Blaikie Desc = *DescOrError;
1068a17564c2SDavid Blaikie break;
1069a17564c2SDavid Blaikie }
1070a17564c2SDavid Blaikie }
1071a17564c2SDavid Blaikie return Desc.validateContributionSize(DA);
10726ecd6a80SWolfgang Pieb }
10736ecd6a80SWolfgang Pieb
1074a17564c2SDavid Blaikie Expected<Optional<StrOffsetsContributionDescriptor>>
determineStringOffsetsTableContribution(DWARFDataExtractor & DA)1075a17564c2SDavid Blaikie DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
10761f48e22dSIgor Kudrin assert(!IsDWO);
1077a17564c2SDavid Blaikie auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
1078a17564c2SDavid Blaikie if (!OptOffset)
1079a17564c2SDavid Blaikie return None;
10801f48e22dSIgor Kudrin auto DescOrError =
10811f48e22dSIgor Kudrin parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
1082a17564c2SDavid Blaikie if (!DescOrError)
1083a17564c2SDavid Blaikie return DescOrError.takeError();
1084a17564c2SDavid Blaikie return *DescOrError;
1085a17564c2SDavid Blaikie }
1086a17564c2SDavid Blaikie
1087a17564c2SDavid Blaikie Expected<Optional<StrOffsetsContributionDescriptor>>
determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA)1088d57b5251SWolfgang Pieb DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
10891f48e22dSIgor Kudrin assert(IsDWO);
1090d57b5251SWolfgang Pieb uint64_t Offset = 0;
1091d57b5251SWolfgang Pieb auto IndexEntry = Header.getIndexEntry();
1092d57b5251SWolfgang Pieb const auto *C =
1093f13ce15dSIgor Kudrin IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
1094d57b5251SWolfgang Pieb if (C)
1095d57b5251SWolfgang Pieb Offset = C->Offset;
10966ecd6a80SWolfgang Pieb if (getVersion() >= 5) {
1097a17564c2SDavid Blaikie if (DA.getData().data() == nullptr)
1098a17564c2SDavid Blaikie return None;
1099a17564c2SDavid Blaikie Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
11006ecd6a80SWolfgang Pieb // Look for a valid contribution at the given offset.
1101a17564c2SDavid Blaikie auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
1102a17564c2SDavid Blaikie if (!DescOrError)
1103a17564c2SDavid Blaikie return DescOrError.takeError();
1104a17564c2SDavid Blaikie return *DescOrError;
11056ecd6a80SWolfgang Pieb }
11066ecd6a80SWolfgang Pieb // Prior to DWARF v5, we derive the contribution size from the
11076ecd6a80SWolfgang Pieb // index table (in a package file). In a .dwo file it is simply
11086ecd6a80SWolfgang Pieb // the length of the string offsets section.
110995fad44eSIgor Kudrin StrOffsetsContributionDescriptor Desc;
1110d57b5251SWolfgang Pieb if (C)
111195fad44eSIgor Kudrin Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4,
111295fad44eSIgor Kudrin Header.getFormat());
111395fad44eSIgor Kudrin else if (!IndexEntry && !StringOffsetSection.Data.empty())
111495fad44eSIgor Kudrin Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
111595fad44eSIgor Kudrin 4, Header.getFormat());
111695fad44eSIgor Kudrin else
1117d57b5251SWolfgang Pieb return None;
111895fad44eSIgor Kudrin auto DescOrError = Desc.validateContributionSize(DA);
111995fad44eSIgor Kudrin if (!DescOrError)
112095fad44eSIgor Kudrin return DescOrError.takeError();
112195fad44eSIgor Kudrin return *DescOrError;
11226ecd6a80SWolfgang Pieb }
1123f7a49d2aSDavid Blaikie
getRnglistOffset(uint32_t Index)1124f7a49d2aSDavid Blaikie Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
1125f7a49d2aSDavid Blaikie DataExtractor RangesData(RangeSection->Data, isLittleEndian,
1126f7a49d2aSDavid Blaikie getAddressByteSize());
11276d0be74aSDavid Blaikie DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
11286d0be74aSDavid Blaikie isLittleEndian, 0);
11296d0be74aSDavid Blaikie if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
11306d0be74aSDavid Blaikie RangesData, RangeSectionBase, getFormat(), Index))
1131f7a49d2aSDavid Blaikie return *Off + RangeSectionBase;
1132f7a49d2aSDavid Blaikie return None;
1133f7a49d2aSDavid Blaikie }
11349670a45cSDavid Blaikie
getLoclistOffset(uint32_t Index)11359670a45cSDavid Blaikie Optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {
11369670a45cSDavid Blaikie if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
11379670a45cSDavid Blaikie LocTable->getData(), LocSectionBase, getFormat(), Index))
11389670a45cSDavid Blaikie return *Off + LocSectionBase;
11399670a45cSDavid Blaikie return None;
11409670a45cSDavid Blaikie }
1141