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