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