[llvm-readobj] Fix another "time of check to time of use bug".
[oota-llvm.git] / tools / llvm-readobj / llvm-readobj.cpp
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 "StreamWriter.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/Signals.h"
39 #include "llvm/Support/TargetRegistry.h"
40 #include "llvm/Support/TargetSelect.h"
41 #include <string>
42 #include <system_error>
43
44 using namespace llvm;
45 using namespace llvm::object;
46
47 namespace opts {
48   cl::list<std::string> InputFilenames(cl::Positional,
49     cl::desc("<input object files>"),
50     cl::ZeroOrMore);
51
52   // -file-headers, -h
53   cl::opt<bool> FileHeaders("file-headers",
54     cl::desc("Display file headers "));
55   cl::alias FileHeadersShort("h",
56     cl::desc("Alias for --file-headers"),
57     cl::aliasopt(FileHeaders));
58
59   // -sections, -s
60   cl::opt<bool> Sections("sections",
61     cl::desc("Display all sections."));
62   cl::alias SectionsShort("s",
63     cl::desc("Alias for --sections"),
64     cl::aliasopt(Sections));
65
66   // -section-relocations, -sr
67   cl::opt<bool> SectionRelocations("section-relocations",
68     cl::desc("Display relocations for each section shown."));
69   cl::alias SectionRelocationsShort("sr",
70     cl::desc("Alias for --section-relocations"),
71     cl::aliasopt(SectionRelocations));
72
73   // -section-symbols, -st
74   cl::opt<bool> SectionSymbols("section-symbols",
75     cl::desc("Display symbols for each section shown."));
76   cl::alias SectionSymbolsShort("st",
77     cl::desc("Alias for --section-symbols"),
78     cl::aliasopt(SectionSymbols));
79
80   // -section-data, -sd
81   cl::opt<bool> SectionData("section-data",
82     cl::desc("Display section data for each section shown."));
83   cl::alias SectionDataShort("sd",
84     cl::desc("Alias for --section-data"),
85     cl::aliasopt(SectionData));
86
87   // -relocations, -r
88   cl::opt<bool> Relocations("relocations",
89     cl::desc("Display the relocation entries in the file"));
90   cl::alias RelocationsShort("r",
91     cl::desc("Alias for --relocations"),
92     cl::aliasopt(Relocations));
93
94   // -dyn-relocations
95   cl::opt<bool> DynRelocs("dyn-relocations",
96     cl::desc("Display the dynamic relocation entries in the file"));
97
98   // -symbols, -t
99   cl::opt<bool> Symbols("symbols",
100     cl::desc("Display the symbol table"));
101   cl::alias SymbolsShort("t",
102     cl::desc("Alias for --symbols"),
103     cl::aliasopt(Symbols));
104
105   // -dyn-symbols, -dt
106   cl::opt<bool> DynamicSymbols("dyn-symbols",
107     cl::desc("Display the dynamic symbol table"));
108   cl::alias DynamicSymbolsShort("dt",
109     cl::desc("Alias for --dyn-symbols"),
110     cl::aliasopt(DynamicSymbols));
111
112   // -unwind, -u
113   cl::opt<bool> UnwindInfo("unwind",
114     cl::desc("Display unwind information"));
115   cl::alias UnwindInfoShort("u",
116     cl::desc("Alias for --unwind"),
117     cl::aliasopt(UnwindInfo));
118
119   // -dynamic-table
120   cl::opt<bool> DynamicTable("dynamic-table",
121     cl::desc("Display the ELF .dynamic section table"));
122
123   // -needed-libs
124   cl::opt<bool> NeededLibraries("needed-libs",
125     cl::desc("Display the needed libraries"));
126
127   // -program-headers
128   cl::opt<bool> ProgramHeaders("program-headers",
129     cl::desc("Display ELF program headers"));
130
131   // -hash-table
132   cl::opt<bool> HashTable("hash-table",
133     cl::desc("Display ELF hash table"));
134
135   // -expand-relocs
136   cl::opt<bool> ExpandRelocs("expand-relocs",
137     cl::desc("Expand each shown relocation to multiple lines"));
138
139   // -codeview
140   cl::opt<bool> CodeView("codeview",
141                          cl::desc("Display CodeView debug information"));
142
143   // -codeview-subsection-bytes
144   cl::opt<bool> CodeViewSubsectionBytes(
145       "codeview-subsection-bytes",
146       cl::desc("Dump raw contents of codeview debug sections and records"));
147
148   // -arm-attributes, -a
149   cl::opt<bool> ARMAttributes("arm-attributes",
150                               cl::desc("Display the ARM attributes section"));
151   cl::alias ARMAttributesShort("-a", cl::desc("Alias for --arm-attributes"),
152                                cl::aliasopt(ARMAttributes));
153
154   // -mips-plt-got
155   cl::opt<bool>
156   MipsPLTGOT("mips-plt-got",
157              cl::desc("Display the MIPS GOT and PLT GOT sections"));
158
159   // -mips-abi-flags
160   cl::opt<bool> MipsABIFlags("mips-abi-flags",
161                              cl::desc("Display the MIPS.abiflags section"));
162
163   // -mips-reginfo
164   cl::opt<bool> MipsReginfo("mips-reginfo",
165                             cl::desc("Display the MIPS .reginfo section"));
166
167   // -coff-imports
168   cl::opt<bool>
169   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
170
171   // -coff-exports
172   cl::opt<bool>
173   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
174
175   // -coff-directives
176   cl::opt<bool>
177   COFFDirectives("coff-directives",
178                  cl::desc("Display the PE/COFF .drectve section"));
179
180   // -coff-basereloc
181   cl::opt<bool>
182   COFFBaseRelocs("coff-basereloc",
183                  cl::desc("Display the PE/COFF .reloc section"));
184
185   // -macho-data-in-code
186   cl::opt<bool>
187   MachODataInCode("macho-data-in-code",
188                   cl::desc("Display MachO Data in Code command"));
189
190   // -macho-indirect-symbols
191   cl::opt<bool>
192   MachOIndirectSymbols("macho-indirect-symbols",
193                   cl::desc("Display MachO indirect symbols"));
194
195   // -macho-linker-options
196   cl::opt<bool>
197   MachOLinkerOptions("macho-linker-options",
198                   cl::desc("Display MachO linker options"));
199
200   // -macho-segment
201   cl::opt<bool>
202   MachOSegment("macho-segment",
203                   cl::desc("Display MachO Segment command"));
204
205   // -macho-version-min
206   cl::opt<bool>
207   MachOVersionMin("macho-version-min",
208                   cl::desc("Display MachO version min command"));
209
210   // -macho-dysymtab
211   cl::opt<bool>
212   MachODysymtab("macho-dysymtab",
213                   cl::desc("Display MachO Dysymtab command"));
214
215   // -stackmap
216   cl::opt<bool>
217   PrintStackMap("stackmap",
218                 cl::desc("Display contents of stackmap section"));
219
220 } // namespace opts
221
222 namespace llvm {
223
224 void reportError(Twine Msg) {
225   outs() << "\nError reading file: " << Msg << ".\n";
226   outs().flush();
227   exit(1);
228 }
229
230 void error(std::error_code EC) {
231   if (!EC)
232     return;
233
234   reportError(EC.message());
235 }
236
237 bool relocAddressLess(RelocationRef a, RelocationRef b) {
238   return a.getOffset() < b.getOffset();
239 }
240
241 } // namespace llvm
242
243 static void reportError(StringRef Input, std::error_code EC) {
244   if (Input == "-")
245     Input = "<stdin>";
246
247   reportError(Twine(Input) + ": " + EC.message());
248 }
249
250 static void reportError(StringRef Input, StringRef Message) {
251   if (Input == "-")
252     Input = "<stdin>";
253
254   reportError(Twine(Input) + ": " + Message);
255 }
256
257 static bool isMipsArch(unsigned Arch) {
258   switch (Arch) {
259   case llvm::Triple::mips:
260   case llvm::Triple::mipsel:
261   case llvm::Triple::mips64:
262   case llvm::Triple::mips64el:
263     return true;
264   default:
265     return false;
266   }
267 }
268
269 /// @brief Creates an format-specific object file dumper.
270 static std::error_code createDumper(const ObjectFile *Obj, StreamWriter &Writer,
271                                     std::unique_ptr<ObjDumper> &Result) {
272   if (!Obj)
273     return readobj_error::unsupported_file_format;
274
275   if (Obj->isCOFF())
276     return createCOFFDumper(Obj, Writer, Result);
277   if (Obj->isELF())
278     return createELFDumper(Obj, Writer, Result);
279   if (Obj->isMachO())
280     return createMachODumper(Obj, Writer, Result);
281
282   return readobj_error::unsupported_obj_file_format;
283 }
284
285 /// @brief Dumps the specified object file.
286 static void dumpObject(const ObjectFile *Obj) {
287   StreamWriter Writer(outs());
288   std::unique_ptr<ObjDumper> Dumper;
289   if (std::error_code EC = createDumper(Obj, Writer, Dumper)) {
290     reportError(Obj->getFileName(), EC);
291     return;
292   }
293
294   outs() << '\n';
295   outs() << "File: " << Obj->getFileName() << "\n";
296   outs() << "Format: " << Obj->getFileFormatName() << "\n";
297   outs() << "Arch: "
298          << Triple::getArchTypeName((llvm::Triple::ArchType)Obj->getArch())
299          << "\n";
300   outs() << "AddressSize: " << (8*Obj->getBytesInAddress()) << "bit\n";
301   Dumper->printLoadName();
302
303   if (opts::FileHeaders)
304     Dumper->printFileHeaders();
305   if (opts::Sections)
306     Dumper->printSections();
307   if (opts::Relocations)
308     Dumper->printRelocations();
309   if (opts::DynRelocs)
310     Dumper->printDynamicRelocations();
311   if (opts::Symbols)
312     Dumper->printSymbols();
313   if (opts::DynamicSymbols)
314     Dumper->printDynamicSymbols();
315   if (opts::UnwindInfo)
316     Dumper->printUnwindInfo();
317   if (opts::DynamicTable)
318     Dumper->printDynamicTable();
319   if (opts::NeededLibraries)
320     Dumper->printNeededLibraries();
321   if (opts::ProgramHeaders)
322     Dumper->printProgramHeaders();
323   if (opts::HashTable)
324     Dumper->printHashTable();
325   if (Obj->getArch() == llvm::Triple::arm && Obj->isELF())
326     if (opts::ARMAttributes)
327       Dumper->printAttributes();
328   if (isMipsArch(Obj->getArch()) && Obj->isELF()) {
329     if (opts::MipsPLTGOT)
330       Dumper->printMipsPLTGOT();
331     if (opts::MipsABIFlags)
332       Dumper->printMipsABIFlags();
333     if (opts::MipsReginfo)
334       Dumper->printMipsReginfo();
335   }
336   if (Obj->isCOFF()) {
337     if (opts::COFFImports)
338       Dumper->printCOFFImports();
339     if (opts::COFFExports)
340       Dumper->printCOFFExports();
341     if (opts::COFFDirectives)
342       Dumper->printCOFFDirectives();
343     if (opts::COFFBaseRelocs)
344       Dumper->printCOFFBaseReloc();
345   }
346   if (Obj->isMachO()) {
347     if (opts::MachODataInCode)
348       Dumper->printMachODataInCode();
349     if (opts::MachOIndirectSymbols)
350       Dumper->printMachOIndirectSymbols();
351     if (opts::MachOLinkerOptions)
352       Dumper->printMachOLinkerOptions();
353     if (opts::MachOSegment)
354       Dumper->printMachOSegment();
355     if (opts::MachOVersionMin)
356       Dumper->printMachOVersionMin();
357     if (opts::MachODysymtab)
358       Dumper->printMachODysymtab();
359   }
360   if (opts::PrintStackMap)
361     Dumper->printStackMap();
362 }
363
364 /// @brief Dumps each object file in \a Arc;
365 static void dumpArchive(const Archive *Arc) {
366   for (const auto &Child : Arc->children()) {
367     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = Child.getAsBinary();
368     if (std::error_code EC = ChildOrErr.getError()) {
369       // Ignore non-object files.
370       if (EC != object_error::invalid_file_type)
371         reportError(Arc->getFileName(), EC.message());
372       continue;
373     }
374
375     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
376       dumpObject(Obj);
377     else
378       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
379   }
380 }
381
382 /// @brief Dumps each object file in \a MachO Universal Binary;
383 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
384   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
385     ErrorOr<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
386     if (ObjOrErr)
387       dumpObject(&*ObjOrErr.get());
388     else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
389       dumpArchive(&*AOrErr.get());
390     else
391       reportError(UBinary->getFileName(), ObjOrErr.getError().message());
392   }
393 }
394
395 /// @brief Opens \a File and dumps it.
396 static void dumpInput(StringRef File) {
397
398   // Attempt to open the binary.
399   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
400   if (std::error_code EC = BinaryOrErr.getError()) {
401     reportError(File, EC);
402     return;
403   }
404   Binary &Binary = *BinaryOrErr.get().getBinary();
405
406   if (Archive *Arc = dyn_cast<Archive>(&Binary))
407     dumpArchive(Arc);
408   else if (MachOUniversalBinary *UBinary =
409                dyn_cast<MachOUniversalBinary>(&Binary))
410     dumpMachOUniversalBinary(UBinary);
411   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
412     dumpObject(Obj);
413   else if (COFFImportFile *Import = dyn_cast<COFFImportFile>(&Binary))
414     dumpCOFFImportFile(Import);
415   else
416     reportError(File, readobj_error::unrecognized_file_format);
417 }
418
419 int main(int argc, const char *argv[]) {
420   sys::PrintStackTraceOnErrorSignal();
421   PrettyStackTraceProgram X(argc, argv);
422   llvm_shutdown_obj Y;
423
424   // Register the target printer for --version.
425   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
426
427   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
428
429   // Default to stdin if no filename is specified.
430   if (opts::InputFilenames.size() == 0)
431     opts::InputFilenames.push_back("-");
432
433   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
434                 dumpInput);
435
436   return 0;
437 }