1 //===-- llvm-objdump.cpp - Object file dumping utility for llvm -----------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 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 12 // flags. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #include "llvm-objdump.h" 17 #include "MCFunction.h" 18 #include "llvm/Object/Archive.h" 19 #include "llvm/Object/COFF.h" 20 #include "llvm/Object/ObjectFile.h" 21 #include "llvm/ADT/OwningPtr.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/ADT/STLExtras.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/MCSubtargetInfo.h" 30 #include "llvm/Support/Casting.h" 31 #include "llvm/Support/CommandLine.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/FileSystem.h" 34 #include "llvm/Support/Format.h" 35 #include "llvm/Support/GraphWriter.h" 36 #include "llvm/Support/Host.h" 37 #include "llvm/Support/ManagedStatic.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/MemoryObject.h" 40 #include "llvm/Support/PrettyStackTrace.h" 41 #include "llvm/Support/Signals.h" 42 #include "llvm/Support/SourceMgr.h" 43 #include "llvm/Support/TargetRegistry.h" 44 #include "llvm/Support/TargetSelect.h" 45 #include "llvm/Support/raw_ostream.h" 46 #include "llvm/Support/system_error.h" 47 #include <algorithm> 48 #include <cstring> 49 using namespace llvm; 50 using namespace object; 51 52 static cl::list<std::string> 53 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 54 55 static cl::opt<bool> 56 Disassemble("disassemble", 57 cl::desc("Display assembler mnemonics for the machine instructions")); 58 static cl::alias 59 Disassembled("d", cl::desc("Alias for --disassemble"), 60 cl::aliasopt(Disassemble)); 61 62 static cl::opt<bool> 63 Relocations("r", cl::desc("Display the relocation entries in the file")); 64 65 static cl::opt<bool> 66 SectionContents("s", cl::desc("Display the content of each section")); 67 68 static cl::opt<bool> 69 SymbolTable("t", cl::desc("Display the symbol table")); 70 71 static cl::opt<bool> 72 MachO("macho", cl::desc("Use MachO specific object file parser")); 73 static cl::alias 74 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO)); 75 76 cl::opt<std::string> 77 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 78 "see -version for available targets")); 79 80 cl::opt<std::string> 81 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " 82 "see -version for available targets")); 83 84 static cl::opt<bool> 85 SectionHeaders("section-headers", cl::desc("Display summaries of the headers " 86 "for each section.")); 87 static cl::alias 88 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 89 cl::aliasopt(SectionHeaders)); 90 static cl::alias 91 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 92 cl::aliasopt(SectionHeaders)); 93 94 static StringRef ToolName; 95 96 static bool error(error_code ec) { 97 if (!ec) return false; 98 99 outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; 100 outs().flush(); 101 return true; 102 } 103 104 static const Target *GetTarget(const ObjectFile *Obj = NULL) { 105 // Figure out the target triple. 106 llvm::Triple TT("unknown-unknown-unknown"); 107 if (TripleName.empty()) { 108 if (Obj) 109 TT.setArch(Triple::ArchType(Obj->getArch())); 110 } else 111 TT.setTriple(Triple::normalize(TripleName)); 112 113 if (!ArchName.empty()) 114 TT.setArchName(ArchName); 115 116 TripleName = TT.str(); 117 118 // Get the target specific parser. 119 std::string Error; 120 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 121 if (TheTarget) 122 return TheTarget; 123 124 errs() << ToolName << ": error: unable to get target for '" << TripleName 125 << "', see --version and --triple.\n"; 126 return 0; 127 } 128 129 void llvm::DumpBytes(StringRef bytes) { 130 static const char hex_rep[] = "0123456789abcdef"; 131 // FIXME: The real way to do this is to figure out the longest instruction 132 // and align to that size before printing. I'll fix this when I get 133 // around to outputting relocations. 134 // 15 is the longest x86 instruction 135 // 3 is for the hex rep of a byte + a space. 136 // 1 is for the null terminator. 137 enum { OutputSize = (15 * 3) + 1 }; 138 char output[OutputSize]; 139 140 assert(bytes.size() <= 15 141 && "DumpBytes only supports instructions of up to 15 bytes"); 142 memset(output, ' ', sizeof(output)); 143 unsigned index = 0; 144 for (StringRef::iterator i = bytes.begin(), 145 e = bytes.end(); i != e; ++i) { 146 output[index] = hex_rep[(*i & 0xF0) >> 4]; 147 output[index + 1] = hex_rep[*i & 0xF]; 148 index += 3; 149 } 150 151 output[sizeof(output) - 1] = 0; 152 outs() << output; 153 } 154 155 static bool RelocAddressLess(RelocationRef a, RelocationRef b) { 156 uint64_t a_addr, b_addr; 157 if (error(a.getAddress(a_addr))) return false; 158 if (error(b.getAddress(b_addr))) return false; 159 return a_addr < b_addr; 160 } 161 162 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 163 const Target *TheTarget = GetTarget(Obj); 164 if (!TheTarget) { 165 // GetTarget prints out stuff. 166 return; 167 } 168 169 error_code ec; 170 for (section_iterator i = Obj->begin_sections(), 171 e = Obj->end_sections(); 172 i != e; i.increment(ec)) { 173 if (error(ec)) break; 174 bool text; 175 if (error(i->isText(text))) break; 176 if (!text) continue; 177 178 uint64_t SectionAddr; 179 if (error(i->getAddress(SectionAddr))) break; 180 181 // Make a list of all the symbols in this section. 182 std::vector<std::pair<uint64_t, StringRef> > Symbols; 183 for (symbol_iterator si = Obj->begin_symbols(), 184 se = Obj->end_symbols(); 185 si != se; si.increment(ec)) { 186 bool contains; 187 if (!error(i->containsSymbol(*si, contains)) && contains) { 188 uint64_t Address; 189 if (error(si->getOffset(Address))) break; 190 StringRef Name; 191 if (error(si->getName(Name))) break; 192 Symbols.push_back(std::make_pair(Address, Name)); 193 } 194 } 195 196 // Sort the symbols by address, just in case they didn't come in that way. 197 array_pod_sort(Symbols.begin(), Symbols.end()); 198 199 // Make a list of all the relocations for this section. 200 std::vector<RelocationRef> Rels; 201 if (InlineRelocs) { 202 for (relocation_iterator ri = i->begin_relocations(), 203 re = i->end_relocations(); 204 ri != re; ri.increment(ec)) { 205 if (error(ec)) break; 206 Rels.push_back(*ri); 207 } 208 } 209 210 // Sort relocations by address. 211 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 212 213 StringRef name; 214 if (error(i->getName(name))) break; 215 outs() << "Disassembly of section " << name << ':'; 216 217 // If the section has no symbols just insert a dummy one and disassemble 218 // the whole section. 219 if (Symbols.empty()) 220 Symbols.push_back(std::make_pair(0, name)); 221 222 // Set up disassembler. 223 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName)); 224 225 if (!AsmInfo) { 226 errs() << "error: no assembly info for target " << TripleName << "\n"; 227 return; 228 } 229 230 OwningPtr<const MCSubtargetInfo> STI( 231 TheTarget->createMCSubtargetInfo(TripleName, "", "")); 232 233 if (!STI) { 234 errs() << "error: no subtarget info for target " << TripleName << "\n"; 235 return; 236 } 237 238 OwningPtr<const MCDisassembler> DisAsm( 239 TheTarget->createMCDisassembler(*STI)); 240 if (!DisAsm) { 241 errs() << "error: no disassembler for target " << TripleName << "\n"; 242 return; 243 } 244 245 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 246 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 247 AsmPrinterVariant, *AsmInfo, *STI)); 248 if (!IP) { 249 errs() << "error: no instruction printer for target " << TripleName 250 << '\n'; 251 return; 252 } 253 254 StringRef Bytes; 255 if (error(i->getContents(Bytes))) break; 256 StringRefMemoryObject memoryObject(Bytes); 257 uint64_t Size; 258 uint64_t Index; 259 uint64_t SectSize; 260 if (error(i->getSize(SectSize))) break; 261 262 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 263 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 264 // Disassemble symbol by symbol. 265 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 266 uint64_t Start = Symbols[si].first; 267 uint64_t End; 268 // The end is either the size of the section or the beginning of the next 269 // symbol. 270 if (si == se - 1) 271 End = SectSize; 272 // Make sure this symbol takes up space. 273 else if (Symbols[si + 1].first != Start) 274 End = Symbols[si + 1].first - 1; 275 else 276 // This symbol has the same address as the next symbol. Skip it. 277 continue; 278 279 outs() << '\n' << Symbols[si].second << ":\n"; 280 281 #ifndef NDEBUG 282 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 283 #else 284 raw_ostream &DebugOut = nulls(); 285 #endif 286 287 for (Index = Start; Index < End; Index += Size) { 288 MCInst Inst; 289 290 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, 291 DebugOut, nulls())) { 292 outs() << format("%8x:\t", SectionAddr + Index); 293 DumpBytes(StringRef(Bytes.data() + Index, Size)); 294 IP->printInst(&Inst, outs(), ""); 295 outs() << "\n"; 296 } else { 297 errs() << ToolName << ": warning: invalid instruction encoding\n"; 298 if (Size == 0) 299 Size = 1; // skip illegible bytes 300 } 301 302 // Print relocation for instruction. 303 while (rel_cur != rel_end) { 304 uint64_t addr; 305 SmallString<16> name; 306 SmallString<32> val; 307 if (error(rel_cur->getAddress(addr))) goto skip_print_rel; 308 // Stop when rel_cur's address is past the current instruction. 309 if (addr > Index + Size) break; 310 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 311 if (error(rel_cur->getValueString(val))) goto skip_print_rel; 312 313 outs() << format("\t\t\t%8x: ", SectionAddr + addr) << name << "\t" 314 << val << "\n"; 315 316 skip_print_rel: 317 ++rel_cur; 318 } 319 } 320 } 321 } 322 } 323 324 static void PrintRelocations(const ObjectFile *o) { 325 error_code ec; 326 for (section_iterator si = o->begin_sections(), se = o->end_sections(); 327 si != se; si.increment(ec)){ 328 if (error(ec)) return; 329 if (si->begin_relocations() == si->end_relocations()) 330 continue; 331 StringRef secname; 332 if (error(si->getName(secname))) continue; 333 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 334 for (relocation_iterator ri = si->begin_relocations(), 335 re = si->end_relocations(); 336 ri != re; ri.increment(ec)) { 337 if (error(ec)) return; 338 339 uint64_t address; 340 SmallString<32> relocname; 341 SmallString<32> valuestr; 342 if (error(ri->getTypeName(relocname))) continue; 343 if (error(ri->getAddress(address))) continue; 344 if (error(ri->getValueString(valuestr))) continue; 345 outs() << address << " " << relocname << " " << valuestr << "\n"; 346 } 347 outs() << "\n"; 348 } 349 } 350 351 static void PrintSectionHeaders(const ObjectFile *o) { 352 outs() << "Sections:\n" 353 "Idx Name Size Address Type\n"; 354 error_code ec; 355 unsigned i = 0; 356 for (section_iterator si = o->begin_sections(), se = o->end_sections(); 357 si != se; si.increment(ec)) { 358 if (error(ec)) return; 359 StringRef Name; 360 if (error(si->getName(Name))) return; 361 uint64_t Address; 362 if (error(si->getAddress(Address))) return; 363 uint64_t Size; 364 if (error(si->getSize(Size))) return; 365 bool Text, Data, BSS; 366 if (error(si->isText(Text))) return; 367 if (error(si->isData(Data))) return; 368 if (error(si->isBSS(BSS))) return; 369 std::string Type = (std::string(Text ? "TEXT " : "") + 370 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 371 outs() << format("%3d %-13s %09"PRIx64" %017"PRIx64" %s\n", i, Name.str().c_str(), Size, 372 Address, Type.c_str()); 373 ++i; 374 } 375 } 376 377 static void PrintSectionContents(const ObjectFile *o) { 378 error_code ec; 379 for (section_iterator si = o->begin_sections(), 380 se = o->end_sections(); 381 si != se; si.increment(ec)) { 382 if (error(ec)) return; 383 StringRef Name; 384 StringRef Contents; 385 uint64_t BaseAddr; 386 if (error(si->getName(Name))) continue; 387 if (error(si->getContents(Contents))) continue; 388 if (error(si->getAddress(BaseAddr))) continue; 389 390 outs() << "Contents of section " << Name << ":\n"; 391 392 // Dump out the content as hex and printable ascii characters. 393 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 394 outs() << format(" %04x ", BaseAddr + addr); 395 // Dump line of hex. 396 for (std::size_t i = 0; i < 16; ++i) { 397 if (i != 0 && i % 4 == 0) 398 outs() << ' '; 399 if (addr + i < end) 400 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 401 << hexdigit(Contents[addr + i] & 0xF, true); 402 else 403 outs() << " "; 404 } 405 // Print ascii. 406 outs() << " "; 407 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 408 if (std::isprint(Contents[addr + i] & 0xFF)) 409 outs() << Contents[addr + i]; 410 else 411 outs() << "."; 412 } 413 outs() << "\n"; 414 } 415 } 416 } 417 418 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 419 const coff_file_header *header; 420 if (error(coff->getHeader(header))) return; 421 int aux_count = 0; 422 const coff_symbol *symbol = 0; 423 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) { 424 if (aux_count--) { 425 // Figure out which type of aux this is. 426 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC 427 && symbol->Value == 0) { // Section definition. 428 const coff_aux_section_definition *asd; 429 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd))) 430 return; 431 outs() << "AUX " 432 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 433 , unsigned(asd->Length) 434 , unsigned(asd->NumberOfRelocations) 435 , unsigned(asd->NumberOfLinenumbers) 436 , unsigned(asd->CheckSum)) 437 << format("assoc %d comdat %d\n" 438 , unsigned(asd->Number) 439 , unsigned(asd->Selection)); 440 } else { 441 outs() << "AUX Unknown\n"; 442 } 443 } else { 444 StringRef name; 445 if (error(coff->getSymbol(i, symbol))) return; 446 if (error(coff->getSymbolName(symbol, name))) return; 447 outs() << "[" << format("%2d", i) << "]" 448 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")" 449 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 450 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")" 451 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") " 452 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") " 453 << "0x" << format("%08x", unsigned(symbol->Value)) << " " 454 << name << "\n"; 455 aux_count = symbol->NumberOfAuxSymbols; 456 } 457 } 458 } 459 460 static void PrintSymbolTable(const ObjectFile *o) { 461 outs() << "SYMBOL TABLE:\n"; 462 463 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) 464 PrintCOFFSymbolTable(coff); 465 else { 466 error_code ec; 467 for (symbol_iterator si = o->begin_symbols(), 468 se = o->end_symbols(); si != se; si.increment(ec)) { 469 if (error(ec)) return; 470 StringRef Name; 471 uint64_t Offset; 472 bool Global; 473 SymbolRef::Type Type; 474 bool Weak; 475 bool Absolute; 476 uint64_t Size; 477 section_iterator Section = o->end_sections(); 478 if (error(si->getName(Name))) continue; 479 if (error(si->getOffset(Offset))) continue; 480 if (error(si->isGlobal(Global))) continue; 481 if (error(si->getType(Type))) continue; 482 if (error(si->isWeak(Weak))) continue; 483 if (error(si->isAbsolute(Absolute))) continue; 484 if (error(si->getSize(Size))) continue; 485 if (error(si->getSection(Section))) continue; 486 487 if (Offset == UnknownAddressOrSize) 488 Offset = 0; 489 char GlobLoc = ' '; 490 if (Type != SymbolRef::ST_External) 491 GlobLoc = Global ? 'g' : 'l'; 492 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 493 ? 'd' : ' '; 494 char FileFunc = ' '; 495 if (Type == SymbolRef::ST_File) 496 FileFunc = 'f'; 497 else if (Type == SymbolRef::ST_Function) 498 FileFunc = 'F'; 499 500 outs() << format("%08x", Offset) << " " 501 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 502 << (Weak ? 'w' : ' ') // Weak? 503 << ' ' // Constructor. Not supported yet. 504 << ' ' // Warning. Not supported yet. 505 << ' ' // Indirect reference to another symbol. 506 << Debug // Debugging (d) or dynamic (D) symbol. 507 << FileFunc // Name of function (F), file (f) or object (O). 508 << ' '; 509 if (Absolute) 510 outs() << "*ABS*"; 511 else if (Section == o->end_sections()) 512 outs() << "*UND*"; 513 else { 514 StringRef SectionName; 515 if (error(Section->getName(SectionName))) 516 SectionName = ""; 517 outs() << SectionName; 518 } 519 outs() << '\t' 520 << format("%08x ", Size) 521 << Name 522 << '\n'; 523 } 524 } 525 } 526 527 static void DumpObject(const ObjectFile *o) { 528 outs() << '\n'; 529 outs() << o->getFileName() 530 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 531 532 if (Disassemble) 533 DisassembleObject(o, Relocations); 534 if (Relocations && !Disassemble) 535 PrintRelocations(o); 536 if (SectionHeaders) 537 PrintSectionHeaders(o); 538 if (SectionContents) 539 PrintSectionContents(o); 540 if (SymbolTable) 541 PrintSymbolTable(o); 542 } 543 544 /// @brief Dump each object file in \a a; 545 static void DumpArchive(const Archive *a) { 546 for (Archive::child_iterator i = a->begin_children(), 547 e = a->end_children(); i != e; ++i) { 548 OwningPtr<Binary> child; 549 if (error_code ec = i->getAsBinary(child)) { 550 errs() << ToolName << ": '" << a->getFileName() << "': " << ec.message() 551 << ".\n"; 552 continue; 553 } 554 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) 555 DumpObject(o); 556 else 557 errs() << ToolName << ": '" << a->getFileName() << "': " 558 << "Unrecognized file type.\n"; 559 } 560 } 561 562 /// @brief Open file and figure out how to dump it. 563 static void DumpInput(StringRef file) { 564 // If file isn't stdin, check that it exists. 565 if (file != "-" && !sys::fs::exists(file)) { 566 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 567 return; 568 } 569 570 if (MachO && Disassemble) { 571 DisassembleInputMachO(file); 572 return; 573 } 574 575 // Attempt to open the binary. 576 OwningPtr<Binary> binary; 577 if (error_code ec = createBinary(file, binary)) { 578 errs() << ToolName << ": '" << file << "': " << ec.message() << ".\n"; 579 return; 580 } 581 582 if (Archive *a = dyn_cast<Archive>(binary.get())) { 583 DumpArchive(a); 584 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) { 585 DumpObject(o); 586 } else { 587 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 588 } 589 } 590 591 int main(int argc, char **argv) { 592 // Print a stack trace if we signal out. 593 sys::PrintStackTraceOnErrorSignal(); 594 PrettyStackTraceProgram X(argc, argv); 595 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 596 597 // Initialize targets and assembly printers/parsers. 598 llvm::InitializeAllTargetInfos(); 599 llvm::InitializeAllTargetMCs(); 600 llvm::InitializeAllAsmParsers(); 601 llvm::InitializeAllDisassemblers(); 602 603 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 604 TripleName = Triple::normalize(TripleName); 605 606 ToolName = argv[0]; 607 608 // Defaults to a.out if no filenames specified. 609 if (InputFilenames.size() == 0) 610 InputFilenames.push_back("a.out"); 611 612 if (!Disassemble 613 && !Relocations 614 && !SectionHeaders 615 && !SectionContents 616 && !SymbolTable) { 617 cl::PrintHelpMessage(); 618 return 2; 619 } 620 621 std::for_each(InputFilenames.begin(), InputFilenames.end(), 622 DumpInput); 623 624 return 0; 625 } 626