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