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 // The flags and output of this program should be near identical to those of
17 //===----------------------------------------------------------------------===//
19 #include "llvm-objdump.h"
20 #include "MCFunction.h"
21 #include "llvm/ADT/OwningPtr.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/MC/MCAsmInfo.h"
26 #include "llvm/MC/MCDisassembler.h"
27 #include "llvm/MC/MCInst.h"
28 #include "llvm/MC/MCInstPrinter.h"
29 #include "llvm/MC/MCInstrInfo.h"
30 #include "llvm/MC/MCRegisterInfo.h"
31 #include "llvm/MC/MCSubtargetInfo.h"
32 #include "llvm/Object/Archive.h"
33 #include "llvm/Object/COFF.h"
34 #include "llvm/Object/MachO.h"
35 #include "llvm/Object/ObjectFile.h"
36 #include "llvm/Support/Casting.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Debug.h"
39 #include "llvm/Support/FileSystem.h"
40 #include "llvm/Support/Format.h"
41 #include "llvm/Support/GraphWriter.h"
42 #include "llvm/Support/Host.h"
43 #include "llvm/Support/ManagedStatic.h"
44 #include "llvm/Support/MemoryBuffer.h"
45 #include "llvm/Support/MemoryObject.h"
46 #include "llvm/Support/PrettyStackTrace.h"
47 #include "llvm/Support/Signals.h"
48 #include "llvm/Support/SourceMgr.h"
49 #include "llvm/Support/TargetRegistry.h"
50 #include "llvm/Support/TargetSelect.h"
51 #include "llvm/Support/raw_ostream.h"
52 #include "llvm/Support/system_error.h"
57 using namespace object;
59 static cl::list<std::string>
60 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore);
63 Disassemble("disassemble",
64 cl::desc("Display assembler mnemonics for the machine instructions"));
66 Disassembled("d", cl::desc("Alias for --disassemble"),
67 cl::aliasopt(Disassemble));
70 Relocations("r", cl::desc("Display the relocation entries in the file"));
73 SectionContents("s", cl::desc("Display the content of each section"));
76 SymbolTable("t", cl::desc("Display the symbol table"));
79 MachOOpt("macho", cl::desc("Use MachO specific object file parser"));
81 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt));
84 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, "
85 "see -version for available targets"));
88 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, "
89 "see -version for available targets"));
92 SectionHeaders("section-headers", cl::desc("Display summaries of the headers "
93 "for each section."));
95 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"),
96 cl::aliasopt(SectionHeaders));
98 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"),
99 cl::aliasopt(SectionHeaders));
101 static cl::list<std::string>
104 cl::desc("Target specific attributes"),
105 cl::value_desc("a1,+a2,-a3,..."));
108 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, "
109 "do not print the instruction bytes."));
112 UnwindInfo("unwind-info", cl::desc("Display unwind information"));
115 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"),
116 cl::aliasopt(UnwindInfo));
119 PrivateHeaders("private-headers",
120 cl::desc("Display format specific file headers"));
123 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"),
124 cl::aliasopt(PrivateHeaders));
126 static StringRef ToolName;
128 bool llvm::error(error_code ec) {
129 if (!ec) return false;
131 outs() << ToolName << ": error reading file: " << ec.message() << ".\n";
136 static const Target *getTarget(const ObjectFile *Obj = NULL) {
137 // Figure out the target triple.
138 llvm::Triple TheTriple("unknown-unknown-unknown");
139 if (TripleName.empty()) {
141 TheTriple.setArch(Triple::ArchType(Obj->getArch()));
143 TheTriple.setTriple(Triple::normalize(TripleName));
145 // Get the target specific parser.
147 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple,
150 errs() << ToolName << ": " << Error;
154 // Update the triple name and return the found target.
155 TripleName = TheTriple.getTriple();
159 void llvm::StringRefMemoryObject::anchor() { }
161 void llvm::DumpBytes(StringRef bytes) {
162 static const char hex_rep[] = "0123456789abcdef";
163 // FIXME: The real way to do this is to figure out the longest instruction
164 // and align to that size before printing. I'll fix this when I get
165 // around to outputting relocations.
166 // 15 is the longest x86 instruction
167 // 3 is for the hex rep of a byte + a space.
168 // 1 is for the null terminator.
169 enum { OutputSize = (15 * 3) + 1 };
170 char output[OutputSize];
172 assert(bytes.size() <= 15
173 && "DumpBytes only supports instructions of up to 15 bytes");
174 memset(output, ' ', sizeof(output));
176 for (StringRef::iterator i = bytes.begin(),
177 e = bytes.end(); i != e; ++i) {
178 output[index] = hex_rep[(*i & 0xF0) >> 4];
179 output[index + 1] = hex_rep[*i & 0xF];
183 output[sizeof(output) - 1] = 0;
187 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) {
188 uint64_t a_addr, b_addr;
189 if (error(a.getAddress(a_addr))) return false;
190 if (error(b.getAddress(b_addr))) return false;
191 return a_addr < b_addr;
194 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) {
195 const Target *TheTarget = getTarget(Obj);
196 // getTarget() will have already issued a diagnostic if necessary, so
197 // just bail here if it failed.
201 // Package up features to be passed to target/subtarget
202 std::string FeaturesStr;
204 SubtargetFeatures Features;
205 for (unsigned i = 0; i != MAttrs.size(); ++i)
206 Features.AddFeature(MAttrs[i]);
207 FeaturesStr = Features.getString();
211 for (section_iterator i = Obj->begin_sections(),
212 e = Obj->end_sections();
213 i != e; i.increment(ec)) {
214 if (error(ec)) break;
216 if (error(i->isText(text))) break;
219 uint64_t SectionAddr;
220 if (error(i->getAddress(SectionAddr))) break;
222 // Make a list of all the symbols in this section.
223 std::vector<std::pair<uint64_t, StringRef> > Symbols;
224 for (symbol_iterator si = Obj->begin_symbols(),
225 se = Obj->end_symbols();
226 si != se; si.increment(ec)) {
228 if (!error(i->containsSymbol(*si, contains)) && contains) {
230 if (error(si->getAddress(Address))) break;
231 Address -= SectionAddr;
234 if (error(si->getName(Name))) break;
235 Symbols.push_back(std::make_pair(Address, Name));
239 // Sort the symbols by address, just in case they didn't come in that way.
240 array_pod_sort(Symbols.begin(), Symbols.end());
242 // Make a list of all the relocations for this section.
243 std::vector<RelocationRef> Rels;
245 for (relocation_iterator ri = i->begin_relocations(),
246 re = i->end_relocations();
247 ri != re; ri.increment(ec)) {
248 if (error(ec)) break;
253 // Sort relocations by address.
254 std::sort(Rels.begin(), Rels.end(), RelocAddressLess);
256 StringRef SegmentName = "";
257 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) {
258 DataRefImpl DR = i->getRawDataRefImpl();
259 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
263 if (error(i->getName(name))) break;
264 outs() << "Disassembly of section ";
265 if (!SegmentName.empty())
266 outs() << SegmentName << ",";
267 outs() << name << ':';
269 // If the section has no symbols just insert a dummy one and disassemble
270 // the whole section.
272 Symbols.push_back(std::make_pair(0, name));
274 // Set up disassembler.
275 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName));
278 errs() << "error: no assembly info for target " << TripleName << "\n";
282 OwningPtr<const MCSubtargetInfo> STI(
283 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr));
286 errs() << "error: no subtarget info for target " << TripleName << "\n";
290 OwningPtr<const MCDisassembler> DisAsm(
291 TheTarget->createMCDisassembler(*STI));
293 errs() << "error: no disassembler for target " << TripleName << "\n";
297 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName));
299 errs() << "error: no register info for target " << TripleName << "\n";
303 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo());
305 errs() << "error: no instruction info for target " << TripleName << "\n";
309 int AsmPrinterVariant = AsmInfo->getAssemblerDialect();
310 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter(
311 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI));
313 errs() << "error: no instruction printer for target " << TripleName
319 if (error(i->getContents(Bytes))) break;
320 StringRefMemoryObject memoryObject(Bytes);
324 if (error(i->getSize(SectSize))) break;
326 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin();
327 std::vector<RelocationRef>::const_iterator rel_end = Rels.end();
328 // Disassemble symbol by symbol.
329 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) {
330 uint64_t Start = Symbols[si].first;
332 // The end is either the size of the section or the beginning of the next
336 // Make sure this symbol takes up space.
337 else if (Symbols[si + 1].first != Start)
338 End = Symbols[si + 1].first - 1;
340 // This symbol has the same address as the next symbol. Skip it.
343 outs() << '\n' << Symbols[si].second << ":\n";
346 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls();
348 raw_ostream &DebugOut = nulls();
351 for (Index = Start; Index < End; Index += Size) {
354 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index,
355 DebugOut, nulls())) {
356 outs() << format("%8" PRIx64 ":", SectionAddr + Index);
357 if (!NoShowRawInsn) {
359 DumpBytes(StringRef(Bytes.data() + Index, Size));
361 IP->printInst(&Inst, outs(), "");
364 errs() << ToolName << ": warning: invalid instruction encoding\n";
366 Size = 1; // skip illegible bytes
369 // Print relocation for instruction.
370 while (rel_cur != rel_end) {
373 SmallString<16> name;
376 // If this relocation is hidden, skip it.
377 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel;
378 if (hidden) goto skip_print_rel;
380 if (error(rel_cur->getAddress(addr))) goto skip_print_rel;
381 // Stop when rel_cur's address is past the current instruction.
382 if (addr >= Index + Size) break;
383 if (error(rel_cur->getTypeName(name))) goto skip_print_rel;
384 if (error(rel_cur->getValueString(val))) goto skip_print_rel;
386 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name
387 << "\t" << val << "\n";
397 static void PrintRelocations(const ObjectFile *o) {
399 for (section_iterator si = o->begin_sections(), se = o->end_sections();
400 si != se; si.increment(ec)){
401 if (error(ec)) return;
402 if (si->begin_relocations() == si->end_relocations())
405 if (error(si->getName(secname))) continue;
406 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n";
407 for (relocation_iterator ri = si->begin_relocations(),
408 re = si->end_relocations();
409 ri != re; ri.increment(ec)) {
410 if (error(ec)) return;
414 SmallString<32> relocname;
415 SmallString<32> valuestr;
416 if (error(ri->getHidden(hidden))) continue;
417 if (hidden) continue;
418 if (error(ri->getTypeName(relocname))) continue;
419 if (error(ri->getAddress(address))) continue;
420 if (error(ri->getValueString(valuestr))) continue;
421 outs() << address << " " << relocname << " " << valuestr << "\n";
427 static void PrintSectionHeaders(const ObjectFile *o) {
428 outs() << "Sections:\n"
429 "Idx Name Size Address Type\n";
432 for (section_iterator si = o->begin_sections(), se = o->end_sections();
433 si != se; si.increment(ec)) {
434 if (error(ec)) return;
436 if (error(si->getName(Name))) return;
438 if (error(si->getAddress(Address))) return;
440 if (error(si->getSize(Size))) return;
441 bool Text, Data, BSS;
442 if (error(si->isText(Text))) return;
443 if (error(si->isData(Data))) return;
444 if (error(si->isBSS(BSS))) return;
445 std::string Type = (std::string(Text ? "TEXT " : "") +
446 (Data ? "DATA " : "") + (BSS ? "BSS" : ""));
447 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n",
448 i, Name.str().c_str(), Size, Address, Type.c_str());
453 static void PrintSectionContents(const ObjectFile *o) {
455 for (section_iterator si = o->begin_sections(),
456 se = o->end_sections();
457 si != se; si.increment(ec)) {
458 if (error(ec)) return;
462 if (error(si->getName(Name))) continue;
463 if (error(si->getContents(Contents))) continue;
464 if (error(si->getAddress(BaseAddr))) continue;
466 outs() << "Contents of section " << Name << ":\n";
468 // Dump out the content as hex and printable ascii characters.
469 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) {
470 outs() << format(" %04" PRIx64 " ", BaseAddr + addr);
472 for (std::size_t i = 0; i < 16; ++i) {
473 if (i != 0 && i % 4 == 0)
476 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true)
477 << hexdigit(Contents[addr + i] & 0xF, true);
483 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) {
484 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF))
485 outs() << Contents[addr + i];
494 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) {
495 const coff_file_header *header;
496 if (error(coff->getHeader(header))) return;
498 const coff_symbol *symbol = 0;
499 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) {
501 // Figure out which type of aux this is.
502 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC
503 && symbol->Value == 0) { // Section definition.
504 const coff_aux_section_definition *asd;
505 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd)))
508 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x "
509 , unsigned(asd->Length)
510 , unsigned(asd->NumberOfRelocations)
511 , unsigned(asd->NumberOfLinenumbers)
512 , unsigned(asd->CheckSum))
513 << format("assoc %d comdat %d\n"
514 , unsigned(asd->Number)
515 , unsigned(asd->Selection));
517 outs() << "AUX Unknown\n";
520 if (error(coff->getSymbol(i, symbol))) return;
521 if (error(coff->getSymbolName(symbol, name))) return;
522 outs() << "[" << format("%2d", i) << "]"
523 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")"
524 << "(fl 0x00)" // Flag bits, which COFF doesn't have.
525 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")"
526 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") "
527 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") "
528 << "0x" << format("%08x", unsigned(symbol->Value)) << " "
530 aux_count = symbol->NumberOfAuxSymbols;
535 static void PrintSymbolTable(const ObjectFile *o) {
536 outs() << "SYMBOL TABLE:\n";
538 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o))
539 PrintCOFFSymbolTable(coff);
542 for (symbol_iterator si = o->begin_symbols(),
543 se = o->end_symbols(); si != se; si.increment(ec)) {
544 if (error(ec)) return;
547 SymbolRef::Type Type;
550 section_iterator Section = o->end_sections();
551 if (error(si->getName(Name))) continue;
552 if (error(si->getAddress(Address))) continue;
553 if (error(si->getFlags(Flags))) continue;
554 if (error(si->getType(Type))) continue;
555 if (error(si->getSize(Size))) continue;
556 if (error(si->getSection(Section))) continue;
558 bool Global = Flags & SymbolRef::SF_Global;
559 bool Weak = Flags & SymbolRef::SF_Weak;
560 bool Absolute = Flags & SymbolRef::SF_Absolute;
562 if (Address == UnknownAddressOrSize)
564 if (Size == UnknownAddressOrSize)
567 if (Type != SymbolRef::ST_Unknown)
568 GlobLoc = Global ? 'g' : 'l';
569 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File)
572 if (Type == SymbolRef::ST_File)
574 else if (Type == SymbolRef::ST_Function)
577 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 :
580 outs() << format(Fmt, Address) << " "
581 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' '
582 << (Weak ? 'w' : ' ') // Weak?
583 << ' ' // Constructor. Not supported yet.
584 << ' ' // Warning. Not supported yet.
585 << ' ' // Indirect reference to another symbol.
586 << Debug // Debugging (d) or dynamic (D) symbol.
587 << FileFunc // Name of function (F), file (f) or object (O).
591 else if (Section == o->end_sections())
594 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(o)) {
595 StringRef SegmentName;
596 DataRefImpl DR = Section->getRawDataRefImpl();
597 if (error(MachO->getSectionFinalSegmentName(DR, SegmentName)))
599 outs() << SegmentName << ",";
601 StringRef SectionName;
602 if (error(Section->getName(SectionName)))
604 outs() << SectionName;
607 << format("%08" PRIx64 " ", Size)
614 static void PrintUnwindInfo(const ObjectFile *o) {
615 outs() << "Unwind info:\n\n";
617 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) {
618 printCOFFUnwindInfo(coff);
620 // TODO: Extract DWARF dump tool to objdump.
621 errs() << "This operation is only currently supported "
622 "for COFF object files.\n";
627 static void DumpObject(const ObjectFile *o) {
629 outs() << o->getFileName()
630 << ":\tfile format " << o->getFileFormatName() << "\n\n";
633 DisassembleObject(o, Relocations);
634 if (Relocations && !Disassemble)
637 PrintSectionHeaders(o);
639 PrintSectionContents(o);
644 if (PrivateHeaders && o->isELF())
645 printELFFileHeader(o);
648 /// @brief Dump each object file in \a a;
649 static void DumpArchive(const Archive *a) {
650 for (Archive::child_iterator i = a->begin_children(),
651 e = a->end_children(); i != e; ++i) {
652 OwningPtr<Binary> child;
653 if (error_code ec = i->getAsBinary(child)) {
654 // Ignore non-object files.
655 if (ec != object_error::invalid_file_type)
656 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message()
660 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get()))
663 errs() << ToolName << ": '" << a->getFileName() << "': "
664 << "Unrecognized file type.\n";
668 /// @brief Open file and figure out how to dump it.
669 static void DumpInput(StringRef file) {
670 // If file isn't stdin, check that it exists.
671 if (file != "-" && !sys::fs::exists(file)) {
672 errs() << ToolName << ": '" << file << "': " << "No such file\n";
676 if (MachOOpt && Disassemble) {
677 DisassembleInputMachO(file);
681 // Attempt to open the binary.
682 OwningPtr<Binary> binary;
683 if (error_code ec = createBinary(file, binary)) {
684 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n";
688 if (Archive *a = dyn_cast<Archive>(binary.get()))
690 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get()))
693 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n";
696 int main(int argc, char **argv) {
697 // Print a stack trace if we signal out.
698 sys::PrintStackTraceOnErrorSignal();
699 PrettyStackTraceProgram X(argc, argv);
700 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit.
702 // Initialize targets and assembly printers/parsers.
703 llvm::InitializeAllTargetInfos();
704 llvm::InitializeAllTargetMCs();
705 llvm::InitializeAllAsmParsers();
706 llvm::InitializeAllDisassemblers();
708 // Register the target printer for --version.
709 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion);
711 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n");
712 TripleName = Triple::normalize(TripleName);
716 // Defaults to a.out if no filenames specified.
717 if (InputFilenames.size() == 0)
718 InputFilenames.push_back("a.out");
726 && !PrivateHeaders) {
727 cl::PrintHelpMessage();
731 std::for_each(InputFilenames.begin(), InputFilenames.end(),