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