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