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