1//===-- llvm-dwarfdump.cpp - Debug info dumping utility for llvm ----------===//
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//
9// This program is a utility that works like "dwarfdump".
10//
11//===----------------------------------------------------------------------===//
12
13#include "llvm-dwarfdump.h"
14#include "llvm/ADT/MapVector.h"
15#include "llvm/ADT/STLExtras.h"
16#include "llvm/ADT/SmallSet.h"
17#include "llvm/ADT/SmallVectorExtras.h"
18#include "llvm/ADT/StringSet.h"
19#include "llvm/BinaryFormat/Dwarf.h"
20#include "llvm/DebugInfo/DIContext.h"
21#include "llvm/DebugInfo/DWARF/DWARFAcceleratorTable.h"
22#include "llvm/DebugInfo/DWARF/DWARFCompileUnit.h"
23#include "llvm/DebugInfo/DWARF/DWARFContext.h"
24#include "llvm/MC/MCRegisterInfo.h"
25#include "llvm/MC/TargetRegistry.h"
26#include "llvm/Object/Archive.h"
27#include "llvm/Object/MachOUniversal.h"
28#include "llvm/Object/ObjectFile.h"
29#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/Format.h"
32#include "llvm/Support/FormatVariadic.h"
33#include "llvm/Support/InitLLVM.h"
34#include "llvm/Support/MemoryBuffer.h"
35#include "llvm/Support/Parallel.h"
36#include "llvm/Support/Path.h"
37#include "llvm/Support/Regex.h"
38#include "llvm/Support/TargetSelect.h"
39#include "llvm/Support/Threading.h"
40#include "llvm/Support/ToolOutputFile.h"
41#include "llvm/Support/WithColor.h"
42#include "llvm/Support/raw_ostream.h"
43#include "llvm/TargetParser/Triple.h"
44#include <cstdlib>
45
46using namespace llvm;
47using namespace llvm::dwarfdump;
48using namespace llvm::object;
49
50namespace {
51/// Parser for options that take an optional offest argument.
52/// @{
53struct OffsetOption {
54 uint64_t Val = 0;
55 bool HasValue = false;
56 bool IsRequested = false;
57};
58struct BoolOption : public OffsetOption {};
59} // namespace
60
61namespace llvm {
62namespace cl {
63template <>
64class parser<OffsetOption> final : public basic_parser<OffsetOption> {
65public:
66 parser(Option &O) : basic_parser(O) {}
67
68 /// Return true on error.
69 bool parse(Option &O, StringRef ArgName, StringRef Arg, OffsetOption &Val) {
70 if (Arg == "") {
71 Val.Val = 0;
72 Val.HasValue = false;
73 Val.IsRequested = true;
74 return false;
75 }
76 if (Arg.getAsInteger(Radix: 0, Result&: Val.Val))
77 return O.error(Message: "'" + Arg + "' value invalid for integer argument");
78 Val.HasValue = true;
79 Val.IsRequested = true;
80 return false;
81 }
82
83 enum ValueExpected getValueExpectedFlagDefault() const {
84 return ValueOptional;
85 }
86
87 StringRef getValueName() const override { return StringRef("offset"); }
88
89 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default,
90 size_t GlobalWidth) const {
91 printOptionName(O, GlobalWidth);
92 outs() << "[=offset]";
93 }
94};
95
96template <> class parser<BoolOption> final : public basic_parser<BoolOption> {
97public:
98 parser(Option &O) : basic_parser(O) {}
99
100 /// Return true on error.
101 bool parse(Option &O, StringRef ArgName, StringRef Arg, BoolOption &Val) {
102 if (Arg != "")
103 return O.error(Message: "this is a flag and does not take a value");
104 Val.Val = 0;
105 Val.HasValue = false;
106 Val.IsRequested = true;
107 return false;
108 }
109
110 enum ValueExpected getValueExpectedFlagDefault() const {
111 return ValueOptional;
112 }
113
114 StringRef getValueName() const override { return StringRef(); }
115
116 void printOptionDiff(const Option &O, OffsetOption V, OptVal Default,
117 size_t GlobalWidth) const {
118 printOptionName(O, GlobalWidth);
119 }
120};
121} // namespace cl
122} // namespace llvm
123
124/// @}
125/// Command line options.
126/// @{
127
128namespace {
129using namespace cl;
130
131enum ErrorDetailLevel {
132 OnlyDetailsNoSummary,
133 NoDetailsOnlySummary,
134 NoDetailsOrSummary,
135 BothDetailsAndSummary,
136 Unspecified
137};
138
139OptionCategory DwarfDumpCategory("Specific Options");
140static list<std::string>
141 InputFilenames(Positional, desc("<input object files or .dSYM bundles>"),
142 cat(DwarfDumpCategory));
143
144cl::OptionCategory SectionCategory("Section-specific Dump Options",
145 "These control which sections are dumped. "
146 "Where applicable these parameters take an "
147 "optional =<offset> argument to dump only "
148 "the entry at the specified offset.");
149
150static opt<bool> DumpAll("all", desc("Dump all debug info sections"),
151 cat(SectionCategory));
152static alias DumpAllAlias("a", desc("Alias for --all"), aliasopt(DumpAll),
153 cl::NotHidden);
154
155// Options for dumping specific sections.
156static unsigned DumpType = DIDT_Null;
157static std::array<std::optional<uint64_t>, (unsigned)DIDT_ID_Count> DumpOffsets;
158#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME, OPTION) \
159 static opt<OPTION> Dump##ENUM_NAME(CMDLINE_NAME, \
160 desc("Dump the " ELF_NAME " section"), \
161 cat(SectionCategory));
162#include "llvm/BinaryFormat/Dwarf.def"
163#undef HANDLE_DWARF_SECTION
164
165// The aliased DumpDebugFrame is created by the Dwarf.def x-macro just above.
166static alias DumpDebugFrameAlias("eh-frame", desc("Alias for --debug-frame"),
167 NotHidden, cat(SectionCategory),
168 aliasopt(DumpDebugFrame));
169static list<std::string>
170 ArchFilters("arch",
171 desc("Dump debug information for the specified CPU "
172 "architecture only. Architectures may be specified by "
173 "name or by number. This option can be specified "
174 "multiple times, once for each desired architecture."),
175 cat(DwarfDumpCategory));
176static opt<bool>
177 Diff("diff",
178 desc("Emit diff-friendly output by omitting offsets and addresses."),
179 cat(DwarfDumpCategory));
180static list<std::string>
181 Find("find",
182 desc("Search for the exact match for <name> in the accelerator tables "
183 "and print the matching debug information entries. When no "
184 "accelerator tables are available, the slower but more complete "
185 "-name option can be used instead."),
186 value_desc("name"), cat(DwarfDumpCategory));
187static alias FindAlias("f", desc("Alias for --find."), aliasopt(Find),
188 cl::NotHidden);
189static opt<bool> FindAllApple(
190 "find-all-apple",
191 desc("Print every debug information entry in the accelerator tables."),
192 cat(DwarfDumpCategory));
193static opt<bool> IgnoreCase("ignore-case",
194 desc("Ignore case distinctions when using --name."),
195 value_desc("i"), cat(DwarfDumpCategory));
196static opt<bool> DumpNonSkeleton(
197 "dwo",
198 desc("Dump the non skeleton DIE in the .dwo or .dwp file after dumping the "
199 "skeleton DIE from the main executable. This allows dumping the .dwo "
200 "files with resolved addresses."),
201 value_desc("d"), cat(DwarfDumpCategory));
202
203static alias IgnoreCaseAlias("i", desc("Alias for --ignore-case."),
204 aliasopt(IgnoreCase), cl::NotHidden);
205static list<std::string> Name(
206 "name",
207 desc("Find and print all debug info entries whose name "
208 "(DW_AT_name/DW_AT_linkage_name attribute) matches the exact text "
209 "in <pattern>. When used with the the -regex option <pattern> is "
210 "interpreted as a regular expression."),
211 value_desc("pattern"), cat(DwarfDumpCategory));
212static alias NameAlias("n", desc("Alias for --name"), aliasopt(Name),
213 cl::NotHidden);
214static opt<uint64_t>
215 Lookup("lookup",
216 desc("Lookup <address> in the debug information and print out any "
217 "available file, function, block and line table details."),
218 value_desc("address"), cat(DwarfDumpCategory));
219static opt<std::string>
220 OutputFilename("o", cl::init(Val: "-"),
221 cl::desc("Redirect output to the specified file."),
222 cl::value_desc("filename"), cat(DwarfDumpCategory));
223static alias OutputFilenameAlias("out-file", desc("Alias for -o."),
224 aliasopt(OutputFilename));
225static opt<bool> UseRegex(
226 "regex",
227 desc("Treat any <pattern> strings as regular "
228 "expressions when searching with --name. If --ignore-case is also "
229 "specified, the regular expression becomes case-insensitive."),
230 cat(DwarfDumpCategory));
231static alias RegexAlias("x", desc("Alias for --regex"), aliasopt(UseRegex),
232 cl::NotHidden);
233static opt<bool>
234 ShowChildren("show-children",
235 desc("Show a debug info entry's children when selectively "
236 "printing entries."),
237 cat(DwarfDumpCategory));
238static alias ShowChildrenAlias("c", desc("Alias for --show-children."),
239 aliasopt(ShowChildren), cl::NotHidden);
240static opt<bool>
241 ShowParents("show-parents",
242 desc("Show a debug info entry's parents when selectively "
243 "printing entries."),
244 cat(DwarfDumpCategory));
245static alias ShowParentsAlias("p", desc("Alias for --show-parents."),
246 aliasopt(ShowParents), cl::NotHidden);
247
248static list<std::string> FilterChildTag(
249 "filter-child-tag",
250 desc("When --show-children is specified, show only DIEs with the "
251 "specified DWARF tags."),
252 value_desc("list of DWARF tags"), cat(DwarfDumpCategory));
253static alias FilterChildTagAlias("t", desc("Alias for --filter-child-tag."),
254 aliasopt(FilterChildTag), cl::NotHidden);
255
256static opt<bool>
257 ShowForm("show-form",
258 desc("Show DWARF form types after the DWARF attribute types."),
259 cat(DwarfDumpCategory));
260static alias ShowFormAlias("F", desc("Alias for --show-form."),
261 aliasopt(ShowForm), cat(DwarfDumpCategory),
262 cl::NotHidden);
263static opt<unsigned>
264 ChildRecurseDepth("recurse-depth",
265 desc("Only recurse to a depth of N when displaying "
266 "children of debug info entries."),
267 cat(DwarfDumpCategory), init(Val: -1U), value_desc("N"));
268static alias ChildRecurseDepthAlias("r", desc("Alias for --recurse-depth."),
269 aliasopt(ChildRecurseDepth), cl::NotHidden);
270static opt<unsigned>
271 ParentRecurseDepth("parent-recurse-depth",
272 desc("Only recurse to a depth of N when displaying "
273 "parents of debug info entries."),
274 cat(DwarfDumpCategory), init(Val: -1U), value_desc("N"));
275static opt<bool>
276 SummarizeTypes("summarize-types",
277 desc("Abbreviate the description of type unit entries."),
278 cat(DwarfDumpCategory));
279static cl::opt<bool>
280 Statistics("statistics",
281 cl::desc("Emit JSON-formatted debug info quality metrics."),
282 cat(DwarfDumpCategory));
283static cl::opt<bool>
284 ShowSectionSizes("show-section-sizes",
285 cl::desc("Show the sizes of all debug sections, "
286 "expressed in bytes."),
287 cat(DwarfDumpCategory));
288static cl::opt<bool> ManuallyGenerateUnitIndex(
289 "manually-generate-unit-index",
290 cl::desc("if the input is dwp file, parse .debug_info "
291 "section and use it to populate "
292 "DW_SECT_INFO contributions in cu-index. "
293 "For DWARF5 it also populated TU Index."),
294 cl::init(Val: false), cl::Hidden, cl::cat(DwarfDumpCategory));
295static cl::opt<bool>
296 ShowSources("show-sources",
297 cl::desc("Show the sources across all compilation units."),
298 cat(DwarfDumpCategory));
299static opt<bool> Verify("verify", desc("Verify the DWARF debug info."),
300 cat(DwarfDumpCategory));
301static opt<unsigned> VerifyNumThreads(
302 "verify-num-threads", init(Val: 1),
303 desc("Number of threads to use for --verify. Single threaded verification "
304 "is the default unless this option is specified. If 0 is specified, "
305 "maximum hardware threads will be used. This can cause the "
306 "output to be non determinisitic, but can speed up verification and "
307 "is useful when running with the summary only or JSON summary modes."),
308 cat(DwarfDumpCategory));
309static opt<ErrorDetailLevel> ErrorDetails(
310 "error-display", init(Val: Unspecified),
311 desc("Set the level of detail and summary to display when verifying "
312 "(implies --verify)"),
313 values(clEnumValN(NoDetailsOrSummary, "quiet",
314 "Only display whether errors occurred."),
315 clEnumValN(NoDetailsOnlySummary, "summary",
316 "Display only a summary of the errors found."),
317 clEnumValN(OnlyDetailsNoSummary, "details",
318 "Display each error in detail but no summary."),
319 clEnumValN(BothDetailsAndSummary, "full",
320 "Display each error as well as a summary. [default]")),
321 cat(DwarfDumpCategory));
322static opt<std::string> JsonErrSummaryFile(
323 "verify-json", init(Val: ""),
324 desc("Output JSON-formatted error summary to the specified file. "
325 "(Implies --verify)"),
326 value_desc("filename.json"), cat(DwarfDumpCategory));
327static opt<bool> Quiet("quiet", desc("Use with -verify to not emit to STDOUT."),
328 cat(DwarfDumpCategory));
329static opt<bool> DumpUUID("uuid", desc("Show the UUID for each architecture."),
330 cat(DwarfDumpCategory));
331static alias DumpUUIDAlias("u", desc("Alias for --uuid."), aliasopt(DumpUUID),
332 cl::NotHidden);
333static opt<bool> Verbose("verbose",
334 desc("Print more low-level encoding details."),
335 cat(DwarfDumpCategory));
336static alias VerboseAlias("v", desc("Alias for --verbose."), aliasopt(Verbose),
337 cat(DwarfDumpCategory), cl::NotHidden);
338static opt<bool>
339 ShowVariableCoverage("show-variable-coverage",
340 desc("Show per-variable coverage metrics."),
341 cat(DwarfDumpCategory));
342static opt<std::string>
343 CoverageBaseline("coverage-baseline",
344 desc("File to use as the baseline for variable coverage "
345 "statistics (implies --show-variable-coverage)"),
346 value_desc("filename"), cat(DwarfDumpCategory));
347static opt<std::string>
348 BitcodeFile("variable-coverage-bitcode-file",
349 desc("File containing LLVM IR (bitcode or textual) used for "
350 "calculating variable definedness in coverage statistics "
351 "(implies --show-variable-coverage)"),
352 value_desc("filename"), cat(DwarfDumpCategory));
353static opt<bool> MaybeUndefined(
354 "variable-coverage-maybe-undefined",
355 desc("Use with --show-variable-coverage and "
356 "--variable-coverage-bitcode-file to consider variables live if they "
357 "are defined on at least one path (default behaviour is to require a "
358 "variable to be defined on all paths to be counted)"),
359 cat(DwarfDumpCategory));
360static opt<bool> CombineInstances(
361 "combine-inline-variable-instances",
362 desc(
363 "Use with --show-variable-coverage to average variable coverage across "
364 "inlined subroutine instances instead of printing them separately."),
365 cat(DwarfDumpCategory));
366static cl::extrahelp
367 HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
368} // namespace
369/// @}
370//===----------------------------------------------------------------------===//
371
372static llvm::SmallVector<unsigned>
373makeTagVector(const list<std::string> &TagStrings) {
374 return llvm::map_to_vector(C: TagStrings, F: [](const std::string &Tag) {
375 return llvm::dwarf::getTag(TagString: Tag);
376 });
377}
378
379static void error(Error Err) {
380 if (!Err)
381 return;
382 WithColor::error() << toString(E: std::move(Err)) << "\n";
383 exit(status: 1);
384}
385
386static void error(StringRef Prefix, Error Err) {
387 if (!Err)
388 return;
389 WithColor::error() << Prefix << ": " << toString(E: std::move(Err)) << "\n";
390 exit(status: 1);
391}
392
393static void error(StringRef Prefix, std::error_code EC) {
394 error(Prefix, Err: errorCodeToError(EC));
395}
396
397static DIDumpOptions getDumpOpts(DWARFContext &C) {
398 DIDumpOptions DumpOpts;
399 DumpOpts.DumpType = DumpType;
400 DumpOpts.ChildRecurseDepth = ChildRecurseDepth;
401 DumpOpts.ParentRecurseDepth = ParentRecurseDepth;
402 DumpOpts.ShowAddresses = !Diff;
403 DumpOpts.ShowChildren = ShowChildren;
404 DumpOpts.ShowParents = ShowParents;
405 DumpOpts.FilterChildTag = makeTagVector(TagStrings: FilterChildTag);
406 DumpOpts.ShowForm = ShowForm;
407 DumpOpts.SummarizeTypes = SummarizeTypes;
408 DumpOpts.Verbose = Verbose;
409 DumpOpts.DumpNonSkeleton = DumpNonSkeleton;
410 DumpOpts.RecoverableErrorHandler = C.getRecoverableErrorHandler();
411 // Address space names are target-dependent.
412 if (const object::ObjectFile *Obj = C.getDWARFObj().getFile())
413 DumpOpts.TT = Obj->makeTriple();
414 // In -verify mode, print DIEs without children in error messages.
415 if (Verify) {
416 DumpOpts.Verbose = ErrorDetails != NoDetailsOnlySummary &&
417 ErrorDetails != NoDetailsOrSummary;
418 DumpOpts.ShowAggregateErrors = ErrorDetails != OnlyDetailsNoSummary &&
419 ErrorDetails != NoDetailsOnlySummary;
420 DumpOpts.JsonErrSummaryFile = JsonErrSummaryFile;
421 return DumpOpts.noImplicitRecursion();
422 }
423 return DumpOpts;
424}
425
426static uint32_t getCPUType(MachOObjectFile &MachO) {
427 if (MachO.is64Bit())
428 return MachO.getHeader64().cputype;
429 else
430 return MachO.getHeader().cputype;
431}
432
433/// Return true if the object file has not been filtered by an --arch option.
434static bool filterArch(ObjectFile &Obj) {
435 if (ArchFilters.empty())
436 return true;
437
438 if (auto *MachO = dyn_cast<MachOObjectFile>(Val: &Obj)) {
439 for (const StringRef Arch : ArchFilters) {
440 // Match architecture number.
441 unsigned Value;
442 if (!Arch.getAsInteger(Radix: 0, Result&: Value))
443 if (Value == getCPUType(MachO&: *MachO))
444 return true;
445
446 // Match as name.
447 if (MachO->getArchTriple().getArchName() == Triple(Arch).getArchName())
448 return true;
449 }
450 }
451 return false;
452}
453
454using HandlerFn = std::function<bool(ObjectFile &, DWARFContext &DICtx,
455 const Twine &, raw_ostream &)>;
456
457/// Print only DIEs that have a certain name.
458static bool filterByName(
459 const StringSet<> &Names, DWARFDie Die, StringRef NameRef, raw_ostream &OS,
460 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
461 DIDumpOptions DumpOpts = getDumpOpts(C&: Die.getDwarfUnit()->getContext());
462 DumpOpts.GetNameForDWARFReg = GetNameForDWARFReg;
463 std::string Name =
464 (IgnoreCase && !UseRegex) ? NameRef.lower() : NameRef.str();
465 if (UseRegex) {
466 // Match regular expression.
467 for (auto Pattern : Names.keys()) {
468 Regex RE(Pattern, IgnoreCase ? Regex::IgnoreCase : Regex::NoFlags);
469 std::string Error;
470 if (!RE.isValid(Error)) {
471 errs() << "error in regular expression: " << Error << "\n";
472 exit(status: 1);
473 }
474 if (RE.match(String: Name)) {
475 Die.dump(OS, indent: 0, DumpOpts);
476 return true;
477 }
478 }
479 } else if (Names.count(Key: Name)) {
480 // Match full text.
481 Die.dump(OS, indent: 0, DumpOpts);
482 return true;
483 }
484 return false;
485}
486
487/// Print only DIEs that have a certain name.
488static void filterByName(
489 const StringSet<> &Names, DWARFContext::unit_iterator_range CUs,
490 raw_ostream &OS,
491 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
492 auto filterDieNames = [&](DWARFUnit *Unit) {
493 for (const auto &Entry : Unit->dies()) {
494 DWARFDie Die = {Unit, &Entry};
495 if (const char *Name = Die.getName(Kind: DINameKind::ShortName))
496 if (filterByName(Names, Die, NameRef: Name, OS, GetNameForDWARFReg))
497 continue;
498 if (const char *Name = Die.getName(Kind: DINameKind::LinkageName))
499 filterByName(Names, Die, NameRef: Name, OS, GetNameForDWARFReg);
500 }
501 };
502 for (const auto &CU : CUs) {
503 filterDieNames(CU.get());
504 if (DumpNonSkeleton) {
505 // If we have split DWARF, then recurse down into the .dwo files as well.
506 // Matching DIEs are printed as they are found and nothing here outlives
507 // them, so the split unit can be released instead of keeping every .dwo
508 // context resident until the end of the search.
509 const bool HadDWO = CU->getDWO();
510 DWARFDie CUDie = CU->getUnitDIE(ExtractUnitDIEOnly: false);
511 DWARFDie CUNonSkeletonDie = CU->getNonSkeletonUnitDIE(ExtractUnitDIEOnly: false);
512 // If we have a DWO file, we need to search it as well
513 if (CUNonSkeletonDie && CUDie != CUNonSkeletonDie)
514 filterDieNames(CUNonSkeletonDie.getDwarfUnit());
515 const DWARFUnit *DWO = CU->getDWO();
516 // Don't release a DWP context -- it is the same for every non-skeleton CU
517 // and we benefit from keeping it resident to avoid the re-parse.
518 if (!HadDWO && DWO && !DWO->getContext().isDWP())
519 CU->clearDWO();
520 }
521 }
522}
523
524static void getDies(DWARFContext &DICtx, const AppleAcceleratorTable &Accel,
525 StringRef Name, SmallVectorImpl<DWARFDie> &Dies) {
526 for (const auto &Entry : Accel.equal_range(Key: Name)) {
527 if (std::optional<uint64_t> Off = Entry.getDIESectionOffset()) {
528 if (DWARFDie Die = DICtx.getDIEForOffset(Offset: *Off))
529 Dies.push_back(Elt: Die);
530 }
531 }
532}
533
534static DWARFDie toDie(const DWARFDebugNames::Entry &Entry,
535 DWARFContext &DICtx) {
536 std::optional<uint64_t> CUOff = Entry.getCUOffset();
537 std::optional<uint64_t> Off = Entry.getDIEUnitOffset();
538 if (!CUOff || !Off)
539 return DWARFDie();
540
541 DWARFCompileUnit *CU = DICtx.getCompileUnitForOffset(Offset: *CUOff);
542 if (!CU)
543 return DWARFDie();
544
545 if (std::optional<uint64_t> DWOId = CU->getDWOId()) {
546 // This is a skeleton unit. Look up the DIE in the DWO unit.
547 CU = DICtx.getDWOCompileUnitForHash(Hash: *DWOId);
548 if (!CU)
549 return DWARFDie();
550 }
551
552 return CU->getDIEForOffset(Offset: CU->getOffset() + *Off);
553}
554
555static void getDies(DWARFContext &DICtx, const DWARFDebugNames &Accel,
556 StringRef Name, SmallVectorImpl<DWARFDie> &Dies) {
557 for (const auto &Entry : Accel.equal_range(Key: Name)) {
558 if (DWARFDie Die = toDie(Entry, DICtx))
559 Dies.push_back(Elt: Die);
560 }
561}
562
563/// Print only DIEs that have a certain name.
564static void filterByAccelName(
565 ArrayRef<std::string> Names, DWARFContext &DICtx, raw_ostream &OS,
566 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
567 SmallVector<DWARFDie, 4> Dies;
568 for (const auto &Name : Names) {
569 getDies(DICtx, Accel: DICtx.getAppleNames(), Name, Dies);
570 getDies(DICtx, Accel: DICtx.getAppleTypes(), Name, Dies);
571 getDies(DICtx, Accel: DICtx.getAppleNamespaces(), Name, Dies);
572 getDies(DICtx, Accel: DICtx.getDebugNames(), Name, Dies);
573 }
574 llvm::sort(C&: Dies);
575 Dies.erase(CS: llvm::unique(R&: Dies), CE: Dies.end());
576
577 DIDumpOptions DumpOpts = getDumpOpts(C&: DICtx);
578 DumpOpts.GetNameForDWARFReg = GetNameForDWARFReg;
579 for (DWARFDie Die : Dies)
580 Die.dump(OS, indent: 0, DumpOpts);
581}
582
583/// Print all DIEs in apple accelerator tables
584static void findAllApple(
585 DWARFContext &DICtx, raw_ostream &OS,
586 std::function<StringRef(uint64_t RegNum, bool IsEH)> GetNameForDWARFReg) {
587 MapVector<StringRef, llvm::SmallSet<DWARFDie, 2>> NameToDies;
588
589 auto PushDIEs = [&](const AppleAcceleratorTable &Accel) {
590 for (const auto &Entry : Accel.entries()) {
591 if (std::optional<uint64_t> Off = Entry.BaseEntry.getDIESectionOffset()) {
592 std::optional<StringRef> MaybeName = Entry.readName();
593 DWARFDie Die = DICtx.getDIEForOffset(Offset: *Off);
594 if (Die && MaybeName)
595 NameToDies[*MaybeName].insert(V: Die);
596 }
597 }
598 };
599
600 PushDIEs(DICtx.getAppleNames());
601 PushDIEs(DICtx.getAppleNamespaces());
602 PushDIEs(DICtx.getAppleTypes());
603
604 DIDumpOptions DumpOpts = getDumpOpts(C&: DICtx);
605 DumpOpts.GetNameForDWARFReg = GetNameForDWARFReg;
606 for (const auto &[Name, Dies] : NameToDies) {
607 OS << llvm::formatv(Fmt: "\nApple accelerator entries with name = \"{0}\":\n",
608 Vals: Name);
609 for (DWARFDie Die : Dies)
610 Die.dump(OS, indent: 0, DumpOpts);
611 }
612}
613
614/// Handle the --lookup option and dump the DIEs and line info for the given
615/// address.
616/// TODO: specified Address for --lookup option could relate for several
617/// different sections(in case not-linked object file). llvm-dwarfdump
618/// need to do something with this: extend lookup option with section
619/// information or probably display all matched entries, or something else...
620static bool lookup(ObjectFile &Obj, DWARFContext &DICtx, uint64_t Address,
621 raw_ostream &OS) {
622 auto DIEsForAddr = DICtx.getDIEsForAddress(Address: Lookup, CheckDWO: DumpNonSkeleton);
623
624 if (!DIEsForAddr)
625 return false;
626
627 DIDumpOptions DumpOpts = getDumpOpts(C&: DICtx);
628 DumpOpts.ChildRecurseDepth = 0;
629 DIEsForAddr.CompileUnit->dump(OS, DumpOpts);
630 if (DIEsForAddr.FunctionDIE) {
631 DIEsForAddr.FunctionDIE.dump(OS, indent: 2, DumpOpts);
632 if (DIEsForAddr.BlockDIE)
633 DIEsForAddr.BlockDIE.dump(OS, indent: 4, DumpOpts);
634 }
635
636 // TODO: it is neccessary to set proper SectionIndex here.
637 // object::SectionedAddress::UndefSection works for only absolute addresses.
638 if (DILineInfo LineInfo =
639 DICtx
640 .getLineInfoForAddress(
641 Address: {.Address: Lookup, .SectionIndex: object::SectionedAddress::UndefSection})
642 .value_or(u: DILineInfo())) {
643 LineInfo.dump(OS);
644 }
645
646 return true;
647}
648
649// Collect all sources referenced from the given line table, scoped to the given
650// CU compilation directory.
651static bool collectLineTableSources(const DWARFDebugLine::LineTable &LT,
652 StringRef CompDir,
653 std::vector<std::string> &Sources) {
654 bool Result = true;
655 std::optional<uint64_t> LastIndex = LT.getLastValidFileIndex();
656 for (uint64_t I = LT.hasFileAtIndex(FileIndex: 0) ? 0 : 1,
657 E = LastIndex ? *LastIndex + 1 : 0;
658 I < E; ++I) {
659 std::string Path;
660 Result &= LT.getFileNameByIndex(
661 FileIndex: I, CompDir, Kind: DILineInfoSpecifier::FileLineInfoKind::AbsoluteFilePath,
662 Result&: Path);
663 Sources.push_back(x: std::move(Path));
664 }
665 return Result;
666}
667
668static bool collectObjectSources(ObjectFile &Obj, DWARFContext &DICtx,
669 const Twine &Filename, raw_ostream &OS) {
670 bool Result = true;
671 std::vector<std::string> Sources;
672
673 bool HasCompileUnits = false;
674 for (const auto &CU : DICtx.compile_units()) {
675 HasCompileUnits = true;
676 // Extract paths from the line table for this CU. This allows combining the
677 // compilation directory with the line information, in case both the include
678 // directory and file names in the line table are relative.
679 const DWARFDebugLine::LineTable *LT = DICtx.getLineTableForUnit(U: CU.get());
680 StringRef CompDir = CU->getCompilationDir();
681 if (LT) {
682 Result &= collectLineTableSources(LT: *LT, CompDir, Sources);
683 } else {
684 // Since there's no line table for this CU, collect the name from the CU
685 // itself.
686 const char *Name = CU->getUnitDIE().getShortName();
687 if (!Name) {
688 WithColor::warning()
689 << Filename << ": missing name for compilation unit\n";
690 continue;
691 }
692 SmallString<64> AbsName;
693 if (sys::path::is_relative(path: Name, style: sys::path::Style::posix) &&
694 sys::path::is_relative(path: Name, style: sys::path::Style::windows))
695 AbsName = CompDir;
696 sys::path::append(path&: AbsName, a: Name);
697 Sources.push_back(x: std::string(AbsName));
698 }
699 }
700
701 if (!HasCompileUnits) {
702 // Since there's no compile units available, walk the line tables and
703 // extract out any referenced paths.
704 DWARFDataExtractor LineData(DICtx.getDWARFObj(),
705 DICtx.getDWARFObj().getLineSection(),
706 DICtx.isLittleEndian(), 0);
707 DWARFDebugLine::SectionParser Parser(LineData, DICtx, DICtx.normal_units());
708 while (!Parser.done()) {
709 const auto RecoverableErrorHandler = [&](Error Err) {
710 Result = false;
711 WithColor::defaultErrorHandler(Err: std::move(Err));
712 };
713 void (*UnrecoverableErrorHandler)(Error Err) = error;
714
715 DWARFDebugLine::LineTable LT =
716 Parser.parseNext(RecoverableErrorHandler, UnrecoverableErrorHandler);
717 Result &= collectLineTableSources(LT, /*CompDir=*/"", Sources);
718 }
719 }
720
721 // Dedup and order the sources.
722 llvm::sort(C&: Sources);
723 Sources.erase(first: llvm::unique(R&: Sources), last: Sources.end());
724
725 for (StringRef Name : Sources)
726 OS << Name << "\n";
727 return Result;
728}
729
730static std::unique_ptr<MCRegisterInfo> createRegInfo(const Triple &TT) {
731 std::unique_ptr<MCRegisterInfo> MCRegInfo;
732 std::string TargetLookupError;
733 const Target *TheTarget = TargetRegistry::lookupTarget(TheTriple: TT, Error&: TargetLookupError);
734 if (!TargetLookupError.empty())
735 return nullptr;
736 MCRegInfo.reset(p: TheTarget->createMCRegInfo(TT));
737 return MCRegInfo;
738}
739
740static bool dumpObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
741 const Twine &Filename, raw_ostream &OS) {
742
743 // Register and address space names are target-dependent.
744 Triple TT = Obj.makeTriple();
745
746 auto MCRegInfo = createRegInfo(TT);
747 if (!MCRegInfo)
748 logAllUnhandledErrors(E: createStringError(EC: inconvertibleErrorCode(),
749 S: "Error in creating MCRegInfo"),
750 OS&: errs(), ErrorBanner: Filename + ": ");
751
752 auto GetRegName = [&MCRegInfo](uint64_t DwarfRegNum, bool IsEH) -> StringRef {
753 if (!MCRegInfo)
754 return {};
755 if (std::optional<MCRegister> LLVMRegNum =
756 MCRegInfo->getLLVMRegNum(RegNum: DwarfRegNum, isEH: IsEH))
757 if (const char *RegName = MCRegInfo->getName(RegNo: *LLVMRegNum))
758 return StringRef(RegName);
759 return {};
760 };
761
762 // The UUID dump already contains all the same information.
763 if (!(DumpType & DIDT_UUID) || DumpType == DIDT_All)
764 OS << Filename << ":\tfile format " << Obj.getFileFormatName() << '\n';
765
766 // Handle the --lookup option.
767 if (Lookup)
768 return lookup(Obj, DICtx, Address: Lookup, OS);
769
770 // Handle the --name option.
771 if (!Name.empty()) {
772 StringSet<> Names;
773 for (const auto &name : Name)
774 Names.insert(key: (IgnoreCase && !UseRegex) ? StringRef(name).lower() : name);
775
776 filterByName(Names, CUs: DICtx.normal_units(), OS, GetNameForDWARFReg: GetRegName);
777 filterByName(Names, CUs: DICtx.dwo_units(), OS, GetNameForDWARFReg: GetRegName);
778 return true;
779 }
780
781 // Handle the --find option and lower it to --debug-info=<offset>.
782 if (!Find.empty()) {
783 filterByAccelName(Names: Find, DICtx, OS, GetNameForDWARFReg: GetRegName);
784 return true;
785 }
786
787 // Handle the --find-all-apple option and lower it to --debug-info=<offset>.
788 if (FindAllApple) {
789 findAllApple(DICtx, OS, GetNameForDWARFReg: GetRegName);
790 return true;
791 }
792
793 // Dump the complete DWARF structure.
794 auto DumpOpts = getDumpOpts(C&: DICtx);
795 DumpOpts.GetNameForDWARFReg = GetRegName;
796 DICtx.dump(OS, DumpOpts, DumpOffsets);
797 return true;
798}
799
800static bool verifyObjectFile(ObjectFile &Obj, DWARFContext &DICtx,
801 const Twine &Filename, raw_ostream &OS) {
802 // Verify the DWARF and exit with non-zero exit status if verification
803 // fails.
804 raw_ostream &stream = Quiet ? nulls() : OS;
805 stream << "Verifying " << Filename.str() << ":\tfile format "
806 << Obj.getFileFormatName() << "\n";
807 bool Result = DICtx.verify(OS&: stream, DumpOpts: getDumpOpts(C&: DICtx));
808 if (Result)
809 stream << "No errors.\n";
810 else
811 stream << "Errors detected.\n";
812 return Result;
813}
814
815static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
816 HandlerFn HandleObj, raw_ostream &OS);
817
818static bool handleArchive(StringRef Filename, Archive &Arch,
819 HandlerFn HandleObj, raw_ostream &OS) {
820 bool Result = true;
821 Error Err = Error::success();
822 for (const auto &Child : Arch.children(Err)) {
823 auto BuffOrErr = Child.getMemoryBufferRef();
824 error(Prefix: Filename, Err: BuffOrErr.takeError());
825 auto NameOrErr = Child.getName();
826 error(Prefix: Filename, Err: NameOrErr.takeError());
827 std::string Name = (Filename + "(" + NameOrErr.get() + ")").str();
828 Result &= handleBuffer(Filename: Name, Buffer: BuffOrErr.get(), HandleObj, OS);
829 }
830 error(Prefix: Filename, Err: std::move(Err));
831
832 return Result;
833}
834
835static bool handleBuffer(StringRef Filename, MemoryBufferRef Buffer,
836 HandlerFn HandleObj, raw_ostream &OS) {
837 Expected<std::unique_ptr<Binary>> BinOrErr = object::createBinary(Source: Buffer);
838 error(Prefix: Filename, Err: BinOrErr.takeError());
839
840 bool Result = true;
841 auto RecoverableErrorHandler = [&](Error E) {
842 Result = false;
843 WithColor::defaultErrorHandler(Err: std::move(E));
844 };
845 if (auto *Obj = dyn_cast<ObjectFile>(Val: BinOrErr->get())) {
846 if (filterArch(Obj&: *Obj)) {
847 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(
848 Obj: *Obj, RelocAction: DWARFContext::ProcessDebugRelocations::Process, L: nullptr, DWPName: "",
849 RecoverableErrorHandler, WarningHandler: WithColor::defaultWarningHandler,
850 /*ThreadSafe=*/true);
851 DICtx->setParseCUTUIndexManually(ManuallyGenerateUnitIndex);
852 if (!HandleObj(*Obj, *DICtx, Filename, OS))
853 Result = false;
854 }
855 } else if (auto *Fat = dyn_cast<MachOUniversalBinary>(Val: BinOrErr->get()))
856 for (auto &ObjForArch : Fat->objects()) {
857 std::string ObjName =
858 (Filename + "(" + ObjForArch.getArchFlagName() + ")").str();
859 if (auto MachOOrErr = ObjForArch.getAsObjectFile()) {
860 auto &Obj = **MachOOrErr;
861 if (filterArch(Obj)) {
862 std::unique_ptr<DWARFContext> DICtx = DWARFContext::create(
863 Obj, RelocAction: DWARFContext::ProcessDebugRelocations::Process, L: nullptr, DWPName: "",
864 RecoverableErrorHandler);
865 if (!HandleObj(Obj, *DICtx, ObjName, OS))
866 Result = false;
867 }
868 continue;
869 } else
870 consumeError(Err: MachOOrErr.takeError());
871 if (auto ArchiveOrErr = ObjForArch.getAsArchive()) {
872 error(Prefix: ObjName, Err: ArchiveOrErr.takeError());
873 if (!handleArchive(Filename: ObjName, Arch&: *ArchiveOrErr.get(), HandleObj, OS))
874 Result = false;
875 continue;
876 } else
877 consumeError(Err: ArchiveOrErr.takeError());
878 }
879 else if (auto *Arch = dyn_cast<Archive>(Val: BinOrErr->get()))
880 Result = handleArchive(Filename, Arch&: *Arch, HandleObj, OS);
881 return Result;
882}
883
884static bool handleFile(StringRef Filename, HandlerFn HandleObj,
885 raw_ostream &OS) {
886 ErrorOr<std::unique_ptr<MemoryBuffer>> BuffOrErr =
887 MemoryBuffer::getFileOrSTDIN(Filename);
888 error(Prefix: Filename, EC: BuffOrErr.getError());
889 std::unique_ptr<MemoryBuffer> Buffer = std::move(BuffOrErr.get());
890 return handleBuffer(Filename, Buffer: *Buffer, HandleObj, OS);
891}
892
893int main(int argc, char **argv) {
894 InitLLVM X(argc, argv);
895
896 // Flush outs() when printing to errs(). This avoids interleaving output
897 // between the two.
898 errs().tie(TieTo: &outs());
899
900 llvm::InitializeAllTargetInfos();
901 llvm::InitializeAllTargetMCs();
902
903 HideUnrelatedOptions(
904 Categories: {&DwarfDumpCategory, &SectionCategory, &getColorCategory()});
905 cl::ParseCommandLineOptions(
906 argc, argv,
907 Overview: "pretty-print DWARF debug information in object files"
908 " and debug info archives.\n");
909
910 // FIXME: Audit interactions between these two options and make them
911 // compatible.
912 if (Diff && Verbose) {
913 WithColor::error() << "incompatible arguments: specifying both -diff and "
914 "-verbose is currently not supported";
915 return 1;
916 }
917 // -error-detail and -json-summary-file both imply -verify
918 if (ErrorDetails != Unspecified || !JsonErrSummaryFile.empty()) {
919 Verify = true;
920 }
921
922 std::error_code EC;
923 ToolOutputFile OutputFile(OutputFilename, EC, sys::fs::OF_TextWithCRLF);
924 error(Prefix: "unable to open output file " + OutputFilename, EC);
925 // Don't remove output file if we exit with an error.
926 OutputFile.keep();
927
928 bool OffsetRequested = false;
929
930 // Defaults to dumping only debug_info, unless: A) verbose mode is specified,
931 // in which case all sections are dumped, or B) a specific section is
932 // requested.
933#define HANDLE_DWARF_SECTION(ENUM_NAME, ELF_NAME, CMDLINE_NAME, OPTION) \
934 if (Dump##ENUM_NAME.IsRequested) { \
935 DumpType |= DIDT_##ENUM_NAME; \
936 if (Dump##ENUM_NAME.HasValue) { \
937 DumpOffsets[DIDT_ID_##ENUM_NAME] = Dump##ENUM_NAME.Val; \
938 OffsetRequested = true; \
939 } \
940 }
941#include "llvm/BinaryFormat/Dwarf.def"
942#undef HANDLE_DWARF_SECTION
943 if (DumpUUID)
944 DumpType |= DIDT_UUID;
945 if (DumpAll)
946 DumpType = DIDT_All;
947 if (DumpType == DIDT_Null && !ShowVariableCoverage &&
948 CoverageBaseline.empty() && BitcodeFile.empty()) {
949 if (Verbose || Verify)
950 DumpType = DIDT_All;
951 else
952 DumpType = DIDT_DebugInfo;
953 }
954
955 // Unless dumping a specific DIE, default to --show-children.
956 if (!ShowChildren && !Verify && !OffsetRequested && Name.empty() &&
957 Find.empty() && !FindAllApple)
958 ShowChildren = true;
959
960 // Defaults to a.out if no filenames specified.
961 if (InputFilenames.empty())
962 InputFilenames.push_back(value: "a.out");
963
964 // Expand any .dSYM bundles to the individual object files contained therein.
965 std::vector<std::string> Objects;
966 for (const auto &F : InputFilenames) {
967 if (auto DsymObjectsOrErr = MachOObjectFile::findDsymObjectMembers(Path: F)) {
968 if (DsymObjectsOrErr->empty())
969 Objects.push_back(x: F);
970 else
971 llvm::append_range(C&: Objects, R&: *DsymObjectsOrErr);
972 } else {
973 error(Err: DsymObjectsOrErr.takeError());
974 }
975 }
976
977 bool Success = true;
978 if (Verify) {
979 if (!VerifyNumThreads)
980 parallel::strategy =
981 hardware_concurrency(ThreadCount: hardware_concurrency().compute_thread_count());
982 else
983 parallel::strategy = hardware_concurrency(ThreadCount: VerifyNumThreads);
984 for (StringRef Object : Objects)
985 Success &= handleFile(Filename: Object, HandleObj: verifyObjectFile, OS&: OutputFile.os());
986 } else if (Statistics) {
987 for (StringRef Object : Objects)
988 Success &= handleFile(Filename: Object, HandleObj: collectStatsForObjectFile, OS&: OutputFile.os());
989 } else if (ShowSectionSizes) {
990 for (StringRef Object : Objects)
991 Success &= handleFile(Filename: Object, HandleObj: collectObjectSectionSizes, OS&: OutputFile.os());
992 } else if (ShowSources) {
993 for (StringRef Object : Objects)
994 Success &= handleFile(Filename: Object, HandleObj: collectObjectSources, OS&: OutputFile.os());
995 } else {
996 for (StringRef Object : Objects)
997 Success &= handleFile(Filename: Object, HandleObj: dumpObjectFile, OS&: OutputFile.os());
998 }
999
1000 if (!CoverageBaseline.empty()) {
1001 auto handleBaseline = [&](ObjectFile &BaselineObj,
1002 DWARFContext &BaselineCtx, const Twine &Filename,
1003 raw_ostream &OS) {
1004 auto showCoverage = [&](ObjectFile &Obj, DWARFContext &DICtx,
1005 const Twine &Filename, raw_ostream &OS) {
1006 return showVariableCoverage(Obj, DICtx, BaselineObj: &BaselineObj, BaselineCtx: &BaselineCtx,
1007 BitcodeFile, MaybeUndefined,
1008 CombineInstances, OS);
1009 };
1010 for (StringRef Object : Objects)
1011 Success &= handleFile(Filename: Object, HandleObj: showCoverage, OS&: OutputFile.os());
1012 return true;
1013 };
1014 Success &= handleFile(Filename: CoverageBaseline, HandleObj: handleBaseline, OS&: OutputFile.os());
1015 } else if (ShowVariableCoverage || !BitcodeFile.empty()) {
1016 auto showCoverage = [&](ObjectFile &Obj, DWARFContext &DICtx,
1017 const Twine &Filename, raw_ostream &OS) {
1018 return showVariableCoverage(Obj, DICtx, BaselineObj: nullptr, BaselineCtx: nullptr, BitcodeFile,
1019 MaybeUndefined, CombineInstances, OS);
1020 };
1021 for (StringRef Object : Objects)
1022 Success &= handleFile(Filename: Object, HandleObj: showCoverage, OS&: OutputFile.os());
1023 }
1024
1025 return Success ? EXIT_SUCCESS : EXIT_FAILURE;
1026}
1027