1 //===-- llvm-mc.cpp - Machine Code Hacking Driver ---------------*- C++ -*-===// 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 "Disassembler.h" 16 #include "llvm/MC/MCAsmBackend.h" 17 #include "llvm/MC/MCAsmInfo.h" 18 #include "llvm/MC/MCContext.h" 19 #include "llvm/MC/MCInstPrinter.h" 20 #include "llvm/MC/MCInstrInfo.h" 21 #include "llvm/MC/MCObjectFileInfo.h" 22 #include "llvm/MC/MCParser/AsmLexer.h" 23 #include "llvm/MC/MCParser/MCTargetAsmParser.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/MCTargetOptionsCommandFlags.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/Compression.h" 31 #include "llvm/Support/FileUtilities.h" 32 #include "llvm/Support/FormattedStream.h" 33 #include "llvm/Support/Host.h" 34 #include "llvm/Support/ManagedStatic.h" 35 #include "llvm/Support/MemoryBuffer.h" 36 #include "llvm/Support/PrettyStackTrace.h" 37 #include "llvm/Support/Signals.h" 38 #include "llvm/Support/SourceMgr.h" 39 #include "llvm/Support/TargetRegistry.h" 40 #include "llvm/Support/TargetSelect.h" 41 #include "llvm/Support/ToolOutputFile.h" 42 43 using namespace llvm; 44 45 static cl::opt<std::string> 46 InputFilename(cl::Positional, cl::desc("<input file>"), cl::init("-")); 47 48 static cl::opt<std::string> 49 OutputFilename("o", cl::desc("Output filename"), 50 cl::value_desc("filename")); 51 52 static cl::opt<bool> 53 ShowEncoding("show-encoding", cl::desc("Show instruction encodings")); 54 55 static cl::opt<bool> 56 RelaxELFRel("relax-relocations", cl::init(false), 57 cl::desc("Emit R_X86_64_GOTPCRELX instead of R_X86_64_GOTPCREL")); 58 59 static cl::opt<DebugCompressionType> 60 CompressDebugSections("compress-debug-sections", cl::ValueOptional, 61 cl::init(DebugCompressionType::DCT_None), 62 cl::desc("Choose DWARF debug sections compression:"), 63 cl::values( 64 clEnumValN(DebugCompressionType::DCT_None, "none", 65 "No compression"), 66 clEnumValN(DebugCompressionType::DCT_Zlib, "zlib", 67 "Use zlib compression"), 68 clEnumValN(DebugCompressionType::DCT_ZlibGnu, "zlib-gnu", 69 "Use zlib-gnu compression (depricated)"), 70 clEnumValEnd)); 71 72 static cl::opt<bool> 73 ShowInst("show-inst", cl::desc("Show internal instruction representation")); 74 75 static cl::opt<bool> 76 ShowInstOperands("show-inst-operands", 77 cl::desc("Show instructions operands as parsed")); 78 79 static cl::opt<unsigned> 80 OutputAsmVariant("output-asm-variant", 81 cl::desc("Syntax variant to use for output printing")); 82 83 static cl::opt<bool> 84 PrintImmHex("print-imm-hex", cl::init(false), 85 cl::desc("Prefer hex format for immediate values")); 86 87 static cl::list<std::string> 88 DefineSymbol("defsym", cl::desc("Defines a symbol to be an integer constant")); 89 90 enum OutputFileType { 91 OFT_Null, 92 OFT_AssemblyFile, 93 OFT_ObjectFile 94 }; 95 static cl::opt<OutputFileType> 96 FileType("filetype", cl::init(OFT_AssemblyFile), 97 cl::desc("Choose an output file type:"), 98 cl::values( 99 clEnumValN(OFT_AssemblyFile, "asm", 100 "Emit an assembly ('.s') file"), 101 clEnumValN(OFT_Null, "null", 102 "Don't emit anything (for timing purposes)"), 103 clEnumValN(OFT_ObjectFile, "obj", 104 "Emit a native object ('.o') file"), 105 clEnumValEnd)); 106 107 static cl::list<std::string> 108 IncludeDirs("I", cl::desc("Directory of include files"), 109 cl::value_desc("directory"), cl::Prefix); 110 111 static cl::opt<std::string> 112 ArchName("arch", cl::desc("Target arch to assemble for, " 113 "see -version for available targets")); 114 115 static cl::opt<std::string> 116 TripleName("triple", cl::desc("Target triple to assemble for, " 117 "see -version for available targets")); 118 119 static cl::opt<std::string> 120 MCPU("mcpu", 121 cl::desc("Target a specific cpu type (-mcpu=help for details)"), 122 cl::value_desc("cpu-name"), 123 cl::init("")); 124 125 static cl::list<std::string> 126 MAttrs("mattr", 127 cl::CommaSeparated, 128 cl::desc("Target specific attributes (-mattr=help for details)"), 129 cl::value_desc("a1,+a2,-a3,...")); 130 131 static cl::opt<bool> PIC("position-independent", 132 cl::desc("Position independent"), cl::init(false)); 133 134 static cl::opt<llvm::CodeModel::Model> 135 CMModel("code-model", 136 cl::desc("Choose code model"), 137 cl::init(CodeModel::Default), 138 cl::values(clEnumValN(CodeModel::Default, "default", 139 "Target default code model"), 140 clEnumValN(CodeModel::Small, "small", 141 "Small code model"), 142 clEnumValN(CodeModel::Kernel, "kernel", 143 "Kernel code model"), 144 clEnumValN(CodeModel::Medium, "medium", 145 "Medium code model"), 146 clEnumValN(CodeModel::Large, "large", 147 "Large code model"), 148 clEnumValEnd)); 149 150 static cl::opt<bool> 151 NoInitialTextSection("n", cl::desc("Don't assume assembly file starts " 152 "in the text section")); 153 154 static cl::opt<bool> 155 GenDwarfForAssembly("g", cl::desc("Generate dwarf debugging info for assembly " 156 "source files")); 157 158 static cl::opt<std::string> 159 DebugCompilationDir("fdebug-compilation-dir", 160 cl::desc("Specifies the debug info's compilation dir")); 161 162 static cl::opt<std::string> 163 MainFileName("main-file-name", 164 cl::desc("Specifies the name we should consider the input file")); 165 166 static cl::opt<bool> SaveTempLabels("save-temp-labels", 167 cl::desc("Don't discard temporary labels")); 168 169 static cl::opt<bool> NoExecStack("no-exec-stack", 170 cl::desc("File doesn't need an exec stack")); 171 172 enum ActionType { 173 AC_AsLex, 174 AC_Assemble, 175 AC_Disassemble, 176 AC_MDisassemble, 177 }; 178 179 static cl::opt<ActionType> 180 Action(cl::desc("Action to perform:"), 181 cl::init(AC_Assemble), 182 cl::values(clEnumValN(AC_AsLex, "as-lex", 183 "Lex tokens from a .s file"), 184 clEnumValN(AC_Assemble, "assemble", 185 "Assemble a .s file (default)"), 186 clEnumValN(AC_Disassemble, "disassemble", 187 "Disassemble strings of hex bytes"), 188 clEnumValN(AC_MDisassemble, "mdis", 189 "Marked up disassembly of strings of hex bytes"), 190 clEnumValEnd)); 191 192 static const Target *GetTarget(const char *ProgName) { 193 // Figure out the target triple. 194 if (TripleName.empty()) 195 TripleName = sys::getDefaultTargetTriple(); 196 Triple TheTriple(Triple::normalize(TripleName)); 197 198 // Get the target specific parser. 199 std::string Error; 200 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 201 Error); 202 if (!TheTarget) { 203 errs() << ProgName << ": " << Error; 204 return nullptr; 205 } 206 207 // Update the triple name and return the found target. 208 TripleName = TheTriple.getTriple(); 209 return TheTarget; 210 } 211 212 static std::unique_ptr<tool_output_file> GetOutputStream() { 213 if (OutputFilename == "") 214 OutputFilename = "-"; 215 216 std::error_code EC; 217 auto Out = llvm::make_unique<tool_output_file>(OutputFilename, EC, 218 sys::fs::F_None); 219 if (EC) { 220 errs() << EC.message() << '\n'; 221 return nullptr; 222 } 223 224 return Out; 225 } 226 227 static std::string DwarfDebugFlags; 228 static void setDwarfDebugFlags(int argc, char **argv) { 229 if (!getenv("RC_DEBUG_OPTIONS")) 230 return; 231 for (int i = 0; i < argc; i++) { 232 DwarfDebugFlags += argv[i]; 233 if (i + 1 < argc) 234 DwarfDebugFlags += " "; 235 } 236 } 237 238 static std::string DwarfDebugProducer; 239 static void setDwarfDebugProducer() { 240 if(!getenv("DEBUG_PRODUCER")) 241 return; 242 DwarfDebugProducer += getenv("DEBUG_PRODUCER"); 243 } 244 245 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, 246 raw_ostream &OS) { 247 248 AsmLexer Lexer(MAI); 249 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer()); 250 251 bool Error = false; 252 while (Lexer.Lex().isNot(AsmToken::Eof)) { 253 AsmToken Tok = Lexer.getTok(); 254 255 switch (Tok.getKind()) { 256 default: 257 SrcMgr.PrintMessage(Lexer.getLoc(), SourceMgr::DK_Warning, 258 "unknown token"); 259 Error = true; 260 break; 261 case AsmToken::Error: 262 Error = true; // error already printed. 263 break; 264 case AsmToken::Identifier: 265 OS << "identifier: " << Lexer.getTok().getString(); 266 break; 267 case AsmToken::Integer: 268 OS << "int: " << Lexer.getTok().getString(); 269 break; 270 case AsmToken::Real: 271 OS << "real: " << Lexer.getTok().getString(); 272 break; 273 case AsmToken::String: 274 OS << "string: " << Lexer.getTok().getString(); 275 break; 276 277 case AsmToken::Amp: OS << "Amp"; break; 278 case AsmToken::AmpAmp: OS << "AmpAmp"; break; 279 case AsmToken::At: OS << "At"; break; 280 case AsmToken::Caret: OS << "Caret"; break; 281 case AsmToken::Colon: OS << "Colon"; break; 282 case AsmToken::Comma: OS << "Comma"; break; 283 case AsmToken::Dollar: OS << "Dollar"; break; 284 case AsmToken::Dot: OS << "Dot"; break; 285 case AsmToken::EndOfStatement: OS << "EndOfStatement"; break; 286 case AsmToken::Eof: OS << "Eof"; break; 287 case AsmToken::Equal: OS << "Equal"; break; 288 case AsmToken::EqualEqual: OS << "EqualEqual"; break; 289 case AsmToken::Exclaim: OS << "Exclaim"; break; 290 case AsmToken::ExclaimEqual: OS << "ExclaimEqual"; break; 291 case AsmToken::Greater: OS << "Greater"; break; 292 case AsmToken::GreaterEqual: OS << "GreaterEqual"; break; 293 case AsmToken::GreaterGreater: OS << "GreaterGreater"; break; 294 case AsmToken::Hash: OS << "Hash"; break; 295 case AsmToken::LBrac: OS << "LBrac"; break; 296 case AsmToken::LCurly: OS << "LCurly"; break; 297 case AsmToken::LParen: OS << "LParen"; break; 298 case AsmToken::Less: OS << "Less"; break; 299 case AsmToken::LessEqual: OS << "LessEqual"; break; 300 case AsmToken::LessGreater: OS << "LessGreater"; break; 301 case AsmToken::LessLess: OS << "LessLess"; break; 302 case AsmToken::Minus: OS << "Minus"; break; 303 case AsmToken::Percent: OS << "Percent"; break; 304 case AsmToken::Pipe: OS << "Pipe"; break; 305 case AsmToken::PipePipe: OS << "PipePipe"; break; 306 case AsmToken::Plus: OS << "Plus"; break; 307 case AsmToken::RBrac: OS << "RBrac"; break; 308 case AsmToken::RCurly: OS << "RCurly"; break; 309 case AsmToken::RParen: OS << "RParen"; break; 310 case AsmToken::Slash: OS << "Slash"; break; 311 case AsmToken::Star: OS << "Star"; break; 312 case AsmToken::Tilde: OS << "Tilde"; break; 313 } 314 315 // Print the token string. 316 OS << " (\""; 317 OS.write_escaped(Tok.getString()); 318 OS << "\")\n"; 319 } 320 321 return Error; 322 } 323 324 static int fillCommandLineSymbols(MCAsmParser &Parser){ 325 for(auto &I: DefineSymbol){ 326 auto Pair = StringRef(I).split('='); 327 if(Pair.second.empty()){ 328 errs() << "error: defsym must be of the form: sym=value: " << I; 329 return 1; 330 } 331 int64_t Value; 332 if(Pair.second.getAsInteger(0, Value)){ 333 errs() << "error: Value is not an integer: " << Pair.second; 334 return 1; 335 } 336 auto &Context = Parser.getContext(); 337 auto Symbol = Context.getOrCreateSymbol(Pair.first); 338 Parser.getStreamer().EmitAssignment(Symbol, 339 MCConstantExpr::create(Value, Context)); 340 } 341 return 0; 342 } 343 344 static int AssembleInput(const char *ProgName, const Target *TheTarget, 345 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, 346 MCAsmInfo &MAI, MCSubtargetInfo &STI, 347 MCInstrInfo &MCII, MCTargetOptions &MCOptions) { 348 std::unique_ptr<MCAsmParser> Parser( 349 createMCAsmParser(SrcMgr, Ctx, Str, MAI)); 350 std::unique_ptr<MCTargetAsmParser> TAP( 351 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions)); 352 353 if (!TAP) { 354 errs() << ProgName 355 << ": error: this target does not support assembly parsing.\n"; 356 return 1; 357 } 358 359 int SymbolResult = fillCommandLineSymbols(*Parser); 360 if(SymbolResult) 361 return SymbolResult; 362 Parser->setShowParsedOperands(ShowInstOperands); 363 Parser->setTargetParser(*TAP); 364 365 int Res = Parser->Run(NoInitialTextSection); 366 367 return Res; 368 } 369 370 int main(int argc, char **argv) { 371 // Print a stack trace if we signal out. 372 sys::PrintStackTraceOnErrorSignal(argv[0]); 373 PrettyStackTraceProgram X(argc, argv); 374 llvm_shutdown_obj Y; // Call llvm_shutdown() on exit. 375 376 // Initialize targets and assembly printers/parsers. 377 llvm::InitializeAllTargetInfos(); 378 llvm::InitializeAllTargetMCs(); 379 llvm::InitializeAllAsmParsers(); 380 llvm::InitializeAllDisassemblers(); 381 382 // Register the target printer for --version. 383 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 384 385 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 386 MCTargetOptions MCOptions = InitMCTargetOptionsFromFlags(); 387 TripleName = Triple::normalize(TripleName); 388 setDwarfDebugFlags(argc, argv); 389 390 setDwarfDebugProducer(); 391 392 const char *ProgName = argv[0]; 393 const Target *TheTarget = GetTarget(ProgName); 394 if (!TheTarget) 395 return 1; 396 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to 397 // construct the Triple object. 398 Triple TheTriple(TripleName); 399 400 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr = 401 MemoryBuffer::getFileOrSTDIN(InputFilename); 402 if (std::error_code EC = BufferPtr.getError()) { 403 errs() << InputFilename << ": " << EC.message() << '\n'; 404 return 1; 405 } 406 MemoryBuffer *Buffer = BufferPtr->get(); 407 408 SourceMgr SrcMgr; 409 410 // Tell SrcMgr about this buffer, which is what the parser will pick up. 411 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc()); 412 413 // Record the location of the include directories so that the lexer can find 414 // it later. 415 SrcMgr.setIncludeDirs(IncludeDirs); 416 417 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 418 assert(MRI && "Unable to create target register info!"); 419 420 std::unique_ptr<MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TripleName)); 421 assert(MAI && "Unable to create target asm info!"); 422 423 MAI->setRelaxELFRelocations(RelaxELFRel); 424 425 if (CompressDebugSections != DebugCompressionType::DCT_None) { 426 if (!zlib::isAvailable()) { 427 errs() << ProgName 428 << ": build tools with zlib to enable -compress-debug-sections"; 429 return 1; 430 } 431 MAI->setCompressDebugSections(CompressDebugSections); 432 } 433 434 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 435 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 436 MCObjectFileInfo MOFI; 437 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr); 438 MOFI.InitMCObjectFileInfo(TheTriple, PIC, CMModel, Ctx); 439 440 if (SaveTempLabels) 441 Ctx.setAllowTemporaryLabels(false); 442 443 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly); 444 // Default to 4 for dwarf version. 445 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4; 446 if (DwarfVersion < 2 || DwarfVersion > 4) { 447 errs() << ProgName << ": Dwarf version " << DwarfVersion 448 << " is not supported." << '\n'; 449 return 1; 450 } 451 Ctx.setDwarfVersion(DwarfVersion); 452 if (!DwarfDebugFlags.empty()) 453 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags)); 454 if (!DwarfDebugProducer.empty()) 455 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer)); 456 if (!DebugCompilationDir.empty()) 457 Ctx.setCompilationDir(DebugCompilationDir); 458 else { 459 // If no compilation dir is set, try to use the current directory. 460 SmallString<128> CWD; 461 if (!sys::fs::current_path(CWD)) 462 Ctx.setCompilationDir(CWD); 463 } 464 if (!MainFileName.empty()) 465 Ctx.setMainFileName(MainFileName); 466 467 // Package up features to be passed to target/subtarget 468 std::string FeaturesStr; 469 if (MAttrs.size()) { 470 SubtargetFeatures Features; 471 for (unsigned i = 0; i != MAttrs.size(); ++i) 472 Features.AddFeature(MAttrs[i]); 473 FeaturesStr = Features.getString(); 474 } 475 476 std::unique_ptr<tool_output_file> Out = GetOutputStream(); 477 if (!Out) 478 return 1; 479 480 std::unique_ptr<buffer_ostream> BOS; 481 raw_pwrite_stream *OS = &Out->os(); 482 std::unique_ptr<MCStreamer> Str; 483 484 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 485 std::unique_ptr<MCSubtargetInfo> STI( 486 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 487 488 MCInstPrinter *IP = nullptr; 489 if (FileType == OFT_AssemblyFile) { 490 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant, 491 *MAI, *MCII, *MRI); 492 493 // Set the display preference for hex vs. decimal immediates. 494 IP->setPrintImmHex(PrintImmHex); 495 496 // Set up the AsmStreamer. 497 MCCodeEmitter *CE = nullptr; 498 MCAsmBackend *MAB = nullptr; 499 if (ShowEncoding) { 500 CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); 501 MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); 502 } 503 auto FOut = llvm::make_unique<formatted_raw_ostream>(*OS); 504 Str.reset(TheTarget->createAsmStreamer( 505 Ctx, std::move(FOut), /*asmverbose*/ true, 506 /*useDwarfDirectory*/ true, IP, CE, MAB, ShowInst)); 507 508 } else if (FileType == OFT_Null) { 509 Str.reset(TheTarget->createNullStreamer(Ctx)); 510 } else { 511 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 512 513 // Don't waste memory on names of temp labels. 514 Ctx.setUseNamesOnTempLabels(false); 515 516 if (!Out->os().supportsSeeking()) { 517 BOS = make_unique<buffer_ostream>(Out->os()); 518 OS = BOS.get(); 519 } 520 521 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); 522 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*MRI, TripleName, MCPU); 523 Str.reset(TheTarget->createMCObjectStreamer( 524 TheTriple, Ctx, *MAB, *OS, CE, *STI, MCOptions.MCRelaxAll, 525 MCOptions.MCIncrementalLinkerCompatible, 526 /*DWARFMustBeAtTheEnd*/ false)); 527 if (NoExecStack) 528 Str->InitSections(true); 529 } 530 531 int Res = 1; 532 bool disassemble = false; 533 switch (Action) { 534 case AC_AsLex: 535 Res = AsLexInput(SrcMgr, *MAI, Out->os()); 536 break; 537 case AC_Assemble: 538 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, 539 *MCII, MCOptions); 540 break; 541 case AC_MDisassemble: 542 assert(IP && "Expected assembly output"); 543 IP->setUseMarkup(1); 544 disassemble = true; 545 break; 546 case AC_Disassemble: 547 disassemble = true; 548 break; 549 } 550 if (disassemble) 551 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, 552 *Buffer, SrcMgr, Out->os()); 553 554 // Keep output if no errors. 555 if (Res == 0) Out->keep(); 556 return Res; 557 } 558