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