xref: /llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp (revision 6d76b7b455cdc9927371785f77f7ae38509c1b03)
1 //===- llvm-readobj.cpp - Dump contents of an Object File -----------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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
12 // for FileCheck.
13 //
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.
17 //
18 // Output should be specialized for each format where appropriate.
19 //
20 //===----------------------------------------------------------------------===//
21 
22 #include "llvm-readobj.h"
23 #include "Error.h"
24 #include "ObjDumper.h"
25 #include "llvm/DebugInfo/CodeView/TypeTableBuilder.h"
26 #include "llvm/Object/Archive.h"
27 #include "llvm/Object/COFFImportFile.h"
28 #include "llvm/Object/ELFObjectFile.h"
29 #include "llvm/Object/MachOUniversal.h"
30 #include "llvm/Object/ObjectFile.h"
31 #include "llvm/Support/Casting.h"
32 #include "llvm/Support/CommandLine.h"
33 #include "llvm/Support/DataTypes.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FileSystem.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/ScopedPrinter.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include <string>
43 #include <system_error>
44 
45 using namespace llvm;
46 using namespace llvm::object;
47 
48 namespace opts {
49   cl::list<std::string> InputFilenames(cl::Positional,
50     cl::desc("<input object files>"),
51     cl::ZeroOrMore);
52 
53   // -file-headers, -h
54   cl::opt<bool> FileHeaders("file-headers",
55     cl::desc("Display file headers "));
56   cl::alias FileHeadersShort("h",
57     cl::desc("Alias for --file-headers"),
58     cl::aliasopt(FileHeaders));
59 
60   // -sections, -s
61   cl::opt<bool> Sections("sections",
62     cl::desc("Display all sections."));
63   cl::alias SectionsShort("s",
64     cl::desc("Alias for --sections"),
65     cl::aliasopt(Sections));
66 
67   // -section-relocations, -sr
68   cl::opt<bool> SectionRelocations("section-relocations",
69     cl::desc("Display relocations for each section shown."));
70   cl::alias SectionRelocationsShort("sr",
71     cl::desc("Alias for --section-relocations"),
72     cl::aliasopt(SectionRelocations));
73 
74   // -section-symbols, -st
75   cl::opt<bool> SectionSymbols("section-symbols",
76     cl::desc("Display symbols for each section shown."));
77   cl::alias SectionSymbolsShort("st",
78     cl::desc("Alias for --section-symbols"),
79     cl::aliasopt(SectionSymbols));
80 
81   // -section-data, -sd
82   cl::opt<bool> SectionData("section-data",
83     cl::desc("Display section data for each section shown."));
84   cl::alias SectionDataShort("sd",
85     cl::desc("Alias for --section-data"),
86     cl::aliasopt(SectionData));
87 
88   // -relocations, -r
89   cl::opt<bool> Relocations("relocations",
90     cl::desc("Display the relocation entries in the file"));
91   cl::alias RelocationsShort("r",
92     cl::desc("Alias for --relocations"),
93     cl::aliasopt(Relocations));
94 
95   // -notes, -n
96   cl::opt<bool> Notes("notes", cl::desc("Display the ELF notes in the file"));
97   cl::alias NotesShort("n", cl::desc("Alias for --notes"), cl::aliasopt(Notes));
98 
99   // -dyn-relocations
100   cl::opt<bool> DynRelocs("dyn-relocations",
101     cl::desc("Display the dynamic relocation entries in the file"));
102 
103   // -symbols, -t
104   cl::opt<bool> Symbols("symbols",
105     cl::desc("Display the symbol table"));
106   cl::alias SymbolsShort("t",
107     cl::desc("Alias for --symbols"),
108     cl::aliasopt(Symbols));
109 
110   // -dyn-symbols, -dt
111   cl::opt<bool> DynamicSymbols("dyn-symbols",
112     cl::desc("Display the dynamic symbol table"));
113   cl::alias DynamicSymbolsShort("dt",
114     cl::desc("Alias for --dyn-symbols"),
115     cl::aliasopt(DynamicSymbols));
116 
117   // -unwind, -u
118   cl::opt<bool> UnwindInfo("unwind",
119     cl::desc("Display unwind information"));
120   cl::alias UnwindInfoShort("u",
121     cl::desc("Alias for --unwind"),
122     cl::aliasopt(UnwindInfo));
123 
124   // -dynamic-table
125   cl::opt<bool> DynamicTable("dynamic-table",
126     cl::desc("Display the ELF .dynamic section table"));
127   cl::alias DynamicTableShort("d", cl::desc("Alias for --dynamic-table"),
128                               cl::aliasopt(DynamicTable));
129 
130   // -needed-libs
131   cl::opt<bool> NeededLibraries("needed-libs",
132     cl::desc("Display the needed libraries"));
133 
134   // -program-headers
135   cl::opt<bool> ProgramHeaders("program-headers",
136     cl::desc("Display ELF program headers"));
137   cl::alias ProgramHeadersShort("l", cl::desc("Alias for --program-headers"),
138                                 cl::aliasopt(ProgramHeaders));
139 
140   // -hash-table
141   cl::opt<bool> HashTable("hash-table",
142     cl::desc("Display ELF hash table"));
143 
144   // -gnu-hash-table
145   cl::opt<bool> GnuHashTable("gnu-hash-table",
146     cl::desc("Display ELF .gnu.hash section"));
147 
148   // -expand-relocs
149   cl::opt<bool> ExpandRelocs("expand-relocs",
150     cl::desc("Expand each shown relocation to multiple lines"));
151 
152   // -codeview
153   cl::opt<bool> CodeView("codeview",
154                          cl::desc("Display CodeView debug information"));
155 
156   // -codeview-merged-types
157   cl::opt<bool>
158       CodeViewMergedTypes("codeview-merged-types",
159                           cl::desc("Display the merged CodeView type stream"));
160 
161   // -codeview-subsection-bytes
162   cl::opt<bool> CodeViewSubsectionBytes(
163       "codeview-subsection-bytes",
164       cl::desc("Dump raw contents of codeview debug sections and records"));
165 
166   // -arm-attributes, -a
167   cl::opt<bool> ARMAttributes("arm-attributes",
168                               cl::desc("Display the ARM attributes section"));
169   cl::alias ARMAttributesShort("a", cl::desc("Alias for --arm-attributes"),
170                                cl::aliasopt(ARMAttributes));
171 
172   // -mips-plt-got
173   cl::opt<bool>
174   MipsPLTGOT("mips-plt-got",
175              cl::desc("Display the MIPS GOT and PLT GOT sections"));
176 
177   // -mips-abi-flags
178   cl::opt<bool> MipsABIFlags("mips-abi-flags",
179                              cl::desc("Display the MIPS.abiflags section"));
180 
181   // -mips-reginfo
182   cl::opt<bool> MipsReginfo("mips-reginfo",
183                             cl::desc("Display the MIPS .reginfo section"));
184 
185   // -mips-options
186   cl::opt<bool> MipsOptions("mips-options",
187                             cl::desc("Display the MIPS .MIPS.options section"));
188 
189   // -amdgpu-runtime-metadata
190   cl::opt<bool> AMDGPURuntimeMD("amdgpu-runtime-metadata",
191                                 cl::desc("Display AMDGPU runtime metadata"));
192 
193   // -coff-imports
194   cl::opt<bool>
195   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
196 
197   // -coff-exports
198   cl::opt<bool>
199   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
200 
201   // -coff-directives
202   cl::opt<bool>
203   COFFDirectives("coff-directives",
204                  cl::desc("Display the PE/COFF .drectve section"));
205 
206   // -coff-basereloc
207   cl::opt<bool>
208   COFFBaseRelocs("coff-basereloc",
209                  cl::desc("Display the PE/COFF .reloc section"));
210 
211   // -coff-debug-directory
212   cl::opt<bool>
213   COFFDebugDirectory("coff-debug-directory",
214                      cl::desc("Display the PE/COFF debug directory"));
215 
216   // -macho-data-in-code
217   cl::opt<bool>
218   MachODataInCode("macho-data-in-code",
219                   cl::desc("Display MachO Data in Code command"));
220 
221   // -macho-indirect-symbols
222   cl::opt<bool>
223   MachOIndirectSymbols("macho-indirect-symbols",
224                   cl::desc("Display MachO indirect symbols"));
225 
226   // -macho-linker-options
227   cl::opt<bool>
228   MachOLinkerOptions("macho-linker-options",
229                   cl::desc("Display MachO linker options"));
230 
231   // -macho-segment
232   cl::opt<bool>
233   MachOSegment("macho-segment",
234                   cl::desc("Display MachO Segment command"));
235 
236   // -macho-version-min
237   cl::opt<bool>
238   MachOVersionMin("macho-version-min",
239                   cl::desc("Display MachO version min command"));
240 
241   // -macho-dysymtab
242   cl::opt<bool>
243   MachODysymtab("macho-dysymtab",
244                   cl::desc("Display MachO Dysymtab command"));
245 
246   // -stackmap
247   cl::opt<bool>
248   PrintStackMap("stackmap",
249                 cl::desc("Display contents of stackmap section"));
250 
251   // -version-info
252   cl::opt<bool>
253       VersionInfo("version-info",
254                   cl::desc("Display ELF version sections (if present)"));
255   cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"),
256                              cl::aliasopt(VersionInfo));
257 
258   cl::opt<bool> SectionGroups("elf-section-groups",
259                               cl::desc("Display ELF section group contents"));
260   cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
261                                cl::aliasopt(SectionGroups));
262   cl::opt<bool> HashHistogram(
263       "elf-hash-histogram",
264       cl::desc("Display bucket list histogram for hash sections"));
265   cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
266                                cl::aliasopt(HashHistogram));
267 
268   cl::opt<OutputStyleTy>
269       Output("elf-output-style", cl::desc("Specify ELF dump style"),
270              cl::values(clEnumVal(LLVM, "LLVM default style"),
271                         clEnumVal(GNU, "GNU readelf style")),
272              cl::init(LLVM));
273 } // namespace opts
274 
275 namespace llvm {
276 
277 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) {
278   errs() << "\nError reading file: " << Msg << ".\n";
279   errs().flush();
280   exit(1);
281 }
282 
283 void error(Error EC) {
284   if (!EC)
285     return;
286   handleAllErrors(std::move(EC),
287                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
288 }
289 
290 void error(std::error_code EC) {
291   if (!EC)
292     return;
293   reportError(EC.message());
294 }
295 
296 bool relocAddressLess(RelocationRef a, RelocationRef b) {
297   return a.getOffset() < b.getOffset();
298 }
299 
300 } // namespace llvm
301 
302 static void reportError(StringRef Input, std::error_code EC) {
303   if (Input == "-")
304     Input = "<stdin>";
305 
306   reportError(Twine(Input) + ": " + EC.message());
307 }
308 
309 static void reportError(StringRef Input, StringRef Message) {
310   if (Input == "-")
311     Input = "<stdin>";
312 
313   reportError(Twine(Input) + ": " + Message);
314 }
315 
316 static void reportError(StringRef Input, Error Err) {
317   if (Input == "-")
318     Input = "<stdin>";
319   std::string ErrMsg;
320   {
321     raw_string_ostream ErrStream(ErrMsg);
322     logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": ");
323   }
324   reportError(ErrMsg);
325 }
326 
327 static bool isMipsArch(unsigned Arch) {
328   switch (Arch) {
329   case llvm::Triple::mips:
330   case llvm::Triple::mipsel:
331   case llvm::Triple::mips64:
332   case llvm::Triple::mips64el:
333     return true;
334   default:
335     return false;
336   }
337 }
338 namespace {
339 struct ReadObjTypeTableBuilder {
340   ReadObjTypeTableBuilder() : Allocator(), Builder(Allocator) {}
341 
342   llvm::BumpPtrAllocator Allocator;
343   llvm::codeview::TypeTableBuilder Builder;
344 };
345 }
346 static ReadObjTypeTableBuilder CVTypes;
347 
348 /// @brief Creates an format-specific object file dumper.
349 static std::error_code createDumper(const ObjectFile *Obj,
350                                     ScopedPrinter &Writer,
351                                     std::unique_ptr<ObjDumper> &Result) {
352   if (!Obj)
353     return readobj_error::unsupported_file_format;
354 
355   if (Obj->isCOFF())
356     return createCOFFDumper(Obj, Writer, Result);
357   if (Obj->isELF())
358     return createELFDumper(Obj, Writer, Result);
359   if (Obj->isMachO())
360     return createMachODumper(Obj, Writer, Result);
361   if (Obj->isWasm())
362     return createWasmDumper(Obj, Writer, Result);
363 
364   return readobj_error::unsupported_obj_file_format;
365 }
366 
367 /// @brief Dumps the specified object file.
368 static void dumpObject(const ObjectFile *Obj) {
369   ScopedPrinter Writer(outs());
370   std::unique_ptr<ObjDumper> Dumper;
371   if (std::error_code EC = createDumper(Obj, Writer, Dumper))
372     reportError(Obj->getFileName(), EC);
373 
374   if (opts::Output == opts::LLVM) {
375     outs() << '\n';
376     outs() << "File: " << Obj->getFileName() << "\n";
377     outs() << "Format: " << Obj->getFileFormatName() << "\n";
378     outs() << "Arch: " << Triple::getArchTypeName(
379                               (llvm::Triple::ArchType)Obj->getArch()) << "\n";
380     outs() << "AddressSize: " << (8 * Obj->getBytesInAddress()) << "bit\n";
381     Dumper->printLoadName();
382   }
383 
384   if (opts::FileHeaders)
385     Dumper->printFileHeaders();
386   if (opts::Sections)
387     Dumper->printSections();
388   if (opts::Relocations)
389     Dumper->printRelocations();
390   if (opts::DynRelocs)
391     Dumper->printDynamicRelocations();
392   if (opts::Symbols)
393     Dumper->printSymbols();
394   if (opts::DynamicSymbols)
395     Dumper->printDynamicSymbols();
396   if (opts::UnwindInfo)
397     Dumper->printUnwindInfo();
398   if (opts::DynamicTable)
399     Dumper->printDynamicTable();
400   if (opts::NeededLibraries)
401     Dumper->printNeededLibraries();
402   if (opts::ProgramHeaders)
403     Dumper->printProgramHeaders();
404   if (opts::HashTable)
405     Dumper->printHashTable();
406   if (opts::GnuHashTable)
407     Dumper->printGnuHashTable();
408   if (opts::VersionInfo)
409     Dumper->printVersionInfo();
410   if (Obj->isELF()) {
411     if (Obj->getArch() == llvm::Triple::arm)
412       if (opts::ARMAttributes)
413         Dumper->printAttributes();
414     if (isMipsArch(Obj->getArch())) {
415       if (opts::MipsPLTGOT)
416         Dumper->printMipsPLTGOT();
417       if (opts::MipsABIFlags)
418         Dumper->printMipsABIFlags();
419       if (opts::MipsReginfo)
420         Dumper->printMipsReginfo();
421       if (opts::MipsOptions)
422         Dumper->printMipsOptions();
423     }
424     if (Obj->getArch() == llvm::Triple::amdgcn)
425       if (opts::AMDGPURuntimeMD)
426         Dumper->printAMDGPURuntimeMD();
427     if (opts::SectionGroups)
428       Dumper->printGroupSections();
429     if (opts::HashHistogram)
430       Dumper->printHashHistogram();
431     if (opts::Notes)
432       Dumper->printNotes();
433   }
434   if (Obj->isCOFF()) {
435     if (opts::COFFImports)
436       Dumper->printCOFFImports();
437     if (opts::COFFExports)
438       Dumper->printCOFFExports();
439     if (opts::COFFDirectives)
440       Dumper->printCOFFDirectives();
441     if (opts::COFFBaseRelocs)
442       Dumper->printCOFFBaseReloc();
443     if (opts::COFFDebugDirectory)
444       Dumper->printCOFFDebugDirectory();
445     if (opts::CodeView)
446       Dumper->printCodeViewDebugInfo();
447     if (opts::CodeViewMergedTypes)
448       Dumper->mergeCodeViewTypes(CVTypes.Builder);
449   }
450   if (Obj->isMachO()) {
451     if (opts::MachODataInCode)
452       Dumper->printMachODataInCode();
453     if (opts::MachOIndirectSymbols)
454       Dumper->printMachOIndirectSymbols();
455     if (opts::MachOLinkerOptions)
456       Dumper->printMachOLinkerOptions();
457     if (opts::MachOSegment)
458       Dumper->printMachOSegment();
459     if (opts::MachOVersionMin)
460       Dumper->printMachOVersionMin();
461     if (opts::MachODysymtab)
462       Dumper->printMachODysymtab();
463   }
464   if (opts::PrintStackMap)
465     Dumper->printStackMap();
466 }
467 
468 /// @brief Dumps each object file in \a Arc;
469 static void dumpArchive(const Archive *Arc) {
470   Error Err = Error::success();
471   for (auto &Child : Arc->children(Err)) {
472     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
473     if (!ChildOrErr) {
474       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) {
475         std::string Buf;
476         raw_string_ostream OS(Buf);
477         logAllUnhandledErrors(ChildOrErr.takeError(), OS, "");
478         OS.flush();
479         reportError(Arc->getFileName(), Buf);
480       }
481       continue;
482     }
483     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
484       dumpObject(Obj);
485     else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
486       dumpCOFFImportFile(Imp);
487     else
488       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
489   }
490   if (Err)
491     reportError(Arc->getFileName(), std::move(Err));
492 }
493 
494 /// @brief Dumps each object file in \a MachO Universal Binary;
495 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
496   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
497     Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
498     if (ObjOrErr)
499       dumpObject(&*ObjOrErr.get());
500     else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
501       std::string Buf;
502       raw_string_ostream OS(Buf);
503       logAllUnhandledErrors(ObjOrErr.takeError(), OS, "");
504       OS.flush();
505       reportError(UBinary->getFileName(), Buf);
506     }
507     else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
508       dumpArchive(&*AOrErr.get());
509   }
510 }
511 
512 /// @brief Opens \a File and dumps it.
513 static void dumpInput(StringRef File) {
514 
515   // Attempt to open the binary.
516   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
517   if (!BinaryOrErr)
518     reportError(File, errorToErrorCode(BinaryOrErr.takeError()));
519   Binary &Binary = *BinaryOrErr.get().getBinary();
520 
521   if (Archive *Arc = dyn_cast<Archive>(&Binary))
522     dumpArchive(Arc);
523   else if (MachOUniversalBinary *UBinary =
524                dyn_cast<MachOUniversalBinary>(&Binary))
525     dumpMachOUniversalBinary(UBinary);
526   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
527     dumpObject(Obj);
528   else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
529     dumpCOFFImportFile(Import);
530   else
531     reportError(File, readobj_error::unrecognized_file_format);
532 }
533 
534 int main(int argc, const char *argv[]) {
535   sys::PrintStackTraceOnErrorSignal(argv[0]);
536   PrettyStackTraceProgram X(argc, argv);
537   llvm_shutdown_obj Y;
538 
539   // Register the target printer for --version.
540   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
541 
542   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
543 
544   // Default to stdin if no filename is specified.
545   if (opts::InputFilenames.size() == 0)
546     opts::InputFilenames.push_back("-");
547 
548   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
549                 dumpInput);
550 
551   if (opts::CodeViewMergedTypes) {
552     ScopedPrinter W(outs());
553     dumpCodeViewMergedTypes(W, CVTypes.Builder);
554   }
555 
556   return 0;
557 }
558