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