7fa01f7633ef1f5bd26b97e6776adc2edbd60e5c
[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(), RelInfo, Obj));
329       if (Symzer)
330         DisAsm->setSymbolizer(std::move(Symzer));
331     }
332   }
333
334   std::unique_ptr<const MCInstrAnalysis> MIA(
335       TheTarget->createMCInstrAnalysis(MII.get()));
336
337   int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
338   std::unique_ptr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
339       AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
340   if (!IP) {
341     errs() << "error: no instruction printer for target " << TripleName
342       << '\n';
343     return;
344   }
345
346   if (CFG || !YAMLCFG.empty()) {
347     std::unique_ptr<MCObjectDisassembler> OD(
348         new MCObjectDisassembler(*Obj, *DisAsm, *MIA));
349     std::unique_ptr<MCModule> Mod(OD->buildModule(/* withCFG */ true));
350     for (MCModule::const_atom_iterator AI = Mod->atom_begin(),
351                                        AE = Mod->atom_end();
352                                        AI != AE; ++AI) {
353       outs() << "Atom " << (*AI)->getName() << ": \n";
354       if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) {
355         for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end();
356              II != IE;
357              ++II) {
358           IP->printInst(&II->Inst, outs(), "");
359           outs() << "\n";
360         }
361       }
362     }
363     if (CFG) {
364       for (MCModule::const_func_iterator FI = Mod->func_begin(),
365                                          FE = Mod->func_end();
366                                          FI != FE; ++FI) {
367         static int filenum = 0;
368         emitDOTFile((Twine((*FI)->getName()) + "_" +
369                      utostr(filenum) + ".dot").str().c_str(),
370                       **FI, IP.get());
371         ++filenum;
372       }
373     }
374     if (!YAMLCFG.empty()) {
375       std::string Error;
376       raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text);
377       if (!Error.empty()) {
378         errs() << ToolName << ": warning: " << Error << '\n';
379         return;
380       }
381       mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI);
382     }
383   }
384
385   // Create a mapping, RelocSecs = SectionRelocMap[S], where sections
386   // in RelocSecs contain the relocations for section S.
387   error_code EC;
388   std::map<SectionRef, SmallVector<SectionRef, 1>> SectionRelocMap;
389   for (const SectionRef &Section : Obj->sections()) {
390     section_iterator Sec2 = Section.getRelocatedSection();
391     if (Sec2 != Obj->section_end())
392       SectionRelocMap[*Sec2].push_back(Section);
393   }
394
395   for (const SectionRef &Section : Obj->sections()) {
396     bool Text;
397     if (error(Section.isText(Text)))
398       break;
399     if (!Text)
400       continue;
401
402     uint64_t SectionAddr;
403     if (error(Section.getAddress(SectionAddr)))
404       break;
405
406     uint64_t SectSize;
407     if (error(Section.getSize(SectSize)))
408       break;
409
410     // Make a list of all the symbols in this section.
411     std::vector<std::pair<uint64_t, StringRef> > Symbols;
412     for (symbol_iterator SI = Obj->symbol_begin(), SE = Obj->symbol_end();
413          SI != SE; ++SI) {
414       bool contains;
415       if (!error(Section.containsSymbol(*SI, contains)) && contains) {
416         uint64_t Address;
417         if (error(SI->getAddress(Address)))
418           break;
419         if (Address == UnknownAddressOrSize)
420           continue;
421         Address -= SectionAddr;
422         if (Address >= SectSize)
423           continue;
424
425         StringRef Name;
426         if (error(SI->getName(Name)))
427           break;
428         Symbols.push_back(std::make_pair(Address, Name));
429       }
430     }
431
432     // Sort the symbols by address, just in case they didn't come in that way.
433     array_pod_sort(Symbols.begin(), Symbols.end());
434
435     // Make a list of all the relocations for this section.
436     std::vector<RelocationRef> Rels;
437     if (InlineRelocs) {
438       SmallVectorImpl<SectionRef> *RelocSecs = &SectionRelocMap[Section];
439       for (SmallVectorImpl<SectionRef>::iterator RelocSec = RelocSecs->begin(),
440                                                  E = RelocSecs->end();
441            RelocSec != E; ++RelocSec) {
442         for (relocation_iterator RI = RelocSec->relocation_begin(),
443                                  RE = RelocSec->relocation_end();
444              RI != RE; ++RI)
445           Rels.push_back(*RI);
446       }
447     }
448
449     // Sort relocations by address.
450     std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
451
452     StringRef SegmentName = "";
453     if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
454       DataRefImpl DR = Section.getRawDataRefImpl();
455       SegmentName = MachO->getSectionFinalSegmentName(DR);
456     }
457     StringRef name;
458     if (error(Section.getName(name)))
459       break;
460     outs() << "Disassembly of section ";
461     if (!SegmentName.empty())
462       outs() << SegmentName << ",";
463     outs() << name << ':';
464
465     // If the section has no symbols just insert a dummy one and disassemble
466     // the whole section.
467     if (Symbols.empty())
468       Symbols.push_back(std::make_pair(0, name));
469
470
471     SmallString<40> Comments;
472     raw_svector_ostream CommentStream(Comments);
473
474     StringRef Bytes;
475     if (error(Section.getContents(Bytes)))
476       break;
477     StringRefMemoryObject memoryObject(Bytes, SectionAddr);
478     uint64_t Size;
479     uint64_t Index;
480
481     std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
482     std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
483     // Disassemble symbol by symbol.
484     for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
485       uint64_t Start = Symbols[si].first;
486       uint64_t End;
487       // The end is either the size of the section or the beginning of the next
488       // symbol.
489       if (si == se - 1)
490         End = SectSize;
491       // Make sure this symbol takes up space.
492       else if (Symbols[si + 1].first != Start)
493         End = Symbols[si + 1].first - 1;
494       else
495         // This symbol has the same address as the next symbol. Skip it.
496         continue;
497
498       outs() << '\n' << Symbols[si].second << ":\n";
499
500 #ifndef NDEBUG
501       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
502 #else
503       raw_ostream &DebugOut = nulls();
504 #endif
505
506       for (Index = Start; Index < End; Index += Size) {
507         MCInst Inst;
508
509         if (DisAsm->getInstruction(Inst, Size, memoryObject,
510                                    SectionAddr + Index,
511                                    DebugOut, CommentStream)) {
512           outs() << format("%8" PRIx64 ":", SectionAddr + Index);
513           if (!NoShowRawInsn) {
514             outs() << "\t";
515             DumpBytes(StringRef(Bytes.data() + Index, Size));
516           }
517           IP->printInst(&Inst, outs(), "");
518           outs() << CommentStream.str();
519           Comments.clear();
520           outs() << "\n";
521         } else {
522           errs() << ToolName << ": warning: invalid instruction encoding\n";
523           if (Size == 0)
524             Size = 1; // skip illegible bytes
525         }
526
527         // Print relocation for instruction.
528         while (rel_cur != rel_end) {
529           bool hidden = false;
530           uint64_t addr;
531           SmallString<16> name;
532           SmallString<32> val;
533
534           // If this relocation is hidden, skip it.
535           if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
536           if (hidden) goto skip_print_rel;
537
538           if (error(rel_cur->getOffset(addr))) goto skip_print_rel;
539           // Stop when rel_cur's address is past the current instruction.
540           if (addr >= Index + Size) break;
541           if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
542           if (error(rel_cur->getValueString(val))) goto skip_print_rel;
543
544           outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
545                  << "\t" << val << "\n";
546
547         skip_print_rel:
548           ++rel_cur;
549         }
550       }
551     }
552   }
553 }
554
555 static void PrintRelocations(const ObjectFile *Obj) {
556   for (const SectionRef &Section : Obj->sections()) {
557     if (Section.relocation_begin() == Section.relocation_end())
558       continue;
559     StringRef secname;
560     if (error(Section.getName(secname)))
561       continue;
562     outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
563     for (relocation_iterator ri = Section.relocation_begin(),
564                              re = Section.relocation_end();
565          ri != re; ++ri) {
566       bool hidden;
567       uint64_t address;
568       SmallString<32> relocname;
569       SmallString<32> valuestr;
570       if (error(ri->getHidden(hidden))) continue;
571       if (hidden) continue;
572       if (error(ri->getTypeName(relocname))) continue;
573       if (error(ri->getOffset(address))) continue;
574       if (error(ri->getValueString(valuestr))) continue;
575       outs() << address << " " << relocname << " " << valuestr << "\n";
576     }
577     outs() << "\n";
578   }
579 }
580
581 static void PrintSectionHeaders(const ObjectFile *Obj) {
582   outs() << "Sections:\n"
583             "Idx Name          Size      Address          Type\n";
584   unsigned i = 0;
585   for (const SectionRef &Section : Obj->sections()) {
586     StringRef Name;
587     if (error(Section.getName(Name)))
588       return;
589     uint64_t Address;
590     if (error(Section.getAddress(Address)))
591       return;
592     uint64_t Size;
593     if (error(Section.getSize(Size)))
594       return;
595     bool Text, Data, BSS;
596     if (error(Section.isText(Text)))
597       return;
598     if (error(Section.isData(Data)))
599       return;
600     if (error(Section.isBSS(BSS)))
601       return;
602     std::string Type = (std::string(Text ? "TEXT " : "") +
603                         (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
604     outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", i,
605                      Name.str().c_str(), Size, Address, Type.c_str());
606     ++i;
607   }
608 }
609
610 static void PrintSectionContents(const ObjectFile *Obj) {
611   error_code EC;
612   for (const SectionRef &Section : Obj->sections()) {
613     StringRef Name;
614     StringRef Contents;
615     uint64_t BaseAddr;
616     bool BSS;
617     if (error(Section.getName(Name)))
618       continue;
619     if (error(Section.getContents(Contents)))
620       continue;
621     if (error(Section.getAddress(BaseAddr)))
622       continue;
623     if (error(Section.isBSS(BSS)))
624       continue;
625
626     outs() << "Contents of section " << Name << ":\n";
627     if (BSS) {
628       outs() << format("<skipping contents of bss section at [%04" PRIx64
629                        ", %04" PRIx64 ")>\n", BaseAddr,
630                        BaseAddr + Contents.size());
631       continue;
632     }
633
634     // Dump out the content as hex and printable ascii characters.
635     for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
636       outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
637       // Dump line of hex.
638       for (std::size_t i = 0; i < 16; ++i) {
639         if (i != 0 && i % 4 == 0)
640           outs() << ' ';
641         if (addr + i < end)
642           outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
643                  << hexdigit(Contents[addr + i] & 0xF, true);
644         else
645           outs() << "  ";
646       }
647       // Print ascii.
648       outs() << "  ";
649       for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
650         if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
651           outs() << Contents[addr + i];
652         else
653           outs() << ".";
654       }
655       outs() << "\n";
656     }
657   }
658 }
659
660 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
661   const coff_file_header *header;
662   if (error(coff->getHeader(header))) return;
663   int aux_count = 0;
664   const coff_symbol *symbol = 0;
665   for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
666     if (aux_count--) {
667       // Figure out which type of aux this is.
668       if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
669           && symbol->Value == 0) { // Section definition.
670         const coff_aux_section_definition *asd;
671         if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
672           return;
673         outs() << "AUX "
674                << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
675                          , unsigned(asd->Length)
676                          , unsigned(asd->NumberOfRelocations)
677                          , unsigned(asd->NumberOfLinenumbers)
678                          , unsigned(asd->CheckSum))
679                << format("assoc %d comdat %d\n"
680                          , unsigned(asd->Number)
681                          , unsigned(asd->Selection));
682       } else
683         outs() << "AUX Unknown\n";
684     } else {
685       StringRef name;
686       if (error(coff->getSymbol(i, symbol))) return;
687       if (error(coff->getSymbolName(symbol, name))) return;
688       outs() << "[" << format("%2d", i) << "]"
689              << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
690              << "(fl 0x00)" // Flag bits, which COFF doesn't have.
691              << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
692              << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
693              << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
694              << "0x" << format("%08x", unsigned(symbol->Value)) << " "
695              << name << "\n";
696       aux_count = symbol->NumberOfAuxSymbols;
697     }
698   }
699 }
700
701 static void PrintSymbolTable(const ObjectFile *o) {
702   outs() << "SYMBOL TABLE:\n";
703
704   if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
705     PrintCOFFSymbolTable(coff);
706   else {
707     for (symbol_iterator si = o->symbol_begin(), se = o->symbol_end();
708          si != se; ++si) {
709       StringRef Name;
710       uint64_t Address;
711       SymbolRef::Type Type;
712       uint64_t Size;
713       uint32_t Flags = si->getFlags();
714       section_iterator Section = o->section_end();
715       if (error(si->getName(Name))) continue;
716       if (error(si->getAddress(Address))) continue;
717       if (error(si->getType(Type))) continue;
718       if (error(si->getSize(Size))) continue;
719       if (error(si->getSection(Section))) continue;
720
721       bool Global = Flags & SymbolRef::SF_Global;
722       bool Weak = Flags & SymbolRef::SF_Weak;
723       bool Absolute = Flags & SymbolRef::SF_Absolute;
724
725       if (Address == UnknownAddressOrSize)
726         Address = 0;
727       if (Size == UnknownAddressOrSize)
728         Size = 0;
729       char GlobLoc = ' ';
730       if (Type != SymbolRef::ST_Unknown)
731         GlobLoc = Global ? 'g' : 'l';
732       char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
733                    ? 'd' : ' ';
734       char FileFunc = ' ';
735       if (Type == SymbolRef::ST_File)
736         FileFunc = 'f';
737       else if (Type == SymbolRef::ST_Function)
738         FileFunc = 'F';
739
740       const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
741                                                      "%08" PRIx64;
742
743       outs() << format(Fmt, Address) << " "
744              << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
745              << (Weak ? 'w' : ' ') // Weak?
746              << ' ' // Constructor. Not supported yet.
747              << ' ' // Warning. Not supported yet.
748              << ' ' // Indirect reference to another symbol.
749              << Debug // Debugging (d) or dynamic (D) symbol.
750              << FileFunc // Name of function (F), file (f) or object (O).
751              << ' ';
752       if (Absolute)
753         outs() << "*ABS*";
754       else if (Section == o->section_end())
755         outs() << "*UND*";
756       else {
757         if (const MachOObjectFile *MachO =
758             dyn_cast<const MachOObjectFile>(o)) {
759           DataRefImpl DR = Section->getRawDataRefImpl();
760           StringRef SegmentName = MachO->getSectionFinalSegmentName(DR);
761           outs() << SegmentName << ",";
762         }
763         StringRef SectionName;
764         if (error(Section->getName(SectionName)))
765           SectionName = "";
766         outs() << SectionName;
767       }
768       outs() << '\t'
769              << format("%08" PRIx64 " ", Size)
770              << Name
771              << '\n';
772     }
773   }
774 }
775
776 static void PrintUnwindInfo(const ObjectFile *o) {
777   outs() << "Unwind info:\n\n";
778
779   if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
780     printCOFFUnwindInfo(coff);
781   } else {
782     // TODO: Extract DWARF dump tool to objdump.
783     errs() << "This operation is only currently supported "
784               "for COFF object files.\n";
785     return;
786   }
787 }
788
789 static void printPrivateFileHeader(const ObjectFile *o) {
790   if (o->isELF()) {
791     printELFFileHeader(o);
792   } else if (o->isCOFF()) {
793     printCOFFFileHeader(o);
794   }
795 }
796
797 static void DumpObject(const ObjectFile *o) {
798   outs() << '\n';
799   outs() << o->getFileName()
800          << ":\tfile format " << o->getFileFormatName() << "\n\n";
801
802   if (Disassemble)
803     DisassembleObject(o, Relocations);
804   if (Relocations && !Disassemble)
805     PrintRelocations(o);
806   if (SectionHeaders)
807     PrintSectionHeaders(o);
808   if (SectionContents)
809     PrintSectionContents(o);
810   if (SymbolTable)
811     PrintSymbolTable(o);
812   if (UnwindInfo)
813     PrintUnwindInfo(o);
814   if (PrivateHeaders)
815     printPrivateFileHeader(o);
816 }
817
818 /// @brief Dump each object file in \a a;
819 static void DumpArchive(const Archive *a) {
820   for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e;
821        ++i) {
822     std::unique_ptr<Binary> child;
823     if (error_code EC = i->getAsBinary(child)) {
824       // Ignore non-object files.
825       if (EC != object_error::invalid_file_type)
826         errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message()
827                << ".\n";
828       continue;
829     }
830     if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
831       DumpObject(o);
832     else
833       errs() << ToolName << ": '" << a->getFileName() << "': "
834               << "Unrecognized file type.\n";
835   }
836 }
837
838 /// @brief Open file and figure out how to dump it.
839 static void DumpInput(StringRef file) {
840   // If file isn't stdin, check that it exists.
841   if (file != "-" && !sys::fs::exists(file)) {
842     errs() << ToolName << ": '" << file << "': " << "No such file\n";
843     return;
844   }
845
846   if (MachOOpt && Disassemble) {
847     DisassembleInputMachO(file);
848     return;
849   }
850
851   // Attempt to open the binary.
852   ErrorOr<Binary *> BinaryOrErr = createBinary(file);
853   if (error_code EC = BinaryOrErr.getError()) {
854     errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n";
855     return;
856   }
857   std::unique_ptr<Binary> binary(BinaryOrErr.get());
858
859   if (Archive *a = dyn_cast<Archive>(binary.get()))
860     DumpArchive(a);
861   else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
862     DumpObject(o);
863   else
864     errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
865 }
866
867 int main(int argc, char **argv) {
868   // Print a stack trace if we signal out.
869   sys::PrintStackTraceOnErrorSignal();
870   PrettyStackTraceProgram X(argc, argv);
871   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
872
873   // Initialize targets and assembly printers/parsers.
874   llvm::InitializeAllTargetInfos();
875   llvm::InitializeAllTargetMCs();
876   llvm::InitializeAllAsmParsers();
877   llvm::InitializeAllDisassemblers();
878
879   // Register the target printer for --version.
880   cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
881
882   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
883   TripleName = Triple::normalize(TripleName);
884
885   ToolName = argv[0];
886
887   // Defaults to a.out if no filenames specified.
888   if (InputFilenames.size() == 0)
889     InputFilenames.push_back("a.out");
890
891   if (!Disassemble
892       && !Relocations
893       && !SectionHeaders
894       && !SectionContents
895       && !SymbolTable
896       && !UnwindInfo
897       && !PrivateHeaders) {
898     cl::PrintHelpMessage();
899     return 2;
900   }
901
902   std::for_each(InputFilenames.begin(), InputFilenames.end(),
903                 DumpInput);
904
905   return 0;
906 }