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/InitLLVM.h"
39 #include "llvm/Support/Path.h"
40 #include "llvm/Support/ScopedPrinter.h"
41 #include "llvm/Support/TargetRegistry.h"
44 using namespace llvm::object
;
47 cl::list
<std::string
> InputFilenames(cl::Positional
,
48 cl::desc("<input object files>"),
52 cl::opt
<bool> WideOutput("wide",
53 cl::desc("Ignored for compatibility with GNU readelf"));
54 cl::alias
WideOutputShort("W",
55 cl::desc("Alias for --wide"),
56 cl::aliasopt(WideOutput
));
59 cl::opt
<bool> FileHeaders("file-headers",
60 cl::desc("Display file headers "));
61 cl::alias
FileHeadersShort("h",
62 cl::desc("Alias for --file-headers"),
63 cl::aliasopt(FileHeaders
));
66 // Note: In GNU readelf, -s means --symbols!
67 cl::opt
<bool> Sections("sections",
68 cl::desc("Display all sections."));
69 cl::alias
SectionsShort("s",
70 cl::desc("Alias for --sections"),
71 cl::aliasopt(Sections
));
72 cl::alias
SectionsShortUpper("S",
73 cl::desc("Alias for --sections"),
74 cl::aliasopt(Sections
));
76 // -section-relocations, -sr
77 cl::opt
<bool> SectionRelocations("section-relocations",
78 cl::desc("Display relocations for each section shown."));
79 cl::alias
SectionRelocationsShort("sr",
80 cl::desc("Alias for --section-relocations"),
81 cl::aliasopt(SectionRelocations
));
83 // -section-symbols, -st
84 cl::opt
<bool> SectionSymbols("section-symbols",
85 cl::desc("Display symbols for each section shown."));
86 cl::alias
SectionSymbolsShort("st",
87 cl::desc("Alias for --section-symbols"),
88 cl::aliasopt(SectionSymbols
));
91 cl::opt
<bool> SectionData("section-data",
92 cl::desc("Display section data for each section shown."));
93 cl::alias
SectionDataShort("sd",
94 cl::desc("Alias for --section-data"),
95 cl::aliasopt(SectionData
));
98 cl::opt
<bool> Relocations("relocations",
99 cl::desc("Display the relocation entries in the file"));
100 cl::alias
RelocationsShort("r",
101 cl::desc("Alias for --relocations"),
102 cl::aliasopt(Relocations
));
105 cl::opt
<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
106 cl::alias
NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes
));
109 cl::opt
<bool> DynRelocs("dyn-relocations",
110 cl::desc("Display the dynamic relocation entries in the file"));
113 cl::opt
<bool> Symbols("symbols",
114 cl::desc("Display the symbol table"));
115 cl::alias
SymbolsShort("t",
116 cl::desc("Alias for --symbols"),
117 cl::aliasopt(Symbols
));
120 cl::opt
<bool> DynamicSymbols("dyn-symbols",
121 cl::desc("Display the dynamic symbol table"));
122 cl::alias
DynamicSymbolsShort("dt",
123 cl::desc("Alias for --dyn-symbols"),
124 cl::aliasopt(DynamicSymbols
));
127 cl::opt
<bool> UnwindInfo("unwind",
128 cl::desc("Display unwind information"));
129 cl::alias
UnwindInfoShort("u",
130 cl::desc("Alias for --unwind"),
131 cl::aliasopt(UnwindInfo
));
134 cl::opt
<bool> DynamicTable("dynamic-table",
135 cl::desc("Display the ELF .dynamic section table"));
136 cl::alias
DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
137 cl::aliasopt(DynamicTable
));
140 cl::opt
<bool> NeededLibraries("needed-libs",
141 cl::desc("Display the needed libraries"));
144 cl::opt
<bool> ProgramHeaders("program-headers",
145 cl::desc("Display ELF program headers"));
146 cl::alias
ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
147 cl::aliasopt(ProgramHeaders
));
150 cl::list
<std::string
> StringDump("string-dump", cl::desc("<number|name>"),
152 cl::alias
StringDumpShort("p", cl::desc("Alias for --string-dump"),
153 cl::aliasopt(StringDump
));
156 cl::list
<std::string
> HexDump("hex-dump", cl::desc("<number|name>"),
158 cl::alias
HexDumpShort("x", cl::desc("Alias for --hex-dump"),
159 cl::aliasopt(HexDump
));
162 cl::opt
<bool> HashTable("hash-table",
163 cl::desc("Display ELF hash table"));
166 cl::opt
<bool> GnuHashTable("gnu-hash-table",
167 cl::desc("Display ELF .gnu.hash section"));
170 cl::opt
<bool> ExpandRelocs("expand-relocs",
171 cl::desc("Expand each shown relocation to multiple lines"));
174 cl::opt
<bool> RawRelr("raw-relr",
175 cl::desc("Do not decode relocations in SHT_RELR section, display raw contents"));
178 cl::opt
<bool> CodeView("codeview",
179 cl::desc("Display CodeView debug information"));
181 // -codeview-merged-types
183 CodeViewMergedTypes("codeview-merged-types",
184 cl::desc("Display the merged CodeView type stream"));
186 // -codeview-subsection-bytes
187 cl::opt
<bool> CodeViewSubsectionBytes(
188 "codeview-subsection-bytes",
189 cl::desc("Dump raw contents of codeview debug sections and records"));
191 // -arm-attributes, -a
192 cl::opt
<bool> ARMAttributes("arm-attributes",
193 cl::desc("Display the ARM attributes section"));
194 cl::alias
ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"),
195 cl::aliasopt(ARMAttributes
));
199 MipsPLTGOT("mips-plt-got",
200 cl::desc("Display the MIPS GOT and PLT GOT sections"));
203 cl::opt
<bool> MipsABIFlags("mips-abi-flags",
204 cl::desc("Display the MIPS.abiflags section"));
207 cl::opt
<bool> MipsReginfo("mips-reginfo",
208 cl::desc("Display the MIPS .reginfo section"));
211 cl::opt
<bool> MipsOptions("mips-options",
212 cl::desc("Display the MIPS .MIPS.options section"));
216 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
220 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
224 COFFDirectives("coff-directives",
225 cl::desc("Display the PE/COFF .drectve section"));
229 COFFBaseRelocs("coff-basereloc",
230 cl::desc("Display the PE/COFF .reloc section"));
232 // -coff-debug-directory
234 COFFDebugDirectory("coff-debug-directory",
235 cl::desc("Display the PE/COFF debug directory"));
238 cl::opt
<bool> COFFResources("coff-resources",
239 cl::desc("Display the PE/COFF .rsrc section"));
243 COFFLoadConfig("coff-load-config",
244 cl::desc("Display the PE/COFF load config"));
246 // -elf-linker-options
248 ELFLinkerOptions("elf-linker-options",
249 cl::desc("Display the ELF .linker-options section"));
251 // -macho-data-in-code
253 MachODataInCode("macho-data-in-code",
254 cl::desc("Display MachO Data in Code command"));
256 // -macho-indirect-symbols
258 MachOIndirectSymbols("macho-indirect-symbols",
259 cl::desc("Display MachO indirect symbols"));
261 // -macho-linker-options
263 MachOLinkerOptions("macho-linker-options",
264 cl::desc("Display MachO linker options"));
268 MachOSegment("macho-segment",
269 cl::desc("Display MachO Segment command"));
271 // -macho-version-min
273 MachOVersionMin("macho-version-min",
274 cl::desc("Display MachO version min command"));
278 MachODysymtab("macho-dysymtab",
279 cl::desc("Display MachO Dysymtab command"));
283 PrintStackMap("stackmap",
284 cl::desc("Display contents of stackmap section"));
288 VersionInfo("version-info",
289 cl::desc("Display ELF version sections (if present)"));
290 cl::alias
VersionInfoShort("V", cl::desc("Alias for -version-info"),
291 cl::aliasopt(VersionInfo
));
293 cl::opt
<bool> SectionGroups("elf-section-groups",
294 cl::desc("Display ELF section group contents"));
295 cl::alias
SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
296 cl::aliasopt(SectionGroups
));
297 cl::opt
<bool> HashHistogram(
298 "elf-hash-histogram",
299 cl::desc("Display bucket list histogram for hash sections"));
300 cl::alias
HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
301 cl::aliasopt(HashHistogram
));
303 cl::opt
<bool> CGProfile("elf-cg-profile", cl::desc("Display callgraph profile section"));
305 cl::opt
<bool> Addrsig("addrsig",
306 cl::desc("Display address-significance table"));
308 cl::opt
<OutputStyleTy
>
309 Output("elf-output-style", cl::desc("Specify ELF dump style"),
310 cl::values(clEnumVal(LLVM
, "LLVM default style"),
311 clEnumVal(GNU
, "GNU readelf style")),
317 LLVM_ATTRIBUTE_NORETURN
void reportError(Twine Msg
) {
318 errs() << "\nError reading file: " << Msg
<< ".\n";
323 void error(Error EC
) {
326 handleAllErrors(std::move(EC
),
327 [&](const ErrorInfoBase
&EI
) { reportError(EI
.message()); });
330 void error(std::error_code EC
) {
333 reportError(EC
.message());
336 bool relocAddressLess(RelocationRef a
, RelocationRef b
) {
337 return a
.getOffset() < b
.getOffset();
342 static void reportError(StringRef Input
, std::error_code EC
) {
346 reportError(Twine(Input
) + ": " + EC
.message());
349 static void reportError(StringRef Input
, Error Err
) {
354 raw_string_ostream
ErrStream(ErrMsg
);
355 logAllUnhandledErrors(std::move(Err
), ErrStream
, Input
+ ": ");
360 static bool isMipsArch(unsigned Arch
) {
362 case llvm::Triple::mips
:
363 case llvm::Triple::mipsel
:
364 case llvm::Triple::mips64
:
365 case llvm::Triple::mips64el
:
372 struct ReadObjTypeTableBuilder
{
373 ReadObjTypeTableBuilder()
374 : Allocator(), IDTable(Allocator
), TypeTable(Allocator
) {}
376 llvm::BumpPtrAllocator Allocator
;
377 llvm::codeview::MergingTypeTableBuilder IDTable
;
378 llvm::codeview::MergingTypeTableBuilder TypeTable
;
381 static ReadObjTypeTableBuilder CVTypes
;
383 /// Creates an format-specific object file dumper.
384 static std::error_code
createDumper(const ObjectFile
*Obj
,
385 ScopedPrinter
&Writer
,
386 std::unique_ptr
<ObjDumper
> &Result
) {
388 return readobj_error::unsupported_file_format
;
391 return createCOFFDumper(Obj
, Writer
, Result
);
393 return createELFDumper(Obj
, Writer
, Result
);
395 return createMachODumper(Obj
, Writer
, Result
);
397 return createWasmDumper(Obj
, Writer
, Result
);
399 return readobj_error::unsupported_obj_file_format
;
402 /// Dumps the specified object file.
403 static void dumpObject(const ObjectFile
*Obj
, ScopedPrinter
&Writer
) {
404 std::unique_ptr
<ObjDumper
> Dumper
;
405 if (std::error_code EC
= createDumper(Obj
, Writer
, Dumper
))
406 reportError(Obj
->getFileName(), EC
);
408 if (opts::Output
== opts::LLVM
) {
409 Writer
.startLine() << "\n";
410 Writer
.printString("File", Obj
->getFileName());
411 Writer
.printString("Format", Obj
->getFileFormatName());
412 Writer
.printString("Arch", Triple::getArchTypeName(
413 (llvm::Triple::ArchType
)Obj
->getArch()));
414 Writer
.printString("AddressSize",
415 formatv("{0}bit", 8 * Obj
->getBytesInAddress()));
416 Dumper
->printLoadName();
419 if (opts::FileHeaders
)
420 Dumper
->printFileHeaders();
422 Dumper
->printSections();
423 if (opts::Relocations
)
424 Dumper
->printRelocations();
426 Dumper
->printDynamicRelocations();
428 Dumper
->printSymbols();
429 if (opts::DynamicSymbols
)
430 Dumper
->printDynamicSymbols();
431 if (opts::UnwindInfo
)
432 Dumper
->printUnwindInfo();
433 if (opts::DynamicTable
)
434 Dumper
->printDynamicTable();
435 if (opts::NeededLibraries
)
436 Dumper
->printNeededLibraries();
437 if (opts::ProgramHeaders
)
438 Dumper
->printProgramHeaders();
439 if (!opts::StringDump
.empty())
440 llvm::for_each(opts::StringDump
, [&Dumper
, Obj
](StringRef SectionName
) {
441 Dumper
->printSectionAsString(Obj
, SectionName
);
443 if (!opts::HexDump
.empty())
444 llvm::for_each(opts::HexDump
, [&Dumper
, Obj
](StringRef SectionName
) {
445 Dumper
->printSectionAsHex(Obj
, SectionName
);
448 Dumper
->printHashTable();
449 if (opts::GnuHashTable
)
450 Dumper
->printGnuHashTable();
451 if (opts::VersionInfo
)
452 Dumper
->printVersionInfo();
454 if (opts::ELFLinkerOptions
)
455 Dumper
->printELFLinkerOptions();
456 if (Obj
->getArch() == llvm::Triple::arm
)
457 if (opts::ARMAttributes
)
458 Dumper
->printAttributes();
459 if (isMipsArch(Obj
->getArch())) {
460 if (opts::MipsPLTGOT
)
461 Dumper
->printMipsPLTGOT();
462 if (opts::MipsABIFlags
)
463 Dumper
->printMipsABIFlags();
464 if (opts::MipsReginfo
)
465 Dumper
->printMipsReginfo();
466 if (opts::MipsOptions
)
467 Dumper
->printMipsOptions();
469 if (opts::SectionGroups
)
470 Dumper
->printGroupSections();
471 if (opts::HashHistogram
)
472 Dumper
->printHashHistogram();
474 Dumper
->printCGProfile();
476 Dumper
->printAddrsig();
478 Dumper
->printNotes();
481 if (opts::COFFImports
)
482 Dumper
->printCOFFImports();
483 if (opts::COFFExports
)
484 Dumper
->printCOFFExports();
485 if (opts::COFFDirectives
)
486 Dumper
->printCOFFDirectives();
487 if (opts::COFFBaseRelocs
)
488 Dumper
->printCOFFBaseReloc();
489 if (opts::COFFDebugDirectory
)
490 Dumper
->printCOFFDebugDirectory();
491 if (opts::COFFResources
)
492 Dumper
->printCOFFResources();
493 if (opts::COFFLoadConfig
)
494 Dumper
->printCOFFLoadConfig();
496 Dumper
->printAddrsig();
498 Dumper
->printCodeViewDebugInfo();
499 if (opts::CodeViewMergedTypes
)
500 Dumper
->mergeCodeViewTypes(CVTypes
.IDTable
, CVTypes
.TypeTable
);
502 if (Obj
->isMachO()) {
503 if (opts::MachODataInCode
)
504 Dumper
->printMachODataInCode();
505 if (opts::MachOIndirectSymbols
)
506 Dumper
->printMachOIndirectSymbols();
507 if (opts::MachOLinkerOptions
)
508 Dumper
->printMachOLinkerOptions();
509 if (opts::MachOSegment
)
510 Dumper
->printMachOSegment();
511 if (opts::MachOVersionMin
)
512 Dumper
->printMachOVersionMin();
513 if (opts::MachODysymtab
)
514 Dumper
->printMachODysymtab();
516 if (opts::PrintStackMap
)
517 Dumper
->printStackMap();
520 /// Dumps each object file in \a Arc;
521 static void dumpArchive(const Archive
*Arc
, ScopedPrinter
&Writer
) {
522 Error Err
= Error::success();
523 for (auto &Child
: Arc
->children(Err
)) {
524 Expected
<std::unique_ptr
<Binary
>> ChildOrErr
= Child
.getAsBinary();
526 if (auto E
= isNotObjectErrorInvalidFileType(ChildOrErr
.takeError())) {
527 reportError(Arc
->getFileName(), ChildOrErr
.takeError());
531 if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&*ChildOrErr
.get()))
532 dumpObject(Obj
, Writer
);
533 else if (COFFImportFile
*Imp
= dyn_cast
<COFFImportFile
>(&*ChildOrErr
.get()))
534 dumpCOFFImportFile(Imp
, Writer
);
536 reportError(Arc
->getFileName(), readobj_error::unrecognized_file_format
);
539 reportError(Arc
->getFileName(), std::move(Err
));
542 /// Dumps each object file in \a MachO Universal Binary;
543 static void dumpMachOUniversalBinary(const MachOUniversalBinary
*UBinary
,
544 ScopedPrinter
&Writer
) {
545 for (const MachOUniversalBinary::ObjectForArch
&Obj
: UBinary
->objects()) {
546 Expected
<std::unique_ptr
<MachOObjectFile
>> ObjOrErr
= Obj
.getAsObjectFile();
548 dumpObject(&*ObjOrErr
.get(), Writer
);
549 else if (auto E
= isNotObjectErrorInvalidFileType(ObjOrErr
.takeError())) {
550 reportError(UBinary
->getFileName(), ObjOrErr
.takeError());
552 else if (Expected
<std::unique_ptr
<Archive
>> AOrErr
= Obj
.getAsArchive())
553 dumpArchive(&*AOrErr
.get(), Writer
);
557 /// Dumps \a WinRes, Windows Resource (.res) file;
558 static void dumpWindowsResourceFile(WindowsResource
*WinRes
) {
559 ScopedPrinter Printer
{outs()};
560 WindowsRes::Dumper
Dumper(WinRes
, Printer
);
561 if (auto Err
= Dumper
.printData())
562 reportError(WinRes
->getFileName(), std::move(Err
));
566 /// Opens \a File and dumps it.
567 static void dumpInput(StringRef File
) {
568 ScopedPrinter
Writer(outs());
570 // Attempt to open the binary.
571 Expected
<OwningBinary
<Binary
>> BinaryOrErr
= createBinary(File
);
573 reportError(File
, BinaryOrErr
.takeError());
574 Binary
&Binary
= *BinaryOrErr
.get().getBinary();
576 if (Archive
*Arc
= dyn_cast
<Archive
>(&Binary
))
577 dumpArchive(Arc
, Writer
);
578 else if (MachOUniversalBinary
*UBinary
=
579 dyn_cast
<MachOUniversalBinary
>(&Binary
))
580 dumpMachOUniversalBinary(UBinary
, Writer
);
581 else if (ObjectFile
*Obj
= dyn_cast
<ObjectFile
>(&Binary
))
582 dumpObject(Obj
, Writer
);
583 else if (COFFImportFile
*Import
= dyn_cast
<COFFImportFile
>(&Binary
))
584 dumpCOFFImportFile(Import
, Writer
);
585 else if (WindowsResource
*WinRes
= dyn_cast
<WindowsResource
>(&Binary
))
586 dumpWindowsResourceFile(WinRes
);
588 reportError(File
, readobj_error::unrecognized_file_format
);
591 int main(int argc
, const char *argv
[]) {
592 InitLLVM
X(argc
, argv
);
594 // Register the target printer for --version.
595 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion
);
597 opts::WideOutput
.setHiddenFlag(cl::Hidden
);
599 if (sys::path::stem(argv
[0]).find("readelf") != StringRef::npos
)
600 opts::Output
= opts::GNU
;
602 cl::ParseCommandLineOptions(argc
, argv
, "LLVM Object Reader\n");
604 // Default to stdin if no filename is specified.
605 if (opts::InputFilenames
.size() == 0)
606 opts::InputFilenames
.push_back("-");
608 llvm::for_each(opts::InputFilenames
, dumpInput
);
610 if (opts::CodeViewMergedTypes
) {
611 ScopedPrinter
W(outs());
612 dumpCodeViewMergedTypes(W
, CVTypes
.IDTable
, CVTypes
.TypeTable
);