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/Object/ObjectFile.h"
21 #include "llvm/Support/Casting.h"
22 #include "llvm/Support/DataExtractor.h"
23 #include "llvm/Support/Path.h"
24 #include <algorithm>
25 #include <cassert>
26 #include <cstddef>
27 #include <cstdint>
28 #include <cstdio>
29 #include <vector>
30 
31 using namespace llvm;
32 using namespace dwarf;
33 
34 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
35   parseImpl(C, Section, C.getDebugAbbrev(), &C.getRangeSection(),
36             C.getStringSection(), C.getStringOffsetSection(),
37             &C.getAddrSection(), C.getLineSection().Data, C.isLittleEndian(),
38             false);
39 }
40 
41 void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
42                                     const DWARFSection &DWOSection,
43                                     DWARFUnitIndex *Index) {
44   parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), &C.getRangeDWOSection(),
45             C.getStringDWOSection(), C.getStringOffsetDWOSection(),
46             &C.getAddrSection(), C.getLineDWOSection().Data, C.isLittleEndian(),
47             true);
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, StringRef LS, bool LE, bool IsDWO,
54                      const DWARFUnitSectionBase &UnitSection,
55                      const DWARFUnitIndex::Entry *IndexEntry)
56     : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
57       LineSection(LS), StringSection(SS), StringOffsetSection(SOS),
58       StringOffsetSectionBase(0), AddrOffsetSection(AOS), isLittleEndian(LE),
59       isDWO(IsDWO), UnitSection(UnitSection), IndexEntry(IndexEntry) {
60   clear();
61 }
62 
63 DWARFUnit::~DWARFUnit() = default;
64 
65 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
66                                                 uint64_t &Result) const {
67   uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
68   if (AddrOffsetSection->Data.size() < Offset + AddrSize)
69     return false;
70   DataExtractor DA(AddrOffsetSection->Data, isLittleEndian, AddrSize);
71   Result = getRelocatedValue(DA, AddrSize, &Offset, &AddrOffsetSection->Relocs);
72   return true;
73 }
74 
75 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
76                                            uint64_t &Result) const {
77   unsigned ItemSize = getFormat() == DWARF64 ? 8 : 4;
78   uint32_t Offset = StringOffsetSectionBase + Index * ItemSize;
79   if (StringOffsetSection.Data.size() < Offset + ItemSize)
80     return false;
81   DataExtractor DA(StringOffsetSection.Data, isLittleEndian, 0);
82   Result = ItemSize == 4 ? DA.getU32(&Offset) : DA.getU64(&Offset);
83   return true;
84 }
85 
86 uint64_t DWARFUnit::getStringOffsetSectionRelocation(uint32_t Index) const {
87   unsigned ItemSize = getFormat() == DWARF64 ? 8 : 4;
88   uint64_t ByteOffset = StringOffsetSectionBase + Index * ItemSize;
89   RelocAddrMap::const_iterator AI = getStringOffsetsRelocMap().find(ByteOffset);
90   if (AI != getStringOffsetsRelocMap().end())
91     return AI->second.Value;
92   return 0;
93 }
94 
95 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
96   Length = debug_info.getU32(offset_ptr);
97   Version = debug_info.getU16(offset_ptr);
98   uint64_t AbbrOffset;
99   if (Version >= 5) {
100     UnitType = debug_info.getU8(offset_ptr);
101     AddrSize = debug_info.getU8(offset_ptr);
102     AbbrOffset = debug_info.getU32(offset_ptr);
103   } else {
104     AbbrOffset = debug_info.getU32(offset_ptr);
105     AddrSize = debug_info.getU8(offset_ptr);
106   }
107   if (IndexEntry) {
108     if (AbbrOffset)
109       return false;
110     auto *UnitContrib = IndexEntry->getOffset();
111     if (!UnitContrib || UnitContrib->Length != (Length + 4))
112       return false;
113     auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
114     if (!AbbrEntry)
115       return false;
116     AbbrOffset = AbbrEntry->Offset;
117   }
118 
119   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
120   bool VersionOK = DWARFContext::isSupportedVersion(Version);
121   bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
122 
123   if (!LengthOK || !VersionOK || !AddrSizeOK)
124     return false;
125 
126   // Keep track of the highest DWARF version we encounter across all units.
127   Context.setMaxVersionIfGreater(Version);
128 
129   Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
130   return Abbrevs != nullptr;
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   DataExtractor RangesData(RangeSection->Data, isLittleEndian, AddrSize);
154   uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
155   return RangeList.extract(RangesData, &ActualRangeListOffset,
156                            RangeSection->Relocs);
157 }
158 
159 void DWARFUnit::clear() {
160   Offset = 0;
161   Length = 0;
162   Version = 0;
163   Abbrevs = nullptr;
164   AddrSize = 0;
165   BaseAddr = 0;
166   RangeSectionBase = 0;
167   AddrOffsetSectionBase = 0;
168   clearDIEs(false);
169   DWO.reset();
170 }
171 
172 const char *DWARFUnit::getCompilationDir() {
173   return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
174 }
175 
176 Optional<uint64_t> DWARFUnit::getDWOId() {
177   return toUnsigned(getUnitDIE().find(DW_AT_GNU_dwo_id));
178 }
179 
180 void DWARFUnit::extractDIEsToVector(
181     bool AppendCUDie, bool AppendNonCUDies,
182     std::vector<DWARFDebugInfoEntry> &Dies) const {
183   if (!AppendCUDie && !AppendNonCUDies)
184     return;
185 
186   // Set the offset to that of the first DIE and calculate the start of the
187   // next compilation unit header.
188   uint32_t DIEOffset = Offset + getHeaderSize();
189   uint32_t NextCUOffset = getNextUnitOffset();
190   DWARFDebugInfoEntry DIE;
191   DataExtractor DebugInfoData = getDebugInfoExtractor();
192   uint32_t Depth = 0;
193   bool IsCUDie = true;
194 
195   while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
196                          Depth)) {
197     if (IsCUDie) {
198       if (AppendCUDie)
199         Dies.push_back(DIE);
200       if (!AppendNonCUDies)
201         break;
202       // The average bytes per DIE entry has been seen to be
203       // around 14-20 so let's pre-reserve the needed memory for
204       // our DIE entries accordingly.
205       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
206       IsCUDie = false;
207     } else {
208       Dies.push_back(DIE);
209     }
210 
211     if (const DWARFAbbreviationDeclaration *AbbrDecl =
212             DIE.getAbbreviationDeclarationPtr()) {
213       // Normal DIE
214       if (AbbrDecl->hasChildren())
215         ++Depth;
216     } else {
217       // NULL DIE.
218       if (Depth > 0)
219         --Depth;
220       if (Depth == 0)
221         break;  // We are done with this compile unit!
222     }
223   }
224 
225   // Give a little bit of info if we encounter corrupt DWARF (our offset
226   // should always terminate at or before the start of the next compilation
227   // unit header).
228   if (DIEOffset > NextCUOffset)
229     fprintf(stderr, "warning: DWARF compile unit extends beyond its "
230                     "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
231 }
232 
233 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
234   if ((CUDieOnly && !DieArray.empty()) ||
235       DieArray.size() > 1)
236     return 0; // Already parsed.
237 
238   bool HasCUDie = !DieArray.empty();
239   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
240 
241   if (DieArray.empty())
242     return 0;
243 
244   // If CU DIE was just parsed, copy several attribute values from it.
245   if (!HasCUDie) {
246     DWARFDie UnitDie = getUnitDIE();
247     auto BaseAddr = toAddress(UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc}));
248     if (BaseAddr)
249       setBaseAddress(*BaseAddr);
250     AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
251     RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
252 
253     // In general, we derive the offset of the unit's contibution to the
254     // debug_str_offsets{.dwo} section from the unit DIE's
255     // DW_AT_str_offsets_base attribute. In dwp files we add to it the offset
256     // we get from the index table.
257     StringOffsetSectionBase =
258         toSectionOffset(UnitDie.find(DW_AT_str_offsets_base), 0);
259     if (IndexEntry)
260       if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
261         StringOffsetSectionBase += C->Offset;
262 
263     // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
264     // skeleton CU DIE, so that DWARF users not aware of it are not broken.
265   }
266 
267   return DieArray.size();
268 }
269 
270 bool DWARFUnit::parseDWO() {
271   if (isDWO)
272     return false;
273   if (DWO.get())
274     return false;
275   DWARFDie UnitDie = getUnitDIE();
276   if (!UnitDie)
277     return false;
278   auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
279   if (!DWOFileName)
280     return false;
281   auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
282   SmallString<16> AbsolutePath;
283   if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
284       *CompilationDir) {
285     sys::path::append(AbsolutePath, *CompilationDir);
286   }
287   sys::path::append(AbsolutePath, *DWOFileName);
288   auto DWOId = getDWOId();
289   if (!DWOId)
290     return false;
291   auto DWOContext = Context.getDWOContext(AbsolutePath);
292   if (!DWOContext)
293     return false;
294 
295   DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
296   if (!DWOCU)
297     return false;
298   DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
299   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
300   DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
301   auto DWORangesBase = UnitDie.getRangesBaseAttribute();
302   DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
303   return true;
304 }
305 
306 void DWARFUnit::clearDIEs(bool KeepCUDie) {
307   if (DieArray.size() > (unsigned)KeepCUDie) {
308     // std::vectors never get any smaller when resized to a smaller size,
309     // or when clear() or erase() are called, the size will report that it
310     // is smaller, but the memory allocated remains intact (call capacity()
311     // to see this). So we need to create a temporary vector and swap the
312     // contents which will cause just the internal pointers to be swapped
313     // so that when temporary vector goes out of scope, it will destroy the
314     // contents.
315     std::vector<DWARFDebugInfoEntry> TmpArray;
316     DieArray.swap(TmpArray);
317     // Save at least the compile unit DIE
318     if (KeepCUDie)
319       DieArray.push_back(TmpArray.front());
320   }
321 }
322 
323 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
324   DWARFDie UnitDie = getUnitDIE();
325   if (!UnitDie)
326     return;
327   // First, check if unit DIE describes address ranges for the whole unit.
328   const auto &CUDIERanges = UnitDie.getAddressRanges();
329   if (!CUDIERanges.empty()) {
330     CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
331     return;
332   }
333 
334   // This function is usually called if there in no .debug_aranges section
335   // in order to produce a compile unit level set of address ranges that
336   // is accurate. If the DIEs weren't parsed, then we don't want all dies for
337   // all compile units to stay loaded when they weren't needed. So we can end
338   // up parsing the DWARF and then throwing them all away to keep memory usage
339   // down.
340   const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
341   getUnitDIE().collectChildrenAddressRanges(CURanges);
342 
343   // Collect address ranges from DIEs in .dwo if necessary.
344   bool DWOCreated = parseDWO();
345   if (DWO)
346     DWO->collectAddressRanges(CURanges);
347   if (DWOCreated)
348     DWO.reset();
349 
350   // Keep memory down by clearing DIEs if this generate function
351   // caused them to be parsed.
352   if (ClearDIEs)
353     clearDIEs(true);
354 }
355 
356 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
357   if (Die.isSubroutineDIE()) {
358     for (const auto &R : Die.getAddressRanges()) {
359       // Ignore 0-sized ranges.
360       if (R.LowPC == R.HighPC)
361         continue;
362       auto B = AddrDieMap.upper_bound(R.LowPC);
363       if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
364         // The range is a sub-range of existing ranges, we need to split the
365         // existing range.
366         if (R.HighPC < B->second.first)
367           AddrDieMap[R.HighPC] = B->second;
368         if (R.LowPC > B->first)
369           AddrDieMap[B->first].first = R.LowPC;
370       }
371       AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
372     }
373   }
374   // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
375   // simplify the logic to update AddrDieMap. The child's range will always
376   // be equal or smaller than the parent's range. With this assumption, when
377   // adding one range into the map, it will at most split a range into 3
378   // sub-ranges.
379   for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
380     updateAddressDieMap(Child);
381 }
382 
383 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
384   extractDIEsIfNeeded(false);
385   if (AddrDieMap.empty())
386     updateAddressDieMap(getUnitDIE());
387   auto R = AddrDieMap.upper_bound(Address);
388   if (R == AddrDieMap.begin())
389     return DWARFDie();
390   // upper_bound's previous item contains Address.
391   --R;
392   if (Address >= R->second.first)
393     return DWARFDie();
394   return R->second.second;
395 }
396 
397 void
398 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
399                                      SmallVectorImpl<DWARFDie> &InlinedChain) {
400   assert(InlinedChain.empty());
401   // Try to look for subprogram DIEs in the DWO file.
402   parseDWO();
403   // First, find the subroutine that contains the given address (the leaf
404   // of inlined chain).
405   DWARFDie SubroutineDIE =
406       (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
407 
408   while (SubroutineDIE) {
409     if (SubroutineDIE.isSubroutineDIE())
410       InlinedChain.push_back(SubroutineDIE);
411     SubroutineDIE  = SubroutineDIE.getParent();
412   }
413 }
414 
415 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
416                                               DWARFSectionKind Kind) {
417   if (Kind == DW_SECT_INFO)
418     return Context.getCUIndex();
419   assert(Kind == DW_SECT_TYPES);
420   return Context.getTUIndex();
421 }
422 
423 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
424   if (!Die)
425     return DWARFDie();
426   const uint32_t Depth = Die->getDepth();
427   // Unit DIEs always have a depth of zero and never have parents.
428   if (Depth == 0)
429     return DWARFDie();
430   // Depth of 1 always means parent is the compile/type unit.
431   if (Depth == 1)
432     return getUnitDIE();
433   // Look for previous DIE with a depth that is one less than the Die's depth.
434   const uint32_t ParentDepth = Depth - 1;
435   for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
436     if (DieArray[I].getDepth() == ParentDepth)
437       return DWARFDie(this, &DieArray[I]);
438   }
439   return DWARFDie();
440 }
441 
442 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
443   if (!Die)
444     return DWARFDie();
445   uint32_t Depth = Die->getDepth();
446   // Unit DIEs always have a depth of zero and never have siblings.
447   if (Depth == 0)
448     return DWARFDie();
449   // NULL DIEs don't have siblings.
450   if (Die->getAbbreviationDeclarationPtr() == nullptr)
451     return DWARFDie();
452 
453   // Find the next DIE whose depth is the same as the Die's depth.
454   for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
455        ++I) {
456     if (DieArray[I].getDepth() == Depth)
457       return DWARFDie(this, &DieArray[I]);
458   }
459   return DWARFDie();
460 }
461