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