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")) {
146 error("lld doesn't support linking directly against " + *s
+
147 ", use an import library");
150 if (Optional
<std::string
> s
= findFile(dir
, name
+ ".dll")) {
151 error("lld doesn't support linking directly against " + *s
+
152 ", use an import library");
157 error("unable to find library -l" + name
);
161 // Convert Unix-ish command line arguments to Windows-ish ones and
162 // then call coff::link.
163 bool mingw::link(ArrayRef
<const char *> argsArr
, bool canExitEarly
,
164 raw_ostream
&stdoutOS
, raw_ostream
&stderrOS
) {
165 lld::stdoutOS
= &stdoutOS
;
166 lld::stderrOS
= &stderrOS
;
168 stderrOS
.enable_colors(stderrOS
.has_colors());
170 MinGWOptTable parser
;
171 opt::InputArgList args
= parser
.parse(argsArr
.slice(1));
176 if (args
.hasArg(OPT_help
)) {
177 printHelp(argsArr
[0]);
181 // A note about "compatible with GNU linkers" message: this is a hack for
182 // scripts generated by GNU Libtool 2.4.6 (released in February 2014 and
183 // still the newest version in March 2017) or earlier to recognize LLD as
184 // a GNU compatible linker. As long as an output for the -v option
185 // contains "GNU" or "with BFD", they recognize us as GNU-compatible.
186 if (args
.hasArg(OPT_v
) || args
.hasArg(OPT_version
))
187 message(getLLDVersion() + " (compatible with GNU linkers)");
189 // The behavior of -v or --version is a bit strange, but this is
190 // needed for compatibility with GNU linkers.
191 if (args
.hasArg(OPT_v
) && !args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
))
193 if (args
.hasArg(OPT_version
))
196 if (!args
.hasArg(OPT_INPUT
) && !args
.hasArg(OPT_l
)) {
197 error("no input files");
201 std::vector
<std::string
> linkArgs
;
202 auto add
= [&](const Twine
&s
) { linkArgs
.push_back(s
.str()); };
207 if (auto *a
= args
.getLastArg(OPT_entry
)) {
208 StringRef s
= a
->getValue();
209 if (args
.getLastArgValue(OPT_m
) == "i386pe" && s
.startswith("_"))
210 add("-entry:" + s
.substr(1));
215 if (args
.hasArg(OPT_major_os_version
, OPT_minor_os_version
,
216 OPT_major_subsystem_version
, OPT_minor_subsystem_version
)) {
217 auto *majOSVer
= args
.getLastArg(OPT_major_os_version
);
218 auto *minOSVer
= args
.getLastArg(OPT_minor_os_version
);
219 auto *majSubSysVer
= args
.getLastArg(OPT_major_subsystem_version
);
220 auto *minSubSysVer
= args
.getLastArg(OPT_minor_subsystem_version
);
221 if (majOSVer
&& majSubSysVer
&&
222 StringRef(majOSVer
->getValue()) != StringRef(majSubSysVer
->getValue()))
223 warn("--major-os-version and --major-subsystem-version set to differing "
224 "versions, not supported");
225 if (minOSVer
&& minSubSysVer
&&
226 StringRef(minOSVer
->getValue()) != StringRef(minSubSysVer
->getValue()))
227 warn("--minor-os-version and --minor-subsystem-version set to differing "
228 "versions, not supported");
229 StringRef subSys
= args
.getLastArgValue(OPT_subs
, "default");
230 StringRef major
= majOSVer
? majOSVer
->getValue()
231 : majSubSysVer
? majSubSysVer
->getValue() : "6";
232 StringRef minor
= minOSVer
? minOSVer
->getValue()
233 : minSubSysVer
? minSubSysVer
->getValue() : "";
234 StringRef sep
= minor
.empty() ? "" : ".";
235 add("-subsystem:" + subSys
+ "," + major
+ sep
+ minor
);
236 } else if (auto *a
= args
.getLastArg(OPT_subs
)) {
237 add("-subsystem:" + StringRef(a
->getValue()));
240 if (auto *a
= args
.getLastArg(OPT_out_implib
))
241 add("-implib:" + StringRef(a
->getValue()));
242 if (auto *a
= args
.getLastArg(OPT_stack
))
243 add("-stack:" + StringRef(a
->getValue()));
244 if (auto *a
= args
.getLastArg(OPT_output_def
))
245 add("-output-def:" + StringRef(a
->getValue()));
246 if (auto *a
= args
.getLastArg(OPT_image_base
))
247 add("-base:" + StringRef(a
->getValue()));
248 if (auto *a
= args
.getLastArg(OPT_map
))
249 add("-lldmap:" + StringRef(a
->getValue()));
250 if (auto *a
= args
.getLastArg(OPT_reproduce
))
251 add("-reproduce:" + StringRef(a
->getValue()));
252 if (auto *a
= args
.getLastArg(OPT_thinlto_cache_dir
))
253 add("-lldltocache:" + StringRef(a
->getValue()));
255 if (auto *a
= args
.getLastArg(OPT_o
))
256 add("-out:" + StringRef(a
->getValue()));
257 else if (args
.hasArg(OPT_shared
))
262 if (auto *a
= args
.getLastArg(OPT_pdb
)) {
264 StringRef v
= a
->getValue();
267 } else if (args
.hasArg(OPT_strip_debug
)) {
268 add("-debug:symtab");
269 } else if (!args
.hasArg(OPT_strip_all
)) {
273 if (args
.hasArg(OPT_shared
))
275 if (args
.hasArg(OPT_verbose
))
277 if (args
.hasArg(OPT_exclude_all_symbols
))
278 add("-exclude-all-symbols");
279 if (args
.hasArg(OPT_export_all_symbols
))
280 add("-export-all-symbols");
281 if (args
.hasArg(OPT_large_address_aware
))
282 add("-largeaddressaware");
283 if (args
.hasArg(OPT_kill_at
))
285 if (args
.hasArg(OPT_appcontainer
))
286 add("-appcontainer");
288 if (args
.getLastArgValue(OPT_m
) != "thumb2pe" &&
289 args
.getLastArgValue(OPT_m
) != "arm64pe" && !args
.hasArg(OPT_dynamicbase
))
290 add("-dynamicbase:no");
292 if (args
.hasFlag(OPT_no_insert_timestamp
, OPT_insert_timestamp
, false))
295 if (args
.hasFlag(OPT_gc_sections
, OPT_no_gc_sections
, false))
300 if (args
.hasFlag(OPT_enable_auto_import
, OPT_disable_auto_import
, true))
303 add("-auto-import:no");
304 if (args
.hasFlag(OPT_enable_runtime_pseudo_reloc
,
305 OPT_disable_runtime_pseudo_reloc
, true))
306 add("-runtime-pseudo-reloc");
308 add("-runtime-pseudo-reloc:no");
310 if (auto *a
= args
.getLastArg(OPT_icf
)) {
311 StringRef s
= a
->getValue();
314 else if (s
== "safe" || s
== "none")
317 error("unknown parameter: --icf=" + s
);
322 if (auto *a
= args
.getLastArg(OPT_m
)) {
323 StringRef s
= a
->getValue();
326 else if (s
== "i386pep")
328 else if (s
== "thumb2pe")
330 else if (s
== "arm64pe")
331 add("-machine:arm64");
333 error("unknown parameter: -m" + s
);
336 for (auto *a
: args
.filtered(OPT_mllvm
))
337 add("-mllvm:" + StringRef(a
->getValue()));
339 for (auto *a
: args
.filtered(OPT_Xlink
))
342 if (args
.getLastArgValue(OPT_m
) == "i386pe")
343 add("-alternatename:__image_base__=___ImageBase");
345 add("-alternatename:__image_base__=__ImageBase");
347 for (auto *a
: args
.filtered(OPT_require_defined
))
348 add("-include:" + StringRef(a
->getValue()));
349 for (auto *a
: args
.filtered(OPT_undefined
))
350 add("-includeoptional:" + StringRef(a
->getValue()));
351 for (auto *a
: args
.filtered(OPT_delayload
))
352 add("-delayload:" + StringRef(a
->getValue()));
354 std::vector
<StringRef
> searchPaths
;
355 for (auto *a
: args
.filtered(OPT_L
)) {
356 searchPaths
.push_back(a
->getValue());
357 add("-libpath:" + StringRef(a
->getValue()));
360 StringRef prefix
= "";
361 bool isStatic
= false;
362 for (auto *a
: args
) {
363 switch (a
->getOption().getID()) {
365 if (StringRef(a
->getValue()).endswith_lower(".def"))
366 add("-def:" + StringRef(a
->getValue()));
368 add(prefix
+ StringRef(a
->getValue()));
371 add(prefix
+ searchLibrary(a
->getValue(), searchPaths
, isStatic
));
373 case OPT_whole_archive
:
374 prefix
= "-wholearchive:";
376 case OPT_no_whole_archive
:
391 if (args
.hasArg(OPT_verbose
) || args
.hasArg(OPT__HASH_HASH_HASH
))
392 lld::outs() << llvm::join(linkArgs
, " ") << "\n";
394 if (args
.hasArg(OPT__HASH_HASH_HASH
))
397 // Repack vector of strings to vector of const char pointers for coff::link.
398 std::vector
<const char *> vec
;
399 for (const std::string
&s
: linkArgs
)
400 vec
.push_back(s
.c_str());
401 return coff::link(vec
, true, stdoutOS
, stderrOS
);