llvm-cxxdump.cpp revision 287506
1//===- llvm-cxxdump.cpp - Dump C++ data 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 C++ data resident in object files and archives.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm-cxxdump.h"
15#include "Error.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"
29#include <map>
30#include <string>
31#include <system_error>
32
33using namespace llvm;
34using namespace llvm::object;
35using namespace llvm::support;
36
37namespace opts {
38cl::list<std::string> InputFilenames(cl::Positional,
39                                     cl::desc("<input object files>"),
40                                     cl::ZeroOrMore);
41} // namespace opts
42
43static int ReturnValue = EXIT_SUCCESS;
44
45namespace llvm {
46
47static bool error(std::error_code EC) {
48  if (!EC)
49    return false;
50
51  ReturnValue = EXIT_FAILURE;
52  outs() << "\nError reading file: " << EC.message() << ".\n";
53  outs().flush();
54  return true;
55}
56
57} // namespace llvm
58
59static void reportError(StringRef Input, StringRef Message) {
60  if (Input == "-")
61    Input = "<stdin>";
62
63  errs() << Input << ": " << Message << "\n";
64  errs().flush();
65  ReturnValue = EXIT_FAILURE;
66}
67
68static void reportError(StringRef Input, std::error_code EC) {
69  reportError(Input, EC.message());
70}
71
72static SmallVectorImpl<SectionRef> &getRelocSections(const ObjectFile *Obj,
73                                                     const SectionRef &Sec) {
74  static bool MappingDone = false;
75  static std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
76  if (!MappingDone) {
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);
81    }
82    MappingDone = true;
83  }
84  return SectionRelocMap[Sec];
85}
86
87static 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()) {
95      if (I == E)
96        break;
97      const object::symbol_iterator RelocSymI = Reloc.getSymbol();
98      if (RelocSymI == Obj->symbol_end())
99        continue;
100      ErrorOr<StringRef> RelocSymName = RelocSymI->getName();
101      if (error(RelocSymName.getError()))
102        return true;
103      uint64_t Offset = Reloc.getOffset();
104      if (Offset >= SymOffset && Offset < SymEnd) {
105        *I = *RelocSymName;
106        ++I;
107      }
108    }
109  }
110  return false;
111}
112
113static bool collectRelocationOffsets(
114    const ObjectFile *Obj, const SectionRef &Sec, uint64_t SecAddress,
115    uint64_t SymAddress, uint64_t SymSize, StringRef SymName,
116    std::map<std::pair<StringRef, uint64_t>, StringRef> &Collection) {
117  uint64_t SymOffset = SymAddress - SecAddress;
118  uint64_t SymEnd = SymOffset + SymSize;
119  for (const SectionRef &SR : getRelocSections(Obj, Sec)) {
120    for (const object::RelocationRef &Reloc : SR.relocations()) {
121      const object::symbol_iterator RelocSymI = Reloc.getSymbol();
122      if (RelocSymI == Obj->symbol_end())
123        continue;
124      ErrorOr<StringRef> RelocSymName = RelocSymI->getName();
125      if (error(RelocSymName.getError()))
126        return true;
127      uint64_t Offset = Reloc.getOffset();
128      if (Offset >= SymOffset && Offset < SymEnd)
129        Collection[std::make_pair(SymName, Offset - SymOffset)] = *RelocSymName;
130    }
131  }
132  return false;
133}
134
135static void dumpCXXData(const ObjectFile *Obj) {
136  struct CompleteObjectLocator {
137    StringRef Symbols[2];
138    ArrayRef<little32_t> Data;
139  };
140  struct ClassHierarchyDescriptor {
141    StringRef Symbols[1];
142    ArrayRef<little32_t> Data;
143  };
144  struct BaseClassDescriptor {
145    StringRef Symbols[2];
146    ArrayRef<little32_t> Data;
147  };
148  struct TypeDescriptor {
149    StringRef Symbols[1];
150    uint64_t AlwaysZero;
151    StringRef MangledName;
152  };
153  struct ThrowInfo {
154    uint32_t Flags;
155  };
156  struct CatchableTypeArray {
157    uint32_t NumEntries;
158  };
159  struct CatchableType {
160    uint32_t Flags;
161    uint32_t NonVirtualBaseAdjustmentOffset;
162    int32_t VirtualBasePointerOffset;
163    uint32_t VirtualBaseAdjustmentOffset;
164    uint32_t Size;
165    StringRef Symbols[2];
166  };
167  std::map<std::pair<StringRef, uint64_t>, StringRef> VFTableEntries;
168  std::map<std::pair<StringRef, uint64_t>, StringRef> TIEntries;
169  std::map<std::pair<StringRef, uint64_t>, StringRef> CTAEntries;
170  std::map<StringRef, ArrayRef<little32_t>> VBTables;
171  std::map<StringRef, CompleteObjectLocator> COLs;
172  std::map<StringRef, ClassHierarchyDescriptor> CHDs;
173  std::map<std::pair<StringRef, uint64_t>, StringRef> BCAEntries;
174  std::map<StringRef, BaseClassDescriptor> BCDs;
175  std::map<StringRef, TypeDescriptor> TDs;
176  std::map<StringRef, ThrowInfo> TIs;
177  std::map<StringRef, CatchableTypeArray> CTAs;
178  std::map<StringRef, CatchableType> CTs;
179
180  std::map<std::pair<StringRef, uint64_t>, StringRef> VTableSymEntries;
181  std::map<std::pair<StringRef, uint64_t>, int64_t> VTableDataEntries;
182  std::map<std::pair<StringRef, uint64_t>, StringRef> VTTEntries;
183  std::map<StringRef, StringRef> TINames;
184
185  uint8_t BytesInAddress = Obj->getBytesInAddress();
186
187  std::vector<std::pair<SymbolRef, uint64_t>> SymAddr =
188      object::computeSymbolSizes(*Obj);
189
190  for (auto &P : SymAddr) {
191    object::SymbolRef Sym = P.first;
192    uint64_t SymSize = P.second;
193    ErrorOr<StringRef> SymNameOrErr = Sym.getName();
194    if (error(SymNameOrErr.getError()))
195      return;
196    StringRef SymName = *SymNameOrErr;
197    object::section_iterator SecI(Obj->section_begin());
198    if (error(Sym.getSection(SecI)))
199      return;
200    // Skip external symbols.
201    if (SecI == Obj->section_end())
202      continue;
203    const SectionRef &Sec = *SecI;
204    // Skip virtual or BSS sections.
205    if (Sec.isBSS() || Sec.isVirtual())
206      continue;
207    StringRef SecContents;
208    if (error(Sec.getContents(SecContents)))
209      return;
210    ErrorOr<uint64_t> SymAddressOrErr = Sym.getAddress();
211    if (error(SymAddressOrErr.getError()))
212      return;
213    uint64_t SymAddress = *SymAddressOrErr;
214    uint64_t SecAddress = Sec.getAddress();
215    uint64_t SecSize = Sec.getSize();
216    uint64_t SymOffset = SymAddress - SecAddress;
217    StringRef SymContents = SecContents.substr(SymOffset, SymSize);
218
219    // VFTables in the MS-ABI start with '??_7' and are contained within their
220    // own COMDAT section.  We then determine the contents of the VFTable by
221    // looking at each relocation in the section.
222    if (SymName.startswith("??_7")) {
223      // Each relocation either names a virtual method or a thunk.  We note the
224      // offset into the section and the symbol used for the relocation.
225      collectRelocationOffsets(Obj, Sec, SecAddress, SecAddress, SecSize,
226                               SymName, VFTableEntries);
227    }
228    // VBTables in the MS-ABI start with '??_8' and are filled with 32-bit
229    // offsets of virtual bases.
230    else if (SymName.startswith("??_8")) {
231      ArrayRef<little32_t> VBTableData(
232          reinterpret_cast<const little32_t *>(SymContents.data()),
233          SymContents.size() / sizeof(little32_t));
234      VBTables[SymName] = VBTableData;
235    }
236    // Complete object locators in the MS-ABI start with '??_R4'
237    else if (SymName.startswith("??_R4")) {
238      CompleteObjectLocator COL;
239      COL.Data = ArrayRef<little32_t>(
240          reinterpret_cast<const little32_t *>(SymContents.data()), 3);
241      StringRef *I = std::begin(COL.Symbols), *E = std::end(COL.Symbols);
242      if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
243                                  E))
244        return;
245      COLs[SymName] = COL;
246    }
247    // Class hierarchy descriptors in the MS-ABI start with '??_R3'
248    else if (SymName.startswith("??_R3")) {
249      ClassHierarchyDescriptor CHD;
250      CHD.Data = ArrayRef<little32_t>(
251          reinterpret_cast<const little32_t *>(SymContents.data()), 3);
252      StringRef *I = std::begin(CHD.Symbols), *E = std::end(CHD.Symbols);
253      if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
254                                  E))
255        return;
256      CHDs[SymName] = CHD;
257    }
258    // Class hierarchy descriptors in the MS-ABI start with '??_R2'
259    else if (SymName.startswith("??_R2")) {
260      // Each relocation names a base class descriptor.  We note the offset into
261      // the section and the symbol used for the relocation.
262      collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
263                               SymName, BCAEntries);
264    }
265    // Base class descriptors in the MS-ABI start with '??_R1'
266    else if (SymName.startswith("??_R1")) {
267      BaseClassDescriptor BCD;
268      BCD.Data = ArrayRef<little32_t>(
269          reinterpret_cast<const little32_t *>(SymContents.data()) + 1, 5);
270      StringRef *I = std::begin(BCD.Symbols), *E = std::end(BCD.Symbols);
271      if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
272                                  E))
273        return;
274      BCDs[SymName] = BCD;
275    }
276    // Type descriptors in the MS-ABI start with '??_R0'
277    else if (SymName.startswith("??_R0")) {
278      const char *DataPtr = SymContents.drop_front(BytesInAddress).data();
279      TypeDescriptor TD;
280      if (BytesInAddress == 8)
281        TD.AlwaysZero = *reinterpret_cast<const little64_t *>(DataPtr);
282      else
283        TD.AlwaysZero = *reinterpret_cast<const little32_t *>(DataPtr);
284      TD.MangledName = SymContents.drop_front(BytesInAddress * 2);
285      StringRef *I = std::begin(TD.Symbols), *E = std::end(TD.Symbols);
286      if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
287                                  E))
288        return;
289      TDs[SymName] = TD;
290    }
291    // Throw descriptors in the MS-ABI start with '_TI'
292    else if (SymName.startswith("_TI") || SymName.startswith("__TI")) {
293      ThrowInfo TI;
294      TI.Flags = *reinterpret_cast<const little32_t *>(SymContents.data());
295      collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
296                               SymName, TIEntries);
297      TIs[SymName] = TI;
298    }
299    // Catchable type arrays in the MS-ABI start with _CTA or __CTA.
300    else if (SymName.startswith("_CTA") || SymName.startswith("__CTA")) {
301      CatchableTypeArray CTA;
302      CTA.NumEntries =
303          *reinterpret_cast<const little32_t *>(SymContents.data());
304      collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
305                               SymName, CTAEntries);
306      CTAs[SymName] = CTA;
307    }
308    // Catchable types in the MS-ABI start with _CT or __CT.
309    else if (SymName.startswith("_CT") || SymName.startswith("__CT")) {
310      const little32_t *DataPtr =
311          reinterpret_cast<const little32_t *>(SymContents.data());
312      CatchableType CT;
313      CT.Flags = DataPtr[0];
314      CT.NonVirtualBaseAdjustmentOffset = DataPtr[2];
315      CT.VirtualBasePointerOffset = DataPtr[3];
316      CT.VirtualBaseAdjustmentOffset = DataPtr[4];
317      CT.Size = DataPtr[5];
318      StringRef *I = std::begin(CT.Symbols), *E = std::end(CT.Symbols);
319      if (collectRelocatedSymbols(Obj, Sec, SecAddress, SymAddress, SymSize, I,
320                                  E))
321        return;
322      CTs[SymName] = CT;
323    }
324    // Construction vtables in the Itanium ABI start with '_ZTT' or '__ZTT'.
325    else if (SymName.startswith("_ZTT") || SymName.startswith("__ZTT")) {
326      collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
327                               SymName, VTTEntries);
328    }
329    // Typeinfo names in the Itanium ABI start with '_ZTS' or '__ZTS'.
330    else if (SymName.startswith("_ZTS") || SymName.startswith("__ZTS")) {
331      TINames[SymName] = SymContents.slice(0, SymContents.find('\0'));
332    }
333    // Vtables in the Itanium ABI start with '_ZTV' or '__ZTV'.
334    else if (SymName.startswith("_ZTV") || SymName.startswith("__ZTV")) {
335      collectRelocationOffsets(Obj, Sec, SecAddress, SymAddress, SymSize,
336                               SymName, VTableSymEntries);
337      for (uint64_t SymOffI = 0; SymOffI < SymSize; SymOffI += BytesInAddress) {
338        auto Key = std::make_pair(SymName, SymOffI);
339        if (VTableSymEntries.count(Key))
340          continue;
341        const char *DataPtr =
342            SymContents.substr(SymOffI, BytesInAddress).data();
343        int64_t VData;
344        if (BytesInAddress == 8)
345          VData = *reinterpret_cast<const little64_t *>(DataPtr);
346        else
347          VData = *reinterpret_cast<const little32_t *>(DataPtr);
348        VTableDataEntries[Key] = VData;
349      }
350    }
351    // Typeinfo structures in the Itanium ABI start with '_ZTI' or '__ZTI'.
352    else if (SymName.startswith("_ZTI") || SymName.startswith("__ZTI")) {
353      // FIXME: Do something with these!
354    }
355  }
356  for (const auto &VFTableEntry : VFTableEntries) {
357    StringRef VFTableName = VFTableEntry.first.first;
358    uint64_t Offset = VFTableEntry.first.second;
359    StringRef SymName = VFTableEntry.second;
360    outs() << VFTableName << '[' << Offset << "]: " << SymName << '\n';
361  }
362  for (const auto &VBTable : VBTables) {
363    StringRef VBTableName = VBTable.first;
364    uint32_t Idx = 0;
365    for (little32_t Offset : VBTable.second) {
366      outs() << VBTableName << '[' << Idx << "]: " << Offset << '\n';
367      Idx += sizeof(Offset);
368    }
369  }
370  for (const auto &COLPair : COLs) {
371    StringRef COLName = COLPair.first;
372    const CompleteObjectLocator &COL = COLPair.second;
373    outs() << COLName << "[IsImageRelative]: " << COL.Data[0] << '\n';
374    outs() << COLName << "[OffsetToTop]: " << COL.Data[1] << '\n';
375    outs() << COLName << "[VFPtrOffset]: " << COL.Data[2] << '\n';
376    outs() << COLName << "[TypeDescriptor]: " << COL.Symbols[0] << '\n';
377    outs() << COLName << "[ClassHierarchyDescriptor]: " << COL.Symbols[1]
378           << '\n';
379  }
380  for (const auto &CHDPair : CHDs) {
381    StringRef CHDName = CHDPair.first;
382    const ClassHierarchyDescriptor &CHD = CHDPair.second;
383    outs() << CHDName << "[AlwaysZero]: " << CHD.Data[0] << '\n';
384    outs() << CHDName << "[Flags]: " << CHD.Data[1] << '\n';
385    outs() << CHDName << "[NumClasses]: " << CHD.Data[2] << '\n';
386    outs() << CHDName << "[BaseClassArray]: " << CHD.Symbols[0] << '\n';
387  }
388  for (const auto &BCAEntry : BCAEntries) {
389    StringRef BCAName = BCAEntry.first.first;
390    uint64_t Offset = BCAEntry.first.second;
391    StringRef SymName = BCAEntry.second;
392    outs() << BCAName << '[' << Offset << "]: " << SymName << '\n';
393  }
394  for (const auto &BCDPair : BCDs) {
395    StringRef BCDName = BCDPair.first;
396    const BaseClassDescriptor &BCD = BCDPair.second;
397    outs() << BCDName << "[TypeDescriptor]: " << BCD.Symbols[0] << '\n';
398    outs() << BCDName << "[NumBases]: " << BCD.Data[0] << '\n';
399    outs() << BCDName << "[OffsetInVBase]: " << BCD.Data[1] << '\n';
400    outs() << BCDName << "[VBPtrOffset]: " << BCD.Data[2] << '\n';
401    outs() << BCDName << "[OffsetInVBTable]: " << BCD.Data[3] << '\n';
402    outs() << BCDName << "[Flags]: " << BCD.Data[4] << '\n';
403    outs() << BCDName << "[ClassHierarchyDescriptor]: " << BCD.Symbols[1]
404           << '\n';
405  }
406  for (const auto &TDPair : TDs) {
407    StringRef TDName = TDPair.first;
408    const TypeDescriptor &TD = TDPair.second;
409    outs() << TDName << "[VFPtr]: " << TD.Symbols[0] << '\n';
410    outs() << TDName << "[AlwaysZero]: " << TD.AlwaysZero << '\n';
411    outs() << TDName << "[MangledName]: ";
412    outs().write_escaped(TD.MangledName.rtrim(StringRef("\0", 1)),
413                         /*UseHexEscapes=*/true)
414        << '\n';
415  }
416  for (const auto &TIPair : TIs) {
417    StringRef TIName = TIPair.first;
418    const ThrowInfo &TI = TIPair.second;
419    auto dumpThrowInfoFlag = [&](const char *Name, uint32_t Flag) {
420      outs() << TIName << "[Flags." << Name
421             << "]: " << (TI.Flags & Flag ? "true" : "false") << '\n';
422    };
423    auto dumpThrowInfoSymbol = [&](const char *Name, int Offset) {
424      outs() << TIName << '[' << Name << "]: ";
425      auto Entry = TIEntries.find(std::make_pair(TIName, Offset));
426      outs() << (Entry == TIEntries.end() ? "null" : Entry->second) << '\n';
427    };
428    outs() << TIName << "[Flags]: " << TI.Flags << '\n';
429    dumpThrowInfoFlag("Const", 1);
430    dumpThrowInfoFlag("Volatile", 2);
431    dumpThrowInfoSymbol("CleanupFn", 4);
432    dumpThrowInfoSymbol("ForwardCompat", 8);
433    dumpThrowInfoSymbol("CatchableTypeArray", 12);
434  }
435  for (const auto &CTAPair : CTAs) {
436    StringRef CTAName = CTAPair.first;
437    const CatchableTypeArray &CTA = CTAPair.second;
438
439    outs() << CTAName << "[NumEntries]: " << CTA.NumEntries << '\n';
440
441    unsigned Idx = 0;
442    for (auto I = CTAEntries.lower_bound(std::make_pair(CTAName, 0)),
443              E = CTAEntries.upper_bound(std::make_pair(CTAName, UINT64_MAX));
444         I != E; ++I)
445      outs() << CTAName << '[' << Idx++ << "]: " << I->second << '\n';
446  }
447  for (const auto &CTPair : CTs) {
448    StringRef CTName = CTPair.first;
449    const CatchableType &CT = CTPair.second;
450    auto dumpCatchableTypeFlag = [&](const char *Name, uint32_t Flag) {
451      outs() << CTName << "[Flags." << Name
452             << "]: " << (CT.Flags & Flag ? "true" : "false") << '\n';
453    };
454    outs() << CTName << "[Flags]: " << CT.Flags << '\n';
455    dumpCatchableTypeFlag("ScalarType", 1);
456    dumpCatchableTypeFlag("VirtualInheritance", 4);
457    outs() << CTName << "[TypeDescriptor]: " << CT.Symbols[0] << '\n';
458    outs() << CTName << "[NonVirtualBaseAdjustmentOffset]: "
459           << CT.NonVirtualBaseAdjustmentOffset << '\n';
460    outs() << CTName
461           << "[VirtualBasePointerOffset]: " << CT.VirtualBasePointerOffset
462           << '\n';
463    outs() << CTName << "[VirtualBaseAdjustmentOffset]: "
464           << CT.VirtualBaseAdjustmentOffset << '\n';
465    outs() << CTName << "[Size]: " << CT.Size << '\n';
466    outs() << CTName
467           << "[CopyCtor]: " << (CT.Symbols[1].empty() ? "null" : CT.Symbols[1])
468           << '\n';
469  }
470  for (const auto &VTTPair : VTTEntries) {
471    StringRef VTTName = VTTPair.first.first;
472    uint64_t VTTOffset = VTTPair.first.second;
473    StringRef VTTEntry = VTTPair.second;
474    outs() << VTTName << '[' << VTTOffset << "]: " << VTTEntry << '\n';
475  }
476  for (const auto &TIPair : TINames) {
477    StringRef TIName = TIPair.first;
478    outs() << TIName << ": " << TIPair.second << '\n';
479  }
480  auto VTableSymI = VTableSymEntries.begin();
481  auto VTableSymE = VTableSymEntries.end();
482  auto VTableDataI = VTableDataEntries.begin();
483  auto VTableDataE = VTableDataEntries.end();
484  for (;;) {
485    bool SymDone = VTableSymI == VTableSymE;
486    bool DataDone = VTableDataI == VTableDataE;
487    if (SymDone && DataDone)
488      break;
489    if (!SymDone && (DataDone || VTableSymI->first < VTableDataI->first)) {
490      StringRef VTableName = VTableSymI->first.first;
491      uint64_t Offset = VTableSymI->first.second;
492      StringRef VTableEntry = VTableSymI->second;
493      outs() << VTableName << '[' << Offset << "]: ";
494      outs() << VTableEntry;
495      outs() << '\n';
496      ++VTableSymI;
497      continue;
498    }
499    if (!DataDone && (SymDone || VTableDataI->first < VTableSymI->first)) {
500      StringRef VTableName = VTableDataI->first.first;
501      uint64_t Offset = VTableDataI->first.second;
502      int64_t VTableEntry = VTableDataI->second;
503      outs() << VTableName << '[' << Offset << "]: ";
504      outs() << VTableEntry;
505      outs() << '\n';
506      ++VTableDataI;
507      continue;
508    }
509  }
510}
511
512static void dumpArchive(const Archive *Arc) {
513  for (const Archive::Child &ArcC : Arc->children()) {
514    ErrorOr<std::unique_ptr<Binary>> ChildOrErr = ArcC.getAsBinary();
515    if (std::error_code EC = ChildOrErr.getError()) {
516      // Ignore non-object files.
517      if (EC != object_error::invalid_file_type)
518        reportError(Arc->getFileName(), EC.message());
519      continue;
520    }
521
522    if (ObjectFile *Obj = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
523      dumpCXXData(Obj);
524    else
525      reportError(Arc->getFileName(), cxxdump_error::unrecognized_file_format);
526  }
527}
528
529static void dumpInput(StringRef File) {
530  // If file isn't stdin, check that it exists.
531  if (File != "-" && !sys::fs::exists(File)) {
532    reportError(File, cxxdump_error::file_not_found);
533    return;
534  }
535
536  // Attempt to open the binary.
537  ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(File);
538  if (std::error_code EC = BinaryOrErr.getError()) {
539    reportError(File, EC);
540    return;
541  }
542  Binary &Binary = *BinaryOrErr.get().getBinary();
543
544  if (Archive *Arc = dyn_cast<Archive>(&Binary))
545    dumpArchive(Arc);
546  else if (ObjectFile *Obj = dyn_cast<ObjectFile>(&Binary))
547    dumpCXXData(Obj);
548  else
549    reportError(File, cxxdump_error::unrecognized_file_format);
550}
551
552int main(int argc, const char *argv[]) {
553  sys::PrintStackTraceOnErrorSignal();
554  PrettyStackTraceProgram X(argc, argv);
555  llvm_shutdown_obj Y;
556
557  // Initialize targets.
558  llvm::InitializeAllTargetInfos();
559
560  // Register the target printer for --version.
561  cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
562
563  cl::ParseCommandLineOptions(argc, argv, "LLVM C++ ABI Data Dumper\n");
564
565  // Default to stdin if no filename is specified.
566  if (opts::InputFilenames.size() == 0)
567    opts::InputFilenames.push_back("-");
568
569  std::for_each(opts::InputFilenames.begin(), opts::InputFilenames.end(),
570                dumpInput);
571
572  return ReturnValue;
573}
574