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