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 255 if (auto *a = args.getLastArg(OPT_o)) 256 add("-out:" + StringRef(a->getValue())); 257 else if (args.hasArg(OPT_shared)) 258 add("-out:a.dll"); 259 else 260 add("-out:a.exe"); 261 262 if (auto *a = args.getLastArg(OPT_pdb)) { 263 add("-debug"); 264 StringRef v = a->getValue(); 265 if (!v.empty()) 266 add("-pdb:" + v); 267 } else if (args.hasArg(OPT_strip_debug)) { 268 add("-debug:symtab"); 269 } else if (!args.hasArg(OPT_strip_all)) { 270 add("-debug:dwarf"); 271 } 272 273 if (args.hasArg(OPT_shared)) 274 add("-dll"); 275 if (args.hasArg(OPT_verbose)) 276 add("-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)) 284 add("-kill-at"); 285 if (args.hasArg(OPT_appcontainer)) 286 add("-appcontainer"); 287 288 if (args.getLastArgValue(OPT_m) != "thumb2pe" && 289 args.getLastArgValue(OPT_m) != "arm64pe" && !args.hasArg(OPT_dynamicbase)) 290 add("-dynamicbase:no"); 291 292 if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false)) 293 add("-timestamp:0"); 294 295 if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false)) 296 add("-opt:ref"); 297 else 298 add("-opt:noref"); 299 300 if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true)) 301 add("-auto-import"); 302 else 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"); 307 else 308 add("-runtime-pseudo-reloc:no"); 309 310 if (auto *a = args.getLastArg(OPT_icf)) { 311 StringRef s = a->getValue(); 312 if (s == "all") 313 add("-opt:icf"); 314 else if (s == "safe" || s == "none") 315 add("-opt:noicf"); 316 else 317 error("unknown parameter: --icf=" + s); 318 } else { 319 add("-opt:noicf"); 320 } 321 322 if (auto *a = args.getLastArg(OPT_m)) { 323 StringRef s = a->getValue(); 324 if (s == "i386pe") 325 add("-machine:x86"); 326 else if (s == "i386pep") 327 add("-machine:x64"); 328 else if (s == "thumb2pe") 329 add("-machine:arm"); 330 else if (s == "arm64pe") 331 add("-machine:arm64"); 332 else 333 error("unknown parameter: -m" + s); 334 } 335 336 for (auto *a : args.filtered(OPT_mllvm)) 337 add("-mllvm:" + StringRef(a->getValue())); 338 339 for (auto *a : args.filtered(OPT_Xlink)) 340 add(a->getValue()); 341 342 if (args.getLastArgValue(OPT_m) == "i386pe") 343 add("-alternatename:__image_base__=___ImageBase"); 344 else 345 add("-alternatename:__image_base__=__ImageBase"); 346 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())); 353 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())); 358 } 359 360 StringRef prefix = ""; 361 bool isStatic = false; 362 for (auto *a : args) { 363 switch (a->getOption().getID()) { 364 case OPT_INPUT: 365 if (StringRef(a->getValue()).endswith_lower(".def")) 366 add("-def:" + StringRef(a->getValue())); 367 else 368 add(prefix + StringRef(a->getValue())); 369 break; 370 case OPT_l: 371 add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic)); 372 break; 373 case OPT_whole_archive: 374 prefix = "-wholearchive:"; 375 break; 376 case OPT_no_whole_archive: 377 prefix = ""; 378 break; 379 case OPT_Bstatic: 380 isStatic = true; 381 break; 382 case OPT_Bdynamic: 383 isStatic = false; 384 break; 385 } 386 } 387 388 if (errorCount()) 389 return false; 390 391 if (args.hasArg(OPT_verbose) || args.hasArg(OPT__HASH_HASH_HASH)) 392 lld::outs() << llvm::join(linkArgs, " ") << "\n"; 393 394 if (args.hasArg(OPT__HASH_HASH_HASH)) 395 return true; 396 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); 402 } 403