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