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(),
23 C.getLineSection().Data, C.isLittleEndian());
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.getLineDWOSection().Data, C.isLittleEndian());
34 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
35 const DWARFDebugAbbrev *DA, StringRef RS, StringRef SS,
36 StringRef SOS, StringRef AOS, StringRef LS, bool LE,
37 const DWARFUnitSectionBase &UnitSection,
38 const DWARFUnitIndex::Entry *IndexEntry)
39 : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
40 LineSection(LS), StringSection(SS), StringOffsetSection([&]() {
42 if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
43 return SOS.slice(C->Offset, C->Offset + C->Length);
46 AddrOffsetSection(AOS), isLittleEndian(LE), UnitSection(UnitSection),
47 IndexEntry(IndexEntry) {
51 DWARFUnit::~DWARFUnit() {
54 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
55 uint64_t &Result) const {
56 uint32_t Offset = AddrOffsetSectionBase + Index * AddrSize;
57 if (AddrOffsetSection.size() < Offset + AddrSize)
59 DataExtractor DA(AddrOffsetSection, isLittleEndian, AddrSize);
60 Result = DA.getAddress(&Offset);
64 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
65 uint32_t &Result) const {
66 // FIXME: string offset section entries are 8-byte for DWARF64.
67 const uint32_t ItemSize = 4;
68 uint32_t Offset = Index * ItemSize;
69 if (StringOffsetSection.size() < Offset + ItemSize)
71 DataExtractor DA(StringOffsetSection, isLittleEndian, 0);
72 Result = DA.getU32(&Offset);
76 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
77 Length = debug_info.getU32(offset_ptr);
78 Version = debug_info.getU16(offset_ptr);
79 uint64_t AbbrOffset = debug_info.getU32(offset_ptr);
83 auto *UnitContrib = IndexEntry->getOffset();
84 if (!UnitContrib || UnitContrib->Length != (Length + 4))
86 auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
89 AbbrOffset = AbbrEntry->Offset;
91 AddrSize = debug_info.getU8(offset_ptr);
93 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
94 bool VersionOK = DWARFContext::isSupportedVersion(Version);
95 bool AddrSizeOK = AddrSize == 4 || AddrSize == 8;
97 if (!LengthOK || !VersionOK || !AddrSizeOK)
100 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
101 return Abbrevs != nullptr;
104 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
107 Offset = *offset_ptr;
109 if (debug_info.isValidOffset(*offset_ptr)) {
110 if (extractImpl(debug_info, offset_ptr))
113 // reset the offset to where we tried to parse from if anything went wrong
114 *offset_ptr = Offset;
120 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
121 DWARFDebugRangeList &RangeList) const {
122 // Require that compile unit is extracted.
123 assert(DieArray.size() > 0);
124 DataExtractor RangesData(RangeSection, isLittleEndian, AddrSize);
125 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
126 return RangeList.extract(RangesData, &ActualRangeListOffset);
129 void DWARFUnit::clear() {
136 RangeSectionBase = 0;
137 AddrOffsetSectionBase = 0;
142 const char *DWARFUnit::getCompilationDir() {
143 extractDIEsIfNeeded(true);
144 if (DieArray.empty())
146 return DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
149 uint64_t DWARFUnit::getDWOId() {
150 extractDIEsIfNeeded(true);
151 const uint64_t FailValue = -1ULL;
152 if (DieArray.empty())
155 .getAttributeValueAsUnsignedConstant(this, DW_AT_GNU_dwo_id, FailValue);
158 void DWARFUnit::setDIERelations() {
159 if (DieArray.size() <= 1)
162 std::vector<DWARFDebugInfoEntryMinimal *> ParentChain;
163 DWARFDebugInfoEntryMinimal *SiblingChain = nullptr;
164 for (auto &DIE : DieArray) {
166 SiblingChain->setSibling(&DIE);
168 if (const DWARFAbbreviationDeclaration *AbbrDecl =
169 DIE.getAbbreviationDeclarationPtr()) {
171 if (AbbrDecl->hasChildren()) {
172 ParentChain.push_back(&DIE);
173 SiblingChain = nullptr;
178 // NULL entry terminates the sibling chain.
179 SiblingChain = ParentChain.back();
180 ParentChain.pop_back();
183 assert(SiblingChain == nullptr || SiblingChain == &DieArray[0]);
184 assert(ParentChain.empty());
187 void DWARFUnit::extractDIEsToVector(
188 bool AppendCUDie, bool AppendNonCUDies,
189 std::vector<DWARFDebugInfoEntryMinimal> &Dies) const {
190 if (!AppendCUDie && !AppendNonCUDies)
193 // Set the offset to that of the first DIE and calculate the start of the
194 // next compilation unit header.
195 uint32_t DIEOffset = Offset + getHeaderSize();
196 uint32_t NextCUOffset = getNextUnitOffset();
197 DWARFDebugInfoEntryMinimal DIE;
201 while (DIEOffset < NextCUOffset && DIE.extractFast(this, &DIEOffset)) {
205 if (!AppendNonCUDies)
207 // The average bytes per DIE entry has been seen to be
208 // around 14-20 so let's pre-reserve the needed memory for
209 // our DIE entries accordingly.
210 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
216 if (const DWARFAbbreviationDeclaration *AbbrDecl =
217 DIE.getAbbreviationDeclarationPtr()) {
219 if (AbbrDecl->hasChildren())
226 break; // We are done with this compile unit!
230 // Give a little bit of info if we encounter corrupt DWARF (our offset
231 // should always terminate at or before the start of the next compilation
233 if (DIEOffset > NextCUOffset)
234 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
235 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
238 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
239 if ((CUDieOnly && DieArray.size() > 0) ||
241 return 0; // Already parsed.
243 bool HasCUDie = DieArray.size() > 0;
244 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
246 if (DieArray.empty())
249 // If CU DIE was just parsed, copy several attribute values from it.
252 DieArray[0].getAttributeValueAsAddress(this, DW_AT_low_pc, -1ULL);
253 if (BaseAddr == -1ULL)
254 BaseAddr = DieArray[0].getAttributeValueAsAddress(this, DW_AT_entry_pc, 0);
255 setBaseAddress(BaseAddr);
256 AddrOffsetSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
257 this, DW_AT_GNU_addr_base, 0);
258 RangeSectionBase = DieArray[0].getAttributeValueAsSectionOffset(
259 this, DW_AT_ranges_base, 0);
260 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
261 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
265 return DieArray.size();
268 DWARFUnit::DWOHolder::DWOHolder(StringRef DWOPath)
269 : DWOFile(), DWOContext(), DWOU(nullptr) {
270 auto Obj = object::ObjectFile::createObjectFile(DWOPath);
273 DWOFile = std::move(Obj.get());
275 cast<DWARFContext>(new DWARFContextInMemory(*DWOFile.getBinary())));
276 if (DWOContext->getNumDWOCompileUnits() > 0)
277 DWOU = DWOContext->getDWOCompileUnitAtIndex(0);
280 bool DWARFUnit::parseDWO() {
283 extractDIEsIfNeeded(true);
284 if (DieArray.empty())
286 const char *DWOFileName =
287 DieArray[0].getAttributeValueAsString(this, DW_AT_GNU_dwo_name, nullptr);
290 const char *CompilationDir =
291 DieArray[0].getAttributeValueAsString(this, DW_AT_comp_dir, nullptr);
292 SmallString<16> AbsolutePath;
293 if (sys::path::is_relative(DWOFileName) && CompilationDir != nullptr) {
294 sys::path::append(AbsolutePath, CompilationDir);
296 sys::path::append(AbsolutePath, DWOFileName);
297 DWO = llvm::make_unique<DWOHolder>(AbsolutePath);
298 DWARFUnit *DWOCU = DWO->getUnit();
299 // Verify that compile unit in .dwo file is valid.
300 if (!DWOCU || DWOCU->getDWOId() != getDWOId()) {
304 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
305 DWOCU->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
306 uint32_t DWORangesBase = DieArray[0].getRangesBaseAttribute(this, 0);
307 DWOCU->setRangesSection(RangeSection, DWORangesBase);
311 void DWARFUnit::clearDIEs(bool KeepCUDie) {
312 if (DieArray.size() > (unsigned)KeepCUDie) {
313 // std::vectors never get any smaller when resized to a smaller size,
314 // or when clear() or erase() are called, the size will report that it
315 // is smaller, but the memory allocated remains intact (call capacity()
316 // to see this). So we need to create a temporary vector and swap the
317 // contents which will cause just the internal pointers to be swapped
318 // so that when temporary vector goes out of scope, it will destroy the
320 std::vector<DWARFDebugInfoEntryMinimal> TmpArray;
321 DieArray.swap(TmpArray);
322 // Save at least the compile unit DIE
324 DieArray.push_back(TmpArray.front());
328 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
329 const auto *U = getUnitDIE();
332 // First, check if unit DIE describes address ranges for the whole unit.
333 const auto &CUDIERanges = U->getAddressRanges(this);
334 if (!CUDIERanges.empty()) {
335 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
339 // This function is usually called if there in no .debug_aranges section
340 // in order to produce a compile unit level set of address ranges that
341 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
342 // all compile units to stay loaded when they weren't needed. So we can end
343 // up parsing the DWARF and then throwing them all away to keep memory usage
345 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
346 DieArray[0].collectChildrenAddressRanges(this, CURanges);
348 // Collect address ranges from DIEs in .dwo if necessary.
349 bool DWOCreated = parseDWO();
351 DWO->getUnit()->collectAddressRanges(CURanges);
355 // Keep memory down by clearing DIEs if this generate function
356 // caused them to be parsed.
361 const DWARFDebugInfoEntryMinimal *
362 DWARFUnit::getSubprogramForAddress(uint64_t Address) {
363 extractDIEsIfNeeded(false);
364 for (const DWARFDebugInfoEntryMinimal &DIE : DieArray) {
365 if (DIE.isSubprogramDIE() &&
366 DIE.addressRangeContainsAddress(this, Address)) {
373 DWARFDebugInfoEntryInlinedChain
374 DWARFUnit::getInlinedChainForAddress(uint64_t Address) {
375 // First, find a subprogram that contains the given address (the root
376 // of inlined chain).
377 const DWARFUnit *ChainCU = nullptr;
378 const DWARFDebugInfoEntryMinimal *SubprogramDIE =
379 getSubprogramForAddress(Address);
383 // Try to look for subprogram DIEs in the DWO file.
386 SubprogramDIE = DWO->getUnit()->getSubprogramForAddress(Address);
388 ChainCU = DWO->getUnit();
392 // Get inlined chain rooted at this subprogram DIE.
394 return DWARFDebugInfoEntryInlinedChain();
395 return SubprogramDIE->getInlinedChainForAddress(ChainCU, Address);
398 const DWARFUnitIndex &getDWARFUnitIndex(DWARFContext &Context,
399 DWARFSectionKind Kind) {
400 if (Kind == DW_SECT_INFO)
401 return Context.getCUIndex();
402 assert(Kind == DW_SECT_TYPES);
403 return Context.getTUIndex();