1 //===- llvm-readobj.cpp - Dump contents of an Object File -----------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This is a tool similar to readelf, except it works on multiple object file
11 // formats. The main purpose of this tool is to provide detailed output suitable
14 // Flags should be similar to readelf where supported, but the output format
15 // does not need to be identical. The point is to not make users learn yet
16 // another set of flags.
18 // Output should be specialized for each format where appropriate.
20 //===----------------------------------------------------------------------===//
22 #include "llvm-readobj.h"
24 #include "ObjDumper.h"
25 #include "WindowsResourceDumper.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/ManagedStatic.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/PrettyStackTrace.h"
41 #include "llvm/Support/ScopedPrinter.h"
42 #include "llvm/Support/Signals.h"
43 #include "llvm/Support/TargetRegistry.h"
46 using namespace llvm::object
;
49 cl::list
<std::string
> InputFilenames(cl::Positional
,
50 cl::desc("<input object files>"),
54 cl::opt
<bool> WideOutput("wide",
55 cl::desc("Ignored for compatibility with GNU readelf"));
56 cl::alias
WideOutputShort("W",
57 cl::desc("Alias for --wide"),
58 cl::aliasopt(WideOutput
));
61 cl::opt
<bool> FileHeaders("file-headers",
62 cl::desc("Display file headers "));
63 cl::alias
FileHeadersShort("h",
64 cl::desc("Alias for --file-headers"),
65 cl::aliasopt(FileHeaders
));
68 // Note: In GNU readelf, -s means --symbols!
69 cl::opt
<bool> Sections("sections",
70 cl::desc("Display all sections."));
71 cl::alias
SectionsShort("s",
72 cl::desc("Alias for --sections"),
73 cl::aliasopt(Sections
));
74 cl::alias
SectionsShortUpper("S",
75 cl::desc("Alias for --sections"),
76 cl::aliasopt(Sections
));
78 // -section-relocations, -sr
79 cl::opt
<bool> SectionRelocations("section-relocations",
80 cl::desc("Display relocations for each section shown."));
81 cl::alias
SectionRelocationsShort("sr",
82 cl::desc("Alias for --section-relocations"),
83 cl::aliasopt(SectionRelocations
));
85 // -section-symbols, -st
86 cl::opt
<bool> SectionSymbols("section-symbols",
87 cl::desc("Display symbols for each section shown."));
88 cl::alias
SectionSymbolsShort("st",
89 cl::desc("Alias for --section-symbols"),
90 cl::aliasopt(SectionSymbols
));
93 cl::opt
<bool> SectionData("section-data",
94 cl::desc("Display section data for each section shown."));
95 cl::alias
SectionDataShort("sd",
96 cl::desc("Alias for --section-data"),
97 cl::aliasopt(SectionData
));
100 cl::opt
<bool> Relocations("relocations",
101 cl::desc("Display the relocation entries in the file"));
102 cl::alias
RelocationsShort("r",
103 cl::desc("Alias for --relocations"),
104 cl::aliasopt(Relocations
));
107 cl::opt
<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
108 cl::alias
NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes
));
111 cl::opt
<bool> DynRelocs("dyn-relocations",
112 cl::desc("Display the dynamic relocation entries in the file"));
115 cl::opt
<bool> Symbols("symbols",
116 cl::desc("Display the symbol table"));
117 cl::alias
SymbolsShort("t",
118 cl::desc("Alias for --symbols"),
119 cl::aliasopt(Symbols
));
122 cl::opt
<bool> DynamicSymbols("dyn-symbols",
123 cl::desc("Display the dynamic symbol table"));
124 cl::alias
DynamicSymbolsShort("dt",
125 cl::desc("Alias for --dyn-symbols"),
126 cl::aliasopt(DynamicSymbols
));
129 cl::opt
<bool> UnwindInfo("unwind",
130 cl::desc("Display unwind information"));
131 cl::alias
UnwindInfoShort("u",
132 cl::desc("Alias for --unwind"),
133 cl::aliasopt(UnwindInfo
));
136 cl::opt
<bool> DynamicTable("dynamic-table",
137 cl::desc("Display the ELF .dynamic section table"));
138 cl::alias
DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
139 cl::aliasopt(DynamicTable
));
142 cl::opt
<bool> NeededLibraries("needed-libs",
143 cl::desc("Display the needed libraries"));
146 cl::opt
<bool> ProgramHeaders("program-headers",
147 cl::desc("Display ELF program headers"));
148 cl::alias
ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
149 cl::aliasopt(ProgramHeaders
));
152 cl::opt
<bool> HashTable("hash-table",
153 cl::desc("Display ELF hash table"));
156 cl::opt
<bool> GnuHashTable("gnu-hash-table",
157 cl::desc("Display ELF .gnu.hash section"));
160 cl::opt
<bool> ExpandRelocs("expand-relocs",
161 cl::desc("Expand each shown relocation to multiple lines"));
164 cl::opt
<bool> CodeView("codeview",
165 cl::desc("Display CodeView debug information"));
167 // -codeview-merged-types
169 CodeViewMergedTypes("codeview-merged-types",
170 cl::desc("Display the merged CodeView type stream"));
172 // -codeview-subsection-bytes
173 cl::opt
<bool> CodeViewSubsectionBytes(
174 "codeview-subsection-bytes",
175 cl::desc("Dump raw contents of codeview debug sections and records"));
177 // -arm-attributes, -a
178 cl::opt
<bool> ARMAttributes("arm-attributes",
179 cl::desc("Display the ARM attributes section"));
180 cl::alias
ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"),
181 cl::aliasopt(ARMAttributes
));
185 MipsPLTGOT("mips-plt-got",
186 cl::desc("Display the MIPS GOT and PLT GOT sections"));
189 cl::opt
<bool> MipsABIFlags("mips-abi-flags",
190 cl::desc("Display the MIPS.abiflags section"));
193 cl::opt
<bool> MipsReginfo("mips-reginfo",
194 cl::desc("Display the MIPS .reginfo section"));
197 cl::opt
<bool> MipsOptions("mips-options",
198 cl::desc("Display the MIPS .MIPS.options section"));
202 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
206 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
210 COFFDirectives("coff-directives",
211 cl::desc("Display the PE/COFF .drectve section"));
215 COFFBaseRelocs("coff-basereloc",
216 cl::desc("Display the PE/COFF .reloc section"));
218 // -coff-debug-directory
220 COFFDebugDirectory("coff-debug-directory",
221 cl::desc("Display the PE/COFF debug directory"));
224 cl::opt
<bool> COFFResources("coff-resources",
225 cl::desc("Display the PE/COFF .rsrc section"));
229 COFFLoadConfig("coff-load-config",
230 cl::desc("Display the PE/COFF load config"));
232 // -elf-linker-options
234 ELFLinkerOptions("elf-linker-options",
235 cl::desc("Display the ELF .linker-options section"));
237 // -macho-data-in-code
239 MachODataInCode("macho-data-in-code",
240 cl::desc("Display MachO Data in Code command"));
242 // -macho-indirect-symbols
244 MachOIndirectSymbols("macho-indirect-symbols",
245 cl::desc("Display MachO indirect symbols"));
247 // -macho-linker-options
249 MachOLinkerOptions("macho-linker-options",
250 cl::desc("Display MachO linker options"));
254 MachOSegment("macho-segment",
255 cl::desc("Display MachO Segment command"));
257 // -macho-version-min
259 MachOVersionMin("macho-version-min",
260 cl::desc("Display MachO version min command"));
264 MachODysymtab("macho-dysymtab",
265 cl::desc("Display MachO Dysymtab command"));
269 PrintStackMap("stackmap",
270 cl::desc("Display contents of stackmap section"));
274 VersionInfo("version-info",
275 cl::desc("Display ELF version sections (if present)"));
276 cl::alias
VersionInfoShort("V", cl::desc("Alias for -version-info"),
277 cl::aliasopt(VersionInfo
));
279 cl::opt
<bool> SectionGroups("elf-section-groups",
280 cl::desc("Display ELF section group contents"));
281 cl::alias
SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
282 cl::aliasopt(SectionGroups
));
283 cl::opt
<bool> HashHistogram(
284 "elf-hash-histogram",
285 cl::desc("Display bucket list histogram for hash sections"));
286 cl::alias
HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
287 cl::aliasopt(HashHistogram
));
289 cl::opt
<OutputStyleTy
>
290 Output("elf-output-style", cl::desc("Specify ELF dump style"),
291 cl::values(clEnumVal(LLVM
, "LLVM default style"),
292 clEnumVal(GNU
, "GNU readelf style")),
298 LLVM_ATTRIBUTE_NORETURN
void reportError(Twine Msg
) {
299 errs() << "\nError reading file: " << Msg
<< ".\n";
304 void error(Error EC
) {
307 handleAllErrors(std::move(EC
),
308 [&](const ErrorInfoBase
&EI
) { reportError(EI
.message()); });
311 void error(std::error_code EC
) {
314 reportError(EC
.message());
317 bool relocAddressLess(RelocationRef a
, RelocationRef b
) {
318 return a
.getOffset() < b
.getOffset();
323 static void reportError(StringRef Input
, std::error_code EC
) {
327 reportError(Twine(Input
) + ": " + EC
.message());
330 static void reportError(StringRef Input
, Error Err
) {
335 raw_string_ostream
ErrStream(ErrMsg
);
336 logAllUnhandledErrors(std::move(Err
), ErrStream
, Input
+ ": ");
341 static bool isMipsArch(unsigned Arch
) {
343 case llvm::Triple::mips
:
344 case llvm::Triple::mipsel
:
345 case llvm::Triple::mips64
:
346 case llvm::Triple::mips64el
:
353 struct ReadObjTypeTableBuilder
{
354 ReadObjTypeTableBuilder()
355 : Allocator(), IDTable(Allocator
), TypeTable(Allocator
) {}
357 llvm::BumpPtrAllocator Allocator
;
358 llvm::codeview::MergingTypeTableBuilder IDTable
;
359 llvm::codeview::MergingTypeTableBuilder TypeTable
;
362 static ReadObjTypeTableBuilder CVTypes
;
364 /// @brief Creates an format-specific object file dumper.
365 static std::error_code
createDumper(const ObjectFile
*Obj
,
366 ScopedPrinter
&Writer
,
367 std::unique_ptr
<ObjDumper
> &Result
) {
369 return readobj_error::unsupported_file_format
;
372 return createCOFFDumper(Obj
, Writer
, Result
);
374 return createELFDumper(Obj
, Writer
, Result
);
376 return createMachODumper(Obj
, Writer
, Result
);
378 return createWasmDumper(Obj
, Writer
, Result
);
380 return readobj_error::unsupported_obj_file_format
;
383 /// @brief Dumps the specified object file.
384 static void dumpObject(const ObjectFile
*Obj
, ScopedPrinter
&Writer
) {
385 std::unique_ptr
<ObjDumper
> Dumper
;
386 if (std::error_code EC
= createDumper(Obj
, Writer
, Dumper
))
387 reportError(Obj
->getFileName(), EC
);
389 if (opts::Output
== opts::LLVM
) {
390 Writer
.startLine() << "\n";
391 Writer
.printString("File", Obj
->getFileName());
392 Writer
.printString("Format", Obj
->getFileFormatName());
393 Writer
.printString("Arch", Triple::getArchTypeName(
394 (llvm::Triple::ArchType
)Obj
->getArch()));
395 Writer
.printString("AddressSize",
396 formatv("{0}bit", 8 * Obj
->getBytesInAddress()));
397 Dumper
->printLoadName();
400 if (opts::FileHeaders
)
401 Dumper
->printFileHeaders();
403 Dumper
->printSections();
404 if (opts::Relocations
)
405 Dumper
->printRelocations();
407 Dumper
->printDynamicRelocations();
409 Dumper
->printSymbols();
410 if (opts::DynamicSymbols
)
411 Dumper
->printDynamicSymbols();
412 if (opts::UnwindInfo
)
413 Dumper
->printUnwindInfo();
414 if (opts::DynamicTable
)
415 Dumper
->printDynamicTable();
416 if (opts::NeededLibraries
)
417 Dumper
->printNeededLibraries();
418 if (opts::ProgramHeaders
)
419 Dumper
->printProgramHeaders();
421 Dumper
->printHashTable();
422 if (opts::GnuHashTable
)
423 Dumper
->printGnuHashTable();
424 if (opts::VersionInfo
)
425 Dumper
->printVersionInfo();
427 if (opts::ELFLinkerOptions
)
428 Dumper
->printELFLinkerOptions();
429 if (Obj
->getArch() == llvm::Triple::arm
)
430 if (opts::ARMAttributes
)
431 Dumper
->printAttributes();
432 if (isMipsArch(Obj
->getArch())) {
433 if (opts::MipsPLTGOT
)
434 Dumper
->printMipsPLTGOT();
435 if (opts::MipsABIFlags
)
436 Dumper
->printMipsABIFlags();
437 if (opts::MipsReginfo
)
438 Dumper
->printMipsReginfo();
439 if (opts::MipsOptions
)
440 Dumper
->printMipsOptions();
442 if (opts::SectionGroups
)
443 Dumper
->printGroupSections();
444 if (opts::HashHistogram
)
445 Dumper
->printHashHistogram();
447 Dumper
->printNotes();
450 if (opts::COFFImports
)
451 Dumper
->printCOFFImports();
452 if (opts::COFFExports
)
453 Dumper
->printCOFFExports();
454 if (opts::COFFDirectives
)
455 Dumper
->printCOFFDirectives();
456 if (opts::COFFBaseRelocs
)
457 Dumper
->printCOFFBaseReloc();
458 if (opts::COFFDebugDirectory
)
459 Dumper
->printCOFFDebugDirectory();
460 if (opts::COFFResources
)
461 Dumper
->printCOFFResources();
462 if (opts::COFFLoadConfig
)
463 Dumper
->printCOFFLoadConfig();
465 Dumper
->printCodeViewDebugInfo();
466 if (opts::CodeViewMergedTypes
)
467 Dumper
->mergeCodeViewTypes(CVTypes
.IDTable
, CVTypes
.TypeTable
);
469 if (Obj
->isMachO()) {
470 if (opts::MachODataInCode
)
471 Dumper
->printMachODataInCode();
472 if (opts::MachOIndirectSymbols
)
473 Dumper
->printMachOIndirectSymbols();
474 if (opts::MachOLinkerOptions
)
475 Dumper
->printMachOLinkerOptions();
476 if (opts::MachOSegment
)
477 Dumper
->printMachOSegment();
478 if (opts::MachOVersionMin
)
479 Dumper
->printMachOVersionMin();
480 if (opts::MachODysymtab
)
481 Dumper
->printMachODysymtab();
483 if (opts::PrintStackMap
)
484 Dumper
->printStackMap();
487 /// @brief Dumps each object file in \a Arc;
488 static void dumpArchive(const Archive
*Arc
, ScopedPrinter
&Writer
) {
489 Error Err
= Error::success();
490 for (auto &Child
: Arc
->children(Err
)) {
491 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= Child
.getAsBinary();
493 if (auto E
= isNotObjectErrorInvalidFileType(ChildOrErr
.takeError())) {
494 reportError(Arc
->getFileName(), ChildOrErr
.takeError());
498 if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&*ChildOrErr
.get()))
499 dumpObject(Obj
, Writer
);
500 else if (COFFImportFile
*Imp
= dyn_cast
<COFFImportFile
>(&*ChildOrErr
.get()))
501 dumpCOFFImportFile(Imp
, Writer
);
503 reportError(Arc
->getFileName(), readobj_error::unrecognized_file_format
);
506 reportError(Arc
->getFileName(), std::move(Err
));
509 /// @brief Dumps each object file in \a MachO Universal Binary;
510 static void dumpMachOUniversalBinary(const MachOUniversalBinary
*UBinary
,
511 ScopedPrinter
&Writer
) {
512 for (const MachOUniversalBinary::ObjectForArch
&Obj
: UBinary
->objects()) {
513 Expected
<std::unique_ptr
<MachOObjectFile
>> ObjOrErr
= Obj
.getAsObjectFile();
515 dumpObject(&*ObjOrErr
.get(), Writer
);
516 else if (auto E
= isNotObjectErrorInvalidFileType(ObjOrErr
.takeError())) {
517 reportError(UBinary
->getFileName(), ObjOrErr
.takeError());
519 else if (Expected
<std::unique_ptr
<Archive
>> AOrErr
= Obj
.getAsArchive())
520 dumpArchive(&*AOrErr
.get(), Writer
);
524 /// @brief Dumps \a WinRes, Windows Resource (.res) file;
525 static void dumpWindowsResourceFile(WindowsResource
*WinRes
) {
526 ScopedPrinter Printer
{outs()};
527 WindowsRes::Dumper
Dumper(WinRes
, Printer
);
528 if (auto Err
= Dumper
.printData())
529 reportError(WinRes
->getFileName(), std::move(Err
));
533 /// @brief Opens \a File and dumps it.
534 static void dumpInput(StringRef File
) {
535 ScopedPrinter
Writer(outs());
537 // Attempt to open the binary.
538 Expected
<OwningBinary
<Binary
>> BinaryOrErr
= createBinary(File
);
540 reportError(File
, BinaryOrErr
.takeError());
541 Binary
&Binary
= *BinaryOrErr
.get().getBinary();
543 if (Archive
*Arc
= dyn_cast
<Archive
>(&Binary
))
544 dumpArchive(Arc
, Writer
);
545 else if (MachOUniversalBinary
*UBinary
=
546 dyn_cast
<MachOUniversalBinary
>(&Binary
))
547 dumpMachOUniversalBinary(UBinary
, Writer
);
548 else if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&Binary
))
549 dumpObject(Obj
, Writer
);
550 else if (COFFImportFile
*Import
= dyn_cast
<COFFImportFile
>(&Binary
))
551 dumpCOFFImportFile(Import
, Writer
);
552 else if (WindowsResource
*WinRes
= dyn_cast
<WindowsResource
>(&Binary
))
553 dumpWindowsResourceFile(WinRes
);
555 reportError(File
, readobj_error::unrecognized_file_format
);
558 int main(int argc
, const char *argv
[]) {
559 StringRef ToolName
= argv
[0];
560 sys::PrintStackTraceOnErrorSignal(ToolName
);
561 PrettyStackTraceProgram
X(argc
, argv
);
564 // Register the target printer for --version.
565 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
567 opts::WideOutput
.setHiddenFlag(cl::Hidden
);
569 if (sys::path::stem(ToolName
).find("readelf") != StringRef::npos
)
570 opts::Output
= opts::GNU
;
572 cl::ParseCommandLineOptions(argc
, argv
, "LLVM Object Reader\n");
574 // Default to stdin if no filename is specified.
575 if (opts::InputFilenames
.size() == 0)
576 opts::InputFilenames
.push_back("-");
578 llvm::for_each(opts::InputFilenames
, dumpInput
);
580 if (opts::CodeViewMergedTypes
) {
581 ScopedPrinter
W(outs());
582 dumpCodeViewMergedTypes(W
, CVTypes
.IDTable
, CVTypes
.TypeTable
);