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