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