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/ErrorHandler.h"
33 #include "lld/Common/Memory.h"
34 #include "lld/Common/Version.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/Optional.h"
37 #include "llvm/ADT/StringExtras.h"
38 #include "llvm/ADT/StringRef.h"
39 #include "llvm/ADT/Triple.h"
40 #include "llvm/Option/Arg.h"
41 #include "llvm/Option/ArgList.h"
42 #include "llvm/Option/Option.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/Host.h"
46 #include "llvm/Support/Path.h"
48 #if !defined(_MSC_VER) && !defined(__MINGW32__)
58 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
59 #include "Options.inc"
63 // Create prefix string literals used in Options.td
64 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
65 #include "Options.inc"
68 // Create table mapping all options defined in Options.td
69 static const opt::OptTable::Info infoTable
[] = {
70 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
71 {X1, X2, X10, X11, OPT_##ID, opt::Option::KIND##Class, \
72 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
73 #include "Options.inc"
78 class MinGWOptTable
: public opt::OptTable
{
80 MinGWOptTable() : OptTable(infoTable
, false) {}
81 opt::InputArgList
parse(ArrayRef
<const char *> argv
);
85 static void printHelp(const char *argv0
) {
86 MinGWOptTable().printHelp(
87 lld::outs(), (std::string(argv0
) + " [options] file...").c_str(), "lld",
88 false /*ShowHidden*/, true /*ShowAllAliases*/);
92 static cl::TokenizerCallback
getQuotingStyle() {
93 if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32
)
94 return cl::TokenizeWindowsCommandLine
;
95 return cl::TokenizeGNUCommandLine
;
98 opt::InputArgList
MinGWOptTable::parse(ArrayRef
<const char *> argv
) {
99 unsigned missingIndex
;
100 unsigned missingCount
;
102 SmallVector
<const char *, 256> vec(argv
.data(), argv
.data() + argv
.size());
103 cl::ExpandResponseFiles(saver
, getQuotingStyle(), vec
);
104 opt::InputArgList args
= this->ParseArgs(vec
, missingIndex
, missingCount
);
107 error(StringRef(args
.getArgString(missingIndex
)) + ": missing argument");
108 for (auto *arg
: args
.filtered(OPT_UNKNOWN
))
109 error("unknown argument: " + arg
->getAsString(args
));
113 // Find a file by concatenating given paths.
114 static Optional
<std::string
> findFile(StringRef path1
, const Twine
&path2
) {
116 sys::path::append(s
, path1
, path2
);
117 if (sys::fs::exists(s
))
118 return std::string(s
);
122 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
124 searchLibrary(StringRef name
, ArrayRef
<StringRef
> searchPaths
, bool bStatic
) {
125 if (name
.startswith(":")) {
126 for (StringRef dir
: searchPaths
)
127 if (Optional
<std::string
> s
= findFile(dir
, name
.substr(1)))
129 error("unable to find library -l" + name
);
133 for (StringRef dir
: searchPaths
) {
135 if (Optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll.a"))
137 if (Optional
<std::string
> s
= findFile(dir
, name
+ ".dll.a"))
140 if (Optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".a"))
143 if (Optional
<std::string
> s
= findFile(dir
, name
+ ".lib"))
145 if (Optional
<std::string
> s
= findFile(dir
, "lib" + name
+ ".dll"))
147 if (Optional
<std::string
> s
= findFile(dir
, name
+ ".dll"))
151 error("unable to find library -l" + name
);
155 // Convert Unix-ish command line arguments to Windows-ish ones and
156 // then call coff::link.
157 bool mingw::link(ArrayRef
<const char *> argsArr
, bool canExitEarly
,
158 raw_ostream
&stdoutOS
, raw_ostream
&stderrOS
) {
159 lld::stdoutOS
= &stdoutOS
;
160 lld::stderrOS
= &stderrOS
;
162 stderrOS
.enable_colors(stderrOS
.has_colors());
164 MinGWOptTable parser
;
165 opt::InputArgList args
= parser
.parse(argsArr
.slice(1));
170 if (args
.hasArg(OPT_help
)) {
171 printHelp(argsArr
[0]);
175 // A note about "compatible with GNU linkers" message: this is a hack for
176 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
177 // still the newest version in March 2017) or earlier to recognize LLD as
178 // a GNU compatible linker. As long as an output for the -v option
179 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
180 if (args
.hasArg(OPT_v
) || args
.hasArg(OPT_version
))
181 message(getLLDVersion() + " (compatible with GNU linkers)");
183 // The behavior of -v or --version is a bit strange, but this is
184 // needed for compatibility with GNU linkers.
185 if (args
.hasArg(OPT_v
) && !args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
))
187 if (args
.hasArg(OPT_version
))
190 if (!args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
)) {
191 error("no input files");
195 std::vector
<std::string
> linkArgs
;
196 auto add
= [&](const Twine
&s
) { linkArgs
.push_back(s
.str()); };
201 if (auto *a
= args
.getLastArg(OPT_entry
)) {
202 StringRef s
= a
->getValue();
203 if (args
.getLastArgValue(OPT_m
) == "i386pe" && s
.startswith("_"))
204 add("-entry:" + s
.substr(1));
209 if (args
.hasArg(OPT_major_os_version
, OPT_minor_os_version
,
210 OPT_major_subsystem_version
, OPT_minor_subsystem_version
)) {
211 StringRef majOSVer
= args
.getLastArgValue(OPT_major_os_version
, "6");
212 StringRef minOSVer
= args
.getLastArgValue(OPT_minor_os_version
, "0");
213 StringRef majSubSysVer
= "6";
214 StringRef minSubSysVer
= "0";
215 StringRef subSysName
= "default";
217 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
218 // the version number components from the last one of them that specifies
220 for (auto *a
: args
.filtered(OPT_major_subsystem_version
,
221 OPT_minor_subsystem_version
, OPT_subs
)) {
222 switch (a
->getOption().getID()) {
223 case OPT_major_subsystem_version
:
224 majSubSysVer
= a
->getValue();
226 case OPT_minor_subsystem_version
:
227 minSubSysVer
= a
->getValue();
230 std::tie(subSysName
, subSysVer
) = StringRef(a
->getValue()).split(':');
231 if (!subSysVer
.empty()) {
232 if (subSysVer
.contains('.'))
233 std::tie(majSubSysVer
, minSubSysVer
) = subSysVer
.split('.');
235 majSubSysVer
= subSysVer
;
240 add("-osversion:" + majOSVer
+ "." + minOSVer
);
241 add("-subsystem:" + subSysName
+ "," + majSubSysVer
+ "." + minSubSysVer
);
242 } else if (args
.hasArg(OPT_subs
)) {
243 StringRef subSys
= args
.getLastArgValue(OPT_subs
, "default");
244 StringRef subSysName
, subSysVer
;
245 std::tie(subSysName
, subSysVer
) = subSys
.split(':');
246 StringRef sep
= subSysVer
.empty() ? "" : ",";
247 add("-subsystem:" + subSysName
+ sep
+ subSysVer
);
250 if (auto *a
= args
.getLastArg(OPT_out_implib
))
251 add("-implib:" + StringRef(a
->getValue()));
252 if (auto *a
= args
.getLastArg(OPT_stack
))
253 add("-stack:" + StringRef(a
->getValue()));
254 if (auto *a
= args
.getLastArg(OPT_output_def
))
255 add("-output-def:" + StringRef(a
->getValue()));
256 if (auto *a
= args
.getLastArg(OPT_image_base
))
257 add("-base:" + StringRef(a
->getValue()));
258 if (auto *a
= args
.getLastArg(OPT_map
))
259 add("-lldmap:" + StringRef(a
->getValue()));
260 if (auto *a
= args
.getLastArg(OPT_reproduce
))
261 add("-reproduce:" + StringRef(a
->getValue()));
262 if (auto *a
= args
.getLastArg(OPT_thinlto_cache_dir
))
263 add("-lldltocache:" + StringRef(a
->getValue()));
264 if (auto *a
= args
.getLastArg(OPT_file_alignment
))
265 add("-filealign:" + StringRef(a
->getValue()));
266 if (auto *a
= args
.getLastArg(OPT_section_alignment
))
267 add("-align:" + StringRef(a
->getValue()));
269 if (auto *a
= args
.getLastArg(OPT_o
))
270 add("-out:" + StringRef(a
->getValue()));
271 else if (args
.hasArg(OPT_shared
))
276 if (auto *a
= args
.getLastArg(OPT_pdb
)) {
278 StringRef v
= a
->getValue();
281 } else if (args
.hasArg(OPT_strip_debug
)) {
282 add("-debug:symtab");
283 } else if (!args
.hasArg(OPT_strip_all
)) {
287 if (args
.hasFlag(OPT_fatal_warnings
, OPT_no_fatal_warnings
, false))
292 if (args
.hasFlag(OPT_enable_stdcall_fixup
, OPT_disable_stdcall_fixup
, false))
293 add("-stdcall-fixup");
294 else if (args
.hasArg(OPT_disable_stdcall_fixup
))
295 add("-stdcall-fixup:no");
297 if (args
.hasArg(OPT_shared
))
299 if (args
.hasArg(OPT_verbose
))
301 if (args
.hasArg(OPT_exclude_all_symbols
))
302 add("-exclude-all-symbols");
303 if (args
.hasArg(OPT_export_all_symbols
))
304 add("-export-all-symbols");
305 if (args
.hasArg(OPT_large_address_aware
))
306 add("-largeaddressaware");
307 if (args
.hasArg(OPT_kill_at
))
309 if (args
.hasArg(OPT_appcontainer
))
310 add("-appcontainer");
311 if (args
.hasFlag(OPT_no_seh
, OPT_disable_no_seh
, false))
314 if (args
.getLastArgValue(OPT_m
) != "thumb2pe" &&
315 args
.getLastArgValue(OPT_m
) != "arm64pe" &&
316 args
.hasFlag(OPT_disable_dynamicbase
, OPT_dynamicbase
, false))
317 add("-dynamicbase:no");
318 if (args
.hasFlag(OPT_disable_high_entropy_va
, OPT_high_entropy_va
, false))
319 add("-highentropyva:no");
320 if (args
.hasFlag(OPT_disable_nxcompat
, OPT_nxcompat
, false))
322 if (args
.hasFlag(OPT_disable_tsaware
, OPT_tsaware
, false))
325 if (args
.hasFlag(OPT_no_insert_timestamp
, OPT_insert_timestamp
, false))
328 if (args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, false))
333 if (args
.hasFlag(OPT_demangle
, OPT_no_demangle
, true))
338 if (args
.hasFlag(OPT_enable_auto_import
, OPT_disable_auto_import
, true))
341 add("-auto-import:no");
342 if (args
.hasFlag(OPT_enable_runtime_pseudo_reloc
,
343 OPT_disable_runtime_pseudo_reloc
, true))
344 add("-runtime-pseudo-reloc");
346 add("-runtime-pseudo-reloc:no");
348 if (args
.hasFlag(OPT_allow_multiple_definition
,
349 OPT_no_allow_multiple_definition
, false))
350 add("-force:multiple");
352 if (auto *a
= args
.getLastArg(OPT_icf
)) {
353 StringRef s
= a
->getValue();
356 else if (s
== "safe" || s
== "none")
359 error("unknown parameter: --icf=" + s
);
364 if (auto *a
= args
.getLastArg(OPT_m
)) {
365 StringRef s
= a
->getValue();
368 else if (s
== "i386pep")
370 else if (s
== "thumb2pe")
372 else if (s
== "arm64pe")
373 add("-machine:arm64");
375 error("unknown parameter: -m" + s
);
378 for (auto *a
: args
.filtered(OPT_mllvm
))
379 add("-mllvm:" + StringRef(a
->getValue()));
381 for (auto *a
: args
.filtered(OPT_Xlink
))
384 if (args
.getLastArgValue(OPT_m
) == "i386pe")
385 add("-alternatename:__image_base__=___ImageBase");
387 add("-alternatename:__image_base__=__ImageBase");
389 for (auto *a
: args
.filtered(OPT_require_defined
))
390 add("-include:" + StringRef(a
->getValue()));
391 for (auto *a
: args
.filtered(OPT_undefined
))
392 add("-includeoptional:" + StringRef(a
->getValue()));
393 for (auto *a
: args
.filtered(OPT_delayload
))
394 add("-delayload:" + StringRef(a
->getValue()));
395 for (auto *a
: args
.filtered(OPT_wrap
))
396 add("-wrap:" + StringRef(a
->getValue()));
398 std::vector
<StringRef
> searchPaths
;
399 for (auto *a
: args
.filtered(OPT_L
)) {
400 searchPaths
.push_back(a
->getValue());
401 add("-libpath:" + StringRef(a
->getValue()));
404 StringRef prefix
= "";
405 bool isStatic
= false;
406 for (auto *a
: args
) {
407 switch (a
->getOption().getID()) {
409 if (StringRef(a
->getValue()).endswith_insensitive(".def"))
410 add("-def:" + StringRef(a
->getValue()));
412 add(prefix
+ StringRef(a
->getValue()));
415 add(prefix
+ searchLibrary(a
->getValue(), searchPaths
, isStatic
));
417 case OPT_whole_archive
:
418 prefix
= "-wholearchive:";
420 case OPT_no_whole_archive
:
435 if (args
.hasArg(OPT_verbose
) || args
.hasArg(OPT__HASH_HASH_HASH
))
436 lld::errs() << llvm::join(linkArgs
, " ") << "\n";
438 if (args
.hasArg(OPT__HASH_HASH_HASH
))
441 // Repack vector of strings to vector of const char pointers for coff::link.
442 std::vector
<const char *> vec
;
443 for (const std::string
&s
: linkArgs
)
444 vec
.push_back(s
.c_str());
445 // Pass the actual binary name, to make error messages be printed with
448 return coff::link(vec
, canExitEarly
, stdoutOS
, stderrOS
);