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