brintos

brintos / llvm-project-archived public Read only

0
0
Text · 46.3 KiB · b8fbdfc Raw
1238 lines · cpp
1//===- DWARFUnit.cpp ------------------------------------------------------===//2//3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.4// See https://llvm.org/LICENSE.txt for license information.5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception6//7//===----------------------------------------------------------------------===//8 9#include "llvm/DebugInfo/DWARF/DWARFUnit.h"10#include "llvm/ADT/SmallString.h"11#include "llvm/ADT/StringRef.h"12#include "llvm/BinaryFormat/Dwarf.h"13#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"14#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"15#include "llvm/DebugInfo/DWARF/DWARFContext.h"16#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"17#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"18#include "llvm/DebugInfo/DWARF/DWARFDebugLoc.h"19#include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"20#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"21#include "llvm/DebugInfo/DWARF/DWARFDie.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/DebugInfo/DWARF/LowLevel/DWARFExpression.h"28#include "llvm/Object/ObjectFile.h"29#include "llvm/Support/DataExtractor.h"30#include "llvm/Support/Errc.h"31#include "llvm/Support/Path.h"32#include <algorithm>33#include <cassert>34#include <cstddef>35#include <cstdint>36#include <utility>37#include <vector>38 39using namespace llvm;40using namespace dwarf;41 42void DWARFUnitVector::addUnitsForSection(DWARFContext &C,43                                         const DWARFSection &Section,44                                         DWARFSectionKind SectionKind) {45  const DWARFObject &D = C.getDWARFObj();46  addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),47               &D.getLocSection(), D.getStrSection(),48               D.getStrOffsetsSection(), &D.getAddrSection(),49               D.getLineSection(), D.isLittleEndian(), false, false,50               SectionKind);51}52 53void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,54                                            const DWARFSection &DWOSection,55                                            DWARFSectionKind SectionKind,56                                            bool Lazy) {57  const DWARFObject &D = C.getDWARFObj();58  addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),59               &D.getLocDWOSection(), D.getStrDWOSection(),60               D.getStrOffsetsDWOSection(), &D.getAddrSection(),61               D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,62               SectionKind);63}64 65void DWARFUnitVector::addUnitsImpl(66    DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,67    const DWARFDebugAbbrev *DA, const DWARFSection *RS,68    const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,69    const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,70    bool Lazy, DWARFSectionKind SectionKind) {71  DWARFDataExtractor Data(Obj, Section, LE, 0);72  // Lazy initialization of Parser, now that we have all section info.73  if (!Parser) {74    Parser = [=, &Context, &Obj, &Section, &SOS,75              &LS](uint64_t Offset, DWARFSectionKind SectionKind,76                   const DWARFSection *CurSection,77                   const DWARFUnitIndex::Entry *IndexEntry)78        -> std::unique_ptr<DWARFUnit> {79      const DWARFSection &InfoSection = CurSection ? *CurSection : Section;80      DWARFDataExtractor Data(Obj, InfoSection, LE, 0);81      if (!Data.isValidOffset(Offset))82        return nullptr;83      DWARFUnitHeader Header;84      if (Error ExtractErr =85              Header.extract(Context, Data, &Offset, SectionKind)) {86        Context.getWarningHandler()(std::move(ExtractErr));87        return nullptr;88      }89      if (!IndexEntry && IsDWO) {90        const DWARFUnitIndex &Index = getDWARFUnitIndex(91            Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);92        if (Index) {93          if (Header.isTypeUnit())94            IndexEntry = Index.getFromHash(Header.getTypeHash());95          else if (auto DWOId = Header.getDWOId())96            IndexEntry = Index.getFromHash(*DWOId);97        }98        if (!IndexEntry)99          IndexEntry = Index.getFromOffset(Header.getOffset());100      }101      if (IndexEntry) {102        if (Error ApplicationErr = Header.applyIndexEntry(IndexEntry)) {103          Context.getWarningHandler()(std::move(ApplicationErr));104          return nullptr;105        }106      }107      std::unique_ptr<DWARFUnit> U;108      if (Header.isTypeUnit())109        U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,110                                             RS, LocSection, SS, SOS, AOS, LS,111                                             LE, IsDWO, *this);112      else113        U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,114                                                DA, RS, LocSection, SS, SOS,115                                                AOS, LS, LE, IsDWO, *this);116      return U;117    };118  }119  if (Lazy)120    return;121  // Find a reasonable insertion point within the vector.  We skip over122  // (a) units from a different section, (b) units from the same section123  // but with lower offset-within-section.  This keeps units in order124  // within a section, although not necessarily within the object file,125  // even if we do lazy parsing.126  auto I = this->begin();127  uint64_t Offset = 0;128  while (Data.isValidOffset(Offset)) {129    if (I != this->end() &&130        (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {131      ++I;132      continue;133    }134    auto U = Parser(Offset, SectionKind, &Section, nullptr);135    // If parsing failed, we're done with this section.136    if (!U)137      break;138    Offset = U->getNextUnitOffset();139    I = std::next(this->insert(I, std::move(U)));140  }141}142 143DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {144  auto I = llvm::upper_bound(*this, Unit,145                             [](const std::unique_ptr<DWARFUnit> &LHS,146                                const std::unique_ptr<DWARFUnit> &RHS) {147                               return LHS->getOffset() < RHS->getOffset();148                             });149  return this->insert(I, std::move(Unit))->get();150}151 152DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {153  auto end = begin() + getNumInfoUnits();154  auto *CU =155      std::upper_bound(begin(), end, Offset,156                       [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {157                         return LHS < RHS->getNextUnitOffset();158                       });159  if (CU != end && (*CU)->getOffset() <= Offset)160    return CU->get();161  return nullptr;162}163 164DWARFUnit *DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E,165                                                 DWARFSectionKind Sec,166                                                 const DWARFSection *Section) {167  const auto *CUOff = E.getContribution(Sec);168  if (!CUOff)169    return nullptr;170 171  uint64_t Offset = CUOff->getOffset();172  auto begin = this->begin();173  auto end = begin + getNumInfoUnits();174 175  if (Sec == DW_SECT_EXT_TYPES) {176    begin = end;177    end = this->end();178  }179 180  auto *CU =181      std::upper_bound(begin, end, CUOff->getOffset(),182                       [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {183                         return LHS < RHS->getNextUnitOffset();184                       });185  if (CU != end && (*CU)->getOffset() <= Offset)186    return CU->get();187 188  if (!Parser)189    return nullptr;190 191  auto U = Parser(Offset, Sec, Section, &E);192  if (!U)193    return nullptr;194 195  auto *NewCU = U.get();196  this->insert(CU, std::move(U));197  if (Sec == DW_SECT_INFO)198    ++NumInfoUnits;199  return NewCU;200}201 202DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,203                     const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,204                     const DWARFSection *RS, const DWARFSection *LocSection,205                     StringRef SS, const DWARFSection &SOS,206                     const DWARFSection *AOS, const DWARFSection &LS, bool LE,207                     bool IsDWO, const DWARFUnitVector &UnitVector)208    : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),209      RangeSection(RS), LineSection(LS), StringSection(SS),210      StringOffsetSection(SOS), AddrOffsetSection(AOS), IsLittleEndian(LE),211      IsDWO(IsDWO), UnitVector(UnitVector) {212  clear();213}214 215DWARFUnit::~DWARFUnit() = default;216 217DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {218  return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, IsLittleEndian,219                            getAddressByteSize());220}221 222std::optional<object::SectionedAddress>223DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {224  if (!AddrOffsetSectionBase) {225    auto R = Context.info_section_units();226    // Surprising if a DWO file has more than one skeleton unit in it - this227    // probably shouldn't be valid, but if a use case is found, here's where to228    // support it (probably have to linearly search for the matching skeleton CU229    // here)230    if (IsDWO && hasSingleElement(R))231      return (*R.begin())->getAddrOffsetSectionItem(Index);232 233    return std::nullopt;234  }235 236  uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();237  if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())238    return std::nullopt;239  DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,240                        IsLittleEndian, getAddressByteSize());241  uint64_t Section;242  uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);243  return {{Address, Section}};244}245 246Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {247  if (!StringOffsetsTableContribution)248    return make_error<StringError>(249        "DW_FORM_strx used without a valid string offsets table",250        inconvertibleErrorCode());251  unsigned ItemSize = getDwarfStringOffsetsByteSize();252  uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;253  if (StringOffsetSection.Data.size() < Offset + ItemSize)254    return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +255                                       ", which is too large",256                                   inconvertibleErrorCode());257  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,258                        IsLittleEndian, 0);259  return DA.getRelocatedValue(ItemSize, &Offset);260}261 262Error DWARFUnitHeader::extract(DWARFContext &Context,263                               const DWARFDataExtractor &debug_info,264                               uint64_t *offset_ptr,265                               DWARFSectionKind SectionKind) {266  Offset = *offset_ptr;267  Error Err = Error::success();268  IndexEntry = nullptr;269  std::tie(Length, FormParams.Format) =270      debug_info.getInitialLength(offset_ptr, &Err);271  FormParams.Version = debug_info.getU16(offset_ptr, &Err);272  if (FormParams.Version >= 5) {273    UnitType = debug_info.getU8(offset_ptr, &Err);274    FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);275    AbbrOffset = debug_info.getRelocatedValue(276        FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);277  } else {278    AbbrOffset = debug_info.getRelocatedValue(279        FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);280    FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);281    // Fake a unit type based on the section type.  This isn't perfect,282    // but distinguishing compile and type units is generally enough.283    if (SectionKind == DW_SECT_EXT_TYPES)284      UnitType = DW_UT_type;285    else286      UnitType = DW_UT_compile;287  }288  if (isTypeUnit()) {289    TypeHash = debug_info.getU64(offset_ptr, &Err);290    TypeOffset = debug_info.getUnsigned(291        offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);292  } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)293    DWOId = debug_info.getU64(offset_ptr, &Err);294 295  if (Err)296    return joinErrors(297        createStringError(298            errc::invalid_argument,299            "DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Offset),300        std::move(Err));301 302  // Header fields all parsed, capture the size of this unit header.303  assert(*offset_ptr - Offset <= 255 && "unexpected header size");304  Size = uint8_t(*offset_ptr - Offset);305  uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();306 307  if (!debug_info.isValidOffset(getNextUnitOffset() - 1))308    return createStringError(errc::invalid_argument,309                             "DWARF unit from offset 0x%8.8" PRIx64 " incl. "310                             "to offset  0x%8.8" PRIx64 " excl. "311                             "extends past section size 0x%8.8zx",312                             Offset, NextCUOffset, debug_info.size());313 314  if (!DWARFContext::isSupportedVersion(getVersion()))315    return createStringError(316        errc::invalid_argument,317        "DWARF unit at offset 0x%8.8" PRIx64 " "318        "has unsupported version %" PRIu16 ", supported are 2-%u",319        Offset, getVersion(), DWARFContext::getMaxSupportedVersion());320 321  // Type offset is unit-relative; should be after the header and before322  // the end of the current unit.323  if (isTypeUnit() && TypeOffset < Size)324    return createStringError(errc::invalid_argument,325                             "DWARF type unit at offset "326                             "0x%8.8" PRIx64 " "327                             "has its relocated type_offset 0x%8.8" PRIx64 " "328                             "pointing inside the header",329                             Offset, Offset + TypeOffset);330 331  if (isTypeUnit() && TypeOffset >= getUnitLengthFieldByteSize() + getLength())332    return createStringError(333        errc::invalid_argument,334        "DWARF type unit from offset 0x%8.8" PRIx64 " incl. "335        "to offset 0x%8.8" PRIx64 " excl. has its "336        "relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",337        Offset, NextCUOffset, Offset + TypeOffset);338 339  if (Error SizeErr = DWARFContext::checkAddressSizeSupported(340          getAddressByteSize(), errc::invalid_argument,341          "DWARF unit at offset 0x%8.8" PRIx64, Offset))342    return SizeErr;343 344  // Keep track of the highest DWARF version we encounter across all units.345  Context.setMaxVersionIfGreater(getVersion());346  return Error::success();347}348 349Error DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {350  assert(Entry);351  assert(!IndexEntry);352  IndexEntry = Entry;353  if (AbbrOffset)354    return createStringError(errc::invalid_argument,355                             "DWARF package unit at offset 0x%8.8" PRIx64356                             " has a non-zero abbreviation offset",357                             Offset);358 359  auto *UnitContrib = IndexEntry->getContribution();360  if (!UnitContrib)361    return createStringError(errc::invalid_argument,362                             "DWARF package unit at offset 0x%8.8" PRIx64363                             " has no contribution index",364                             Offset);365 366  uint64_t IndexLength = getLength() + getUnitLengthFieldByteSize();367  if (UnitContrib->getLength() != IndexLength)368    return createStringError(errc::invalid_argument,369                             "DWARF package unit at offset 0x%8.8" PRIx64370                             " has an inconsistent index (expected: %" PRIu64371                             ", actual: %" PRIu64 ")",372                             Offset, UnitContrib->getLength(), IndexLength);373 374  auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);375  if (!AbbrEntry)376    return createStringError(errc::invalid_argument,377                             "DWARF package unit at offset 0x%8.8" PRIx64378                             " missing abbreviation column",379                             Offset);380 381  AbbrOffset = AbbrEntry->getOffset();382  return Error::success();383}384 385Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,386                                  DWARFDebugRangeList &RangeList) const {387  // Require that compile unit is extracted.388  assert(!DieArray.empty());389  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,390                                IsLittleEndian, getAddressByteSize());391  uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;392  return RangeList.extract(RangesData, &ActualRangeListOffset);393}394 395void DWARFUnit::clear() {396  Abbrevs = nullptr;397  BaseAddr.reset();398  RangeSectionBase = 0;399  LocSectionBase = 0;400  AddrOffsetSectionBase = std::nullopt;401  SU = nullptr;402  clearDIEs(false);403  AddrDieMap.clear();404  if (DWO)405    DWO->clear();406  DWO.reset();407}408 409const char *DWARFUnit::getCompilationDir() {410  return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);411}412 413void DWARFUnit::extractDIEsToVector(414    bool AppendCUDie, bool AppendNonCUDies,415    std::vector<DWARFDebugInfoEntry> &Dies) const {416  if (!AppendCUDie && !AppendNonCUDies)417    return;418 419  // Set the offset to that of the first DIE and calculate the start of the420  // next compilation unit header.421  uint64_t DIEOffset = getOffset() + getHeaderSize();422  uint64_t NextCUOffset = getNextUnitOffset();423  DWARFDebugInfoEntry DIE;424  DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();425  // The end offset has been already checked by DWARFUnitHeader::extract.426  assert(DebugInfoData.isValidOffset(NextCUOffset - 1));427  std::vector<uint32_t> Parents;428  std::vector<uint32_t> PrevSiblings;429  bool IsCUDie = true;430 431  assert(432      ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&433      "Dies array is not empty");434 435  // Fill Parents and Siblings stacks with initial value.436  Parents.push_back(UINT32_MAX);437  if (!AppendCUDie)438    Parents.push_back(0);439  PrevSiblings.push_back(0);440 441  // Start to extract dies.442  do {443    assert(Parents.size() > 0 && "Empty parents stack");444    assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&445           "Wrong parent index");446 447    // Extract die. Stop if any error occurred.448    if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,449                         Parents.back()))450      break;451 452    // If previous sibling is remembered then update it`s SiblingIdx field.453    if (PrevSiblings.back() > 0) {454      assert(PrevSiblings.back() < Dies.size() &&455             "Previous sibling index is out of Dies boundaries");456      Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());457    }458 459    // Store die into the Dies vector.460    if (IsCUDie) {461      if (AppendCUDie)462        Dies.push_back(DIE);463      if (!AppendNonCUDies)464        break;465      // The average bytes per DIE entry has been seen to be466      // around 14-20 so let's pre-reserve the needed memory for467      // our DIE entries accordingly.468      Dies.reserve(Dies.size() + getDebugInfoSize() / 14);469    } else {470      // Remember last previous sibling.471      PrevSiblings.back() = Dies.size();472 473      Dies.push_back(DIE);474    }475 476    // Check for new children scope.477    if (const DWARFAbbreviationDeclaration *AbbrDecl =478            DIE.getAbbreviationDeclarationPtr()) {479      if (AbbrDecl->hasChildren()) {480        if (AppendCUDie || !IsCUDie) {481          assert(Dies.size() > 0 && "Dies does not contain any die");482          Parents.push_back(Dies.size() - 1);483          PrevSiblings.push_back(0);484        }485      } else if (IsCUDie)486        // Stop if we have single compile unit die w/o children.487        break;488    } else {489      // NULL DIE: finishes current children scope.490      Parents.pop_back();491      PrevSiblings.pop_back();492    }493 494    if (IsCUDie)495      IsCUDie = false;496 497    // Stop when compile unit die is removed from the parents stack.498  } while (Parents.size() > 1);499}500 501void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {502  if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))503    Context.getRecoverableErrorHandler()(std::move(e));504}505 506Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {507  if ((CUDieOnly && !DieArray.empty()) || DieArray.size() > 1)508    return Error::success(); // Already parsed.509 510  bool HasCUDie = !DieArray.empty();511  extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);512 513  if (DieArray.empty())514    return Error::success();515 516  // If CU DIE was just parsed, copy several attribute values from it.517  if (HasCUDie)518    return Error::success();519 520  DWARFDie UnitDie(this, &DieArray[0]);521  if (std::optional<uint64_t> DWOId =522          toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))523    Header.setDWOId(*DWOId);524  if (!IsDWO) {525    assert(AddrOffsetSectionBase == std::nullopt);526    assert(RangeSectionBase == 0);527    assert(LocSectionBase == 0);528    AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));529    if (!AddrOffsetSectionBase)530      AddrOffsetSectionBase =531          toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));532    RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);533    LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);534  }535 536  // In general, in DWARF v5 and beyond we derive the start of the unit's537  // contribution to the string offsets table from the unit DIE's538  // DW_AT_str_offsets_base attribute. Split DWARF units do not use this539  // attribute, so we assume that there is a contribution to the string540  // offsets table starting at offset 0 of the debug_str_offsets.dwo section.541  // In both cases we need to determine the format of the contribution,542  // which may differ from the unit's format.543  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,544                        IsLittleEndian, 0);545  if (IsDWO || getVersion() >= 5) {546    auto StringOffsetOrError =547        IsDWO ? determineStringOffsetsTableContributionDWO(DA)548              : determineStringOffsetsTableContribution(DA);549    if (!StringOffsetOrError)550      return createStringError(errc::invalid_argument,551                               "invalid reference to or invalid content in "552                               ".debug_str_offsets[.dwo]: " +553                                   toString(StringOffsetOrError.takeError()));554 555    StringOffsetsTableContribution = *StringOffsetOrError;556  }557 558  // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to559  // describe address ranges.560  if (getVersion() >= 5) {561    // In case of DWP, the base offset from the index has to be added.562    if (IsDWO) {563      uint64_t ContributionBaseOffset = 0;564      if (auto *IndexEntry = Header.getIndexEntry())565        if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))566          ContributionBaseOffset = Contrib->getOffset();567      setRangesSection(568          &Context.getDWARFObj().getRnglistsDWOSection(),569          ContributionBaseOffset +570              DWARFListTableHeader::getHeaderSize(Header.getFormat()));571    } else572      setRangesSection(&Context.getDWARFObj().getRnglistsSection(),573                       toSectionOffset(UnitDie.find(DW_AT_rnglists_base),574                                       DWARFListTableHeader::getHeaderSize(575                                           Header.getFormat())));576  }577 578  if (IsDWO) {579    // If we are reading a package file, we need to adjust the location list580    // data based on the index entries.581    StringRef Data = Header.getVersion() >= 5582                         ? Context.getDWARFObj().getLoclistsDWOSection().Data583                         : Context.getDWARFObj().getLocDWOSection().Data;584    if (auto *IndexEntry = Header.getIndexEntry())585      if (const auto *C = IndexEntry->getContribution(586              Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))587        Data = Data.substr(C->getOffset(), C->getLength());588 589    DWARFDataExtractor DWARFData(Data, IsLittleEndian, getAddressByteSize());590    LocTable =591        std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());592    LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());593  } else if (getVersion() >= 5) {594    LocTable = std::make_unique<DWARFDebugLoclists>(595        DWARFDataExtractor(Context.getDWARFObj(),596                           Context.getDWARFObj().getLoclistsSection(),597                           IsLittleEndian, getAddressByteSize()),598        getVersion());599  } else {600    LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(601        Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),602        IsLittleEndian, getAddressByteSize()));603  }604 605  // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for606  // skeleton CU DIE, so that DWARF users not aware of it are not broken.607  return Error::success();608}609 610bool DWARFUnit::parseDWO(StringRef DWOAlternativeLocation) {611  if (IsDWO)612    return false;613  if (DWO)614    return false;615  DWARFDie UnitDie = getUnitDIE();616  if (!UnitDie)617    return false;618  auto DWOFileName = getVersion() >= 5619                         ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))620                         : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));621  if (!DWOFileName)622    return false;623  auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));624  SmallString<16> AbsolutePath;625  if (sys::path::is_relative(*DWOFileName) && CompilationDir &&626      *CompilationDir) {627    sys::path::append(AbsolutePath, *CompilationDir);628  }629  sys::path::append(AbsolutePath, *DWOFileName);630  auto DWOId = getDWOId();631  if (!DWOId)632    return false;633  auto DWOContext = Context.getDWOContext(AbsolutePath);634  if (!DWOContext) {635    // Use the alternative location to get the DWARF context for the DWO object.636    if (DWOAlternativeLocation.empty())637      return false;638    // If the alternative context does not correspond to the original DWO object639    // (different hashes), the below 'getDWOCompileUnitForHash' call will catch640    // the issue, with a returned null context.641    DWOContext = Context.getDWOContext(DWOAlternativeLocation);642    if (!DWOContext)643      return false;644  }645 646  DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);647  if (!DWOCU)648    return false;649  DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);650  DWO->setSkeletonUnit(this);651  // Share .debug_addr and .debug_ranges section with compile unit in .dwo652  if (AddrOffsetSectionBase)653    DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);654  if (getVersion() == 4) {655    auto DWORangesBase = UnitDie.getRangesBaseAttribute();656    DWO->setRangesSection(RangeSection, DWORangesBase.value_or(0));657  }658 659  return true;660}661 662void DWARFUnit::clearDIEs(bool KeepCUDie) {663  // Do not use resize() + shrink_to_fit() to free memory occupied by dies.664  // shrink_to_fit() is a *non-binding* request to reduce capacity() to size().665  // It depends on the implementation whether the request is fulfilled.666  // Create a new vector with a small capacity and assign it to the DieArray to667  // have previous contents freed.668  DieArray = (KeepCUDie && !DieArray.empty())669                 ? std::vector<DWARFDebugInfoEntry>({DieArray[0]})670                 : std::vector<DWARFDebugInfoEntry>();671}672 673Expected<DWARFAddressRangesVector>674DWARFUnit::findRnglistFromOffset(uint64_t Offset) {675  if (getVersion() <= 4) {676    DWARFDebugRangeList RangeList;677    if (Error E = extractRangeList(Offset, RangeList))678      return std::move(E);679    return RangeList.getAbsoluteRanges(getBaseAddress());680  }681  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,682                                IsLittleEndian, Header.getAddressByteSize());683  DWARFDebugRnglistTable RnglistTable;684  auto RangeListOrError = RnglistTable.findList(RangesData, Offset);685  if (RangeListOrError)686    return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);687  return RangeListOrError.takeError();688}689 690Expected<DWARFAddressRangesVector>691DWARFUnit::findRnglistFromIndex(uint32_t Index) {692  if (auto Offset = getRnglistOffset(Index))693    return findRnglistFromOffset(*Offset);694 695  return createStringError(errc::invalid_argument,696                           "invalid range list table index %d (possibly "697                           "missing the entire range list table)",698                           Index);699}700 701Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {702  DWARFDie UnitDie = getUnitDIE();703  if (!UnitDie)704    return createStringError(errc::invalid_argument, "No unit DIE");705 706  // First, check if unit DIE describes address ranges for the whole unit.707  auto CUDIERangesOrError = UnitDie.getAddressRanges();708  if (!CUDIERangesOrError)709    return createStringError(errc::invalid_argument,710                             "decoding address ranges: %s",711                             toString(CUDIERangesOrError.takeError()).c_str());712  return *CUDIERangesOrError;713}714 715Expected<DWARFLocationExpressionsVector>716DWARFUnit::findLoclistFromOffset(uint64_t Offset) {717  DWARFLocationExpressionsVector Result;718 719  Error InterpretationError = Error::success();720 721  Error ParseError = getLocationTable().visitAbsoluteLocationList(722      Offset, getBaseAddress(),723      [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },724      [&](Expected<DWARFLocationExpression> L) {725        if (L)726          Result.push_back(std::move(*L));727        else728          InterpretationError =729              joinErrors(L.takeError(), std::move(InterpretationError));730        return !InterpretationError;731      });732 733  if (ParseError || InterpretationError)734    return joinErrors(std::move(ParseError), std::move(InterpretationError));735 736  return Result;737}738 739void DWARFUnit::updateAddressDieMap(DWARFDie Die) {740  if (Die.isSubroutineDIE()) {741    auto DIERangesOrError = Die.getAddressRanges();742    if (DIERangesOrError) {743      for (const auto &R : DIERangesOrError.get()) {744        // Ignore 0-sized ranges.745        if (R.LowPC == R.HighPC)746          continue;747        auto B = AddrDieMap.upper_bound(R.LowPC);748        if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {749          // The range is a sub-range of existing ranges, we need to split the750          // existing range.751          if (R.HighPC < B->second.first)752            AddrDieMap[R.HighPC] = B->second;753          if (R.LowPC > B->first)754            AddrDieMap[B->first].first = R.LowPC;755        }756        AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);757      }758    } else759      llvm::consumeError(DIERangesOrError.takeError());760  }761  // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to762  // simplify the logic to update AddrDieMap. The child's range will always763  // be equal or smaller than the parent's range. With this assumption, when764  // adding one range into the map, it will at most split a range into 3765  // sub-ranges.766  for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())767    updateAddressDieMap(Child);768}769 770DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {771  extractDIEsIfNeeded(false);772  if (AddrDieMap.empty())773    updateAddressDieMap(getUnitDIE());774  auto R = AddrDieMap.upper_bound(Address);775  if (R == AddrDieMap.begin())776    return DWARFDie();777  // upper_bound's previous item contains Address.778  --R;779  if (Address >= R->second.first)780    return DWARFDie();781  return R->second.second;782}783 784void DWARFUnit::updateVariableDieMap(DWARFDie Die) {785  for (DWARFDie Child : Die) {786    if (isType(Child.getTag()))787      continue;788    updateVariableDieMap(Child);789  }790 791  if (Die.getTag() != DW_TAG_variable)792    return;793 794  Expected<DWARFLocationExpressionsVector> Locations =795      Die.getLocations(DW_AT_location);796  if (!Locations) {797    // Missing DW_AT_location is fine here.798    consumeError(Locations.takeError());799    return;800  }801 802  uint64_t Address = UINT64_MAX;803 804  for (const DWARFLocationExpression &Location : *Locations) {805    uint8_t AddressSize = getAddressByteSize();806    DataExtractor Data(Location.Expr, isLittleEndian(), AddressSize);807    DWARFExpression Expr(Data, AddressSize);808    auto It = Expr.begin();809    if (It == Expr.end())810      continue;811 812    // Match exactly the main sequence used to describe global variables:813    // `DW_OP_addr[x] [+ DW_OP_plus_uconst]`. Currently, this is the sequence814    // that LLVM produces for DILocalVariables and DIGlobalVariables. If, in815    // future, the DWARF producer (`DwarfCompileUnit::addLocationAttribute()` is816    // a good starting point) is extended to use further expressions, this code817    // needs to be updated.818    uint64_t LocationAddr;819    if (It->getCode() == dwarf::DW_OP_addr) {820      LocationAddr = It->getRawOperand(0);821    } else if (It->getCode() == dwarf::DW_OP_addrx) {822      uint64_t DebugAddrOffset = It->getRawOperand(0);823      if (auto Pointer = getAddrOffsetSectionItem(DebugAddrOffset)) {824        LocationAddr = Pointer->Address;825      }826    } else {827      continue;828    }829 830    // Read the optional 2nd operand, a DW_OP_plus_uconst.831    if (++It != Expr.end()) {832      if (It->getCode() != dwarf::DW_OP_plus_uconst)833        continue;834 835      LocationAddr += It->getRawOperand(0);836 837      // Probe for a 3rd operand, if it exists, bail.838      if (++It != Expr.end())839        continue;840    }841 842    Address = LocationAddr;843    break;844  }845 846  // Get the size of the global variable. If all else fails (i.e. the global has847  // no type), then we use a size of one to still allow symbolization of the848  // exact address.849  uint64_t GVSize = 1;850  if (Die.getAttributeValueAsReferencedDie(DW_AT_type))851    if (std::optional<uint64_t> Size = Die.getTypeSize(getAddressByteSize()))852      GVSize = *Size;853 854  if (Address != UINT64_MAX)855    VariableDieMap[Address] = {Address + GVSize, Die};856}857 858DWARFDie DWARFUnit::getVariableForAddress(uint64_t Address) {859  extractDIEsIfNeeded(false);860 861  auto RootDie = getUnitDIE();862 863  auto RootLookup = RootsParsedForVariables.insert(RootDie.getOffset());864  if (RootLookup.second)865    updateVariableDieMap(RootDie);866 867  auto R = VariableDieMap.upper_bound(Address);868  if (R == VariableDieMap.begin())869    return DWARFDie();870 871  // upper_bound's previous item contains Address.872  --R;873  if (Address >= R->second.first)874    return DWARFDie();875  return R->second.second;876}877 878void879DWARFUnit::getInlinedChainForAddress(uint64_t Address,880                                     SmallVectorImpl<DWARFDie> &InlinedChain) {881  assert(InlinedChain.empty());882  // Try to look for subprogram DIEs in the DWO file.883  parseDWO();884  // First, find the subroutine that contains the given address (the leaf885  // of inlined chain).886  DWARFDie SubroutineDIE =887      (DWO ? *DWO : *this).getSubroutineForAddress(Address);888 889  while (SubroutineDIE) {890    if (SubroutineDIE.isSubprogramDIE()) {891      InlinedChain.push_back(SubroutineDIE);892      return;893    }894    if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)895      InlinedChain.push_back(SubroutineDIE);896    SubroutineDIE  = SubroutineDIE.getParent();897  }898}899 900const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,901                                              DWARFSectionKind Kind) {902  if (Kind == DW_SECT_INFO)903    return Context.getCUIndex();904  assert(Kind == DW_SECT_EXT_TYPES);905  return Context.getTUIndex();906}907 908DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {909  if (const DWARFDebugInfoEntry *Entry = getParentEntry(Die))910    return DWARFDie(this, Entry);911 912  return DWARFDie();913}914 915const DWARFDebugInfoEntry *916DWARFUnit::getParentEntry(const DWARFDebugInfoEntry *Die) const {917  if (!Die)918    return nullptr;919  assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());920 921  if (std::optional<uint32_t> ParentIdx = Die->getParentIdx()) {922    assert(*ParentIdx < DieArray.size() &&923           "ParentIdx is out of DieArray boundaries");924    return getDebugInfoEntry(*ParentIdx);925  }926 927  return nullptr;928}929 930DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {931  if (const DWARFDebugInfoEntry *Sibling = getSiblingEntry(Die))932    return DWARFDie(this, Sibling);933 934  return DWARFDie();935}936 937const DWARFDebugInfoEntry *938DWARFUnit::getSiblingEntry(const DWARFDebugInfoEntry *Die) const {939  if (!Die)940    return nullptr;941  assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());942 943  if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {944    assert(*SiblingIdx < DieArray.size() &&945           "SiblingIdx is out of DieArray boundaries");946    return &DieArray[*SiblingIdx];947  }948 949  return nullptr;950}951 952DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {953  if (const DWARFDebugInfoEntry *Sibling = getPreviousSiblingEntry(Die))954    return DWARFDie(this, Sibling);955 956  return DWARFDie();957}958 959const DWARFDebugInfoEntry *960DWARFUnit::getPreviousSiblingEntry(const DWARFDebugInfoEntry *Die) const {961  if (!Die)962    return nullptr;963  assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());964 965  std::optional<uint32_t> ParentIdx = Die->getParentIdx();966  if (!ParentIdx)967    // Die is a root die, there is no previous sibling.968    return nullptr;969 970  assert(*ParentIdx < DieArray.size() &&971         "ParentIdx is out of DieArray boundaries");972  assert(getDIEIndex(Die) > 0 && "Die is a root die");973 974  uint32_t PrevDieIdx = getDIEIndex(Die) - 1;975  if (PrevDieIdx == *ParentIdx)976    // Immediately previous node is parent, there is no previous sibling.977    return nullptr;978 979  while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {980    PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();981 982    assert(PrevDieIdx < DieArray.size() &&983           "PrevDieIdx is out of DieArray boundaries");984    assert(PrevDieIdx >= *ParentIdx &&985           "PrevDieIdx is not a child of parent of Die");986  }987 988  return &DieArray[PrevDieIdx];989}990 991DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {992  if (const DWARFDebugInfoEntry *Child = getFirstChildEntry(Die))993    return DWARFDie(this, Child);994 995  return DWARFDie();996}997 998const DWARFDebugInfoEntry *999DWARFUnit::getFirstChildEntry(const DWARFDebugInfoEntry *Die) const {1000  if (!Die)1001    return nullptr;1002  assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());1003 1004  if (!Die->hasChildren())1005    return nullptr;1006 1007  // TODO: Instead of checking here for invalid die we might reject1008  // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).1009  // We do not want access out of bounds when parsing corrupted debug data.1010  size_t I = getDIEIndex(Die) + 1;1011  if (I >= DieArray.size())1012    return nullptr;1013  return &DieArray[I];1014}1015 1016DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {1017  if (const DWARFDebugInfoEntry *Child = getLastChildEntry(Die))1018    return DWARFDie(this, Child);1019 1020  return DWARFDie();1021}1022 1023const DWARFDebugInfoEntry *1024DWARFUnit::getLastChildEntry(const DWARFDebugInfoEntry *Die) const {1025  if (!Die)1026    return nullptr;1027  assert(Die >= DieArray.data() && Die < DieArray.data() + DieArray.size());1028 1029  if (!Die->hasChildren())1030    return nullptr;1031 1032  if (std::optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {1033    assert(*SiblingIdx < DieArray.size() &&1034           "SiblingIdx is out of DieArray boundaries");1035    assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&1036           "Bad end of children marker");1037    return &DieArray[*SiblingIdx - 1];1038  }1039 1040  // If SiblingIdx is set for non-root dies we could be sure that DWARF is1041  // correct and "end of children marker" must be found. For root die we do not1042  // have such a guarantee(parsing root die might be stopped if "end of children1043  // marker" is missing, SiblingIdx is always zero for root die). That is why we1044  // do not use assertion for checking for "end of children marker" for root1045  // die.1046 1047  // TODO: Instead of checking here for invalid die we might reject1048  // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).1049  if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&1050      DieArray.back().getTag() == dwarf::DW_TAG_null) {1051    // For the unit die we might take last item from DieArray.1052    assert(getDIEIndex(Die) ==1053               getDIEIndex(const_cast<DWARFUnit *>(this)->getUnitDIE()) &&1054           "Bad unit die");1055    return &DieArray.back();1056  }1057 1058  return nullptr;1059}1060 1061const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {1062  if (!Abbrevs) {1063    Expected<const DWARFAbbreviationDeclarationSet *> AbbrevsOrError =1064        Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset());1065    if (!AbbrevsOrError) {1066      // FIXME: We should propagate this error upwards.1067      consumeError(AbbrevsOrError.takeError());1068      return nullptr;1069    }1070    Abbrevs = *AbbrevsOrError;1071  }1072  return Abbrevs;1073}1074 1075std::optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {1076  if (BaseAddr)1077    return BaseAddr;1078 1079  DWARFDie UnitDie = (SU ? SU : this)->getUnitDIE();1080  std::optional<DWARFFormValue> PC =1081      UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});1082  BaseAddr = toSectionedAddress(PC);1083  return BaseAddr;1084}1085 1086Expected<StrOffsetsContributionDescriptor>1087StrOffsetsContributionDescriptor::validateContributionSize(1088    DWARFDataExtractor &DA) {1089  uint8_t EntrySize = getDwarfOffsetByteSize();1090  // In order to ensure that we don't read a partial record at the end of1091  // the section we validate for a multiple of the entry size.1092  uint64_t ValidationSize = alignTo(Size, EntrySize);1093  // Guard against overflow.1094  if (ValidationSize >= Size)1095    if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))1096      return *this;1097  return createStringError(errc::invalid_argument, "length exceeds section size");1098}1099 1100// Look for a DWARF64-formatted contribution to the string offsets table1101// starting at a given offset and record it in a descriptor.1102static Expected<StrOffsetsContributionDescriptor>1103parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {1104  if (!DA.isValidOffsetForDataOfSize(Offset, 16))1105    return createStringError(errc::invalid_argument, "section offset exceeds section size");1106 1107  if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)1108    return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");1109 1110  uint64_t Size = DA.getU64(&Offset);1111  uint8_t Version = DA.getU16(&Offset);1112  (void)DA.getU16(&Offset); // padding1113  // The encoded length includes the 2-byte version field and the 2-byte1114  // padding, so we need to subtract them out when we populate the descriptor.1115  return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);1116}1117 1118// Look for a DWARF32-formatted contribution to the string offsets table1119// starting at a given offset and record it in a descriptor.1120static Expected<StrOffsetsContributionDescriptor>1121parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {1122  if (!DA.isValidOffsetForDataOfSize(Offset, 8))1123    return createStringError(errc::invalid_argument, "section offset exceeds section size");1124 1125  uint32_t ContributionSize = DA.getU32(&Offset);1126  if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)1127    return createStringError(errc::invalid_argument, "invalid length");1128 1129  uint8_t Version = DA.getU16(&Offset);1130  (void)DA.getU16(&Offset); // padding1131  // The encoded length includes the 2-byte version field and the 2-byte1132  // padding, so we need to subtract them out when we populate the descriptor.1133  return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,1134                                          DWARF32);1135}1136 1137static Expected<StrOffsetsContributionDescriptor>1138parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,1139                                   llvm::dwarf::DwarfFormat Format,1140                                   uint64_t Offset) {1141  StrOffsetsContributionDescriptor Desc;1142  switch (Format) {1143  case dwarf::DwarfFormat::DWARF64: {1144    if (Offset < 16)1145      return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");1146    auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);1147    if (!DescOrError)1148      return DescOrError.takeError();1149    Desc = *DescOrError;1150    break;1151  }1152  case dwarf::DwarfFormat::DWARF32: {1153    if (Offset < 8)1154      return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");1155    auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);1156    if (!DescOrError)1157      return DescOrError.takeError();1158    Desc = *DescOrError;1159    break;1160  }1161  }1162  return Desc.validateContributionSize(DA);1163}1164 1165Expected<std::optional<StrOffsetsContributionDescriptor>>1166DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {1167  assert(!IsDWO);1168  auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));1169  if (!OptOffset)1170    return std::nullopt;1171  auto DescOrError =1172      parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);1173  if (!DescOrError)1174    return DescOrError.takeError();1175  return *DescOrError;1176}1177 1178Expected<std::optional<StrOffsetsContributionDescriptor>>1179DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA) {1180  assert(IsDWO);1181  uint64_t Offset = 0;1182  auto IndexEntry = Header.getIndexEntry();1183  const auto *C =1184      IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;1185  if (C)1186    Offset = C->getOffset();1187  if (getVersion() >= 5) {1188    if (DA.getData().data() == nullptr)1189      return std::nullopt;1190    // FYI: The .debug_str_offsets.dwo section may use DWARF64 even when the1191    // rest of the file uses DWARF32, so respect whichever encoding the1192    // header/length uses.1193    uint64_t Length = 0;1194    DwarfFormat Format = dwarf::DwarfFormat::DWARF32;1195    std::tie(Length, Format) = DA.getInitialLength(&Offset);1196    Offset += 4; // Skip the DWARF version uint16_t and the uint16_t padding.1197    // Look for a valid contribution at the given offset.1198    auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Format, Offset);1199    if (!DescOrError)1200      return DescOrError.takeError();1201    return *DescOrError;1202  }1203  // Prior to DWARF v5, we derive the contribution size from the1204  // index table (in a package file). In a .dwo file it is simply1205  // the length of the string offsets section.1206  StrOffsetsContributionDescriptor Desc;1207  if (C)1208    Desc = StrOffsetsContributionDescriptor(C->getOffset(), C->getLength(), 4,1209                                            Header.getFormat());1210  else if (!IndexEntry && !StringOffsetSection.Data.empty())1211    Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),1212                                            4, Header.getFormat());1213  else1214    return std::nullopt;1215  auto DescOrError = Desc.validateContributionSize(DA);1216  if (!DescOrError)1217    return DescOrError.takeError();1218  return *DescOrError;1219}1220 1221std::optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {1222  DataExtractor RangesData(RangeSection->Data, IsLittleEndian,1223                           getAddressByteSize());1224  DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,1225                              IsLittleEndian, 0);1226  if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(1227          RangesData, RangeSectionBase, getFormat(), Index))1228    return *Off + RangeSectionBase;1229  return std::nullopt;1230}1231 1232std::optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {1233  if (std::optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(1234          LocTable->getData(), LocSectionBase, getFormat(), Index))1235    return *Off + LocSectionBase;1236  return std::nullopt;1237}1238