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