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