LLVM  9.0.0svn
DWARFContext.cpp
Go to the documentation of this file.
1 //===- DWARFContext.cpp ---------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
10 #include "llvm/ADT/STLExtras.h"
11 #include "llvm/ADT/SmallString.h"
12 #include "llvm/ADT/SmallVector.h"
13 #include "llvm/ADT/StringRef.h"
14 #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"
44 #include "llvm/Support/LEB128.h"
46 #include "llvm/Support/Path.h"
48 #include "llvm/Support/WithColor.h"
50 #include <algorithm>
51 #include <cstdint>
52 #include <deque>
53 #include <map>
54 #include <string>
55 #include <utility>
56 #include <vector>
57 
58 using namespace llvm;
59 using namespace dwarf;
60 using namespace object;
61 
62 #define DEBUG_TYPE "dwarf"
63 
67 
68 DWARFContext::DWARFContext(std::unique_ptr<const DWARFObject> DObj,
69  std::string DWPName)
70  : DIContext(CK_DWARF), DWPName(std::move(DWPName)), DObj(std::move(DObj)) {}
71 
72 DWARFContext::~DWARFContext() = default;
73 
74 /// Dump the UUID load command.
75 static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj) {
76  auto *MachO = dyn_cast<MachOObjectFile>(&Obj);
77  if (!MachO)
78  return;
79  for (auto LC : MachO->load_commands()) {
81  if (LC.C.cmd == MachO::LC_UUID) {
82  if (LC.C.cmdsize < sizeof(UUID) + sizeof(LC.C)) {
83  OS << "error: UUID load command is too short.\n";
84  return;
85  }
86  OS << "UUID: ";
87  memcpy(&UUID, LC.Ptr+sizeof(LC.C), sizeof(UUID));
88  OS.write_uuid(UUID);
89  Triple T = MachO->getArchTriple();
90  OS << " (" << T.getArchName() << ')';
91  OS << ' ' << MachO->getFileName() << '\n';
92  }
93  }
94 }
95 
97  std::vector<Optional<StrOffsetsContributionDescriptor>>;
98 
99 // Collect all the contributions to the string offsets table from all units,
100 // sort them by their starting offsets and remove duplicates.
103  ContributionCollection Contributions;
104  for (const auto &U : Units)
105  if (const auto &C = U->getStringOffsetsTableContribution())
106  Contributions.push_back(C);
107  // Sort the contributions so that any invalid ones are placed at
108  // the start of the contributions vector. This way they are reported
109  // first.
110  llvm::sort(Contributions,
113  if (L && R)
114  return L->Base < R->Base;
115  return R.hasValue();
116  });
117 
118  // Uniquify contributions, as it is possible that units (specifically
119  // type units in dwo or dwp files) share contributions. We don't want
120  // to report them more than once.
121  Contributions.erase(
122  std::unique(Contributions.begin(), Contributions.end(),
125  if (L && R)
126  return L->Base == R->Base && L->Size == R->Size;
127  return false;
128  }),
129  Contributions.end());
130  return Contributions;
131 }
132 
134  raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj,
135  const DWARFSection &StringOffsetsSection, StringRef StringSection,
136  DWARFContext::unit_iterator_range Units, bool LittleEndian) {
137  auto Contributions = collectContributionData(Units);
138  DWARFDataExtractor StrOffsetExt(Obj, StringOffsetsSection, LittleEndian, 0);
139  DataExtractor StrData(StringSection, LittleEndian, 0);
140  uint64_t SectionSize = StringOffsetsSection.Data.size();
141  uint32_t Offset = 0;
142  for (auto &Contribution : Contributions) {
143  // Report an ill-formed contribution.
144  if (!Contribution) {
145  OS << "error: invalid contribution to string offsets table in section ."
146  << SectionName << ".\n";
147  return;
148  }
149 
150  dwarf::DwarfFormat Format = Contribution->getFormat();
151  uint16_t Version = Contribution->getVersion();
152  uint64_t ContributionHeader = Contribution->Base;
153  // In DWARF v5 there is a contribution header that immediately precedes
154  // the string offsets base (the location we have previously retrieved from
155  // the CU DIE's DW_AT_str_offsets attribute). The header is located either
156  // 8 or 16 bytes before the base, depending on the contribution's format.
157  if (Version >= 5)
158  ContributionHeader -= Format == DWARF32 ? 8 : 16;
159 
160  // Detect overlapping contributions.
161  if (Offset > ContributionHeader) {
163  << "overlapping contributions to string offsets table in section ."
164  << SectionName << ".\n";
165  return;
166  }
167  // Report a gap in the table.
168  if (Offset < ContributionHeader) {
169  OS << format("0x%8.8x: Gap, length = ", Offset);
170  OS << (ContributionHeader - Offset) << "\n";
171  }
172  OS << format("0x%8.8x: ", (uint32_t)ContributionHeader);
173  // In DWARF v5 the contribution size in the descriptor does not equal
174  // the originally encoded length (it does not contain the length of the
175  // version field and the padding, a total of 4 bytes). Add them back in
176  // for reporting.
177  OS << "Contribution size = " << (Contribution->Size + (Version < 5 ? 0 : 4))
178  << ", Format = " << (Format == DWARF32 ? "DWARF32" : "DWARF64")
179  << ", Version = " << Version << "\n";
180 
181  Offset = Contribution->Base;
182  unsigned EntrySize = Contribution->getDwarfOffsetByteSize();
183  while (Offset - Contribution->Base < Contribution->Size) {
184  OS << format("0x%8.8x: ", Offset);
185  // FIXME: We can only extract strings if the offset fits in 32 bits.
186  uint64_t StringOffset =
187  StrOffsetExt.getRelocatedValue(EntrySize, &Offset);
188  // Extract the string if we can and display it. Otherwise just report
189  // the offset.
190  if (StringOffset <= std::numeric_limits<uint32_t>::max()) {
191  uint32_t StringOffset32 = (uint32_t)StringOffset;
192  OS << format("%8.8x ", StringOffset32);
193  const char *S = StrData.getCStr(&StringOffset32);
194  if (S)
195  OS << format("\"%s\"", S);
196  } else
197  OS << format("%16.16" PRIx64 " ", StringOffset);
198  OS << "\n";
199  }
200  }
201  // Report a gap at the end of the table.
202  if (Offset < SectionSize) {
203  OS << format("0x%8.8x: Gap, length = ", Offset);
204  OS << (SectionSize - Offset) << "\n";
205  }
206 }
207 
208 // Dump a DWARF string offsets section. This may be a DWARF v5 formatted
209 // string offsets section, where each compile or type unit contributes a
210 // number of entries (string offsets), with each contribution preceded by
211 // a header containing size and version number. Alternatively, it may be a
212 // monolithic series of string offsets, as generated by the pre-DWARF v5
213 // implementation of split DWARF.
215  const DWARFObject &Obj,
216  const DWARFSection &StringOffsetsSection,
217  StringRef StringSection,
219  bool LittleEndian, unsigned MaxVersion) {
220  // If we have at least one (compile or type) unit with DWARF v5 or greater,
221  // we assume that the section is formatted like a DWARF v5 string offsets
222  // section.
223  if (MaxVersion >= 5)
224  dumpDWARFv5StringOffsetsSection(OS, SectionName, Obj, StringOffsetsSection,
225  StringSection, Units, LittleEndian);
226  else {
227  DataExtractor strOffsetExt(StringOffsetsSection.Data, LittleEndian, 0);
228  uint32_t offset = 0;
229  uint64_t size = StringOffsetsSection.Data.size();
230  // Ensure that size is a multiple of the size of an entry.
231  if (size & ((uint64_t)(sizeof(uint32_t) - 1))) {
232  OS << "error: size of ." << SectionName << " is not a multiple of "
233  << sizeof(uint32_t) << ".\n";
234  size &= -(uint64_t)sizeof(uint32_t);
235  }
236  DataExtractor StrData(StringSection, LittleEndian, 0);
237  while (offset < size) {
238  OS << format("0x%8.8x: ", offset);
239  uint32_t StringOffset = strOffsetExt.getU32(&offset);
240  OS << format("%8.8x ", StringOffset);
241  const char *S = StrData.getCStr(&StringOffset);
242  if (S)
243  OS << format("\"%s\"", S);
244  OS << "\n";
245  }
246  }
247 }
248 
249 // Dump the .debug_addr section.
250 static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData,
251  DIDumpOptions DumpOpts, uint16_t Version,
252  uint8_t AddrSize) {
253  uint32_t Offset = 0;
254  while (AddrData.isValidOffset(Offset)) {
255  DWARFDebugAddrTable AddrTable;
256  uint32_t TableOffset = Offset;
257  if (Error Err = AddrTable.extract(AddrData, &Offset, Version, AddrSize,
259  WithColor::error() << toString(std::move(Err)) << '\n';
260  // Keep going after an error, if we can, assuming that the length field
261  // could be read. If it couldn't, stop reading the section.
262  if (!AddrTable.hasValidLength())
263  break;
264  uint64_t Length = AddrTable.getLength();
265  Offset = TableOffset + Length;
266  } else {
267  AddrTable.dump(OS, DumpOpts);
268  }
269  }
270 }
271 
272 // Dump the .debug_rnglists or .debug_rnglists.dwo section (DWARF v5).
274  raw_ostream &OS, DWARFDataExtractor &rnglistData,
276  LookupPooledAddress,
277  DIDumpOptions DumpOpts) {
278  uint32_t Offset = 0;
279  while (rnglistData.isValidOffset(Offset)) {
281  uint32_t TableOffset = Offset;
282  if (Error Err = Rnglists.extract(rnglistData, &Offset)) {
283  WithColor::error() << toString(std::move(Err)) << '\n';
284  uint64_t Length = Rnglists.length();
285  // Keep going after an error, if we can, assuming that the length field
286  // could be read. If it couldn't, stop reading the section.
287  if (Length == 0)
288  break;
289  Offset = TableOffset + Length;
290  } else {
291  Rnglists.dump(OS, LookupPooledAddress, DumpOpts);
292  }
293  }
294 }
295 
298  const MCRegisterInfo *MRI,
299  Optional<uint64_t> DumpOffset) {
300  uint32_t Offset = 0;
301  DWARFDebugLoclists Loclists;
302 
303  DWARFListTableHeader Header(".debug_loclists", "locations");
304  if (Error E = Header.extract(Data, &Offset)) {
305  WithColor::error() << toString(std::move(E)) << '\n';
306  return;
307  }
308 
309  Header.dump(OS, DumpOpts);
310  DataExtractor LocData(Data.getData().drop_front(Offset),
311  Data.isLittleEndian(), Header.getAddrSize());
312 
313  Loclists.parse(LocData, Header.getVersion());
314  Loclists.dump(OS, 0, MRI, DumpOffset);
315 }
316 
318  raw_ostream &OS, DIDumpOptions DumpOpts,
319  std::array<Optional<uint64_t>, DIDT_ID_Count> DumpOffsets) {
320 
321  uint64_t DumpType = DumpOpts.DumpType;
322 
323  StringRef Extension = sys::path::extension(DObj->getFileName());
324  bool IsDWO = (Extension == ".dwo") || (Extension == ".dwp");
325 
326  // Print UUID header.
327  const auto *ObjFile = DObj->getFile();
328  if (DumpType & DIDT_UUID)
329  dumpUUID(OS, *ObjFile);
330 
331  // Print a header for each explicitly-requested section.
332  // Otherwise just print one for non-empty sections.
333  // Only print empty .dwo section headers when dumping a .dwo file.
334  bool Explicit = DumpType != DIDT_All && !IsDWO;
335  bool ExplicitDWO = Explicit && IsDWO;
336  auto shouldDump = [&](bool Explicit, const char *Name, unsigned ID,
338  unsigned Mask = 1U << ID;
339  bool Should = (DumpType & Mask) && (Explicit || !Section.empty());
340  if (!Should)
341  return nullptr;
342  OS << "\n" << Name << " contents:\n";
343  return &DumpOffsets[ID];
344  };
345 
346  // Dump individual sections.
347  if (shouldDump(Explicit, ".debug_abbrev", DIDT_ID_DebugAbbrev,
348  DObj->getAbbrevSection()))
349  getDebugAbbrev()->dump(OS);
350  if (shouldDump(ExplicitDWO, ".debug_abbrev.dwo", DIDT_ID_DebugAbbrev,
351  DObj->getAbbrevDWOSection()))
352  getDebugAbbrevDWO()->dump(OS);
353 
354  auto dumpDebugInfo = [&](const char *Name, unit_iterator_range Units) {
355  OS << '\n' << Name << " contents:\n";
356  if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugInfo])
357  for (const auto &U : Units)
358  U->getDIEForOffset(DumpOffset.getValue())
359  .dump(OS, 0, DumpOpts.noImplicitRecursion());
360  else
361  for (const auto &U : Units)
362  U->dump(OS, DumpOpts);
363  };
364  if ((DumpType & DIDT_DebugInfo)) {
365  if (Explicit || getNumCompileUnits())
366  dumpDebugInfo(".debug_info", info_section_units());
367  if (ExplicitDWO || getNumDWOCompileUnits())
368  dumpDebugInfo(".debug_info.dwo", dwo_info_section_units());
369  }
370 
371  auto dumpDebugType = [&](const char *Name, unit_iterator_range Units) {
372  OS << '\n' << Name << " contents:\n";
373  for (const auto &U : Units)
374  if (auto DumpOffset = DumpOffsets[DIDT_ID_DebugTypes])
375  U->getDIEForOffset(*DumpOffset)
376  .dump(OS, 0, DumpOpts.noImplicitRecursion());
377  else
378  U->dump(OS, DumpOpts);
379  };
380  if ((DumpType & DIDT_DebugTypes)) {
381  if (Explicit || getNumTypeUnits())
382  dumpDebugType(".debug_types", types_section_units());
383  if (ExplicitDWO || getNumDWOTypeUnits())
384  dumpDebugType(".debug_types.dwo", dwo_types_section_units());
385  }
386 
387  if (const auto *Off = shouldDump(Explicit, ".debug_loc", DIDT_ID_DebugLoc,
388  DObj->getLocSection().Data)) {
389  getDebugLoc()->dump(OS, getRegisterInfo(), *Off);
390  }
391  if (const auto *Off =
392  shouldDump(Explicit, ".debug_loclists", DIDT_ID_DebugLoclists,
393  DObj->getLoclistsSection().Data)) {
394  DWARFDataExtractor Data(*DObj, DObj->getLoclistsSection(), isLittleEndian(),
395  0);
396  dumpLoclistsSection(OS, DumpOpts, Data, getRegisterInfo(), *Off);
397  }
398  if (const auto *Off =
399  shouldDump(ExplicitDWO, ".debug_loc.dwo", DIDT_ID_DebugLoc,
400  DObj->getLocDWOSection().Data)) {
401  getDebugLocDWO()->dump(OS, 0, getRegisterInfo(), *Off);
402  }
403 
404  if (const auto *Off = shouldDump(Explicit, ".debug_frame", DIDT_ID_DebugFrame,
405  DObj->getDebugFrameSection()))
406  getDebugFrame()->dump(OS, getRegisterInfo(), *Off);
407 
408  if (const auto *Off = shouldDump(Explicit, ".eh_frame", DIDT_ID_DebugFrame,
409  DObj->getEHFrameSection()))
410  getEHFrame()->dump(OS, getRegisterInfo(), *Off);
411 
412  if (DumpType & DIDT_DebugMacro) {
413  if (Explicit || !getDebugMacro()->empty()) {
414  OS << "\n.debug_macinfo contents:\n";
415  getDebugMacro()->dump(OS);
416  }
417  }
418 
419  if (shouldDump(Explicit, ".debug_aranges", DIDT_ID_DebugAranges,
420  DObj->getARangeSection())) {
421  uint32_t offset = 0;
422  DataExtractor arangesData(DObj->getARangeSection(), isLittleEndian(), 0);
424  while (set.extract(arangesData, &offset))
425  set.dump(OS);
426  }
427 
428  auto DumpLineSection = [&](DWARFDebugLine::SectionParser Parser,
429  DIDumpOptions DumpOpts,
430  Optional<uint64_t> DumpOffset) {
431  while (!Parser.done()) {
432  if (DumpOffset && Parser.getOffset() != *DumpOffset) {
433  Parser.skip(dumpWarning);
434  continue;
435  }
436  OS << "debug_line[" << format("0x%8.8x", Parser.getOffset()) << "]\n";
437  if (DumpOpts.Verbose) {
438  Parser.parseNext(dumpWarning, dumpWarning, &OS);
439  } else {
440  DWARFDebugLine::LineTable LineTable =
442  LineTable.dump(OS, DumpOpts);
443  }
444  }
445  };
446 
447  if (const auto *Off = shouldDump(Explicit, ".debug_line", DIDT_ID_DebugLine,
448  DObj->getLineSection().Data)) {
449  DWARFDataExtractor LineData(*DObj, DObj->getLineSection(), isLittleEndian(),
450  0);
451  DWARFDebugLine::SectionParser Parser(LineData, *this, compile_units(),
452  type_units());
453  DumpLineSection(Parser, DumpOpts, *Off);
454  }
455 
456  if (const auto *Off =
457  shouldDump(ExplicitDWO, ".debug_line.dwo", DIDT_ID_DebugLine,
458  DObj->getLineDWOSection().Data)) {
459  DWARFDataExtractor LineData(*DObj, DObj->getLineDWOSection(),
460  isLittleEndian(), 0);
461  DWARFDebugLine::SectionParser Parser(LineData, *this, dwo_compile_units(),
462  dwo_type_units());
463  DumpLineSection(Parser, DumpOpts, *Off);
464  }
465 
466  if (shouldDump(Explicit, ".debug_cu_index", DIDT_ID_DebugCUIndex,
467  DObj->getCUIndexSection())) {
468  getCUIndex().dump(OS);
469  }
470 
471  if (shouldDump(Explicit, ".debug_tu_index", DIDT_ID_DebugTUIndex,
472  DObj->getTUIndexSection())) {
473  getTUIndex().dump(OS);
474  }
475 
476  if (shouldDump(Explicit, ".debug_str", DIDT_ID_DebugStr,
477  DObj->getStringSection())) {
478  DataExtractor strData(DObj->getStringSection(), isLittleEndian(), 0);
479  uint32_t offset = 0;
480  uint32_t strOffset = 0;
481  while (const char *s = strData.getCStr(&offset)) {
482  OS << format("0x%8.8x: \"%s\"\n", strOffset, s);
483  strOffset = offset;
484  }
485  }
486  if (shouldDump(ExplicitDWO, ".debug_str.dwo", DIDT_ID_DebugStr,
487  DObj->getStringDWOSection())) {
488  DataExtractor strDWOData(DObj->getStringDWOSection(), isLittleEndian(), 0);
489  uint32_t offset = 0;
490  uint32_t strDWOOffset = 0;
491  while (const char *s = strDWOData.getCStr(&offset)) {
492  OS << format("0x%8.8x: \"%s\"\n", strDWOOffset, s);
493  strDWOOffset = offset;
494  }
495  }
496  if (shouldDump(Explicit, ".debug_line_str", DIDT_ID_DebugLineStr,
497  DObj->getLineStringSection())) {
498  DataExtractor strData(DObj->getLineStringSection(), isLittleEndian(), 0);
499  uint32_t offset = 0;
500  uint32_t strOffset = 0;
501  while (const char *s = strData.getCStr(&offset)) {
502  OS << format("0x%8.8x: \"", strOffset);
503  OS.write_escaped(s);
504  OS << "\"\n";
505  strOffset = offset;
506  }
507  }
508 
509  if (shouldDump(Explicit, ".debug_addr", DIDT_ID_DebugAddr,
510  DObj->getAddrSection().Data)) {
511  DWARFDataExtractor AddrData(*DObj, DObj->getAddrSection(),
512  isLittleEndian(), 0);
513  dumpAddrSection(OS, AddrData, DumpOpts, getMaxVersion(), getCUAddrSize());
514  }
515 
516  if (shouldDump(Explicit, ".debug_ranges", DIDT_ID_DebugRanges,
517  DObj->getRangeSection().Data)) {
518  uint8_t savedAddressByteSize = getCUAddrSize();
519  DWARFDataExtractor rangesData(*DObj, DObj->getRangeSection(),
520  isLittleEndian(), savedAddressByteSize);
521  uint32_t offset = 0;
522  DWARFDebugRangeList rangeList;
523  while (rangesData.isValidOffset(offset)) {
524  if (Error E = rangeList.extract(rangesData, &offset)) {
525  WithColor::error() << toString(std::move(E)) << '\n';
526  break;
527  }
528  rangeList.dump(OS);
529  }
530  }
531 
532  auto LookupPooledAddress = [&](uint32_t Index) -> Optional<SectionedAddress> {
533  const auto &CUs = compile_units();
534  auto I = CUs.begin();
535  if (I == CUs.end())
536  return None;
537  return (*I)->getAddrOffsetSectionItem(Index);
538  };
539 
540  if (shouldDump(Explicit, ".debug_rnglists", DIDT_ID_DebugRnglists,
541  DObj->getRnglistsSection().Data)) {
542  DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsSection(),
543  isLittleEndian(), 0);
544  dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
545  }
546 
547  if (shouldDump(ExplicitDWO, ".debug_rnglists.dwo", DIDT_ID_DebugRnglists,
548  DObj->getRnglistsDWOSection().Data)) {
549  DWARFDataExtractor RnglistData(*DObj, DObj->getRnglistsDWOSection(),
550  isLittleEndian(), 0);
551  dumpRnglistsSection(OS, RnglistData, LookupPooledAddress, DumpOpts);
552  }
553 
554  if (shouldDump(Explicit, ".debug_pubnames", DIDT_ID_DebugPubnames,
555  DObj->getPubNamesSection().Data))
556  DWARFDebugPubTable(*DObj, DObj->getPubNamesSection(), isLittleEndian(), false)
557  .dump(OS);
558 
559  if (shouldDump(Explicit, ".debug_pubtypes", DIDT_ID_DebugPubtypes,
560  DObj->getPubTypesSection().Data))
561  DWARFDebugPubTable(*DObj, DObj->getPubTypesSection(), isLittleEndian(), false)
562  .dump(OS);
563 
564  if (shouldDump(Explicit, ".debug_gnu_pubnames", DIDT_ID_DebugGnuPubnames,
565  DObj->getGnuPubNamesSection().Data))
566  DWARFDebugPubTable(*DObj, DObj->getGnuPubNamesSection(), isLittleEndian(),
567  true /* GnuStyle */)
568  .dump(OS);
569 
570  if (shouldDump(Explicit, ".debug_gnu_pubtypes", DIDT_ID_DebugGnuPubtypes,
571  DObj->getGnuPubTypesSection().Data))
572  DWARFDebugPubTable(*DObj, DObj->getGnuPubTypesSection(), isLittleEndian(),
573  true /* GnuStyle */)
574  .dump(OS);
575 
576  if (shouldDump(Explicit, ".debug_str_offsets", DIDT_ID_DebugStrOffsets,
577  DObj->getStringOffsetSection().Data))
578  dumpStringOffsetsSection(OS, "debug_str_offsets", *DObj,
579  DObj->getStringOffsetSection(),
580  DObj->getStringSection(), normal_units(),
582  if (shouldDump(ExplicitDWO, ".debug_str_offsets.dwo", DIDT_ID_DebugStrOffsets,
583  DObj->getStringOffsetDWOSection().Data))
584  dumpStringOffsetsSection(OS, "debug_str_offsets.dwo", *DObj,
585  DObj->getStringOffsetDWOSection(),
586  DObj->getStringDWOSection(), dwo_units(),
588 
589  if (shouldDump(Explicit, ".gdb_index", DIDT_ID_GdbIndex,
590  DObj->getGdbIndexSection())) {
591  getGdbIndex().dump(OS);
592  }
593 
594  if (shouldDump(Explicit, ".apple_names", DIDT_ID_AppleNames,
595  DObj->getAppleNamesSection().Data))
596  getAppleNames().dump(OS);
597 
598  if (shouldDump(Explicit, ".apple_types", DIDT_ID_AppleTypes,
599  DObj->getAppleTypesSection().Data))
600  getAppleTypes().dump(OS);
601 
602  if (shouldDump(Explicit, ".apple_namespaces", DIDT_ID_AppleNamespaces,
603  DObj->getAppleNamespacesSection().Data))
604  getAppleNamespaces().dump(OS);
605 
606  if (shouldDump(Explicit, ".apple_objc", DIDT_ID_AppleObjC,
607  DObj->getAppleObjCSection().Data))
608  getAppleObjC().dump(OS);
609  if (shouldDump(Explicit, ".debug_names", DIDT_ID_DebugNames,
610  DObj->getDebugNamesSection().Data))
611  getDebugNames().dump(OS);
612 }
613 
615  parseDWOUnits(LazyParse);
616 
617  if (const auto &CUI = getCUIndex()) {
618  if (const auto *R = CUI.getFromHash(Hash))
619  return dyn_cast_or_null<DWARFCompileUnit>(
620  DWOUnits.getUnitForIndexEntry(*R));
621  return nullptr;
622  }
623 
624  // If there's no index, just search through the CUs in the DWO - there's
625  // probably only one unless this is something like LTO - though an in-process
626  // built/cached lookup table could be used in that case to improve repeated
627  // lookups of different CUs in the DWO.
628  for (const auto &DWOCU : dwo_compile_units()) {
629  // Might not have parsed DWO ID yet.
630  if (!DWOCU->getDWOId()) {
631  if (Optional<uint64_t> DWOId =
632  toUnsigned(DWOCU->getUnitDIE().find(DW_AT_GNU_dwo_id)))
633  DWOCU->setDWOId(*DWOId);
634  else
635  // No DWO ID?
636  continue;
637  }
638  if (DWOCU->getDWOId() == Hash)
639  return dyn_cast<DWARFCompileUnit>(DWOCU.get());
640  }
641  return nullptr;
642 }
643 
645  parseNormalUnits();
646  if (auto *CU = NormalUnits.getUnitForOffset(Offset))
647  return CU->getDIEForOffset(Offset);
648  return DWARFDie();
649 }
650 
652  bool Success = true;
653  DWARFVerifier verifier(OS, *this, DumpOpts);
654 
655  Success &= verifier.handleDebugAbbrev();
656  if (DumpOpts.DumpType & DIDT_DebugInfo)
657  Success &= verifier.handleDebugInfo();
658  if (DumpOpts.DumpType & DIDT_DebugLine)
659  Success &= verifier.handleDebugLine();
660  Success &= verifier.handleAccelTables();
661  return Success;
662 }
663 
665  if (CUIndex)
666  return *CUIndex;
667 
668  DataExtractor CUIndexData(DObj->getCUIndexSection(), isLittleEndian(), 0);
669 
670  CUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_INFO);
671  CUIndex->parse(CUIndexData);
672  return *CUIndex;
673 }
674 
676  if (TUIndex)
677  return *TUIndex;
678 
679  DataExtractor TUIndexData(DObj->getTUIndexSection(), isLittleEndian(), 0);
680 
681  TUIndex = llvm::make_unique<DWARFUnitIndex>(DW_SECT_TYPES);
682  TUIndex->parse(TUIndexData);
683  return *TUIndex;
684 }
685 
687  if (GdbIndex)
688  return *GdbIndex;
689 
690  DataExtractor GdbIndexData(DObj->getGdbIndexSection(), true /*LE*/, 0);
691  GdbIndex = llvm::make_unique<DWARFGdbIndex>();
692  GdbIndex->parse(GdbIndexData);
693  return *GdbIndex;
694 }
695 
697  if (Abbrev)
698  return Abbrev.get();
699 
700  DataExtractor abbrData(DObj->getAbbrevSection(), isLittleEndian(), 0);
701 
702  Abbrev.reset(new DWARFDebugAbbrev());
703  Abbrev->extract(abbrData);
704  return Abbrev.get();
705 }
706 
708  if (AbbrevDWO)
709  return AbbrevDWO.get();
710 
711  DataExtractor abbrData(DObj->getAbbrevDWOSection(), isLittleEndian(), 0);
712  AbbrevDWO.reset(new DWARFDebugAbbrev());
713  AbbrevDWO->extract(abbrData);
714  return AbbrevDWO.get();
715 }
716 
718  if (Loc)
719  return Loc.get();
720 
721  Loc.reset(new DWARFDebugLoc);
722  // Assume all units have the same address byte size.
723  if (getNumCompileUnits()) {
724  DWARFDataExtractor LocData(*DObj, DObj->getLocSection(), isLittleEndian(),
726  Loc->parse(LocData);
727  }
728  return Loc.get();
729 }
730 
732  if (LocDWO)
733  return LocDWO.get();
734 
735  LocDWO.reset(new DWARFDebugLoclists());
736  // Assume all compile units have the same address byte size.
737  // FIXME: We don't need AddressSize for split DWARF since relocatable
738  // addresses cannot appear there. At the moment DWARFExpression requires it.
739  DataExtractor LocData(DObj->getLocDWOSection().Data, isLittleEndian(), 4);
740  // Use version 4. DWO does not support the DWARF v5 .debug_loclists yet and
741  // that means we are parsing the new style .debug_loc (pre-standatized version
742  // of the .debug_loclists).
743  LocDWO->parse(LocData, 4 /* Version */);
744  return LocDWO.get();
745 }
746 
748  if (Aranges)
749  return Aranges.get();
750 
751  Aranges.reset(new DWARFDebugAranges());
752  Aranges->generate(this);
753  return Aranges.get();
754 }
755 
757  if (DebugFrame)
758  return DebugFrame.get();
759 
760  // There's a "bug" in the DWARFv3 standard with respect to the target address
761  // size within debug frame sections. While DWARF is supposed to be independent
762  // of its container, FDEs have fields with size being "target address size",
763  // which isn't specified in DWARF in general. It's only specified for CUs, but
764  // .eh_frame can appear without a .debug_info section. Follow the example of
765  // other tools (libdwarf) and extract this from the container (ObjectFile
766  // provides this information). This problem is fixed in DWARFv4
767  // See this dwarf-discuss discussion for more details:
768  // http://lists.dwarfstd.org/htdig.cgi/dwarf-discuss-dwarfstd.org/2011-December/001173.html
769  DWARFDataExtractor debugFrameData(DObj->getDebugFrameSection(),
770  isLittleEndian(), DObj->getAddressSize());
771  DebugFrame.reset(new DWARFDebugFrame(getArch(), false /* IsEH */));
772  DebugFrame->parse(debugFrameData);
773  return DebugFrame.get();
774 }
775 
777  if (EHFrame)
778  return EHFrame.get();
779 
780  DWARFDataExtractor debugFrameData(DObj->getEHFrameSection(), isLittleEndian(),
781  DObj->getAddressSize());
782  DebugFrame.reset(new DWARFDebugFrame(getArch(), true /* IsEH */));
783  DebugFrame->parse(debugFrameData);
784  return DebugFrame.get();
785 }
786 
788  if (Macro)
789  return Macro.get();
790 
791  DataExtractor MacinfoData(DObj->getMacinfoSection(), isLittleEndian(), 0);
792  Macro.reset(new DWARFDebugMacro());
793  Macro->parse(MacinfoData);
794  return Macro.get();
795 }
796 
797 template <typename T>
798 static T &getAccelTable(std::unique_ptr<T> &Cache, const DWARFObject &Obj,
799  const DWARFSection &Section, StringRef StringSection,
800  bool IsLittleEndian) {
801  if (Cache)
802  return *Cache;
803  DWARFDataExtractor AccelSection(Obj, Section, IsLittleEndian, 0);
804  DataExtractor StrData(StringSection, IsLittleEndian, 0);
805  Cache.reset(new T(AccelSection, StrData));
806  if (Error E = Cache->extract())
807  llvm::consumeError(std::move(E));
808  return *Cache;
809 }
810 
812  return getAccelTable(Names, *DObj, DObj->getDebugNamesSection(),
813  DObj->getStringSection(), isLittleEndian());
814 }
815 
817  return getAccelTable(AppleNames, *DObj, DObj->getAppleNamesSection(),
818  DObj->getStringSection(), isLittleEndian());
819 }
820 
822  return getAccelTable(AppleTypes, *DObj, DObj->getAppleTypesSection(),
823  DObj->getStringSection(), isLittleEndian());
824 }
825 
827  return getAccelTable(AppleNamespaces, *DObj,
828  DObj->getAppleNamespacesSection(),
829  DObj->getStringSection(), isLittleEndian());
830 }
831 
833  return getAccelTable(AppleObjC, *DObj, DObj->getAppleObjCSection(),
834  DObj->getStringSection(), isLittleEndian());
835 }
836 
841  if (!ExpectedLineTable) {
842  dumpWarning(ExpectedLineTable.takeError());
843  return nullptr;
844  }
845  return *ExpectedLineTable;
846 }
847 
849  DWARFUnit *U, std::function<void(Error)> RecoverableErrorCallback) {
850  if (!Line)
851  Line.reset(new DWARFDebugLine);
852 
853  auto UnitDIE = U->getUnitDIE();
854  if (!UnitDIE)
855  return nullptr;
856 
857  auto Offset = toSectionOffset(UnitDIE.find(DW_AT_stmt_list));
858  if (!Offset)
859  return nullptr; // No line table for this compile unit.
860 
861  uint32_t stmtOffset = *Offset + U->getLineTableOffset();
862  // See if the line table is cached.
863  if (const DWARFLineTable *lt = Line->getLineTable(stmtOffset))
864  return lt;
865 
866  // Make sure the offset is good before we try to parse.
867  if (stmtOffset >= U->getLineSection().Data.size())
868  return nullptr;
869 
870  // We have to parse it first.
871  DWARFDataExtractor lineData(*DObj, U->getLineSection(), isLittleEndian(),
872  U->getAddressByteSize());
873  return Line->getOrParseLineTable(lineData, stmtOffset, *this, U,
874  RecoverableErrorCallback);
875 }
876 
877 void DWARFContext::parseNormalUnits() {
878  if (!NormalUnits.empty())
879  return;
880  DObj->forEachInfoSections([&](const DWARFSection &S) {
881  NormalUnits.addUnitsForSection(*this, S, DW_SECT_INFO);
882  });
883  NormalUnits.finishedInfoUnits();
884  DObj->forEachTypesSections([&](const DWARFSection &S) {
885  NormalUnits.addUnitsForSection(*this, S, DW_SECT_TYPES);
886  });
887 }
888 
889 void DWARFContext::parseDWOUnits(bool Lazy) {
890  if (!DWOUnits.empty())
891  return;
892  DObj->forEachInfoDWOSections([&](const DWARFSection &S) {
893  DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_INFO, Lazy);
894  });
895  DWOUnits.finishedInfoUnits();
896  DObj->forEachTypesDWOSections([&](const DWARFSection &S) {
897  DWOUnits.addUnitsForDWOSection(*this, S, DW_SECT_TYPES, Lazy);
898  });
899 }
900 
902  parseNormalUnits();
903  return dyn_cast_or_null<DWARFCompileUnit>(
904  NormalUnits.getUnitForOffset(Offset));
905 }
906 
907 DWARFCompileUnit *DWARFContext::getCompileUnitForAddress(uint64_t Address) {
908  // First, get the offset of the compile unit.
909  uint32_t CUOffset = getDebugAranges()->findAddress(Address);
910  // Retrieve the compile unit.
911  return getCompileUnitForOffset(CUOffset);
912 }
913 
915  DIEsForAddress Result;
916 
917  DWARFCompileUnit *CU = getCompileUnitForAddress(Address);
918  if (!CU)
919  return Result;
920 
921  Result.CompileUnit = CU;
922  Result.FunctionDIE = CU->getSubroutineForAddress(Address);
923 
924  std::vector<DWARFDie> Worklist;
925  Worklist.push_back(Result.FunctionDIE);
926  while (!Worklist.empty()) {
927  DWARFDie DIE = Worklist.back();
928  Worklist.pop_back();
929 
930  if (!DIE.isValid())
931  continue;
932 
933  if (DIE.getTag() == DW_TAG_lexical_block &&
934  DIE.addressRangeContainsAddress(Address)) {
935  Result.BlockDIE = DIE;
936  break;
937  }
938 
939  for (auto Child : DIE)
940  Worklist.push_back(Child);
941  }
942 
943  return Result;
944 }
945 
946 /// TODO: change input parameter from "uint64_t Address"
947 /// into "SectionedAddress Address"
949  uint64_t Address,
950  FunctionNameKind Kind,
951  std::string &FunctionName,
952  uint32_t &StartLine) {
953  // The address may correspond to instruction in some inlined function,
954  // so we have to build the chain of inlined functions and take the
955  // name of the topmost function in it.
956  SmallVector<DWARFDie, 4> InlinedChain;
957  CU->getInlinedChainForAddress(Address, InlinedChain);
958  if (InlinedChain.empty())
959  return false;
960 
961  const DWARFDie &DIE = InlinedChain[0];
962  bool FoundResult = false;
963  const char *Name = nullptr;
964  if (Kind != FunctionNameKind::None && (Name = DIE.getSubroutineName(Kind))) {
965  FunctionName = Name;
966  FoundResult = true;
967  }
968  if (auto DeclLineResult = DIE.getDeclLine()) {
969  StartLine = DeclLineResult;
970  FoundResult = true;
971  }
972 
973  return FoundResult;
974 }
975 
976 static Optional<uint64_t> getTypeSize(DWARFDie Type, uint64_t PointerSize) {
977  if (auto SizeAttr = Type.find(DW_AT_byte_size))
978  if (Optional<uint64_t> Size = SizeAttr->getAsUnsignedConstant())
979  return Size;
980 
981  switch (Type.getTag()) {
982  case DW_TAG_pointer_type:
983  case DW_TAG_reference_type:
984  case DW_TAG_rvalue_reference_type:
985  return PointerSize;
986  case DW_TAG_ptr_to_member_type: {
987  if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
988  if (BaseType.getTag() == DW_TAG_subroutine_type)
989  return 2 * PointerSize;
990  return PointerSize;
991  }
992  case DW_TAG_const_type:
993  case DW_TAG_volatile_type:
994  case DW_TAG_restrict_type:
995  case DW_TAG_typedef: {
996  if (DWARFDie BaseType = Type.getAttributeValueAsReferencedDie(DW_AT_type))
997  return getTypeSize(BaseType, PointerSize);
998  break;
999  }
1000  case DW_TAG_array_type: {
1002  if (!BaseType)
1003  return Optional<uint64_t>();
1004  Optional<uint64_t> BaseSize = getTypeSize(BaseType, PointerSize);
1005  if (!BaseSize)
1006  return Optional<uint64_t>();
1007  uint64_t Size = *BaseSize;
1008  for (DWARFDie Child : Type) {
1009  if (Child.getTag() != DW_TAG_subrange_type)
1010  continue;
1011 
1012  if (auto ElemCountAttr = Child.find(DW_AT_count))
1013  if (Optional<uint64_t> ElemCount =
1014  ElemCountAttr->getAsUnsignedConstant())
1015  Size *= *ElemCount;
1016  if (auto UpperBoundAttr = Child.find(DW_AT_upper_bound))
1017  if (Optional<int64_t> UpperBound =
1018  UpperBoundAttr->getAsSignedConstant()) {
1019  int64_t LowerBound = 0;
1020  if (auto LowerBoundAttr = Child.find(DW_AT_lower_bound))
1021  LowerBound = LowerBoundAttr->getAsSignedConstant().getValueOr(0);
1022  Size *= *UpperBound - LowerBound + 1;
1023  }
1024  }
1025  return Size;
1026  }
1027  default:
1028  break;
1029  }
1030  return Optional<uint64_t>();
1031 }
1032 
1033 void DWARFContext::addLocalsForDie(DWARFCompileUnit *CU, DWARFDie Subprogram,
1034  DWARFDie Die, std::vector<DILocal> &Result) {
1035  if (Die.getTag() == DW_TAG_variable ||
1036  Die.getTag() == DW_TAG_formal_parameter) {
1037  DILocal Local;
1038  if (auto NameAttr = Subprogram.find(DW_AT_name))
1039  if (Optional<const char *> Name = NameAttr->getAsCString())
1040  Local.FunctionName = *Name;
1041  if (auto LocationAttr = Die.find(DW_AT_location))
1042  if (Optional<ArrayRef<uint8_t>> Location = LocationAttr->getAsBlock())
1043  if (!Location->empty() && (*Location)[0] == DW_OP_fbreg)
1044  Local.FrameOffset =
1045  decodeSLEB128(Location->data() + 1, nullptr, Location->end());
1046  if (auto TagOffsetAttr = Die.find(DW_AT_LLVM_tag_offset))
1047  Local.TagOffset = TagOffsetAttr->getAsUnsignedConstant();
1048 
1049  if (auto Origin =
1050  Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1051  Die = Origin;
1052  if (auto NameAttr = Die.find(DW_AT_name))
1053  if (Optional<const char *> Name = NameAttr->getAsCString())
1054  Local.Name = *Name;
1055  if (auto Type = Die.getAttributeValueAsReferencedDie(DW_AT_type))
1056  Local.Size = getTypeSize(Type, getCUAddrSize());
1057  if (auto DeclFileAttr = Die.find(DW_AT_decl_file)) {
1058  if (const auto *LT = CU->getContext().getLineTableForUnit(CU))
1059  LT->getFileNameByIndex(
1060  DeclFileAttr->getAsUnsignedConstant().getValue(),
1061  CU->getCompilationDir(),
1063  Local.DeclFile);
1064  }
1065  if (auto DeclLineAttr = Die.find(DW_AT_decl_line))
1066  Local.DeclLine = DeclLineAttr->getAsUnsignedConstant().getValue();
1067 
1068  Result.push_back(Local);
1069  return;
1070  }
1071 
1072  if (Die.getTag() == DW_TAG_inlined_subroutine)
1073  if (auto Origin =
1074  Die.getAttributeValueAsReferencedDie(DW_AT_abstract_origin))
1075  Subprogram = Origin;
1076 
1077  for (auto Child : Die)
1078  addLocalsForDie(CU, Subprogram, Child, Result);
1079 }
1080 
1081 std::vector<DILocal>
1083  std::vector<DILocal> Result;
1084  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1085  if (!CU)
1086  return Result;
1087 
1088  DWARFDie Subprogram = CU->getSubroutineForAddress(Address.Address);
1089  if (Subprogram.isValid())
1090  addLocalsForDie(CU, Subprogram, Subprogram, Result);
1091  return Result;
1092 }
1093 
1095  DILineInfoSpecifier Spec) {
1096  DILineInfo Result;
1097 
1098  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1099  if (!CU)
1100  return Result;
1101 
1103  Result.FunctionName, Result.StartLine);
1104  if (Spec.FLIKind != FileLineInfoKind::None) {
1105  if (const DWARFLineTable *LineTable = getLineTableForUnit(CU)) {
1106  LineTable->getFileLineInfoForAddress(
1107  {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1108  Spec.FLIKind, Result);
1109  }
1110  }
1111  return Result;
1112 }
1113 
1115  object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Spec) {
1116  DILineInfoTable Lines;
1117  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1118  if (!CU)
1119  return Lines;
1120 
1121  std::string FunctionName = "<invalid>";
1122  uint32_t StartLine = 0;
1124  FunctionName, StartLine);
1125 
1126  // If the Specifier says we don't need FileLineInfo, just
1127  // return the top-most function at the starting address.
1128  if (Spec.FLIKind == FileLineInfoKind::None) {
1129  DILineInfo Result;
1130  Result.FunctionName = FunctionName;
1131  Result.StartLine = StartLine;
1132  Lines.push_back(std::make_pair(Address.Address, Result));
1133  return Lines;
1134  }
1135 
1136  const DWARFLineTable *LineTable = getLineTableForUnit(CU);
1137 
1138  // Get the index of row we're looking for in the line table.
1139  std::vector<uint32_t> RowVector;
1140  if (!LineTable->lookupAddressRange({Address.Address, Address.SectionIndex},
1141  Size, RowVector)) {
1142  return Lines;
1143  }
1144 
1145  for (uint32_t RowIndex : RowVector) {
1146  // Take file number and line/column from the row.
1147  const DWARFDebugLine::Row &Row = LineTable->Rows[RowIndex];
1148  DILineInfo Result;
1149  LineTable->getFileNameByIndex(Row.File, CU->getCompilationDir(),
1150  Spec.FLIKind, Result.FileName);
1151  Result.FunctionName = FunctionName;
1152  Result.Line = Row.Line;
1153  Result.Column = Row.Column;
1154  Result.StartLine = StartLine;
1155  Lines.push_back(std::make_pair(Row.Address.Address, Result));
1156  }
1157 
1158  return Lines;
1159 }
1160 
1163  DILineInfoSpecifier Spec) {
1164  DIInliningInfo InliningInfo;
1165 
1166  DWARFCompileUnit *CU = getCompileUnitForAddress(Address.Address);
1167  if (!CU)
1168  return InliningInfo;
1169 
1170  const DWARFLineTable *LineTable = nullptr;
1171  SmallVector<DWARFDie, 4> InlinedChain;
1172  CU->getInlinedChainForAddress(Address.Address, InlinedChain);
1173  if (InlinedChain.size() == 0) {
1174  // If there is no DIE for address (e.g. it is in unavailable .dwo file),
1175  // try to at least get file/line info from symbol table.
1176  if (Spec.FLIKind != FileLineInfoKind::None) {
1177  DILineInfo Frame;
1178  LineTable = getLineTableForUnit(CU);
1179  if (LineTable && LineTable->getFileLineInfoForAddress(
1180  {Address.Address, Address.SectionIndex},
1181  CU->getCompilationDir(), Spec.FLIKind, Frame))
1182  InliningInfo.addFrame(Frame);
1183  }
1184  return InliningInfo;
1185  }
1186 
1187  uint32_t CallFile = 0, CallLine = 0, CallColumn = 0, CallDiscriminator = 0;
1188  for (uint32_t i = 0, n = InlinedChain.size(); i != n; i++) {
1189  DWARFDie &FunctionDIE = InlinedChain[i];
1190  DILineInfo Frame;
1191  // Get function name if necessary.
1192  if (const char *Name = FunctionDIE.getSubroutineName(Spec.FNKind))
1193  Frame.FunctionName = Name;
1194  if (auto DeclLineResult = FunctionDIE.getDeclLine())
1195  Frame.StartLine = DeclLineResult;
1196  if (Spec.FLIKind != FileLineInfoKind::None) {
1197  if (i == 0) {
1198  // For the topmost frame, initialize the line table of this
1199  // compile unit and fetch file/line info from it.
1200  LineTable = getLineTableForUnit(CU);
1201  // For the topmost routine, get file/line info from line table.
1202  if (LineTable)
1203  LineTable->getFileLineInfoForAddress(
1204  {Address.Address, Address.SectionIndex}, CU->getCompilationDir(),
1205  Spec.FLIKind, Frame);
1206  } else {
1207  // Otherwise, use call file, call line and call column from
1208  // previous DIE in inlined chain.
1209  if (LineTable)
1210  LineTable->getFileNameByIndex(CallFile, CU->getCompilationDir(),
1211  Spec.FLIKind, Frame.FileName);
1212  Frame.Line = CallLine;
1213  Frame.Column = CallColumn;
1214  Frame.Discriminator = CallDiscriminator;
1215  }
1216  // Get call file/line/column of a current DIE.
1217  if (i + 1 < n) {
1218  FunctionDIE.getCallerFrame(CallFile, CallLine, CallColumn,
1219  CallDiscriminator);
1220  }
1221  }
1222  InliningInfo.addFrame(Frame);
1223  }
1224  return InliningInfo;
1225 }
1226 
1227 std::shared_ptr<DWARFContext>
1229  if (auto S = DWP.lock()) {
1230  DWARFContext *Ctxt = S->Context.get();
1231  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1232  }
1233 
1234  std::weak_ptr<DWOFile> *Entry = &DWOFiles[AbsolutePath];
1235 
1236  if (auto S = Entry->lock()) {
1237  DWARFContext *Ctxt = S->Context.get();
1238  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1239  }
1240 
1242  if (!CheckedForDWP) {
1243  SmallString<128> DWPName;
1245  this->DWPName.empty()
1246  ? (DObj->getFileName() + ".dwp").toStringRef(DWPName)
1247  : StringRef(this->DWPName));
1248  if (Obj) {
1249  Entry = &DWP;
1250  return Obj;
1251  } else {
1252  CheckedForDWP = true;
1253  // TODO: Should this error be handled (maybe in a high verbosity mode)
1254  // before falling back to .dwo files?
1255  consumeError(Obj.takeError());
1256  }
1257  }
1258 
1259  return object::ObjectFile::createObjectFile(AbsolutePath);
1260  }();
1261 
1262  if (!Obj) {
1263  // TODO: Actually report errors helpfully.
1264  consumeError(Obj.takeError());
1265  return nullptr;
1266  }
1267 
1268  auto S = std::make_shared<DWOFile>();
1269  S->File = std::move(Obj.get());
1270  S->Context = DWARFContext::create(*S->File.getBinary());
1271  *Entry = S;
1272  auto *Ctxt = S->Context.get();
1273  return std::shared_ptr<DWARFContext>(std::move(S), Ctxt);
1274 }
1275 
1276 static Error createError(const Twine &Reason, llvm::Error E) {
1277  return make_error<StringError>(Reason + toString(std::move(E)),
1279 }
1280 
1281 /// SymInfo contains information about symbol: it's address
1282 /// and section index which is -1LL for absolute symbols.
1283 struct SymInfo {
1284  uint64_t Address;
1285  uint64_t SectionIndex;
1286 };
1287 
1288 /// Returns the address of symbol relocation used against and a section index.
1289 /// Used for futher relocations computation. Symbol's section load address is
1291  const RelocationRef &Reloc,
1292  const LoadedObjectInfo *L,
1293  std::map<SymbolRef, SymInfo> &Cache) {
1294  SymInfo Ret = {0, (uint64_t)-1LL};
1296  object::symbol_iterator Sym = Reloc.getSymbol();
1297 
1298  std::map<SymbolRef, SymInfo>::iterator CacheIt = Cache.end();
1299  // First calculate the address of the symbol or section as it appears
1300  // in the object file
1301  if (Sym != Obj.symbol_end()) {
1302  bool New;
1303  std::tie(CacheIt, New) = Cache.insert({*Sym, {0, 0}});
1304  if (!New)
1305  return CacheIt->second;
1306 
1307  Expected<uint64_t> SymAddrOrErr = Sym->getAddress();
1308  if (!SymAddrOrErr)
1309  return createError("failed to compute symbol address: ",
1310  SymAddrOrErr.takeError());
1311 
1312  // Also remember what section this symbol is in for later
1313  auto SectOrErr = Sym->getSection();
1314  if (!SectOrErr)
1315  return createError("failed to get symbol section: ",
1316  SectOrErr.takeError());
1317 
1318  RSec = *SectOrErr;
1319  Ret.Address = *SymAddrOrErr;
1320  } else if (auto *MObj = dyn_cast<MachOObjectFile>(&Obj)) {
1321  RSec = MObj->getRelocationSection(Reloc.getRawDataRefImpl());
1322  Ret.Address = RSec->getAddress();
1323  }
1324 
1325  if (RSec != Obj.section_end())
1326  Ret.SectionIndex = RSec->getIndex();
1327 
1328  // If we are given load addresses for the sections, we need to adjust:
1329  // SymAddr = (Address of Symbol Or Section in File) -
1330  // (Address of Section in File) +
1331  // (Load Address of Section)
1332  // RSec is now either the section being targeted or the section
1333  // containing the symbol being targeted. In either case,
1334  // we need to perform the same computation.
1335  if (L && RSec != Obj.section_end())
1336  if (uint64_t SectionLoadAddress = L->getSectionLoadAddress(*RSec))
1337  Ret.Address += SectionLoadAddress - RSec->getAddress();
1338 
1339  if (CacheIt != Cache.end())
1340  CacheIt->second = Ret;
1341 
1342  return Ret;
1343 }
1344 
1345 static bool isRelocScattered(const object::ObjectFile &Obj,
1346  const RelocationRef &Reloc) {
1347  const MachOObjectFile *MachObj = dyn_cast<MachOObjectFile>(&Obj);
1348  if (!MachObj)
1349  return false;
1350  // MachO also has relocations that point to sections and
1351  // scattered relocations.
1352  auto RelocInfo = MachObj->getRelocation(Reloc.getRawDataRefImpl());
1353  return MachObj->isRelocationScattered(RelocInfo);
1354 }
1355 
1357  WithColor::error() << toString(std::move(E)) << '\n';
1358  return ErrorPolicy::Continue;
1359 }
1360 
1361 namespace {
1362 struct DWARFSectionMap final : public DWARFSection {
1363  RelocAddrMap Relocs;
1364 };
1365 
1366 class DWARFObjInMemory final : public DWARFObject {
1367  bool IsLittleEndian;
1368  uint8_t AddressSize;
1369  StringRef FileName;
1370  const object::ObjectFile *Obj = nullptr;
1371  std::vector<SectionName> SectionNames;
1372 
1373  using InfoSectionMap = MapVector<object::SectionRef, DWARFSectionMap,
1374  std::map<object::SectionRef, unsigned>>;
1375 
1376  InfoSectionMap InfoSections;
1377  InfoSectionMap TypesSections;
1378  InfoSectionMap InfoDWOSections;
1379  InfoSectionMap TypesDWOSections;
1380 
1381  DWARFSectionMap LocSection;
1382  DWARFSectionMap LocListsSection;
1383  DWARFSectionMap LineSection;
1384  DWARFSectionMap RangeSection;
1385  DWARFSectionMap RnglistsSection;
1386  DWARFSectionMap StringOffsetSection;
1387  DWARFSectionMap LineDWOSection;
1388  DWARFSectionMap LocDWOSection;
1389  DWARFSectionMap StringOffsetDWOSection;
1390  DWARFSectionMap RangeDWOSection;
1391  DWARFSectionMap RnglistsDWOSection;
1392  DWARFSectionMap AddrSection;
1393  DWARFSectionMap AppleNamesSection;
1394  DWARFSectionMap AppleTypesSection;
1395  DWARFSectionMap AppleNamespacesSection;
1396  DWARFSectionMap AppleObjCSection;
1397  DWARFSectionMap DebugNamesSection;
1398  DWARFSectionMap PubNamesSection;
1399  DWARFSectionMap PubTypesSection;
1400  DWARFSectionMap GnuPubNamesSection;
1401  DWARFSectionMap GnuPubTypesSection;
1402 
1403  DWARFSectionMap *mapNameToDWARFSection(StringRef Name) {
1405  .Case("debug_loc", &LocSection)
1406  .Case("debug_loclists", &LocListsSection)
1407  .Case("debug_line", &LineSection)
1408  .Case("debug_str_offsets", &StringOffsetSection)
1409  .Case("debug_ranges", &RangeSection)
1410  .Case("debug_rnglists", &RnglistsSection)
1411  .Case("debug_loc.dwo", &LocDWOSection)
1412  .Case("debug_line.dwo", &LineDWOSection)
1413  .Case("debug_names", &DebugNamesSection)
1414  .Case("debug_rnglists.dwo", &RnglistsDWOSection)
1415  .Case("debug_str_offsets.dwo", &StringOffsetDWOSection)
1416  .Case("debug_addr", &AddrSection)
1417  .Case("apple_names", &AppleNamesSection)
1418  .Case("debug_pubnames", &PubNamesSection)
1419  .Case("debug_pubtypes", &PubTypesSection)
1420  .Case("debug_gnu_pubnames", &GnuPubNamesSection)
1421  .Case("debug_gnu_pubtypes", &GnuPubTypesSection)
1422  .Case("apple_types", &AppleTypesSection)
1423  .Case("apple_namespaces", &AppleNamespacesSection)
1424  .Case("apple_namespac", &AppleNamespacesSection)
1425  .Case("apple_objc", &AppleObjCSection)
1426  .Default(nullptr);
1427  }
1428 
1429  StringRef AbbrevSection;
1430  StringRef ARangeSection;
1431  StringRef DebugFrameSection;
1432  StringRef EHFrameSection;
1433  StringRef StringSection;
1434  StringRef MacinfoSection;
1435  StringRef AbbrevDWOSection;
1436  StringRef StringDWOSection;
1437  StringRef CUIndexSection;
1438  StringRef GdbIndexSection;
1439  StringRef TUIndexSection;
1440  StringRef LineStringSection;
1441 
1442  // A deque holding section data whose iterators are not invalidated when
1443  // new decompressed sections are inserted at the end.
1444  std::deque<SmallString<0>> UncompressedSections;
1445 
1446  StringRef *mapSectionToMember(StringRef Name) {
1447  if (DWARFSection *Sec = mapNameToDWARFSection(Name))
1448  return &Sec->Data;
1450  .Case("debug_abbrev", &AbbrevSection)
1451  .Case("debug_aranges", &ARangeSection)
1452  .Case("debug_frame", &DebugFrameSection)
1453  .Case("eh_frame", &EHFrameSection)
1454  .Case("debug_str", &StringSection)
1455  .Case("debug_macinfo", &MacinfoSection)
1456  .Case("debug_abbrev.dwo", &AbbrevDWOSection)
1457  .Case("debug_str.dwo", &StringDWOSection)
1458  .Case("debug_cu_index", &CUIndexSection)
1459  .Case("debug_tu_index", &TUIndexSection)
1460  .Case("gdb_index", &GdbIndexSection)
1461  .Case("debug_line_str", &LineStringSection)
1462  // Any more debug info sections go here.
1463  .Default(nullptr);
1464  }
1465 
1466  /// If Sec is compressed section, decompresses and updates its contents
1467  /// provided by Data. Otherwise leaves it unchanged.
1468  Error maybeDecompress(const object::SectionRef &Sec, StringRef Name,
1469  StringRef &Data) {
1470  if (!Decompressor::isCompressed(Sec))
1471  return Error::success();
1472 
1473  Expected<Decompressor> Decompressor =
1474  Decompressor::create(Name, Data, IsLittleEndian, AddressSize == 8);
1475  if (!Decompressor)
1476  return Decompressor.takeError();
1477 
1478  SmallString<0> Out;
1479  if (auto Err = Decompressor->resizeAndDecompress(Out))
1480  return Err;
1481 
1482  UncompressedSections.push_back(std::move(Out));
1483  Data = UncompressedSections.back();
1484 
1485  return Error::success();
1486  }
1487 
1488 public:
1489  DWARFObjInMemory(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1490  uint8_t AddrSize, bool IsLittleEndian)
1491  : IsLittleEndian(IsLittleEndian) {
1492  for (const auto &SecIt : Sections) {
1493  if (StringRef *SectionData = mapSectionToMember(SecIt.first()))
1494  *SectionData = SecIt.second->getBuffer();
1495  else if (SecIt.first() == "debug_info")
1496  // Find debug_info and debug_types data by section rather than name as
1497  // there are multiple, comdat grouped, of these sections.
1498  InfoSections[SectionRef()].Data = SecIt.second->getBuffer();
1499  else if (SecIt.first() == "debug_info.dwo")
1500  InfoDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1501  else if (SecIt.first() == "debug_types")
1502  TypesSections[SectionRef()].Data = SecIt.second->getBuffer();
1503  else if (SecIt.first() == "debug_types.dwo")
1504  TypesDWOSections[SectionRef()].Data = SecIt.second->getBuffer();
1505  }
1506  }
1507  DWARFObjInMemory(const object::ObjectFile &Obj, const LoadedObjectInfo *L,
1508  function_ref<ErrorPolicy(Error)> HandleError)
1509  : IsLittleEndian(Obj.isLittleEndian()),
1510  AddressSize(Obj.getBytesInAddress()), FileName(Obj.getFileName()),
1511  Obj(&Obj) {
1512 
1513  StringMap<unsigned> SectionAmountMap;
1514  for (const SectionRef &Section : Obj.sections()) {
1515  StringRef Name;
1516  Section.getName(Name);
1517  ++SectionAmountMap[Name];
1518  SectionNames.push_back({ Name, true });
1519 
1520  // Skip BSS and Virtual sections, they aren't interesting.
1521  if (Section.isBSS() || Section.isVirtual())
1522  continue;
1523 
1524  // Skip sections stripped by dsymutil.
1525  if (Section.isStripped())
1526  continue;
1527 
1528  StringRef Data;
1529  section_iterator RelocatedSection = Section.getRelocatedSection();
1530  // Try to obtain an already relocated version of this section.
1531  // Else use the unrelocated section from the object file. We'll have to
1532  // apply relocations ourselves later.
1533  if (!L || !L->getLoadedSectionContents(*RelocatedSection, Data)) {
1534  Expected<StringRef> E = Section.getContents();
1535  if (E)
1536  Data = *E;
1537  else
1538  // maybeDecompress below will error.
1539  consumeError(E.takeError());
1540  }
1541 
1542  if (auto Err = maybeDecompress(Section, Name, Data)) {
1543  ErrorPolicy EP = HandleError(createError(
1544  "failed to decompress '" + Name + "', ", std::move(Err)));
1545  if (EP == ErrorPolicy::Halt)
1546  return;
1547  continue;
1548  }
1549 
1550  // Compressed sections names in GNU style starts from ".z",
1551  // at this point section is decompressed and we drop compression prefix.
1552  Name = Name.substr(
1553  Name.find_first_not_of("._z")); // Skip ".", "z" and "_" prefixes.
1554 
1555  // Map platform specific debug section names to DWARF standard section
1556  // names.
1557  Name = Obj.mapDebugSectionName(Name);
1558 
1559  if (StringRef *SectionData = mapSectionToMember(Name)) {
1560  *SectionData = Data;
1561  if (Name == "debug_ranges") {
1562  // FIXME: Use the other dwo range section when we emit it.
1563  RangeDWOSection.Data = Data;
1564  }
1565  } else if (Name == "debug_info") {
1566  // Find debug_info and debug_types data by section rather than name as
1567  // there are multiple, comdat grouped, of these sections.
1568  InfoSections[Section].Data = Data;
1569  } else if (Name == "debug_info.dwo") {
1570  InfoDWOSections[Section].Data = Data;
1571  } else if (Name == "debug_types") {
1572  TypesSections[Section].Data = Data;
1573  } else if (Name == "debug_types.dwo") {
1574  TypesDWOSections[Section].Data = Data;
1575  }
1576 
1577  if (RelocatedSection == Obj.section_end())
1578  continue;
1579 
1580  StringRef RelSecName;
1581  StringRef RelSecData;
1582  RelocatedSection->getName(RelSecName);
1583 
1584  // If the section we're relocating was relocated already by the JIT,
1585  // then we used the relocated version above, so we do not need to process
1586  // relocations for it now.
1587  if (L && L->getLoadedSectionContents(*RelocatedSection, RelSecData))
1588  continue;
1589 
1590  // In Mach-o files, the relocations do not need to be applied if
1591  // there is no load offset to apply. The value read at the
1592  // relocation point already factors in the section address
1593  // (actually applying the relocations will produce wrong results
1594  // as the section address will be added twice).
1595  if (!L && isa<MachOObjectFile>(&Obj))
1596  continue;
1597 
1598  RelSecName = RelSecName.substr(
1599  RelSecName.find_first_not_of("._z")); // Skip . and _ prefixes.
1600 
1601  // TODO: Add support for relocations in other sections as needed.
1602  // Record relocations for the debug_info and debug_line sections.
1603  DWARFSectionMap *Sec = mapNameToDWARFSection(RelSecName);
1604  RelocAddrMap *Map = Sec ? &Sec->Relocs : nullptr;
1605  if (!Map) {
1606  // Find debug_info and debug_types relocs by section rather than name
1607  // as there are multiple, comdat grouped, of these sections.
1608  if (RelSecName == "debug_info")
1609  Map = &static_cast<DWARFSectionMap &>(InfoSections[*RelocatedSection])
1610  .Relocs;
1611  else if (RelSecName == "debug_info.dwo")
1612  Map = &static_cast<DWARFSectionMap &>(
1613  InfoDWOSections[*RelocatedSection])
1614  .Relocs;
1615  else if (RelSecName == "debug_types")
1616  Map =
1617  &static_cast<DWARFSectionMap &>(TypesSections[*RelocatedSection])
1618  .Relocs;
1619  else if (RelSecName == "debug_types.dwo")
1620  Map = &static_cast<DWARFSectionMap &>(
1621  TypesDWOSections[*RelocatedSection])
1622  .Relocs;
1623  else
1624  continue;
1625  }
1626 
1627  if (Section.relocation_begin() == Section.relocation_end())
1628  continue;
1629 
1630  // Symbol to [address, section index] cache mapping.
1631  std::map<SymbolRef, SymInfo> AddrCache;
1632  bool (*Supports)(uint64_t);
1634  std::tie(Supports, Resolver) = getRelocationResolver(Obj);
1635  for (const RelocationRef &Reloc : Section.relocations()) {
1636  // FIXME: it's not clear how to correctly handle scattered
1637  // relocations.
1638  if (isRelocScattered(Obj, Reloc))
1639  continue;
1640 
1641  Expected<SymInfo> SymInfoOrErr =
1642  getSymbolInfo(Obj, Reloc, L, AddrCache);
1643  if (!SymInfoOrErr) {
1644  if (HandleError(SymInfoOrErr.takeError()) == ErrorPolicy::Halt)
1645  return;
1646  continue;
1647  }
1648 
1649  // Check if Resolver can handle this relocation type early so as not to
1650  // handle invalid cases in DWARFDataExtractor.
1651  //
1652  // TODO Don't store Resolver in every RelocAddrEntry.
1653  if (Supports && Supports(Reloc.getType())) {
1654  auto I = Map->try_emplace(
1655  Reloc.getOffset(),
1656  RelocAddrEntry{SymInfoOrErr->SectionIndex, Reloc,
1657  SymInfoOrErr->Address,
1658  Optional<object::RelocationRef>(), 0, Resolver});
1659  // If we didn't successfully insert that's because we already had a
1660  // relocation for that offset. Store it as a second relocation in the
1661  // same RelocAddrEntry instead.
1662  if (!I.second) {
1663  RelocAddrEntry &entry = I.first->getSecond();
1664  if (entry.Reloc2) {
1665  ErrorPolicy EP = HandleError(createError(
1666  "At most two relocations per offset are supported"));
1667  if (EP == ErrorPolicy::Halt)
1668  return;
1669  }
1670  entry.Reloc2 = Reloc;
1671  entry.SymbolValue2 = SymInfoOrErr->Address;
1672  }
1673  } else {
1675  Reloc.getTypeName(Type);
1676  ErrorPolicy EP = HandleError(
1677  createError("failed to compute relocation: " + Type + ", ",
1678  errorCodeToError(object_error::parse_failed)));
1679  if (EP == ErrorPolicy::Halt)
1680  return;
1681  }
1682  }
1683  }
1684 
1685  for (SectionName &S : SectionNames)
1686  if (SectionAmountMap[S.Name] > 1)
1687  S.IsNameUnique = false;
1688  }
1689 
1691  uint64_t Pos) const override {
1692  auto &Sec = static_cast<const DWARFSectionMap &>(S);
1693  RelocAddrMap::const_iterator AI = Sec.Relocs.find(Pos);
1694  if (AI == Sec.Relocs.end())
1695  return None;
1696  return AI->second;
1697  }
1698 
1699  const object::ObjectFile *getFile() const override { return Obj; }
1700 
1701  ArrayRef<SectionName> getSectionNames() const override {
1702  return SectionNames;
1703  }
1704 
1705  bool isLittleEndian() const override { return IsLittleEndian; }
1706  StringRef getAbbrevDWOSection() const override { return AbbrevDWOSection; }
1707  const DWARFSection &getLineDWOSection() const override {
1708  return LineDWOSection;
1709  }
1710  const DWARFSection &getLocDWOSection() const override {
1711  return LocDWOSection;
1712  }
1713  StringRef getStringDWOSection() const override { return StringDWOSection; }
1714  const DWARFSection &getStringOffsetDWOSection() const override {
1715  return StringOffsetDWOSection;
1716  }
1717  const DWARFSection &getRangeDWOSection() const override {
1718  return RangeDWOSection;
1719  }
1720  const DWARFSection &getRnglistsDWOSection() const override {
1721  return RnglistsDWOSection;
1722  }
1723  const DWARFSection &getAddrSection() const override { return AddrSection; }
1724  StringRef getCUIndexSection() const override { return CUIndexSection; }
1725  StringRef getGdbIndexSection() const override { return GdbIndexSection; }
1726  StringRef getTUIndexSection() const override { return TUIndexSection; }
1727 
1728  // DWARF v5
1729  const DWARFSection &getStringOffsetSection() const override {
1730  return StringOffsetSection;
1731  }
1732  StringRef getLineStringSection() const override { return LineStringSection; }
1733 
1734  // Sections for DWARF5 split dwarf proposal.
1735  void forEachInfoDWOSections(
1736  function_ref<void(const DWARFSection &)> F) const override {
1737  for (auto &P : InfoDWOSections)
1738  F(P.second);
1739  }
1740  void forEachTypesDWOSections(
1741  function_ref<void(const DWARFSection &)> F) const override {
1742  for (auto &P : TypesDWOSections)
1743  F(P.second);
1744  }
1745 
1746  StringRef getAbbrevSection() const override { return AbbrevSection; }
1747  const DWARFSection &getLocSection() const override { return LocSection; }
1748  const DWARFSection &getLoclistsSection() const override { return LocListsSection; }
1749  StringRef getARangeSection() const override { return ARangeSection; }
1750  StringRef getDebugFrameSection() const override { return DebugFrameSection; }
1751  StringRef getEHFrameSection() const override { return EHFrameSection; }
1752  const DWARFSection &getLineSection() const override { return LineSection; }
1753  StringRef getStringSection() const override { return StringSection; }
1754  const DWARFSection &getRangeSection() const override { return RangeSection; }
1755  const DWARFSection &getRnglistsSection() const override {
1756  return RnglistsSection;
1757  }
1758  StringRef getMacinfoSection() const override { return MacinfoSection; }
1759  const DWARFSection &getPubNamesSection() const override { return PubNamesSection; }
1760  const DWARFSection &getPubTypesSection() const override { return PubTypesSection; }
1761  const DWARFSection &getGnuPubNamesSection() const override {
1762  return GnuPubNamesSection;
1763  }
1764  const DWARFSection &getGnuPubTypesSection() const override {
1765  return GnuPubTypesSection;
1766  }
1767  const DWARFSection &getAppleNamesSection() const override {
1768  return AppleNamesSection;
1769  }
1770  const DWARFSection &getAppleTypesSection() const override {
1771  return AppleTypesSection;
1772  }
1773  const DWARFSection &getAppleNamespacesSection() const override {
1774  return AppleNamespacesSection;
1775  }
1776  const DWARFSection &getAppleObjCSection() const override {
1777  return AppleObjCSection;
1778  }
1779  const DWARFSection &getDebugNamesSection() const override {
1780  return DebugNamesSection;
1781  }
1782 
1783  StringRef getFileName() const override { return FileName; }
1784  uint8_t getAddressSize() const override { return AddressSize; }
1785  void forEachInfoSections(
1786  function_ref<void(const DWARFSection &)> F) const override {
1787  for (auto &P : InfoSections)
1788  F(P.second);
1789  }
1790  void forEachTypesSections(
1791  function_ref<void(const DWARFSection &)> F) const override {
1792  for (auto &P : TypesSections)
1793  F(P.second);
1794  }
1795 };
1796 } // namespace
1797 
1798 std::unique_ptr<DWARFContext>
1800  function_ref<ErrorPolicy(Error)> HandleError,
1801  std::string DWPName) {
1802  auto DObj = llvm::make_unique<DWARFObjInMemory>(Obj, L, HandleError);
1803  return llvm::make_unique<DWARFContext>(std::move(DObj), std::move(DWPName));
1804 }
1805 
1806 std::unique_ptr<DWARFContext>
1807 DWARFContext::create(const StringMap<std::unique_ptr<MemoryBuffer>> &Sections,
1808  uint8_t AddrSize, bool isLittleEndian) {
1809  auto DObj =
1810  llvm::make_unique<DWARFObjInMemory>(Sections, AddrSize, isLittleEndian);
1811  return llvm::make_unique<DWARFContext>(std::move(DObj), "");
1812 }
1813 
1815  // Detect the architecture from the object file. We usually don't need OS
1816  // info to lookup a target and create register info.
1817  Triple TT;
1818  TT.setArch(Triple::ArchType(Obj.getArch()));
1821  std::string TargetLookupError;
1822  const Target *TheTarget =
1823  TargetRegistry::lookupTarget(TT.str(), TargetLookupError);
1824  if (!TargetLookupError.empty())
1826  TargetLookupError.c_str());
1827  RegInfo.reset(TheTarget->createMCRegInfo(TT.str()));
1828  return Error::success();
1829 }
1830 
1832  // In theory, different compile units may have different address byte
1833  // sizes, but for simplicity we just use the address byte size of the
1834  // last compile unit. In practice the address size field is repeated across
1835  // various DWARF headers (at least in version 5) to make it easier to dump
1836  // them independently, not to enable varying the address size.
1837  uint8_t Addr = 0;
1838  for (const auto &CU : compile_units()) {
1839  Addr = CU->getAddressByteSize();
1840  break;
1841  }
1842  return Addr;
1843 }
1844 
1846  handleAllErrors(std::move(Warning), [](ErrorInfoBase &Info) {
1847  WithColor::warning() << Info.message() << '\n';
1848  });
1849 }
const DWARFUnitIndex & getTUIndex()
uint64_t CallInst * C
uint32_t StartLine
Definition: DIContext.h:36
static Expected< OwningBinary< ObjectFile > > createObjectFile(StringRef ObjectPath)
Definition: ObjectFile.cpp:163
void getInlinedChainForAddress(uint64_t Address, SmallVectorImpl< DWARFDie > &InlinedChain)
getInlinedChainForAddress - fetches inlined chain for a given address.
Definition: DWARFUnit.cpp:637
const DWARFDebugFrame * getEHFrame()
Get a pointer to the parsed eh frame information object.
std::string DeclFile
Definition: DIContext.h:118
uint32_t Discriminator
Definition: DIContext.h:39
const DWARFDebugFrame * getDebugFrame()
Get a pointer to the parsed frame information object.
unsigned getMaxDWOVersion()
Definition: DWARFContext.h:239
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
static void dumpStringOffsetsSection(raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, const DWARFSection &StringOffsetsSection, StringRef StringSection, DWARFContext::unit_iterator_range Units, bool LittleEndian, unsigned MaxVersion)
bool isValid() const
Definition: DWARFDie.h:50
uint8_t[16] uuid_t
Output a formatted UUID with dash separators.
Definition: raw_ostream.h:218
std::string FileName
Definition: DIContext.h:31
Optional< int64_t > FrameOffset
Definition: DIContext.h:120
static void dumpLoclistsSection(raw_ostream &OS, DIDumpOptions DumpOpts, DWARFDataExtractor Data, const MCRegisterInfo *MRI, Optional< uint64_t > DumpOffset)
unit_iterator_range dwo_type_units()
Get type units in the DWO context.
Definition: DWARFContext.h:181
A parsed .debug_frame or .eh_frame section.
This class represents lattice values for constants.
Definition: AllocatorList.h:23
Represents structure for holding and parsing .debug_pub* tables.
A class representing the header of a list table such as the range list table in the ...
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:269
void dump(raw_ostream &OS, const MCRegisterInfo *RegInfo, Optional< uint64_t > Offset) const
Print the location lists found within the debug_loc section.
std::pair< bool(*)(uint64_t), RelocationResolver > getRelocationResolver(const ObjectFile &Obj)
amdgpu Simplify well known AMD library false FunctionCallee Value const Twine & Name
ErrorPolicy
Used as a return value for a error callback passed to DWARF context.
Definition: DWARFContext.h:53
bool addressRangeContainsAddress(const uint64_t Address) const
Definition: DWARFDie.cpp:507
void setVendor(VendorType Kind)
setVendor - Set the vendor (second) component of the triple to a known type.
Definition: Triple.cpp:1172
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
void push_back(const T &Elt)
Definition: SmallVector.h:211
DWARFGdbIndex & getGdbIndex()
std::shared_ptr< DWARFContext > getDWOContext(StringRef AbsolutePath)
static raw_ostream & error()
Convenience method for printing "error: " to stderr.
Definition: WithColor.cpp:60
unsigned getNumDWOCompileUnits()
Get the number of compile units in the DWO context.
Definition: DWARFContext.h:202
constexpr T getValueOr(U &&value) const LLVM_LVALUE_FUNCTION
Definition: Optional.h:266
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:123
bool handleDebugLine()
Verify the information in the .debug_line section.
An efficient, type-erasing, non-owning reference to a callable.
Definition: STLExtras.h:116
uint8_t getCUAddrSize()
Get address size from CUs.
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...
bool getFileNameByIndex(uint64_t FileIndex, StringRef CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, std::string &Result) const
Extracts filename by its index in filename table in prologue.
This class is the base class for all object file types.
Definition: ObjectFile.h:226
virtual std::string message() const
Return the error message as a string.
Definition: Error.h:56
static raw_ostream & warning()
Convenience method for printing "warning: " to stderr.
Definition: WithColor.cpp:62
This class implements a map that also provides access to all stored values in a deterministic order...
Definition: MapVector.h:37
Optional< uint64_t > TagOffset
Definition: DIContext.h:122
const DWARFDebugLine::LineTable * getLineTableForUnit(DWARFUnit *U)
Get a pointer to a parsed line table corresponding to a compile unit.
DWARFDie getAttributeValueAsReferencedDie(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE as the referenced DIE.
Definition: DWARFDie.cpp:424
unsigned getNumTypeUnits()
Get the number of type units in this context.
Definition: DWARFContext.h:196
StringRef getData() const
Get the data pointed to by this extractor.
Definition: DataExtractor.h:54
F(f)
unit_iterator_range dwo_info_section_units()
Get units from .debug_info..dwo in the DWO context.
Definition: DWARFContext.h:164
Error extract(DWARFDataExtractor Data, uint32_t *OffsetPtr)
Extract the table header and the array of offsets.
void setOS(OSType Kind)
setOS - Set the operating system (third) component of the triple to a known type. ...
Definition: Triple.cpp:1176
void addFrame(const DILineInfo &Frame)
Definition: DIContext.h:97
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:127
static void dumpRnglistsSection(raw_ostream &OS, DWARFDataExtractor &rnglistData, llvm::function_ref< Optional< object::SectionedAddress >(uint32_t)> LookupPooledAddress, DIDumpOptions DumpOpts)
Error takeError()
Take ownership of the stored error.
Definition: Error.h:552
static const Target * lookupTarget(const std::string &Triple, std::string &Error)
lookupTarget - Lookup a target based on a target triple.
bool getFileLineInfoForAddress(object::SectionedAddress Address, const char *CompDir, DILineInfoSpecifier::FileLineInfoKind Kind, DILineInfo &Result) const
Fills the Result argument with the file and line information corresponding to Address.
Base class for error info classes.
Definition: Error.h:48
void addUnitsForSection(DWARFContext &C, const DWARFSection &Section, DWARFSectionKind SectionKind)
Read units from a .debug_info or .debug_types section.
Definition: DWARFUnit.cpp:36
Optional< object::RelocationRef > Reloc2
Definition: DWARFRelocMap.h:24
StringSwitch & Case(StringLiteral S, T Value)
Definition: StringSwitch.h:67
bool handleDebugInfo()
Verify the information in the .debug_info and .debug_types sections.
raw_ostream & write_uuid(const uuid_t UUID)
A format-neutral container for source line information.
Definition: DIContext.h:30
DWARFDie getSubroutineForAddress(uint64_t Address)
Returns subprogram DIE with address range encompassing the provided address.
Definition: DWARFUnit.cpp:622
void dump(raw_ostream &OS, uint64_t BaseAddr, const MCRegisterInfo *RegInfo, Optional< uint64_t > Offset) const
object::SectionedAddress Address
The program-counter value corresponding to a machine instruction generated by the compiler and sectio...
Definition: BitVector.h:937
std::string toString(Error E)
Write all error messages (if any) in E to a string.
Definition: Error.h:966
bool lookupAddressRange(object::SectionedAddress Address, uint64_t Size, std::vector< uint32_t > &Result) const
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)
TODO: change input parameter from "uint64_t Address" into "SectionedAddress Address".
Triple::ArchType getArch() const
Definition: DWARFContext.h:370
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:80
DwarfFormat
Constants that define the DWARF format as 32 or 64 bit.
Definition: Dwarf.h:65
unit_iterator_range normal_units()
Get all normal compile/type units in this context.
Definition: DWARFContext.h:158
const char * getCompilationDir()
Definition: DWARFUnit.cpp:345
FunctionNameKind FNKind
Definition: DIContext.h:136
LLVM_NODISCARD StringRef drop_front(size_t N=1) const
Return a StringRef equal to &#39;this&#39; but with the first N elements dropped.
Definition: StringRef.h:620
A class representing an address table as specified in DWARF v5.
unsigned getNumCompileUnits()
Get the number of compile units in this context.
Definition: DWARFContext.h:190
const DWARFSection & getLineSection() const
Definition: DWARFUnit.h:292
int64_t decodeSLEB128(const uint8_t *p, unsigned *n=nullptr, const uint8_t *end=nullptr, const char **error=nullptr)
Utility function to decode a SLEB128 value.
Definition: LEB128.h:161
unit_iterator_range compile_units()
Get compile units in this context.
Definition: DWARFContext.h:152
FileLineInfoKind FLIKind
Definition: DIContext.h:135
LLVM_NODISCARD R Default(T Value)
Definition: StringSwitch.h:181
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:545
virtual uint64_t getSectionLoadAddress(const object::SectionRef &Sec) const
Obtain the Load Address of a section by SectionRef.
Definition: DIContext.h:254
Tagged union holding either a T or a Error.
Definition: CachePruning.h:22
LLVM_NODISCARD StringRef substr(size_t Start, size_t N=npos) const
Return a reference to the substring from [Start, Start + N).
Definition: StringRef.h:578
uint64_t Size
The contribution size not including the header.
Definition: DWARFUnit.h:171
const MCRegisterInfo * getRegisterInfo() const
Definition: DWARFContext.h:344
unsigned getNumDWOTypeUnits()
Get the number of type units in the DWO context.
Definition: DWARFContext.h:208
uint8_t getAddressByteSize() const
Definition: DWARFUnit.h:283
content_iterator< SectionRef > section_iterator
Definition: ObjectFile.h:48
bool verify(raw_ostream &OS, DIDumpOptions DumpOpts={}) override
const DWARFDebugAranges * getDebugAranges()
Get a pointer to the parsed DebugAranges object.
LLVM_NODISCARD size_t size() const
size - Get the string size.
Definition: StringRef.h:130
const DWARFDebugAbbrev * getDebugAbbrev()
Get a pointer to the parsed DebugAbbrev object.
section_iterator_range sections() const
Definition: ObjectFile.h:315
bool isLittleEndian() const
Get the endianness for this extractor.
Definition: DataExtractor.h:56
static Optional< uint64_t > getTypeSize(DWARFDie Type, uint64_t PointerSize)
const std::string & str() const
Definition: Triple.h:365
Analysis containing CSE Info
Definition: CSEInfo.cpp:20
uint64_t DeclLine
Definition: DIContext.h:119
uint64_t getDeclLine() const
Returns the declaration line (start line) for a DIE, assuming it specifies a subprogram.
Definition: DWARFDie.cpp:541
Expected< section_iterator > getSection() const
Get section this symbol is defined in reference to.
Definition: ObjectFile.h:400
void dump(raw_ostream &OS, const MCRegisterInfo *MRI, Optional< uint64_t > Offset) const
Dump the section data into the given stream.
MCRegisterInfo base class - We assume that the target defines a static array of MCRegisterDesc object...
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:167
unit_iterator_range info_section_units()
Get units from .debug_info in this context.
Definition: DWARFContext.h:137
virtual StringRef mapDebugSectionName(StringRef Name) const
Maps a debug section name to a standard DWARF section name.
Definition: ObjectFile.h:335
static Expected< StringRef > getFileName(const DebugStringTableSubsectionRef &Strings, const DebugChecksumsSubsectionRef &Checksums, uint32_t FileID)
uint8_t getAddrSize() const
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:42
Utility class that carries the DWARF compile/type unit and the debug info entry in an object...
Definition: DWARFDie.h:42
unsigned getMaxVersion()
Definition: DWARFContext.h:233
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.
unit_iterator_range dwo_types_section_units()
Get units from .debug_types.dwo in the DWO context.
Definition: DWARFContext.h:171
uint32_t Column
Definition: DIContext.h:35
unsigned const MachineRegisterInfo * MRI
virtual uint8_t getBytesInAddress() const =0
The number of bytes used to represent an address in this object file format.
const DWARFDebugLoclists * getDebugLocDWO()
Get a pointer to the parsed DebugLoc object.
The instances of the Type class are immutable: once they are created, they are never changed...
Definition: Type.h:45
Controls which fields of DILineInfo container should be filled with data.
Definition: DIContext.h:131
DIDumpOptions noImplicitRecursion() const
Return the options with RecurseDepth set to 0 unless explicitly required.
Definition: DIContext.h:190
uint16_t getVersion() const
static void dumpAddrSection(raw_ostream &OS, DWARFDataExtractor &AddrData, DIDumpOptions DumpOpts, uint16_t Version, uint8_t AddrSize)
LineTable parseNext(function_ref< void(Error)> RecoverableErrorCallback, function_ref< void(Error)> UnrecoverableErrorCallback, raw_ostream *OS=nullptr)
Get the next line table from the section.
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:87
const DWARFDebugMacro * getDebugMacro()
Get a pointer to the parsed DebugMacro object.
A format-neutral container for inlined code description.
Definition: DIContext.h:77
A structured debug information entry.
Definition: DIE.h:700
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:249
Interface for looking up the initializer for a variable name, used by Init::resolveReferences.
Definition: Record.h:1856
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 void dumpWarning(Error Warning)
Dump Error as warning message to stderr.
static Error createError(const Twine &Reason, llvm::Error E)
static ErrorPolicy defaultErrorHandler(Error E)
Function used to handle default error reporting policy.
MCRegisterInfo * createMCRegInfo(StringRef TT) const
createMCRegInfo - Create a MCRegisterInfo implementation.
Error extract(DWARFDataExtractor Data, uint32_t *OffsetPtr, uint16_t Version, uint8_t AddrSize, std::function< void(Error)> WarnCallback)
Extract an entire table, including all addresses.
void dump(raw_ostream &OS)
DWARFContext & getContext() const
Definition: DWARFUnit.h:274
virtual basic_symbol_iterator symbol_end() const =0
static void dumpDWARFv5StringOffsetsSection(raw_ostream &OS, StringRef SectionName, const DWARFObject &Obj, const DWARFSection &StringOffsetsSection, StringRef StringSection, DWARFContext::unit_iterator_range Units, bool LittleEndian)
static void dumpUUID(raw_ostream &OS, const ObjectFile &Obj)
Dump the UUID load command.
static bool isRelocScattered(const object::ObjectFile &Obj, const RelocationRef &Reloc)
std::pair< llvm::MachO::Architecture, std::string > UUID
void dump(raw_ostream &OS) const
Print the macro list found within the debug_macinfo section.
StringRef toStringRef(bool B)
Construct a string ref from a boolean.
Definition: StringExtras.h:52
Expected< uint64_t > getAddress() const
Returns the symbol virtual address (i.e.
Definition: ObjectFile.h:384
void consumeError(Error Err)
Consume a Error without doing anything.
Definition: Error.h:981
size_t size() const
Definition: SmallVector.h:52
LLVM_NODISCARD char back() const
back - Get the last character in the string.
Definition: StringRef.h:141
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:1213
void dump(raw_ostream &OS, DIDumpOptions DumpOptions) const
DWARFUnit * getUnitForOffset(uint32_t Offset) const
Definition: DWARFUnit.cpp:129
bool isLittleEndian() const
Definition: Binary.h:140
std::pair< iterator, bool > try_emplace(KeyT &&Key, Ts &&... Args)
Definition: DenseMap.h:236
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:43
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:1122
DWARFUnit * getUnitForIndexEntry(const DWARFUnitIndex::Entry &E)
Definition: DWARFUnit.cpp:142
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Definition: STLExtras.h:209
BaseType
A given derived pointer can have multiple base pointers through phi/selects.
A DataExtractor (typically for an in-memory copy of an object-file section) plus a relocation map for...
unit_iterator_range dwo_compile_units()
Get compile units in the DWO context.
Definition: DWARFContext.h:178
std::vector< DILocal > getLocalsForAddress(object::SectionedAddress Address) override
.debug_names section consists of one or more units.
DWARFCompileUnit * getDWOCompileUnitForHash(uint64_t Hash)
std::string Name
Definition: DIContext.h:117
void dump(raw_ostream &OS, DIDumpOptions DumpOpts={}) const
void handleAllErrors(Error E, HandlerTs &&... Handlers)
Behaves the same as handleErrors, except that by contract all errors must be handled by the given han...
Definition: Error.h:904
DIInliningInfo getInliningInfoForAddress(object::SectionedAddress Address, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
uint16_t Column
An unsigned integer indicating a column number within a source line.
DWARFDie getUnitDIE(bool ExtractUnitDIEOnly=true)
Definition: DWARFUnit.h:385
StringRef getArchName() const
getArchName - Get the architecture (first) component of the triple.
Definition: Triple.cpp:989
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 llvm::isPrint into an escape...
static ErrorSuccess success()
Create a success value.
Definition: Error.h:326
unit_iterator_range type_units()
Get type units in this context.
Definition: DWARFContext.h:155
uint32_t getLength() const
Returns the length of this table, including the length field, or 0 if the length has not been determi...
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:1173
uint32_t Line
Definition: DIContext.h:34
void addUnitsForDWOSection(DWARFContext &C, const DWARFSection &DWOSection, DWARFSectionKind SectionKind, bool Lazy=false)
Read units from a .debug_info.dwo or .debug_types.dwo section.
Definition: DWARFUnit.cpp:47
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:837
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:32
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:58
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:219
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:239
void parse(DataExtractor data, unsigned Version)
void dump(raw_ostream &OS, llvm::function_ref< Optional< object::SectionedAddress >(uint32_t)> LookupPooledAddress, DIDumpOptions DumpOpts={}) const
loop extract
void dump(raw_ostream &OS) const
#define Success
unit_iterator_range types_section_units()
Get units from .debug_types in this context.
Definition: DWARFContext.h:145
RelocAddrEntry contains relocated value and section index.
Definition: DWARFRelocMap.h:20
void finishedInfoUnits()
Indicate that parsing .debug_info[.dwo] is done, and remaining units will be from ...
Definition: DWARFUnit.h:155
bool hasValue() const
Definition: Optional.h:259
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
virtual section_iterator section_end() const =0
dwarf::Tag getTag() const
Definition: DWARFDie.h:71
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:55
const AppleAcceleratorTable & getAppleNames()
Get a reference to the parsed accelerator table object.
Wraps the returned DIEs for a given address.
Definition: DWARFContext.h:311
Optional< uint64_t > Size
Definition: DIContext.h:121
bool handleAccelTables()
Verify the information in accelerator tables, if they exist.
#define I(x, y, z)
Definition: MD5.cpp:58
static ContributionCollection collectContributionData(DWARFContext::unit_iterator_range Units)
unit_iterator_range dwo_units()
Get all units in the DWO context.
Definition: DWARFContext.h:184
const char * getCStr(uint32_t *offset_ptr) const
Extract a C string from *offset_ptr.
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:332
DWARFUnit * getUnitAtIndex(unsigned index)
Get the unit at the specified index.
Definition: DWARFContext.h:214
DILineInfo getLineInfoForAddress(object::SectionedAddress Address, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
uint32_t Size
Definition: Profile.cpp:46
void dump(raw_ostream &OS, DIDumpOptions DumpOpts, std::array< Optional< uint64_t >, DIDT_ID_Count > DumpOffsets)
Dump a textual representation to OS.
DWARFContext(std::unique_ptr< const DWARFObject > DObj, std::string DWPName="")
DILineInfoTable getLineInfoForAddressRange(object::SectionedAddress Address, uint64_t Size, DILineInfoSpecifier Specifier=DILineInfoSpecifier()) override
bool isLittleEndian() const
Definition: DWARFContext.h:337
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:133
Error extract(DWARFDataExtractor Data, uint32_t *OffsetPtr)
Extract an entire table, including all list entries.
uint64_t(*)(RelocationRef R, uint64_t S, uint64_t A) RelocationResolver
Optional< DWARFFormValue > find(dwarf::Attribute Attr) const
Extract the specified attribute from this DIE.
Definition: DWARFDie.cpp:366
std::string FunctionName
Definition: DIContext.h:116
Lightweight error class with error context and mandatory checking.
Definition: Error.h:157
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:80
This class implements an extremely fast bulk output stream that can only output to a stream...
Definition: raw_ostream.h:45
print Print MemDeps of function
print Instructions which execute on loop entry
StringRef - Represent a constant reference to a string, i.e.
Definition: StringRef.h:48
bool hasValidLength() const
Verify that the given length is valid for this table.
void dump(raw_ostream &OS, DIDumpOptions DumpOpts={}) const
void skip(function_ref< void(Error)> ErrorCallback)
Skip the current line table and go to the following line table (if present) immediately.
Helper to allow for parsing of an entire .debug_line section in sequence.
const uint64_t Version
Definition: InstrProf.h:984
bool done() const
Indicates if the parser has parsed as much as possible.
uint32_t getLineTableOffset() const
Definition: DWARFUnit.h:485
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:520
void setArch(ArchType Kind)
setArch - Set the architecture (first) component of the triple to a known type.
Definition: Triple.cpp:1168
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 createStringError(std::error_code EC, char const *Fmt, const Ts &... Vals)
Create formatted StringError object.
Definition: Error.h:1163
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
StringRef extension(StringRef path, Style style=Style::native)
Get extension.
Definition: Path.cpp:580
std::error_code inconvertibleErrorCode()
The value returned by this function can be returned from convertToErrorCode for Error values where no...
Definition: Error.cpp:77