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 "llvm-objdump.h"
17 #include "MCFunction.h"
18 #include "llvm/Object/ObjectFile.h"
19 #include "llvm/ADT/OwningPtr.h"
20 #include "llvm/ADT/Triple.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/MC/MCDisassembler.h"
24 #include "llvm/MC/MCInst.h"
25 #include "llvm/MC/MCInstPrinter.h"
26 #include "llvm/MC/MCInstrAnalysis.h"
27 #include "llvm/MC/MCInstrDesc.h"
28 #include "llvm/MC/MCInstrInfo.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/Format.h"
33 #include "llvm/Support/GraphWriter.h"
34 #include "llvm/Support/Host.h"
35 #include "llvm/Support/ManagedStatic.h"
36 #include "llvm/Support/MemoryBuffer.h"
37 #include "llvm/Support/MemoryObject.h"
38 #include "llvm/Support/PrettyStackTrace.h"
39 #include "llvm/Support/Signals.h"
40 #include "llvm/Support/SourceMgr.h"
41 #include "llvm/Support/TargetRegistry.h"
42 #include "llvm/Support/TargetSelect.h"
43 #include "llvm/Support/raw_ostream.h"
44 #include "llvm/Support/system_error.h"
48 using namespace object;
50 static cl::list<std::string>
51 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
54 Disassemble("disassemble",
55 cl::desc("Display assembler mnemonics for the machine instructions"));
57 Disassembled("d", cl::desc("Alias for --disassemble"),
58 cl::aliasopt(Disassemble));
61 MachO("macho", cl::desc("Use MachO specific object file parser"));
63 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
66 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
67 "see -version for available targets"));
70 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
71 "see -version for available targets"));
73 static StringRef ToolName;
75 static bool error(error_code ec) {
76 if (!ec) return false;
78 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
83 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
84 // Figure out the target triple.
85 llvm::Triple TT("unknown-unknown-unknown");
86 if (TripleName.empty()) {
88 TT.setArch(Triple::ArchType(Obj->getArch()));
90 TT.setTriple(Triple::normalize(TripleName));
92 if (!ArchName.empty())
93 TT.setArchName(ArchName);
95 TripleName = TT.str();
97 // Get the target specific parser.
99 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
103 errs() << ToolName << ": error: unable to get target for '" << TripleName
104 << "', see --version and --triple.\n";
108 void llvm::DumpBytes(StringRef bytes) {
109 static const char hex_rep[] = "0123456789abcdef";
110 // FIXME: The real way to do this is to figure out the longest instruction
111 // and align to that size before printing. I'll fix this when I get
112 // around to outputting relocations.
113 // 15 is the longest x86 instruction
114 // 3 is for the hex rep of a byte + a space.
115 // 1 is for the null terminator.
116 enum { OutputSize = (15 * 3) + 1 };
117 char output[OutputSize];
119 assert(bytes.size() <= 15
120 && "DumpBytes only supports instructions of up to 15 bytes");
121 memset(output, ' ', sizeof(output));
123 for (StringRef::iterator i = bytes.begin(),
124 e = bytes.end(); i != e; ++i) {
125 output[index] = hex_rep[(*i & 0xF0) >> 4];
126 output[index + 1] = hex_rep[*i & 0xF];
130 output[sizeof(output) - 1] = 0;
134 void llvm::DisassembleInputLibObject(StringRef Filename) {
135 OwningPtr<MemoryBuffer> Buff;
137 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) {
138 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n";
142 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take()));
144 const Target *TheTarget = GetTarget(Obj.get());
146 // GetTarget prints out stuff.
149 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo();
150 OwningPtr<MCInstrAnalysis>
151 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo));
155 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
158 for (section_iterator i = Obj->begin_sections(),
159 e = Obj->end_sections();
160 i != e; i.increment(ec)) {
161 if (error(ec)) break;
163 if (error(i->isText(text))) break;
166 // Make a list of all the symbols in this section.
167 std::vector<std::pair<uint64_t, StringRef> > Symbols;
168 for (symbol_iterator si = Obj->begin_symbols(),
169 se = Obj->end_symbols();
170 si != se; si.increment(ec)) {
172 if (!error(i->containsSymbol(*si, contains)) && contains) {
174 if (error(si->getOffset(Address))) break;
176 if (error(si->getName(Name))) break;
177 Symbols.push_back(std::make_pair(Address, Name));
181 // Sort the symbols by address, just in case they didn't come in that way.
182 array_pod_sort(Symbols.begin(), Symbols.end());
185 if (error(i->getName(name))) break;
186 outs() << "Disassembly of section " << name << ':';
188 // If the section has no symbols just insert a dummy one and disassemble
189 // the whole section.
191 Symbols.push_back(std::make_pair(0, name));
193 // Set up disassembler.
194 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
197 errs() << "error: no assembly info for target " << TripleName << "\n";
201 OwningPtr<const MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(TripleName, "", ""));
204 errs() << "error: no subtarget info for target " << TripleName << "\n";
208 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI));
210 errs() << "error: no disassembler for target " << TripleName << "\n";
214 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
215 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
216 AsmPrinterVariant, *AsmInfo, *STI));
218 errs() << "error: no instruction printer for target " << TripleName << '\n';
223 if (error(i->getContents(Bytes))) break;
224 StringRefMemoryObject memoryObject(Bytes);
228 if (error(i->getSize(SectSize))) break;
230 // 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";
237 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
239 raw_ostream &DebugOut = nulls();
242 for (Index = Start; Index < End; Index += Size) {
245 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
246 DebugOut, nulls())) {
248 if (error(i->getAddress(addr))) break;
249 outs() << format("%8x:\t", addr + Index);
250 DumpBytes(StringRef(Bytes.data() + Index, Size));
251 IP->printInst(&Inst, outs(), "");
254 errs() << ToolName << ": warning: invalid instruction encoding\n";
256 Size = 1; // skip illegible bytes
263 int main(int argc, char **argv) {
264 // Print a stack trace if we signal out.
265 sys::PrintStackTraceOnErrorSignal();
266 PrettyStackTraceProgram X(argc, argv);
267 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
269 // Initialize targets and assembly printers/parsers.
270 llvm::InitializeAllTargetInfos();
271 llvm::InitializeAllTargetMCs();
272 llvm::InitializeAllAsmParsers();
273 llvm::InitializeAllDisassemblers();
275 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
276 TripleName = Triple::normalize(TripleName);
280 // Defaults to a.out if no filenames specified.
281 if (InputFilenames.size() == 0)
282 InputFilenames.push_back("a.out");
284 // -d is the only flag that is currently implemented, so just print help if
287 cl::PrintHelpMessage();
292 std::for_each(InputFilenames.begin(), InputFilenames.end(),
293 DisassembleInputMachO);
295 std::for_each(InputFilenames.begin(), InputFilenames.end(),
296 DisassembleInputLibObject);