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/TypeTableBuilder.h"
27 #include "llvm/Object/Archive.h"
28 #include "llvm/Object/COFFImportFile.h"
29 #include "llvm/Object/ELFObjectFile.h"
30 #include "llvm/Object/MachOUniversal.h"
31 #include "llvm/Object/ObjectFile.h"
32 #include "llvm/Object/WindowsResource.h"
33 #include "llvm/Support/Casting.h"
34 #include "llvm/Support/CommandLine.h"
35 #include "llvm/Support/DataTypes.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/FileSystem.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"
44 #include "llvm/Support/TargetSelect.h"
46 #include <system_error>
49 using namespace llvm::object
;
52 cl::list
<std::string
> InputFilenames(cl::Positional
,
53 cl::desc("<input object files>"),
57 cl::opt
<bool> WideOutput("wide",
58 cl::desc("Ignored for compatibility with GNU readelf"));
59 cl::alias
WideOutputShort("W",
60 cl::desc("Alias for --wide"),
61 cl::aliasopt(WideOutput
));
64 cl::opt
<bool> FileHeaders("file-headers",
65 cl::desc("Display file headers "));
66 cl::alias
FileHeadersShort("h",
67 cl::desc("Alias for --file-headers"),
68 cl::aliasopt(FileHeaders
));
71 // Note: In GNU readelf, -s means --symbols!
72 cl::opt
<bool> Sections("sections",
73 cl::desc("Display all sections."));
74 cl::alias
SectionsShort("s",
75 cl::desc("Alias for --sections"),
76 cl::aliasopt(Sections
));
77 cl::alias
SectionsShortUpper("S",
78 cl::desc("Alias for --sections"),
79 cl::aliasopt(Sections
));
81 // -section-relocations, -sr
82 cl::opt
<bool> SectionRelocations("section-relocations",
83 cl::desc("Display relocations for each section shown."));
84 cl::alias
SectionRelocationsShort("sr",
85 cl::desc("Alias for --section-relocations"),
86 cl::aliasopt(SectionRelocations
));
88 // -section-symbols, -st
89 cl::opt
<bool> SectionSymbols("section-symbols",
90 cl::desc("Display symbols for each section shown."));
91 cl::alias
SectionSymbolsShort("st",
92 cl::desc("Alias for --section-symbols"),
93 cl::aliasopt(SectionSymbols
));
96 cl::opt
<bool> SectionData("section-data",
97 cl::desc("Display section data for each section shown."));
98 cl::alias
SectionDataShort("sd",
99 cl::desc("Alias for --section-data"),
100 cl::aliasopt(SectionData
));
103 cl::opt
<bool> Relocations("relocations",
104 cl::desc("Display the relocation entries in the file"));
105 cl::alias
RelocationsShort("r",
106 cl::desc("Alias for --relocations"),
107 cl::aliasopt(Relocations
));
110 cl::opt
<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
111 cl::alias
NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes
));
114 cl::opt
<bool> DynRelocs("dyn-relocations",
115 cl::desc("Display the dynamic relocation entries in the file"));
118 cl::opt
<bool> Symbols("symbols",
119 cl::desc("Display the symbol table"));
120 cl::alias
SymbolsShort("t",
121 cl::desc("Alias for --symbols"),
122 cl::aliasopt(Symbols
));
125 cl::opt
<bool> DynamicSymbols("dyn-symbols",
126 cl::desc("Display the dynamic symbol table"));
127 cl::alias
DynamicSymbolsShort("dt",
128 cl::desc("Alias for --dyn-symbols"),
129 cl::aliasopt(DynamicSymbols
));
132 cl::opt
<bool> UnwindInfo("unwind",
133 cl::desc("Display unwind information"));
134 cl::alias
UnwindInfoShort("u",
135 cl::desc("Alias for --unwind"),
136 cl::aliasopt(UnwindInfo
));
139 cl::opt
<bool> DynamicTable("dynamic-table",
140 cl::desc("Display the ELF .dynamic section table"));
141 cl::alias
DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
142 cl::aliasopt(DynamicTable
));
145 cl::opt
<bool> NeededLibraries("needed-libs",
146 cl::desc("Display the needed libraries"));
149 cl::opt
<bool> ProgramHeaders("program-headers",
150 cl::desc("Display ELF program headers"));
151 cl::alias
ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
152 cl::aliasopt(ProgramHeaders
));
155 cl::opt
<bool> HashTable("hash-table",
156 cl::desc("Display ELF hash table"));
159 cl::opt
<bool> GnuHashTable("gnu-hash-table",
160 cl::desc("Display ELF .gnu.hash section"));
163 cl::opt
<bool> ExpandRelocs("expand-relocs",
164 cl::desc("Expand each shown relocation to multiple lines"));
167 cl::opt
<bool> CodeView("codeview",
168 cl::desc("Display CodeView debug information"));
170 // -codeview-merged-types
172 CodeViewMergedTypes("codeview-merged-types",
173 cl::desc("Display the merged CodeView type stream"));
175 // -codeview-subsection-bytes
176 cl::opt
<bool> CodeViewSubsectionBytes(
177 "codeview-subsection-bytes",
178 cl::desc("Dump raw contents of codeview debug sections and records"));
180 // -arm-attributes, -a
181 cl::opt
<bool> ARMAttributes("arm-attributes",
182 cl::desc("Display the ARM attributes section"));
183 cl::alias
ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"),
184 cl::aliasopt(ARMAttributes
));
188 MipsPLTGOT("mips-plt-got",
189 cl::desc("Display the MIPS GOT and PLT GOT sections"));
192 cl::opt
<bool> MipsABIFlags("mips-abi-flags",
193 cl::desc("Display the MIPS.abiflags section"));
196 cl::opt
<bool> MipsReginfo("mips-reginfo",
197 cl::desc("Display the MIPS .reginfo section"));
200 cl::opt
<bool> MipsOptions("mips-options",
201 cl::desc("Display the MIPS .MIPS.options section"));
203 // -amdgpu-code-object-metadata
204 cl::opt
<bool> AMDGPUCodeObjectMetadata(
205 "amdgpu-code-object-metadata",
206 cl::desc("Display AMDGPU code object metadata"));
210 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
214 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
218 COFFDirectives("coff-directives",
219 cl::desc("Display the PE/COFF .drectve section"));
223 COFFBaseRelocs("coff-basereloc",
224 cl::desc("Display the PE/COFF .reloc section"));
226 // -coff-debug-directory
228 COFFDebugDirectory("coff-debug-directory",
229 cl::desc("Display the PE/COFF debug directory"));
232 cl::opt
<bool> COFFResources("coff-resources",
233 cl::desc("Display the PE/COFF .rsrc section"));
237 COFFLoadConfig("coff-load-config",
238 cl::desc("Display the PE/COFF load config"));
240 // -macho-data-in-code
242 MachODataInCode("macho-data-in-code",
243 cl::desc("Display MachO Data in Code command"));
245 // -macho-indirect-symbols
247 MachOIndirectSymbols("macho-indirect-symbols",
248 cl::desc("Display MachO indirect symbols"));
250 // -macho-linker-options
252 MachOLinkerOptions("macho-linker-options",
253 cl::desc("Display MachO linker options"));
257 MachOSegment("macho-segment",
258 cl::desc("Display MachO Segment command"));
260 // -macho-version-min
262 MachOVersionMin("macho-version-min",
263 cl::desc("Display MachO version min command"));
267 MachODysymtab("macho-dysymtab",
268 cl::desc("Display MachO Dysymtab command"));
272 PrintStackMap("stackmap",
273 cl::desc("Display contents of stackmap section"));
277 VersionInfo("version-info",
278 cl::desc("Display ELF version sections (if present)"));
279 cl::alias
VersionInfoShort("V", cl::desc("Alias for -version-info"),
280 cl::aliasopt(VersionInfo
));
282 cl::opt
<bool> SectionGroups("elf-section-groups",
283 cl::desc("Display ELF section group contents"));
284 cl::alias
SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
285 cl::aliasopt(SectionGroups
));
286 cl::opt
<bool> HashHistogram(
287 "elf-hash-histogram",
288 cl::desc("Display bucket list histogram for hash sections"));
289 cl::alias
HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
290 cl::aliasopt(HashHistogram
));
292 cl::opt
<OutputStyleTy
>
293 Output("elf-output-style", cl::desc("Specify ELF dump style"),
294 cl::values(clEnumVal(LLVM
, "LLVM default style"),
295 clEnumVal(GNU
, "GNU readelf style")),
301 LLVM_ATTRIBUTE_NORETURN
void reportError(Twine Msg
) {
302 errs() << "\nError reading file: " << Msg
<< ".\n";
307 void error(Error EC
) {
310 handleAllErrors(std::move(EC
),
311 [&](const ErrorInfoBase
&EI
) { reportError(EI
.message()); });
314 void error(std::error_code EC
) {
317 reportError(EC
.message());
320 bool relocAddressLess(RelocationRef a
, RelocationRef b
) {
321 return a
.getOffset() < b
.getOffset();
326 static void reportError(StringRef Input
, std::error_code EC
) {
330 reportError(Twine(Input
) + ": " + EC
.message());
333 static void reportError(StringRef Input
, Error Err
) {
338 raw_string_ostream
ErrStream(ErrMsg
);
339 logAllUnhandledErrors(std::move(Err
), ErrStream
, Input
+ ": ");
344 static bool isMipsArch(unsigned Arch
) {
346 case llvm::Triple::mips
:
347 case llvm::Triple::mipsel
:
348 case llvm::Triple::mips64
:
349 case llvm::Triple::mips64el
:
356 struct ReadObjTypeTableBuilder
{
357 ReadObjTypeTableBuilder()
358 : Allocator(), IDTable(Allocator
), TypeTable(Allocator
) {}
360 llvm::BumpPtrAllocator Allocator
;
361 llvm::codeview::TypeTableBuilder IDTable
;
362 llvm::codeview::TypeTableBuilder TypeTable
;
365 static ReadObjTypeTableBuilder CVTypes
;
367 /// @brief Creates an format-specific object file dumper.
368 static std::error_code
createDumper(const ObjectFile
*Obj
,
369 ScopedPrinter
&Writer
,
370 std::unique_ptr
<ObjDumper
> &Result
) {
372 return readobj_error::unsupported_file_format
;
375 return createCOFFDumper(Obj
, Writer
, Result
);
377 return createELFDumper(Obj
, Writer
, Result
);
379 return createMachODumper(Obj
, Writer
, Result
);
381 return createWasmDumper(Obj
, Writer
, Result
);
383 return readobj_error::unsupported_obj_file_format
;
386 /// @brief Dumps the specified object file.
387 static void dumpObject(const ObjectFile
*Obj
) {
388 ScopedPrinter
Writer(outs());
389 std::unique_ptr
<ObjDumper
> Dumper
;
390 if (std::error_code EC
= createDumper(Obj
, Writer
, Dumper
))
391 reportError(Obj
->getFileName(), EC
);
393 if (opts::Output
== opts::LLVM
) {
395 outs() << "File: " << Obj
->getFileName() << "\n";
396 outs() << "Format: " << Obj
->getFileFormatName() << "\n";
397 outs() << "Arch: " << Triple::getArchTypeName(
398 (llvm::Triple::ArchType
)Obj
->getArch()) << "\n";
399 outs() << "AddressSize: " << (8 * Obj
->getBytesInAddress()) << "bit\n";
400 Dumper
->printLoadName();
403 if (opts::FileHeaders
)
404 Dumper
->printFileHeaders();
406 Dumper
->printSections();
407 if (opts::Relocations
)
408 Dumper
->printRelocations();
410 Dumper
->printDynamicRelocations();
412 Dumper
->printSymbols();
413 if (opts::DynamicSymbols
)
414 Dumper
->printDynamicSymbols();
415 if (opts::UnwindInfo
)
416 Dumper
->printUnwindInfo();
417 if (opts::DynamicTable
)
418 Dumper
->printDynamicTable();
419 if (opts::NeededLibraries
)
420 Dumper
->printNeededLibraries();
421 if (opts::ProgramHeaders
)
422 Dumper
->printProgramHeaders();
424 Dumper
->printHashTable();
425 if (opts::GnuHashTable
)
426 Dumper
->printGnuHashTable();
427 if (opts::VersionInfo
)
428 Dumper
->printVersionInfo();
430 if (Obj
->getArch() == llvm::Triple::arm
)
431 if (opts::ARMAttributes
)
432 Dumper
->printAttributes();
433 if (isMipsArch(Obj
->getArch())) {
434 if (opts::MipsPLTGOT
)
435 Dumper
->printMipsPLTGOT();
436 if (opts::MipsABIFlags
)
437 Dumper
->printMipsABIFlags();
438 if (opts::MipsReginfo
)
439 Dumper
->printMipsReginfo();
440 if (opts::MipsOptions
)
441 Dumper
->printMipsOptions();
443 if (Obj
->getArch() == llvm::Triple::amdgcn
)
444 if (opts::AMDGPUCodeObjectMetadata
)
445 Dumper
->printAMDGPUCodeObjectMetadata();
446 if (opts::SectionGroups
)
447 Dumper
->printGroupSections();
448 if (opts::HashHistogram
)
449 Dumper
->printHashHistogram();
451 Dumper
->printNotes();
454 if (opts::COFFImports
)
455 Dumper
->printCOFFImports();
456 if (opts::COFFExports
)
457 Dumper
->printCOFFExports();
458 if (opts::COFFDirectives
)
459 Dumper
->printCOFFDirectives();
460 if (opts::COFFBaseRelocs
)
461 Dumper
->printCOFFBaseReloc();
462 if (opts::COFFDebugDirectory
)
463 Dumper
->printCOFFDebugDirectory();
464 if (opts::COFFResources
)
465 Dumper
->printCOFFResources();
466 if (opts::COFFLoadConfig
)
467 Dumper
->printCOFFLoadConfig();
469 Dumper
->printCodeViewDebugInfo();
470 if (opts::CodeViewMergedTypes
)
471 Dumper
->mergeCodeViewTypes(CVTypes
.IDTable
, CVTypes
.TypeTable
);
473 if (Obj
->isMachO()) {
474 if (opts::MachODataInCode
)
475 Dumper
->printMachODataInCode();
476 if (opts::MachOIndirectSymbols
)
477 Dumper
->printMachOIndirectSymbols();
478 if (opts::MachOLinkerOptions
)
479 Dumper
->printMachOLinkerOptions();
480 if (opts::MachOSegment
)
481 Dumper
->printMachOSegment();
482 if (opts::MachOVersionMin
)
483 Dumper
->printMachOVersionMin();
484 if (opts::MachODysymtab
)
485 Dumper
->printMachODysymtab();
487 if (opts::PrintStackMap
)
488 Dumper
->printStackMap();
491 /// @brief Dumps each object file in \a Arc;
492 static void dumpArchive(const Archive
*Arc
) {
493 Error Err
= Error::success();
494 for (auto &Child
: Arc
->children(Err
)) {
495 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= Child
.getAsBinary();
497 if (auto E
= isNotObjectErrorInvalidFileType(ChildOrErr
.takeError())) {
498 reportError(Arc
->getFileName(), ChildOrErr
.takeError());
502 if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&*ChildOrErr
.get()))
504 else if (COFFImportFile
*Imp
= dyn_cast
<COFFImportFile
>(&*ChildOrErr
.get()))
505 dumpCOFFImportFile(Imp
);
507 reportError(Arc
->getFileName(), readobj_error::unrecognized_file_format
);
510 reportError(Arc
->getFileName(), std::move(Err
));
513 /// @brief Dumps each object file in \a MachO Universal Binary;
514 static void dumpMachOUniversalBinary(const MachOUniversalBinary
*UBinary
) {
515 for (const MachOUniversalBinary::ObjectForArch
&Obj
: UBinary
->objects()) {
516 Expected
<std::unique_ptr
<MachOObjectFile
>> ObjOrErr
= Obj
.getAsObjectFile();
518 dumpObject(&*ObjOrErr
.get());
519 else if (auto E
= isNotObjectErrorInvalidFileType(ObjOrErr
.takeError())) {
520 reportError(UBinary
->getFileName(), ObjOrErr
.takeError());
522 else if (Expected
<std::unique_ptr
<Archive
>> AOrErr
= Obj
.getAsArchive())
523 dumpArchive(&*AOrErr
.get());
527 /// @brief Dumps \a WinRes, Windows Resource (.res) file;
528 static void dumpWindowsResourceFile(WindowsResource
*WinRes
) {
529 ScopedPrinter Printer
{outs()};
530 WindowsRes::Dumper
Dumper(WinRes
, Printer
);
531 if (auto Err
= Dumper
.printData())
532 reportError(WinRes
->getFileName(), std::move(Err
));
536 /// @brief Opens \a File and dumps it.
537 static void dumpInput(StringRef File
) {
539 // Attempt to open the binary.
540 Expected
<OwningBinary
<Binary
>> BinaryOrErr
= createBinary(File
);
542 reportError(File
, BinaryOrErr
.takeError());
543 Binary
&Binary
= *BinaryOrErr
.get().getBinary();
545 if (Archive
*Arc
= dyn_cast
<Archive
>(&Binary
))
547 else if (MachOUniversalBinary
*UBinary
=
548 dyn_cast
<MachOUniversalBinary
>(&Binary
))
549 dumpMachOUniversalBinary(UBinary
);
550 else if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&Binary
))
552 else if (COFFImportFile
*Import
= dyn_cast
<COFFImportFile
>(&Binary
))
553 dumpCOFFImportFile(Import
);
554 else if (WindowsResource
*WinRes
= dyn_cast
<WindowsResource
>(&Binary
))
555 dumpWindowsResourceFile(WinRes
);
557 reportError(File
, readobj_error::unrecognized_file_format
);
560 int main(int argc
, const char *argv
[]) {
561 StringRef ToolName
= argv
[0];
562 sys::PrintStackTraceOnErrorSignal(ToolName
);
563 PrettyStackTraceProgram
X(argc
, argv
);
566 // Register the target printer for --version.
567 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
569 opts::WideOutput
.setHiddenFlag(cl::Hidden
);
571 if (sys::path::stem(ToolName
).find("readelf") != StringRef::npos
)
572 opts::Output
= opts::GNU
;
574 cl::ParseCommandLineOptions(argc
, argv
, "LLVM Object Reader\n");
576 // Default to stdin if no filename is specified.
577 if (opts::InputFilenames
.size() == 0)
578 opts::InputFilenames
.push_back("-");
580 std::for_each(opts::InputFilenames
.begin(), opts::InputFilenames
.end(),
583 if (opts::CodeViewMergedTypes
) {
584 ScopedPrinter
W(outs());
585 dumpCodeViewMergedTypes(W
, CVTypes
.IDTable
, CVTypes
.TypeTable
);