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 "MCFunction.h" 17 #include "llvm/Object/ObjectFile.h" 18 #include "llvm/ADT/OwningPtr.h" 19 #include "llvm/ADT/Triple.h" 20 #include "llvm/ADT/STLExtras.h" 21 #include "llvm/MC/MCAsmInfo.h" 22 #include "llvm/MC/MCDisassembler.h" 23 #include "llvm/MC/MCInst.h" 24 #include "llvm/MC/MCInstPrinter.h" 25 #include "llvm/MC/MCInstrAnalysis.h" 26 #include "llvm/MC/MCInstrDesc.h" 27 #include "llvm/MC/MCInstrInfo.h" 28 #include "llvm/MC/MCSubtargetInfo.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/Format.h" 32 #include "llvm/Support/GraphWriter.h" 33 #include "llvm/Support/Host.h" 34 #include "llvm/Support/ManagedStatic.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/MemoryObject.h" 37 #include "llvm/Support/PrettyStackTrace.h" 38 #include "llvm/Support/Signals.h" 39 #include "llvm/Support/SourceMgr.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/TargetSelect.h" 42 #include "llvm/Support/raw_ostream.h" 43 #include "llvm/Support/system_error.h" 44 #include <algorithm> 45 #include <cstring> 46 using namespace llvm; 47 using namespace object; 48 49 namespace { 50 cl::list<std::string> 51 InputFilenames(cl::Positional, cl::desc("<input object files>"), 52 cl::ZeroOrMore); 53 54 cl::opt<bool> 55 Disassemble("disassemble", 56 cl::desc("Display assembler mnemonics for the machine instructions")); 57 cl::alias 58 Disassembled("d", cl::desc("Alias for --disassemble"), 59 cl::aliasopt(Disassemble)); 60 61 cl::opt<bool> 62 CFG("cfg", cl::desc("Create a CFG for every symbol in the object file and" 63 "write it to a graphviz file")); 64 65 cl::opt<std::string> 66 TripleName("triple", cl::desc("Target triple to disassemble for, " 67 "see -version for available targets")); 68 69 cl::opt<std::string> 70 ArchName("arch", cl::desc("Target arch to disassemble for, " 71 "see -version for available targets")); 72 73 StringRef ToolName; 74 75 bool error(error_code ec) { 76 if (!ec) return false; 77 78 outs() << ToolName << ": error reading file: " << ec.message() << ".\n"; 79 outs().flush(); 80 return true; 81 } 82 } 83 84 static const Target *GetTarget(const ObjectFile *Obj = NULL) { 85 // Figure out the target triple. 86 llvm::Triple TT("unknown-unknown-unknown"); 87 if (TripleName.empty()) { 88 if (Obj) 89 TT.setArch(Triple::ArchType(Obj->getArch())); 90 } else 91 TT.setTriple(Triple::normalize(TripleName)); 92 93 if (!ArchName.empty()) 94 TT.setArchName(ArchName); 95 96 TripleName = TT.str(); 97 98 // Get the target specific parser. 99 std::string Error; 100 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 101 if (TheTarget) 102 return TheTarget; 103 104 errs() << ToolName << ": error: unable to get target for '" << TripleName 105 << "', see --version and --triple.\n"; 106 return 0; 107 } 108 109 namespace { 110 class StringRefMemoryObject : public MemoryObject { 111 private: 112 StringRef Bytes; 113 public: 114 StringRefMemoryObject(StringRef bytes) : Bytes(bytes) {} 115 116 uint64_t getBase() const { return 0; } 117 uint64_t getExtent() const { return Bytes.size(); } 118 119 int readByte(uint64_t Addr, uint8_t *Byte) const { 120 if (Addr >= getExtent()) 121 return -1; 122 *Byte = Bytes[Addr]; 123 return 0; 124 } 125 }; 126 } 127 128 static void DumpBytes(StringRef bytes) { 129 static char hex_rep[] = "0123456789abcdef"; 130 // FIXME: The real way to do this is to figure out the longest instruction 131 // and align to that size before printing. I'll fix this when I get 132 // around to outputting relocations. 133 // 15 is the longest x86 instruction 134 // 3 is for the hex rep of a byte + a space. 135 // 1 is for the null terminator. 136 enum { OutputSize = (15 * 3) + 1 }; 137 char output[OutputSize]; 138 139 assert(bytes.size() <= 15 140 && "DumpBytes only supports instructions of up to 15 bytes"); 141 memset(output, ' ', sizeof(output)); 142 unsigned index = 0; 143 for (StringRef::iterator i = bytes.begin(), 144 e = bytes.end(); i != e; ++i) { 145 output[index] = hex_rep[(*i & 0xF0) >> 4]; 146 output[index + 1] = hex_rep[*i & 0xF]; 147 index += 3; 148 } 149 150 output[sizeof(output) - 1] = 0; 151 outs() << output; 152 } 153 154 static void DisassembleInput(const StringRef &Filename) { 155 OwningPtr<MemoryBuffer> Buff; 156 157 if (error_code ec = MemoryBuffer::getFileOrSTDIN(Filename, Buff)) { 158 errs() << ToolName << ": " << Filename << ": " << ec.message() << "\n"; 159 return; 160 } 161 162 OwningPtr<ObjectFile> Obj(ObjectFile::createObjectFile(Buff.take())); 163 164 const Target *TheTarget = GetTarget(Obj.get()); 165 if (!TheTarget) { 166 // GetTarget prints out stuff. 167 return; 168 } 169 const MCInstrInfo *InstrInfo = TheTarget->createMCInstrInfo(); 170 OwningPtr<MCInstrAnalysis> 171 InstrAnalysis(TheTarget->createMCInstrAnalysis(InstrInfo)); 172 173 outs() << '\n'; 174 outs() << Filename 175 << ":\tfile format " << Obj->getFileFormatName() << "\n\n"; 176 177 error_code ec; 178 for (ObjectFile::section_iterator i = Obj->begin_sections(), 179 e = Obj->end_sections(); 180 i != e; i.increment(ec)) { 181 if (error(ec)) break; 182 bool text; 183 if (error(i->isText(text))) break; 184 if (!text) continue; 185 186 // Make a list of all the symbols in this section. 187 std::vector<std::pair<uint64_t, StringRef> > Symbols; 188 for (ObjectFile::symbol_iterator si = Obj->begin_symbols(), 189 se = Obj->end_symbols(); 190 si != se; si.increment(ec)) { 191 bool contains; 192 if (!error(i->containsSymbol(*si, contains)) && contains) { 193 uint64_t Address; 194 if (error(si->getOffset(Address))) break; 195 StringRef Name; 196 if (error(si->getName(Name))) break; 197 Symbols.push_back(std::make_pair(Address, Name)); 198 } 199 } 200 201 // Sort the symbols by address, just in case they didn't come in that way. 202 array_pod_sort(Symbols.begin(), Symbols.end()); 203 204 StringRef name; 205 if (error(i->getName(name))) break; 206 outs() << "Disassembly of section " << name << ':'; 207 208 // If the section has no symbols just insert a dummy one and disassemble 209 // the whole section. 210 if (Symbols.empty()) 211 Symbols.push_back(std::make_pair(0, name)); 212 213 // Set up disassembler. 214 OwningPtr<const MCAsmInfo> AsmInfo(TheTarget->createMCAsmInfo(TripleName)); 215 216 if (!AsmInfo) { 217 errs() << "error: no assembly info for target " << TripleName << "\n"; 218 return; 219 } 220 221 OwningPtr<const MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo(TripleName, "", "")); 222 223 if (!STI) { 224 errs() << "error: no subtarget info for target " << TripleName << "\n"; 225 return; 226 } 227 228 OwningPtr<const MCDisassembler> DisAsm(TheTarget->createMCDisassembler(*STI)); 229 if (!DisAsm) { 230 errs() << "error: no disassembler for target " << TripleName << "\n"; 231 return; 232 } 233 234 int AsmPrinterVariant = AsmInfo->getAssemblerDialect(); 235 OwningPtr<MCInstPrinter> IP(TheTarget->createMCInstPrinter( 236 AsmPrinterVariant, *AsmInfo, *STI)); 237 if (!IP) { 238 errs() << "error: no instruction printer for target " << TripleName << '\n'; 239 return; 240 } 241 242 StringRef Bytes; 243 if (error(i->getContents(Bytes))) break; 244 StringRefMemoryObject memoryObject(Bytes); 245 uint64_t Size; 246 uint64_t Index; 247 uint64_t SectSize; 248 if (error(i->getSize(SectSize))) break; 249 250 // Disassemble symbol by symbol. 251 for (unsigned si = 0, se = Symbols.size(); si != se; ++si) { 252 uint64_t Start = Symbols[si].first; 253 uint64_t End = si == se-1 ? SectSize : Symbols[si + 1].first - 1; 254 outs() << '\n' << Symbols[si].second << ":\n"; 255 256 #ifndef NDEBUG 257 raw_ostream &DebugOut = DebugFlag ? dbgs() : nulls(); 258 #else 259 raw_ostream &DebugOut = nulls(); 260 #endif 261 262 if (!CFG) { 263 for (Index = Start; Index < End; Index += Size) { 264 MCInst Inst; 265 266 if (DisAsm->getInstruction(Inst, Size, memoryObject, Index, 267 DebugOut, nulls())) { 268 uint64_t addr; 269 if (error(i->getAddress(addr))) break; 270 outs() << format("%8x:\t", addr + Index); 271 DumpBytes(StringRef(Bytes.data() + Index, Size)); 272 IP->printInst(&Inst, outs(), ""); 273 outs() << "\n"; 274 } else { 275 errs() << ToolName << ": warning: invalid instruction encoding\n"; 276 if (Size == 0) 277 Size = 1; // skip illegible bytes 278 } 279 } 280 281 } else { 282 // Create CFG and use it for disassembly. 283 MCFunction f = 284 MCFunction::createFunctionFromMC(Symbols[si].second, DisAsm.get(), 285 memoryObject, Start, End, 286 InstrAnalysis.get(), DebugOut); 287 288 for (MCFunction::iterator fi = f.begin(), fe = f.end(); fi != fe; ++fi){ 289 bool hasPreds = false; 290 // Only print blocks that have predecessors. 291 // FIXME: Slow. 292 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe; 293 ++pi) 294 if (pi->second.contains(&fi->second)) { 295 hasPreds = true; 296 break; 297 } 298 299 // Data block. 300 if (!hasPreds && fi != f.begin()) { 301 uint64_t End = llvm::next(fi) == fe ? SectSize : 302 llvm::next(fi)->first; 303 uint64_t addr; 304 if (error(i->getAddress(addr))) break; 305 outs() << "# " << End-fi->first << " bytes of data:\n"; 306 for (unsigned pos = fi->first; pos != End; ++pos) { 307 outs() << format("%8x:\t", addr + pos); 308 DumpBytes(StringRef(Bytes.data() + pos, 1)); 309 outs() << format("\t.byte 0x%02x\n", (uint8_t)Bytes[pos]); 310 } 311 continue; 312 } 313 314 if (fi->second.contains(&fi->second)) 315 outs() << "# Loop begin:\n"; 316 317 for (unsigned ii = 0, ie = fi->second.getInsts().size(); ii != ie; 318 ++ii) { 319 uint64_t addr; 320 if (error(i->getAddress(addr))) break; 321 const MCDecodedInst &Inst = fi->second.getInsts()[ii]; 322 outs() << format("%8x:\t", addr + Inst.Address); 323 DumpBytes(StringRef(Bytes.data() + Inst.Address, Inst.Size)); 324 // Simple loops. 325 if (fi->second.contains(&fi->second)) 326 outs() << '\t'; 327 IP->printInst(&Inst.Inst, outs(), ""); 328 outs() << '\n'; 329 } 330 } 331 332 // Start a new dot file. 333 std::string Error; 334 raw_fd_ostream Out((f.getName().str() + ".dot").c_str(), Error); 335 if (!Error.empty()) { 336 errs() << ToolName << ": warning: " << Error << '\n'; 337 continue; 338 } 339 340 Out << "digraph " << f.getName() << " {\n"; 341 Out << "graph [ rankdir = \"LR\" ];\n"; 342 for (MCFunction::iterator i = f.begin(), e = f.end(); i != e; ++i) { 343 bool hasPreds = false; 344 // Only print blocks that have predecessors. 345 // FIXME: Slow. 346 for (MCFunction::iterator pi = f.begin(), pe = f.end(); pi != pe; 347 ++pi) 348 if (pi->second.contains(&i->second)) { 349 hasPreds = true; 350 break; 351 } 352 353 if (!hasPreds && i != f.begin()) 354 continue; 355 356 Out << '"' << (uintptr_t)&i->second << "\" [ label=\"<a>"; 357 // Print instructions. 358 for (unsigned ii = 0, ie = i->second.getInsts().size(); ii != ie; 359 ++ii) { 360 // Escape special chars and print the instruction in mnemonic form. 361 std::string Str; 362 raw_string_ostream OS(Str); 363 IP->printInst(&i->second.getInsts()[ii].Inst, OS, ""); 364 Out << DOT::EscapeString(OS.str()) << '|'; 365 } 366 Out << "<o>\" shape=\"record\" ];\n"; 367 368 // Add edges. 369 for (MCBasicBlock::succ_iterator si = i->second.succ_begin(), 370 se = i->second.succ_end(); si != se; ++si) 371 Out << (uintptr_t)&i->second << ":o -> " << (uintptr_t)*si <<":a\n"; 372 } 373 Out << "}\n"; 374 } 375 } 376 } 377 } 378 379 int main(int argc, char **argv) { 380 // Print a stack trace if we signal out. 381 sys::PrintStackTraceOnErrorSignal(); 382 PrettyStackTraceProgram X(argc, argv); 383 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 384 385 // Initialize targets and assembly printers/parsers. 386 llvm::InitializeAllTargetInfos(); 387 llvm::InitializeAllTargetMCs(); 388 llvm::InitializeAllAsmParsers(); 389 llvm::InitializeAllDisassemblers(); 390 391 cl::ParseCommandLineOptions(argc, argv, "llvm object file dumper\n"); 392 TripleName = Triple::normalize(TripleName); 393 394 ToolName = argv[0]; 395 396 // Defaults to a.out if no filenames specified. 397 if (InputFilenames.size() == 0) 398 InputFilenames.push_back("a.out"); 399 400 // -d is the only flag that is currently implemented, so just print help if 401 // it is not set. 402 if (!Disassemble) { 403 cl::PrintHelpMessage(); 404 return 2; 405 } 406 407 std::for_each(InputFilenames.begin(), InputFilenames.end(), 408 DisassembleInput); 409 410 return 0; 411 } 412