xref: /llvm-project/llvm/tools/llvm-objdump/llvm-objdump.cpp (revision fe6e405e8c8a7f75996ef44e4e7ad77c1261dc7a)
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 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Object/ObjectFile.h"
17 // This config must be included before llvm-config.h.
18 #include "llvm/Config/config.h"
19 #include "../../lib/MC/MCDisassembler/EDDisassembler.h"
20 #include "../../lib/MC/MCDisassembler/EDInst.h"
21 #include "../../lib/MC/MCDisassembler/EDOperand.h"
22 #include "../../lib/MC/MCDisassembler/EDToken.h"
23 #include "llvm/ADT/OwningPtr.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/Host.h"
33 #include "llvm/Support/ManagedStatic.h"
34 #include "llvm/Support/MemoryBuffer.h"
35 #include "llvm/Support/MemoryObject.h"
36 #include "llvm/Support/PrettyStackTrace.h"
37 #include "llvm/Support/Signals.h"
38 #include "llvm/Support/SourceMgr.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/Support/system_error.h"
41 #include "llvm/Target/TargetMachine.h"
42 #include "llvm/Target/TargetRegistry.h"
43 #include "llvm/Target/TargetSelect.h"
44 #include <algorithm>
45 #include <cctype>
46 #include <cerrno>
47 #include <cstring>
48 using namespace llvm;
49 using namespace object;
50 
51 namespace {
52   cl::list<std::string>
53   InputFilenames(cl::Positional, cl::desc("<input object files>"),
54                  cl::ZeroOrMore);
55 
56   cl::opt<bool>
57   Disassemble("disassemble",
58     cl::desc("Display assembler mnemonics for the machine instructions"));
59   cl::alias
60   Disassembled("d", cl::desc("Alias for --disassemble"),
61                cl::aliasopt(Disassemble));
62 
63   cl::opt<std::string>
64   TripleName("triple", cl::desc("Target triple to disassemble for, "
65                                 "see -version for available targets"));
66 
67   cl::opt<std::string>
68   ArchName("arch", cl::desc("Target arch to disassemble for, "
69                             "see -version for available targets"));
70 
71   StringRef ToolName;
72 
73   bool error(error_code ec) {
74     if (!ec) return false;
75 
76     outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
77     outs().flush();
78     return true;
79   }
80 }
81 
82 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
83   // Figure out the target triple.
84   llvm::Triple TT("unknown-unknown-unknown");
85   if (TripleName.empty()) {
86     if (Obj)
87       TT.setArch(Triple::ArchType(Obj->getArch()));
88   } else
89     TT.setTriple(Triple::normalize(TripleName));
90 
91   if (!ArchName.empty())
92     TT.setArchName(ArchName);
93 
94   TripleName = TT.str();
95 
96   // Get the target specific parser.
97   std::string Error;
98   const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
99   if (TheTarget)
100     return TheTarget;
101 
102   errs() << ToolName << ": error: unable to get target for '" << TripleName
103          << "', see --version and --triple.\n";
104   return 0;
105 }
106 
107 namespace {
108 class StringRefMemoryObject : public MemoryObject {
109 private:
110   StringRef Bytes;
111 public:
112   StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
113 
114   uint64_t getBase() const { return 0; }
115   uint64_t getExtent() const { return Bytes.size(); }
116 
117   int readByte(uint64_t Addr, uint8_t *Byte) const {
118     if (Addr > getExtent())
119       return -1;
120     *Byte = Bytes[Addr];
121     return 0;
122   }
123 };
124 }
125 
126 static void DumpBytes(StringRef bytes) {
127   static char hex_rep[] = "0123456789abcdef";
128   // FIXME: The real way to do this is to figure out the longest instruction
129   //        and align to that size before printing. I'll fix this when I get
130   //        around to outputting relocations.
131   // 15 is the longest x86 instruction
132   // 3 is for the hex rep of a byte + a space.
133   // 1 is for the null terminator.
134   enum { OutputSize = (15 * 3) + 1 };
135   char output[OutputSize];
136 
137   assert(bytes.size() <= 15
138     && "DumpBytes only supports instructions of up to 15 bytes");
139   memset(output, ' ', sizeof(output));
140   unsigned index = 0;
141   for (StringRef::iterator i = bytes.begin(),
142                            e = bytes.end(); i != e; ++i) {
143     output[index] = hex_rep[(*i & 0xF0) >> 4];
144     output[index + 1] = hex_rep[*i & 0xF];
145     index += 3;
146   }
147 
148   output[sizeof(output) - 1] = 0;
149   outs() << output;
150 }
151 
152 static void DisassembleInput(const StringRef &Filename) {
153   OwningPtr<MemoryBuffer> Buff;
154 
155   if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
156     errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
157     return;
158   }
159 
160   OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
161 
162   const Target *TheTarget = GetTarget(Obj.get());
163   if (!TheTarget) {
164     // GetTarget prints out stuff.
165     return;
166   }
167 
168   outs() << '\n';
169   outs() << Filename
170          << ":\tfile format " << Obj->getFileFormatName() << "\n\n\n";
171 
172   error_code ec;
173   for (ObjectFile::section_iterator i = Obj->begin_sections(),
174                                     e = Obj->end_sections();
175                                     i != e; i.increment(ec)) {
176     if (error(ec)) break;
177     bool text;
178     if (error(i->isText(text))) break;
179     if (!text) continue;
180 
181     StringRef name;
182     if (error(i->getName(name))) break;
183     outs() << "Disassembly of section " << name << ":\n\n";
184 
185     // Set up disassembler.
186     OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createAsmInfo(TripleName));
187 
188     if (!AsmInfo) {
189       errs() << "error: no assembly info for target " << TripleName << "\n";
190       return;
191     }
192 
193     OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
194     if (!DisAsm) {
195       errs() << "error: no disassembler for target " << TripleName << "\n";
196       return;
197     }
198 
199     // FIXME: We shouldn't need to do this (and link in codegen).
200     //        When we split this out, we should do it in a way that makes
201     //        it straightforward to switch subtargets on the fly (.e.g,
202     //        the .cpu and .code16 directives).
203     std::string FeaturesStr;
204     std::string CPU;
205     OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, CPU,
206                                                                FeaturesStr));
207     if (!TM) {
208       errs() << "error: could not create target for triple " << TripleName << "\n";
209       return;
210     }
211 
212     int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
213     OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
214                                   *TM, AsmPrinterVariant, *AsmInfo));
215     if (!IP) {
216       errs() << "error: no instruction printer for target " << TripleName << '\n';
217       return;
218     }
219 
220     StringRef Bytes;
221     if (error(i->getContents(Bytes))) break;
222     StringRefMemoryObject memoryObject(Bytes);
223     uint64_t Size;
224     uint64_t Index;
225 
226     for (Index = 0; Index < Bytes.size(); Index += Size) {
227       MCInst Inst;
228 
229 #     ifndef NDEBUG
230       raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
231 #     else
232       raw_ostream &DebugOut = nulls();
233 #     endif
234 
235       if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut)) {
236         uint64_t addr;
237         if (error(i->getAddress(addr))) break;
238         outs() << format("%8x:\t", addr + Index);
239         DumpBytes(StringRef(Bytes.data() + Index, Size));
240         IP->printInst(&Inst, outs());
241         outs() << "\n";
242       } else {
243         errs() << ToolName << ": warning: invalid instruction encoding\n";
244         if (Size == 0)
245           Size = 1; // skip illegible bytes
246       }
247     }
248   }
249 }
250 
251 int main(int argc, char **argv) {
252   // Print a stack trace if we signal out.
253   sys::PrintStackTraceOnErrorSignal();
254   PrettyStackTraceProgram X(argc, argv);
255   llvm_shutdown_obj Y;  // Call llvm_shutdown() on exit.
256 
257   // Initialize targets and assembly printers/parsers.
258   llvm::InitializeAllTargetInfos();
259   // FIXME: We shouldn't need to initialize the Target(Machine)s.
260   llvm::InitializeAllTargets();
261   llvm::InitializeAllAsmPrinters();
262   llvm::InitializeAllAsmParsers();
263   llvm::InitializeAllDisassemblers();
264 
265   cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
266   TripleName = Triple::normalize(TripleName);
267 
268   ToolName = argv[0];
269 
270   // Defaults to a.out if no filenames specified.
271   if (InputFilenames.size() == 0)
272     InputFilenames.push_back("a.out");
273 
274   // -d is the only flag that is currently implemented, so just print help if
275   // it is not set.
276   if (!Disassemble) {
277     cl::PrintHelpMessage();
278     return 2;
279   }
280 
281   std::for_each(InputFilenames.begin(), InputFilenames.end(),
282                 DisassembleInput);
283 
284   return 0;
285 }
286