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/Host.h"
31 #include "llvm/Support/ManagedStatic.h"
32 #include "llvm/Support/MemoryBuffer.h"
33 #include "llvm/Support/MemoryObject.h"
34 #include "llvm/Support/PrettyStackTrace.h"
35 #include "llvm/Support/Signals.h"
36 #include "llvm/Support/SourceMgr.h"
37 #include "llvm/Support/raw_ostream.h"
38 #include "llvm/Support/system_error.h"
39 #include "llvm/Target/TargetRegistry.h"
40 #include "llvm/Target/TargetSelect.h"
44 using namespace object;
48 InputFilenames(cl::Positional, cl::desc("<input object files>"),
52 Disassemble("disassemble",
53 cl::desc("Display assembler mnemonics for the machine instructions"));
55 Disassembled("d", cl::desc("Alias for --disassemble"),
56 cl::aliasopt(Disassemble));
59 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
60 "write it to a graphviz file"));
63 TripleName("triple", cl::desc("Target triple to disassemble for, "
64 "see -version for available targets"));
67 ArchName("arch", cl::desc("Target arch to disassemble for, "
68 "see -version for available targets"));
72 bool error(error_code ec) {
73 if (!ec) return false;
75 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
81 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
82 // Figure out the target triple.
83 llvm::Triple TT("unknown-unknown-unknown");
84 if (TripleName.empty()) {
86 TT.setArch(Triple::ArchType(Obj->getArch()));
88 TT.setTriple(Triple::normalize(TripleName));
90 if (!ArchName.empty())
91 TT.setArchName(ArchName);
93 TripleName = TT.str();
95 // Get the target specific parser.
97 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
101 errs() << ToolName << ": error: unable to get target for '" << TripleName
102 << "', see --version and --triple.\n";
107 class StringRefMemoryObject : public MemoryObject {
111 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
113 uint64_t getBase() const { return 0; }
114 uint64_t getExtent() const { return Bytes.size(); }
116 int readByte(uint64_t Addr, uint8_t *Byte) const {
117 if (Addr >= getExtent())
125 static void DumpBytes(StringRef bytes) {
126 static char hex_rep[] = "0123456789abcdef";
127 // FIXME: The real way to do this is to figure out the longest instruction
128 // and align to that size before printing. I'll fix this when I get
129 // around to outputting relocations.
130 // 15 is the longest x86 instruction
131 // 3 is for the hex rep of a byte + a space.
132 // 1 is for the null terminator.
133 enum { OutputSize = (15 * 3) + 1 };
134 char output[OutputSize];
136 assert(bytes.size() <= 15
137 && "DumpBytes only supports instructions of up to 15 bytes");
138 memset(output, ' ', sizeof(output));
140 for (StringRef::iterator i = bytes.begin(),
141 e = bytes.end(); i != e; ++i) {
142 output[index] = hex_rep[(*i & 0xF0) >> 4];
143 output[index + 1] = hex_rep[*i & 0xF];
147 output[sizeof(output) - 1] = 0;
151 static void DisassembleInput(const StringRef &Filename) {
152 OwningPtr<MemoryBuffer> Buff;
154 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
155 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
159 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
161 const Target *TheTarget = GetTarget(Obj.get());
163 // GetTarget prints out stuff.
166 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
170 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
173 for (ObjectFile::section_iterator i = Obj->begin_sections(),
174 e = Obj->end_sections();
175 i != e; i.increment(ec)) {
176 if (error(ec)) break;
178 if (error(i->isText(text))) break;
181 // Make a list of all the symbols in this section.
182 std::vector<std::pair<uint64_t, StringRef> > Symbols;
183 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(),
184 se = Obj->end_symbols();
185 si != se; si.increment(ec)) {
187 if (!error(i->containsSymbol(*si, contains)) && contains) {
189 if (error(si->getAddress(Address))) break;
191 if (error(si->getName(Name))) break;
192 Symbols.push_back(std::make_pair(Address, Name));
196 // Sort the symbols by address, just in case they didn't come in that way.
197 array_pod_sort(Symbols.begin(), Symbols.end());
200 if (error(i->getName(name))) break;
201 outs() << "Disassembly of section " << name << ':';
203 // If the section has no symbols just insert a dummy one and disassemble
204 // the whole section.
206 Symbols.push_back(std::make_pair(0, name));
208 // Set up disassembler.
209 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
212 errs() << "error: no assembly info for target " << TripleName << "\n";
216 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler());
218 errs() << "error: no disassembler for target " << TripleName << "\n";
222 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
223 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
224 AsmPrinterVariant, *AsmInfo));
226 errs() << "error: no instruction printer for target " << TripleName << '\n';
231 if (error(i->getContents(Bytes))) break;
232 StringRefMemoryObject memoryObject(Bytes);
236 if (error(i->getSize(SectSize))) break;
238 // Disassemble symbol by symbol.
239 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
240 uint64_t Start = Symbols[si].first;
241 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
242 outs() << '\n' << Symbols[si].second << ":\n";
245 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
247 raw_ostream &DebugOut = nulls();
250 for (Index = Start; Index < End; Index += Size) {
252 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, DebugOut)) {
254 if (error(i->getAddress(addr))) break;
255 outs() << format("%8x:\t", addr + Index);
256 DumpBytes(StringRef(Bytes.data() + Index, Size));
257 IP->printInst(&Inst, outs());
260 errs() << ToolName << ": warning: invalid instruction encoding\n";
262 Size = 1; // skip illegible bytes
268 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
269 memoryObject, Start, End, InstrInfo,
272 // Start a new dot file.
274 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
276 Out << "digraph " << f.getName() << " {\n";
277 Out << "graph [ rankdir = \"LR\" ];\n";
278 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
279 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
280 // Print instructions.
281 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
283 IP->printInst(&i->second.getInsts()[ii].Inst, Out);
286 Out << "<o>\" shape=\"record\" ];\n";
289 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
290 se = i->second.succ_end(); si != se; ++si)
291 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
299 int main(int argc, char **argv) {
300 // Print a stack trace if we signal out.
301 sys::PrintStackTraceOnErrorSignal();
302 PrettyStackTraceProgram X(argc, argv);
303 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
305 // Initialize targets and assembly printers/parsers.
306 llvm::InitializeAllTargetInfos();
307 // FIXME: We shouldn't need to initialize the Target(Machine)s.
308 llvm::InitializeAllTargets();
309 llvm::InitializeAllMCAsmInfos();
310 llvm::InitializeAllMCCodeGenInfos();
311 llvm::InitializeAllMCInstrInfos();
312 llvm::InitializeAllAsmPrinters();
313 llvm::InitializeAllAsmParsers();
314 llvm::InitializeAllDisassemblers();
316 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
317 TripleName = Triple::normalize(TripleName);
321 // Defaults to a.out if no filenames specified.
322 if (InputFilenames.size() == 0)
323 InputFilenames.push_back("a.out");
325 // -d is the only flag that is currently implemented, so just print help if
328 cl::PrintHelpMessage();
332 std::for_each(InputFilenames.begin(), InputFilenames.end(),