1 //===-- llvm-mc.cpp - Machine Code Hacking Driver -------------------------===// 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 utility is a simple driver that allows command line hacking on machine 11 // code. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "llvm/MC/MCParser/AsmLexer.h" 16 #include "llvm/MC/MCParser/MCAsmLexer.h" 17 #include "llvm/MC/MCAsmBackend.h" 18 #include "llvm/MC/MCContext.h" 19 #include "llvm/MC/MCCodeEmitter.h" 20 #include "llvm/MC/MCInstPrinter.h" 21 #include "llvm/MC/MCInstrInfo.h" 22 #include "llvm/MC/MCObjectFileInfo.h" 23 #include "llvm/MC/MCRegisterInfo.h" 24 #include "llvm/MC/MCSectionMachO.h" 25 #include "llvm/MC/MCStreamer.h" 26 #include "llvm/MC/MCSubtargetInfo.h" 27 #include "llvm/MC/MCTargetAsmParser.h" 28 #include "llvm/MC/SubtargetFeature.h" 29 #include "llvm/ADT/OwningPtr.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/FileUtilities.h" 32 #include "llvm/Support/FormattedStream.h" 33 #include "llvm/Support/ManagedStatic.h" 34 #include "llvm/Support/MemoryBuffer.h" 35 #include "llvm/Support/PrettyStackTrace.h" 36 #include "llvm/Support/SourceMgr.h" 37 #include "llvm/Support/ToolOutputFile.h" 38 #include "llvm/Support/Host.h" 39 #include "llvm/Support/Signals.h" 40 #include "llvm/Support/TargetRegistry.h" 41 #include "llvm/Support/TargetSelect.h" 42 #include "llvm/Support/system_error.h" 43 #include "Disassembler.h" 44 using namespace llvm; 45 46 static cl::opt<std::string> 47 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); 48 49 static cl::opt<std::string> 50 OutputFilename("o", cl::desc("Output filename"), 51 cl::value_desc("filename")); 52 53 static cl::opt<bool> 54 ShowEncoding("show-encoding", cl::desc("Show instruction encodings")); 55 56 static cl::opt<bool> 57 ShowInst("show-inst", cl::desc("Show internal instruction representation")); 58 59 static cl::opt<bool> 60 ShowInstOperands("show-inst-operands", 61 cl::desc("Show instructions operands as parsed")); 62 63 static cl::opt<unsigned> 64 OutputAsmVariant("output-asm-variant", 65 cl::desc("Syntax variant to use for output printing")); 66 67 static cl::opt<bool> 68 RelaxAll("mc-relax-all", cl::desc("Relax all fixups")); 69 70 static cl::opt<bool> 71 NoExecStack("mc-no-exec-stack", cl::desc("File doesn't need an exec stack")); 72 73 static cl::opt<bool> 74 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging")); 75 76 enum OutputFileType { 77 OFT_Null, 78 OFT_AssemblyFile, 79 OFT_ObjectFile 80 }; 81 static cl::opt<OutputFileType> 82 FileType("filetype", cl::init(OFT_AssemblyFile), 83 cl::desc("Choose an output file type:"), 84 cl::values( 85 clEnumValN(OFT_AssemblyFile, "asm", 86 "Emit an assembly ('.s') file"), 87 clEnumValN(OFT_Null, "null", 88 "Don't emit anything (for timing purposes)"), 89 clEnumValN(OFT_ObjectFile, "obj", 90 "Emit a native object ('.o') file"), 91 clEnumValEnd)); 92 93 static cl::list<std::string> 94 IncludeDirs("I", cl::desc("Directory of include files"), 95 cl::value_desc("directory"), cl::Prefix); 96 97 static cl::opt<std::string> 98 ArchName("arch", cl::desc("Target arch to assemble for, " 99 "see -version for available targets")); 100 101 static cl::opt<std::string> 102 TripleName("triple", cl::desc("Target triple to assemble for, " 103 "see -version for available targets")); 104 105 static cl::opt<std::string> 106 MCPU("mcpu", 107 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 108 cl::value_desc("cpu-name"), 109 cl::init("")); 110 111 static cl::opt<Reloc::Model> 112 RelocModel("relocation-model", 113 cl::desc("Choose relocation model"), 114 cl::init(Reloc::Default), 115 cl::values( 116 clEnumValN(Reloc::Default, "default", 117 "Target default relocation model"), 118 clEnumValN(Reloc::Static, "static", 119 "Non-relocatable code"), 120 clEnumValN(Reloc::PIC_, "pic", 121 "Fully relocatable, position independent code"), 122 clEnumValN(Reloc::DynamicNoPIC, "dynamic-no-pic", 123 "Relocatable external references, non-relocatable code"), 124 clEnumValEnd)); 125 126 static cl::opt<llvm::CodeModel::Model> 127 CMModel("code-model", 128 cl::desc("Choose code model"), 129 cl::init(CodeModel::Default), 130 cl::values(clEnumValN(CodeModel::Default, "default", 131 "Target default code model"), 132 clEnumValN(CodeModel::Small, "small", 133 "Small code model"), 134 clEnumValN(CodeModel::Kernel, "kernel", 135 "Kernel code model"), 136 clEnumValN(CodeModel::Medium, "medium", 137 "Medium code model"), 138 clEnumValN(CodeModel::Large, "large", 139 "Large code model"), 140 clEnumValEnd)); 141 142 static cl::opt<bool> 143 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts " 144 "in the text section")); 145 146 static cl::opt<bool> 147 SaveTempLabels("L", cl::desc("Don't discard temporary labels")); 148 149 enum ActionType { 150 AC_AsLex, 151 AC_Assemble, 152 AC_Disassemble, 153 AC_EDisassemble 154 }; 155 156 static cl::opt<ActionType> 157 Action(cl::desc("Action to perform:"), 158 cl::init(AC_Assemble), 159 cl::values(clEnumValN(AC_AsLex, "as-lex", 160 "Lex tokens from a .s file"), 161 clEnumValN(AC_Assemble, "assemble", 162 "Assemble a .s file (default)"), 163 clEnumValN(AC_Disassemble, "disassemble", 164 "Disassemble strings of hex bytes"), 165 clEnumValN(AC_EDisassemble, "edis", 166 "Enhanced disassembly of strings of hex bytes"), 167 clEnumValEnd)); 168 169 static const Target *GetTarget(const char *ProgName) { 170 // Figure out the target triple. 171 if (TripleName.empty()) 172 TripleName = sys::getHostTriple(); 173 Triple TheTriple(Triple::normalize(TripleName)); 174 175 const Target *TheTarget = 0; 176 if (!ArchName.empty()) { 177 for (TargetRegistry::iterator it = TargetRegistry::begin(), 178 ie = TargetRegistry::end(); it != ie; ++it) { 179 if (ArchName == it->getName()) { 180 TheTarget = &*it; 181 break; 182 } 183 } 184 185 if (!TheTarget) { 186 errs() << ProgName << ": error: invalid target '" << ArchName << "'.\n"; 187 return 0; 188 } 189 190 // Adjust the triple to match (if known), otherwise stick with the 191 // module/host triple. 192 Triple::ArchType Type = Triple::getArchTypeForLLVMName(ArchName); 193 if (Type != Triple::UnknownArch) 194 TheTriple.setArch(Type); 195 } else { 196 // Get the target specific parser. 197 std::string Error; 198 TheTarget = TargetRegistry::lookupTarget(TheTriple.getTriple(), Error); 199 if (TheTarget == 0) { 200 errs() << ProgName << ": error: unable to get target for '" 201 << TheTriple.getTriple() 202 << "', see --version and --triple.\n"; 203 return 0; 204 } 205 } 206 207 TripleName = TheTriple.getTriple(); 208 return TheTarget; 209 } 210 211 static tool_output_file *GetOutputStream() { 212 if (OutputFilename == "") 213 OutputFilename = "-"; 214 215 std::string Err; 216 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err, 217 raw_fd_ostream::F_Binary); 218 if (!Err.empty()) { 219 errs() << Err << '\n'; 220 delete Out; 221 return 0; 222 } 223 224 return Out; 225 } 226 227 static int AsLexInput(const char *ProgName) { 228 OwningPtr<MemoryBuffer> BufferPtr; 229 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) { 230 errs() << ProgName << ": " << ec.message() << '\n'; 231 return 1; 232 } 233 MemoryBuffer *Buffer = BufferPtr.take(); 234 235 SourceMgr SrcMgr; 236 237 // Tell SrcMgr about this buffer, which is what TGParser will pick up. 238 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 239 240 // Record the location of the include directories so that the lexer can find 241 // it later. 242 SrcMgr.setIncludeDirs(IncludeDirs); 243 244 const Target *TheTarget = GetTarget(ProgName); 245 if (!TheTarget) 246 return 1; 247 248 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName)); 249 assert(MAI && "Unable to create target asm info!"); 250 251 AsmLexer Lexer(*MAI); 252 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0)); 253 254 OwningPtr<tool_output_file> Out(GetOutputStream()); 255 if (!Out) 256 return 1; 257 258 bool Error = false; 259 while (Lexer.Lex().isNot(AsmToken::Eof)) { 260 AsmToken Tok = Lexer.getTok(); 261 262 switch (Tok.getKind()) { 263 default: 264 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning"); 265 Error = true; 266 break; 267 case AsmToken::Error: 268 Error = true; // error already printed. 269 break; 270 case AsmToken::Identifier: 271 Out->os() << "identifier: " << Lexer.getTok().getString(); 272 break; 273 case AsmToken::Integer: 274 Out->os() << "int: " << Lexer.getTok().getString(); 275 break; 276 case AsmToken::Real: 277 Out->os() << "real: " << Lexer.getTok().getString(); 278 break; 279 case AsmToken::Register: 280 Out->os() << "register: " << Lexer.getTok().getRegVal(); 281 break; 282 case AsmToken::String: 283 Out->os() << "string: " << Lexer.getTok().getString(); 284 break; 285 286 case AsmToken::Amp: Out->os() << "Amp"; break; 287 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break; 288 case AsmToken::At: Out->os() << "At"; break; 289 case AsmToken::Caret: Out->os() << "Caret"; break; 290 case AsmToken::Colon: Out->os() << "Colon"; break; 291 case AsmToken::Comma: Out->os() << "Comma"; break; 292 case AsmToken::Dollar: Out->os() << "Dollar"; break; 293 case AsmToken::Dot: Out->os() << "Dot"; break; 294 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break; 295 case AsmToken::Eof: Out->os() << "Eof"; break; 296 case AsmToken::Equal: Out->os() << "Equal"; break; 297 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break; 298 case AsmToken::Exclaim: Out->os() << "Exclaim"; break; 299 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break; 300 case AsmToken::Greater: Out->os() << "Greater"; break; 301 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break; 302 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break; 303 case AsmToken::Hash: Out->os() << "Hash"; break; 304 case AsmToken::LBrac: Out->os() << "LBrac"; break; 305 case AsmToken::LCurly: Out->os() << "LCurly"; break; 306 case AsmToken::LParen: Out->os() << "LParen"; break; 307 case AsmToken::Less: Out->os() << "Less"; break; 308 case AsmToken::LessEqual: Out->os() << "LessEqual"; break; 309 case AsmToken::LessGreater: Out->os() << "LessGreater"; break; 310 case AsmToken::LessLess: Out->os() << "LessLess"; break; 311 case AsmToken::Minus: Out->os() << "Minus"; break; 312 case AsmToken::Percent: Out->os() << "Percent"; break; 313 case AsmToken::Pipe: Out->os() << "Pipe"; break; 314 case AsmToken::PipePipe: Out->os() << "PipePipe"; break; 315 case AsmToken::Plus: Out->os() << "Plus"; break; 316 case AsmToken::RBrac: Out->os() << "RBrac"; break; 317 case AsmToken::RCurly: Out->os() << "RCurly"; break; 318 case AsmToken::RParen: Out->os() << "RParen"; break; 319 case AsmToken::Slash: Out->os() << "Slash"; break; 320 case AsmToken::Star: Out->os() << "Star"; break; 321 case AsmToken::Tilde: Out->os() << "Tilde"; break; 322 } 323 324 // Print the token string. 325 Out->os() << " (\""; 326 Out->os().write_escaped(Tok.getString()); 327 Out->os() << "\")\n"; 328 } 329 330 // Keep output if no errors. 331 if (Error == 0) Out->keep(); 332 333 return Error; 334 } 335 336 static int AssembleInput(const char *ProgName) { 337 const Target *TheTarget = GetTarget(ProgName); 338 if (!TheTarget) 339 return 1; 340 341 OwningPtr<MemoryBuffer> BufferPtr; 342 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, BufferPtr)) { 343 errs() << ProgName << ": " << ec.message() << '\n'; 344 return 1; 345 } 346 MemoryBuffer *Buffer = BufferPtr.take(); 347 348 SourceMgr SrcMgr; 349 350 // Tell SrcMgr about this buffer, which is what the parser will pick up. 351 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 352 353 // Record the location of the include directories so that the lexer can find 354 // it later. 355 SrcMgr.setIncludeDirs(IncludeDirs); 356 357 358 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(TripleName)); 359 assert(MAI && "Unable to create target asm info!"); 360 361 llvm::OwningPtr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 362 assert(MRI && "Unable to create target register info!"); 363 364 // Package up features to be passed to target/subtarget 365 std::string FeaturesStr; 366 367 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 368 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 369 OwningPtr<MCObjectFileInfo> MOFI(new MCObjectFileInfo()); 370 MCContext Ctx(*MAI, *MRI, MOFI.get()); 371 MOFI->InitMCObjectFileInfo(TripleName, RelocModel, CMModel, Ctx); 372 373 if (SaveTempLabels) 374 Ctx.setAllowTemporaryLabels(false); 375 376 OwningPtr<tool_output_file> Out(GetOutputStream()); 377 if (!Out) 378 return 1; 379 380 formatted_raw_ostream FOS(Out->os()); 381 OwningPtr<MCStreamer> Str; 382 383 OwningPtr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 384 OwningPtr<MCSubtargetInfo> 385 STI(TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 386 387 // FIXME: There is a bit of code duplication with addPassesToEmitFile. 388 if (FileType == OFT_AssemblyFile) { 389 MCInstPrinter *IP = 390 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI); 391 MCCodeEmitter *CE = 0; 392 MCAsmBackend *MAB = 0; 393 if (ShowEncoding) { 394 CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx); 395 MAB = TheTarget->createMCAsmBackend(TripleName); 396 } 397 Str.reset(TheTarget->createAsmStreamer(Ctx, FOS, /*asmverbose*/true, 398 /*useLoc*/ true, 399 /*useCFI*/ true, IP, CE, MAB, 400 ShowInst)); 401 } else if (FileType == OFT_Null) { 402 Str.reset(createNullStreamer(Ctx)); 403 } else { 404 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 405 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *STI, Ctx); 406 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(TripleName); 407 Str.reset(TheTarget->createMCObjectStreamer(TripleName, Ctx, *MAB, 408 FOS, CE, RelaxAll, 409 NoExecStack)); 410 } 411 412 if (EnableLogging) { 413 Str.reset(createLoggingStreamer(Str.take(), errs())); 414 } 415 416 OwningPtr<MCAsmParser> Parser(createMCAsmParser(SrcMgr, Ctx, 417 *Str.get(), *MAI)); 418 OwningPtr<MCTargetAsmParser> TAP(TheTarget->createMCAsmParser(*STI, *Parser)); 419 if (!TAP) { 420 errs() << ProgName 421 << ": error: this target does not support assembly parsing.\n"; 422 return 1; 423 } 424 425 Parser->setShowParsedOperands(ShowInstOperands); 426 Parser->setTargetParser(*TAP.get()); 427 428 int Res = Parser->Run(NoInitialTextSection); 429 430 // Keep output if no errors. 431 if (Res == 0) Out->keep(); 432 433 return Res; 434 } 435 436 static int DisassembleInput(const char *ProgName, bool Enhanced) { 437 const Target *TheTarget = GetTarget(ProgName); 438 if (!TheTarget) 439 return 0; 440 441 OwningPtr<MemoryBuffer> Buffer; 442 if (error_code ec = MemoryBuffer::getFileOrSTDIN(InputFilename, Buffer)) { 443 errs() << ProgName << ": " << ec.message() << '\n'; 444 return 1; 445 } 446 447 OwningPtr<tool_output_file> Out(GetOutputStream()); 448 if (!Out) 449 return 1; 450 451 int Res; 452 if (Enhanced) { 453 Res = 454 Disassembler::disassembleEnhanced(TripleName, *Buffer.take(), Out->os()); 455 } else { 456 Res = Disassembler::disassemble(*TheTarget, TripleName, 457 *Buffer.take(), Out->os()); 458 } 459 460 // Keep output if no errors. 461 if (Res == 0) Out->keep(); 462 463 return Res; 464 } 465 466 467 int main(int argc, char **argv) { 468 // Print a stack trace if we signal out. 469 sys::PrintStackTraceOnErrorSignal(); 470 PrettyStackTraceProgram X(argc, argv); 471 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 472 473 // Initialize targets and assembly printers/parsers. 474 llvm::InitializeAllTargetInfos(); 475 llvm::InitializeAllTargetMCs(); 476 llvm::InitializeAllAsmParsers(); 477 llvm::InitializeAllDisassemblers(); 478 479 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 480 TripleName = Triple::normalize(TripleName); 481 482 switch (Action) { 483 default: 484 case AC_AsLex: 485 return AsLexInput(argv[0]); 486 case AC_Assemble: 487 return AssembleInput(argv[0]); 488 case AC_Disassemble: 489 return DisassembleInput(argv[0], false); 490 case AC_EDisassemble: 491 return DisassembleInput(argv[0], true); 492 } 493 494 return 0; 495 } 496 497