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