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