llvm-vtabledump: A vtable dumper
[oota-llvm.git] / tools / llvm-vtabledump / llvm-vtabledump.cpp
1 //===- llvm-vtabledump.cpp - Dump vtables in an Object File -----*- C++ -*-===//
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 // Dumps VTables resident in object files and archives.  Note, it currently only
11 // supports MS-ABI style object files.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "llvm-vtabledump.h"
16 #include "Error.h"
17 #include "llvm/ADT/ArrayRef.h"
18 #include "llvm/ADT/StringMap.h"
19 #include "llvm/Object/Archive.h"
20 #include "llvm/Object/ObjectFile.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/Endian.h"
23 #include "llvm/Support/FileSystem.h"
24 #include "llvm/Support/ManagedStatic.h"
25 #include "llvm/Support/PrettyStackTrace.h"
26 #include "llvm/Support/Signals.h"
27 #include "llvm/Support/TargetRegistry.h"
28 #include "llvm/Support/TargetSelect.h"
29 #include <map>
30 #include <string>
31 #include <system_error>
32
33 using namespace llvm;
34 using namespace llvm::object;
35 using namespace llvm::support;
36
37 namespace opts {
38 cl::list<std::string> InputFilenames(cl::Positional,
39                                      cl::desc("<input object files>"),
40                                      cl::ZeroOrMore);
41 } // namespace opts
42
43 static int ReturnValue = EXIT_SUCCESS;
44
45 namespace llvm {
46
47 bool error(std::error_code EC) {
48   if (!EC)
49     return false;
50
51   ReturnValue = EXIT_FAILURE;
52   outs() << "\nError reading file: " << EC.message() << ".\n";
53   outs().flush();
54   return true;
55 }
56
57 } // namespace llvm
58
59 static void reportError(StringRef Input, StringRef Message) {
60   if (Input == "-")
61     Input = "<stdin>";
62
63   errs() << Input << ": " << Message << "\n";
64   errs().flush();
65   ReturnValue = EXIT_FAILURE;
66 }
67
68 static void reportError(StringRef Input, std::error_code EC) {
69   reportError(Input, EC.message());
70 }
71
72 static void dumpVTables(const ObjectFile *Obj) {
73   std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
74   StringMap<ArrayRef<aligned_little32_t>> VBTables;
75   for (const object::SymbolRef &Sym : Obj->symbols()) {
76     StringRef SymName;
77     if (error(Sym.getName(SymName)))
78       return;
79     // VFTables in the MS-ABI start with '??_7' and are contained within their
80     // own COMDAT section.  We then determine the contents of the VFTable by
81     // looking at each relocation in the section.
82     if (SymName.startswith("??_7")) {
83       object::section_iterator SecI(Obj->section_begin());
84       if (error(Sym.getSection(SecI)))
85         return;
86       if (SecI == Obj->section_end())
87         continue;
88       // Each relocation either names a virtual method or a thunk.  We note the
89       // offset into the section and the symbol used for the relocation.
90       for (const object::RelocationRef &Reloc : SecI->relocations()) {
91         const object::symbol_iterator RelocSymI = Reloc.getSymbol();
92         if (RelocSymI == Obj->symbol_end())
93           continue;
94         StringRef RelocSymName;
95         if (error(RelocSymI->getName(RelocSymName)))
96           return;
97         uint64_t Offset;
98         if (error(Reloc.getOffset(Offset)))
99           return;
100         VFTableEntries[std::make_pair(SymName, Offset)] = RelocSymName;
101       }
102     }
103     // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
104     // offsets of virtual bases.
105     else if (SymName.startswith("??_8")) {
106       object::section_iterator SecI(Obj->section_begin());
107       if (error(Sym.getSection(SecI)))
108         return;
109       if (SecI == Obj->section_end())
110         continue;
111       StringRef SecContents;
112       if (error(SecI->getContents(SecContents)))
113         return;
114
115       ArrayRef<aligned_little32_t> VBTableData(
116           reinterpret_cast<const aligned_little32_t *>(SecContents.data()),
117           SecContents.size() / sizeof(aligned_little32_t));
118       VBTables[SymName] = VBTableData;
119     }
120   }
121   for (
122       const std::pair<std::pair<StringRef, uint64_t>, StringRef> &VFTableEntry :
123       VFTableEntries) {
124     StringRef VFTableName = VFTableEntry.first.first;
125     uint64_t Offset = VFTableEntry.first.second;
126     StringRef SymName = VFTableEntry.second;
127     outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
128   }
129   for (const StringMapEntry<ArrayRef<aligned_little32_t>> &VBTable : VBTables) {
130     StringRef VBTableName = VBTable.getKey();
131     uint32_t Idx = 0;
132     for (aligned_little32_t Offset : VBTable.getValue()) {
133       outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
134       Idx += sizeof(aligned_little32_t);
135     }
136   }
137 }
138
139 static void dumpArchive(const Archive *Arc) {
140   for (Archive::child_iterator ArcI = Arc->child_begin(),
141                                ArcE = Arc->child_end();
142        ArcI != ArcE; ++ArcI) {
143     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcI->getAsBinary();
144     if (std::error_code EC = ChildOrErr.getError()) {
145       // Ignore non-object files.
146       if (EC != object_error::invalid_file_type)
147         reportError(Arc->getFileName(), EC.message());
148       continue;
149     }
150
151     if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
152       dumpVTables(Obj);
153     else
154       reportError(Arc->getFileName(),
155                   vtabledump_error::unrecognized_file_format);
156   }
157 }
158
159 static void dumpInput(StringRef File) {
160   // If file isn't stdin, check that it exists.
161   if (File != "-" && !sys::fs::exists(File)) {
162     reportError(File, vtabledump_error::file_not_found);
163     return;
164   }
165
166   // Attempt to open the binary.
167   ErrorOr<Binary *> BinaryOrErr = createBinary(File);
168   if (std::error_code EC = BinaryOrErr.getError()) {
169     reportError(File, EC);
170     return;
171   }
172   std::unique_ptr<Binary> Binary(BinaryOrErr.get());
173
174   if (Archive *Arc = dyn_cast<Archive>(Binary.get()))
175     dumpArchive(Arc);
176   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(Binary.get()))
177     dumpVTables(Obj);
178   else
179     reportError(File, vtabledump_error::unrecognized_file_format);
180 }
181
182 int main(int argc, const char *argv[]) {
183   sys::PrintStackTraceOnErrorSignal();
184   PrettyStackTraceProgram X(argc, argv);
185   llvm_shutdown_obj Y;
186
187   // Initialize targets.
188   llvm::InitializeAllTargetInfos();
189
190   // Register the target printer for --version.
191   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
192
193   cl::ParseCommandLineOptions(argc, argv, "LLVM VTable Dumper\n");
194
195   // Default to stdin if no filename is specified.
196   if (opts::InputFilenames.size() == 0)
197     opts::InputFilenames.push_back("-");
198
199   std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
200                 dumpInput);
201
202   return ReturnValue;
203 }