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