LLVM  7.0.0svn
DWARFContext.cpp
Go to the documentation of this file.
1 //===- DWARFContext.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/STLExtras.h"
12 #include "llvm/ADT/SmallString.h"
13 #include "llvm/ADT/SmallVector.h"
14 #include "llvm/ADT/StringRef.h"
15 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/MC/MCRegisterInfo.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
39 #include "llvm/Support/Casting.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/Format.h"
44 #include "llvm/Support/Path.h"
47 #include <algorithm>
48 #include <cstdint>
49 #include <map>
50 #include <string>
51 #include <utility>
52 #include <vector>
53 
54 using namespace llvm;
55 using namespace dwarf;
56 using namespace object;
57 
58 #define DEBUG_TYPE "dwarf"
59 
63 
64 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
65  std::string DWPName)
66  : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
67 
68 DWARFContext::~DWARFContext() = default;
69 
70 /// Dump the UUID load command.
71 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
72  auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
73  if (!MachO)
74  return;
75  for (auto LC : MachO->load_commands()) {
77  if (LC.C.cmd == MachO::LC_UUID) {
78  if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
79  OS << "error: UUID load command is too short.\n";
80  return;
81  }
82  OS << "UUID: ";
83  memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
84  OS.write_uuid(UUID);
85  Triple T = MachO->getArchTriple();
86  OS << " (" << T.getArchName() << ')';
87  OS << ' ' << MachO->getFileName() << '\n';
88  }
89  }
90 }
91 
93  std::vector<Optional<StrOffsetsContributionDescriptor>>;
94 
95 // Collect all the contributions to the string offsets table from all units,
96 // sort them by their starting offsets and remove duplicates.
100  ContributionCollection Contributions;
101  for (const auto &CU : CUs)
102  Contributions.push_back(CU->getStringOffsetsTableContribution());
103  for (const auto &TUS : TUSs)
104  for (const auto &TU : TUS)
105  Contributions.push_back(TU->getStringOffsetsTableContribution());
106 
107  // Sort the contributions so that any invalid ones are placed at
108  // the start of the contributions vector. This way they are reported
109  // first.
110  std::sort(Contributions.begin(), Contributions.end(),
113  if (L && R) return L->Base < R->Base;
114  return R.hasValue();
115  });
116 
117  // Uniquify contributions, as it is possible that units (specifically
118  // type units in dwo or dwp files) share contributions. We don't want
119  // to report them more than once.
120  Contributions.erase(
121  std::unique(Contributions.begin(), Contributions.end(),
124  if (L && R)
125  return L->Base == R->Base && L->Size == R->Size;
126  return false;
127  }),
128  Contributions.end());
129  return Contributions;
130 }
131 
133  raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
134  const DWARFSection &StringOffsetsSection, StringRef StringSection,
136  DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian) {
137  auto Contributions = collectContributionData(CUs, TUSs);
138  DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
139  DataExtractor StrData(StringSection, LittleEndian, 0);
140  uint64_t SectionSize = StringOffsetsSection.Data.size();
141  uint32_t Offset = 0;
142  for (auto &Contribution : Contributions) {
143  // Report an ill-formed contribution.
144  if (!Contribution) {
145  OS << "error: invalid contribution to string offsets table in section ."
146  << SectionName << ".\n";
147  return;
148  }
149 
150  dwarf::DwarfFormat Format = Contribution->getFormat();
151  uint16_t Version = Contribution->getVersion();
152  uint64_t ContributionHeader = Contribution->Base;
153  // In DWARF v5 there is a contribution header that immediately precedes
154  // the string offsets base (the location we have previously retrieved from
155  // the CU DIE's DW_AT_str_offsets attribute). The header is located either
156  // 8 or 16 bytes before the base, depending on the contribution's format.
157  if (Version >= 5)
158  ContributionHeader -= Format == DWARF32 ? 8 : 16;
159 
160  // Detect overlapping contributions.
161  if (Offset > ContributionHeader) {
162  OS << "error: overlapping contributions to string offsets table in "
163  "section ."
164  << SectionName << ".\n";
165  return;
166  }
167  // Report a gap in the table.
168  if (Offset < ContributionHeader) {
169  OS << format("0x%8.8x: Gap, length = ", Offset);
170  OS << (ContributionHeader - Offset) << "\n";
171  }
172  OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
173  OS << "Contribution size = " << Contribution->Size
174  << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
175  << ", Version = " << Version << "\n";
176 
177  Offset = Contribution->Base;
178  unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
179  while (Offset - Contribution->Base < Contribution->Size) {
180  OS << format("0x%8.8x: ", Offset);
181  // FIXME: We can only extract strings if the offset fits in 32 bits.
182  uint64_t StringOffset =
183  StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
184  // Extract the string if we can and display it. Otherwise just report
185  // the offset.
186  if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
187  uint32_t StringOffset32 = (uint32_t)StringOffset;
188  OS << format("%8.8x ", StringOffset32);
189  const char *S = StrData.getCStr(&StringOffset32);
190  if (S)
191  OS << format("\"%s\"", S);
192  } else
193  OS << format("%16.16" PRIx64 " ", StringOffset);
194  OS << "\n";
195  }
196  }
197  // Report a gap at the end of the table.
198  if (Offset < SectionSize) {
199  OS << format("0x%8.8x: Gap, length = ", Offset);
200  OS << (SectionSize - Offset) << "\n";
201  }
202 }
203 
204 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
205 // string offsets section, where each compile or type unit contributes a
206 // number of entries (string offsets), with each contribution preceded by
207 // a header containing size and version number. Alternatively, it may be a
208 // monolithic series of string offsets, as generated by the pre-DWARF v5
209 // implementation of split DWARF.
211  raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
212  const DWARFSection &StringOffsetsSection, StringRef StringSection,
214  DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian,
215  unsigned MaxVersion) {
216  // If we have at least one (compile or type) unit with DWARF v5 or greater,
217  // we assume that the section is formatted like a DWARF v5 string offsets
218  // section.
219  if (MaxVersion >= 5)
220  dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
221  StringSection, CUs, TUSs, LittleEndian);
222  else {
223  DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
224  uint32_t offset = 0;
225  uint64_t size = StringOffsetsSection.Data.size();
226  // Ensure that size is a multiple of the size of an entry.
227  if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
228  OS << "error: size of ." << SectionName << " is not a multiple of "
229  << sizeof(uint32_t) << ".\n";
230  size &= -(uint64_t)sizeof(uint32_t);
231  }
232  DataExtractor StrData(StringSection, LittleEndian, 0);
233  while (offset < size) {
234  OS << format("0x%8.8x: ", offset);
235  uint32_t StringOffset = strOffsetExt.getU32(&offset);
236  OS << format("%8.8x ", StringOffset);
237  const char *S = StrData.getCStr(&StringOffset);
238  if (S)
239  OS << format("\"%s\"", S);
240  OS << "\n";
241  }
242  }
243 }
244 
245 // We want to supply the Unit associated with a .debug_line[.dwo] table when
246 // we dump it, if possible, but still dump the table even if there isn't a Unit.
247 // Therefore, collect up handles on all the Units that point into the
248 // line-table section.
249 typedef std::map<uint64_t, DWARFUnit *> LineToUnitMap;
250 
251 static LineToUnitMap
254  LineToUnitMap LineToUnit;
255  for (const auto &CU : CUs)
256  if (auto CUDIE = CU->getUnitDIE())
257  if (auto StmtOffset = toSectionOffset(CUDIE.find(DW_AT_stmt_list)))
258  LineToUnit.insert(std::make_pair(*StmtOffset, &*CU));
259  for (const auto &TUS : TUSections)
260  for (const auto &TU : TUS)
261  if (auto TUDIE = TU->getUnitDIE())
262  if (auto StmtOffset = toSectionOffset(TUDIE.find(DW_AT_stmt_list)))
263  LineToUnit.insert(std::make_pair(*StmtOffset, &*TU));
264  return LineToUnit;
265 }
266 
268  raw_ostream &OS, DIDumpOptions DumpOpts,
269  std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
270 
271  Optional<uint64_t> DumpOffset;
272  uint64_t DumpType = DumpOpts.DumpType;
273 
274  StringRef Extension = sys::path::extension(DObj->getFileName());
275  bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
276 
277  // Print UUID header.
278  const auto *ObjFile = DObj->getFile();
279  if (DumpType & DIDT_UUID)
280  dumpUUID(OS, *ObjFile);
281 
282  // Print a header for each explicitly-requested section.
283  // Otherwise just print one for non-empty sections.
284  // Only print empty .dwo section headers when dumping a .dwo file.
285  bool Explicit = DumpType != DIDT_All && !IsDWO;
286  bool ExplicitDWO = Explicit && IsDWO;
287  auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
288  StringRef Section) {
289  DumpOffset = DumpOffsets[ID];
290  unsigned Mask = 1U << ID;
291  bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
292  if (Should)
293  OS << "\n" << Name << " contents:\n";
294  return Should;
295  };
296 
297  // Dump individual sections.
298  if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
299  DObj->getAbbrevSection()))
300  getDebugAbbrev()->dump(OS);
301  if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
302  DObj->getAbbrevDWOSection()))
303  getDebugAbbrevDWO()->dump(OS);
304 
305  auto dumpDebugInfo = [&](bool IsExplicit, const char *Name,
307  if (shouldDump(IsExplicit, Name, DIDT_ID_DebugInfo, Section.Data)) {
308  if (DumpOffset)
309  getDIEForOffset(DumpOffset.getValue())
310  .dump(OS, 0, DumpOpts.noImplicitRecursion());
311  else
312  for (const auto &CU : CUs)
313  CU->dump(OS, DumpOpts);
314  }
315  };
316  dumpDebugInfo(Explicit, ".debug_info", DObj->getInfoSection(),
317  compile_units());
318  dumpDebugInfo(ExplicitDWO, ".debug_info.dwo", DObj->getInfoDWOSection(),
320 
321  auto dumpDebugType = [&](const char *Name,
322  tu_section_iterator_range TUSections) {
323  OS << '\n' << Name << " contents:\n";
324  DumpOffset = DumpOffsets[DIDT_ID_DebugTypes];
325  for (const auto &TUS : TUSections)
326  for (const auto &TU : TUS)
327  if (DumpOffset)
328  TU->getDIEForOffset(*DumpOffset)
329  .dump(OS, 0, DumpOpts.noImplicitRecursion());
330  else
331  TU->dump(OS, DumpOpts);
332  };
333  if ((DumpType & DIDT_DebugTypes)) {
334  if (Explicit || getNumTypeUnits())
335  dumpDebugType(".debug_types", type_unit_sections());
336  if (ExplicitDWO || getNumDWOTypeUnits())
337  dumpDebugType(".debug_types.dwo", dwo_type_unit_sections());
338  }
339 
340  if (shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
341  DObj->getLocSection().Data)) {
342  getDebugLoc()->dump(OS, getRegisterInfo(), DumpOffset);
343  }
344  if (shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
345  DObj->getLocDWOSection().Data)) {
346  getDebugLocDWO()->dump(OS, getRegisterInfo(), DumpOffset);
347  }
348 
349  if (shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
350  DObj->getDebugFrameSection()))
351  getDebugFrame()->dump(OS, DumpOffset);
352 
353  if (shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
354  DObj->getEHFrameSection()))
355  getEHFrame()->dump(OS, DumpOffset);
356 
357  if (DumpType & DIDT_DebugMacro) {
358  if (Explicit || !getDebugMacro()->empty()) {
359  OS << "\n.debug_macinfo contents:\n";
360  getDebugMacro()->dump(OS);
361  }
362  }
363 
364  if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
365  DObj->getARangeSection())) {
366  uint32_t offset = 0;
367  DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
369  while (set.extract(arangesData, &offset))
370  set.dump(OS);
371  }
372 
373  if (shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
374  DObj->getLineSection().Data)) {
375  LineToUnitMap LineToUnit =
377  unsigned Offset = 0;
378  DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
379  0);
380  while (Offset < LineData.getData().size()) {
381  DWARFUnit *U = nullptr;
382  auto It = LineToUnit.find(Offset);
383  if (It != LineToUnit.end())
384  U = It->second;
385  LineData.setAddressSize(U ? U->getAddressByteSize() : 0);
386  DWARFDebugLine::LineTable LineTable;
387  if (DumpOffset && Offset != *DumpOffset) {
388  // Find the size of this part of the line table section and skip it.
389  unsigned OldOffset = Offset;
390  LineTable.Prologue.parse(LineData, &Offset, U);
391  Offset = OldOffset + LineTable.Prologue.TotalLength +
392  LineTable.Prologue.sizeofTotalLength();
393  continue;
394  }
395  // Verbose dumping is done during parsing and not on the intermediate
396  // representation.
397  OS << "debug_line[" << format("0x%8.8x", Offset) << "]\n";
398  unsigned OldOffset = Offset;
399  if (DumpOpts.Verbose) {
400  LineTable.parse(LineData, &Offset, U, &OS);
401  } else {
402  LineTable.parse(LineData, &Offset, U);
403  LineTable.dump(OS);
404  }
405  // Check for unparseable prologue, to avoid infinite loops.
406  if (OldOffset == Offset)
407  break;
408  }
409  }
410 
411  if (shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
412  DObj->getLineDWOSection().Data)) {
413  LineToUnitMap LineToUnit =
415  unsigned Offset = 0;
416  DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
417  isLittleEndian(), 0);
418  while (Offset < LineData.getData().size()) {
419  DWARFUnit *U = nullptr;
420  auto It = LineToUnit.find(Offset);
421  if (It != LineToUnit.end())
422  U = It->second;
423  DWARFDebugLine::LineTable LineTable;
424  unsigned OldOffset = Offset;
425  if (!LineTable.Prologue.parse(LineData, &Offset, U))
426  break;
427  if (!DumpOffset || OldOffset == *DumpOffset)
428  LineTable.dump(OS);
429  }
430  }
431 
432  if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
433  DObj->getCUIndexSection())) {
434  getCUIndex().dump(OS);
435  }
436 
437  if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
438  DObj->getTUIndexSection())) {
439  getTUIndex().dump(OS);
440  }
441 
442  if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
443  DObj->getStringSection())) {
444  DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
445  uint32_t offset = 0;
446  uint32_t strOffset = 0;
447  while (const char *s = strData.getCStr(&offset)) {
448  OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
449  strOffset = offset;
450  }
451  }
452  if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
453  DObj->getStringDWOSection())) {
454  DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
455  uint32_t offset = 0;
456  uint32_t strDWOOffset = 0;
457  while (const char *s = strDWOData.getCStr(&offset)) {
458  OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
459  strDWOOffset = offset;
460  }
461  }
462 
463  if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
464  DObj->getRangeSection().Data)) {
465  // In fact, different compile units may have different address byte
466  // sizes, but for simplicity we just use the address byte size of the
467  // last compile unit (there is no easy and fast way to associate address
468  // range list and the compile unit it describes).
469  // FIXME: savedAddressByteSize seems sketchy.
470  uint8_t savedAddressByteSize = 0;
471  for (const auto &CU : compile_units()) {
472  savedAddressByteSize = CU->getAddressByteSize();
473  break;
474  }
475  DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
476  isLittleEndian(), savedAddressByteSize);
477  uint32_t offset = 0;
478  DWARFDebugRangeList rangeList;
479  while (rangeList.extract(rangesData, &offset))
480  rangeList.dump(OS);
481  }
482 
483  if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
484  DObj->getPubNamesSection()))
485  DWARFDebugPubTable(DObj->getPubNamesSection(), isLittleEndian(), false)
486  .dump(OS);
487 
488  if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
489  DObj->getPubTypesSection()))
490  DWARFDebugPubTable(DObj->getPubTypesSection(), isLittleEndian(), false)
491  .dump(OS);
492 
493  if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
494  DObj->getGnuPubNamesSection()))
495  DWARFDebugPubTable(DObj->getGnuPubNamesSection(), isLittleEndian(),
496  true /* GnuStyle */)
497  .dump(OS);
498 
499  if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
500  DObj->getGnuPubTypesSection()))
501  DWARFDebugPubTable(DObj->getGnuPubTypesSection(), isLittleEndian(),
502  true /* GnuStyle */)
503  .dump(OS);
504 
505  if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
506  DObj->getStringOffsetSection().Data))
508  OS, "debug_str_offsets", *DObj, DObj->getStringOffsetSection(),
509  DObj->getStringSection(), compile_units(), type_unit_sections(),
511  if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
512  DObj->getStringOffsetDWOSection().Data))
514  OS, "debug_str_offsets.dwo", *DObj, DObj->getStringOffsetDWOSection(),
515  DObj->getStringDWOSection(), dwo_compile_units(),
517 
518  if (shouldDump(Explicit, ".gnu_index", DIDT_ID_GdbIndex,
519  DObj->getGdbIndexSection())) {
520  getGdbIndex().dump(OS);
521  }
522 
523  if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
524  DObj->getAppleNamesSection().Data))
525  getAppleNames().dump(OS);
526 
527  if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
528  DObj->getAppleTypesSection().Data))
529  getAppleTypes().dump(OS);
530 
531  if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
532  DObj->getAppleNamespacesSection().Data))
533  getAppleNamespaces().dump(OS);
534 
535  if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
536  DObj->getAppleObjCSection().Data))
537  getAppleObjC().dump(OS);
538 }
539 
541  DWOCUs.parseDWO(*this, DObj->getInfoDWOSection(), true);
542 
543  if (const auto &CUI = getCUIndex()) {
544  if (const auto *R = CUI.getFromHash(Hash))
545  return DWOCUs.getUnitForIndexEntry(*R);
546  return nullptr;
547  }
548 
549  // If there's no index, just search through the CUs in the DWO - there's
550  // probably only one unless this is something like LTO - though an in-process
551  // built/cached lookup table could be used in that case to improve repeated
552  // lookups of different CUs in the DWO.
553  for (const auto &DWOCU : dwo_compile_units())
554  if (DWOCU->getDWOId() == Hash)
555  return DWOCU.get();
556  return nullptr;
557 }
558 
560  parseCompileUnits();
561  if (auto *CU = CUs.getUnitForOffset(Offset))
562  return CU->getDIEForOffset(Offset);
563  return DWARFDie();
564 }
565 
567  bool Success = true;
568  DWARFVerifier verifier(OS, *this, DumpOpts);
569 
570  Success &= verifier.handleDebugAbbrev();
571  if (DumpOpts.DumpType & DIDT_DebugInfo)
572  Success &= verifier.handleDebugInfo();
573  if (DumpOpts.DumpType & DIDT_DebugLine)
574  Success &= verifier.handleDebugLine();
575  Success &= verifier.handleAccelTables();
576  return Success;
577 }
578 
580  if (CUIndex)
581  return *CUIndex;
582 
583  DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
584 
585  CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
586  CUIndex->parse(CUIndexData);
587  return *CUIndex;
588 }
589 
591  if (TUIndex)
592  return *TUIndex;
593 
594  DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
595 
596  TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
597  TUIndex->parse(TUIndexData);
598  return *TUIndex;
599 }
600 
602  if (GdbIndex)
603  return *GdbIndex;
604 
605  DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
606  GdbIndex = llvm::make_unique<DWARFGdbIndex>();
607  GdbIndex->parse(GdbIndexData);
608  return *GdbIndex;
609 }
610 
612  if (Abbrev)
613  return Abbrev.get();
614 
615  DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
616 
617  Abbrev.reset(new DWARFDebugAbbrev());
618  Abbrev->extract(abbrData);
619  return Abbrev.get();
620 }
621 
623  if (AbbrevDWO)
624  return AbbrevDWO.get();
625 
626  DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
627  AbbrevDWO.reset(new DWARFDebugAbbrev());
628  AbbrevDWO->extract(abbrData);
629  return AbbrevDWO.get();
630 }
631 
633  if (Loc)
634  return Loc.get();
635 
636  Loc.reset(new DWARFDebugLoc);
637  // assume all compile units have the same address byte size
638  if (getNumCompileUnits()) {
639  DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
641  Loc->parse(LocData);
642  }
643  return Loc.get();
644 }
645 
647  if (LocDWO)
648  return LocDWO.get();
649 
650  DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 0);
651  LocDWO.reset(new DWARFDebugLocDWO());
652  LocDWO->parse(LocData);
653  return LocDWO.get();
654 }
655 
657  if (Aranges)
658  return Aranges.get();
659 
660  Aranges.reset(new DWARFDebugAranges());
661  Aranges->generate(this);
662  return Aranges.get();
663 }
664 
666  if (DebugFrame)
667  return DebugFrame.get();
668 
669  // There's a "bug" in the DWARFv3 standard with respect to the target address
670  // size within debug frame sections. While DWARF is supposed to be independent
671  // of its container, FDEs have fields with size being "target address size",
672  // which isn't specified in DWARF in general. It's only specified for CUs, but
673  // .eh_frame can appear without a .debug_info section. Follow the example of
674  // other tools (libdwarf) and extract this from the container (ObjectFile
675  // provides this information). This problem is fixed in DWARFv4
676  // See this dwarf-discuss discussion for more details:
677  // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
678  DataExtractor debugFrameData(DObj->getDebugFrameSection(), isLittleEndian(),
679  DObj->getAddressSize());
680  DebugFrame.reset(new DWARFDebugFrame(false /* IsEH */));
681  DebugFrame->parse(debugFrameData);
682  return DebugFrame.get();
683 }
684 
686  if (EHFrame)
687  return EHFrame.get();
688 
689  DataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
690  DObj->getAddressSize());
691  DebugFrame.reset(new DWARFDebugFrame(true /* IsEH */));
692  DebugFrame->parse(debugFrameData);
693  return DebugFrame.get();
694 }
695 
697  if (Macro)
698  return Macro.get();
699 
700  DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
701  Macro.reset(new DWARFDebugMacro());
702  Macro->parse(MacinfoData);
703  return Macro.get();
704 }
705 
706 static DWARFAcceleratorTable &
707 getAccelTable(std::unique_ptr<DWARFAcceleratorTable> &Cache,
708  const DWARFObject &Obj, const DWARFSection &Section,
709  StringRef StringSection, bool IsLittleEndian) {
710  if (Cache)
711  return *Cache;
712  DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
713  DataExtractor StrData(StringSection, IsLittleEndian, 0);
714  Cache.reset(new DWARFAcceleratorTable(AccelSection, StrData));
715  if (Error E = Cache->extract())
716  llvm::consumeError(std::move(E));
717  return *Cache;
718 }
719 
721  return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
722  DObj->getStringSection(), isLittleEndian());
723 }
724 
726  return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
727  DObj->getStringSection(), isLittleEndian());
728 }
729 
731  return getAccelTable(AppleNamespaces, *DObj,
732  DObj->getAppleNamespacesSection(),
733  DObj->getStringSection(), isLittleEndian());
734 }
735 
737  return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
738  DObj->getStringSection(), isLittleEndian());
739 }
740 
741 const DWARFLineTable *
743  if (!Line)
744  Line.reset(new DWARFDebugLine);
745 
746  auto UnitDIE = U->getUnitDIE();
747  if (!UnitDIE)
748  return nullptr;
749 
750  auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
751  if (!Offset)
752  return nullptr; // No line table for this compile unit.
753 
754  uint32_t stmtOffset = *Offset + U->getLineTableOffset();
755  // See if the line table is cached.
756  if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
757  return lt;
758 
759  // Make sure the offset is good before we try to parse.
760  if (stmtOffset >= U->getLineSection().Data.size())
761  return nullptr;
762 
763  // We have to parse it first.
765  U->getAddressByteSize());
766  return Line->getOrParseLineTable(lineData, stmtOffset, U);
767 }
768 
769 void DWARFContext::parseCompileUnits() {
770  CUs.parse(*this, DObj->getInfoSection());
771 }
772 
773 void DWARFContext::parseTypeUnits() {
774  if (!TUs.empty())
775  return;
776  DObj->forEachTypesSections([&](const DWARFSection &S) {
777  TUs.emplace_back();
778  TUs.back().parse(*this, S);
779  });
780 }
781 
782 void DWARFContext::parseDWOCompileUnits() {
783  DWOCUs.parseDWO(*this, DObj->getInfoDWOSection());
784 }
785 
786 void DWARFContext::parseDWOTypeUnits() {
787  if (!DWOTUs.empty())
788  return;
789  DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
790  DWOTUs.emplace_back();
791  DWOTUs.back().parseDWO(*this, S);
792  });
793 }
794 
795 DWARFCompileUnit *DWARFContext::getCompileUnitForOffset(uint32_t Offset) {
796  parseCompileUnits();
797  return CUs.getUnitForOffset(Offset);
798 }
799 
800 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
801  // First, get the offset of the compile unit.
802  uint32_t CUOffset = getDebugAranges()->findAddress(Address);
803  // Retrieve the compile unit.
804  return getCompileUnitForOffset(CUOffset);
805 }
806 
808  DIEsForAddress Result;
809 
810  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
811  if (!CU)
812  return Result;
813 
814  Result.CompileUnit = CU;
815  Result.FunctionDIE = CU->getSubroutineForAddress(Address);
816 
817  std::vector<DWARFDie> Worklist;
818  Worklist.push_back(Result.FunctionDIE);
819  while (!Worklist.empty()) {
820  DWARFDie DIE = Worklist.back();
821  Worklist.pop_back();
822 
823  if (DIE.getTag() == DW_TAG_lexical_block &&
824  DIE.addressRangeContainsAddress(Address)) {
825  Result.BlockDIE = DIE;
826  break;
827  }
828 
829  for (auto Child : DIE)
830  Worklist.push_back(Child);
831  }
832 
833  return Result;
834 }
835 
837  uint64_t Address,
838  FunctionNameKind Kind,
839  std::string &FunctionName,
840  uint32_t &StartLine) {
841  // The address may correspond to instruction in some inlined function,
842  // so we have to build the chain of inlined functions and take the
843  // name of the topmost function in it.
844  SmallVector<DWARFDie, 4> InlinedChain;
845  CU->getInlinedChainForAddress(Address, InlinedChain);
846  if (InlinedChain.empty())
847  return false;
848 
849  const DWARFDie &DIE = InlinedChain[0];
850  bool FoundResult = false;
851  const char *Name = nullptr;
852  if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
853  FunctionName = Name;
854  FoundResult = true;
855  }
856  if (auto DeclLineResult = DIE.getDeclLine()) {
857  StartLine = DeclLineResult;
858  FoundResult = true;
859  }
860 
861  return FoundResult;
862 }
863 
865  DILineInfoSpecifier Spec) {
866  DILineInfo Result;
867 
868  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
869  if (!CU)
870  return Result;
872  Result.FunctionName,
873  Result.StartLine);
874  if (Spec.FLIKind != FileLineInfoKind::None) {
875  if (const DWARFLineTable *LineTable = getLineTableForUnit(CU))
876  LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
877  Spec.FLIKind, Result);
878  }
879  return Result;
880 }
881 
884  DILineInfoSpecifier Spec) {
885  DILineInfoTable Lines;
886  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
887  if (!CU)
888  return Lines;
889 
890  std::string FunctionName = "<invalid>";
891  uint32_t StartLine = 0;
892  getFunctionNameAndStartLineForAddress(CU, Address, Spec.FNKind, FunctionName,
893  StartLine);
894 
895  // If the Specifier says we don't need FileLineInfo, just
896  // return the top-most function at the starting address.
897  if (Spec.FLIKind == FileLineInfoKind::None) {
898  DILineInfo Result;
899  Result.FunctionName = FunctionName;
900  Result.StartLine = StartLine;
901  Lines.push_back(std::make_pair(Address, Result));
902  return Lines;
903  }
904 
905  const DWARFLineTable *LineTable = getLineTableForUnit(CU);
906 
907  // Get the index of row we're looking for in the line table.
908  std::vector<uint32_t> RowVector;
909  if (!LineTable->lookupAddressRange(Address, Size, RowVector))
910  return Lines;
911 
912  for (uint32_t RowIndex : RowVector) {
913  // Take file number and line/column from the row.
914  const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
915  DILineInfo Result;
916  LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
917  Spec.FLIKind, Result.FileName);
918  Result.FunctionName = FunctionName;
919  Result.Line = Row.Line;
920  Result.Column = Row.Column;
921  Result.StartLine = StartLine;
922  Lines.push_back(std::make_pair(Row.Address, Result));
923  }
924 
925  return Lines;
926 }
927 
930  DILineInfoSpecifier Spec) {
931  DIInliningInfo InliningInfo;
932 
933  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
934  if (!CU)
935  return InliningInfo;
936 
937  const DWARFLineTable *LineTable = nullptr;
938  SmallVector<DWARFDie, 4> InlinedChain;
939  CU->getInlinedChainForAddress(Address, InlinedChain);
940  if (InlinedChain.size() == 0) {
941  // If there is no DIE for address (e.g. it is in unavailable .dwo file),
942  // try to at least get file/line info from symbol table.
943  if (Spec.FLIKind != FileLineInfoKind::None) {
944  DILineInfo Frame;
945  LineTable = getLineTableForUnit(CU);
946  if (LineTable &&
947  LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
948  Spec.FLIKind, Frame))
949  InliningInfo.addFrame(Frame);
950  }
951  return InliningInfo;
952  }
953 
954  uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
955  for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
956  DWARFDie &FunctionDIE = InlinedChain[i];
957  DILineInfo Frame;
958  // Get function name if necessary.
959  if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
960  Frame.FunctionName = Name;
961  if (auto DeclLineResult = FunctionDIE.getDeclLine())
962  Frame.StartLine = DeclLineResult;
963  if (Spec.FLIKind != FileLineInfoKind::None) {
964  if (i == 0) {
965  // For the topmost frame, initialize the line table of this
966  // compile unit and fetch file/line info from it.
967  LineTable = getLineTableForUnit(CU);
968  // For the topmost routine, get file/line info from line table.
969  if (LineTable)
970  LineTable->getFileLineInfoForAddress(Address, CU->getCompilationDir(),
971  Spec.FLIKind, Frame);
972  } else {
973  // Otherwise, use call file, call line and call column from
974  // previous DIE in inlined chain.
975  if (LineTable)
976  LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
977  Spec.FLIKind, Frame.FileName);
978  Frame.Line = CallLine;
979  Frame.Column = CallColumn;
980  Frame.Discriminator = CallDiscriminator;
981  }
982  // Get call file/line/column of a current DIE.
983  if (i + 1 < n) {
984  FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
985  CallDiscriminator);
986  }
987  }
988  InliningInfo.addFrame(Frame);
989  }
990  return InliningInfo;
991 }
992 
993 std::shared_ptr<DWARFContext>
995  if (auto S = DWP.lock()) {
996  DWARFContext *Ctxt = S->Context.get();
997  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
998  }
999 
1000  std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1001 
1002  if (auto S = Entry->lock()) {
1003  DWARFContext *Ctxt = S->Context.get();
1004  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1005  }
1006 
1008  if (!CheckedForDWP) {
1009  SmallString<128> DWPName;
1011  this->DWPName.empty()
1012  ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1013  : StringRef(this->DWPName));
1014  if (Obj) {
1015  Entry = &DWP;
1016  return Obj;
1017  } else {
1018  CheckedForDWP = true;
1019  // TODO: Should this error be handled (maybe in a high verbosity mode)
1020  // before falling back to .dwo files?
1021  consumeError(Obj.takeError());
1022  }
1023  }
1024 
1025  return object::ObjectFile::createObjectFile(AbsolutePath);
1026  }();
1027 
1028  if (!Obj) {
1029  // TODO: Actually report errors helpfully.
1030  consumeError(Obj.takeError());
1031  return nullptr;
1032  }
1033 
1034  auto S = std::make_shared<DWOFile>();
1035  S->File = std::move(Obj.get());
1036  S->Context = DWARFContext::create(*S->File.getBinary());
1037  *Entry = S;
1038  auto *Ctxt = S->Context.get();
1039  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1040 }
1041 
1042 static Error createError(const Twine &Reason, llvm::Error E) {
1043  return make_error<StringError>(Reason + toString(std::move(E)),
1045 }
1046 
1047 /// SymInfo contains information about symbol: it's address
1048 /// and section index which is -1LL for absolute symbols.
1049 struct SymInfo {
1050  uint64_t Address;
1051  uint64_t SectionIndex;
1052 };
1053 
1054 /// Returns the address of symbol relocation used against and a section index.
1055 /// Used for futher relocations computation. Symbol's section load address is
1057  const RelocationRef &Reloc,
1058  const LoadedObjectInfo *L,
1059  std::map<SymbolRef, SymInfo> &Cache) {
1060  SymInfo Ret = {0, (uint64_t)-1LL};
1062  object::symbol_iterator Sym = Reloc.getSymbol();
1063 
1064  std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1065  // First calculate the address of the symbol or section as it appears
1066  // in the object file
1067  if (Sym != Obj.symbol_end()) {
1068  bool New;
1069  std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1070  if (!New)
1071  return CacheIt->second;
1072 
1073  Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1074  if (!SymAddrOrErr)
1075  return createError("failed to compute symbol address: ",
1076  SymAddrOrErr.takeError());
1077 
1078  // Also remember what section this symbol is in for later
1079  auto SectOrErr = Sym->getSection();
1080  if (!SectOrErr)
1081  return createError("failed to get symbol section: ",
1082  SectOrErr.takeError());
1083 
1084  RSec = *SectOrErr;
1085  Ret.Address = *SymAddrOrErr;
1086  } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1087  RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1088  Ret.Address = RSec->getAddress();
1089  }
1090 
1091  if (RSec != Obj.section_end())
1092  Ret.SectionIndex = RSec->getIndex();
1093 
1094  // If we are given load addresses for the sections, we need to adjust:
1095  // SymAddr = (Address of Symbol Or Section in File) -
1096  // (Address of Section in File) +
1097  // (Load Address of Section)
1098  // RSec is now either the section being targeted or the section
1099  // containing the symbol being targeted. In either case,
1100  // we need to perform the same computation.
1101  if (L && RSec != Obj.section_end())
1102  if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1103  Ret.Address += SectionLoadAddress - RSec->getAddress();
1104 
1105  if (CacheIt != Cache.end())
1106  CacheIt->second = Ret;
1107 
1108  return Ret;
1109 }
1110 
1111 static bool isRelocScattered(const object::ObjectFile &Obj,
1112  const RelocationRef &Reloc) {
1113  const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1114  if (!MachObj)
1115  return false;
1116  // MachO also has relocations that point to sections and
1117  // scattered relocations.
1118  auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1119  return MachObj->isRelocationScattered(RelocInfo);
1120 }
1121 
1123  errs() << "error: " + toString(std::move(E)) << '\n';
1124  return ErrorPolicy::Continue;
1125 }
1126 
1127 namespace {
1128 struct DWARFSectionMap final : public DWARFSection {
1129  RelocAddrMap Relocs;
1130 };
1131 
1132 class DWARFObjInMemory final : public DWARFObject {
1133  bool IsLittleEndian;
1134  uint8_t AddressSize;
1135  StringRef FileName;
1136  const object::ObjectFile *Obj = nullptr;
1137  std::vector<SectionName> SectionNames;
1138 
1139  using TypeSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1140  std::map<object::SectionRef, unsigned>>;
1141 
1142  TypeSectionMap TypesSections;
1143  TypeSectionMap TypesDWOSections;
1144 
1145  DWARFSectionMap InfoSection;
1146  DWARFSectionMap LocSection;
1147  DWARFSectionMap LineSection;
1148  DWARFSectionMap RangeSection;
1149  DWARFSectionMap StringOffsetSection;
1150  DWARFSectionMap InfoDWOSection;
1151  DWARFSectionMap LineDWOSection;
1152  DWARFSectionMap LocDWOSection;
1153  DWARFSectionMap StringOffsetDWOSection;
1154  DWARFSectionMap RangeDWOSection;
1155  DWARFSectionMap AddrSection;
1156  DWARFSectionMap AppleNamesSection;
1157  DWARFSectionMap AppleTypesSection;
1158  DWARFSectionMap AppleNamespacesSection;
1159  DWARFSectionMap AppleObjCSection;
1160 
1161  DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1163  .Case("debug_info", &InfoSection)
1164  .Case("debug_loc", &LocSection)
1165  .Case("debug_line", &LineSection)
1166  .Case("debug_str_offsets", &StringOffsetSection)
1167  .Case("debug_ranges", &RangeSection)
1168  .Case("debug_info.dwo", &InfoDWOSection)
1169  .Case("debug_loc.dwo", &LocDWOSection)
1170  .Case("debug_line.dwo", &LineDWOSection)
1171  .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1172  .Case("debug_addr", &AddrSection)
1173  .Case("apple_names", &AppleNamesSection)
1174  .Case("apple_types", &AppleTypesSection)
1175  .Case("apple_namespaces", &AppleNamespacesSection)
1176  .Case("apple_namespac", &AppleNamespacesSection)
1177  .Case("apple_objc", &AppleObjCSection)
1178  .Default(nullptr);
1179  }
1180 
1181  StringRef AbbrevSection;
1182  StringRef ARangeSection;
1183  StringRef DebugFrameSection;
1184  StringRef EHFrameSection;
1185  StringRef StringSection;
1186  StringRef MacinfoSection;
1187  StringRef PubNamesSection;
1188  StringRef PubTypesSection;
1189  StringRef GnuPubNamesSection;
1190  StringRef AbbrevDWOSection;
1191  StringRef StringDWOSection;
1192  StringRef GnuPubTypesSection;
1193  StringRef CUIndexSection;
1194  StringRef GdbIndexSection;
1195  StringRef TUIndexSection;
1196 
1197  SmallVector<SmallString<32>, 4> UncompressedSections;
1198 
1199  StringRef *mapSectionToMember(StringRef Name) {
1200  if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1201  return &Sec->Data;
1203  .Case("debug_abbrev", &AbbrevSection)
1204  .Case("debug_aranges", &ARangeSection)
1205  .Case("debug_frame", &DebugFrameSection)
1206  .Case("eh_frame", &EHFrameSection)
1207  .Case("debug_str", &StringSection)
1208  .Case("debug_macinfo", &MacinfoSection)
1209  .Case("debug_pubnames", &PubNamesSection)
1210  .Case("debug_pubtypes", &PubTypesSection)
1211  .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1212  .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1213  .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1214  .Case("debug_str.dwo", &StringDWOSection)
1215  .Case("debug_cu_index", &CUIndexSection)
1216  .Case("debug_tu_index", &TUIndexSection)
1217  .Case("gdb_index", &GdbIndexSection)
1218  // Any more debug info sections go here.
1219  .Default(nullptr);
1220  }
1221 
1222  /// If Sec is compressed section, decompresses and updates its contents
1223  /// provided by Data. Otherwise leaves it unchanged.
1224  Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1225  StringRef &Data) {
1226  if (!Decompressor::isCompressed(Sec))
1227  return Error::success();
1228 
1229  Expected<Decompressor> Decompressor =
1230  Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1231  if (!Decompressor)
1232  return Decompressor.takeError();
1233 
1234  SmallString<32> Out;
1235  if (auto Err = Decompressor->resizeAndDecompress(Out))
1236  return Err;
1237 
1238  UncompressedSections.emplace_back(std::move(Out));
1239  Data = UncompressedSections.back();
1240 
1241  return Error::success();
1242  }
1243 
1244 public:
1245  DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1246  uint8_t AddrSize, bool IsLittleEndian)
1247  : IsLittleEndian(IsLittleEndian) {
1248  for (const auto &SecIt : Sections) {
1249  if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1250  *SectionData = SecIt.second->getBuffer();
1251  }
1252  }
1253  DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1254  function_ref<ErrorPolicy(Error)> HandleError)
1255  : IsLittleEndian(Obj.isLittleEndian()),
1256  AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1257  Obj(&Obj) {
1258 
1259  StringMap<unsigned> SectionAmountMap;
1260  for (const SectionRef &Section : Obj.sections()) {
1261  StringRef Name;
1262  Section.getName(Name);
1263  ++SectionAmountMap[Name];
1264  SectionNames.push_back({ Name, true });
1265 
1266  // Skip BSS and Virtual sections, they aren't interesting.
1267  if (Section.isBSS() || Section.isVirtual())
1268  continue;
1269 
1270  // Skip sections stripped by dsymutil.
1271  if (Section.isStripped())
1272  continue;
1273 
1274  StringRef Data;
1275  section_iterator RelocatedSection = Section.getRelocatedSection();
1276  // Try to obtain an already relocated version of this section.
1277  // Else use the unrelocated section from the object file. We'll have to
1278  // apply relocations ourselves later.
1279  if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data))
1280  Section.getContents(Data);
1281 
1282  if (auto Err = maybeDecompress(Section, Name, Data)) {
1283  ErrorPolicy EP = HandleError(createError(
1284  "failed to decompress '" + Name + "', ", std::move(Err)));
1285  if (EP == ErrorPolicy::Halt)
1286  return;
1287  continue;
1288  }
1289 
1290  // Compressed sections names in GNU style starts from ".z",
1291  // at this point section is decompressed and we drop compression prefix.
1292  Name = Name.substr(
1293  Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1294 
1295  // Map platform specific debug section names to DWARF standard section
1296  // names.
1297  Name = Obj.mapDebugSectionName(Name);
1298 
1299  if (StringRef *SectionData = mapSectionToMember(Name)) {
1300  *SectionData = Data;
1301  if (Name == "debug_ranges") {
1302  // FIXME: Use the other dwo range section when we emit it.
1303  RangeDWOSection.Data = Data;
1304  }
1305  } else if (Name == "debug_types") {
1306  // Find debug_types data by section rather than name as there are
1307  // multiple, comdat grouped, debug_types sections.
1308  TypesSections[Section].Data = Data;
1309  } else if (Name == "debug_types.dwo") {
1310  TypesDWOSections[Section].Data = Data;
1311  }
1312 
1313  if (RelocatedSection == Obj.section_end())
1314  continue;
1315 
1316  StringRef RelSecName;
1317  StringRef RelSecData;
1318  RelocatedSection->getName(RelSecName);
1319 
1320  // If the section we're relocating was relocated already by the JIT,
1321  // then we used the relocated version above, so we do not need to process
1322  // relocations for it now.
1323  if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1324  continue;
1325 
1326  // In Mach-o files, the relocations do not need to be applied if
1327  // there is no load offset to apply. The value read at the
1328  // relocation point already factors in the section address
1329  // (actually applying the relocations will produce wrong results
1330  // as the section address will be added twice).
1331  if (!L && isa<MachOObjectFile>(&Obj))
1332  continue;
1333 
1334  RelSecName = RelSecName.substr(
1335  RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1336 
1337  // TODO: Add support for relocations in other sections as needed.
1338  // Record relocations for the debug_info and debug_line sections.
1339  DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1340  RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1341  if (!Map) {
1342  // Find debug_types relocs by section rather than name as there are
1343  // multiple, comdat grouped, debug_types sections.
1344  if (RelSecName == "debug_types")
1345  Map =
1346  &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1347  .Relocs;
1348  else if (RelSecName == "debug_types.dwo")
1349  Map = &static_cast<DWARFSectionMap &>(
1350  TypesDWOSections[*RelocatedSection])
1351  .Relocs;
1352  else
1353  continue;
1354  }
1355 
1356  if (Section.relocation_begin() == Section.relocation_end())
1357  continue;
1358 
1359  // Symbol to [address, section index] cache mapping.
1360  std::map<SymbolRef, SymInfo> AddrCache;
1361  for (const RelocationRef &Reloc : Section.relocations()) {
1362  // FIXME: it's not clear how to correctly handle scattered
1363  // relocations.
1364  if (isRelocScattered(Obj, Reloc))
1365  continue;
1366 
1367  Expected<SymInfo> SymInfoOrErr =
1368  getSymbolInfo(Obj, Reloc, L, AddrCache);
1369  if (!SymInfoOrErr) {
1370  if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1371  return;
1372  continue;
1373  }
1374 
1375  object::RelocVisitor V(Obj);
1376  uint64_t Val = V.visit(Reloc.getType(), Reloc, SymInfoOrErr->Address);
1377  if (V.error()) {
1379  Reloc.getTypeName(Type);
1380  ErrorPolicy EP = HandleError(
1381  createError("failed to compute relocation: " + Type + ", ",
1382  errorCodeToError(object_error::parse_failed)));
1383  if (EP == ErrorPolicy::Halt)
1384  return;
1385  continue;
1386  }
1387  RelocAddrEntry Rel = {SymInfoOrErr->SectionIndex, Val};
1388  Map->insert({Reloc.getOffset(), Rel});
1389  }
1390  }
1391 
1392  for (SectionName &S : SectionNames)
1393  if (SectionAmountMap[S.Name] > 1)
1394  S.IsNameUnique = false;
1395  }
1396 
1398  uint64_t Pos) const override {
1399  auto &Sec = static_cast<const DWARFSectionMap &>(S);
1400  RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1401  if (AI == Sec.Relocs.end())
1402  return None;
1403  return AI->second;
1404  }
1405 
1406  const object::ObjectFile *getFile() const override { return Obj; }
1407 
1408  ArrayRef<SectionName> getSectionNames() const override {
1409  return SectionNames;
1410  }
1411 
1412  bool isLittleEndian() const override { return IsLittleEndian; }
1413  StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1414  const DWARFSection &getLineDWOSection() const override {
1415  return LineDWOSection;
1416  }
1417  const DWARFSection &getLocDWOSection() const override {
1418  return LocDWOSection;
1419  }
1420  StringRef getStringDWOSection() const override { return StringDWOSection; }
1421  const DWARFSection &getStringOffsetDWOSection() const override {
1422  return StringOffsetDWOSection;
1423  }
1424  const DWARFSection &getRangeDWOSection() const override {
1425  return RangeDWOSection;
1426  }
1427  const DWARFSection &getAddrSection() const override { return AddrSection; }
1428  StringRef getCUIndexSection() const override { return CUIndexSection; }
1429  StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1430  StringRef getTUIndexSection() const override { return TUIndexSection; }
1431 
1432  // DWARF v5
1433  const DWARFSection &getStringOffsetSection() const override {
1434  return StringOffsetSection;
1435  }
1436 
1437  // Sections for DWARF5 split dwarf proposal.
1438  const DWARFSection &getInfoDWOSection() const override {
1439  return InfoDWOSection;
1440  }
1441  void forEachTypesDWOSections(
1442  function_ref<void(const DWARFSection &)> F) const override {
1443  for (auto &P : TypesDWOSections)
1444  F(P.second);
1445  }
1446 
1447  StringRef getAbbrevSection() const override { return AbbrevSection; }
1448  const DWARFSection &getLocSection() const override { return LocSection; }
1449  StringRef getARangeSection() const override { return ARangeSection; }
1450  StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1451  StringRef getEHFrameSection() const override { return EHFrameSection; }
1452  const DWARFSection &getLineSection() const override { return LineSection; }
1453  StringRef getStringSection() const override { return StringSection; }
1454  const DWARFSection &getRangeSection() const override { return RangeSection; }
1455  StringRef getMacinfoSection() const override { return MacinfoSection; }
1456  StringRef getPubNamesSection() const override { return PubNamesSection; }
1457  StringRef getPubTypesSection() const override { return PubTypesSection; }
1458  StringRef getGnuPubNamesSection() const override {
1459  return GnuPubNamesSection;
1460  }
1461  StringRef getGnuPubTypesSection() const override {
1462  return GnuPubTypesSection;
1463  }
1464  const DWARFSection &getAppleNamesSection() const override {
1465  return AppleNamesSection;
1466  }
1467  const DWARFSection &getAppleTypesSection() const override {
1468  return AppleTypesSection;
1469  }
1470  const DWARFSection &getAppleNamespacesSection() const override {
1471  return AppleNamespacesSection;
1472  }
1473  const DWARFSection &getAppleObjCSection() const override {
1474  return AppleObjCSection;
1475  }
1476 
1477  StringRef getFileName() const override { return FileName; }
1478  uint8_t getAddressSize() const override { return AddressSize; }
1479  const DWARFSection &getInfoSection() const override { return InfoSection; }
1480  void forEachTypesSections(
1481  function_ref<void(const DWARFSection &)> F) const override {
1482  for (auto &P : TypesSections)
1483  F(P.second);
1484  }
1485 };
1486 } // namespace
1487 
1488 std::unique_ptr<DWARFContext>
1490  function_ref<ErrorPolicy(Error)> HandleError,
1491  std::string DWPName) {
1492  auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
1493  return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
1494 }
1495 
1496 std::unique_ptr<DWARFContext>
1497 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1498  uint8_t AddrSize, bool isLittleEndian) {
1499  auto DObj =
1500  llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1501  return llvm::make_unique<DWARFContext>(std::move(DObj), "");
1502 }
1503 
1505  // Detect the architecture from the object file. We usually don't need OS
1506  // info to lookup a target and create register info.
1507  Triple TT;
1508  TT.setArch(Triple::ArchType(Obj.getArch()));
1511  std::string TargetLookupError;
1512  const Target *TheTarget =
1513  TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1514  if (!TargetLookupError.empty())
1515  return make_error<StringError>(TargetLookupError, inconvertibleErrorCode());
1516  RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1517  return Error::success();
1518 }
const DWARFUnitIndex & getTUIndex()
This implements the Apple accelerator table format, a precursor of the DWARF 5 accelerator table form...
uint32_t StartLine
Definition: DIContext.h:36
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Create ObjectFile from path.
Definition: ObjectFile.cpp:152
void getInlinedChainForAddress(uint64_t Address, SmallVectorImpl< DWARFDie > &InlinedChain)
getInlinedChainForAddress - fetches inlined chain for a given address.
Definition: DWARFUnit.cpp:738
const DWARFDebugFrame * getEHFrame()
Get a pointer to the parsed eh frame information object.
void push_back(const T &Elt)
Definition: SmallVector.h:212
uint32_t Discriminator
Definition: DIContext.h:39
const DWARFDebugFrame * getDebugFrame()
Get a pointer to the parsed frame information object.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
Definition: raw_ostream.h:217
std::string FileName
Definition: DIContext.h:32
A parsed .debug_frame or .eh_frame section.
static DWARFAcceleratorTable & getAccelTable(std::unique_ptr< DWARFAcceleratorTable > &Cache, const DWARFObject &Obj, const DWARFSection &Section, StringRef StringSection, bool IsLittleEndian)
Compute iterated dominance frontiers using a linear time algorithm.
Definition: AllocatorList.h:24
static ContributionCollection collectContributionData(DWARFContext::cu_iterator_range CUs, DWARFContext::tu_section_iterator_range TUSs)
const DWARFDebugLocDWO * getDebugLocDWO()
Get a pointer to the parsed DebugLoc object.
Represents structure for holding and parsing .debug_pub* tables.
const DWARFDebugLoc * getDebugLoc()
Get a pointer to the parsed DebugLoc object.
virtual bool getLoadedSectionContents(const object::SectionRef &Sec, StringRef &Data) const
If conveniently available, return the content of the given Section.
Definition: DIContext.h:242
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
Definition: SmallVector.h:136
void dump(raw_ostream &OS, const MCRegisterInfo *RegInfo, Optional< uint64_t > Offset) const
Print the location lists found within the debug_loc section.
ErrorPolicy
Used as a return value for a error callback passed to DWARF context.
Definition: DWARFContext.h:54
uint32_t sizeofTotalLength() const
bool addressRangeContainsAddress(const uint64_t Address) const
Definition: DWARFDie.cpp:395
void setVendor(VendorType Kind)
setVendor - Set the vendor (second) component of the triple to a known type.
Definition: Triple.cpp:1123
StringRef getFileName() const
Definition: Binary.cpp:41
void dump(raw_ostream &OS) const
DWARFDie getDIEForOffset(uint32_t Offset)
Get a DIE given an exact offset.
uint64_t Address
DWARFGdbIndex & getGdbIndex()
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
uint32_t findAddress(uint64_t Address) const
format_object< Ts... > format(const char *Fmt, const Ts &... Vals)
These are helper functions used to produce formatted output.
Definition: Format.h:124
bool handleDebugLine()
Verify the information in the .debug_line section.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:89
uint32_t Line
An unsigned integer indicating a source line number.
DIEsForAddress getDIEsForAddress(uint64_t Address)
Get the compilation unit, the function DIE and lexical block DIE for the given address where applicab...
static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, const DWARFSection &StringOffsetsSection, StringRef StringSection, DWARFContext::cu_iterator_range CUs, DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian, unsigned MaxVersion)
This class is the base class for all object file types.
Definition: ObjectFile.h:190
bool parse(const DWARFDataExtractor &DebugLineData, uint32_t *OffsetPtr, const DWARFUnit *U=nullptr)
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:38
unsigned getNumTypeUnits()
Get the number of compile units in this context.
Definition: DWARFContext.h:176
F(f)
void setOS(OSType Kind)
setOS - Set the operating system (third) component of the triple to a known type. ...
Definition: Triple.cpp:1127
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:97
unsigned getMaxVersion() const
Definition: DWARFContext.h:210
const DWARFDebugAbbrev * getDebugAbbrevDWO()
Get a pointer to the parsed dwo abbreviations object.
DINameKind
A DINameKind is passed to name search methods to specify a preference regarding the type of name reso...
Definition: DIContext.h:113
Error takeError()
Take ownership of the stored error.
Definition: Error.h:537
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
std::unique_ptr< const DWARFObject > DObj
Definition: DWARFContext.h:113
bool handleDebugInfo()
Verify the information in the .debug_info section.
raw_ostream & write_uuid(const uuid_t UUID)
A format-neutral container for source line information.
Definition: DIContext.h:31
DWARFDie getSubroutineForAddress(uint64_t Address)
Returns subprogram DIE with address range encompassing the provided address.
Definition: DWARFUnit.cpp:673
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:191
void dump(raw_ostream &OS, Optional< uint64_t > Offset) const
Dump the section data into the given stream.
Definition: BitVector.h:920
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:947
uint32_t getU32(uint32_t *offset_ptr) const
Extract a uint32_t value from *offset_ptr.
static bool getFunctionNameAndStartLineForAddress(DWARFCompileUnit *CU, uint64_t Address, FunctionNameKind Kind, std::string &FunctionName, uint32_t &StartLine)
Twine - A lightweight data structure for efficiently representing the concatenation of temporary valu...
Definition: Twine.h:81
DwarfFormat
Constants that define the DWARF format as 32 or 64 bit.
Definition: Dwarf.h:518
const char * getCompilationDir()
Definition: DWARFUnit.cpp:170
FunctionNameKind FNKind
Definition: DIContext.h:122
unsigned getNumCompileUnits()
Get the number of compile units in this context.
Definition: DWARFContext.h:170
const DWARFSection & getLineSection() const
Definition: DWARFUnit.h:304
FileLineInfoKind FLIKind
Definition: DIContext.h:121
uint64_t Address
The program-counter value corresponding to a machine instruction generated by the compiler...
void getCallerFrame(uint32_t &CallFile, uint32_t &CallLine, uint32_t &CallColumn, uint32_t &CallDiscriminator) const
Retrieves values of DW_AT_call_file, DW_AT_call_line and DW_AT_call_column from DIE (or zeroes if the...
Definition: DWARFDie.cpp:428
virtual uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const
Obtain the Load Address of a section by SectionRef.
Definition: DIContext.h:227
Tagged union holding either a T or a Error.
Definition: CachePruning.h:23
const MCRegisterInfo * getRegisterInfo() const
Definition: DWARFContext.h:286
unsigned getNumDWOTypeUnits()
Get the number of compile units in the DWO context.
Definition: DWARFContext.h:188
uint8_t getAddressByteSize() const
Definition: DWARFUnit.h:349
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:48
LLVM_ATTRIBUTE_ALWAYS_INLINE StringSwitch & Case(const char(&S)[N], const T &Value)
Definition: StringSwitch.h:74
bool verify(raw_ostream &OS, DIDumpOptions DumpOpts={}) override
const T & getValue() const LLVM_LVALUE_FUNCTION
Definition: Optional.h:181
const DWARFDebugAranges * getDebugAranges()
Get a pointer to the parsed DebugAranges object.
static void dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, const DWARFSection &StringOffsetsSection, StringRef StringSection, DWARFContext::cu_iterator_range CUs, DWARFContext::tu_section_iterator_range TUSs, bool LittleEndian)
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Definition: APInt.h:33
uint64_t TotalLength
The size in bytes of the statement information for this compilation unit (not including the total_len...
const DWARFDebugAbbrev * getDebugAbbrev()
Get a pointer to the parsed DebugAbbrev object.
section_iterator_range sections() const
Definition: ObjectFile.h:274
DWARFCompileUnit * getCompileUnitAtIndex(unsigned index)
Get the compile unit at the specified index for this compile unit.
Definition: DWARFContext.h:194
const DWARFAcceleratorTable & getAppleObjC()
Get a reference to the parsed accelerator table 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
const std::string & str() const
Definition: Triple.h:354
std::map< uint64_t, DWARFUnit * > LineToUnitMap
uint64_t getDeclLine() const
Returns the declaration line (start line) for a DIE, assuming it specifies a subprogram.
Definition: DWARFDie.cpp:424
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:364
uint64_t SectionIndex
Error loadRegisterInfo(const object::ObjectFile &Obj)
Loads register info for the architecture of the provided object file.
Container for dump options that control which debug information will be dumped.
Definition: DIContext.h:153
virtual StringRef mapDebugSectionName(StringRef Name) const
Maps a debug section name to a standard DWARF section name.
Definition: ObjectFile.h:302
static Expected< StringRef > getFileName(const DebugStringTableSubsectionRef &Strings, const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID)
Optional< uint64_t > toSectionOffset(const Optional< DWARFFormValue > &V)
Take an optional DWARFFormValue and try to extract an section offset.
#define P(N)
A switch()-like statement whose cases are string literals.
Definition: StringSwitch.h:43
Utility class that carries the DWARF compile/type unit and the debug info entry in an object...
Definition: DWARFDie.h:43
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
uint32_t Column
Definition: DIContext.h:35
virtual uint8_t getBytesInAddress() const =0
The number of bytes used to represent an address in this object file format.
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:117
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
Definition: DIContext.h:171
uint16_t File
An unsigned integer indicating the identity of the source file corresponding to a machine instruction...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
Error errorCodeToError(std::error_code EC)
Helper for converting an std::error_code to a Error.
Definition: Error.cpp:78
const DWARFDebugMacro * getDebugMacro()
Get a pointer to the parsed DebugMacro object.
A format-neutral container for inlined code description.
Definition: DIContext.h:77
A structured debug information entry.
Definition: DIE.h:662
LLVM_NODISCARD size_t find_first_not_of(char C, size_t From=0) const
Find the first character in the string that is not C or npos if not found.
Definition: StringRef.cpp:250
void dump(raw_ostream &OS) const
bool handleDebugAbbrev()
Verify the information in any of the following sections, if available: .debug_abbrev, debug_abbrev.dwo.
static Error createError(const Twine &Reason, llvm::Error E)
DILineInfo getLineInfoForAddress(uint64_t Address, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
static ErrorPolicy defaultErrorHandler(Error E)
Function used to handle default error reporting policy.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
void dump(raw_ostream &OS)
virtual basic_symbol_iterator symbol_end() const =0
void dump(raw_ostream &OS, const MCRegisterInfo *RegInfo, Optional< uint64_t > Offset) const
static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj)
Dump the UUID load command.
static bool isRelocScattered(const object::ObjectFile &Obj, const RelocationRef &Reloc)
void dump(raw_ostream &OS) const
Print the macro list found within the debug_macinfo section.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Definition: StringExtras.h:43
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition: ObjectFile.h:348
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:962
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:835
bool isLittleEndian() const
Definition: Binary.h:131
LLVM_ATTRIBUTE_ALWAYS_INLINE R Default(const T &Value) const
Definition: StringSwitch.h:244
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...
Triple - Helper class for working with autoconf configuration names.
Definition: Triple.h:44
Standard .debug_line state machine structure.
static std::unique_ptr< DWARFContext > create(const object::ObjectFile &Obj, const LoadedObjectInfo *L=nullptr, function_ref< ErrorPolicy(Error)> HandleError=defaultErrorHandler, std::string DWPName="")
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
bool lookupAddressRange(uint64_t Address, uint64_t Size, std::vector< uint32_t > &Result) const
DWARFCompileUnit * getDWOCompileUnitForHash(uint64_t Hash)
uint16_t Column
An unsigned integer indicating a column number within a source line.
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition: DWARFUnit.h:410
StringRef getArchName() const
getArchName - Get the architecture (first) component of the triple.
Definition: Triple.cpp:940
static ErrorSuccess success()
Create a success value.
Definition: Error.h:313
bool getFileLineInfoForAddress(uint64_t Address, const char *CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, DILineInfo &Result) const
Fills the Result argument with the file and line information corresponding to Address.
uint32_t Line
Definition: DIContext.h:34
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:862
static LineToUnitMap buildLineToUnitMap(DWARFContext::cu_iterator_range CUs, DWARFContext::tu_section_iterator_range TUSections)
DIInliningInfo getInliningInfoForAddress(uint64_t Address, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
static Expected< SymInfo > getSymbolInfo(const object::ObjectFile &Obj, const RelocationRef &Reloc, const LoadedObjectInfo *L, std::map< SymbolRef, SymInfo > &Cache)
Returns the address of symbol relocation used against and a section index.
std::string FunctionName
Definition: DIContext.h:33
virtual Triple::ArchType getArch() const =0
DWARFContext This data structure is the top level entity that deals with dwarf debug information pars...
Definition: DWARFContext.h:59
tu_section_iterator_range dwo_type_unit_sections()
Get type units in the DWO context.
Definition: DWARFContext.h:164
A range adaptor for a pair of iterators.
StringMap - This is an unconventional map that is specialized for handling keys that are "strings"...
Definition: StringMap.h:222
This file contains constants used for implementing Dwarf debug support.
Target - Wrapper for Target specific information.
An inferface for inquiring the load address of a loaded object file to be used by the DIContext imple...
Definition: DIContext.h:212
const DWARFAcceleratorTable & getAppleTypes()
Get a reference to the parsed accelerator table object.
loop extract
void dump(raw_ostream &OS) const
#define Success
DILineInfoTable getLineInfoForAddressRange(uint64_t Address, uint64_t Size, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
RelocAddrEntry contains relocated value and section index.
Definition: DWARFRelocMap.h:20
A class that verifies DWARF debug information given a DWARF Context.
Definition: DWARFVerifier.h:34
void dump(raw_ostream &OS) const
void emplace_back(ArgTypes &&... Args)
Definition: SmallVector.h:654
virtual section_iterator section_end() const =0
dwarf::Tag getTag() const
Definition: DWARFDie.h:72
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:61
Wraps the returned DIEs for a given address.
Definition: DWARFContext.h:261
bool handleAccelTables()
Verify the information in accelerator tables, if they exist.
const char * getCStr(uint32_t *offset_ptr) const
Extract a C string from *offset_ptr.
cu_iterator_range compile_units()
Get compile units in this context.
Definition: DWARFContext.h:146
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Definition: Casting.h:323
const DWARFAcceleratorTable & getAppleNames()
Get a reference to the parsed accelerator table object.
void dump(raw_ostream &OS, DIDumpOptions DumpOpts, std::array< Optional< uint64_t >, DIDT_ID_Count > DumpOffsets)
Dump a textual representation to OS.
DWARFContext(std::unique_ptr< const DWARFObject > DObj, std::string DWPName="")
bool isLittleEndian() const
Definition: DWARFContext.h:279
const DWARFUnitIndex & getCUIndex()
SymInfo contains information about symbol: it&#39;s address and section index which is -1LL for absolute ...
DINameKind FunctionNameKind
Definition: DIContext.h:119
cu_iterator_range dwo_compile_units()
Get compile units in the DWO context.
Definition: DWARFContext.h:158
bool getFileNameByIndex(uint64_t FileIndex, const char *CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, std::string &Result) const
Extracts filename by its index in filename table in prologue.
const DWARFDebugLine::LineTable * getLineTableForUnit(DWARFUnit *cu)
Get a pointer to a parsed line table corresponding to a compile unit.
constexpr char Size[]
Key for Kernel::Arg::Metadata::mSize.
Lightweight error class with error context and mandatory checking.
Definition: Error.h:156
std::underlying_type< E >::type Mask()
Get a bitmask with 1s in all places up to the high-order bit of E&#39;s largest value.
Definition: BitmaskEnum.h:81
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:44
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:49
tu_section_iterator_range type_unit_sections()
Get type units in this context.
Definition: DWARFContext.h:152
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
Definition: Parallel.h:199
bool parse(DWARFDataExtractor &DebugLineData, uint32_t *OffsetPtr, const DWARFUnit *U, raw_ostream *OS=nullptr)
Parse prologue and all rows.
const DWARFAcceleratorTable & getAppleNamespaces()
Get a reference to the parsed accelerator table object.
const uint64_t Version
Definition: InstrProf.h:867
bool extract(const DWARFDataExtractor &data, uint32_t *offset_ptr)
uint64_t visit(uint32_t Rel, RelocationRef R, uint64_t Value=0)
Definition: RelocVisitor.h:42
uint32_t getLineTableOffset() const
Definition: DWARFUnit.h:480
const char * getSubroutineName(DINameKind Kind) const
If a DIE represents a subprogram (or inlined subroutine), returns its mangled name (or short name...
Definition: DWARFDie.cpp:403
void setArch(ArchType Kind)
setArch - Set the architecture (first) component of the triple to a known type.
Definition: Triple.cpp:1119
This is a value type class that represents a single section in the list of sections in the object fil...
Definition: ObjectFile.h:81
std::vector< Optional< StrOffsetsContributionDescriptor > > ContributionCollection
Base class for object file relocation visitors.
Definition: RelocVisitor.h:35
StringRef extension(StringRef path, Style style=Style::native)
Get extension.
Definition: Path.cpp:591
void dump(raw_ostream &OS) const
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:73