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