[InstCombine] Signed saturation patterns
[llvm-core.git] / tools / llvm-readobj / llvm-readobj.cpp
blob4db13897879d1121bf28b37266eaf6b04a8dca0f
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.
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.
17 // Output should be specialized for each format where appropriate.
19 //===----------------------------------------------------------------------===//
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"
44 using namespace llvm;
45 using namespace llvm::object;
47 namespace opts {
48 cl::list<std::string> InputFilenames(cl::Positional,
49 cl::desc("<input object files>"),
50 cl::ZeroOrMore);
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));
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));
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));
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));
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);
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."));
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."));
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."));
111 // --section-mapping
112 cl::opt<cl::boolOrDefault>
113 SectionMapping("section-mapping",
114 cl::desc("Display the section to segment mapping."));
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));
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));
128 // --dyn-relocations
129 cl::opt<bool> DynRelocs("dyn-relocations",
130 cl::desc("Display the dynamic relocation entries in the file"));
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));
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));
148 // --hash-symbols
149 cl::opt<bool> HashSymbols(
150 "hash-symbols",
151 cl::desc("Display the dynamic symbols derived from the hash section"));
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));
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));
168 // --needed-libs
169 cl::opt<bool> NeededLibraries("needed-libs",
170 cl::desc("Display the needed libraries"));
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));
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);
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);
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);
198 // --hash-table
199 cl::opt<bool> HashTable("hash-table",
200 cl::desc("Display ELF hash table"));
202 // --gnu-hash-table
203 cl::opt<bool> GnuHashTable("gnu-hash-table",
204 cl::desc("Display ELF .gnu.hash section"));
206 // --expand-relocs
207 cl::opt<bool> ExpandRelocs("expand-relocs",
208 cl::desc("Expand each shown relocation to multiple lines"));
210 // --raw-relr
211 cl::opt<bool> RawRelr("raw-relr",
212 cl::desc("Do not decode relocations in SHT_RELR section, display raw contents"));
214 // --codeview
215 cl::opt<bool> CodeView("codeview",
216 cl::desc("Display CodeView debug information"));
218 // --codeview-merged-types
219 cl::opt<bool>
220 CodeViewMergedTypes("codeview-merged-types",
221 cl::desc("Display the merged CodeView type stream"));
223 // --codeview-ghash
224 cl::opt<bool> CodeViewEnableGHash(
225 "codeview-ghash",
226 cl::desc(
227 "Enable global hashing for CodeView type stream de-duplication"));
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"));
234 // --arch-specific
235 cl::opt<bool> ArchSpecificInfo("arch-specific",
236 cl::desc("Displays architecture-specific information, if there is any."));
237 cl::alias ArchSpecifcInfoShort("A", cl::desc("Alias for --arch-specific"),
238 cl::aliasopt(ArchSpecificInfo), cl::NotHidden);
240 // --coff-imports
241 cl::opt<bool>
242 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
244 // --coff-exports
245 cl::opt<bool>
246 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
248 // --coff-directives
249 cl::opt<bool>
250 COFFDirectives("coff-directives",
251 cl::desc("Display the PE/COFF .drectve section"));
253 // --coff-basereloc
254 cl::opt<bool>
255 COFFBaseRelocs("coff-basereloc",
256 cl::desc("Display the PE/COFF .reloc section"));
258 // --coff-debug-directory
259 cl::opt<bool>
260 COFFDebugDirectory("coff-debug-directory",
261 cl::desc("Display the PE/COFF debug directory"));
263 // --coff-resources
264 cl::opt<bool> COFFResources("coff-resources",
265 cl::desc("Display the PE/COFF .rsrc section"));
267 // --coff-load-config
268 cl::opt<bool>
269 COFFLoadConfig("coff-load-config",
270 cl::desc("Display the PE/COFF load config"));
272 // --elf-linker-options
273 cl::opt<bool>
274 ELFLinkerOptions("elf-linker-options",
275 cl::desc("Display the ELF .linker-options section"));
277 // --macho-data-in-code
278 cl::opt<bool>
279 MachODataInCode("macho-data-in-code",
280 cl::desc("Display MachO Data in Code command"));
282 // --macho-indirect-symbols
283 cl::opt<bool>
284 MachOIndirectSymbols("macho-indirect-symbols",
285 cl::desc("Display MachO indirect symbols"));
287 // --macho-linker-options
288 cl::opt<bool>
289 MachOLinkerOptions("macho-linker-options",
290 cl::desc("Display MachO linker options"));
292 // --macho-segment
293 cl::opt<bool>
294 MachOSegment("macho-segment",
295 cl::desc("Display MachO Segment command"));
297 // --macho-version-min
298 cl::opt<bool>
299 MachOVersionMin("macho-version-min",
300 cl::desc("Display MachO version min command"));
302 // --macho-dysymtab
303 cl::opt<bool>
304 MachODysymtab("macho-dysymtab",
305 cl::desc("Display MachO Dysymtab command"));
307 // --stackmap
308 cl::opt<bool>
309 PrintStackMap("stackmap",
310 cl::desc("Display contents of stackmap section"));
312 // --stack-sizes
313 cl::opt<bool>
314 PrintStackSizes("stack-sizes",
315 cl::desc("Display contents of all stack sizes sections"));
317 // --version-info, -V
318 cl::opt<bool>
319 VersionInfo("version-info",
320 cl::desc("Display ELF version sections (if present)"));
321 cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"),
322 cl::aliasopt(VersionInfo));
324 // --elf-section-groups, --section-groups, -g
325 cl::opt<bool> SectionGroups("elf-section-groups",
326 cl::desc("Display ELF section group contents"));
327 cl::alias SectionGroupsAlias("section-groups",
328 cl::desc("Alias for -elf-sections-groups"),
329 cl::aliasopt(SectionGroups));
330 cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
331 cl::aliasopt(SectionGroups));
333 // --elf-hash-histogram, --histogram, -I
334 cl::opt<bool> HashHistogram(
335 "elf-hash-histogram",
336 cl::desc("Display bucket list histogram for hash sections"));
337 cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
338 cl::aliasopt(HashHistogram));
339 cl::alias HistogramAlias("histogram",
340 cl::desc("Alias for --elf-hash-histogram"),
341 cl::aliasopt(HashHistogram));
343 // --elf-cg-profile
344 cl::opt<bool> CGProfile("elf-cg-profile", cl::desc("Display callgraph profile section"));
346 // -addrsig
347 cl::opt<bool> Addrsig("addrsig",
348 cl::desc("Display address-significance table"));
350 // -elf-output-style
351 cl::opt<OutputStyleTy>
352 Output("elf-output-style", cl::desc("Specify ELF dump style"),
353 cl::values(clEnumVal(LLVM, "LLVM default style"),
354 clEnumVal(GNU, "GNU readelf style")),
355 cl::init(LLVM));
357 cl::extrahelp
358 HelpResponse("\nPass @FILE as argument to read options from FILE.\n");
359 } // namespace opts
361 static StringRef ToolName;
363 namespace llvm {
365 LLVM_ATTRIBUTE_NORETURN static void error(Twine Msg) {
366 // Flush the standard output to print the error at a
367 // proper place.
368 fouts().flush();
369 errs() << "\n";
370 WithColor::error(errs(), ToolName) << Msg << "\n";
371 exit(1);
374 LLVM_ATTRIBUTE_NORETURN void reportError(Error Err, StringRef Input) {
375 assert(Err);
376 if (Input == "-")
377 Input = "<stdin>";
378 handleAllErrors(createFileError(Input, std::move(Err)),
379 [&](const ErrorInfoBase &EI) { error(EI.message()); });
380 llvm_unreachable("error() call should never return");
383 void reportWarning(Error Err, StringRef Input) {
384 assert(Err);
385 if (Input == "-")
386 Input = "<stdin>";
388 // Flush the standard output to print the warning at a
389 // proper place.
390 fouts().flush();
391 handleAllErrors(
392 createFileError(Input, std::move(Err)), [&](const ErrorInfoBase &EI) {
393 errs() << "\n";
394 WithColor::warning(errs(), ToolName) << EI.message() << "\n";
398 } // namespace llvm
400 namespace {
401 struct ReadObjTypeTableBuilder {
402 ReadObjTypeTableBuilder()
403 : Allocator(), IDTable(Allocator), TypeTable(Allocator),
404 GlobalIDTable(Allocator), GlobalTypeTable(Allocator) {}
406 llvm::BumpPtrAllocator Allocator;
407 llvm::codeview::MergingTypeTableBuilder IDTable;
408 llvm::codeview::MergingTypeTableBuilder TypeTable;
409 llvm::codeview::GlobalTypeTableBuilder GlobalIDTable;
410 llvm::codeview::GlobalTypeTableBuilder GlobalTypeTable;
411 std::vector<OwningBinary<Binary>> Binaries;
413 } // namespace
414 static ReadObjTypeTableBuilder CVTypes;
416 /// Creates an format-specific object file dumper.
417 static std::error_code createDumper(const ObjectFile *Obj,
418 ScopedPrinter &Writer,
419 std::unique_ptr<ObjDumper> &Result) {
420 if (!Obj)
421 return readobj_error::unsupported_file_format;
423 if (Obj->isCOFF())
424 return createCOFFDumper(Obj, Writer, Result);
425 if (Obj->isELF())
426 return createELFDumper(Obj, Writer, Result);
427 if (Obj->isMachO())
428 return createMachODumper(Obj, Writer, Result);
429 if (Obj->isWasm())
430 return createWasmDumper(Obj, Writer, Result);
431 if (Obj->isXCOFF())
432 return createXCOFFDumper(Obj, Writer, Result);
434 return readobj_error::unsupported_obj_file_format;
437 /// Dumps the specified object file.
438 static void dumpObject(const ObjectFile *Obj, ScopedPrinter &Writer,
439 const Archive *A = nullptr) {
440 std::string FileStr =
441 A ? Twine(A->getFileName() + "(" + Obj->getFileName() + ")").str()
442 : Obj->getFileName().str();
444 std::unique_ptr<ObjDumper> Dumper;
445 if (std::error_code EC = createDumper(Obj, Writer, Dumper))
446 reportError(errorCodeToError(EC), FileStr);
448 if (opts::Output == opts::LLVM || opts::InputFilenames.size() > 1 || A) {
449 Writer.startLine() << "\n";
450 Writer.printString("File", FileStr);
452 if (opts::Output == opts::LLVM) {
453 Writer.printString("Format", Obj->getFileFormatName());
454 Writer.printString("Arch", Triple::getArchTypeName(
455 (llvm::Triple::ArchType)Obj->getArch()));
456 Writer.printString("AddressSize",
457 formatv("{0}bit", 8 * Obj->getBytesInAddress()));
458 Dumper->printLoadName();
461 if (opts::FileHeaders)
462 Dumper->printFileHeaders();
463 if (opts::SectionHeaders)
464 Dumper->printSectionHeaders();
465 if (opts::Relocations)
466 Dumper->printRelocations();
467 if (opts::DynRelocs)
468 Dumper->printDynamicRelocations();
469 if (opts::Symbols || opts::DynamicSymbols)
470 Dumper->printSymbols(opts::Symbols, opts::DynamicSymbols);
471 if (opts::HashSymbols)
472 Dumper->printHashSymbols();
473 if (opts::UnwindInfo)
474 Dumper->printUnwindInfo();
475 if (opts::DynamicTable)
476 Dumper->printDynamicTable();
477 if (opts::NeededLibraries)
478 Dumper->printNeededLibraries();
479 if (opts::ProgramHeaders || opts::SectionMapping == cl::BOU_TRUE)
480 Dumper->printProgramHeaders(opts::ProgramHeaders, opts::SectionMapping);
481 if (!opts::StringDump.empty())
482 Dumper->printSectionsAsString(Obj, opts::StringDump);
483 if (!opts::HexDump.empty())
484 Dumper->printSectionsAsHex(Obj, opts::HexDump);
485 if (opts::HashTable)
486 Dumper->printHashTable();
487 if (opts::GnuHashTable)
488 Dumper->printGnuHashTable();
489 if (opts::VersionInfo)
490 Dumper->printVersionInfo();
491 if (Obj->isELF()) {
492 if (opts::ELFLinkerOptions)
493 Dumper->printELFLinkerOptions();
494 if (opts::ArchSpecificInfo)
495 Dumper->printArchSpecificInfo();
496 if (opts::SectionGroups)
497 Dumper->printGroupSections();
498 if (opts::HashHistogram)
499 Dumper->printHashHistogram();
500 if (opts::CGProfile)
501 Dumper->printCGProfile();
502 if (opts::Addrsig)
503 Dumper->printAddrsig();
504 if (opts::Notes)
505 Dumper->printNotes();
507 if (Obj->isCOFF()) {
508 if (opts::COFFImports)
509 Dumper->printCOFFImports();
510 if (opts::COFFExports)
511 Dumper->printCOFFExports();
512 if (opts::COFFDirectives)
513 Dumper->printCOFFDirectives();
514 if (opts::COFFBaseRelocs)
515 Dumper->printCOFFBaseReloc();
516 if (opts::COFFDebugDirectory)
517 Dumper->printCOFFDebugDirectory();
518 if (opts::COFFResources)
519 Dumper->printCOFFResources();
520 if (opts::COFFLoadConfig)
521 Dumper->printCOFFLoadConfig();
522 if (opts::Addrsig)
523 Dumper->printAddrsig();
524 if (opts::CodeView)
525 Dumper->printCodeViewDebugInfo();
526 if (opts::CodeViewMergedTypes)
527 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable,
528 CVTypes.GlobalIDTable, CVTypes.GlobalTypeTable,
529 opts::CodeViewEnableGHash);
531 if (Obj->isMachO()) {
532 if (opts::MachODataInCode)
533 Dumper->printMachODataInCode();
534 if (opts::MachOIndirectSymbols)
535 Dumper->printMachOIndirectSymbols();
536 if (opts::MachOLinkerOptions)
537 Dumper->printMachOLinkerOptions();
538 if (opts::MachOSegment)
539 Dumper->printMachOSegment();
540 if (opts::MachOVersionMin)
541 Dumper->printMachOVersionMin();
542 if (opts::MachODysymtab)
543 Dumper->printMachODysymtab();
545 if (opts::PrintStackMap)
546 Dumper->printStackMap();
547 if (opts::PrintStackSizes)
548 Dumper->printStackSizes();
551 /// Dumps each object file in \a Arc;
552 static void dumpArchive(const Archive *Arc, ScopedPrinter &Writer) {
553 Error Err = Error::success();
554 for (auto &Child : Arc->children(Err)) {
555 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
556 if (!ChildOrErr) {
557 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError()))
558 reportError(std::move(E), Arc->getFileName());
559 continue;
561 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
562 dumpObject(Obj, Writer, Arc);
563 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
564 dumpCOFFImportFile(Imp, Writer);
565 else
566 reportError(errorCodeToError(readobj_error::unrecognized_file_format),
567 Arc->getFileName());
569 if (Err)
570 reportError(std::move(Err), Arc->getFileName());
573 /// Dumps each object file in \a MachO Universal Binary;
574 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary,
575 ScopedPrinter &Writer) {
576 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
577 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
578 if (ObjOrErr)
579 dumpObject(&*ObjOrErr.get(), Writer);
580 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError()))
581 reportError(ObjOrErr.takeError(), UBinary->getFileName());
582 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
583 dumpArchive(&*AOrErr.get(), Writer);
587 /// Dumps \a WinRes, Windows Resource (.res) file;
588 static void dumpWindowsResourceFile(WindowsResource *WinRes,
589 ScopedPrinter &Printer) {
590 WindowsRes::Dumper Dumper(WinRes, Printer);
591 if (auto Err = Dumper.printData())
592 reportError(std::move(Err), WinRes->getFileName());
596 /// Opens \a File and dumps it.
597 static void dumpInput(StringRef File, ScopedPrinter &Writer) {
598 // Attempt to open the binary.
599 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
600 if (!BinaryOrErr)
601 reportError(BinaryOrErr.takeError(), File);
602 Binary &Binary = *BinaryOrErr.get().getBinary();
604 if (Archive *Arc = dyn_cast<Archive>(&Binary))
605 dumpArchive(Arc, Writer);
606 else if (MachOUniversalBinary *UBinary =
607 dyn_cast<MachOUniversalBinary>(&Binary))
608 dumpMachOUniversalBinary(UBinary, Writer);
609 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
610 dumpObject(Obj, Writer);
611 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
612 dumpCOFFImportFile(Import, Writer);
613 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary))
614 dumpWindowsResourceFile(WinRes, Writer);
615 else
616 reportError(errorCodeToError(readobj_error::unrecognized_file_format),
617 File);
619 CVTypes.Binaries.push_back(std::move(*BinaryOrErr));
622 /// Registers aliases that should only be allowed by readobj.
623 static void registerReadobjAliases() {
624 // -s has meant --sections for a very long time in llvm-readobj despite
625 // meaning --symbols in readelf.
626 static cl::alias SectionsShort("s", cl::desc("Alias for --section-headers"),
627 cl::aliasopt(opts::SectionHeaders),
628 cl::NotHidden);
630 // Only register -t in llvm-readobj, as readelf reserves it for
631 // --section-details (not implemented yet).
632 static cl::alias SymbolsShort("t", cl::desc("Alias for --symbols"),
633 cl::aliasopt(opts::Symbols), cl::NotHidden);
635 // The following two-letter aliases are only provided for readobj, as readelf
636 // allows single-letter args to be grouped together.
637 static cl::alias SectionRelocationsShort(
638 "sr", cl::desc("Alias for --section-relocations"),
639 cl::aliasopt(opts::SectionRelocations));
640 static cl::alias SectionDataShort("sd", cl::desc("Alias for --section-data"),
641 cl::aliasopt(opts::SectionData));
642 static cl::alias SectionSymbolsShort("st",
643 cl::desc("Alias for --section-symbols"),
644 cl::aliasopt(opts::SectionSymbols));
645 static cl::alias DynamicSymbolsShort("dt",
646 cl::desc("Alias for --dyn-symbols"),
647 cl::aliasopt(opts::DynamicSymbols));
650 /// Registers aliases that should only be allowed by readelf.
651 static void registerReadelfAliases() {
652 // -s is here because for readobj it means --sections.
653 static cl::alias SymbolsShort("s", cl::desc("Alias for --symbols"),
654 cl::aliasopt(opts::Symbols), cl::NotHidden,
655 cl::Grouping);
657 // Allow all single letter flags to be grouped together.
658 for (auto &OptEntry : cl::getRegisteredOptions()) {
659 StringRef ArgName = OptEntry.getKey();
660 cl::Option *Option = OptEntry.getValue();
661 if (ArgName.size() == 1)
662 apply(Option, cl::Grouping);
666 int main(int argc, const char *argv[]) {
667 InitLLVM X(argc, argv);
668 ToolName = argv[0];
670 // Register the target printer for --version.
671 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
673 if (sys::path::stem(argv[0]).contains("readelf")) {
674 opts::Output = opts::GNU;
675 registerReadelfAliases();
676 } else {
677 registerReadobjAliases();
680 cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
682 if (opts::All) {
683 opts::FileHeaders = true;
684 opts::ProgramHeaders = true;
685 opts::SectionHeaders = true;
686 opts::Symbols = true;
687 opts::Relocations = true;
688 opts::DynamicTable = true;
689 opts::Notes = true;
690 opts::VersionInfo = true;
691 opts::UnwindInfo = true;
692 opts::SectionGroups = true;
693 opts::HashHistogram = true;
694 if (opts::Output == opts::LLVM) {
695 opts::Addrsig = true;
696 opts::PrintStackSizes = true;
700 if (opts::Headers) {
701 opts::FileHeaders = true;
702 opts::ProgramHeaders = true;
703 opts::SectionHeaders = true;
706 // Default to stdin if no filename is specified.
707 if (opts::InputFilenames.empty())
708 opts::InputFilenames.push_back("-");
710 ScopedPrinter Writer(fouts());
711 for (const std::string &I : opts::InputFilenames)
712 dumpInput(I, Writer);
714 if (opts::CodeViewMergedTypes) {
715 if (opts::CodeViewEnableGHash)
716 dumpCodeViewMergedTypes(Writer, CVTypes.GlobalIDTable.records(),
717 CVTypes.GlobalTypeTable.records());
718 else
719 dumpCodeViewMergedTypes(Writer, CVTypes.IDTable.records(),
720 CVTypes.TypeTable.records());
723 return 0;