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