1 //===- MinGW/Driver.cpp ---------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
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
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"
49 #if !defined(_MSC_VER) && !defined(__MINGW32__)
54 using namespace llvm::opt
;
60 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
61 #include "Options.inc"
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"
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, \
82 #include "Options.inc"
87 class MinGWOptTable
: public opt::GenericOptTable
{
89 MinGWOptTable() : opt::GenericOptTable(infoTable
, false) {}
90 opt::InputArgList
parse(ArrayRef
<const char *> argv
);
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*/);
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
);
116 error(StringRef(args
.getArgString(missingIndex
)) + ": missing argument");
117 for (auto *arg
: args
.filtered(OPT_UNKNOWN
))
118 error("unknown argument: " + arg
->getAsString(args
));
122 // Find a file by concatenating given paths.
123 static std::optional
<std::string
> findFile(StringRef path1
,
124 const Twine
&path2
) {
126 sys::path::append(s
, path1
, path2
);
127 if (sys::fs::exists(s
))
128 return std::string(s
);
132 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
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)))
139 error("unable to find library -l" + name
);
143 for (StringRef dir
: searchPaths
) {
145 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll.a"))
147 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".dll.a"))
150 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".a"))
152 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".lib"))
155 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll"))
157 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".dll"))
161 error("unable to find library -l" + name
);
167 bool link(ArrayRef
<const char *> argsArr
, llvm::raw_ostream
&stdoutOS
,
168 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
);
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));
185 if (args
.hasArg(OPT_help
)) {
186 printHelp(argsArr
[0]);
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
))
202 if (args
.hasArg(OPT_version
))
205 if (!args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
)) {
206 error("no input files");
210 std::vector
<std::string
> linkArgs
;
211 auto add
= [&](const Twine
&s
) { linkArgs
.push_back(s
.str()); };
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));
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";
232 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
233 // the version number components from the last one of them that specifies
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();
241 case OPT_minor_subsystem_version
:
242 minSubSysVer
= a
->getValue();
245 std::tie(subSysName
, subSysVer
) = StringRef(a
->getValue()).split(':');
246 if (!subSysVer
.empty()) {
247 if (subSysVer
.contains('.'))
248 std::tie(majSubSysVer
, minSubSysVer
) = subSysVer
.split('.');
250 majSubSysVer
= subSysVer
;
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
))
293 if (auto *a
= args
.getLastArg(OPT_pdb
)) {
295 StringRef v
= a
->getValue();
298 } else if (args
.hasArg(OPT_strip_debug
)) {
299 add("-debug:symtab");
300 } else if (!args
.hasArg(OPT_strip_all
)) {
304 if (args
.hasFlag(OPT_fatal_warnings
, OPT_no_fatal_warnings
, false))
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
))
316 if (args
.hasArg(OPT_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
))
326 if (args
.hasArg(OPT_appcontainer
))
327 add("-appcontainer");
328 if (args
.hasFlag(OPT_no_seh
, OPT_disable_no_seh
, false))
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))
339 if (args
.hasFlag(OPT_disable_tsaware
, OPT_tsaware
, false))
342 if (args
.hasFlag(OPT_disable_reloc_section
, OPT_enable_reloc_section
, false))
345 if (args
.hasFlag(OPT_no_insert_timestamp
, OPT_insert_timestamp
, false))
348 if (args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, false))
353 if (args
.hasFlag(OPT_demangle
, OPT_no_demangle
, true))
358 if (args
.hasFlag(OPT_enable_auto_import
, OPT_disable_auto_import
, true))
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");
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();
376 else if (s
== "safe" || s
== "none")
379 error("unknown parameter: --icf=" + s
);
384 if (auto *a
= args
.getLastArg(OPT_m
)) {
385 StringRef s
= a
->getValue();
388 else if (s
== "i386pep")
390 else if (s
== "thumb2pe")
392 else if (s
== "arm64pe")
393 add("-machine:arm64");
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");
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
)) {
411 StringRef s
= a
->getValue();
412 if (s
.getAsInteger(10, n
))
413 error(a
->getSpelling() + ": number expected, but got " + s
);
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() +
438 for (auto *a
: args
.filtered(OPT_Xlink
))
441 if (args
.getLastArgValue(OPT_m
) == "i386pe")
442 add("-alternatename:__image_base__=___ImageBase");
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()) {
468 if (StringRef(a
->getValue()).ends_with_insensitive(".def"))
469 add("-def:" + StringRef(a
->getValue()));
471 add(prefix
+ StringRef(a
->getValue()));
474 add(prefix
+ searchLibrary(a
->getValue(), searchPaths
, isStatic
));
476 case OPT_whole_archive
:
477 prefix
= "-wholearchive:";
479 case OPT_no_whole_archive
:
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
))
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
508 // The context will be re-created in the COFF driver.
509 lld::CommonLinkerContext::destroy();
511 return coff::link(vec
, stdoutOS
, stderrOS
, exitEarly
, disableOutput
);