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/StringExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/MC/MCAsmInfo.h"
25 #include "llvm/MC/MCDisassembler.h"
26 #include "llvm/MC/MCInst.h"
27 #include "llvm/MC/MCInstPrinter.h"
28 #include "llvm/MC/MCSubtargetInfo.h"
29 #include "llvm/Support/Casting.h"
30 #include "llvm/Support/CommandLine.h"
31 #include "llvm/Support/Debug.h"
32 #include "llvm/Support/FileSystem.h"
33 #include "llvm/Support/Format.h"
34 #include "llvm/Support/GraphWriter.h"
35 #include "llvm/Support/Host.h"
36 #include "llvm/Support/ManagedStatic.h"
37 #include "llvm/Support/MemoryBuffer.h"
38 #include "llvm/Support/MemoryObject.h"
39 #include "llvm/Support/PrettyStackTrace.h"
40 #include "llvm/Support/Signals.h"
41 #include "llvm/Support/SourceMgr.h"
42 #include "llvm/Support/TargetRegistry.h"
43 #include "llvm/Support/TargetSelect.h"
44 #include "llvm/Support/raw_ostream.h"
45 #include "llvm/Support/system_error.h"
49 using namespace object;
51 static cl::list<std::string>
52 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
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 Relocations("r", cl::desc("Display the relocation entries in the file"));
65 SectionContents("s", cl::desc("Display the content of each section"));
68 MachO("macho", cl::desc("Use MachO specific object file parser"));
70 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO));
73 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
74 "see -version for available targets"));
77 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
78 "see -version for available targets"));
81 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
82 "for each section."));
84 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
85 cl::aliasopt(SectionHeaders));
87 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
88 cl::aliasopt(SectionHeaders));
90 static StringRef ToolName;
92 static bool error(error_code ec) {
93 if (!ec) return false;
95 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
100 static const Target *GetTarget(const ObjectFile *Obj = NULL) {
101 // Figure out the target triple.
102 llvm::Triple TT("unknown-unknown-unknown");
103 if (TripleName.empty()) {
105 TT.setArch(Triple::ArchType(Obj->getArch()));
107 TT.setTriple(Triple::normalize(TripleName));
109 if (!ArchName.empty())
110 TT.setArchName(ArchName);
112 TripleName = TT.str();
114 // Get the target specific parser.
116 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error);
120 errs() << ToolName << ": error: unable to get target for '" << TripleName
121 << "', see --version and --triple.\n";
125 void llvm::DumpBytes(StringRef bytes) {
126 static const 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 bool RelocAddressLess(RelocationRef a, RelocationRef b) {
152 uint64_t a_addr, b_addr;
153 if (error(a.getAddress(a_addr))) return false;
154 if (error(b.getAddress(b_addr))) return false;
155 return a_addr < b_addr;
158 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
159 const Target *TheTarget = GetTarget(Obj);
161 // GetTarget prints out stuff.
166 for (section_iterator i = Obj->begin_sections(),
167 e = Obj->end_sections();
168 i != e; i.increment(ec)) {
169 if (error(ec)) break;
171 if (error(i->isText(text))) break;
174 uint64_t SectionAddr;
175 if (error(i->getAddress(SectionAddr))) break;
177 // Make a list of all the symbols in this section.
178 std::vector<std::pair<uint64_t, StringRef> > Symbols;
179 for (symbol_iterator si = Obj->begin_symbols(),
180 se = Obj->end_symbols();
181 si != se; si.increment(ec)) {
183 if (!error(i->containsSymbol(*si, contains)) && contains) {
185 if (error(si->getOffset(Address))) break;
187 if (error(si->getName(Name))) break;
188 Symbols.push_back(std::make_pair(Address, Name));
192 // Sort the symbols by address, just in case they didn't come in that way.
193 array_pod_sort(Symbols.begin(), Symbols.end());
195 // Make a list of all the relocations for this section.
196 std::vector<RelocationRef> Rels;
198 for (relocation_iterator ri = i->begin_relocations(),
199 re = i->end_relocations();
200 ri != re; ri.increment(ec)) {
201 if (error(ec)) break;
206 // Sort relocations by address.
207 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
210 if (error(i->getName(name))) break;
211 outs() << "Disassembly of section " << name << ':';
213 // If the section has no symbols just insert a dummy one and disassemble
214 // the whole section.
216 Symbols.push_back(std::make_pair(0, name));
218 // Set up disassembler.
219 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
222 errs() << "error: no assembly info for target " << TripleName << "\n";
226 OwningPtr<const MCSubtargetInfo> STI(
227 TheTarget->createMCSubtargetInfo(TripleName, "", ""));
230 errs() << "error: no subtarget info for target " << TripleName << "\n";
234 OwningPtr<const MCDisassembler> DisAsm(
235 TheTarget->createMCDisassembler(*STI));
237 errs() << "error: no disassembler for target " << TripleName << "\n";
241 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
242 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
243 AsmPrinterVariant, *AsmInfo, *STI));
245 errs() << "error: no instruction printer for target " << TripleName
251 if (error(i->getContents(Bytes))) break;
252 StringRefMemoryObject memoryObject(Bytes);
256 if (error(i->getSize(SectSize))) break;
258 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
259 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
260 // Disassemble symbol by symbol.
261 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
262 uint64_t Start = Symbols[si].first;
264 // The end is either the size of the section or the beginning of the next
268 // Make sure this symbol takes up space.
269 else if (Symbols[si + 1].first != Start)
270 End = Symbols[si + 1].first - 1;
272 // This symbol has the same address as the next symbol. Skip it.
275 outs() << '\n' << Symbols[si].second << ":\n";
278 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
280 raw_ostream &DebugOut = nulls();
283 for (Index = Start; Index < End; Index += Size) {
286 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
287 DebugOut, nulls())) {
288 outs() << format("%8x:\t", SectionAddr + Index);
289 DumpBytes(StringRef(Bytes.data() + Index, Size));
290 IP->printInst(&Inst, outs(), "");
293 errs() << ToolName << ": warning: invalid instruction encoding\n";
295 Size = 1; // skip illegible bytes
298 // Print relocation for instruction.
299 while (rel_cur != rel_end) {
301 SmallString<16> name;
303 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
304 // Stop when rel_cur's address is past the current instruction.
305 if (addr > Index + Size) break;
306 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
307 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
309 outs() << format("\t\t\t%8x: ", SectionAddr + addr) << name << "\t"
320 static void PrintRelocations(const ObjectFile *o) {
322 for (section_iterator si = o->begin_sections(), se = o->end_sections();
323 si != se; si.increment(ec)){
324 if (error(ec)) return;
325 if (si->begin_relocations() == si->end_relocations())
328 if (error(si->getName(secname))) continue;
329 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
330 for (relocation_iterator ri = si->begin_relocations(),
331 re = si->end_relocations();
332 ri != re; ri.increment(ec)) {
333 if (error(ec)) return;
336 SmallString<32> relocname;
337 SmallString<32> valuestr;
338 if (error(ri->getTypeName(relocname))) continue;
339 if (error(ri->getAddress(address))) continue;
340 if (error(ri->getValueString(valuestr))) continue;
341 outs() << address << " " << relocname << " " << valuestr << "\n";
347 static void PrintSectionHeaders(const ObjectFile *o) {
348 outs() << "Sections:\n"
349 "Idx Name Size Address Type\n";
352 for (section_iterator si = o->begin_sections(), se = o->end_sections();
353 si != se; si.increment(ec)) {
354 if (error(ec)) return;
356 if (error(si->getName(Name))) return;
358 if (error(si->getAddress(Address))) return;
360 if (error(si->getSize(Size))) return;
361 bool Text, Data, BSS;
362 if (error(si->isText(Text))) return;
363 if (error(si->isData(Data))) return;
364 if (error(si->isBSS(BSS))) return;
365 std::string Type = (std::string(Text ? "TEXT " : "") +
366 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
367 outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size,
368 Address, Type.c_str());
373 static void PrintSectionContents(const ObjectFile *o) {
375 for (section_iterator si = o->begin_sections(),
376 se = o->end_sections();
377 si != se; si.increment(ec)) {
378 if (error(ec)) return;
382 if (error(si->getName(Name))) continue;
383 if (error(si->getContents(Contents))) continue;
384 if (error(si->getAddress(BaseAddr))) continue;
386 outs() << "Contents of section " << Name << ":\n";
388 // Dump out the content as hex and printable ascii characters.
389 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
390 outs() << format(" %04x ", BaseAddr + addr);
392 for (std::size_t i = 0; i < 16; ++i) {
393 if (i != 0 && i % 4 == 0)
396 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
397 << hexdigit(Contents[addr + i] & 0xF, true);
403 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
404 if (std::isprint(Contents[addr + i] & 0xFF))
405 outs() << Contents[addr + i];
414 static void DumpObject(const ObjectFile *o) {
416 outs() << o->getFileName()
417 << ":\tfile format " << o->getFileFormatName() << "\n\n";
420 DisassembleObject(o, Relocations);
421 if (Relocations && !Disassemble)
424 PrintSectionHeaders(o);
426 PrintSectionContents(o);
429 /// @brief Dump each object file in \a a;
430 static void DumpArchive(const Archive *a) {
431 for (Archive::child_iterator i = a->begin_children(),
432 e = a->end_children(); i != e; ++i) {
433 OwningPtr<Binary> child;
434 if (error_code ec = i->getAsBinary(child)) {
435 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
439 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
442 errs() << ToolName << ": '" << a->getFileName() << "': "
443 << "Unrecognized file type.\n";
447 /// @brief Open file and figure out how to dump it.
448 static void DumpInput(StringRef file) {
449 // If file isn't stdin, check that it exists.
450 if (file != "-" && !sys::fs::exists(file)) {
451 errs() << ToolName << ": '" << file << "': " << "No such file\n";
455 if (MachO && Disassemble) {
456 DisassembleInputMachO(file);
460 // Attempt to open the binary.
461 OwningPtr<Binary> binary;
462 if (error_code ec = createBinary(file, binary)) {
463 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
467 if (Archive *a = dyn_cast<Archive>(binary.get())) {
469 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) {
472 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
476 int main(int argc, char **argv) {
477 // Print a stack trace if we signal out.
478 sys::PrintStackTraceOnErrorSignal();
479 PrettyStackTraceProgram X(argc, argv);
480 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
482 // Initialize targets and assembly printers/parsers.
483 llvm::InitializeAllTargetInfos();
484 llvm::InitializeAllTargetMCs();
485 llvm::InitializeAllAsmParsers();
486 llvm::InitializeAllDisassemblers();
488 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
489 TripleName = Triple::normalize(TripleName);
493 // Defaults to a.out if no filenames specified.
494 if (InputFilenames.size() == 0)
495 InputFilenames.push_back("a.out");
497 if (!Disassemble && !Relocations && !SectionHeaders && !SectionContents) {
498 cl::PrintHelpMessage();
502 std::for_each(InputFilenames.begin(), InputFilenames.end(),