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 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 383 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 384 MCObjectFileInfo MOFI; 385 MCContext Ctx(MAI.get(), MRI.get(), &MOFI, &SrcMgr, &MCOptions); 386 MOFI.InitMCObjectFileInfo(TheTriple, PIC, Ctx, LargeCodeModel); 387 388 if (SaveTempLabels) 389 Ctx.setAllowTemporaryLabels(false); 390 391 Ctx.setGenDwarfForAssembly(GenDwarfForAssembly); 392 // Default to 4 for dwarf version. 393 unsigned DwarfVersion = MCOptions.DwarfVersion ? MCOptions.DwarfVersion : 4; 394 if (DwarfVersion < 2 || DwarfVersion > 5) { 395 errs() << ProgName << ": Dwarf version " << DwarfVersion 396 << " is not supported." << '\n'; 397 return 1; 398 } 399 Ctx.setDwarfVersion(DwarfVersion); 400 if (MCOptions.Dwarf64) { 401 // The 64-bit DWARF format was introduced in DWARFv3. 402 if (DwarfVersion < 3) { 403 errs() << ProgName 404 << ": the 64-bit DWARF format is not supported for DWARF versions " 405 "prior to 3\n"; 406 return 1; 407 } 408 // 32-bit targets don't support DWARF64, which requires 64-bit relocations. 409 if (MAI->getCodePointerSize() < 8) { 410 errs() << ProgName 411 << ": the 64-bit DWARF format is only supported for 64-bit " 412 "targets\n"; 413 return 1; 414 } 415 // If needsDwarfSectionOffsetDirective is true, we would eventually call 416 // MCStreamer::emitSymbolValue() with IsSectionRelative = true, but that 417 // is supported only for 4-byte long references. 418 if (MAI->needsDwarfSectionOffsetDirective()) { 419 errs() << ProgName << ": the 64-bit DWARF format is not supported for " 420 << TheTriple.normalize() << "\n"; 421 return 1; 422 } 423 Ctx.setDwarfFormat(dwarf::DWARF64); 424 } 425 if (!DwarfDebugFlags.empty()) 426 Ctx.setDwarfDebugFlags(StringRef(DwarfDebugFlags)); 427 if (!DwarfDebugProducer.empty()) 428 Ctx.setDwarfDebugProducer(StringRef(DwarfDebugProducer)); 429 if (!DebugCompilationDir.empty()) 430 Ctx.setCompilationDir(DebugCompilationDir); 431 else { 432 // If no compilation dir is set, try to use the current directory. 433 SmallString<128> CWD; 434 if (!sys::fs::current_path(CWD)) 435 Ctx.setCompilationDir(CWD); 436 } 437 for (const auto &Arg : DebugPrefixMap) { 438 const auto &KV = StringRef(Arg).split('='); 439 Ctx.addDebugPrefixMapEntry(std::string(KV.first), std::string(KV.second)); 440 } 441 if (!MainFileName.empty()) 442 Ctx.setMainFileName(MainFileName); 443 if (GenDwarfForAssembly) 444 Ctx.setGenDwarfRootFile(InputFilename, Buffer->getBuffer()); 445 446 // Package up features to be passed to target/subtarget 447 std::string FeaturesStr; 448 if (MAttrs.size()) { 449 SubtargetFeatures Features; 450 for (unsigned i = 0; i != MAttrs.size(); ++i) 451 Features.AddFeature(MAttrs[i]); 452 FeaturesStr = Features.getString(); 453 } 454 455 sys::fs::OpenFlags Flags = (FileType == OFT_AssemblyFile) 456 ? sys::fs::OF_TextWithCRLF 457 : sys::fs::OF_None; 458 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename, Flags); 459 if (!Out) 460 return 1; 461 462 std::unique_ptr<ToolOutputFile> DwoOut; 463 if (!SplitDwarfFile.empty()) { 464 if (FileType != OFT_ObjectFile) { 465 WithColor::error() << "dwo output only supported with object files\n"; 466 return 1; 467 } 468 DwoOut = GetOutputStream(SplitDwarfFile, sys::fs::OF_None); 469 if (!DwoOut) 470 return 1; 471 } 472 473 std::unique_ptr<buffer_ostream> BOS; 474 raw_pwrite_stream *OS = &Out->os(); 475 std::unique_ptr<MCStreamer> Str; 476 477 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 478 assert(MCII && "Unable to create instruction info!"); 479 480 std::unique_ptr<MCSubtargetInfo> STI( 481 TheTarget->createMCSubtargetInfo(TripleName, MCPU, FeaturesStr)); 482 assert(STI && "Unable to create subtarget info!"); 483 484 MCInstPrinter *IP = nullptr; 485 if (FileType == OFT_AssemblyFile) { 486 IP = TheTarget->createMCInstPrinter(Triple(TripleName), OutputAsmVariant, 487 *MAI, *MCII, *MRI); 488 489 if (!IP) { 490 WithColor::error() 491 << "unable to create instruction printer for target triple '" 492 << TheTriple.normalize() << "' with assembly variant " 493 << OutputAsmVariant << ".\n"; 494 return 1; 495 } 496 497 // Set the display preference for hex vs. decimal immediates. 498 IP->setPrintImmHex(PrintImmHex); 499 500 // Set up the AsmStreamer. 501 std::unique_ptr<MCCodeEmitter> CE; 502 if (ShowEncoding) 503 CE.reset(TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx)); 504 505 std::unique_ptr<MCAsmBackend> MAB( 506 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions)); 507 auto FOut = std::make_unique<formatted_raw_ostream>(*OS); 508 Str.reset( 509 TheTarget->createAsmStreamer(Ctx, std::move(FOut), /*asmverbose*/ true, 510 /*useDwarfDirectory*/ true, IP, 511 std::move(CE), std::move(MAB), ShowInst)); 512 513 } else if (FileType == OFT_Null) { 514 Str.reset(TheTarget->createNullStreamer(Ctx)); 515 } else { 516 assert(FileType == OFT_ObjectFile && "Invalid file type!"); 517 518 if (!Out->os().supportsSeeking()) { 519 BOS = std::make_unique<buffer_ostream>(Out->os()); 520 OS = BOS.get(); 521 } 522 523 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, *MRI, Ctx); 524 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions); 525 Str.reset(TheTarget->createMCObjectStreamer( 526 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), 527 DwoOut ? MAB->createDwoObjectWriter(*OS, DwoOut->os()) 528 : MAB->createObjectWriter(*OS), 529 std::unique_ptr<MCCodeEmitter>(CE), *STI, MCOptions.MCRelaxAll, 530 MCOptions.MCIncrementalLinkerCompatible, 531 /*DWARFMustBeAtTheEnd*/ false)); 532 if (NoExecStack) 533 Str->InitSections(true); 534 } 535 536 // Use Assembler information for parsing. 537 Str->setUseAssemblerInfoForParsing(true); 538 539 int Res = 1; 540 bool disassemble = false; 541 switch (Action) { 542 case AC_AsLex: 543 Res = AsLexInput(SrcMgr, *MAI, Out->os()); 544 break; 545 case AC_Assemble: 546 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, 547 *MCII, MCOptions); 548 break; 549 case AC_MDisassemble: 550 assert(IP && "Expected assembly output"); 551 IP->setUseMarkup(true); 552 disassemble = true; 553 break; 554 case AC_Disassemble: 555 disassemble = true; 556 break; 557 } 558 if (disassemble) 559 Res = Disassembler::disassemble(*TheTarget, TripleName, *STI, *Str, *Buffer, 560 SrcMgr, Ctx, Out->os(), MCOptions); 561 562 // Keep output if no errors. 563 if (Res == 0) { 564 Out->keep(); 565 if (DwoOut) 566 DwoOut->keep(); 567 } 568 return Res; 569 } 570