Nuke MCAnalysis.
[oota-llvm.git] / tools / llvm-objdump / llvm-objdump.cpp
1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
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 // This program is a utility that works like binutils "objdump", that is, it
11 // dumps out a plethora of information about an object file depending on the
12 // flags.
13 //
14 // The flags and output of this program should be near identical to those of
15 // binutils objdump.
16 //
17 //===----------------------------------------------------------------------===//
18
19 #include "llvm-objdump.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCContext.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCInstrAnalysis.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCObjectFileInfo.h"
31 #include "llvm/MC/MCRegisterInfo.h"
32 #include "llvm/MC/MCRelocationInfo.h"
33 #include "llvm/MC/MCSubtargetInfo.h"
34 #include "llvm/Object/Archive.h"
35 #include "llvm/Object/COFF.h"
36 #include "llvm/Object/MachO.h"
37 #include "llvm/Object/ObjectFile.h"
38 #include "llvm/Support/Casting.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FileSystem.h"
42 #include "llvm/Support/Format.h"
43 #include "llvm/Support/GraphWriter.h"
44 #include "llvm/Support/Host.h"
45 #include "llvm/Support/ManagedStatic.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/MemoryObject.h"
48 #include "llvm/Support/PrettyStackTrace.h"
49 #include "llvm/Support/Signals.h"
50 #include "llvm/Support/SourceMgr.h"
51 #include "llvm/Support/TargetRegistry.h"
52 #include "llvm/Support/TargetSelect.h"
53 #include "llvm/Support/raw_ostream.h"
54 #include <algorithm>
55 #include <cctype>
56 #include <cstring>
57 #include <system_error>
58
59 using namespace llvm;
60 using namespace object;
61
62 static cl::list<std::string>
63 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
64
65 static cl::opt<bool>
66 Disassemble("disassemble",
67   cl::desc("Display assembler mnemonics for the machine instructions"));
68 static cl::alias
69 Disassembled("d", cl::desc("Alias for --disassemble"),
70              cl::aliasopt(Disassemble));
71
72 static cl::opt<bool>
73 Relocations("r", cl::desc("Display the relocation entries in the file"));
74
75 static cl::opt<bool>
76 SectionContents("s", cl::desc("Display the content of each section"));
77
78 static cl::opt<bool>
79 SymbolTable("t", cl::desc("Display the symbol table"));
80
81 static cl::opt<bool>
82 ExportsTrie("exports-trie", cl::desc("Display mach-o exported symbols"));
83
84 static cl::opt<bool>
85 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
86 static cl::alias
87 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
88
89 cl::opt<std::string>
90 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
91                                     "see -version for available targets"));
92
93 cl::opt<std::string>
94 llvm::MCPU("mcpu",
95      cl::desc("Target a specific cpu type (-mcpu=help for details)"),
96      cl::value_desc("cpu-name"),
97      cl::init(""));
98
99 cl::opt<std::string>
100 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
101                                 "see -version for available targets"));
102
103 static cl::opt<bool>
104 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
105                                            "for each section."));
106 static cl::alias
107 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
108                     cl::aliasopt(SectionHeaders));
109 static cl::alias
110 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
111                       cl::aliasopt(SectionHeaders));
112
113 cl::list<std::string>
114 llvm::MAttrs("mattr",
115   cl::CommaSeparated,
116   cl::desc("Target specific attributes"),
117   cl::value_desc("a1,+a2,-a3,..."));
118
119 static cl::opt<bool>
120 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
121                                            "do not print the instruction bytes."));
122
123 static cl::opt<bool>
124 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
125
126 static cl::alias
127 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
128                 cl::aliasopt(UnwindInfo));
129
130 static cl::opt<bool>
131 PrivateHeaders("private-headers",
132                cl::desc("Display format specific file headers"));
133
134 static cl::alias
135 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
136                     cl::aliasopt(PrivateHeaders));
137
138 static StringRef ToolName;
139
140 bool llvm::error(std::error_code EC) {
141   if (!EC)
142     return false;
143
144   outs() << ToolName << ": error reading file: " << EC.message() << ".\n";
145   outs().flush();
146   return true;
147 }
148
149 static const Target *getTarget(const ObjectFile *Obj = nullptr) {
150   // Figure out the target triple.
151   llvm::Triple TheTriple("unknown-unknown-unknown");
152   if (TripleName.empty()) {
153     if (Obj) {
154       TheTriple.setArch(Triple::ArchType(Obj->getArch()));
155       // TheTriple defaults to ELF, and COFF doesn't have an environment:
156       // the best we can do here is indicate that it is mach-o.
157       if (Obj->isMachO())
158         TheTriple.setObjectFormat(Triple::MachO);
159
160       if (Obj->isCOFF()) {
161         const auto COFFObj = dyn_cast<COFFObjectFile>(Obj);
162         if (COFFObj->getArch() == Triple::thumb)
163           TheTriple.setTriple("thumbv7-windows");
164       }
165     }
166   } else
167     TheTriple.setTriple(Triple::normalize(TripleName));
168
169   // Get the target specific parser.
170   std::string Error;
171   const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
172                                                          Error);
173   if (!TheTarget) {
174     errs() << ToolName << ": " << Error;
175     return nullptr;
176   }
177
178   // Update the triple name and return the found target.
179   TripleName = TheTriple.getTriple();
180   return TheTarget;
181 }
182
183 void llvm::DumpBytes(StringRef bytes) {
184   static const char hex_rep[] = "0123456789abcdef";
185   // FIXME: The real way to do this is to figure out the longest instruction
186   //        and align to that size before printing. I'll fix this when I get
187   //        around to outputting relocations.
188   // 15 is the longest x86 instruction
189   // 3 is for the hex rep of a byte + a space.
190   // 1 is for the null terminator.
191   enum { OutputSize = (15 * 3) + 1 };
192   char output[OutputSize];
193
194   assert(bytes.size() <= 15
195     && "DumpBytes only supports instructions of up to 15 bytes");
196   memset(output, ' ', sizeof(output));
197   unsigned index = 0;
198   for (StringRef::iterator i = bytes.begin(),
199                            e = bytes.end(); i != e; ++i) {
200     output[index] = hex_rep[(*i & 0xF0) >> 4];
201     output[index + 1] = hex_rep[*i & 0xF];
202     index += 3;
203   }
204
205   output[sizeof(output) - 1] = 0;
206   outs() << output;
207 }
208
209 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
210   uint64_t a_addr, b_addr;
211   if (error(a.getOffset(a_addr))) return false;
212   if (error(b.getOffset(b_addr))) return false;
213   return a_addr < b_addr;
214 }
215
216 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
217   const Target *TheTarget = getTarget(Obj);
218   // getTarget() will have already issued a diagnostic if necessary, so
219   // just bail here if it failed.
220   if (!TheTarget)
221     return;
222
223   // Package up features to be passed to target/subtarget
224   std::string FeaturesStr;
225   if (MAttrs.size()) {
226     SubtargetFeatures Features;
227     for (unsigned i = 0; i != MAttrs.size(); ++i)
228       Features.AddFeature(MAttrs[i]);
229     FeaturesStr = Features.getString();
230   }
231
232   std::unique_ptr<const MCRegisterInfo> MRI(
233       TheTarget->createMCRegInfo(TripleName));
234   if (!MRI) {
235     errs() << "error: no register info for target " << TripleName << "\n";
236     return;
237   }
238
239   // Set up disassembler.
240   std::unique_ptr<const MCAsmInfo> AsmInfo(
241       TheTarget->createMCAsmInfo(*MRI, TripleName));
242   if (!AsmInfo) {
243     errs() << "error: no assembly info for target " << TripleName << "\n";
244     return;
245   }
246
247   std::unique_ptr<const MCSubtargetInfo> STI(
248       TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr));
249   if (!STI) {
250     errs() << "error: no subtarget info for target " << TripleName << "\n";
251     return;
252   }
253
254   std::unique_ptr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
255   if (!MII) {
256     errs() << "error: no instruction info for target " << TripleName << "\n";
257     return;
258   }
259
260   std::unique_ptr<const MCObjectFileInfo> MOFI(new MCObjectFileInfo);
261   MCContext Ctx(AsmInfo.get(), MRI.get(), MOFI.get());
262
263   std::unique_ptr<MCDisassembler> DisAsm(
264     TheTarget->createMCDisassembler(*STI, Ctx));
265
266   if (!DisAsm) {
267     errs() << "error: no disassembler for target " << TripleName << "\n";
268     return;
269   }
270
271   std::unique_ptr<const MCInstrAnalysis> MIA(
272       TheTarget->createMCInstrAnalysis(MII.get()));
273
274   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
275   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
276       AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
277   if (!IP) {
278     errs() << "error: no instruction printer for target " << TripleName
279       << '\n';
280     return;
281   }
282
283   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "\t\t%016" PRIx64 ":  " :
284                                                  "\t\t\t%08" PRIx64 ":  ";
285
286   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
287   // in RelocSecs contain the relocations for section S.
288   std::error_code EC;
289   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
290   for (const SectionRef &Section : Obj->sections()) {
291     section_iterator Sec2 = Section.getRelocatedSection();
292     if (Sec2 != Obj->section_end())
293       SectionRelocMap[*Sec2].push_back(Section);
294   }
295
296   for (const SectionRef &Section : Obj->sections()) {
297     bool Text;
298     if (error(Section.isText(Text)))
299       break;
300     if (!Text)
301       continue;
302
303     uint64_t SectionAddr;
304     if (error(Section.getAddress(SectionAddr)))
305       break;
306
307     uint64_t SectSize;
308     if (error(Section.getSize(SectSize)))
309       break;
310
311     // Make a list of all the symbols in this section.
312     std::vector<std::pair<uint64_t, StringRef>> Symbols;
313     for (const SymbolRef &Symbol : Obj->symbols()) {
314       bool contains;
315       if (!error(Section.containsSymbol(Symbol, contains)) && contains) {
316         uint64_t Address;
317         if (error(Symbol.getAddress(Address)))
318           break;
319         if (Address == UnknownAddressOrSize)
320           continue;
321         Address -= SectionAddr;
322         if (Address >= SectSize)
323           continue;
324
325         StringRef Name;
326         if (error(Symbol.getName(Name)))
327           break;
328         Symbols.push_back(std::make_pair(Address, Name));
329       }
330     }
331
332     // Sort the symbols by address, just in case they didn't come in that way.
333     array_pod_sort(Symbols.begin(), Symbols.end());
334
335     // Make a list of all the relocations for this section.
336     std::vector<RelocationRef> Rels;
337     if (InlineRelocs) {
338       for (const SectionRef &RelocSec : SectionRelocMap[Section]) {
339         for (const RelocationRef &Reloc : RelocSec.relocations()) {
340           Rels.push_back(Reloc);
341         }
342       }
343     }
344
345     // Sort relocations by address.
346     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
347
348     StringRef SegmentName = "";
349     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
350       DataRefImpl DR = Section.getRawDataRefImpl();
351       SegmentName = MachO->getSectionFinalSegmentName(DR);
352     }
353     StringRef name;
354     if (error(Section.getName(name)))
355       break;
356     outs() << "Disassembly of section ";
357     if (!SegmentName.empty())
358       outs() << SegmentName << ",";
359     outs() << name << ':';
360
361     // If the section has no symbols just insert a dummy one and disassemble
362     // the whole section.
363     if (Symbols.empty())
364       Symbols.push_back(std::make_pair(0, name));
365
366
367     SmallString<40> Comments;
368     raw_svector_ostream CommentStream(Comments);
369
370     StringRef Bytes;
371     if (error(Section.getContents(Bytes)))
372       break;
373     StringRefMemoryObject memoryObject(Bytes, SectionAddr);
374     uint64_t Size;
375     uint64_t Index;
376
377     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
378     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
379     // Disassemble symbol by symbol.
380     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
381
382       uint64_t Start = Symbols[si].first;
383       // The end is either the section end or the beginning of the next symbol.
384       uint64_t End = (si == se - 1) ? SectSize : Symbols[si + 1].first;
385       // If this symbol has the same address as the next symbol, then skip it.
386       if (Start == End)
387         continue;
388
389       outs() << '\n' << Symbols[si].second << ":\n";
390
391 #ifndef NDEBUG
392       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
393 #else
394       raw_ostream &DebugOut = nulls();
395 #endif
396
397       for (Index = Start; Index < End; Index += Size) {
398         MCInst Inst;
399
400         if (DisAsm->getInstruction(Inst, Size, memoryObject,
401                                    SectionAddr + Index,
402                                    DebugOut, CommentStream)) {
403           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
404           if (!NoShowRawInsn) {
405             outs() << "\t";
406             DumpBytes(StringRef(Bytes.data() + Index, Size));
407           }
408           IP->printInst(&Inst, outs(), "");
409           outs() << CommentStream.str();
410           Comments.clear();
411           outs() << "\n";
412         } else {
413           errs() << ToolName << ": warning: invalid instruction encoding\n";
414           if (Size == 0)
415             Size = 1; // skip illegible bytes
416         }
417
418         // Print relocation for instruction.
419         while (rel_cur != rel_end) {
420           bool hidden = false;
421           uint64_t addr;
422           SmallString<16> name;
423           SmallString<32> val;
424
425           // If this relocation is hidden, skip it.
426           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
427           if (hidden) goto skip_print_rel;
428
429           if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
430           // Stop when rel_cur's address is past the current instruction.
431           if (addr >= Index + Size) break;
432           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
433           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
434
435           outs() << format(Fmt.data(), SectionAddr + addr) << name
436                  << "\t" << val << "\n";
437
438         skip_print_rel:
439           ++rel_cur;
440         }
441       }
442     }
443   }
444 }
445
446 static void PrintRelocations(const ObjectFile *Obj) {
447   StringRef Fmt = Obj->getBytesInAddress() > 4 ? "%016" PRIx64 :
448                                                  "%08" PRIx64;
449   // Regular objdump doesn't print relocations in non-relocatable object
450   // files.
451   if (!Obj->isRelocatableObject())
452     return;
453
454   for (const SectionRef &Section : Obj->sections()) {
455     if (Section.relocation_begin() == Section.relocation_end())
456       continue;
457     StringRef secname;
458     if (error(Section.getName(secname)))
459       continue;
460     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
461     for (const RelocationRef &Reloc : Section.relocations()) {
462       bool hidden;
463       uint64_t address;
464       SmallString<32> relocname;
465       SmallString<32> valuestr;
466       if (error(Reloc.getHidden(hidden)))
467         continue;
468       if (hidden)
469         continue;
470       if (error(Reloc.getTypeName(relocname)))
471         continue;
472       if (error(Reloc.getOffset(address)))
473         continue;
474       if (error(Reloc.getValueString(valuestr)))
475         continue;
476       outs() << format(Fmt.data(), address) << " " << relocname << " "
477              << valuestr << "\n";
478     }
479     outs() << "\n";
480   }
481 }
482
483 static void PrintSectionHeaders(const ObjectFile *Obj) {
484   outs() << "Sections:\n"
485             "Idx Name          Size      Address          Type\n";
486   unsigned i = 0;
487   for (const SectionRef &Section : Obj->sections()) {
488     StringRef Name;
489     if (error(Section.getName(Name)))
490       return;
491     uint64_t Address;
492     if (error(Section.getAddress(Address)))
493       return;
494     uint64_t Size;
495     if (error(Section.getSize(Size)))
496       return;
497     bool Text, Data, BSS;
498     if (error(Section.isText(Text)))
499       return;
500     if (error(Section.isData(Data)))
501       return;
502     if (error(Section.isBSS(BSS)))
503       return;
504     std::string Type = (std::string(Text ? "TEXT " : "") +
505                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
506     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
507                      Name.str().c_str(), Size, Address, Type.c_str());
508     ++i;
509   }
510 }
511
512 static void PrintSectionContents(const ObjectFile *Obj) {
513   std::error_code EC;
514   for (const SectionRef &Section : Obj->sections()) {
515     StringRef Name;
516     StringRef Contents;
517     uint64_t BaseAddr;
518     bool BSS;
519     if (error(Section.getName(Name)))
520       continue;
521     if (error(Section.getAddress(BaseAddr)))
522       continue;
523     if (error(Section.isBSS(BSS)))
524       continue;
525
526     outs() << "Contents of section " << Name << ":\n";
527     if (BSS) {
528       uint64_t Size;
529       if (error(Section.getSize(Size)))
530         continue;
531       outs() << format("<skipping contents of bss section at [%04" PRIx64
532                        ", %04" PRIx64 ")>\n",
533                        BaseAddr, BaseAddr + Size);
534       continue;
535     }
536
537     if (error(Section.getContents(Contents)))
538       continue;
539
540     // Dump out the content as hex and printable ascii characters.
541     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
542       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
543       // Dump line of hex.
544       for (std::size_t i = 0; i < 16; ++i) {
545         if (i != 0 && i % 4 == 0)
546           outs() << ' ';
547         if (addr + i < end)
548           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
549                  << hexdigit(Contents[addr + i] & 0xF, true);
550         else
551           outs() << "  ";
552       }
553       // Print ascii.
554       outs() << "  ";
555       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
556         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
557           outs() << Contents[addr + i];
558         else
559           outs() << ".";
560       }
561       outs() << "\n";
562     }
563   }
564 }
565
566 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
567   const coff_file_header *header;
568   if (error(coff->getHeader(header)))
569     return;
570
571   for (unsigned SI = 0, SE = header->NumberOfSymbols; SI != SE; ++SI) {
572     const coff_symbol *Symbol;
573     StringRef Name;
574     if (error(coff->getSymbol(SI, Symbol)))
575       return;
576
577     if (error(coff->getSymbolName(Symbol, Name)))
578       return;
579
580     outs() << "[" << format("%2d", SI) << "]"
581            << "(sec " << format("%2d", int(Symbol->SectionNumber)) << ")"
582            << "(fl 0x00)" // Flag bits, which COFF doesn't have.
583            << "(ty " << format("%3x", unsigned(Symbol->Type)) << ")"
584            << "(scl " << format("%3x", unsigned(Symbol->StorageClass)) << ") "
585            << "(nx " << unsigned(Symbol->NumberOfAuxSymbols) << ") "
586            << "0x" << format("%08x", unsigned(Symbol->Value)) << " "
587            << Name << "\n";
588
589     for (unsigned AI = 0, AE = Symbol->NumberOfAuxSymbols; AI < AE; ++AI, ++SI) {
590       if (Symbol->isSectionDefinition()) {
591         const coff_aux_section_definition *asd;
592         if (error(coff->getAuxSymbol<coff_aux_section_definition>(SI + 1, asd)))
593           return;
594
595         outs() << "AUX "
596                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
597                          , unsigned(asd->Length)
598                          , unsigned(asd->NumberOfRelocations)
599                          , unsigned(asd->NumberOfLinenumbers)
600                          , unsigned(asd->CheckSum))
601                << format("assoc %d comdat %d\n"
602                          , unsigned(asd->Number)
603                          , unsigned(asd->Selection));
604       } else if (Symbol->isFileRecord()) {
605         const coff_aux_file *AF;
606         if (error(coff->getAuxSymbol<coff_aux_file>(SI + 1, AF)))
607           return;
608
609         StringRef Name(AF->FileName,
610                        Symbol->NumberOfAuxSymbols * COFF::SymbolSize);
611         outs() << "AUX " << Name.rtrim(StringRef("\0", 1))  << '\n';
612
613         SI = SI + Symbol->NumberOfAuxSymbols;
614         break;
615       } else {
616         outs() << "AUX Unknown\n";
617       }
618     }
619   }
620 }
621
622 static void PrintSymbolTable(const ObjectFile *o) {
623   outs() << "SYMBOL TABLE:\n";
624
625   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) {
626     PrintCOFFSymbolTable(coff);
627     return;
628   }
629   for (const SymbolRef &Symbol : o->symbols()) {
630     StringRef Name;
631     uint64_t Address;
632     SymbolRef::Type Type;
633     uint64_t Size;
634     uint32_t Flags = Symbol.getFlags();
635     section_iterator Section = o->section_end();
636     if (error(Symbol.getName(Name)))
637       continue;
638     if (error(Symbol.getAddress(Address)))
639       continue;
640     if (error(Symbol.getType(Type)))
641       continue;
642     if (error(Symbol.getSize(Size)))
643       continue;
644     if (error(Symbol.getSection(Section)))
645       continue;
646
647     bool Global = Flags & SymbolRef::SF_Global;
648     bool Weak = Flags & SymbolRef::SF_Weak;
649     bool Absolute = Flags & SymbolRef::SF_Absolute;
650
651     if (Address == UnknownAddressOrSize)
652       Address = 0;
653     if (Size == UnknownAddressOrSize)
654       Size = 0;
655     char GlobLoc = ' ';
656     if (Type != SymbolRef::ST_Unknown)
657       GlobLoc = Global ? 'g' : 'l';
658     char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
659                  ? 'd' : ' ';
660     char FileFunc = ' ';
661     if (Type == SymbolRef::ST_File)
662       FileFunc = 'f';
663     else if (Type == SymbolRef::ST_Function)
664       FileFunc = 'F';
665
666     const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
667                                                    "%08" PRIx64;
668
669     outs() << format(Fmt, Address) << " "
670            << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
671            << (Weak ? 'w' : ' ') // Weak?
672            << ' ' // Constructor. Not supported yet.
673            << ' ' // Warning. Not supported yet.
674            << ' ' // Indirect reference to another symbol.
675            << Debug // Debugging (d) or dynamic (D) symbol.
676            << FileFunc // Name of function (F), file (f) or object (O).
677            << ' ';
678     if (Absolute) {
679       outs() << "*ABS*";
680     } else if (Section == o->section_end()) {
681       outs() << "*UND*";
682     } else {
683       if (const MachOObjectFile *MachO =
684           dyn_cast<const MachOObjectFile>(o)) {
685         DataRefImpl DR = Section->getRawDataRefImpl();
686         StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
687         outs() << SegmentName << ",";
688       }
689       StringRef SectionName;
690       if (error(Section->getName(SectionName)))
691         SectionName = "";
692       outs() << SectionName;
693     }
694     outs() << '\t'
695            << format("%08" PRIx64 " ", Size)
696            << Name
697            << '\n';
698   }
699 }
700
701 static void PrintUnwindInfo(const ObjectFile *o) {
702   outs() << "Unwind info:\n\n";
703
704   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
705     printCOFFUnwindInfo(coff);
706   } else if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
707     printMachOUnwindInfo(MachO);
708   else {
709     // TODO: Extract DWARF dump tool to objdump.
710     errs() << "This operation is only currently supported "
711               "for COFF and MachO object files.\n";
712     return;
713   }
714 }
715
716 static void printExportsTrie(const ObjectFile *o) {
717   outs() << "Exports trie:\n";
718   if (const MachOObjectFile *MachO = dyn_cast<MachOObjectFile>(o))
719     printMachOExportsTrie(MachO);
720   else {
721     errs() << "This operation is only currently supported "
722               "for Mach-O executable files.\n";
723     return;
724   }
725 }
726
727 static void printPrivateFileHeader(const ObjectFile *o) {
728   if (o->isELF()) {
729     printELFFileHeader(o);
730   } else if (o->isCOFF()) {
731     printCOFFFileHeader(o);
732   } else if (o->isMachO()) {
733     printMachOFileHeader(o);
734   }
735 }
736
737 static void DumpObject(const ObjectFile *o) {
738   outs() << '\n';
739   outs() << o->getFileName()
740          << ":\tfile format " << o->getFileFormatName() << "\n\n";
741
742   if (Disassemble)
743     DisassembleObject(o, Relocations);
744   if (Relocations && !Disassemble)
745     PrintRelocations(o);
746   if (SectionHeaders)
747     PrintSectionHeaders(o);
748   if (SectionContents)
749     PrintSectionContents(o);
750   if (SymbolTable)
751     PrintSymbolTable(o);
752   if (UnwindInfo)
753     PrintUnwindInfo(o);
754   if (PrivateHeaders)
755     printPrivateFileHeader(o);
756   if (ExportsTrie)
757     printExportsTrie(o);
758 }
759
760 /// @brief Dump each object file in \a a;
761 static void DumpArchive(const Archive *a) {
762   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
763        ++i) {
764     ErrorOr<std::unique_ptr<Binary>> ChildOrErr = i->getAsBinary();
765     if (std::error_code EC = ChildOrErr.getError()) {
766       // Ignore non-object files.
767       if (EC != object_error::invalid_file_type)
768         errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
769                << ".\n";
770       continue;
771     }
772     if (ObjectFile *o = dyn_cast<ObjectFile>(&*ChildOrErr.get()))
773       DumpObject(o);
774     else
775       errs() << ToolName << ": '" << a->getFileName() << "': "
776               << "Unrecognized file type.\n";
777   }
778 }
779
780 /// @brief Open file and figure out how to dump it.
781 static void DumpInput(StringRef file) {
782   // If file isn't stdin, check that it exists.
783   if (file != "-" && !sys::fs::exists(file)) {
784     errs() << ToolName << ": '" << file << "': " << "No such file\n";
785     return;
786   }
787
788   if (MachOOpt && Disassemble) {
789     DisassembleInputMachO(file);
790     return;
791   }
792
793   // Attempt to open the binary.
794   ErrorOr<OwningBinary<Binary>> BinaryOrErr = createBinary(file);
795   if (std::error_code EC = BinaryOrErr.getError()) {
796     errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
797     return;
798   }
799   Binary &Binary = *BinaryOrErr.get().getBinary();
800
801   if (Archive *a = dyn_cast<Archive>(&Binary))
802     DumpArchive(a);
803   else if (ObjectFile *o = dyn_cast<ObjectFile>(&Binary))
804     DumpObject(o);
805   else
806     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
807 }
808
809 int main(int argc, char **argv) {
810   // Print a stack trace if we signal out.
811   sys::PrintStackTraceOnErrorSignal();
812   PrettyStackTraceProgram X(argc, argv);
813   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
814
815   // Initialize targets and assembly printers/parsers.
816   llvm::InitializeAllTargetInfos();
817   llvm::InitializeAllTargetMCs();
818   llvm::InitializeAllAsmParsers();
819   llvm::InitializeAllDisassemblers();
820
821   // Register the target printer for --version.
822   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
823
824   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
825   TripleName = Triple::normalize(TripleName);
826
827   ToolName = argv[0];
828
829   // Defaults to a.out if no filenames specified.
830   if (InputFilenames.size() == 0)
831     InputFilenames.push_back("a.out");
832
833   if (!Disassemble
834       && !Relocations
835       && !SectionHeaders
836       && !SectionContents
837       && !SymbolTable
838       && !UnwindInfo
839       && !PrivateHeaders
840       && !ExportsTrie) {
841     cl::PrintHelpMessage();
842     return 2;
843   }
844
845   std::for_each(InputFilenames.begin(), InputFilenames.end(),
846                 DumpInput);
847
848   return 0;
849 }