Don't own the buffer in object::Binary.
[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/Object/Archive.h"
19 #include "llvm/Object/ObjectFile.h"
20 #include "llvm/Support/Debug.h"
21 #include "llvm/Support/Endian.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/ManagedStatic.h"
24 #include "llvm/Support/PrettyStackTrace.h"
25 #include "llvm/Support/Signals.h"
26 #include "llvm/Support/TargetRegistry.h"
27 #include "llvm/Support/TargetSelect.h"
28 #include <map>
29 #include <string>
30 #include <system_error>
31
32 using namespace llvm;
33 using namespace llvm::object;
34 using namespace llvm::support;
35
36 namespace opts {
37 cl::list<std::string> InputFilenames(cl::Positional,
38                                      cl::desc("<input object files>"),
39                                      cl::ZeroOrMore);
40 } // namespace opts
41
42 static int ReturnValue = EXIT_SUCCESS;
43
44 namespace llvm {
45
46 bool error(std::error_code EC) {
47   if (!EC)
48     return false;
49
50   ReturnValue = EXIT_FAILURE;
51   outs() << "\nError reading file: " << EC.message() << ".\n";
52   outs().flush();
53   return true;
54 }
55
56 } // namespace llvm
57
58 static void reportError(StringRef Input, StringRef Message) {
59   if (Input == "-")
60     Input = "<stdin>";
61
62   errs() << Input << ": " << Message << "\n";
63   errs().flush();
64   ReturnValue = EXIT_FAILURE;
65 }
66
67 static void reportError(StringRef Input, std::error_code EC) {
68   reportError(Input, EC.message());
69 }
70
71 static void dumpVTables(const ObjectFile *Obj) {
72   std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
73   std::map<StringRef, ArrayRef<aligned_little32_t>> VBTables;
74   for (const object::SymbolRef &Sym : Obj->symbols()) {
75     StringRef SymName;
76     if (error(Sym.getName(SymName)))
77       return;
78     // VFTables in the MS-ABI start with '??_7' and are contained within their
79     // own COMDAT section.  We then determine the contents of the VFTable by
80     // looking at each relocation in the section.
81     if (SymName.startswith("??_7")) {
82       object::section_iterator SecI(Obj->section_begin());
83       if (error(Sym.getSection(SecI)))
84         return;
85       if (SecI == Obj->section_end())
86         continue;
87       // Each relocation either names a virtual method or a thunk.  We note the
88       // offset into the section and the symbol used for the relocation.
89       for (const object::RelocationRef &Reloc : SecI->relocations()) {
90         const object::symbol_iterator RelocSymI = Reloc.getSymbol();
91         if (RelocSymI == Obj->symbol_end())
92           continue;
93         StringRef RelocSymName;
94         if (error(RelocSymI->getName(RelocSymName)))
95           return;
96         uint64_t Offset;
97         if (error(Reloc.getOffset(Offset)))
98           return;
99         VFTableEntries[std::make_pair(SymName, Offset)] = RelocSymName;
100       }
101     }
102     // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
103     // offsets of virtual bases.
104     else if (SymName.startswith("??_8")) {
105       object::section_iterator SecI(Obj->section_begin());
106       if (error(Sym.getSection(SecI)))
107         return;
108       if (SecI == Obj->section_end())
109         continue;
110       StringRef SecContents;
111       if (error(SecI->getContents(SecContents)))
112         return;
113
114       ArrayRef<aligned_little32_t> VBTableData(
115           reinterpret_cast<const aligned_little32_t *>(SecContents.data()),
116           SecContents.size() / sizeof(aligned_little32_t));
117       VBTables[SymName] = VBTableData;
118     }
119   }
120   for (
121       const std::pair<std::pair<StringRef, uint64_t>, StringRef> &VFTableEntry :
122       VFTableEntries) {
123     StringRef VFTableName = VFTableEntry.first.first;
124     uint64_t Offset = VFTableEntry.first.second;
125     StringRef SymName = VFTableEntry.second;
126     outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
127   }
128   for (const std::pair<StringRef, ArrayRef<aligned_little32_t>> &VBTable :
129        VBTables) {
130     StringRef VBTableName = VBTable.first;
131     uint32_t Idx = 0;
132     for (aligned_little32_t Offset : VBTable.second) {
133       outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
134       Idx += sizeof(Offset);
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<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
168   if (std::error_code EC = BinaryOrErr.getError()) {
169     reportError(File, EC);
170     return;
171   }
172   Binary &Binary = *BinaryOrErr.get().getBinary();
173
174   if (Archive *Arc = dyn_cast<Archive>(&Binary))
175     dumpArchive(Arc);
176   else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
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 }