Remove all uses of 'using std::error_code' from headers.
[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/ObjectFile.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/DataTypes.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/TargetRegistry.h"
37 #include "llvm/Support/TargetSelect.h"
38 #include <string>
39 #include <system_error>
40
41
42 using namespace llvm;
43 using namespace llvm::object;
44 using std::error_code;
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   // -symbols, -t
94   cl::opt<bool> Symbols("symbols",
95     cl::desc("Display the symbol table"));
96   cl::alias SymbolsShort("t",
97     cl::desc("Alias for --symbols"),
98     cl::aliasopt(Symbols));
99
100   // -dyn-symbols, -dt
101   cl::opt<bool> DynamicSymbols("dyn-symbols",
102     cl::desc("Display the dynamic symbol table"));
103   cl::alias DynamicSymbolsShort("dt",
104     cl::desc("Alias for --dyn-symbols"),
105     cl::aliasopt(DynamicSymbols));
106
107   // -unwind, -u
108   cl::opt<bool> UnwindInfo("unwind",
109     cl::desc("Display unwind information"));
110   cl::alias UnwindInfoShort("u",
111     cl::desc("Alias for --unwind"),
112     cl::aliasopt(UnwindInfo));
113
114   // -dynamic-table
115   cl::opt<bool> DynamicTable("dynamic-table",
116     cl::desc("Display the ELF .dynamic section table"));
117
118   // -needed-libs
119   cl::opt<bool> NeededLibraries("needed-libs",
120     cl::desc("Display the needed libraries"));
121
122   // -program-headers
123   cl::opt<bool> ProgramHeaders("program-headers",
124     cl::desc("Display ELF program headers"));
125
126   // -expand-relocs
127   cl::opt<bool> ExpandRelocs("expand-relocs",
128     cl::desc("Expand each shown relocation to multiple lines"));
129
130   // -codeview-linetables
131   cl::opt<bool> CodeViewLineTables("codeview-linetables",
132     cl::desc("Display CodeView line table information"));
133
134   // -arm-attributes, -a
135   cl::opt<bool> ARMAttributes("arm-attributes",
136                               cl::desc("Display the ARM attributes section"));
137   cl::alias ARMAttributesShort("-a", cl::desc("Alias for --arm-attributes"),
138                                cl::aliasopt(ARMAttributes));
139 } // namespace opts
140
141 static int ReturnValue = EXIT_SUCCESS;
142
143 namespace llvm {
144
145 bool error(error_code EC) {
146   if (!EC)
147     return false;
148
149   ReturnValue = EXIT_FAILURE;
150   outs() << "\nError reading file: " << EC.message() << ".\n";
151   outs().flush();
152   return true;
153 }
154
155 bool relocAddressLess(RelocationRef a, RelocationRef b) {
156   uint64_t a_addr, b_addr;
157   if (error(a.getOffset(a_addr))) return false;
158   if (error(b.getOffset(b_addr))) return false;
159   return a_addr < b_addr;
160 }
161
162 } // namespace llvm
163
164
165 static void reportError(StringRef Input, error_code EC) {
166   if (Input == "-")
167     Input = "<stdin>";
168
169   errs() << Input << ": " << EC.message() << "\n";
170   errs().flush();
171   ReturnValue = EXIT_FAILURE;
172 }
173
174 static void reportError(StringRef Input, StringRef Message) {
175   if (Input == "-")
176     Input = "<stdin>";
177
178   errs() << Input << ": " << Message << "\n";
179   ReturnValue = EXIT_FAILURE;
180 }
181
182 /// @brief Creates an format-specific object file dumper.
183 static error_code createDumper(const ObjectFile *Obj, StreamWriter &Writer,
184                                std::unique_ptr<ObjDumper> &Result) {
185   if (!Obj)
186     return readobj_error::unsupported_file_format;
187
188   if (Obj->isCOFF())
189     return createCOFFDumper(Obj, Writer, Result);
190   if (Obj->isELF())
191     return createELFDumper(Obj, Writer, Result);
192   if (Obj->isMachO())
193     return createMachODumper(Obj, Writer, Result);
194
195   return readobj_error::unsupported_obj_file_format;
196 }
197
198
199 /// @brief Dumps the specified object file.
200 static void dumpObject(const ObjectFile *Obj) {
201   StreamWriter Writer(outs());
202   std::unique_ptr<ObjDumper> Dumper;
203   if (error_code EC = createDumper(Obj, Writer, Dumper)) {
204     reportError(Obj->getFileName(), EC);
205     return;
206   }
207
208   outs() << '\n';
209   outs() << "File: " << Obj->getFileName() << "\n";
210   outs() << "Format: " << Obj->getFileFormatName() << "\n";
211   outs() << "Arch: "
212          << Triple::getArchTypeName((llvm::Triple::ArchType)Obj->getArch())
213          << "\n";
214   outs() << "AddressSize: " << (8*Obj->getBytesInAddress()) << "bit\n";
215   if (Obj->isELF())
216     outs() << "LoadName: " << Obj->getLoadName() << "\n";
217
218   if (opts::FileHeaders)
219     Dumper->printFileHeaders();
220   if (opts::Sections)
221     Dumper->printSections();
222   if (opts::Relocations)
223     Dumper->printRelocations();
224   if (opts::Symbols)
225     Dumper->printSymbols();
226   if (opts::DynamicSymbols)
227     Dumper->printDynamicSymbols();
228   if (opts::UnwindInfo)
229     Dumper->printUnwindInfo();
230   if (opts::DynamicTable)
231     Dumper->printDynamicTable();
232   if (opts::NeededLibraries)
233     Dumper->printNeededLibraries();
234   if (opts::ProgramHeaders)
235     Dumper->printProgramHeaders();
236   if (Obj->getArch() == llvm::Triple::arm && Obj->isELF())
237     if (opts::ARMAttributes)
238       Dumper->printAttributes();
239 }
240
241
242 /// @brief Dumps each object file in \a Arc;
243 static void dumpArchive(const Archive *Arc) {
244   for (Archive::child_iterator ArcI = Arc->child_begin(),
245                                ArcE = Arc->child_end();
246                                ArcI != ArcE; ++ArcI) {
247     std::unique_ptr<Binary> child;
248     if (error_code EC = ArcI->getAsBinary(child)) {
249       // Ignore non-object files.
250       if (EC != object_error::invalid_file_type)
251         reportError(Arc->getFileName(), EC.message());
252       continue;
253     }
254
255     if (ObjectFile *Obj = dyn_cast<ObjectFile>(child.get()))
256       dumpObject(Obj);
257     else
258       reportError(Arc->getFileName(), readobj_error::unrecognized_file_format);
259   }
260 }
261
262
263 /// @brief Opens \a File and dumps it.
264 static void dumpInput(StringRef File) {
265   // If file isn't stdin, check that it exists.
266   if (File != "-" && !sys::fs::exists(File)) {
267     reportError(File, readobj_error::file_not_found);
268     return;
269   }
270
271   // Attempt to open the binary.
272   ErrorOr<Binary *> BinaryOrErr = createBinary(File);
273   if (error_code EC = BinaryOrErr.getError()) {
274     reportError(File, EC);
275     return;
276   }
277   std::unique_ptr<Binary> Binary(BinaryOrErr.get());
278
279   if (Archive *Arc = dyn_cast<Archive>(Binary.get()))
280     dumpArchive(Arc);
281   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Binary.get()))
282     dumpObject(Obj);
283   else
284     reportError(File, readobj_error::unrecognized_file_format);
285 }
286
287
288 int main(int argc, const char *argv[]) {
289   sys::PrintStackTraceOnErrorSignal();
290   PrettyStackTraceProgram X(argc, argv);
291   llvm_shutdown_obj Y;
292
293   // Initialize targets.
294   llvm::InitializeAllTargetInfos();
295
296   // Register the target printer for --version.
297   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
298
299   cl::ParseCommandLineOptions(argc, argv, "LLVM Object Reader\n");
300
301   // Default to stdin if no filename is specified.
302   if (opts::InputFilenames.size() == 0)
303     opts::InputFilenames.push_back("-");
304
305   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
306                 dumpInput);
307
308   return ReturnValue;
309 }