Path: blob/main/contrib/llvm-project/llvm/lib/DebugInfo/DWARF/DWARFUnit.cpp
35269 views
//===- DWARFUnit.cpp ------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "llvm/DebugInfo/DWARF/DWARFUnit.h"9#include "llvm/ADT/SmallString.h"10#include "llvm/ADT/StringRef.h"11#include "llvm/BinaryFormat/Dwarf.h"12#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"13#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"14#include "llvm/DebugInfo/DWARF/DWARFContext.h"15#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"16#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"17#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"18#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"19#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"20#include "llvm/DebugInfo/DWARF/DWARFDie.h"21#include "llvm/DebugInfo/DWARF/DWARFExpression.h"22#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"23#include "llvm/DebugInfo/DWARF/DWARFListTable.h"24#include "llvm/DebugInfo/DWARF/DWARFObject.h"25#include "llvm/DebugInfo/DWARF/DWARFSection.h"26#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"27#include "llvm/Object/ObjectFile.h"28#include "llvm/Support/DataExtractor.h"29#include "llvm/Support/Errc.h"30#include "llvm/Support/Path.h"31#include <algorithm>32#include <cassert>33#include <cstddef>34#include <cstdint>35#include <utility>36#include <vector>3738using namespace llvm;39using namespace dwarf;4041void DWARFUnitVector::addUnitsForSection(DWARFContext &C,42const DWARFSection &Section,43DWARFSectionKind SectionKind) {44const DWARFObject &D = C.getDWARFObj();45addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),46&D.getLocSection(), D.getStrSection(),47D.getStrOffsetsSection(), &D.getAddrSection(),48D.getLineSection(), D.isLittleEndian(), false, false,49SectionKind);50}5152void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,53const DWARFSection &DWOSection,54DWARFSectionKind SectionKind,55bool Lazy) {56const DWARFObject &D = C.getDWARFObj();57addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),58&D.getLocDWOSection(), D.getStrDWOSection(),59D.getStrOffsetsDWOSection(), &D.getAddrSection(),60D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,61SectionKind);62}6364void DWARFUnitVector::addUnitsImpl(65DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,66const DWARFDebugAbbrev *DA, const DWARFSection *RS,67const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,68const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,69bool Lazy, DWARFSectionKind SectionKind) {70DWARFDataExtractor Data(Obj, Section, LE, 0);71// Lazy initialization of Parser, now that we have all section info.72if (!Parser) {73Parser = [=, &Context, &Obj, &Section, &SOS,74&LS](uint64_t Offset, DWARFSectionKind SectionKind,75const DWARFSection *CurSection,76const DWARFUnitIndex::Entry *IndexEntry)77-> std::unique_ptr<DWARFUnit> {78const DWARFSection &InfoSection = CurSection ? *CurSection : Section;79DWARFDataExtractor Data(Obj, InfoSection, LE, 0);80if (!Data.isValidOffset(Offset))81return nullptr;82DWARFUnitHeader Header;83if (Error ExtractErr =84Header.extract(Context, Data, &Offset, SectionKind)) {85Context.getWarningHandler()(std::move(ExtractErr));86return nullptr;87}88if (!IndexEntry && IsDWO) {89const DWARFUnitIndex &Index = getDWARFUnitIndex(90Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);91if (Index) {92if (Header.isTypeUnit())93IndexEntry = Index.getFromHash(Header.getTypeHash());94else if (auto DWOId = Header.getDWOId())95IndexEntry = Index.getFromHash(*DWOId);96}97if (!IndexEntry)98IndexEntry = Index.getFromOffset(Header.getOffset());99}100if (IndexEntry) {101if (Error ApplicationErr = Header.applyIndexEntry(IndexEntry)) {102Context.getWarningHandler()(std::move(ApplicationErr));103return nullptr;104}105}106std::unique_ptr<DWARFUnit> U;107if (Header.isTypeUnit())108U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,109RS, LocSection, SS, SOS, AOS, LS,110LE, IsDWO, *this);111else112U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,113DA, RS, LocSection, SS, SOS,114AOS, LS, LE, IsDWO, *this);115return U;116};117}118if (Lazy)119return;120// Find a reasonable insertion point within the vector. We skip over121// (a) units from a different section, (b) units from the same section122// but with lower offset-within-section. This keeps units in order123// within a section, although not necessarily within the object file,124// even if we do lazy parsing.125auto I = this->begin();126uint64_t Offset = 0;127while (Data.isValidOffset(Offset)) {128if (I != this->end() &&129(&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {130++I;131continue;132}133auto U = Parser(Offset, SectionKind, &Section, nullptr);134// If parsing failed, we're done with this section.135if (!U)136break;137Offset = U->getNextUnitOffset();138I = std::next(this->insert(I, std::move(U)));139}140}141142DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {143auto I = llvm::upper_bound(*this, Unit,144[](const std::unique_ptr<DWARFUnit> &LHS,145const std::unique_ptr<DWARFUnit> &RHS) {146return LHS->getOffset() < RHS->getOffset();147});148return this->insert(I, std::move(Unit))->get();149}150151DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {152auto end = begin() + getNumInfoUnits();153auto *CU =154std::upper_bound(begin(), end, Offset,155[](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {156return LHS < RHS->getNextUnitOffset();157});158if (CU != end && (*CU)->getOffset() <= Offset)159return CU->get();160return nullptr;161}162163DWARFUnit *164DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) {165const auto *CUOff = E.getContribution(DW_SECT_INFO);166if (!CUOff)167return nullptr;168169uint64_t Offset = CUOff->getOffset();170auto end = begin() + getNumInfoUnits();171172auto *CU =173std::upper_bound(begin(), end, CUOff->getOffset(),174[](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {175return LHS < RHS->getNextUnitOffset();176});177if (CU != end && (*CU)->getOffset() <= Offset)178return CU->get();179180if (!Parser)181return nullptr;182183auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E);184if (!U)185return nullptr;186187auto *NewCU = U.get();188this->insert(CU, std::move(U));189++NumInfoUnits;190return NewCU;191}192193DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,194const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,195const DWARFSection *RS, const DWARFSection *LocSection,196StringRef SS, const DWARFSection &SOS,197const DWARFSection *AOS, const DWARFSection &LS, bool LE,198bool IsDWO, const DWARFUnitVector &UnitVector)199: Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),200RangeSection(RS), LineSection(LS), StringSection(SS),201StringOffsetSection(SOS), AddrOffsetSection(AOS), IsLittleEndian(LE),202IsDWO(IsDWO), UnitVector(UnitVector) {203clear();204}205206DWARFUnit::~DWARFUnit() = default;207208DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {209return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, IsLittleEndian,210getAddressByteSize());211}212213std::optional<object::SectionedAddress>214DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {215if (!AddrOffsetSectionBase) {216auto R = Context.info_section_units();217// Surprising if a DWO file has more than one skeleton unit in it - this218// probably shouldn't be valid, but if a use case is found, here's where to219// support it (probably have to linearly search for the matching skeleton CU220// here)221if (IsDWO && hasSingleElement(R))222return (*R.begin())->getAddrOffsetSectionItem(Index);223224return std::nullopt;225}226227uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();228if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())229return std::nullopt;230DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,231IsLittleEndian, getAddressByteSize());232uint64_t Section;233uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);234return {{Address, Section}};235}236237Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {238if (!StringOffsetsTableContribution)239return make_error<StringError>(240"DW_FORM_strx used without a valid string offsets table",241inconvertibleErrorCode());242unsigned ItemSize = getDwarfStringOffsetsByteSize();243uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;244if (StringOffsetSection.Data.size() < Offset + ItemSize)245return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +246", which is too large",247inconvertibleErrorCode());248DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,249IsLittleEndian, 0);250return DA.getRelocatedValue(ItemSize, &Offset);251}252253Error DWARFUnitHeader::extract(DWARFContext &Context,254const DWARFDataExtractor &debug_info,255uint64_t *offset_ptr,256DWARFSectionKind SectionKind) {257Offset = *offset_ptr;258Error Err = Error::success();259IndexEntry = nullptr;260std::tie(Length, FormParams.Format) =261debug_info.getInitialLength(offset_ptr, &Err);262FormParams.Version = debug_info.getU16(offset_ptr, &Err);263if (FormParams.Version >= 5) {264UnitType = debug_info.getU8(offset_ptr, &Err);265FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);266AbbrOffset = debug_info.getRelocatedValue(267FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);268} else {269AbbrOffset = debug_info.getRelocatedValue(270FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);271FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);272// Fake a unit type based on the section type. This isn't perfect,273// but distinguishing compile and type units is generally enough.274if (SectionKind == DW_SECT_EXT_TYPES)275UnitType = DW_UT_type;276else277UnitType = DW_UT_compile;278}279if (isTypeUnit()) {280TypeHash = debug_info.getU64(offset_ptr, &Err);281TypeOffset = debug_info.getUnsigned(282offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);283} else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)284DWOId = debug_info.getU64(offset_ptr, &Err);285286if (Err)287return joinErrors(288createStringError(289errc::invalid_argument,290"DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Offset),291std::move(Err));292293// Header fields all parsed, capture the size of this unit header.294assert(*offset_ptr - Offset <= 255 && "unexpected header size");295Size = uint8_t(*offset_ptr - Offset);296uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();297298if (!debug_info.isValidOffset(getNextUnitOffset() - 1))299return createStringError(errc::invalid_argument,300"DWARF unit from offset 0x%8.8" PRIx64 " incl. "301"to offset 0x%8.8" PRIx64 " excl. "302"extends past section size 0x%8.8zx",303Offset, NextCUOffset, debug_info.size());304305if (!DWARFContext::isSupportedVersion(getVersion()))306return createStringError(307errc::invalid_argument,308"DWARF unit at offset 0x%8.8" PRIx64 " "309"has unsupported version %" PRIu16 ", supported are 2-%u",310Offset, getVersion(), DWARFContext::getMaxSupportedVersion());311312// Type offset is unit-relative; should be after the header and before313// the end of the current unit.314if (isTypeUnit() && TypeOffset < Size)315return createStringError(errc::invalid_argument,316"DWARF type unit at offset "317"0x%8.8" PRIx64 " "318"has its relocated type_offset 0x%8.8" PRIx64 " "319"pointing inside the header",320Offset, Offset + TypeOffset);321322if (isTypeUnit() && TypeOffset >= getUnitLengthFieldByteSize() + getLength())323return createStringError(324errc::invalid_argument,325"DWARF type unit from offset 0x%8.8" PRIx64 " incl. "326"to offset 0x%8.8" PRIx64 " excl. has its "327"relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",328Offset, NextCUOffset, Offset + TypeOffset);329330if (Error SizeErr = DWARFContext::checkAddressSizeSupported(331getAddressByteSize(), errc::invalid_argument,332"DWARF unit at offset 0x%8.8" PRIx64, Offset))333return SizeErr;334335// Keep track of the highest DWARF version we encounter across all units.336Context.setMaxVersionIfGreater(getVersion());337return Error::success();338}339340Error DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {341assert(Entry);342assert(!IndexEntry);343IndexEntry = Entry;344if (AbbrOffset)345return createStringError(errc::invalid_argument,346"DWARF package unit at offset 0x%8.8" PRIx64347" has a non-zero abbreviation offset",348Offset);349350auto *UnitContrib = IndexEntry->getContribution();351if (!UnitContrib)352return createStringError(errc::invalid_argument,353"DWARF package unit at offset 0x%8.8" PRIx64354" has no contribution index",355Offset);356357uint64_t IndexLength = getLength() + getUnitLengthFieldByteSize();358if (UnitContrib->getLength() != IndexLength)359return createStringError(errc::invalid_argument,360"DWARF package unit at offset 0x%8.8" PRIx64361" has an inconsistent index (expected: %" PRIu64362", actual: %" PRIu64 ")",363Offset, UnitContrib->getLength(), IndexLength);364365auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);366if (!AbbrEntry)367return createStringError(errc::invalid_argument,368"DWARF package unit at offset 0x%8.8" PRIx64369" missing abbreviation column",370Offset);371372AbbrOffset = AbbrEntry->getOffset();373return Error::success();374}375376Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,377DWARFDebugRangeList &RangeList) const {378// Require that compile unit is extracted.379assert(!DieArray.empty());380DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,381IsLittleEndian, getAddressByteSize());382uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;383return RangeList.extract(RangesData, &ActualRangeListOffset);384}385386void DWARFUnit::clear() {387Abbrevs = nullptr;388BaseAddr.reset();389RangeSectionBase = 0;390LocSectionBase = 0;391AddrOffsetSectionBase = std::nullopt;392SU = nullptr;393clearDIEs(false);394AddrDieMap.clear();395if (DWO)396DWO->clear();397DWO.reset();398}399400const char *DWARFUnit::getCompilationDir() {401return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);402}403404void DWARFUnit::extractDIEsToVector(405bool AppendCUDie, bool AppendNonCUDies,406std::vector<DWARFDebugInfoEntry> &Dies) const {407if (!AppendCUDie && !AppendNonCUDies)408return;409410// Set the offset to that of the first DIE and calculate the start of the411// next compilation unit header.412uint64_t DIEOffset = getOffset() + getHeaderSize();413uint64_t NextCUOffset = getNextUnitOffset();414DWARFDebugInfoEntry DIE;415DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();416// The end offset has been already checked by DWARFUnitHeader::extract.417assert(DebugInfoData.isValidOffset(NextCUOffset - 1));418std::vector<uint32_t> Parents;419std::vector<uint32_t> PrevSiblings;420bool IsCUDie = true;421422assert(423((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&424"Dies array is not empty");425426// Fill Parents and Siblings stacks with initial value.427Parents.push_back(UINT32_MAX);428if (!AppendCUDie)429Parents.push_back(0);430PrevSiblings.push_back(0);431432// Start to extract dies.433do {434assert(Parents.size() > 0 && "Empty parents stack");435assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&436"Wrong parent index");437438// Extract die. Stop if any error occurred.439if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,440Parents.back()))441break;442443// If previous sibling is remembered then update it`s SiblingIdx field.444if (PrevSiblings.back() > 0) {445assert(PrevSiblings.back() < Dies.size() &&446"Previous sibling index is out of Dies boundaries");447Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());448}449450// Store die into the Dies vector.451if (IsCUDie) {452if (AppendCUDie)453Dies.push_back(DIE);454if (!AppendNonCUDies)455break;456// The average bytes per DIE entry has been seen to be457// around 14-20 so let's pre-reserve the needed memory for458// our DIE entries accordingly.459Dies.reserve(Dies.size() + getDebugInfoSize() / 14);460} else {461// Remember last previous sibling.462PrevSiblings.back() = Dies.size();463464Dies.push_back(DIE);465}466467// Check for new children scope.468if (const DWARFAbbreviationDeclaration *AbbrDecl =469DIE.getAbbreviationDeclarationPtr()) {470if (AbbrDecl->hasChildren()) {471if (AppendCUDie || !IsCUDie) {472assert(Dies.size() > 0 && "Dies does not contain any die");473Parents.push_back(Dies.size() - 1);474PrevSiblings.push_back(0);475}476} else if (IsCUDie)477// Stop if we have single compile unit die w/o children.478break;479} else {480// NULL DIE: finishes current children scope.481Parents.pop_back();482PrevSiblings.pop_back();483}484485if (IsCUDie)486IsCUDie = false;487488// Stop when compile unit die is removed from the parents stack.489} while (Parents.size() > 1);490}491492void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {493if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))494Context.getRecoverableErrorHandler()(std::move(e));495}496497Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {498if ((CUDieOnly && !DieArray.empty()) ||499DieArray.size() > 1)500return Error::success(); // Already parsed.501502bool HasCUDie = !DieArray.empty();503extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);504505if (DieArray.empty())506return Error::success();507508// If CU DIE was just parsed, copy several attribute values from it.509if (HasCUDie)510return Error::success();511512DWARFDie UnitDie(this, &DieArray[0]);513if (std::optional<uint64_t> DWOId =514toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))515Header.setDWOId(*DWOId);516if (!IsDWO) {517assert(AddrOffsetSectionBase == std::nullopt);518assert(RangeSectionBase == 0);519assert(LocSectionBase == 0);520AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));521if (!AddrOffsetSectionBase)522AddrOffsetSectionBase =523toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));524RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);525LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);526}527528// In general, in DWARF v5 and beyond we derive the start of the unit's529// contribution to the string offsets table from the unit DIE's530// DW_AT_str_offsets_base attribute. Split DWARF units do not use this531// attribute, so we assume that there is a contribution to the string532// offsets table starting at offset 0 of the debug_str_offsets.dwo section.533// In both cases we need to determine the format of the contribution,534// which may differ from the unit's format.535DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,536IsLittleEndian, 0);537if (IsDWO || getVersion() >= 5) {538auto StringOffsetOrError =539IsDWO ? determineStringOffsetsTableContributionDWO(DA)540: determineStringOffsetsTableContribution(DA);541if (!StringOffsetOrError)542return createStringError(errc::invalid_argument,543"invalid reference to or invalid content in "544".debug_str_offsets[.dwo]: " +545toString(StringOffsetOrError.takeError()));546547StringOffsetsTableContribution = *StringOffsetOrError;548}549550// DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to551// describe address ranges.552if (getVersion() >= 5) {553// In case of DWP, the base offset from the index has to be added.554if (IsDWO) {555uint64_t ContributionBaseOffset = 0;556if (auto *IndexEntry = Header.getIndexEntry())557if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))558ContributionBaseOffset = Contrib->getOffset();559setRangesSection(560&Context.getDWARFObj().getRnglistsDWOSection(),561ContributionBaseOffset +562DWARFListTableHeader::getHeaderSize(Header.getFormat()));563} else564setRangesSection(&Context.getDWARFObj().getRnglistsSection(),565toSectionOffset(UnitDie.find(DW_AT_rnglists_base),566DWARFListTableHeader::getHeaderSize(567Header.getFormat())));568}569570if (IsDWO) {571// If we are reading a package file, we need to adjust the location list572// data based on the index entries.573StringRef Data = Header.getVersion() >= 5574? Context.getDWARFObj().getLoclistsDWOSection().Data575: Context.getDWARFObj().getLocDWOSection().Data;576if (auto *IndexEntry = Header.getIndexEntry())577if (const auto *C = IndexEntry->getContribution(578Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))579Data = Data.substr(C->getOffset(), C->getLength());580581DWARFDataExtractor DWARFData(Data, IsLittleEndian, getAddressByteSize());582LocTable =583std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());584LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());585} else if (getVersion() >= 5) {586LocTable = std::make_unique<DWARFDebugLoclists>(587DWARFDataExtractor(Context.getDWARFObj(),588Context.getDWARFObj().getLoclistsSection(),589IsLittleEndian, getAddressByteSize()),590getVersion());591} else {592LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(593Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),594IsLittleEndian, getAddressByteSize()));595}596597// Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for598// skeleton CU DIE, so that DWARF users not aware of it are not broken.599return Error::success();600}601602bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {603if (IsDWO)604return false;605if (DWO)606return false;607DWARFDie UnitDie = getUnitDIE();608if (!UnitDie)609return false;610auto DWOFileName = getVersion() >= 5611? dwarf::toString(UnitDie.find(DW_AT_dwo_name))612: dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));613if (!DWOFileName)614return false;615auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));616SmallString<16> AbsolutePath;617if (sys::path::is_relative(*DWOFileName) && CompilationDir &&618*CompilationDir) {619sys::path::append(AbsolutePath, *CompilationDir);620}621sys::path::append(AbsolutePath, *DWOFileName);622auto DWOId = getDWOId();623if (!DWOId)624return false;625auto DWOContext = Context.getDWOContext(AbsolutePath);626if (!DWOContext) {627// Use the alternative location to get the DWARF context for the DWO object.628if (DWOAlternativeLocation.empty())629return false;630// If the alternative context does not correspond to the original DWO object631// (different hashes), the below 'getDWOCompileUnitForHash' call will catch632// the issue, with a returned null context.633DWOContext = Context.getDWOContext(DWOAlternativeLocation);634if (!DWOContext)635return false;636}637638DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);639if (!DWOCU)640return false;641DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);642DWO->setSkeletonUnit(this);643// Share .debug_addr and .debug_ranges section with compile unit in .dwo644if (AddrOffsetSectionBase)645DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);646if (getVersion() == 4) {647auto DWORangesBase = UnitDie.getRangesBaseAttribute();648DWO->setRangesSection(RangeSection, DWORangesBase.value_or(0));649}650651return true;652}653654void DWARFUnit::clearDIEs(bool KeepCUDie) {655// Do not use resize() + shrink_to_fit() to free memory occupied by dies.656// shrink_to_fit() is a *non-binding* request to reduce capacity() to size().657// It depends on the implementation whether the request is fulfilled.658// Create a new vector with a small capacity and assign it to the DieArray to659// have previous contents freed.660DieArray = (KeepCUDie && !DieArray.empty())661? std::vector<DWARFDebugInfoEntry>({DieArray[0]})662: std::vector<DWARFDebugInfoEntry>();663}664665Expected<DWARFAddressRangesVector>666DWARFUnit::findRnglistFromOffset(uint64_t Offset) {667if (getVersion() <= 4) {668DWARFDebugRangeList RangeList;669if (Error E = extractRangeList(Offset, RangeList))670return std::move(E);671return RangeList.getAbsoluteRanges(getBaseAddress());672}673DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,674IsLittleEndian, Header.getAddressByteSize());675DWARFDebugRnglistTable RnglistTable;676auto RangeListOrError = RnglistTable.findList(RangesData, Offset);677if (RangeListOrError)678return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);679return RangeListOrError.takeError();680}681682Expected<DWARFAddressRangesVector>683DWARFUnit::findRnglistFromIndex(uint32_t Index) {684if (auto Offset = getRnglistOffset(Index))685return findRnglistFromOffset(*Offset);686687return createStringError(errc::invalid_argument,688"invalid range list table index %d (possibly "689"missing the entire range list table)",690Index);691}692693Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {694DWARFDie UnitDie = getUnitDIE();695if (!UnitDie)696return createStringError(errc::invalid_argument, "No unit DIE");697698// First, check if unit DIE describes address ranges for the whole unit.699auto CUDIERangesOrError = UnitDie.getAddressRanges();700if (!CUDIERangesOrError)701return createStringError(errc::invalid_argument,702"decoding address ranges: %s",703toString(CUDIERangesOrError.takeError()).c_str());704return *CUDIERangesOrError;705}706707Expected<DWARFLocationExpressionsVector>708DWARFUnit::findLoclistFromOffset(uint64_t Offset) {709DWARFLocationExpressionsVector Result;710711Error InterpretationError = Error::success();712713Error ParseError = getLocationTable().visitAbsoluteLocationList(714Offset, getBaseAddress(),715[this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },716[&](Expected<DWARFLocationExpression> L) {717if (L)718Result.push_back(std::move(*L));719else720InterpretationError =721joinErrors(L.takeError(), std::move(InterpretationError));722return !InterpretationError;723});724725if (ParseError || InterpretationError)726return joinErrors(std::move(ParseError), std::move(InterpretationError));727728return Result;729}730731void DWARFUnit::updateAddressDieMap(DWARFDie Die) {732if (Die.isSubroutineDIE()) {733auto DIERangesOrError = Die.getAddressRanges();734if (DIERangesOrError) {735for (const auto &R : DIERangesOrError.get()) {736// Ignore 0-sized ranges.737if (R.LowPC == R.HighPC)738continue;739auto B = AddrDieMap.upper_bound(R.LowPC);740if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {741// The range is a sub-range of existing ranges, we need to split the742// existing range.743if (R.HighPC < B->second.first)744AddrDieMap[R.HighPC] = B->second;745if (R.LowPC > B->first)746AddrDieMap[B->first].first = R.LowPC;747}748AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);749}750} else751llvm::consumeError(DIERangesOrError.takeError());752}753// Parent DIEs are added to the AddrDieMap prior to the Children DIEs to754// simplify the logic to update AddrDieMap. The child's range will always755// be equal or smaller than the parent's range. With this assumption, when756// adding one range into the map, it will at most split a range into 3757// sub-ranges.758for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())759updateAddressDieMap(Child);760}761762DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {763extractDIEsIfNeeded(false);764if (AddrDieMap.empty())765updateAddressDieMap(getUnitDIE());766auto R = AddrDieMap.upper_bound(Address);767if (R == AddrDieMap.begin())768return DWARFDie();769// upper_bound's previous item contains Address.770--R;771if (Address >= R->second.first)772return DWARFDie();773return R->second.second;774}775776void DWARFUnit::updateVariableDieMap(DWARFDie Die) {777for (DWARFDie Child : Die) {778if (isType(Child.getTag()))779continue;780updateVariableDieMap(Child);781}782783if (Die.getTag() != DW_TAG_variable)784return;785786Expected<DWARFLocationExpressionsVector> Locations =787Die.getLocations(DW_AT_location);788if (!Locations) {789// Missing DW_AT_location is fine here.790consumeError(Locations.takeError());791return;792}793794uint64_t Address = UINT64_MAX;795796for (const DWARFLocationExpression &Location : *Locations) {797uint8_t AddressSize = getAddressByteSize();798DataExtractor Data(Location.Expr, isLittleEndian(), AddressSize);799DWARFExpression Expr(Data, AddressSize);800auto It = Expr.begin();801if (It == Expr.end())802continue;803804// Match exactly the main sequence used to describe global variables:805// `DW_OP_addr[x] [+ DW_OP_plus_uconst]`. Currently, this is the sequence806// that LLVM produces for DILocalVariables and DIGlobalVariables. If, in807// future, the DWARF producer (`DwarfCompileUnit::addLocationAttribute()` is808// a good starting point) is extended to use further expressions, this code809// needs to be updated.810uint64_t LocationAddr;811if (It->getCode() == dwarf::DW_OP_addr) {812LocationAddr = It->getRawOperand(0);813} else if (It->getCode() == dwarf::DW_OP_addrx) {814uint64_t DebugAddrOffset = It->getRawOperand(0);815if (auto Pointer = getAddrOffsetSectionItem(DebugAddrOffset)) {816LocationAddr = Pointer->Address;817}818} else {819continue;820}821822// Read the optional 2nd operand, a DW_OP_plus_uconst.823if (++It != Expr.end()) {824if (It->getCode() != dwarf::DW_OP_plus_uconst)825continue;826827LocationAddr += It->getRawOperand(0);828829// Probe for a 3rd operand, if it exists, bail.830if (++It != Expr.end())831continue;832}833834Address = LocationAddr;835break;836}837838// Get the size of the global variable. If all else fails (i.e. the global has839// no type), then we use a size of one to still allow symbolization of the840// exact address.841uint64_t GVSize = 1;842if (Die.getAttributeValueAsReferencedDie(DW_AT_type))843if (std::optional<uint64_t> Size = Die.getTypeSize(getAddressByteSize()))844GVSize = *Size;845846if (Address != UINT64_MAX)847VariableDieMap[Address] = {Address + GVSize, Die};848}849850DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {851extractDIEsIfNeeded(false);852853auto RootDie = getUnitDIE();854855auto RootLookup = RootsParsedForVariables.insert(RootDie.getOffset());856if (RootLookup.second)857updateVariableDieMap(RootDie);858859auto R = VariableDieMap.upper_bound(Address);860if (R == VariableDieMap.begin())861return DWARFDie();862863// upper_bound's previous item contains Address.864--R;865if (Address >= R->second.first)866return DWARFDie();867return R->second.second;868}869870void871DWARFUnit::getInlinedChainForAddress(uint64_t Address,872SmallVectorImpl<DWARFDie> &InlinedChain) {873assert(InlinedChain.empty());874// Try to look for subprogram DIEs in the DWO file.875parseDWO();876// First, find the subroutine that contains the given address (the leaf877// of inlined chain).878DWARFDie SubroutineDIE =879(DWO ? *DWO : *this).getSubroutineForAddress(Address);880881while (SubroutineDIE) {882if (SubroutineDIE.isSubprogramDIE()) {883InlinedChain.push_back(SubroutineDIE);884return;885}886if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)887InlinedChain.push_back(SubroutineDIE);888SubroutineDIE = SubroutineDIE.getParent();889}890}891892const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,893DWARFSectionKind Kind) {894if (Kind == DW_SECT_INFO)895return Context.getCUIndex();896assert(Kind == DW_SECT_EXT_TYPES);897return Context.getTUIndex();898}899900DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {901if (const DWARFDebugInfoEntry *Entry = getParentEntry(Die))902return DWARFDie(this, Entry);903904return DWARFDie();905}906907const DWARFDebugInfoEntry *908DWARFUnit::getParentEntry(const DWARFDebugInfoEntry *Die) const {909if (!Die)910return nullptr;911assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());912913if (std::optional<uint32_t> ParentIdx = Die->getParentIdx()) {914assert(*ParentIdx < DieArray.size() &&915"ParentIdx is out of DieArray boundaries");916return getDebugInfoEntry(*ParentIdx);917}918919return nullptr;920}921922DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {923if (const DWARFDebugInfoEntry *Sibling = getSiblingEntry(Die))924return DWARFDie(this, Sibling);925926return DWARFDie();927}928929const DWARFDebugInfoEntry *930DWARFUnit::getSiblingEntry(const DWARFDebugInfoEntry *Die) const {931if (!Die)932return nullptr;933assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());934935if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {936assert(*SiblingIdx < DieArray.size() &&937"SiblingIdx is out of DieArray boundaries");938return &DieArray[*SiblingIdx];939}940941return nullptr;942}943944DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {945if (const DWARFDebugInfoEntry *Sibling = getPreviousSiblingEntry(Die))946return DWARFDie(this, Sibling);947948return DWARFDie();949}950951const DWARFDebugInfoEntry *952DWARFUnit::getPreviousSiblingEntry(const DWARFDebugInfoEntry *Die) const {953if (!Die)954return nullptr;955assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());956957std::optional<uint32_t> ParentIdx = Die->getParentIdx();958if (!ParentIdx)959// Die is a root die, there is no previous sibling.960return nullptr;961962assert(*ParentIdx < DieArray.size() &&963"ParentIdx is out of DieArray boundaries");964assert(getDIEIndex(Die) > 0 && "Die is a root die");965966uint32_t PrevDieIdx = getDIEIndex(Die) - 1;967if (PrevDieIdx == *ParentIdx)968// Immediately previous node is parent, there is no previous sibling.969return nullptr;970971while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {972PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();973974assert(PrevDieIdx < DieArray.size() &&975"PrevDieIdx is out of DieArray boundaries");976assert(PrevDieIdx >= *ParentIdx &&977"PrevDieIdx is not a child of parent of Die");978}979980return &DieArray[PrevDieIdx];981}982983DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {984if (const DWARFDebugInfoEntry *Child = getFirstChildEntry(Die))985return DWARFDie(this, Child);986987return DWARFDie();988}989990const DWARFDebugInfoEntry *991DWARFUnit::getFirstChildEntry(const DWARFDebugInfoEntry *Die) const {992if (!Die)993return nullptr;994assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());995996if (!Die->hasChildren())997return nullptr;998999// TODO: Instead of checking here for invalid die we might reject1000// invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).1001// We do not want access out of bounds when parsing corrupted debug data.1002size_t I = getDIEIndex(Die) + 1;1003if (I >= DieArray.size())1004return nullptr;1005return &DieArray[I];1006}10071008DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {1009if (const DWARFDebugInfoEntry *Child = getLastChildEntry(Die))1010return DWARFDie(this, Child);10111012return DWARFDie();1013}10141015const DWARFDebugInfoEntry *1016DWARFUnit::getLastChildEntry(const DWARFDebugInfoEntry *Die) const {1017if (!Die)1018return nullptr;1019assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());10201021if (!Die->hasChildren())1022return nullptr;10231024if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {1025assert(*SiblingIdx < DieArray.size() &&1026"SiblingIdx is out of DieArray boundaries");1027assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&1028"Bad end of children marker");1029return &DieArray[*SiblingIdx - 1];1030}10311032// If SiblingIdx is set for non-root dies we could be sure that DWARF is1033// correct and "end of children marker" must be found. For root die we do not1034// have such a guarantee(parsing root die might be stopped if "end of children1035// marker" is missing, SiblingIdx is always zero for root die). That is why we1036// do not use assertion for checking for "end of children marker" for root1037// die.10381039// TODO: Instead of checking here for invalid die we might reject1040// invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).1041if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&1042DieArray.back().getTag() == dwarf::DW_TAG_null) {1043// For the unit die we might take last item from DieArray.1044assert(getDIEIndex(Die) ==1045getDIEIndex(const_cast<DWARFUnit *>(this)->getUnitDIE()) &&1046"Bad unit die");1047return &DieArray.back();1048}10491050return nullptr;1051}10521053const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {1054if (!Abbrevs) {1055Expected<const DWARFAbbreviationDeclarationSet *> AbbrevsOrError =1056Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset());1057if (!AbbrevsOrError) {1058// FIXME: We should propagate this error upwards.1059consumeError(AbbrevsOrError.takeError());1060return nullptr;1061}1062Abbrevs = *AbbrevsOrError;1063}1064return Abbrevs;1065}10661067std::optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {1068if (BaseAddr)1069return BaseAddr;10701071DWARFDie UnitDie = (SU ? SU : this)->getUnitDIE();1072std::optional<DWARFFormValue> PC =1073UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});1074BaseAddr = toSectionedAddress(PC);1075return BaseAddr;1076}10771078Expected<StrOffsetsContributionDescriptor>1079StrOffsetsContributionDescriptor::validateContributionSize(1080DWARFDataExtractor &DA) {1081uint8_t EntrySize = getDwarfOffsetByteSize();1082// In order to ensure that we don't read a partial record at the end of1083// the section we validate for a multiple of the entry size.1084uint64_t ValidationSize = alignTo(Size, EntrySize);1085// Guard against overflow.1086if (ValidationSize >= Size)1087if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))1088return *this;1089return createStringError(errc::invalid_argument, "length exceeds section size");1090}10911092// Look for a DWARF64-formatted contribution to the string offsets table1093// starting at a given offset and record it in a descriptor.1094static Expected<StrOffsetsContributionDescriptor>1095parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {1096if (!DA.isValidOffsetForDataOfSize(Offset, 16))1097return createStringError(errc::invalid_argument, "section offset exceeds section size");10981099if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)1100return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");11011102uint64_t Size = DA.getU64(&Offset);1103uint8_t Version = DA.getU16(&Offset);1104(void)DA.getU16(&Offset); // padding1105// The encoded length includes the 2-byte version field and the 2-byte1106// padding, so we need to subtract them out when we populate the descriptor.1107return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);1108}11091110// Look for a DWARF32-formatted contribution to the string offsets table1111// starting at a given offset and record it in a descriptor.1112static Expected<StrOffsetsContributionDescriptor>1113parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {1114if (!DA.isValidOffsetForDataOfSize(Offset, 8))1115return createStringError(errc::invalid_argument, "section offset exceeds section size");11161117uint32_t ContributionSize = DA.getU32(&Offset);1118if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)1119return createStringError(errc::invalid_argument, "invalid length");11201121uint8_t Version = DA.getU16(&Offset);1122(void)DA.getU16(&Offset); // padding1123// The encoded length includes the 2-byte version field and the 2-byte1124// padding, so we need to subtract them out when we populate the descriptor.1125return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,1126DWARF32);1127}11281129static Expected<StrOffsetsContributionDescriptor>1130parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,1131llvm::dwarf::DwarfFormat Format,1132uint64_t Offset) {1133StrOffsetsContributionDescriptor Desc;1134switch (Format) {1135case dwarf::DwarfFormat::DWARF64: {1136if (Offset < 16)1137return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");1138auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);1139if (!DescOrError)1140return DescOrError.takeError();1141Desc = *DescOrError;1142break;1143}1144case dwarf::DwarfFormat::DWARF32: {1145if (Offset < 8)1146return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");1147auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);1148if (!DescOrError)1149return DescOrError.takeError();1150Desc = *DescOrError;1151break;1152}1153}1154return Desc.validateContributionSize(DA);1155}11561157Expected<std::optional<StrOffsetsContributionDescriptor>>1158DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {1159assert(!IsDWO);1160auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));1161if (!OptOffset)1162return std::nullopt;1163auto DescOrError =1164parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);1165if (!DescOrError)1166return DescOrError.takeError();1167return *DescOrError;1168}11691170Expected<std::optional<StrOffsetsContributionDescriptor>>1171DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA) {1172assert(IsDWO);1173uint64_t Offset = 0;1174auto IndexEntry = Header.getIndexEntry();1175const auto *C =1176IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;1177if (C)1178Offset = C->getOffset();1179if (getVersion() >= 5) {1180if (DA.getData().data() == nullptr)1181return std::nullopt;1182Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;1183// Look for a valid contribution at the given offset.1184auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);1185if (!DescOrError)1186return DescOrError.takeError();1187return *DescOrError;1188}1189// Prior to DWARF v5, we derive the contribution size from the1190// index table (in a package file). In a .dwo file it is simply1191// the length of the string offsets section.1192StrOffsetsContributionDescriptor Desc;1193if (C)1194Desc = StrOffsetsContributionDescriptor(C->getOffset(), C->getLength(), 4,1195Header.getFormat());1196else if (!IndexEntry && !StringOffsetSection.Data.empty())1197Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),11984, Header.getFormat());1199else1200return std::nullopt;1201auto DescOrError = Desc.validateContributionSize(DA);1202if (!DescOrError)1203return DescOrError.takeError();1204return *DescOrError;1205}12061207std::optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {1208DataExtractor RangesData(RangeSection->Data, IsLittleEndian,1209getAddressByteSize());1210DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,1211IsLittleEndian, 0);1212if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(1213RangesData, RangeSectionBase, getFormat(), Index))1214return *Off + RangeSectionBase;1215return std::nullopt;1216}12171218std::optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {1219if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(1220LocTable->getData(), LocSectionBase, getFormat(), Index))1221return *Off + LocSectionBase;1222return std::nullopt;1223}122412251226