1 //===-- llvm-ml.cpp - masm-compatible assembler -----------------*- 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 // A simple driver around MasmParser; based on llvm-mc. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "llvm/ADT/StringSwitch.h" 14 #include "llvm/MC/MCAsmBackend.h" 15 #include "llvm/MC/MCAsmInfo.h" 16 #include "llvm/MC/MCCodeEmitter.h" 17 #include "llvm/MC/MCContext.h" 18 #include "llvm/MC/MCInstPrinter.h" 19 #include "llvm/MC/MCInstrInfo.h" 20 #include "llvm/MC/MCObjectFileInfo.h" 21 #include "llvm/MC/MCObjectWriter.h" 22 #include "llvm/MC/MCParser/AsmLexer.h" 23 #include "llvm/MC/MCParser/MCTargetAsmParser.h" 24 #include "llvm/MC/MCRegisterInfo.h" 25 #include "llvm/MC/MCStreamer.h" 26 #include "llvm/MC/MCSubtargetInfo.h" 27 #include "llvm/MC/MCSymbol.h" 28 #include "llvm/MC/MCTargetOptionsCommandFlags.h" 29 #include "llvm/MC/TargetRegistry.h" 30 #include "llvm/Option/Arg.h" 31 #include "llvm/Option/ArgList.h" 32 #include "llvm/Option/Option.h" 33 #include "llvm/Support/Compression.h" 34 #include "llvm/Support/FileUtilities.h" 35 #include "llvm/Support/FormatVariadic.h" 36 #include "llvm/Support/FormattedStream.h" 37 #include "llvm/Support/LLVMDriver.h" 38 #include "llvm/Support/MemoryBuffer.h" 39 #include "llvm/Support/Path.h" 40 #include "llvm/Support/Process.h" 41 #include "llvm/Support/SourceMgr.h" 42 #include "llvm/Support/TargetSelect.h" 43 #include "llvm/Support/ToolOutputFile.h" 44 #include "llvm/Support/WithColor.h" 45 #include "llvm/TargetParser/Host.h" 46 #include <ctime> 47 #include <optional> 48 49 using namespace llvm; 50 using namespace llvm::opt; 51 52 namespace { 53 54 enum ID { 55 OPT_INVALID = 0, // This is not an option ID. 56 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__), 57 #include "Opts.inc" 58 #undef OPTION 59 }; 60 61 #define PREFIX(NAME, VALUE) \ 62 static constexpr StringLiteral NAME##_init[] = VALUE; \ 63 static constexpr ArrayRef<StringLiteral> NAME(NAME##_init, \ 64 std::size(NAME##_init) - 1); 65 #include "Opts.inc" 66 #undef PREFIX 67 68 static constexpr opt::OptTable::Info InfoTable[] = { 69 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__), 70 #include "Opts.inc" 71 #undef OPTION 72 }; 73 74 class MLOptTable : public opt::GenericOptTable { 75 public: 76 MLOptTable() : opt::GenericOptTable(InfoTable, /*IgnoreCase=*/false) {} 77 }; 78 } // namespace 79 80 static Triple GetTriple(StringRef ProgName, opt::InputArgList &Args) { 81 // Figure out the target triple. 82 StringRef DefaultBitness = "32"; 83 SmallString<255> Program = ProgName; 84 sys::path::replace_extension(Program, ""); 85 if (Program.ends_with("ml64")) 86 DefaultBitness = "64"; 87 88 StringRef TripleName = 89 StringSwitch<StringRef>(Args.getLastArgValue(OPT_bitness, DefaultBitness)) 90 .Case("32", "i386-pc-windows") 91 .Case("64", "x86_64-pc-windows") 92 .Default(""); 93 return Triple(Triple::normalize(TripleName)); 94 } 95 96 static std::unique_ptr<ToolOutputFile> GetOutputStream(StringRef Path) { 97 std::error_code EC; 98 auto Out = std::make_unique<ToolOutputFile>(Path, EC, sys::fs::OF_None); 99 if (EC) { 100 WithColor::error() << EC.message() << '\n'; 101 return nullptr; 102 } 103 104 return Out; 105 } 106 107 static int AsLexInput(SourceMgr &SrcMgr, MCAsmInfo &MAI, raw_ostream &OS) { 108 AsmLexer Lexer(MAI); 109 Lexer.setBuffer(SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer()); 110 Lexer.setLexMasmIntegers(true); 111 Lexer.useMasmDefaultRadix(true); 112 Lexer.setLexMasmHexFloats(true); 113 Lexer.setLexMasmStrings(true); 114 115 bool Error = false; 116 while (Lexer.Lex().isNot(AsmToken::Eof)) { 117 Lexer.getTok().dump(OS); 118 OS << "\n"; 119 if (Lexer.getTok().getKind() == AsmToken::Error) 120 Error = true; 121 } 122 123 return Error; 124 } 125 126 static int AssembleInput(StringRef ProgName, const Target *TheTarget, 127 SourceMgr &SrcMgr, MCContext &Ctx, MCStreamer &Str, 128 MCAsmInfo &MAI, MCSubtargetInfo &STI, 129 MCInstrInfo &MCII, MCTargetOptions &MCOptions, 130 const opt::ArgList &InputArgs) { 131 struct tm TM; 132 time_t Timestamp; 133 if (InputArgs.hasArg(OPT_timestamp)) { 134 StringRef TimestampStr = InputArgs.getLastArgValue(OPT_timestamp); 135 int64_t IntTimestamp; 136 if (TimestampStr.getAsInteger(10, IntTimestamp)) { 137 WithColor::error(errs(), ProgName) 138 << "invalid timestamp '" << TimestampStr 139 << "'; must be expressed in seconds since the UNIX epoch.\n"; 140 return 1; 141 } 142 Timestamp = IntTimestamp; 143 } else { 144 Timestamp = time(nullptr); 145 } 146 if (InputArgs.hasArg(OPT_utc)) { 147 // Not thread-safe. 148 TM = *gmtime(&Timestamp); 149 } else { 150 // Not thread-safe. 151 TM = *localtime(&Timestamp); 152 } 153 154 std::unique_ptr<MCAsmParser> Parser( 155 createMCMasmParser(SrcMgr, Ctx, Str, MAI, TM, 0)); 156 std::unique_ptr<MCTargetAsmParser> TAP( 157 TheTarget->createMCAsmParser(STI, *Parser, MCII, MCOptions)); 158 159 if (!TAP) { 160 WithColor::error(errs(), ProgName) 161 << "this target does not support assembly parsing.\n"; 162 return 1; 163 } 164 165 Parser->setShowParsedOperands(InputArgs.hasArg(OPT_show_inst_operands)); 166 Parser->setTargetParser(*TAP); 167 Parser->getLexer().setLexMasmIntegers(true); 168 Parser->getLexer().useMasmDefaultRadix(true); 169 Parser->getLexer().setLexMasmHexFloats(true); 170 Parser->getLexer().setLexMasmStrings(true); 171 172 auto Defines = InputArgs.getAllArgValues(OPT_define); 173 for (StringRef Define : Defines) { 174 const auto NameValue = Define.split('='); 175 StringRef Name = NameValue.first, Value = NameValue.second; 176 if (Parser->defineMacro(Name, Value)) { 177 WithColor::error(errs(), ProgName) 178 << "can't define macro '" << Name << "' = '" << Value << "'\n"; 179 return 1; 180 } 181 } 182 183 int Res = Parser->Run(/*NoInitialTextSection=*/true); 184 185 return Res; 186 } 187 188 int llvm_ml_main(int Argc, char **Argv, const llvm::ToolContext &) { 189 StringRef ProgName = sys::path::filename(Argv[0]); 190 191 // Initialize targets and assembly printers/parsers. 192 llvm::InitializeAllTargetInfos(); 193 llvm::InitializeAllTargetMCs(); 194 llvm::InitializeAllAsmParsers(); 195 llvm::InitializeAllDisassemblers(); 196 197 MLOptTable T; 198 unsigned MissingArgIndex, MissingArgCount; 199 ArrayRef<const char *> ArgsArr = ArrayRef(Argv + 1, Argc - 1); 200 opt::InputArgList InputArgs = 201 T.ParseArgs(ArgsArr, MissingArgIndex, MissingArgCount); 202 203 std::string InputFilename; 204 for (auto *Arg : InputArgs.filtered(OPT_INPUT)) { 205 std::string ArgString = Arg->getAsString(InputArgs); 206 bool IsFile = false; 207 std::error_code IsFileEC = 208 llvm::sys::fs::is_regular_file(ArgString, IsFile); 209 if (ArgString == "-" || IsFile) { 210 if (!InputFilename.empty()) { 211 WithColor::warning(errs(), ProgName) 212 << "does not support multiple assembly files in one command; " 213 << "ignoring '" << InputFilename << "'\n"; 214 } 215 InputFilename = ArgString; 216 } else { 217 std::string Diag; 218 raw_string_ostream OS(Diag); 219 OS << ArgString << ": " << IsFileEC.message(); 220 221 std::string Nearest; 222 if (T.findNearest(ArgString, Nearest) < 2) 223 OS << ", did you mean '" << Nearest << "'?"; 224 225 WithColor::error(errs(), ProgName) << OS.str() << '\n'; 226 exit(1); 227 } 228 } 229 for (auto *Arg : InputArgs.filtered(OPT_assembly_file)) { 230 if (!InputFilename.empty()) { 231 WithColor::warning(errs(), ProgName) 232 << "does not support multiple assembly files in one command; " 233 << "ignoring '" << InputFilename << "'\n"; 234 } 235 InputFilename = Arg->getValue(); 236 } 237 238 for (auto *Arg : InputArgs.filtered(OPT_unsupported_Group)) { 239 WithColor::warning(errs(), ProgName) 240 << "ignoring unsupported '" << Arg->getOption().getName() 241 << "' option\n"; 242 } 243 244 if (InputArgs.hasArg(OPT_debug)) { 245 DebugFlag = true; 246 } 247 for (auto *Arg : InputArgs.filtered(OPT_debug_only)) { 248 setCurrentDebugTypes(Arg->getValues().data(), Arg->getNumValues()); 249 } 250 251 if (InputArgs.hasArg(OPT_help)) { 252 std::string Usage = llvm::formatv("{0} [ /options ] file", ProgName).str(); 253 T.printHelp(outs(), Usage.c_str(), "LLVM MASM Assembler", 254 /*ShowHidden=*/false); 255 return 0; 256 } else if (InputFilename.empty()) { 257 outs() << "USAGE: " << ProgName << " [ /options ] file\n" 258 << "Run \"" << ProgName << " /?\" or \"" << ProgName 259 << " /help\" for more info.\n"; 260 return 0; 261 } 262 263 MCTargetOptions MCOptions; 264 MCOptions.AssemblyLanguage = "masm"; 265 MCOptions.MCFatalWarnings = InputArgs.hasArg(OPT_fatal_warnings); 266 MCOptions.MCSaveTempLabels = InputArgs.hasArg(OPT_save_temp_labels); 267 268 Triple TheTriple = GetTriple(ProgName, InputArgs); 269 std::string Error; 270 const Target *TheTarget = TargetRegistry::lookupTarget("", TheTriple, Error); 271 if (!TheTarget) { 272 WithColor::error(errs(), ProgName) << Error; 273 return 1; 274 } 275 const std::string &TripleName = TheTriple.getTriple(); 276 277 bool SafeSEH = InputArgs.hasArg(OPT_safeseh); 278 if (SafeSEH && !(TheTriple.isArch32Bit() && TheTriple.isX86())) { 279 WithColor::warning() 280 << "/safeseh applies only to 32-bit X86 platforms; ignoring.\n"; 281 SafeSEH = false; 282 } 283 284 ErrorOr<std::unique_ptr<MemoryBuffer>> BufferPtr = 285 MemoryBuffer::getFileOrSTDIN(InputFilename); 286 if (std::error_code EC = BufferPtr.getError()) { 287 WithColor::error(errs(), ProgName) 288 << InputFilename << ": " << EC.message() << '\n'; 289 return 1; 290 } 291 292 SourceMgr SrcMgr; 293 294 // Tell SrcMgr about this buffer, which is what the parser will pick up. 295 SrcMgr.AddNewSourceBuffer(std::move(*BufferPtr), SMLoc()); 296 297 // Record the location of the include directories so that the lexer can find 298 // included files later. 299 std::vector<std::string> IncludeDirs = 300 InputArgs.getAllArgValues(OPT_include_path); 301 if (!InputArgs.hasArg(OPT_ignore_include_envvar)) { 302 if (std::optional<std::string> IncludeEnvVar = 303 llvm::sys::Process::GetEnv("INCLUDE")) { 304 SmallVector<StringRef, 8> Dirs; 305 StringRef(*IncludeEnvVar) 306 .split(Dirs, ";", /*MaxSplit=*/-1, /*KeepEmpty=*/false); 307 IncludeDirs.reserve(IncludeDirs.size() + Dirs.size()); 308 for (StringRef Dir : Dirs) 309 IncludeDirs.push_back(Dir.str()); 310 } 311 } 312 SrcMgr.setIncludeDirs(IncludeDirs); 313 314 std::unique_ptr<MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TripleName)); 315 assert(MRI && "Unable to create target register info!"); 316 317 std::unique_ptr<MCAsmInfo> MAI( 318 TheTarget->createMCAsmInfo(*MRI, TripleName, MCOptions)); 319 assert(MAI && "Unable to create target asm info!"); 320 321 MAI->setPreserveAsmComments(InputArgs.hasArg(OPT_preserve_comments)); 322 323 std::unique_ptr<MCSubtargetInfo> STI(TheTarget->createMCSubtargetInfo( 324 TripleName, /*CPU=*/"", /*Features=*/"")); 325 assert(STI && "Unable to create subtarget info!"); 326 327 // FIXME: This is not pretty. MCContext has a ptr to MCObjectFileInfo and 328 // MCObjectFileInfo needs a MCContext reference in order to initialize itself. 329 MCContext Ctx(TheTriple, MAI.get(), MRI.get(), STI.get(), &SrcMgr); 330 std::unique_ptr<MCObjectFileInfo> MOFI(TheTarget->createMCObjectFileInfo( 331 Ctx, /*PIC=*/false, /*LargeCodeModel=*/true)); 332 Ctx.setObjectFileInfo(MOFI.get()); 333 334 // Set compilation information. 335 SmallString<128> CWD; 336 if (!sys::fs::current_path(CWD)) 337 Ctx.setCompilationDir(CWD); 338 Ctx.setMainFileName(InputFilename); 339 340 StringRef FileType = InputArgs.getLastArgValue(OPT_filetype, "obj"); 341 SmallString<255> DefaultOutputFilename; 342 if (InputArgs.hasArg(OPT_as_lex)) { 343 DefaultOutputFilename = "-"; 344 } else { 345 DefaultOutputFilename = InputFilename; 346 sys::path::replace_extension(DefaultOutputFilename, FileType); 347 } 348 const StringRef OutputFilename = 349 InputArgs.getLastArgValue(OPT_output_file, DefaultOutputFilename); 350 std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename); 351 if (!Out) 352 return 1; 353 354 std::unique_ptr<buffer_ostream> BOS; 355 raw_pwrite_stream *OS = &Out->os(); 356 std::unique_ptr<MCStreamer> Str; 357 358 std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo()); 359 assert(MCII && "Unable to create instruction info!"); 360 361 MCInstPrinter *IP = nullptr; 362 if (FileType == "s") { 363 const bool OutputATTAsm = InputArgs.hasArg(OPT_output_att_asm); 364 const unsigned OutputAsmVariant = OutputATTAsm ? 0U // ATT dialect 365 : 1U; // Intel dialect 366 IP = TheTarget->createMCInstPrinter(TheTriple, OutputAsmVariant, *MAI, 367 *MCII, *MRI); 368 369 if (!IP) { 370 WithColor::error() 371 << "unable to create instruction printer for target triple '" 372 << TheTriple.normalize() << "' with " 373 << (OutputATTAsm ? "ATT" : "Intel") << " assembly variant.\n"; 374 return 1; 375 } 376 377 // Set the display preference for hex vs. decimal immediates. 378 IP->setPrintImmHex(InputArgs.hasArg(OPT_print_imm_hex)); 379 380 // Set up the AsmStreamer. 381 std::unique_ptr<MCCodeEmitter> CE; 382 if (InputArgs.hasArg(OPT_show_encoding)) 383 CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx)); 384 385 std::unique_ptr<MCAsmBackend> MAB( 386 TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions)); 387 auto FOut = std::make_unique<formatted_raw_ostream>(*OS); 388 Str.reset(TheTarget->createAsmStreamer( 389 Ctx, std::move(FOut), /*asmverbose*/ true, 390 /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB), 391 InputArgs.hasArg(OPT_show_inst))); 392 393 } else if (FileType == "null") { 394 Str.reset(TheTarget->createNullStreamer(Ctx)); 395 } else if (FileType == "obj") { 396 if (!Out->os().supportsSeeking()) { 397 BOS = std::make_unique<buffer_ostream>(Out->os()); 398 OS = BOS.get(); 399 } 400 401 MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx); 402 MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions); 403 Str.reset(TheTarget->createMCObjectStreamer( 404 TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB), 405 MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE), 406 *STI)); 407 } else { 408 llvm_unreachable("Invalid file type!"); 409 } 410 411 if (TheTriple.isOSBinFormatCOFF()) { 412 // Emit an absolute @feat.00 symbol. This is a features bitfield read by 413 // link.exe. 414 int64_t Feat00Flags = 0x2; 415 if (SafeSEH) { 416 // According to the PE-COFF spec, the LSB of this value marks the object 417 // for "registered SEH". This means that all SEH handler entry points 418 // must be registered in .sxdata. Use of any unregistered handlers will 419 // cause the process to terminate immediately. 420 Feat00Flags |= 0x1; 421 } 422 MCSymbol *Feat00Sym = Ctx.getOrCreateSymbol("@feat.00"); 423 Feat00Sym->setRedefinable(true); 424 Str->emitSymbolAttribute(Feat00Sym, MCSA_Global); 425 Str->emitAssignment(Feat00Sym, MCConstantExpr::create(Feat00Flags, Ctx)); 426 } 427 428 int Res = 1; 429 if (InputArgs.hasArg(OPT_as_lex)) { 430 // -as-lex; Lex only, and output a stream of tokens 431 Res = AsLexInput(SrcMgr, *MAI, Out->os()); 432 } else { 433 Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI, 434 *MCII, MCOptions, InputArgs); 435 } 436 437 // Keep output if no errors. 438 if (Res == 0) 439 Out->keep(); 440 return Res; 441 } 442