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