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