1 //===- llvm-vtabledump.cpp - Dump vtables in an Object File -----*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Dumps VTables resident in object files and archives. Note, it currently only
11 // supports MS-ABI style object files.
13 //===----------------------------------------------------------------------===//
15 #include "llvm-vtabledump.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"
30 #include <system_error>
33 using namespace llvm::object;
34 using namespace llvm::support;
37 cl::list<std::string> InputFilenames(cl::Positional,
38 cl::desc("<input object files>"),
42 static int ReturnValue = EXIT_SUCCESS;
46 bool error(std::error_code EC) {
50 ReturnValue = EXIT_FAILURE;
51 outs() << "\nError reading file: " << EC.message() << ".\n";
58 static void reportError(StringRef Input, StringRef Message) {
62 errs() << Input << ": " << Message << "\n";
64 ReturnValue = EXIT_FAILURE;
67 static void reportError(StringRef Input, std::error_code EC) {
68 reportError(Input, EC.message());
71 static bool collectRelocatedSymbols(const ObjectFile *Obj,
72 object::section_iterator SecI, StringRef *I,
74 for (const object::RelocationRef &Reloc : SecI->relocations()) {
77 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
78 if (RelocSymI == Obj->symbol_end())
80 StringRef RelocSymName;
81 if (error(RelocSymI->getName(RelocSymName)))
89 static bool collectRelocationOffsets(
90 const ObjectFile *Obj, object::section_iterator SecI, StringRef SymName,
91 std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) {
92 for (const object::RelocationRef &Reloc : SecI->relocations()) {
93 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
94 if (RelocSymI == Obj->symbol_end())
96 StringRef RelocSymName;
97 if (error(RelocSymI->getName(RelocSymName)))
100 if (error(Reloc.getOffset(Offset)))
102 Collection[std::make_pair(SymName, Offset)] = RelocSymName;
107 static void dumpVTables(const ObjectFile *Obj) {
108 struct CompleteObjectLocator {
109 StringRef Symbols[2];
110 ArrayRef<little32_t> Data;
112 struct ClassHierarchyDescriptor {
113 StringRef Symbols[1];
114 ArrayRef<little32_t> Data;
116 struct BaseClassDescriptor {
117 StringRef Symbols[2];
118 ArrayRef<little32_t> Data;
120 struct TypeDescriptor {
121 StringRef Symbols[1];
123 StringRef MangledName;
125 std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
126 std::map<StringRef, ArrayRef<little32_t>> VBTables;
127 std::map<StringRef, CompleteObjectLocator> COLs;
128 std::map<StringRef, ClassHierarchyDescriptor> CHDs;
129 std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries;
130 std::map<StringRef, BaseClassDescriptor> BCDs;
131 std::map<StringRef, TypeDescriptor> TDs;
132 for (const object::SymbolRef &Sym : Obj->symbols()) {
134 if (error(Sym.getName(SymName)))
136 object::section_iterator SecI(Obj->section_begin());
137 if (error(Sym.getSection(SecI)))
139 // Skip external symbols.
140 if (SecI == Obj->section_end())
142 bool IsBSS, IsVirtual;
143 if (error(SecI->isBSS(IsBSS)) || error(SecI->isVirtual(IsVirtual)))
145 // Skip virtual or BSS sections.
146 if (IsBSS || IsVirtual)
148 StringRef SecContents;
149 if (error(SecI->getContents(SecContents)))
151 // VFTables in the MS-ABI start with '??_7' and are contained within their
152 // own COMDAT section. We then determine the contents of the VFTable by
153 // looking at each relocation in the section.
154 if (SymName.startswith("??_7")) {
155 // Each relocation either names a virtual method or a thunk. We note the
156 // offset into the section and the symbol used for the relocation.
157 collectRelocationOffsets(Obj, SecI, SymName, VFTableEntries);
159 // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
160 // offsets of virtual bases.
161 else if (SymName.startswith("??_8")) {
162 ArrayRef<little32_t> VBTableData(
163 reinterpret_cast<const little32_t *>(SecContents.data()),
164 SecContents.size() / sizeof(little32_t));
165 VBTables[SymName] = VBTableData;
167 // Complete object locators in the MS-ABI start with '??_R4'
168 else if (SymName.startswith("??_R4")) {
169 CompleteObjectLocator COL;
170 COL.Data = ArrayRef<little32_t>(
171 reinterpret_cast<const little32_t *>(SecContents.data()), 3);
172 StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols);
173 if (collectRelocatedSymbols(Obj, SecI, I, E))
177 // Class hierarchy descriptors in the MS-ABI start with '??_R3'
178 else if (SymName.startswith("??_R3")) {
179 ClassHierarchyDescriptor CHD;
180 CHD.Data = ArrayRef<little32_t>(
181 reinterpret_cast<const little32_t *>(SecContents.data()), 3);
182 StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols);
183 if (collectRelocatedSymbols(Obj, SecI, I, E))
187 // Class hierarchy descriptors in the MS-ABI start with '??_R2'
188 else if (SymName.startswith("??_R2")) {
189 // Each relocation names a base class descriptor. We note the offset into
190 // the section and the symbol used for the relocation.
191 collectRelocationOffsets(Obj, SecI, SymName, BCAEntries);
193 // Base class descriptors in the MS-ABI start with '??_R1'
194 else if (SymName.startswith("??_R1")) {
195 BaseClassDescriptor BCD;
196 BCD.Data = ArrayRef<little32_t>(
197 reinterpret_cast<const little32_t *>(SecContents.data()) + 1,
199 StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols);
200 if (collectRelocatedSymbols(Obj, SecI, I, E))
204 // Type descriptors in the MS-ABI start with '??_R0'
205 else if (SymName.startswith("??_R0")) {
206 uint8_t BytesInAddress = Obj->getBytesInAddress();
207 const char *DataPtr =
208 SecContents.drop_front(Obj->getBytesInAddress()).data();
210 if (BytesInAddress == 8)
211 TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr);
213 TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr);
214 TD.MangledName = SecContents.drop_front(Obj->getBytesInAddress() * 2);
215 StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols);
216 if (collectRelocatedSymbols(Obj, SecI, I, E))
221 for (const std::pair<std::pair<StringRef, uint64_t>, StringRef> &VFTableEntry :
223 StringRef VFTableName = VFTableEntry.first.first;
224 uint64_t Offset = VFTableEntry.first.second;
225 StringRef SymName = VFTableEntry.second;
226 outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
228 for (const std::pair<StringRef, ArrayRef<little32_t>> &VBTable :
230 StringRef VBTableName = VBTable.first;
232 for (little32_t Offset : VBTable.second) {
233 outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
234 Idx += sizeof(Offset);
237 for (const std::pair<StringRef, CompleteObjectLocator> &COLPair : COLs) {
238 StringRef COLName = COLPair.first;
239 const CompleteObjectLocator &COL = COLPair.second;
240 outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n';
241 outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n';
242 outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n';
243 outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n';
244 outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1] << '\n';
246 for (const std::pair<StringRef, ClassHierarchyDescriptor> &CHDPair : CHDs) {
247 StringRef CHDName = CHDPair.first;
248 const ClassHierarchyDescriptor &CHD = CHDPair.second;
249 outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n';
250 outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n';
251 outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n';
252 outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n';
254 for (const std::pair<std::pair<StringRef, uint64_t>, StringRef> &BCAEntry :
256 StringRef BCAName = BCAEntry.first.first;
257 uint64_t Offset = BCAEntry.first.second;
258 StringRef SymName = BCAEntry.second;
259 outs() << BCAName << '[' << Offset << "]: " << SymName << '\n';
261 for (const std::pair<StringRef, BaseClassDescriptor> &BCDPair : BCDs) {
262 StringRef BCDName = BCDPair.first;
263 const BaseClassDescriptor &BCD = BCDPair.second;
264 outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n';
265 outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n';
266 outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n';
267 outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n';
268 outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n';
269 outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n';
270 outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1] << '\n';
272 for (const std::pair<StringRef, TypeDescriptor> &TDPair : TDs) {
273 StringRef TDName = TDPair.first;
274 const TypeDescriptor &TD = TDPair.second;
275 outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n';
276 outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n';
277 outs() << TDName << "[MangledName]: ";
278 outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)),
279 /*UseHexEscapes=*/true)
284 static void dumpArchive(const Archive *Arc) {
285 for (const Archive::Child &ArcC : Arc->children()) {
286 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary();
287 if (std::error_code EC = ChildOrErr.getError()) {
288 // Ignore non-object files.
289 if (EC != object_error::invalid_file_type)
290 reportError(Arc->getFileName(), EC.message());
294 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
297 reportError(Arc->getFileName(),
298 vtabledump_error::unrecognized_file_format);
302 static void dumpInput(StringRef File) {
303 // If file isn't stdin, check that it exists.
304 if (File != "-" && !sys::fs::exists(File)) {
305 reportError(File, vtabledump_error::file_not_found);
309 // Attempt to open the binary.
310 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
311 if (std::error_code EC = BinaryOrErr.getError()) {
312 reportError(File, EC);
315 Binary &Binary = *BinaryOrErr.get().getBinary();
317 if (Archive *Arc = dyn_cast<Archive>(&Binary))
319 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
322 reportError(File, vtabledump_error::unrecognized_file_format);
325 int main(int argc, const char *argv[]) {
326 sys::PrintStackTraceOnErrorSignal();
327 PrettyStackTraceProgram X(argc, argv);
330 // Initialize targets.
331 llvm::InitializeAllTargetInfos();
333 // Register the target printer for --version.
334 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
336 cl::ParseCommandLineOptions(argc, argv, "LLVM VTable Dumper\n");
338 // Default to stdin if no filename is specified.
339 if (opts::InputFilenames.size() == 0)
340 opts::InputFilenames.push_back("-");
342 std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),