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