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