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