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(const DWARFDebugAbbrev *DA, StringRef IS, StringRef RS,
21 StringRef SS, StringRef SOS, StringRef AOS,
22 const RelocAddrMap *M, bool LE)
23 : Abbrev(DA), InfoSection(IS), RangeSection(RS), StringSection(SS),
24 StringOffsetSection(SOS), AddrOffsetSection(AOS), RelocMap(M),
29 DWARFUnit::~DWARFUnit() {
32 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
33 uint64_t &Result) const {
34 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
35 if (AddrOffsetSection.size() < Offset + AddrSize)
37 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
38 Result = DA.getAddress(&Offset);
42 bool 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)
49 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
50 Result = DA.getU32(&Offset);
54 bool 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);
60 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
61 bool VersionOK = DWARFContext::isSupportedVersion(Version);
62 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
64 if (!LengthOK || !VersionOK || !AddrSizeOK)
67 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
68 if (Abbrevs == nullptr)
74 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
79 if (debug_info.isValidOffset(*offset_ptr)) {
80 if (extractImpl(debug_info, offset_ptr))
83 // reset the offset to where we tried to parse from if anything went wrong
90 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
91 DWARFDebugRangeList &RangeList) const {
92 // Require that compile unit is extracted.
93 assert(DieArray.size() > 0);
94 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
95 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
96 return RangeList.extract(RangesData, &ActualRangeListOffset);
99 void DWARFUnit::clear() {
106 RangeSectionBase = 0;
107 AddrOffsetSectionBase = 0;
112 const char *DWARFUnit::getCompilationDir() {
113 extractDIEsIfNeeded(true);
114 if (DieArray.empty())
116 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
119 uint64_t DWARFUnit::getDWOId() {
120 extractDIEsIfNeeded(true);
121 const uint64_t FailValue = -1ULL;
122 if (DieArray.empty())
125 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
128 void DWARFUnit::setDIERelations() {
129 if (DieArray.size() <= 1)
132 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
133 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
134 for (auto &DIE : DieArray) {
136 SiblingChain->setSibling(&DIE);
138 if (const DWARFAbbreviationDeclaration *AbbrDecl =
139 DIE.getAbbreviationDeclarationPtr()) {
141 if (AbbrDecl->hasChildren()) {
142 ParentChain.push_back(&DIE);
143 SiblingChain = nullptr;
148 // NULL entry terminates the sibling chain.
149 SiblingChain = ParentChain.back();
150 ParentChain.pop_back();
153 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
154 assert(ParentChain.empty());
157 void DWARFUnit::extractDIEsToVector(
158 bool AppendCUDie, bool AppendNonCUDies,
159 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
160 if (!AppendCUDie && !AppendNonCUDies)
163 // Set the offset to that of the first DIE and calculate the start of the
164 // next compilation unit header.
165 uint32_t DIEOffset = Offset + getHeaderSize();
166 uint32_t NextCUOffset = getNextUnitOffset();
167 DWARFDebugInfoEntryMinimal DIE;
171 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
175 if (!AppendNonCUDies)
177 // The average bytes per DIE entry has been seen to be
178 // around 14-20 so let's pre-reserve the needed memory for
179 // our DIE entries accordingly.
180 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
186 if (const DWARFAbbreviationDeclaration *AbbrDecl =
187 DIE.getAbbreviationDeclarationPtr()) {
189 if (AbbrDecl->hasChildren())
196 break; // We are done with this compile unit!
200 // Give a little bit of info if we encounter corrupt DWARF (our offset
201 // should always terminate at or before the start of the next compilation
203 if (DIEOffset > NextCUOffset)
204 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
205 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
208 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
209 if ((CUDieOnly && DieArray.size() > 0) ||
211 return 0; // Already parsed.
213 bool HasCUDie = DieArray.size() > 0;
214 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
216 if (DieArray.empty())
219 // If CU DIE was just parsed, copy several attribute values from it.
222 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
223 if (BaseAddr == -1ULL)
224 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
225 setBaseAddress(BaseAddr);
226 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
227 this, DW_AT_GNU_addr_base, 0);
228 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
229 this, DW_AT_GNU_ranges_base, 0);
233 return DieArray.size();
236 DWARFUnit::DWOHolder::DWOHolder(object::ObjectFile *DWOFile)
238 DWOContext(cast<DWARFContext>(DIContext::getDWARFContext(DWOFile))),
240 if (DWOContext->getNumDWOCompileUnits() > 0)
241 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
244 bool DWARFUnit::parseDWO() {
247 extractDIEsIfNeeded(true);
248 if (DieArray.empty())
250 const char *DWOFileName =
251 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
254 const char *CompilationDir =
255 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
256 SmallString<16> AbsolutePath;
257 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
258 sys::path::append(AbsolutePath, CompilationDir);
260 sys::path::append(AbsolutePath, DWOFileName);
261 ErrorOr<object::ObjectFile *> DWOFile =
262 object::ObjectFile::createObjectFile(AbsolutePath);
266 DWO.reset(new DWOHolder(DWOFile.get()));
267 DWARFUnit *DWOCU = DWO->getUnit();
268 // Verify that compile unit in .dwo file is valid.
269 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
273 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
274 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
275 DWOCU->setRangesSection(RangeSection, RangeSectionBase);
279 void DWARFUnit::clearDIEs(bool KeepCUDie) {
280 if (DieArray.size() > (unsigned)KeepCUDie) {
281 // std::vectors never get any smaller when resized to a smaller size,
282 // or when clear() or erase() are called, the size will report that it
283 // is smaller, but the memory allocated remains intact (call capacity()
284 // to see this). So we need to create a temporary vector and swap the
285 // contents which will cause just the internal pointers to be swapped
286 // so that when temporary vector goes out of scope, it will destroy the
288 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
289 DieArray.swap(TmpArray);
290 // Save at least the compile unit DIE
292 DieArray.push_back(TmpArray.front());
296 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
297 // First, check if CU DIE describes address ranges for the unit.
298 const auto &CUDIERanges = getCompileUnitDIE()->getAddressRanges(this);
299 if (!CUDIERanges.empty()) {
300 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
304 // This function is usually called if there in no .debug_aranges section
305 // in order to produce a compile unit level set of address ranges that
306 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
307 // all compile units to stay loaded when they weren't needed. So we can end
308 // up parsing the DWARF and then throwing them all away to keep memory usage
310 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
311 DieArray[0].collectChildrenAddressRanges(this, CURanges);
313 // Collect address ranges from DIEs in .dwo if necessary.
314 bool DWOCreated = parseDWO();
316 DWO->getUnit()->collectAddressRanges(CURanges);
320 // Keep memory down by clearing DIEs if this generate function
321 // caused them to be parsed.
326 const DWARFDebugInfoEntryMinimal *
327 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
328 extractDIEsIfNeeded(false);
329 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
330 if (DIE.isSubprogramDIE() &&
331 DIE.addressRangeContainsAddress(this, Address)) {
338 DWARFDebugInfoEntryInlinedChain
339 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
340 // First, find a subprogram that contains the given address (the root
341 // of inlined chain).
342 const DWARFUnit *ChainCU = nullptr;
343 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
344 getSubprogramForAddress(Address);
348 // Try to look for subprogram DIEs in the DWO file.
351 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
353 ChainCU = DWO->getUnit();
357 // Get inlined chain rooted at this subprogram DIE.
359 return DWARFDebugInfoEntryInlinedChain();
360 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);