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