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 // The flags and output of this program should be near identical to those of 15 // binutils objdump. 16 // 17 //===----------------------------------------------------------------------===// 18 19 #include "llvm-objdump.h" 20 #include "llvm/ADT/OwningPtr.h" 21 #include "llvm/ADT/STLExtras.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/ADT/Triple.h" 24 #include "llvm/MC/MCAsmInfo.h" 25 #include "llvm/MC/MCAtom.h" 26 #include "llvm/MC/MCContext.h" 27 #include "llvm/MC/MCDisassembler.h" 28 #include "llvm/MC/MCFunction.h" 29 #include "llvm/MC/MCInst.h" 30 #include "llvm/MC/MCInstPrinter.h" 31 #include "llvm/MC/MCInstrAnalysis.h" 32 #include "llvm/MC/MCInstrInfo.h" 33 #include "llvm/MC/MCModule.h" 34 #include "llvm/MC/MCModuleYAML.h" 35 #include "llvm/MC/MCObjectDisassembler.h" 36 #include "llvm/MC/MCObjectFileInfo.h" 37 #include "llvm/MC/MCObjectSymbolizer.h" 38 #include "llvm/MC/MCRegisterInfo.h" 39 #include "llvm/MC/MCRelocationInfo.h" 40 #include "llvm/MC/MCSubtargetInfo.h" 41 #include "llvm/Object/Archive.h" 42 #include "llvm/Object/COFF.h" 43 #include "llvm/Object/MachO.h" 44 #include "llvm/Object/ObjectFile.h" 45 #include "llvm/Support/Casting.h" 46 #include "llvm/Support/CommandLine.h" 47 #include "llvm/Support/Debug.h" 48 #include "llvm/Support/FileSystem.h" 49 #include "llvm/Support/Format.h" 50 #include "llvm/Support/GraphWriter.h" 51 #include "llvm/Support/Host.h" 52 #include "llvm/Support/ManagedStatic.h" 53 #include "llvm/Support/MemoryBuffer.h" 54 #include "llvm/Support/MemoryObject.h" 55 #include "llvm/Support/PrettyStackTrace.h" 56 #include "llvm/Support/Signals.h" 57 #include "llvm/Support/SourceMgr.h" 58 #include "llvm/Support/TargetRegistry.h" 59 #include "llvm/Support/TargetSelect.h" 60 #include "llvm/Support/raw_ostream.h" 61 #include "llvm/Support/system_error.h" 62 #include <algorithm> 63 #include <cctype> 64 #include <cstring> 65 66 using namespace llvm; 67 using namespace object; 68 69 static cl::list<std::string> 70 InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 71 72 static cl::opt<bool> 73 Disassemble("disassemble", 74 cl::desc("Display assembler mnemonics for the machine instructions")); 75 static cl::alias 76 Disassembled("d", cl::desc("Alias for --disassemble"), 77 cl::aliasopt(Disassemble)); 78 79 static cl::opt<bool> 80 Relocations("r", cl::desc("Display the relocation entries in the file")); 81 82 static cl::opt<bool> 83 SectionContents("s", cl::desc("Display the content of each section")); 84 85 static cl::opt<bool> 86 SymbolTable("t", cl::desc("Display the symbol table")); 87 88 static cl::opt<bool> 89 MachOOpt("macho", cl::desc("Use MachO specific object file parser")); 90 static cl::alias 91 MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachOOpt)); 92 93 cl::opt<std::string> 94 llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 95 "see -version for available targets")); 96 97 cl::opt<std::string> 98 llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " 99 "see -version for available targets")); 100 101 static cl::opt<bool> 102 SectionHeaders("section-headers", cl::desc("Display summaries of the headers " 103 "for each section.")); 104 static cl::alias 105 SectionHeadersShort("headers", cl::desc("Alias for --section-headers"), 106 cl::aliasopt(SectionHeaders)); 107 static cl::alias 108 SectionHeadersShorter("h", cl::desc("Alias for --section-headers"), 109 cl::aliasopt(SectionHeaders)); 110 111 static cl::list<std::string> 112 MAttrs("mattr", 113 cl::CommaSeparated, 114 cl::desc("Target specific attributes"), 115 cl::value_desc("a1,+a2,-a3,...")); 116 117 static cl::opt<bool> 118 NoShowRawInsn("no-show-raw-insn", cl::desc("When disassembling instructions, " 119 "do not print the instruction bytes.")); 120 121 static cl::opt<bool> 122 UnwindInfo("unwind-info", cl::desc("Display unwind information")); 123 124 static cl::alias 125 UnwindInfoShort("u", cl::desc("Alias for --unwind-info"), 126 cl::aliasopt(UnwindInfo)); 127 128 static cl::opt<bool> 129 PrivateHeaders("private-headers", 130 cl::desc("Display format specific file headers")); 131 132 static cl::alias 133 PrivateHeadersShort("p", cl::desc("Alias for --private-headers"), 134 cl::aliasopt(PrivateHeaders)); 135 136 static cl::opt<bool> 137 Symbolize("symbolize", cl::desc("When disassembling instructions, " 138 "try to symbolize operands.")); 139 140 static cl::opt<bool> 141 CFG("cfg", cl::desc("Create a CFG for every function found in the object" 142 " and write it to a graphviz file")); 143 144 // FIXME: Does it make sense to have a dedicated tool for yaml cfg output? 145 static cl::opt<std::string> 146 YAMLCFG("yaml-cfg", 147 cl::desc("Create a CFG and write it as a YAML MCModule."), 148 cl::value_desc("yaml output file")); 149 150 static StringRef ToolName; 151 152 bool llvm::error(error_code EC) { 153 if (!EC) 154 return false; 155 156 outs() << ToolName << ": error reading file: " << EC.message() << ".\n"; 157 outs().flush(); 158 return true; 159 } 160 161 static const Target *getTarget(const ObjectFile *Obj = NULL) { 162 // Figure out the target triple. 163 llvm::Triple TheTriple("unknown-unknown-unknown"); 164 if (TripleName.empty()) { 165 if (Obj) { 166 TheTriple.setArch(Triple::ArchType(Obj->getArch())); 167 // TheTriple defaults to ELF, and COFF doesn't have an environment: 168 // the best we can do here is indicate that it is mach-o. 169 if (Obj->isMachO()) 170 TheTriple.setEnvironment(Triple::MachO); 171 } 172 } else 173 TheTriple.setTriple(Triple::normalize(TripleName)); 174 175 // Get the target specific parser. 176 std::string Error; 177 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 178 Error); 179 if (!TheTarget) { 180 errs() << ToolName << ": " << Error; 181 return 0; 182 } 183 184 // Update the triple name and return the found target. 185 TripleName = TheTriple.getTriple(); 186 return TheTarget; 187 } 188 189 // Write a graphviz file for the CFG inside an MCFunction. 190 // FIXME: Use GraphWriter 191 static void emitDOTFile(const char *FileName, const MCFunction &f, 192 MCInstPrinter *IP) { 193 // Start a new dot file. 194 std::string Error; 195 raw_fd_ostream Out(FileName, Error, sys::fs::F_Text); 196 if (!Error.empty()) { 197 errs() << "llvm-objdump: warning: " << Error << '\n'; 198 return; 199 } 200 201 Out << "digraph \"" << f.getName() << "\" {\n"; 202 Out << "graph [ rankdir = \"LR\" ];\n"; 203 for (MCFunction::const_iterator i = f.begin(), e = f.end(); i != e; ++i) { 204 // Only print blocks that have predecessors. 205 bool hasPreds = (*i)->pred_begin() != (*i)->pred_end(); 206 207 if (!hasPreds && i != f.begin()) 208 continue; 209 210 Out << '"' << (*i)->getInsts()->getBeginAddr() << "\" [ label=\"<a>"; 211 // Print instructions. 212 for (unsigned ii = 0, ie = (*i)->getInsts()->size(); ii != ie; 213 ++ii) { 214 if (ii != 0) // Not the first line, start a new row. 215 Out << '|'; 216 if (ii + 1 == ie) // Last line, add an end id. 217 Out << "<o>"; 218 219 // Escape special chars and print the instruction in mnemonic form. 220 std::string Str; 221 raw_string_ostream OS(Str); 222 IP->printInst(&(*i)->getInsts()->at(ii).Inst, OS, ""); 223 Out << DOT::EscapeString(OS.str()); 224 } 225 Out << "\" shape=\"record\" ];\n"; 226 227 // Add edges. 228 for (MCBasicBlock::succ_const_iterator si = (*i)->succ_begin(), 229 se = (*i)->succ_end(); si != se; ++si) 230 Out << (*i)->getInsts()->getBeginAddr() << ":o -> " 231 << (*si)->getInsts()->getBeginAddr() << ":a\n"; 232 } 233 Out << "}\n"; 234 } 235 236 void llvm::DumpBytes(StringRef bytes) { 237 static const char hex_rep[] = "0123456789abcdef"; 238 // FIXME: The real way to do this is to figure out the longest instruction 239 // and align to that size before printing. I'll fix this when I get 240 // around to outputting relocations. 241 // 15 is the longest x86 instruction 242 // 3 is for the hex rep of a byte + a space. 243 // 1 is for the null terminator. 244 enum { OutputSize = (15 * 3) + 1 }; 245 char output[OutputSize]; 246 247 assert(bytes.size() <= 15 248 && "DumpBytes only supports instructions of up to 15 bytes"); 249 memset(output, ' ', sizeof(output)); 250 unsigned index = 0; 251 for (StringRef::iterator i = bytes.begin(), 252 e = bytes.end(); i != e; ++i) { 253 output[index] = hex_rep[(*i & 0xF0) >> 4]; 254 output[index + 1] = hex_rep[*i & 0xF]; 255 index += 3; 256 } 257 258 output[sizeof(output) - 1] = 0; 259 outs() << output; 260 } 261 262 bool llvm::RelocAddressLess(RelocationRef a, RelocationRef b) { 263 uint64_t a_addr, b_addr; 264 if (error(a.getOffset(a_addr))) return false; 265 if (error(b.getOffset(b_addr))) return false; 266 return a_addr < b_addr; 267 } 268 269 static void DisassembleObject(const ObjectFile *Obj, bool InlineRelocs) { 270 const Target *TheTarget = getTarget(Obj); 271 // getTarget() will have already issued a diagnostic if necessary, so 272 // just bail here if it failed. 273 if (!TheTarget) 274 return; 275 276 // Package up features to be passed to target/subtarget 277 std::string FeaturesStr; 278 if (MAttrs.size()) { 279 SubtargetFeatures Features; 280 for (unsigned i = 0; i != MAttrs.size(); ++i) 281 Features.AddFeature(MAttrs[i]); 282 FeaturesStr = Features.getString(); 283 } 284 285 OwningPtr<const MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 286 if (!MRI) { 287 errs() << "error: no register info for target " << TripleName << "\n"; 288 return; 289 } 290 291 // Set up disassembler. 292 OwningPtr<const MCAsmInfo> AsmInfo( 293 TheTarget->createMCAsmInfo(*MRI, TripleName)); 294 if (!AsmInfo) { 295 errs() << "error: no assembly info for target " << TripleName << "\n"; 296 return; 297 } 298 299 OwningPtr<const MCSubtargetInfo> STI( 300 TheTarget->createMCSubtargetInfo(TripleName, "", FeaturesStr)); 301 if (!STI) { 302 errs() << "error: no subtarget info for target " << TripleName << "\n"; 303 return; 304 } 305 306 OwningPtr<const MCInstrInfo> MII(TheTarget->createMCInstrInfo()); 307 if (!MII) { 308 errs() << "error: no instruction info for target " << TripleName << "\n"; 309 return; 310 } 311 312 OwningPtr<MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI)); 313 if (!DisAsm) { 314 errs() << "error: no disassembler for target " << TripleName << "\n"; 315 return; 316 } 317 318 OwningPtr<const MCObjectFileInfo> MOFI; 319 OwningPtr<MCContext> Ctx; 320 321 if (Symbolize) { 322 MOFI.reset(new MCObjectFileInfo); 323 Ctx.reset(new MCContext(AsmInfo.get(), MRI.get(), MOFI.get())); 324 OwningPtr<MCRelocationInfo> RelInfo( 325 TheTarget->createMCRelocationInfo(TripleName, *Ctx.get())); 326 if (RelInfo) { 327 OwningPtr<MCSymbolizer> Symzer( 328 MCObjectSymbolizer::createObjectSymbolizer(*Ctx.get(), RelInfo, Obj)); 329 if (Symzer) 330 DisAsm->setSymbolizer(Symzer); 331 } 332 } 333 334 OwningPtr<const MCInstrAnalysis> 335 MIA(TheTarget->createMCInstrAnalysis(MII.get())); 336 337 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 338 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 339 AsmPrinterVariant, *AsmInfo, *MII, *MRI, *STI)); 340 if (!IP) { 341 errs() << "error: no instruction printer for target " << TripleName 342 << '\n'; 343 return; 344 } 345 346 if (CFG || !YAMLCFG.empty()) { 347 OwningPtr<MCObjectDisassembler> OD( 348 new MCObjectDisassembler(*Obj, *DisAsm, *MIA)); 349 OwningPtr<MCModule> Mod(OD->buildModule(/* withCFG */ true)); 350 for (MCModule::const_atom_iterator AI = Mod->atom_begin(), 351 AE = Mod->atom_end(); 352 AI != AE; ++AI) { 353 outs() << "Atom " << (*AI)->getName() << ": \n"; 354 if (const MCTextAtom *TA = dyn_cast<MCTextAtom>(*AI)) { 355 for (MCTextAtom::const_iterator II = TA->begin(), IE = TA->end(); 356 II != IE; 357 ++II) { 358 IP->printInst(&II->Inst, outs(), ""); 359 outs() << "\n"; 360 } 361 } 362 } 363 if (CFG) { 364 for (MCModule::const_func_iterator FI = Mod->func_begin(), 365 FE = Mod->func_end(); 366 FI != FE; ++FI) { 367 static int filenum = 0; 368 emitDOTFile((Twine((*FI)->getName()) + "_" + 369 utostr(filenum) + ".dot").str().c_str(), 370 **FI, IP.get()); 371 ++filenum; 372 } 373 } 374 if (!YAMLCFG.empty()) { 375 std::string Error; 376 raw_fd_ostream YAMLOut(YAMLCFG.c_str(), Error, sys::fs::F_Text); 377 if (!Error.empty()) { 378 errs() << ToolName << ": warning: " << Error << '\n'; 379 return; 380 } 381 mcmodule2yaml(YAMLOut, *Mod, *MII, *MRI); 382 } 383 } 384 385 // Create a mapping, RelocSecs = SectionRelocMap[S], where sections 386 // in RelocSecs contain the relocations for section S. 387 error_code EC; 388 std::map<SectionRef, SmallVector<SectionRef, 1> > SectionRelocMap; 389 for (section_iterator I = Obj->section_begin(), E = Obj->section_end(); 390 I != E; ++I) { 391 section_iterator Sec2 = I->getRelocatedSection(); 392 if (Sec2 != Obj->section_end()) 393 SectionRelocMap[*Sec2].push_back(*I); 394 } 395 396 for (section_iterator I = Obj->section_begin(), E = Obj->section_end(); 397 I != E; ++I) { 398 bool Text; 399 if (error(I->isText(Text))) 400 break; 401 if (!Text) 402 continue; 403 404 uint64_t SectionAddr; 405 if (error(I->getAddress(SectionAddr))) 406 break; 407 408 // Make a list of all the symbols in this section. 409 std::vector<std::pair<uint64_t, StringRef> > Symbols; 410 for (symbol_iterator SI = Obj->symbol_begin(), SE = Obj->symbol_end(); 411 SI != SE; ++SI) { 412 bool contains; 413 if (!error(I->containsSymbol(*SI, contains)) && contains) { 414 uint64_t Address; 415 if (error(SI->getAddress(Address))) 416 break; 417 if (Address == UnknownAddressOrSize) 418 continue; 419 Address -= SectionAddr; 420 421 StringRef Name; 422 if (error(SI->getName(Name))) 423 break; 424 Symbols.push_back(std::make_pair(Address, Name)); 425 } 426 } 427 428 // Sort the symbols by address, just in case they didn't come in that way. 429 array_pod_sort(Symbols.begin(), Symbols.end()); 430 431 // Make a list of all the relocations for this section. 432 std::vector<RelocationRef> Rels; 433 if (InlineRelocs) { 434 SmallVectorImpl<SectionRef> *RelocSecs = &SectionRelocMap[*I]; 435 for (SmallVectorImpl<SectionRef>::iterator RelocSec = RelocSecs->begin(), 436 E = RelocSecs->end(); 437 RelocSec != E; ++RelocSec) { 438 for (relocation_iterator RI = RelocSec->relocation_begin(), 439 RE = RelocSec->relocation_end(); 440 RI != RE; ++RI) 441 Rels.push_back(*RI); 442 } 443 } 444 445 // Sort relocations by address. 446 std::sort(Rels.begin(), Rels.end(), RelocAddressLess); 447 448 StringRef SegmentName = ""; 449 if (const MachOObjectFile *MachO = dyn_cast<const MachOObjectFile>(Obj)) { 450 DataRefImpl DR = I->getRawDataRefImpl(); 451 SegmentName = MachO->getSectionFinalSegmentName(DR); 452 } 453 StringRef name; 454 if (error(I->getName(name))) 455 break; 456 outs() << "Disassembly of section "; 457 if (!SegmentName.empty()) 458 outs() << SegmentName << ","; 459 outs() << name << ':'; 460 461 // If the section has no symbols just insert a dummy one and disassemble 462 // the whole section. 463 if (Symbols.empty()) 464 Symbols.push_back(std::make_pair(0, name)); 465 466 467 SmallString<40> Comments; 468 raw_svector_ostream CommentStream(Comments); 469 470 StringRef Bytes; 471 if (error(I->getContents(Bytes))) 472 break; 473 StringRefMemoryObject memoryObject(Bytes, SectionAddr); 474 uint64_t Size; 475 uint64_t Index; 476 uint64_t SectSize; 477 if (error(I->getSize(SectSize))) 478 break; 479 480 std::vector<RelocationRef>::const_iterator rel_cur = Rels.begin(); 481 std::vector<RelocationRef>::const_iterator rel_end = Rels.end(); 482 // Disassemble symbol by symbol. 483 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 484 uint64_t Start = Symbols[si].first; 485 uint64_t End; 486 // The end is either the size of the section or the beginning of the next 487 // symbol. 488 if (si == se - 1) 489 End = SectSize; 490 // Make sure this symbol takes up space. 491 else if (Symbols[si + 1].first != Start) 492 End = Symbols[si + 1].first - 1; 493 else 494 // This symbol has the same address as the next symbol. Skip it. 495 continue; 496 497 outs() << '\n' << Symbols[si].second << ":\n"; 498 499 #ifndef NDEBUG 500 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 501 #else 502 raw_ostream &DebugOut = nulls(); 503 #endif 504 505 for (Index = Start; Index < End; Index += Size) { 506 MCInst Inst; 507 508 if (DisAsm->getInstruction(Inst, Size, memoryObject, 509 SectionAddr + Index, 510 DebugOut, CommentStream)) { 511 outs() << format("%8" PRIx64 ":", SectionAddr + Index); 512 if (!NoShowRawInsn) { 513 outs() << "\t"; 514 DumpBytes(StringRef(Bytes.data() + Index, Size)); 515 } 516 IP->printInst(&Inst, outs(), ""); 517 outs() << CommentStream.str(); 518 Comments.clear(); 519 outs() << "\n"; 520 } else { 521 errs() << ToolName << ": warning: invalid instruction encoding\n"; 522 if (Size == 0) 523 Size = 1; // skip illegible bytes 524 } 525 526 // Print relocation for instruction. 527 while (rel_cur != rel_end) { 528 bool hidden = false; 529 uint64_t addr; 530 SmallString<16> name; 531 SmallString<32> val; 532 533 // If this relocation is hidden, skip it. 534 if (error(rel_cur->getHidden(hidden))) goto skip_print_rel; 535 if (hidden) goto skip_print_rel; 536 537 if (error(rel_cur->getOffset(addr))) goto skip_print_rel; 538 // Stop when rel_cur's address is past the current instruction. 539 if (addr >= Index + Size) break; 540 if (error(rel_cur->getTypeName(name))) goto skip_print_rel; 541 if (error(rel_cur->getValueString(val))) goto skip_print_rel; 542 543 outs() << format("\t\t\t%8" PRIx64 ": ", SectionAddr + addr) << name 544 << "\t" << val << "\n"; 545 546 skip_print_rel: 547 ++rel_cur; 548 } 549 } 550 } 551 } 552 } 553 554 static void PrintRelocations(const ObjectFile *o) { 555 for (section_iterator si = o->section_begin(), se = o->section_end(); 556 si != se; ++si) { 557 if (si->relocation_begin() == si->relocation_end()) 558 continue; 559 StringRef secname; 560 if (error(si->getName(secname))) continue; 561 outs() << "RELOCATION RECORDS FOR [" << secname << "]:\n"; 562 for (relocation_iterator ri = si->relocation_begin(), 563 re = si->relocation_end(); 564 ri != re; ++ri) { 565 bool hidden; 566 uint64_t address; 567 SmallString<32> relocname; 568 SmallString<32> valuestr; 569 if (error(ri->getHidden(hidden))) continue; 570 if (hidden) continue; 571 if (error(ri->getTypeName(relocname))) continue; 572 if (error(ri->getOffset(address))) continue; 573 if (error(ri->getValueString(valuestr))) continue; 574 outs() << address << " " << relocname << " " << valuestr << "\n"; 575 } 576 outs() << "\n"; 577 } 578 } 579 580 static void PrintSectionHeaders(const ObjectFile *o) { 581 outs() << "Sections:\n" 582 "Idx Name Size Address Type\n"; 583 unsigned i = 0; 584 for (section_iterator si = o->section_begin(), se = o->section_end(); 585 si != se; ++si) { 586 StringRef Name; 587 if (error(si->getName(Name))) 588 return; 589 uint64_t Address; 590 if (error(si->getAddress(Address))) return; 591 uint64_t Size; 592 if (error(si->getSize(Size))) return; 593 bool Text, Data, BSS; 594 if (error(si->isText(Text))) return; 595 if (error(si->isData(Data))) return; 596 if (error(si->isBSS(BSS))) return; 597 std::string Type = (std::string(Text ? "TEXT " : "") + 598 (Data ? "DATA " : "") + (BSS ? "BSS" : "")); 599 outs() << format("%3d %-13s %08" PRIx64 " %016" PRIx64 " %s\n", 600 i, Name.str().c_str(), Size, Address, Type.c_str()); 601 ++i; 602 } 603 } 604 605 static void PrintSectionContents(const ObjectFile *o) { 606 error_code EC; 607 for (section_iterator si = o->section_begin(), se = o->section_end(); 608 si != se; ++si) { 609 StringRef Name; 610 StringRef Contents; 611 uint64_t BaseAddr; 612 bool BSS; 613 if (error(si->getName(Name))) continue; 614 if (error(si->getContents(Contents))) continue; 615 if (error(si->getAddress(BaseAddr))) continue; 616 if (error(si->isBSS(BSS))) continue; 617 618 outs() << "Contents of section " << Name << ":\n"; 619 if (BSS) { 620 outs() << format("<skipping contents of bss section at [%04" PRIx64 621 ", %04" PRIx64 ")>\n", BaseAddr, 622 BaseAddr + Contents.size()); 623 continue; 624 } 625 626 // Dump out the content as hex and printable ascii characters. 627 for (std::size_t addr = 0, end = Contents.size(); addr < end; addr += 16) { 628 outs() << format(" %04" PRIx64 " ", BaseAddr + addr); 629 // Dump line of hex. 630 for (std::size_t i = 0; i < 16; ++i) { 631 if (i != 0 && i % 4 == 0) 632 outs() << ' '; 633 if (addr + i < end) 634 outs() << hexdigit((Contents[addr + i] >> 4) & 0xF, true) 635 << hexdigit(Contents[addr + i] & 0xF, true); 636 else 637 outs() << " "; 638 } 639 // Print ascii. 640 outs() << " "; 641 for (std::size_t i = 0; i < 16 && addr + i < end; ++i) { 642 if (std::isprint(static_cast<unsigned char>(Contents[addr + i]) & 0xFF)) 643 outs() << Contents[addr + i]; 644 else 645 outs() << "."; 646 } 647 outs() << "\n"; 648 } 649 } 650 } 651 652 static void PrintCOFFSymbolTable(const COFFObjectFile *coff) { 653 const coff_file_header *header; 654 if (error(coff->getHeader(header))) return; 655 int aux_count = 0; 656 const coff_symbol *symbol = 0; 657 for (int i = 0, e = header->NumberOfSymbols; i != e; ++i) { 658 if (aux_count--) { 659 // Figure out which type of aux this is. 660 if (symbol->StorageClass == COFF::IMAGE_SYM_CLASS_STATIC 661 && symbol->Value == 0) { // Section definition. 662 const coff_aux_section_definition *asd; 663 if (error(coff->getAuxSymbol<coff_aux_section_definition>(i, asd))) 664 return; 665 outs() << "AUX " 666 << format("scnlen 0x%x nreloc %d nlnno %d checksum 0x%x " 667 , unsigned(asd->Length) 668 , unsigned(asd->NumberOfRelocations) 669 , unsigned(asd->NumberOfLinenumbers) 670 , unsigned(asd->CheckSum)) 671 << format("assoc %d comdat %d\n" 672 , unsigned(asd->Number) 673 , unsigned(asd->Selection)); 674 } else 675 outs() << "AUX Unknown\n"; 676 } else { 677 StringRef name; 678 if (error(coff->getSymbol(i, symbol))) return; 679 if (error(coff->getSymbolName(symbol, name))) return; 680 outs() << "[" << format("%2d", i) << "]" 681 << "(sec " << format("%2d", int(symbol->SectionNumber)) << ")" 682 << "(fl 0x00)" // Flag bits, which COFF doesn't have. 683 << "(ty " << format("%3x", unsigned(symbol->Type)) << ")" 684 << "(scl " << format("%3x", unsigned(symbol->StorageClass)) << ") " 685 << "(nx " << unsigned(symbol->NumberOfAuxSymbols) << ") " 686 << "0x" << format("%08x", unsigned(symbol->Value)) << " " 687 << name << "\n"; 688 aux_count = symbol->NumberOfAuxSymbols; 689 } 690 } 691 } 692 693 static void PrintSymbolTable(const ObjectFile *o) { 694 outs() << "SYMBOL TABLE:\n"; 695 696 if (const COFFObjectFile *coff = dyn_cast<const COFFObjectFile>(o)) 697 PrintCOFFSymbolTable(coff); 698 else { 699 for (symbol_iterator si = o->symbol_begin(), se = o->symbol_end(); 700 si != se; ++si) { 701 StringRef Name; 702 uint64_t Address; 703 SymbolRef::Type Type; 704 uint64_t Size; 705 uint32_t Flags = si->getFlags(); 706 section_iterator Section = o->section_end(); 707 if (error(si->getName(Name))) continue; 708 if (error(si->getAddress(Address))) continue; 709 if (error(si->getType(Type))) continue; 710 if (error(si->getSize(Size))) continue; 711 if (error(si->getSection(Section))) continue; 712 713 bool Global = Flags & SymbolRef::SF_Global; 714 bool Weak = Flags & SymbolRef::SF_Weak; 715 bool Absolute = Flags & SymbolRef::SF_Absolute; 716 717 if (Address == UnknownAddressOrSize) 718 Address = 0; 719 if (Size == UnknownAddressOrSize) 720 Size = 0; 721 char GlobLoc = ' '; 722 if (Type != SymbolRef::ST_Unknown) 723 GlobLoc = Global ? 'g' : 'l'; 724 char Debug = (Type == SymbolRef::ST_Debug || Type == SymbolRef::ST_File) 725 ? 'd' : ' '; 726 char FileFunc = ' '; 727 if (Type == SymbolRef::ST_File) 728 FileFunc = 'f'; 729 else if (Type == SymbolRef::ST_Function) 730 FileFunc = 'F'; 731 732 const char *Fmt = o->getBytesInAddress() > 4 ? "%016" PRIx64 : 733 "%08" PRIx64; 734 735 outs() << format(Fmt, Address) << " " 736 << GlobLoc // Local -> 'l', Global -> 'g', Neither -> ' ' 737 << (Weak ? 'w' : ' ') // Weak? 738 << ' ' // Constructor. Not supported yet. 739 << ' ' // Warning. Not supported yet. 740 << ' ' // Indirect reference to another symbol. 741 << Debug // Debugging (d) or dynamic (D) symbol. 742 << FileFunc // Name of function (F), file (f) or object (O). 743 << ' '; 744 if (Absolute) 745 outs() << "*ABS*"; 746 else if (Section == o->section_end()) 747 outs() << "*UND*"; 748 else { 749 if (const MachOObjectFile *MachO = 750 dyn_cast<const MachOObjectFile>(o)) { 751 DataRefImpl DR = Section->getRawDataRefImpl(); 752 StringRef SegmentName = MachO->getSectionFinalSegmentName(DR); 753 outs() << SegmentName << ","; 754 } 755 StringRef SectionName; 756 if (error(Section->getName(SectionName))) 757 SectionName = ""; 758 outs() << SectionName; 759 } 760 outs() << '\t' 761 << format("%08" PRIx64 " ", Size) 762 << Name 763 << '\n'; 764 } 765 } 766 } 767 768 static void PrintUnwindInfo(const ObjectFile *o) { 769 outs() << "Unwind info:\n\n"; 770 771 if (const COFFObjectFile *coff = dyn_cast<COFFObjectFile>(o)) { 772 printCOFFUnwindInfo(coff); 773 } else { 774 // TODO: Extract DWARF dump tool to objdump. 775 errs() << "This operation is only currently supported " 776 "for COFF object files.\n"; 777 return; 778 } 779 } 780 781 static void printPrivateFileHeader(const ObjectFile *o) { 782 if (o->isELF()) { 783 printELFFileHeader(o); 784 } else if (o->isCOFF()) { 785 printCOFFFileHeader(o); 786 } 787 } 788 789 static void DumpObject(const ObjectFile *o) { 790 outs() << '\n'; 791 outs() << o->getFileName() 792 << ":\tfile format " << o->getFileFormatName() << "\n\n"; 793 794 if (Disassemble) 795 DisassembleObject(o, Relocations); 796 if (Relocations && !Disassemble) 797 PrintRelocations(o); 798 if (SectionHeaders) 799 PrintSectionHeaders(o); 800 if (SectionContents) 801 PrintSectionContents(o); 802 if (SymbolTable) 803 PrintSymbolTable(o); 804 if (UnwindInfo) 805 PrintUnwindInfo(o); 806 if (PrivateHeaders) 807 printPrivateFileHeader(o); 808 } 809 810 /// @brief Dump each object file in \a a; 811 static void DumpArchive(const Archive *a) { 812 for (Archive::child_iterator i = a->child_begin(), e = a->child_end(); i != e; 813 ++i) { 814 OwningPtr<Binary> child; 815 if (error_code EC = i->getAsBinary(child)) { 816 // Ignore non-object files. 817 if (EC != object_error::invalid_file_type) 818 errs() << ToolName << ": '" << a->getFileName() << "': " << EC.message() 819 << ".\n"; 820 continue; 821 } 822 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) 823 DumpObject(o); 824 else 825 errs() << ToolName << ": '" << a->getFileName() << "': " 826 << "Unrecognized file type.\n"; 827 } 828 } 829 830 /// @brief Open file and figure out how to dump it. 831 static void DumpInput(StringRef file) { 832 // If file isn't stdin, check that it exists. 833 if (file != "-" && !sys::fs::exists(file)) { 834 errs() << ToolName << ": '" << file << "': " << "No such file\n"; 835 return; 836 } 837 838 if (MachOOpt && Disassemble) { 839 DisassembleInputMachO(file); 840 return; 841 } 842 843 // Attempt to open the binary. 844 ErrorOr<Binary *> BinaryOrErr = createBinary(file); 845 if (error_code EC = BinaryOrErr.getError()) { 846 errs() << ToolName << ": '" << file << "': " << EC.message() << ".\n"; 847 return; 848 } 849 OwningPtr<Binary> binary(BinaryOrErr.get()); 850 851 if (Archive *a = dyn_cast<Archive>(binary.get())) 852 DumpArchive(a); 853 else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) 854 DumpObject(o); 855 else 856 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 857 } 858 859 int main(int argc, char **argv) { 860 // Print a stack trace if we signal out. 861 sys::PrintStackTraceOnErrorSignal(); 862 PrettyStackTraceProgram X(argc, argv); 863 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 864 865 // Initialize targets and assembly printers/parsers. 866 llvm::InitializeAllTargetInfos(); 867 llvm::InitializeAllTargetMCs(); 868 llvm::InitializeAllAsmParsers(); 869 llvm::InitializeAllDisassemblers(); 870 871 // Register the target printer for --version. 872 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 873 874 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 875 TripleName = Triple::normalize(TripleName); 876 877 ToolName = argv[0]; 878 879 // Defaults to a.out if no filenames specified. 880 if (InputFilenames.size() == 0) 881 InputFilenames.push_back("a.out"); 882 883 if (!Disassemble 884 && !Relocations 885 && !SectionHeaders 886 && !SectionContents 887 && !SymbolTable 888 && !UnwindInfo 889 && !PrivateHeaders) { 890 cl::PrintHelpMessage(); 891 return 2; 892 } 893 894 std::for_each(InputFilenames.begin(), InputFilenames.end(), 895 DumpInput); 896 897 return 0; 898 } 899