1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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
14 //===----------------------------------------------------------------------===//
16 #include "MCFunction.h"
17 #include "llvm/Object/ObjectFile.h"
18 #include "llvm/ADT/OwningPtr.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/MC/MCAsmInfo.h"
22 #include "llvm/MC/MCDisassembler.h"
23 #include "llvm/MC/MCInst.h"
24 #include "llvm/MC/MCInstPrinter.h"
25 #include "llvm/MC/MCInstrDesc.h"
26 #include "llvm/MC/MCInstrInfo.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Format.h"
30 #include "llvm/Support/GraphWriter.h"
31 #include "llvm/Support/Host.h"
32 #include "llvm/Support/ManagedStatic.h"
33 #include "llvm/Support/MemoryBuffer.h"
34 #include "llvm/Support/MemoryObject.h"
35 #include "llvm/Support/PrettyStackTrace.h"
36 #include "llvm/Support/Signals.h"
37 #include "llvm/Support/SourceMgr.h"
38 #include "llvm/Support/raw_ostream.h"
39 #include "llvm/Support/system_error.h"
40 #include "llvm/Target/TargetRegistry.h"
41 #include "llvm/Target/TargetSelect.h"
45 using namespace object;
49 InputFilenames(cl::Positional, cl::desc("<input object files>"),
53 Disassemble("disassemble",
54 cl::desc("Display assembler mnemonics for the machine instructions"));
56 Disassembled("d", cl::desc("Alias for --disassemble"),
57 cl::aliasopt(Disassemble));
60 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
61 "write it to a graphviz file"));
64 TripleName("triple", cl::desc("Target triple to disassemble for, "
65 "see -version for available targets"));
68 ArchName("arch", cl::desc("Target arch to disassemble for, "
69 "see -version for available targets"));
73 bool error(error_code ec) {
74 if (!ec) return false;
76 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
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()) {
87 TT.setArch(Triple::ArchType(Obj->getArch()));
89 TT.setTriple(Triple::normalize(TripleName));
91 if (!ArchName.empty())
92 TT.setArchName(ArchName);
94 TripleName = TT.str();
96 // Get the target specific parser.
98 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
102 errs() << ToolName << ": error: unable to get target for '" << TripleName
103 << "', see --version and --triple.\n";
108 class StringRefMemoryObject : public MemoryObject {
112 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
114 uint64_t getBase() const { return 0; }
115 uint64_t getExtent() const { return Bytes.size(); }
117 int readByte(uint64_t Addr, uint8_t *Byte) const {
118 if (Addr >= getExtent())
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];
137 assert(bytes.size() <= 15
138 && "DumpBytes only supports instructions of up to 15 bytes");
139 memset(output, ' ', sizeof(output));
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];
148 output[sizeof(output) - 1] = 0;
152 static void DisassembleInput(const StringRef &Filename) {
153 OwningPtr<MemoryBuffer> Buff;
155 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
156 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
160 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
162 const Target *TheTarget = GetTarget(Obj.get());
164 // GetTarget prints out stuff.
167 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
171 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
174 for (ObjectFile::section_iterator i = Obj->begin_sections(),
175 e = Obj->end_sections();
176 i != e; i.increment(ec)) {
177 if (error(ec)) break;
179 if (error(i->isText(text))) break;
182 // Make a list of all the symbols in this section.
183 std::vector<std::pair<uint64_t, StringRef> > Symbols;
184 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
185 se = Obj->end_symbols();
186 si != se; si.increment(ec)) {
188 if (!error(i->containsSymbol(*si, contains)) && contains) {
190 if (error(si->getAddress(Address))) break;
192 if (error(si->getName(Name))) break;
193 Symbols.push_back(std::make_pair(Address, Name));
197 // Sort the symbols by address, just in case they didn't come in that way.
198 array_pod_sort(Symbols.begin(), Symbols.end());
201 if (error(i->getName(name))) break;
202 outs() << "Disassembly of section " << name << ':';
204 // If the section has no symbols just insert a dummy one and disassemble
205 // the whole section.
207 Symbols.push_back(std::make_pair(0, name));
209 // Set up disassembler.
210 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
213 errs() << "error: no assembly info for target " << TripleName << "\n";
217 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
219 errs() << "error: no disassembler for target " << TripleName << "\n";
223 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
224 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
225 AsmPrinterVariant, *AsmInfo));
227 errs() << "error: no instruction printer for target " << TripleName << '\n';
232 if (error(i->getContents(Bytes))) break;
233 StringRefMemoryObject memoryObject(Bytes);
237 if (error(i->getSize(SectSize))) break;
239 // Disassemble symbol by symbol.
240 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
241 uint64_t Start = Symbols[si].first;
242 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
243 outs() << '\n' << Symbols[si].second << ":\n";
246 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
248 raw_ostream &DebugOut = nulls();
252 for (Index = Start; Index < End; Index += Size) {
254 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
257 if (error(i->getAddress(addr))) break;
258 outs() << format("%8x:\t", addr + Index);
259 DumpBytes(StringRef(Bytes.data() + Index, Size));
260 IP->printInst(&Inst, outs());
263 errs() << ToolName << ": warning: invalid instruction encoding\n";
265 Size = 1; // skip illegible bytes
270 // Create CFG and use it for disassembly.
272 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
273 memoryObject, Start, End, InstrInfo,
276 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
277 bool hasPreds = false;
278 // Only print blocks that have predecessors.
280 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
282 if (pi->second.contains(&fi->second)) {
287 if (!hasPreds && fi != f.begin())
290 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
293 if (error(i->getAddress(addr))) break;
294 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
295 outs() << format("%8x:\t", addr + Inst.Address);
296 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
297 IP->printInst(&Inst.Inst, outs());
302 // Start a new dot file.
304 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
305 if (!Error.empty()) {
306 errs() << ToolName << ": warning: " << Error << '\n';
310 Out << "digraph " << f.getName() << " {\n";
311 Out << "graph [ rankdir = \"LR\" ];\n";
312 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
313 bool hasPreds = false;
314 // Only print blocks that have predecessors.
316 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
318 if (pi->second.contains(&i->second)) {
323 if (!hasPreds && i != f.begin())
326 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
327 // Print instructions.
328 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
330 // Escape special chars and print the instruction in mnemonic form.
332 raw_string_ostream OS(Str);
333 IP->printInst(&i->second.getInsts()[ii].Inst, OS);
334 Out << DOT::EscapeString(OS.str()) << '|';
336 Out << "<o>\" shape=\"record\" ];\n";
339 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
340 se = i->second.succ_end(); si != se; ++si)
341 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
349 int main(int argc, char **argv) {
350 // Print a stack trace if we signal out.
351 sys::PrintStackTraceOnErrorSignal();
352 PrettyStackTraceProgram X(argc, argv);
353 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
355 // Initialize targets and assembly printers/parsers.
356 llvm::InitializeAllTargetInfos();
357 llvm::InitializeAllTargetMCs();
358 llvm::InitializeAllAsmParsers();
359 llvm::InitializeAllDisassemblers();
361 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
362 TripleName = Triple::normalize(TripleName);
366 // Defaults to a.out if no filenames specified.
367 if (InputFilenames.size() == 0)
368 InputFilenames.push_back("a.out");
370 // -d is the only flag that is currently implemented, so just print help if
373 cl::PrintHelpMessage();
377 std::for_each(InputFilenames.begin(), InputFilenames.end(),