blob: 4079e4aabe60a5ae579c9a82430576447210f9c7 [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"
Benjamin Kramer739b65b2011-07-15 18:39:24 +000019#include "llvm/ADT/STLExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000020#include "llvm/MC/MCAsmInfo.h"
21#include "llvm/MC/MCDisassembler.h"
22#include "llvm/MC/MCInst.h"
23#include "llvm/MC/MCInstPrinter.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
26#include "llvm/Support/Format.h"
27#include "llvm/Support/Host.h"
28#include "llvm/Support/ManagedStatic.h"
29#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000030#include "llvm/Support/MemoryObject.h"
31#include "llvm/Support/PrettyStackTrace.h"
32#include "llvm/Support/Signals.h"
33#include "llvm/Support/SourceMgr.h"
34#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000035#include "llvm/Support/system_error.h"
36#include "llvm/Target/TargetRegistry.h"
37#include "llvm/Target/TargetSelect.h"
38#include <algorithm>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000039#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000040using namespace llvm;
41using namespace object;
42
43namespace {
44 cl::list<std::string>
45 InputFilenames(cl::Positional, cl::desc("<input object files>"),
46 cl::ZeroOrMore);
47
48 cl::opt<bool>
49 Disassemble("disassemble",
50 cl::desc("Display assembler mnemonics for the machine instructions"));
51 cl::alias
52 Disassembled("d", cl::desc("Alias for --disassemble"),
53 cl::aliasopt(Disassemble));
54
55 cl::opt<std::string>
56 TripleName("triple", cl::desc("Target triple to disassemble for, "
57 "see -version for available targets"));
58
59 cl::opt<std::string>
60 ArchName("arch", cl::desc("Target arch to disassemble for, "
61 "see -version for available targets"));
62
63 StringRef ToolName;
Michael J. Spencer25b15772011-06-25 17:55:23 +000064
65 bool error(error_code ec) {
66 if (!ec) return false;
67
68 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
69 outs().flush();
70 return true;
71 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000072}
73
74static const Target *GetTarget(const ObjectFile *Obj = NULL) {
75 // Figure out the target triple.
76 llvm::Triple TT("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +000077 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000078 if (Obj)
79 TT.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +000080 } else
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000081 TT.setTriple(Triple::normalize(TripleName));
82
83 if (!ArchName.empty())
84 TT.setArchName(ArchName);
85
86 TripleName = TT.str();
87
88 // Get the target specific parser.
89 std::string Error;
90 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
91 if (TheTarget)
92 return TheTarget;
93
94 errs() << ToolName << ": error: unable to get target for '" << TripleName
95 << "', see --version and --triple.\n";
96 return 0;
97}
98
99namespace {
100class StringRefMemoryObject : public MemoryObject {
101private:
102 StringRef Bytes;
103public:
104 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
105
106 uint64_t getBase() const { return 0; }
107 uint64_t getExtent() const { return Bytes.size(); }
108
109 int readByte(uint64_t Addr, uint8_t *Byte) const {
110 if (Addr > getExtent())
111 return -1;
112 *Byte = Bytes[Addr];
113 return 0;
114 }
115};
116}
117
118static void DumpBytes(StringRef bytes) {
119 static char hex_rep[] = "0123456789abcdef";
120 // FIXME: The real way to do this is to figure out the longest instruction
121 // and align to that size before printing. I'll fix this when I get
122 // around to outputting relocations.
123 // 15 is the longest x86 instruction
124 // 3 is for the hex rep of a byte + a space.
125 // 1 is for the null terminator.
126 enum { OutputSize = (15 * 3) + 1 };
127 char output[OutputSize];
128
129 assert(bytes.size() <= 15
130 && "DumpBytes only supports instructions of up to 15 bytes");
131 memset(output, ' ', sizeof(output));
132 unsigned index = 0;
133 for (StringRef::iterator i = bytes.begin(),
134 e = bytes.end(); i != e; ++i) {
135 output[index] = hex_rep[(*i & 0xF0) >> 4];
136 output[index + 1] = hex_rep[*i & 0xF];
137 index += 3;
138 }
139
140 output[sizeof(output) - 1] = 0;
141 outs() << output;
142}
143
144static void DisassembleInput(const StringRef &Filename) {
145 OwningPtr<MemoryBuffer> Buff;
146
147 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
148 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
149 return;
150 }
151
152 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
153
154 const Target *TheTarget = GetTarget(Obj.get());
155 if (!TheTarget) {
156 // GetTarget prints out stuff.
157 return;
158 }
159
160 outs() << '\n';
161 outs() << Filename
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000162 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000163
Michael J. Spencer25b15772011-06-25 17:55:23 +0000164 error_code ec;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000165 for (ObjectFile::section_iterator i = Obj->begin_sections(),
166 e = Obj->end_sections();
Michael J. Spencer25b15772011-06-25 17:55:23 +0000167 i != e; i.increment(ec)) {
168 if (error(ec)) break;
169 bool text;
170 if (error(i->isText(text))) break;
171 if (!text) continue;
172
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000173 // Make a list of all the symbols in this section.
174 std::vector<std::pair<uint64_t, StringRef> > Symbols;
175 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
176 se = Obj->end_symbols();
177 si != se; si.increment(ec)) {
178 bool contains;
179 if (!error(i->containsSymbol(*si, contains)) && contains) {
180 uint64_t Address;
181 if (error(si->getAddress(Address))) break;
182 StringRef Name;
183 if (error(si->getName(Name))) break;
184 Symbols.push_back(std::make_pair(Address, Name));
185 }
186 }
187
188 // Sort the symbols by address, just in case they didn't come in that way.
189 array_pod_sort(Symbols.begin(), Symbols.end());
190
Michael J. Spencer25b15772011-06-25 17:55:23 +0000191 StringRef name;
192 if (error(i->getName(name))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000193 outs() << "Disassembly of section " << name << ':';
194
195 // If the section has no symbols just insert a dummy one and disassemble
196 // the whole section.
197 if (Symbols.empty())
198 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000199
200 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000201 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000202
203 if (!AsmInfo) {
204 errs() << "error: no assembly info for target " << TripleName << "\n";
205 return;
206 }
207
208 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
209 if (!DisAsm) {
210 errs() << "error: no disassembler for target " << TripleName << "\n";
211 return;
212 }
213
214 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
215 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
Evan Chengb2627992011-07-06 19:45:42 +0000216 AsmPrinterVariant, *AsmInfo));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000217 if (!IP) {
218 errs() << "error: no instruction printer for target " << TripleName << '\n';
219 return;
220 }
221
Michael J. Spencer25b15772011-06-25 17:55:23 +0000222 StringRef Bytes;
223 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000224 StringRefMemoryObject memoryObject(Bytes);
225 uint64_t Size;
226 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000227 uint64_t SectSize;
228 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000229
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000230 // Disassemble symbol by symbol.
231 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
232 uint64_t Start = Symbols[si].first;
233 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
234 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000235
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000236 for (Index = Start; Index < End; Index += Size) {
237 MCInst Inst;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000238
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000239#ifndef NDEBUG
240 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
241#else
242 raw_ostream &DebugOut = nulls();
243#endif
244
245 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut)) {
246 uint64_t addr;
247 if (error(i->getAddress(addr))) break;
248 outs() << format("%8x:\t", addr + Index);
249 DumpBytes(StringRef(Bytes.data() + Index, Size));
250 IP->printInst(&Inst, outs());
251 outs() << "\n";
252 } else {
253 errs() << ToolName << ": warning: invalid instruction encoding\n";
254 if (Size == 0)
255 Size = 1; // skip illegible bytes
256 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000257 }
258 }
259 }
260}
261
262int main(int argc, char **argv) {
263 // Print a stack trace if we signal out.
264 sys::PrintStackTraceOnErrorSignal();
265 PrettyStackTraceProgram X(argc, argv);
266 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
267
268 // Initialize targets and assembly printers/parsers.
269 llvm::InitializeAllTargetInfos();
270 // FIXME: We shouldn't need to initialize the Target(Machine)s.
271 llvm::InitializeAllTargets();
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000272 llvm::InitializeAllMCAsmInfos();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000273 llvm::InitializeAllAsmPrinters();
274 llvm::InitializeAllAsmParsers();
275 llvm::InitializeAllDisassemblers();
276
277 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
278 TripleName = Triple::normalize(TripleName);
279
280 ToolName = argv[0];
281
282 // Defaults to a.out if no filenames specified.
283 if (InputFilenames.size() == 0)
284 InputFilenames.push_back("a.out");
285
286 // -d is the only flag that is currently implemented, so just print help if
287 // it is not set.
288 if (!Disassemble) {
289 cl::PrintHelpMessage();
290 return 2;
291 }
292
293 std::for_each(InputFilenames.begin(), InputFilenames.end(),
294 DisassembleInput);
295
296 return 0;
297}