xref: /freebsd/contrib/llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp (revision cfd6422a5217410fbd66f7a7a8a64d9d85e61229)
1 //===- llvm-readobj.cpp - Dump contents of an Object File -----------------===//
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 is a tool similar to readelf, except it works on multiple object file
10 // formats. The main purpose of this tool is to provide detailed output suitable
11 // for FileCheck.
12 //
13 // Flags should be similar to readelf where supported, but the output format
14 // does not need to be identical. The point is to not make users learn yet
15 // another set of flags.
16 //
17 // Output should be specialized for each format where appropriate.
18 //
19 //===----------------------------------------------------------------------===//
20 
21 #include "llvm-readobj.h"
22 #include "Error.h"
23 #include "ObjDumper.h"
24 #include "WindowsResourceDumper.h"
25 #include "llvm/DebugInfo/CodeView/GlobalTypeTableBuilder.h"
26 #include "llvm/DebugInfo/CodeView/MergingTypeTableBuilder.h"
27 #include "llvm/Object/Archive.h"
28 #include "llvm/Object/COFFImportFile.h"
29 #include "llvm/Object/MachOUniversal.h"
30 #include "llvm/Object/ObjectFile.h"
31 #include "llvm/Object/WindowsResource.h"
32 #include "llvm/Support/Casting.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/DataTypes.h"
35 #include "llvm/Support/Debug.h"
36 #include "llvm/Support/FileSystem.h"
37 #include "llvm/Support/FormatVariadic.h"
38 #include "llvm/Support/InitLLVM.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/ScopedPrinter.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/WithColor.h"
43 
44 using namespace llvm;
45 using namespace llvm::object;
46 
47 namespace opts {
48   cl::list<std::string> InputFilenames(cl::Positional,
49     cl::desc("<input object files>"),
50     cl::ZeroOrMore);
51 
52   // --all, -a
53   cl::opt<bool>
54       All("all",
55           cl::desc("Equivalent to setting: --file-headers, --program-headers, "
56                    "--section-headers, --symbols, --relocations, "
57                    "--dynamic-table, --notes, --version-info, --unwind, "
58                    "--section-groups and --elf-hash-histogram."));
59   cl::alias AllShort("a", cl::desc("Alias for --all"), cl::aliasopt(All));
60 
61   // --dependent-libraries
62   cl::opt<bool>
63       DependentLibraries("dependent-libraries",
64                          cl::desc("Display the dependent libraries section"));
65 
66   // --headers -e
67   cl::opt<bool>
68       Headers("headers",
69           cl::desc("Equivalent to setting: --file-headers, --program-headers, "
70                    "--section-headers"));
71   cl::alias HeadersShort("e", cl::desc("Alias for --headers"),
72      cl::aliasopt(Headers));
73 
74   // --wide, -W
75   cl::opt<bool>
76       WideOutput("wide", cl::desc("Ignored for compatibility with GNU readelf"),
77                  cl::Hidden);
78   cl::alias WideOutputShort("W",
79     cl::desc("Alias for --wide"),
80     cl::aliasopt(WideOutput));
81 
82   // --file-headers, --file-header, -h
83   cl::opt<bool> FileHeaders("file-headers",
84     cl::desc("Display file headers "));
85   cl::alias FileHeadersShort("h", cl::desc("Alias for --file-headers"),
86                              cl::aliasopt(FileHeaders), cl::NotHidden);
87   cl::alias FileHeadersSingular("file-header",
88                                 cl::desc("Alias for --file-headers"),
89                                 cl::aliasopt(FileHeaders));
90 
91   // --section-headers, --sections, -S
92   // Also -s in llvm-readobj mode.
93   cl::opt<bool> SectionHeaders("section-headers",
94                                cl::desc("Display all section headers."));
95   cl::alias SectionsShortUpper("S", cl::desc("Alias for --section-headers"),
96                                cl::aliasopt(SectionHeaders), cl::NotHidden);
97   cl::alias SectionHeadersAlias("sections",
98                                 cl::desc("Alias for --section-headers"),
99                                 cl::aliasopt(SectionHeaders), cl::NotHidden);
100 
101   // --section-relocations
102   // Also --sr in llvm-readobj mode.
103   cl::opt<bool> SectionRelocations("section-relocations",
104     cl::desc("Display relocations for each section shown."));
105 
106   // --section-symbols
107   // Also --st in llvm-readobj mode.
108   cl::opt<bool> SectionSymbols("section-symbols",
109     cl::desc("Display symbols for each section shown."));
110 
111   // --section-data
112   // Also --sd in llvm-readobj mode.
113   cl::opt<bool> SectionData("section-data",
114     cl::desc("Display section data for each section shown."));
115 
116   // --section-mapping
117   cl::opt<cl::boolOrDefault>
118       SectionMapping("section-mapping",
119                      cl::desc("Display the section to segment mapping."));
120 
121   // --relocations, --relocs, -r
122   cl::opt<bool> Relocations("relocations",
123     cl::desc("Display the relocation entries in the file"));
124   cl::alias RelocationsShort("r", cl::desc("Alias for --relocations"),
125                              cl::aliasopt(Relocations), cl::NotHidden);
126   cl::alias RelocationsGNU("relocs", cl::desc("Alias for --relocations"),
127                            cl::aliasopt(Relocations));
128 
129   // --notes, -n
130   cl::opt<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
131   cl::alias NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes));
132 
133   // --dyn-relocations
134   cl::opt<bool> DynRelocs("dyn-relocations",
135     cl::desc("Display the dynamic relocation entries in the file"));
136 
137   // --symbols
138   // Also -s in llvm-readelf mode, or -t in llvm-readobj mode.
139   cl::opt<bool>
140       Symbols("symbols",
141               cl::desc("Display the symbol table. Also display the dynamic "
142                        "symbol table when using GNU output style for ELF"));
143   cl::alias SymbolsGNU("syms", cl::desc("Alias for --symbols"),
144                        cl::aliasopt(Symbols));
145 
146   // --dyn-symbols, --dyn-syms
147   // Also --dt in llvm-readobj mode.
148   cl::opt<bool> DynamicSymbols("dyn-symbols",
149     cl::desc("Display the dynamic symbol table"));
150   cl::alias DynSymsGNU("dyn-syms", cl::desc("Alias for --dyn-symbols"),
151                        cl::aliasopt(DynamicSymbols));
152 
153   // --hash-symbols
154   cl::opt<bool> HashSymbols(
155       "hash-symbols",
156       cl::desc("Display the dynamic symbols derived from the hash section"));
157 
158   // --unwind, -u
159   cl::opt<bool> UnwindInfo("unwind",
160     cl::desc("Display unwind information"));
161   cl::alias UnwindInfoShort("u",
162     cl::desc("Alias for --unwind"),
163     cl::aliasopt(UnwindInfo));
164 
165   // --dynamic-table, --dynamic, -d
166   cl::opt<bool> DynamicTable("dynamic-table",
167     cl::desc("Display the ELF .dynamic section table"));
168   cl::alias DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
169                               cl::aliasopt(DynamicTable), cl::NotHidden);
170   cl::alias DynamicTableAlias("dynamic", cl::desc("Alias for --dynamic-table"),
171                               cl::aliasopt(DynamicTable));
172 
173   // --needed-libs
174   cl::opt<bool> NeededLibraries("needed-libs",
175     cl::desc("Display the needed libraries"));
176 
177   // --program-headers, --segments, -l
178   cl::opt<bool> ProgramHeaders("program-headers",
179     cl::desc("Display ELF program headers"));
180   cl::alias ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
181                                 cl::aliasopt(ProgramHeaders), cl::NotHidden);
182   cl::alias SegmentsAlias("segments", cl::desc("Alias for --program-headers"),
183                           cl::aliasopt(ProgramHeaders));
184 
185   // --string-dump, -p
186   cl::list<std::string> StringDump("string-dump", cl::desc("<number|name>"),
187                                    cl::ZeroOrMore);
188   cl::alias StringDumpShort("p", cl::desc("Alias for --string-dump"),
189                             cl::aliasopt(StringDump), cl::Prefix);
190 
191   // --hex-dump, -x
192   cl::list<std::string> HexDump("hex-dump", cl::desc("<number|name>"),
193                                 cl::ZeroOrMore);
194   cl::alias HexDumpShort("x", cl::desc("Alias for --hex-dump"),
195                          cl::aliasopt(HexDump), cl::Prefix);
196 
197   // --demangle, -C
198   cl::opt<bool> Demangle("demangle",
199                          cl::desc("Demangle symbol names in output"));
200   cl::alias DemangleShort("C", cl::desc("Alias for --demangle"),
201                           cl::aliasopt(Demangle), cl::NotHidden);
202 
203   // --hash-table
204   cl::opt<bool> HashTable("hash-table",
205     cl::desc("Display ELF hash table"));
206 
207   // --gnu-hash-table
208   cl::opt<bool> GnuHashTable("gnu-hash-table",
209     cl::desc("Display ELF .gnu.hash section"));
210 
211   // --expand-relocs
212   cl::opt<bool> ExpandRelocs("expand-relocs",
213     cl::desc("Expand each shown relocation to multiple lines"));
214 
215   // --raw-relr
216   cl::opt<bool> RawRelr("raw-relr",
217     cl::desc("Do not decode relocations in SHT_RELR section, display raw contents"));
218 
219   // --codeview
220   cl::opt<bool> CodeView("codeview",
221                          cl::desc("Display CodeView debug information"));
222 
223   // --codeview-merged-types
224   cl::opt<bool>
225       CodeViewMergedTypes("codeview-merged-types",
226                           cl::desc("Display the merged CodeView type stream"));
227 
228   // --codeview-ghash
229   cl::opt<bool> CodeViewEnableGHash(
230       "codeview-ghash",
231       cl::desc(
232           "Enable global hashing for CodeView type stream de-duplication"));
233 
234   // --codeview-subsection-bytes
235   cl::opt<bool> CodeViewSubsectionBytes(
236       "codeview-subsection-bytes",
237       cl::desc("Dump raw contents of codeview debug sections and records"));
238 
239   // --arch-specific
240   cl::opt<bool> ArchSpecificInfo("arch-specific",
241                               cl::desc("Displays architecture-specific information, if there is any."));
242   cl::alias ArchSpecifcInfoShort("A", cl::desc("Alias for --arch-specific"),
243                                  cl::aliasopt(ArchSpecificInfo), cl::NotHidden);
244 
245   // --coff-imports
246   cl::opt<bool>
247   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
248 
249   // --coff-exports
250   cl::opt<bool>
251   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
252 
253   // --coff-directives
254   cl::opt<bool>
255   COFFDirectives("coff-directives",
256                  cl::desc("Display the PE/COFF .drectve section"));
257 
258   // --coff-basereloc
259   cl::opt<bool>
260   COFFBaseRelocs("coff-basereloc",
261                  cl::desc("Display the PE/COFF .reloc section"));
262 
263   // --coff-debug-directory
264   cl::opt<bool>
265   COFFDebugDirectory("coff-debug-directory",
266                      cl::desc("Display the PE/COFF debug directory"));
267 
268   // --coff-resources
269   cl::opt<bool> COFFResources("coff-resources",
270                               cl::desc("Display the PE/COFF .rsrc section"));
271 
272   // --coff-load-config
273   cl::opt<bool>
274   COFFLoadConfig("coff-load-config",
275                  cl::desc("Display the PE/COFF load config"));
276 
277   // --elf-linker-options
278   cl::opt<bool>
279   ELFLinkerOptions("elf-linker-options",
280                    cl::desc("Display the ELF .linker-options section"));
281 
282   // --macho-data-in-code
283   cl::opt<bool>
284   MachODataInCode("macho-data-in-code",
285                   cl::desc("Display MachO Data in Code command"));
286 
287   // --macho-indirect-symbols
288   cl::opt<bool>
289   MachOIndirectSymbols("macho-indirect-symbols",
290                   cl::desc("Display MachO indirect symbols"));
291 
292   // --macho-linker-options
293   cl::opt<bool>
294   MachOLinkerOptions("macho-linker-options",
295                   cl::desc("Display MachO linker options"));
296 
297   // --macho-segment
298   cl::opt<bool>
299   MachOSegment("macho-segment",
300                   cl::desc("Display MachO Segment command"));
301 
302   // --macho-version-min
303   cl::opt<bool>
304   MachOVersionMin("macho-version-min",
305                   cl::desc("Display MachO version min command"));
306 
307   // --macho-dysymtab
308   cl::opt<bool>
309   MachODysymtab("macho-dysymtab",
310                   cl::desc("Display MachO Dysymtab command"));
311 
312   // --stackmap
313   cl::opt<bool>
314   PrintStackMap("stackmap",
315                 cl::desc("Display contents of stackmap section"));
316 
317   // --stack-sizes
318   cl::opt<bool>
319       PrintStackSizes("stack-sizes",
320                       cl::desc("Display contents of all stack sizes sections"));
321 
322   // --version-info, -V
323   cl::opt<bool>
324       VersionInfo("version-info",
325                   cl::desc("Display ELF version sections (if present)"));
326   cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"),
327                              cl::aliasopt(VersionInfo));
328 
329   // --elf-section-groups, --section-groups, -g
330   cl::opt<bool> SectionGroups("elf-section-groups",
331                               cl::desc("Display ELF section group contents"));
332   cl::alias SectionGroupsAlias("section-groups",
333                                cl::desc("Alias for -elf-sections-groups"),
334                                cl::aliasopt(SectionGroups));
335   cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
336                                cl::aliasopt(SectionGroups));
337 
338   // --elf-hash-histogram, --histogram, -I
339   cl::opt<bool> HashHistogram(
340       "elf-hash-histogram",
341       cl::desc("Display bucket list histogram for hash sections"));
342   cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
343                                cl::aliasopt(HashHistogram));
344   cl::alias HistogramAlias("histogram",
345                            cl::desc("Alias for --elf-hash-histogram"),
346                            cl::aliasopt(HashHistogram));
347 
348   // --cg-profile
349   cl::opt<bool> CGProfile("cg-profile",
350                           cl::desc("Display callgraph profile section"));
351   cl::alias ELFCGProfile("elf-cg-profile", cl::desc("Alias for --cg-profile"),
352                          cl::aliasopt(CGProfile));
353 
354   // -addrsig
355   cl::opt<bool> Addrsig("addrsig",
356                         cl::desc("Display address-significance table"));
357 
358   // -elf-output-style
359   cl::opt<OutputStyleTy>
360       Output("elf-output-style", cl::desc("Specify ELF dump style"),
361              cl::values(clEnumVal(LLVM, "LLVM default style"),
362                         clEnumVal(GNU, "GNU readelf style")),
363              cl::init(LLVM));
364 
365   cl::extrahelp
366       HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
367 } // namespace opts
368 
369 static StringRef ToolName;
370 
371 namespace llvm {
372 
373 LLVM_ATTRIBUTE_NORETURN static void error(Twine Msg) {
374   // Flush the standard output to print the error at a
375   // proper place.
376   fouts().flush();
377   WithColor::error(errs(), ToolName) << Msg << "\n";
378   exit(1);
379 }
380 
381 LLVM_ATTRIBUTE_NORETURN void reportError(Error Err, StringRef Input) {
382   assert(Err);
383   if (Input == "-")
384     Input = "<stdin>";
385   handleAllErrors(createFileError(Input, std::move(Err)),
386                   [&](const ErrorInfoBase &EI) { error(EI.message()); });
387   llvm_unreachable("error() call should never return");
388 }
389 
390 void reportWarning(Error Err, StringRef Input) {
391   assert(Err);
392   if (Input == "-")
393     Input = "<stdin>";
394 
395   // Flush the standard output to print the warning at a
396   // proper place.
397   fouts().flush();
398   handleAllErrors(
399       createFileError(Input, std::move(Err)), [&](const ErrorInfoBase &EI) {
400         WithColor::warning(errs(), ToolName) << EI.message() << "\n";
401       });
402 }
403 
404 } // namespace llvm
405 
406 namespace {
407 struct ReadObjTypeTableBuilder {
408   ReadObjTypeTableBuilder()
409       : Allocator(), IDTable(Allocator), TypeTable(Allocator),
410         GlobalIDTable(Allocator), GlobalTypeTable(Allocator) {}
411 
412   llvm::BumpPtrAllocator Allocator;
413   llvm::codeview::MergingTypeTableBuilder IDTable;
414   llvm::codeview::MergingTypeTableBuilder TypeTable;
415   llvm::codeview::GlobalTypeTableBuilder GlobalIDTable;
416   llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable;
417   std::vector<OwningBinary<Binary>> Binaries;
418 };
419 } // namespace
420 static ReadObjTypeTableBuilder CVTypes;
421 
422 /// Creates an format-specific object file dumper.
423 static std::error_code createDumper(const ObjectFile *Obj,
424                                     ScopedPrinter &Writer,
425                                     std::unique_ptr<ObjDumper> &Result) {
426   if (!Obj)
427     return readobj_error::unsupported_file_format;
428 
429   if (Obj->isCOFF())
430     return createCOFFDumper(Obj, Writer, Result);
431   if (Obj->isELF())
432     return createELFDumper(Obj, Writer, Result);
433   if (Obj->isMachO())
434     return createMachODumper(Obj, Writer, Result);
435   if (Obj->isWasm())
436     return createWasmDumper(Obj, Writer, Result);
437   if (Obj->isXCOFF())
438     return createXCOFFDumper(Obj, Writer, Result);
439 
440   return readobj_error::unsupported_obj_file_format;
441 }
442 
443 /// Dumps the specified object file.
444 static void dumpObject(const ObjectFile *Obj, ScopedPrinter &Writer,
445                        const Archive *A = nullptr) {
446   std::string FileStr =
447           A ? Twine(A->getFileName() + "(" + Obj->getFileName() + ")").str()
448             : Obj->getFileName().str();
449 
450   std::unique_ptr<ObjDumper> Dumper;
451   if (std::error_code EC = createDumper(Obj, Writer, Dumper))
452     reportError(errorCodeToError(EC), FileStr);
453 
454   if (opts::Output == opts::LLVM || opts::InputFilenames.size() > 1 || A) {
455     Writer.startLine() << "\n";
456     Writer.printString("File", FileStr);
457   }
458   if (opts::Output == opts::LLVM) {
459     Writer.printString("Format", Obj->getFileFormatName());
460     Writer.printString("Arch", Triple::getArchTypeName(
461                                    (llvm::Triple::ArchType)Obj->getArch()));
462     Writer.printString(
463         "AddressSize",
464         std::string(formatv("{0}bit", 8 * Obj->getBytesInAddress())));
465     Dumper->printLoadName();
466   }
467 
468   if (opts::FileHeaders)
469     Dumper->printFileHeaders();
470   if (opts::SectionHeaders)
471     Dumper->printSectionHeaders();
472   if (opts::HashSymbols)
473     Dumper->printHashSymbols();
474   if (opts::ProgramHeaders || opts::SectionMapping == cl::BOU_TRUE)
475     Dumper->printProgramHeaders(opts::ProgramHeaders, opts::SectionMapping);
476   if (opts::DynamicTable)
477     Dumper->printDynamicTable();
478   if (opts::NeededLibraries)
479     Dumper->printNeededLibraries();
480   if (opts::Relocations)
481     Dumper->printRelocations();
482   if (opts::DynRelocs)
483     Dumper->printDynamicRelocations();
484   if (opts::UnwindInfo)
485     Dumper->printUnwindInfo();
486   if (opts::Symbols || opts::DynamicSymbols)
487     Dumper->printSymbols(opts::Symbols, opts::DynamicSymbols);
488   if (!opts::StringDump.empty())
489     Dumper->printSectionsAsString(Obj, opts::StringDump);
490   if (!opts::HexDump.empty())
491     Dumper->printSectionsAsHex(Obj, opts::HexDump);
492   if (opts::HashTable)
493     Dumper->printHashTable();
494   if (opts::GnuHashTable)
495     Dumper->printGnuHashTable(Obj);
496   if (opts::VersionInfo)
497     Dumper->printVersionInfo();
498   if (Obj->isELF()) {
499     if (opts::DependentLibraries)
500       Dumper->printDependentLibs();
501     if (opts::ELFLinkerOptions)
502       Dumper->printELFLinkerOptions();
503     if (opts::ArchSpecificInfo)
504       Dumper->printArchSpecificInfo();
505     if (opts::SectionGroups)
506       Dumper->printGroupSections();
507     if (opts::HashHistogram)
508       Dumper->printHashHistograms();
509     if (opts::CGProfile)
510       Dumper->printCGProfile();
511     if (opts::Addrsig)
512       Dumper->printAddrsig();
513     if (opts::Notes)
514       Dumper->printNotes();
515   }
516   if (Obj->isCOFF()) {
517     if (opts::COFFImports)
518       Dumper->printCOFFImports();
519     if (opts::COFFExports)
520       Dumper->printCOFFExports();
521     if (opts::COFFDirectives)
522       Dumper->printCOFFDirectives();
523     if (opts::COFFBaseRelocs)
524       Dumper->printCOFFBaseReloc();
525     if (opts::COFFDebugDirectory)
526       Dumper->printCOFFDebugDirectory();
527     if (opts::COFFResources)
528       Dumper->printCOFFResources();
529     if (opts::COFFLoadConfig)
530       Dumper->printCOFFLoadConfig();
531     if (opts::CGProfile)
532       Dumper->printCGProfile();
533     if (opts::Addrsig)
534       Dumper->printAddrsig();
535     if (opts::CodeView)
536       Dumper->printCodeViewDebugInfo();
537     if (opts::CodeViewMergedTypes)
538       Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable,
539                                  CVTypes.GlobalIDTable, CVTypes.GlobalTypeTable,
540                                  opts::CodeViewEnableGHash);
541   }
542   if (Obj->isMachO()) {
543     if (opts::MachODataInCode)
544       Dumper->printMachODataInCode();
545     if (opts::MachOIndirectSymbols)
546       Dumper->printMachOIndirectSymbols();
547     if (opts::MachOLinkerOptions)
548       Dumper->printMachOLinkerOptions();
549     if (opts::MachOSegment)
550       Dumper->printMachOSegment();
551     if (opts::MachOVersionMin)
552       Dumper->printMachOVersionMin();
553     if (opts::MachODysymtab)
554       Dumper->printMachODysymtab();
555   }
556   if (opts::PrintStackMap)
557     Dumper->printStackMap();
558   if (opts::PrintStackSizes)
559     Dumper->printStackSizes();
560 }
561 
562 /// Dumps each object file in \a Arc;
563 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) {
564   Error Err = Error::success();
565   for (auto &Child : Arc->children(Err)) {
566     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
567     if (!ChildOrErr) {
568       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
569         reportError(std::move(E), Arc->getFileName());
570       continue;
571     }
572     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
573       dumpObject(Obj, Writer, Arc);
574     else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
575       dumpCOFFImportFile(Imp, Writer);
576     else
577       reportError(errorCodeToError(readobj_error::unrecognized_file_format),
578                   Arc->getFileName());
579   }
580   if (Err)
581     reportError(std::move(Err), Arc->getFileName());
582 }
583 
584 /// Dumps each object file in \a MachO Universal Binary;
585 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary,
586                                      ScopedPrinter &Writer) {
587   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
588     Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
589     if (ObjOrErr)
590       dumpObject(&*ObjOrErr.get(), Writer);
591     else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError()))
592       reportError(ObjOrErr.takeError(), UBinary->getFileName());
593     else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
594       dumpArchive(&*AOrErr.get(), Writer);
595   }
596 }
597 
598 /// Dumps \a WinRes, Windows Resource (.res) file;
599 static void dumpWindowsResourceFile(WindowsResource *WinRes,
600                                     ScopedPrinter &Printer) {
601   WindowsRes::Dumper Dumper(WinRes, Printer);
602   if (auto Err = Dumper.printData())
603     reportError(std::move(Err), WinRes->getFileName());
604 }
605 
606 
607 /// Opens \a File and dumps it.
608 static void dumpInput(StringRef File, ScopedPrinter &Writer) {
609   // Attempt to open the binary.
610   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
611   if (!BinaryOrErr)
612     reportError(BinaryOrErr.takeError(), File);
613   Binary &Binary = *BinaryOrErr.get().getBinary();
614 
615   if (Archive *Arc = dyn_cast<Archive>(&Binary))
616     dumpArchive(Arc, Writer);
617   else if (MachOUniversalBinary *UBinary =
618                dyn_cast<MachOUniversalBinary>(&Binary))
619     dumpMachOUniversalBinary(UBinary, Writer);
620   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
621     dumpObject(Obj, Writer);
622   else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
623     dumpCOFFImportFile(Import, Writer);
624   else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary))
625     dumpWindowsResourceFile(WinRes, Writer);
626   else
627     reportError(errorCodeToError(readobj_error::unrecognized_file_format),
628                 File);
629 
630   CVTypes.Binaries.push_back(std::move(*BinaryOrErr));
631 }
632 
633 /// Registers aliases that should only be allowed by readobj.
634 static void registerReadobjAliases() {
635   // -s has meant --sections for a very long time in llvm-readobj despite
636   // meaning --symbols in readelf.
637   static cl::alias SectionsShort("s", cl::desc("Alias for --section-headers"),
638                                  cl::aliasopt(opts::SectionHeaders),
639                                  cl::NotHidden);
640 
641   // Only register -t in llvm-readobj, as readelf reserves it for
642   // --section-details (not implemented yet).
643   static cl::alias SymbolsShort("t", cl::desc("Alias for --symbols"),
644                                 cl::aliasopt(opts::Symbols), cl::NotHidden);
645 
646   // The following two-letter aliases are only provided for readobj, as readelf
647   // allows single-letter args to be grouped together.
648   static cl::alias SectionRelocationsShort(
649       "sr", cl::desc("Alias for --section-relocations"),
650       cl::aliasopt(opts::SectionRelocations));
651   static cl::alias SectionDataShort("sd", cl::desc("Alias for --section-data"),
652                                     cl::aliasopt(opts::SectionData));
653   static cl::alias SectionSymbolsShort("st",
654                                        cl::desc("Alias for --section-symbols"),
655                                        cl::aliasopt(opts::SectionSymbols));
656   static cl::alias DynamicSymbolsShort("dt",
657                                        cl::desc("Alias for --dyn-symbols"),
658                                        cl::aliasopt(opts::DynamicSymbols));
659 }
660 
661 /// Registers aliases that should only be allowed by readelf.
662 static void registerReadelfAliases() {
663   // -s is here because for readobj it means --sections.
664   static cl::alias SymbolsShort("s", cl::desc("Alias for --symbols"),
665                                 cl::aliasopt(opts::Symbols), cl::NotHidden,
666                                 cl::Grouping);
667 
668   // Allow all single letter flags to be grouped together.
669   for (auto &OptEntry : cl::getRegisteredOptions()) {
670     StringRef ArgName = OptEntry.getKey();
671     cl::Option *Option = OptEntry.getValue();
672     if (ArgName.size() == 1)
673       apply(Option, cl::Grouping);
674   }
675 }
676 
677 int main(int argc, const char *argv[]) {
678   InitLLVM X(argc, argv);
679   ToolName = argv[0];
680 
681   // Register the target printer for --version.
682   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
683 
684   if (sys::path::stem(argv[0]).contains("readelf")) {
685     opts::Output = opts::GNU;
686     registerReadelfAliases();
687   } else {
688     registerReadobjAliases();
689   }
690 
691   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
692 
693   if (opts::All) {
694     opts::FileHeaders = true;
695     opts::ProgramHeaders = true;
696     opts::SectionHeaders = true;
697     opts::Symbols = true;
698     opts::Relocations = true;
699     opts::DynamicTable = true;
700     opts::Notes = true;
701     opts::VersionInfo = true;
702     opts::UnwindInfo = true;
703     opts::SectionGroups = true;
704     opts::HashHistogram = true;
705     if (opts::Output == opts::LLVM) {
706       opts::Addrsig = true;
707       opts::PrintStackSizes = true;
708     }
709   }
710 
711   if (opts::Headers) {
712     opts::FileHeaders = true;
713     opts::ProgramHeaders = true;
714     opts::SectionHeaders = true;
715   }
716 
717   // Default to stdin if no filename is specified.
718   if (opts::InputFilenames.empty())
719     opts::InputFilenames.push_back("-");
720 
721   ScopedPrinter Writer(fouts());
722   for (const std::string &I : opts::InputFilenames)
723     dumpInput(I, Writer);
724 
725   if (opts::CodeViewMergedTypes) {
726     if (opts::CodeViewEnableGHash)
727       dumpCodeViewMergedTypes(Writer, CVTypes.GlobalIDTable.records(),
728                               CVTypes.GlobalTypeTable.records());
729     else
730       dumpCodeViewMergedTypes(Writer, CVTypes.IDTable.records(),
731                               CVTypes.TypeTable.records());
732   }
733 
734   return 0;
735 }
736