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