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