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> LexMotorolaIntegers( 177 "motorola-integers", 178 cl::desc("Enable binary and hex Motorola integers (%110 and $ABC)")); 179 180 static cl::opt<bool> NoExecStack("no-exec-stack", 181 cl::desc("File doesn't need an exec stack")); 182 183 enum ActionType { 184 AC_AsLex, 185 AC_Assemble, 186 AC_Disassemble, 187 AC_MDisassemble, 188 }; 189 190 static cl::opt<ActionType> 191 Action(cl::desc("Action to perform:"), 192 cl::init(AC_Assemble), 193 cl::values(clEnumValN(AC_AsLex, "as-lex", 194 "Lex tokens from a .s file"), 195 clEnumValN(AC_Assemble, "assemble", 196 "Assemble a .s file (default)"), 197 clEnumValN(AC_Disassemble, "disassemble", 198 "Disassemble strings of hex bytes"), 199 clEnumValN(AC_MDisassemble, "mdis", 200 "Marked up disassembly of strings of hex bytes"))); 201 202 static const Target *GetTarget(const char *ProgName) { 203 // Figure out the target triple. 204 if (TripleName.empty()) 205 TripleName = sys::getDefaultTargetTriple(); 206 Triple TheTriple(Triple::normalize(TripleName)); 207 208 // Get the target specific parser. 209 std::string Error; 210 const Target *TheTarget = TargetRegistry::lookupTarget(ArchName, TheTriple, 211 Error); 212 if (!TheTarget) { 213 WithColor::error(errs(), ProgName) << Error; 214 return nullptr; 215 } 216 217 // Update the triple name and return the found target. 218 TripleName = TheTriple.getTriple(); 219 return TheTarget; 220 } 221 222 static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path, 223 sys::fs::OpenFlags Flags) { 224 std::error_code EC; 225 auto Out = std::make_unique<ToolOutputFile>(Path, EC, Flags); 226 if (EC) { 227 WithColor::error() << EC.message() << '\n'; 228 return nullptr; 229 } 230 231 return Out; 232 } 233 234 static std::string DwarfDebugFlags; 235 static void setDwarfDebugFlags(int argc, char **argv) { 236 if (!getenv("RC_DEBUG_OPTIONS")) 237 return; 238 for (int i = 0; i < argc; i++) { 239 DwarfDebugFlags += argv[i]; 240 if (i + 1 < argc) 241 DwarfDebugFlags += " "; 242 } 243 } 244 245 static std::string DwarfDebugProducer; 246 static void setDwarfDebugProducer() { 247 if(!getenv("DEBUG_PRODUCER")) 248 return; 249 DwarfDebugProducer += getenv("DEBUG_PRODUCER"); 250 } 251 252 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, 253 raw_ostream &OS) { 254 255 AsmLexer Lexer(MAI); 256 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer()); 257 258 bool Error = false; 259 while (Lexer.Lex().isNot(AsmToken::Eof)) { 260 Lexer.getTok().dump(OS); 261 OS << "\n"; 262 if (Lexer.getTok().getKind() == AsmToken::Error) 263 Error = true; 264 } 265 266 return Error; 267 } 268 269 static int fillCommandLineSymbols(MCAsmParser &Parser) { 270 for (auto &I: DefineSymbol) { 271 auto Pair = StringRef(I).split('='); 272 auto Sym = Pair.first; 273 auto Val = Pair.second; 274 275 if (Sym.empty() || Val.empty()) { 276 WithColor::error() << "defsym must be of the form: sym=value: " << I 277 << "\n"; 278 return 1; 279 } 280 int64_t Value; 281 if (Val.getAsInteger(0, Value)) { 282 WithColor::error() << "value is not an integer: " << Val << "\n"; 283 return 1; 284 } 285 Parser.getContext().setSymbolValue(Parser.getStreamer(), Sym, Value); 286 } 287 return 0; 288 } 289 290 static int AssembleInput(const char *ProgName, const Target *TheTarget, 291 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, 292 MCAsmInfo &MAI, MCSubtargetInfo &STI, 293 MCInstrInfo &MCII, MCTargetOptions const &MCOptions) { 294 std::unique_ptr<MCAsmParser> Parser( 295 createMCAsmParser(SrcMgr, Ctx, Str, MAI)); 296 std::unique_ptr<MCTargetAsmParser> TAP( 297 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions)); 298 299 if (!TAP) { 300 WithColor::error(errs(), ProgName) 301 << "this target does not support assembly parsing.\n"; 302 return 1; 303 } 304 305 int SymbolResult = fillCommandLineSymbols(*Parser); 306 if(SymbolResult) 307 return SymbolResult; 308 Parser->setShowParsedOperands(ShowInstOperands); 309 Parser->setTargetParser(*TAP); 310 Parser->getLexer().setLexMasmIntegers(LexMasmIntegers); 311 Parser->getLexer().setLexMasmHexFloats(LexMasmHexFloats); 312 Parser->getLexer().setLexMotorolaIntegers(LexMotorolaIntegers); 313 314 int Res = Parser->Run(NoInitialTextSection); 315 316 return Res; 317 } 318 319 int main(int argc, char **argv) { 320 InitLLVM X(argc, argv); 321 322 // Initialize targets and assembly printers/parsers. 323 llvm::InitializeAllTargetInfos(); 324 llvm::InitializeAllTargetMCs(); 325 llvm::InitializeAllAsmParsers(); 326 llvm::InitializeAllDisassemblers(); 327 328 // Register the target printer for --version. 329 cl::AddExtraVersionPrinter(TargetRegistry::printRegisteredTargetsForVersion); 330 331 cl::ParseCommandLineOptions(argc, argv, "llvm machine code playground\n"); 332 const MCTargetOptions MCOptions = mc::InitMCTargetOptionsFromFlags(); 333 setDwarfDebugFlags(argc, argv); 334 335 setDwarfDebugProducer(); 336 337 const char *ProgName = argv[0]; 338 const Target *TheTarget = GetTarget(ProgName); 339 if (!TheTarget) 340 return 1; 341 // Now that GetTarget() has (potentially) replaced TripleName, it's safe to 342 // construct the Triple object. 343 Triple TheTriple(TripleName); 344 345 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr = 346 MemoryBuffer::getFileOrSTDIN(InputFilename, /*IsText=*/true); 347 if (std::error_code EC = BufferPtr.getError()) { 348 WithColor::error(errs(), ProgName) 349 << InputFilename << ": " << EC.message() << '\n'; 350 return 1; 351 } 352 MemoryBuffer *Buffer = BufferPtr->get(); 353 354 SourceMgr SrcMgr; 355 356 // Tell SrcMgr about this buffer, which is what the parser will pick up. 357 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc()); 358 359 // Record the location of the include directories so that the lexer can find 360 // it later. 361 SrcMgr.setIncludeDirs(IncludeDirs); 362 363 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 364 assert(MRI && "Unable to create target register info!"); 365 366 std::unique_ptr<MCAsmInfo> MAI( 367 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 368 assert(MAI && "Unable to create target asm info!"); 369 370 MAI->setRelaxELFRelocations(RelaxELFRel); 371 372 if (CompressDebugSections != DebugCompressionType::None) { 373 if (!zlib::isAvailable()) { 374 WithColor::error(errs(), ProgName) 375 << "build tools with zlib to enable -compress-debug-sections"; 376 return 1; 377 } 378 MAI->setCompressDebugSections(CompressDebugSections); 379 } 380 MAI->setPreserveAsmComments(PreserveComments); 381 382 // Package up features to be passed to target/subtarget 383 std::string FeaturesStr; 384 if (MAttrs.size()) { 385 SubtargetFeatures Features; 386 for (unsigned i = 0; i != MAttrs.size(); ++i) 387 Features.AddFeature(MAttrs[i]); 388 FeaturesStr = Features.getString(); 389 } 390 391 std::unique_ptr<MCSubtargetInfo> STI( 392 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 393 assert(STI && "Unable to create subtarget info!"); 394 395 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 396 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 397 MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr, 398 &MCOptions); 399 std::unique_ptr<MCObjectFileInfo> MOFI( 400 TheTarget->createMCObjectFileInfo(Ctx, PIC, LargeCodeModel)); 401 Ctx.setObjectFileInfo(MOFI.get()); 402 403 if (SaveTempLabels) 404 Ctx.setAllowTemporaryLabels(false); 405 406 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly); 407 // Default to 4 for dwarf version. 408 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4; 409 if (DwarfVersion < 2 || DwarfVersion > 5) { 410 errs() << ProgName << ": Dwarf version " << DwarfVersion 411 << " is not supported." << '\n'; 412 return 1; 413 } 414 Ctx.setDwarfVersion(DwarfVersion); 415 if (MCOptions.Dwarf64) { 416 // The 64-bit DWARF format was introduced in DWARFv3. 417 if (DwarfVersion < 3) { 418 errs() << ProgName 419 << ": the 64-bit DWARF format is not supported for DWARF versions " 420 "prior to 3\n"; 421 return 1; 422 } 423 // 32-bit targets don't support DWARF64, which requires 64-bit relocations. 424 if (MAI->getCodePointerSize() < 8) { 425 errs() << ProgName 426 << ": the 64-bit DWARF format is only supported for 64-bit " 427 "targets\n"; 428 return 1; 429 } 430 // If needsDwarfSectionOffsetDirective is true, we would eventually call 431 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that 432 // is supported only for 4-byte long references. 433 if (MAI->needsDwarfSectionOffsetDirective()) { 434 errs() << ProgName << ": the 64-bit DWARF format is not supported for " 435 << TheTriple.normalize() << "\n"; 436 return 1; 437 } 438 Ctx.setDwarfFormat(dwarf::DWARF64); 439 } 440 if (!DwarfDebugFlags.empty()) 441 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags)); 442 if (!DwarfDebugProducer.empty()) 443 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer)); 444 if (!DebugCompilationDir.empty()) 445 Ctx.setCompilationDir(DebugCompilationDir); 446 else { 447 // If no compilation dir is set, try to use the current directory. 448 SmallString<128> CWD; 449 if (!sys::fs::current_path(CWD)) 450 Ctx.setCompilationDir(CWD); 451 } 452 for (const auto &Arg : DebugPrefixMap) { 453 const auto &KV = StringRef(Arg).split('='); 454 Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second)); 455 } 456 if (!MainFileName.empty()) 457 Ctx.setMainFileName(MainFileName); 458 if (GenDwarfForAssembly) 459 Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer()); 460 461 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile) 462 ? sys::fs::OF_TextWithCRLF 463 : sys::fs::OF_None; 464 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags); 465 if (!Out) 466 return 1; 467 468 std::unique_ptr<ToolOutputFile> DwoOut; 469 if (!SplitDwarfFile.empty()) { 470 if (FileType != OFT_ObjectFile) { 471 WithColor::error() << "dwo output only supported with object files\n"; 472 return 1; 473 } 474 DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None); 475 if (!DwoOut) 476 return 1; 477 } 478 479 std::unique_ptr<buffer_ostream> BOS; 480 raw_pwrite_stream *OS = &Out->os(); 481 std::unique_ptr<MCStreamer> Str; 482 483 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 484 assert(MCII && "Unable to create instruction info!"); 485 486 MCInstPrinter *IP = nullptr; 487 if (FileType == OFT_AssemblyFile) { 488 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant, 489 *MAI, *MCII, *MRI); 490 491 if (!IP) { 492 WithColor::error() 493 << "unable to create instruction printer for target triple '" 494 << TheTriple.normalize() << "' with assembly variant " 495 << OutputAsmVariant << ".\n"; 496 return 1; 497 } 498 499 // Set the display preference for hex vs. decimal immediates. 500 IP->setPrintImmHex(PrintImmHex); 501 502 // Set up the AsmStreamer. 503 std::unique_ptr<MCCodeEmitter> CE; 504 if (ShowEncoding) 505 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx)); 506 507 std::unique_ptr<MCAsmBackend> MAB( 508 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions)); 509 auto FOut = std::make_unique<formatted_raw_ostream>(*OS); 510 Str.reset( 511 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true, 512 /*useDwarfDirectory*/ true, IP, 513 std::move(CE), std::move(MAB), ShowInst)); 514 515 } else if (FileType == OFT_Null) { 516 Str.reset(TheTarget->createNullStreamer(Ctx)); 517 } else { 518 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 519 520 if (!Out->os().supportsSeeking()) { 521 BOS = std::make_unique<buffer_ostream>(Out->os()); 522 OS = BOS.get(); 523 } 524 525 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); 526 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions); 527 Str.reset(TheTarget->createMCObjectStreamer( 528 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), 529 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os()) 530 : MAB->createObjectWriter(*OS), 531 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll, 532 MCOptions.MCIncrementalLinkerCompatible, 533 /*DWARFMustBeAtTheEnd*/ false)); 534 if (NoExecStack) 535 Str->InitSections(true); 536 } 537 538 // Use Assembler information for parsing. 539 Str->setUseAssemblerInfoForParsing(true); 540 541 int Res = 1; 542 bool disassemble = false; 543 switch (Action) { 544 case AC_AsLex: 545 Res = AsLexInput(SrcMgr, *MAI, Out->os()); 546 break; 547 case AC_Assemble: 548 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, 549 *MCII, MCOptions); 550 break; 551 case AC_MDisassemble: 552 assert(IP && "Expected assembly output"); 553 IP->setUseMarkup(true); 554 disassemble = true; 555 break; 556 case AC_Disassemble: 557 disassemble = true; 558 break; 559 } 560 if (disassemble) 561 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer, 562 SrcMgr, Ctx, Out->os(), MCOptions); 563 564 // Keep output if no errors. 565 if (Res == 0) { 566 Out->keep(); 567 if (DwoOut) 568 DwoOut->keep(); 569 } 570 return Res; 571 } 572