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/MCInstrAnalysis.h"
26 #include "llvm/MC/MCInstrDesc.h"
27 #include "llvm/MC/MCInstrInfo.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/Format.h"
32 #include "llvm/Support/GraphWriter.h"
33 #include "llvm/Support/Host.h"
34 #include "llvm/Support/ManagedStatic.h"
35 #include "llvm/Support/MemoryBuffer.h"
36 #include "llvm/Support/MemoryObject.h"
37 #include "llvm/Support/PrettyStackTrace.h"
38 #include "llvm/Support/Signals.h"
39 #include "llvm/Support/SourceMgr.h"
40 #include "llvm/Support/TargetRegistry.h"
41 #include "llvm/Support/TargetSelect.h"
42 #include "llvm/Support/raw_ostream.h"
43 #include "llvm/Support/system_error.h"
47 using namespace object;
51 InputFilenames(cl::Positional, cl::desc("<input object files>"),
55 Disassemble("disassemble",
56 cl::desc("Display assembler mnemonics for the machine instructions"));
58 Disassembled("d", cl::desc("Alias for --disassemble"),
59 cl::aliasopt(Disassemble));
62 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and"
63 "write it to a graphviz file"));
66 TripleName("triple", cl::desc("Target triple to disassemble for, "
67 "see -version for available targets"));
70 ArchName("arch", cl::desc("Target arch to disassemble for, "
71 "see -version for available targets"));
75 bool error(error_code ec) {
76 if (!ec) return false;
78 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
84 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
85 // Figure out the target triple.
86 llvm::Triple TT("unknown-unknown-unknown");
87 if (TripleName.empty()) {
89 TT.setArch(Triple::ArchType(Obj->getArch()));
91 TT.setTriple(Triple::normalize(TripleName));
93 if (!ArchName.empty())
94 TT.setArchName(ArchName);
96 TripleName = TT.str();
98 // Get the target specific parser.
100 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
104 errs() << ToolName << ": error: unable to get target for '" << TripleName
105 << "', see --version and --triple.\n";
110 class StringRefMemoryObject : public MemoryObject {
114 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {}
116 uint64_t getBase() const { return 0; }
117 uint64_t getExtent() const { return Bytes.size(); }
119 int readByte(uint64_t Addr, uint8_t *Byte) const {
120 if (Addr >= getExtent())
128 static 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];
139 assert(bytes.size() <= 15
140 && "DumpBytes only supports instructions of up to 15 bytes");
141 memset(output, ' ', sizeof(output));
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];
150 output[sizeof(output) - 1] = 0;
154 static void DisassembleInput(const StringRef &Filename) {
155 OwningPtr<MemoryBuffer> Buff;
157 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
158 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
162 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
164 const Target *TheTarget = GetTarget(Obj.get());
166 // GetTarget prints out stuff.
169 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
170 OwningPtr<MCInstrAnalysis>
171 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
175 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
178 for (ObjectFile::section_iterator i = Obj->begin_sections(),
179 e = Obj->end_sections();
180 i != e; i.increment(ec)) {
181 if (error(ec)) break;
183 if (error(i->isText(text))) break;
186 // 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)) {
192 if (!error(i->containsSymbol(*si, contains)) && contains) {
194 if (error(si->getOffset(Address))) break;
196 if (error(si->getName(Name))) break;
197 Symbols.push_back(std::make_pair(Address, Name));
201 // Sort the symbols by address, just in case they didn't come in that way.
202 array_pod_sort(Symbols.begin(), Symbols.end());
205 if (error(i->getName(name))) break;
206 outs() << "Disassembly of section " << name << ':';
208 // If the section has no symbols just insert a dummy one and disassemble
209 // the whole section.
211 Symbols.push_back(std::make_pair(0, name));
213 // Set up disassembler.
214 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
217 errs() << "error: no assembly info for target " << TripleName << "\n";
221 OwningPtr<const MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
224 errs() << "error: no subtarget info for target " << TripleName << "\n";
228 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
230 errs() << "error: no disassembler for target " << TripleName << "\n";
234 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
235 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
236 AsmPrinterVariant, *AsmInfo, *STI));
238 errs() << "error: no instruction printer for target " << TripleName << '\n';
243 if (error(i->getContents(Bytes))) break;
244 StringRefMemoryObject memoryObject(Bytes);
248 if (error(i->getSize(SectSize))) break;
250 // 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";
257 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
259 raw_ostream &DebugOut = nulls();
263 for (Index = Start; Index < End; Index += Size) {
265 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
268 if (error(i->getAddress(addr))) break;
269 outs() << format("%8x:\t", addr + Index);
270 DumpBytes(StringRef(Bytes.data() + Index, Size));
271 IP->printInst(&Inst, outs());
274 errs() << ToolName << ": warning: invalid instruction encoding\n";
276 Size = 1; // skip illegible bytes
281 // Create CFG and use it for disassembly.
283 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(),
284 memoryObject, Start, End,
285 InstrAnalysis.get(), DebugOut);
287 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){
288 bool hasPreds = false;
289 // Only print blocks that have predecessors.
291 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
293 if (pi->second.contains(&fi->second)) {
299 if (!hasPreds && fi != f.begin()) {
300 uint64_t End = llvm::next(fi) == fe ? SectSize :
301 llvm::next(fi)->first;
303 if (error(i->getAddress(addr))) break;
304 outs() << "# " << End-fi->first << " bytes of data:\n";
305 for (unsigned pos = fi->first; pos != End; ++pos) {
306 outs() << format("%8x:\t", addr + pos);
307 DumpBytes(StringRef(Bytes.data() + pos, 1));
308 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]);
313 if (fi->second.contains(&fi->second))
314 outs() << "# Loop begin:\n";
316 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie;
319 if (error(i->getAddress(addr))) break;
320 const MCDecodedInst &Inst = fi->second.getInsts()[ii];
321 outs() << format("%8x:\t", addr + Inst.Address);
322 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size));
324 if (fi->second.contains(&fi->second))
326 IP->printInst(&Inst.Inst, outs());
331 // Start a new dot file.
333 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error);
334 if (!Error.empty()) {
335 errs() << ToolName << ": warning: " << Error << '\n';
339 Out << "digraph " << f.getName() << " {\n";
340 Out << "graph [ rankdir = \"LR\" ];\n";
341 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) {
342 bool hasPreds = false;
343 // Only print blocks that have predecessors.
345 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe;
347 if (pi->second.contains(&i->second)) {
352 if (!hasPreds && i != f.begin())
355 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>";
356 // Print instructions.
357 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie;
359 // Escape special chars and print the instruction in mnemonic form.
361 raw_string_ostream OS(Str);
362 IP->printInst(&i->second.getInsts()[ii].Inst, OS);
363 Out << DOT::EscapeString(OS.str()) << '|';
365 Out << "<o>\" shape=\"record\" ];\n";
368 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(),
369 se = i->second.succ_end(); si != se; ++si)
370 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n";
378 int main(int argc, char **argv) {
379 // Print a stack trace if we signal out.
380 sys::PrintStackTraceOnErrorSignal();
381 PrettyStackTraceProgram X(argc, argv);
382 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
384 // Initialize targets and assembly printers/parsers.
385 llvm::InitializeAllTargetInfos();
386 llvm::InitializeAllTargetMCs();
387 llvm::InitializeAllAsmParsers();
388 llvm::InitializeAllDisassemblers();
390 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
391 TripleName = Triple::normalize(TripleName);
395 // Defaults to a.out if no filenames specified.
396 if (InputFilenames.size() == 0)
397 InputFilenames.push_back("a.out");
399 // -d is the only flag that is currently implemented, so just print help if
402 cl::PrintHelpMessage();
406 std::for_each(InputFilenames.begin(), InputFilenames.end(),