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;
21 void DWARFUnitSectionBase::parse(DWARFContext &C, StringRef SectionData,
22 const RelocAddrMap &Map) {
23 parseImpl(C, C.getDebugAbbrev(), SectionData, C.getRangeSection(),
24 C.getStringSection(), StringRef(), C.getAddrSection(), Map,
28 void DWARFUnitSectionBase::parseDWO(DWARFContext &C, StringRef SectionData,
29 const RelocAddrMap &Map) {
30 parseImpl(C, C.getDebugAbbrevDWO(), SectionData, C.getRangeDWOSection(),
31 C.getStringDWOSection(), C.getStringOffsetDWOSection(),
32 C.getAddrSection(), Map, C.isLittleEndian());
35 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFDebugAbbrev *DA,
36 StringRef IS, StringRef RS, StringRef SS, StringRef SOS,
37 StringRef AOS, const RelocAddrMap *M, bool LE,
38 const DWARFUnitSectionBase& UnitSection)
39 : Context(DC), Abbrev(DA), InfoSection(IS), RangeSection(RS),
40 StringSection(SS), StringOffsetSection(SOS), AddrOffsetSection(AOS),
41 RelocMap(M), isLittleEndian(LE), UnitSection(UnitSection) {
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);
74 AddrSize = debug_info.getU8(offset_ptr);
76 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
77 bool VersionOK = DWARFContext::isSupportedVersion(Version);
78 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
80 if (!LengthOK || !VersionOK || !AddrSizeOK)
83 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
84 if (Abbrevs == nullptr)
90 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
95 if (debug_info.isValidOffset(*offset_ptr)) {
96 if (extractImpl(debug_info, offset_ptr))
99 // reset the offset to where we tried to parse from if anything went wrong
100 *offset_ptr = Offset;
106 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
107 DWARFDebugRangeList &RangeList) const {
108 // Require that compile unit is extracted.
109 assert(DieArray.size() > 0);
110 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
111 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
112 return RangeList.extract(RangesData, &ActualRangeListOffset);
115 void DWARFUnit::clear() {
122 RangeSectionBase = 0;
123 AddrOffsetSectionBase = 0;
128 const char *DWARFUnit::getCompilationDir() {
129 extractDIEsIfNeeded(true);
130 if (DieArray.empty())
132 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
135 uint64_t DWARFUnit::getDWOId() {
136 extractDIEsIfNeeded(true);
137 const uint64_t FailValue = -1ULL;
138 if (DieArray.empty())
141 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
144 void DWARFUnit::setDIERelations() {
145 if (DieArray.size() <= 1)
148 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
149 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
150 for (auto &DIE : DieArray) {
152 SiblingChain->setSibling(&DIE);
154 if (const DWARFAbbreviationDeclaration *AbbrDecl =
155 DIE.getAbbreviationDeclarationPtr()) {
157 if (AbbrDecl->hasChildren()) {
158 ParentChain.push_back(&DIE);
159 SiblingChain = nullptr;
164 // NULL entry terminates the sibling chain.
165 SiblingChain = ParentChain.back();
166 ParentChain.pop_back();
169 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
170 assert(ParentChain.empty());
173 void DWARFUnit::extractDIEsToVector(
174 bool AppendCUDie, bool AppendNonCUDies,
175 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
176 if (!AppendCUDie && !AppendNonCUDies)
179 // Set the offset to that of the first DIE and calculate the start of the
180 // next compilation unit header.
181 uint32_t DIEOffset = Offset + getHeaderSize();
182 uint32_t NextCUOffset = getNextUnitOffset();
183 DWARFDebugInfoEntryMinimal DIE;
187 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
191 if (!AppendNonCUDies)
193 // The average bytes per DIE entry has been seen to be
194 // around 14-20 so let's pre-reserve the needed memory for
195 // our DIE entries accordingly.
196 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
202 if (const DWARFAbbreviationDeclaration *AbbrDecl =
203 DIE.getAbbreviationDeclarationPtr()) {
205 if (AbbrDecl->hasChildren())
212 break; // We are done with this compile unit!
216 // Give a little bit of info if we encounter corrupt DWARF (our offset
217 // should always terminate at or before the start of the next compilation
219 if (DIEOffset > NextCUOffset)
220 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
221 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
224 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
225 if ((CUDieOnly && DieArray.size() > 0) ||
227 return 0; // Already parsed.
229 bool HasCUDie = DieArray.size() > 0;
230 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
232 if (DieArray.empty())
235 // If CU DIE was just parsed, copy several attribute values from it.
238 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
239 if (BaseAddr == -1ULL)
240 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
241 setBaseAddress(BaseAddr);
242 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
243 this, DW_AT_GNU_addr_base, 0);
244 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
245 this, DW_AT_ranges_base, 0);
246 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
247 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
251 return DieArray.size();
254 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
255 : DWOFile(), DWOContext(), DWOU(nullptr) {
256 auto Obj = object::ObjectFile::createObjectFile(DWOPath);
259 DWOFile = std::move(Obj.get());
261 cast<DWARFContext>(DIContext::getDWARFContext(*DWOFile.getBinary())));
262 if (DWOContext->getNumDWOCompileUnits() > 0)
263 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
266 bool DWARFUnit::parseDWO() {
269 extractDIEsIfNeeded(true);
270 if (DieArray.empty())
272 const char *DWOFileName =
273 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
276 const char *CompilationDir =
277 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
278 SmallString<16> AbsolutePath;
279 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
280 sys::path::append(AbsolutePath, CompilationDir);
282 sys::path::append(AbsolutePath, DWOFileName);
283 DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
284 DWARFUnit *DWOCU = DWO->getUnit();
285 // Verify that compile unit in .dwo file is valid.
286 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
290 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
291 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
292 uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
293 DWOCU->setRangesSection(RangeSection, DWORangesBase);
297 void DWARFUnit::clearDIEs(bool KeepCUDie) {
298 if (DieArray.size() > (unsigned)KeepCUDie) {
299 // std::vectors never get any smaller when resized to a smaller size,
300 // or when clear() or erase() are called, the size will report that it
301 // is smaller, but the memory allocated remains intact (call capacity()
302 // to see this). So we need to create a temporary vector and swap the
303 // contents which will cause just the internal pointers to be swapped
304 // so that when temporary vector goes out of scope, it will destroy the
306 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
307 DieArray.swap(TmpArray);
308 // Save at least the compile unit DIE
310 DieArray.push_back(TmpArray.front());
314 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
315 // First, check if CU DIE describes address ranges for the unit.
316 const auto &CUDIERanges = getCompileUnitDIE()->getAddressRanges(this);
317 if (!CUDIERanges.empty()) {
318 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
322 // This function is usually called if there in no .debug_aranges section
323 // in order to produce a compile unit level set of address ranges that
324 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
325 // all compile units to stay loaded when they weren't needed. So we can end
326 // up parsing the DWARF and then throwing them all away to keep memory usage
328 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
329 DieArray[0].collectChildrenAddressRanges(this, CURanges);
331 // Collect address ranges from DIEs in .dwo if necessary.
332 bool DWOCreated = parseDWO();
334 DWO->getUnit()->collectAddressRanges(CURanges);
338 // Keep memory down by clearing DIEs if this generate function
339 // caused them to be parsed.
344 const DWARFDebugInfoEntryMinimal *
345 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
346 extractDIEsIfNeeded(false);
347 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
348 if (DIE.isSubprogramDIE() &&
349 DIE.addressRangeContainsAddress(this, Address)) {
356 DWARFDebugInfoEntryInlinedChain
357 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
358 // First, find a subprogram that contains the given address (the root
359 // of inlined chain).
360 const DWARFUnit *ChainCU = nullptr;
361 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
362 getSubprogramForAddress(Address);
366 // Try to look for subprogram DIEs in the DWO file.
369 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
371 ChainCU = DWO->getUnit();
375 // Get inlined chain rooted at this subprogram DIE.
377 return DWARFDebugInfoEntryInlinedChain();
378 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);