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