LLVM  8.0.0svn
DWARFUnit.cpp
Go to the documentation of this file.
1 //===- DWARFUnit.cpp ------------------------------------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/StringRef.h"
23 #include "llvm/Support/Errc.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/WithColor.h"
26 #include <algorithm>
27 #include <cassert>
28 #include <cstddef>
29 #include <cstdint>
30 #include <cstdio>
31 #include <utility>
32 #include <vector>
33 
34 using namespace llvm;
35 using namespace dwarf;
36 
38  const DWARFSection &Section,
40  const DWARFObject &D = C.getDWARFObj();
41  addUnitsImpl(C, D, Section, C.getDebugAbbrev(), &D.getRangeSection(),
44  false, false, SectionKind);
45 }
46 
48  const DWARFSection &DWOSection,
50  bool Lazy) {
51  const DWARFObject &D = C.getDWARFObj();
52  addUnitsImpl(C, D, DWOSection, C.getDebugAbbrevDWO(), &D.getRangeDWOSection(),
55  true, Lazy, SectionKind);
56 }
57 
58 void DWARFUnitVector::addUnitsImpl(
60  const DWARFDebugAbbrev *DA, const DWARFSection *RS, StringRef SS,
61  const DWARFSection &SOS, const DWARFSection *AOS, const DWARFSection &LS,
62  bool LE, bool IsDWO, bool Lazy, DWARFSectionKind SectionKind) {
63  DWARFDataExtractor Data(Obj, Section, LE, 0);
64  // Lazy initialization of Parser, now that we have all section info.
65  if (!Parser) {
66  Parser = [=, &Context, &Obj, &Section, &SOS, &LS](
67  uint32_t Offset, DWARFSectionKind SectionKind,
68  const DWARFSection *CurSection) -> std::unique_ptr<DWARFUnit> {
69  const DWARFSection &InfoSection = CurSection ? *CurSection : Section;
70  DWARFDataExtractor Data(Obj, InfoSection, LE, 0);
71  if (!Data.isValidOffset(Offset))
72  return nullptr;
73  const DWARFUnitIndex *Index = nullptr;
74  if (IsDWO)
75  Index = &getDWARFUnitIndex(Context, SectionKind);
76  DWARFUnitHeader Header;
77  if (!Header.extract(Context, Data, &Offset, SectionKind, Index))
78  return nullptr;
79  std::unique_ptr<DWARFUnit> U;
80  if (Header.isTypeUnit())
81  U = llvm::make_unique<DWARFTypeUnit>(Context, InfoSection, Header, DA,
82  RS, SS, SOS, AOS, LS, LE, IsDWO,
83  *this);
84  else
85  U = llvm::make_unique<DWARFCompileUnit>(Context, InfoSection, Header,
86  DA, RS, SS, SOS, AOS, LS, LE,
87  IsDWO, *this);
88  return U;
89  };
90  }
91  if (Lazy)
92  return;
93  // Find a reasonable insertion point within the vector. We skip over
94  // (a) units from a different section, (b) units from the same section
95  // but with lower offset-within-section. This keeps units in order
96  // within a section, although not necessarily within the object file,
97  // even if we do lazy parsing.
98  auto I = this->begin();
99  uint32_t Offset = 0;
100  while (Data.isValidOffset(Offset)) {
101  if (I != this->end() &&
102  (&(*I)->getInfoSection() != &Section || (*I)->getOffset() == Offset)) {
103  ++I;
104  continue;
105  }
106  auto U = Parser(Offset, SectionKind, &Section);
107  // If parsing failed, we're done with this section.
108  if (!U)
109  break;
110  Offset = U->getNextUnitOffset();
111  I = std::next(this->insert(I, std::move(U)));
112  }
113 }
114 
116  auto end = begin() + getNumInfoUnits();
117  auto *CU =
118  std::upper_bound(begin(), end, Offset,
119  [](uint32_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
120  return LHS < RHS->getNextUnitOffset();
121  });
122  if (CU != end && (*CU)->getOffset() <= Offset)
123  return CU->get();
124  return nullptr;
125 }
126 
127 DWARFUnit *
129  const auto *CUOff = E.getOffset(DW_SECT_INFO);
130  if (!CUOff)
131  return nullptr;
132 
133  auto Offset = CUOff->Offset;
134  auto end = begin() + getNumInfoUnits();
135 
136  auto *CU =
137  std::upper_bound(begin(), end, CUOff->Offset,
138  [](uint32_t LHS, const std::unique_ptr<DWARFUnit> &RHS) {
139  return LHS < RHS->getNextUnitOffset();
140  });
141  if (CU != end && (*CU)->getOffset() <= Offset)
142  return CU->get();
143 
144  if (!Parser)
145  return nullptr;
146 
147  auto U = Parser(Offset, DW_SECT_INFO, nullptr);
148  if (!U)
149  U = nullptr;
150 
151  auto *NewCU = U.get();
152  this->insert(CU, std::move(U));
153  ++NumInfoUnits;
154  return NewCU;
155 }
156 
158  const DWARFUnitHeader &Header,
159  const DWARFDebugAbbrev *DA, const DWARFSection *RS,
160  StringRef SS, const DWARFSection &SOS,
161  const DWARFSection *AOS, const DWARFSection &LS, bool LE,
162  bool IsDWO, const DWARFUnitVector &UnitVector)
163  : Context(DC), InfoSection(Section), Header(Header), Abbrev(DA),
164  RangeSection(RS), LineSection(LS), StringSection(SS),
165  StringOffsetSection(SOS), AddrOffsetSection(AOS), isLittleEndian(LE),
166  isDWO(IsDWO), UnitVector(UnitVector) {
167  clear();
168 }
169 
170 DWARFUnit::~DWARFUnit() = default;
171 
173  return DWARFDataExtractor(Context.getDWARFObj(), InfoSection, isLittleEndian,
175 }
176 
178  uint64_t &Result) const {
179  uint32_t Offset = AddrOffsetSectionBase + Index * getAddressByteSize();
180  if (AddrOffsetSection->Data.size() < Offset + getAddressByteSize())
181  return false;
182  DWARFDataExtractor DA(Context.getDWARFObj(), *AddrOffsetSection,
183  isLittleEndian, getAddressByteSize());
184  Result = DA.getRelocatedAddress(&Offset);
185  return true;
186 }
187 
189  uint64_t &Result) const {
190  if (!StringOffsetsTableContribution)
191  return false;
192  unsigned ItemSize = getDwarfStringOffsetsByteSize();
193  uint32_t Offset = getStringOffsetsBase() + Index * ItemSize;
194  if (StringOffsetSection.Data.size() < Offset + ItemSize)
195  return false;
196  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
197  isLittleEndian, 0);
198  Result = DA.getRelocatedValue(ItemSize, &Offset);
199  return true;
200 }
201 
203  const DWARFDataExtractor &debug_info,
204  uint32_t *offset_ptr,
206  const DWARFUnitIndex *Index) {
207  Offset = *offset_ptr;
208  IndexEntry = Index ? Index->getFromOffset(*offset_ptr) : nullptr;
209  Length = debug_info.getU32(offset_ptr);
210  // FIXME: Support DWARF64.
211  unsigned SizeOfLength = 4;
213  FormParams.Version = debug_info.getU16(offset_ptr);
214  if (FormParams.Version >= 5) {
215  UnitType = debug_info.getU8(offset_ptr);
216  FormParams.AddrSize = debug_info.getU8(offset_ptr);
217  AbbrOffset = debug_info.getU32(offset_ptr);
218  } else {
219  AbbrOffset = debug_info.getRelocatedValue(4, offset_ptr);
220  FormParams.AddrSize = debug_info.getU8(offset_ptr);
221  // Fake a unit type based on the section type. This isn't perfect,
222  // but distinguishing compile and type units is generally enough.
223  if (SectionKind == DW_SECT_TYPES)
224  UnitType = DW_UT_type;
225  else
226  UnitType = DW_UT_compile;
227  }
228  if (IndexEntry) {
229  if (AbbrOffset)
230  return false;
231  auto *UnitContrib = IndexEntry->getOffset();
232  if (!UnitContrib || UnitContrib->Length != (Length + 4))
233  return false;
234  auto *AbbrEntry = IndexEntry->getOffset(DW_SECT_ABBREV);
235  if (!AbbrEntry)
236  return false;
237  AbbrOffset = AbbrEntry->Offset;
238  }
239  if (isTypeUnit()) {
240  TypeHash = debug_info.getU64(offset_ptr);
241  TypeOffset = debug_info.getU32(offset_ptr);
242  } else if (UnitType == DW_UT_split_compile || UnitType == DW_UT_skeleton)
243  DWOId = debug_info.getU64(offset_ptr);
244 
245  // Header fields all parsed, capture the size of this unit header.
246  assert(*offset_ptr - Offset <= 255 && "unexpected header size");
247  Size = uint8_t(*offset_ptr - Offset);
248 
249  // Type offset is unit-relative; should be after the header and before
250  // the end of the current unit.
251  bool TypeOffsetOK =
252  !isTypeUnit()
253  ? true
254  : TypeOffset >= Size && TypeOffset < getLength() + SizeOfLength;
255  bool LengthOK = debug_info.isValidOffset(getNextUnitOffset() - 1);
256  bool VersionOK = DWARFContext::isSupportedVersion(getVersion());
257  bool AddrSizeOK = getAddressByteSize() == 4 || getAddressByteSize() == 8;
258 
259  if (!LengthOK || !VersionOK || !AddrSizeOK || !TypeOffsetOK)
260  return false;
261 
262  // Keep track of the highest DWARF version we encounter across all units.
264  return true;
265 }
266 
267 // Parse the rangelist table header, including the optional array of offsets
268 // following it (DWARF v5 and later).
271  // TODO: Support DWARF64
272  // We are expected to be called with Offset 0 or pointing just past the table
273  // header, which is 12 bytes long for DWARF32.
274  if (Offset > 0) {
275  if (Offset < 12U)
276  return createStringError(errc::invalid_argument, "Did not detect a valid"
277  " range list table with base = 0x%" PRIu32,
278  Offset);
279  Offset -= 12U;
280  }
282  if (Error E = Table.extractHeaderAndOffsets(DA, &Offset))
283  return std::move(E);
284  return Table;
285 }
286 
288  DWARFDebugRangeList &RangeList) const {
289  // Require that compile unit is extracted.
290  assert(!DieArray.empty());
291  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
292  isLittleEndian, getAddressByteSize());
293  uint32_t ActualRangeListOffset = RangeSectionBase + RangeListOffset;
294  return RangeList.extract(RangesData, &ActualRangeListOffset);
295 }
296 
298  Abbrevs = nullptr;
299  BaseAddr.reset();
300  RangeSectionBase = 0;
301  AddrOffsetSectionBase = 0;
302  clearDIEs(false);
303  DWO.reset();
304 }
305 
307  return dwarf::toString(getUnitDIE().find(DW_AT_comp_dir), nullptr);
308 }
309 
310 void DWARFUnit::extractDIEsToVector(
311  bool AppendCUDie, bool AppendNonCUDies,
312  std::vector<DWARFDebugInfoEntry> &Dies) const {
313  if (!AppendCUDie && !AppendNonCUDies)
314  return;
315 
316  // Set the offset to that of the first DIE and calculate the start of the
317  // next compilation unit header.
318  uint32_t DIEOffset = getOffset() + getHeaderSize();
319  uint32_t NextCUOffset = getNextUnitOffset();
321  DWARFDataExtractor DebugInfoData = getDebugInfoExtractor();
322  uint32_t Depth = 0;
323  bool IsCUDie = true;
324 
325  while (DIE.extractFast(*this, &DIEOffset, DebugInfoData, NextCUOffset,
326  Depth)) {
327  if (IsCUDie) {
328  if (AppendCUDie)
329  Dies.push_back(DIE);
330  if (!AppendNonCUDies)
331  break;
332  // The average bytes per DIE entry has been seen to be
333  // around 14-20 so let's pre-reserve the needed memory for
334  // our DIE entries accordingly.
335  Dies.reserve(Dies.size() + getDebugInfoSize() / 14);
336  IsCUDie = false;
337  } else {
338  Dies.push_back(DIE);
339  }
340 
341  if (const DWARFAbbreviationDeclaration *AbbrDecl =
343  // Normal DIE
344  if (AbbrDecl->hasChildren())
345  ++Depth;
346  } else {
347  // NULL DIE.
348  if (Depth > 0)
349  --Depth;
350  if (Depth == 0)
351  break; // We are done with this compile unit!
352  }
353  }
354 
355  // Give a little bit of info if we encounter corrupt DWARF (our offset
356  // should always terminate at or before the start of the next compilation
357  // unit header).
358  if (DIEOffset > NextCUOffset)
359  WithColor::warning() << format("DWARF compile unit extends beyond its "
360  "bounds cu 0x%8.8x at 0x%8.8x\n",
361  getOffset(), DIEOffset);
362 }
363 
364 size_t DWARFUnit::extractDIEsIfNeeded(bool CUDieOnly) {
365  if ((CUDieOnly && !DieArray.empty()) ||
366  DieArray.size() > 1)
367  return 0; // Already parsed.
368 
369  bool HasCUDie = !DieArray.empty();
370  extractDIEsToVector(!HasCUDie, !CUDieOnly, DieArray);
371 
372  if (DieArray.empty())
373  return 0;
374 
375  // If CU DIE was just parsed, copy several attribute values from it.
376  if (!HasCUDie) {
377  DWARFDie UnitDie = getUnitDIE();
378  if (Optional<uint64_t> DWOId = toUnsigned(UnitDie.find(DW_AT_GNU_dwo_id)))
379  Header.setDWOId(*DWOId);
380  if (!isDWO) {
381  assert(AddrOffsetSectionBase == 0);
382  assert(RangeSectionBase == 0);
383  AddrOffsetSectionBase =
384  toSectionOffset(UnitDie.find(DW_AT_GNU_addr_base), 0);
385  RangeSectionBase = toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0);
386  }
387 
388  // In general, in DWARF v5 and beyond we derive the start of the unit's
389  // contribution to the string offsets table from the unit DIE's
390  // DW_AT_str_offsets_base attribute. Split DWARF units do not use this
391  // attribute, so we assume that there is a contribution to the string
392  // offsets table starting at offset 0 of the debug_str_offsets.dwo section.
393  // In both cases we need to determine the format of the contribution,
394  // which may differ from the unit's format.
395  uint64_t StringOffsetsContributionBase =
396  isDWO ? 0 : toSectionOffset(UnitDie.find(DW_AT_str_offsets_base), 0);
397  auto IndexEntry = Header.getIndexEntry();
398  if (IndexEntry)
399  if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
400  StringOffsetsContributionBase += C->Offset;
401 
402  DWARFDataExtractor DA(Context.getDWARFObj(), StringOffsetSection,
403  isLittleEndian, 0);
404  if (isDWO)
405  StringOffsetsTableContribution =
407  DA, StringOffsetsContributionBase);
408  else if (getVersion() >= 5)
409  StringOffsetsTableContribution = determineStringOffsetsTableContribution(
410  DA, StringOffsetsContributionBase);
411 
412  // DWARF v5 uses the .debug_rnglists and .debug_rnglists.dwo sections to
413  // describe address ranges.
414  if (getVersion() >= 5) {
415  if (isDWO)
417  else
419  toSectionOffset(UnitDie.find(DW_AT_rnglists_base), 0));
420  if (RangeSection->Data.size()) {
421  // Parse the range list table header. Individual range lists are
422  // extracted lazily.
423  DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
424  isLittleEndian, 0);
425  if (auto TableOrError =
426  parseRngListTableHeader(RangesDA, RangeSectionBase))
427  RngListTable = TableOrError.get();
428  else
429  WithColor::error() << "parsing a range list table: "
430  << toString(TableOrError.takeError())
431  << '\n';
432 
433  // In a split dwarf unit, there is no DW_AT_rnglists_base attribute.
434  // Adjust RangeSectionBase to point past the table header.
435  if (isDWO && RngListTable)
436  RangeSectionBase = RngListTable->getHeaderSize();
437  }
438  }
439 
440  // Don't fall back to DW_AT_GNU_ranges_base: it should be ignored for
441  // skeleton CU DIE, so that DWARF users not aware of it are not broken.
442  }
443 
444  return DieArray.size();
445 }
446 
447 bool DWARFUnit::parseDWO() {
448  if (isDWO)
449  return false;
450  if (DWO.get())
451  return false;
452  DWARFDie UnitDie = getUnitDIE();
453  if (!UnitDie)
454  return false;
455  auto DWOFileName = dwarf::toString(UnitDie.find(DW_AT_GNU_dwo_name));
456  if (!DWOFileName)
457  return false;
458  auto CompilationDir = dwarf::toString(UnitDie.find(DW_AT_comp_dir));
459  SmallString<16> AbsolutePath;
460  if (sys::path::is_relative(*DWOFileName) && CompilationDir &&
461  *CompilationDir) {
462  sys::path::append(AbsolutePath, *CompilationDir);
463  }
464  sys::path::append(AbsolutePath, *DWOFileName);
465  auto DWOId = getDWOId();
466  if (!DWOId)
467  return false;
468  auto DWOContext = Context.getDWOContext(AbsolutePath);
469  if (!DWOContext)
470  return false;
471 
472  DWARFCompileUnit *DWOCU = DWOContext->getDWOCompileUnitForHash(*DWOId);
473  if (!DWOCU)
474  return false;
475  DWO = std::shared_ptr<DWARFCompileUnit>(std::move(DWOContext), DWOCU);
476  // Share .debug_addr and .debug_ranges section with compile unit in .dwo
477  DWO->setAddrOffsetSection(AddrOffsetSection, AddrOffsetSectionBase);
478  if (getVersion() >= 5) {
479  DWO->setRangesSection(&Context.getDWARFObj().getRnglistsDWOSection(), 0);
480  DWARFDataExtractor RangesDA(Context.getDWARFObj(), *RangeSection,
481  isLittleEndian, 0);
482  if (auto TableOrError = parseRngListTableHeader(RangesDA, RangeSectionBase))
483  DWO->RngListTable = TableOrError.get();
484  else
485  WithColor::error() << "parsing a range list table: "
486  << toString(TableOrError.takeError())
487  << '\n';
488  if (DWO->RngListTable)
489  DWO->RangeSectionBase = DWO->RngListTable->getHeaderSize();
490  } else {
491  auto DWORangesBase = UnitDie.getRangesBaseAttribute();
492  DWO->setRangesSection(RangeSection, DWORangesBase ? *DWORangesBase : 0);
493  }
494 
495  return true;
496 }
497 
498 void DWARFUnit::clearDIEs(bool KeepCUDie) {
499  if (DieArray.size() > (unsigned)KeepCUDie) {
500  DieArray.resize((unsigned)KeepCUDie);
501  DieArray.shrink_to_fit();
502  }
503 }
504 
507  if (getVersion() <= 4) {
508  DWARFDebugRangeList RangeList;
509  if (Error E = extractRangeList(Offset, RangeList))
510  return std::move(E);
511  return RangeList.getAbsoluteRanges(getBaseAddress());
512  }
513  if (RngListTable) {
514  DWARFDataExtractor RangesData(Context.getDWARFObj(), *RangeSection,
515  isLittleEndian, RngListTable->getAddrSize());
516  auto RangeListOrError = RngListTable->findList(RangesData, Offset);
517  if (RangeListOrError)
518  return RangeListOrError.get().getAbsoluteRanges(getBaseAddress());
519  return RangeListOrError.takeError();
520  }
521 
523  "missing or invalid range list table");
524 }
525 
528  if (auto Offset = getRnglistOffset(Index))
529  return findRnglistFromOffset(*Offset + RangeSectionBase);
530 
531  if (RngListTable)
533  "invalid range list table index %d", Index);
534  else
536  "missing or invalid range list table");
537 }
538 
540  DWARFDie UnitDie = getUnitDIE();
541  if (!UnitDie)
542  return;
543  // First, check if unit DIE describes address ranges for the whole unit.
544  auto CUDIERangesOrError = UnitDie.getAddressRanges();
545  if (CUDIERangesOrError) {
546  if (!CUDIERangesOrError.get().empty()) {
547  CURanges.insert(CURanges.end(), CUDIERangesOrError.get().begin(),
548  CUDIERangesOrError.get().end());
549  return;
550  }
551  } else
552  WithColor::error() << "decoding address ranges: "
553  << toString(CUDIERangesOrError.takeError()) << '\n';
554 
555  // This function is usually called if there in no .debug_aranges section
556  // in order to produce a compile unit level set of address ranges that
557  // is accurate. If the DIEs weren't parsed, then we don't want all dies for
558  // all compile units to stay loaded when they weren't needed. So we can end
559  // up parsing the DWARF and then throwing them all away to keep memory usage
560  // down.
561  const bool ClearDIEs = extractDIEsIfNeeded(false) > 1;
563 
564  // Collect address ranges from DIEs in .dwo if necessary.
565  bool DWOCreated = parseDWO();
566  if (DWO)
567  DWO->collectAddressRanges(CURanges);
568  if (DWOCreated)
569  DWO.reset();
570 
571  // Keep memory down by clearing DIEs if this generate function
572  // caused them to be parsed.
573  if (ClearDIEs)
574  clearDIEs(true);
575 }
576 
578  if (Die.isSubroutineDIE()) {
579  auto DIERangesOrError = Die.getAddressRanges();
580  if (DIERangesOrError) {
581  for (const auto &R : DIERangesOrError.get()) {
582  // Ignore 0-sized ranges.
583  if (R.LowPC == R.HighPC)
584  continue;
585  auto B = AddrDieMap.upper_bound(R.LowPC);
586  if (B != AddrDieMap.begin() && R.LowPC < (--B)->second.first) {
587  // The range is a sub-range of existing ranges, we need to split the
588  // existing range.
589  if (R.HighPC < B->second.first)
590  AddrDieMap[R.HighPC] = B->second;
591  if (R.LowPC > B->first)
592  AddrDieMap[B->first].first = R.LowPC;
593  }
594  AddrDieMap[R.LowPC] = std::make_pair(R.HighPC, Die);
595  }
596  } else
597  llvm::consumeError(DIERangesOrError.takeError());
598  }
599  // Parent DIEs are added to the AddrDieMap prior to the Children DIEs to
600  // simplify the logic to update AddrDieMap. The child's range will always
601  // be equal or smaller than the parent's range. With this assumption, when
602  // adding one range into the map, it will at most split a range into 3
603  // sub-ranges.
604  for (DWARFDie Child = Die.getFirstChild(); Child; Child = Child.getSibling())
605  updateAddressDieMap(Child);
606 }
607 
609  extractDIEsIfNeeded(false);
610  if (AddrDieMap.empty())
612  auto R = AddrDieMap.upper_bound(Address);
613  if (R == AddrDieMap.begin())
614  return DWARFDie();
615  // upper_bound's previous item contains Address.
616  --R;
617  if (Address >= R->second.first)
618  return DWARFDie();
619  return R->second.second;
620 }
621 
622 void
624  SmallVectorImpl<DWARFDie> &InlinedChain) {
625  assert(InlinedChain.empty());
626  // Try to look for subprogram DIEs in the DWO file.
627  parseDWO();
628  // First, find the subroutine that contains the given address (the leaf
629  // of inlined chain).
630  DWARFDie SubroutineDIE =
631  (DWO ? DWO.get() : this)->getSubroutineForAddress(Address);
632 
633  if (!SubroutineDIE)
634  return;
635 
636  while (!SubroutineDIE.isSubprogramDIE()) {
637  if (SubroutineDIE.getTag() == DW_TAG_inlined_subroutine)
638  InlinedChain.push_back(SubroutineDIE);
639  SubroutineDIE = SubroutineDIE.getParent();
640  }
641  InlinedChain.push_back(SubroutineDIE);
642 }
643 
646  if (Kind == DW_SECT_INFO)
647  return Context.getCUIndex();
648  assert(Kind == DW_SECT_TYPES);
649  return Context.getTUIndex();
650 }
651 
653  if (!Die)
654  return DWARFDie();
655  const uint32_t Depth = Die->getDepth();
656  // Unit DIEs always have a depth of zero and never have parents.
657  if (Depth == 0)
658  return DWARFDie();
659  // Depth of 1 always means parent is the compile/type unit.
660  if (Depth == 1)
661  return getUnitDIE();
662  // Look for previous DIE with a depth that is one less than the Die's depth.
663  const uint32_t ParentDepth = Depth - 1;
664  for (uint32_t I = getDIEIndex(Die) - 1; I > 0; --I) {
665  if (DieArray[I].getDepth() == ParentDepth)
666  return DWARFDie(this, &DieArray[I]);
667  }
668  return DWARFDie();
669 }
670 
672  if (!Die)
673  return DWARFDie();
674  uint32_t Depth = Die->getDepth();
675  // Unit DIEs always have a depth of zero and never have siblings.
676  if (Depth == 0)
677  return DWARFDie();
678  // NULL DIEs don't have siblings.
679  if (Die->getAbbreviationDeclarationPtr() == nullptr)
680  return DWARFDie();
681 
682  // Find the next DIE whose depth is the same as the Die's depth.
683  for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
684  ++I) {
685  if (DieArray[I].getDepth() == Depth)
686  return DWARFDie(this, &DieArray[I]);
687  }
688  return DWARFDie();
689 }
690 
692  if (!Die)
693  return DWARFDie();
694  uint32_t Depth = Die->getDepth();
695  // Unit DIEs always have a depth of zero and never have siblings.
696  if (Depth == 0)
697  return DWARFDie();
698 
699  // Find the previous DIE whose depth is the same as the Die's depth.
700  for (size_t I = getDIEIndex(Die); I > 0;) {
701  --I;
702  if (DieArray[I].getDepth() == Depth - 1)
703  return DWARFDie();
704  if (DieArray[I].getDepth() == Depth)
705  return DWARFDie(this, &DieArray[I]);
706  }
707  return DWARFDie();
708 }
709 
711  if (!Die->hasChildren())
712  return DWARFDie();
713 
714  // We do not want access out of bounds when parsing corrupted debug data.
715  size_t I = getDIEIndex(Die) + 1;
716  if (I >= DieArray.size())
717  return DWARFDie();
718  return DWARFDie(this, &DieArray[I]);
719 }
720 
722  if (!Die->hasChildren())
723  return DWARFDie();
724 
725  uint32_t Depth = Die->getDepth();
726  for (size_t I = getDIEIndex(Die) + 1, EndIdx = DieArray.size(); I < EndIdx;
727  ++I) {
728  if (DieArray[I].getDepth() == Depth + 1 &&
729  DieArray[I].getTag() == dwarf::DW_TAG_null)
730  return DWARFDie(this, &DieArray[I]);
731  assert(DieArray[I].getDepth() > Depth && "Not processing children?");
732  }
733  return DWARFDie();
734 }
735 
737  if (!Abbrevs)
738  Abbrevs = Abbrev->getAbbreviationDeclarationSet(Header.getAbbrOffset());
739  return Abbrevs;
740 }
741 
743  if (BaseAddr)
744  return BaseAddr;
745 
746  DWARFDie UnitDie = getUnitDIE();
747  Optional<DWARFFormValue> PC = UnitDie.find({DW_AT_low_pc, DW_AT_entry_pc});
748  if (Optional<uint64_t> Addr = toAddress(PC))
749  BaseAddr = {*Addr, PC->getSectionIndex()};
750 
751  return BaseAddr;
752 }
753 
756  DWARFDataExtractor &DA) {
757  uint8_t EntrySize = getDwarfOffsetByteSize();
758  // In order to ensure that we don't read a partial record at the end of
759  // the section we validate for a multiple of the entry size.
760  uint64_t ValidationSize = alignTo(Size, EntrySize);
761  // Guard against overflow.
762  if (ValidationSize >= Size)
763  if (DA.isValidOffsetForDataOfSize((uint32_t)Base, ValidationSize))
764  return *this;
766 }
767 
768 // Look for a DWARF64-formatted contribution to the string offsets table
769 // starting at a given offset and record it in a descriptor.
772  if (!DA.isValidOffsetForDataOfSize(Offset, 16))
774 
775  if (DA.getU32(&Offset) != 0xffffffff)
777 
778  uint64_t Size = DA.getU64(&Offset);
779  uint8_t Version = DA.getU16(&Offset);
780  (void)DA.getU16(&Offset); // padding
781  // The encoded length includes the 2-byte version field and the 2-byte
782  // padding, so we need to subtract them out when we populate the descriptor.
783  return StrOffsetsContributionDescriptor(Offset, Size - 4, Version, DWARF64);
784  //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
785 }
786 
787 // Look for a DWARF32-formatted contribution to the string offsets table
788 // starting at a given offset and record it in a descriptor.
791  if (!DA.isValidOffsetForDataOfSize(Offset, 8))
793  uint32_t ContributionSize = DA.getU32(&Offset);
794  if (ContributionSize >= 0xfffffff0)
796  uint8_t Version = DA.getU16(&Offset);
797  (void)DA.getU16(&Offset); // padding
798  // The encoded length includes the 2-byte version field and the 2-byte
799  // padding, so we need to subtract them out when we populate the descriptor.
800  return StrOffsetsContributionDescriptor(Offset, ContributionSize - 4, Version,
801  DWARF32);
802  //return Optional<StrOffsetsContributionDescriptor>(Descriptor);
803 }
804 
807  uint64_t Offset) {
809  // Attempt to find a DWARF64 contribution 16 bytes before the base.
810  if (Offset >= 16)
811  Descriptor =
813  // Try to find a DWARF32 contribution 8 bytes before the base.
814  if (!Descriptor && Offset >= 8)
815  Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset - 8);
816  return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
817 }
818 
821  uint64_t Offset) {
822  if (getVersion() >= 5) {
823  // Look for a valid contribution at the given offset.
824  auto Descriptor =
826  if (!Descriptor)
827  Descriptor = parseDWARF32StringOffsetsTableHeader(DA, (uint32_t)Offset);
828  return Descriptor ? Descriptor->validateContributionSize(DA) : Descriptor;
829  }
830  // Prior to DWARF v5, we derive the contribution size from the
831  // index table (in a package file). In a .dwo file it is simply
832  // the length of the string offsets section.
833  uint64_t Size = 0;
834  auto IndexEntry = Header.getIndexEntry();
835  if (!IndexEntry)
836  Size = StringOffsetSection.Data.size();
837  else if (const auto *C = IndexEntry->getOffset(DW_SECT_STR_OFFSETS))
838  Size = C->Length;
839  // Return a descriptor with the given offset as base, version 4 and
840  // DWARF32 format.
841  //return Optional<StrOffsetsContributionDescriptor>(
842  //StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32));
843  return StrOffsetsContributionDescriptor(Offset, Size, 4, DWARF32);
844 }
const DWARFAbbreviationDeclarationSet * getAbbreviations() const
Definition: DWARFUnit.cpp:736
const DWARFUnitIndex & getTUIndex()
uint64_t CallInst * C
void getInlinedChainForAddress(uint64_t Address, SmallVectorImpl< DWARFDie > &InlinedChain)
getInlinedChainForAddress - fetches inlined chain for a given address.
Definition: DWARFUnit.cpp:623
virtual ~DWARFUnit()
const_iterator end(StringRef path)
Get end iterator over path.
Definition: Path.cpp:259
virtual const DWARFSection & getAddrSection() const
Definition: DWARFObject.h:67
A helper struct providing information about the byte size of DW_FORM values that vary in size dependi...
Definition: Dwarf.h:494
LLVMContext & Context
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
Definition: Path.cpp:250
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
Represents a unit&#39;s contribution to the string offsets table.
Definition: DWARFUnit.h:165
bool isSubprogramDIE() const
Returns true if DIE represents a subprogram (not inlined).
Definition: DWARFDie.cpp:286
bool isTypeUnit() const
Definition: DWARFUnit.h:279
uint64_t getSectionIndex() const
std::shared_ptr< DWARFContext > getDWOContext(StringRef AbsolutePath)
void collectAddressRanges(DWARFAddressRangesVector &CURanges)
Definition: DWARFUnit.cpp:539
LLVM_NODISCARD LLVM_ATTRIBUTE_ALWAYS_INLINE size_t size() const
size - Get the string size.
Definition: StringRef.h:138
static raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition: WithColor.cpp:63
void collectChildrenAddressRanges(DWARFAddressRangesVector &Ranges) const
Get all address ranges for any DW_TAG_subprogram DIEs in this DIE or any of its children.
Definition: DWARFDie.cpp:411
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
DWARFDie getSibling(const DWARFDebugInfoEntry *Die)
Definition: DWARFUnit.cpp:671
unsigned second
static raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition: WithColor.cpp:65
static Optional< StrOffsetsContributionDescriptor > parseDWARF64StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset)
Definition: DWARFUnit.cpp:771
Optional< StrOffsetsContributionDescriptor > validateContributionSize(DWARFDataExtractor &DA)
Determine whether a contribution to the string offsets table is consistent with the relevant section ...
Definition: DWARFUnit.cpp:755
uint64_t alignTo(uint64_t Value, uint64_t Align, uint64_t Skew=0)
Returns the next integer (mod 2**64) that is greater than or equal to Value and is a multiple of Alig...
Definition: MathExtras.h:685
virtual const DWARFSection & getRnglistsDWOSection() const
Definition: DWARFObject.h:66
block Block Frequency true
Optional< StrOffsetsContributionDescriptor > determineStringOffsetsTableContribution(DWARFDataExtractor &DA, uint64_t Offset)
Find the unit&#39;s contribution to the string offsets table and determine its length and form...
Definition: DWARFUnit.cpp:806
const DWARFDebugAbbrev * getDebugAbbrevDWO()
Get a pointer to the parsed dwo abbreviations object.
uint8_t getDwarfStringOffsetsByteSize() const
Definition: DWARFUnit.h:322
uint16_t getU16(uint32_t *offset_ptr) const
Extract a uint16_t value from *offset_ptr.
void addUnitsForSection(DWARFContext &C, const DWARFSection &Section, DWARFSectionKind SectionKind)
Read units from a .debug_info or .debug_types section.
Definition: DWARFUnit.cpp:37
Optional< uint64_t > toAddress(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an address.
DWARFDie getSubroutineForAddress(uint64_t Address)
Returns subprogram DIE with address range encompassing the provided address.
Definition: DWARFUnit.cpp:608
static Optional< StrOffsetsContributionDescriptor > parseDWARF32StringOffsetsTableHeader(DWARFDataExtractor &DA, uint32_t Offset)
Definition: DWARFUnit.cpp:790
virtual bool isLittleEndian() const =0
uint32_t getNextUnitOffset() const
Definition: DWARFUnit.h:280
bool getAddrOffsetSectionItem(uint32_t Index, uint64_t &Result) const
Definition: DWARFUnit.cpp:177
void append(SmallVectorImpl< char > &path, const Twine &a, const Twine &b="", const Twine &c="", const Twine &d="")
Append to path.
Definition: Path.cpp:480
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:963
uint32_t getU32(uint32_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
static ManagedStatic< DebugCounter > DC
const char * getCompilationDir()
Definition: DWARFUnit.cpp:306
Optional< uint64_t > getRangesBaseAttribute() const
Extract the range base attribute from this DIE as absolute section offset.
Definition: DWARFDie.cpp:361
uint64_t getAbbrOffset() const
Definition: DWARFUnit.h:86
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Definition: APFloat.h:42
Error extractRangeList(uint32_t RangeListOffset, DWARFDebugRangeList &RangeList) const
Extract the range list referenced by this compile unit from the .debug_ranges section.
Definition: DWARFUnit.cpp:287
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
bool isTypeUnit() const
Definition: DWARFUnit.h:96
virtual const DWARFSection & getStringOffsetDWOSection() const
Definition: DWARFObject.h:62
uint8_t getAddressByteSize() const
Definition: DWARFUnit.h:272
SmallString - A SmallString is just a SmallVector with methods and accessors that make it work better...
Definition: SmallString.h:26
const DWARFDebugAbbrev * getDebugAbbrev()
Get a pointer to the parsed DebugAbbrev object.
DWARFDie getLastChild(const DWARFDebugInfoEntry *Die)
Definition: DWARFUnit.cpp:721
uint16_t getVersion() const
Definition: DWARFUnit.h:271
DWARFDie getSibling() const
Get the sibling of this DIE object.
Definition: DWARFDie.cpp:554
DWARFUnit(DWARFContext &Context, const DWARFSection &Section, const DWARFUnitHeader &Header, const DWARFDebugAbbrev *DA, const DWARFSection *RS, StringRef SS, const DWARFSection &SOS, const DWARFSection *AOS, const DWARFSection &LS, bool LE, bool IsDWO, const DWARFUnitVector &UnitVector)
Definition: DWARFUnit.cpp:157
Expected< DWARFAddressRangesVector > findRnglistFromIndex(uint32_t Index)
Return a vector of address ranges retrieved from an encoded range list whose offset is found via a ta...
Definition: DWARFUnit.cpp:527
DWARFDie getFirstChild(const DWARFDebugInfoEntry *Die)
Definition: DWARFUnit.cpp:710
Optional< uint64_t > toSectionOffset(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
bool isValidOffsetForDataOfSize(uint32_t offset, uint32_t length) const
Test the availability of length bytes of data from offset.
Utility class that carries the DWARF compile/type unit and the debug info entry in an object...
Definition: DWARFDie.h:43
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
virtual const DWARFSection & getStringOffsetSection() const
Definition: DWARFObject.h:54
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
DWARFSectionKind
A structured debug information entry.
Definition: DIE.h:662
bool isSubroutineDIE() const
Returns true if DIE represents a subprogram or an inlined subroutine.
Definition: DWARFDie.cpp:288
Optional< uint64_t > getDWOId()
Definition: DWARFUnit.h:381
bool extractFast(const DWARFUnit &U, uint32_t *OffsetPtr)
Extracts a debug info entry, which is a child of a given unit, starting at a given offset...
const DWARFAbbreviationDeclarationSet * getAbbreviationDeclarationSet(uint64_t CUAbbrOffset) const
DWARFDie getParent(const DWARFDebugInfoEntry *Die)
Definition: DWARFUnit.cpp:652
virtual const DWARFSection & getLineDWOSection() const
Definition: DWARFObject.h:59
uint8_t getU8(uint32_t *offset_ptr) const
Extract a uint8_t value from *offset_ptr.
SectionKind - This is a simple POD value that classifies the properties of a section.
Definition: SectionKind.h:23
virtual StringRef getStringSection() const
Definition: DWARFObject.h:46
void setRangesSection(const DWARFSection *RS, uint32_t Base)
Definition: DWARFUnit.h:295
virtual StringRef getStringDWOSection() const
Definition: DWARFObject.h:61
bool extract(DWARFContext &Context, const DWARFDataExtractor &debug_info, uint32_t *offset_ptr, DWARFSectionKind Kind=DW_SECT_INFO, const DWARFUnitIndex *Index=nullptr)
Parse a unit header from debug_info starting at offset_ptr.
Definition: DWARFUnit.cpp:202
uint32_t getHeaderSize() const
Size in bytes of the parsed unit header.
Definition: DWARFUnit.h:238
uint64_t getU64(uint32_t *offset_ptr) const
Extract a uint64_t value from *offset_ptr.
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:978
const DWARFUnitIndex & getDWARFUnitIndex(DWARFContext &Context, DWARFSectionKind Kind)
Definition: DWARFUnit.cpp:644
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1063
DWARFAddressRangesVector getAbsoluteRanges(llvm::Optional< BaseAddress > BaseAddr) const
getAbsoluteRanges - Returns absolute address ranges defined by this range list.
DWARFUnit * getUnitForOffset(uint32_t Offset) const
Definition: DWARFUnit.cpp:115
Base class describing the header of any kind of "unit." Some information is specific to certain unit ...
Definition: DWARFUnit.h:47
uint64_t getRelocatedValue(uint32_t Size, uint32_t *Off, uint64_t *SectionIndex=nullptr) const
Extracts a value and applies a relocation to the result if one exists for the given offset...
llvm::Optional< BaseAddress > getBaseAddress()
Definition: DWARFUnit.cpp:742
UnitType
Constants for unit types in DWARF v5.
Definition: Dwarf.h:327
DWARFUnit * getUnitForIndexEntry(const DWARFUnitIndex::Entry &E)
Definition: DWARFUnit.cpp:128
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
uint64_t getStringOffsetsBase() const
Definition: DWARFUnit.h:327
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition: DWARFUnit.h:373
const DWARFAbbreviationDeclaration * getAbbreviationDeclarationPtr() const
void setDWOId(uint64_t Id)
Definition: DWARFUnit.h:88
const DWARFUnitIndex::Entry * getIndexEntry() const
Definition: DWARFUnit.h:92
static Expected< DWARFDebugRnglistTable > parseRngListTableHeader(DWARFDataExtractor &DA, uint32_t Offset)
Definition: DWARFUnit.cpp:270
void addUnitsForDWOSection(DWARFContext &C, const DWARFSection &DWOSection, DWARFSectionKind SectionKind, bool Lazy=false)
Read units from a .debug_info.dwo or .debug_types.dwo section.
Definition: DWARFUnit.cpp:47
Error extractHeaderAndOffsets(DWARFDataExtractor Data, uint32_t *OffsetPtr)
Extract the table header and the array of offsets.
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:59
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
Describe a collection of units.
Definition: DWARFUnit.h:109
Optional< const char * > toString(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract a string value from it.
virtual const DWARFSection & getRnglistsSection() const
Definition: DWARFObject.h:48
uint32_t getLength() const
Definition: DWARFUnit.h:277
DWARFDataExtractor getDebugInfoExtractor() const
Definition: DWARFUnit.cpp:172
virtual const DWARFSection & getLineSection() const
Definition: DWARFObject.h:44
static bool isSupportedVersion(unsigned version)
Definition: DWARFContext.h:321
virtual const DWARFSection & getRangeDWOSection() const
Definition: DWARFObject.h:65
bool getStringOffsetSectionItem(uint32_t Index, uint64_t &Result) const
Definition: DWARFUnit.cpp:188
dwarf::Tag getTag() const
Definition: DWARFDie.h:72
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
Expected< DWARFAddressRangesVector > findRnglistFromOffset(uint32_t Offset)
Return a vector of address ranges resulting from a (possibly encoded) range list starting at a given ...
Definition: DWARFUnit.cpp:506
#define I(x, y, z)
Definition: MD5.cpp:58
bool is_relative(const Twine &path, Style style=Style::native)
Is path relative?
Definition: Path.cpp:699
uint32_t getOffset() const
Definition: DWARFUnit.h:267
Expected< DWARFAddressRangesVector > getAddressRanges() const
Get the address ranges for this DIE.
Definition: DWARFDie.cpp:394
DWARFDie getPreviousSibling(const DWARFDebugInfoEntry *Die)
Definition: DWARFUnit.cpp:691
uint32_t Size
Definition: Profile.cpp:47
void updateAddressDieMap(DWARFDie Die)
Recursively update address to Die map.
Definition: DWARFUnit.cpp:577
bool isLittleEndian() const
Definition: DWARFContext.h:320
const DWARFObject & getDWARFObj() const
Definition: DWARFContext.h:117
bool isValidOffset(uint32_t offset) const
Test the validity of offset.
const DWARFUnitIndex & getCUIndex()
virtual const DWARFSection & getRangeSection() const
Definition: DWARFObject.h:47
auto upper_bound(R &&Range, ForwardIt I) -> decltype(adl_begin(Range))
Provide wrappers to std::upper_bound which take ranges instead of having to pass begin/end explicitly...
Definition: STLExtras.h:1145
const unsigned Kind
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
DwarfFormat Format
Definition: Dwarf.h:497
Optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition: DWARFDie.cpp:293
std::vector< DWARFAddressRange > DWARFAddressRangesVector
DWARFAddressRangesVector - represents a set of absolute address ranges.
DWARFDebugInfoEntry - A DIE with only the minimum required data.
DWARFDie getFirstChild() const
Get the first child of this DIE object.
Definition: DWARFDie.cpp:566
Lightweight error class with error context and mandatory checking.
Definition: Error.h:158
const Entry * getFromOffset(uint32_t Offset) const
const SectionContribution * getOffset(DWARFSectionKind Sec) const
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
Optional< uint32_t > getRnglistOffset(uint32_t Index)
Return a rangelist&#39;s offset based on an index.
Definition: DWARFUnit.h:399
const uint64_t Version
Definition: InstrProf.h:895
uint8_t getDwarfOffsetByteSize() const
Definition: DWARFUnit.h:274
void setMaxVersionIfGreater(unsigned Version)
Definition: DWARFContext.h:236
Optional< uint64_t > toUnsigned(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an unsigned constant.
Error createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1158
DWARFDie getParent() const
Get the parent of this DIE object.
Definition: DWARFDie.cpp:548
Error extract(const DWARFDataExtractor &data, uint32_t *offset_ptr)
Optional< StrOffsetsContributionDescriptor > determineStringOffsetsTableContributionDWO(DWARFDataExtractor &DA, uint64_t Offset)
Find the unit&#39;s contribution to the string offsets table and determine its length and form...
Definition: DWARFUnit.cpp:820