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/Support/Debug.h"
20 #include "llvm/Support/Endian.h"
21 #include "llvm/Support/FileSystem.h"
22 #include "llvm/Support/ManagedStatic.h"
23 #include "llvm/Support/PrettyStackTrace.h"
24 #include "llvm/Support/Signals.h"
25 #include "llvm/Support/TargetRegistry.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/raw_ostream.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 static 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 SmallVectorImpl<SectionRef> &getRelocSections(const ObjectFile *Obj,
72 const SectionRef &Sec) {
73 static bool MappingDone = false;
74 static std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
76 for (const SectionRef &Section : Obj->sections()) {
77 section_iterator Sec2 = Section.getRelocatedSection();
78 if (Sec2 != Obj->section_end())
79 SectionRelocMap[*Sec2].push_back(Section);
83 return SectionRelocMap[Sec];
86 static bool collectRelocatedSymbols(const ObjectFile *Obj,
87 const SectionRef &Sec, uint64_t SecAddress,
88 uint64_t SymAddress, uint64_t SymSize,
89 StringRef *I, StringRef *E) {
90 uint64_t SymOffset = SymAddress - SecAddress;
91 uint64_t SymEnd = SymOffset + SymSize;
92 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
93 for (const object::RelocationRef &Reloc : SR.relocations()) {
96 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
97 if (RelocSymI == Obj->symbol_end())
99 StringRef RelocSymName;
100 if (error(RelocSymI->getName(RelocSymName)))
103 if (error(Reloc.getOffset(Offset)))
105 if (Offset >= SymOffset && Offset < SymEnd) {
114 static bool collectRelocationOffsets(
115 const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress,
116 uint64_t SymAddress, uint64_t SymSize, StringRef SymName,
117 std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) {
118 uint64_t SymOffset = SymAddress - SecAddress;
119 uint64_t SymEnd = SymOffset + SymSize;
120 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
121 for (const object::RelocationRef &Reloc : SR.relocations()) {
122 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
123 if (RelocSymI == Obj->symbol_end())
125 StringRef RelocSymName;
126 if (error(RelocSymI->getName(RelocSymName)))
129 if (error(Reloc.getOffset(Offset)))
131 if (Offset >= SymOffset && Offset < SymEnd)
132 Collection[std::make_pair(SymName, Offset - SymOffset)] = RelocSymName;
138 static void dumpCXXData(const ObjectFile *Obj) {
139 struct CompleteObjectLocator {
140 StringRef Symbols[2];
141 ArrayRef<little32_t> Data;
143 struct ClassHierarchyDescriptor {
144 StringRef Symbols[1];
145 ArrayRef<little32_t> Data;
147 struct BaseClassDescriptor {
148 StringRef Symbols[2];
149 ArrayRef<little32_t> Data;
151 struct TypeDescriptor {
152 StringRef Symbols[1];
154 StringRef MangledName;
159 struct CatchableTypeArray {
162 struct CatchableType {
164 uint32_t NonVirtualBaseAdjustmentOffset;
165 int32_t VirtualBasePointerOffset;
166 uint32_t VirtualBaseAdjustmentOffset;
168 StringRef Symbols[2];
170 std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
171 std::map<std::pair<StringRef, uint64_t>, StringRef> TIEntries;
172 std::map<std::pair<StringRef, uint64_t>, StringRef> CTAEntries;
173 std::map<StringRef, ArrayRef<little32_t>> VBTables;
174 std::map<StringRef, CompleteObjectLocator> COLs;
175 std::map<StringRef, ClassHierarchyDescriptor> CHDs;
176 std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries;
177 std::map<StringRef, BaseClassDescriptor> BCDs;
178 std::map<StringRef, TypeDescriptor> TDs;
179 std::map<StringRef, ThrowInfo> TIs;
180 std::map<StringRef, CatchableTypeArray> CTAs;
181 std::map<StringRef, CatchableType> CTs;
183 std::map<std::pair<StringRef, uint64_t>, StringRef> VTableSymEntries;
184 std::map<std::pair<StringRef, uint64_t>, int64_t> VTableDataEntries;
185 std::map<std::pair<StringRef, uint64_t>, StringRef> VTTEntries;
186 std::map<StringRef, StringRef> TINames;
188 uint8_t BytesInAddress = Obj->getBytesInAddress();
190 for (const object::SymbolRef &Sym : Obj->symbols()) {
192 if (error(Sym.getName(SymName)))
194 object::section_iterator SecI(Obj->section_begin());
195 if (error(Sym.getSection(SecI)))
197 // Skip external symbols.
198 if (SecI == Obj->section_end())
200 const SectionRef &Sec = *SecI;
201 // Skip virtual or BSS sections.
202 if (Sec.isBSS() || Sec.isVirtual())
204 StringRef SecContents;
205 if (error(Sec.getContents(SecContents)))
208 if (error(Sym.getAddress(SymAddress)))
210 uint64_t SymSize = Sym.getSize();
211 uint64_t SecAddress = Sec.getAddress();
212 uint64_t SecSize = Sec.getSize();
213 uint64_t SymOffset = SymAddress - SecAddress;
214 StringRef SymContents = SecContents.substr(SymOffset, SymSize);
216 // VFTables in the MS-ABI start with '??_7' and are contained within their
217 // own COMDAT section. We then determine the contents of the VFTable by
218 // looking at each relocation in the section.
219 if (SymName.startswith("??_7")) {
220 // Each relocation either names a virtual method or a thunk. We note the
221 // offset into the section and the symbol used for the relocation.
222 collectRelocationOffsets(Obj, Sec, SecAddress, SecAddress, SecSize,
223 SymName, VFTableEntries);
225 // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
226 // offsets of virtual bases.
227 else if (SymName.startswith("??_8")) {
228 ArrayRef<little32_t> VBTableData(
229 reinterpret_cast<const little32_t *>(SymContents.data()),
230 SymContents.size() / sizeof(little32_t));
231 VBTables[SymName] = VBTableData;
233 // Complete object locators in the MS-ABI start with '??_R4'
234 else if (SymName.startswith("??_R4")) {
235 CompleteObjectLocator COL;
236 COL.Data = ArrayRef<little32_t>(
237 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
238 StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols);
239 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
244 // Class hierarchy descriptors in the MS-ABI start with '??_R3'
245 else if (SymName.startswith("??_R3")) {
246 ClassHierarchyDescriptor CHD;
247 CHD.Data = ArrayRef<little32_t>(
248 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
249 StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols);
250 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
255 // Class hierarchy descriptors in the MS-ABI start with '??_R2'
256 else if (SymName.startswith("??_R2")) {
257 // Each relocation names a base class descriptor. We note the offset into
258 // the section and the symbol used for the relocation.
259 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
260 SymName, BCAEntries);
262 // Base class descriptors in the MS-ABI start with '??_R1'
263 else if (SymName.startswith("??_R1")) {
264 BaseClassDescriptor BCD;
265 BCD.Data = ArrayRef<little32_t>(
266 reinterpret_cast<const little32_t *>(SymContents.data()) + 1, 5);
267 StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols);
268 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
273 // Type descriptors in the MS-ABI start with '??_R0'
274 else if (SymName.startswith("??_R0")) {
275 const char *DataPtr = SymContents.drop_front(BytesInAddress).data();
277 if (BytesInAddress == 8)
278 TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr);
280 TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr);
281 TD.MangledName = SymContents.drop_front(BytesInAddress * 2);
282 StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols);
283 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
288 // Throw descriptors in the MS-ABI start with '_TI'
289 else if (SymName.startswith("_TI") || SymName.startswith("__TI")) {
291 TI.Flags = *reinterpret_cast<const little32_t *>(SymContents.data());
292 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
296 // Catchable type arrays in the MS-ABI start with _CTA or __CTA.
297 else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) {
298 CatchableTypeArray CTA;
300 *reinterpret_cast<const little32_t *>(SymContents.data());
301 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
302 SymName, CTAEntries);
305 // Catchable types in the MS-ABI start with _CT or __CT.
306 else if (SymName.startswith("_CT") || SymName.startswith("__CT")) {
307 const little32_t *DataPtr =
308 reinterpret_cast<const little32_t *>(SymContents.data());
310 CT.Flags = DataPtr[0];
311 CT.NonVirtualBaseAdjustmentOffset = DataPtr[2];
312 CT.VirtualBasePointerOffset = DataPtr[3];
313 CT.VirtualBaseAdjustmentOffset = DataPtr[4];
314 CT.Size = DataPtr[5];
315 StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols);
316 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
321 // Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'.
322 else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) {
323 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
324 SymName, VTTEntries);
326 // Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'.
327 else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) {
328 TINames[SymName] = SymContents.slice(0, SymContents.find('\0'));
330 // Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'.
331 else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) {
332 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
333 SymName, VTableSymEntries);
334 for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) {
335 auto Key = std::make_pair(SymName, SymOffI);
336 if (VTableSymEntries.count(Key))
338 const char *DataPtr =
339 SymContents.substr(SymOffI, BytesInAddress).data();
341 if (BytesInAddress == 8)
342 VData = *reinterpret_cast<const little64_t *>(DataPtr);
344 VData = *reinterpret_cast<const little32_t *>(DataPtr);
345 VTableDataEntries[Key] = VData;
348 // Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'.
349 else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) {
350 // FIXME: Do something with these!
353 for (const auto &VFTableEntry : VFTableEntries) {
354 StringRef VFTableName = VFTableEntry.first.first;
355 uint64_t Offset = VFTableEntry.first.second;
356 StringRef SymName = VFTableEntry.second;
357 outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
359 for (const auto &VBTable : VBTables) {
360 StringRef VBTableName = VBTable.first;
362 for (little32_t Offset : VBTable.second) {
363 outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
364 Idx += sizeof(Offset);
367 for (const auto &COLPair : COLs) {
368 StringRef COLName = COLPair.first;
369 const CompleteObjectLocator &COL = COLPair.second;
370 outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n';
371 outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n';
372 outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n';
373 outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n';
374 outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1]
377 for (const auto &CHDPair : CHDs) {
378 StringRef CHDName = CHDPair.first;
379 const ClassHierarchyDescriptor &CHD = CHDPair.second;
380 outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n';
381 outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n';
382 outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n';
383 outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n';
385 for (const auto &BCAEntry : BCAEntries) {
386 StringRef BCAName = BCAEntry.first.first;
387 uint64_t Offset = BCAEntry.first.second;
388 StringRef SymName = BCAEntry.second;
389 outs() << BCAName << '[' << Offset << "]: " << SymName << '\n';
391 for (const auto &BCDPair : BCDs) {
392 StringRef BCDName = BCDPair.first;
393 const BaseClassDescriptor &BCD = BCDPair.second;
394 outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n';
395 outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n';
396 outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n';
397 outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n';
398 outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n';
399 outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n';
400 outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1]
403 for (const auto &TDPair : TDs) {
404 StringRef TDName = TDPair.first;
405 const TypeDescriptor &TD = TDPair.second;
406 outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n';
407 outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n';
408 outs() << TDName << "[MangledName]: ";
409 outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)),
410 /*UseHexEscapes=*/true)
413 for (const auto &TIPair : TIs) {
414 StringRef TIName = TIPair.first;
415 const ThrowInfo &TI = TIPair.second;
416 auto dumpThrowInfoFlag = [&](const char *Name, uint32_t Flag) {
417 outs() << TIName << "[Flags." << Name
418 << "]: " << (TI.Flags & Flag ? "true" : "false") << '\n';
420 auto dumpThrowInfoSymbol = [&](const char *Name, int Offset) {
421 outs() << TIName << '[' << Name << "]: ";
422 auto Entry = TIEntries.find(std::make_pair(TIName, Offset));
423 outs() << (Entry == TIEntries.end() ? "null" : Entry->second) << '\n';
425 outs() << TIName << "[Flags]: " << TI.Flags << '\n';
426 dumpThrowInfoFlag("Const", 1);
427 dumpThrowInfoFlag("Volatile", 2);
428 dumpThrowInfoSymbol("CleanupFn", 4);
429 dumpThrowInfoSymbol("ForwardCompat", 8);
430 dumpThrowInfoSymbol("CatchableTypeArray", 12);
432 for (const auto &CTAPair : CTAs) {
433 StringRef CTAName = CTAPair.first;
434 const CatchableTypeArray &CTA = CTAPair.second;
436 outs() << CTAName << "[NumEntries]: " << CTA.NumEntries << '\n';
439 for (auto I = CTAEntries.lower_bound(std::make_pair(CTAName, 0)),
440 E = CTAEntries.upper_bound(std::make_pair(CTAName, UINT64_MAX));
442 outs() << CTAName << '[' << Idx++ << "]: " << I->second << '\n';
444 for (const auto &CTPair : CTs) {
445 StringRef CTName = CTPair.first;
446 const CatchableType &CT = CTPair.second;
447 auto dumpCatchableTypeFlag = [&](const char *Name, uint32_t Flag) {
448 outs() << CTName << "[Flags." << Name
449 << "]: " << (CT.Flags & Flag ? "true" : "false") << '\n';
451 outs() << CTName << "[Flags]: " << CT.Flags << '\n';
452 dumpCatchableTypeFlag("ScalarType", 1);
453 dumpCatchableTypeFlag("VirtualInheritance", 4);
454 outs() << CTName << "[TypeDescriptor]: " << CT.Symbols[0] << '\n';
455 outs() << CTName << "[NonVirtualBaseAdjustmentOffset]: "
456 << CT.NonVirtualBaseAdjustmentOffset << '\n';
458 << "[VirtualBasePointerOffset]: " << CT.VirtualBasePointerOffset
460 outs() << CTName << "[VirtualBaseAdjustmentOffset]: "
461 << CT.VirtualBaseAdjustmentOffset << '\n';
462 outs() << CTName << "[Size]: " << CT.Size << '\n';
464 << "[CopyCtor]: " << (CT.Symbols[1].empty() ? "null" : CT.Symbols[1])
467 for (const auto &VTTPair : VTTEntries) {
468 StringRef VTTName = VTTPair.first.first;
469 uint64_t VTTOffset = VTTPair.first.second;
470 StringRef VTTEntry = VTTPair.second;
471 outs() << VTTName << '[' << VTTOffset << "]: " << VTTEntry << '\n';
473 for (const auto &TIPair : TINames) {
474 StringRef TIName = TIPair.first;
475 outs() << TIName << ": " << TIPair.second << '\n';
477 auto VTableSymI = VTableSymEntries.begin();
478 auto VTableSymE = VTableSymEntries.end();
479 auto VTableDataI = VTableDataEntries.begin();
480 auto VTableDataE = VTableDataEntries.end();
482 bool SymDone = VTableSymI == VTableSymE;
483 bool DataDone = VTableDataI == VTableDataE;
484 if (SymDone && DataDone)
486 if (!SymDone && (DataDone || VTableSymI->first < VTableDataI->first)) {
487 StringRef VTableName = VTableSymI->first.first;
488 uint64_t Offset = VTableSymI->first.second;
489 StringRef VTableEntry = VTableSymI->second;
490 outs() << VTableName << '[' << Offset << "]: ";
491 outs() << VTableEntry;
496 if (!DataDone && (SymDone || VTableDataI->first < VTableSymI->first)) {
497 StringRef VTableName = VTableDataI->first.first;
498 uint64_t Offset = VTableDataI->first.second;
499 int64_t VTableEntry = VTableDataI->second;
500 outs() << VTableName << '[' << Offset << "]: ";
501 outs() << VTableEntry;
509 static void dumpArchive(const Archive *Arc) {
510 for (const Archive::Child &ArcC : Arc->children()) {
511 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary();
512 if (std::error_code EC = ChildOrErr.getError()) {
513 // Ignore non-object files.
514 if (EC != object_error::invalid_file_type)
515 reportError(Arc->getFileName(), EC.message());
519 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
522 reportError(Arc->getFileName(), cxxdump_error::unrecognized_file_format);
526 static void dumpInput(StringRef File) {
527 // If file isn't stdin, check that it exists.
528 if (File != "-" && !sys::fs::exists(File)) {
529 reportError(File, cxxdump_error::file_not_found);
533 // Attempt to open the binary.
534 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
535 if (std::error_code EC = BinaryOrErr.getError()) {
536 reportError(File, EC);
539 Binary &Binary = *BinaryOrErr.get().getBinary();
541 if (Archive *Arc = dyn_cast<Archive>(&Binary))
543 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
546 reportError(File, cxxdump_error::unrecognized_file_format);
549 int main(int argc, const char *argv[]) {
550 sys::PrintStackTraceOnErrorSignal();
551 PrettyStackTraceProgram X(argc, argv);
554 // Initialize targets.
555 llvm::InitializeAllTargetInfos();
557 // Register the target printer for --version.
558 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
560 cl::ParseCommandLineOptions(argc, argv, "LLVM C++ ABI Data Dumper\n");
562 // Default to stdin if no filename is specified.
563 if (opts::InputFilenames.size() == 0)
564 opts::InputFilenames.push_back("-");
566 std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),