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-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
10 #include "llvm/ADT/SmallString.h"
11 #include "llvm/ADT/StringRef.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/DWARFDebugRnglists.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
21 #include "llvm/Support/DataExtractor.h"
22 #include "llvm/Support/Errc.h"
23 #include "llvm/Support/Path.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cstddef>
27 #include <cstdint>
28 #include <cstdio>
29 #include <utility>
30 #include <vector>
31 
32 using namespace llvm;
33 using namespace dwarf;
34 
35 void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
36                                          const DWARFSection &Section,
37                                          DWARFSectionKind SectionKind) {
38   const DWARFObject &D = C.getDWARFObj();
39   addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
40                &D.getLocSection(), D.getStrSection(),
41                D.getStrOffsetsSection(), &D.getAddrSection(),
42                D.getLineSection(), D.isLittleEndian(), false, false,
43                SectionKind);
44 }
45 
46 void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
47                                             const DWARFSection &DWOSection,
48                                             DWARFSectionKind SectionKind,
49                                             bool Lazy) {
50   const DWARFObject &D = C.getDWARFObj();
51   addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
52                &D.getLocDWOSection(), D.getStrDWOSection(),
53                D.getStrOffsetsDWOSection(), &D.getAddrSection(),
54                D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
55                SectionKind);
56 }
57 
58 void DWARFUnitVector::addUnitsImpl(
59     DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
60     const DWARFDebugAbbrev *DA, const DWARFSection *RS,
61     const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
62     const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
63     bool Lazy, DWARFSectionKind SectionKind) {
64   DWARFDataExtractor Data(Obj, Section, LE, 0);
65   // Lazy initialization of Parser, now that we have all section info.
66   if (!Parser) {
67     Parser = [=, &Context, &Obj, &Section, &SOS,
68               &LS](uint64_t Offset, DWARFSectionKind SectionKind,
69                    const DWARFSection *CurSection,
70                    const DWARFUnitIndex::Entry *IndexEntry)
71         -> std::unique_ptr<DWARFUnit> {
72       const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
73       DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
74       if (!Data.isValidOffset(Offset))
75         return nullptr;
76       DWARFUnitHeader Header;
77       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 
122 DWARFUnit *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 
131 DWARFUnit *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 
143 DWARFUnit *
144 DWARFUnitVector::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 
173 DWARFUnit::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   if (IsDWO) {
185     // If we are reading a package file, we need to adjust the location list
186     // data based on the index entries.
187     StringRef Data = Header.getVersion() >= 5
188                          ? Context.getDWARFObj().getLoclistsDWOSection().Data
189                          : LocSection->Data;
190     if (auto *IndexEntry = Header.getIndexEntry())
191       if (const auto *C = IndexEntry->getContribution(
192               Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
193         Data = Data.substr(C->Offset, C->Length);
194 
195     DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize());
196     LocTable =
197         std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());
198   } else if (Header.getVersion() >= 5) {
199     LocTable = std::make_unique<DWARFDebugLoclists>(
200         DWARFDataExtractor(Context.getDWARFObj(),
201                            Context.getDWARFObj().getLoclistsSection(),
202                            isLittleEndian, getAddressByteSize()),
203         Header.getVersion());
204   } else {
205     LocTable = std::make_unique<DWARFDebugLoc>(
206         DWARFDataExtractor(Context.getDWARFObj(), *LocSection, isLittleEndian,
207                            getAddressByteSize()));
208   }
209 }
210 
211 DWARFUnit::~DWARFUnit() = default;
212 
213 DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
214   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
215                             getAddressByteSize());
216 }
217 
218 Optional<object::SectionedAddress>
219 DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
220   if (IsDWO) {
221     auto R = Context.info_section_units();
222     auto I = R.begin();
223     // Surprising if a DWO file has more than one skeleton unit in it - this
224     // probably shouldn't be valid, but if a use case is found, here's where to
225     // support it (probably have to linearly search for the matching skeleton CU
226     // here)
227     if (I != R.end() && std::next(I) == R.end())
228       return (*I)->getAddrOffsetSectionItem(Index);
229   }
230   if (!AddrOffsetSectionBase)
231     return None;
232   uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
233   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
234     return None;
235   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
236                         isLittleEndian, getAddressByteSize());
237   uint64_t Section;
238   uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
239   return {{Address, Section}};
240 }
241 
242 Optional<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
243   if (!StringOffsetsTableContribution)
244     return None;
245   unsigned ItemSize = getDwarfStringOffsetsByteSize();
246   uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
247   if (StringOffsetSection.Data.size() < Offset + ItemSize)
248     return None;
249   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
250                         isLittleEndian, 0);
251   return DA.getRelocatedValue(ItemSize, &Offset);
252 }
253 
254 bool DWARFUnitHeader::extract(DWARFContext &Context,
255                               const DWARFDataExtractor &debug_info,
256                               uint64_t *offset_ptr,
257                               DWARFSectionKind SectionKind) {
258   Offset = *offset_ptr;
259   Error Err = Error::success();
260   IndexEntry = nullptr;
261   std::tie(Length, FormParams.Format) =
262       debug_info.getInitialLength(offset_ptr, &Err);
263   FormParams.Version = debug_info.getU16(offset_ptr, &Err);
264   if (FormParams.Version >= 5) {
265     UnitType = debug_info.getU8(offset_ptr, &Err);
266     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
267     AbbrOffset = debug_info.getRelocatedValue(
268         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
269   } else {
270     AbbrOffset = debug_info.getRelocatedValue(
271         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
272     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
273     // Fake a unit type based on the section type.  This isn't perfect,
274     // but distinguishing compile and type units is generally enough.
275     if (SectionKind == DW_SECT_EXT_TYPES)
276       UnitType = DW_UT_type;
277     else
278       UnitType = DW_UT_compile;
279   }
280   if (isTypeUnit()) {
281     TypeHash = debug_info.getU64(offset_ptr, &Err);
282     TypeOffset = debug_info.getUnsigned(
283         offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);
284   } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
285     DWOId = debug_info.getU64(offset_ptr, &Err);
286 
287   if (errorToBool(std::move(Err)))
288     return false;
289 
290   // Header fields all parsed, capture the size of this unit header.
291   assert(*offset_ptr - Offset <= 255 && "unexpected header size");
292   Size = uint8_t(*offset_ptr - Offset);
293 
294   // Type offset is unit-relative; should be after the header and before
295   // the end of the current unit.
296   bool TypeOffsetOK =
297       !isTypeUnit()
298           ? true
299           : TypeOffset >= Size &&
300                 TypeOffset < getLength() + getUnitLengthFieldByteSize();
301   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
302   bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
303   bool AddrSizeOK = DWARFContext::isAddressSizeSupported(getAddressByteSize());
304 
305   if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK)
306     return false;
307 
308   // Keep track of the highest DWARF version we encounter across all units.
309   Context.setMaxVersionIfGreater(getVersion());
310   return true;
311 }
312 
313 bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
314   assert(Entry);
315   assert(!IndexEntry);
316   IndexEntry = Entry;
317   if (AbbrOffset)
318     return false;
319   auto *UnitContrib = IndexEntry->getContribution();
320   if (!UnitContrib ||
321       UnitContrib->Length != (getLength() + getUnitLengthFieldByteSize()))
322     return false;
323   auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);
324   if (!AbbrEntry)
325     return false;
326   AbbrOffset = AbbrEntry->Offset;
327   return true;
328 }
329 
330 // Parse the rangelist table header, including the optional array of offsets
331 // following it (DWARF v5 and later).
332 template<typename ListTableType>
333 static Expected<ListTableType>
334 parseListTableHeader(DWARFDataExtractor &DA, uint64_t Offset,
335                         DwarfFormat Format) {
336   // We are expected to be called with Offset 0 or pointing just past the table
337   // header. Correct Offset in the latter case so that it points to the start
338   // of the header.
339   if (Offset > 0) {
340     uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Format);
341     if (Offset < HeaderSize)
342       return createStringError(errc::invalid_argument, "did not detect a valid"
343                                " list table with base = 0x%" PRIx64 "\n",
344                                Offset);
345     Offset -= HeaderSize;
346   }
347   ListTableType Table;
348   if (Error E = Table.extractHeaderAndOffsets(DA, &Offset))
349     return std::move(E);
350   return Table;
351 }
352 
353 Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
354                                   DWARFDebugRangeList &RangeList) const {
355   // Require that compile unit is extracted.
356   assert(!DieArray.empty());
357   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
358                                 isLittleEndian, getAddressByteSize());
359   uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
360   return RangeList.extract(RangesData, &ActualRangeListOffset);
361 }
362 
363 void DWARFUnit::clear() {
364   Abbrevs = nullptr;
365   BaseAddr.reset();
366   RangeSectionBase = 0;
367   LocSectionBase = 0;
368   AddrOffsetSectionBase = None;
369   clearDIEs(false);
370   DWO.reset();
371 }
372 
373 const char *DWARFUnit::getCompilationDir() {
374   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
375 }
376 
377 void DWARFUnit::extractDIEsToVector(
378     bool AppendCUDie, bool AppendNonCUDies,
379     std::vector<DWARFDebugInfoEntry> &Dies) const {
380   if (!AppendCUDie && !AppendNonCUDies)
381     return;
382 
383   // Set the offset to that of the first DIE and calculate the start of the
384   // next compilation unit header.
385   uint64_t DIEOffset = getOffset() + getHeaderSize();
386   uint64_t NextCUOffset = getNextUnitOffset();
387   DWARFDebugInfoEntry DIE;
388   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
389   uint32_t Depth = 0;
390   bool IsCUDie = true;
391 
392   while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
393                          Depth)) {
394     if (IsCUDie) {
395       if (AppendCUDie)
396         Dies.push_back(DIE);
397       if (!AppendNonCUDies)
398         break;
399       // The average bytes per DIE entry has been seen to be
400       // around 14-20 so let's pre-reserve the needed memory for
401       // our DIE entries accordingly.
402       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
403       IsCUDie = false;
404     } else {
405       Dies.push_back(DIE);
406     }
407 
408     if (const DWARFAbbreviationDeclaration *AbbrDecl =
409             DIE.getAbbreviationDeclarationPtr()) {
410       // Normal DIE
411       if (AbbrDecl->hasChildren())
412         ++Depth;
413     } else {
414       // NULL DIE.
415       if (Depth > 0)
416         --Depth;
417       if (Depth == 0)
418         break;  // We are done with this compile unit!
419     }
420   }
421 
422   // Give a little bit of info if we encounter corrupt DWARF (our offset
423   // should always terminate at or before the start of the next compilation
424   // unit header).
425   if (DIEOffset > NextCUOffset)
426     Context.getWarningHandler()(
427         createStringError(errc::invalid_argument,
428                           "DWARF compile unit extends beyond its "
429                           "bounds cu 0x%8.8" PRIx64 " "
430                           "at 0x%8.8" PRIx64 "\n",
431                           getOffset(), DIEOffset));
432 }
433 
434 void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
435   if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
436     Context.getRecoverableErrorHandler()(std::move(e));
437 }
438 
439 Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
440   if ((CUDieOnly && !DieArray.empty()) ||
441       DieArray.size() > 1)
442     return Error::success(); // Already parsed.
443 
444   bool HasCUDie = !DieArray.empty();
445   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
446 
447   if (DieArray.empty())
448     return Error::success();
449 
450   // If CU DIE was just parsed, copy several attribute values from it.
451   if (HasCUDie)
452     return Error::success();
453 
454   DWARFDie UnitDie(this, &DieArray[0]);
455   if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
456     Header.setDWOId(*DWOId);
457   if (!IsDWO) {
458     assert(AddrOffsetSectionBase == None);
459     assert(RangeSectionBase == 0);
460     assert(LocSectionBase == 0);
461     AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));
462     if (!AddrOffsetSectionBase)
463       AddrOffsetSectionBase =
464           toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));
465     RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
466     LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);
467   }
468 
469   // In general, in DWARF v5 and beyond we derive the start of the unit's
470   // contribution to the string offsets table from the unit DIE's
471   // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
472   // attribute, so we assume that there is a contribution to the string
473   // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
474   // In both cases we need to determine the format of the contribution,
475   // which may differ from the unit's format.
476   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
477                         isLittleEndian, 0);
478   if (IsDWO || getVersion() >= 5) {
479     auto StringOffsetOrError =
480         IsDWO ? determineStringOffsetsTableContributionDWO(DA)
481               : determineStringOffsetsTableContribution(DA);
482     if (!StringOffsetOrError)
483       return createStringError(errc::invalid_argument,
484                                "invalid reference to or invalid content in "
485                                ".debug_str_offsets[.dwo]: " +
486                                    toString(StringOffsetOrError.takeError()));
487 
488     StringOffsetsTableContribution = *StringOffsetOrError;
489   }
490 
491   // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
492   // describe address ranges.
493   if (getVersion() >= 5) {
494     // In case of DWP, the base offset from the index has to be added.
495     uint64_t ContributionBaseOffset = 0;
496     if (IsDWO) {
497       if (auto *IndexEntry = Header.getIndexEntry())
498         if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))
499           ContributionBaseOffset = Contrib->Offset;
500       setRangesSection(
501           &Context.getDWARFObj().getRnglistsDWOSection(),
502           ContributionBaseOffset +
503               DWARFListTableHeader::getHeaderSize(Header.getFormat()));
504     } else
505       setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
506                        toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0));
507     if (RangeSection->Data.size()) {
508       // Parse the range list table header. Individual range lists are
509       // extracted lazily.
510       DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
511                                   isLittleEndian, 0);
512       auto TableOrError = parseListTableHeader<DWARFDebugRnglistTable>(
513           RangesDA, RangeSectionBase, Header.getFormat());
514       if (!TableOrError)
515         return createStringError(errc::invalid_argument,
516                                  "parsing a range list table: " +
517                                      toString(TableOrError.takeError()));
518 
519       RngListTable = TableOrError.get();
520 
521       // In a split dwarf unit, there is no DW_AT_rnglists_base attribute.
522       // Adjust RangeSectionBase to point past the table header.
523       if (IsDWO && RngListTable)
524         RangeSectionBase =
525             ContributionBaseOffset + RngListTable->getHeaderSize();
526     }
527 
528     // In a split dwarf unit, there is no DW_AT_loclists_base attribute.
529     // Setting LocSectionBase to point past the table header.
530     if (IsDWO) {
531       auto &DWOSection = Context.getDWARFObj().getLoclistsDWOSection();
532       if (DWOSection.Data.empty())
533         return Error::success();
534       setLocSection(&DWOSection,
535                     DWARFListTableHeader::getHeaderSize(Header.getFormat()));
536     } else if (auto X = UnitDie.find(DW_AT_loclists_base)) {
537       setLocSection(&Context.getDWARFObj().getLoclistsSection(),
538                     toSectionOffset(X, 0));
539     } else {
540       return Error::success();
541     }
542 
543     if (LocSection) {
544       if (IsDWO)
545         LoclistTableHeader.emplace(".debug_loclists.dwo", "locations");
546       else
547         LoclistTableHeader.emplace(".debug_loclists", "locations");
548 
549       uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Header.getFormat());
550       uint64_t Offset = getLocSectionBase();
551       const DWARFDataExtractor &Data = LocTable->getData();
552       if (Offset < HeaderSize)
553         return createStringError(errc::invalid_argument,
554                                  "did not detect a valid"
555                                  " list table with base = 0x%" PRIx64 "\n",
556                                  Offset);
557       Offset -= HeaderSize;
558       if (Error E = LoclistTableHeader->extract(Data, &Offset))
559         return createStringError(errc::invalid_argument,
560                                  "parsing a loclist table: " +
561                                      toString(std::move(E)));
562     }
563   }
564 
565   // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
566   // skeleton CU DIE, so that DWARF users not aware of it are not broken.
567   return Error::success();
568 }
569 
570 bool DWARFUnit::parseDWO() {
571   if (IsDWO)
572     return false;
573   if (DWO.get())
574     return false;
575   DWARFDie UnitDie = getUnitDIE();
576   if (!UnitDie)
577     return false;
578   auto DWOFileName = getVersion() >= 5
579                          ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
580                          : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
581   if (!DWOFileName)
582     return false;
583   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
584   SmallString<16> AbsolutePath;
585   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
586       *CompilationDir) {
587     sys::path::append(AbsolutePath, *CompilationDir);
588   }
589   sys::path::append(AbsolutePath, *DWOFileName);
590   auto DWOId = getDWOId();
591   if (!DWOId)
592     return false;
593   auto DWOContext = Context.getDWOContext(AbsolutePath);
594   if (!DWOContext)
595     return false;
596 
597   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
598   if (!DWOCU)
599     return false;
600   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
601   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
602   if (AddrOffsetSectionBase)
603     DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
604   if (getVersion() >= 5) {
605     DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
606     DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
607                                 isLittleEndian, 0);
608     if (auto TableOrError = parseListTableHeader<DWARFDebugRnglistTable>(
609             RangesDA, RangeSectionBase, Header.getFormat()))
610       DWO->RngListTable = TableOrError.get();
611     else
612       Context.getRecoverableErrorHandler()(createStringError(
613           errc::invalid_argument, "parsing a range list table: %s",
614           toString(TableOrError.takeError()).c_str()));
615 
616     if (DWO->RngListTable)
617       DWO->RangeSectionBase = DWO->RngListTable->getHeaderSize();
618   } else {
619     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
620     DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
621   }
622 
623   return true;
624 }
625 
626 void DWARFUnit::clearDIEs(bool KeepCUDie) {
627   if (DieArray.size() > (unsigned)KeepCUDie) {
628     DieArray.resize((unsigned)KeepCUDie);
629     DieArray.shrink_to_fit();
630   }
631 }
632 
633 Expected<DWARFAddressRangesVector>
634 DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
635   if (getVersion() <= 4) {
636     DWARFDebugRangeList RangeList;
637     if (Error E = extractRangeList(Offset, RangeList))
638       return std::move(E);
639     return RangeList.getAbsoluteRanges(getBaseAddress());
640   }
641   if (RngListTable) {
642     DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
643                                   isLittleEndian, RngListTable->getAddrSize());
644     auto RangeListOrError = RngListTable->findList(RangesData, Offset);
645     if (RangeListOrError)
646       return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
647     return RangeListOrError.takeError();
648   }
649 
650   return createStringError(errc::invalid_argument,
651                            "missing or invalid range list table");
652 }
653 
654 Expected<DWARFAddressRangesVector>
655 DWARFUnit::findRnglistFromIndex(uint32_t Index) {
656   if (auto Offset = getRnglistOffset(Index))
657     return findRnglistFromOffset(*Offset);
658 
659   if (RngListTable)
660     return createStringError(errc::invalid_argument,
661                              "invalid range list table index %d", Index);
662 
663   return createStringError(errc::invalid_argument,
664                            "missing or invalid range list table");
665 }
666 
667 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
668   DWARFDie UnitDie = getUnitDIE();
669   if (!UnitDie)
670     return createStringError(errc::invalid_argument, "No unit DIE");
671 
672   // First, check if unit DIE describes address ranges for the whole unit.
673   auto CUDIERangesOrError = UnitDie.getAddressRanges();
674   if (!CUDIERangesOrError)
675     return createStringError(errc::invalid_argument,
676                              "decoding address ranges: %s",
677                              toString(CUDIERangesOrError.takeError()).c_str());
678   return *CUDIERangesOrError;
679 }
680 
681 Expected<DWARFLocationExpressionsVector>
682 DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
683   DWARFLocationExpressionsVector Result;
684 
685   Error InterpretationError = Error::success();
686 
687   Error ParseError = getLocationTable().visitAbsoluteLocationList(
688       Offset, getBaseAddress(),
689       [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
690       [&](Expected<DWARFLocationExpression> L) {
691         if (L)
692           Result.push_back(std::move(*L));
693         else
694           InterpretationError =
695               joinErrors(L.takeError(), std::move(InterpretationError));
696         return !InterpretationError;
697       });
698 
699   if (ParseError || InterpretationError)
700     return joinErrors(std::move(ParseError), std::move(InterpretationError));
701 
702   return Result;
703 }
704 
705 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
706   if (Die.isSubroutineDIE()) {
707     auto DIERangesOrError = Die.getAddressRanges();
708     if (DIERangesOrError) {
709       for (const auto &R : DIERangesOrError.get()) {
710         // Ignore 0-sized ranges.
711         if (R.LowPC == R.HighPC)
712           continue;
713         auto B = AddrDieMap.upper_bound(R.LowPC);
714         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
715           // The range is a sub-range of existing ranges, we need to split the
716           // existing range.
717           if (R.HighPC < B->second.first)
718             AddrDieMap[R.HighPC] = B->second;
719           if (R.LowPC > B->first)
720             AddrDieMap[B->first].first = R.LowPC;
721         }
722         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
723       }
724     } else
725       llvm::consumeError(DIERangesOrError.takeError());
726   }
727   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
728   // simplify the logic to update AddrDieMap. The child's range will always
729   // be equal or smaller than the parent's range. With this assumption, when
730   // adding one range into the map, it will at most split a range into 3
731   // sub-ranges.
732   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
733     updateAddressDieMap(Child);
734 }
735 
736 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
737   extractDIEsIfNeeded(false);
738   if (AddrDieMap.empty())
739     updateAddressDieMap(getUnitDIE());
740   auto R = AddrDieMap.upper_bound(Address);
741   if (R == AddrDieMap.begin())
742     return DWARFDie();
743   // upper_bound's previous item contains Address.
744   --R;
745   if (Address >= R->second.first)
746     return DWARFDie();
747   return R->second.second;
748 }
749 
750 void
751 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
752                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
753   assert(InlinedChain.empty());
754   // Try to look for subprogram DIEs in the DWO file.
755   parseDWO();
756   // First, find the subroutine that contains the given address (the leaf
757   // of inlined chain).
758   DWARFDie SubroutineDIE =
759       (DWO ? *DWO : *this).getSubroutineForAddress(Address);
760 
761   if (!SubroutineDIE)
762     return;
763 
764   while (!SubroutineDIE.isSubprogramDIE()) {
765     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
766       InlinedChain.push_back(SubroutineDIE);
767     SubroutineDIE  = SubroutineDIE.getParent();
768   }
769   InlinedChain.push_back(SubroutineDIE);
770 }
771 
772 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
773                                               DWARFSectionKind Kind) {
774   if (Kind == DW_SECT_INFO)
775     return Context.getCUIndex();
776   assert(Kind == DW_SECT_EXT_TYPES);
777   return Context.getTUIndex();
778 }
779 
780 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
781   if (!Die)
782     return DWARFDie();
783   const uint32_t Depth = Die->getDepth();
784   // Unit DIEs always have a depth of zero and never have parents.
785   if (Depth == 0)
786     return DWARFDie();
787   // Depth of 1 always means parent is the compile/type unit.
788   if (Depth == 1)
789     return getUnitDIE();
790   // Look for previous DIE with a depth that is one less than the Die's depth.
791   const uint32_t ParentDepth = Depth - 1;
792   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
793     if (DieArray[I].getDepth() == ParentDepth)
794       return DWARFDie(this, &DieArray[I]);
795   }
796   return DWARFDie();
797 }
798 
799 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
800   if (!Die)
801     return DWARFDie();
802   uint32_t Depth = Die->getDepth();
803   // Unit DIEs always have a depth of zero and never have siblings.
804   if (Depth == 0)
805     return DWARFDie();
806   // NULL DIEs don't have siblings.
807   if (Die->getAbbreviationDeclarationPtr() == nullptr)
808     return DWARFDie();
809 
810   // Find the next DIE whose depth is the same as the Die's depth.
811   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
812        ++I) {
813     if (DieArray[I].getDepth() == Depth)
814       return DWARFDie(this, &DieArray[I]);
815   }
816   return DWARFDie();
817 }
818 
819 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
820   if (!Die)
821     return DWARFDie();
822   uint32_t Depth = Die->getDepth();
823   // Unit DIEs always have a depth of zero and never have siblings.
824   if (Depth == 0)
825     return DWARFDie();
826 
827   // Find the previous DIE whose depth is the same as the Die's depth.
828   for (size_t I = getDIEIndex(Die); I > 0;) {
829     --I;
830     if (DieArray[I].getDepth() == Depth - 1)
831       return DWARFDie();
832     if (DieArray[I].getDepth() == Depth)
833       return DWARFDie(this, &DieArray[I]);
834   }
835   return DWARFDie();
836 }
837 
838 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
839   if (!Die->hasChildren())
840     return DWARFDie();
841 
842   // We do not want access out of bounds when parsing corrupted debug data.
843   size_t I = getDIEIndex(Die) + 1;
844   if (I >= DieArray.size())
845     return DWARFDie();
846   return DWARFDie(this, &DieArray[I]);
847 }
848 
849 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
850   if (!Die->hasChildren())
851     return DWARFDie();
852 
853   uint32_t Depth = Die->getDepth();
854   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
855        ++I) {
856     if (DieArray[I].getDepth() == Depth + 1 &&
857         DieArray[I].getTag() == dwarf::DW_TAG_null)
858       return DWARFDie(this, &DieArray[I]);
859     assert(DieArray[I].getDepth() > Depth && "Not processing children?");
860   }
861   return DWARFDie();
862 }
863 
864 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
865   if (!Abbrevs)
866     Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
867   return Abbrevs;
868 }
869 
870 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
871   if (BaseAddr)
872     return BaseAddr;
873 
874   DWARFDie UnitDie = getUnitDIE();
875   Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
876   BaseAddr = toSectionedAddress(PC);
877   return BaseAddr;
878 }
879 
880 Expected<StrOffsetsContributionDescriptor>
881 StrOffsetsContributionDescriptor::validateContributionSize(
882     DWARFDataExtractor &DA) {
883   uint8_t EntrySize = getDwarfOffsetByteSize();
884   // In order to ensure that we don't read a partial record at the end of
885   // the section we validate for a multiple of the entry size.
886   uint64_t ValidationSize = alignTo(Size, EntrySize);
887   // Guard against overflow.
888   if (ValidationSize >= Size)
889     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
890       return *this;
891   return createStringError(errc::invalid_argument, "length exceeds section size");
892 }
893 
894 // Look for a DWARF64-formatted contribution to the string offsets table
895 // starting at a given offset and record it in a descriptor.
896 static Expected<StrOffsetsContributionDescriptor>
897 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
898   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
899     return createStringError(errc::invalid_argument, "section offset exceeds section size");
900 
901   if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
902     return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
903 
904   uint64_t Size = DA.getU64(&Offset);
905   uint8_t Version = DA.getU16(&Offset);
906   (void)DA.getU16(&Offset); // padding
907   // The encoded length includes the 2-byte version field and the 2-byte
908   // padding, so we need to subtract them out when we populate the descriptor.
909   return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
910 }
911 
912 // Look for a DWARF32-formatted contribution to the string offsets table
913 // starting at a given offset and record it in a descriptor.
914 static Expected<StrOffsetsContributionDescriptor>
915 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
916   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
917     return createStringError(errc::invalid_argument, "section offset exceeds section size");
918 
919   uint32_t ContributionSize = DA.getU32(&Offset);
920   if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
921     return createStringError(errc::invalid_argument, "invalid length");
922 
923   uint8_t Version = DA.getU16(&Offset);
924   (void)DA.getU16(&Offset); // padding
925   // The encoded length includes the 2-byte version field and the 2-byte
926   // padding, so we need to subtract them out when we populate the descriptor.
927   return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
928                                           DWARF32);
929 }
930 
931 static Expected<StrOffsetsContributionDescriptor>
932 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
933                                    llvm::dwarf::DwarfFormat Format,
934                                    uint64_t Offset) {
935   StrOffsetsContributionDescriptor Desc;
936   switch (Format) {
937   case dwarf::DwarfFormat::DWARF64: {
938     if (Offset < 16)
939       return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
940     auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
941     if (!DescOrError)
942       return DescOrError.takeError();
943     Desc = *DescOrError;
944     break;
945   }
946   case dwarf::DwarfFormat::DWARF32: {
947     if (Offset < 8)
948       return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
949     auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
950     if (!DescOrError)
951       return DescOrError.takeError();
952     Desc = *DescOrError;
953     break;
954   }
955   }
956   return Desc.validateContributionSize(DA);
957 }
958 
959 Expected<Optional<StrOffsetsContributionDescriptor>>
960 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
961   assert(!IsDWO);
962   auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
963   if (!OptOffset)
964     return None;
965   auto DescOrError =
966       parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
967   if (!DescOrError)
968     return DescOrError.takeError();
969   return *DescOrError;
970 }
971 
972 Expected<Optional<StrOffsetsContributionDescriptor>>
973 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
974   assert(IsDWO);
975   uint64_t Offset = 0;
976   auto IndexEntry = Header.getIndexEntry();
977   const auto *C =
978       IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
979   if (C)
980     Offset = C->Offset;
981   if (getVersion() >= 5) {
982     if (DA.getData().data() == nullptr)
983       return None;
984     Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
985     // Look for a valid contribution at the given offset.
986     auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
987     if (!DescOrError)
988       return DescOrError.takeError();
989     return *DescOrError;
990   }
991   // Prior to DWARF v5, we derive the contribution size from the
992   // index table (in a package file). In a .dwo file it is simply
993   // the length of the string offsets section.
994   StrOffsetsContributionDescriptor Desc;
995   if (C)
996     Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4,
997                                             Header.getFormat());
998   else if (!IndexEntry && !StringOffsetSection.Data.empty())
999     Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
1000                                             4, Header.getFormat());
1001   else
1002     return None;
1003   auto DescOrError = Desc.validateContributionSize(DA);
1004   if (!DescOrError)
1005     return DescOrError.takeError();
1006   return *DescOrError;
1007 }
1008 
1009 Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
1010   if (!RngListTable)
1011     return None;
1012   DataExtractor RangesData(RangeSection->Data, isLittleEndian,
1013                            getAddressByteSize());
1014   if (Optional<uint64_t> Off = RngListTable->getOffsetEntry(RangesData, Index))
1015     return *Off + RangeSectionBase;
1016   return None;
1017 }
1018