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