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