dwarfdump: Use the index to find the right abbrev offset in DWP files
[oota-llvm.git] / 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/DebugInfo/DWARF/DWARFContext.h"
12 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
13 #include "llvm/Support/Dwarf.h"
14 #include "llvm/Support/Path.h"
15 #include <cstdio>
16
17 namespace llvm {
18 using namespace dwarf;
19
20 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
21   parseImpl(C, Section, C.getDebugAbbrev(), C.getRangeSection(),
22             C.getStringSection(), StringRef(), C.getAddrSection(),
23             C.isLittleEndian());
24 }
25
26 void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
27                                     const DWARFSection &DWOSection,
28                                     DWARFUnitIndex *Index) {
29   parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), C.getRangeDWOSection(),
30             C.getStringDWOSection(), C.getStringOffsetDWOSection(),
31             C.getAddrSection(), C.isLittleEndian());
32 }
33
34 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
35                      const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS,
36                      StringRef SOS, StringRef AOS, bool LE,
37                      const DWARFUnitSectionBase &UnitSection,
38                      const DWARFUnitIndex::Entry *IndexEntry)
39     : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
40       StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
41       isLittleEndian(LE), UnitSection(UnitSection), IndexEntry(IndexEntry) {
42   clear();
43 }
44
45 DWARFUnit::~DWARFUnit() {
46 }
47
48 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
49                                                 uint64_t &Result) const {
50   uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
51   if (AddrOffsetSection.size() < Offset + AddrSize)
52     return false;
53   DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
54   Result = DA.getAddress(&Offset);
55   return true;
56 }
57
58 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
59                                                   uint32_t &Result) const {
60   // FIXME: string offset section entries are 8-byte for DWARF64.
61   const uint32_t ItemSize = 4;
62   uint32_t Offset = Index * ItemSize;
63   if (StringOffsetSection.size() < Offset + ItemSize)
64     return false;
65   DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
66   Result = DA.getU32(&Offset);
67   return true;
68 }
69
70 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
71   Length = debug_info.getU32(offset_ptr);
72   Version = debug_info.getU16(offset_ptr);
73   uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
74   if (IndexEntry) {
75     if (AbbrOffset)
76       return false;
77     auto *UnitContrib = IndexEntry->getOffset();
78     if (!UnitContrib || UnitContrib->Length != (Length + 4))
79       return false;
80     auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
81     if (!AbbrEntry)
82       return false;
83     AbbrOffset = AbbrEntry->Offset;
84   }
85   AddrSize = debug_info.getU8(offset_ptr);
86
87   bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
88   bool VersionOK = DWARFContext::isSupportedVersion(Version);
89   bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
90
91   if (!LengthOK || !VersionOK || !AddrSizeOK)
92     return false;
93
94   Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
95   return Abbrevs != nullptr;
96 }
97
98 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
99   clear();
100
101   Offset = *offset_ptr;
102
103   if (debug_info.isValidOffset(*offset_ptr)) {
104     if (extractImpl(debug_info, offset_ptr))
105       return true;
106
107     // reset the offset to where we tried to parse from if anything went wrong
108     *offset_ptr = Offset;
109   }
110
111   return false;
112 }
113
114 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
115                                         DWARFDebugRangeList &RangeList) const {
116   // Require that compile unit is extracted.
117   assert(DieArray.size() > 0);
118   DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
119   uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
120   return RangeList.extract(RangesData, &ActualRangeListOffset);
121 }
122
123 void DWARFUnit::clear() {
124   Offset = 0;
125   Length = 0;
126   Version = 0;
127   Abbrevs = nullptr;
128   AddrSize = 0;
129   BaseAddr = 0;
130   RangeSectionBase = 0;
131   AddrOffsetSectionBase = 0;
132   clearDIEs(false);
133   DWO.reset();
134 }
135
136 const char *DWARFUnit::getCompilationDir() {
137   extractDIEsIfNeeded(true);
138   if (DieArray.empty())
139     return nullptr;
140   return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
141 }
142
143 uint64_t DWARFUnit::getDWOId() {
144   extractDIEsIfNeeded(true);
145   const uint64_t FailValue = -1ULL;
146   if (DieArray.empty())
147     return FailValue;
148   return DieArray[0]
149       .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
150 }
151
152 void DWARFUnit::setDIERelations() {
153   if (DieArray.size() <= 1)
154     return;
155
156   std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
157   DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
158   for (auto &DIE : DieArray) {
159     if (SiblingChain) {
160       SiblingChain->setSibling(&DIE);
161     }
162     if (const DWARFAbbreviationDeclaration *AbbrDecl =
163             DIE.getAbbreviationDeclarationPtr()) {
164       // Normal DIE.
165       if (AbbrDecl->hasChildren()) {
166         ParentChain.push_back(&DIE);
167         SiblingChain = nullptr;
168       } else {
169         SiblingChain = &DIE;
170       }
171     } else {
172       // NULL entry terminates the sibling chain.
173       SiblingChain = ParentChain.back();
174       ParentChain.pop_back();
175     }
176   }
177   assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
178   assert(ParentChain.empty());
179 }
180
181 void DWARFUnit::extractDIEsToVector(
182     bool AppendCUDie, bool AppendNonCUDies,
183     std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
184   if (!AppendCUDie && !AppendNonCUDies)
185     return;
186
187   // Set the offset to that of the first DIE and calculate the start of the
188   // next compilation unit header.
189   uint32_t DIEOffset = Offset + getHeaderSize();
190   uint32_t NextCUOffset = getNextUnitOffset();
191   DWARFDebugInfoEntryMinimal DIE;
192   uint32_t Depth = 0;
193   bool IsCUDie = true;
194
195   while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
196     if (IsCUDie) {
197       if (AppendCUDie)
198         Dies.push_back(DIE);
199       if (!AppendNonCUDies)
200         break;
201       // The average bytes per DIE entry has been seen to be
202       // around 14-20 so let's pre-reserve the needed memory for
203       // our DIE entries accordingly.
204       Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
205       IsCUDie = false;
206     } else {
207       Dies.push_back(DIE);
208     }
209
210     if (const DWARFAbbreviationDeclaration *AbbrDecl =
211             DIE.getAbbreviationDeclarationPtr()) {
212       // Normal DIE
213       if (AbbrDecl->hasChildren())
214         ++Depth;
215     } else {
216       // NULL DIE.
217       if (Depth > 0)
218         --Depth;
219       if (Depth == 0)
220         break;  // We are done with this compile unit!
221     }
222   }
223
224   // Give a little bit of info if we encounter corrupt DWARF (our offset
225   // should always terminate at or before the start of the next compilation
226   // unit header).
227   if (DIEOffset > NextCUOffset)
228     fprintf(stderr, "warning: DWARF compile unit extends beyond its "
229                     "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
230 }
231
232 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
233   if ((CUDieOnly && DieArray.size() > 0) ||
234       DieArray.size() > 1)
235     return 0; // Already parsed.
236
237   bool HasCUDie = DieArray.size() > 0;
238   extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
239
240   if (DieArray.empty())
241     return 0;
242
243   // If CU DIE was just parsed, copy several attribute values from it.
244   if (!HasCUDie) {
245     uint64_t BaseAddr =
246         DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
247     if (BaseAddr == -1ULL)
248       BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
249     setBaseAddress(BaseAddr);
250     AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
251         this, DW_AT_GNU_addr_base, 0);
252     RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
253         this, DW_AT_ranges_base, 0);
254     // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
255     // skeleton CU DIE, so that DWARF users not aware of it are not broken.
256   }
257
258   setDIERelations();
259   return DieArray.size();
260 }
261
262 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
263     : DWOFile(), DWOContext(), DWOU(nullptr) {
264   auto Obj = object::ObjectFile::createObjectFile(DWOPath);
265   if (!Obj)
266     return;
267   DWOFile = std::move(Obj.get());
268   DWOContext.reset(
269       cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary())));
270   if (DWOContext->getNumDWOCompileUnits() > 0)
271     DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
272 }
273
274 bool DWARFUnit::parseDWO() {
275   if (DWO.get())
276     return false;
277   extractDIEsIfNeeded(true);
278   if (DieArray.empty())
279     return false;
280   const char *DWOFileName =
281       DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
282   if (!DWOFileName)
283     return false;
284   const char *CompilationDir =
285       DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
286   SmallString<16> AbsolutePath;
287   if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
288     sys::path::append(AbsolutePath, CompilationDir);
289   }
290   sys::path::append(AbsolutePath, DWOFileName);
291   DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
292   DWARFUnit *DWOCU = DWO->getUnit();
293   // Verify that compile unit in .dwo file is valid.
294   if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
295     DWO.reset();
296     return false;
297   }
298   // Share .debug_addr and .debug_ranges section with compile unit in .dwo
299   DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
300   uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
301   DWOCU->setRangesSection(RangeSection, DWORangesBase);
302   return true;
303 }
304
305 void DWARFUnit::clearDIEs(bool KeepCUDie) {
306   if (DieArray.size() > (unsigned)KeepCUDie) {
307     // std::vectors never get any smaller when resized to a smaller size,
308     // or when clear() or erase() are called, the size will report that it
309     // is smaller, but the memory allocated remains intact (call capacity()
310     // to see this). So we need to create a temporary vector and swap the
311     // contents which will cause just the internal pointers to be swapped
312     // so that when temporary vector goes out of scope, it will destroy the
313     // contents.
314     std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
315     DieArray.swap(TmpArray);
316     // Save at least the compile unit DIE
317     if (KeepCUDie)
318       DieArray.push_back(TmpArray.front());
319   }
320 }
321
322 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
323   const auto *U = getUnitDIE();
324   if (U == nullptr)
325     return;
326   // First, check if unit DIE describes address ranges for the whole unit.
327   const auto &CUDIERanges = U->getAddressRanges(this);
328   if (!CUDIERanges.empty()) {
329     CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
330     return;
331   }
332
333   // This function is usually called if there in no .debug_aranges section
334   // in order to produce a compile unit level set of address ranges that
335   // is accurate. If the DIEs weren't parsed, then we don't want all dies for
336   // all compile units to stay loaded when they weren't needed. So we can end
337   // up parsing the DWARF and then throwing them all away to keep memory usage
338   // down.
339   const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
340   DieArray[0].collectChildrenAddressRanges(this, CURanges);
341
342   // Collect address ranges from DIEs in .dwo if necessary.
343   bool DWOCreated = parseDWO();
344   if (DWO.get())
345     DWO->getUnit()->collectAddressRanges(CURanges);
346   if (DWOCreated)
347     DWO.reset();
348
349   // Keep memory down by clearing DIEs if this generate function
350   // caused them to be parsed.
351   if (ClearDIEs)
352     clearDIEs(true);
353 }
354
355 const DWARFDebugInfoEntryMinimal *
356 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
357   extractDIEsIfNeeded(false);
358   for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
359     if (DIE.isSubprogramDIE() &&
360         DIE.addressRangeContainsAddress(this, Address)) {
361       return &DIE;
362     }
363   }
364   return nullptr;
365 }
366
367 DWARFDebugInfoEntryInlinedChain
368 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
369   // First, find a subprogram that contains the given address (the root
370   // of inlined chain).
371   const DWARFUnit *ChainCU = nullptr;
372   const DWARFDebugInfoEntryMinimal *SubprogramDIE =
373       getSubprogramForAddress(Address);
374   if (SubprogramDIE) {
375     ChainCU = this;
376   } else {
377     // Try to look for subprogram DIEs in the DWO file.
378     parseDWO();
379     if (DWO.get()) {
380       SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
381       if (SubprogramDIE)
382         ChainCU = DWO->getUnit();
383     }
384   }
385
386   // Get inlined chain rooted at this subprogram DIE.
387   if (!SubprogramDIE)
388     return DWARFDebugInfoEntryInlinedChain();
389   return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);
390 }
391
392 const DWARFUnitIndex &getDWARFUnitIndex(DWARFContext &Context,
393                                         DWARFSectionKind Kind) {
394   if (Kind == DW_SECT_INFO)
395     return Context.getCUIndex();
396   assert(Kind == DW_SECT_TYPES);
397   return Context.getTUIndex();
398 }
399 }