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/ManagedStatic.h"
38 #include "llvm/Support/Path.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/ScopedPrinter.h"
41 #include "llvm/Support/Signals.h"
42 #include "llvm/Support/TargetRegistry.h"
45 using namespace llvm::object;
48 cl::list<std::string> InputFilenames(cl::Positional,
49 cl::desc("<input object files>"),
53 cl::opt<bool> WideOutput("wide",
54 cl::desc("Ignored for compatibility with GNU readelf"));
55 cl::alias WideOutputShort("W",
56 cl::desc("Alias for --wide"),
57 cl::aliasopt(WideOutput));
60 cl::opt<bool> FileHeaders("file-headers",
61 cl::desc("Display file headers "));
62 cl::alias FileHeadersShort("h",
63 cl::desc("Alias for --file-headers"),
64 cl::aliasopt(FileHeaders));
67 // Note: In GNU readelf, -s means --symbols!
68 cl::opt<bool> Sections("sections",
69 cl::desc("Display all sections."));
70 cl::alias SectionsShort("s",
71 cl::desc("Alias for --sections"),
72 cl::aliasopt(Sections));
73 cl::alias SectionsShortUpper("S",
74 cl::desc("Alias for --sections"),
75 cl::aliasopt(Sections));
77 // -section-relocations, -sr
78 cl::opt<bool> SectionRelocations("section-relocations",
79 cl::desc("Display relocations for each section shown."));
80 cl::alias SectionRelocationsShort("sr",
81 cl::desc("Alias for --section-relocations"),
82 cl::aliasopt(SectionRelocations));
84 // -section-symbols, -st
85 cl::opt<bool> SectionSymbols("section-symbols",
86 cl::desc("Display symbols for each section shown."));
87 cl::alias SectionSymbolsShort("st",
88 cl::desc("Alias for --section-symbols"),
89 cl::aliasopt(SectionSymbols));
92 cl::opt<bool> SectionData("section-data",
93 cl::desc("Display section data for each section shown."));
94 cl::alias SectionDataShort("sd",
95 cl::desc("Alias for --section-data"),
96 cl::aliasopt(SectionData));
99 cl::opt<bool> Relocations("relocations",
100 cl::desc("Display the relocation entries in the file"));
101 cl::alias RelocationsShort("r",
102 cl::desc("Alias for --relocations"),
103 cl::aliasopt(Relocations));
106 cl::opt<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
107 cl::alias NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes));
110 cl::opt<bool> DynRelocs("dyn-relocations",
111 cl::desc("Display the dynamic relocation entries in the file"));
114 cl::opt<bool> Symbols("symbols",
115 cl::desc("Display the symbol table"));
116 cl::alias SymbolsShort("t",
117 cl::desc("Alias for --symbols"),
118 cl::aliasopt(Symbols));
121 cl::opt<bool> DynamicSymbols("dyn-symbols",
122 cl::desc("Display the dynamic symbol table"));
123 cl::alias DynamicSymbolsShort("dt",
124 cl::desc("Alias for --dyn-symbols"),
125 cl::aliasopt(DynamicSymbols));
128 cl::opt<bool> UnwindInfo("unwind",
129 cl::desc("Display unwind information"));
130 cl::alias UnwindInfoShort("u",
131 cl::desc("Alias for --unwind"),
132 cl::aliasopt(UnwindInfo));
135 cl::opt<bool> DynamicTable("dynamic-table",
136 cl::desc("Display the ELF .dynamic section table"));
137 cl::alias DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
138 cl::aliasopt(DynamicTable));
141 cl::opt<bool> NeededLibraries("needed-libs",
142 cl::desc("Display the needed libraries"));
145 cl::opt<bool> ProgramHeaders("program-headers",
146 cl::desc("Display ELF program headers"));
147 cl::alias ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
148 cl::aliasopt(ProgramHeaders));
151 cl::opt<bool> HashTable("hash-table",
152 cl::desc("Display ELF hash table"));
155 cl::opt<bool> GnuHashTable("gnu-hash-table",
156 cl::desc("Display ELF .gnu.hash section"));
159 cl::opt<bool> ExpandRelocs("expand-relocs",
160 cl::desc("Expand each shown relocation to multiple lines"));
163 cl::opt<bool> CodeView("codeview",
164 cl::desc("Display CodeView debug information"));
166 // -codeview-merged-types
168 CodeViewMergedTypes("codeview-merged-types",
169 cl::desc("Display the merged CodeView type stream"));
171 // -codeview-subsection-bytes
172 cl::opt<bool> CodeViewSubsectionBytes(
173 "codeview-subsection-bytes",
174 cl::desc("Dump raw contents of codeview debug sections and records"));
176 // -arm-attributes, -a
177 cl::opt<bool> ARMAttributes("arm-attributes",
178 cl::desc("Display the ARM attributes section"));
179 cl::alias ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"),
180 cl::aliasopt(ARMAttributes));
184 MipsPLTGOT("mips-plt-got",
185 cl::desc("Display the MIPS GOT and PLT GOT sections"));
188 cl::opt<bool> MipsABIFlags("mips-abi-flags",
189 cl::desc("Display the MIPS.abiflags section"));
192 cl::opt<bool> MipsReginfo("mips-reginfo",
193 cl::desc("Display the MIPS .reginfo section"));
196 cl::opt<bool> MipsOptions("mips-options",
197 cl::desc("Display the MIPS .MIPS.options section"));
201 COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
205 COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
209 COFFDirectives("coff-directives",
210 cl::desc("Display the PE/COFF .drectve section"));
214 COFFBaseRelocs("coff-basereloc",
215 cl::desc("Display the PE/COFF .reloc section"));
217 // -coff-debug-directory
219 COFFDebugDirectory("coff-debug-directory",
220 cl::desc("Display the PE/COFF debug directory"));
223 cl::opt<bool> COFFResources("coff-resources",
224 cl::desc("Display the PE/COFF .rsrc section"));
228 COFFLoadConfig("coff-load-config",
229 cl::desc("Display the PE/COFF load config"));
231 // -macho-data-in-code
233 MachODataInCode("macho-data-in-code",
234 cl::desc("Display MachO Data in Code command"));
236 // -macho-indirect-symbols
238 MachOIndirectSymbols("macho-indirect-symbols",
239 cl::desc("Display MachO indirect symbols"));
241 // -macho-linker-options
243 MachOLinkerOptions("macho-linker-options",
244 cl::desc("Display MachO linker options"));
248 MachOSegment("macho-segment",
249 cl::desc("Display MachO Segment command"));
251 // -macho-version-min
253 MachOVersionMin("macho-version-min",
254 cl::desc("Display MachO version min command"));
258 MachODysymtab("macho-dysymtab",
259 cl::desc("Display MachO Dysymtab command"));
263 PrintStackMap("stackmap",
264 cl::desc("Display contents of stackmap section"));
268 VersionInfo("version-info",
269 cl::desc("Display ELF version sections (if present)"));
270 cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"),
271 cl::aliasopt(VersionInfo));
273 cl::opt<bool> SectionGroups("elf-section-groups",
274 cl::desc("Display ELF section group contents"));
275 cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
276 cl::aliasopt(SectionGroups));
277 cl::opt<bool> HashHistogram(
278 "elf-hash-histogram",
279 cl::desc("Display bucket list histogram for hash sections"));
280 cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
281 cl::aliasopt(HashHistogram));
283 cl::opt<OutputStyleTy>
284 Output("elf-output-style", cl::desc("Specify ELF dump style"),
285 cl::values(clEnumVal(LLVM, "LLVM default style"),
286 clEnumVal(GNU, "GNU readelf style")),
292 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) {
293 errs() << "\nError reading file: " << Msg << ".\n";
298 void error(Error EC) {
301 handleAllErrors(std::move(EC),
302 [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
305 void error(std::error_code EC) {
308 reportError(EC.message());
311 bool relocAddressLess(RelocationRef a, RelocationRef b) {
312 return a.getOffset() < b.getOffset();
317 static void reportError(StringRef Input, std::error_code EC) {
321 reportError(Twine(Input) + ": " + EC.message());
324 static void reportError(StringRef Input, Error Err) {
329 raw_string_ostream ErrStream(ErrMsg);
330 logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": ");
335 static bool isMipsArch(unsigned Arch) {
337 case llvm::Triple::mips:
338 case llvm::Triple::mipsel:
339 case llvm::Triple::mips64:
340 case llvm::Triple::mips64el:
347 struct ReadObjTypeTableBuilder {
348 ReadObjTypeTableBuilder()
349 : Allocator(), IDTable(Allocator), TypeTable(Allocator) {}
351 llvm::BumpPtrAllocator Allocator;
352 llvm::codeview::MergingTypeTableBuilder IDTable;
353 llvm::codeview::MergingTypeTableBuilder TypeTable;
356 static ReadObjTypeTableBuilder CVTypes;
358 /// @brief Creates an format-specific object file dumper.
359 static std::error_code createDumper(const ObjectFile *Obj,
360 ScopedPrinter &Writer,
361 std::unique_ptr<ObjDumper> &Result) {
363 return readobj_error::unsupported_file_format;
366 return createCOFFDumper(Obj, Writer, Result);
368 return createELFDumper(Obj, Writer, Result);
370 return createMachODumper(Obj, Writer, Result);
372 return createWasmDumper(Obj, Writer, Result);
374 return readobj_error::unsupported_obj_file_format;
377 /// @brief Dumps the specified object file.
378 static void dumpObject(const ObjectFile *Obj) {
379 ScopedPrinter Writer(outs());
380 std::unique_ptr<ObjDumper> Dumper;
381 if (std::error_code EC = createDumper(Obj, Writer, Dumper))
382 reportError(Obj->getFileName(), EC);
384 if (opts::Output == opts::LLVM) {
386 outs() << "File: " << Obj->getFileName() << "\n";
387 outs() << "Format: " << Obj->getFileFormatName() << "\n";
388 outs() << "Arch: " << Triple::getArchTypeName(
389 (llvm::Triple::ArchType)Obj->getArch()) << "\n";
390 outs() << "AddressSize: " << (8 * Obj->getBytesInAddress()) << "bit\n";
391 Dumper->printLoadName();
394 if (opts::FileHeaders)
395 Dumper->printFileHeaders();
397 Dumper->printSections();
398 if (opts::Relocations)
399 Dumper->printRelocations();
401 Dumper->printDynamicRelocations();
403 Dumper->printSymbols();
404 if (opts::DynamicSymbols)
405 Dumper->printDynamicSymbols();
406 if (opts::UnwindInfo)
407 Dumper->printUnwindInfo();
408 if (opts::DynamicTable)
409 Dumper->printDynamicTable();
410 if (opts::NeededLibraries)
411 Dumper->printNeededLibraries();
412 if (opts::ProgramHeaders)
413 Dumper->printProgramHeaders();
415 Dumper->printHashTable();
416 if (opts::GnuHashTable)
417 Dumper->printGnuHashTable();
418 if (opts::VersionInfo)
419 Dumper->printVersionInfo();
421 if (Obj->getArch() == llvm::Triple::arm)
422 if (opts::ARMAttributes)
423 Dumper->printAttributes();
424 if (isMipsArch(Obj->getArch())) {
425 if (opts::MipsPLTGOT)
426 Dumper->printMipsPLTGOT();
427 if (opts::MipsABIFlags)
428 Dumper->printMipsABIFlags();
429 if (opts::MipsReginfo)
430 Dumper->printMipsReginfo();
431 if (opts::MipsOptions)
432 Dumper->printMipsOptions();
434 if (opts::SectionGroups)
435 Dumper->printGroupSections();
436 if (opts::HashHistogram)
437 Dumper->printHashHistogram();
439 Dumper->printNotes();
442 if (opts::COFFImports)
443 Dumper->printCOFFImports();
444 if (opts::COFFExports)
445 Dumper->printCOFFExports();
446 if (opts::COFFDirectives)
447 Dumper->printCOFFDirectives();
448 if (opts::COFFBaseRelocs)
449 Dumper->printCOFFBaseReloc();
450 if (opts::COFFDebugDirectory)
451 Dumper->printCOFFDebugDirectory();
452 if (opts::COFFResources)
453 Dumper->printCOFFResources();
454 if (opts::COFFLoadConfig)
455 Dumper->printCOFFLoadConfig();
457 Dumper->printCodeViewDebugInfo();
458 if (opts::CodeViewMergedTypes)
459 Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable);
461 if (Obj->isMachO()) {
462 if (opts::MachODataInCode)
463 Dumper->printMachODataInCode();
464 if (opts::MachOIndirectSymbols)
465 Dumper->printMachOIndirectSymbols();
466 if (opts::MachOLinkerOptions)
467 Dumper->printMachOLinkerOptions();
468 if (opts::MachOSegment)
469 Dumper->printMachOSegment();
470 if (opts::MachOVersionMin)
471 Dumper->printMachOVersionMin();
472 if (opts::MachODysymtab)
473 Dumper->printMachODysymtab();
475 if (opts::PrintStackMap)
476 Dumper->printStackMap();
479 /// @brief Dumps each object file in \a Arc;
480 static void dumpArchive(const Archive *Arc) {
481 Error Err = Error::success();
482 for (auto &Child : Arc->children(Err)) {
483 Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
485 if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) {
486 reportError(Arc->getFileName(), ChildOrErr.takeError());
490 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
492 else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
493 dumpCOFFImportFile(Imp);
495 reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
498 reportError(Arc->getFileName(), std::move(Err));
501 /// @brief Dumps each object file in \a MachO Universal Binary;
502 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
503 for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
504 Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
506 dumpObject(&*ObjOrErr.get());
507 else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
508 reportError(UBinary->getFileName(), ObjOrErr.takeError());
510 else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
511 dumpArchive(&*AOrErr.get());
515 /// @brief Dumps \a WinRes, Windows Resource (.res) file;
516 static void dumpWindowsResourceFile(WindowsResource *WinRes) {
517 ScopedPrinter Printer{outs()};
518 WindowsRes::Dumper Dumper(WinRes, Printer);
519 if (auto Err = Dumper.printData())
520 reportError(WinRes->getFileName(), std::move(Err));
524 /// @brief Opens \a File and dumps it.
525 static void dumpInput(StringRef File) {
527 // Attempt to open the binary.
528 Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
530 reportError(File, BinaryOrErr.takeError());
531 Binary &Binary = *BinaryOrErr.get().getBinary();
533 if (Archive *Arc = dyn_cast<Archive>(&Binary))
535 else if (MachOUniversalBinary *UBinary =
536 dyn_cast<MachOUniversalBinary>(&Binary))
537 dumpMachOUniversalBinary(UBinary);
538 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
540 else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
541 dumpCOFFImportFile(Import);
542 else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary))
543 dumpWindowsResourceFile(WinRes);
545 reportError(File, readobj_error::unrecognized_file_format);
548 int main(int argc, const char *argv[]) {
549 StringRef ToolName = argv[0];
550 sys::PrintStackTraceOnErrorSignal(ToolName);
551 PrettyStackTraceProgram X(argc, argv);
554 // Register the target printer for --version.
555 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
557 opts::WideOutput.setHiddenFlag(cl::Hidden);
559 if (sys::path::stem(ToolName).find("readelf") != StringRef::npos)
560 opts::Output = opts::GNU;
562 cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
564 // Default to stdin if no filename is specified.
565 if (opts::InputFilenames.size() == 0)
566 opts::InputFilenames.push_back("-");
568 llvm::for_each(opts::InputFilenames, dumpInput);
570 if (opts::CodeViewMergedTypes) {
571 ScopedPrinter W(outs());
572 dumpCodeViewMergedTypes(W, CVTypes.IDTable, CVTypes.TypeTable);