llvm-objdump.cpp revision d226ed71f24f2db200e3751e05b82c7700514116
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/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" 45#include <algorithm> 46#include <cstring> 47using namespace llvm; 48using namespace object; 49 50static cl::list<std::string> 51InputFilenames(cl::Positional, cl::desc("<input object files>"),cl::ZeroOrMore); 52 53static cl::opt<bool> 54Disassemble("disassemble", 55 cl::desc("Display assembler mnemonics for the machine instructions")); 56static cl::alias 57Disassembled("d", cl::desc("Alias for --disassemble"), 58 cl::aliasopt(Disassemble)); 59 60static cl::opt<bool> 61Relocations("r", cl::desc("Display the relocation entries in the file")); 62 63static cl::opt<bool> 64MachO("macho", cl::desc("Use MachO specific object file parser")); 65static cl::alias 66MachOm("m", cl::desc("Alias for --macho"), cl::aliasopt(MachO)); 67 68cl::opt<std::string> 69llvm::TripleName("triple", cl::desc("Target triple to disassemble for, " 70 "see -version for available targets")); 71 72cl::opt<std::string> 73llvm::ArchName("arch", cl::desc("Target arch to disassemble for, " 74 "see -version for available targets")); 75 76static StringRef ToolName; 77 78static bool error(error_code ec) { 79 if (!ec) return false; 80 81 outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; 82 outs().flush(); 83 return true; 84} 85 86static const Target *GetTarget(const ObjectFile *Obj = NULL) { 87 // Figure out the target triple. 88 llvm::Triple TT("unknown-unknown-unknown"); 89 if (TripleName.empty()) { 90 if (Obj) 91 TT.setArch(Triple::ArchType(Obj->getArch())); 92 } else 93 TT.setTriple(Triple::normalize(TripleName)); 94 95 if (!ArchName.empty()) 96 TT.setArchName(ArchName); 97 98 TripleName = TT.str(); 99 100 // Get the target specific parser. 101 std::string Error; 102 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 103 if (TheTarget) 104 return TheTarget; 105 106 errs() << ToolName << ": error: unable to get target for '" << TripleName 107 << "', see --version and --triple.\n"; 108 return 0; 109} 110 111void 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]; 121 122 assert(bytes.size() <= 15 123 && "DumpBytes only supports instructions of up to 15 bytes"); 124 memset(output, ' ', sizeof(output)); 125 unsigned index = 0; 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]; 130 index += 3; 131 } 132 133 output[sizeof(output) - 1] = 0; 134 outs() << output; 135} 136 137static void DisassembleObject(const ObjectFile *Obj) { 138 const Target *TheTarget = GetTarget(Obj); 139 if (!TheTarget) { 140 // GetTarget prints out stuff. 141 return; 142 } 143 144 outs() << '\n'; 145 outs() << Obj->getFileName() 146 << ":\tfile format " << Obj->getFileFormatName() << "\n\n"; 147 148 error_code ec; 149 for (section_iterator i = Obj->begin_sections(), 150 e = Obj->end_sections(); 151 i != e; i.increment(ec)) { 152 if (error(ec)) break; 153 bool text; 154 if (error(i->isText(text))) break; 155 if (!text) continue; 156 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)) { 162 bool contains; 163 if (!error(i->containsSymbol(*si, contains)) && contains) { 164 uint64_t Address; 165 if (error(si->getOffset(Address))) break; 166 StringRef Name; 167 if (error(si->getName(Name))) break; 168 Symbols.push_back(std::make_pair(Address, Name)); 169 } 170 } 171 172 // Sort the symbols by address, just in case they didn't come in that way. 173 array_pod_sort(Symbols.begin(), Symbols.end()); 174 175 StringRef name; 176 if (error(i->getName(name))) break; 177 outs() << "Disassembly of section " << name << ':'; 178 179 // If the section has no symbols just insert a dummy one and disassemble 180 // the whole section. 181 if (Symbols.empty()) 182 Symbols.push_back(std::make_pair(0, name)); 183 184 // Set up disassembler. 185 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName)); 186 187 if (!AsmInfo) { 188 errs() << "error: no assembly info for target " << TripleName << "\n"; 189 return; 190 } 191 192 OwningPtr<const MCSubtargetInfo> STI( 193 TheTarget->createMCSubtargetInfo(TripleName, "", "")); 194 195 if (!STI) { 196 errs() << "error: no subtarget info for target " << TripleName << "\n"; 197 return; 198 } 199 200 OwningPtr<const MCDisassembler> DisAsm( 201 TheTarget->createMCDisassembler(*STI)); 202 if (!DisAsm) { 203 errs() << "error: no disassembler for target " << TripleName << "\n"; 204 return; 205 } 206 207 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 208 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 209 AsmPrinterVariant, *AsmInfo, *STI)); 210 if (!IP) { 211 errs() << "error: no instruction printer for target " << TripleName 212 << '\n'; 213 return; 214 } 215 216 StringRef Bytes; 217 if (error(i->getContents(Bytes))) break; 218 StringRefMemoryObject memoryObject(Bytes); 219 uint64_t Size; 220 uint64_t Index; 221 uint64_t SectSize; 222 if (error(i->getSize(SectSize))) break; 223 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"; 229 230#ifndef NDEBUG 231 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 232#else 233 raw_ostream &DebugOut = nulls(); 234#endif 235 236 for (Index = Start; Index < End; Index += Size) { 237 MCInst Inst; 238 239 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, 240 DebugOut, nulls())) { 241 uint64_t addr; 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(), ""); 246 outs() << "\n"; 247 } else { 248 errs() << ToolName << ": warning: invalid instruction encoding\n"; 249 if (Size == 0) 250 Size = 1; // skip illegible bytes 251 } 252 } 253 } 254 } 255} 256 257static void PrintRelocations(const ObjectFile *o) { 258 error_code ec; 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()) 263 continue; 264 StringRef secname; 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; 271 272 uint64_t address; 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"; 279 } 280 outs() << "\n"; 281 } 282} 283 284static void DumpObject(const ObjectFile *o) { 285 if (Disassemble) 286 DisassembleObject(o); 287 if (Relocations) 288 PrintRelocations(o); 289} 290 291/// @brief Dump each object file in \a a; 292static 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() 298 << ".\n"; 299 continue; 300 } 301 if (ObjectFile *o = dyn_cast<ObjectFile>(child.get())) 302 DumpObject(o); 303 else 304 errs() << ToolName << ": '" << a->getFileName() << "': " 305 << "Unrecognized file type.\n"; 306 } 307} 308 309/// @brief Open file and figure out how to dump it. 310static 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"; 314 return; 315 } 316 317 if (MachO && Disassemble) { 318 DisassembleInputMachO(file); 319 return; 320 } 321 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"; 326 return; 327 } 328 329 if (Archive *a = dyn_cast<Archive>(binary.get())) { 330 DumpArchive(a); 331 } else if (ObjectFile *o = dyn_cast<ObjectFile>(binary.get())) { 332 DumpObject(o); 333 } else { 334 errs() << ToolName << ": '" << file << "': " << "Unrecognized file type.\n"; 335 } 336} 337 338int 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. 343 344 // Initialize targets and assembly printers/parsers. 345 llvm::InitializeAllTargetInfos(); 346 llvm::InitializeAllTargetMCs(); 347 llvm::InitializeAllAsmParsers(); 348 llvm::InitializeAllDisassemblers(); 349 350 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 351 TripleName = Triple::normalize(TripleName); 352 353 ToolName = argv[0]; 354 355 // Defaults to a.out if no filenames specified. 356 if (InputFilenames.size() == 0) 357 InputFilenames.push_back("a.out"); 358 359 if (!Disassemble && !Relocations) { 360 cl::PrintHelpMessage(); 361 return 2; 362 } 363 364 std::for_each(InputFilenames.begin(), InputFilenames.end(), 365 DumpInput); 366 367 return 0; 368} 369