xref: /openbsd/gnu/llvm/lld/MinGW/Driver.cpp (revision 73471bf0)
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.
12 //
13 // lld/MinGW is a drop-in replacement for GNU ld/MinGW.
14 //
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.
19 //
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".
23 //
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.
28 //
29 //===----------------------------------------------------------------------===//
30 
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"
47 
48 #if !defined(_MSC_VER) && !defined(__MINGW32__)
49 #include <unistd.h>
50 #endif
51 
52 using namespace lld;
53 using namespace llvm;
54 
55 // Create OptTable
56 enum {
57   OPT_INVALID = 0,
58 #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID,
59 #include "Options.inc"
60 #undef OPTION
61 };
62 
63 // Create prefix string literals used in Options.td
64 #define PREFIX(NAME, VALUE) static const char *const NAME[] = VALUE;
65 #include "Options.inc"
66 #undef PREFIX
67 
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"
74 #undef OPTION
75 };
76 
77 namespace {
78 class MinGWOptTable : public opt::OptTable {
79 public:
80   MinGWOptTable() : OptTable(infoTable, false) {}
81   opt::InputArgList parse(ArrayRef<const char *> argv);
82 };
83 } // namespace
84 
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*/);
89   lld::outs() << "\n";
90 }
91 
92 static cl::TokenizerCallback getQuotingStyle() {
93   if (Triple(sys::getProcessTriple()).getOS() == Triple::Win32)
94     return cl::TokenizeWindowsCommandLine;
95   return cl::TokenizeGNUCommandLine;
96 }
97 
98 opt::InputArgList MinGWOptTable::parse(ArrayRef<const char *> argv) {
99   unsigned missingIndex;
100   unsigned missingCount;
101 
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);
105 
106   if (missingCount)
107     error(StringRef(args.getArgString(missingIndex)) + ": missing argument");
108   for (auto *arg : args.filtered(OPT_UNKNOWN))
109     error("unknown argument: " + arg->getAsString(args));
110   return args;
111 }
112 
113 // Find a file by concatenating given paths.
114 static Optional<std::string> findFile(StringRef path1, const Twine &path2) {
115   SmallString<128> s;
116   sys::path::append(s, path1, path2);
117   if (sys::fs::exists(s))
118     return std::string(s);
119   return None;
120 }
121 
122 // This is for -lfoo. We'll look for libfoo.dll.a or libfoo.a from search paths.
123 static std::string
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)))
128         return *s;
129     error("unable to find library -l" + name);
130     return "";
131   }
132 
133   for (StringRef dir : searchPaths) {
134     if (!bStatic) {
135       if (Optional<std::string> s = findFile(dir, "lib" + name + ".dll.a"))
136         return *s;
137       if (Optional<std::string> s = findFile(dir, name + ".dll.a"))
138         return *s;
139     }
140     if (Optional<std::string> s = findFile(dir, "lib" + name + ".a"))
141       return *s;
142     if (!bStatic) {
143       if (Optional<std::string> s = findFile(dir, name + ".lib"))
144         return *s;
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");
148         return "";
149       }
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");
153         return "";
154       }
155     }
156   }
157   error("unable to find library -l" + name);
158   return "";
159 }
160 
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;
167 
168   stderrOS.enable_colors(stderrOS.has_colors());
169 
170   MinGWOptTable parser;
171   opt::InputArgList args = parser.parse(argsArr.slice(1));
172 
173   if (errorCount())
174     return false;
175 
176   if (args.hasArg(OPT_help)) {
177     printHelp(argsArr[0]);
178     return true;
179   }
180 
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)");
188 
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))
192     return true;
193   if (args.hasArg(OPT_version))
194     return true;
195 
196   if (!args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l)) {
197     error("no input files");
198     return false;
199   }
200 
201   std::vector<std::string> linkArgs;
202   auto add = [&](const Twine &s) { linkArgs.push_back(s.str()); };
203 
204   add("lld-link");
205   add("-lldmingw");
206 
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));
211     else
212       add("-entry:" + s);
213   }
214 
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()));
238   }
239 
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()));
254   if (auto *a = args.getLastArg(OPT_file_alignment))
255     add("-filealign:" + StringRef(a->getValue()));
256   if (auto *a = args.getLastArg(OPT_section_alignment))
257     add("-align:" + StringRef(a->getValue()));
258 
259   if (auto *a = args.getLastArg(OPT_o))
260     add("-out:" + StringRef(a->getValue()));
261   else if (args.hasArg(OPT_shared))
262     add("-out:a.dll");
263   else
264     add("-out:a.exe");
265 
266   if (auto *a = args.getLastArg(OPT_pdb)) {
267     add("-debug");
268     StringRef v = a->getValue();
269     if (!v.empty())
270       add("-pdb:" + v);
271   } else if (args.hasArg(OPT_strip_debug)) {
272     add("-debug:symtab");
273   } else if (!args.hasArg(OPT_strip_all)) {
274     add("-debug:dwarf");
275   }
276 
277   if (args.hasArg(OPT_shared))
278     add("-dll");
279   if (args.hasArg(OPT_verbose))
280     add("-verbose");
281   if (args.hasArg(OPT_exclude_all_symbols))
282     add("-exclude-all-symbols");
283   if (args.hasArg(OPT_export_all_symbols))
284     add("-export-all-symbols");
285   if (args.hasArg(OPT_large_address_aware))
286     add("-largeaddressaware");
287   if (args.hasArg(OPT_kill_at))
288     add("-kill-at");
289   if (args.hasArg(OPT_appcontainer))
290     add("-appcontainer");
291   if (args.hasArg(OPT_no_seh))
292     add("-noseh");
293 
294   if (args.getLastArgValue(OPT_m) != "thumb2pe" &&
295       args.getLastArgValue(OPT_m) != "arm64pe" && !args.hasArg(OPT_dynamicbase))
296     add("-dynamicbase:no");
297 
298   if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false))
299     add("-timestamp:0");
300 
301   if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false))
302     add("-opt:ref");
303   else
304     add("-opt:noref");
305 
306   if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true))
307     add("-auto-import");
308   else
309     add("-auto-import:no");
310   if (args.hasFlag(OPT_enable_runtime_pseudo_reloc,
311                    OPT_disable_runtime_pseudo_reloc, true))
312     add("-runtime-pseudo-reloc");
313   else
314     add("-runtime-pseudo-reloc:no");
315 
316   if (auto *a = args.getLastArg(OPT_icf)) {
317     StringRef s = a->getValue();
318     if (s == "all")
319       add("-opt:icf");
320     else if (s == "safe" || s == "none")
321       add("-opt:noicf");
322     else
323       error("unknown parameter: --icf=" + s);
324   } else {
325     add("-opt:noicf");
326   }
327 
328   if (auto *a = args.getLastArg(OPT_m)) {
329     StringRef s = a->getValue();
330     if (s == "i386pe")
331       add("-machine:x86");
332     else if (s == "i386pep")
333       add("-machine:x64");
334     else if (s == "thumb2pe")
335       add("-machine:arm");
336     else if (s == "arm64pe")
337       add("-machine:arm64");
338     else
339       error("unknown parameter: -m" + s);
340   }
341 
342   for (auto *a : args.filtered(OPT_mllvm))
343     add("-mllvm:" + StringRef(a->getValue()));
344 
345   for (auto *a : args.filtered(OPT_Xlink))
346     add(a->getValue());
347 
348   if (args.getLastArgValue(OPT_m) == "i386pe")
349     add("-alternatename:__image_base__=___ImageBase");
350   else
351     add("-alternatename:__image_base__=__ImageBase");
352 
353   for (auto *a : args.filtered(OPT_require_defined))
354     add("-include:" + StringRef(a->getValue()));
355   for (auto *a : args.filtered(OPT_undefined))
356     add("-includeoptional:" + StringRef(a->getValue()));
357   for (auto *a : args.filtered(OPT_delayload))
358     add("-delayload:" + StringRef(a->getValue()));
359 
360   std::vector<StringRef> searchPaths;
361   for (auto *a : args.filtered(OPT_L)) {
362     searchPaths.push_back(a->getValue());
363     add("-libpath:" + StringRef(a->getValue()));
364   }
365 
366   StringRef prefix = "";
367   bool isStatic = false;
368   for (auto *a : args) {
369     switch (a->getOption().getID()) {
370     case OPT_INPUT:
371       if (StringRef(a->getValue()).endswith_lower(".def"))
372         add("-def:" + StringRef(a->getValue()));
373       else
374         add(prefix + StringRef(a->getValue()));
375       break;
376     case OPT_l:
377       add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic));
378       break;
379     case OPT_whole_archive:
380       prefix = "-wholearchive:";
381       break;
382     case OPT_no_whole_archive:
383       prefix = "";
384       break;
385     case OPT_Bstatic:
386       isStatic = true;
387       break;
388     case OPT_Bdynamic:
389       isStatic = false;
390       break;
391     }
392   }
393 
394   if (errorCount())
395     return false;
396 
397   if (args.hasArg(OPT_verbose) || args.hasArg(OPT__HASH_HASH_HASH))
398     lld::outs() << llvm::join(linkArgs, " ") << "\n";
399 
400   if (args.hasArg(OPT__HASH_HASH_HASH))
401     return true;
402 
403   // Repack vector of strings to vector of const char pointers for coff::link.
404   std::vector<const char *> vec;
405   for (const std::string &s : linkArgs)
406     vec.push_back(s.c_str());
407   return coff::link(vec, true, stdoutOS, stderrOS);
408 }
409