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),
507                                        DWARFListTableHeader::getHeaderSize(
508                                            Header.getFormat())));
509 
510     // In a split dwarf unit, there is no DW_AT_loclists_base attribute.
511     // Setting LocSectionBase to point past the table header.
512     if (IsDWO) {
513       auto &DWOSection = Context.getDWARFObj().getLoclistsDWOSection();
514       if (DWOSection.Data.empty())
515         return Error::success();
516       setLocSection(&DWOSection,
517                     DWARFListTableHeader::getHeaderSize(Header.getFormat()));
518     } else if (auto X = UnitDie.find(DW_AT_loclists_base)) {
519       setLocSection(&Context.getDWARFObj().getLoclistsSection(),
520                     toSectionOffset(X, 0));
521     } else {
522       return Error::success();
523     }
524 
525     if (LocSection) {
526       if (IsDWO)
527         LoclistTableHeader.emplace(".debug_loclists.dwo", "locations");
528       else
529         LoclistTableHeader.emplace(".debug_loclists", "locations");
530 
531       uint64_t HeaderSize = DWARFListTableHeader::getHeaderSize(Header.getFormat());
532       uint64_t Offset = getLocSectionBase();
533       const DWARFDataExtractor &Data = LocTable->getData();
534       if (Offset < HeaderSize)
535         return createStringError(errc::invalid_argument,
536                                  "did not detect a valid"
537                                  " list table with base = 0x%" PRIx64 "\n",
538                                  Offset);
539       Offset -= HeaderSize;
540       if (Error E = LoclistTableHeader->extract(Data, &Offset))
541         return createStringError(errc::invalid_argument,
542                                  "parsing a loclist table: " +
543                                      toString(std::move(E)));
544     }
545   }
546 
547   // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
548   // skeleton CU DIE, so that DWARF users not aware of it are not broken.
549   return Error::success();
550 }
551 
552 bool DWARFUnit::parseDWO() {
553   if (IsDWO)
554     return false;
555   if (DWO.get())
556     return false;
557   DWARFDie UnitDie = getUnitDIE();
558   if (!UnitDie)
559     return false;
560   auto DWOFileName = getVersion() >= 5
561                          ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
562                          : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
563   if (!DWOFileName)
564     return false;
565   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
566   SmallString<16> AbsolutePath;
567   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
568       *CompilationDir) {
569     sys::path::append(AbsolutePath, *CompilationDir);
570   }
571   sys::path::append(AbsolutePath, *DWOFileName);
572   auto DWOId = getDWOId();
573   if (!DWOId)
574     return false;
575   auto DWOContext = Context.getDWOContext(AbsolutePath);
576   if (!DWOContext)
577     return false;
578 
579   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
580   if (!DWOCU)
581     return false;
582   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
583   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
584   if (AddrOffsetSectionBase)
585     DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
586   if (getVersion() >= 5) {
587     DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(),
588                           DWARFListTableHeader::getHeaderSize(getFormat()));
589   } else {
590     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
591     DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
592   }
593 
594   return true;
595 }
596 
597 void DWARFUnit::clearDIEs(bool KeepCUDie) {
598   if (DieArray.size() > (unsigned)KeepCUDie) {
599     DieArray.resize((unsigned)KeepCUDie);
600     DieArray.shrink_to_fit();
601   }
602 }
603 
604 Expected<DWARFAddressRangesVector>
605 DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
606   if (getVersion() <= 4) {
607     DWARFDebugRangeList RangeList;
608     if (Error E = extractRangeList(Offset, RangeList))
609       return std::move(E);
610     return RangeList.getAbsoluteRanges(getBaseAddress());
611   }
612   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
613                                 isLittleEndian, Header.getAddressByteSize());
614   DWARFDebugRnglistTable RnglistTable;
615   auto RangeListOrError = RnglistTable.findList(RangesData, Offset);
616   if (RangeListOrError)
617     return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
618   return RangeListOrError.takeError();
619 }
620 
621 Expected<DWARFAddressRangesVector>
622 DWARFUnit::findRnglistFromIndex(uint32_t Index) {
623   if (auto Offset = getRnglistOffset(Index))
624     return findRnglistFromOffset(*Offset);
625 
626   return createStringError(errc::invalid_argument,
627                            "invalid range list table index %d (possibly "
628                            "missing the entire range list table)",
629                            Index);
630 }
631 
632 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
633   DWARFDie UnitDie = getUnitDIE();
634   if (!UnitDie)
635     return createStringError(errc::invalid_argument, "No unit DIE");
636 
637   // First, check if unit DIE describes address ranges for the whole unit.
638   auto CUDIERangesOrError = UnitDie.getAddressRanges();
639   if (!CUDIERangesOrError)
640     return createStringError(errc::invalid_argument,
641                              "decoding address ranges: %s",
642                              toString(CUDIERangesOrError.takeError()).c_str());
643   return *CUDIERangesOrError;
644 }
645 
646 Expected<DWARFLocationExpressionsVector>
647 DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
648   DWARFLocationExpressionsVector Result;
649 
650   Error InterpretationError = Error::success();
651 
652   Error ParseError = getLocationTable().visitAbsoluteLocationList(
653       Offset, getBaseAddress(),
654       [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
655       [&](Expected<DWARFLocationExpression> L) {
656         if (L)
657           Result.push_back(std::move(*L));
658         else
659           InterpretationError =
660               joinErrors(L.takeError(), std::move(InterpretationError));
661         return !InterpretationError;
662       });
663 
664   if (ParseError || InterpretationError)
665     return joinErrors(std::move(ParseError), std::move(InterpretationError));
666 
667   return Result;
668 }
669 
670 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
671   if (Die.isSubroutineDIE()) {
672     auto DIERangesOrError = Die.getAddressRanges();
673     if (DIERangesOrError) {
674       for (const auto &R : DIERangesOrError.get()) {
675         // Ignore 0-sized ranges.
676         if (R.LowPC == R.HighPC)
677           continue;
678         auto B = AddrDieMap.upper_bound(R.LowPC);
679         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
680           // The range is a sub-range of existing ranges, we need to split the
681           // existing range.
682           if (R.HighPC < B->second.first)
683             AddrDieMap[R.HighPC] = B->second;
684           if (R.LowPC > B->first)
685             AddrDieMap[B->first].first = R.LowPC;
686         }
687         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
688       }
689     } else
690       llvm::consumeError(DIERangesOrError.takeError());
691   }
692   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
693   // simplify the logic to update AddrDieMap. The child's range will always
694   // be equal or smaller than the parent's range. With this assumption, when
695   // adding one range into the map, it will at most split a range into 3
696   // sub-ranges.
697   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
698     updateAddressDieMap(Child);
699 }
700 
701 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
702   extractDIEsIfNeeded(false);
703   if (AddrDieMap.empty())
704     updateAddressDieMap(getUnitDIE());
705   auto R = AddrDieMap.upper_bound(Address);
706   if (R == AddrDieMap.begin())
707     return DWARFDie();
708   // upper_bound's previous item contains Address.
709   --R;
710   if (Address >= R->second.first)
711     return DWARFDie();
712   return R->second.second;
713 }
714 
715 void
716 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
717                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
718   assert(InlinedChain.empty());
719   // Try to look for subprogram DIEs in the DWO file.
720   parseDWO();
721   // First, find the subroutine that contains the given address (the leaf
722   // of inlined chain).
723   DWARFDie SubroutineDIE =
724       (DWO ? *DWO : *this).getSubroutineForAddress(Address);
725 
726   if (!SubroutineDIE)
727     return;
728 
729   while (!SubroutineDIE.isSubprogramDIE()) {
730     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
731       InlinedChain.push_back(SubroutineDIE);
732     SubroutineDIE  = SubroutineDIE.getParent();
733   }
734   InlinedChain.push_back(SubroutineDIE);
735 }
736 
737 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
738                                               DWARFSectionKind Kind) {
739   if (Kind == DW_SECT_INFO)
740     return Context.getCUIndex();
741   assert(Kind == DW_SECT_EXT_TYPES);
742   return Context.getTUIndex();
743 }
744 
745 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
746   if (!Die)
747     return DWARFDie();
748   const uint32_t Depth = Die->getDepth();
749   // Unit DIEs always have a depth of zero and never have parents.
750   if (Depth == 0)
751     return DWARFDie();
752   // Depth of 1 always means parent is the compile/type unit.
753   if (Depth == 1)
754     return getUnitDIE();
755   // Look for previous DIE with a depth that is one less than the Die's depth.
756   const uint32_t ParentDepth = Depth - 1;
757   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
758     if (DieArray[I].getDepth() == ParentDepth)
759       return DWARFDie(this, &DieArray[I]);
760   }
761   return DWARFDie();
762 }
763 
764 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
765   if (!Die)
766     return DWARFDie();
767   uint32_t Depth = Die->getDepth();
768   // Unit DIEs always have a depth of zero and never have siblings.
769   if (Depth == 0)
770     return DWARFDie();
771   // NULL DIEs don't have siblings.
772   if (Die->getAbbreviationDeclarationPtr() == nullptr)
773     return DWARFDie();
774 
775   // Find the next DIE whose depth is the same as the Die's depth.
776   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
777        ++I) {
778     if (DieArray[I].getDepth() == Depth)
779       return DWARFDie(this, &DieArray[I]);
780   }
781   return DWARFDie();
782 }
783 
784 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
785   if (!Die)
786     return DWARFDie();
787   uint32_t Depth = Die->getDepth();
788   // Unit DIEs always have a depth of zero and never have siblings.
789   if (Depth == 0)
790     return DWARFDie();
791 
792   // Find the previous DIE whose depth is the same as the Die's depth.
793   for (size_t I = getDIEIndex(Die); I > 0;) {
794     --I;
795     if (DieArray[I].getDepth() == Depth - 1)
796       return DWARFDie();
797     if (DieArray[I].getDepth() == Depth)
798       return DWARFDie(this, &DieArray[I]);
799   }
800   return DWARFDie();
801 }
802 
803 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
804   if (!Die->hasChildren())
805     return DWARFDie();
806 
807   // We do not want access out of bounds when parsing corrupted debug data.
808   size_t I = getDIEIndex(Die) + 1;
809   if (I >= DieArray.size())
810     return DWARFDie();
811   return DWARFDie(this, &DieArray[I]);
812 }
813 
814 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
815   if (!Die->hasChildren())
816     return DWARFDie();
817 
818   uint32_t Depth = Die->getDepth();
819   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
820        ++I) {
821     if (DieArray[I].getDepth() == Depth + 1 &&
822         DieArray[I].getTag() == dwarf::DW_TAG_null)
823       return DWARFDie(this, &DieArray[I]);
824     assert(DieArray[I].getDepth() > Depth && "Not processing children?");
825   }
826   return DWARFDie();
827 }
828 
829 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
830   if (!Abbrevs)
831     Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
832   return Abbrevs;
833 }
834 
835 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
836   if (BaseAddr)
837     return BaseAddr;
838 
839   DWARFDie UnitDie = getUnitDIE();
840   Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
841   BaseAddr = toSectionedAddress(PC);
842   return BaseAddr;
843 }
844 
845 Expected<StrOffsetsContributionDescriptor>
846 StrOffsetsContributionDescriptor::validateContributionSize(
847     DWARFDataExtractor &DA) {
848   uint8_t EntrySize = getDwarfOffsetByteSize();
849   // In order to ensure that we don't read a partial record at the end of
850   // the section we validate for a multiple of the entry size.
851   uint64_t ValidationSize = alignTo(Size, EntrySize);
852   // Guard against overflow.
853   if (ValidationSize >= Size)
854     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
855       return *this;
856   return createStringError(errc::invalid_argument, "length exceeds section size");
857 }
858 
859 // Look for a DWARF64-formatted contribution to the string offsets table
860 // starting at a given offset and record it in a descriptor.
861 static Expected<StrOffsetsContributionDescriptor>
862 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
863   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
864     return createStringError(errc::invalid_argument, "section offset exceeds section size");
865 
866   if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
867     return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
868 
869   uint64_t Size = DA.getU64(&Offset);
870   uint8_t Version = DA.getU16(&Offset);
871   (void)DA.getU16(&Offset); // padding
872   // The encoded length includes the 2-byte version field and the 2-byte
873   // padding, so we need to subtract them out when we populate the descriptor.
874   return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
875 }
876 
877 // Look for a DWARF32-formatted contribution to the string offsets table
878 // starting at a given offset and record it in a descriptor.
879 static Expected<StrOffsetsContributionDescriptor>
880 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
881   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
882     return createStringError(errc::invalid_argument, "section offset exceeds section size");
883 
884   uint32_t ContributionSize = DA.getU32(&Offset);
885   if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
886     return createStringError(errc::invalid_argument, "invalid length");
887 
888   uint8_t Version = DA.getU16(&Offset);
889   (void)DA.getU16(&Offset); // padding
890   // The encoded length includes the 2-byte version field and the 2-byte
891   // padding, so we need to subtract them out when we populate the descriptor.
892   return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
893                                           DWARF32);
894 }
895 
896 static Expected<StrOffsetsContributionDescriptor>
897 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
898                                    llvm::dwarf::DwarfFormat Format,
899                                    uint64_t Offset) {
900   StrOffsetsContributionDescriptor Desc;
901   switch (Format) {
902   case dwarf::DwarfFormat::DWARF64: {
903     if (Offset < 16)
904       return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
905     auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
906     if (!DescOrError)
907       return DescOrError.takeError();
908     Desc = *DescOrError;
909     break;
910   }
911   case dwarf::DwarfFormat::DWARF32: {
912     if (Offset < 8)
913       return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
914     auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
915     if (!DescOrError)
916       return DescOrError.takeError();
917     Desc = *DescOrError;
918     break;
919   }
920   }
921   return Desc.validateContributionSize(DA);
922 }
923 
924 Expected<Optional<StrOffsetsContributionDescriptor>>
925 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
926   assert(!IsDWO);
927   auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
928   if (!OptOffset)
929     return None;
930   auto DescOrError =
931       parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
932   if (!DescOrError)
933     return DescOrError.takeError();
934   return *DescOrError;
935 }
936 
937 Expected<Optional<StrOffsetsContributionDescriptor>>
938 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
939   assert(IsDWO);
940   uint64_t Offset = 0;
941   auto IndexEntry = Header.getIndexEntry();
942   const auto *C =
943       IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
944   if (C)
945     Offset = C->Offset;
946   if (getVersion() >= 5) {
947     if (DA.getData().data() == nullptr)
948       return None;
949     Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
950     // Look for a valid contribution at the given offset.
951     auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
952     if (!DescOrError)
953       return DescOrError.takeError();
954     return *DescOrError;
955   }
956   // Prior to DWARF v5, we derive the contribution size from the
957   // index table (in a package file). In a .dwo file it is simply
958   // the length of the string offsets section.
959   StrOffsetsContributionDescriptor Desc;
960   if (C)
961     Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4,
962                                             Header.getFormat());
963   else if (!IndexEntry && !StringOffsetSection.Data.empty())
964     Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
965                                             4, Header.getFormat());
966   else
967     return None;
968   auto DescOrError = Desc.validateContributionSize(DA);
969   if (!DescOrError)
970     return DescOrError.takeError();
971   return *DescOrError;
972 }
973 
974 Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
975   DataExtractor RangesData(RangeSection->Data, isLittleEndian,
976                            getAddressByteSize());
977   DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
978                               isLittleEndian, 0);
979   if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
980           RangesData, RangeSectionBase, getFormat(), Index))
981     return *Off + RangeSectionBase;
982   return None;
983 }
984