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"
50 using namespace llvm::opt
;
56 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
57 #include "Options.inc"
61 // Create prefix string literals used in Options.td
62 #define PREFIX(NAME, VALUE) \
63 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
64 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
65 NAME##_init, std::size(NAME##_init) - 1);
66 #include "Options.inc"
69 // Create table mapping all options defined in Options.td
70 static constexpr opt::OptTable::Info infoTable
[] = {
71 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, \
72 VISIBILITY, PARAM, HELPTEXT, HELPTEXTSFORVARIANTS, METAVAR, \
77 HELPTEXTSFORVARIANTS, \
80 opt::Option::KIND##Class, \
88 #include "Options.inc"
93 class MinGWOptTable
: public opt::GenericOptTable
{
95 MinGWOptTable() : opt::GenericOptTable(infoTable
, false) {}
96 opt::InputArgList
parse(ArrayRef
<const char *> argv
);
100 static void printHelp(const char *argv0
) {
101 MinGWOptTable().printHelp(
102 lld::outs(), (std::string(argv0
) + " [options] file...").c_str(), "lld",
103 false /*ShowHidden*/, true /*ShowAllAliases*/);
107 static cl::TokenizerCallback
getQuotingStyle() {
108 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32
)
109 return cl::TokenizeWindowsCommandLine
;
110 return cl::TokenizeGNUCommandLine
;
113 opt::InputArgList
MinGWOptTable::parse(ArrayRef
<const char *> argv
) {
114 unsigned missingIndex
;
115 unsigned missingCount
;
117 SmallVector
<const char *, 256> vec(argv
.data(), argv
.data() + argv
.size());
118 cl::ExpandResponseFiles(saver(), getQuotingStyle(), vec
);
119 opt::InputArgList args
= this->ParseArgs(vec
, missingIndex
, missingCount
);
122 error(StringRef(args
.getArgString(missingIndex
)) + ": missing argument");
123 for (auto *arg
: args
.filtered(OPT_UNKNOWN
))
124 error("unknown argument: " + arg
->getAsString(args
));
128 // Find a file by concatenating given paths.
129 static std::optional
<std::string
> findFile(StringRef path1
,
130 const Twine
&path2
) {
132 sys::path::append(s
, path1
, path2
);
133 if (sys::fs::exists(s
))
134 return std::string(s
);
138 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
140 searchLibrary(StringRef name
, ArrayRef
<StringRef
> searchPaths
, bool bStatic
) {
141 if (name
.starts_with(":")) {
142 for (StringRef dir
: searchPaths
)
143 if (std::optional
<std::string
> s
= findFile(dir
, name
.substr(1)))
145 error("unable to find library -l" + name
);
149 for (StringRef dir
: searchPaths
) {
151 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll.a"))
153 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".dll.a"))
156 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".a"))
158 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".lib"))
161 if (std::optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll"))
163 if (std::optional
<std::string
> s
= findFile(dir
, name
+ ".dll"))
167 error("unable to find library -l" + name
);
173 bool link(ArrayRef
<const char *> argsArr
, llvm::raw_ostream
&stdoutOS
,
174 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
);
178 // Convert Unix-ish command line arguments to Windows-ish ones and
179 // then call coff::link.
180 bool link(ArrayRef
<const char *> argsArr
, llvm::raw_ostream
&stdoutOS
,
181 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
) {
182 auto *ctx
= new CommonLinkerContext
;
183 ctx
->e
.initialize(stdoutOS
, stderrOS
, exitEarly
, disableOutput
);
185 MinGWOptTable parser
;
186 opt::InputArgList args
= parser
.parse(argsArr
.slice(1));
191 if (args
.hasArg(OPT_help
)) {
192 printHelp(argsArr
[0]);
196 // A note about "compatible with GNU linkers" message: this is a hack for
197 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
198 // still the newest version in March 2017) or earlier to recognize LLD as
199 // a GNU compatible linker. As long as an output for the -v option
200 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
201 if (args
.hasArg(OPT_v
) || args
.hasArg(OPT_version
))
202 message(getLLDVersion() + " (compatible with GNU linkers)");
204 // The behavior of -v or --version is a bit strange, but this is
205 // needed for compatibility with GNU linkers.
206 if (args
.hasArg(OPT_v
) && !args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
))
208 if (args
.hasArg(OPT_version
))
211 if (!args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
)) {
212 error("no input files");
216 std::vector
<std::string
> linkArgs
;
217 auto add
= [&](const Twine
&s
) { linkArgs
.push_back(s
.str()); };
222 if (auto *a
= args
.getLastArg(OPT_entry
)) {
223 StringRef s
= a
->getValue();
224 if (args
.getLastArgValue(OPT_m
) == "i386pe" && s
.starts_with("_"))
225 add("-entry:" + s
.substr(1));
232 if (args
.hasArg(OPT_major_os_version
, OPT_minor_os_version
,
233 OPT_major_subsystem_version
, OPT_minor_subsystem_version
)) {
234 StringRef majOSVer
= args
.getLastArgValue(OPT_major_os_version
, "6");
235 StringRef minOSVer
= args
.getLastArgValue(OPT_minor_os_version
, "0");
236 StringRef majSubSysVer
= "6";
237 StringRef minSubSysVer
= "0";
238 StringRef subSysName
= "default";
240 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
241 // the version number components from the last one of them that specifies
243 for (auto *a
: args
.filtered(OPT_major_subsystem_version
,
244 OPT_minor_subsystem_version
, OPT_subs
)) {
245 switch (a
->getOption().getID()) {
246 case OPT_major_subsystem_version
:
247 majSubSysVer
= a
->getValue();
249 case OPT_minor_subsystem_version
:
250 minSubSysVer
= a
->getValue();
253 std::tie(subSysName
, subSysVer
) = StringRef(a
->getValue()).split(':');
254 if (!subSysVer
.empty()) {
255 if (subSysVer
.contains('.'))
256 std::tie(majSubSysVer
, minSubSysVer
) = subSysVer
.split('.');
258 majSubSysVer
= subSysVer
;
263 add("-osversion:" + majOSVer
+ "." + minOSVer
);
264 add("-subsystem:" + subSysName
+ "," + majSubSysVer
+ "." + minSubSysVer
);
265 } else if (args
.hasArg(OPT_subs
)) {
266 StringRef subSys
= args
.getLastArgValue(OPT_subs
, "default");
267 StringRef subSysName
, subSysVer
;
268 std::tie(subSysName
, subSysVer
) = subSys
.split(':');
269 StringRef sep
= subSysVer
.empty() ? "" : ",";
270 add("-subsystem:" + subSysName
+ sep
+ subSysVer
);
273 if (auto *a
= args
.getLastArg(OPT_out_implib
))
274 add("-implib:" + StringRef(a
->getValue()));
275 if (auto *a
= args
.getLastArg(OPT_stack
))
276 add("-stack:" + StringRef(a
->getValue()));
277 if (auto *a
= args
.getLastArg(OPT_output_def
))
278 add("-output-def:" + StringRef(a
->getValue()));
279 if (auto *a
= args
.getLastArg(OPT_image_base
))
280 add("-base:" + StringRef(a
->getValue()));
281 if (auto *a
= args
.getLastArg(OPT_map
))
282 add("-lldmap:" + StringRef(a
->getValue()));
283 if (auto *a
= args
.getLastArg(OPT_reproduce
))
284 add("-reproduce:" + StringRef(a
->getValue()));
285 if (auto *a
= args
.getLastArg(OPT_file_alignment
))
286 add("-filealign:" + StringRef(a
->getValue()));
287 if (auto *a
= args
.getLastArg(OPT_section_alignment
))
288 add("-align:" + StringRef(a
->getValue()));
289 if (auto *a
= args
.getLastArg(OPT_heap
))
290 add("-heap:" + StringRef(a
->getValue()));
291 if (auto *a
= args
.getLastArg(OPT_threads
))
292 add("-threads:" + StringRef(a
->getValue()));
294 if (auto *a
= args
.getLastArg(OPT_o
))
295 add("-out:" + StringRef(a
->getValue()));
296 else if (args
.hasArg(OPT_shared
))
301 if (auto *a
= args
.getLastArg(OPT_pdb
)) {
303 StringRef v
= a
->getValue();
306 if (args
.hasArg(OPT_strip_all
)) {
307 add("-debug:nodwarf,nosymtab");
308 } else if (args
.hasArg(OPT_strip_debug
)) {
309 add("-debug:nodwarf,symtab");
311 } else if (args
.hasArg(OPT_strip_debug
)) {
312 add("-debug:symtab");
313 } else if (!args
.hasArg(OPT_strip_all
)) {
316 if (auto *a
= args
.getLastArg(OPT_build_id
)) {
317 StringRef v
= a
->getValue();
322 warn("unsupported build id hashing: " + v
+ ", using default hashing.");
326 if (args
.hasArg(OPT_strip_debug
) || args
.hasArg(OPT_strip_all
))
332 if (args
.hasFlag(OPT_fatal_warnings
, OPT_no_fatal_warnings
, false))
337 if (args
.hasFlag(OPT_enable_stdcall_fixup
, OPT_disable_stdcall_fixup
, false))
338 add("-stdcall-fixup");
339 else if (args
.hasArg(OPT_disable_stdcall_fixup
))
340 add("-stdcall-fixup:no");
342 if (args
.hasArg(OPT_shared
))
344 if (args
.hasArg(OPT_verbose
))
346 if (args
.hasArg(OPT_exclude_all_symbols
))
347 add("-exclude-all-symbols");
348 if (args
.hasArg(OPT_export_all_symbols
))
349 add("-export-all-symbols");
350 if (args
.hasArg(OPT_large_address_aware
))
351 add("-largeaddressaware");
352 if (args
.hasArg(OPT_kill_at
))
354 if (args
.hasArg(OPT_appcontainer
))
355 add("-appcontainer");
356 if (args
.hasFlag(OPT_no_seh
, OPT_disable_no_seh
, false))
359 if (args
.getLastArgValue(OPT_m
) != "thumb2pe" &&
360 args
.getLastArgValue(OPT_m
) != "arm64pe" &&
361 args
.getLastArgValue(OPT_m
) != "arm64ecpe" &&
362 args
.hasFlag(OPT_disable_dynamicbase
, OPT_dynamicbase
, false))
363 add("-dynamicbase:no");
364 if (args
.hasFlag(OPT_disable_high_entropy_va
, OPT_high_entropy_va
, false))
365 add("-highentropyva:no");
366 if (args
.hasFlag(OPT_disable_nxcompat
, OPT_nxcompat
, false))
368 if (args
.hasFlag(OPT_disable_tsaware
, OPT_tsaware
, false))
371 if (args
.hasFlag(OPT_disable_reloc_section
, OPT_enable_reloc_section
, false))
374 if (args
.hasFlag(OPT_no_insert_timestamp
, OPT_insert_timestamp
, false))
377 if (args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, false))
382 if (args
.hasFlag(OPT_demangle
, OPT_no_demangle
, true))
387 if (args
.hasFlag(OPT_enable_auto_import
, OPT_disable_auto_import
, true))
390 add("-auto-import:no");
391 if (args
.hasFlag(OPT_enable_runtime_pseudo_reloc
,
392 OPT_disable_runtime_pseudo_reloc
, true))
393 add("-runtime-pseudo-reloc");
395 add("-runtime-pseudo-reloc:no");
397 if (args
.hasFlag(OPT_allow_multiple_definition
,
398 OPT_no_allow_multiple_definition
, false))
399 add("-force:multiple");
401 if (auto *a
= args
.getLastArg(OPT_icf
)) {
402 StringRef s
= a
->getValue();
405 else if (s
== "safe")
407 else if (s
== "none")
410 error("unknown parameter: --icf=" + s
);
415 if (auto *a
= args
.getLastArg(OPT_m
)) {
416 StringRef s
= a
->getValue();
419 else if (s
== "i386pep")
421 else if (s
== "thumb2pe")
423 else if (s
== "arm64pe")
424 add("-machine:arm64");
425 else if (s
== "arm64ecpe")
426 add("-machine:arm64ec");
428 error("unknown parameter: -m" + s
);
431 if (args
.hasFlag(OPT_guard_cf
, OPT_no_guard_cf
, false)) {
432 if (args
.hasFlag(OPT_guard_longjmp
, OPT_no_guard_longjmp
, true))
433 add("-guard:cf,longjmp");
435 add("-guard:cf,nolongjmp");
436 } else if (args
.hasFlag(OPT_guard_longjmp
, OPT_no_guard_longjmp
, false)) {
437 auto *a
= args
.getLastArg(OPT_guard_longjmp
);
438 warn("parameter " + a
->getSpelling() +
439 " only takes effect when used with --guard-cf");
442 if (auto *a
= args
.getLastArg(OPT_error_limit
)) {
444 StringRef s
= a
->getValue();
445 if (s
.getAsInteger(10, n
))
446 error(a
->getSpelling() + ": number expected, but got " + s
);
448 add("-errorlimit:" + s
);
451 if (auto *a
= args
.getLastArg(OPT_rpath
))
452 warn("parameter " + a
->getSpelling() + " has no effect on PE/COFF targets");
454 for (auto *a
: args
.filtered(OPT_mllvm
))
455 add("-mllvm:" + StringRef(a
->getValue()));
457 if (auto *arg
= args
.getLastArg(OPT_plugin_opt_mcpu_eq
))
458 add("-mllvm:-mcpu=" + StringRef(arg
->getValue()));
459 if (auto *arg
= args
.getLastArg(OPT_lto_O
))
460 add("-opt:lldlto=" + StringRef(arg
->getValue()));
461 if (auto *arg
= args
.getLastArg(OPT_lto_CGO
))
462 add("-opt:lldltocgo=" + StringRef(arg
->getValue()));
463 if (auto *arg
= args
.getLastArg(OPT_plugin_opt_dwo_dir_eq
))
464 add("-dwodir:" + StringRef(arg
->getValue()));
465 if (args
.hasArg(OPT_lto_cs_profile_generate
))
466 add("-lto-cs-profile-generate");
467 if (auto *arg
= args
.getLastArg(OPT_lto_cs_profile_file
))
468 add("-lto-cs-profile-file:" + StringRef(arg
->getValue()));
469 if (args
.hasArg(OPT_plugin_opt_emit_llvm
))
470 add("-lldemit:llvm");
471 if (args
.hasArg(OPT_lto_emit_asm
))
473 if (auto *arg
= args
.getLastArg(OPT_lto_sample_profile
))
474 add("-lto-sample-profile:" + StringRef(arg
->getValue()));
476 if (auto *a
= args
.getLastArg(OPT_thinlto_cache_dir
))
477 add("-lldltocache:" + StringRef(a
->getValue()));
478 if (auto *a
= args
.getLastArg(OPT_thinlto_cache_policy
))
479 add("-lldltocachepolicy:" + StringRef(a
->getValue()));
480 if (args
.hasArg(OPT_thinlto_emit_imports_files
))
481 add("-thinlto-emit-imports-files");
482 if (args
.hasArg(OPT_thinlto_index_only
))
483 add("-thinlto-index-only");
484 if (auto *arg
= args
.getLastArg(OPT_thinlto_index_only_eq
))
485 add("-thinlto-index-only:" + StringRef(arg
->getValue()));
486 if (auto *arg
= args
.getLastArg(OPT_thinlto_jobs_eq
))
487 add("-opt:lldltojobs=" + StringRef(arg
->getValue()));
488 if (auto *arg
= args
.getLastArg(OPT_thinlto_object_suffix_replace_eq
))
489 add("-thinlto-object-suffix-replace:" + StringRef(arg
->getValue()));
490 if (auto *arg
= args
.getLastArg(OPT_thinlto_prefix_replace_eq
))
491 add("-thinlto-prefix-replace:" + StringRef(arg
->getValue()));
493 for (auto *a
: args
.filtered(OPT_plugin_opt_eq_minus
))
494 add("-mllvm:-" + StringRef(a
->getValue()));
496 // GCC collect2 passes -plugin-opt=path/to/lto-wrapper with an absolute or
497 // relative path. Just ignore. If not ended with "lto-wrapper" (or
498 // "lto-wrapper.exe" for GCC cross-compiled for Windows), consider it an
499 // unsupported LLVMgold.so option and error.
500 for (opt::Arg
*arg
: args
.filtered(OPT_plugin_opt_eq
)) {
501 StringRef
v(arg
->getValue());
502 if (!v
.ends_with("lto-wrapper") && !v
.ends_with("lto-wrapper.exe"))
503 error(arg
->getSpelling() + ": unknown plugin option '" + arg
->getValue() +
507 for (auto *a
: args
.filtered(OPT_Xlink
))
510 if (args
.getLastArgValue(OPT_m
) == "i386pe")
511 add("-alternatename:__image_base__=___ImageBase");
513 add("-alternatename:__image_base__=__ImageBase");
515 for (auto *a
: args
.filtered(OPT_require_defined
))
516 add("-include:" + StringRef(a
->getValue()));
517 for (auto *a
: args
.filtered(OPT_undefined
))
518 add("-includeoptional:" + StringRef(a
->getValue()));
519 for (auto *a
: args
.filtered(OPT_delayload
))
520 add("-delayload:" + StringRef(a
->getValue()));
521 for (auto *a
: args
.filtered(OPT_wrap
))
522 add("-wrap:" + StringRef(a
->getValue()));
523 for (auto *a
: args
.filtered(OPT_exclude_symbols
))
524 add("-exclude-symbols:" + StringRef(a
->getValue()));
526 std::vector
<StringRef
> searchPaths
;
527 for (auto *a
: args
.filtered(OPT_L
)) {
528 searchPaths
.push_back(a
->getValue());
529 add("-libpath:" + StringRef(a
->getValue()));
532 StringRef prefix
= "";
533 bool isStatic
= false;
534 for (auto *a
: args
) {
535 switch (a
->getOption().getID()) {
537 if (StringRef(a
->getValue()).ends_with_insensitive(".def"))
538 add("-def:" + StringRef(a
->getValue()));
540 add(prefix
+ StringRef(a
->getValue()));
543 add(prefix
+ searchLibrary(a
->getValue(), searchPaths
, isStatic
));
545 case OPT_whole_archive
:
546 prefix
= "-wholearchive:";
548 case OPT_no_whole_archive
:
563 if (args
.hasArg(OPT_verbose
) || args
.hasArg(OPT__HASH_HASH_HASH
))
564 lld::errs() << llvm::join(linkArgs
, " ") << "\n";
566 if (args
.hasArg(OPT__HASH_HASH_HASH
))
569 // Repack vector of strings to vector of const char pointers for coff::link.
570 std::vector
<const char *> vec
;
571 for (const std::string
&s
: linkArgs
)
572 vec
.push_back(s
.c_str());
573 // Pass the actual binary name, to make error messages be printed with
577 // The context will be re-created in the COFF driver.
578 lld::CommonLinkerContext::destroy();
580 return coff::link(vec
, stdoutOS
, stderrOS
, exitEarly
, disableOutput
);