1 //===- llvm-cxxdump.cpp - Dump C++ data 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 C++ data resident in object files and archives.
12 //===----------------------------------------------------------------------===//
14 #include "llvm-cxxdump.h"
16 #include "llvm/ADT/ArrayRef.h"
17 #include "llvm/Object/Archive.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/Object/SymbolSize.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 "llvm/Support/raw_ostream.h"
31 #include <system_error>
34 using namespace llvm::object;
35 using namespace llvm::support;
38 cl::list<std::string> InputFilenames(cl::Positional,
39 cl::desc("<input object files>"),
45 static void error(std::error_code EC) {
48 outs() << "\nError reading file: " << EC.message() << ".\n";
55 static void reportError(StringRef Input, StringRef Message) {
58 errs() << Input << ": " << Message << "\n";
63 static void reportError(StringRef Input, std::error_code EC) {
64 reportError(Input, EC.message());
67 static SmallVectorImpl<SectionRef> &getRelocSections(const ObjectFile *Obj,
68 const SectionRef &Sec) {
69 static bool MappingDone = false;
70 static std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
72 for (const SectionRef &Section : Obj->sections()) {
73 section_iterator Sec2 = Section.getRelocatedSection();
74 if (Sec2 != Obj->section_end())
75 SectionRelocMap[*Sec2].push_back(Section);
79 return SectionRelocMap[Sec];
82 static void collectRelocatedSymbols(const ObjectFile *Obj,
83 const SectionRef &Sec, uint64_t SecAddress,
84 uint64_t SymAddress, uint64_t SymSize,
85 StringRef *I, StringRef *E) {
86 uint64_t SymOffset = SymAddress - SecAddress;
87 uint64_t SymEnd = SymOffset + SymSize;
88 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
89 for (const object::RelocationRef &Reloc : SR.relocations()) {
92 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
93 if (RelocSymI == Obj->symbol_end())
95 ErrorOr<StringRef> RelocSymName = RelocSymI->getName();
96 error(RelocSymName.getError());
97 uint64_t Offset = Reloc.getOffset();
98 if (Offset >= SymOffset && Offset < SymEnd) {
106 static void collectRelocationOffsets(
107 const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress,
108 uint64_t SymAddress, uint64_t SymSize, StringRef SymName,
109 std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) {
110 uint64_t SymOffset = SymAddress - SecAddress;
111 uint64_t SymEnd = SymOffset + SymSize;
112 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
113 for (const object::RelocationRef &Reloc : SR.relocations()) {
114 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
115 if (RelocSymI == Obj->symbol_end())
117 ErrorOr<StringRef> RelocSymName = RelocSymI->getName();
118 error(RelocSymName.getError());
119 uint64_t Offset = Reloc.getOffset();
120 if (Offset >= SymOffset && Offset < SymEnd)
121 Collection[std::make_pair(SymName, Offset - SymOffset)] = *RelocSymName;
126 static void dumpCXXData(const ObjectFile *Obj) {
127 struct CompleteObjectLocator {
128 StringRef Symbols[2];
129 ArrayRef<little32_t> Data;
131 struct ClassHierarchyDescriptor {
132 StringRef Symbols[1];
133 ArrayRef<little32_t> Data;
135 struct BaseClassDescriptor {
136 StringRef Symbols[2];
137 ArrayRef<little32_t> Data;
139 struct TypeDescriptor {
140 StringRef Symbols[1];
142 StringRef MangledName;
147 struct CatchableTypeArray {
150 struct CatchableType {
152 uint32_t NonVirtualBaseAdjustmentOffset;
153 int32_t VirtualBasePointerOffset;
154 uint32_t VirtualBaseAdjustmentOffset;
156 StringRef Symbols[2];
158 std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
159 std::map<std::pair<StringRef, uint64_t>, StringRef> TIEntries;
160 std::map<std::pair<StringRef, uint64_t>, StringRef> CTAEntries;
161 std::map<StringRef, ArrayRef<little32_t>> VBTables;
162 std::map<StringRef, CompleteObjectLocator> COLs;
163 std::map<StringRef, ClassHierarchyDescriptor> CHDs;
164 std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries;
165 std::map<StringRef, BaseClassDescriptor> BCDs;
166 std::map<StringRef, TypeDescriptor> TDs;
167 std::map<StringRef, ThrowInfo> TIs;
168 std::map<StringRef, CatchableTypeArray> CTAs;
169 std::map<StringRef, CatchableType> CTs;
171 std::map<std::pair<StringRef, uint64_t>, StringRef> VTableSymEntries;
172 std::map<std::pair<StringRef, uint64_t>, int64_t> VTableDataEntries;
173 std::map<std::pair<StringRef, uint64_t>, StringRef> VTTEntries;
174 std::map<StringRef, StringRef> TINames;
176 uint8_t BytesInAddress = Obj->getBytesInAddress();
178 std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
179 object::computeSymbolSizes(*Obj);
181 for (auto &P : SymAddr) {
182 object::SymbolRef Sym = P.first;
183 uint64_t SymSize = P.second;
184 ErrorOr<StringRef> SymNameOrErr = Sym.getName();
185 error(SymNameOrErr.getError());
186 StringRef SymName = *SymNameOrErr;
187 ErrorOr<object::section_iterator> SecIOrErr = Sym.getSection();
188 error(SecIOrErr.getError());
189 object::section_iterator SecI = *SecIOrErr;
190 // Skip external symbols.
191 if (SecI == Obj->section_end())
193 const SectionRef &Sec = *SecI;
194 // Skip virtual or BSS sections.
195 if (Sec.isBSS() || Sec.isVirtual())
197 StringRef SecContents;
198 error(Sec.getContents(SecContents));
199 ErrorOr<uint64_t> SymAddressOrErr = Sym.getAddress();
200 error(SymAddressOrErr.getError());
201 uint64_t SymAddress = *SymAddressOrErr;
202 uint64_t SecAddress = Sec.getAddress();
203 uint64_t SecSize = Sec.getSize();
204 uint64_t SymOffset = SymAddress - SecAddress;
205 StringRef SymContents = SecContents.substr(SymOffset, SymSize);
207 // VFTables in the MS-ABI start with '??_7' and are contained within their
208 // own COMDAT section. We then determine the contents of the VFTable by
209 // looking at each relocation in the section.
210 if (SymName.startswith("??_7")) {
211 // Each relocation either names a virtual method or a thunk. We note the
212 // offset into the section and the symbol used for the relocation.
213 collectRelocationOffsets(Obj, Sec, SecAddress, SecAddress, SecSize,
214 SymName, VFTableEntries);
216 // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
217 // offsets of virtual bases.
218 else if (SymName.startswith("??_8")) {
219 ArrayRef<little32_t> VBTableData(
220 reinterpret_cast<const little32_t *>(SymContents.data()),
221 SymContents.size() / sizeof(little32_t));
222 VBTables[SymName] = VBTableData;
224 // Complete object locators in the MS-ABI start with '??_R4'
225 else if (SymName.startswith("??_R4")) {
226 CompleteObjectLocator COL;
227 COL.Data = ArrayRef<little32_t>(
228 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
229 StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols);
230 collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
233 // Class hierarchy descriptors in the MS-ABI start with '??_R3'
234 else if (SymName.startswith("??_R3")) {
235 ClassHierarchyDescriptor CHD;
236 CHD.Data = ArrayRef<little32_t>(
237 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
238 StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols);
239 collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
242 // Class hierarchy descriptors in the MS-ABI start with '??_R2'
243 else if (SymName.startswith("??_R2")) {
244 // Each relocation names a base class descriptor. We note the offset into
245 // the section and the symbol used for the relocation.
246 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
247 SymName, BCAEntries);
249 // Base class descriptors in the MS-ABI start with '??_R1'
250 else if (SymName.startswith("??_R1")) {
251 BaseClassDescriptor BCD;
252 BCD.Data = ArrayRef<little32_t>(
253 reinterpret_cast<const little32_t *>(SymContents.data()) + 1, 5);
254 StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols);
255 collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
258 // Type descriptors in the MS-ABI start with '??_R0'
259 else if (SymName.startswith("??_R0")) {
260 const char *DataPtr = SymContents.drop_front(BytesInAddress).data();
262 if (BytesInAddress == 8)
263 TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr);
265 TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr);
266 TD.MangledName = SymContents.drop_front(BytesInAddress * 2);
267 StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols);
268 collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
271 // Throw descriptors in the MS-ABI start with '_TI'
272 else if (SymName.startswith("_TI") || SymName.startswith("__TI")) {
274 TI.Flags = *reinterpret_cast<const little32_t *>(SymContents.data());
275 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
279 // Catchable type arrays in the MS-ABI start with _CTA or __CTA.
280 else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) {
281 CatchableTypeArray CTA;
283 *reinterpret_cast<const little32_t *>(SymContents.data());
284 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
285 SymName, CTAEntries);
288 // Catchable types in the MS-ABI start with _CT or __CT.
289 else if (SymName.startswith("_CT") || SymName.startswith("__CT")) {
290 const little32_t *DataPtr =
291 reinterpret_cast<const little32_t *>(SymContents.data());
293 CT.Flags = DataPtr[0];
294 CT.NonVirtualBaseAdjustmentOffset = DataPtr[2];
295 CT.VirtualBasePointerOffset = DataPtr[3];
296 CT.VirtualBaseAdjustmentOffset = DataPtr[4];
297 CT.Size = DataPtr[5];
298 StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols);
299 collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I, E);
302 // Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'.
303 else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) {
304 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
305 SymName, VTTEntries);
307 // Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'.
308 else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) {
309 TINames[SymName] = SymContents.slice(0, SymContents.find('\0'));
311 // Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'.
312 else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) {
313 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
314 SymName, VTableSymEntries);
315 for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) {
316 auto Key = std::make_pair(SymName, SymOffI);
317 if (VTableSymEntries.count(Key))
319 const char *DataPtr =
320 SymContents.substr(SymOffI, BytesInAddress).data();
322 if (BytesInAddress == 8)
323 VData = *reinterpret_cast<const little64_t *>(DataPtr);
325 VData = *reinterpret_cast<const little32_t *>(DataPtr);
326 VTableDataEntries[Key] = VData;
329 // Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'.
330 else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) {
331 // FIXME: Do something with these!
334 for (const auto &VFTableEntry : VFTableEntries) {
335 StringRef VFTableName = VFTableEntry.first.first;
336 uint64_t Offset = VFTableEntry.first.second;
337 StringRef SymName = VFTableEntry.second;
338 outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
340 for (const auto &VBTable : VBTables) {
341 StringRef VBTableName = VBTable.first;
343 for (little32_t Offset : VBTable.second) {
344 outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
345 Idx += sizeof(Offset);
348 for (const auto &COLPair : COLs) {
349 StringRef COLName = COLPair.first;
350 const CompleteObjectLocator &COL = COLPair.second;
351 outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n';
352 outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n';
353 outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n';
354 outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n';
355 outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1]
358 for (const auto &CHDPair : CHDs) {
359 StringRef CHDName = CHDPair.first;
360 const ClassHierarchyDescriptor &CHD = CHDPair.second;
361 outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n';
362 outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n';
363 outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n';
364 outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n';
366 for (const auto &BCAEntry : BCAEntries) {
367 StringRef BCAName = BCAEntry.first.first;
368 uint64_t Offset = BCAEntry.first.second;
369 StringRef SymName = BCAEntry.second;
370 outs() << BCAName << '[' << Offset << "]: " << SymName << '\n';
372 for (const auto &BCDPair : BCDs) {
373 StringRef BCDName = BCDPair.first;
374 const BaseClassDescriptor &BCD = BCDPair.second;
375 outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n';
376 outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n';
377 outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n';
378 outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n';
379 outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n';
380 outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n';
381 outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1]
384 for (const auto &TDPair : TDs) {
385 StringRef TDName = TDPair.first;
386 const TypeDescriptor &TD = TDPair.second;
387 outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n';
388 outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n';
389 outs() << TDName << "[MangledName]: ";
390 outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)),
391 /*UseHexEscapes=*/true)
394 for (const auto &TIPair : TIs) {
395 StringRef TIName = TIPair.first;
396 const ThrowInfo &TI = TIPair.second;
397 auto dumpThrowInfoFlag = [&](const char *Name, uint32_t Flag) {
398 outs() << TIName << "[Flags." << Name
399 << "]: " << (TI.Flags & Flag ? "true" : "false") << '\n';
401 auto dumpThrowInfoSymbol = [&](const char *Name, int Offset) {
402 outs() << TIName << '[' << Name << "]: ";
403 auto Entry = TIEntries.find(std::make_pair(TIName, Offset));
404 outs() << (Entry == TIEntries.end() ? "null" : Entry->second) << '\n';
406 outs() << TIName << "[Flags]: " << TI.Flags << '\n';
407 dumpThrowInfoFlag("Const", 1);
408 dumpThrowInfoFlag("Volatile", 2);
409 dumpThrowInfoSymbol("CleanupFn", 4);
410 dumpThrowInfoSymbol("ForwardCompat", 8);
411 dumpThrowInfoSymbol("CatchableTypeArray", 12);
413 for (const auto &CTAPair : CTAs) {
414 StringRef CTAName = CTAPair.first;
415 const CatchableTypeArray &CTA = CTAPair.second;
417 outs() << CTAName << "[NumEntries]: " << CTA.NumEntries << '\n';
420 for (auto I = CTAEntries.lower_bound(std::make_pair(CTAName, 0)),
421 E = CTAEntries.upper_bound(std::make_pair(CTAName, UINT64_MAX));
423 outs() << CTAName << '[' << Idx++ << "]: " << I->second << '\n';
425 for (const auto &CTPair : CTs) {
426 StringRef CTName = CTPair.first;
427 const CatchableType &CT = CTPair.second;
428 auto dumpCatchableTypeFlag = [&](const char *Name, uint32_t Flag) {
429 outs() << CTName << "[Flags." << Name
430 << "]: " << (CT.Flags & Flag ? "true" : "false") << '\n';
432 outs() << CTName << "[Flags]: " << CT.Flags << '\n';
433 dumpCatchableTypeFlag("ScalarType", 1);
434 dumpCatchableTypeFlag("VirtualInheritance", 4);
435 outs() << CTName << "[TypeDescriptor]: " << CT.Symbols[0] << '\n';
436 outs() << CTName << "[NonVirtualBaseAdjustmentOffset]: "
437 << CT.NonVirtualBaseAdjustmentOffset << '\n';
439 << "[VirtualBasePointerOffset]: " << CT.VirtualBasePointerOffset
441 outs() << CTName << "[VirtualBaseAdjustmentOffset]: "
442 << CT.VirtualBaseAdjustmentOffset << '\n';
443 outs() << CTName << "[Size]: " << CT.Size << '\n';
445 << "[CopyCtor]: " << (CT.Symbols[1].empty() ? "null" : CT.Symbols[1])
448 for (const auto &VTTPair : VTTEntries) {
449 StringRef VTTName = VTTPair.first.first;
450 uint64_t VTTOffset = VTTPair.first.second;
451 StringRef VTTEntry = VTTPair.second;
452 outs() << VTTName << '[' << VTTOffset << "]: " << VTTEntry << '\n';
454 for (const auto &TIPair : TINames) {
455 StringRef TIName = TIPair.first;
456 outs() << TIName << ": " << TIPair.second << '\n';
458 auto VTableSymI = VTableSymEntries.begin();
459 auto VTableSymE = VTableSymEntries.end();
460 auto VTableDataI = VTableDataEntries.begin();
461 auto VTableDataE = VTableDataEntries.end();
463 bool SymDone = VTableSymI == VTableSymE;
464 bool DataDone = VTableDataI == VTableDataE;
465 if (SymDone && DataDone)
467 if (!SymDone && (DataDone || VTableSymI->first < VTableDataI->first)) {
468 StringRef VTableName = VTableSymI->first.first;
469 uint64_t Offset = VTableSymI->first.second;
470 StringRef VTableEntry = VTableSymI->second;
471 outs() << VTableName << '[' << Offset << "]: ";
472 outs() << VTableEntry;
477 if (!DataDone && (SymDone || VTableDataI->first < VTableSymI->first)) {
478 StringRef VTableName = VTableDataI->first.first;
479 uint64_t Offset = VTableDataI->first.second;
480 int64_t VTableEntry = VTableDataI->second;
481 outs() << VTableName << '[' << Offset << "]: ";
482 outs() << VTableEntry;
490 static void dumpArchive(const Archive *Arc) {
491 for (const Archive::Child &ArcC : Arc->children()) {
492 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary();
493 if (std::error_code EC = ChildOrErr.getError()) {
494 // Ignore non-object files.
495 if (EC != object_error::invalid_file_type)
496 reportError(Arc->getFileName(), EC.message());
500 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
503 reportError(Arc->getFileName(), cxxdump_error::unrecognized_file_format);
507 static void dumpInput(StringRef File) {
508 // If file isn't stdin, check that it exists.
509 if (File != "-" && !sys::fs::exists(File)) {
510 reportError(File, cxxdump_error::file_not_found);
514 // Attempt to open the binary.
515 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
516 if (std::error_code EC = BinaryOrErr.getError()) {
517 reportError(File, EC);
520 Binary &Binary = *BinaryOrErr.get().getBinary();
522 if (Archive *Arc = dyn_cast<Archive>(&Binary))
524 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
527 reportError(File, cxxdump_error::unrecognized_file_format);
530 int main(int argc, const char *argv[]) {
531 sys::PrintStackTraceOnErrorSignal();
532 PrettyStackTraceProgram X(argc, argv);
535 // Initialize targets.
536 llvm::InitializeAllTargetInfos();
538 // Register the target printer for --version.
539 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
541 cl::ParseCommandLineOptions(argc, argv, "LLVM C++ ABI Data Dumper\n");
543 // Default to stdin if no filename is specified.
544 if (opts::InputFilenames.size() == 0)
545 opts::InputFilenames.push_back("-");
547 std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),