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