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