ea37d105dc6ea11c02ea00bb9b8fb078e225ef4d
[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 "llvm/ADT/Triple.h"
25 #include "llvm/Analysis/Verifier.h"
26 #include "llvm/Object/ELF.h"
27 #include "llvm/Object/ObjectFile.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/Format.h"
31 #include "llvm/Support/FormattedStream.h"
32 #include "llvm/Support/PrettyStackTrace.h"
33 #include "llvm/Support/Signals.h"
34
35 using namespace llvm;
36 using namespace llvm::object;
37
38 static cl::opt<std::string>
39 InputFilename(cl::Positional, cl::desc("<input object>"), cl::init(""));
40
41 static void dumpSymbolHeader() {
42   outs() << format("  %-32s", (const char *)"Name")
43          << format("  %-4s", (const char *)"Type")
44          << format("  %-4s", (const char *)"Section")
45          << format("  %-16s", (const char *)"Address")
46          << format("  %-16s", (const char *)"Size")
47          << format("  %-16s", (const char *)"FileOffset")
48          << format("  %-26s", (const char *)"Flags") << "\n";
49 }
50
51 static void dumpSectionHeader() {
52   outs() << format("  %-24s", (const char*)"Name")
53          << format("  %-16s", (const char*)"Address")
54          << format("  %-16s", (const char*)"Size")
55          << format("  %-8s", (const char*)"Align")
56          << format("  %-26s", (const char*)"Flags")
57          << "\n";
58 }
59
60 static const char *getTypeStr(SymbolRef::Type Type) {
61   switch (Type) {
62   case SymbolRef::ST_Unknown: return "?";
63   case SymbolRef::ST_Data: return "DATA";
64   case SymbolRef::ST_Debug: return "DBG";
65   case SymbolRef::ST_File: return "FILE";
66   case SymbolRef::ST_Function: return "FUNC";
67   case SymbolRef::ST_Other: return "-";
68   }
69   return "INV";
70 }
71
72 static std::string getSymbolFlagStr(uint32_t Flags) {
73   std::string result;
74   if (Flags & SymbolRef::SF_Undefined)
75     result += "undef,";
76   if (Flags & SymbolRef::SF_Global)
77     result += "global,";
78   if (Flags & SymbolRef::SF_Weak)
79     result += "weak,";
80   if (Flags & SymbolRef::SF_Absolute)
81     result += "absolute,";
82   if (Flags & SymbolRef::SF_ThreadLocal)
83     result += "threadlocal,";
84   if (Flags & SymbolRef::SF_Common)
85     result += "common,";
86   if (Flags & SymbolRef::SF_FormatSpecific)
87     result += "formatspecific,";
88
89   // Remove trailing comma
90   if (result.size() > 0) {
91     result.erase(result.size() - 1);
92   }
93   return result;
94 }
95
96 static void checkError(error_code ec, const char *msg) {
97   if (ec)
98     report_fatal_error(std::string(msg) + ": " + ec.message());
99 }
100
101 static std::string getSectionFlagStr(const SectionRef &Section) {
102   const struct {
103     error_code (SectionRef::*MemF)(bool &) const;
104     const char *FlagStr, *ErrorStr;
105   } Work[] =
106       {{ &SectionRef::isText, "text,", "Section.isText() failed" },
107        { &SectionRef::isData, "data,", "Section.isData() failed" },
108        { &SectionRef::isBSS, "bss,", "Section.isBSS() failed"  },
109        { &SectionRef::isRequiredForExecution, "required,",
110          "Section.isRequiredForExecution() failed" },
111        { &SectionRef::isVirtual, "virtual,", "Section.isVirtual() failed" },
112        { &SectionRef::isZeroInit, "zeroinit,", "Section.isZeroInit() failed" },
113        { &SectionRef::isReadOnlyData, "rodata,",
114          "Section.isReadOnlyData() failed" }};
115
116   std::string result;
117   for (uint32_t I = 0; I < sizeof(Work)/sizeof(*Work); ++I) {
118     bool B;
119     checkError((Section.*Work[I].MemF)(B), Work[I].ErrorStr);
120     if (B)
121       result += Work[I].FlagStr;
122   }
123
124   // Remove trailing comma
125   if (result.size() > 0) {
126     result.erase(result.size() - 1);
127   }
128   return result;
129 }
130
131 static void
132 dumpSymbol(const SymbolRef &Sym, const ObjectFile *obj, bool IsDynamic) {
133   StringRef Name;
134   SymbolRef::Type Type;
135   uint32_t Flags;
136   uint64_t Address;
137   uint64_t Size;
138   uint64_t FileOffset;
139   checkError(Sym.getName(Name), "SymbolRef.getName() failed");
140   checkError(Sym.getAddress(Address), "SymbolRef.getAddress() failed");
141   checkError(Sym.getSize(Size), "SymbolRef.getSize() failed");
142   checkError(Sym.getFileOffset(FileOffset),
143              "SymbolRef.getFileOffset() failed");
144   checkError(Sym.getType(Type), "SymbolRef.getType() failed");
145   checkError(Sym.getFlags(Flags), "SymbolRef.getFlags() failed");
146   std::string FullName = Name;
147
148   llvm::object::section_iterator symSection(obj->begin_sections());
149   Sym.getSection(symSection);
150   StringRef sectionName;
151
152   if (symSection != obj->end_sections())
153     checkError(symSection->getName(sectionName),
154                "SectionRef::getName() failed");
155
156   // If this is a dynamic symbol from an ELF object, append
157   // the symbol's version to the name.
158   if (IsDynamic && obj->isELF()) {
159     StringRef Version;
160     bool IsDefault;
161     GetELFSymbolVersion(obj, Sym, Version, IsDefault);
162     if (!Version.empty()) {
163       FullName += (IsDefault ? "@@" : "@");
164       FullName += Version;
165     }
166   }
167
168   // format() can't handle StringRefs
169   outs() << format("  %-32s", FullName.c_str())
170          << format("  %-4s", getTypeStr(Type))
171          << format("  %-32s", std::string(sectionName).c_str())
172          << format("  %16" PRIx64, Address) << format("  %16" PRIx64, Size)
173          << format("  %16" PRIx64, FileOffset) << "  "
174          << getSymbolFlagStr(Flags) << "\n";
175 }
176
177 static void dumpStaticSymbol(const SymbolRef &Sym, const ObjectFile *obj) {
178   return dumpSymbol(Sym, obj, false);
179 }
180
181 static void dumpDynamicSymbol(const SymbolRef &Sym, const ObjectFile *obj) {
182   return dumpSymbol(Sym, obj, true);
183 }
184
185 static void dumpSection(const SectionRef &Section, const ObjectFile *obj) {
186   StringRef Name;
187   checkError(Section.getName(Name), "SectionRef::getName() failed");
188   uint64_t Addr, Size, Align;
189   checkError(Section.getAddress(Addr), "SectionRef::getAddress() failed");
190   checkError(Section.getSize(Size), "SectionRef::getSize() failed");
191   checkError(Section.getAlignment(Align), "SectionRef::getAlignment() failed");
192   outs() << format("  %-24s", std::string(Name).c_str())
193          << format("  %16" PRIx64, Addr)
194          << format("  %16" PRIx64, Size)
195          << format("  %8" PRIx64, Align)
196          << "  " << getSectionFlagStr(Section)
197          << "\n";
198 }
199
200 static void dumpLibrary(const LibraryRef &lib, const ObjectFile *obj) {
201   StringRef path;
202   lib.getPath(path);
203   outs() << "  " << path << "\n";
204 }
205
206 template<typename Iterator, typename Func>
207 static void dump(const ObjectFile *obj, Func f, Iterator begin, Iterator end,
208                  const char *errStr) {
209   error_code ec;
210   uint32_t count = 0;
211   Iterator it = begin, ie = end;
212   while (it != ie) {
213     f(*it, obj);
214     it.increment(ec);
215     if (ec)
216       report_fatal_error(errStr);
217     ++count;
218   }
219   outs() << "  Total: " << count << "\n\n";
220 }
221
222 static void dumpHeaders(const ObjectFile *obj) {
223   outs() << "File Format : " << obj->getFileFormatName() << "\n";
224   outs() << "Arch        : "
225          << Triple::getArchTypeName((llvm::Triple::ArchType)obj->getArch())
226          << "\n";
227   outs() << "Address Size: " << (8*obj->getBytesInAddress()) << " bits\n";
228   outs() << "Load Name   : " << obj->getLoadName() << "\n";
229   outs() << "\n";
230 }
231
232 int main(int argc, char** argv) {
233   error_code ec;
234   sys::PrintStackTraceOnErrorSignal();
235   PrettyStackTraceProgram X(argc, argv);
236
237   cl::ParseCommandLineOptions(argc, argv,
238                               "LLVM Object Reader\n");
239
240   if (InputFilename.empty()) {
241     errs() << "Please specify an input filename\n";
242     return 1;
243   }
244
245   // Open the object file
246   OwningPtr<MemoryBuffer> File;
247   if (MemoryBuffer::getFile(InputFilename, File)) {
248     errs() << InputFilename << ": Open failed\n";
249     return 1;
250   }
251
252   OwningPtr<ObjectFile> o(ObjectFile::createObjectFile(File.take()));
253   ObjectFile *obj = o.get();
254   if (!obj) {
255     errs() << InputFilename << ": Object type not recognized\n";
256   }
257
258   dumpHeaders(obj);
259
260   outs() << "Symbols:\n";
261   dumpSymbolHeader();
262   dump(obj, dumpStaticSymbol, obj->begin_symbols(), obj->end_symbols(),
263        "Symbol iteration failed");
264
265   outs() << "Dynamic Symbols:\n";
266   dumpSymbolHeader();
267   dump(obj, dumpDynamicSymbol, obj->begin_dynamic_symbols(),
268        obj->end_dynamic_symbols(), "Symbol iteration failed");
269
270   outs() << "Sections:\n";
271   dumpSectionHeader();
272   dump(obj, &dumpSection, obj->begin_sections(), obj->end_sections(),
273        "Section iteration failed");
274
275   if (obj->isELF()) {
276     if (ErrorOr<void> e = dumpELFDynamicTable(obj, outs()))
277       ;
278     else
279       errs() << "InputFilename" << ": " << error_code(e).message() << "\n";
280   }
281
282   outs() << "Libraries needed:\n";
283   dump(obj, &dumpLibrary, obj->begin_libraries_needed(),
284        obj->end_libraries_needed(), "Needed libraries iteration failed");
285
286   return 0;
287 }
288