xref: /llvm-project/llvm/tools/llvm-readobj/llvm-readobj.cpp (revision c2189b8311affb1a8de08862767b597415010d96)
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 "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"
45 #include <string>
46 #include <system_error>
47 
48 using namespace llvm;
49 using namespace llvm::object;
50 
51 namespace opts {
52   cl::list<std::string> InputFilenames(cl::Positional,
53     cl::desc("<input object files>"),
54     cl::ZeroOrMore);
55 
56   // -wide, -W
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));
62 
63   // -file-headers, -h
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));
69 
70   // -sections, -s, -S
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));
80 
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));
87 
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));
94 
95   // -section-data, -sd
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));
101 
102   // -relocations, -r
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));
108 
109   // -notes, -n
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));
112 
113   // -dyn-relocations
114   cl::opt<bool> DynRelocs("dyn-relocations",
115     cl::desc("Display the dynamic relocation entries in the file"));
116 
117   // -symbols, -t
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));
123 
124   // -dyn-symbols, -dt
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));
130 
131   // -unwind, -u
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));
137 
138   // -dynamic-table
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));
143 
144   // -needed-libs
145   cl::opt<bool> NeededLibraries("needed-libs",
146     cl::desc("Display the needed libraries"));
147 
148   // -program-headers
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));
153 
154   // -hash-table
155   cl::opt<bool> HashTable("hash-table",
156     cl::desc("Display ELF hash table"));
157 
158   // -gnu-hash-table
159   cl::opt<bool> GnuHashTable("gnu-hash-table",
160     cl::desc("Display ELF .gnu.hash section"));
161 
162   // -expand-relocs
163   cl::opt<bool> ExpandRelocs("expand-relocs",
164     cl::desc("Expand each shown relocation to multiple lines"));
165 
166   // -codeview
167   cl::opt<bool> CodeView("codeview",
168                          cl::desc("Display CodeView debug information"));
169 
170   // -codeview-merged-types
171   cl::opt<bool>
172       CodeViewMergedTypes("codeview-merged-types",
173                           cl::desc("Display the merged CodeView type stream"));
174 
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"));
179 
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));
185 
186   // -mips-plt-got
187   cl::opt<bool>
188   MipsPLTGOT("mips-plt-got",
189              cl::desc("Display the MIPS GOT and PLT GOT sections"));
190 
191   // -mips-abi-flags
192   cl::opt<bool> MipsABIFlags("mips-abi-flags",
193                              cl::desc("Display the MIPS.abiflags section"));
194 
195   // -mips-reginfo
196   cl::opt<bool> MipsReginfo("mips-reginfo",
197                             cl::desc("Display the MIPS .reginfo section"));
198 
199   // -mips-options
200   cl::opt<bool> MipsOptions("mips-options",
201                             cl::desc("Display the MIPS .MIPS.options section"));
202 
203   // -amdgpu-code-object-metadata
204   cl::opt<bool> AMDGPUCodeObjectMetadata(
205       "amdgpu-code-object-metadata",
206       cl::desc("Display AMDGPU code object metadata"));
207 
208   // -coff-imports
209   cl::opt<bool>
210   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
211 
212   // -coff-exports
213   cl::opt<bool>
214   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
215 
216   // -coff-directives
217   cl::opt<bool>
218   COFFDirectives("coff-directives",
219                  cl::desc("Display the PE/COFF .drectve section"));
220 
221   // -coff-basereloc
222   cl::opt<bool>
223   COFFBaseRelocs("coff-basereloc",
224                  cl::desc("Display the PE/COFF .reloc section"));
225 
226   // -coff-debug-directory
227   cl::opt<bool>
228   COFFDebugDirectory("coff-debug-directory",
229                      cl::desc("Display the PE/COFF debug directory"));
230 
231   // -coff-resources
232   cl::opt<bool> COFFResources("coff-resources",
233                               cl::desc("Display the PE/COFF .rsrc section"));
234 
235   // -coff-load-config
236   cl::opt<bool>
237   COFFLoadConfig("coff-load-config",
238                  cl::desc("Display the PE/COFF load config"));
239 
240   // -macho-data-in-code
241   cl::opt<bool>
242   MachODataInCode("macho-data-in-code",
243                   cl::desc("Display MachO Data in Code command"));
244 
245   // -macho-indirect-symbols
246   cl::opt<bool>
247   MachOIndirectSymbols("macho-indirect-symbols",
248                   cl::desc("Display MachO indirect symbols"));
249 
250   // -macho-linker-options
251   cl::opt<bool>
252   MachOLinkerOptions("macho-linker-options",
253                   cl::desc("Display MachO linker options"));
254 
255   // -macho-segment
256   cl::opt<bool>
257   MachOSegment("macho-segment",
258                   cl::desc("Display MachO Segment command"));
259 
260   // -macho-version-min
261   cl::opt<bool>
262   MachOVersionMin("macho-version-min",
263                   cl::desc("Display MachO version min command"));
264 
265   // -macho-dysymtab
266   cl::opt<bool>
267   MachODysymtab("macho-dysymtab",
268                   cl::desc("Display MachO Dysymtab command"));
269 
270   // -stackmap
271   cl::opt<bool>
272   PrintStackMap("stackmap",
273                 cl::desc("Display contents of stackmap section"));
274 
275   // -version-info
276   cl::opt<bool>
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));
281 
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));
291 
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")),
296              cl::init(LLVM));
297 } // namespace opts
298 
299 namespace llvm {
300 
301 LLVM_ATTRIBUTE_NORETURN void reportError(Twine Msg) {
302   errs() << "\nError reading file: " << Msg << ".\n";
303   errs().flush();
304   exit(1);
305 }
306 
307 void error(Error EC) {
308   if (!EC)
309     return;
310   handleAllErrors(std::move(EC),
311                   [&](const ErrorInfoBase &EI) { reportError(EI.message()); });
312 }
313 
314 void error(std::error_code EC) {
315   if (!EC)
316     return;
317   reportError(EC.message());
318 }
319 
320 bool relocAddressLess(RelocationRef a, RelocationRef b) {
321   return a.getOffset() < b.getOffset();
322 }
323 
324 } // namespace llvm
325 
326 static void reportError(StringRef Input, std::error_code EC) {
327   if (Input == "-")
328     Input = "<stdin>";
329 
330   reportError(Twine(Input) + ": " + EC.message());
331 }
332 
333 static void reportError(StringRef Input, Error Err) {
334   if (Input == "-")
335     Input = "<stdin>";
336   std::string ErrMsg;
337   {
338     raw_string_ostream ErrStream(ErrMsg);
339     logAllUnhandledErrors(std::move(Err), ErrStream, Input + ": ");
340   }
341   reportError(ErrMsg);
342 }
343 
344 static bool isMipsArch(unsigned Arch) {
345   switch (Arch) {
346   case llvm::Triple::mips:
347   case llvm::Triple::mipsel:
348   case llvm::Triple::mips64:
349   case llvm::Triple::mips64el:
350     return true;
351   default:
352     return false;
353   }
354 }
355 namespace {
356 struct ReadObjTypeTableBuilder {
357   ReadObjTypeTableBuilder()
358       : Allocator(), IDTable(Allocator), TypeTable(Allocator) {}
359 
360   llvm::BumpPtrAllocator Allocator;
361   llvm::codeview::TypeTableBuilder IDTable;
362   llvm::codeview::TypeTableBuilder TypeTable;
363 };
364 }
365 static ReadObjTypeTableBuilder CVTypes;
366 
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) {
371   if (!Obj)
372     return readobj_error::unsupported_file_format;
373 
374   if (Obj->isCOFF())
375     return createCOFFDumper(Obj, Writer, Result);
376   if (Obj->isELF())
377     return createELFDumper(Obj, Writer, Result);
378   if (Obj->isMachO())
379     return createMachODumper(Obj, Writer, Result);
380   if (Obj->isWasm())
381     return createWasmDumper(Obj, Writer, Result);
382 
383   return readobj_error::unsupported_obj_file_format;
384 }
385 
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);
392 
393   if (opts::Output == opts::LLVM) {
394     outs() << '\n';
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();
401   }
402 
403   if (opts::FileHeaders)
404     Dumper->printFileHeaders();
405   if (opts::Sections)
406     Dumper->printSections();
407   if (opts::Relocations)
408     Dumper->printRelocations();
409   if (opts::DynRelocs)
410     Dumper->printDynamicRelocations();
411   if (opts::Symbols)
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();
423   if (opts::HashTable)
424     Dumper->printHashTable();
425   if (opts::GnuHashTable)
426     Dumper->printGnuHashTable();
427   if (opts::VersionInfo)
428     Dumper->printVersionInfo();
429   if (Obj->isELF()) {
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();
442     }
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();
450     if (opts::Notes)
451       Dumper->printNotes();
452   }
453   if (Obj->isCOFF()) {
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();
468     if (opts::CodeView)
469       Dumper->printCodeViewDebugInfo();
470     if (opts::CodeViewMergedTypes)
471       Dumper->mergeCodeViewTypes(CVTypes.IDTable, CVTypes.TypeTable);
472   }
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();
486   }
487   if (opts::PrintStackMap)
488     Dumper->printStackMap();
489 }
490 
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();
496     if (!ChildOrErr) {
497       if (auto E = isNotObjectErrorInvalidFileType(ChildOrErr.takeError())) {
498         reportError(Arc->getFileName(), ChildOrErr.takeError());
499       }
500       continue;
501     }
502     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
503       dumpObject(Obj);
504     else if (COFFImportFile *Imp = dyn_cast<COFFImportFile>(&*ChildOrErr.get()))
505       dumpCOFFImportFile(Imp);
506     else
507       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
508   }
509   if (Err)
510     reportError(Arc->getFileName(), std::move(Err));
511 }
512 
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();
517     if (ObjOrErr)
518       dumpObject(&*ObjOrErr.get());
519     else if (auto E = isNotObjectErrorInvalidFileType(ObjOrErr.takeError())) {
520       reportError(UBinary->getFileName(), ObjOrErr.takeError());
521     }
522     else if (Expected<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
523       dumpArchive(&*AOrErr.get());
524   }
525 }
526 
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));
533 }
534 
535 
536 /// @brief Opens \a File and dumps it.
537 static void dumpInput(StringRef File) {
538 
539   // Attempt to open the binary.
540   Expected<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
541   if (!BinaryOrErr)
542     reportError(File, BinaryOrErr.takeError());
543   Binary &Binary = *BinaryOrErr.get().getBinary();
544 
545   if (Archive *Arc = dyn_cast<Archive>(&Binary))
546     dumpArchive(Arc);
547   else if (MachOUniversalBinary *UBinary =
548                dyn_cast<MachOUniversalBinary>(&Binary))
549     dumpMachOUniversalBinary(UBinary);
550   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
551     dumpObject(Obj);
552   else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
553     dumpCOFFImportFile(Import);
554   else if (WindowsResource *WinRes = dyn_cast<WindowsResource>(&Binary))
555     dumpWindowsResourceFile(WinRes);
556   else
557     reportError(File, readobj_error::unrecognized_file_format);
558 }
559 
560 int main(int argc, const char *argv[]) {
561   StringRef ToolName = argv[0];
562   sys::PrintStackTraceOnErrorSignal(ToolName);
563   PrettyStackTraceProgram X(argc, argv);
564   llvm_shutdown_obj Y;
565 
566   // Register the target printer for --version.
567   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
568 
569   opts::WideOutput.setHiddenFlag(cl::Hidden);
570 
571   if (sys::path::stem(ToolName).find("readelf") != StringRef::npos)
572     opts::Output = opts::GNU;
573 
574   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
575 
576   // Default to stdin if no filename is specified.
577   if (opts::InputFilenames.size() == 0)
578     opts::InputFilenames.push_back("-");
579 
580   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
581                 dumpInput);
582 
583   if (opts::CodeViewMergedTypes) {
584     ScopedPrinter W(outs());
585     dumpCodeViewMergedTypes(W, CVTypes.IDTable, CVTypes.TypeTable);
586   }
587 
588   return 0;
589 }
590