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/ADT/SmallString.h"
12 #include "llvm/ADT/StringRef.h"
13 #include "llvm/DebugInfo/DWARF/DWARFAbbreviationDeclaration.h"
14 #include "llvm/DebugInfo/DWARF/DWARFContext.h"
15 #include "llvm/DebugInfo/DWARF/DWARFDebugAbbrev.h"
16 #include "llvm/DebugInfo/DWARF/DWARFDebugInfoEntry.h"
17 #include "llvm/DebugInfo/DWARF/DWARFDie.h"
18 #include "llvm/DebugInfo/DWARF/DWARFFormValue.h"
19 #include "llvm/Support/DataExtractor.h"
20 #include "llvm/Support/Path.h"
30 using namespace dwarf;
32 void DWARFUnitSectionBase::parse(DWARFContext &C, const DWARFSection &Section) {
33 parseImpl(C, Section, C.getDebugAbbrev(), &C.getRangeSection(),
34 C.getStringSection(), C.getStringOffsetSection(),
35 &C.getAddrSection(), C.getLineSection(), C.isLittleEndian(), false);
38 void DWARFUnitSectionBase::parseDWO(DWARFContext &C,
39 const DWARFSection &DWOSection,
40 DWARFUnitIndex *Index) {
41 parseImpl(C, DWOSection, C.getDebugAbbrevDWO(), &C.getRangeDWOSection(),
42 C.getStringDWOSection(), C.getStringOffsetDWOSection(),
43 &C.getAddrSection(), C.getLineDWOSection(), C.isLittleEndian(),
47 DWARFUnit::DWARFUnit(DWARFContext &DC, const DWARFSection &Section,
48 const DWARFDebugAbbrev *DA, const DWARFSection *RS,
49 StringRef SS, const DWARFSection &SOS,
50 const DWARFSection *AOS, const DWARFSection &LS, bool LE,
51 bool IsDWO, const DWARFUnitSectionBase &UnitSection,
52 const DWARFUnitIndex::Entry *IndexEntry)
53 : Context(DC), InfoSection(Section), Abbrev(DA), RangeSection(RS),
54 LineSection(LS), StringSection(SS), StringOffsetSection(SOS),
55 AddrOffsetSection(AOS), isLittleEndian(LE), isDWO(IsDWO),
56 UnitSection(UnitSection), IndexEntry(IndexEntry) {
60 DWARFUnit::~DWARFUnit() = default;
62 bool DWARFUnit::getAddrOffsetSectionItem(uint32_t Index,
63 uint64_t &Result) const {
64 uint32_t Offset = AddrOffsetSectionBase + Index * getAddressByteSize();
65 if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
67 DWARFDataExtractor DA(*AddrOffsetSection, isLittleEndian,
68 getAddressByteSize());
69 Result = DA.getRelocatedAddress(&Offset);
73 bool DWARFUnit::getStringOffsetSectionItem(uint32_t Index,
74 uint64_t &Result) const {
75 unsigned ItemSize = getDwarfOffsetByteSize();
76 uint32_t Offset = StringOffsetSectionBase + Index * ItemSize;
77 if (StringOffsetSection.Data.size() < Offset + ItemSize)
79 DWARFDataExtractor DA(StringOffsetSection, isLittleEndian, 0);
80 Result = DA.getRelocatedValue(ItemSize, &Offset);
84 bool DWARFUnit::extractImpl(DataExtractor debug_info, uint32_t *offset_ptr) {
85 Length = debug_info.getU32(offset_ptr);
86 // FIXME: Support DWARF64.
87 FormParams.Format = DWARF32;
88 FormParams.Version = debug_info.getU16(offset_ptr);
90 if (FormParams.Version >= 5) {
91 UnitType = debug_info.getU8(offset_ptr);
92 FormParams.AddrSize = debug_info.getU8(offset_ptr);
93 AbbrOffset = debug_info.getU32(offset_ptr);
95 AbbrOffset = debug_info.getU32(offset_ptr);
96 FormParams.AddrSize = debug_info.getU8(offset_ptr);
101 auto *UnitContrib = IndexEntry->getOffset();
102 if (!UnitContrib || UnitContrib->Length != (Length + 4))
104 auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
107 AbbrOffset = AbbrEntry->Offset;
110 bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
111 bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
112 bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8;
114 if (!LengthOK || !VersionOK || !AddrSizeOK)
117 // Keep track of the highest DWARF version we encounter across all units.
118 Context.setMaxVersionIfGreater(getVersion());
120 Abbrevs = Abbrev->getAbbreviationDeclarationSet(AbbrOffset);
121 return Abbrevs != nullptr;
124 bool DWARFUnit::extract(DataExtractor debug_info, uint32_t *offset_ptr) {
127 Offset = *offset_ptr;
129 if (debug_info.isValidOffset(*offset_ptr)) {
130 if (extractImpl(debug_info, offset_ptr))
133 // reset the offset to where we tried to parse from if anything went wrong
134 *offset_ptr = Offset;
140 bool DWARFUnit::extractRangeList(uint32_t RangeListOffset,
141 DWARFDebugRangeList &RangeList) const {
142 // Require that compile unit is extracted.
143 assert(!DieArray.empty());
144 DWARFDataExtractor RangesData(*RangeSection, isLittleEndian,
145 getAddressByteSize());
146 uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
147 return RangeList.extract(RangesData, &ActualRangeListOffset);
150 void DWARFUnit::clear() {
154 FormParams = DWARFFormParams({0, 0, DWARF32});
156 RangeSectionBase = 0;
157 AddrOffsetSectionBase = 0;
162 const char *DWARFUnit::getCompilationDir() {
163 return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
166 Optional<uint64_t> DWARFUnit::getDWOId() {
167 return toUnsigned(getUnitDIE().find(DW_AT_GNU_dwo_id));
170 void DWARFUnit::extractDIEsToVector(
171 bool AppendCUDie, bool AppendNonCUDies,
172 std::vector<DWARFDebugInfoEntry> &Dies) const {
173 if (!AppendCUDie && !AppendNonCUDies)
176 // Set the offset to that of the first DIE and calculate the start of the
177 // next compilation unit header.
178 uint32_t DIEOffset = Offset + getHeaderSize();
179 uint32_t NextCUOffset = getNextUnitOffset();
180 DWARFDebugInfoEntry DIE;
181 DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
185 while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
190 if (!AppendNonCUDies)
192 // The average bytes per DIE entry has been seen to be
193 // around 14-20 so let's pre-reserve the needed memory for
194 // our DIE entries accordingly.
195 Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
201 if (const DWARFAbbreviationDeclaration *AbbrDecl =
202 DIE.getAbbreviationDeclarationPtr()) {
204 if (AbbrDecl->hasChildren())
211 break; // We are done with this compile unit!
215 // Give a little bit of info if we encounter corrupt DWARF (our offset
216 // should always terminate at or before the start of the next compilation
218 if (DIEOffset > NextCUOffset)
219 fprintf(stderr, "warning: DWARF compile unit extends beyond its "
220 "bounds cu 0x%8.8x at 0x%8.8x'\n", getOffset(), DIEOffset);
223 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
224 if ((CUDieOnly && !DieArray.empty()) ||
226 return 0; // Already parsed.
228 bool HasCUDie = !DieArray.empty();
229 extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
231 if (DieArray.empty())
234 // If CU DIE was just parsed, copy several attribute values from it.
236 DWARFDie UnitDie = getUnitDIE();
237 auto BaseAddr = toAddress(UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc}));
239 setBaseAddress(*BaseAddr);
240 AddrOffsetSectionBase = toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
241 RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
243 // In general, we derive the offset of the unit's contibution to the
244 // debug_str_offsets{.dwo} section from the unit DIE's
245 // DW_AT_str_offsets_base attribute. In dwp files we add to it the offset
246 // we get from the index table.
247 StringOffsetSectionBase =
248 toSectionOffset(UnitDie.find(DW_AT_str_offsets_base), 0);
250 if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
251 StringOffsetSectionBase += C->Offset;
253 // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
254 // skeleton CU DIE, so that DWARF users not aware of it are not broken.
257 return DieArray.size();
260 bool DWARFUnit::parseDWO() {
265 DWARFDie UnitDie = getUnitDIE();
268 auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
271 auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
272 SmallString<16> AbsolutePath;
273 if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
275 sys::path::append(AbsolutePath, *CompilationDir);
277 sys::path::append(AbsolutePath, *DWOFileName);
278 auto DWOId = getDWOId();
281 auto DWOContext = Context.getDWOContext(AbsolutePath);
285 DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
288 DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
289 // Share .debug_addr and .debug_ranges section with compile unit in .dwo
290 DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
291 auto DWORangesBase = UnitDie.getRangesBaseAttribute();
292 DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
296 void DWARFUnit::clearDIEs(bool KeepCUDie) {
297 if (DieArray.size() > (unsigned)KeepCUDie) {
298 // std::vectors never get any smaller when resized to a smaller size,
299 // or when clear() or erase() are called, the size will report that it
300 // is smaller, but the memory allocated remains intact (call capacity()
301 // to see this). So we need to create a temporary vector and swap the
302 // contents which will cause just the internal pointers to be swapped
303 // so that when temporary vector goes out of scope, it will destroy the
305 std::vector<DWARFDebugInfoEntry> TmpArray;
306 DieArray.swap(TmpArray);
307 // Save at least the compile unit DIE
309 DieArray.push_back(TmpArray.front());
313 void DWARFUnit::collectAddressRanges(DWARFAddressRangesVector &CURanges) {
314 DWARFDie UnitDie = getUnitDIE();
317 // First, check if unit DIE describes address ranges for the whole unit.
318 const auto &CUDIERanges = UnitDie.getAddressRanges();
319 if (!CUDIERanges.empty()) {
320 CURanges.insert(CURanges.end(), CUDIERanges.begin(), CUDIERanges.end());
324 // This function is usually called if there in no .debug_aranges section
325 // in order to produce a compile unit level set of address ranges that
326 // is accurate. If the DIEs weren't parsed, then we don't want all dies for
327 // all compile units to stay loaded when they weren't needed. So we can end
328 // up parsing the DWARF and then throwing them all away to keep memory usage
330 const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
331 getUnitDIE().collectChildrenAddressRanges(CURanges);
333 // Collect address ranges from DIEs in .dwo if necessary.
334 bool DWOCreated = parseDWO();
336 DWO->collectAddressRanges(CURanges);
340 // Keep memory down by clearing DIEs if this generate function
341 // caused them to be parsed.
346 void DWARFUnit::updateAddressDieMap(DWARFDie Die) {
347 if (Die.isSubroutineDIE()) {
348 for (const auto &R : Die.getAddressRanges()) {
349 // Ignore 0-sized ranges.
350 if (R.LowPC == R.HighPC)
352 auto B = AddrDieMap.upper_bound(R.LowPC);
353 if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
354 // The range is a sub-range of existing ranges, we need to split the
356 if (R.HighPC < B->second.first)
357 AddrDieMap[R.HighPC] = B->second;
358 if (R.LowPC > B->first)
359 AddrDieMap[B->first].first = R.LowPC;
361 AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
364 // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
365 // simplify the logic to update AddrDieMap. The child's range will always
366 // be equal or smaller than the parent's range. With this assumption, when
367 // adding one range into the map, it will at most split a range into 3
369 for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
370 updateAddressDieMap(Child);
373 DWARFDie DWARFUnit::getSubroutineForAddress(uint64_t Address) {
374 extractDIEsIfNeeded(false);
375 if (AddrDieMap.empty())
376 updateAddressDieMap(getUnitDIE());
377 auto R = AddrDieMap.upper_bound(Address);
378 if (R == AddrDieMap.begin())
380 // upper_bound's previous item contains Address.
382 if (Address >= R->second.first)
384 return R->second.second;
388 DWARFUnit::getInlinedChainForAddress(uint64_t Address,
389 SmallVectorImpl<DWARFDie> &InlinedChain) {
390 assert(InlinedChain.empty());
391 // Try to look for subprogram DIEs in the DWO file.
393 // First, find the subroutine that contains the given address (the leaf
394 // of inlined chain).
395 DWARFDie SubroutineDIE =
396 (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
398 while (SubroutineDIE) {
399 if (SubroutineDIE.isSubroutineDIE())
400 InlinedChain.push_back(SubroutineDIE);
401 SubroutineDIE = SubroutineDIE.getParent();
405 const DWARFUnitIndex &llvm::getDWARFUnitIndex(DWARFContext &Context,
406 DWARFSectionKind Kind) {
407 if (Kind == DW_SECT_INFO)
408 return Context.getCUIndex();
409 assert(Kind == DW_SECT_TYPES);
410 return Context.getTUIndex();
413 DWARFDie DWARFUnit::getParent(const DWARFDebugInfoEntry *Die) {
416 const uint32_t Depth = Die->getDepth();
417 // Unit DIEs always have a depth of zero and never have parents.
420 // Depth of 1 always means parent is the compile/type unit.
423 // Look for previous DIE with a depth that is one less than the Die's depth.
424 const uint32_t ParentDepth = Depth - 1;
425 for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
426 if (DieArray[I].getDepth() == ParentDepth)
427 return DWARFDie(this, &DieArray[I]);
432 DWARFDie DWARFUnit::getSibling(const DWARFDebugInfoEntry *Die) {
435 uint32_t Depth = Die->getDepth();
436 // Unit DIEs always have a depth of zero and never have siblings.
439 // NULL DIEs don't have siblings.
440 if (Die->getAbbreviationDeclarationPtr() == nullptr)
443 // Find the next DIE whose depth is the same as the Die's depth.
444 for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
446 if (DieArray[I].getDepth() == Depth)
447 return DWARFDie(this, &DieArray[I]);