1 //===- DWARFUnit.cpp ------------------------------------------------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "llvm/DebugInfo/DWARF/DWARFUnit.h"
11 #include "llvm/ADT/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/StringRef.h"
14 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.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/DWARFDie.h"
19 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
20 #include "llvm/Support/DataExtractor.h"
21 #include "llvm/Support/Path.h"
22 #include <algorithm>
23 #include <cassert>
24 #include <cstddef>
25 #include <cstdint>
26 #include <cstdio>
27 #include <utility>
28 #include <vector>
29 
30 using namespace llvm;
31 using namespace dwarf;
32 
33 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
34   const DWARFObject &D = C.getDWARFObj();
35   parseImpl(C, Section, C.getDebugAbbrev(), &D.getRangeSection(),
36             D.getStringSection(), D.getStringOffsetSection(),
37             &D.getAddrSection(), D.getLineSection(), D.getLineStringSection(),
38             D.isLittleEndian(), false, false);
39 }
40 
41 void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
42                                     const DWARFSection &DWOSection, bool Lazy) {
43   const DWARFObject &D = C.getDWARFObj();
44   parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), &D.getRangeDWOSection(),
45             D.getStringDWOSection(), D.getStringOffsetDWOSection(),
46             &D.getAddrSection(), D.getLineDWOSection(), StringRef(),
47             C.isLittleEndian(), true, Lazy);
48 }
49 
50 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
51                      const DWARFDebugAbbrev *DA, const DWARFSection *RS,
52                      StringRef SS, const DWARFSection &SOS,
53                      const DWARFSection *AOS, const DWARFSection &LS,
54                      StringRef LSS, bool LE, bool IsDWO,
55                      const DWARFUnitSectionBase &UnitSection,
56                      const DWARFUnitIndex::Entry *IndexEntry)
57     : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
58       LineSection(LS), LineStringSection(LSS), StringSection(SS),
59       StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE),
60       isDWO(IsDWO), UnitSection(UnitSection), IndexEntry(IndexEntry) {
61   clear();
62 }
63 
64 DWARFUnit::~DWARFUnit() = default;
65 
66 DWARFDataExtractor DWARFUnit::getDebugInfoExtractor() const {
67   return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
68                             getAddressByteSize());
69 }
70 
71 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
72                                                 uint64_t &Result) const {
73   uint32_t Offset = AddrOffsetSectionBase + Index * getAddressByteSize();
74   if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
75     return false;
76   DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
77                         isLittleEndian, getAddressByteSize());
78   Result = DA.getRelocatedAddress(&Offset);
79   return true;
80 }
81 
82 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
83                                            uint64_t &Result) const {
84   if (!StringOffsetsTableContribution)
85     return false;
86   unsigned ItemSize = getDwarfStringOffsetsByteSize();
87   uint32_t Offset = getStringOffsetsBase() + Index * ItemSize;
88   if (StringOffsetSection.Data.size() < Offset + ItemSize)
89     return false;
90   DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
91                         isLittleEndian, 0);
92   Result = DA.getRelocatedValue(ItemSize, &Offset);
93   return true;
94 }
95 
96 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
97   Length = debug_info.getU32(offset_ptr);
98   // FIXME: Support DWARF64.
99   FormParams.Format = DWARF32;
100   FormParams.Version = debug_info.getU16(offset_ptr);
101   if (FormParams.Version >= 5) {
102     UnitType = debug_info.getU8(offset_ptr);
103     FormParams.AddrSize = debug_info.getU8(offset_ptr);
104     AbbrOffset = debug_info.getU32(offset_ptr);
105   } else {
106     AbbrOffset = debug_info.getU32(offset_ptr);
107     FormParams.AddrSize = debug_info.getU8(offset_ptr);
108   }
109   if (IndexEntry) {
110     if (AbbrOffset)
111       return false;
112     auto *UnitContrib = IndexEntry->getOffset();
113     if (!UnitContrib || UnitContrib->Length != (Length + 4))
114       return false;
115     auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
116     if (!AbbrEntry)
117       return false;
118     AbbrOffset = AbbrEntry->Offset;
119   }
120 
121   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
122   bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
123   bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8;
124 
125   if (!LengthOK || !VersionOK || !AddrSizeOK)
126     return false;
127 
128   // Keep track of the highest DWARF version we encounter across all units.
129   Context.setMaxVersionIfGreater(getVersion());
130   return true;
131 }
132 
133 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
134   clear();
135 
136   Offset = *offset_ptr;
137 
138   if (debug_info.isValidOffset(*offset_ptr)) {
139     if (extractImpl(debug_info, offset_ptr))
140       return true;
141 
142     // reset the offset to where we tried to parse from if anything went wrong
143     *offset_ptr = Offset;
144   }
145 
146   return false;
147 }
148 
149 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
150                                  DWARFDebugRangeList &RangeList) const {
151   // Require that compile unit is extracted.
152   assert(!DieArray.empty());
153   DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
154                                 isLittleEndian, getAddressByteSize());
155   uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
156   return RangeList.extract(RangesData, &ActualRangeListOffset);
157 }
158 
159 void DWARFUnit::clear() {
160   Offset = 0;
161   Length = 0;
162   Abbrevs = nullptr;
163   FormParams = DWARFFormParams({0, 0, DWARF32});
164   BaseAddr.reset();
165   RangeSectionBase = 0;
166   AddrOffsetSectionBase = 0;
167   clearDIEs(false);
168   DWO.reset();
169 }
170 
171 const char *DWARFUnit::getCompilationDir() {
172   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
173 }
174 
175 Optional<uint64_t> DWARFUnit::getDWOId() {
176   return toUnsigned(getUnitDIE().find(DW_AT_GNU_dwo_id));
177 }
178 
179 void DWARFUnit::extractDIEsToVector(
180     bool AppendCUDie, bool AppendNonCUDies,
181     std::vector<DWARFDebugInfoEntry> &Dies) const {
182   if (!AppendCUDie && !AppendNonCUDies)
183     return;
184 
185   // Set the offset to that of the first DIE and calculate the start of the
186   // next compilation unit header.
187   uint32_t DIEOffset = Offset + getHeaderSize();
188   uint32_t NextCUOffset = getNextUnitOffset();
189   DWARFDebugInfoEntry DIE;
190   DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
191   uint32_t Depth = 0;
192   bool IsCUDie = true;
193 
194   while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
195                          Depth)) {
196     if (IsCUDie) {
197       if (AppendCUDie)
198         Dies.push_back(DIE);
199       if (!AppendNonCUDies)
200         break;
201       // The average bytes per DIE entry has been seen to be
202       // around 14-20 so let's pre-reserve the needed memory for
203       // our DIE entries accordingly.
204       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
205       IsCUDie = false;
206     } else {
207       Dies.push_back(DIE);
208     }
209 
210     if (const DWARFAbbreviationDeclaration *AbbrDecl =
211             DIE.getAbbreviationDeclarationPtr()) {
212       // Normal DIE
213       if (AbbrDecl->hasChildren())
214         ++Depth;
215     } else {
216       // NULL DIE.
217       if (Depth > 0)
218         --Depth;
219       if (Depth == 0)
220         break;  // We are done with this compile unit!
221     }
222   }
223 
224   // Give a little bit of info if we encounter corrupt DWARF (our offset
225   // should always terminate at or before the start of the next compilation
226   // unit header).
227   if (DIEOffset > NextCUOffset)
228     fprintf(stderr, "warning: DWARF compile unit extends beyond its "
229                     "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
230 }
231 
232 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
233   if ((CUDieOnly && !DieArray.empty()) ||
234       DieArray.size() > 1)
235     return 0; // Already parsed.
236 
237   bool HasCUDie = !DieArray.empty();
238   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
239 
240   if (DieArray.empty())
241     return 0;
242 
243   // If CU DIE was just parsed, copy several attribute values from it.
244   if (!HasCUDie) {
245     DWARFDie UnitDie = getUnitDIE();
246     Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
247     if (Optional<uint64_t> Addr = toAddress(PC))
248         setBaseAddress({*Addr, PC->getSectionIndex()});
249 
250     if (!isDWO) {
251       assert(AddrOffsetSectionBase == 0);
252       assert(RangeSectionBase == 0);
253       AddrOffsetSectionBase =
254           toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
255       RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
256     }
257 
258     // In general, in DWARF v5 and beyond we derive the start of the unit's
259     // contribution to the string offsets table from the unit DIE's
260     // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
261     // attribute, so we assume that there is a contribution to the string
262     // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
263     // In both cases we need to determine the format of the contribution,
264     // which may differ from the unit's format.
265     uint64_t StringOffsetsContributionBase =
266         isDWO ? 0 : toSectionOffset(UnitDie.find(DW_AT_str_offsets_base), 0);
267     if (IndexEntry)
268       if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
269         StringOffsetsContributionBase += C->Offset;
270 
271     DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
272                           isLittleEndian, 0);
273     if (isDWO)
274       StringOffsetsTableContribution =
275           determineStringOffsetsTableContributionDWO(
276               DA, StringOffsetsContributionBase);
277     else if (getVersion() >= 5)
278       StringOffsetsTableContribution = determineStringOffsetsTableContribution(
279           DA, StringOffsetsContributionBase);
280 
281     // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
282     // skeleton CU DIE, so that DWARF users not aware of it are not broken.
283   }
284 
285   return DieArray.size();
286 }
287 
288 bool DWARFUnit::parseDWO() {
289   if (isDWO)
290     return false;
291   if (DWO.get())
292     return false;
293   DWARFDie UnitDie = getUnitDIE();
294   if (!UnitDie)
295     return false;
296   auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
297   if (!DWOFileName)
298     return false;
299   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
300   SmallString<16> AbsolutePath;
301   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
302       *CompilationDir) {
303     sys::path::append(AbsolutePath, *CompilationDir);
304   }
305   sys::path::append(AbsolutePath, *DWOFileName);
306   auto DWOId = getDWOId();
307   if (!DWOId)
308     return false;
309   auto DWOContext = Context.getDWOContext(AbsolutePath);
310   if (!DWOContext)
311     return false;
312 
313   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
314   if (!DWOCU)
315     return false;
316   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
317   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
318   DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
319   auto DWORangesBase = UnitDie.getRangesBaseAttribute();
320   DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
321   return true;
322 }
323 
324 void DWARFUnit::clearDIEs(bool KeepCUDie) {
325   if (DieArray.size() > (unsigned)KeepCUDie) {
326     DieArray.resize((unsigned)KeepCUDie);
327     DieArray.shrink_to_fit();
328   }
329 }
330 
331 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
332   DWARFDie UnitDie = getUnitDIE();
333   if (!UnitDie)
334     return;
335   // First, check if unit DIE describes address ranges for the whole unit.
336   const auto &CUDIERanges = UnitDie.getAddressRanges();
337   if (!CUDIERanges.empty()) {
338     CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
339     return;
340   }
341 
342   // This function is usually called if there in no .debug_aranges section
343   // in order to produce a compile unit level set of address ranges that
344   // is accurate. If the DIEs weren't parsed, then we don't want all dies for
345   // all compile units to stay loaded when they weren't needed. So we can end
346   // up parsing the DWARF and then throwing them all away to keep memory usage
347   // down.
348   const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
349   getUnitDIE().collectChildrenAddressRanges(CURanges);
350 
351   // Collect address ranges from DIEs in .dwo if necessary.
352   bool DWOCreated = parseDWO();
353   if (DWO)
354     DWO->collectAddressRanges(CURanges);
355   if (DWOCreated)
356     DWO.reset();
357 
358   // Keep memory down by clearing DIEs if this generate function
359   // caused them to be parsed.
360   if (ClearDIEs)
361     clearDIEs(true);
362 }
363 
364 // Populates a map from PC addresses to subprogram DIEs.
365 //
366 // This routine tries to look at the smallest amount of the debug info it can
367 // to locate the DIEs. This is because many subprograms will never end up being
368 // read or needed at all. We want to be as lazy as possible.
369 void DWARFUnit::buildSubprogramDIEAddrMap() {
370   assert(SubprogramDIEAddrMap.empty() && "Must only build this map once!");
371   SmallVector<DWARFDie, 16> Worklist;
372   Worklist.push_back(getUnitDIE());
373   do {
374     DWARFDie Die = Worklist.pop_back_val();
375 
376     // Queue up child DIEs to recurse through.
377     // FIXME: This causes us to read a lot more debug info than we really need.
378     // We should look at pruning out DIEs which cannot transitively hold
379     // separate subprograms.
380     for (DWARFDie Child : Die.children())
381       Worklist.push_back(Child);
382 
383     // If handling a non-subprogram DIE, nothing else to do.
384     if (!Die.isSubprogramDIE())
385       continue;
386 
387     // For subprogram DIEs, store them, and insert relevant markers into the
388     // address map. We don't care about overlap at all here as DWARF doesn't
389     // meaningfully support that, so we simply will insert a range with no DIE
390     // starting from the high PC. In the event there are overlaps, sorting
391     // these may truncate things in surprising ways but still will allow
392     // lookups to proceed.
393     int DIEIndex = SubprogramDIEAddrInfos.size();
394     SubprogramDIEAddrInfos.push_back({Die, (uint64_t)-1, {}});
395     for (const auto &R : Die.getAddressRanges()) {
396       // Ignore 0-sized ranges.
397       if (R.LowPC == R.HighPC)
398         continue;
399 
400       SubprogramDIEAddrMap.push_back({R.LowPC, DIEIndex});
401       SubprogramDIEAddrMap.push_back({R.HighPC, -1});
402 
403       if (R.LowPC < SubprogramDIEAddrInfos.back().SubprogramBasePC)
404         SubprogramDIEAddrInfos.back().SubprogramBasePC = R.LowPC;
405     }
406   } while (!Worklist.empty());
407 
408   if (SubprogramDIEAddrMap.empty()) {
409     // If we found no ranges, create a no-op map so that lookups remain simple
410     // but never find anything.
411     SubprogramDIEAddrMap.push_back({0, -1});
412     return;
413   }
414 
415   // Next, sort the ranges and remove both exact duplicates and runs with the
416   // same DIE index. We order the ranges so that non-empty ranges are
417   // preferred. Because there may be ties, we also need to use stable sort.
418   std::stable_sort(SubprogramDIEAddrMap.begin(), SubprogramDIEAddrMap.end(),
419                    [](const std::pair<uint64_t, int64_t> &LHS,
420                       const std::pair<uint64_t, int64_t> &RHS) {
421                      if (LHS.first < RHS.first)
422                        return true;
423                      if (LHS.first > RHS.first)
424                        return false;
425 
426                      // For ranges that start at the same address, keep the one
427                      // with a DIE.
428                      if (LHS.second != -1 && RHS.second == -1)
429                        return true;
430 
431                      return false;
432                    });
433   SubprogramDIEAddrMap.erase(
434       std::unique(SubprogramDIEAddrMap.begin(), SubprogramDIEAddrMap.end(),
435                   [](const std::pair<uint64_t, int64_t> &LHS,
436                      const std::pair<uint64_t, int64_t> &RHS) {
437                     // If the start addresses are exactly the same, we can
438                     // remove all but the first one as it is the only one that
439                     // will be found and used.
440                     //
441                     // If the DIE indices are the same, we can "merge" the
442                     // ranges by eliminating the second.
443                     return LHS.first == RHS.first || LHS.second == RHS.second;
444                   }),
445       SubprogramDIEAddrMap.end());
446 
447   assert(SubprogramDIEAddrMap.back().second == -1 &&
448          "The last interval must not have a DIE as each DIE's address range is "
449          "bounded.");
450 }
451 
452 // Build the second level of mapping from PC to DIE, specifically one that maps
453 // a PC *within* a particular DWARF subprogram into a precise, maximally nested
454 // inlined subroutine DIE (if any exists). We build a separate map for each
455 // subprogram because many subprograms will never get queried for an address
456 // and this allows us to be significantly lazier in reading the DWARF itself.
457 void DWARFUnit::buildInlinedSubroutineDIEAddrMap(
458     SubprogramDIEAddrInfo &SPInfo) {
459   auto &AddrMap = SPInfo.InlinedSubroutineDIEAddrMap;
460   uint64_t BasePC = SPInfo.SubprogramBasePC;
461 
462   auto SubroutineAddrMapSorter = [](const std::pair<int, int> &LHS,
463                                     const std::pair<int, int> &RHS) {
464     if (LHS.first < RHS.first)
465       return true;
466     if (LHS.first > RHS.first)
467       return false;
468 
469     // For ranges that start at the same address, keep the
470     // non-empty one.
471     if (LHS.second != -1 && RHS.second == -1)
472       return true;
473 
474     return false;
475   };
476   auto SubroutineAddrMapUniquer = [](const std::pair<int, int> &LHS,
477                                      const std::pair<int, int> &RHS) {
478     // If the start addresses are exactly the same, we can
479     // remove all but the first one as it is the only one that
480     // will be found and used.
481     //
482     // If the DIE indices are the same, we can "merge" the
483     // ranges by eliminating the second.
484     return LHS.first == RHS.first || LHS.second == RHS.second;
485   };
486 
487   struct DieAndParentIntervalRange {
488     DWARFDie Die;
489     int ParentIntervalsBeginIdx, ParentIntervalsEndIdx;
490   };
491 
492   SmallVector<DieAndParentIntervalRange, 16> Worklist;
493   auto EnqueueChildDIEs = [&](const DWARFDie &Die, int ParentIntervalsBeginIdx,
494                               int ParentIntervalsEndIdx) {
495     for (DWARFDie Child : Die.children())
496       Worklist.push_back(
497           {Child, ParentIntervalsBeginIdx, ParentIntervalsEndIdx});
498   };
499   EnqueueChildDIEs(SPInfo.SubprogramDIE, 0, 0);
500   while (!Worklist.empty()) {
501     DWARFDie Die = Worklist.back().Die;
502     int ParentIntervalsBeginIdx = Worklist.back().ParentIntervalsBeginIdx;
503     int ParentIntervalsEndIdx = Worklist.back().ParentIntervalsEndIdx;
504     Worklist.pop_back();
505 
506     // If we encounter a nested subprogram, simply ignore it. We map to
507     // (disjoint) subprograms before arriving here and we don't want to examine
508     // any inlined subroutines of an unrelated subpragram.
509     if (Die.getTag() == DW_TAG_subprogram)
510       continue;
511 
512     // For non-subroutines, just recurse to keep searching for inlined
513     // subroutines.
514     if (Die.getTag() != DW_TAG_inlined_subroutine) {
515       EnqueueChildDIEs(Die, ParentIntervalsBeginIdx, ParentIntervalsEndIdx);
516       continue;
517     }
518 
519     // Capture the inlined subroutine DIE that we will reference from the map.
520     int DIEIndex = InlinedSubroutineDIEs.size();
521     InlinedSubroutineDIEs.push_back(Die);
522 
523     int DieIntervalsBeginIdx = AddrMap.size();
524     // First collect the PC ranges for this DIE into our subroutine interval
525     // map.
526     for (auto R : Die.getAddressRanges()) {
527       // Clamp the PCs to be above the base.
528       R.LowPC = std::max(R.LowPC, BasePC);
529       R.HighPC = std::max(R.HighPC, BasePC);
530       // Compute relative PCs from the subprogram base and drop down to an
531       // unsigned 32-bit int to represent them within the data structure. This
532       // lets us cover a 4gb single subprogram. Because subprograms may be
533       // partitioned into distant parts of a binary (think hot/cold
534       // partitioning) we want to preserve as much as we can here without
535       // burning extra memory. Past that, we will simply truncate and lose the
536       // ability to map those PCs to a DIE more precise than the subprogram.
537       const uint32_t MaxRelativePC = std::numeric_limits<uint32_t>::max();
538       uint32_t RelativeLowPC = (R.LowPC - BasePC) > (uint64_t)MaxRelativePC
539                                    ? MaxRelativePC
540                                    : (uint32_t)(R.LowPC - BasePC);
541       uint32_t RelativeHighPC = (R.HighPC - BasePC) > (uint64_t)MaxRelativePC
542                                     ? MaxRelativePC
543                                     : (uint32_t)(R.HighPC - BasePC);
544       // Ignore empty or bogus ranges.
545       if (RelativeLowPC >= RelativeHighPC)
546         continue;
547       AddrMap.push_back({RelativeLowPC, DIEIndex});
548       AddrMap.push_back({RelativeHighPC, -1});
549     }
550 
551     // If there are no address ranges, there is nothing to do to map into them
552     // and there cannot be any child subroutine DIEs with address ranges of
553     // interest as those would all be required to nest within this DIE's
554     // non-existent ranges, so we can immediately continue to the next DIE in
555     // the worklist.
556     if (DieIntervalsBeginIdx == (int)AddrMap.size())
557       continue;
558 
559     // The PCs from this DIE should never overlap, so we can easily sort them
560     // here.
561     std::sort(AddrMap.begin() + DieIntervalsBeginIdx, AddrMap.end(),
562               SubroutineAddrMapSorter);
563     // Remove any dead ranges. These should only come from "empty" ranges that
564     // were clobbered by some other range.
565     AddrMap.erase(std::unique(AddrMap.begin() + DieIntervalsBeginIdx,
566                               AddrMap.end(), SubroutineAddrMapUniquer),
567                   AddrMap.end());
568 
569     // Compute the end index of this DIE's addr map intervals.
570     int DieIntervalsEndIdx = AddrMap.size();
571 
572     assert(DieIntervalsBeginIdx != DieIntervalsEndIdx &&
573            "Must not have an empty map for this layer!");
574     assert(AddrMap.back().second == -1 && "Must end with an empty range!");
575     assert(std::is_sorted(AddrMap.begin() + DieIntervalsBeginIdx, AddrMap.end(),
576                           less_first()) &&
577            "Failed to sort this DIE's interals!");
578 
579     // If we have any parent intervals, walk the newly added ranges and find
580     // the parent ranges they were inserted into. Both of these are sorted and
581     // neither has any overlaps. We need to append new ranges to split up any
582     // parent ranges these new ranges would overlap when we merge them.
583     if (ParentIntervalsBeginIdx != ParentIntervalsEndIdx) {
584       int ParentIntervalIdx = ParentIntervalsBeginIdx;
585       for (int i = DieIntervalsBeginIdx, e = DieIntervalsEndIdx - 1; i < e;
586            ++i) {
587         const uint32_t IntervalStart = AddrMap[i].first;
588         const uint32_t IntervalEnd = AddrMap[i + 1].first;
589         const int IntervalDieIdx = AddrMap[i].second;
590         if (IntervalDieIdx == -1) {
591           // For empty intervals, nothing is required. This is a bit surprising
592           // however. If the prior interval overlaps a parent interval and this
593           // would be necessary to mark the end, we will synthesize a new end
594           // that switches back to the parent DIE below. And this interval will
595           // get dropped in favor of one with a DIE attached. However, we'll
596           // still include this and so worst-case, it will still end the prior
597           // interval.
598           continue;
599         }
600 
601         // We are walking the new ranges in order, so search forward from the
602         // last point for a parent range that might overlap.
603         auto ParentIntervalsRange =
604             make_range(AddrMap.begin() + ParentIntervalIdx,
605                        AddrMap.begin() + ParentIntervalsEndIdx);
606         assert(std::is_sorted(ParentIntervalsRange.begin(),
607                               ParentIntervalsRange.end(), less_first()) &&
608                "Unsorted parent intervals can't be searched!");
609         auto PI = std::upper_bound(
610             ParentIntervalsRange.begin(), ParentIntervalsRange.end(),
611             IntervalStart,
612             [](uint32_t LHS, const std::pair<uint32_t, int32_t> &RHS) {
613               return LHS < RHS.first;
614             });
615         if (PI == ParentIntervalsRange.begin() ||
616             PI == ParentIntervalsRange.end())
617           continue;
618 
619         ParentIntervalIdx = PI - AddrMap.begin();
620         int32_t &ParentIntervalDieIdx = std::prev(PI)->second;
621         uint32_t &ParentIntervalStart = std::prev(PI)->first;
622         const uint32_t ParentIntervalEnd = PI->first;
623 
624         // If the new range starts exactly at the position of the parent range,
625         // we need to adjust the parent range. Note that these collisions can
626         // only happen with the original parent range because we will merge any
627         // adjacent ranges in the child.
628         if (IntervalStart == ParentIntervalStart) {
629           // If there will be a tail, just shift the start of the parent
630           // forward. Note that this cannot change the parent ordering.
631           if (IntervalEnd < ParentIntervalEnd) {
632             ParentIntervalStart = IntervalEnd;
633             continue;
634           }
635           // Otherwise, mark this as becoming empty so we'll remove it and
636           // prefer the child range.
637           ParentIntervalDieIdx = -1;
638           continue;
639         }
640 
641         // Finally, if the parent interval will need to remain as a prefix to
642         // this one, insert a new interval to cover any tail.
643         if (IntervalEnd < ParentIntervalEnd)
644           AddrMap.push_back({IntervalEnd, ParentIntervalDieIdx});
645       }
646     }
647 
648     // Note that we don't need to re-sort even this DIE's address map intervals
649     // after this. All of the newly added intervals actually fill in *gaps* in
650     // this DIE's address map, and we know that children won't need to lookup
651     // into those gaps.
652 
653     // Recurse through its children, giving them the interval map range of this
654     // DIE to use as their parent intervals.
655     EnqueueChildDIEs(Die, DieIntervalsBeginIdx, DieIntervalsEndIdx);
656   }
657 
658   if (AddrMap.empty()) {
659     AddrMap.push_back({0, -1});
660     return;
661   }
662 
663   // Now that we've added all of the intervals needed, we need to resort and
664   // unique them. Most notably, this will remove all the empty ranges that had
665   // a parent range covering, etc. We only expect a single non-empty interval
666   // at any given start point, so we just use std::sort. This could potentially
667   // produce non-deterministic maps for invalid DWARF.
668   std::sort(AddrMap.begin(), AddrMap.end(), SubroutineAddrMapSorter);
669   AddrMap.erase(
670       std::unique(AddrMap.begin(), AddrMap.end(), SubroutineAddrMapUniquer),
671       AddrMap.end());
672 }
673 
674 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
675   extractDIEsIfNeeded(false);
676 
677   // We use a two-level mapping structure to locate subroutines for a given PC
678   // address.
679   //
680   // First, we map the address to a subprogram. This can be done more cheaply
681   // because subprograms cannot nest within each other. It also allows us to
682   // avoid detailed examination of many subprograms, instead only focusing on
683   // the ones which we end up actively querying.
684   if (SubprogramDIEAddrMap.empty())
685     buildSubprogramDIEAddrMap();
686 
687   assert(!SubprogramDIEAddrMap.empty() &&
688          "We must always end up with a non-empty map!");
689 
690   auto I = std::upper_bound(
691       SubprogramDIEAddrMap.begin(), SubprogramDIEAddrMap.end(), Address,
692       [](uint64_t LHS, const std::pair<uint64_t, int64_t> &RHS) {
693         return LHS < RHS.first;
694       });
695   // If we find the beginning, then the address is before the first subprogram.
696   if (I == SubprogramDIEAddrMap.begin())
697     return DWARFDie();
698   // Back up to the interval containing the address and see if it
699   // has a DIE associated with it.
700   --I;
701   if (I->second == -1)
702     return DWARFDie();
703 
704   auto &SPInfo = SubprogramDIEAddrInfos[I->second];
705 
706   // Now that we have the subprogram for this address, we do the second level
707   // mapping by building a map within a subprogram's PC range to any specific
708   // inlined subroutine.
709   if (SPInfo.InlinedSubroutineDIEAddrMap.empty())
710     buildInlinedSubroutineDIEAddrMap(SPInfo);
711 
712   // We lookup within the inlined subroutine using a subprogram-relative
713   // address.
714   assert(Address >= SPInfo.SubprogramBasePC &&
715          "Address isn't above the start of the subprogram!");
716   uint32_t RelativeAddr = ((Address - SPInfo.SubprogramBasePC) >
717                            (uint64_t)std::numeric_limits<uint32_t>::max())
718                               ? std::numeric_limits<uint32_t>::max()
719                               : (uint32_t)(Address - SPInfo.SubprogramBasePC);
720 
721   auto J =
722       std::upper_bound(SPInfo.InlinedSubroutineDIEAddrMap.begin(),
723                        SPInfo.InlinedSubroutineDIEAddrMap.end(), RelativeAddr,
724                        [](uint32_t LHS, const std::pair<uint32_t, int32_t> &RHS) {
725                          return LHS < RHS.first;
726                        });
727   // If we find the beginning, the address is before any inlined subroutine so
728   // return the subprogram DIE.
729   if (J == SPInfo.InlinedSubroutineDIEAddrMap.begin())
730     return SPInfo.SubprogramDIE;
731   // Back up `J` and return the inlined subroutine if we have one or the
732   // subprogram if we don't.
733   --J;
734   return J->second == -1 ? SPInfo.SubprogramDIE
735                          : InlinedSubroutineDIEs[J->second];
736 }
737 
738 void
739 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
740                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
741   assert(InlinedChain.empty());
742   // Try to look for subprogram DIEs in the DWO file.
743   parseDWO();
744   // First, find the subroutine that contains the given address (the leaf
745   // of inlined chain).
746   DWARFDie SubroutineDIE =
747       (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
748 
749   while (SubroutineDIE) {
750     if (SubroutineDIE.isSubroutineDIE())
751       InlinedChain.push_back(SubroutineDIE);
752     SubroutineDIE  = SubroutineDIE.getParent();
753   }
754 }
755 
756 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
757                                               DWARFSectionKind Kind) {
758   if (Kind == DW_SECT_INFO)
759     return Context.getCUIndex();
760   assert(Kind == DW_SECT_TYPES);
761   return Context.getTUIndex();
762 }
763 
764 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
765   if (!Die)
766     return DWARFDie();
767   const uint32_t Depth = Die->getDepth();
768   // Unit DIEs always have a depth of zero and never have parents.
769   if (Depth == 0)
770     return DWARFDie();
771   // Depth of 1 always means parent is the compile/type unit.
772   if (Depth == 1)
773     return getUnitDIE();
774   // Look for previous DIE with a depth that is one less than the Die's depth.
775   const uint32_t ParentDepth = Depth - 1;
776   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
777     if (DieArray[I].getDepth() == ParentDepth)
778       return DWARFDie(this, &DieArray[I]);
779   }
780   return DWARFDie();
781 }
782 
783 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
784   if (!Die)
785     return DWARFDie();
786   uint32_t Depth = Die->getDepth();
787   // Unit DIEs always have a depth of zero and never have siblings.
788   if (Depth == 0)
789     return DWARFDie();
790   // NULL DIEs don't have siblings.
791   if (Die->getAbbreviationDeclarationPtr() == nullptr)
792     return DWARFDie();
793 
794   // Find the next DIE whose depth is the same as the Die's depth.
795   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
796        ++I) {
797     if (DieArray[I].getDepth() == Depth)
798       return DWARFDie(this, &DieArray[I]);
799   }
800   return DWARFDie();
801 }
802 
803 DWARFDie DWARFUnit::getFirstChild(const DWARFDebugInfoEntry *Die) {
804   if (!Die->hasChildren())
805     return DWARFDie();
806 
807   // We do not want access out of bounds when parsing corrupted debug data.
808   size_t I = getDIEIndex(Die) + 1;
809   if (I >= DieArray.size())
810     return DWARFDie();
811   return DWARFDie(this, &DieArray[I]);
812 }
813 
814 const DWARFAbbreviationDeclarationSet *DWARFUnit::getAbbreviations() const {
815   if (!Abbrevs)
816     Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
817   return Abbrevs;
818 }
819 
820 Optional<StrOffsetsContributionDescriptor>
821 StrOffsetsContributionDescriptor::validateContributionSize(
822     DWARFDataExtractor &DA) {
823   uint8_t EntrySize = getDwarfOffsetByteSize();
824   // In order to ensure that we don't read a partial record at the end of
825   // the section we validate for a multiple of the entry size.
826   uint64_t ValidationSize = alignTo(Size, EntrySize);
827   // Guard against overflow.
828   if (ValidationSize >= Size)
829     if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
830       return *this;
831   return Optional<StrOffsetsContributionDescriptor>();
832 }
833 
834 // Look for a DWARF64-formatted contribution to the string offsets table
835 // starting at a given offset and record it in a descriptor.
836 static Optional<StrOffsetsContributionDescriptor>
837 parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
838   if (!DA.isValidOffsetForDataOfSize(Offset, 16))
839     return Optional<StrOffsetsContributionDescriptor>();
840 
841   if (DA.getU32(&Offset) != 0xffffffff)
842     return Optional<StrOffsetsContributionDescriptor>();
843 
844   uint64_t Size = DA.getU64(&Offset);
845   uint8_t Version = DA.getU16(&Offset);
846   (void)DA.getU16(&Offset); // padding
847   return StrOffsetsContributionDescriptor(Offset, Size, Version, DWARF64);
848   //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
849 }
850 
851 // Look for a DWARF32-formatted contribution to the string offsets table
852 // starting at a given offset and record it in a descriptor.
853 static Optional<StrOffsetsContributionDescriptor>
854 parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset) {
855   if (!DA.isValidOffsetForDataOfSize(Offset, 8))
856     return Optional<StrOffsetsContributionDescriptor>();
857   uint32_t ContributionSize = DA.getU32(&Offset);
858   if (ContributionSize >= 0xfffffff0)
859     return Optional<StrOffsetsContributionDescriptor>();
860   uint8_t Version = DA.getU16(&Offset);
861   (void)DA.getU16(&Offset); // padding
862   return StrOffsetsContributionDescriptor(Offset, ContributionSize, Version, DWARF32);
863   //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
864 }
865 
866 Optional<StrOffsetsContributionDescriptor>
867 DWARFUnit::determineStringOffsetsTableContribution(DWARFDataExtractor &DA,
868                                                    uint64_t Offset) {
869   Optional<StrOffsetsContributionDescriptor> Descriptor;
870   // Attempt to find a DWARF64 contribution 16 bytes before the base.
871   if (Offset >= 16)
872     Descriptor =
873         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset - 16);
874   // Try to find a DWARF32 contribution 8 bytes before the base.
875   if (!Descriptor && Offset >= 8)
876     Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset - 8);
877   return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
878 }
879 
880 Optional<StrOffsetsContributionDescriptor>
881 DWARFUnit::determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA,
882                                                       uint64_t Offset) {
883   if (getVersion() >= 5) {
884     // Look for a valid contribution at the given offset.
885     auto Descriptor =
886         parseDWARF64StringOffsetsTableHeader(DA, (uint32_t)Offset);
887     if (!Descriptor)
888       Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset);
889     return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
890   }
891   // Prior to DWARF v5, we derive the contribution size from the
892   // index table (in a package file). In a .dwo file it is simply
893   // the length of the string offsets section.
894   uint64_t Size = 0;
895   if (!IndexEntry)
896     Size = StringOffsetSection.Data.size();
897   else if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
898     Size = C->Length;
899   // Return a descriptor with the given offset as base, version 4 and
900   // DWARF32 format.
901   //return Optional<StrOffsetsContributionDescriptor>(
902       //StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32));
903   return StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32);
904 }
905