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