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