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>"),
43 static int ReturnValue = EXIT_SUCCESS;
47 static bool error(std::error_code EC) {
51 ReturnValue = EXIT_FAILURE;
52 outs() << "\nError reading file: " << EC.message() << ".\n";
59 static void reportError(StringRef Input, StringRef Message) {
63 errs() << Input << ": " << Message << "\n";
65 ReturnValue = EXIT_FAILURE;
68 static void reportError(StringRef Input, std::error_code EC) {
69 reportError(Input, EC.message());
72 static SmallVectorImpl<SectionRef> &getRelocSections(const ObjectFile *Obj,
73 const SectionRef &Sec) {
74 static bool MappingDone = false;
75 static std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
77 for (const SectionRef &Section : Obj->sections()) {
78 section_iterator Sec2 = Section.getRelocatedSection();
79 if (Sec2 != Obj->section_end())
80 SectionRelocMap[*Sec2].push_back(Section);
84 return SectionRelocMap[Sec];
87 static bool collectRelocatedSymbols(const ObjectFile *Obj,
88 const SectionRef &Sec, uint64_t SecAddress,
89 uint64_t SymAddress, uint64_t SymSize,
90 StringRef *I, StringRef *E) {
91 uint64_t SymOffset = SymAddress - SecAddress;
92 uint64_t SymEnd = SymOffset + SymSize;
93 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
94 for (const object::RelocationRef &Reloc : SR.relocations()) {
97 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
98 if (RelocSymI == Obj->symbol_end())
100 StringRef RelocSymName;
101 if (error(RelocSymI->getName(RelocSymName)))
104 if (error(Reloc.getOffset(Offset)))
106 if (Offset >= SymOffset && Offset < SymEnd) {
115 static bool collectRelocationOffsets(
116 const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress,
117 uint64_t SymAddress, uint64_t SymSize, StringRef SymName,
118 std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) {
119 uint64_t SymOffset = SymAddress - SecAddress;
120 uint64_t SymEnd = SymOffset + SymSize;
121 for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
122 for (const object::RelocationRef &Reloc : SR.relocations()) {
123 const object::symbol_iterator RelocSymI = Reloc.getSymbol();
124 if (RelocSymI == Obj->symbol_end())
126 StringRef RelocSymName;
127 if (error(RelocSymI->getName(RelocSymName)))
130 if (error(Reloc.getOffset(Offset)))
132 if (Offset >= SymOffset && Offset < SymEnd)
133 Collection[std::make_pair(SymName, Offset - SymOffset)] = RelocSymName;
139 static void dumpCXXData(const ObjectFile *Obj) {
140 struct CompleteObjectLocator {
141 StringRef Symbols[2];
142 ArrayRef<little32_t> Data;
144 struct ClassHierarchyDescriptor {
145 StringRef Symbols[1];
146 ArrayRef<little32_t> Data;
148 struct BaseClassDescriptor {
149 StringRef Symbols[2];
150 ArrayRef<little32_t> Data;
152 struct TypeDescriptor {
153 StringRef Symbols[1];
155 StringRef MangledName;
160 struct CatchableTypeArray {
163 struct CatchableType {
165 uint32_t NonVirtualBaseAdjustmentOffset;
166 int32_t VirtualBasePointerOffset;
167 uint32_t VirtualBaseAdjustmentOffset;
169 StringRef Symbols[2];
171 std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
172 std::map<std::pair<StringRef, uint64_t>, StringRef> TIEntries;
173 std::map<std::pair<StringRef, uint64_t>, StringRef> CTAEntries;
174 std::map<StringRef, ArrayRef<little32_t>> VBTables;
175 std::map<StringRef, CompleteObjectLocator> COLs;
176 std::map<StringRef, ClassHierarchyDescriptor> CHDs;
177 std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries;
178 std::map<StringRef, BaseClassDescriptor> BCDs;
179 std::map<StringRef, TypeDescriptor> TDs;
180 std::map<StringRef, ThrowInfo> TIs;
181 std::map<StringRef, CatchableTypeArray> CTAs;
182 std::map<StringRef, CatchableType> CTs;
184 std::map<std::pair<StringRef, uint64_t>, StringRef> VTableSymEntries;
185 std::map<std::pair<StringRef, uint64_t>, int64_t> VTableDataEntries;
186 std::map<std::pair<StringRef, uint64_t>, StringRef> VTTEntries;
187 std::map<StringRef, StringRef> TINames;
189 uint8_t BytesInAddress = Obj->getBytesInAddress();
191 ErrorOr<std::vector<std::pair<SymbolRef, uint64_t>>> SymAddrOrErr =
192 object::computeSymbolSizes(*Obj);
193 if (error(SymAddrOrErr.getError()))
196 for (auto &P : *SymAddrOrErr) {
197 object::SymbolRef Sym = P.first;
198 uint64_t SymSize = P.second;
200 if (error(Sym.getName(SymName)))
202 object::section_iterator SecI(Obj->section_begin());
203 if (error(Sym.getSection(SecI)))
205 // Skip external symbols.
206 if (SecI == Obj->section_end())
208 const SectionRef &Sec = *SecI;
209 // Skip virtual or BSS sections.
210 if (Sec.isBSS() || Sec.isVirtual())
212 StringRef SecContents;
213 if (error(Sec.getContents(SecContents)))
216 if (error(Sym.getAddress(SymAddress)))
218 uint64_t SecAddress = Sec.getAddress();
219 uint64_t SecSize = Sec.getSize();
220 uint64_t SymOffset = SymAddress - SecAddress;
221 StringRef SymContents = SecContents.substr(SymOffset, SymSize);
223 // VFTables in the MS-ABI start with '??_7' and are contained within their
224 // own COMDAT section. We then determine the contents of the VFTable by
225 // looking at each relocation in the section.
226 if (SymName.startswith("??_7")) {
227 // Each relocation either names a virtual method or a thunk. We note the
228 // offset into the section and the symbol used for the relocation.
229 collectRelocationOffsets(Obj, Sec, SecAddress, SecAddress, SecSize,
230 SymName, VFTableEntries);
232 // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
233 // offsets of virtual bases.
234 else if (SymName.startswith("??_8")) {
235 ArrayRef<little32_t> VBTableData(
236 reinterpret_cast<const little32_t *>(SymContents.data()),
237 SymContents.size() / sizeof(little32_t));
238 VBTables[SymName] = VBTableData;
240 // Complete object locators in the MS-ABI start with '??_R4'
241 else if (SymName.startswith("??_R4")) {
242 CompleteObjectLocator COL;
243 COL.Data = ArrayRef<little32_t>(
244 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
245 StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols);
246 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
251 // Class hierarchy descriptors in the MS-ABI start with '??_R3'
252 else if (SymName.startswith("??_R3")) {
253 ClassHierarchyDescriptor CHD;
254 CHD.Data = ArrayRef<little32_t>(
255 reinterpret_cast<const little32_t *>(SymContents.data()), 3);
256 StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols);
257 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
262 // Class hierarchy descriptors in the MS-ABI start with '??_R2'
263 else if (SymName.startswith("??_R2")) {
264 // Each relocation names a base class descriptor. We note the offset into
265 // the section and the symbol used for the relocation.
266 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
267 SymName, BCAEntries);
269 // Base class descriptors in the MS-ABI start with '??_R1'
270 else if (SymName.startswith("??_R1")) {
271 BaseClassDescriptor BCD;
272 BCD.Data = ArrayRef<little32_t>(
273 reinterpret_cast<const little32_t *>(SymContents.data()) + 1, 5);
274 StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols);
275 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
280 // Type descriptors in the MS-ABI start with '??_R0'
281 else if (SymName.startswith("??_R0")) {
282 const char *DataPtr = SymContents.drop_front(BytesInAddress).data();
284 if (BytesInAddress == 8)
285 TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr);
287 TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr);
288 TD.MangledName = SymContents.drop_front(BytesInAddress * 2);
289 StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols);
290 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
295 // Throw descriptors in the MS-ABI start with '_TI'
296 else if (SymName.startswith("_TI") || SymName.startswith("__TI")) {
298 TI.Flags = *reinterpret_cast<const little32_t *>(SymContents.data());
299 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
303 // Catchable type arrays in the MS-ABI start with _CTA or __CTA.
304 else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) {
305 CatchableTypeArray CTA;
307 *reinterpret_cast<const little32_t *>(SymContents.data());
308 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
309 SymName, CTAEntries);
312 // Catchable types in the MS-ABI start with _CT or __CT.
313 else if (SymName.startswith("_CT") || SymName.startswith("__CT")) {
314 const little32_t *DataPtr =
315 reinterpret_cast<const little32_t *>(SymContents.data());
317 CT.Flags = DataPtr[0];
318 CT.NonVirtualBaseAdjustmentOffset = DataPtr[2];
319 CT.VirtualBasePointerOffset = DataPtr[3];
320 CT.VirtualBaseAdjustmentOffset = DataPtr[4];
321 CT.Size = DataPtr[5];
322 StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols);
323 if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
328 // Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'.
329 else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) {
330 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
331 SymName, VTTEntries);
333 // Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'.
334 else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) {
335 TINames[SymName] = SymContents.slice(0, SymContents.find('\0'));
337 // Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'.
338 else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) {
339 collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
340 SymName, VTableSymEntries);
341 for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) {
342 auto Key = std::make_pair(SymName, SymOffI);
343 if (VTableSymEntries.count(Key))
345 const char *DataPtr =
346 SymContents.substr(SymOffI, BytesInAddress).data();
348 if (BytesInAddress == 8)
349 VData = *reinterpret_cast<const little64_t *>(DataPtr);
351 VData = *reinterpret_cast<const little32_t *>(DataPtr);
352 VTableDataEntries[Key] = VData;
355 // Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'.
356 else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) {
357 // FIXME: Do something with these!
360 for (const auto &VFTableEntry : VFTableEntries) {
361 StringRef VFTableName = VFTableEntry.first.first;
362 uint64_t Offset = VFTableEntry.first.second;
363 StringRef SymName = VFTableEntry.second;
364 outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
366 for (const auto &VBTable : VBTables) {
367 StringRef VBTableName = VBTable.first;
369 for (little32_t Offset : VBTable.second) {
370 outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
371 Idx += sizeof(Offset);
374 for (const auto &COLPair : COLs) {
375 StringRef COLName = COLPair.first;
376 const CompleteObjectLocator &COL = COLPair.second;
377 outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n';
378 outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n';
379 outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n';
380 outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n';
381 outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1]
384 for (const auto &CHDPair : CHDs) {
385 StringRef CHDName = CHDPair.first;
386 const ClassHierarchyDescriptor &CHD = CHDPair.second;
387 outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n';
388 outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n';
389 outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n';
390 outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n';
392 for (const auto &BCAEntry : BCAEntries) {
393 StringRef BCAName = BCAEntry.first.first;
394 uint64_t Offset = BCAEntry.first.second;
395 StringRef SymName = BCAEntry.second;
396 outs() << BCAName << '[' << Offset << "]: " << SymName << '\n';
398 for (const auto &BCDPair : BCDs) {
399 StringRef BCDName = BCDPair.first;
400 const BaseClassDescriptor &BCD = BCDPair.second;
401 outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n';
402 outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n';
403 outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n';
404 outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n';
405 outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n';
406 outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n';
407 outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1]
410 for (const auto &TDPair : TDs) {
411 StringRef TDName = TDPair.first;
412 const TypeDescriptor &TD = TDPair.second;
413 outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n';
414 outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n';
415 outs() << TDName << "[MangledName]: ";
416 outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)),
417 /*UseHexEscapes=*/true)
420 for (const auto &TIPair : TIs) {
421 StringRef TIName = TIPair.first;
422 const ThrowInfo &TI = TIPair.second;
423 auto dumpThrowInfoFlag = [&](const char *Name, uint32_t Flag) {
424 outs() << TIName << "[Flags." << Name
425 << "]: " << (TI.Flags & Flag ? "true" : "false") << '\n';
427 auto dumpThrowInfoSymbol = [&](const char *Name, int Offset) {
428 outs() << TIName << '[' << Name << "]: ";
429 auto Entry = TIEntries.find(std::make_pair(TIName, Offset));
430 outs() << (Entry == TIEntries.end() ? "null" : Entry->second) << '\n';
432 outs() << TIName << "[Flags]: " << TI.Flags << '\n';
433 dumpThrowInfoFlag("Const", 1);
434 dumpThrowInfoFlag("Volatile", 2);
435 dumpThrowInfoSymbol("CleanupFn", 4);
436 dumpThrowInfoSymbol("ForwardCompat", 8);
437 dumpThrowInfoSymbol("CatchableTypeArray", 12);
439 for (const auto &CTAPair : CTAs) {
440 StringRef CTAName = CTAPair.first;
441 const CatchableTypeArray &CTA = CTAPair.second;
443 outs() << CTAName << "[NumEntries]: " << CTA.NumEntries << '\n';
446 for (auto I = CTAEntries.lower_bound(std::make_pair(CTAName, 0)),
447 E = CTAEntries.upper_bound(std::make_pair(CTAName, UINT64_MAX));
449 outs() << CTAName << '[' << Idx++ << "]: " << I->second << '\n';
451 for (const auto &CTPair : CTs) {
452 StringRef CTName = CTPair.first;
453 const CatchableType &CT = CTPair.second;
454 auto dumpCatchableTypeFlag = [&](const char *Name, uint32_t Flag) {
455 outs() << CTName << "[Flags." << Name
456 << "]: " << (CT.Flags & Flag ? "true" : "false") << '\n';
458 outs() << CTName << "[Flags]: " << CT.Flags << '\n';
459 dumpCatchableTypeFlag("ScalarType", 1);
460 dumpCatchableTypeFlag("VirtualInheritance", 4);
461 outs() << CTName << "[TypeDescriptor]: " << CT.Symbols[0] << '\n';
462 outs() << CTName << "[NonVirtualBaseAdjustmentOffset]: "
463 << CT.NonVirtualBaseAdjustmentOffset << '\n';
465 << "[VirtualBasePointerOffset]: " << CT.VirtualBasePointerOffset
467 outs() << CTName << "[VirtualBaseAdjustmentOffset]: "
468 << CT.VirtualBaseAdjustmentOffset << '\n';
469 outs() << CTName << "[Size]: " << CT.Size << '\n';
471 << "[CopyCtor]: " << (CT.Symbols[1].empty() ? "null" : CT.Symbols[1])
474 for (const auto &VTTPair : VTTEntries) {
475 StringRef VTTName = VTTPair.first.first;
476 uint64_t VTTOffset = VTTPair.first.second;
477 StringRef VTTEntry = VTTPair.second;
478 outs() << VTTName << '[' << VTTOffset << "]: " << VTTEntry << '\n';
480 for (const auto &TIPair : TINames) {
481 StringRef TIName = TIPair.first;
482 outs() << TIName << ": " << TIPair.second << '\n';
484 auto VTableSymI = VTableSymEntries.begin();
485 auto VTableSymE = VTableSymEntries.end();
486 auto VTableDataI = VTableDataEntries.begin();
487 auto VTableDataE = VTableDataEntries.end();
489 bool SymDone = VTableSymI == VTableSymE;
490 bool DataDone = VTableDataI == VTableDataE;
491 if (SymDone && DataDone)
493 if (!SymDone && (DataDone || VTableSymI->first < VTableDataI->first)) {
494 StringRef VTableName = VTableSymI->first.first;
495 uint64_t Offset = VTableSymI->first.second;
496 StringRef VTableEntry = VTableSymI->second;
497 outs() << VTableName << '[' << Offset << "]: ";
498 outs() << VTableEntry;
503 if (!DataDone && (SymDone || VTableDataI->first < VTableSymI->first)) {
504 StringRef VTableName = VTableDataI->first.first;
505 uint64_t Offset = VTableDataI->first.second;
506 int64_t VTableEntry = VTableDataI->second;
507 outs() << VTableName << '[' << Offset << "]: ";
508 outs() << VTableEntry;
516 static void dumpArchive(const Archive *Arc) {
517 for (const Archive::Child &ArcC : Arc->children()) {
518 ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary();
519 if (std::error_code EC = ChildOrErr.getError()) {
520 // Ignore non-object files.
521 if (EC != object_error::invalid_file_type)
522 reportError(Arc->getFileName(), EC.message());
526 if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
529 reportError(Arc->getFileName(), cxxdump_error::unrecognized_file_format);
533 static void dumpInput(StringRef File) {
534 // If file isn't stdin, check that it exists.
535 if (File != "-" && !sys::fs::exists(File)) {
536 reportError(File, cxxdump_error::file_not_found);
540 // Attempt to open the binary.
541 ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
542 if (std::error_code EC = BinaryOrErr.getError()) {
543 reportError(File, EC);
546 Binary &Binary = *BinaryOrErr.get().getBinary();
548 if (Archive *Arc = dyn_cast<Archive>(&Binary))
550 else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
553 reportError(File, cxxdump_error::unrecognized_file_format);
556 int main(int argc, const char *argv[]) {
557 sys::PrintStackTraceOnErrorSignal();
558 PrettyStackTraceProgram X(argc, argv);
561 // Initialize targets.
562 llvm::InitializeAllTargetInfos();
564 // Register the target printer for --version.
565 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
567 cl::ParseCommandLineOptions(argc, argv, "LLVM C++ ABI Data Dumper\n");
569 // Default to stdin if no filename is specified.
570 if (opts::InputFilenames.size() == 0)
571 opts::InputFilenames.push_back("-");
573 std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),