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