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