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