[lld][WebAssembly] Add `--table-base` setting
[llvm-project.git] / lld / MinGW / Driver.cpp
blob26bd7b3829f23c4d03ca2d3d7184c3cf39adda90
1 //===- MinGW/Driver.cpp ---------------------------------------------------===//
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 // MinGW is a GNU development environment for Windows. It consists of GNU
10 // tools such as GCC and GNU ld. Unlike Cygwin, there's no POSIX-compatible
11 // layer, as it aims to be a native development toolchain.
13 // lld/MinGW is a drop-in replacement for GNU ld/MinGW.
15 // Being a native development tool, a MinGW linker is not very different from
16 // Microsoft link.exe, so a MinGW linker can be implemented as a thin wrapper
17 // for lld/COFF. This driver takes Unix-ish command line options, translates
18 // them to Windows-ish ones, and then passes them to lld/COFF.
20 // When this driver calls the lld/COFF driver, it passes a hidden option
21 // "-lldmingw" along with other user-supplied options, to run the lld/COFF
22 // linker in "MinGW mode".
24 // There are subtle differences between MS link.exe and GNU ld/MinGW, and GNU
25 // ld/MinGW implements a few GNU-specific features. Such features are directly
26 // implemented in lld/COFF and enabled only when the linker is running in MinGW
27 // mode.
29 //===----------------------------------------------------------------------===//
31 #include "lld/Common/Driver.h"
32 #include "lld/Common/CommonLinkerContext.h"
33 #include "lld/Common/ErrorHandler.h"
34 #include "lld/Common/Memory.h"
35 #include "lld/Common/Version.h"
36 #include "llvm/ADT/ArrayRef.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/Option/Arg.h"
40 #include "llvm/Option/ArgList.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/TargetParser/Host.h"
46 #include "llvm/TargetParser/Triple.h"
47 #include <optional>
49 #if !defined(_MSC_VER) && !defined(__MINGW32__)
50 #include <unistd.h>
51 #endif
53 using namespace lld;
54 using namespace llvm::opt;
55 using namespace llvm;
57 // Create OptTable
58 enum {
59 OPT_INVALID = 0,
60 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
61 #include "Options.inc"
62 #undef OPTION
65 // Create prefix string literals used in Options.td
66 #define PREFIX(NAME, VALUE) \
67 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
68 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
69 NAME##_init, std::size(NAME##_init) - 1);
70 #include "Options.inc"
71 #undef PREFIX
73 // Create table mapping all options defined in Options.td
74 static constexpr opt::OptTable::Info infoTable[] = {
75 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
76 VISIBILITY, PARAM, HELPTEXT, METAVAR, VALUES) \
77 {PREFIX, NAME, HELPTEXT, \
78 METAVAR, OPT_##ID, opt::Option::KIND##Class, \
79 PARAM, FLAGS, VISIBILITY, \
80 OPT_##GROUP, OPT_##ALIAS, ALIASARGS, \
81 VALUES},
82 #include "Options.inc"
83 #undef OPTION
86 namespace {
87 class MinGWOptTable : public opt::GenericOptTable {
88 public:
89 MinGWOptTable() : opt::GenericOptTable(infoTable, false) {}
90 opt::InputArgList parse(ArrayRef<const char *> argv);
92 } // namespace
94 static void printHelp(const char *argv0) {
95 MinGWOptTable().printHelp(
96 lld::outs(), (std::string(argv0) + " [options] file...").c_str(), "lld",
97 false /*ShowHidden*/, true /*ShowAllAliases*/);
98 lld::outs() << "\n";
101 static cl::TokenizerCallback getQuotingStyle() {
102 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
103 return cl::TokenizeWindowsCommandLine;
104 return cl::TokenizeGNUCommandLine;
107 opt::InputArgList MinGWOptTable::parse(ArrayRef<const char *> argv) {
108 unsigned missingIndex;
109 unsigned missingCount;
111 SmallVector<const char *, 256> vec(argv.data(), argv.data() + argv.size());
112 cl::ExpandResponseFiles(saver(), getQuotingStyle(), vec);
113 opt::InputArgList args = this->ParseArgs(vec, missingIndex, missingCount);
115 if (missingCount)
116 error(StringRef(args.getArgString(missingIndex)) + ": missing argument");
117 for (auto *arg : args.filtered(OPT_UNKNOWN))
118 error("unknown argument: " + arg->getAsString(args));
119 return args;
122 // Find a file by concatenating given paths.
123 static std::optional<std::string> findFile(StringRef path1,
124 const Twine &path2) {
125 SmallString<128> s;
126 sys::path::append(s, path1, path2);
127 if (sys::fs::exists(s))
128 return std::string(s);
129 return std::nullopt;
132 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
133 static std::string
134 searchLibrary(StringRef name, ArrayRef<StringRef> searchPaths, bool bStatic) {
135 if (name.starts_with(":")) {
136 for (StringRef dir : searchPaths)
137 if (std::optional<std::string> s = findFile(dir, name.substr(1)))
138 return *s;
139 error("unable to find library -l" + name);
140 return "";
143 for (StringRef dir : searchPaths) {
144 if (!bStatic) {
145 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll.a"))
146 return *s;
147 if (std::optional<std::string> s = findFile(dir, name + ".dll.a"))
148 return *s;
150 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))
151 return *s;
152 if (std::optional<std::string> s = findFile(dir, name + ".lib"))
153 return *s;
154 if (!bStatic) {
155 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll"))
156 return *s;
157 if (std::optional<std::string> s = findFile(dir, name + ".dll"))
158 return *s;
161 error("unable to find library -l" + name);
162 return "";
165 namespace lld {
166 namespace coff {
167 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
168 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
171 namespace mingw {
172 // Convert Unix-ish command line arguments to Windows-ish ones and
173 // then call coff::link.
174 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
175 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
176 auto *ctx = new CommonLinkerContext;
177 ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
179 MinGWOptTable parser;
180 opt::InputArgList args = parser.parse(argsArr.slice(1));
182 if (errorCount())
183 return false;
185 if (args.hasArg(OPT_help)) {
186 printHelp(argsArr[0]);
187 return true;
190 // A note about "compatible with GNU linkers" message: this is a hack for
191 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
192 // still the newest version in March 2017) or earlier to recognize LLD as
193 // a GNU compatible linker. As long as an output for the -v option
194 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
195 if (args.hasArg(OPT_v) || args.hasArg(OPT_version))
196 message(getLLDVersion() + " (compatible with GNU linkers)");
198 // The behavior of -v or --version is a bit strange, but this is
199 // needed for compatibility with GNU linkers.
200 if (args.hasArg(OPT_v) && !args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l))
201 return true;
202 if (args.hasArg(OPT_version))
203 return true;
205 if (!args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l)) {
206 error("no input files");
207 return false;
210 std::vector<std::string> linkArgs;
211 auto add = [&](const Twine &s) { linkArgs.push_back(s.str()); };
213 add("lld-link");
214 add("-lldmingw");
216 if (auto *a = args.getLastArg(OPT_entry)) {
217 StringRef s = a->getValue();
218 if (args.getLastArgValue(OPT_m) == "i386pe" && s.starts_with("_"))
219 add("-entry:" + s.substr(1));
220 else
221 add("-entry:" + s);
224 if (args.hasArg(OPT_major_os_version, OPT_minor_os_version,
225 OPT_major_subsystem_version, OPT_minor_subsystem_version)) {
226 StringRef majOSVer = args.getLastArgValue(OPT_major_os_version, "6");
227 StringRef minOSVer = args.getLastArgValue(OPT_minor_os_version, "0");
228 StringRef majSubSysVer = "6";
229 StringRef minSubSysVer = "0";
230 StringRef subSysName = "default";
231 StringRef subSysVer;
232 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
233 // the version number components from the last one of them that specifies
234 // a version.
235 for (auto *a : args.filtered(OPT_major_subsystem_version,
236 OPT_minor_subsystem_version, OPT_subs)) {
237 switch (a->getOption().getID()) {
238 case OPT_major_subsystem_version:
239 majSubSysVer = a->getValue();
240 break;
241 case OPT_minor_subsystem_version:
242 minSubSysVer = a->getValue();
243 break;
244 case OPT_subs:
245 std::tie(subSysName, subSysVer) = StringRef(a->getValue()).split(':');
246 if (!subSysVer.empty()) {
247 if (subSysVer.contains('.'))
248 std::tie(majSubSysVer, minSubSysVer) = subSysVer.split('.');
249 else
250 majSubSysVer = subSysVer;
252 break;
255 add("-osversion:" + majOSVer + "." + minOSVer);
256 add("-subsystem:" + subSysName + "," + majSubSysVer + "." + minSubSysVer);
257 } else if (args.hasArg(OPT_subs)) {
258 StringRef subSys = args.getLastArgValue(OPT_subs, "default");
259 StringRef subSysName, subSysVer;
260 std::tie(subSysName, subSysVer) = subSys.split(':');
261 StringRef sep = subSysVer.empty() ? "" : ",";
262 add("-subsystem:" + subSysName + sep + subSysVer);
265 if (auto *a = args.getLastArg(OPT_out_implib))
266 add("-implib:" + StringRef(a->getValue()));
267 if (auto *a = args.getLastArg(OPT_stack))
268 add("-stack:" + StringRef(a->getValue()));
269 if (auto *a = args.getLastArg(OPT_output_def))
270 add("-output-def:" + StringRef(a->getValue()));
271 if (auto *a = args.getLastArg(OPT_image_base))
272 add("-base:" + StringRef(a->getValue()));
273 if (auto *a = args.getLastArg(OPT_map))
274 add("-lldmap:" + StringRef(a->getValue()));
275 if (auto *a = args.getLastArg(OPT_reproduce))
276 add("-reproduce:" + StringRef(a->getValue()));
277 if (auto *a = args.getLastArg(OPT_thinlto_cache_dir))
278 add("-lldltocache:" + StringRef(a->getValue()));
279 if (auto *a = args.getLastArg(OPT_file_alignment))
280 add("-filealign:" + StringRef(a->getValue()));
281 if (auto *a = args.getLastArg(OPT_section_alignment))
282 add("-align:" + StringRef(a->getValue()));
283 if (auto *a = args.getLastArg(OPT_heap))
284 add("-heap:" + StringRef(a->getValue()));
286 if (auto *a = args.getLastArg(OPT_o))
287 add("-out:" + StringRef(a->getValue()));
288 else if (args.hasArg(OPT_shared))
289 add("-out:a.dll");
290 else
291 add("-out:a.exe");
293 if (auto *a = args.getLastArg(OPT_pdb)) {
294 add("-debug");
295 StringRef v = a->getValue();
296 if (!v.empty())
297 add("-pdb:" + v);
298 } else if (args.hasArg(OPT_strip_debug)) {
299 add("-debug:symtab");
300 } else if (!args.hasArg(OPT_strip_all)) {
301 add("-debug:dwarf");
304 if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false))
305 add("-WX");
306 else
307 add("-WX:no");
309 if (args.hasFlag(OPT_enable_stdcall_fixup, OPT_disable_stdcall_fixup, false))
310 add("-stdcall-fixup");
311 else if (args.hasArg(OPT_disable_stdcall_fixup))
312 add("-stdcall-fixup:no");
314 if (args.hasArg(OPT_shared))
315 add("-dll");
316 if (args.hasArg(OPT_verbose))
317 add("-verbose");
318 if (args.hasArg(OPT_exclude_all_symbols))
319 add("-exclude-all-symbols");
320 if (args.hasArg(OPT_export_all_symbols))
321 add("-export-all-symbols");
322 if (args.hasArg(OPT_large_address_aware))
323 add("-largeaddressaware");
324 if (args.hasArg(OPT_kill_at))
325 add("-kill-at");
326 if (args.hasArg(OPT_appcontainer))
327 add("-appcontainer");
328 if (args.hasFlag(OPT_no_seh, OPT_disable_no_seh, false))
329 add("-noseh");
331 if (args.getLastArgValue(OPT_m) != "thumb2pe" &&
332 args.getLastArgValue(OPT_m) != "arm64pe" &&
333 args.hasFlag(OPT_disable_dynamicbase, OPT_dynamicbase, false))
334 add("-dynamicbase:no");
335 if (args.hasFlag(OPT_disable_high_entropy_va, OPT_high_entropy_va, false))
336 add("-highentropyva:no");
337 if (args.hasFlag(OPT_disable_nxcompat, OPT_nxcompat, false))
338 add("-nxcompat:no");
339 if (args.hasFlag(OPT_disable_tsaware, OPT_tsaware, false))
340 add("-tsaware:no");
342 if (args.hasFlag(OPT_disable_reloc_section, OPT_enable_reloc_section, false))
343 add("-fixed");
345 if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false))
346 add("-timestamp:0");
348 if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false))
349 add("-opt:ref");
350 else
351 add("-opt:noref");
353 if (args.hasFlag(OPT_demangle, OPT_no_demangle, true))
354 add("-demangle");
355 else
356 add("-demangle:no");
358 if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true))
359 add("-auto-import");
360 else
361 add("-auto-import:no");
362 if (args.hasFlag(OPT_enable_runtime_pseudo_reloc,
363 OPT_disable_runtime_pseudo_reloc, true))
364 add("-runtime-pseudo-reloc");
365 else
366 add("-runtime-pseudo-reloc:no");
368 if (args.hasFlag(OPT_allow_multiple_definition,
369 OPT_no_allow_multiple_definition, false))
370 add("-force:multiple");
372 if (auto *a = args.getLastArg(OPT_icf)) {
373 StringRef s = a->getValue();
374 if (s == "all")
375 add("-opt:icf");
376 else if (s == "safe" || s == "none")
377 add("-opt:noicf");
378 else
379 error("unknown parameter: --icf=" + s);
380 } else {
381 add("-opt:noicf");
384 if (auto *a = args.getLastArg(OPT_m)) {
385 StringRef s = a->getValue();
386 if (s == "i386pe")
387 add("-machine:x86");
388 else if (s == "i386pep")
389 add("-machine:x64");
390 else if (s == "thumb2pe")
391 add("-machine:arm");
392 else if (s == "arm64pe")
393 add("-machine:arm64");
394 else
395 error("unknown parameter: -m" + s);
398 if (args.hasFlag(OPT_guard_cf, OPT_no_guard_cf, false)) {
399 if (args.hasFlag(OPT_guard_longjmp, OPT_no_guard_longjmp, true))
400 add("-guard:cf,longjmp");
401 else
402 add("-guard:cf,nolongjmp");
403 } else if (args.hasFlag(OPT_guard_longjmp, OPT_no_guard_longjmp, false)) {
404 auto *a = args.getLastArg(OPT_guard_longjmp);
405 warn("parameter " + a->getSpelling() +
406 " only takes effect when used with --guard-cf");
409 if (auto *a = args.getLastArg(OPT_error_limit)) {
410 int n;
411 StringRef s = a->getValue();
412 if (s.getAsInteger(10, n))
413 error(a->getSpelling() + ": number expected, but got " + s);
414 else
415 add("-errorlimit:" + s);
418 for (auto *a : args.filtered(OPT_mllvm))
419 add("-mllvm:" + StringRef(a->getValue()));
421 if (auto *arg = args.getLastArg(OPT_plugin_opt_mcpu_eq))
422 add("-mllvm:-mcpu=" + StringRef(arg->getValue()));
424 for (auto *a : args.filtered(OPT_plugin_opt_eq_minus))
425 add("-mllvm:-" + StringRef(a->getValue()));
427 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
428 // relative path. Just ignore. If not ended with "lto-wrapper" (or
429 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
430 // unsupported LLVMgold.so option and error.
431 for (opt::Arg *arg : args.filtered(OPT_plugin_opt_eq)) {
432 StringRef v(arg->getValue());
433 if (!v.ends_with("lto-wrapper") && !v.ends_with("lto-wrapper.exe"))
434 error(arg->getSpelling() + ": unknown plugin option '" + arg->getValue() +
435 "'");
438 for (auto *a : args.filtered(OPT_Xlink))
439 add(a->getValue());
441 if (args.getLastArgValue(OPT_m) == "i386pe")
442 add("-alternatename:__image_base__=___ImageBase");
443 else
444 add("-alternatename:__image_base__=__ImageBase");
446 for (auto *a : args.filtered(OPT_require_defined))
447 add("-include:" + StringRef(a->getValue()));
448 for (auto *a : args.filtered(OPT_undefined))
449 add("-includeoptional:" + StringRef(a->getValue()));
450 for (auto *a : args.filtered(OPT_delayload))
451 add("-delayload:" + StringRef(a->getValue()));
452 for (auto *a : args.filtered(OPT_wrap))
453 add("-wrap:" + StringRef(a->getValue()));
454 for (auto *a : args.filtered(OPT_exclude_symbols))
455 add("-exclude-symbols:" + StringRef(a->getValue()));
457 std::vector<StringRef> searchPaths;
458 for (auto *a : args.filtered(OPT_L)) {
459 searchPaths.push_back(a->getValue());
460 add("-libpath:" + StringRef(a->getValue()));
463 StringRef prefix = "";
464 bool isStatic = false;
465 for (auto *a : args) {
466 switch (a->getOption().getID()) {
467 case OPT_INPUT:
468 if (StringRef(a->getValue()).ends_with_insensitive(".def"))
469 add("-def:" + StringRef(a->getValue()));
470 else
471 add(prefix + StringRef(a->getValue()));
472 break;
473 case OPT_l:
474 add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic));
475 break;
476 case OPT_whole_archive:
477 prefix = "-wholearchive:";
478 break;
479 case OPT_no_whole_archive:
480 prefix = "";
481 break;
482 case OPT_Bstatic:
483 isStatic = true;
484 break;
485 case OPT_Bdynamic:
486 isStatic = false;
487 break;
491 if (errorCount())
492 return false;
494 if (args.hasArg(OPT_verbose) || args.hasArg(OPT__HASH_HASH_HASH))
495 lld::errs() << llvm::join(linkArgs, " ") << "\n";
497 if (args.hasArg(OPT__HASH_HASH_HASH))
498 return true;
500 // Repack vector of strings to vector of const char pointers for coff::link.
501 std::vector<const char *> vec;
502 for (const std::string &s : linkArgs)
503 vec.push_back(s.c_str());
504 // Pass the actual binary name, to make error messages be printed with
505 // the right prefix.
506 vec[0] = argsArr[0];
508 // The context will be re-created in the COFF driver.
509 lld::CommonLinkerContext::destroy();
511 return coff::link(vec, stdoutOS, stderrOS, exitEarly, disableOutput);
513 } // namespace mingw
514 } // namespace lld