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.getRangeSection(),
41                &D.getLocSection(), D.getStringSection(),
42                D.getStringOffsetSection(), &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.getRangeDWOSection(),
53                &D.getLocDWOSection(), D.getStringDWOSection(),
54                D.getStringOffsetDWOSection(), &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](uint32_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 = llvm::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
87                                              RS, LocSection, SS, SOS, AOS, LS,
88                                              LE, IsDWO, *this);
89       else
90         U = llvm::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   uint32_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(uint32_t Offset) const {
130   auto end = begin() + getNumInfoUnits();
131   auto *CU =
132       std::upper_bound(begin(), end, Offset,
133                        [](uint32_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                        [](uint32_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), LocSection(LocSection), LineSection(LS),
179       StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
180       isLittleEndian(LE), IsDWO(IsDWO), UnitVector(UnitVector) {
181   clear();
182   // For split DWARF we only need to keep track of the location list section's
183   // data (no relocations), and if we are reading a package file, we need to
184   // adjust the location list data based on the index entries.
185   if (IsDWO) {
186     LocSectionData = LocSection->Data;
187     if (auto *IndexEntry = Header.getIndexEntry())
188       if (const auto *C = IndexEntry->getOffset(DW_SECT_LOC))
189         LocSectionData = LocSectionData.substr(C->Offset, C->Length);
190   }
191 }
192 
193 DWARFUnit::~DWARFUnit() = default;
194 
195 DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
196   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
197                             getAddressByteSize());
198 }
199 
200 Optional<object::SectionedAddress>
201 DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
202   if (IsDWO) {
203     auto R = Context.info_section_units();
204     auto I = R.begin();
205     // Surprising if a DWO file has more than one skeleton unit in it - this
206     // probably shouldn't be valid, but if a use case is found, here's where to
207     // support it (probably have to linearly search for the matching skeleton CU
208     // here)
209     if (I != R.end() && std::next(I) == R.end())
210       return (*I)->getAddrOffsetSectionItem(Index);
211   }
212   uint32_t Offset = AddrOffsetSectionBase + Index * getAddressByteSize();
213   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
214     return None;
215   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
216                         isLittleEndian, getAddressByteSize());
217   uint64_t Section;
218   uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
219   return {{Address, Section}};
220 }
221 
222 Optional<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
223   if (!StringOffsetsTableContribution)
224     return None;
225   unsigned ItemSize = getDwarfStringOffsetsByteSize();
226   uint32_t Offset = getStringOffsetsBase() + Index * ItemSize;
227   if (StringOffsetSection.Data.size() < Offset + ItemSize)
228     return None;
229   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
230                         isLittleEndian, 0);
231   return DA.getRelocatedValue(ItemSize, &Offset);
232 }
233 
234 bool DWARFUnitHeader::extract(DWARFContext &Context,
235                               const DWARFDataExtractor &debug_info,
236                               uint32_t *offset_ptr,
237                               DWARFSectionKind SectionKind,
238                               const DWARFUnitIndex *Index,
239                               const DWARFUnitIndex::Entry *Entry) {
240   Offset = *offset_ptr;
241   IndexEntry = Entry;
242   if (!IndexEntry && Index)
243     IndexEntry = Index->getFromOffset(*offset_ptr);
244   Length = debug_info.getU32(offset_ptr);
245   // FIXME: Support DWARF64.
246   unsigned SizeOfLength = 4;
247   FormParams.Format = DWARF32;
248   FormParams.Version = debug_info.getU16(offset_ptr);
249   if (FormParams.Version >= 5) {
250     UnitType = debug_info.getU8(offset_ptr);
251     FormParams.AddrSize = debug_info.getU8(offset_ptr);
252     AbbrOffset = debug_info.getU32(offset_ptr);
253   } else {
254     AbbrOffset = debug_info.getRelocatedValue(4, offset_ptr);
255     FormParams.AddrSize = debug_info.getU8(offset_ptr);
256     // Fake a unit type based on the section type.  This isn't perfect,
257     // but distinguishing compile and type units is generally enough.
258     if (SectionKind == DW_SECT_TYPES)
259       UnitType = DW_UT_type;
260     else
261       UnitType = DW_UT_compile;
262   }
263   if (IndexEntry) {
264     if (AbbrOffset)
265       return false;
266     auto *UnitContrib = IndexEntry->getOffset();
267     if (!UnitContrib || UnitContrib->Length != (Length + 4))
268       return false;
269     auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
270     if (!AbbrEntry)
271       return false;
272     AbbrOffset = AbbrEntry->Offset;
273   }
274   if (isTypeUnit()) {
275     TypeHash = debug_info.getU64(offset_ptr);
276     TypeOffset = debug_info.getU32(offset_ptr);
277   } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
278     DWOId = debug_info.getU64(offset_ptr);
279 
280   // Header fields all parsed, capture the size of this unit header.
281   assert(*offset_ptr - Offset <= 255 && "unexpected header size");
282   Size = uint8_t(*offset_ptr - Offset);
283 
284   // Type offset is unit-relative; should be after the header and before
285   // the end of the current unit.
286   bool TypeOffsetOK =
287       !isTypeUnit()
288           ? true
289           : TypeOffset >= Size && TypeOffset < getLength() + SizeOfLength;
290   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
291   bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
292   bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8;
293 
294   if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK)
295     return false;
296 
297   // Keep track of the highest DWARF version we encounter across all units.
298   Context.setMaxVersionIfGreater(getVersion());
299   return true;
300 }
301 
302 // Parse the rangelist table header, including the optional array of offsets
303 // following it (DWARF v5 and later).
304 static Expected<DWARFDebugRnglistTable>
305 parseRngListTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
306   // TODO: Support DWARF64
307   // We are expected to be called with Offset 0 or pointing just past the table
308   // header, which is 12 bytes long for DWARF32.
309   if (Offset > 0) {
310     if (Offset < 12U)
311       return createStringError(errc::invalid_argument, "Did not detect a valid"
312                                " range list table with base = 0x%" PRIu32,
313                                Offset);
314     Offset -= 12U;
315   }
316   llvm::DWARFDebugRnglistTable Table;
317   if (Error E = Table.extractHeaderAndOffsets(DA, &Offset))
318     return std::move(E);
319   return Table;
320 }
321 
322 Error DWARFUnit::extractRangeList(uint32_t RangeListOffset,
323                                   DWARFDebugRangeList &RangeList) const {
324   // Require that compile unit is extracted.
325   assert(!DieArray.empty());
326   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
327                                 isLittleEndian, getAddressByteSize());
328   uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
329   return RangeList.extract(RangesData, &ActualRangeListOffset);
330 }
331 
332 void DWARFUnit::clear() {
333   Abbrevs = nullptr;
334   BaseAddr.reset();
335   RangeSectionBase = 0;
336   AddrOffsetSectionBase = 0;
337   clearDIEs(false);
338   DWO.reset();
339 }
340 
341 const char *DWARFUnit::getCompilationDir() {
342   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
343 }
344 
345 void DWARFUnit::extractDIEsToVector(
346     bool AppendCUDie, bool AppendNonCUDies,
347     std::vector<DWARFDebugInfoEntry> &Dies) const {
348   if (!AppendCUDie && !AppendNonCUDies)
349     return;
350 
351   // Set the offset to that of the first DIE and calculate the start of the
352   // next compilation unit header.
353   uint32_t DIEOffset = getOffset() + getHeaderSize();
354   uint32_t NextCUOffset = getNextUnitOffset();
355   DWARFDebugInfoEntry DIE;
356   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
357   uint32_t Depth = 0;
358   bool IsCUDie = true;
359 
360   while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
361                          Depth)) {
362     if (IsCUDie) {
363       if (AppendCUDie)
364         Dies.push_back(DIE);
365       if (!AppendNonCUDies)
366         break;
367       // The average bytes per DIE entry has been seen to be
368       // around 14-20 so let's pre-reserve the needed memory for
369       // our DIE entries accordingly.
370       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
371       IsCUDie = false;
372     } else {
373       Dies.push_back(DIE);
374     }
375 
376     if (const DWARFAbbreviationDeclaration *AbbrDecl =
377             DIE.getAbbreviationDeclarationPtr()) {
378       // Normal DIE
379       if (AbbrDecl->hasChildren())
380         ++Depth;
381     } else {
382       // NULL DIE.
383       if (Depth > 0)
384         --Depth;
385       if (Depth == 0)
386         break;  // We are done with this compile unit!
387     }
388   }
389 
390   // Give a little bit of info if we encounter corrupt DWARF (our offset
391   // should always terminate at or before the start of the next compilation
392   // unit header).
393   if (DIEOffset > NextCUOffset)
394     WithColor::warning() << format("DWARF compile unit extends beyond its "
395                                    "bounds cu 0x%8.8x at 0x%8.8x\n",
396                                    getOffset(), DIEOffset);
397 }
398 
399 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
400   if ((CUDieOnly && !DieArray.empty()) ||
401       DieArray.size() > 1)
402     return 0; // Already parsed.
403 
404   bool HasCUDie = !DieArray.empty();
405   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
406 
407   if (DieArray.empty())
408     return 0;
409 
410   // If CU DIE was just parsed, copy several attribute values from it.
411   if (!HasCUDie) {
412     DWARFDie UnitDie = getUnitDIE();
413     if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
414       Header.setDWOId(*DWOId);
415     if (!IsDWO) {
416       assert(AddrOffsetSectionBase == 0);
417       assert(RangeSectionBase == 0);
418       AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base), 0);
419       if (!AddrOffsetSectionBase)
420         AddrOffsetSectionBase =
421             toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
422       RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
423     }
424 
425     // In general, in DWARF v5 and beyond we derive the start of the unit's
426     // contribution to the string offsets table from the unit DIE's
427     // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
428     // attribute, so we assume that there is a contribution to the string
429     // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
430     // In both cases we need to determine the format of the contribution,
431     // which may differ from the unit's format.
432     DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
433                           isLittleEndian, 0);
434     if (IsDWO)
435       StringOffsetsTableContribution =
436           determineStringOffsetsTableContributionDWO(DA);
437     else if (getVersion() >= 5)
438       StringOffsetsTableContribution =
439           determineStringOffsetsTableContribution(DA);
440 
441     // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
442     // describe address ranges.
443     if (getVersion() >= 5) {
444       if (IsDWO)
445         setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
446       else
447         setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
448                          toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0));
449       if (RangeSection->Data.size()) {
450         // Parse the range list table header. Individual range lists are
451         // extracted lazily.
452         DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
453                                     isLittleEndian, 0);
454         if (auto TableOrError =
455                 parseRngListTableHeader(RangesDA, RangeSectionBase))
456           RngListTable = TableOrError.get();
457         else
458           WithColor::error() << "parsing a range list table: "
459                              << toString(TableOrError.takeError())
460                              << '\n';
461 
462         // In a split dwarf unit, there is no DW_AT_rnglists_base attribute.
463         // Adjust RangeSectionBase to point past the table header.
464         if (IsDWO && RngListTable)
465           RangeSectionBase = RngListTable->getHeaderSize();
466       }
467     }
468 
469     // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
470     // skeleton CU DIE, so that DWARF users not aware of it are not broken.
471     }
472 
473   return DieArray.size();
474 }
475 
476 bool DWARFUnit::parseDWO() {
477   if (IsDWO)
478     return false;
479   if (DWO.get())
480     return false;
481   DWARFDie UnitDie = getUnitDIE();
482   if (!UnitDie)
483     return false;
484   auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
485   if (!DWOFileName)
486     return false;
487   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
488   SmallString<16> AbsolutePath;
489   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
490       *CompilationDir) {
491     sys::path::append(AbsolutePath, *CompilationDir);
492   }
493   sys::path::append(AbsolutePath, *DWOFileName);
494   auto DWOId = getDWOId();
495   if (!DWOId)
496     return false;
497   auto DWOContext = Context.getDWOContext(AbsolutePath);
498   if (!DWOContext)
499     return false;
500 
501   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
502   if (!DWOCU)
503     return false;
504   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
505   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
506   DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
507   if (getVersion() >= 5) {
508     DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
509     DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
510                                 isLittleEndian, 0);
511     if (auto TableOrError = parseRngListTableHeader(RangesDA, RangeSectionBase))
512       DWO->RngListTable = TableOrError.get();
513     else
514       WithColor::error() << "parsing a range list table: "
515                          << toString(TableOrError.takeError())
516                          << '\n';
517     if (DWO->RngListTable)
518       DWO->RangeSectionBase = DWO->RngListTable->getHeaderSize();
519   } else {
520     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
521     DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
522   }
523 
524   return true;
525 }
526 
527 void DWARFUnit::clearDIEs(bool KeepCUDie) {
528   if (DieArray.size() > (unsigned)KeepCUDie) {
529     DieArray.resize((unsigned)KeepCUDie);
530     DieArray.shrink_to_fit();
531   }
532 }
533 
534 Expected<DWARFAddressRangesVector>
535 DWARFUnit::findRnglistFromOffset(uint32_t Offset) {
536   if (getVersion() <= 4) {
537     DWARFDebugRangeList RangeList;
538     if (Error E = extractRangeList(Offset, RangeList))
539       return std::move(E);
540     return RangeList.getAbsoluteRanges(getBaseAddress());
541   }
542   if (RngListTable) {
543     DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
544                                   isLittleEndian, RngListTable->getAddrSize());
545     auto RangeListOrError = RngListTable->findList(RangesData, Offset);
546     if (RangeListOrError)
547       return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
548     return RangeListOrError.takeError();
549   }
550 
551   return createStringError(errc::invalid_argument,
552                            "missing or invalid range list table");
553 }
554 
555 Expected<DWARFAddressRangesVector>
556 DWARFUnit::findRnglistFromIndex(uint32_t Index) {
557   if (auto Offset = getRnglistOffset(Index))
558     return findRnglistFromOffset(*Offset + RangeSectionBase);
559 
560   if (RngListTable)
561     return createStringError(errc::invalid_argument,
562                              "invalid range list table index %d", Index);
563   else
564     return createStringError(errc::invalid_argument,
565                              "missing or invalid range list table");
566 }
567 
568 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
569   DWARFDie UnitDie = getUnitDIE();
570   if (!UnitDie)
571     return createStringError(errc::invalid_argument, "No unit DIE");
572 
573   // First, check if unit DIE describes address ranges for the whole unit.
574   auto CUDIERangesOrError = UnitDie.getAddressRanges();
575   if (!CUDIERangesOrError)
576     return createStringError(errc::invalid_argument,
577                              "decoding address ranges: %s",
578                              toString(CUDIERangesOrError.takeError()).c_str());
579   return *CUDIERangesOrError;
580 }
581 
582 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
583   if (Die.isSubroutineDIE()) {
584     auto DIERangesOrError = Die.getAddressRanges();
585     if (DIERangesOrError) {
586       for (const auto &R : DIERangesOrError.get()) {
587         // Ignore 0-sized ranges.
588         if (R.LowPC == R.HighPC)
589           continue;
590         auto B = AddrDieMap.upper_bound(R.LowPC);
591         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
592           // The range is a sub-range of existing ranges, we need to split the
593           // existing range.
594           if (R.HighPC < B->second.first)
595             AddrDieMap[R.HighPC] = B->second;
596           if (R.LowPC > B->first)
597             AddrDieMap[B->first].first = R.LowPC;
598         }
599         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
600       }
601     } else
602       llvm::consumeError(DIERangesOrError.takeError());
603   }
604   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
605   // simplify the logic to update AddrDieMap. The child's range will always
606   // be equal or smaller than the parent's range. With this assumption, when
607   // adding one range into the map, it will at most split a range into 3
608   // sub-ranges.
609   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
610     updateAddressDieMap(Child);
611 }
612 
613 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
614   extractDIEsIfNeeded(false);
615   if (AddrDieMap.empty())
616     updateAddressDieMap(getUnitDIE());
617   auto R = AddrDieMap.upper_bound(Address);
618   if (R == AddrDieMap.begin())
619     return DWARFDie();
620   // upper_bound's previous item contains Address.
621   --R;
622   if (Address >= R->second.first)
623     return DWARFDie();
624   return R->second.second;
625 }
626 
627 void
628 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
629                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
630   assert(InlinedChain.empty());
631   // Try to look for subprogram DIEs in the DWO file.
632   parseDWO();
633   // First, find the subroutine that contains the given address (the leaf
634   // of inlined chain).
635   DWARFDie SubroutineDIE =
636       (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
637 
638   if (!SubroutineDIE)
639     return;
640 
641   while (!SubroutineDIE.isSubprogramDIE()) {
642     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
643       InlinedChain.push_back(SubroutineDIE);
644     SubroutineDIE  = SubroutineDIE.getParent();
645   }
646   InlinedChain.push_back(SubroutineDIE);
647 }
648 
649 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
650                                               DWARFSectionKind Kind) {
651   if (Kind == DW_SECT_INFO)
652     return Context.getCUIndex();
653   assert(Kind == DW_SECT_TYPES);
654   return Context.getTUIndex();
655 }
656 
657 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
658   if (!Die)
659     return DWARFDie();
660   const uint32_t Depth = Die->getDepth();
661   // Unit DIEs always have a depth of zero and never have parents.
662   if (Depth == 0)
663     return DWARFDie();
664   // Depth of 1 always means parent is the compile/type unit.
665   if (Depth == 1)
666     return getUnitDIE();
667   // Look for previous DIE with a depth that is one less than the Die's depth.
668   const uint32_t ParentDepth = Depth - 1;
669   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
670     if (DieArray[I].getDepth() == ParentDepth)
671       return DWARFDie(this, &DieArray[I]);
672   }
673   return DWARFDie();
674 }
675 
676 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
677   if (!Die)
678     return DWARFDie();
679   uint32_t Depth = Die->getDepth();
680   // Unit DIEs always have a depth of zero and never have siblings.
681   if (Depth == 0)
682     return DWARFDie();
683   // NULL DIEs don't have siblings.
684   if (Die->getAbbreviationDeclarationPtr() == nullptr)
685     return DWARFDie();
686 
687   // Find the next DIE whose depth is the same as the Die's depth.
688   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
689        ++I) {
690     if (DieArray[I].getDepth() == Depth)
691       return DWARFDie(this, &DieArray[I]);
692   }
693   return DWARFDie();
694 }
695 
696 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
697   if (!Die)
698     return DWARFDie();
699   uint32_t Depth = Die->getDepth();
700   // Unit DIEs always have a depth of zero and never have siblings.
701   if (Depth == 0)
702     return DWARFDie();
703 
704   // Find the previous DIE whose depth is the same as the Die's depth.
705   for (size_t I = getDIEIndex(Die); I > 0;) {
706     --I;
707     if (DieArray[I].getDepth() == Depth - 1)
708       return DWARFDie();
709     if (DieArray[I].getDepth() == Depth)
710       return DWARFDie(this, &DieArray[I]);
711   }
712   return DWARFDie();
713 }
714 
715 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
716   if (!Die->hasChildren())
717     return DWARFDie();
718 
719   // We do not want access out of bounds when parsing corrupted debug data.
720   size_t I = getDIEIndex(Die) + 1;
721   if (I >= DieArray.size())
722     return DWARFDie();
723   return DWARFDie(this, &DieArray[I]);
724 }
725 
726 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
727   if (!Die->hasChildren())
728     return DWARFDie();
729 
730   uint32_t Depth = Die->getDepth();
731   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
732        ++I) {
733     if (DieArray[I].getDepth() == Depth + 1 &&
734         DieArray[I].getTag() == dwarf::DW_TAG_null)
735       return DWARFDie(this, &DieArray[I]);
736     assert(DieArray[I].getDepth() > Depth && "Not processing children?");
737   }
738   return DWARFDie();
739 }
740 
741 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
742   if (!Abbrevs)
743     Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
744   return Abbrevs;
745 }
746 
747 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
748   if (BaseAddr)
749     return BaseAddr;
750 
751   DWARFDie UnitDie = getUnitDIE();
752   Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
753   BaseAddr = toSectionedAddress(PC);
754   return BaseAddr;
755 }
756 
757 Optional<StrOffsetsContributionDescriptor>
758 StrOffsetsContributionDescriptor::validateContributionSize(
759     DWARFDataExtractor &DA) {
760   uint8_t EntrySize = getDwarfOffsetByteSize();
761   // In order to ensure that we don't read a partial record at the end of
762   // the section we validate for a multiple of the entry size.
763   uint64_t ValidationSize = alignTo(Size, EntrySize);
764   // Guard against overflow.
765   if (ValidationSize >= Size)
766     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
767       return *this;
768   return None;
769 }
770 
771 // Look for a DWARF64-formatted contribution to the string offsets table
772 // starting at a given offset and record it in a descriptor.
773 static Optional<StrOffsetsContributionDescriptor>
774 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
775   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
776     return None;
777 
778   if (DA.getU32(&Offset) != 0xffffffff)
779     return None;
780 
781   uint64_t Size = DA.getU64(&Offset);
782   uint8_t Version = DA.getU16(&Offset);
783   (void)DA.getU16(&Offset); // padding
784   // The encoded length includes the 2-byte version field and the 2-byte
785   // padding, so we need to subtract them out when we populate the descriptor.
786   return {{Offset, Size - 4, Version, DWARF64}};
787 }
788 
789 // Look for a DWARF32-formatted contribution to the string offsets table
790 // starting at a given offset and record it in a descriptor.
791 static Optional<StrOffsetsContributionDescriptor>
792 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
793   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
794     return None;
795   uint32_t ContributionSize = DA.getU32(&Offset);
796   if (ContributionSize >= 0xfffffff0)
797     return None;
798   uint8_t Version = DA.getU16(&Offset);
799   (void)DA.getU16(&Offset); // padding
800   // The encoded length includes the 2-byte version field and the 2-byte
801   // padding, so we need to subtract them out when we populate the descriptor.
802   return {{Offset, ContributionSize - 4, Version, DWARF32}};
803 }
804 
805 Optional<StrOffsetsContributionDescriptor>
806 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
807   auto Offset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base), 0);
808   Optional<StrOffsetsContributionDescriptor> Descriptor;
809   // Attempt to find a DWARF64 contribution 16 bytes before the base.
810   if (Offset >= 16)
811     Descriptor =
812         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset - 16);
813   // Try to find a DWARF32 contribution 8 bytes before the base.
814   if (!Descriptor && Offset >= 8)
815     Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset - 8);
816   return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
817 }
818 
819 Optional<StrOffsetsContributionDescriptor>
820 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
821   uint64_t Offset = 0;
822   auto IndexEntry = Header.getIndexEntry();
823   const auto *C =
824       IndexEntry ? IndexEntry->getOffset(DW_SECT_STR_OFFSETS) : nullptr;
825   if (C)
826     Offset = C->Offset;
827   if (getVersion() >= 5) {
828     // Look for a valid contribution at the given offset.
829     auto Descriptor =
830         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset);
831     if (!Descriptor)
832       Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset);
833     return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
834   }
835   // Prior to DWARF v5, we derive the contribution size from the
836   // index table (in a package file). In a .dwo file it is simply
837   // the length of the string offsets section.
838   if (!IndexEntry)
839     return {{0, StringOffsetSection.Data.size(), 4, DWARF32}};
840   if (C)
841     return {{C->Offset, C->Length, 4, DWARF32}};
842   return None;
843 }
844