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