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