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 "llvm/DebugInfo/DWARF/DWARFUnit.h"
11 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
12 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
13 #include "llvm/Support/Dwarf.h"
14 #include "llvm/Support/Path.h"
18 using namespace dwarf;
20 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
21 parseImpl(C, Section, C.getDebugAbbrev(), C.getRangeSection(),
22 C.getStringSection(), StringRef(), C.getAddrSection(),
26 void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
27 const DWARFSection &DWOSection) {
28 parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), C.getRangeDWOSection(),
29 C.getStringDWOSection(), C.getStringOffsetDWOSection(),
30 C.getAddrSection(), C.isLittleEndian());
33 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
34 const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS,
35 StringRef SOS, StringRef AOS, bool LE,
36 const DWARFUnitSectionBase &UnitSection)
37 : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
38 StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
39 isLittleEndian(LE), UnitSection(UnitSection) {
43 DWARFUnit::~DWARFUnit() {
46 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
47 uint64_t &Result) const {
48 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
49 if (AddrOffsetSection.size() < Offset + AddrSize)
51 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
52 Result = DA.getAddress(&Offset);
56 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
57 uint32_t &Result) const {
58 // FIXME: string offset section entries are 8-byte for DWARF64.
59 const uint32_t ItemSize = 4;
60 uint32_t Offset = Index * ItemSize;
61 if (StringOffsetSection.size() < Offset + ItemSize)
63 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
64 Result = DA.getU32(&Offset);
68 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
69 Length = debug_info.getU32(offset_ptr);
70 Version = debug_info.getU16(offset_ptr);
71 uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
72 AddrSize = debug_info.getU8(offset_ptr);
74 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
75 bool VersionOK = DWARFContext::isSupportedVersion(Version);
76 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
78 if (!LengthOK || !VersionOK || !AddrSizeOK)
81 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
82 return Abbrevs != nullptr;
85 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
90 if (debug_info.isValidOffset(*offset_ptr)) {
91 if (extractImpl(debug_info, offset_ptr))
94 // reset the offset to where we tried to parse from if anything went wrong
101 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
102 DWARFDebugRangeList &RangeList) const {
103 // Require that compile unit is extracted.
104 assert(DieArray.size() > 0);
105 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
106 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
107 return RangeList.extract(RangesData, &ActualRangeListOffset);
110 void DWARFUnit::clear() {
117 RangeSectionBase = 0;
118 AddrOffsetSectionBase = 0;
123 const char *DWARFUnit::getCompilationDir() {
124 extractDIEsIfNeeded(true);
125 if (DieArray.empty())
127 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
130 uint64_t DWARFUnit::getDWOId() {
131 extractDIEsIfNeeded(true);
132 const uint64_t FailValue = -1ULL;
133 if (DieArray.empty())
136 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
139 void DWARFUnit::setDIERelations() {
140 if (DieArray.size() <= 1)
143 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
144 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
145 for (auto &DIE : DieArray) {
147 SiblingChain->setSibling(&DIE);
149 if (const DWARFAbbreviationDeclaration *AbbrDecl =
150 DIE.getAbbreviationDeclarationPtr()) {
152 if (AbbrDecl->hasChildren()) {
153 ParentChain.push_back(&DIE);
154 SiblingChain = nullptr;
159 // NULL entry terminates the sibling chain.
160 SiblingChain = ParentChain.back();
161 ParentChain.pop_back();
164 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
165 assert(ParentChain.empty());
168 void DWARFUnit::extractDIEsToVector(
169 bool AppendCUDie, bool AppendNonCUDies,
170 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
171 if (!AppendCUDie && !AppendNonCUDies)
174 // Set the offset to that of the first DIE and calculate the start of the
175 // next compilation unit header.
176 uint32_t DIEOffset = Offset + getHeaderSize();
177 uint32_t NextCUOffset = getNextUnitOffset();
178 DWARFDebugInfoEntryMinimal DIE;
182 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
186 if (!AppendNonCUDies)
188 // The average bytes per DIE entry has been seen to be
189 // around 14-20 so let's pre-reserve the needed memory for
190 // our DIE entries accordingly.
191 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
197 if (const DWARFAbbreviationDeclaration *AbbrDecl =
198 DIE.getAbbreviationDeclarationPtr()) {
200 if (AbbrDecl->hasChildren())
207 break; // We are done with this compile unit!
211 // Give a little bit of info if we encounter corrupt DWARF (our offset
212 // should always terminate at or before the start of the next compilation
214 if (DIEOffset > NextCUOffset)
215 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
216 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
219 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
220 if ((CUDieOnly && DieArray.size() > 0) ||
222 return 0; // Already parsed.
224 bool HasCUDie = DieArray.size() > 0;
225 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
227 if (DieArray.empty())
230 // If CU DIE was just parsed, copy several attribute values from it.
233 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
234 if (BaseAddr == -1ULL)
235 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
236 setBaseAddress(BaseAddr);
237 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
238 this, DW_AT_GNU_addr_base, 0);
239 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
240 this, DW_AT_ranges_base, 0);
241 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
242 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
246 return DieArray.size();
249 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
250 : DWOFile(), DWOContext(), DWOU(nullptr) {
251 auto Obj = object::ObjectFile::createObjectFile(DWOPath);
254 DWOFile = std::move(Obj.get());
256 cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary())));
257 if (DWOContext->getNumDWOCompileUnits() > 0)
258 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
261 bool DWARFUnit::parseDWO() {
264 extractDIEsIfNeeded(true);
265 if (DieArray.empty())
267 const char *DWOFileName =
268 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
271 const char *CompilationDir =
272 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
273 SmallString<16> AbsolutePath;
274 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
275 sys::path::append(AbsolutePath, CompilationDir);
277 sys::path::append(AbsolutePath, DWOFileName);
278 DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
279 DWARFUnit *DWOCU = DWO->getUnit();
280 // Verify that compile unit in .dwo file is valid.
281 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
285 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
286 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
287 uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
288 DWOCU->setRangesSection(RangeSection, DWORangesBase);
292 void DWARFUnit::clearDIEs(bool KeepCUDie) {
293 if (DieArray.size() > (unsigned)KeepCUDie) {
294 // std::vectors never get any smaller when resized to a smaller size,
295 // or when clear() or erase() are called, the size will report that it
296 // is smaller, but the memory allocated remains intact (call capacity()
297 // to see this). So we need to create a temporary vector and swap the
298 // contents which will cause just the internal pointers to be swapped
299 // so that when temporary vector goes out of scope, it will destroy the
301 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
302 DieArray.swap(TmpArray);
303 // Save at least the compile unit DIE
305 DieArray.push_back(TmpArray.front());
309 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
310 const auto *U = getUnitDIE();
313 // First, check if unit DIE describes address ranges for the whole unit.
314 const auto &CUDIERanges = U->getAddressRanges(this);
315 if (!CUDIERanges.empty()) {
316 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
320 // This function is usually called if there in no .debug_aranges section
321 // in order to produce a compile unit level set of address ranges that
322 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
323 // all compile units to stay loaded when they weren't needed. So we can end
324 // up parsing the DWARF and then throwing them all away to keep memory usage
326 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
327 DieArray[0].collectChildrenAddressRanges(this, CURanges);
329 // Collect address ranges from DIEs in .dwo if necessary.
330 bool DWOCreated = parseDWO();
332 DWO->getUnit()->collectAddressRanges(CURanges);
336 // Keep memory down by clearing DIEs if this generate function
337 // caused them to be parsed.
342 const DWARFDebugInfoEntryMinimal *
343 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
344 extractDIEsIfNeeded(false);
345 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
346 if (DIE.isSubprogramDIE() &&
347 DIE.addressRangeContainsAddress(this, Address)) {
354 DWARFDebugInfoEntryInlinedChain
355 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
356 // First, find a subprogram that contains the given address (the root
357 // of inlined chain).
358 const DWARFUnit *ChainCU = nullptr;
359 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
360 getSubprogramForAddress(Address);
364 // Try to look for subprogram DIEs in the DWO file.
367 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
369 ChainCU = DWO->getUnit();
373 // Get inlined chain rooted at this subprogram DIE.
375 return DWARFDebugInfoEntryInlinedChain();
376 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);