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