[SLP]Fix PR104422: Wrong value truncation
[llvm-project.git] / lld / MinGW / Driver.cpp
blobc7d7b9cfca386f5abe76fe9c48410ca569a1fbe0
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 using namespace lld;
50 using namespace llvm::opt;
51 using namespace llvm;
53 // Create OptTable
54 enum {
55 OPT_INVALID = 0,
56 #define OPTION(...) LLVM_MAKE_OPT_ID(__VA_ARGS__),
57 #include "Options.inc"
58 #undef OPTION
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"
67 #undef PREFIX
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, \
73 VALUES) \
74 {PREFIX, \
75 NAME, \
76 HELPTEXT, \
77 HELPTEXTSFORVARIANTS, \
78 METAVAR, \
79 OPT_##ID, \
80 opt::Option::KIND##Class, \
81 PARAM, \
82 FLAGS, \
83 VISIBILITY, \
84 OPT_##GROUP, \
85 OPT_##ALIAS, \
86 ALIASARGS, \
87 VALUES},
88 #include "Options.inc"
89 #undef OPTION
92 namespace {
93 class MinGWOptTable : public opt::GenericOptTable {
94 public:
95 MinGWOptTable() : opt::GenericOptTable(infoTable, false) {}
96 opt::InputArgList parse(ArrayRef<const char *> argv);
98 } // namespace
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*/);
104 lld::outs() << "\n";
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);
121 if (missingCount)
122 error(StringRef(args.getArgString(missingIndex)) + ": missing argument");
123 for (auto *arg : args.filtered(OPT_UNKNOWN))
124 error("unknown argument: " + arg->getAsString(args));
125 return args;
128 // Find a file by concatenating given paths.
129 static std::optional<std::string> findFile(StringRef path1,
130 const Twine &path2) {
131 SmallString<128> s;
132 sys::path::append(s, path1, path2);
133 if (sys::fs::exists(s))
134 return std::string(s);
135 return std::nullopt;
138 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
139 static std::string
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)))
144 return *s;
145 error("unable to find library -l" + name);
146 return "";
149 for (StringRef dir : searchPaths) {
150 if (!bStatic) {
151 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll.a"))
152 return *s;
153 if (std::optional<std::string> s = findFile(dir, name + ".dll.a"))
154 return *s;
156 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".a"))
157 return *s;
158 if (std::optional<std::string> s = findFile(dir, name + ".lib"))
159 return *s;
160 if (!bStatic) {
161 if (std::optional<std::string> s = findFile(dir, "lib" + name + ".dll"))
162 return *s;
163 if (std::optional<std::string> s = findFile(dir, name + ".dll"))
164 return *s;
167 error("unable to find library -l" + name);
168 return "";
171 namespace lld {
172 namespace coff {
173 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
174 llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput);
177 namespace mingw {
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));
188 if (errorCount())
189 return false;
191 if (args.hasArg(OPT_help)) {
192 printHelp(argsArr[0]);
193 return true;
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))
207 return true;
208 if (args.hasArg(OPT_version))
209 return true;
211 if (!args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l)) {
212 error("no input files");
213 return false;
216 std::vector<std::string> linkArgs;
217 auto add = [&](const Twine &s) { linkArgs.push_back(s.str()); };
219 add("lld-link");
220 add("-lldmingw");
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));
226 else if (!s.empty())
227 add("-entry:" + s);
228 else
229 add("-noentry");
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";
239 StringRef subSysVer;
240 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick
241 // the version number components from the last one of them that specifies
242 // a version.
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();
248 break;
249 case OPT_minor_subsystem_version:
250 minSubSysVer = a->getValue();
251 break;
252 case OPT_subs:
253 std::tie(subSysName, subSysVer) = StringRef(a->getValue()).split(':');
254 if (!subSysVer.empty()) {
255 if (subSysVer.contains('.'))
256 std::tie(majSubSysVer, minSubSysVer) = subSysVer.split('.');
257 else
258 majSubSysVer = subSysVer;
260 break;
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))
297 add("-out:a.dll");
298 else
299 add("-out:a.exe");
301 if (auto *a = args.getLastArg(OPT_pdb)) {
302 add("-debug");
303 StringRef v = a->getValue();
304 if (!v.empty())
305 add("-pdb:" + v);
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)) {
314 add("-debug:dwarf");
316 if (auto *a = args.getLastArg(OPT_build_id)) {
317 StringRef v = a->getValue();
318 if (v == "none")
319 add("-build-id:no");
320 else {
321 if (!v.empty())
322 warn("unsupported build id hashing: " + v + ", using default hashing.");
323 add("-build-id");
325 } else {
326 if (args.hasArg(OPT_strip_debug) || args.hasArg(OPT_strip_all))
327 add("-build-id:no");
328 else
329 add("-build-id");
332 if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false))
333 add("-WX");
334 else
335 add("-WX:no");
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))
343 add("-dll");
344 if (args.hasArg(OPT_verbose))
345 add("-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))
353 add("-kill-at");
354 if (args.hasArg(OPT_appcontainer))
355 add("-appcontainer");
356 if (args.hasFlag(OPT_no_seh, OPT_disable_no_seh, false))
357 add("-noseh");
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))
367 add("-nxcompat:no");
368 if (args.hasFlag(OPT_disable_tsaware, OPT_tsaware, false))
369 add("-tsaware:no");
371 if (args.hasFlag(OPT_disable_reloc_section, OPT_enable_reloc_section, false))
372 add("-fixed");
374 if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false))
375 add("-timestamp:0");
377 if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false))
378 add("-opt:ref");
379 else
380 add("-opt:noref");
382 if (args.hasFlag(OPT_demangle, OPT_no_demangle, true))
383 add("-demangle");
384 else
385 add("-demangle:no");
387 if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true))
388 add("-auto-import");
389 else
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");
394 else
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();
403 if (s == "all")
404 add("-opt:icf");
405 else if (s == "safe")
406 add("-opt:safeicf");
407 else if (s == "none")
408 add("-opt:noicf");
409 else
410 error("unknown parameter: --icf=" + s);
411 } else {
412 add("-opt:noicf");
415 if (auto *a = args.getLastArg(OPT_m)) {
416 StringRef s = a->getValue();
417 if (s == "i386pe")
418 add("-machine:x86");
419 else if (s == "i386pep")
420 add("-machine:x64");
421 else if (s == "thumb2pe")
422 add("-machine:arm");
423 else if (s == "arm64pe")
424 add("-machine:arm64");
425 else if (s == "arm64ecpe")
426 add("-machine:arm64ec");
427 else
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");
434 else
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)) {
443 int n;
444 StringRef s = a->getValue();
445 if (s.getAsInteger(10, n))
446 error(a->getSpelling() + ": number expected, but got " + s);
447 else
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))
472 add("-lldemit: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() +
504 "'");
507 for (auto *a : args.filtered(OPT_Xlink))
508 add(a->getValue());
510 if (args.getLastArgValue(OPT_m) == "i386pe")
511 add("-alternatename:__image_base__=___ImageBase");
512 else
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()) {
536 case OPT_INPUT:
537 if (StringRef(a->getValue()).ends_with_insensitive(".def"))
538 add("-def:" + StringRef(a->getValue()));
539 else
540 add(prefix + StringRef(a->getValue()));
541 break;
542 case OPT_l:
543 add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic));
544 break;
545 case OPT_whole_archive:
546 prefix = "-wholearchive:";
547 break;
548 case OPT_no_whole_archive:
549 prefix = "";
550 break;
551 case OPT_Bstatic:
552 isStatic = true;
553 break;
554 case OPT_Bdynamic:
555 isStatic = false;
556 break;
560 if (errorCount())
561 return false;
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))
567 return true;
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
574 // the right prefix.
575 vec[0] = argsArr[0];
577 // The context will be re-created in the COFF driver.
578 lld::CommonLinkerContext::destroy();
580 return coff::link(vec, stdoutOS, stderrOS, exitEarly, disableOutput);
582 } // namespace mingw
583 } // namespace lld