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