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 return *s; 147 if (Optional<std::string> s = findFile(dir, name + ".dll")) 148 return *s; 149 } 150 } 151 error("unable to find library -l" + name); 152 return ""; 153 } 154 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; 161 162 stderrOS.enable_colors(stderrOS.has_colors()); 163 164 MinGWOptTable parser; 165 opt::InputArgList args = parser.parse(argsArr.slice(1)); 166 167 if (errorCount()) 168 return false; 169 170 if (args.hasArg(OPT_help)) { 171 printHelp(argsArr[0]); 172 return true; 173 } 174 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)"); 182 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)) 186 return true; 187 if (args.hasArg(OPT_version)) 188 return true; 189 190 if (!args.hasArg(OPT_INPUT) && !args.hasArg(OPT_l)) { 191 error("no input files"); 192 return false; 193 } 194 195 std::vector<std::string> linkArgs; 196 auto add = [&](const Twine &s) { linkArgs.push_back(s.str()); }; 197 198 add("lld-link"); 199 add("-lldmingw"); 200 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)); 205 else 206 add("-entry:" + s); 207 } 208 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"; 216 StringRef subSysVer; 217 // Iterate over --{major,minor}-subsystem-version and --subsystem, and pick 218 // the version number components from the last one of them that specifies 219 // a version. 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(); 225 break; 226 case OPT_minor_subsystem_version: 227 minSubSysVer = a->getValue(); 228 break; 229 case OPT_subs: 230 std::tie(subSysName, subSysVer) = StringRef(a->getValue()).split(':'); 231 if (!subSysVer.empty()) { 232 if (subSysVer.contains('.')) 233 std::tie(majSubSysVer, minSubSysVer) = subSysVer.split('.'); 234 else 235 majSubSysVer = subSysVer; 236 } 237 break; 238 } 239 } 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); 248 } 249 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())); 268 269 if (auto *a = args.getLastArg(OPT_o)) 270 add("-out:" + StringRef(a->getValue())); 271 else if (args.hasArg(OPT_shared)) 272 add("-out:a.dll"); 273 else 274 add("-out:a.exe"); 275 276 if (auto *a = args.getLastArg(OPT_pdb)) { 277 add("-debug"); 278 StringRef v = a->getValue(); 279 if (!v.empty()) 280 add("-pdb:" + v); 281 } else if (args.hasArg(OPT_strip_debug)) { 282 add("-debug:symtab"); 283 } else if (!args.hasArg(OPT_strip_all)) { 284 add("-debug:dwarf"); 285 } 286 287 if (args.hasFlag(OPT_fatal_warnings, OPT_no_fatal_warnings, false)) 288 add("-WX"); 289 else 290 add("-WX:no"); 291 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"); 296 297 if (args.hasArg(OPT_shared)) 298 add("-dll"); 299 if (args.hasArg(OPT_verbose)) 300 add("-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)) 308 add("-kill-at"); 309 if (args.hasArg(OPT_appcontainer)) 310 add("-appcontainer"); 311 if (args.hasFlag(OPT_no_seh, OPT_disable_no_seh, false)) 312 add("-noseh"); 313 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)) 321 add("-nxcompat:no"); 322 if (args.hasFlag(OPT_disable_tsaware, OPT_tsaware, false)) 323 add("-tsaware:no"); 324 325 if (args.hasFlag(OPT_no_insert_timestamp, OPT_insert_timestamp, false)) 326 add("-timestamp:0"); 327 328 if (args.hasFlag(OPT_gc_sections, OPT_no_gc_sections, false)) 329 add("-opt:ref"); 330 else 331 add("-opt:noref"); 332 333 if (args.hasFlag(OPT_demangle, OPT_no_demangle, true)) 334 add("-demangle"); 335 else 336 add("-demangle:no"); 337 338 if (args.hasFlag(OPT_enable_auto_import, OPT_disable_auto_import, true)) 339 add("-auto-import"); 340 else 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"); 345 else 346 add("-runtime-pseudo-reloc:no"); 347 348 if (args.hasFlag(OPT_allow_multiple_definition, 349 OPT_no_allow_multiple_definition, false)) 350 add("-force:multiple"); 351 352 if (auto *a = args.getLastArg(OPT_icf)) { 353 StringRef s = a->getValue(); 354 if (s == "all") 355 add("-opt:icf"); 356 else if (s == "safe" || s == "none") 357 add("-opt:noicf"); 358 else 359 error("unknown parameter: --icf=" + s); 360 } else { 361 add("-opt:noicf"); 362 } 363 364 if (auto *a = args.getLastArg(OPT_m)) { 365 StringRef s = a->getValue(); 366 if (s == "i386pe") 367 add("-machine:x86"); 368 else if (s == "i386pep") 369 add("-machine:x64"); 370 else if (s == "thumb2pe") 371 add("-machine:arm"); 372 else if (s == "arm64pe") 373 add("-machine:arm64"); 374 else 375 error("unknown parameter: -m" + s); 376 } 377 378 for (auto *a : args.filtered(OPT_mllvm)) 379 add("-mllvm:" + StringRef(a->getValue())); 380 381 for (auto *a : args.filtered(OPT_Xlink)) 382 add(a->getValue()); 383 384 if (args.getLastArgValue(OPT_m) == "i386pe") 385 add("-alternatename:__image_base__=___ImageBase"); 386 else 387 add("-alternatename:__image_base__=__ImageBase"); 388 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())); 397 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())); 402 } 403 404 StringRef prefix = ""; 405 bool isStatic = false; 406 for (auto *a : args) { 407 switch (a->getOption().getID()) { 408 case OPT_INPUT: 409 if (StringRef(a->getValue()).endswith_insensitive(".def")) 410 add("-def:" + StringRef(a->getValue())); 411 else 412 add(prefix + StringRef(a->getValue())); 413 break; 414 case OPT_l: 415 add(prefix + searchLibrary(a->getValue(), searchPaths, isStatic)); 416 break; 417 case OPT_whole_archive: 418 prefix = "-wholearchive:"; 419 break; 420 case OPT_no_whole_archive: 421 prefix = ""; 422 break; 423 case OPT_Bstatic: 424 isStatic = true; 425 break; 426 case OPT_Bdynamic: 427 isStatic = false; 428 break; 429 } 430 } 431 432 if (errorCount()) 433 return false; 434 435 if (args.hasArg(OPT_verbose) || args.hasArg(OPT__HASH_HASH_HASH)) 436 lld::errs() << llvm::join(linkArgs, " ") << "\n"; 437 438 if (args.hasArg(OPT__HASH_HASH_HASH)) 439 return true; 440 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 446 // the right prefix. 447 vec[0] = argsArr[0]; 448 return coff::link(vec, canExitEarly, stdoutOS, stderrOS); 449 } 450