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