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