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/DWARFDebugLoc.h"
18 #include "llvm/DebugInfo/DWARF/DWARFDebugRangeList.h"
19 #include "llvm/DebugInfo/DWARF/DWARFDebugRnglists.h"
20 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
21 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
22 #include "llvm/DebugInfo/DWARF/DWARFListTable.h"
23 #include "llvm/DebugInfo/DWARF/DWARFObject.h"
24 #include "llvm/DebugInfo/DWARF/DWARFSection.h"
25 #include "llvm/DebugInfo/DWARF/DWARFTypeUnit.h"
26 #include "llvm/Support/DataExtractor.h"
27 #include "llvm/Support/Errc.h"
28 #include "llvm/Support/Path.h"
29 #include <algorithm>
30 #include <cassert>
31 #include <cstddef>
32 #include <cstdint>
33 #include <utility>
34 #include <vector>
35 
36 using namespace llvm;
37 using namespace dwarf;
38 
39 void DWARFUnitVector::addUnitsForSection(DWARFContext &C,
40                                          const DWARFSection &Section,
41                                          DWARFSectionKind SectionKind) {
42   const DWARFObject &D = C.getDWARFObj();
43   addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangesSection(),
44                &D.getLocSection(), D.getStrSection(),
45                D.getStrOffsetsSection(), &D.getAddrSection(),
46                D.getLineSection(), D.isLittleEndian(), false, false,
47                SectionKind);
48 }
49 
50 void DWARFUnitVector::addUnitsForDWOSection(DWARFContext &C,
51                                             const DWARFSection &DWOSection,
52                                             DWARFSectionKind SectionKind,
53                                             bool Lazy) {
54   const DWARFObject &D = C.getDWARFObj();
55   addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangesDWOSection(),
56                &D.getLocDWOSection(), D.getStrDWOSection(),
57                D.getStrOffsetsDWOSection(), &D.getAddrSection(),
58                D.getLineDWOSection(), C.isLittleEndian(), true, Lazy,
59                SectionKind);
60 }
61 
62 void DWARFUnitVector::addUnitsImpl(
63     DWARFContext &Context, const DWARFObject &Obj, const DWARFSection &Section,
64     const DWARFDebugAbbrev *DA, const DWARFSection *RS,
65     const DWARFSection *LocSection, StringRef SS, const DWARFSection &SOS,
66     const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO,
67     bool Lazy, DWARFSectionKind SectionKind) {
68   DWARFDataExtractor Data(Obj, Section, LE, 0);
69   // Lazy initialization of Parser, now that we have all section info.
70   if (!Parser) {
71     Parser = [=, &Context, &Obj, &Section, &SOS,
72               &LS](uint64_t Offset, DWARFSectionKind SectionKind,
73                    const DWARFSection *CurSection,
74                    const DWARFUnitIndex::Entry *IndexEntry)
75         -> std::unique_ptr<DWARFUnit> {
76       const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
77       DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
78       if (!Data.isValidOffset(Offset))
79         return nullptr;
80       DWARFUnitHeader Header;
81       if (!Header.extract(Context, Data, &Offset, SectionKind))
82         return nullptr;
83       if (!IndexEntry && IsDWO) {
84         const DWARFUnitIndex &Index = getDWARFUnitIndex(
85             Context, Header.isTypeUnit() ? DW_SECT_EXT_TYPES : DW_SECT_INFO);
86         if (Index) {
87           if (Header.isTypeUnit())
88             IndexEntry = Index.getFromHash(Header.getTypeHash());
89           else if (auto DWOId = Header.getDWOId())
90             IndexEntry = Index.getFromHash(*DWOId);
91         }
92         if (!IndexEntry)
93           IndexEntry = Index.getFromOffset(Header.getOffset());
94       }
95       if (IndexEntry && !Header.applyIndexEntry(IndexEntry))
96         return nullptr;
97       std::unique_ptr<DWARFUnit> U;
98       if (Header.isTypeUnit())
99         U = std::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
100                                              RS, LocSection, SS, SOS, AOS, LS,
101                                              LE, IsDWO, *this);
102       else
103         U = std::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
104                                                 DA, RS, LocSection, SS, SOS,
105                                                 AOS, LS, LE, IsDWO, *this);
106       return U;
107     };
108   }
109   if (Lazy)
110     return;
111   // Find a reasonable insertion point within the vector.  We skip over
112   // (a) units from a different section, (b) units from the same section
113   // but with lower offset-within-section.  This keeps units in order
114   // within a section, although not necessarily within the object file,
115   // even if we do lazy parsing.
116   auto I = this->begin();
117   uint64_t Offset = 0;
118   while (Data.isValidOffset(Offset)) {
119     if (I != this->end() &&
120         (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
121       ++I;
122       continue;
123     }
124     auto U = Parser(Offset, SectionKind, &Section, nullptr);
125     // If parsing failed, we're done with this section.
126     if (!U)
127       break;
128     Offset = U->getNextUnitOffset();
129     I = std::next(this->insert(I, std::move(U)));
130   }
131 }
132 
133 DWARFUnit *DWARFUnitVector::addUnit(std::unique_ptr<DWARFUnit> Unit) {
134   auto I = std::upper_bound(begin(), end(), Unit,
135                             [](const std::unique_ptr<DWARFUnit> &LHS,
136                                const std::unique_ptr<DWARFUnit> &RHS) {
137                               return LHS->getOffset() < RHS->getOffset();
138                             });
139   return this->insert(I, std::move(Unit))->get();
140 }
141 
142 DWARFUnit *DWARFUnitVector::getUnitForOffset(uint64_t Offset) const {
143   auto end = begin() + getNumInfoUnits();
144   auto *CU =
145       std::upper_bound(begin(), end, Offset,
146                        [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
147                          return LHS < RHS->getNextUnitOffset();
148                        });
149   if (CU != end && (*CU)->getOffset() <= Offset)
150     return CU->get();
151   return nullptr;
152 }
153 
154 DWARFUnit *
155 DWARFUnitVector::getUnitForIndexEntry(const DWARFUnitIndex::Entry &E) {
156   const auto *CUOff = E.getContribution(DW_SECT_INFO);
157   if (!CUOff)
158     return nullptr;
159 
160   auto Offset = CUOff->Offset;
161   auto end = begin() + getNumInfoUnits();
162 
163   auto *CU =
164       std::upper_bound(begin(), end, CUOff->Offset,
165                        [](uint64_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
166                          return LHS < RHS->getNextUnitOffset();
167                        });
168   if (CU != end && (*CU)->getOffset() <= Offset)
169     return CU->get();
170 
171   if (!Parser)
172     return nullptr;
173 
174   auto U = Parser(Offset, DW_SECT_INFO, nullptr, &E);
175   if (!U)
176     U = nullptr;
177 
178   auto *NewCU = U.get();
179   this->insert(CU, std::move(U));
180   ++NumInfoUnits;
181   return NewCU;
182 }
183 
184 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
185                      const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA,
186                      const DWARFSection *RS, const DWARFSection *LocSection,
187                      StringRef SS, const DWARFSection &SOS,
188                      const DWARFSection *AOS, const DWARFSection &LS, bool LE,
189                      bool IsDWO, const DWARFUnitVector &UnitVector)
190     : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
191       RangeSection(RS), LineSection(LS), StringSection(SS),
192       StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE),
193       IsDWO(IsDWO), UnitVector(UnitVector) {
194   clear();
195 }
196 
197 DWARFUnit::~DWARFUnit() = default;
198 
199 DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
200   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
201                             getAddressByteSize());
202 }
203 
204 Optional<object::SectionedAddress>
205 DWARFUnit::getAddrOffsetSectionItem(uint32_t Index) const {
206   if (!AddrOffsetSectionBase) {
207     auto R = Context.info_section_units();
208     // Surprising if a DWO file has more than one skeleton unit in it - this
209     // probably shouldn't be valid, but if a use case is found, here's where to
210     // support it (probably have to linearly search for the matching skeleton CU
211     // here)
212     if (IsDWO && hasSingleElement(R))
213       return (*R.begin())->getAddrOffsetSectionItem(Index);
214 
215     return None;
216   }
217 
218   uint64_t Offset = *AddrOffsetSectionBase + Index * getAddressByteSize();
219   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
220     return None;
221   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
222                         isLittleEndian, getAddressByteSize());
223   uint64_t Section;
224   uint64_t Address = DA.getRelocatedAddress(&Offset, &Section);
225   return {{Address, Section}};
226 }
227 
228 Expected<uint64_t> DWARFUnit::getStringOffsetSectionItem(uint32_t Index) const {
229   if (!StringOffsetsTableContribution)
230     return make_error<StringError>(
231         "DW_FORM_strx used without a valid string offsets table",
232         inconvertibleErrorCode());
233   unsigned ItemSize = getDwarfStringOffsetsByteSize();
234   uint64_t Offset = getStringOffsetsBase() + Index * ItemSize;
235   if (StringOffsetSection.Data.size() < Offset + ItemSize)
236     return make_error<StringError>("DW_FORM_strx uses index " + Twine(Index) +
237                                        ", which is too large",
238                                    inconvertibleErrorCode());
239   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
240                         isLittleEndian, 0);
241   return DA.getRelocatedValue(ItemSize, &Offset);
242 }
243 
244 bool DWARFUnitHeader::extract(DWARFContext &Context,
245                               const DWARFDataExtractor &debug_info,
246                               uint64_t *offset_ptr,
247                               DWARFSectionKind SectionKind) {
248   Offset = *offset_ptr;
249   Error Err = Error::success();
250   IndexEntry = nullptr;
251   std::tie(Length, FormParams.Format) =
252       debug_info.getInitialLength(offset_ptr, &Err);
253   FormParams.Version = debug_info.getU16(offset_ptr, &Err);
254   if (FormParams.Version >= 5) {
255     UnitType = debug_info.getU8(offset_ptr, &Err);
256     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
257     AbbrOffset = debug_info.getRelocatedValue(
258         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
259   } else {
260     AbbrOffset = debug_info.getRelocatedValue(
261         FormParams.getDwarfOffsetByteSize(), offset_ptr, nullptr, &Err);
262     FormParams.AddrSize = debug_info.getU8(offset_ptr, &Err);
263     // Fake a unit type based on the section type.  This isn't perfect,
264     // but distinguishing compile and type units is generally enough.
265     if (SectionKind == DW_SECT_EXT_TYPES)
266       UnitType = DW_UT_type;
267     else
268       UnitType = DW_UT_compile;
269   }
270   if (isTypeUnit()) {
271     TypeHash = debug_info.getU64(offset_ptr, &Err);
272     TypeOffset = debug_info.getUnsigned(
273         offset_ptr, FormParams.getDwarfOffsetByteSize(), &Err);
274   } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
275     DWOId = debug_info.getU64(offset_ptr, &Err);
276 
277   if (Err) {
278     Context.getWarningHandler()(joinErrors(
279         createStringError(
280             errc::invalid_argument,
281             "DWARF unit at 0x%8.8" PRIx64 " cannot be parsed:", Offset),
282         std::move(Err)));
283     return false;
284   }
285 
286   // Header fields all parsed, capture the size of this unit header.
287   assert(*offset_ptr - Offset <= 255 && "unexpected header size");
288   Size = uint8_t(*offset_ptr - Offset);
289   uint64_t NextCUOffset = Offset + getUnitLengthFieldByteSize() + getLength();
290 
291   if (!debug_info.isValidOffset(getNextUnitOffset() - 1)) {
292     Context.getWarningHandler()(
293         createStringError(errc::invalid_argument,
294                           "DWARF unit from offset 0x%8.8" PRIx64 " incl. "
295                           "to offset  0x%8.8" PRIx64 " excl. "
296                           "extends past section size 0x%8.8zx",
297                           Offset, NextCUOffset, debug_info.size()));
298     return false;
299   }
300 
301   if (!DWARFContext::isSupportedVersion(getVersion())) {
302     Context.getWarningHandler()(createStringError(
303         errc::invalid_argument,
304         "DWARF unit at offset 0x%8.8" PRIx64 " "
305         "has unsupported version %" PRIu16 ", supported are 2-%u",
306         Offset, getVersion(), DWARFContext::getMaxSupportedVersion()));
307     return false;
308   }
309 
310   // Type offset is unit-relative; should be after the header and before
311   // the end of the current unit.
312   if (isTypeUnit() && TypeOffset < Size) {
313     Context.getWarningHandler()(
314         createStringError(errc::invalid_argument,
315                           "DWARF type unit at offset "
316                           "0x%8.8" PRIx64 " "
317                           "has its relocated type_offset 0x%8.8" PRIx64 " "
318                           "pointing inside the header",
319                           Offset, Offset + TypeOffset));
320     return false;
321   }
322   if (isTypeUnit() &&
323       TypeOffset >= getUnitLengthFieldByteSize() + getLength()) {
324     Context.getWarningHandler()(createStringError(
325         errc::invalid_argument,
326         "DWARF type unit from offset 0x%8.8" PRIx64 " incl. "
327         "to offset 0x%8.8" PRIx64 " excl. has its "
328         "relocated type_offset 0x%8.8" PRIx64 " pointing past the unit end",
329         Offset, NextCUOffset, Offset + TypeOffset));
330     return false;
331   }
332 
333   if (Error SizeErr = DWARFContext::checkAddressSizeSupported(
334           getAddressByteSize(), errc::invalid_argument,
335           "DWARF unit at offset 0x%8.8" PRIx64, Offset)) {
336     Context.getWarningHandler()(std::move(SizeErr));
337     return false;
338   }
339 
340   // Keep track of the highest DWARF version we encounter across all units.
341   Context.setMaxVersionIfGreater(getVersion());
342   return true;
343 }
344 
345 bool DWARFUnitHeader::applyIndexEntry(const DWARFUnitIndex::Entry *Entry) {
346   assert(Entry);
347   assert(!IndexEntry);
348   IndexEntry = Entry;
349   if (AbbrOffset)
350     return false;
351   auto *UnitContrib = IndexEntry->getContribution();
352   if (!UnitContrib ||
353       UnitContrib->Length != (getLength() + getUnitLengthFieldByteSize()))
354     return false;
355   auto *AbbrEntry = IndexEntry->getContribution(DW_SECT_ABBREV);
356   if (!AbbrEntry)
357     return false;
358   AbbrOffset = AbbrEntry->Offset;
359   return true;
360 }
361 
362 Error DWARFUnit::extractRangeList(uint64_t RangeListOffset,
363                                   DWARFDebugRangeList &RangeList) const {
364   // Require that compile unit is extracted.
365   assert(!DieArray.empty());
366   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
367                                 isLittleEndian, getAddressByteSize());
368   uint64_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
369   return RangeList.extract(RangesData, &ActualRangeListOffset);
370 }
371 
372 void DWARFUnit::clear() {
373   Abbrevs = nullptr;
374   BaseAddr.reset();
375   RangeSectionBase = 0;
376   LocSectionBase = 0;
377   AddrOffsetSectionBase = None;
378   SU = nullptr;
379   clearDIEs(false);
380   DWO.reset();
381 }
382 
383 const char *DWARFUnit::getCompilationDir() {
384   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
385 }
386 
387 void DWARFUnit::extractDIEsToVector(
388     bool AppendCUDie, bool AppendNonCUDies,
389     std::vector<DWARFDebugInfoEntry> &Dies) const {
390   if (!AppendCUDie && !AppendNonCUDies)
391     return;
392 
393   // Set the offset to that of the first DIE and calculate the start of the
394   // next compilation unit header.
395   uint64_t DIEOffset = getOffset() + getHeaderSize();
396   uint64_t NextCUOffset = getNextUnitOffset();
397   DWARFDebugInfoEntry DIE;
398   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
399   // The end offset has been already checked by DWARFUnitHeader::extract.
400   assert(DebugInfoData.isValidOffset(NextCUOffset - 1));
401   std::vector<uint32_t> Parents;
402   std::vector<uint32_t> PrevSiblings;
403   bool IsCUDie = true;
404 
405   assert(
406       ((AppendCUDie && Dies.empty()) || (!AppendCUDie && Dies.size() == 1)) &&
407       "Dies array is not empty");
408 
409   // Fill Parents and Siblings stacks with initial value.
410   Parents.push_back(UINT32_MAX);
411   if (!AppendCUDie)
412     Parents.push_back(0);
413   PrevSiblings.push_back(0);
414 
415   // Start to extract dies.
416   do {
417     assert(Parents.size() > 0 && "Empty parents stack");
418     assert((Parents.back() == UINT32_MAX || Parents.back() <= Dies.size()) &&
419            "Wrong parent index");
420 
421     // Extract die. Stop if any error occurred.
422     if (!DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
423                          Parents.back()))
424       break;
425 
426     // If previous sibling is remembered then update it`s SiblingIdx field.
427     if (PrevSiblings.back() > 0) {
428       assert(PrevSiblings.back() < Dies.size() &&
429              "Previous sibling index is out of Dies boundaries");
430       Dies[PrevSiblings.back()].setSiblingIdx(Dies.size());
431     }
432 
433     // Store die into the Dies vector.
434     if (IsCUDie) {
435       if (AppendCUDie)
436         Dies.push_back(DIE);
437       if (!AppendNonCUDies)
438         break;
439       // The average bytes per DIE entry has been seen to be
440       // around 14-20 so let's pre-reserve the needed memory for
441       // our DIE entries accordingly.
442       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
443     } else {
444       // Remember last previous sibling.
445       PrevSiblings.back() = Dies.size();
446 
447       Dies.push_back(DIE);
448     }
449 
450     // Check for new children scope.
451     if (const DWARFAbbreviationDeclaration *AbbrDecl =
452             DIE.getAbbreviationDeclarationPtr()) {
453       if (AbbrDecl->hasChildren()) {
454         if (AppendCUDie || !IsCUDie) {
455           assert(Dies.size() > 0 && "Dies does not contain any die");
456           Parents.push_back(Dies.size() - 1);
457           PrevSiblings.push_back(0);
458         }
459       } else if (IsCUDie)
460         // Stop if we have single compile unit die w/o children.
461         break;
462     } else {
463       // NULL DIE: finishes current children scope.
464       Parents.pop_back();
465       PrevSiblings.pop_back();
466     }
467 
468     if (IsCUDie)
469       IsCUDie = false;
470 
471     // Stop when compile unit die is removed from the parents stack.
472   } while (Parents.size() > 1);
473 }
474 
475 void DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
476   if (Error e = tryExtractDIEsIfNeeded(CUDieOnly))
477     Context.getRecoverableErrorHandler()(std::move(e));
478 }
479 
480 Error DWARFUnit::tryExtractDIEsIfNeeded(bool CUDieOnly) {
481   if ((CUDieOnly && !DieArray.empty()) ||
482       DieArray.size() > 1)
483     return Error::success(); // Already parsed.
484 
485   bool HasCUDie = !DieArray.empty();
486   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
487 
488   if (DieArray.empty())
489     return Error::success();
490 
491   // If CU DIE was just parsed, copy several attribute values from it.
492   if (HasCUDie)
493     return Error::success();
494 
495   DWARFDie UnitDie(this, &DieArray[0]);
496   if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
497     Header.setDWOId(*DWOId);
498   if (!IsDWO) {
499     assert(AddrOffsetSectionBase == None);
500     assert(RangeSectionBase == 0);
501     assert(LocSectionBase == 0);
502     AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_addr_base));
503     if (!AddrOffsetSectionBase)
504       AddrOffsetSectionBase =
505           toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base));
506     RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
507     LocSectionBase = toSectionOffset(UnitDie.find(DW_AT_loclists_base), 0);
508   }
509 
510   // In general, in DWARF v5 and beyond we derive the start of the unit's
511   // contribution to the string offsets table from the unit DIE's
512   // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
513   // attribute, so we assume that there is a contribution to the string
514   // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
515   // In both cases we need to determine the format of the contribution,
516   // which may differ from the unit's format.
517   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
518                         isLittleEndian, 0);
519   if (IsDWO || getVersion() >= 5) {
520     auto StringOffsetOrError =
521         IsDWO ? determineStringOffsetsTableContributionDWO(DA)
522               : determineStringOffsetsTableContribution(DA);
523     if (!StringOffsetOrError)
524       return createStringError(errc::invalid_argument,
525                                "invalid reference to or invalid content in "
526                                ".debug_str_offsets[.dwo]: " +
527                                    toString(StringOffsetOrError.takeError()));
528 
529     StringOffsetsTableContribution = *StringOffsetOrError;
530   }
531 
532   // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
533   // describe address ranges.
534   if (getVersion() >= 5) {
535     // In case of DWP, the base offset from the index has to be added.
536     if (IsDWO) {
537       uint64_t ContributionBaseOffset = 0;
538       if (auto *IndexEntry = Header.getIndexEntry())
539         if (auto *Contrib = IndexEntry->getContribution(DW_SECT_RNGLISTS))
540           ContributionBaseOffset = Contrib->Offset;
541       setRangesSection(
542           &Context.getDWARFObj().getRnglistsDWOSection(),
543           ContributionBaseOffset +
544               DWARFListTableHeader::getHeaderSize(Header.getFormat()));
545     } else
546       setRangesSection(&Context.getDWARFObj().getRnglistsSection(),
547                        toSectionOffset(UnitDie.find(DW_AT_rnglists_base),
548                                        DWARFListTableHeader::getHeaderSize(
549                                            Header.getFormat())));
550   }
551 
552   if (IsDWO) {
553     // If we are reading a package file, we need to adjust the location list
554     // data based on the index entries.
555     StringRef Data = Header.getVersion() >= 5
556                          ? Context.getDWARFObj().getLoclistsDWOSection().Data
557                          : Context.getDWARFObj().getLocDWOSection().Data;
558     if (auto *IndexEntry = Header.getIndexEntry())
559       if (const auto *C = IndexEntry->getContribution(
560               Header.getVersion() >= 5 ? DW_SECT_LOCLISTS : DW_SECT_EXT_LOC))
561         Data = Data.substr(C->Offset, C->Length);
562 
563     DWARFDataExtractor DWARFData(Data, isLittleEndian, getAddressByteSize());
564     LocTable =
565         std::make_unique<DWARFDebugLoclists>(DWARFData, Header.getVersion());
566     LocSectionBase = DWARFListTableHeader::getHeaderSize(Header.getFormat());
567   } else if (getVersion() >= 5) {
568     LocTable = std::make_unique<DWARFDebugLoclists>(
569         DWARFDataExtractor(Context.getDWARFObj(),
570                            Context.getDWARFObj().getLoclistsSection(),
571                            isLittleEndian, getAddressByteSize()),
572         getVersion());
573   } else {
574     LocTable = std::make_unique<DWARFDebugLoc>(DWARFDataExtractor(
575         Context.getDWARFObj(), Context.getDWARFObj().getLocSection(),
576         isLittleEndian, getAddressByteSize()));
577   }
578 
579   // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
580   // skeleton CU DIE, so that DWARF users not aware of it are not broken.
581   return Error::success();
582 }
583 
584 bool DWARFUnit::parseDWO() {
585   if (IsDWO)
586     return false;
587   if (DWO.get())
588     return false;
589   DWARFDie UnitDie = getUnitDIE();
590   if (!UnitDie)
591     return false;
592   auto DWOFileName = getVersion() >= 5
593                          ? dwarf::toString(UnitDie.find(DW_AT_dwo_name))
594                          : dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
595   if (!DWOFileName)
596     return false;
597   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
598   SmallString<16> AbsolutePath;
599   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
600       *CompilationDir) {
601     sys::path::append(AbsolutePath, *CompilationDir);
602   }
603   sys::path::append(AbsolutePath, *DWOFileName);
604   auto DWOId = getDWOId();
605   if (!DWOId)
606     return false;
607   auto DWOContext = Context.getDWOContext(AbsolutePath);
608   if (!DWOContext)
609     return false;
610 
611   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
612   if (!DWOCU)
613     return false;
614   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
615   DWO->setSkeletonUnit(this);
616   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
617   if (AddrOffsetSectionBase)
618     DWO->setAddrOffsetSection(AddrOffsetSection, *AddrOffsetSectionBase);
619   if (getVersion() == 4) {
620     auto DWORangesBase = UnitDie.getRangesBaseAttribute();
621     DWO->setRangesSection(RangeSection, DWORangesBase.getValueOr(0));
622   }
623 
624   return true;
625 }
626 
627 void DWARFUnit::clearDIEs(bool KeepCUDie) {
628   // Do not use resize() + shrink_to_fit() to free memory occupied by dies.
629   // shrink_to_fit() is a *non-binding* request to reduce capacity() to size().
630   // It depends on the implementation whether the request is fulfilled.
631   // Create a new vector with a small capacity and assign it to the DieArray to
632   // have previous contents freed.
633   DieArray = (KeepCUDie && !DieArray.empty())
634                  ? std::vector<DWARFDebugInfoEntry>({DieArray[0]})
635                  : std::vector<DWARFDebugInfoEntry>();
636 }
637 
638 Expected<DWARFAddressRangesVector>
639 DWARFUnit::findRnglistFromOffset(uint64_t Offset) {
640   if (getVersion() <= 4) {
641     DWARFDebugRangeList RangeList;
642     if (Error E = extractRangeList(Offset, RangeList))
643       return std::move(E);
644     return RangeList.getAbsoluteRanges(getBaseAddress());
645   }
646   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
647                                 isLittleEndian, Header.getAddressByteSize());
648   DWARFDebugRnglistTable RnglistTable;
649   auto RangeListOrError = RnglistTable.findList(RangesData, Offset);
650   if (RangeListOrError)
651     return RangeListOrError.get().getAbsoluteRanges(getBaseAddress(), *this);
652   return RangeListOrError.takeError();
653 }
654 
655 Expected<DWARFAddressRangesVector>
656 DWARFUnit::findRnglistFromIndex(uint32_t Index) {
657   if (auto Offset = getRnglistOffset(Index))
658     return findRnglistFromOffset(*Offset);
659 
660   return createStringError(errc::invalid_argument,
661                            "invalid range list table index %d (possibly "
662                            "missing the entire range list table)",
663                            Index);
664 }
665 
666 Expected<DWARFAddressRangesVector> DWARFUnit::collectAddressRanges() {
667   DWARFDie UnitDie = getUnitDIE();
668   if (!UnitDie)
669     return createStringError(errc::invalid_argument, "No unit DIE");
670 
671   // First, check if unit DIE describes address ranges for the whole unit.
672   auto CUDIERangesOrError = UnitDie.getAddressRanges();
673   if (!CUDIERangesOrError)
674     return createStringError(errc::invalid_argument,
675                              "decoding address ranges: %s",
676                              toString(CUDIERangesOrError.takeError()).c_str());
677   return *CUDIERangesOrError;
678 }
679 
680 Expected<DWARFLocationExpressionsVector>
681 DWARFUnit::findLoclistFromOffset(uint64_t Offset) {
682   DWARFLocationExpressionsVector Result;
683 
684   Error InterpretationError = Error::success();
685 
686   Error ParseError = getLocationTable().visitAbsoluteLocationList(
687       Offset, getBaseAddress(),
688       [this](uint32_t Index) { return getAddrOffsetSectionItem(Index); },
689       [&](Expected<DWARFLocationExpression> L) {
690         if (L)
691           Result.push_back(std::move(*L));
692         else
693           InterpretationError =
694               joinErrors(L.takeError(), std::move(InterpretationError));
695         return !InterpretationError;
696       });
697 
698   if (ParseError || InterpretationError)
699     return joinErrors(std::move(ParseError), std::move(InterpretationError));
700 
701   return Result;
702 }
703 
704 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
705   if (Die.isSubroutineDIE()) {
706     auto DIERangesOrError = Die.getAddressRanges();
707     if (DIERangesOrError) {
708       for (const auto &R : DIERangesOrError.get()) {
709         // Ignore 0-sized ranges.
710         if (R.LowPC == R.HighPC)
711           continue;
712         auto B = AddrDieMap.upper_bound(R.LowPC);
713         if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
714           // The range is a sub-range of existing ranges, we need to split the
715           // existing range.
716           if (R.HighPC < B->second.first)
717             AddrDieMap[R.HighPC] = B->second;
718           if (R.LowPC > B->first)
719             AddrDieMap[B->first].first = R.LowPC;
720         }
721         AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
722       }
723     } else
724       llvm::consumeError(DIERangesOrError.takeError());
725   }
726   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
727   // simplify the logic to update AddrDieMap. The child's range will always
728   // be equal or smaller than the parent's range. With this assumption, when
729   // adding one range into the map, it will at most split a range into 3
730   // sub-ranges.
731   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
732     updateAddressDieMap(Child);
733 }
734 
735 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
736   extractDIEsIfNeeded(false);
737   if (AddrDieMap.empty())
738     updateAddressDieMap(getUnitDIE());
739   auto R = AddrDieMap.upper_bound(Address);
740   if (R == AddrDieMap.begin())
741     return DWARFDie();
742   // upper_bound's previous item contains Address.
743   --R;
744   if (Address >= R->second.first)
745     return DWARFDie();
746   return R->second.second;
747 }
748 
749 void
750 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
751                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
752   assert(InlinedChain.empty());
753   // Try to look for subprogram DIEs in the DWO file.
754   parseDWO();
755   // First, find the subroutine that contains the given address (the leaf
756   // of inlined chain).
757   DWARFDie SubroutineDIE =
758       (DWO ? *DWO : *this).getSubroutineForAddress(Address);
759 
760   while (SubroutineDIE) {
761     if (SubroutineDIE.isSubprogramDIE()) {
762       InlinedChain.push_back(SubroutineDIE);
763       return;
764     }
765     if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
766       InlinedChain.push_back(SubroutineDIE);
767     SubroutineDIE  = SubroutineDIE.getParent();
768   }
769 }
770 
771 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
772                                               DWARFSectionKind Kind) {
773   if (Kind == DW_SECT_INFO)
774     return Context.getCUIndex();
775   assert(Kind == DW_SECT_EXT_TYPES);
776   return Context.getTUIndex();
777 }
778 
779 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
780   if (!Die)
781     return DWARFDie();
782 
783   if (Optional<uint32_t> ParentIdx = Die->getParentIdx()) {
784     assert(*ParentIdx < DieArray.size() &&
785            "ParentIdx is out of DieArray boundaries");
786     return DWARFDie(this, &DieArray[*ParentIdx]);
787   }
788 
789   return DWARFDie();
790 }
791 
792 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
793   if (!Die)
794     return DWARFDie();
795 
796   if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
797     assert(*SiblingIdx < DieArray.size() &&
798            "SiblingIdx is out of DieArray boundaries");
799     return DWARFDie(this, &DieArray[*SiblingIdx]);
800   }
801 
802   return DWARFDie();
803 }
804 
805 DWARFDie DWARFUnit::getPreviousSibling(const DWARFDebugInfoEntry *Die) {
806   if (!Die)
807     return DWARFDie();
808 
809   Optional<uint32_t> ParentIdx = Die->getParentIdx();
810   if (!ParentIdx)
811     // Die is a root die, there is no previous sibling.
812     return DWARFDie();
813 
814   assert(*ParentIdx < DieArray.size() &&
815          "ParentIdx is out of DieArray boundaries");
816   assert(getDIEIndex(Die) > 0 && "Die is a root die");
817 
818   uint32_t PrevDieIdx = getDIEIndex(Die) - 1;
819   if (PrevDieIdx == *ParentIdx)
820     // Immediately previous node is parent, there is no previous sibling.
821     return DWARFDie();
822 
823   while (DieArray[PrevDieIdx].getParentIdx() != *ParentIdx) {
824     PrevDieIdx = *DieArray[PrevDieIdx].getParentIdx();
825 
826     assert(PrevDieIdx < DieArray.size() &&
827            "PrevDieIdx is out of DieArray boundaries");
828     assert(PrevDieIdx >= *ParentIdx &&
829            "PrevDieIdx is not a child of parent of Die");
830   }
831 
832   return DWARFDie(this, &DieArray[PrevDieIdx]);
833 }
834 
835 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
836   if (!Die->hasChildren())
837     return DWARFDie();
838 
839   // TODO: Instead of checking here for invalid die we might reject
840   // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
841   // We do not want access out of bounds when parsing corrupted debug data.
842   size_t I = getDIEIndex(Die) + 1;
843   if (I >= DieArray.size())
844     return DWARFDie();
845   return DWARFDie(this, &DieArray[I]);
846 }
847 
848 DWARFDie DWARFUnit::getLastChild(const DWARFDebugInfoEntry *Die) {
849   if (!Die->hasChildren())
850     return DWARFDie();
851 
852   if (Optional<uint32_t> SiblingIdx = Die->getSiblingIdx()) {
853     assert(*SiblingIdx < DieArray.size() &&
854            "SiblingIdx is out of DieArray boundaries");
855     assert(DieArray[*SiblingIdx - 1].getTag() == dwarf::DW_TAG_null &&
856            "Bad end of children marker");
857     return DWARFDie(this, &DieArray[*SiblingIdx - 1]);
858   }
859 
860   // If SiblingIdx is set for non-root dies we could be sure that DWARF is
861   // correct and "end of children marker" must be found. For root die we do not
862   // have such a guarantee(parsing root die might be stopped if "end of children
863   // marker" is missing, SiblingIdx is always zero for root die). That is why we
864   // do not use assertion for checking for "end of children marker" for root
865   // die.
866 
867   // TODO: Instead of checking here for invalid die we might reject
868   // invalid dies at parsing stage(DWARFUnit::extractDIEsToVector).
869   if (getDIEIndex(Die) == 0 && DieArray.size() > 1 &&
870       DieArray.back().getTag() == dwarf::DW_TAG_null) {
871     // For the unit die we might take last item from DieArray.
872     assert(getDIEIndex(Die) == getDIEIndex(getUnitDIE()) && "Bad unit die");
873     return DWARFDie(this, &DieArray.back());
874   }
875 
876   return DWARFDie();
877 }
878 
879 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
880   if (!Abbrevs)
881     Abbrevs = Abbrev->getAbbreviationDeclarationSet(getAbbreviationsOffset());
882   return Abbrevs;
883 }
884 
885 llvm::Optional<object::SectionedAddress> DWARFUnit::getBaseAddress() {
886   if (BaseAddr)
887     return BaseAddr;
888 
889   DWARFDie UnitDie = getUnitDIE();
890   Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
891   BaseAddr = toSectionedAddress(PC);
892   return BaseAddr;
893 }
894 
895 Expected<StrOffsetsContributionDescriptor>
896 StrOffsetsContributionDescriptor::validateContributionSize(
897     DWARFDataExtractor &DA) {
898   uint8_t EntrySize = getDwarfOffsetByteSize();
899   // In order to ensure that we don't read a partial record at the end of
900   // the section we validate for a multiple of the entry size.
901   uint64_t ValidationSize = alignTo(Size, EntrySize);
902   // Guard against overflow.
903   if (ValidationSize >= Size)
904     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
905       return *this;
906   return createStringError(errc::invalid_argument, "length exceeds section size");
907 }
908 
909 // Look for a DWARF64-formatted contribution to the string offsets table
910 // starting at a given offset and record it in a descriptor.
911 static Expected<StrOffsetsContributionDescriptor>
912 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
913   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
914     return createStringError(errc::invalid_argument, "section offset exceeds section size");
915 
916   if (DA.getU32(&Offset) != dwarf::DW_LENGTH_DWARF64)
917     return createStringError(errc::invalid_argument, "32 bit contribution referenced from a 64 bit unit");
918 
919   uint64_t Size = DA.getU64(&Offset);
920   uint8_t Version = DA.getU16(&Offset);
921   (void)DA.getU16(&Offset); // padding
922   // The encoded length includes the 2-byte version field and the 2-byte
923   // padding, so we need to subtract them out when we populate the descriptor.
924   return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
925 }
926 
927 // Look for a DWARF32-formatted contribution to the string offsets table
928 // starting at a given offset and record it in a descriptor.
929 static Expected<StrOffsetsContributionDescriptor>
930 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint64_t Offset) {
931   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
932     return createStringError(errc::invalid_argument, "section offset exceeds section size");
933 
934   uint32_t ContributionSize = DA.getU32(&Offset);
935   if (ContributionSize >= dwarf::DW_LENGTH_lo_reserved)
936     return createStringError(errc::invalid_argument, "invalid length");
937 
938   uint8_t Version = DA.getU16(&Offset);
939   (void)DA.getU16(&Offset); // padding
940   // The encoded length includes the 2-byte version field and the 2-byte
941   // padding, so we need to subtract them out when we populate the descriptor.
942   return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
943                                           DWARF32);
944 }
945 
946 static Expected<StrOffsetsContributionDescriptor>
947 parseDWARFStringOffsetsTableHeader(DWARFDataExtractor &DA,
948                                    llvm::dwarf::DwarfFormat Format,
949                                    uint64_t Offset) {
950   StrOffsetsContributionDescriptor Desc;
951   switch (Format) {
952   case dwarf::DwarfFormat::DWARF64: {
953     if (Offset < 16)
954       return createStringError(errc::invalid_argument, "insufficient space for 64 bit header prefix");
955     auto DescOrError = parseDWARF64StringOffsetsTableHeader(DA, Offset - 16);
956     if (!DescOrError)
957       return DescOrError.takeError();
958     Desc = *DescOrError;
959     break;
960   }
961   case dwarf::DwarfFormat::DWARF32: {
962     if (Offset < 8)
963       return createStringError(errc::invalid_argument, "insufficient space for 32 bit header prefix");
964     auto DescOrError = parseDWARF32StringOffsetsTableHeader(DA, Offset - 8);
965     if (!DescOrError)
966       return DescOrError.takeError();
967     Desc = *DescOrError;
968     break;
969   }
970   }
971   return Desc.validateContributionSize(DA);
972 }
973 
974 Expected<Optional<StrOffsetsContributionDescriptor>>
975 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA) {
976   assert(!IsDWO);
977   auto OptOffset = toSectionOffset(getUnitDIE().find(DW_AT_str_offsets_base));
978   if (!OptOffset)
979     return None;
980   auto DescOrError =
981       parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), *OptOffset);
982   if (!DescOrError)
983     return DescOrError.takeError();
984   return *DescOrError;
985 }
986 
987 Expected<Optional<StrOffsetsContributionDescriptor>>
988 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor & DA) {
989   assert(IsDWO);
990   uint64_t Offset = 0;
991   auto IndexEntry = Header.getIndexEntry();
992   const auto *C =
993       IndexEntry ? IndexEntry->getContribution(DW_SECT_STR_OFFSETS) : nullptr;
994   if (C)
995     Offset = C->Offset;
996   if (getVersion() >= 5) {
997     if (DA.getData().data() == nullptr)
998       return None;
999     Offset += Header.getFormat() == dwarf::DwarfFormat::DWARF32 ? 8 : 16;
1000     // Look for a valid contribution at the given offset.
1001     auto DescOrError = parseDWARFStringOffsetsTableHeader(DA, Header.getFormat(), Offset);
1002     if (!DescOrError)
1003       return DescOrError.takeError();
1004     return *DescOrError;
1005   }
1006   // Prior to DWARF v5, we derive the contribution size from the
1007   // index table (in a package file). In a .dwo file it is simply
1008   // the length of the string offsets section.
1009   StrOffsetsContributionDescriptor Desc;
1010   if (C)
1011     Desc = StrOffsetsContributionDescriptor(C->Offset, C->Length, 4,
1012                                             Header.getFormat());
1013   else if (!IndexEntry && !StringOffsetSection.Data.empty())
1014     Desc = StrOffsetsContributionDescriptor(0, StringOffsetSection.Data.size(),
1015                                             4, Header.getFormat());
1016   else
1017     return None;
1018   auto DescOrError = Desc.validateContributionSize(DA);
1019   if (!DescOrError)
1020     return DescOrError.takeError();
1021   return *DescOrError;
1022 }
1023 
1024 Optional<uint64_t> DWARFUnit::getRnglistOffset(uint32_t Index) {
1025   DataExtractor RangesData(RangeSection->Data, isLittleEndian,
1026                            getAddressByteSize());
1027   DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
1028                               isLittleEndian, 0);
1029   if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1030           RangesData, RangeSectionBase, getFormat(), Index))
1031     return *Off + RangeSectionBase;
1032   return None;
1033 }
1034 
1035 Optional<uint64_t> DWARFUnit::getLoclistOffset(uint32_t Index) {
1036   if (Optional<uint64_t> Off = llvm::DWARFListTableHeader::getOffsetEntry(
1037           LocTable->getData(), LocSectionBase, getFormat(), Index))
1038     return *Off + LocSectionBase;
1039   return None;
1040 }
1041