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