xref: /llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp (revision 7498cd61fb7930a64a0ed4dae8703b49ae0500ff)
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-code-object-metadata
190   cl::opt<bool> AMDGPUCodeObjectMetadata(
191       "amdgpu-code-object-metadata",
192       cl::desc("Display AMDGPU code object metadata"));
193 
194   // -coff-imports
195   cl::opt<bool>
196   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
197 
198   // -coff-exports
199   cl::opt<bool>
200   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
201 
202   // -coff-directives
203   cl::opt<bool>
204   COFFDirectives("coff-directives",
205                  cl::desc("Display the PE/COFF .drectve section"));
206 
207   // -coff-basereloc
208   cl::opt<bool>
209   COFFBaseRelocs("coff-basereloc",
210                  cl::desc("Display the PE/COFF .reloc section"));
211 
212   // -coff-debug-directory
213   cl::opt<bool>
214   COFFDebugDirectory("coff-debug-directory",
215                      cl::desc("Display the PE/COFF debug directory"));
216 
217   // -macho-data-in-code
218   cl::opt<bool>
219   MachODataInCode("macho-data-in-code",
220                   cl::desc("Display MachO Data in Code command"));
221 
222   // -macho-indirect-symbols
223   cl::opt<bool>
224   MachOIndirectSymbols("macho-indirect-symbols",
225                   cl::desc("Display MachO indirect symbols"));
226 
227   // -macho-linker-options
228   cl::opt<bool>
229   MachOLinkerOptions("macho-linker-options",
230                   cl::desc("Display MachO linker options"));
231 
232   // -macho-segment
233   cl::opt<bool>
234   MachOSegment("macho-segment",
235                   cl::desc("Display MachO Segment command"));
236 
237   // -macho-version-min
238   cl::opt<bool>
239   MachOVersionMin("macho-version-min",
240                   cl::desc("Display MachO version min command"));
241 
242   // -macho-dysymtab
243   cl::opt<bool>
244   MachODysymtab("macho-dysymtab",
245                   cl::desc("Display MachO Dysymtab command"));
246 
247   // -stackmap
248   cl::opt<bool>
249   PrintStackMap("stackmap",
250                 cl::desc("Display contents of stackmap section"));
251 
252   // -version-info
253   cl::opt<bool>
254       VersionInfo("version-info",
255                   cl::desc("Display ELF version sections (if present)"));
256   cl::alias VersionInfoShort("V", cl::desc("Alias for -version-info"),
257                              cl::aliasopt(VersionInfo));
258 
259   cl::opt<bool> SectionGroups("elf-section-groups",
260                               cl::desc("Display ELF section group contents"));
261   cl::alias SectionGroupsShort("g", cl::desc("Alias for -elf-sections-groups"),
262                                cl::aliasopt(SectionGroups));
263   cl::opt<bool> HashHistogram(
264       "elf-hash-histogram",
265       cl::desc("Display bucket list histogram for hash sections"));
266   cl::alias HashHistogramShort("I", cl::desc("Alias for -elf-hash-histogram"),
267                                cl::aliasopt(HashHistogram));
268 
269   cl::opt<OutputStyleTy>
270       Output("elf-output-style", cl::desc("Specify ELF dump style"),
271              cl::values(clEnumVal(LLVM, "LLVM default style"),
272                         clEnumVal(GNU, "GNU readelf style")),
273              cl::init(LLVM));
274 } // namespace opts
275 
276 namespace llvm {
277 
278 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) {
279   errs() << "\nError reading file: " << Msg << ".\n";
280   errs().flush();
281   exit(1);
282 }
283 
284 void error(Error EC) {
285   if (!EC)
286     return;
287   handleAllErrors(std::move(EC),
288                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
289 }
290 
291 void error(std::error_code EC) {
292   if (!EC)
293     return;
294   reportError(EC.message());
295 }
296 
297 bool relocAddressLess(RelocationRef a, RelocationRef b) {
298   return a.getOffset() < b.getOffset();
299 }
300 
301 } // namespace llvm
302 
303 static void reportError(StringRef Input, std::error_code EC) {
304   if (Input == "-")
305     Input = "<stdin>";
306 
307   reportError(Twine(Input) + ": " + EC.message());
308 }
309 
310 static void reportError(StringRef Input, StringRef Message) {
311   if (Input == "-")
312     Input = "<stdin>";
313 
314   reportError(Twine(Input) + ": " + Message);
315 }
316 
317 static void reportError(StringRef Input, Error Err) {
318   if (Input == "-")
319     Input = "<stdin>";
320   std::string ErrMsg;
321   {
322     raw_string_ostream ErrStream(ErrMsg);
323     logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": ");
324   }
325   reportError(ErrMsg);
326 }
327 
328 static bool isMipsArch(unsigned Arch) {
329   switch (Arch) {
330   case llvm::Triple::mips:
331   case llvm::Triple::mipsel:
332   case llvm::Triple::mips64:
333   case llvm::Triple::mips64el:
334     return true;
335   default:
336     return false;
337   }
338 }
339 namespace {
340 struct ReadObjTypeTableBuilder {
341   ReadObjTypeTableBuilder() : Allocator(), Builder(Allocator) {}
342 
343   llvm::BumpPtrAllocator Allocator;
344   llvm::codeview::TypeTableBuilder Builder;
345 };
346 }
347 static ReadObjTypeTableBuilder CVTypes;
348 
349 /// @brief Creates an format-specific object file dumper.
350 static std::error_code createDumper(const ObjectFile *Obj,
351                                     ScopedPrinter &Writer,
352                                     std::unique_ptr<ObjDumper> &Result) {
353   if (!Obj)
354     return readobj_error::unsupported_file_format;
355 
356   if (Obj->isCOFF())
357     return createCOFFDumper(Obj, Writer, Result);
358   if (Obj->isELF())
359     return createELFDumper(Obj, Writer, Result);
360   if (Obj->isMachO())
361     return createMachODumper(Obj, Writer, Result);
362   if (Obj->isWasm())
363     return createWasmDumper(Obj, Writer, Result);
364 
365   return readobj_error::unsupported_obj_file_format;
366 }
367 
368 /// @brief Dumps the specified object file.
369 static void dumpObject(const ObjectFile *Obj) {
370   ScopedPrinter Writer(outs());
371   std::unique_ptr<ObjDumper> Dumper;
372   if (std::error_code EC = createDumper(Obj, Writer, Dumper))
373     reportError(Obj->getFileName(), EC);
374 
375   if (opts::Output == opts::LLVM) {
376     outs() << '\n';
377     outs() << "File: " << Obj->getFileName() << "\n";
378     outs() << "Format: " << Obj->getFileFormatName() << "\n";
379     outs() << "Arch: " << Triple::getArchTypeName(
380                               (llvm::Triple::ArchType)Obj->getArch()) << "\n";
381     outs() << "AddressSize: " << (8 * Obj->getBytesInAddress()) << "bit\n";
382     Dumper->printLoadName();
383   }
384 
385   if (opts::FileHeaders)
386     Dumper->printFileHeaders();
387   if (opts::Sections)
388     Dumper->printSections();
389   if (opts::Relocations)
390     Dumper->printRelocations();
391   if (opts::DynRelocs)
392     Dumper->printDynamicRelocations();
393   if (opts::Symbols)
394     Dumper->printSymbols();
395   if (opts::DynamicSymbols)
396     Dumper->printDynamicSymbols();
397   if (opts::UnwindInfo)
398     Dumper->printUnwindInfo();
399   if (opts::DynamicTable)
400     Dumper->printDynamicTable();
401   if (opts::NeededLibraries)
402     Dumper->printNeededLibraries();
403   if (opts::ProgramHeaders)
404     Dumper->printProgramHeaders();
405   if (opts::HashTable)
406     Dumper->printHashTable();
407   if (opts::GnuHashTable)
408     Dumper->printGnuHashTable();
409   if (opts::VersionInfo)
410     Dumper->printVersionInfo();
411   if (Obj->isELF()) {
412     if (Obj->getArch() == llvm::Triple::arm)
413       if (opts::ARMAttributes)
414         Dumper->printAttributes();
415     if (isMipsArch(Obj->getArch())) {
416       if (opts::MipsPLTGOT)
417         Dumper->printMipsPLTGOT();
418       if (opts::MipsABIFlags)
419         Dumper->printMipsABIFlags();
420       if (opts::MipsReginfo)
421         Dumper->printMipsReginfo();
422       if (opts::MipsOptions)
423         Dumper->printMipsOptions();
424     }
425     if (Obj->getArch() == llvm::Triple::amdgcn)
426       if (opts::AMDGPUCodeObjectMetadata)
427         Dumper->printAMDGPUCodeObjectMetadata();
428     if (opts::SectionGroups)
429       Dumper->printGroupSections();
430     if (opts::HashHistogram)
431       Dumper->printHashHistogram();
432     if (opts::Notes)
433       Dumper->printNotes();
434   }
435   if (Obj->isCOFF()) {
436     if (opts::COFFImports)
437       Dumper->printCOFFImports();
438     if (opts::COFFExports)
439       Dumper->printCOFFExports();
440     if (opts::COFFDirectives)
441       Dumper->printCOFFDirectives();
442     if (opts::COFFBaseRelocs)
443       Dumper->printCOFFBaseReloc();
444     if (opts::COFFDebugDirectory)
445       Dumper->printCOFFDebugDirectory();
446     if (opts::CodeView)
447       Dumper->printCodeViewDebugInfo();
448     if (opts::CodeViewMergedTypes)
449       Dumper->mergeCodeViewTypes(CVTypes.Builder);
450   }
451   if (Obj->isMachO()) {
452     if (opts::MachODataInCode)
453       Dumper->printMachODataInCode();
454     if (opts::MachOIndirectSymbols)
455       Dumper->printMachOIndirectSymbols();
456     if (opts::MachOLinkerOptions)
457       Dumper->printMachOLinkerOptions();
458     if (opts::MachOSegment)
459       Dumper->printMachOSegment();
460     if (opts::MachOVersionMin)
461       Dumper->printMachOVersionMin();
462     if (opts::MachODysymtab)
463       Dumper->printMachODysymtab();
464   }
465   if (opts::PrintStackMap)
466     Dumper->printStackMap();
467 }
468 
469 /// @brief Dumps each object file in \a Arc;
470 static void dumpArchive(const Archive *Arc) {
471   Error Err = Error::success();
472   for (auto &Child : Arc->children(Err)) {
473     Expected<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
474     if (!ChildOrErr) {
475       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) {
476         std::string Buf;
477         raw_string_ostream OS(Buf);
478         logAllUnhandledErrors(ChildOrErr.takeError(), OS, "");
479         OS.flush();
480         reportError(Arc->getFileName(), Buf);
481       }
482       continue;
483     }
484     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
485       dumpObject(Obj);
486     else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
487       dumpCOFFImportFile(Imp);
488     else
489       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
490   }
491   if (Err)
492     reportError(Arc->getFileName(), std::move(Err));
493 }
494 
495 /// @brief Dumps each object file in \a MachO Universal Binary;
496 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
497   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
498     Expected<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
499     if (ObjOrErr)
500       dumpObject(&*ObjOrErr.get());
501     else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
502       std::string Buf;
503       raw_string_ostream OS(Buf);
504       logAllUnhandledErrors(ObjOrErr.takeError(), OS, "");
505       OS.flush();
506       reportError(UBinary->getFileName(), Buf);
507     }
508     else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
509       dumpArchive(&*AOrErr.get());
510   }
511 }
512 
513 /// @brief Opens \a File and dumps it.
514 static void dumpInput(StringRef File) {
515 
516   // Attempt to open the binary.
517   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
518   if (!BinaryOrErr)
519     reportError(File, errorToErrorCode(BinaryOrErr.takeError()));
520   Binary &Binary = *BinaryOrErr.get().getBinary();
521 
522   if (Archive *Arc = dyn_cast<Archive>(&Binary))
523     dumpArchive(Arc);
524   else if (MachOUniversalBinary *UBinary =
525                dyn_cast<MachOUniversalBinary>(&Binary))
526     dumpMachOUniversalBinary(UBinary);
527   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
528     dumpObject(Obj);
529   else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
530     dumpCOFFImportFile(Import);
531   else
532     reportError(File, readobj_error::unrecognized_file_format);
533 }
534 
535 int main(int argc, const char *argv[]) {
536   sys::PrintStackTraceOnErrorSignal(argv[0]);
537   PrettyStackTraceProgram X(argc, argv);
538   llvm_shutdown_obj Y;
539 
540   // Register the target printer for --version.
541   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
542 
543   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
544 
545   // Default to stdin if no filename is specified.
546   if (opts::InputFilenames.size() == 0)
547     opts::InputFilenames.push_back("-");
548 
549   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
550                 dumpInput);
551 
552   if (opts::CodeViewMergedTypes) {
553     ScopedPrinter W(outs());
554     dumpCodeViewMergedTypes(W, CVTypes.Builder);
555   }
556 
557   return 0;
558 }
559