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