[llvm-readobj] Print MIPS .reginfo section content
[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
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   // -symbols, -t
95   cl::opt<bool> Symbols("symbols",
96     cl::desc("Display the symbol table"));
97   cl::alias SymbolsShort("t",
98     cl::desc("Alias for --symbols"),
99     cl::aliasopt(Symbols));
100
101   // -dyn-symbols, -dt
102   cl::opt<bool> DynamicSymbols("dyn-symbols",
103     cl::desc("Display the dynamic symbol table"));
104   cl::alias DynamicSymbolsShort("dt",
105     cl::desc("Alias for --dyn-symbols"),
106     cl::aliasopt(DynamicSymbols));
107
108   // -unwind, -u
109   cl::opt<bool> UnwindInfo("unwind",
110     cl::desc("Display unwind information"));
111   cl::alias UnwindInfoShort("u",
112     cl::desc("Alias for --unwind"),
113     cl::aliasopt(UnwindInfo));
114
115   // -dynamic-table
116   cl::opt<bool> DynamicTable("dynamic-table",
117     cl::desc("Display the ELF .dynamic section table"));
118
119   // -needed-libs
120   cl::opt<bool> NeededLibraries("needed-libs",
121     cl::desc("Display the needed libraries"));
122
123   // -program-headers
124   cl::opt<bool> ProgramHeaders("program-headers",
125     cl::desc("Display ELF program headers"));
126
127   // -expand-relocs
128   cl::opt<bool> ExpandRelocs("expand-relocs",
129     cl::desc("Expand each shown relocation to multiple lines"));
130
131   // -codeview
132   cl::opt<bool> CodeView("codeview",
133                          cl::desc("Display CodeView debug information"));
134
135   // -codeview-subsection-bytes
136   cl::opt<bool> CodeViewSubsectionBytes(
137       "codeview-subsection-bytes",
138       cl::desc("Dump raw contents of codeview debug sections and records"));
139
140   // -arm-attributes, -a
141   cl::opt<bool> ARMAttributes("arm-attributes",
142                               cl::desc("Display the ARM attributes section"));
143   cl::alias ARMAttributesShort("-a", cl::desc("Alias for --arm-attributes"),
144                                cl::aliasopt(ARMAttributes));
145
146   // -mips-plt-got
147   cl::opt<bool>
148   MipsPLTGOT("mips-plt-got",
149              cl::desc("Display the MIPS GOT and PLT GOT sections"));
150
151   // -mips-abi-flags
152   cl::opt<bool> MipsABIFlags("mips-abi-flags",
153                              cl::desc("Display the MIPS.abiflags section"));
154
155   // -mips-reginfo
156   cl::opt<bool> MipsReginfo("mips-reginfo",
157                             cl::desc("Display the MIPS .reginfo section"));
158
159   // -coff-imports
160   cl::opt<bool>
161   COFFImports("coff-imports", cl::desc("Display the PE/COFF import table"));
162
163   // -coff-exports
164   cl::opt<bool>
165   COFFExports("coff-exports", cl::desc("Display the PE/COFF export table"));
166
167   // -coff-directives
168   cl::opt<bool>
169   COFFDirectives("coff-directives",
170                  cl::desc("Display the PE/COFF .drectve section"));
171
172   // -coff-basereloc
173   cl::opt<bool>
174   COFFBaseRelocs("coff-basereloc",
175                  cl::desc("Display the PE/COFF .reloc section"));
176 } // namespace opts
177
178 static int ReturnValue = EXIT_SUCCESS;
179
180 namespace llvm {
181
182 bool error(std::error_code EC) {
183   if (!EC)
184     return false;
185
186   ReturnValue = EXIT_FAILURE;
187   outs() << "\nError reading file: " << EC.message() << ".\n";
188   outs().flush();
189   return true;
190 }
191
192 bool relocAddressLess(RelocationRef a, RelocationRef b) {
193   uint64_t a_addr, b_addr;
194   if (error(a.getOffset(a_addr))) exit(ReturnValue);
195   if (error(b.getOffset(b_addr))) exit(ReturnValue);
196   return a_addr < b_addr;
197 }
198
199 } // namespace llvm
200
201 static void reportError(StringRef Input, std::error_code EC) {
202   if (Input == "-")
203     Input = "<stdin>";
204
205   errs() << Input << ": " << EC.message() << "\n";
206   errs().flush();
207   ReturnValue = EXIT_FAILURE;
208 }
209
210 static void reportError(StringRef Input, StringRef Message) {
211   if (Input == "-")
212     Input = "<stdin>";
213
214   errs() << Input << ": " << Message << "\n";
215   ReturnValue = EXIT_FAILURE;
216 }
217
218 static bool isMipsArch(unsigned Arch) {
219   switch (Arch) {
220   case llvm::Triple::mips:
221   case llvm::Triple::mipsel:
222   case llvm::Triple::mips64:
223   case llvm::Triple::mips64el:
224     return true;
225   default:
226     return false;
227   }
228 }
229
230 /// @brief Creates an format-specific object file dumper.
231 static std::error_code createDumper(const ObjectFile *Obj, StreamWriter &Writer,
232                                     std::unique_ptr<ObjDumper> &Result) {
233   if (!Obj)
234     return readobj_error::unsupported_file_format;
235
236   if (Obj->isCOFF())
237     return createCOFFDumper(Obj, Writer, Result);
238   if (Obj->isELF())
239     return createELFDumper(Obj, Writer, Result);
240   if (Obj->isMachO())
241     return createMachODumper(Obj, Writer, Result);
242
243   return readobj_error::unsupported_obj_file_format;
244 }
245
246 static StringRef getLoadName(const ObjectFile *Obj) {
247   if (auto *ELF = dyn_cast<ELF32LEObjectFile>(Obj))
248     return ELF->getLoadName();
249   if (auto *ELF = dyn_cast<ELF64LEObjectFile>(Obj))
250     return ELF->getLoadName();
251   if (auto *ELF = dyn_cast<ELF32BEObjectFile>(Obj))
252     return ELF->getLoadName();
253   if (auto *ELF = dyn_cast<ELF64BEObjectFile>(Obj))
254     return ELF->getLoadName();
255   llvm_unreachable("Not ELF");
256 }
257
258 /// @brief Dumps the specified object file.
259 static void dumpObject(const ObjectFile *Obj) {
260   StreamWriter Writer(outs());
261   std::unique_ptr<ObjDumper> Dumper;
262   if (std::error_code EC = createDumper(Obj, Writer, Dumper)) {
263     reportError(Obj->getFileName(), EC);
264     return;
265   }
266
267   outs() << '\n';
268   outs() << "File: " << Obj->getFileName() << "\n";
269   outs() << "Format: " << Obj->getFileFormatName() << "\n";
270   outs() << "Arch: "
271          << Triple::getArchTypeName((llvm::Triple::ArchType)Obj->getArch())
272          << "\n";
273   outs() << "AddressSize: " << (8*Obj->getBytesInAddress()) << "bit\n";
274   if (Obj->isELF())
275     outs() << "LoadName: " << getLoadName(Obj) << "\n";
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::Symbols)
284     Dumper->printSymbols();
285   if (opts::DynamicSymbols)
286     Dumper->printDynamicSymbols();
287   if (opts::UnwindInfo)
288     Dumper->printUnwindInfo();
289   if (opts::DynamicTable)
290     Dumper->printDynamicTable();
291   if (opts::NeededLibraries)
292     Dumper->printNeededLibraries();
293   if (opts::ProgramHeaders)
294     Dumper->printProgramHeaders();
295   if (Obj->getArch() == llvm::Triple::arm && Obj->isELF())
296     if (opts::ARMAttributes)
297       Dumper->printAttributes();
298   if (isMipsArch(Obj->getArch()) && Obj->isELF()) {
299     if (opts::MipsPLTGOT)
300       Dumper->printMipsPLTGOT();
301     if (opts::MipsABIFlags)
302       Dumper->printMipsABIFlags();
303     if (opts::MipsReginfo)
304       Dumper->printMipsReginfo();
305   }
306   if (opts::COFFImports)
307     Dumper->printCOFFImports();
308   if (opts::COFFExports)
309     Dumper->printCOFFExports();
310   if (opts::COFFDirectives)
311     Dumper->printCOFFDirectives();
312   if (opts::COFFBaseRelocs)
313     Dumper->printCOFFBaseReloc();
314 }
315
316
317 /// @brief Dumps each object file in \a Arc;
318 static void dumpArchive(const Archive *Arc) {
319   for (Archive::child_iterator ArcI = Arc->child_begin(),
320                                ArcE = Arc->child_end();
321                                ArcI != ArcE; ++ArcI) {
322     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcI->getAsBinary();
323     if (std::error_code EC = ChildOrErr.getError()) {
324       // Ignore non-object files.
325       if (EC != object_error::invalid_file_type)
326         reportError(Arc->getFileName(), EC.message());
327       continue;
328     }
329
330     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
331       dumpObject(Obj);
332     else
333       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
334   }
335 }
336
337 /// @brief Dumps each object file in \a MachO Universal Binary;
338 static void dumpMachOUniversalBinary(const MachOUniversalBinary *UBinary) {
339   for (const MachOUniversalBinary::ObjectForArch &Obj : UBinary->objects()) {
340     ErrorOr<std::unique_ptr<MachOObjectFile>> ObjOrErr = Obj.getAsObjectFile();
341     if (ObjOrErr)
342       dumpObject(&*ObjOrErr.get());
343     else if (ErrorOr<std::unique_ptr<Archive>> AOrErr = Obj.getAsArchive())
344       dumpArchive(&*AOrErr.get());
345     else
346       reportError(UBinary->getFileName(), ObjOrErr.getError().message());
347   }
348 }
349
350 /// @brief Opens \a File and dumps it.
351 static void dumpInput(StringRef File) {
352   // If file isn't stdin, check that it exists.
353   if (File != "-" && !sys::fs::exists(File)) {
354     reportError(File, readobj_error::file_not_found);
355     return;
356   }
357
358   // Attempt to open the binary.
359   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
360   if (std::error_code EC = BinaryOrErr.getError()) {
361     reportError(File, EC);
362     return;
363   }
364   Binary &Binary = *BinaryOrErr.get().getBinary();
365
366   if (Archive *Arc = dyn_cast<Archive>(&Binary))
367     dumpArchive(Arc);
368   else if (MachOUniversalBinary *UBinary =
369                dyn_cast<MachOUniversalBinary>(&Binary))
370     dumpMachOUniversalBinary(UBinary);
371   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
372     dumpObject(Obj);
373   else
374     reportError(File, readobj_error::unrecognized_file_format);
375 }
376
377
378 int main(int argc, const char *argv[]) {
379   sys::PrintStackTraceOnErrorSignal();
380   PrettyStackTraceProgram X(argc, argv);
381   llvm_shutdown_obj Y;
382
383   // Initialize targets.
384   llvm::InitializeAllTargetInfos();
385
386   // Register the target printer for --version.
387   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
388
389   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
390
391   // Default to stdin if no filename is specified.
392   if (opts::InputFilenames.size() == 0)
393     opts::InputFilenames.push_back("-");
394
395   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
396                 dumpInput);
397
398   return ReturnValue;
399 }