10b57cec5SDimitry Andric //===- DWARFUnit.cpp ------------------------------------------------------===//
20b57cec5SDimitry Andric //
30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
60b57cec5SDimitry Andric //
70b57cec5SDimitry Andric //===----------------------------------------------------------------------===//
80b57cec5SDimitry Andric 
90b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
100b57cec5SDimitry Andric #include "llvm/ADT/SmallString.h"
110b57cec5SDimitry Andric #include "llvm/ADT/StringRef.h"
1281ad6265SDimitry Andric #include "llvm/BinaryFormat/Dwarf.h"
130b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
140b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
150b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFContext.h"
160b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
170b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
1881ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"
1981ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
200b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
210b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFDie.h"
2281ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFExpression.h"
230b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
2481ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFListTable.h"
2581ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFObject.h"
2681ad6265SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFSection.h"
270b57cec5SDimitry Andric #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
2881ad6265SDimitry Andric #include "llvm/Object/ObjectFile.h"
290b57cec5SDimitry Andric #include "llvm/Support/DataExtractor.h"
300b57cec5SDimitry Andric #include "llvm/Support/Errc.h"
310b57cec5SDimitry Andric #include "llvm/Support/Path.h"
320b57cec5SDimitry Andric #include <algorithm>
330b57cec5SDimitry Andric #include <cassert>
340b57cec5SDimitry Andric #include <cstddef>
350b57cec5SDimitry Andric #include <cstdint>
360b57cec5SDimitry Andric #include <utility>
370b57cec5SDimitry Andric #include <vector>
380b57cec5SDimitry Andric 
390b57cec5SDimitry Andric using namespace llvm;
400b57cec5SDimitry Andric using namespace dwarf;
410b57cec5SDimitry Andric 
addUnitsForSection(DWARFContext & C,const DWARFSection & Section,DWARFSectionKind SectionKind)420b57cec5SDimitry Andric void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
430b57cec5SDimitry Andric                                          const DWARFSection &Section,
440b57cec5SDimitry Andric                                          DWARFSectionKind SectionKind) {
450b57cec5SDimitry Andric   const DWARFObject &D = C.getDWARFObj();
468bcb0991SDimitry Andric   addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
478bcb0991SDimitry Andric                &D.getLocSection(), D.getStrSection(),
488bcb0991SDimitry Andric                D.getStrOffsetsSection(), &D.getAddrSection(),
490b57cec5SDimitry Andric                D.getLineSection(), D.isLittleEndian(), false, false,
500b57cec5SDimitry Andric                SectionKind);
510b57cec5SDimitry Andric }
520b57cec5SDimitry Andric 
addUnitsForDWOSection(DWARFContext & C,const DWARFSection & DWOSection,DWARFSectionKind SectionKind,bool Lazy)530b57cec5SDimitry Andric void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
540b57cec5SDimitry Andric                                             const DWARFSection &DWOSection,
550b57cec5SDimitry Andric                                             DWARFSectionKind SectionKind,
560b57cec5SDimitry Andric                                             bool Lazy) {
570b57cec5SDimitry Andric   const DWARFObject &D = C.getDWARFObj();
588bcb0991SDimitry Andric   addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
598bcb0991SDimitry Andric                &D.getLocDWOSection(), D.getStrDWOSection(),
608bcb0991SDimitry Andric                D.getStrOffsetsDWOSection(), &D.getAddrSection(),
610b57cec5SDimitry Andric                D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
620b57cec5SDimitry Andric                SectionKind);
630b57cec5SDimitry Andric }
640b57cec5SDimitry Andric 
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)650b57cec5SDimitry Andric void DWARFUnitVector::addUnitsImpl(
660b57cec5SDimitry Andric     DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
670b57cec5SDimitry Andric     const DWARFDebugAbbrev *DA, const DWARFSection *RS,
680b57cec5SDimitry Andric     const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
690b57cec5SDimitry Andric     const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
700b57cec5SDimitry Andric     bool Lazy, DWARFSectionKind SectionKind) {
710b57cec5SDimitry Andric   DWARFDataExtractor Data(Obj, Section, LE, 0);
720b57cec5SDimitry Andric   // Lazy initialization of Parser, now that we have all section info.
730b57cec5SDimitry Andric   if (!Parser) {
740b57cec5SDimitry Andric     Parser = [=, &Context, &Obj, &Section, &SOS,
758bcb0991SDimitry Andric               &LS](uint64_t Offset, DWARFSectionKind SectionKind,
760b57cec5SDimitry Andric                    const DWARFSection *CurSection,
770b57cec5SDimitry Andric                    const DWARFUnitIndex::Entry *IndexEntry)
780b57cec5SDimitry Andric         -> std::unique_ptr<DWARFUnit> {
790b57cec5SDimitry Andric       const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
800b57cec5SDimitry Andric       DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
810b57cec5SDimitry Andric       if (!Data.isValidOffset(Offset))
820b57cec5SDimitry Andric         return nullptr;
830b57cec5SDimitry Andric       DWARFUnitHeader Header;
845f757f3fSDimitry Andric       if (Error ExtractErr =
855f757f3fSDimitry Andric               Header.extract(Context, Data, &Offset, SectionKind)) {
865f757f3fSDimitry Andric         Context.getWarningHandler()(std::move(ExtractErr));
875ffd83dbSDimitry Andric         return nullptr;
885f757f3fSDimitry Andric       }
895ffd83dbSDimitry Andric       if (!IndexEntry && IsDWO) {
905ffd83dbSDimitry Andric         const DWARFUnitIndex &Index = getDWARFUnitIndex(
915ffd83dbSDimitry Andric             Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);
9281ad6265SDimitry Andric         if (Index) {
9381ad6265SDimitry Andric           if (Header.isTypeUnit())
9481ad6265SDimitry Andric             IndexEntry = Index.getFromHash(Header.getTypeHash());
9581ad6265SDimitry Andric           else if (auto DWOId = Header.getDWOId())
9681ad6265SDimitry Andric             IndexEntry = Index.getFromHash(*DWOId);
9781ad6265SDimitry Andric         }
9881ad6265SDimitry Andric         if (!IndexEntry)
995ffd83dbSDimitry Andric           IndexEntry = Index.getFromOffset(Header.getOffset());
1005ffd83dbSDimitry Andric       }
1015ffd83dbSDimitry Andric       if (IndexEntry && !Header.applyIndexEntry(IndexEntry))
1020b57cec5SDimitry Andric         return nullptr;
1030b57cec5SDimitry Andric       std::unique_ptr<DWARFUnit> U;
1040b57cec5SDimitry Andric       if (Header.isTypeUnit())
1058bcb0991SDimitry Andric         U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
1060b57cec5SDimitry Andric                                              RS, LocSection, SS, SOS, AOS, LS,
1070b57cec5SDimitry Andric                                              LE, IsDWO, *this);
1080b57cec5SDimitry Andric       else
1098bcb0991SDimitry Andric         U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
1100b57cec5SDimitry Andric                                                 DA, RS, LocSection, SS, SOS,
1110b57cec5SDimitry Andric                                                 AOS, LS, LE, IsDWO, *this);
1120b57cec5SDimitry Andric       return U;
1130b57cec5SDimitry Andric     };
1140b57cec5SDimitry Andric   }
1150b57cec5SDimitry Andric   if (Lazy)
1160b57cec5SDimitry Andric     return;
1170b57cec5SDimitry Andric   // Find a reasonable insertion point within the vector.  We skip over
1180b57cec5SDimitry Andric   // (a) units from a different section, (b) units from the same section
1190b57cec5SDimitry Andric   // but with lower offset-within-section.  This keeps units in order
1200b57cec5SDimitry Andric   // within a section, although not necessarily within the object file,
1210b57cec5SDimitry Andric   // even if we do lazy parsing.
1220b57cec5SDimitry Andric   auto I = this->begin();
1238bcb0991SDimitry Andric   uint64_t Offset = 0;
1240b57cec5SDimitry Andric   while (Data.isValidOffset(Offset)) {
1250b57cec5SDimitry Andric     if (I != this->end() &&
1260b57cec5SDimitry Andric         (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
1270b57cec5SDimitry Andric       ++I;
1280b57cec5SDimitry Andric       continue;
1290b57cec5SDimitry Andric     }
1300b57cec5SDimitry Andric     auto U = Parser(Offset, SectionKind, &Section, nullptr);
1310b57cec5SDimitry Andric     // If parsing failed, we're done with this section.
1320b57cec5SDimitry Andric     if (!U)
1330b57cec5SDimitry Andric       break;
1340b57cec5SDimitry Andric     Offset = U->getNextUnitOffset();
1350b57cec5SDimitry Andric     I = std::next(this->insert(I, std::move(U)));
1360b57cec5SDimitry Andric   }
1370b57cec5SDimitry Andric }
1380b57cec5SDimitry Andric 
addUnit(std::unique_ptr<DWARFUnit> Unit)1390b57cec5SDimitry Andric DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {
140bdd1243dSDimitry Andric   auto I = llvm::upper_bound(*this, Unit,
1410b57cec5SDimitry Andric                              [](const std::unique_ptr<DWARFUnit> &LHS,
1420b57cec5SDimitry Andric                                 const std::unique_ptr<DWARFUnit> &RHS) {
1430b57cec5SDimitry Andric                                return LHS->getOffset() < RHS->getOffset();
1440b57cec5SDimitry Andric                              });
1450b57cec5SDimitry Andric   return this->insert(I, std::move(Unit))->get();
1460b57cec5SDimitry Andric }
1470b57cec5SDimitry Andric 
getUnitForOffset(uint64_t Offset) const1488bcb0991SDimitry Andric DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {
1490b57cec5SDimitry Andric   auto end = begin() + getNumInfoUnits();
1500b57cec5SDimitry Andric   auto *CU =
1510b57cec5SDimitry Andric       std::upper_bound(begin(), end, Offset,
1528bcb0991SDimitry Andric                        [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
1530b57cec5SDimitry Andric                          return LHS < RHS->getNextUnitOffset();
1540b57cec5SDimitry Andric                        });
1550b57cec5SDimitry Andric   if (CU != end && (*CU)->getOffset() <= Offset)
1560b57cec5SDimitry Andric     return CU->get();
1570b57cec5SDimitry Andric   return nullptr;
1580b57cec5SDimitry Andric }
1590b57cec5SDimitry Andric 
1600b57cec5SDimitry Andric DWARFUnit *
getUnitForIndexEntry(const DWARFUnitIndex::Entry & E)1610b57cec5SDimitry Andric DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) {
1625ffd83dbSDimitry Andric   const auto *CUOff = E.getContribution(DW_SECT_INFO);
1630b57cec5SDimitry Andric   if (!CUOff)
1640b57cec5SDimitry Andric     return nullptr;
1650b57cec5SDimitry Andric 
166bdd1243dSDimitry Andric   uint64_t Offset = CUOff->getOffset();
1670b57cec5SDimitry Andric   auto end = begin() + getNumInfoUnits();
1680b57cec5SDimitry Andric 
1690b57cec5SDimitry Andric   auto *CU =
170bdd1243dSDimitry Andric       std::upper_bound(begin(), end, CUOff->getOffset(),
1718bcb0991SDimitry Andric                        [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
1720b57cec5SDimitry Andric                          return LHS < RHS->getNextUnitOffset();
1730b57cec5SDimitry Andric                        });
1740b57cec5SDimitry Andric   if (CU != end && (*CU)->getOffset() <= Offset)
1750b57cec5SDimitry Andric     return CU->get();
1760b57cec5SDimitry Andric 
1770b57cec5SDimitry Andric   if (!Parser)
1780b57cec5SDimitry Andric     return nullptr;
1790b57cec5SDimitry Andric 
1800b57cec5SDimitry Andric   auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E);
1810b57cec5SDimitry Andric   if (!U)
18206c3fb27SDimitry Andric     return nullptr;
1830b57cec5SDimitry Andric 
1840b57cec5SDimitry Andric   auto *NewCU = U.get();
1850b57cec5SDimitry Andric   this->insert(CU, std::move(U));
1860b57cec5SDimitry Andric   ++NumInfoUnits;
1870b57cec5SDimitry Andric   return NewCU;
1880b57cec5SDimitry Andric }
1890b57cec5SDimitry Andric 
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)1900b57cec5SDimitry Andric DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
1910b57cec5SDimitry Andric                      const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
1920b57cec5SDimitry Andric                      const DWARFSection *RS, const DWARFSection *LocSection,
1930b57cec5SDimitry Andric                      StringRef SS, const DWARFSection &SOS,
1940b57cec5SDimitry Andric                      const DWARFSection *AOS, const DWARFSection &LS, bool LE,
1950b57cec5SDimitry Andric                      bool IsDWO, const DWARFUnitVector &UnitVector)
1960b57cec5SDimitry Andric     : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
197480093f4SDimitry Andric       RangeSection(RS), LineSection(LS), StringSection(SS),
198bdd1243dSDimitry Andric       StringOffsetSection(SOS), AddrOffsetSection(AOS), IsLittleEndian(LE),
199480093f4SDimitry Andric       IsDWO(IsDWO), UnitVector(UnitVector) {
2000b57cec5SDimitry Andric   clear();
2010b57cec5SDimitry Andric }
2020b57cec5SDimitry Andric 
2030b57cec5SDimitry Andric DWARFUnit::~DWARFUnit() = default;
2040b57cec5SDimitry Andric 
getDebugInfoExtractor() const2050b57cec5SDimitry Andric DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
206bdd1243dSDimitry Andric   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, IsLittleEndian,
2070b57cec5SDimitry Andric                             getAddressByteSize());
2080b57cec5SDimitry Andric }
2090b57cec5SDimitry Andric 
210bdd1243dSDimitry Andric std::optional<object::SectionedAddress>
getAddrOffsetSectionItem(uint32_t Index) const2110b57cec5SDimitry Andric DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
212fe6060f1SDimitry Andric   if (!AddrOffsetSectionBase) {
2130b57cec5SDimitry Andric     auto R = Context.info_section_units();
2140b57cec5SDimitry Andric     // Surprising if a DWO file has more than one skeleton unit in it - this
2150b57cec5SDimitry Andric     // probably shouldn't be valid, but if a use case is found, here's where to
2160b57cec5SDimitry Andric     // support it (probably have to linearly search for the matching skeleton CU
2170b57cec5SDimitry Andric     // here)
218fe6060f1SDimitry Andric     if (IsDWO && hasSingleElement(R))
219e8d8bef9SDimitry Andric       return (*R.begin())->getAddrOffsetSectionItem(Index);
220fe6060f1SDimitry Andric 
221bdd1243dSDimitry Andric     return std::nullopt;
222fe6060f1SDimitry Andric   }
223fe6060f1SDimitry Andric 
224480093f4SDimitry Andric   uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
2250b57cec5SDimitry Andric   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
226bdd1243dSDimitry Andric     return std::nullopt;
2270b57cec5SDimitry Andric   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
228bdd1243dSDimitry Andric                         IsLittleEndian, getAddressByteSize());
2290b57cec5SDimitry Andric   uint64_t Section;
2300b57cec5SDimitry Andric   uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
2310b57cec5SDimitry Andric   return {{Address, Section}};
2320b57cec5SDimitry Andric }
2330b57cec5SDimitry Andric 
getStringOffsetSectionItem(uint32_t Index) const2340eae32dcSDimitry Andric Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
2350b57cec5SDimitry Andric   if (!StringOffsetsTableContribution)
2360eae32dcSDimitry Andric     return make_error<StringError>(
2370eae32dcSDimitry Andric         "DW_FORM_strx used without a valid string offsets table",
2380eae32dcSDimitry Andric         inconvertibleErrorCode());
2390b57cec5SDimitry Andric   unsigned ItemSize = getDwarfStringOffsetsByteSize();
2408bcb0991SDimitry Andric   uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
2410b57cec5SDimitry Andric   if (StringOffsetSection.Data.size() < Offset + ItemSize)
2420eae32dcSDimitry Andric     return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +
2430eae32dcSDimitry Andric                                        ", which is too large",
2440eae32dcSDimitry Andric                                    inconvertibleErrorCode());
2450b57cec5SDimitry Andric   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
246bdd1243dSDimitry Andric                         IsLittleEndian, 0);
2470b57cec5SDimitry Andric   return DA.getRelocatedValue(ItemSize, &Offset);
2480b57cec5SDimitry Andric }
2490b57cec5SDimitry Andric 
extract(DWARFContext & Context,const DWARFDataExtractor & debug_info,uint64_t * offset_ptr,DWARFSectionKind SectionKind)2505f757f3fSDimitry Andric Error DWARFUnitHeader::extract(DWARFContext &Context,
2510b57cec5SDimitry Andric                                const DWARFDataExtractor &debug_info,
2528bcb0991SDimitry Andric                                uint64_t *offset_ptr,
2535ffd83dbSDimitry Andric                                DWARFSectionKind SectionKind) {
2540b57cec5SDimitry Andric   Offset = *offset_ptr;
255480093f4SDimitry Andric   Error Err = Error::success();
2565ffd83dbSDimitry Andric   IndexEntry = nullptr;
2575ffd83dbSDimitry Andric   std::tie(Length, FormParams.Format) =
2585ffd83dbSDimitry Andric       debug_info.getInitialLength(offset_ptr, &Err);
259480093f4SDimitry Andric   FormParams.Version = debug_info.getU16(offset_ptr, &Err);
2600b57cec5SDimitry Andric   if (FormParams.Version >= 5) {
261480093f4SDimitry Andric     UnitType = debug_info.getU8(offset_ptr, &Err);
262480093f4SDimitry Andric     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
263480093f4SDimitry Andric     AbbrOffset = debug_info.getRelocatedValue(
264480093f4SDimitry Andric         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
2650b57cec5SDimitry Andric   } else {
266480093f4SDimitry Andric     AbbrOffset = debug_info.getRelocatedValue(
267480093f4SDimitry Andric         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
268480093f4SDimitry Andric     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
2690b57cec5SDimitry Andric     // Fake a unit type based on the section type.  This isn't perfect,
2700b57cec5SDimitry Andric     // but distinguishing compile and type units is generally enough.
2715ffd83dbSDimitry Andric     if (SectionKind == DW_SECT_EXT_TYPES)
2720b57cec5SDimitry Andric       UnitType = DW_UT_type;
2730b57cec5SDimitry Andric     else
2740b57cec5SDimitry Andric       UnitType = DW_UT_compile;
2750b57cec5SDimitry Andric   }
2760b57cec5SDimitry Andric   if (isTypeUnit()) {
277480093f4SDimitry Andric     TypeHash = debug_info.getU64(offset_ptr, &Err);
278480093f4SDimitry Andric     TypeOffset = debug_info.getUnsigned(
279480093f4SDimitry Andric         offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);
2800b57cec5SDimitry Andric   } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
281480093f4SDimitry Andric     DWOId = debug_info.getU64(offset_ptr, &Err);
282480093f4SDimitry Andric 
2835f757f3fSDimitry Andric   if (Err)
2845f757f3fSDimitry Andric     return joinErrors(
285fe6060f1SDimitry Andric         createStringError(
286fe6060f1SDimitry Andric             errc::invalid_argument,
287fe6060f1SDimitry Andric             "DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Offset),
2885f757f3fSDimitry Andric         std::move(Err));
2890b57cec5SDimitry Andric 
2900b57cec5SDimitry Andric   // Header fields all parsed, capture the size of this unit header.
2910b57cec5SDimitry Andric   assert(*offset_ptr - Offset <= 255 && "unexpected header size");
2920b57cec5SDimitry Andric   Size = uint8_t(*offset_ptr - Offset);
293fe6060f1SDimitry Andric   uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();
294fe6060f1SDimitry Andric 
2955f757f3fSDimitry Andric   if (!debug_info.isValidOffset(getNextUnitOffset() - 1))
2965f757f3fSDimitry Andric     return createStringError(errc::invalid_argument,
297fe6060f1SDimitry Andric                              "DWARF unit from offset 0x%8.8" PRIx64 " incl. "
298fe6060f1SDimitry Andric                              "to offset  0x%8.8" PRIx64 " excl. "
299fe6060f1SDimitry Andric                              "extends past section size 0x%8.8zx",
3005f757f3fSDimitry Andric                              Offset, NextCUOffset, debug_info.size());
301fe6060f1SDimitry Andric 
3025f757f3fSDimitry Andric   if (!DWARFContext::isSupportedVersion(getVersion()))
3035f757f3fSDimitry Andric     return createStringError(
304fe6060f1SDimitry Andric         errc::invalid_argument,
305fe6060f1SDimitry Andric         "DWARF unit at offset 0x%8.8" PRIx64 " "
306fe6060f1SDimitry Andric         "has unsupported version %" PRIu16 ", supported are 2-%u",
3075f757f3fSDimitry Andric         Offset, getVersion(), DWARFContext::getMaxSupportedVersion());
3080b57cec5SDimitry Andric 
3090b57cec5SDimitry Andric   // Type offset is unit-relative; should be after the header and before
3100b57cec5SDimitry Andric   // the end of the current unit.
3115f757f3fSDimitry Andric   if (isTypeUnit() && TypeOffset < Size)
3125f757f3fSDimitry Andric     return createStringError(errc::invalid_argument,
313fe6060f1SDimitry Andric                              "DWARF type unit at offset "
314fe6060f1SDimitry Andric                              "0x%8.8" PRIx64 " "
315fe6060f1SDimitry Andric                              "has its relocated type_offset 0x%8.8" PRIx64 " "
316fe6060f1SDimitry Andric                              "pointing inside the header",
3175f757f3fSDimitry Andric                              Offset, Offset + TypeOffset);
3185f757f3fSDimitry Andric 
3195f757f3fSDimitry Andric   if (isTypeUnit() && TypeOffset >= getUnitLengthFieldByteSize() + getLength())
3205f757f3fSDimitry Andric     return createStringError(
321fe6060f1SDimitry Andric         errc::invalid_argument,
322fe6060f1SDimitry Andric         "DWARF type unit from offset 0x%8.8" PRIx64 " incl. "
323fe6060f1SDimitry Andric         "to offset 0x%8.8" PRIx64 " excl. has its "
324fe6060f1SDimitry Andric         "relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",
3255f757f3fSDimitry Andric         Offset, NextCUOffset, Offset + TypeOffset);
326fe6060f1SDimitry Andric 
327349cc55cSDimitry Andric   if (Error SizeErr = DWARFContext::checkAddressSizeSupported(
328349cc55cSDimitry Andric           getAddressByteSize(), errc::invalid_argument,
3295f757f3fSDimitry Andric           "DWARF unit at offset 0x%8.8" PRIx64, Offset))
3305f757f3fSDimitry Andric     return SizeErr;
3310b57cec5SDimitry Andric 
3320b57cec5SDimitry Andric   // Keep track of the highest DWARF version we encounter across all units.
3330b57cec5SDimitry Andric   Context.setMaxVersionIfGreater(getVersion());
3345f757f3fSDimitry Andric   return Error::success();
3350b57cec5SDimitry Andric }
3360b57cec5SDimitry Andric 
applyIndexEntry(const DWARFUnitIndex::Entry * Entry)3375ffd83dbSDimitry Andric bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
3385ffd83dbSDimitry Andric   assert(Entry);
3395ffd83dbSDimitry Andric   assert(!IndexEntry);
3405ffd83dbSDimitry Andric   IndexEntry = Entry;
3415ffd83dbSDimitry Andric   if (AbbrOffset)
3425ffd83dbSDimitry Andric     return false;
3435ffd83dbSDimitry Andric   auto *UnitContrib = IndexEntry->getContribution();
3445ffd83dbSDimitry Andric   if (!UnitContrib ||
345bdd1243dSDimitry Andric       UnitContrib->getLength() != (getLength() + getUnitLengthFieldByteSize()))
3465ffd83dbSDimitry Andric     return false;
3475ffd83dbSDimitry Andric   auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);
3485ffd83dbSDimitry Andric   if (!AbbrEntry)
3495ffd83dbSDimitry Andric     return false;
350bdd1243dSDimitry Andric   AbbrOffset = AbbrEntry->getOffset();
3515ffd83dbSDimitry Andric   return true;
3525ffd83dbSDimitry Andric }
3535ffd83dbSDimitry Andric 
extractRangeList(uint64_t RangeListOffset,DWARFDebugRangeList & RangeList) const3548bcb0991SDimitry Andric Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
3550b57cec5SDimitry Andric                                   DWARFDebugRangeList &RangeList) const {
3560b57cec5SDimitry Andric   // Require that compile unit is extracted.
3570b57cec5SDimitry Andric   assert(!DieArray.empty());
3580b57cec5SDimitry Andric   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
359bdd1243dSDimitry Andric                                 IsLittleEndian, getAddressByteSize());
3608bcb0991SDimitry Andric   uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
3610b57cec5SDimitry Andric   return RangeList.extract(RangesData, &ActualRangeListOffset);
3620b57cec5SDimitry Andric }
3630b57cec5SDimitry Andric 
clear()3640b57cec5SDimitry Andric void DWARFUnit::clear() {
3650b57cec5SDimitry Andric   Abbrevs = nullptr;
3660b57cec5SDimitry Andric   BaseAddr.reset();
3670b57cec5SDimitry Andric   RangeSectionBase = 0;
368480093f4SDimitry Andric   LocSectionBase = 0;
369bdd1243dSDimitry Andric   AddrOffsetSectionBase = std::nullopt;
370fe6060f1SDimitry Andric   SU = nullptr;
3710b57cec5SDimitry Andric   clearDIEs(false);
37281ad6265SDimitry Andric   AddrDieMap.clear();
37381ad6265SDimitry Andric   if (DWO)
37481ad6265SDimitry Andric     DWO->clear();
3750b57cec5SDimitry Andric   DWO.reset();
3760b57cec5SDimitry Andric }
3770b57cec5SDimitry Andric 
getCompilationDir()3780b57cec5SDimitry Andric const char *DWARFUnit::getCompilationDir() {
3790b57cec5SDimitry Andric   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
3800b57cec5SDimitry Andric }
3810b57cec5SDimitry Andric 
extractDIEsToVector(bool AppendCUDie,bool AppendNonCUDies,std::vector<DWARFDebugInfoEntry> & Dies) const3820b57cec5SDimitry Andric void DWARFUnit::extractDIEsToVector(
3830b57cec5SDimitry Andric     bool AppendCUDie, bool AppendNonCUDies,
3840b57cec5SDimitry Andric     std::vector<DWARFDebugInfoEntry> &Dies) const {
3850b57cec5SDimitry Andric   if (!AppendCUDie && !AppendNonCUDies)
3860b57cec5SDimitry Andric     return;
3870b57cec5SDimitry Andric 
3880b57cec5SDimitry Andric   // Set the offset to that of the first DIE and calculate the start of the
3890b57cec5SDimitry Andric   // next compilation unit header.
3908bcb0991SDimitry Andric   uint64_t DIEOffset = getOffset() + getHeaderSize();
3918bcb0991SDimitry Andric   uint64_t NextCUOffset = getNextUnitOffset();
3920b57cec5SDimitry Andric   DWARFDebugInfoEntry DIE;
3930b57cec5SDimitry Andric   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
394fe6060f1SDimitry Andric   // The end offset has been already checked by DWARFUnitHeader::extract.
395fe6060f1SDimitry Andric   assert(DebugInfoData.isValidOffset(NextCUOffset - 1));
396349cc55cSDimitry Andric   std::vector<uint32_t> Parents;
397349cc55cSDimitry Andric   std::vector<uint32_t> PrevSiblings;
3980b57cec5SDimitry Andric   bool IsCUDie = true;
3990b57cec5SDimitry Andric 
400349cc55cSDimitry Andric   assert(
401349cc55cSDimitry Andric       ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&
402349cc55cSDimitry Andric       "Dies array is not empty");
403349cc55cSDimitry Andric 
404349cc55cSDimitry Andric   // Fill Parents and Siblings stacks with initial value.
405349cc55cSDimitry Andric   Parents.push_back(UINT32_MAX);
406349cc55cSDimitry Andric   if (!AppendCUDie)
407349cc55cSDimitry Andric     Parents.push_back(0);
408349cc55cSDimitry Andric   PrevSiblings.push_back(0);
409349cc55cSDimitry Andric 
410349cc55cSDimitry Andric   // Start to extract dies.
411349cc55cSDimitry Andric   do {
412349cc55cSDimitry Andric     assert(Parents.size() > 0 && "Empty parents stack");
413349cc55cSDimitry Andric     assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&
414349cc55cSDimitry Andric            "Wrong parent index");
415349cc55cSDimitry Andric 
41681ad6265SDimitry Andric     // Extract die. Stop if any error occurred.
417349cc55cSDimitry Andric     if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
418349cc55cSDimitry Andric                          Parents.back()))
419349cc55cSDimitry Andric       break;
420349cc55cSDimitry Andric 
421349cc55cSDimitry Andric     // If previous sibling is remembered then update it`s SiblingIdx field.
422349cc55cSDimitry Andric     if (PrevSiblings.back() > 0) {
423349cc55cSDimitry Andric       assert(PrevSiblings.back() < Dies.size() &&
424349cc55cSDimitry Andric              "Previous sibling index is out of Dies boundaries");
425349cc55cSDimitry Andric       Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());
426349cc55cSDimitry Andric     }
427349cc55cSDimitry Andric 
428349cc55cSDimitry Andric     // Store die into the Dies vector.
4290b57cec5SDimitry Andric     if (IsCUDie) {
4300b57cec5SDimitry Andric       if (AppendCUDie)
4310b57cec5SDimitry Andric         Dies.push_back(DIE);
4320b57cec5SDimitry Andric       if (!AppendNonCUDies)
4330b57cec5SDimitry Andric         break;
4340b57cec5SDimitry Andric       // The average bytes per DIE entry has been seen to be
4350b57cec5SDimitry Andric       // around 14-20 so let's pre-reserve the needed memory for
4360b57cec5SDimitry Andric       // our DIE entries accordingly.
4370b57cec5SDimitry Andric       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
4380b57cec5SDimitry Andric     } else {
439349cc55cSDimitry Andric       // Remember last previous sibling.
440349cc55cSDimitry Andric       PrevSiblings.back() = Dies.size();
441349cc55cSDimitry Andric 
4420b57cec5SDimitry Andric       Dies.push_back(DIE);
4430b57cec5SDimitry Andric     }
4440b57cec5SDimitry Andric 
445349cc55cSDimitry Andric     // Check for new children scope.
4460b57cec5SDimitry Andric     if (const DWARFAbbreviationDeclaration *AbbrDecl =
4470b57cec5SDimitry Andric             DIE.getAbbreviationDeclarationPtr()) {
448349cc55cSDimitry Andric       if (AbbrDecl->hasChildren()) {
449349cc55cSDimitry Andric         if (AppendCUDie || !IsCUDie) {
450349cc55cSDimitry Andric           assert(Dies.size() > 0 && "Dies does not contain any die");
451349cc55cSDimitry Andric           Parents.push_back(Dies.size() - 1);
452349cc55cSDimitry Andric           PrevSiblings.push_back(0);
453349cc55cSDimitry Andric         }
454349cc55cSDimitry Andric       } else if (IsCUDie)
455349cc55cSDimitry Andric         // Stop if we have single compile unit die w/o children.
456349cc55cSDimitry Andric         break;
4570b57cec5SDimitry Andric     } else {
458349cc55cSDimitry Andric       // NULL DIE: finishes current children scope.
459349cc55cSDimitry Andric       Parents.pop_back();
460349cc55cSDimitry Andric       PrevSiblings.pop_back();
4610b57cec5SDimitry Andric     }
462349cc55cSDimitry Andric 
463349cc55cSDimitry Andric     if (IsCUDie)
464349cc55cSDimitry Andric       IsCUDie = false;
465349cc55cSDimitry Andric 
466349cc55cSDimitry Andric     // Stop when compile unit die is removed from the parents stack.
467349cc55cSDimitry Andric   } while (Parents.size() > 1);
4680b57cec5SDimitry Andric }
4690b57cec5SDimitry Andric 
extractDIEsIfNeeded(bool CUDieOnly)4708bcb0991SDimitry Andric void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
4718bcb0991SDimitry Andric   if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
4725ffd83dbSDimitry Andric     Context.getRecoverableErrorHandler()(std::move(e));
4738bcb0991SDimitry Andric }
4748bcb0991SDimitry Andric 
tryExtractDIEsIfNeeded(bool CUDieOnly)4758bcb0991SDimitry Andric Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
4760b57cec5SDimitry Andric   if ((CUDieOnly && !DieArray.empty()) ||
4770b57cec5SDimitry Andric       DieArray.size() > 1)
4788bcb0991SDimitry Andric     return Error::success(); // Already parsed.
4790b57cec5SDimitry Andric 
4800b57cec5SDimitry Andric   bool HasCUDie = !DieArray.empty();
4810b57cec5SDimitry Andric   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
4820b57cec5SDimitry Andric 
4830b57cec5SDimitry Andric   if (DieArray.empty())
4848bcb0991SDimitry Andric     return Error::success();
4850b57cec5SDimitry Andric 
4860b57cec5SDimitry Andric   // If CU DIE was just parsed, copy several attribute values from it.
4878bcb0991SDimitry Andric   if (HasCUDie)
4888bcb0991SDimitry Andric     return Error::success();
4898bcb0991SDimitry Andric 
4908bcb0991SDimitry Andric   DWARFDie UnitDie(this, &DieArray[0]);
491bdd1243dSDimitry Andric   if (std::optional<uint64_t> DWOId =
492bdd1243dSDimitry Andric           toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
4930b57cec5SDimitry Andric     Header.setDWOId(*DWOId);
4940b57cec5SDimitry Andric   if (!IsDWO) {
495bdd1243dSDimitry Andric     assert(AddrOffsetSectionBase == std::nullopt);
4960b57cec5SDimitry Andric     assert(RangeSectionBase == 0);
497480093f4SDimitry Andric     assert(LocSectionBase == 0);
498480093f4SDimitry Andric     AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));
4990b57cec5SDimitry Andric     if (!AddrOffsetSectionBase)
5000b57cec5SDimitry Andric       AddrOffsetSectionBase =
501480093f4SDimitry Andric           toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));
5020b57cec5SDimitry Andric     RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
503480093f4SDimitry Andric     LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);
5040b57cec5SDimitry Andric   }
5050b57cec5SDimitry Andric 
5060b57cec5SDimitry Andric   // In general, in DWARF v5 and beyond we derive the start of the unit's
5070b57cec5SDimitry Andric   // contribution to the string offsets table from the unit DIE's
5080b57cec5SDimitry Andric   // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
5090b57cec5SDimitry Andric   // attribute, so we assume that there is a contribution to the string
5100b57cec5SDimitry Andric   // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
5110b57cec5SDimitry Andric   // In both cases we need to determine the format of the contribution,
5120b57cec5SDimitry Andric   // which may differ from the unit's format.
5130b57cec5SDimitry Andric   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
514bdd1243dSDimitry Andric                         IsLittleEndian, 0);
5150b57cec5SDimitry Andric   if (IsDWO || getVersion() >= 5) {
5160b57cec5SDimitry Andric     auto StringOffsetOrError =
5170b57cec5SDimitry Andric         IsDWO ? determineStringOffsetsTableContributionDWO(DA)
5180b57cec5SDimitry Andric               : determineStringOffsetsTableContribution(DA);
5198bcb0991SDimitry Andric     if (!StringOffsetOrError)
5208bcb0991SDimitry Andric       return createStringError(errc::invalid_argument,
5218bcb0991SDimitry Andric                                "invalid reference to or invalid content in "
5228bcb0991SDimitry Andric                                ".debug_str_offsets[.dwo]: " +
5238bcb0991SDimitry Andric                                    toString(StringOffsetOrError.takeError()));
5248bcb0991SDimitry Andric 
5250b57cec5SDimitry Andric     StringOffsetsTableContribution = *StringOffsetOrError;
5260b57cec5SDimitry Andric   }
5270b57cec5SDimitry Andric 
5280b57cec5SDimitry Andric   // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
5290b57cec5SDimitry Andric   // describe address ranges.
5300b57cec5SDimitry Andric   if (getVersion() >= 5) {
5315ffd83dbSDimitry Andric     // In case of DWP, the base offset from the index has to be added.
5325ffd83dbSDimitry Andric     if (IsDWO) {
533e8d8bef9SDimitry Andric       uint64_t ContributionBaseOffset = 0;
5345ffd83dbSDimitry Andric       if (auto *IndexEntry = Header.getIndexEntry())
5355ffd83dbSDimitry Andric         if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))
536bdd1243dSDimitry Andric           ContributionBaseOffset = Contrib->getOffset();
5375ffd83dbSDimitry Andric       setRangesSection(
5385ffd83dbSDimitry Andric           &Context.getDWARFObj().getRnglistsDWOSection(),
5395ffd83dbSDimitry Andric           ContributionBaseOffset +
5405ffd83dbSDimitry Andric               DWARFListTableHeader::getHeaderSize(Header.getFormat()));
5415ffd83dbSDimitry Andric     } else
5420b57cec5SDimitry Andric       setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
543e8d8bef9SDimitry Andric                        toSectionOffset(UnitDie.find(DW_AT_rnglists_base),
544e8d8bef9SDimitry Andric                                        DWARFListTableHeader::getHeaderSize(
545e8d8bef9SDimitry Andric                                            Header.getFormat())));
5460b57cec5SDimitry Andric   }
547480093f4SDimitry Andric 
5485ffd83dbSDimitry Andric   if (IsDWO) {
549e8d8bef9SDimitry Andric     // If we are reading a package file, we need to adjust the location list
550e8d8bef9SDimitry Andric     // data based on the index entries.
551e8d8bef9SDimitry Andric     StringRef Data = Header.getVersion() >= 5
552e8d8bef9SDimitry Andric                          ? Context.getDWARFObj().getLoclistsDWOSection().Data
553e8d8bef9SDimitry Andric                          : Context.getDWARFObj().getLocDWOSection().Data;
5545ffd83dbSDimitry Andric     if (auto *IndexEntry = Header.getIndexEntry())
555e8d8bef9SDimitry Andric       if (const auto *C = IndexEntry->getContribution(
556e8d8bef9SDimitry Andric               Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
557bdd1243dSDimitry Andric         Data = Data.substr(C->getOffset(), C->getLength());
558e8d8bef9SDimitry Andric 
559bdd1243dSDimitry Andric     DWARFDataExtractor DWARFData(Data, IsLittleEndian, getAddressByteSize());
560e8d8bef9SDimitry Andric     LocTable =
561e8d8bef9SDimitry Andric         std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());
562e8d8bef9SDimitry Andric     LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());
563e8d8bef9SDimitry Andric   } else if (getVersion() >= 5) {
564e8d8bef9SDimitry Andric     LocTable = std::make_unique<DWARFDebugLoclists>(
565e8d8bef9SDimitry Andric         DWARFDataExtractor(Context.getDWARFObj(),
566e8d8bef9SDimitry Andric                            Context.getDWARFObj().getLoclistsSection(),
567bdd1243dSDimitry Andric                            IsLittleEndian, getAddressByteSize()),
568e8d8bef9SDimitry Andric         getVersion());
569e8d8bef9SDimitry Andric   } else {
570e8d8bef9SDimitry Andric     LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(
571e8d8bef9SDimitry Andric         Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),
572bdd1243dSDimitry Andric         IsLittleEndian, getAddressByteSize()));
5730b57cec5SDimitry Andric   }
5740b57cec5SDimitry Andric 
5750b57cec5SDimitry Andric   // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
5760b57cec5SDimitry Andric   // skeleton CU DIE, so that DWARF users not aware of it are not broken.
5778bcb0991SDimitry Andric   return Error::success();
5780b57cec5SDimitry Andric }
5790b57cec5SDimitry Andric 
parseDWO(StringRef DWOAlternativeLocation)580bdd1243dSDimitry Andric bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {
5810b57cec5SDimitry Andric   if (IsDWO)
5820b57cec5SDimitry Andric     return false;
583bdd1243dSDimitry Andric   if (DWO)
5840b57cec5SDimitry Andric     return false;
5850b57cec5SDimitry Andric   DWARFDie UnitDie = getUnitDIE();
5860b57cec5SDimitry Andric   if (!UnitDie)
5870b57cec5SDimitry Andric     return false;
588480093f4SDimitry Andric   auto DWOFileName = getVersion() >= 5
589480093f4SDimitry Andric                          ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
590480093f4SDimitry Andric                          : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
5910b57cec5SDimitry Andric   if (!DWOFileName)
5920b57cec5SDimitry Andric     return false;
5930b57cec5SDimitry Andric   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
5940b57cec5SDimitry Andric   SmallString<16> AbsolutePath;
5950b57cec5SDimitry Andric   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
5960b57cec5SDimitry Andric       *CompilationDir) {
5970b57cec5SDimitry Andric     sys::path::append(AbsolutePath, *CompilationDir);
5980b57cec5SDimitry Andric   }
5990b57cec5SDimitry Andric   sys::path::append(AbsolutePath, *DWOFileName);
6000b57cec5SDimitry Andric   auto DWOId = getDWOId();
6010b57cec5SDimitry Andric   if (!DWOId)
6020b57cec5SDimitry Andric     return false;
6030b57cec5SDimitry Andric   auto DWOContext = Context.getDWOContext(AbsolutePath);
604bdd1243dSDimitry Andric   if (!DWOContext) {
605bdd1243dSDimitry Andric     // Use the alternative location to get the DWARF context for the DWO object.
606bdd1243dSDimitry Andric     if (DWOAlternativeLocation.empty())
607bdd1243dSDimitry Andric       return false;
608bdd1243dSDimitry Andric     // If the alternative context does not correspond to the original DWO object
609bdd1243dSDimitry Andric     // (different hashes), the below 'getDWOCompileUnitForHash' call will catch
610bdd1243dSDimitry Andric     // the issue, with a returned null context.
611bdd1243dSDimitry Andric     DWOContext = Context.getDWOContext(DWOAlternativeLocation);
6120b57cec5SDimitry Andric     if (!DWOContext)
6130b57cec5SDimitry Andric       return false;
614bdd1243dSDimitry Andric   }
6150b57cec5SDimitry Andric 
6160b57cec5SDimitry Andric   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
6170b57cec5SDimitry Andric   if (!DWOCU)
6180b57cec5SDimitry Andric     return false;
6190b57cec5SDimitry Andric   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
620fe6060f1SDimitry Andric   DWO->setSkeletonUnit(this);
6210b57cec5SDimitry Andric   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
622480093f4SDimitry Andric   if (AddrOffsetSectionBase)
623480093f4SDimitry Andric     DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
624fe6060f1SDimitry Andric   if (getVersion() == 4) {
6250b57cec5SDimitry Andric     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
62681ad6265SDimitry Andric     DWO->setRangesSection(RangeSection, DWORangesBase.value_or(0));
6270b57cec5SDimitry Andric   }
6280b57cec5SDimitry Andric 
6290b57cec5SDimitry Andric   return true;
6300b57cec5SDimitry Andric }
6310b57cec5SDimitry Andric 
clearDIEs(bool KeepCUDie)6320b57cec5SDimitry Andric void DWARFUnit::clearDIEs(bool KeepCUDie) {
633349cc55cSDimitry Andric   // Do not use resize() + shrink_to_fit() to free memory occupied by dies.
634349cc55cSDimitry Andric   // shrink_to_fit() is a *non-binding* request to reduce capacity() to size().
635349cc55cSDimitry Andric   // It depends on the implementation whether the request is fulfilled.
636349cc55cSDimitry Andric   // Create a new vector with a small capacity and assign it to the DieArray to
637349cc55cSDimitry Andric   // have previous contents freed.
638349cc55cSDimitry Andric   DieArray = (KeepCUDie && !DieArray.empty())
639349cc55cSDimitry Andric                  ? std::vector<DWARFDebugInfoEntry>({DieArray[0]})
640349cc55cSDimitry Andric                  : std::vector<DWARFDebugInfoEntry>();
6410b57cec5SDimitry Andric }
6420b57cec5SDimitry Andric 
6430b57cec5SDimitry Andric Expected<DWARFAddressRangesVector>
findRnglistFromOffset(uint64_t Offset)6448bcb0991SDimitry Andric DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
6450b57cec5SDimitry Andric   if (getVersion() <= 4) {
6460b57cec5SDimitry Andric     DWARFDebugRangeList RangeList;
6470b57cec5SDimitry Andric     if (Error E = extractRangeList(Offset, RangeList))
6480b57cec5SDimitry Andric       return std::move(E);
6490b57cec5SDimitry Andric     return RangeList.getAbsoluteRanges(getBaseAddress());
6500b57cec5SDimitry Andric   }
6510b57cec5SDimitry Andric   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
652bdd1243dSDimitry Andric                                 IsLittleEndian, Header.getAddressByteSize());
653e8d8bef9SDimitry Andric   DWARFDebugRnglistTable RnglistTable;
654e8d8bef9SDimitry Andric   auto RangeListOrError = RnglistTable.findList(RangesData, Offset);
6550b57cec5SDimitry Andric   if (RangeListOrError)
6560b57cec5SDimitry Andric     return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
6570b57cec5SDimitry Andric   return RangeListOrError.takeError();
6580b57cec5SDimitry Andric }
6590b57cec5SDimitry Andric 
6600b57cec5SDimitry Andric Expected<DWARFAddressRangesVector>
findRnglistFromIndex(uint32_t Index)6610b57cec5SDimitry Andric DWARFUnit::findRnglistFromIndex(uint32_t Index) {
6620b57cec5SDimitry Andric   if (auto Offset = getRnglistOffset(Index))
663480093f4SDimitry Andric     return findRnglistFromOffset(*Offset);
6640b57cec5SDimitry Andric 
6650b57cec5SDimitry Andric   return createStringError(errc::invalid_argument,
666e8d8bef9SDimitry Andric                            "invalid range list table index %d (possibly "
667e8d8bef9SDimitry Andric                            "missing the entire range list table)",
668e8d8bef9SDimitry Andric                            Index);
6690b57cec5SDimitry Andric }
6700b57cec5SDimitry Andric 
collectAddressRanges()6710b57cec5SDimitry Andric Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
6720b57cec5SDimitry Andric   DWARFDie UnitDie = getUnitDIE();
6730b57cec5SDimitry Andric   if (!UnitDie)
6740b57cec5SDimitry Andric     return createStringError(errc::invalid_argument, "No unit DIE");
6750b57cec5SDimitry Andric 
6760b57cec5SDimitry Andric   // First, check if unit DIE describes address ranges for the whole unit.
6770b57cec5SDimitry Andric   auto CUDIERangesOrError = UnitDie.getAddressRanges();
6780b57cec5SDimitry Andric   if (!CUDIERangesOrError)
6790b57cec5SDimitry Andric     return createStringError(errc::invalid_argument,
6800b57cec5SDimitry Andric                              "decoding address ranges: %s",
6810b57cec5SDimitry Andric                              toString(CUDIERangesOrError.takeError()).c_str());
6820b57cec5SDimitry Andric   return *CUDIERangesOrError;
6830b57cec5SDimitry Andric }
6840b57cec5SDimitry Andric 
685480093f4SDimitry Andric Expected<DWARFLocationExpressionsVector>
findLoclistFromOffset(uint64_t Offset)686480093f4SDimitry Andric DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
687480093f4SDimitry Andric   DWARFLocationExpressionsVector Result;
688480093f4SDimitry Andric 
689480093f4SDimitry Andric   Error InterpretationError = Error::success();
690480093f4SDimitry Andric 
691480093f4SDimitry Andric   Error ParseError = getLocationTable().visitAbsoluteLocationList(
692480093f4SDimitry Andric       Offset, getBaseAddress(),
693480093f4SDimitry Andric       [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
694480093f4SDimitry Andric       [&](Expected<DWARFLocationExpression> L) {
695480093f4SDimitry Andric         if (L)
696480093f4SDimitry Andric           Result.push_back(std::move(*L));
697480093f4SDimitry Andric         else
698480093f4SDimitry Andric           InterpretationError =
699480093f4SDimitry Andric               joinErrors(L.takeError(), std::move(InterpretationError));
700480093f4SDimitry Andric         return !InterpretationError;
701480093f4SDimitry Andric       });
702480093f4SDimitry Andric 
703480093f4SDimitry Andric   if (ParseError || InterpretationError)
704480093f4SDimitry Andric     return joinErrors(std::move(ParseError), std::move(InterpretationError));
705480093f4SDimitry Andric 
706480093f4SDimitry Andric   return Result;
707480093f4SDimitry Andric }
708480093f4SDimitry Andric 
updateAddressDieMap(DWARFDie Die)7090b57cec5SDimitry Andric void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
7100b57cec5SDimitry Andric   if (Die.isSubroutineDIE()) {
7110b57cec5SDimitry Andric     auto DIERangesOrError = Die.getAddressRanges();
7120b57cec5SDimitry Andric     if (DIERangesOrError) {
7130b57cec5SDimitry Andric       for (const auto &R : DIERangesOrError.get()) {
7140b57cec5SDimitry Andric         // Ignore 0-sized ranges.
7150b57cec5SDimitry Andric         if (R.LowPC == R.HighPC)
7160b57cec5SDimitry Andric           continue;
7170b57cec5SDimitry Andric         auto B = AddrDieMap.upper_bound(R.LowPC);
7180b57cec5SDimitry Andric         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
7190b57cec5SDimitry Andric           // The range is a sub-range of existing ranges, we need to split the
7200b57cec5SDimitry Andric           // existing range.
7210b57cec5SDimitry Andric           if (R.HighPC < B->second.first)
7220b57cec5SDimitry Andric             AddrDieMap[R.HighPC] = B->second;
7230b57cec5SDimitry Andric           if (R.LowPC > B->first)
7240b57cec5SDimitry Andric             AddrDieMap[B->first].first = R.LowPC;
7250b57cec5SDimitry Andric         }
7260b57cec5SDimitry Andric         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
7270b57cec5SDimitry Andric       }
7280b57cec5SDimitry Andric     } else
7290b57cec5SDimitry Andric       llvm::consumeError(DIERangesOrError.takeError());
7300b57cec5SDimitry Andric   }
7310b57cec5SDimitry Andric   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
7320b57cec5SDimitry Andric   // simplify the logic to update AddrDieMap. The child's range will always
7330b57cec5SDimitry Andric   // be equal or smaller than the parent's range. With this assumption, when
7340b57cec5SDimitry Andric   // adding one range into the map, it will at most split a range into 3
7350b57cec5SDimitry Andric   // sub-ranges.
7360b57cec5SDimitry Andric   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
7370b57cec5SDimitry Andric     updateAddressDieMap(Child);
7380b57cec5SDimitry Andric }
7390b57cec5SDimitry Andric 
getSubroutineForAddress(uint64_t Address)7400b57cec5SDimitry Andric DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
7410b57cec5SDimitry Andric   extractDIEsIfNeeded(false);
7420b57cec5SDimitry Andric   if (AddrDieMap.empty())
7430b57cec5SDimitry Andric     updateAddressDieMap(getUnitDIE());
7440b57cec5SDimitry Andric   auto R = AddrDieMap.upper_bound(Address);
7450b57cec5SDimitry Andric   if (R == AddrDieMap.begin())
7460b57cec5SDimitry Andric     return DWARFDie();
7470b57cec5SDimitry Andric   // upper_bound's previous item contains Address.
7480b57cec5SDimitry Andric   --R;
7490b57cec5SDimitry Andric   if (Address >= R->second.first)
7500b57cec5SDimitry Andric     return DWARFDie();
7510b57cec5SDimitry Andric   return R->second.second;
7520b57cec5SDimitry Andric }
7530b57cec5SDimitry Andric 
updateVariableDieMap(DWARFDie Die)75481ad6265SDimitry Andric void DWARFUnit::updateVariableDieMap(DWARFDie Die) {
75581ad6265SDimitry Andric   for (DWARFDie Child : Die) {
75681ad6265SDimitry Andric     if (isType(Child.getTag()))
75781ad6265SDimitry Andric       continue;
75881ad6265SDimitry Andric     updateVariableDieMap(Child);
75981ad6265SDimitry Andric   }
76081ad6265SDimitry Andric 
76181ad6265SDimitry Andric   if (Die.getTag() != DW_TAG_variable)
76281ad6265SDimitry Andric     return;
76381ad6265SDimitry Andric 
76481ad6265SDimitry Andric   Expected<DWARFLocationExpressionsVector> Locations =
76581ad6265SDimitry Andric       Die.getLocations(DW_AT_location);
76681ad6265SDimitry Andric   if (!Locations) {
76781ad6265SDimitry Andric     // Missing DW_AT_location is fine here.
76881ad6265SDimitry Andric     consumeError(Locations.takeError());
76981ad6265SDimitry Andric     return;
77081ad6265SDimitry Andric   }
77181ad6265SDimitry Andric 
77281ad6265SDimitry Andric   uint64_t Address = UINT64_MAX;
77381ad6265SDimitry Andric 
77481ad6265SDimitry Andric   for (const DWARFLocationExpression &Location : *Locations) {
77581ad6265SDimitry Andric     uint8_t AddressSize = getAddressByteSize();
7765f757f3fSDimitry Andric     DataExtractor Data(Location.Expr, isLittleEndian(), AddressSize);
77781ad6265SDimitry Andric     DWARFExpression Expr(Data, AddressSize);
77881ad6265SDimitry Andric     auto It = Expr.begin();
77981ad6265SDimitry Andric     if (It == Expr.end())
78081ad6265SDimitry Andric       continue;
78181ad6265SDimitry Andric 
78281ad6265SDimitry Andric     // Match exactly the main sequence used to describe global variables:
78381ad6265SDimitry Andric     // `DW_OP_addr[x] [+ DW_OP_plus_uconst]`. Currently, this is the sequence
78481ad6265SDimitry Andric     // that LLVM produces for DILocalVariables and DIGlobalVariables. If, in
78581ad6265SDimitry Andric     // future, the DWARF producer (`DwarfCompileUnit::addLocationAttribute()` is
78681ad6265SDimitry Andric     // a good starting point) is extended to use further expressions, this code
78781ad6265SDimitry Andric     // needs to be updated.
78881ad6265SDimitry Andric     uint64_t LocationAddr;
78981ad6265SDimitry Andric     if (It->getCode() == dwarf::DW_OP_addr) {
79081ad6265SDimitry Andric       LocationAddr = It->getRawOperand(0);
79181ad6265SDimitry Andric     } else if (It->getCode() == dwarf::DW_OP_addrx) {
79281ad6265SDimitry Andric       uint64_t DebugAddrOffset = It->getRawOperand(0);
79381ad6265SDimitry Andric       if (auto Pointer = getAddrOffsetSectionItem(DebugAddrOffset)) {
79481ad6265SDimitry Andric         LocationAddr = Pointer->Address;
79581ad6265SDimitry Andric       }
79681ad6265SDimitry Andric     } else {
79781ad6265SDimitry Andric       continue;
79881ad6265SDimitry Andric     }
79981ad6265SDimitry Andric 
80081ad6265SDimitry Andric     // Read the optional 2nd operand, a DW_OP_plus_uconst.
80181ad6265SDimitry Andric     if (++It != Expr.end()) {
80281ad6265SDimitry Andric       if (It->getCode() != dwarf::DW_OP_plus_uconst)
80381ad6265SDimitry Andric         continue;
80481ad6265SDimitry Andric 
80581ad6265SDimitry Andric       LocationAddr += It->getRawOperand(0);
80681ad6265SDimitry Andric 
80781ad6265SDimitry Andric       // Probe for a 3rd operand, if it exists, bail.
80881ad6265SDimitry Andric       if (++It != Expr.end())
80981ad6265SDimitry Andric         continue;
81081ad6265SDimitry Andric     }
81181ad6265SDimitry Andric 
81281ad6265SDimitry Andric     Address = LocationAddr;
81381ad6265SDimitry Andric     break;
81481ad6265SDimitry Andric   }
81581ad6265SDimitry Andric 
81681ad6265SDimitry Andric   // Get the size of the global variable. If all else fails (i.e. the global has
81781ad6265SDimitry Andric   // no type), then we use a size of one to still allow symbolization of the
81881ad6265SDimitry Andric   // exact address.
81981ad6265SDimitry Andric   uint64_t GVSize = 1;
8205f757f3fSDimitry Andric   if (Die.getAttributeValueAsReferencedDie(DW_AT_type))
821bdd1243dSDimitry Andric     if (std::optional<uint64_t> Size = Die.getTypeSize(getAddressByteSize()))
82281ad6265SDimitry Andric       GVSize = *Size;
82381ad6265SDimitry Andric 
82481ad6265SDimitry Andric   if (Address != UINT64_MAX)
82581ad6265SDimitry Andric     VariableDieMap[Address] = {Address + GVSize, Die};
82681ad6265SDimitry Andric }
82781ad6265SDimitry Andric 
getVariableForAddress(uint64_t Address)82881ad6265SDimitry Andric DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {
82981ad6265SDimitry Andric   extractDIEsIfNeeded(false);
83081ad6265SDimitry Andric 
83181ad6265SDimitry Andric   auto RootDie = getUnitDIE();
83281ad6265SDimitry Andric 
83381ad6265SDimitry Andric   auto RootLookup = RootsParsedForVariables.insert(RootDie.getOffset());
83481ad6265SDimitry Andric   if (RootLookup.second)
83581ad6265SDimitry Andric     updateVariableDieMap(RootDie);
83681ad6265SDimitry Andric 
83781ad6265SDimitry Andric   auto R = VariableDieMap.upper_bound(Address);
83881ad6265SDimitry Andric   if (R == VariableDieMap.begin())
83981ad6265SDimitry Andric     return DWARFDie();
84081ad6265SDimitry Andric 
84181ad6265SDimitry Andric   // upper_bound's previous item contains Address.
84281ad6265SDimitry Andric   --R;
84381ad6265SDimitry Andric   if (Address >= R->second.first)
84481ad6265SDimitry Andric     return DWARFDie();
84581ad6265SDimitry Andric   return R->second.second;
84681ad6265SDimitry Andric }
84781ad6265SDimitry Andric 
8480b57cec5SDimitry Andric void
getInlinedChainForAddress(uint64_t Address,SmallVectorImpl<DWARFDie> & InlinedChain)8490b57cec5SDimitry Andric DWARFUnit::getInlinedChainForAddress(uint64_t Address,
8500b57cec5SDimitry Andric                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
8510b57cec5SDimitry Andric   assert(InlinedChain.empty());
8520b57cec5SDimitry Andric   // Try to look for subprogram DIEs in the DWO file.
8530b57cec5SDimitry Andric   parseDWO();
8540b57cec5SDimitry Andric   // First, find the subroutine that contains the given address (the leaf
8550b57cec5SDimitry Andric   // of inlined chain).
8560b57cec5SDimitry Andric   DWARFDie SubroutineDIE =
8570b57cec5SDimitry Andric       (DWO ? *DWO : *this).getSubroutineForAddress(Address);
8580b57cec5SDimitry Andric 
859fe6060f1SDimitry Andric   while (SubroutineDIE) {
860fe6060f1SDimitry Andric     if (SubroutineDIE.isSubprogramDIE()) {
861fe6060f1SDimitry Andric       InlinedChain.push_back(SubroutineDIE);
8620b57cec5SDimitry Andric       return;
863fe6060f1SDimitry Andric     }
8640b57cec5SDimitry Andric     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
8650b57cec5SDimitry Andric       InlinedChain.push_back(SubroutineDIE);
8660b57cec5SDimitry Andric     SubroutineDIE  = SubroutineDIE.getParent();
8670b57cec5SDimitry Andric   }
8680b57cec5SDimitry Andric }
8690b57cec5SDimitry Andric 
getDWARFUnitIndex(DWARFContext & Context,DWARFSectionKind Kind)8700b57cec5SDimitry Andric const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
8710b57cec5SDimitry Andric                                               DWARFSectionKind Kind) {
8720b57cec5SDimitry Andric   if (Kind == DW_SECT_INFO)
8730b57cec5SDimitry Andric     return Context.getCUIndex();
8745ffd83dbSDimitry Andric   assert(Kind == DW_SECT_EXT_TYPES);
8750b57cec5SDimitry Andric   return Context.getTUIndex();
8760b57cec5SDimitry Andric }
8770b57cec5SDimitry Andric 
getParent(const DWARFDebugInfoEntry * Die)8780b57cec5SDimitry Andric DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
879bdd1243dSDimitry Andric   if (const DWARFDebugInfoEntry *Entry = getParentEntry(Die))
880bdd1243dSDimitry Andric     return DWARFDie(this, Entry);
881349cc55cSDimitry Andric 
882bdd1243dSDimitry Andric   return DWARFDie();
8830b57cec5SDimitry Andric }
884349cc55cSDimitry Andric 
885bdd1243dSDimitry Andric const DWARFDebugInfoEntry *
getParentEntry(const DWARFDebugInfoEntry * Die) const886bdd1243dSDimitry Andric DWARFUnit::getParentEntry(const DWARFDebugInfoEntry *Die) const {
887bdd1243dSDimitry Andric   if (!Die)
888bdd1243dSDimitry Andric     return nullptr;
889bdd1243dSDimitry Andric   assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
890bdd1243dSDimitry Andric 
891bdd1243dSDimitry Andric   if (std::optional<uint32_t> ParentIdx = Die->getParentIdx()) {
892bdd1243dSDimitry Andric     assert(*ParentIdx < DieArray.size() &&
893bdd1243dSDimitry Andric            "ParentIdx is out of DieArray boundaries");
894bdd1243dSDimitry Andric     return getDebugInfoEntry(*ParentIdx);
895bdd1243dSDimitry Andric   }
896bdd1243dSDimitry Andric 
897bdd1243dSDimitry Andric   return nullptr;
8980b57cec5SDimitry Andric }
8990b57cec5SDimitry Andric 
getSibling(const DWARFDebugInfoEntry * Die)9000b57cec5SDimitry Andric DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
901bdd1243dSDimitry Andric   if (const DWARFDebugInfoEntry *Sibling = getSiblingEntry(Die))
902bdd1243dSDimitry Andric     return DWARFDie(this, Sibling);
9030b57cec5SDimitry Andric 
904bdd1243dSDimitry Andric   return DWARFDie();
9050b57cec5SDimitry Andric }
906349cc55cSDimitry Andric 
907bdd1243dSDimitry Andric const DWARFDebugInfoEntry *
getSiblingEntry(const DWARFDebugInfoEntry * Die) const908bdd1243dSDimitry Andric DWARFUnit::getSiblingEntry(const DWARFDebugInfoEntry *Die) const {
909bdd1243dSDimitry Andric   if (!Die)
910bdd1243dSDimitry Andric     return nullptr;
911bdd1243dSDimitry Andric   assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
912bdd1243dSDimitry Andric 
913bdd1243dSDimitry Andric   if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
914bdd1243dSDimitry Andric     assert(*SiblingIdx < DieArray.size() &&
915bdd1243dSDimitry Andric            "SiblingIdx is out of DieArray boundaries");
916bdd1243dSDimitry Andric     return &DieArray[*SiblingIdx];
917bdd1243dSDimitry Andric   }
918bdd1243dSDimitry Andric 
919bdd1243dSDimitry Andric   return nullptr;
9200b57cec5SDimitry Andric }
9210b57cec5SDimitry Andric 
getPreviousSibling(const DWARFDebugInfoEntry * Die)9220b57cec5SDimitry Andric DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
923bdd1243dSDimitry Andric   if (const DWARFDebugInfoEntry *Sibling = getPreviousSiblingEntry(Die))
924bdd1243dSDimitry Andric     return DWARFDie(this, Sibling);
925349cc55cSDimitry Andric 
926bdd1243dSDimitry Andric   return DWARFDie();
927bdd1243dSDimitry Andric }
928bdd1243dSDimitry Andric 
929bdd1243dSDimitry Andric const DWARFDebugInfoEntry *
getPreviousSiblingEntry(const DWARFDebugInfoEntry * Die) const930bdd1243dSDimitry Andric DWARFUnit::getPreviousSiblingEntry(const DWARFDebugInfoEntry *Die) const {
931bdd1243dSDimitry Andric   if (!Die)
932bdd1243dSDimitry Andric     return nullptr;
933bdd1243dSDimitry Andric   assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
934bdd1243dSDimitry Andric 
935bdd1243dSDimitry Andric   std::optional<uint32_t> ParentIdx = Die->getParentIdx();
936349cc55cSDimitry Andric   if (!ParentIdx)
937349cc55cSDimitry Andric     // Die is a root die, there is no previous sibling.
938bdd1243dSDimitry Andric     return nullptr;
9390b57cec5SDimitry Andric 
940349cc55cSDimitry Andric   assert(*ParentIdx < DieArray.size() &&
941349cc55cSDimitry Andric          "ParentIdx is out of DieArray boundaries");
942349cc55cSDimitry Andric   assert(getDIEIndex(Die) > 0 && "Die is a root die");
943349cc55cSDimitry Andric 
944349cc55cSDimitry Andric   uint32_t PrevDieIdx = getDIEIndex(Die) - 1;
945349cc55cSDimitry Andric   if (PrevDieIdx == *ParentIdx)
946349cc55cSDimitry Andric     // Immediately previous node is parent, there is no previous sibling.
947bdd1243dSDimitry Andric     return nullptr;
948349cc55cSDimitry Andric 
949349cc55cSDimitry Andric   while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {
950349cc55cSDimitry Andric     PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();
951349cc55cSDimitry Andric 
952349cc55cSDimitry Andric     assert(PrevDieIdx < DieArray.size() &&
953349cc55cSDimitry Andric            "PrevDieIdx is out of DieArray boundaries");
954349cc55cSDimitry Andric     assert(PrevDieIdx >= *ParentIdx &&
955349cc55cSDimitry Andric            "PrevDieIdx is not a child of parent of Die");
9560b57cec5SDimitry Andric   }
957349cc55cSDimitry Andric 
958bdd1243dSDimitry Andric   return &DieArray[PrevDieIdx];
9590b57cec5SDimitry Andric }
9600b57cec5SDimitry Andric 
getFirstChild(const DWARFDebugInfoEntry * Die)9610b57cec5SDimitry Andric DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
962bdd1243dSDimitry Andric   if (const DWARFDebugInfoEntry *Child = getFirstChildEntry(Die))
963bdd1243dSDimitry Andric     return DWARFDie(this, Child);
964bdd1243dSDimitry Andric 
9650b57cec5SDimitry Andric   return DWARFDie();
966bdd1243dSDimitry Andric }
967bdd1243dSDimitry Andric 
968bdd1243dSDimitry Andric const DWARFDebugInfoEntry *
getFirstChildEntry(const DWARFDebugInfoEntry * Die) const969bdd1243dSDimitry Andric DWARFUnit::getFirstChildEntry(const DWARFDebugInfoEntry *Die) const {
970bdd1243dSDimitry Andric   if (!Die)
971bdd1243dSDimitry Andric     return nullptr;
972bdd1243dSDimitry Andric   assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
973bdd1243dSDimitry Andric 
974bdd1243dSDimitry Andric   if (!Die->hasChildren())
975bdd1243dSDimitry Andric     return nullptr;
9760b57cec5SDimitry Andric 
977349cc55cSDimitry Andric   // TODO: Instead of checking here for invalid die we might reject
978349cc55cSDimitry Andric   // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
9790b57cec5SDimitry Andric   // We do not want access out of bounds when parsing corrupted debug data.
9800b57cec5SDimitry Andric   size_t I = getDIEIndex(Die) + 1;
9810b57cec5SDimitry Andric   if (I >= DieArray.size())
982bdd1243dSDimitry Andric     return nullptr;
983bdd1243dSDimitry Andric   return &DieArray[I];
9840b57cec5SDimitry Andric }
9850b57cec5SDimitry Andric 
getLastChild(const DWARFDebugInfoEntry * Die)9860b57cec5SDimitry Andric DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
987bdd1243dSDimitry Andric   if (const DWARFDebugInfoEntry *Child = getLastChildEntry(Die))
988bdd1243dSDimitry Andric     return DWARFDie(this, Child);
9890b57cec5SDimitry Andric 
990bdd1243dSDimitry Andric   return DWARFDie();
991bdd1243dSDimitry Andric }
992bdd1243dSDimitry Andric 
993bdd1243dSDimitry Andric const DWARFDebugInfoEntry *
getLastChildEntry(const DWARFDebugInfoEntry * Die) const994bdd1243dSDimitry Andric DWARFUnit::getLastChildEntry(const DWARFDebugInfoEntry *Die) const {
995bdd1243dSDimitry Andric   if (!Die)
996bdd1243dSDimitry Andric     return nullptr;
997bdd1243dSDimitry Andric   assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());
998bdd1243dSDimitry Andric 
999bdd1243dSDimitry Andric   if (!Die->hasChildren())
1000bdd1243dSDimitry Andric     return nullptr;
1001bdd1243dSDimitry Andric 
1002bdd1243dSDimitry Andric   if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
1003349cc55cSDimitry Andric     assert(*SiblingIdx < DieArray.size() &&
1004349cc55cSDimitry Andric            "SiblingIdx is out of DieArray boundaries");
1005349cc55cSDimitry Andric     assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&
1006349cc55cSDimitry Andric            "Bad end of children marker");
1007bdd1243dSDimitry Andric     return &DieArray[*SiblingIdx - 1];
10080b57cec5SDimitry Andric   }
1009349cc55cSDimitry Andric 
1010349cc55cSDimitry Andric   // If SiblingIdx is set for non-root dies we could be sure that DWARF is
1011349cc55cSDimitry Andric   // correct and "end of children marker" must be found. For root die we do not
1012349cc55cSDimitry Andric   // have such a guarantee(parsing root die might be stopped if "end of children
1013349cc55cSDimitry Andric   // marker" is missing, SiblingIdx is always zero for root die). That is why we
1014349cc55cSDimitry Andric   // do not use assertion for checking for "end of children marker" for root
1015349cc55cSDimitry Andric   // die.
1016349cc55cSDimitry Andric 
1017349cc55cSDimitry Andric   // TODO: Instead of checking here for invalid die we might reject
1018349cc55cSDimitry Andric   // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
1019349cc55cSDimitry Andric   if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&
1020349cc55cSDimitry Andric       DieArray.back().getTag() == dwarf::DW_TAG_null) {
1021349cc55cSDimitry Andric     // For the unit die we might take last item from DieArray.
1022bdd1243dSDimitry Andric     assert(getDIEIndex(Die) ==
1023bdd1243dSDimitry Andric                getDIEIndex(const_cast<DWARFUnit *>(this)->getUnitDIE()) &&
1024bdd1243dSDimitry Andric            "Bad unit die");
1025bdd1243dSDimitry Andric     return &DieArray.back();
1026349cc55cSDimitry Andric   }
1027349cc55cSDimitry Andric 
1028bdd1243dSDimitry Andric   return nullptr;
10290b57cec5SDimitry Andric }
10300b57cec5SDimitry Andric 
getAbbreviations() const10310b57cec5SDimitry Andric const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
103206c3fb27SDimitry Andric   if (!Abbrevs) {
103306c3fb27SDimitry Andric     Expected<const DWARFAbbreviationDeclarationSet *> AbbrevsOrError =
103406c3fb27SDimitry Andric         Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset());
103506c3fb27SDimitry Andric     if (!AbbrevsOrError) {
103606c3fb27SDimitry Andric       // FIXME: We should propagate this error upwards.
103706c3fb27SDimitry Andric       consumeError(AbbrevsOrError.takeError());
103806c3fb27SDimitry Andric       return nullptr;
103906c3fb27SDimitry Andric     }
104006c3fb27SDimitry Andric     Abbrevs = *AbbrevsOrError;
104106c3fb27SDimitry Andric   }
10420b57cec5SDimitry Andric   return Abbrevs;
10430b57cec5SDimitry Andric }
10440b57cec5SDimitry Andric 
getBaseAddress()1045bdd1243dSDimitry Andric std::optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
10460b57cec5SDimitry Andric   if (BaseAddr)
10470b57cec5SDimitry Andric     return BaseAddr;
10480b57cec5SDimitry Andric 
104906c3fb27SDimitry Andric   DWARFDie UnitDie = (SU ? SU : this)->getUnitDIE();
1050bdd1243dSDimitry Andric   std::optional<DWARFFormValue> PC =
1051bdd1243dSDimitry Andric       UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
10520b57cec5SDimitry Andric   BaseAddr = toSectionedAddress(PC);
10530b57cec5SDimitry Andric   return BaseAddr;
10540b57cec5SDimitry Andric }
10550b57cec5SDimitry Andric 
10560b57cec5SDimitry Andric Expected<StrOffsetsContributionDescriptor>
validateContributionSize(DWARFDataExtractor & DA)10570b57cec5SDimitry Andric StrOffsetsContributionDescriptor::validateContributionSize(
10580b57cec5SDimitry Andric     DWARFDataExtractor &DA) {
10590b57cec5SDimitry Andric   uint8_t EntrySize = getDwarfOffsetByteSize();
10600b57cec5SDimitry Andric   // In order to ensure that we don't read a partial record at the end of
10610b57cec5SDimitry Andric   // the section we validate for a multiple of the entry size.
10620b57cec5SDimitry Andric   uint64_t ValidationSize = alignTo(Size, EntrySize);
10630b57cec5SDimitry Andric   // Guard against overflow.
10640b57cec5SDimitry Andric   if (ValidationSize >= Size)
10650b57cec5SDimitry Andric     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
10660b57cec5SDimitry Andric       return *this;
10670b57cec5SDimitry Andric   return createStringError(errc::invalid_argument, "length exceeds section size");
10680b57cec5SDimitry Andric }
10690b57cec5SDimitry Andric 
10700b57cec5SDimitry Andric // Look for a DWARF64-formatted contribution to the string offsets table
10710b57cec5SDimitry Andric // starting at a given offset and record it in a descriptor.
10720b57cec5SDimitry Andric static Expected<StrOffsetsContributionDescriptor>
parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor & DA,uint64_t Offset)10738bcb0991SDimitry Andric parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
10740b57cec5SDimitry Andric   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
10750b57cec5SDimitry Andric     return createStringError(errc::invalid_argument, "section offset exceeds section size");
10760b57cec5SDimitry Andric 
10778bcb0991SDimitry Andric   if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
10780b57cec5SDimitry Andric     return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
10790b57cec5SDimitry Andric 
10800b57cec5SDimitry Andric   uint64_t Size = DA.getU64(&Offset);
10810b57cec5SDimitry Andric   uint8_t Version = DA.getU16(&Offset);
10820b57cec5SDimitry Andric   (void)DA.getU16(&Offset); // padding
10830b57cec5SDimitry Andric   // The encoded length includes the 2-byte version field and the 2-byte
10840b57cec5SDimitry Andric   // padding, so we need to subtract them out when we populate the descriptor.
10850b57cec5SDimitry Andric   return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
10860b57cec5SDimitry Andric }
10870b57cec5SDimitry Andric 
10880b57cec5SDimitry Andric // Look for a DWARF32-formatted contribution to the string offsets table
10890b57cec5SDimitry Andric // starting at a given offset and record it in a descriptor.
10900b57cec5SDimitry Andric static Expected<StrOffsetsContributionDescriptor>
parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor & DA,uint64_t Offset)10918bcb0991SDimitry Andric parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
10920b57cec5SDimitry Andric   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
10930b57cec5SDimitry Andric     return createStringError(errc::invalid_argument, "section offset exceeds section size");
10940b57cec5SDimitry Andric 
10950b57cec5SDimitry Andric   uint32_t ContributionSize = DA.getU32(&Offset);
10968bcb0991SDimitry Andric   if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
10970b57cec5SDimitry Andric     return createStringError(errc::invalid_argument, "invalid length");
10980b57cec5SDimitry Andric 
10990b57cec5SDimitry Andric   uint8_t Version = DA.getU16(&Offset);
11000b57cec5SDimitry Andric   (void)DA.getU16(&Offset); // padding
11010b57cec5SDimitry Andric   // The encoded length includes the 2-byte version field and the 2-byte
11020b57cec5SDimitry Andric   // padding, so we need to subtract them out when we populate the descriptor.
11030b57cec5SDimitry Andric   return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
11040b57cec5SDimitry Andric                                           DWARF32);
11050b57cec5SDimitry Andric }
11060b57cec5SDimitry Andric 
11070b57cec5SDimitry Andric static Expected<StrOffsetsContributionDescriptor>
parseDWARFStringOffsetsTableHeader(DWARFDataExtractor & DA,llvm::dwarf::DwarfFormat Format,uint64_t Offset)11080b57cec5SDimitry Andric parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
11090b57cec5SDimitry Andric                                    llvm::dwarf::DwarfFormat Format,
11100b57cec5SDimitry Andric                                    uint64_t Offset) {
11110b57cec5SDimitry Andric   StrOffsetsContributionDescriptor Desc;
11120b57cec5SDimitry Andric   switch (Format) {
11130b57cec5SDimitry Andric   case dwarf::DwarfFormat::DWARF64: {
11140b57cec5SDimitry Andric     if (Offset < 16)
11150b57cec5SDimitry Andric       return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
11168bcb0991SDimitry Andric     auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
11170b57cec5SDimitry Andric     if (!DescOrError)
11180b57cec5SDimitry Andric       return DescOrError.takeError();
11190b57cec5SDimitry Andric     Desc = *DescOrError;
11200b57cec5SDimitry Andric     break;
11210b57cec5SDimitry Andric   }
11220b57cec5SDimitry Andric   case dwarf::DwarfFormat::DWARF32: {
11230b57cec5SDimitry Andric     if (Offset < 8)
11240b57cec5SDimitry Andric       return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
11258bcb0991SDimitry Andric     auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
11260b57cec5SDimitry Andric     if (!DescOrError)
11270b57cec5SDimitry Andric       return DescOrError.takeError();
11280b57cec5SDimitry Andric     Desc = *DescOrError;
11290b57cec5SDimitry Andric     break;
11300b57cec5SDimitry Andric   }
11310b57cec5SDimitry Andric   }
11320b57cec5SDimitry Andric   return Desc.validateContributionSize(DA);
11330b57cec5SDimitry Andric }
11340b57cec5SDimitry Andric 
1135bdd1243dSDimitry Andric Expected<std::optional<StrOffsetsContributionDescriptor>>
determineStringOffsetsTableContribution(DWARFDataExtractor & DA)11360b57cec5SDimitry Andric DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
11375ffd83dbSDimitry Andric   assert(!IsDWO);
11380b57cec5SDimitry Andric   auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
11390b57cec5SDimitry Andric   if (!OptOffset)
1140bdd1243dSDimitry Andric     return std::nullopt;
11415ffd83dbSDimitry Andric   auto DescOrError =
11425ffd83dbSDimitry Andric       parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
11430b57cec5SDimitry Andric   if (!DescOrError)
11440b57cec5SDimitry Andric     return DescOrError.takeError();
11450b57cec5SDimitry Andric   return *DescOrError;
11460b57cec5SDimitry Andric }
11470b57cec5SDimitry Andric 
1148bdd1243dSDimitry Andric Expected<std::optional<StrOffsetsContributionDescriptor>>
determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA)11490b57cec5SDimitry Andric DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA) {
11505ffd83dbSDimitry Andric   assert(IsDWO);
11510b57cec5SDimitry Andric   uint64_t Offset = 0;
11520b57cec5SDimitry Andric   auto IndexEntry = Header.getIndexEntry();
11530b57cec5SDimitry Andric   const auto *C =
11545ffd83dbSDimitry Andric       IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
11550b57cec5SDimitry Andric   if (C)
1156bdd1243dSDimitry Andric     Offset = C->getOffset();
11570b57cec5SDimitry Andric   if (getVersion() >= 5) {
11580b57cec5SDimitry Andric     if (DA.getData().data() == nullptr)
1159bdd1243dSDimitry Andric       return std::nullopt;
11600b57cec5SDimitry Andric     Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
11610b57cec5SDimitry Andric     // Look for a valid contribution at the given offset.
11620b57cec5SDimitry Andric     auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
11630b57cec5SDimitry Andric     if (!DescOrError)
11640b57cec5SDimitry Andric       return DescOrError.takeError();
11650b57cec5SDimitry Andric     return *DescOrError;
11660b57cec5SDimitry Andric   }
11670b57cec5SDimitry Andric   // Prior to DWARF v5, we derive the contribution size from the
11680b57cec5SDimitry Andric   // index table (in a package file). In a .dwo file it is simply
11690b57cec5SDimitry Andric   // the length of the string offsets section.
1170e8d8bef9SDimitry Andric   StrOffsetsContributionDescriptor Desc;
11710b57cec5SDimitry Andric   if (C)
1172bdd1243dSDimitry Andric     Desc = StrOffsetsContributionDescriptor(C->getOffset(), C->getLength(), 4,
1173e8d8bef9SDimitry Andric                                             Header.getFormat());
1174e8d8bef9SDimitry Andric   else if (!IndexEntry && !StringOffsetSection.Data.empty())
1175e8d8bef9SDimitry Andric     Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
1176e8d8bef9SDimitry Andric                                             4, Header.getFormat());
1177e8d8bef9SDimitry Andric   else
1178bdd1243dSDimitry Andric     return std::nullopt;
1179e8d8bef9SDimitry Andric   auto DescOrError = Desc.validateContributionSize(DA);
1180e8d8bef9SDimitry Andric   if (!DescOrError)
1181e8d8bef9SDimitry Andric     return DescOrError.takeError();
1182e8d8bef9SDimitry Andric   return *DescOrError;
1183e8d8bef9SDimitry Andric }
1184e8d8bef9SDimitry Andric 
getRnglistOffset(uint32_t Index)1185bdd1243dSDimitry Andric std::optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
1186bdd1243dSDimitry Andric   DataExtractor RangesData(RangeSection->Data, IsLittleEndian,
1187e8d8bef9SDimitry Andric                            getAddressByteSize());
1188e8d8bef9SDimitry Andric   DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
1189bdd1243dSDimitry Andric                               IsLittleEndian, 0);
1190bdd1243dSDimitry Andric   if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1191e8d8bef9SDimitry Andric           RangesData, RangeSectionBase, getFormat(), Index))
1192e8d8bef9SDimitry Andric     return *Off + RangeSectionBase;
1193bdd1243dSDimitry Andric   return std::nullopt;
1194e8d8bef9SDimitry Andric }
1195e8d8bef9SDimitry Andric 
getLoclistOffset(uint32_t Index)1196bdd1243dSDimitry Andric std::optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {
1197bdd1243dSDimitry Andric   if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1198e8d8bef9SDimitry Andric           LocTable->getData(), LocSectionBase, getFormat(), Index))
1199e8d8bef9SDimitry Andric     return *Off + LocSectionBase;
1200bdd1243dSDimitry Andric   return std::nullopt;
12010b57cec5SDimitry Andric }
1202