1 //===-- DWARFUnit.cpp -----------------------------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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"
17 using namespace dwarf;
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) {
28 DWARFUnit::~DWARFUnit() {
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)
36 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
37 Result = DA.getAddress(&Offset);
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)
48 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
49 Result = DA.getU32(&Offset);
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);
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;
64 if (!lengthOK || !versionOK || !addrSizeOK || !abbrOffsetOK)
67 Abbrevs = Abbrev->getAbbreviationDeclarationSet(abbrOffset);
71 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
76 if (debug_info.isValidOffset(*offset_ptr)) {
77 if (extractImpl(debug_info, offset_ptr))
80 // reset the offset to where we tried to parse from if anything went wrong
88 DWARFUnit::extract(uint32_t offset, DataExtractor debug_info_data,
89 const DWARFAbbreviationDeclarationSet *abbrevs) {
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();
99 AddrSize = debug_info_data.getU8(&offset);
101 bool versionOK = DWARFContext::isSupportedVersion(Version);
102 bool addrSizeOK = AddrSize == 4 || AddrSize == 8;
104 if (versionOK && addrSizeOK && abbrevsOK &&
105 debug_info_data.isValidOffset(offset))
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);
120 void DWARFUnit::clear() {
127 RangeSectionBase = 0;
128 AddrOffsetSectionBase = 0;
133 const char *DWARFUnit::getCompilationDir() {
134 extractDIEsIfNeeded(true);
135 if (DieArray.empty())
137 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, 0);
140 uint64_t DWARFUnit::getDWOId() {
141 extractDIEsIfNeeded(true);
142 const uint64_t FailValue = -1ULL;
143 if (DieArray.empty())
146 .getAttributeValueAsUnsigned(this, DW_AT_GNU_dwo_id, FailValue);
149 void DWARFUnit::setDIERelations() {
150 if (DieArray.empty())
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;
162 const DWARFAbbreviationDeclaration *curr_die_abbrev =
163 curr_die->getAbbreviationDeclarationPtr();
165 if (curr_die_abbrev) {
167 if (curr_die_abbrev->hasChildren())
168 next_die->setParent(curr_die);
170 curr_die->setSibling(next_die);
172 // NULL DIE that terminates a sibling chain
173 DWARFDebugInfoEntryMinimal *parent = curr_die->getParent();
175 parent->setSibling(next_die);
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);
184 void DWARFUnit::extractDIEsToVector(
185 bool AppendCUDie, bool AppendNonCUDies,
186 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
187 if (!AppendCUDie && !AppendNonCUDies)
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;
196 const uint8_t *FixedFormSizes =
197 DWARFFormValue::getFixedFormSizes(getAddressByteSize(), getVersion());
200 while (Offset < NextCUOffset &&
201 DIE.extractFast(this, FixedFormSizes, &Offset)) {
205 if (!AppendNonCUDies)
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);
216 const DWARFAbbreviationDeclaration *AbbrDecl =
217 DIE.getAbbreviationDeclarationPtr();
220 if (AbbrDecl->hasChildren())
227 break; // We are done with this compile unit!
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
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);
239 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
240 if ((CUDieOnly && DieArray.size() > 0) ||
242 return 0; // Already parsed.
244 bool HasCUDie = DieArray.size() > 0;
245 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
247 if (DieArray.empty())
250 // If CU DIE was just parsed, copy several attribute values from it.
253 DieArray[0].getAttributeValueAsUnsigned(this, DW_AT_low_pc, -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);
260 DieArray[0].getAttributeValueAsReference(this, DW_AT_GNU_ranges_base, 0);
264 return DieArray.size();
267 DWARFUnit::DWOHolder::DWOHolder(object::ObjectFile *DWOFile)
269 DWOContext(cast<DWARFContext>(DIContext::getDWARFContext(DWOFile))),
271 if (DWOContext->getNumDWOCompileUnits() > 0)
272 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
275 bool DWARFUnit::parseDWO() {
278 extractDIEsIfNeeded(true);
279 if (DieArray.empty())
281 const char *DWOFileName =
282 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, 0);
283 if (DWOFileName == 0)
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);
291 sys::path::append(AbsolutePath, DWOFileName);
292 object::ObjectFile *DWOFile =
293 object::ObjectFile::createObjectFile(AbsolutePath);
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()) {
304 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
305 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
306 DWOCU->setRangesSection(RangeSection, RangeSectionBase);
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
319 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
320 DieArray.swap(TmpArray);
321 // Save at least the compile unit DIE
323 DieArray.push_back(TmpArray.front());
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
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();
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);
348 if (DWOCreated && clear_dies_if_already_not_parsed)
351 // Keep memory down by clearing DIEs if this generate function
352 // caused them to be parsed.
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)) {
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);
378 // Try to look for subprogram DIEs in the DWO file.
381 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
383 ChainCU = DWO->getUnit();
387 // Get inlined chain rooted at this subprogram DIE.
389 return DWARFDebugInfoEntryInlinedChain();
390 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);