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