184447Sdfr//===- DWARFUnit.cpp ------------------------------------------------------===//
284447Sdfr//
384447Sdfr// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
484447Sdfr// See https://llvm.org/LICENSE.txt for license information.
584447Sdfr// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
684447Sdfr//
784447Sdfr//===----------------------------------------------------------------------===//
884447Sdfr
984447Sdfr#include "llvm/DebugInfo/DWARF/DWARFUnit.h"
1084447Sdfr#include "llvm/ADT/SmallString.h"
1184447Sdfr#include "llvm/ADT/StringRef.h"
1284447Sdfr#include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
1384447Sdfr#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
1484447Sdfr#include "llvm/DebugInfo/DWARF/DWARFContext.h"
1584447Sdfr#include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
1684447Sdfr#include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
1784447Sdfr#include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
1884447Sdfr#include "llvm/DebugInfo/DWARF/DWARFDie.h"
1984447Sdfr#include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
2084447Sdfr#include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
2184447Sdfr#include "llvm/Support/DataExtractor.h"
2284447Sdfr#include "llvm/Support/Errc.h"
2384447Sdfr#include "llvm/Support/Path.h"
2484447Sdfr#include <algorithm>
2584447Sdfr#include <cassert>
2684447Sdfr#include <cstddef>
2784447Sdfr#include <cstdint>
28135453Smarcel#include <cstdio>
29135453Smarcel#include <utility>
30135453Smarcel#include <vector>
31108026Smarcel
32270296Semasteusing namespace llvm;
33108026Smarcelusing namespace dwarf;
3484447Sdfr
35193530Sjkimvoid DWARFUnitVector::addUnitsForSection(DWARFContext &C,
3684447Sdfr                                         const DWARFSection &Section,
37135453Smarcel                                         DWARFSectionKind SectionKind) {
38108026Smarcel  const DWARFObject &D = C.getDWARFObj();
39135453Smarcel  addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
40135453Smarcel               &D.getLocSection(), D.getStrSection(),
41108026Smarcel               D.getStrOffsetsSection(), &D.getAddrSection(),
4284447Sdfr               D.getLineSection(), D.isLittleEndian(), false, false,
4384447Sdfr               SectionKind);
4484447Sdfr}
45135453Smarcel
46215023Sjkimvoid DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
4784447Sdfr                                            const DWARFSection &DWOSection,
4884447Sdfr                                            DWARFSectionKind SectionKind,
4984447Sdfr                                            bool Lazy) {
5084447Sdfr  const DWARFObject &D = C.getDWARFObj();
5184447Sdfr  addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
52135453Smarcel               &D.getLocDWOSection(), D.getStrDWOSection(),
53215023Sjkim               D.getStrOffsetsDWOSection(), &D.getAddrSection(),
5484447Sdfr               D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
5584447Sdfr               SectionKind);
56215023Sjkim}
57215023Sjkim
58215023Sjkimvoid DWARFUnitVector::addUnitsImpl(
59215023Sjkim    DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
60215023Sjkim    const DWARFDebugAbbrev *DA, const DWARFSection *RS,
61215023Sjkim    const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
62215023Sjkim    const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
63215023Sjkim    bool Lazy, DWARFSectionKind SectionKind) {
64215023Sjkim  DWARFDataExtractor Data(Obj, Section, LE, 0);
65215023Sjkim  // Lazy initialization of Parser, now that we have all section info.
66215023Sjkim  if (!Parser) {
67215023Sjkim    Parser = [=, &Context, &Obj, &Section, &SOS,
68215023Sjkim              &LS](uint64_t Offset, DWARFSectionKind SectionKind,
69167814Sjkim                   const DWARFSection *CurSection,
70167814Sjkim                   const DWARFUnitIndex::Entry *IndexEntry)
7184447Sdfr        -> std::unique_ptr<DWARFUnit> {
72135453Smarcel      const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
73215023Sjkim      DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
74215023Sjkim      if (!Data.isValidOffset(Offset))
7584447Sdfr        return nullptr;
76167814Sjkim      DWARFUnitHeader Header;
7784447Sdfr      if (!Header.extract(Context, Data, &Offset, SectionKind))
78        return nullptr;
79      if (!IndexEntry && IsDWO) {
80        const DWARFUnitIndex &Index = getDWARFUnitIndex(
81            Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);
82        IndexEntry = Index.getFromOffset(Header.getOffset());
83      }
84      if (IndexEntry && !Header.applyIndexEntry(IndexEntry))
85        return nullptr;
86      std::unique_ptr<DWARFUnit> U;
87      if (Header.isTypeUnit())
88        U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
89                                             RS, LocSection, SS, SOS, AOS, LS,
90                                             LE, IsDWO, *this);
91      else
92        U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
93                                                DA, RS, LocSection, SS, SOS,
94                                                AOS, LS, LE, IsDWO, *this);
95      return U;
96    };
97  }
98  if (Lazy)
99    return;
100  // Find a reasonable insertion point within the vector.  We skip over
101  // (a) units from a different section, (b) units from the same section
102  // but with lower offset-within-section.  This keeps units in order
103  // within a section, although not necessarily within the object file,
104  // even if we do lazy parsing.
105  auto I = this->begin();
106  uint64_t Offset = 0;
107  while (Data.isValidOffset(Offset)) {
108    if (I != this->end() &&
109        (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
110      ++I;
111      continue;
112    }
113    auto U = Parser(Offset, SectionKind, &Section, nullptr);
114    // If parsing failed, we're done with this section.
115    if (!U)
116      break;
117    Offset = U->getNextUnitOffset();
118    I = std::next(this->insert(I, std::move(U)));
119  }
120}
121
122DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {
123  auto I = std::upper_bound(begin(), end(), Unit,
124                            [](const std::unique_ptr<DWARFUnit> &LHS,
125                               const std::unique_ptr<DWARFUnit> &RHS) {
126                              return LHS->getOffset() < RHS->getOffset();
127                            });
128  return this->insert(I, std::move(Unit))->get();
129}
130
131DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {
132  auto end = begin() + getNumInfoUnits();
133  auto *CU =
134      std::upper_bound(begin(), end, Offset,
135                       [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
136                         return LHS < RHS->getNextUnitOffset();
137                       });
138  if (CU != end && (*CU)->getOffset() <= Offset)
139    return CU->get();
140  return nullptr;
141}
142
143DWARFUnit *
144DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) {
145  const auto *CUOff = E.getContribution(DW_SECT_INFO);
146  if (!CUOff)
147    return nullptr;
148
149  auto Offset = CUOff->Offset;
150  auto end = begin() + getNumInfoUnits();
151
152  auto *CU =
153      std::upper_bound(begin(), end, CUOff->Offset,
154                       [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
155                         return LHS < RHS->getNextUnitOffset();
156                       });
157  if (CU != end && (*CU)->getOffset() <= Offset)
158    return CU->get();
159
160  if (!Parser)
161    return nullptr;
162
163  auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E);
164  if (!U)
165    U = nullptr;
166
167  auto *NewCU = U.get();
168  this->insert(CU, std::move(U));
169  ++NumInfoUnits;
170  return NewCU;
171}
172
173DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
174                     const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
175                     const DWARFSection *RS, const DWARFSection *LocSection,
176                     StringRef SS, const DWARFSection &SOS,
177                     const DWARFSection *AOS, const DWARFSection &LS, bool LE,
178                     bool IsDWO, const DWARFUnitVector &UnitVector)
179    : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
180      RangeSection(RS), LineSection(LS), StringSection(SS),
181      StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE),
182      IsDWO(IsDWO), UnitVector(UnitVector) {
183  clear();
184}
185
186DWARFUnit::~DWARFUnit() = default;
187
188DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
189  return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
190                            getAddressByteSize());
191}
192
193Optional<object::SectionedAddress>
194DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
195  if (!AddrOffsetSectionBase) {
196    auto R = Context.info_section_units();
197    // Surprising if a DWO file has more than one skeleton unit in it - this
198    // probably shouldn't be valid, but if a use case is found, here's where to
199    // support it (probably have to linearly search for the matching skeleton CU
200    // here)
201    if (IsDWO && hasSingleElement(R))
202      return (*R.begin())->getAddrOffsetSectionItem(Index);
203
204    return None;
205  }
206
207  uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
208  if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
209    return None;
210  DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
211                        isLittleEndian, getAddressByteSize());
212  uint64_t Section;
213  uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
214  return {{Address, Section}};
215}
216
217Optional<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
218  if (!StringOffsetsTableContribution)
219    return None;
220  unsigned ItemSize = getDwarfStringOffsetsByteSize();
221  uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
222  if (StringOffsetSection.Data.size() < Offset + ItemSize)
223    return None;
224  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
225                        isLittleEndian, 0);
226  return DA.getRelocatedValue(ItemSize, &Offset);
227}
228
229bool DWARFUnitHeader::extract(DWARFContext &Context,
230                              const DWARFDataExtractor &debug_info,
231                              uint64_t *offset_ptr,
232                              DWARFSectionKind SectionKind) {
233  Offset = *offset_ptr;
234  Error Err = Error::success();
235  IndexEntry = nullptr;
236  std::tie(Length, FormParams.Format) =
237      debug_info.getInitialLength(offset_ptr, &Err);
238  FormParams.Version = debug_info.getU16(offset_ptr, &Err);
239  if (FormParams.Version >= 5) {
240    UnitType = debug_info.getU8(offset_ptr, &Err);
241    FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
242    AbbrOffset = debug_info.getRelocatedValue(
243        FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
244  } else {
245    AbbrOffset = debug_info.getRelocatedValue(
246        FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
247    FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
248    // Fake a unit type based on the section type.  This isn't perfect,
249    // but distinguishing compile and type units is generally enough.
250    if (SectionKind == DW_SECT_EXT_TYPES)
251      UnitType = DW_UT_type;
252    else
253      UnitType = DW_UT_compile;
254  }
255  if (isTypeUnit()) {
256    TypeHash = debug_info.getU64(offset_ptr, &Err);
257    TypeOffset = debug_info.getUnsigned(
258        offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);
259  } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
260    DWOId = debug_info.getU64(offset_ptr, &Err);
261
262  if (errorToBool(std::move(Err)))
263    return false;
264
265  // Header fields all parsed, capture the size of this unit header.
266  assert(*offset_ptr - Offset <= 255 && "unexpected header size");
267  Size = uint8_t(*offset_ptr - Offset);
268
269  // Type offset is unit-relative; should be after the header and before
270  // the end of the current unit.
271  bool TypeOffsetOK =
272      !isTypeUnit()
273          ? true
274          : TypeOffset >= Size &&
275                TypeOffset < getLength() + getUnitLengthFieldByteSize();
276  bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
277  bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
278  bool AddrSizeOK = DWARFContext::isAddressSizeSupported(getAddressByteSize());
279
280  if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK)
281    return false;
282
283  // Keep track of the highest DWARF version we encounter across all units.
284  Context.setMaxVersionIfGreater(getVersion());
285  return true;
286}
287
288bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
289  assert(Entry);
290  assert(!IndexEntry);
291  IndexEntry = Entry;
292  if (AbbrOffset)
293    return false;
294  auto *UnitContrib = IndexEntry->getContribution();
295  if (!UnitContrib ||
296      UnitContrib->Length != (getLength() + getUnitLengthFieldByteSize()))
297    return false;
298  auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);
299  if (!AbbrEntry)
300    return false;
301  AbbrOffset = AbbrEntry->Offset;
302  return true;
303}
304
305// Parse the rangelist table header, including the optional array of offsets
306// following it (DWARF v5 and later).
307template<typename ListTableType>
308static Expected<ListTableType>
309parseListTableHeader(DWARFDataExtractor &DA, uint64_t Offset,
310                        DwarfFormat Format) {
311  // We are expected to be called with Offset 0 or pointing just past the table
312  // header. Correct Offset in the latter case so that it points to the start
313  // of the header.
314  if (Offset > 0) {
315    uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Format);
316    if (Offset < HeaderSize)
317      return createStringError(errc::invalid_argument, "did not detect a valid"
318                               " list table with base = 0x%" PRIx64 "\n",
319                               Offset);
320    Offset -= HeaderSize;
321  }
322  ListTableType Table;
323  if (Error E = Table.extractHeaderAndOffsets(DA, &Offset))
324    return std::move(E);
325  return Table;
326}
327
328Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
329                                  DWARFDebugRangeList &RangeList) const {
330  // Require that compile unit is extracted.
331  assert(!DieArray.empty());
332  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
333                                isLittleEndian, getAddressByteSize());
334  uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
335  return RangeList.extract(RangesData, &ActualRangeListOffset);
336}
337
338void DWARFUnit::clear() {
339  Abbrevs = nullptr;
340  BaseAddr.reset();
341  RangeSectionBase = 0;
342  LocSectionBase = 0;
343  AddrOffsetSectionBase = None;
344  clearDIEs(false);
345  DWO.reset();
346}
347
348const char *DWARFUnit::getCompilationDir() {
349  return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
350}
351
352void DWARFUnit::extractDIEsToVector(
353    bool AppendCUDie, bool AppendNonCUDies,
354    std::vector<DWARFDebugInfoEntry> &Dies) const {
355  if (!AppendCUDie && !AppendNonCUDies)
356    return;
357
358  // Set the offset to that of the first DIE and calculate the start of the
359  // next compilation unit header.
360  uint64_t DIEOffset = getOffset() + getHeaderSize();
361  uint64_t NextCUOffset = getNextUnitOffset();
362  DWARFDebugInfoEntry DIE;
363  DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
364  uint32_t Depth = 0;
365  bool IsCUDie = true;
366
367  while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
368                         Depth)) {
369    if (IsCUDie) {
370      if (AppendCUDie)
371        Dies.push_back(DIE);
372      if (!AppendNonCUDies)
373        break;
374      // The average bytes per DIE entry has been seen to be
375      // around 14-20 so let's pre-reserve the needed memory for
376      // our DIE entries accordingly.
377      Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
378      IsCUDie = false;
379    } else {
380      Dies.push_back(DIE);
381    }
382
383    if (const DWARFAbbreviationDeclaration *AbbrDecl =
384            DIE.getAbbreviationDeclarationPtr()) {
385      // Normal DIE
386      if (AbbrDecl->hasChildren())
387        ++Depth;
388    } else {
389      // NULL DIE.
390      if (Depth > 0)
391        --Depth;
392      if (Depth == 0)
393        break;  // We are done with this compile unit!
394    }
395  }
396
397  // Give a little bit of info if we encounter corrupt DWARF (our offset
398  // should always terminate at or before the start of the next compilation
399  // unit header).
400  if (DIEOffset > NextCUOffset)
401    Context.getWarningHandler()(
402        createStringError(errc::invalid_argument,
403                          "DWARF compile unit extends beyond its "
404                          "bounds cu 0x%8.8" PRIx64 " "
405                          "at 0x%8.8" PRIx64 "\n",
406                          getOffset(), DIEOffset));
407}
408
409void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
410  if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
411    Context.getRecoverableErrorHandler()(std::move(e));
412}
413
414Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
415  if ((CUDieOnly && !DieArray.empty()) ||
416      DieArray.size() > 1)
417    return Error::success(); // Already parsed.
418
419  bool HasCUDie = !DieArray.empty();
420  extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
421
422  if (DieArray.empty())
423    return Error::success();
424
425  // If CU DIE was just parsed, copy several attribute values from it.
426  if (HasCUDie)
427    return Error::success();
428
429  DWARFDie UnitDie(this, &DieArray[0]);
430  if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
431    Header.setDWOId(*DWOId);
432  if (!IsDWO) {
433    assert(AddrOffsetSectionBase == None);
434    assert(RangeSectionBase == 0);
435    assert(LocSectionBase == 0);
436    AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));
437    if (!AddrOffsetSectionBase)
438      AddrOffsetSectionBase =
439          toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));
440    RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
441    LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);
442  }
443
444  // In general, in DWARF v5 and beyond we derive the start of the unit's
445  // contribution to the string offsets table from the unit DIE's
446  // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
447  // attribute, so we assume that there is a contribution to the string
448  // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
449  // In both cases we need to determine the format of the contribution,
450  // which may differ from the unit's format.
451  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
452                        isLittleEndian, 0);
453  if (IsDWO || getVersion() >= 5) {
454    auto StringOffsetOrError =
455        IsDWO ? determineStringOffsetsTableContributionDWO(DA)
456              : determineStringOffsetsTableContribution(DA);
457    if (!StringOffsetOrError)
458      return createStringError(errc::invalid_argument,
459                               "invalid reference to or invalid content in "
460                               ".debug_str_offsets[.dwo]: " +
461                                   toString(StringOffsetOrError.takeError()));
462
463    StringOffsetsTableContribution = *StringOffsetOrError;
464  }
465
466  // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
467  // describe address ranges.
468  if (getVersion() >= 5) {
469    // In case of DWP, the base offset from the index has to be added.
470    if (IsDWO) {
471      uint64_t ContributionBaseOffset = 0;
472      if (auto *IndexEntry = Header.getIndexEntry())
473        if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))
474          ContributionBaseOffset = Contrib->Offset;
475      setRangesSection(
476          &Context.getDWARFObj().getRnglistsDWOSection(),
477          ContributionBaseOffset +
478              DWARFListTableHeader::getHeaderSize(Header.getFormat()));
479    } else
480      setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
481                       toSectionOffset(UnitDie.find(DW_AT_rnglists_base),
482                                       DWARFListTableHeader::getHeaderSize(
483                                           Header.getFormat())));
484  }
485
486  if (IsDWO) {
487    // If we are reading a package file, we need to adjust the location list
488    // data based on the index entries.
489    StringRef Data = Header.getVersion() >= 5
490                         ? Context.getDWARFObj().getLoclistsDWOSection().Data
491                         : Context.getDWARFObj().getLocDWOSection().Data;
492    if (auto *IndexEntry = Header.getIndexEntry())
493      if (const auto *C = IndexEntry->getContribution(
494              Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
495        Data = Data.substr(C->Offset, C->Length);
496
497    DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize());
498    LocTable =
499        std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());
500    LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());
501  } else if (getVersion() >= 5) {
502    LocTable = std::make_unique<DWARFDebugLoclists>(
503        DWARFDataExtractor(Context.getDWARFObj(),
504                           Context.getDWARFObj().getLoclistsSection(),
505                           isLittleEndian, getAddressByteSize()),
506        getVersion());
507  } else {
508    LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(
509        Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),
510        isLittleEndian, getAddressByteSize()));
511  }
512
513  // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
514  // skeleton CU DIE, so that DWARF users not aware of it are not broken.
515  return Error::success();
516}
517
518bool DWARFUnit::parseDWO() {
519  if (IsDWO)
520    return false;
521  if (DWO.get())
522    return false;
523  DWARFDie UnitDie = getUnitDIE();
524  if (!UnitDie)
525    return false;
526  auto DWOFileName = getVersion() >= 5
527                         ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
528                         : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
529  if (!DWOFileName)
530    return false;
531  auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
532  SmallString<16> AbsolutePath;
533  if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
534      *CompilationDir) {
535    sys::path::append(AbsolutePath, *CompilationDir);
536  }
537  sys::path::append(AbsolutePath, *DWOFileName);
538  auto DWOId = getDWOId();
539  if (!DWOId)
540    return false;
541  auto DWOContext = Context.getDWOContext(AbsolutePath);
542  if (!DWOContext)
543    return false;
544
545  DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
546  if (!DWOCU)
547    return false;
548  DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
549  // Share .debug_addr and .debug_ranges section with compile unit in .dwo
550  if (AddrOffsetSectionBase)
551    DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
552  if (getVersion() >= 5) {
553    DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(),
554                          DWARFListTableHeader::getHeaderSize(getFormat()));
555  } else {
556    auto DWORangesBase = UnitDie.getRangesBaseAttribute();
557    DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
558  }
559
560  return true;
561}
562
563void DWARFUnit::clearDIEs(bool KeepCUDie) {
564  if (DieArray.size() > (unsigned)KeepCUDie) {
565    DieArray.resize((unsigned)KeepCUDie);
566    DieArray.shrink_to_fit();
567  }
568}
569
570Expected<DWARFAddressRangesVector>
571DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
572  if (getVersion() <= 4) {
573    DWARFDebugRangeList RangeList;
574    if (Error E = extractRangeList(Offset, RangeList))
575      return std::move(E);
576    return RangeList.getAbsoluteRanges(getBaseAddress());
577  }
578  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
579                                isLittleEndian, Header.getAddressByteSize());
580  DWARFDebugRnglistTable RnglistTable;
581  auto RangeListOrError = RnglistTable.findList(RangesData, Offset);
582  if (RangeListOrError)
583    return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
584  return RangeListOrError.takeError();
585}
586
587Expected<DWARFAddressRangesVector>
588DWARFUnit::findRnglistFromIndex(uint32_t Index) {
589  if (auto Offset = getRnglistOffset(Index))
590    return findRnglistFromOffset(*Offset);
591
592  return createStringError(errc::invalid_argument,
593                           "invalid range list table index %d (possibly "
594                           "missing the entire range list table)",
595                           Index);
596}
597
598Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
599  DWARFDie UnitDie = getUnitDIE();
600  if (!UnitDie)
601    return createStringError(errc::invalid_argument, "No unit DIE");
602
603  // First, check if unit DIE describes address ranges for the whole unit.
604  auto CUDIERangesOrError = UnitDie.getAddressRanges();
605  if (!CUDIERangesOrError)
606    return createStringError(errc::invalid_argument,
607                             "decoding address ranges: %s",
608                             toString(CUDIERangesOrError.takeError()).c_str());
609  return *CUDIERangesOrError;
610}
611
612Expected<DWARFLocationExpressionsVector>
613DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
614  DWARFLocationExpressionsVector Result;
615
616  Error InterpretationError = Error::success();
617
618  Error ParseError = getLocationTable().visitAbsoluteLocationList(
619      Offset, getBaseAddress(),
620      [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
621      [&](Expected<DWARFLocationExpression> L) {
622        if (L)
623          Result.push_back(std::move(*L));
624        else
625          InterpretationError =
626              joinErrors(L.takeError(), std::move(InterpretationError));
627        return !InterpretationError;
628      });
629
630  if (ParseError || InterpretationError)
631    return joinErrors(std::move(ParseError), std::move(InterpretationError));
632
633  return Result;
634}
635
636void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
637  if (Die.isSubroutineDIE()) {
638    auto DIERangesOrError = Die.getAddressRanges();
639    if (DIERangesOrError) {
640      for (const auto &R : DIERangesOrError.get()) {
641        // Ignore 0-sized ranges.
642        if (R.LowPC == R.HighPC)
643          continue;
644        auto B = AddrDieMap.upper_bound(R.LowPC);
645        if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
646          // The range is a sub-range of existing ranges, we need to split the
647          // existing range.
648          if (R.HighPC < B->second.first)
649            AddrDieMap[R.HighPC] = B->second;
650          if (R.LowPC > B->first)
651            AddrDieMap[B->first].first = R.LowPC;
652        }
653        AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
654      }
655    } else
656      llvm::consumeError(DIERangesOrError.takeError());
657  }
658  // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
659  // simplify the logic to update AddrDieMap. The child's range will always
660  // be equal or smaller than the parent's range. With this assumption, when
661  // adding one range into the map, it will at most split a range into 3
662  // sub-ranges.
663  for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
664    updateAddressDieMap(Child);
665}
666
667DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
668  extractDIEsIfNeeded(false);
669  if (AddrDieMap.empty())
670    updateAddressDieMap(getUnitDIE());
671  auto R = AddrDieMap.upper_bound(Address);
672  if (R == AddrDieMap.begin())
673    return DWARFDie();
674  // upper_bound's previous item contains Address.
675  --R;
676  if (Address >= R->second.first)
677    return DWARFDie();
678  return R->second.second;
679}
680
681void
682DWARFUnit::getInlinedChainForAddress(uint64_t Address,
683                                     SmallVectorImpl<DWARFDie> &InlinedChain) {
684  assert(InlinedChain.empty());
685  // Try to look for subprogram DIEs in the DWO file.
686  parseDWO();
687  // First, find the subroutine that contains the given address (the leaf
688  // of inlined chain).
689  DWARFDie SubroutineDIE =
690      (DWO ? *DWO : *this).getSubroutineForAddress(Address);
691
692  while (SubroutineDIE) {
693    if (SubroutineDIE.isSubprogramDIE()) {
694      InlinedChain.push_back(SubroutineDIE);
695      return;
696    }
697    if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
698      InlinedChain.push_back(SubroutineDIE);
699    SubroutineDIE  = SubroutineDIE.getParent();
700  }
701}
702
703const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
704                                              DWARFSectionKind Kind) {
705  if (Kind == DW_SECT_INFO)
706    return Context.getCUIndex();
707  assert(Kind == DW_SECT_EXT_TYPES);
708  return Context.getTUIndex();
709}
710
711DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
712  if (!Die)
713    return DWARFDie();
714  const uint32_t Depth = Die->getDepth();
715  // Unit DIEs always have a depth of zero and never have parents.
716  if (Depth == 0)
717    return DWARFDie();
718  // Depth of 1 always means parent is the compile/type unit.
719  if (Depth == 1)
720    return getUnitDIE();
721  // Look for previous DIE with a depth that is one less than the Die's depth.
722  const uint32_t ParentDepth = Depth - 1;
723  for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
724    if (DieArray[I].getDepth() == ParentDepth)
725      return DWARFDie(this, &DieArray[I]);
726  }
727  return DWARFDie();
728}
729
730DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
731  if (!Die)
732    return DWARFDie();
733  uint32_t Depth = Die->getDepth();
734  // Unit DIEs always have a depth of zero and never have siblings.
735  if (Depth == 0)
736    return DWARFDie();
737  // NULL DIEs don't have siblings.
738  if (Die->getAbbreviationDeclarationPtr() == nullptr)
739    return DWARFDie();
740
741  // Find the next DIE whose depth is the same as the Die's depth.
742  for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
743       ++I) {
744    if (DieArray[I].getDepth() == Depth)
745      return DWARFDie(this, &DieArray[I]);
746  }
747  return DWARFDie();
748}
749
750DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
751  if (!Die)
752    return DWARFDie();
753  uint32_t Depth = Die->getDepth();
754  // Unit DIEs always have a depth of zero and never have siblings.
755  if (Depth == 0)
756    return DWARFDie();
757
758  // Find the previous DIE whose depth is the same as the Die's depth.
759  for (size_t I = getDIEIndex(Die); I > 0;) {
760    --I;
761    if (DieArray[I].getDepth() == Depth - 1)
762      return DWARFDie();
763    if (DieArray[I].getDepth() == Depth)
764      return DWARFDie(this, &DieArray[I]);
765  }
766  return DWARFDie();
767}
768
769DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
770  if (!Die->hasChildren())
771    return DWARFDie();
772
773  // We do not want access out of bounds when parsing corrupted debug data.
774  size_t I = getDIEIndex(Die) + 1;
775  if (I >= DieArray.size())
776    return DWARFDie();
777  return DWARFDie(this, &DieArray[I]);
778}
779
780DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
781  if (!Die->hasChildren())
782    return DWARFDie();
783
784  uint32_t Depth = Die->getDepth();
785  for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
786       ++I) {
787    if (DieArray[I].getDepth() == Depth + 1 &&
788        DieArray[I].getTag() == dwarf::DW_TAG_null)
789      return DWARFDie(this, &DieArray[I]);
790    assert(DieArray[I].getDepth() > Depth && "Not processing children?");
791  }
792  return DWARFDie();
793}
794
795const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
796  if (!Abbrevs)
797    Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
798  return Abbrevs;
799}
800
801llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
802  if (BaseAddr)
803    return BaseAddr;
804
805  DWARFDie UnitDie = getUnitDIE();
806  Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
807  BaseAddr = toSectionedAddress(PC);
808  return BaseAddr;
809}
810
811Expected<StrOffsetsContributionDescriptor>
812StrOffsetsContributionDescriptor::validateContributionSize(
813    DWARFDataExtractor &DA) {
814  uint8_t EntrySize = getDwarfOffsetByteSize();
815  // In order to ensure that we don't read a partial record at the end of
816  // the section we validate for a multiple of the entry size.
817  uint64_t ValidationSize = alignTo(Size, EntrySize);
818  // Guard against overflow.
819  if (ValidationSize >= Size)
820    if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
821      return *this;
822  return createStringError(errc::invalid_argument, "length exceeds section size");
823}
824
825// Look for a DWARF64-formatted contribution to the string offsets table
826// starting at a given offset and record it in a descriptor.
827static Expected<StrOffsetsContributionDescriptor>
828parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
829  if (!DA.isValidOffsetForDataOfSize(Offset, 16))
830    return createStringError(errc::invalid_argument, "section offset exceeds section size");
831
832  if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
833    return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
834
835  uint64_t Size = DA.getU64(&Offset);
836  uint8_t Version = DA.getU16(&Offset);
837  (void)DA.getU16(&Offset); // padding
838  // The encoded length includes the 2-byte version field and the 2-byte
839  // padding, so we need to subtract them out when we populate the descriptor.
840  return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
841}
842
843// Look for a DWARF32-formatted contribution to the string offsets table
844// starting at a given offset and record it in a descriptor.
845static Expected<StrOffsetsContributionDescriptor>
846parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
847  if (!DA.isValidOffsetForDataOfSize(Offset, 8))
848    return createStringError(errc::invalid_argument, "section offset exceeds section size");
849
850  uint32_t ContributionSize = DA.getU32(&Offset);
851  if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
852    return createStringError(errc::invalid_argument, "invalid length");
853
854  uint8_t Version = DA.getU16(&Offset);
855  (void)DA.getU16(&Offset); // padding
856  // The encoded length includes the 2-byte version field and the 2-byte
857  // padding, so we need to subtract them out when we populate the descriptor.
858  return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
859                                          DWARF32);
860}
861
862static Expected<StrOffsetsContributionDescriptor>
863parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
864                                   llvm::dwarf::DwarfFormat Format,
865                                   uint64_t Offset) {
866  StrOffsetsContributionDescriptor Desc;
867  switch (Format) {
868  case dwarf::DwarfFormat::DWARF64: {
869    if (Offset < 16)
870      return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
871    auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
872    if (!DescOrError)
873      return DescOrError.takeError();
874    Desc = *DescOrError;
875    break;
876  }
877  case dwarf::DwarfFormat::DWARF32: {
878    if (Offset < 8)
879      return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
880    auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
881    if (!DescOrError)
882      return DescOrError.takeError();
883    Desc = *DescOrError;
884    break;
885  }
886  }
887  return Desc.validateContributionSize(DA);
888}
889
890Expected<Optional<StrOffsetsContributionDescriptor>>
891DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
892  assert(!IsDWO);
893  auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
894  if (!OptOffset)
895    return None;
896  auto DescOrError =
897      parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
898  if (!DescOrError)
899    return DescOrError.takeError();
900  return *DescOrError;
901}
902
903Expected<Optional<StrOffsetsContributionDescriptor>>
904DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
905  assert(IsDWO);
906  uint64_t Offset = 0;
907  auto IndexEntry = Header.getIndexEntry();
908  const auto *C =
909      IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
910  if (C)
911    Offset = C->Offset;
912  if (getVersion() >= 5) {
913    if (DA.getData().data() == nullptr)
914      return None;
915    Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
916    // Look for a valid contribution at the given offset.
917    auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
918    if (!DescOrError)
919      return DescOrError.takeError();
920    return *DescOrError;
921  }
922  // Prior to DWARF v5, we derive the contribution size from the
923  // index table (in a package file). In a .dwo file it is simply
924  // the length of the string offsets section.
925  StrOffsetsContributionDescriptor Desc;
926  if (C)
927    Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4,
928                                            Header.getFormat());
929  else if (!IndexEntry && !StringOffsetSection.Data.empty())
930    Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
931                                            4, Header.getFormat());
932  else
933    return None;
934  auto DescOrError = Desc.validateContributionSize(DA);
935  if (!DescOrError)
936    return DescOrError.takeError();
937  return *DescOrError;
938}
939
940Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
941  DataExtractor RangesData(RangeSection->Data, isLittleEndian,
942                           getAddressByteSize());
943  DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
944                              isLittleEndian, 0);
945  if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
946          RangesData, RangeSectionBase, getFormat(), Index))
947    return *Off + RangeSectionBase;
948  return None;
949}
950
951Optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {
952  if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
953          LocTable->getData(), LocSectionBase, getFormat(), Index))
954    return *Off + LocSectionBase;
955  return None;
956}
957