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 DWARFUnitIndex *Index) {
29 parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), C.getRangeDWOSection(),
30 C.getStringDWOSection(), C.getStringOffsetDWOSection(),
31 C.getAddrSection(), C.isLittleEndian());
34 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
35 const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS,
36 StringRef SOS, StringRef AOS, bool LE,
37 const DWARFUnitSectionBase &UnitSection,
38 const DWARFUnitIndex::Entry *IndexEntry)
39 : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
40 StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
41 isLittleEndian(LE), UnitSection(UnitSection), IndexEntry(IndexEntry) {
45 DWARFUnit::~DWARFUnit() {
48 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
49 uint64_t &Result) const {
50 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
51 if (AddrOffsetSection.size() < Offset + AddrSize)
53 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
54 Result = DA.getAddress(&Offset);
58 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
59 uint32_t &Result) const {
60 // FIXME: string offset section entries are 8-byte for DWARF64.
61 const uint32_t ItemSize = 4;
62 uint32_t Offset = Index * ItemSize;
63 if (StringOffsetSection.size() < Offset + ItemSize)
65 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
66 Result = DA.getU32(&Offset);
70 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
71 Length = debug_info.getU32(offset_ptr);
72 Version = debug_info.getU16(offset_ptr);
73 uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
77 auto *UnitContrib = IndexEntry->getOffset();
78 if (!UnitContrib || UnitContrib->Length != (Length + 4))
80 auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
83 AbbrOffset = AbbrEntry->Offset;
85 AddrSize = debug_info.getU8(offset_ptr);
87 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
88 bool VersionOK = DWARFContext::isSupportedVersion(Version);
89 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
91 if (!LengthOK || !VersionOK || !AddrSizeOK)
94 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
95 return Abbrevs != nullptr;
98 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
101 Offset = *offset_ptr;
103 if (debug_info.isValidOffset(*offset_ptr)) {
104 if (extractImpl(debug_info, offset_ptr))
107 // reset the offset to where we tried to parse from if anything went wrong
108 *offset_ptr = Offset;
114 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
115 DWARFDebugRangeList &RangeList) const {
116 // Require that compile unit is extracted.
117 assert(DieArray.size() > 0);
118 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
119 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
120 return RangeList.extract(RangesData, &ActualRangeListOffset);
123 void DWARFUnit::clear() {
130 RangeSectionBase = 0;
131 AddrOffsetSectionBase = 0;
136 const char *DWARFUnit::getCompilationDir() {
137 extractDIEsIfNeeded(true);
138 if (DieArray.empty())
140 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
143 uint64_t DWARFUnit::getDWOId() {
144 extractDIEsIfNeeded(true);
145 const uint64_t FailValue = -1ULL;
146 if (DieArray.empty())
149 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
152 void DWARFUnit::setDIERelations() {
153 if (DieArray.size() <= 1)
156 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
157 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
158 for (auto &DIE : DieArray) {
160 SiblingChain->setSibling(&DIE);
162 if (const DWARFAbbreviationDeclaration *AbbrDecl =
163 DIE.getAbbreviationDeclarationPtr()) {
165 if (AbbrDecl->hasChildren()) {
166 ParentChain.push_back(&DIE);
167 SiblingChain = nullptr;
172 // NULL entry terminates the sibling chain.
173 SiblingChain = ParentChain.back();
174 ParentChain.pop_back();
177 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
178 assert(ParentChain.empty());
181 void DWARFUnit::extractDIEsToVector(
182 bool AppendCUDie, bool AppendNonCUDies,
183 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
184 if (!AppendCUDie && !AppendNonCUDies)
187 // Set the offset to that of the first DIE and calculate the start of the
188 // next compilation unit header.
189 uint32_t DIEOffset = Offset + getHeaderSize();
190 uint32_t NextCUOffset = getNextUnitOffset();
191 DWARFDebugInfoEntryMinimal DIE;
195 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
199 if (!AppendNonCUDies)
201 // The average bytes per DIE entry has been seen to be
202 // around 14-20 so let's pre-reserve the needed memory for
203 // our DIE entries accordingly.
204 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
210 if (const DWARFAbbreviationDeclaration *AbbrDecl =
211 DIE.getAbbreviationDeclarationPtr()) {
213 if (AbbrDecl->hasChildren())
220 break; // We are done with this compile unit!
224 // Give a little bit of info if we encounter corrupt DWARF (our offset
225 // should always terminate at or before the start of the next compilation
227 if (DIEOffset > NextCUOffset)
228 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
229 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
232 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
233 if ((CUDieOnly && DieArray.size() > 0) ||
235 return 0; // Already parsed.
237 bool HasCUDie = DieArray.size() > 0;
238 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
240 if (DieArray.empty())
243 // If CU DIE was just parsed, copy several attribute values from it.
246 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
247 if (BaseAddr == -1ULL)
248 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
249 setBaseAddress(BaseAddr);
250 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
251 this, DW_AT_GNU_addr_base, 0);
252 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
253 this, DW_AT_ranges_base, 0);
254 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
255 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
259 return DieArray.size();
262 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
263 : DWOFile(), DWOContext(), DWOU(nullptr) {
264 auto Obj = object::ObjectFile::createObjectFile(DWOPath);
267 DWOFile = std::move(Obj.get());
269 cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary())));
270 if (DWOContext->getNumDWOCompileUnits() > 0)
271 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
274 bool DWARFUnit::parseDWO() {
277 extractDIEsIfNeeded(true);
278 if (DieArray.empty())
280 const char *DWOFileName =
281 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
284 const char *CompilationDir =
285 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
286 SmallString<16> AbsolutePath;
287 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
288 sys::path::append(AbsolutePath, CompilationDir);
290 sys::path::append(AbsolutePath, DWOFileName);
291 DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
292 DWARFUnit *DWOCU = DWO->getUnit();
293 // Verify that compile unit in .dwo file is valid.
294 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
298 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
299 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
300 uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
301 DWOCU->setRangesSection(RangeSection, DWORangesBase);
305 void DWARFUnit::clearDIEs(bool KeepCUDie) {
306 if (DieArray.size() > (unsigned)KeepCUDie) {
307 // std::vectors never get any smaller when resized to a smaller size,
308 // or when clear() or erase() are called, the size will report that it
309 // is smaller, but the memory allocated remains intact (call capacity()
310 // to see this). So we need to create a temporary vector and swap the
311 // contents which will cause just the internal pointers to be swapped
312 // so that when temporary vector goes out of scope, it will destroy the
314 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
315 DieArray.swap(TmpArray);
316 // Save at least the compile unit DIE
318 DieArray.push_back(TmpArray.front());
322 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
323 const auto *U = getUnitDIE();
326 // First, check if unit DIE describes address ranges for the whole unit.
327 const auto &CUDIERanges = U->getAddressRanges(this);
328 if (!CUDIERanges.empty()) {
329 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
333 // This function is usually called if there in no .debug_aranges section
334 // in order to produce a compile unit level set of address ranges that
335 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
336 // all compile units to stay loaded when they weren't needed. So we can end
337 // up parsing the DWARF and then throwing them all away to keep memory usage
339 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
340 DieArray[0].collectChildrenAddressRanges(this, CURanges);
342 // Collect address ranges from DIEs in .dwo if necessary.
343 bool DWOCreated = parseDWO();
345 DWO->getUnit()->collectAddressRanges(CURanges);
349 // Keep memory down by clearing DIEs if this generate function
350 // caused them to be parsed.
355 const DWARFDebugInfoEntryMinimal *
356 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
357 extractDIEsIfNeeded(false);
358 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
359 if (DIE.isSubprogramDIE() &&
360 DIE.addressRangeContainsAddress(this, Address)) {
367 DWARFDebugInfoEntryInlinedChain
368 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
369 // First, find a subprogram that contains the given address (the root
370 // of inlined chain).
371 const DWARFUnit *ChainCU = nullptr;
372 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
373 getSubprogramForAddress(Address);
377 // Try to look for subprogram DIEs in the DWO file.
380 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
382 ChainCU = DWO->getUnit();
386 // Get inlined chain rooted at this subprogram DIE.
388 return DWARFDebugInfoEntryInlinedChain();
389 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);
392 const DWARFUnitIndex &getDWARFUnitIndex(DWARFContext &Context,
393 DWARFSectionKind Kind) {
394 if (Kind == DW_SECT_INFO)
395 return Context.getCUIndex();
396 assert(Kind == DW_SECT_TYPES);
397 return Context.getTUIndex();