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