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/MCContext.h" 18 #include "llvm/MC/MCCodeEmitter.h" 19 #include "llvm/MC/MCInstPrinter.h" 20 #include "llvm/MC/MCSectionMachO.h" 21 #include "llvm/MC/MCStreamer.h" 22 #include "llvm/Target/TargetAsmBackend.h" 23 #include "llvm/Target/TargetAsmParser.h" 24 #include "llvm/Target/TargetData.h" 25 #include "llvm/Target/TargetRegistry.h" 26 #include "llvm/Target/TargetMachine.h" // FIXME. 27 #include "llvm/Target/TargetSelect.h" 28 #include "llvm/ADT/OwningPtr.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/FileUtilities.h" 31 #include "llvm/Support/FormattedStream.h" 32 #include "llvm/Support/ManagedStatic.h" 33 #include "llvm/Support/MemoryBuffer.h" 34 #include "llvm/Support/PrettyStackTrace.h" 35 #include "llvm/Support/SourceMgr.h" 36 #include "llvm/Support/ToolOutputFile.h" 37 #include "llvm/System/Host.h" 38 #include "llvm/System/Signals.h" 39 #include "Disassembler.h" 40 using namespace llvm; 41 42 static cl::opt<std::string> 43 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); 44 45 static cl::opt<std::string> 46 OutputFilename("o", cl::desc("Output filename"), 47 cl::value_desc("filename")); 48 49 static cl::opt<bool> 50 ShowEncoding("show-encoding", cl::desc("Show instruction encodings")); 51 52 static cl::opt<bool> 53 ShowInst("show-inst", cl::desc("Show internal instruction representation")); 54 55 static cl::opt<bool> 56 ShowInstOperands("show-inst-operands", 57 cl::desc("Show instructions operands as parsed")); 58 59 static cl::opt<unsigned> 60 OutputAsmVariant("output-asm-variant", 61 cl::desc("Syntax variant to use for output printing")); 62 63 static cl::opt<bool> 64 RelaxAll("mc-relax-all", cl::desc("Relax all fixups")); 65 66 static cl::opt<bool> 67 EnableLogging("enable-api-logging", cl::desc("Enable MC API logging")); 68 69 enum OutputFileType { 70 OFT_Null, 71 OFT_AssemblyFile, 72 OFT_ObjectFile 73 }; 74 static cl::opt<OutputFileType> 75 FileType("filetype", cl::init(OFT_AssemblyFile), 76 cl::desc("Choose an output file type:"), 77 cl::values( 78 clEnumValN(OFT_AssemblyFile, "asm", 79 "Emit an assembly ('.s') file"), 80 clEnumValN(OFT_Null, "null", 81 "Don't emit anything (for timing purposes)"), 82 clEnumValN(OFT_ObjectFile, "obj", 83 "Emit a native object ('.o') file"), 84 clEnumValEnd)); 85 86 static cl::list<std::string> 87 IncludeDirs("I", cl::desc("Directory of include files"), 88 cl::value_desc("directory"), cl::Prefix); 89 90 static cl::opt<std::string> 91 ArchName("arch", cl::desc("Target arch to assemble for, " 92 "see -version for available targets")); 93 94 static cl::opt<std::string> 95 TripleName("triple", cl::desc("Target triple to assemble for, " 96 "see -version for available targets")); 97 98 static cl::opt<bool> 99 NoInitialTextSection("n", cl::desc( 100 "Don't assume assembly file starts in the text section")); 101 102 enum ActionType { 103 AC_AsLex, 104 AC_Assemble, 105 AC_Disassemble, 106 AC_EDisassemble 107 }; 108 109 static cl::opt<ActionType> 110 Action(cl::desc("Action to perform:"), 111 cl::init(AC_Assemble), 112 cl::values(clEnumValN(AC_AsLex, "as-lex", 113 "Lex tokens from a .s file"), 114 clEnumValN(AC_Assemble, "assemble", 115 "Assemble a .s file (default)"), 116 clEnumValN(AC_Disassemble, "disassemble", 117 "Disassemble strings of hex bytes"), 118 clEnumValN(AC_EDisassemble, "edis", 119 "Enhanced disassembly of strings of hex bytes"), 120 clEnumValEnd)); 121 122 static const Target *GetTarget(const char *ProgName) { 123 // Figure out the target triple. 124 if (TripleName.empty()) 125 TripleName = sys::getHostTriple(); 126 if (!ArchName.empty()) { 127 llvm::Triple TT(TripleName); 128 TT.setArchName(ArchName); 129 TripleName = TT.str(); 130 } 131 132 // Get the target specific parser. 133 std::string Error; 134 const Target *TheTarget = TargetRegistry::lookupTarget(TripleName, Error); 135 if (TheTarget) 136 return TheTarget; 137 138 errs() << ProgName << ": error: unable to get target for '" << TripleName 139 << "', see --version and --triple.\n"; 140 return 0; 141 } 142 143 static tool_output_file *GetOutputStream() { 144 if (OutputFilename == "") 145 OutputFilename = "-"; 146 147 std::string Err; 148 tool_output_file *Out = new tool_output_file(OutputFilename.c_str(), Err, 149 raw_fd_ostream::F_Binary); 150 if (!Err.empty()) { 151 errs() << Err << '\n'; 152 delete Out; 153 return 0; 154 } 155 156 return Out; 157 } 158 159 static int AsLexInput(const char *ProgName) { 160 std::string ErrorMessage; 161 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, 162 &ErrorMessage); 163 if (Buffer == 0) { 164 errs() << ProgName << ": "; 165 if (ErrorMessage.size()) 166 errs() << ErrorMessage << "\n"; 167 else 168 errs() << "input file didn't read correctly.\n"; 169 return 1; 170 } 171 172 SourceMgr SrcMgr; 173 174 // Tell SrcMgr about this buffer, which is what TGParser will pick up. 175 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 176 177 // Record the location of the include directories so that the lexer can find 178 // it later. 179 SrcMgr.setIncludeDirs(IncludeDirs); 180 181 const Target *TheTarget = GetTarget(ProgName); 182 if (!TheTarget) 183 return 1; 184 185 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName)); 186 assert(MAI && "Unable to create target asm info!"); 187 188 AsmLexer Lexer(*MAI); 189 Lexer.setBuffer(SrcMgr.getMemoryBuffer(0)); 190 191 OwningPtr<tool_output_file> Out(GetOutputStream()); 192 if (!Out) 193 return 1; 194 195 bool Error = false; 196 while (Lexer.Lex().isNot(AsmToken::Eof)) { 197 AsmToken Tok = Lexer.getTok(); 198 199 switch (Tok.getKind()) { 200 default: 201 SrcMgr.PrintMessage(Lexer.getLoc(), "unknown token", "warning"); 202 Error = true; 203 break; 204 case AsmToken::Error: 205 Error = true; // error already printed. 206 break; 207 case AsmToken::Identifier: 208 Out->os() << "identifier: " << Lexer.getTok().getString(); 209 break; 210 case AsmToken::Integer: 211 Out->os() << "int: " << Lexer.getTok().getString(); 212 break; 213 case AsmToken::Real: 214 Out->os() << "real: " << Lexer.getTok().getString(); 215 break; 216 case AsmToken::Register: 217 Out->os() << "register: " << Lexer.getTok().getRegVal(); 218 break; 219 case AsmToken::String: 220 Out->os() << "string: " << Lexer.getTok().getString(); 221 break; 222 223 case AsmToken::Amp: Out->os() << "Amp"; break; 224 case AsmToken::AmpAmp: Out->os() << "AmpAmp"; break; 225 case AsmToken::At: Out->os() << "At"; break; 226 case AsmToken::Caret: Out->os() << "Caret"; break; 227 case AsmToken::Colon: Out->os() << "Colon"; break; 228 case AsmToken::Comma: Out->os() << "Comma"; break; 229 case AsmToken::Dollar: Out->os() << "Dollar"; break; 230 case AsmToken::Dot: Out->os() << "Dot"; break; 231 case AsmToken::EndOfStatement: Out->os() << "EndOfStatement"; break; 232 case AsmToken::Eof: Out->os() << "Eof"; break; 233 case AsmToken::Equal: Out->os() << "Equal"; break; 234 case AsmToken::EqualEqual: Out->os() << "EqualEqual"; break; 235 case AsmToken::Exclaim: Out->os() << "Exclaim"; break; 236 case AsmToken::ExclaimEqual: Out->os() << "ExclaimEqual"; break; 237 case AsmToken::Greater: Out->os() << "Greater"; break; 238 case AsmToken::GreaterEqual: Out->os() << "GreaterEqual"; break; 239 case AsmToken::GreaterGreater: Out->os() << "GreaterGreater"; break; 240 case AsmToken::Hash: Out->os() << "Hash"; break; 241 case AsmToken::LBrac: Out->os() << "LBrac"; break; 242 case AsmToken::LCurly: Out->os() << "LCurly"; break; 243 case AsmToken::LParen: Out->os() << "LParen"; break; 244 case AsmToken::Less: Out->os() << "Less"; break; 245 case AsmToken::LessEqual: Out->os() << "LessEqual"; break; 246 case AsmToken::LessGreater: Out->os() << "LessGreater"; break; 247 case AsmToken::LessLess: Out->os() << "LessLess"; break; 248 case AsmToken::Minus: Out->os() << "Minus"; break; 249 case AsmToken::Percent: Out->os() << "Percent"; break; 250 case AsmToken::Pipe: Out->os() << "Pipe"; break; 251 case AsmToken::PipePipe: Out->os() << "PipePipe"; break; 252 case AsmToken::Plus: Out->os() << "Plus"; break; 253 case AsmToken::RBrac: Out->os() << "RBrac"; break; 254 case AsmToken::RCurly: Out->os() << "RCurly"; break; 255 case AsmToken::RParen: Out->os() << "RParen"; break; 256 case AsmToken::Slash: Out->os() << "Slash"; break; 257 case AsmToken::Star: Out->os() << "Star"; break; 258 case AsmToken::Tilde: Out->os() << "Tilde"; break; 259 } 260 261 // Print the token string. 262 Out->os() << " (\""; 263 Out->os().write_escaped(Tok.getString()); 264 Out->os() << "\")\n"; 265 } 266 267 // Keep output if no errors. 268 if (Error == 0) Out->keep(); 269 270 return Error; 271 } 272 273 static int AssembleInput(const char *ProgName) { 274 const Target *TheTarget = GetTarget(ProgName); 275 if (!TheTarget) 276 return 1; 277 278 std::string Error; 279 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, &Error); 280 if (Buffer == 0) { 281 errs() << ProgName << ": "; 282 if (Error.size()) 283 errs() << Error << "\n"; 284 else 285 errs() << "input file didn't read correctly.\n"; 286 return 1; 287 } 288 289 SourceMgr SrcMgr; 290 291 // Tell SrcMgr about this buffer, which is what the parser will pick up. 292 SrcMgr.AddNewSourceBuffer(Buffer, SMLoc()); 293 294 // Record the location of the include directories so that the lexer can find 295 // it later. 296 SrcMgr.setIncludeDirs(IncludeDirs); 297 298 299 llvm::OwningPtr<MCAsmInfo> MAI(TheTarget->createAsmInfo(TripleName)); 300 assert(MAI && "Unable to create target asm info!"); 301 302 MCContext Ctx(*MAI); 303 304 // FIXME: We shouldn't need to do this (and link in codegen). 305 OwningPtr<TargetMachine> TM(TheTarget->createTargetMachine(TripleName, "")); 306 307 if (!TM) { 308 errs() << ProgName << ": error: could not create target for triple '" 309 << TripleName << "'.\n"; 310 return 1; 311 } 312 313 OwningPtr<tool_output_file> Out(GetOutputStream()); 314 if (!Out) 315 return 1; 316 317 formatted_raw_ostream FOS(Out->os()); 318 OwningPtr<MCStreamer> Str; 319 320 if (FileType == OFT_AssemblyFile) { 321 MCInstPrinter *IP = 322 TheTarget->createMCInstPrinter(OutputAsmVariant, *MAI); 323 MCCodeEmitter *CE = 0; 324 if (ShowEncoding) 325 CE = TheTarget->createCodeEmitter(*TM, Ctx); 326 Str.reset(createAsmStreamer(Ctx, FOS, 327 TM->getTargetData()->isLittleEndian(), 328 /*asmverbose*/true, IP, CE, ShowInst)); 329 } else if (FileType == OFT_Null) { 330 Str.reset(createNullStreamer(Ctx)); 331 } else { 332 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 333 MCCodeEmitter *CE = TheTarget->createCodeEmitter(*TM, Ctx); 334 TargetAsmBackend *TAB = TheTarget->createAsmBackend(TripleName); 335 Str.reset(TheTarget->createObjectStreamer(TripleName, Ctx, *TAB, 336 FOS, CE, RelaxAll)); 337 } 338 339 if (EnableLogging) { 340 Str.reset(createLoggingStreamer(Str.take(), errs())); 341 } 342 343 OwningPtr<MCAsmParser> Parser(createMCAsmParser(*TheTarget, SrcMgr, Ctx, 344 *Str.get(), *MAI)); 345 OwningPtr<TargetAsmParser> TAP(TheTarget->createAsmParser(*Parser, *TM)); 346 if (!TAP) { 347 errs() << ProgName 348 << ": error: this target does not support assembly parsing.\n"; 349 return 1; 350 } 351 352 Parser->setShowParsedOperands(ShowInstOperands); 353 Parser->setTargetParser(*TAP.get()); 354 355 int Res = Parser->Run(NoInitialTextSection); 356 357 // Keep output if no errors. 358 if (Res == 0) Out->keep(); 359 360 return Res; 361 } 362 363 static int DisassembleInput(const char *ProgName, bool Enhanced) { 364 const Target *TheTarget = GetTarget(ProgName); 365 if (!TheTarget) 366 return 0; 367 368 std::string ErrorMessage; 369 370 MemoryBuffer *Buffer = MemoryBuffer::getFileOrSTDIN(InputFilename, 371 &ErrorMessage); 372 373 if (Buffer == 0) { 374 errs() << ProgName << ": "; 375 if (ErrorMessage.size()) 376 errs() << ErrorMessage << "\n"; 377 else 378 errs() << "input file didn't read correctly.\n"; 379 return 1; 380 } 381 382 OwningPtr<tool_output_file> Out(GetOutputStream()); 383 if (!Out) 384 return 1; 385 386 int Res; 387 if (Enhanced) 388 Res = Disassembler::disassembleEnhanced(TripleName, *Buffer, Out->os()); 389 else 390 Res = Disassembler::disassemble(*TheTarget, TripleName, *Buffer, Out->os()); 391 392 // Keep output if no errors. 393 if (Res == 0) Out->keep(); 394 395 return Res; 396 } 397 398 399 int main(int argc, char **argv) { 400 // Print a stack trace if we signal out. 401 sys::PrintStackTraceOnErrorSignal(); 402 PrettyStackTraceProgram X(argc, argv); 403 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 404 405 // Initialize targets and assembly printers/parsers. 406 llvm::InitializeAllTargetInfos(); 407 // FIXME: We shouldn't need to initialize the Target(Machine)s. 408 llvm::InitializeAllTargets(); 409 llvm::InitializeAllAsmPrinters(); 410 llvm::InitializeAllAsmParsers(); 411 llvm::InitializeAllDisassemblers(); 412 413 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 414 TripleName = Triple::normalize(TripleName); 415 416 switch (Action) { 417 default: 418 case AC_AsLex: 419 return AsLexInput(argv[0]); 420 case AC_Assemble: 421 return AssembleInput(argv[0]); 422 case AC_Disassemble: 423 return DisassembleInput(argv[0], false); 424 case AC_EDisassemble: 425 return DisassembleInput(argv[0], true); 426 } 427 428 return 0; 429 } 430 431