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