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