blob: 4cfd4f4164a8f3cbaf20ba1ffb6f120f46f0b39b [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
Benjamin Kramer685a2502011-07-20 19:37:35 +000016#include "MCFunction.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000017#include "llvm/Object/ObjectFile.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000018#include "llvm/ADT/OwningPtr.h"
19#include "llvm/ADT/Triple.h"
Benjamin Kramer739b65b2011-07-15 18:39:24 +000020#include "llvm/ADT/STLExtras.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000021#include "llvm/MC/MCAsmInfo.h"
22#include "llvm/MC/MCDisassembler.h"
23#include "llvm/MC/MCInst.h"
24#include "llvm/MC/MCInstPrinter.h"
Evan Cheng78011362011-08-23 20:15:21 +000025#include "llvm/MC/MCInstrAnalysis.h"
Benjamin Kramer685a2502011-07-20 19:37:35 +000026#include "llvm/MC/MCInstrDesc.h"
27#include "llvm/MC/MCInstrInfo.h"
James Molloyb9505852011-09-07 17:24:38 +000028#include "llvm/MC/MCSubtargetInfo.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000029#include "llvm/Support/CommandLine.h"
30#include "llvm/Support/Debug.h"
31#include "llvm/Support/Format.h"
Benjamin Kramer853b0fd2011-07-25 23:04:36 +000032#include "llvm/Support/GraphWriter.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000033#include "llvm/Support/Host.h"
34#include "llvm/Support/ManagedStatic.h"
35#include "llvm/Support/MemoryBuffer.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000036#include "llvm/Support/MemoryObject.h"
37#include "llvm/Support/PrettyStackTrace.h"
38#include "llvm/Support/Signals.h"
39#include "llvm/Support/SourceMgr.h"
Evan Cheng3e74d6f2011-08-24 18:08:43 +000040#include "llvm/Support/TargetRegistry.h"
41#include "llvm/Support/TargetSelect.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000042#include "llvm/Support/raw_ostream.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000043#include "llvm/Support/system_error.h"
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000044#include <algorithm>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000045#include <cstring>
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000046using namespace llvm;
47using namespace object;
48
49namespace {
50 cl::list<std::string>
51 InputFilenames(cl::Positional, cl::desc("<input object files>"),
52 cl::ZeroOrMore);
53
54 cl::opt<bool>
55 Disassemble("disassemble",
56 cl::desc("Display assembler mnemonics for the machine instructions"));
57 cl::alias
58 Disassembled("d", cl::desc("Alias for --disassemble"),
59 cl::aliasopt(Disassemble));
60
Benjamin Kramer685a2502011-07-20 19:37:35 +000061 cl::opt<bool>
62 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
63 "write it to a graphviz file"));
64
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000065 cl::opt<std::string>
66 TripleName("triple", cl::desc("Target triple to disassemble for, "
67 "see -version for available targets"));
68
69 cl::opt<std::string>
70 ArchName("arch", cl::desc("Target arch to disassemble for, "
71 "see -version for available targets"));
72
73 StringRef ToolName;
Michael J. Spencer25b15772011-06-25 17:55:23 +000074
75 bool error(error_code ec) {
76 if (!ec) return false;
77
78 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
79 outs().flush();
80 return true;
81 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000082}
83
84static const Target *GetTarget(const ObjectFile *Obj = NULL) {
85 // Figure out the target triple.
86 llvm::Triple TT("unknown-unknown-unknown");
Michael J. Spencerd11699d2011-01-20 07:22:04 +000087 if (TripleName.empty()) {
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000088 if (Obj)
89 TT.setArch(Triple::ArchType(Obj->getArch()));
Michael J. Spencerd11699d2011-01-20 07:22:04 +000090 } else
Michael J. Spencer92e1deb2011-01-20 06:39:06 +000091 TT.setTriple(Triple::normalize(TripleName));
92
93 if (!ArchName.empty())
94 TT.setArchName(ArchName);
95
96 TripleName = TT.str();
97
98 // Get the target specific parser.
99 std::string Error;
100 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
101 if (TheTarget)
102 return TheTarget;
103
104 errs() << ToolName << ": error: unable to get target for '" << TripleName
105 << "', see --version and --triple.\n";
106 return 0;
107}
108
109namespace {
110class StringRefMemoryObject : public MemoryObject {
111private:
112 StringRef Bytes;
113public:
114 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
115
116 uint64_t getBase() const { return 0; }
117 uint64_t getExtent() const { return Bytes.size(); }
118
119 int readByte(uint64_t Addr, uint8_t *Byte) const {
Benjamin Kramer14c92462011-07-19 22:59:25 +0000120 if (Addr >= getExtent())
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000121 return -1;
122 *Byte = Bytes[Addr];
123 return 0;
124 }
125};
126}
127
128static void DumpBytes(StringRef bytes) {
129 static char hex_rep[] = "0123456789abcdef";
130 // FIXME: The real way to do this is to figure out the longest instruction
131 // and align to that size before printing. I'll fix this when I get
132 // around to outputting relocations.
133 // 15 is the longest x86 instruction
134 // 3 is for the hex rep of a byte + a space.
135 // 1 is for the null terminator.
136 enum { OutputSize = (15 * 3) + 1 };
137 char output[OutputSize];
138
139 assert(bytes.size() <= 15
140 && "DumpBytes only supports instructions of up to 15 bytes");
141 memset(output, ' ', sizeof(output));
142 unsigned index = 0;
143 for (StringRef::iterator i = bytes.begin(),
144 e = bytes.end(); i != e; ++i) {
145 output[index] = hex_rep[(*i & 0xF0) >> 4];
146 output[index + 1] = hex_rep[*i & 0xF];
147 index += 3;
148 }
149
150 output[sizeof(output) - 1] = 0;
151 outs() << output;
152}
153
154static void DisassembleInput(const StringRef &Filename) {
155 OwningPtr<MemoryBuffer> Buff;
156
157 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
158 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
159 return;
160 }
161
162 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
163
164 const Target *TheTarget = GetTarget(Obj.get());
165 if (!TheTarget) {
166 // GetTarget prints out stuff.
167 return;
168 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000169 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
Benjamin Kramer41ab14b2011-08-08 18:56:44 +0000170 OwningPtr<MCInstrAnalysis>
171 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000172
173 outs() << '\n';
174 outs() << Filename
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000175 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000176
Michael J. Spencer25b15772011-06-25 17:55:23 +0000177 error_code ec;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000178 for (ObjectFile::section_iterator i = Obj->begin_sections(),
179 e = Obj->end_sections();
Michael J. Spencer25b15772011-06-25 17:55:23 +0000180 i != e; i.increment(ec)) {
181 if (error(ec)) break;
182 bool text;
183 if (error(i->isText(text))) break;
184 if (!text) continue;
185
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000186 // Make a list of all the symbols in this section.
187 std::vector<std::pair<uint64_t, StringRef> > Symbols;
188 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
189 se = Obj->end_symbols();
190 si != se; si.increment(ec)) {
191 bool contains;
192 if (!error(i->containsSymbol(*si, contains)) && contains) {
193 uint64_t Address;
Benjamin Kramerac241fe2011-09-14 01:22:52 +0000194 if (error(si->getOffset(Address))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000195 StringRef Name;
196 if (error(si->getName(Name))) break;
197 Symbols.push_back(std::make_pair(Address, Name));
198 }
199 }
200
201 // Sort the symbols by address, just in case they didn't come in that way.
202 array_pod_sort(Symbols.begin(), Symbols.end());
203
Michael J. Spencer25b15772011-06-25 17:55:23 +0000204 StringRef name;
205 if (error(i->getName(name))) break;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000206 outs() << "Disassembly of section " << name << ':';
207
208 // If the section has no symbols just insert a dummy one and disassemble
209 // the whole section.
210 if (Symbols.empty())
211 Symbols.push_back(std::make_pair(0, name));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000212
213 // Set up disassembler.
Evan Cheng1abf2cb2011-07-14 23:50:31 +0000214 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000215
216 if (!AsmInfo) {
217 errs() << "error: no assembly info for target " << TripleName << "\n";
218 return;
219 }
220
James Molloyb9505852011-09-07 17:24:38 +0000221 OwningPtr<const MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
222
223 if (!STI) {
224 errs() << "error: no subtarget info for target " << TripleName << "\n";
225 return;
226 }
227
228 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000229 if (!DisAsm) {
230 errs() << "error: no disassembler for target " << TripleName << "\n";
231 return;
232 }
233
234 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
235 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
James Molloyb9505852011-09-07 17:24:38 +0000236 AsmPrinterVariant, *AsmInfo, *STI));
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000237 if (!IP) {
238 errs() << "error: no instruction printer for target " << TripleName << '\n';
239 return;
240 }
241
Michael J. Spencer25b15772011-06-25 17:55:23 +0000242 StringRef Bytes;
243 if (error(i->getContents(Bytes))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000244 StringRefMemoryObject memoryObject(Bytes);
245 uint64_t Size;
246 uint64_t Index;
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000247 uint64_t SectSize;
248 if (error(i->getSize(SectSize))) break;
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000249
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000250 // Disassemble symbol by symbol.
251 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
252 uint64_t Start = Symbols[si].first;
253 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
254 outs() << '\n' << Symbols[si].second << ":\n";
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000255
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000256#ifndef NDEBUG
257 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
258#else
259 raw_ostream &DebugOut = nulls();
260#endif
261
Benjamin Kramera21d8132011-08-08 18:32:12 +0000262 if (!CFG) {
263 for (Index = Start; Index < End; Index += Size) {
264 MCInst Inst;
Owen Anderson98c5dda2011-09-15 23:38:46 +0000265
Benjamin Kramera21d8132011-08-08 18:32:12 +0000266 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
Owen Anderson98c5dda2011-09-15 23:38:46 +0000267 DebugOut, nulls())) {
Benjamin Kramera21d8132011-08-08 18:32:12 +0000268 uint64_t addr;
269 if (error(i->getAddress(addr))) break;
270 outs() << format("%8x:\t", addr + Index);
271 DumpBytes(StringRef(Bytes.data() + Index, Size));
Owen Anderson98c5dda2011-09-15 23:38:46 +0000272 IP->printInst(&Inst, outs(), "");
Benjamin Kramera21d8132011-08-08 18:32:12 +0000273 outs() << "\n";
274 } else {
275 errs() << ToolName << ": warning: invalid instruction encoding\n";
276 if (Size == 0)
277 Size = 1; // skip illegible bytes
278 }
Benjamin Kramer739b65b2011-07-15 18:39:24 +0000279 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000280
Benjamin Kramera21d8132011-08-08 18:32:12 +0000281 } else {
282 // Create CFG and use it for disassembly.
Benjamin Kramer685a2502011-07-20 19:37:35 +0000283 MCFunction f =
284 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
Benjamin Kramer41ab14b2011-08-08 18:56:44 +0000285 memoryObject, Start, End,
286 InstrAnalysis.get(), DebugOut);
Benjamin Kramer685a2502011-07-20 19:37:35 +0000287
Benjamin Kramera21d8132011-08-08 18:32:12 +0000288 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
289 bool hasPreds = false;
290 // Only print blocks that have predecessors.
291 // FIXME: Slow.
292 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
293 ++pi)
294 if (pi->second.contains(&fi->second)) {
295 hasPreds = true;
296 break;
297 }
298
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000299 // Data block.
300 if (!hasPreds && fi != f.begin()) {
301 uint64_t End = llvm::next(fi) == fe ? SectSize :
302 llvm::next(fi)->first;
303 uint64_t addr;
304 if (error(i->getAddress(addr))) break;
305 outs() << "# " << End-fi->first << " bytes of data:\n";
306 for (unsigned pos = fi->first; pos != End; ++pos) {
307 outs() << format("%8x:\t", addr + pos);
308 DumpBytes(StringRef(Bytes.data() + pos, 1));
309 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
310 }
Benjamin Kramera21d8132011-08-08 18:32:12 +0000311 continue;
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000312 }
313
314 if (fi->second.contains(&fi->second))
315 outs() << "# Loop begin:\n";
Benjamin Kramera21d8132011-08-08 18:32:12 +0000316
317 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
318 ++ii) {
319 uint64_t addr;
320 if (error(i->getAddress(addr))) break;
321 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
322 outs() << format("%8x:\t", addr + Inst.Address);
323 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
Benjamin Kramerc13464f2011-08-08 18:41:34 +0000324 // Simple loops.
325 if (fi->second.contains(&fi->second))
326 outs() << '\t';
Owen Anderson98c5dda2011-09-15 23:38:46 +0000327 IP->printInst(&Inst.Inst, outs(), "");
Benjamin Kramera21d8132011-08-08 18:32:12 +0000328 outs() << '\n';
329 }
330 }
331
Benjamin Kramer685a2502011-07-20 19:37:35 +0000332 // Start a new dot file.
333 std::string Error;
334 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
Benjamin Kramera503ede2011-07-22 18:35:11 +0000335 if (!Error.empty()) {
336 errs() << ToolName << ": warning: " << Error << '\n';
337 continue;
338 }
Benjamin Kramer685a2502011-07-20 19:37:35 +0000339
340 Out << "digraph " << f.getName() << " {\n";
341 Out << "graph [ rankdir = \"LR\" ];\n";
342 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000343 bool hasPreds = false;
344 // Only print blocks that have predecessors.
345 // FIXME: Slow.
346 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
347 ++pi)
Benjamin Kramerdbc46d72011-07-25 23:10:23 +0000348 if (pi->second.contains(&i->second)) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000349 hasPreds = true;
350 break;
351 }
352
353 if (!hasPreds && i != f.begin())
354 continue;
355
Benjamin Kramer685a2502011-07-20 19:37:35 +0000356 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
357 // Print instructions.
358 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
359 ++ii) {
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000360 // Escape special chars and print the instruction in mnemonic form.
361 std::string Str;
362 raw_string_ostream OS(Str);
Owen Anderson98c5dda2011-09-15 23:38:46 +0000363 IP->printInst(&i->second.getInsts()[ii].Inst, OS, "");
Benjamin Kramer853b0fd2011-07-25 23:04:36 +0000364 Out << DOT::EscapeString(OS.str()) << '|';
Benjamin Kramer685a2502011-07-20 19:37:35 +0000365 }
366 Out << "<o>\" shape=\"record\" ];\n";
367
368 // Add edges.
369 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
370 se = i->second.succ_end(); si != se; ++si)
371 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
372 }
373 Out << "}\n";
374 }
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000375 }
376 }
377}
378
379int main(int argc, char **argv) {
380 // Print a stack trace if we signal out.
381 sys::PrintStackTraceOnErrorSignal();
382 PrettyStackTraceProgram X(argc, argv);
383 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
384
385 // Initialize targets and assembly printers/parsers.
386 llvm::InitializeAllTargetInfos();
Evan Chenge78085a2011-07-22 21:58:54 +0000387 llvm::InitializeAllTargetMCs();
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000388 llvm::InitializeAllAsmParsers();
389 llvm::InitializeAllDisassemblers();
390
Michael J. Spencer92e1deb2011-01-20 06:39:06 +0000391 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
392 TripleName = Triple::normalize(TripleName);
393
394 ToolName = argv[0];
395
396 // Defaults to a.out if no filenames specified.
397 if (InputFilenames.size() == 0)
398 InputFilenames.push_back("a.out");
399
400 // -d is the only flag that is currently implemented, so just print help if
401 // it is not set.
402 if (!Disassemble) {
403 cl::PrintHelpMessage();
404 return 2;
405 }
406
407 std::for_each(InputFilenames.begin(), InputFilenames.end(),
408 DisassembleInput);
409
410 return 0;
411}