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/Archive.h"
19 #include "llvm/Object/ObjectFile.h"
20 #include "llvm/ADT/OwningPtr.h"
21 #include "llvm/ADT/Triple.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/MC/MCDisassembler.h"
25 #include "llvm/MC/MCInst.h"
26 #include "llvm/MC/MCInstPrinter.h"
27 #include "llvm/MC/MCSubtargetInfo.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/Debug.h"
31 #include "llvm/Support/FileSystem.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 Relocations("r", cl::desc("Display the relocation entries in the file"));
64 MachO("macho", cl::desc("Use MachO specific object file parser"));
66 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
69 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
70 "see -version for available targets"));
73 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
74 "see -version for available targets"));
76 static StringRef ToolName;
78 static bool error(error_code ec) {
79 if (!ec) return false;
81 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
86 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
87 // Figure out the target triple.
88 llvm::Triple TT("unknown-unknown-unknown");
89 if (TripleName.empty()) {
91 TT.setArch(Triple::ArchType(Obj->getArch()));
93 TT.setTriple(Triple::normalize(TripleName));
95 if (!ArchName.empty())
96 TT.setArchName(ArchName);
98 TripleName = TT.str();
100 // Get the target specific parser.
102 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
106 errs() << ToolName << ": error: unable to get target for '" << TripleName
107 << "', see --version and --triple.\n";
111 void llvm::DumpBytes(StringRef bytes) {
112 static const char hex_rep[] = "0123456789abcdef";
113 // FIXME: The real way to do this is to figure out the longest instruction
114 // and align to that size before printing. I'll fix this when I get
115 // around to outputting relocations.
116 // 15 is the longest x86 instruction
117 // 3 is for the hex rep of a byte + a space.
118 // 1 is for the null terminator.
119 enum { OutputSize = (15 * 3) + 1 };
120 char output[OutputSize];
122 assert(bytes.size() <= 15
123 && "DumpBytes only supports instructions of up to 15 bytes");
124 memset(output, ' ', sizeof(output));
126 for (StringRef::iterator i = bytes.begin(),
127 e = bytes.end(); i != e; ++i) {
128 output[index] = hex_rep[(*i & 0xF0) >> 4];
129 output[index + 1] = hex_rep[*i & 0xF];
133 output[sizeof(output) - 1] = 0;
137 static void DisassembleObject(const ObjectFile *Obj) {
138 const Target *TheTarget = GetTarget(Obj);
140 // GetTarget prints out stuff.
145 outs() << Obj->getFileName()
146 << ":\tfile format " << Obj->getFileFormatName() << "\n\n";
149 for (section_iterator i = Obj->begin_sections(),
150 e = Obj->end_sections();
151 i != e; i.increment(ec)) {
152 if (error(ec)) break;
154 if (error(i->isText(text))) break;
157 // Make a list of all the symbols in this section.
158 std::vector<std::pair<uint64_t, StringRef> > Symbols;
159 for (symbol_iterator si = Obj->begin_symbols(),
160 se = Obj->end_symbols();
161 si != se; si.increment(ec)) {
163 if (!error(i->containsSymbol(*si, contains)) && contains) {
165 if (error(si->getOffset(Address))) break;
167 if (error(si->getName(Name))) break;
168 Symbols.push_back(std::make_pair(Address, Name));
172 // Sort the symbols by address, just in case they didn't come in that way.
173 array_pod_sort(Symbols.begin(), Symbols.end());
176 if (error(i->getName(name))) break;
177 outs() << "Disassembly of section " << name << ':';
179 // If the section has no symbols just insert a dummy one and disassemble
180 // the whole section.
182 Symbols.push_back(std::make_pair(0, name));
184 // Set up disassembler.
185 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
188 errs() << "error: no assembly info for target " << TripleName << "\n";
192 OwningPtr<const MCSubtargetInfo> STI(
193 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
196 errs() << "error: no subtarget info for target " << TripleName << "\n";
200 OwningPtr<const MCDisassembler> DisAsm(
201 TheTarget->createMCDisassembler(*STI));
203 errs() << "error: no disassembler for target " << TripleName << "\n";
207 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
208 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
209 AsmPrinterVariant, *AsmInfo, *STI));
211 errs() << "error: no instruction printer for target " << TripleName
217 if (error(i->getContents(Bytes))) break;
218 StringRefMemoryObject memoryObject(Bytes);
222 if (error(i->getSize(SectSize))) break;
224 // Disassemble symbol by symbol.
225 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
226 uint64_t Start = Symbols[si].first;
227 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1;
228 outs() << '\n' << Symbols[si].second << ":\n";
231 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
233 raw_ostream &DebugOut = nulls();
236 for (Index = Start; Index < End; Index += Size) {
239 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
240 DebugOut, nulls())) {
242 if (error(i->getAddress(addr))) break;
243 outs() << format("%8x:\t", addr + Index);
244 DumpBytes(StringRef(Bytes.data() + Index, Size));
245 IP->printInst(&Inst, outs(), "");
248 errs() << ToolName << ": warning: invalid instruction encoding\n";
250 Size = 1; // skip illegible bytes
257 static void PrintRelocations(const ObjectFile *o) {
259 for (section_iterator si = o->begin_sections(), se = o->end_sections();
260 si != se; si.increment(ec)){
261 if (error(ec)) return;
262 if (si->begin_relocations() == si->end_relocations())
265 if (error(si->getName(secname))) continue;
266 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
267 for (relocation_iterator ri = si->begin_relocations(),
268 re = si->end_relocations();
269 ri != re; ri.increment(ec)) {
270 if (error(ec)) return;
273 SmallString<32> relocname;
274 SmallString<32> valuestr;
275 if (error(ri->getTypeName(relocname))) continue;
276 if (error(ri->getAddress(address))) continue;
277 if (error(ri->getValueString(valuestr))) continue;
278 outs() << address << " " << relocname << " " << valuestr << "\n";
284 static void DumpObject(const ObjectFile *o) {
286 DisassembleObject(o);
291 /// @brief Dump each object file in \a a;
292 static void DumpArchive(const Archive *a) {
293 for (Archive::child_iterator i = a->begin_children(),
294 e = a->end_children(); i != e; ++i) {
295 OwningPtr<Binary> child;
296 if (error_code ec = i->getAsBinary(child)) {
297 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
301 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
304 errs() << ToolName << ": '" << a->getFileName() << "': "
305 << "Unrecognized file type.\n";
309 /// @brief Open file and figure out how to dump it.
310 static void DumpInput(StringRef file) {
311 // If file isn't stdin, check that it exists.
312 if (file != "-" && !sys::fs::exists(file)) {
313 errs() << ToolName << ": '" << file << "': " << "No such file\n";
317 if (MachO && Disassemble) {
318 DisassembleInputMachO(file);
322 // Attempt to open the binary.
323 OwningPtr<Binary> binary;
324 if (error_code ec = createBinary(file, binary)) {
325 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
329 if (Archive *a = dyn_cast<Archive>(binary.get())) {
331 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
334 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
338 int main(int argc, char **argv) {
339 // Print a stack trace if we signal out.
340 sys::PrintStackTraceOnErrorSignal();
341 PrettyStackTraceProgram X(argc, argv);
342 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
344 // Initialize targets and assembly printers/parsers.
345 llvm::InitializeAllTargetInfos();
346 llvm::InitializeAllTargetMCs();
347 llvm::InitializeAllAsmParsers();
348 llvm::InitializeAllDisassemblers();
350 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
351 TripleName = Triple::normalize(TripleName);
355 // Defaults to a.out if no filenames specified.
356 if (InputFilenames.size() == 0)
357 InputFilenames.push_back("a.out");
359 if (!Disassemble && !Relocations) {
360 cl::PrintHelpMessage();
364 std::for_each(InputFilenames.begin(), InputFilenames.end(),