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