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"
18 using namespace dwarf;
20 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFDebugAbbrev *DA,
21 StringRef IS, StringRef RS, StringRef SS, StringRef SOS,
22 StringRef AOS, const RelocAddrMap *M, bool LE,
23 const DWARFUnitSectionBase& UnitSection)
24 : Context(DC), Abbrev(DA), InfoSection(IS), RangeSection(RS),
25 StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
26 RelocMap(M), isLittleEndian(LE), UnitSection(UnitSection) {
30 DWARFUnit::~DWARFUnit() {
33 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
34 uint64_t &Result) const {
35 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
36 if (AddrOffsetSection.size() < Offset + AddrSize)
38 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
39 Result = DA.getAddress(&Offset);
43 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
44 uint32_t &Result) const {
45 // FIXME: string offset section entries are 8-byte for DWARF64.
46 const uint32_t ItemSize = 4;
47 uint32_t Offset = Index * ItemSize;
48 if (StringOffsetSection.size() < Offset + ItemSize)
50 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
51 Result = DA.getU32(&Offset);
55 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
56 Length = debug_info.getU32(offset_ptr);
57 Version = debug_info.getU16(offset_ptr);
58 uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
59 AddrSize = debug_info.getU8(offset_ptr);
61 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
62 bool VersionOK = DWARFContext::isSupportedVersion(Version);
63 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
65 if (!LengthOK || !VersionOK || !AddrSizeOK)
68 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
69 if (Abbrevs == nullptr)
75 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
80 if (debug_info.isValidOffset(*offset_ptr)) {
81 if (extractImpl(debug_info, offset_ptr))
84 // reset the offset to where we tried to parse from if anything went wrong
91 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
92 DWARFDebugRangeList &RangeList) const {
93 // Require that compile unit is extracted.
94 assert(DieArray.size() > 0);
95 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
96 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
97 return RangeList.extract(RangesData, &ActualRangeListOffset);
100 void DWARFUnit::clear() {
107 RangeSectionBase = 0;
108 AddrOffsetSectionBase = 0;
113 const char *DWARFUnit::getCompilationDir() {
114 extractDIEsIfNeeded(true);
115 if (DieArray.empty())
117 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
120 uint64_t DWARFUnit::getDWOId() {
121 extractDIEsIfNeeded(true);
122 const uint64_t FailValue = -1ULL;
123 if (DieArray.empty())
126 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
129 void DWARFUnit::setDIERelations() {
130 if (DieArray.size() <= 1)
133 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
134 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
135 for (auto &DIE : DieArray) {
137 SiblingChain->setSibling(&DIE);
139 if (const DWARFAbbreviationDeclaration *AbbrDecl =
140 DIE.getAbbreviationDeclarationPtr()) {
142 if (AbbrDecl->hasChildren()) {
143 ParentChain.push_back(&DIE);
144 SiblingChain = nullptr;
149 // NULL entry terminates the sibling chain.
150 SiblingChain = ParentChain.back();
151 ParentChain.pop_back();
154 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
155 assert(ParentChain.empty());
158 void DWARFUnit::extractDIEsToVector(
159 bool AppendCUDie, bool AppendNonCUDies,
160 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
161 if (!AppendCUDie && !AppendNonCUDies)
164 // Set the offset to that of the first DIE and calculate the start of the
165 // next compilation unit header.
166 uint32_t DIEOffset = Offset + getHeaderSize();
167 uint32_t NextCUOffset = getNextUnitOffset();
168 DWARFDebugInfoEntryMinimal DIE;
172 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
176 if (!AppendNonCUDies)
178 // The average bytes per DIE entry has been seen to be
179 // around 14-20 so let's pre-reserve the needed memory for
180 // our DIE entries accordingly.
181 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
187 if (const DWARFAbbreviationDeclaration *AbbrDecl =
188 DIE.getAbbreviationDeclarationPtr()) {
190 if (AbbrDecl->hasChildren())
197 break; // We are done with this compile unit!
201 // Give a little bit of info if we encounter corrupt DWARF (our offset
202 // should always terminate at or before the start of the next compilation
204 if (DIEOffset > NextCUOffset)
205 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
206 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
209 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
210 if ((CUDieOnly && DieArray.size() > 0) ||
212 return 0; // Already parsed.
214 bool HasCUDie = DieArray.size() > 0;
215 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
217 if (DieArray.empty())
220 // If CU DIE was just parsed, copy several attribute values from it.
223 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
224 if (BaseAddr == -1ULL)
225 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
226 setBaseAddress(BaseAddr);
227 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
228 this, DW_AT_GNU_addr_base, 0);
229 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
230 this, DW_AT_ranges_base, 0);
231 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
232 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
236 return DieArray.size();
239 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
240 : DWOFile(), DWOContext(), DWOU(nullptr) {
241 auto Obj = object::ObjectFile::createObjectFile(DWOPath);
244 DWOFile = std::move(Obj.get());
246 cast<DWARFContext>(DIContext::getDWARFContext(*DWOFile.getBinary())));
247 if (DWOContext->getNumDWOCompileUnits() > 0)
248 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
251 bool DWARFUnit::parseDWO() {
254 extractDIEsIfNeeded(true);
255 if (DieArray.empty())
257 const char *DWOFileName =
258 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
261 const char *CompilationDir =
262 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
263 SmallString<16> AbsolutePath;
264 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
265 sys::path::append(AbsolutePath, CompilationDir);
267 sys::path::append(AbsolutePath, DWOFileName);
268 DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
269 DWARFUnit *DWOCU = DWO->getUnit();
270 // Verify that compile unit in .dwo file is valid.
271 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
275 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
276 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
277 uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
278 DWOCU->setRangesSection(RangeSection, DWORangesBase);
282 void DWARFUnit::clearDIEs(bool KeepCUDie) {
283 if (DieArray.size() > (unsigned)KeepCUDie) {
284 // std::vectors never get any smaller when resized to a smaller size,
285 // or when clear() or erase() are called, the size will report that it
286 // is smaller, but the memory allocated remains intact (call capacity()
287 // to see this). So we need to create a temporary vector and swap the
288 // contents which will cause just the internal pointers to be swapped
289 // so that when temporary vector goes out of scope, it will destroy the
291 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
292 DieArray.swap(TmpArray);
293 // Save at least the compile unit DIE
295 DieArray.push_back(TmpArray.front());
299 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
300 // First, check if CU DIE describes address ranges for the unit.
301 const auto &CUDIERanges = getCompileUnitDIE()->getAddressRanges(this);
302 if (!CUDIERanges.empty()) {
303 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
307 // This function is usually called if there in no .debug_aranges section
308 // in order to produce a compile unit level set of address ranges that
309 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
310 // all compile units to stay loaded when they weren't needed. So we can end
311 // up parsing the DWARF and then throwing them all away to keep memory usage
313 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
314 DieArray[0].collectChildrenAddressRanges(this, CURanges);
316 // Collect address ranges from DIEs in .dwo if necessary.
317 bool DWOCreated = parseDWO();
319 DWO->getUnit()->collectAddressRanges(CURanges);
323 // Keep memory down by clearing DIEs if this generate function
324 // caused them to be parsed.
329 const DWARFDebugInfoEntryMinimal *
330 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
331 extractDIEsIfNeeded(false);
332 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
333 if (DIE.isSubprogramDIE() &&
334 DIE.addressRangeContainsAddress(this, Address)) {
341 DWARFDebugInfoEntryInlinedChain
342 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
343 // First, find a subprogram that contains the given address (the root
344 // of inlined chain).
345 const DWARFUnit *ChainCU = nullptr;
346 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
347 getSubprogramForAddress(Address);
351 // Try to look for subprogram DIEs in the DWO file.
354 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
356 ChainCU = DWO->getUnit();
360 // Get inlined chain rooted at this subprogram DIE.
362 return DWARFDebugInfoEntryInlinedChain();
363 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);