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