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