xref: /llvm-project/llvm/tools/llvm-ml/llvm-ml.cpp (revision 99f8751c1509e66ca8401886c756751ac94bc222)
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/InitLLVM.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.endswith("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 main(int Argc, char **Argv) {
189   InitLLVM X(Argc, Argv);
190   StringRef ProgName = sys::path::filename(Argv[0]);
191 
192   // Initialize targets and assembly printers/parsers.
193   llvm::InitializeAllTargetInfos();
194   llvm::InitializeAllTargetMCs();
195   llvm::InitializeAllAsmParsers();
196   llvm::InitializeAllDisassemblers();
197 
198   MLOptTable T;
199   unsigned MissingArgIndex, MissingArgCount;
200   ArrayRef<const char *> ArgsArr = ArrayRef(Argv + 1, Argc - 1);
201   opt::InputArgList InputArgs =
202       T.ParseArgs(ArgsArr, MissingArgIndex, MissingArgCount);
203 
204   std::string InputFilename;
205   for (auto *Arg : InputArgs.filtered(OPT_INPUT)) {
206     std::string ArgString = Arg->getAsString(InputArgs);
207     bool IsFile = false;
208     std::error_code IsFileEC =
209         llvm::sys::fs::is_regular_file(ArgString, IsFile);
210     if (ArgString == "-" || IsFile) {
211       if (!InputFilename.empty()) {
212         WithColor::warning(errs(), ProgName)
213             << "does not support multiple assembly files in one command; "
214             << "ignoring '" << InputFilename << "'\n";
215       }
216       InputFilename = ArgString;
217     } else {
218       std::string Diag;
219       raw_string_ostream OS(Diag);
220       OS << ArgString << ": " << IsFileEC.message();
221 
222       std::string Nearest;
223       if (T.findNearest(ArgString, Nearest) < 2)
224         OS << ", did you mean '" << Nearest << "'?";
225 
226       WithColor::error(errs(), ProgName) << OS.str() << '\n';
227       exit(1);
228     }
229   }
230   for (auto *Arg : InputArgs.filtered(OPT_assembly_file)) {
231     if (!InputFilename.empty()) {
232       WithColor::warning(errs(), ProgName)
233           << "does not support multiple assembly files in one command; "
234           << "ignoring '" << InputFilename << "'\n";
235     }
236     InputFilename = Arg->getValue();
237   }
238 
239   for (auto *Arg : InputArgs.filtered(OPT_unsupported_Group)) {
240     WithColor::warning(errs(), ProgName)
241         << "ignoring unsupported '" << Arg->getOption().getName()
242         << "' option\n";
243   }
244 
245   if (InputArgs.hasArg(OPT_debug)) {
246     DebugFlag = true;
247   }
248   for (auto *Arg : InputArgs.filtered(OPT_debug_only)) {
249     setCurrentDebugTypes(Arg->getValues().data(), Arg->getNumValues());
250   }
251 
252   if (InputArgs.hasArg(OPT_help)) {
253     std::string Usage = llvm::formatv("{0} [ /options ] file", ProgName).str();
254     T.printHelp(outs(), Usage.c_str(), "LLVM MASM Assembler",
255                 /*ShowHidden=*/false);
256     return 0;
257   } else if (InputFilename.empty()) {
258     outs() << "USAGE: " << ProgName << " [ /options ] file\n"
259            << "Run \"" << ProgName << " /?\" or \"" << ProgName
260            << " /help\" for more info.\n";
261     return 0;
262   }
263 
264   MCTargetOptions MCOptions;
265   MCOptions.AssemblyLanguage = "masm";
266   MCOptions.MCFatalWarnings = InputArgs.hasArg(OPT_fatal_warnings);
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   if (InputArgs.hasArg(OPT_save_temp_labels))
335     Ctx.setAllowTemporaryLabels(false);
336 
337   // Set compilation information.
338   SmallString<128> CWD;
339   if (!sys::fs::current_path(CWD))
340     Ctx.setCompilationDir(CWD);
341   Ctx.setMainFileName(InputFilename);
342 
343   StringRef FileType = InputArgs.getLastArgValue(OPT_filetype, "obj");
344   SmallString<255> DefaultOutputFilename;
345   if (InputArgs.hasArg(OPT_as_lex)) {
346     DefaultOutputFilename = "-";
347   } else {
348     DefaultOutputFilename = InputFilename;
349     sys::path::replace_extension(DefaultOutputFilename, FileType);
350   }
351   const StringRef OutputFilename =
352       InputArgs.getLastArgValue(OPT_output_file, DefaultOutputFilename);
353   std::unique_ptr<ToolOutputFile> Out = GetOutputStream(OutputFilename);
354   if (!Out)
355     return 1;
356 
357   std::unique_ptr<buffer_ostream> BOS;
358   raw_pwrite_stream *OS = &Out->os();
359   std::unique_ptr<MCStreamer> Str;
360 
361   std::unique_ptr<MCInstrInfo> MCII(TheTarget->createMCInstrInfo());
362   assert(MCII && "Unable to create instruction info!");
363 
364   MCInstPrinter *IP = nullptr;
365   if (FileType == "s") {
366     const bool OutputATTAsm = InputArgs.hasArg(OPT_output_att_asm);
367     const unsigned OutputAsmVariant = OutputATTAsm ? 0U   // ATT dialect
368                                                    : 1U;  // Intel dialect
369     IP = TheTarget->createMCInstPrinter(TheTriple, OutputAsmVariant, *MAI,
370                                         *MCII, *MRI);
371 
372     if (!IP) {
373       WithColor::error()
374           << "unable to create instruction printer for target triple '"
375           << TheTriple.normalize() << "' with "
376           << (OutputATTAsm ? "ATT" : "Intel") << " assembly variant.\n";
377       return 1;
378     }
379 
380     // Set the display preference for hex vs. decimal immediates.
381     IP->setPrintImmHex(InputArgs.hasArg(OPT_print_imm_hex));
382 
383     // Set up the AsmStreamer.
384     std::unique_ptr<MCCodeEmitter> CE;
385     if (InputArgs.hasArg(OPT_show_encoding))
386       CE.reset(TheTarget->createMCCodeEmitter(*MCII, Ctx));
387 
388     std::unique_ptr<MCAsmBackend> MAB(
389         TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions));
390     auto FOut = std::make_unique<formatted_raw_ostream>(*OS);
391     Str.reset(TheTarget->createAsmStreamer(
392         Ctx, std::move(FOut), /*asmverbose*/ true,
393         /*useDwarfDirectory*/ true, IP, std::move(CE), std::move(MAB),
394         InputArgs.hasArg(OPT_show_inst)));
395 
396   } else if (FileType == "null") {
397     Str.reset(TheTarget->createNullStreamer(Ctx));
398   } else if (FileType == "obj") {
399     if (!Out->os().supportsSeeking()) {
400       BOS = std::make_unique<buffer_ostream>(Out->os());
401       OS = BOS.get();
402     }
403 
404     MCCodeEmitter *CE = TheTarget->createMCCodeEmitter(*MCII, Ctx);
405     MCAsmBackend *MAB = TheTarget->createMCAsmBackend(*STI, *MRI, MCOptions);
406     Str.reset(TheTarget->createMCObjectStreamer(
407         TheTriple, Ctx, std::unique_ptr<MCAsmBackend>(MAB),
408         MAB->createObjectWriter(*OS), std::unique_ptr<MCCodeEmitter>(CE), *STI,
409         MCOptions.MCRelaxAll, MCOptions.MCIncrementalLinkerCompatible,
410         /*DWARFMustBeAtTheEnd*/ false));
411   } else {
412     llvm_unreachable("Invalid file type!");
413   }
414 
415   if (TheTriple.isOSBinFormatCOFF()) {
416     // Emit an absolute @feat.00 symbol. This is a features bitfield read by
417     // link.exe.
418     int64_t Feat00Flags = 0x2;
419     if (SafeSEH) {
420       // According to the PE-COFF spec, the LSB of this value marks the object
421       // for "registered SEH".  This means that all SEH handler entry points
422       // must be registered in .sxdata.  Use of any unregistered handlers will
423       // cause the process to terminate immediately.
424       Feat00Flags |= 0x1;
425     }
426     MCSymbol *Feat00Sym = Ctx.getOrCreateSymbol("@feat.00");
427     Feat00Sym->setRedefinable(true);
428     Str->emitSymbolAttribute(Feat00Sym, MCSA_Global);
429     Str->emitAssignment(Feat00Sym, MCConstantExpr::create(Feat00Flags, Ctx));
430   }
431 
432   // Use Assembler information for parsing.
433   Str->setUseAssemblerInfoForParsing(true);
434 
435   int Res = 1;
436   if (InputArgs.hasArg(OPT_as_lex)) {
437     // -as-lex; Lex only, and output a stream of tokens
438     Res = AsLexInput(SrcMgr, *MAI, Out->os());
439   } else {
440     Res = AssembleInput(ProgName, TheTarget, SrcMgr, Ctx, *Str, *MAI, *STI,
441                         *MCII, MCOptions, InputArgs);
442   }
443 
444   // Keep output if no errors.
445   if (Res == 0)
446     Out->keep();
447   return Res;
448 }
449