1 //===- 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 #include "Driver.h" 10 #include "COFFLinkerContext.h" 11 #include "Config.h" 12 #include "DebugTypes.h" 13 #include "ICF.h" 14 #include "InputFiles.h" 15 #include "MarkLive.h" 16 #include "MinGW.h" 17 #include "SymbolTable.h" 18 #include "Symbols.h" 19 #include "Writer.h" 20 #include "lld/Common/Args.h" 21 #include "lld/Common/Driver.h" 22 #include "lld/Common/ErrorHandler.h" 23 #include "lld/Common/Filesystem.h" 24 #include "lld/Common/Memory.h" 25 #include "lld/Common/Timer.h" 26 #include "lld/Common/Version.h" 27 #include "llvm/ADT/Optional.h" 28 #include "llvm/ADT/StringSwitch.h" 29 #include "llvm/BinaryFormat/Magic.h" 30 #include "llvm/Config/llvm-config.h" 31 #include "llvm/LTO/LTO.h" 32 #include "llvm/Object/ArchiveWriter.h" 33 #include "llvm/Object/COFFImportFile.h" 34 #include "llvm/Object/COFFModuleDefinition.h" 35 #include "llvm/Object/WindowsMachineFlag.h" 36 #include "llvm/Option/Arg.h" 37 #include "llvm/Option/ArgList.h" 38 #include "llvm/Option/Option.h" 39 #include "llvm/Support/BinaryStreamReader.h" 40 #include "llvm/Support/CommandLine.h" 41 #include "llvm/Support/Debug.h" 42 #include "llvm/Support/LEB128.h" 43 #include "llvm/Support/MathExtras.h" 44 #include "llvm/Support/Parallel.h" 45 #include "llvm/Support/Path.h" 46 #include "llvm/Support/Process.h" 47 #include "llvm/Support/TarWriter.h" 48 #include "llvm/Support/TargetSelect.h" 49 #include "llvm/Support/raw_ostream.h" 50 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 51 #include <algorithm> 52 #include <future> 53 #include <memory> 54 55 using namespace llvm; 56 using namespace llvm::object; 57 using namespace llvm::COFF; 58 using namespace llvm::sys; 59 60 namespace lld { 61 namespace coff { 62 63 Configuration *config; 64 LinkerDriver *driver; 65 66 bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS, 67 raw_ostream &stderrOS) { 68 lld::stdoutOS = &stdoutOS; 69 lld::stderrOS = &stderrOS; 70 71 errorHandler().cleanupCallback = []() { 72 freeArena(); 73 }; 74 75 errorHandler().logName = args::getFilenameWithoutExe(args[0]); 76 errorHandler().errorLimitExceededMsg = 77 "too many errors emitted, stopping now" 78 " (use /errorlimit:0 to see all errors)"; 79 errorHandler().exitEarly = canExitEarly; 80 stderrOS.enable_colors(stderrOS.has_colors()); 81 82 COFFLinkerContext ctx; 83 config = make<Configuration>(); 84 driver = make<LinkerDriver>(ctx); 85 86 driver->linkerMain(args); 87 88 // Call exit() if we can to avoid calling destructors. 89 if (canExitEarly) 90 exitLld(errorCount() ? 1 : 0); 91 92 bool ret = errorCount() == 0; 93 if (!canExitEarly) 94 errorHandler().reset(); 95 return ret; 96 } 97 98 // Parse options of the form "old;new". 99 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 100 unsigned id) { 101 auto *arg = args.getLastArg(id); 102 if (!arg) 103 return {"", ""}; 104 105 StringRef s = arg->getValue(); 106 std::pair<StringRef, StringRef> ret = s.split(';'); 107 if (ret.second.empty()) 108 error(arg->getSpelling() + " expects 'old;new' format, but got " + s); 109 return ret; 110 } 111 112 // Drop directory components and replace extension with 113 // ".exe", ".dll" or ".sys". 114 static std::string getOutputPath(StringRef path) { 115 StringRef ext = ".exe"; 116 if (config->dll) 117 ext = ".dll"; 118 else if (config->driver) 119 ext = ".sys"; 120 121 return (sys::path::stem(path) + ext).str(); 122 } 123 124 // Returns true if S matches /crtend.?\.o$/. 125 static bool isCrtend(StringRef s) { 126 if (!s.endswith(".o")) 127 return false; 128 s = s.drop_back(2); 129 if (s.endswith("crtend")) 130 return true; 131 return !s.empty() && s.drop_back().endswith("crtend"); 132 } 133 134 // ErrorOr is not default constructible, so it cannot be used as the type 135 // parameter of a future. 136 // FIXME: We could open the file in createFutureForFile and avoid needing to 137 // return an error here, but for the moment that would cost us a file descriptor 138 // (a limited resource on Windows) for the duration that the future is pending. 139 using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 140 141 // Create a std::future that opens and maps a file using the best strategy for 142 // the host platform. 143 static std::future<MBErrPair> createFutureForFile(std::string path) { 144 #if _WIN64 145 // On Windows, file I/O is relatively slow so it is best to do this 146 // asynchronously. But 32-bit has issues with potentially launching tons 147 // of threads 148 auto strategy = std::launch::async; 149 #else 150 auto strategy = std::launch::deferred; 151 #endif 152 return std::async(strategy, [=]() { 153 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 154 /*RequiresNullTerminator=*/false); 155 if (!mbOrErr) 156 return MBErrPair{nullptr, mbOrErr.getError()}; 157 return MBErrPair{std::move(*mbOrErr), std::error_code()}; 158 }); 159 } 160 161 // Symbol names are mangled by prepending "_" on x86. 162 static StringRef mangle(StringRef sym) { 163 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN); 164 if (config->machine == I386) 165 return saver.save("_" + sym); 166 return sym; 167 } 168 169 bool LinkerDriver::findUnderscoreMangle(StringRef sym) { 170 Symbol *s = ctx.symtab.findMangle(mangle(sym)); 171 return s && !isa<Undefined>(s); 172 } 173 174 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { 175 MemoryBufferRef mbref = *mb; 176 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership 177 178 if (driver->tar) 179 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()), 180 mbref.getBuffer()); 181 return mbref; 182 } 183 184 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, 185 bool wholeArchive, bool lazy) { 186 StringRef filename = mb->getBufferIdentifier(); 187 188 MemoryBufferRef mbref = takeBuffer(std::move(mb)); 189 filePaths.push_back(filename); 190 191 // File type is detected by contents, not by file extension. 192 switch (identify_magic(mbref.getBuffer())) { 193 case file_magic::windows_resource: 194 resources.push_back(mbref); 195 break; 196 case file_magic::archive: 197 if (wholeArchive) { 198 std::unique_ptr<Archive> file = 199 CHECK(Archive::create(mbref), filename + ": failed to parse archive"); 200 Archive *archive = file.get(); 201 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 202 203 int memberIndex = 0; 204 for (MemoryBufferRef m : getArchiveMembers(archive)) 205 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++); 206 return; 207 } 208 ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref)); 209 break; 210 case file_magic::bitcode: 211 if (lazy) 212 ctx.symtab.addFile(make<LazyObjFile>(ctx, mbref)); 213 else 214 ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0)); 215 break; 216 case file_magic::coff_object: 217 case file_magic::coff_import_library: 218 if (lazy) 219 ctx.symtab.addFile(make<LazyObjFile>(ctx, mbref)); 220 else 221 ctx.symtab.addFile(make<ObjFile>(ctx, mbref)); 222 break; 223 case file_magic::pdb: 224 ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref)); 225 break; 226 case file_magic::coff_cl_gl_object: 227 error(filename + ": is not a native COFF file. Recompile without /GL"); 228 break; 229 case file_magic::pecoff_executable: 230 if (config->mingw) { 231 ctx.symtab.addFile(make<DLLFile>(ctx, mbref)); 232 break; 233 } 234 if (filename.endswith_insensitive(".dll")) { 235 error(filename + ": bad file type. Did you specify a DLL instead of an " 236 "import library?"); 237 break; 238 } 239 LLVM_FALLTHROUGH; 240 default: 241 error(mbref.getBufferIdentifier() + ": unknown file type"); 242 break; 243 } 244 } 245 246 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 247 auto future = std::make_shared<std::future<MBErrPair>>( 248 createFutureForFile(std::string(path))); 249 std::string pathStr = std::string(path); 250 enqueueTask([=]() { 251 auto mbOrErr = future->get(); 252 if (mbOrErr.second) { 253 std::string msg = 254 "could not open '" + pathStr + "': " + mbOrErr.second.message(); 255 // Check if the filename is a typo for an option flag. OptTable thinks 256 // that all args that are not known options and that start with / are 257 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 258 // the option `/nodefaultlib` than a reference to a file in the root 259 // directory. 260 std::string nearest; 261 if (optTable.findNearest(pathStr, nearest) > 1) 262 error(msg); 263 else 264 error(msg + "; did you mean '" + nearest + "'"); 265 } else 266 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 267 }); 268 } 269 270 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 271 StringRef parentName, 272 uint64_t offsetInArchive) { 273 file_magic magic = identify_magic(mb.getBuffer()); 274 if (magic == file_magic::coff_import_library) { 275 InputFile *imp = make<ImportFile>(ctx, mb); 276 imp->parentName = parentName; 277 ctx.symtab.addFile(imp); 278 return; 279 } 280 281 InputFile *obj; 282 if (magic == file_magic::coff_object) { 283 obj = make<ObjFile>(ctx, mb); 284 } else if (magic == file_magic::bitcode) { 285 obj = make<BitcodeFile>(ctx, mb, parentName, offsetInArchive); 286 } else { 287 error("unknown file type: " + mb.getBufferIdentifier()); 288 return; 289 } 290 291 obj->parentName = parentName; 292 ctx.symtab.addFile(obj); 293 log("Loaded " + toString(obj) + " for " + symName); 294 } 295 296 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 297 const Archive::Symbol &sym, 298 StringRef parentName) { 299 300 auto reportBufferError = [=](Error &&e, StringRef childName) { 301 fatal("could not get the buffer for the member defining symbol " + 302 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " + 303 toString(std::move(e))); 304 }; 305 306 if (!c.getParent()->isThin()) { 307 uint64_t offsetInArchive = c.getChildOffset(); 308 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 309 if (!mbOrErr) 310 reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 311 MemoryBufferRef mb = mbOrErr.get(); 312 enqueueTask([=]() { 313 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName, 314 offsetInArchive); 315 }); 316 return; 317 } 318 319 std::string childName = CHECK( 320 c.getFullName(), 321 "could not get the filename for the member defining symbol " + 322 toCOFFString(sym)); 323 auto future = std::make_shared<std::future<MBErrPair>>( 324 createFutureForFile(childName)); 325 enqueueTask([=]() { 326 auto mbOrErr = future->get(); 327 if (mbOrErr.second) 328 reportBufferError(errorCodeToError(mbOrErr.second), childName); 329 // Pass empty string as archive name so that the original filename is 330 // used as the buffer identifier. 331 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 332 toCOFFString(sym), "", /*OffsetInArchive=*/0); 333 }); 334 } 335 336 static bool isDecorated(StringRef sym) { 337 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 338 (!config->mingw && sym.contains('@')); 339 } 340 341 // Parses .drectve section contents and returns a list of files 342 // specified by /defaultlib. 343 void LinkerDriver::parseDirectives(InputFile *file) { 344 StringRef s = file->getDirectives(); 345 if (s.empty()) 346 return; 347 348 log("Directives: " + toString(file) + ": " + s); 349 350 ArgParser parser; 351 // .drectve is always tokenized using Windows shell rules. 352 // /EXPORT: option can appear too many times, processing in fastpath. 353 ParsedDirectives directives = parser.parseDirectives(s); 354 355 for (StringRef e : directives.exports) { 356 // If a common header file contains dllexported function 357 // declarations, many object files may end up with having the 358 // same /EXPORT options. In order to save cost of parsing them, 359 // we dedup them first. 360 if (!directivesExports.insert(e).second) 361 continue; 362 363 Export exp = parseExport(e); 364 if (config->machine == I386 && config->mingw) { 365 if (!isDecorated(exp.name)) 366 exp.name = saver.save("_" + exp.name); 367 if (!exp.extName.empty() && !isDecorated(exp.extName)) 368 exp.extName = saver.save("_" + exp.extName); 369 } 370 exp.directives = true; 371 config->exports.push_back(exp); 372 } 373 374 // Handle /include: in bulk. 375 for (StringRef inc : directives.includes) 376 addUndefined(inc); 377 378 // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160 379 for (auto *arg : directives.args) { 380 switch (arg->getOption().getID()) { 381 case OPT_aligncomm: 382 parseAligncomm(arg->getValue()); 383 break; 384 case OPT_alternatename: 385 parseAlternateName(arg->getValue()); 386 break; 387 case OPT_defaultlib: 388 if (Optional<StringRef> path = findLib(arg->getValue())) 389 enqueuePath(*path, false, false); 390 break; 391 case OPT_entry: 392 config->entry = addUndefined(mangle(arg->getValue())); 393 break; 394 case OPT_failifmismatch: 395 checkFailIfMismatch(arg->getValue(), file); 396 break; 397 case OPT_incl: 398 addUndefined(arg->getValue()); 399 break; 400 case OPT_manifestdependency: 401 config->manifestDependencies.insert(arg->getValue()); 402 break; 403 case OPT_merge: 404 parseMerge(arg->getValue()); 405 break; 406 case OPT_nodefaultlib: 407 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 408 break; 409 case OPT_section: 410 parseSection(arg->getValue()); 411 break; 412 case OPT_stack: 413 parseNumbers(arg->getValue(), &config->stackReserve, 414 &config->stackCommit); 415 break; 416 case OPT_subsystem: { 417 bool gotVersion = false; 418 parseSubsystem(arg->getValue(), &config->subsystem, 419 &config->majorSubsystemVersion, 420 &config->minorSubsystemVersion, &gotVersion); 421 if (gotVersion) { 422 config->majorOSVersion = config->majorSubsystemVersion; 423 config->minorOSVersion = config->minorSubsystemVersion; 424 } 425 break; 426 } 427 // Only add flags here that link.exe accepts in 428 // `#pragma comment(linker, "/flag")`-generated sections. 429 case OPT_editandcontinue: 430 case OPT_guardsym: 431 case OPT_throwingnew: 432 break; 433 default: 434 error(arg->getSpelling() + " is not allowed in .drectve"); 435 } 436 } 437 } 438 439 // Find file from search paths. You can omit ".obj", this function takes 440 // care of that. Note that the returned path is not guaranteed to exist. 441 StringRef LinkerDriver::doFindFile(StringRef filename) { 442 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 443 if (hasPathSep) 444 return filename; 445 bool hasExt = filename.contains('.'); 446 for (StringRef dir : searchPaths) { 447 SmallString<128> path = dir; 448 sys::path::append(path, filename); 449 if (sys::fs::exists(path.str())) 450 return saver.save(path.str()); 451 if (!hasExt) { 452 path.append(".obj"); 453 if (sys::fs::exists(path.str())) 454 return saver.save(path.str()); 455 } 456 } 457 return filename; 458 } 459 460 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 461 sys::fs::UniqueID ret; 462 if (sys::fs::getUniqueID(path, ret)) 463 return None; 464 return ret; 465 } 466 467 // Resolves a file path. This never returns the same path 468 // (in that case, it returns None). 469 Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 470 StringRef path = doFindFile(filename); 471 472 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 473 bool seen = !visitedFiles.insert(*id).second; 474 if (seen) 475 return None; 476 } 477 478 if (path.endswith_insensitive(".lib")) 479 visitedLibs.insert(std::string(sys::path::filename(path))); 480 return path; 481 } 482 483 // MinGW specific. If an embedded directive specified to link to 484 // foo.lib, but it isn't found, try libfoo.a instead. 485 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 486 if (filename.contains('/') || filename.contains('\\')) 487 return filename; 488 489 SmallString<128> s = filename; 490 sys::path::replace_extension(s, ".a"); 491 StringRef libName = saver.save("lib" + s.str()); 492 return doFindFile(libName); 493 } 494 495 // Find library file from search path. 496 StringRef LinkerDriver::doFindLib(StringRef filename) { 497 // Add ".lib" to Filename if that has no file extension. 498 bool hasExt = filename.contains('.'); 499 if (!hasExt) 500 filename = saver.save(filename + ".lib"); 501 StringRef ret = doFindFile(filename); 502 // For MinGW, if the find above didn't turn up anything, try 503 // looking for a MinGW formatted library name. 504 if (config->mingw && ret == filename) 505 return doFindLibMinGW(filename); 506 return ret; 507 } 508 509 // Resolves a library path. /nodefaultlib options are taken into 510 // consideration. This never returns the same path (in that case, 511 // it returns None). 512 Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 513 if (config->noDefaultLibAll) 514 return None; 515 if (!visitedLibs.insert(filename.lower()).second) 516 return None; 517 518 StringRef path = doFindLib(filename); 519 if (config->noDefaultLibs.count(path.lower())) 520 return None; 521 522 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 523 if (!visitedFiles.insert(*id).second) 524 return None; 525 return path; 526 } 527 528 // Parses LIB environment which contains a list of search paths. 529 void LinkerDriver::addLibSearchPaths() { 530 Optional<std::string> envOpt = Process::GetEnv("LIB"); 531 if (!envOpt.hasValue()) 532 return; 533 StringRef env = saver.save(*envOpt); 534 while (!env.empty()) { 535 StringRef path; 536 std::tie(path, env) = env.split(';'); 537 searchPaths.push_back(path); 538 } 539 } 540 541 Symbol *LinkerDriver::addUndefined(StringRef name) { 542 Symbol *b = ctx.symtab.addUndefined(name); 543 if (!b->isGCRoot) { 544 b->isGCRoot = true; 545 config->gcroot.push_back(b); 546 } 547 return b; 548 } 549 550 StringRef LinkerDriver::mangleMaybe(Symbol *s) { 551 // If the plain symbol name has already been resolved, do nothing. 552 Undefined *unmangled = dyn_cast<Undefined>(s); 553 if (!unmangled) 554 return ""; 555 556 // Otherwise, see if a similar, mangled symbol exists in the symbol table. 557 Symbol *mangled = ctx.symtab.findMangle(unmangled->getName()); 558 if (!mangled) 559 return ""; 560 561 // If we find a similar mangled symbol, make this an alias to it and return 562 // its name. 563 log(unmangled->getName() + " aliased to " + mangled->getName()); 564 unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName()); 565 return mangled->getName(); 566 } 567 568 // Windows specific -- find default entry point name. 569 // 570 // There are four different entry point functions for Windows executables, 571 // each of which corresponds to a user-defined "main" function. This function 572 // infers an entry point from a user-defined "main" function. 573 StringRef LinkerDriver::findDefaultEntry() { 574 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 575 "must handle /subsystem before calling this"); 576 577 if (config->mingw) 578 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 579 ? "WinMainCRTStartup" 580 : "mainCRTStartup"); 581 582 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 583 if (findUnderscoreMangle("wWinMain")) { 584 if (!findUnderscoreMangle("WinMain")) 585 return mangle("wWinMainCRTStartup"); 586 warn("found both wWinMain and WinMain; using latter"); 587 } 588 return mangle("WinMainCRTStartup"); 589 } 590 if (findUnderscoreMangle("wmain")) { 591 if (!findUnderscoreMangle("main")) 592 return mangle("wmainCRTStartup"); 593 warn("found both wmain and main; using latter"); 594 } 595 return mangle("mainCRTStartup"); 596 } 597 598 WindowsSubsystem LinkerDriver::inferSubsystem() { 599 if (config->dll) 600 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 601 if (config->mingw) 602 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 603 // Note that link.exe infers the subsystem from the presence of these 604 // functions even if /entry: or /nodefaultlib are passed which causes them 605 // to not be called. 606 bool haveMain = findUnderscoreMangle("main"); 607 bool haveWMain = findUnderscoreMangle("wmain"); 608 bool haveWinMain = findUnderscoreMangle("WinMain"); 609 bool haveWWinMain = findUnderscoreMangle("wWinMain"); 610 if (haveMain || haveWMain) { 611 if (haveWinMain || haveWWinMain) { 612 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 613 (haveWinMain ? "WinMain" : "wWinMain") + 614 "; defaulting to /subsystem:console"); 615 } 616 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 617 } 618 if (haveWinMain || haveWWinMain) 619 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 620 return IMAGE_SUBSYSTEM_UNKNOWN; 621 } 622 623 static uint64_t getDefaultImageBase() { 624 if (config->is64()) 625 return config->dll ? 0x180000000 : 0x140000000; 626 return config->dll ? 0x10000000 : 0x400000; 627 } 628 629 static std::string rewritePath(StringRef s) { 630 if (fs::exists(s)) 631 return relativeToRoot(s); 632 return std::string(s); 633 } 634 635 // Reconstructs command line arguments so that so that you can re-run 636 // the same command with the same inputs. This is for --reproduce. 637 static std::string createResponseFile(const opt::InputArgList &args, 638 ArrayRef<StringRef> filePaths, 639 ArrayRef<StringRef> searchPaths) { 640 SmallString<0> data; 641 raw_svector_ostream os(data); 642 643 for (auto *arg : args) { 644 switch (arg->getOption().getID()) { 645 case OPT_linkrepro: 646 case OPT_reproduce: 647 case OPT_INPUT: 648 case OPT_defaultlib: 649 case OPT_libpath: 650 break; 651 case OPT_call_graph_ordering_file: 652 case OPT_deffile: 653 case OPT_manifestinput: 654 case OPT_natvis: 655 os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 656 break; 657 case OPT_order: { 658 StringRef orderFile = arg->getValue(); 659 orderFile.consume_front("@"); 660 os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 661 break; 662 } 663 case OPT_pdbstream: { 664 const std::pair<StringRef, StringRef> nameFile = 665 StringRef(arg->getValue()).split("="); 666 os << arg->getSpelling() << nameFile.first << '=' 667 << quote(rewritePath(nameFile.second)) << '\n'; 668 break; 669 } 670 case OPT_implib: 671 case OPT_manifestfile: 672 case OPT_pdb: 673 case OPT_pdbstripped: 674 case OPT_out: 675 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 676 break; 677 default: 678 os << toString(*arg) << "\n"; 679 } 680 } 681 682 for (StringRef path : searchPaths) { 683 std::string relPath = relativeToRoot(path); 684 os << "/libpath:" << quote(relPath) << "\n"; 685 } 686 687 for (StringRef path : filePaths) 688 os << quote(relativeToRoot(path)) << "\n"; 689 690 return std::string(data.str()); 691 } 692 693 enum class DebugKind { 694 Unknown, 695 None, 696 Full, 697 FastLink, 698 GHash, 699 NoGHash, 700 Dwarf, 701 Symtab 702 }; 703 704 static DebugKind parseDebugKind(const opt::InputArgList &args) { 705 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 706 if (!a) 707 return DebugKind::None; 708 if (a->getNumValues() == 0) 709 return DebugKind::Full; 710 711 DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 712 .CaseLower("none", DebugKind::None) 713 .CaseLower("full", DebugKind::Full) 714 .CaseLower("fastlink", DebugKind::FastLink) 715 // LLD extensions 716 .CaseLower("ghash", DebugKind::GHash) 717 .CaseLower("noghash", DebugKind::NoGHash) 718 .CaseLower("dwarf", DebugKind::Dwarf) 719 .CaseLower("symtab", DebugKind::Symtab) 720 .Default(DebugKind::Unknown); 721 722 if (debug == DebugKind::FastLink) { 723 warn("/debug:fastlink unsupported; using /debug:full"); 724 return DebugKind::Full; 725 } 726 if (debug == DebugKind::Unknown) { 727 error("/debug: unknown option: " + Twine(a->getValue())); 728 return DebugKind::None; 729 } 730 return debug; 731 } 732 733 static unsigned parseDebugTypes(const opt::InputArgList &args) { 734 unsigned debugTypes = static_cast<unsigned>(DebugType::None); 735 736 if (auto *a = args.getLastArg(OPT_debugtype)) { 737 SmallVector<StringRef, 3> types; 738 StringRef(a->getValue()) 739 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 740 741 for (StringRef type : types) { 742 unsigned v = StringSwitch<unsigned>(type.lower()) 743 .Case("cv", static_cast<unsigned>(DebugType::CV)) 744 .Case("pdata", static_cast<unsigned>(DebugType::PData)) 745 .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 746 .Default(0); 747 if (v == 0) { 748 warn("/debugtype: unknown option '" + type + "'"); 749 continue; 750 } 751 debugTypes |= v; 752 } 753 return debugTypes; 754 } 755 756 // Default debug types 757 debugTypes = static_cast<unsigned>(DebugType::CV); 758 if (args.hasArg(OPT_driver)) 759 debugTypes |= static_cast<unsigned>(DebugType::PData); 760 if (args.hasArg(OPT_profile)) 761 debugTypes |= static_cast<unsigned>(DebugType::Fixup); 762 763 return debugTypes; 764 } 765 766 static std::string getMapFile(const opt::InputArgList &args, 767 opt::OptSpecifier os, opt::OptSpecifier osFile) { 768 auto *arg = args.getLastArg(os, osFile); 769 if (!arg) 770 return ""; 771 if (arg->getOption().getID() == osFile.getID()) 772 return arg->getValue(); 773 774 assert(arg->getOption().getID() == os.getID()); 775 StringRef outFile = config->outputFile; 776 return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 777 } 778 779 static std::string getImplibPath() { 780 if (!config->implib.empty()) 781 return std::string(config->implib); 782 SmallString<128> out = StringRef(config->outputFile); 783 sys::path::replace_extension(out, ".lib"); 784 return std::string(out.str()); 785 } 786 787 // The import name is calculated as follows: 788 // 789 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 790 // -----+----------------+---------------------+------------------ 791 // LINK | {value} | {value}.{.dll/.exe} | {output name} 792 // LIB | {value} | {value}.dll | {output name}.dll 793 // 794 static std::string getImportName(bool asLib) { 795 SmallString<128> out; 796 797 if (config->importName.empty()) { 798 out.assign(sys::path::filename(config->outputFile)); 799 if (asLib) 800 sys::path::replace_extension(out, ".dll"); 801 } else { 802 out.assign(config->importName); 803 if (!sys::path::has_extension(out)) 804 sys::path::replace_extension(out, 805 (config->dll || asLib) ? ".dll" : ".exe"); 806 } 807 808 return std::string(out.str()); 809 } 810 811 static void createImportLibrary(bool asLib) { 812 std::vector<COFFShortExport> exports; 813 for (Export &e1 : config->exports) { 814 COFFShortExport e2; 815 e2.Name = std::string(e1.name); 816 e2.SymbolName = std::string(e1.symbolName); 817 e2.ExtName = std::string(e1.extName); 818 e2.Ordinal = e1.ordinal; 819 e2.Noname = e1.noname; 820 e2.Data = e1.data; 821 e2.Private = e1.isPrivate; 822 e2.Constant = e1.constant; 823 exports.push_back(e2); 824 } 825 826 auto handleError = [](Error &&e) { 827 handleAllErrors(std::move(e), 828 [](ErrorInfoBase &eib) { error(eib.message()); }); 829 }; 830 std::string libName = getImportName(asLib); 831 std::string path = getImplibPath(); 832 833 if (!config->incremental) { 834 handleError(writeImportLibrary(libName, path, exports, config->machine, 835 config->mingw)); 836 return; 837 } 838 839 // If the import library already exists, replace it only if the contents 840 // have changed. 841 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 842 path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 843 if (!oldBuf) { 844 handleError(writeImportLibrary(libName, path, exports, config->machine, 845 config->mingw)); 846 return; 847 } 848 849 SmallString<128> tmpName; 850 if (std::error_code ec = 851 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 852 fatal("cannot create temporary file for import library " + path + ": " + 853 ec.message()); 854 855 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 856 config->mingw)) { 857 handleError(std::move(e)); 858 return; 859 } 860 861 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 862 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 863 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 864 oldBuf->reset(); 865 handleError(errorCodeToError(sys::fs::rename(tmpName, path))); 866 } else { 867 sys::fs::remove(tmpName); 868 } 869 } 870 871 static void parseModuleDefs(StringRef path) { 872 std::unique_ptr<MemoryBuffer> mb = 873 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 874 /*RequiresNullTerminator=*/false, 875 /*IsVolatile=*/true), 876 "could not open " + path); 877 COFFModuleDefinition m = check(parseCOFFModuleDefinition( 878 mb->getMemBufferRef(), config->machine, config->mingw)); 879 880 // Include in /reproduce: output if applicable. 881 driver->takeBuffer(std::move(mb)); 882 883 if (config->outputFile.empty()) 884 config->outputFile = std::string(saver.save(m.OutputFile)); 885 config->importName = std::string(saver.save(m.ImportName)); 886 if (m.ImageBase) 887 config->imageBase = m.ImageBase; 888 if (m.StackReserve) 889 config->stackReserve = m.StackReserve; 890 if (m.StackCommit) 891 config->stackCommit = m.StackCommit; 892 if (m.HeapReserve) 893 config->heapReserve = m.HeapReserve; 894 if (m.HeapCommit) 895 config->heapCommit = m.HeapCommit; 896 if (m.MajorImageVersion) 897 config->majorImageVersion = m.MajorImageVersion; 898 if (m.MinorImageVersion) 899 config->minorImageVersion = m.MinorImageVersion; 900 if (m.MajorOSVersion) 901 config->majorOSVersion = m.MajorOSVersion; 902 if (m.MinorOSVersion) 903 config->minorOSVersion = m.MinorOSVersion; 904 905 for (COFFShortExport e1 : m.Exports) { 906 Export e2; 907 // In simple cases, only Name is set. Renamed exports are parsed 908 // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 909 // it shouldn't be a normal exported function but a forward to another 910 // DLL instead. This is supported by both MS and GNU linkers. 911 if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 912 StringRef(e1.Name).contains('.')) { 913 e2.name = saver.save(e1.ExtName); 914 e2.forwardTo = saver.save(e1.Name); 915 config->exports.push_back(e2); 916 continue; 917 } 918 e2.name = saver.save(e1.Name); 919 e2.extName = saver.save(e1.ExtName); 920 e2.ordinal = e1.Ordinal; 921 e2.noname = e1.Noname; 922 e2.data = e1.Data; 923 e2.isPrivate = e1.Private; 924 e2.constant = e1.Constant; 925 config->exports.push_back(e2); 926 } 927 } 928 929 void LinkerDriver::enqueueTask(std::function<void()> task) { 930 taskQueue.push_back(std::move(task)); 931 } 932 933 bool LinkerDriver::run() { 934 ScopedTimer t(ctx.inputFileTimer); 935 936 bool didWork = !taskQueue.empty(); 937 while (!taskQueue.empty()) { 938 taskQueue.front()(); 939 taskQueue.pop_front(); 940 } 941 return didWork; 942 } 943 944 // Parse an /order file. If an option is given, the linker places 945 // COMDAT sections in the same order as their names appear in the 946 // given file. 947 static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) { 948 // For some reason, the MSVC linker requires a filename to be 949 // preceded by "@". 950 if (!arg.startswith("@")) { 951 error("malformed /order option: '@' missing"); 952 return; 953 } 954 955 // Get a list of all comdat sections for error checking. 956 DenseSet<StringRef> set; 957 for (Chunk *c : ctx.symtab.getChunks()) 958 if (auto *sec = dyn_cast<SectionChunk>(c)) 959 if (sec->sym) 960 set.insert(sec->sym->getName()); 961 962 // Open a file. 963 StringRef path = arg.substr(1); 964 std::unique_ptr<MemoryBuffer> mb = 965 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 966 /*RequiresNullTerminator=*/false, 967 /*IsVolatile=*/true), 968 "could not open " + path); 969 970 // Parse a file. An order file contains one symbol per line. 971 // All symbols that were not present in a given order file are 972 // considered to have the lowest priority 0 and are placed at 973 // end of an output section. 974 for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 975 std::string s(arg); 976 if (config->machine == I386 && !isDecorated(s)) 977 s = "_" + s; 978 979 if (set.count(s) == 0) { 980 if (config->warnMissingOrderSymbol) 981 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 982 } 983 else 984 config->order[s] = INT_MIN + config->order.size(); 985 } 986 987 // Include in /reproduce: output if applicable. 988 driver->takeBuffer(std::move(mb)); 989 } 990 991 static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) { 992 std::unique_ptr<MemoryBuffer> mb = 993 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 994 /*RequiresNullTerminator=*/false, 995 /*IsVolatile=*/true), 996 "could not open " + path); 997 998 // Build a map from symbol name to section. 999 DenseMap<StringRef, Symbol *> map; 1000 for (ObjFile *file : ctx.objFileInstances) 1001 for (Symbol *sym : file->getSymbols()) 1002 if (sym) 1003 map[sym->getName()] = sym; 1004 1005 auto findSection = [&](StringRef name) -> SectionChunk * { 1006 Symbol *sym = map.lookup(name); 1007 if (!sym) { 1008 if (config->warnMissingOrderSymbol) 1009 warn(path + ": no such symbol: " + name); 1010 return nullptr; 1011 } 1012 1013 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1014 return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1015 return nullptr; 1016 }; 1017 1018 for (StringRef line : args::getLines(*mb)) { 1019 SmallVector<StringRef, 3> fields; 1020 line.split(fields, ' '); 1021 uint64_t count; 1022 1023 if (fields.size() != 3 || !to_integer(fields[2], count)) { 1024 error(path + ": parse error"); 1025 return; 1026 } 1027 1028 if (SectionChunk *from = findSection(fields[0])) 1029 if (SectionChunk *to = findSection(fields[1])) 1030 config->callGraphProfile[{from, to}] += count; 1031 } 1032 1033 // Include in /reproduce: output if applicable. 1034 driver->takeBuffer(std::move(mb)); 1035 } 1036 1037 static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1038 for (ObjFile *obj : ctx.objFileInstances) { 1039 if (obj->callgraphSec) { 1040 ArrayRef<uint8_t> contents; 1041 cantFail( 1042 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1043 BinaryStreamReader reader(contents, support::little); 1044 while (!reader.empty()) { 1045 uint32_t fromIndex, toIndex; 1046 uint64_t count; 1047 if (Error err = reader.readInteger(fromIndex)) 1048 fatal(toString(obj) + ": Expected 32-bit integer"); 1049 if (Error err = reader.readInteger(toIndex)) 1050 fatal(toString(obj) + ": Expected 32-bit integer"); 1051 if (Error err = reader.readInteger(count)) 1052 fatal(toString(obj) + ": Expected 64-bit integer"); 1053 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1054 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1055 if (!fromSym || !toSym) 1056 continue; 1057 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1058 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1059 if (from && to) 1060 config->callGraphProfile[{from, to}] += count; 1061 } 1062 } 1063 } 1064 } 1065 1066 static void markAddrsig(Symbol *s) { 1067 if (auto *d = dyn_cast_or_null<Defined>(s)) 1068 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 1069 c->keepUnique = true; 1070 } 1071 1072 static void findKeepUniqueSections(COFFLinkerContext &ctx) { 1073 // Exported symbols could be address-significant in other executables or DSOs, 1074 // so we conservatively mark them as address-significant. 1075 for (Export &r : config->exports) 1076 markAddrsig(r.sym); 1077 1078 // Visit the address-significance table in each object file and mark each 1079 // referenced symbol as address-significant. 1080 for (ObjFile *obj : ctx.objFileInstances) { 1081 ArrayRef<Symbol *> syms = obj->getSymbols(); 1082 if (obj->addrsigSec) { 1083 ArrayRef<uint8_t> contents; 1084 cantFail( 1085 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 1086 const uint8_t *cur = contents.begin(); 1087 while (cur != contents.end()) { 1088 unsigned size; 1089 const char *err; 1090 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 1091 if (err) 1092 fatal(toString(obj) + ": could not decode addrsig section: " + err); 1093 if (symIndex >= syms.size()) 1094 fatal(toString(obj) + ": invalid symbol index in addrsig section"); 1095 markAddrsig(syms[symIndex]); 1096 cur += size; 1097 } 1098 } else { 1099 // If an object file does not have an address-significance table, 1100 // conservatively mark all of its symbols as address-significant. 1101 for (Symbol *s : syms) 1102 markAddrsig(s); 1103 } 1104 } 1105 } 1106 1107 // link.exe replaces each %foo% in altPath with the contents of environment 1108 // variable foo, and adds the two magic env vars _PDB (expands to the basename 1109 // of pdb's output path) and _EXT (expands to the extension of the output 1110 // binary). 1111 // lld only supports %_PDB% and %_EXT% and warns on references to all other env 1112 // vars. 1113 static void parsePDBAltPath(StringRef altPath) { 1114 SmallString<128> buf; 1115 StringRef pdbBasename = 1116 sys::path::filename(config->pdbPath, sys::path::Style::windows); 1117 StringRef binaryExtension = 1118 sys::path::extension(config->outputFile, sys::path::Style::windows); 1119 if (!binaryExtension.empty()) 1120 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 1121 1122 // Invariant: 1123 // +--------- cursor ('a...' might be the empty string). 1124 // | +----- firstMark 1125 // | | +- secondMark 1126 // v v v 1127 // a...%...%... 1128 size_t cursor = 0; 1129 while (cursor < altPath.size()) { 1130 size_t firstMark, secondMark; 1131 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 1132 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 1133 // Didn't find another full fragment, treat rest of string as literal. 1134 buf.append(altPath.substr(cursor)); 1135 break; 1136 } 1137 1138 // Found a full fragment. Append text in front of first %, and interpret 1139 // text between first and second % as variable name. 1140 buf.append(altPath.substr(cursor, firstMark - cursor)); 1141 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1142 if (var.equals_insensitive("%_pdb%")) 1143 buf.append(pdbBasename); 1144 else if (var.equals_insensitive("%_ext%")) 1145 buf.append(binaryExtension); 1146 else { 1147 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 1148 var + " as literal"); 1149 buf.append(var); 1150 } 1151 1152 cursor = secondMark + 1; 1153 } 1154 1155 config->pdbAltPath = buf; 1156 } 1157 1158 /// Convert resource files and potentially merge input resource object 1159 /// trees into one resource tree. 1160 /// Call after ObjFile::Instances is complete. 1161 void LinkerDriver::convertResources() { 1162 std::vector<ObjFile *> resourceObjFiles; 1163 1164 for (ObjFile *f : ctx.objFileInstances) { 1165 if (f->isResourceObjFile()) 1166 resourceObjFiles.push_back(f); 1167 } 1168 1169 if (!config->mingw && 1170 (resourceObjFiles.size() > 1 || 1171 (resourceObjFiles.size() == 1 && !resources.empty()))) { 1172 error((!resources.empty() ? "internal .obj file created from .res files" 1173 : toString(resourceObjFiles[1])) + 1174 ": more than one resource obj file not allowed, already got " + 1175 toString(resourceObjFiles.front())); 1176 return; 1177 } 1178 1179 if (resources.empty() && resourceObjFiles.size() <= 1) { 1180 // No resources to convert, and max one resource object file in 1181 // the input. Keep that preconverted resource section as is. 1182 for (ObjFile *f : resourceObjFiles) 1183 f->includeResourceChunks(); 1184 return; 1185 } 1186 ObjFile *f = 1187 make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1188 ctx.symtab.addFile(f); 1189 f->includeResourceChunks(); 1190 } 1191 1192 // In MinGW, if no symbols are chosen to be exported, then all symbols are 1193 // automatically exported by default. This behavior can be forced by the 1194 // -export-all-symbols option, so that it happens even when exports are 1195 // explicitly specified. The automatic behavior can be disabled using the 1196 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 1197 // than MinGW in the case that nothing is explicitly exported. 1198 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1199 if (!args.hasArg(OPT_export_all_symbols)) { 1200 if (!config->dll) 1201 return; 1202 1203 if (!config->exports.empty()) 1204 return; 1205 if (args.hasArg(OPT_exclude_all_symbols)) 1206 return; 1207 } 1208 1209 AutoExporter exporter; 1210 1211 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1212 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1213 exporter.addWholeArchive(*path); 1214 1215 ctx.symtab.forEachSymbol([&](Symbol *s) { 1216 auto *def = dyn_cast<Defined>(s); 1217 if (!exporter.shouldExport(ctx, def)) 1218 return; 1219 1220 if (!def->isGCRoot) { 1221 def->isGCRoot = true; 1222 config->gcroot.push_back(def); 1223 } 1224 1225 Export e; 1226 e.name = def->getName(); 1227 e.sym = def; 1228 if (Chunk *c = def->getChunk()) 1229 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 1230 e.data = true; 1231 s->isUsedInRegularObj = true; 1232 config->exports.push_back(e); 1233 }); 1234 } 1235 1236 // lld has a feature to create a tar file containing all input files as well as 1237 // all command line options, so that other people can run lld again with exactly 1238 // the same inputs. This feature is accessible via /linkrepro and /reproduce. 1239 // 1240 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 1241 // name while /reproduce takes a full path. We have /linkrepro for compatibility 1242 // with Microsoft link.exe. 1243 Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 1244 if (auto *arg = args.getLastArg(OPT_reproduce)) 1245 return std::string(arg->getValue()); 1246 1247 if (auto *arg = args.getLastArg(OPT_linkrepro)) { 1248 SmallString<64> path = StringRef(arg->getValue()); 1249 sys::path::append(path, "repro.tar"); 1250 return std::string(path); 1251 } 1252 1253 // This is intentionally not guarded by OPT_lldignoreenv since writing 1254 // a repro tar file doesn't affect the main output. 1255 if (auto *path = getenv("LLD_REPRODUCE")) 1256 return std::string(path); 1257 1258 return None; 1259 } 1260 1261 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1262 ScopedTimer rootTimer(ctx.rootTimer); 1263 1264 // Needed for LTO. 1265 InitializeAllTargetInfos(); 1266 InitializeAllTargets(); 1267 InitializeAllTargetMCs(); 1268 InitializeAllAsmParsers(); 1269 InitializeAllAsmPrinters(); 1270 1271 // If the first command line argument is "/lib", link.exe acts like lib.exe. 1272 // We call our own implementation of lib.exe that understands bitcode files. 1273 if (argsArr.size() > 1 && 1274 (StringRef(argsArr[1]).equals_insensitive("/lib") || 1275 StringRef(argsArr[1]).equals_insensitive("-lib"))) { 1276 if (llvm::libDriverMain(argsArr.slice(1)) != 0) 1277 fatal("lib failed"); 1278 return; 1279 } 1280 1281 // Parse command line options. 1282 ArgParser parser; 1283 opt::InputArgList args = parser.parse(argsArr); 1284 1285 // Parse and evaluate -mllvm options. 1286 std::vector<const char *> v; 1287 v.push_back("lld-link (LLVM option parsing)"); 1288 for (auto *arg : args.filtered(OPT_mllvm)) 1289 v.push_back(arg->getValue()); 1290 cl::ResetAllOptionOccurrences(); 1291 cl::ParseCommandLineOptions(v.size(), v.data()); 1292 1293 // Handle /errorlimit early, because error() depends on it. 1294 if (auto *arg = args.getLastArg(OPT_errorlimit)) { 1295 int n = 20; 1296 StringRef s = arg->getValue(); 1297 if (s.getAsInteger(10, n)) 1298 error(arg->getSpelling() + " number expected, but got " + s); 1299 errorHandler().errorLimit = n; 1300 } 1301 1302 // Handle /help 1303 if (args.hasArg(OPT_help)) { 1304 printHelp(argsArr[0]); 1305 return; 1306 } 1307 1308 // /threads: takes a positive integer and provides the default value for 1309 // /opt:lldltojobs=. 1310 if (auto *arg = args.getLastArg(OPT_threads)) { 1311 StringRef v(arg->getValue()); 1312 unsigned threads = 0; 1313 if (!llvm::to_integer(v, threads, 0) || threads == 0) 1314 error(arg->getSpelling() + ": expected a positive integer, but got '" + 1315 arg->getValue() + "'"); 1316 parallel::strategy = hardware_concurrency(threads); 1317 config->thinLTOJobs = v.str(); 1318 } 1319 1320 if (args.hasArg(OPT_show_timing)) 1321 config->showTiming = true; 1322 1323 config->showSummary = args.hasArg(OPT_summary); 1324 1325 // Handle --version, which is an lld extension. This option is a bit odd 1326 // because it doesn't start with "/", but we deliberately chose "--" to 1327 // avoid conflict with /version and for compatibility with clang-cl. 1328 if (args.hasArg(OPT_dash_dash_version)) { 1329 message(getLLDVersion()); 1330 return; 1331 } 1332 1333 // Handle /lldmingw early, since it can potentially affect how other 1334 // options are handled. 1335 config->mingw = args.hasArg(OPT_lldmingw); 1336 1337 // Handle /linkrepro and /reproduce. 1338 if (Optional<std::string> path = getReproduceFile(args)) { 1339 Expected<std::unique_ptr<TarWriter>> errOrWriter = 1340 TarWriter::create(*path, sys::path::stem(*path)); 1341 1342 if (errOrWriter) { 1343 tar = std::move(*errOrWriter); 1344 } else { 1345 error("/linkrepro: failed to open " + *path + ": " + 1346 toString(errOrWriter.takeError())); 1347 } 1348 } 1349 1350 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1351 if (args.hasArg(OPT_deffile)) 1352 config->noEntry = true; 1353 else 1354 fatal("no input files"); 1355 } 1356 1357 // Construct search path list. 1358 searchPaths.push_back(""); 1359 for (auto *arg : args.filtered(OPT_libpath)) 1360 searchPaths.push_back(arg->getValue()); 1361 if (!args.hasArg(OPT_lldignoreenv)) 1362 addLibSearchPaths(); 1363 1364 // Handle /ignore 1365 for (auto *arg : args.filtered(OPT_ignore)) { 1366 SmallVector<StringRef, 8> vec; 1367 StringRef(arg->getValue()).split(vec, ','); 1368 for (StringRef s : vec) { 1369 if (s == "4037") 1370 config->warnMissingOrderSymbol = false; 1371 else if (s == "4099") 1372 config->warnDebugInfoUnusable = false; 1373 else if (s == "4217") 1374 config->warnLocallyDefinedImported = false; 1375 else if (s == "longsections") 1376 config->warnLongSectionNames = false; 1377 // Other warning numbers are ignored. 1378 } 1379 } 1380 1381 // Handle /out 1382 if (auto *arg = args.getLastArg(OPT_out)) 1383 config->outputFile = arg->getValue(); 1384 1385 // Handle /verbose 1386 if (args.hasArg(OPT_verbose)) 1387 config->verbose = true; 1388 errorHandler().verbose = config->verbose; 1389 1390 // Handle /force or /force:unresolved 1391 if (args.hasArg(OPT_force, OPT_force_unresolved)) 1392 config->forceUnresolved = true; 1393 1394 // Handle /force or /force:multiple 1395 if (args.hasArg(OPT_force, OPT_force_multiple)) 1396 config->forceMultiple = true; 1397 1398 // Handle /force or /force:multipleres 1399 if (args.hasArg(OPT_force, OPT_force_multipleres)) 1400 config->forceMultipleRes = true; 1401 1402 // Handle /debug 1403 DebugKind debug = parseDebugKind(args); 1404 if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1405 debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 1406 config->debug = true; 1407 config->incremental = true; 1408 } 1409 1410 // Handle /demangle 1411 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 1412 1413 // Handle /debugtype 1414 config->debugTypes = parseDebugTypes(args); 1415 1416 // Handle /driver[:uponly|:wdm]. 1417 config->driverUponly = args.hasArg(OPT_driver_uponly) || 1418 args.hasArg(OPT_driver_uponly_wdm) || 1419 args.hasArg(OPT_driver_wdm_uponly); 1420 config->driverWdm = args.hasArg(OPT_driver_wdm) || 1421 args.hasArg(OPT_driver_uponly_wdm) || 1422 args.hasArg(OPT_driver_wdm_uponly); 1423 config->driver = 1424 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1425 1426 // Handle /pdb 1427 bool shouldCreatePDB = 1428 (debug == DebugKind::Full || debug == DebugKind::GHash || 1429 debug == DebugKind::NoGHash); 1430 if (shouldCreatePDB) { 1431 if (auto *arg = args.getLastArg(OPT_pdb)) 1432 config->pdbPath = arg->getValue(); 1433 if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 1434 config->pdbAltPath = arg->getValue(); 1435 if (args.hasArg(OPT_natvis)) 1436 config->natvisFiles = args.getAllArgValues(OPT_natvis); 1437 if (args.hasArg(OPT_pdbstream)) { 1438 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 1439 const std::pair<StringRef, StringRef> nameFile = value.split("="); 1440 const StringRef name = nameFile.first; 1441 const std::string file = nameFile.second.str(); 1442 config->namedStreams[name] = file; 1443 } 1444 } 1445 1446 if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 1447 config->pdbSourcePath = arg->getValue(); 1448 } 1449 1450 // Handle /pdbstripped 1451 if (args.hasArg(OPT_pdbstripped)) 1452 warn("ignoring /pdbstripped flag, it is not yet supported"); 1453 1454 // Handle /noentry 1455 if (args.hasArg(OPT_noentry)) { 1456 if (args.hasArg(OPT_dll)) 1457 config->noEntry = true; 1458 else 1459 error("/noentry must be specified with /dll"); 1460 } 1461 1462 // Handle /dll 1463 if (args.hasArg(OPT_dll)) { 1464 config->dll = true; 1465 config->manifestID = 2; 1466 } 1467 1468 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 1469 // because we need to explicitly check whether that option or its inverse was 1470 // present in the argument list in order to handle /fixed. 1471 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 1472 if (dynamicBaseArg && 1473 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 1474 config->dynamicBase = false; 1475 1476 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 1477 // default setting for any other project type.", but link.exe defaults to 1478 // /FIXED:NO for exe outputs as well. Match behavior, not docs. 1479 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 1480 if (fixed) { 1481 if (dynamicBaseArg && 1482 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 1483 error("/fixed must not be specified with /dynamicbase"); 1484 } else { 1485 config->relocatable = false; 1486 config->dynamicBase = false; 1487 } 1488 } 1489 1490 // Handle /appcontainer 1491 config->appContainer = 1492 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 1493 1494 // Handle /machine 1495 if (auto *arg = args.getLastArg(OPT_machine)) { 1496 config->machine = getMachineType(arg->getValue()); 1497 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 1498 fatal(Twine("unknown /machine argument: ") + arg->getValue()); 1499 } 1500 1501 // Handle /nodefaultlib:<filename> 1502 for (auto *arg : args.filtered(OPT_nodefaultlib)) 1503 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 1504 1505 // Handle /nodefaultlib 1506 if (args.hasArg(OPT_nodefaultlib_all)) 1507 config->noDefaultLibAll = true; 1508 1509 // Handle /base 1510 if (auto *arg = args.getLastArg(OPT_base)) 1511 parseNumbers(arg->getValue(), &config->imageBase); 1512 1513 // Handle /filealign 1514 if (auto *arg = args.getLastArg(OPT_filealign)) { 1515 parseNumbers(arg->getValue(), &config->fileAlign); 1516 if (!isPowerOf2_64(config->fileAlign)) 1517 error("/filealign: not a power of two: " + Twine(config->fileAlign)); 1518 } 1519 1520 // Handle /stack 1521 if (auto *arg = args.getLastArg(OPT_stack)) 1522 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 1523 1524 // Handle /guard:cf 1525 if (auto *arg = args.getLastArg(OPT_guard)) 1526 parseGuard(arg->getValue()); 1527 1528 // Handle /heap 1529 if (auto *arg = args.getLastArg(OPT_heap)) 1530 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 1531 1532 // Handle /version 1533 if (auto *arg = args.getLastArg(OPT_version)) 1534 parseVersion(arg->getValue(), &config->majorImageVersion, 1535 &config->minorImageVersion); 1536 1537 // Handle /subsystem 1538 if (auto *arg = args.getLastArg(OPT_subsystem)) 1539 parseSubsystem(arg->getValue(), &config->subsystem, 1540 &config->majorSubsystemVersion, 1541 &config->minorSubsystemVersion); 1542 1543 // Handle /osversion 1544 if (auto *arg = args.getLastArg(OPT_osversion)) { 1545 parseVersion(arg->getValue(), &config->majorOSVersion, 1546 &config->minorOSVersion); 1547 } else { 1548 config->majorOSVersion = config->majorSubsystemVersion; 1549 config->minorOSVersion = config->minorSubsystemVersion; 1550 } 1551 1552 // Handle /timestamp 1553 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 1554 if (arg->getOption().getID() == OPT_repro) { 1555 config->timestamp = 0; 1556 config->repro = true; 1557 } else { 1558 config->repro = false; 1559 StringRef value(arg->getValue()); 1560 if (value.getAsInteger(0, config->timestamp)) 1561 fatal(Twine("invalid timestamp: ") + value + 1562 ". Expected 32-bit integer"); 1563 } 1564 } else { 1565 config->repro = false; 1566 config->timestamp = time(nullptr); 1567 } 1568 1569 // Handle /alternatename 1570 for (auto *arg : args.filtered(OPT_alternatename)) 1571 parseAlternateName(arg->getValue()); 1572 1573 // Handle /include 1574 for (auto *arg : args.filtered(OPT_incl)) 1575 addUndefined(arg->getValue()); 1576 1577 // Handle /implib 1578 if (auto *arg = args.getLastArg(OPT_implib)) 1579 config->implib = arg->getValue(); 1580 1581 // Handle /opt. 1582 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1583 Optional<ICFLevel> icfLevel = None; 1584 if (args.hasArg(OPT_profile)) 1585 icfLevel = ICFLevel::None; 1586 unsigned tailMerge = 1; 1587 bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1588 bool ltoDebugPM = false; 1589 for (auto *arg : args.filtered(OPT_opt)) { 1590 std::string str = StringRef(arg->getValue()).lower(); 1591 SmallVector<StringRef, 1> vec; 1592 StringRef(str).split(vec, ','); 1593 for (StringRef s : vec) { 1594 if (s == "ref") { 1595 doGC = true; 1596 } else if (s == "noref") { 1597 doGC = false; 1598 } else if (s == "icf" || s.startswith("icf=")) { 1599 icfLevel = ICFLevel::All; 1600 } else if (s == "safeicf") { 1601 icfLevel = ICFLevel::Safe; 1602 } else if (s == "noicf") { 1603 icfLevel = ICFLevel::None; 1604 } else if (s == "lldtailmerge") { 1605 tailMerge = 2; 1606 } else if (s == "nolldtailmerge") { 1607 tailMerge = 0; 1608 } else if (s == "ltonewpassmanager") { 1609 ltoNewPM = true; 1610 } else if (s == "noltonewpassmanager") { 1611 ltoNewPM = false; 1612 } else if (s == "ltodebugpassmanager") { 1613 ltoDebugPM = true; 1614 } else if (s == "noltodebugpassmanager") { 1615 ltoDebugPM = false; 1616 } else if (s.startswith("lldlto=")) { 1617 StringRef optLevel = s.substr(7); 1618 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 1619 error("/opt:lldlto: invalid optimization level: " + optLevel); 1620 } else if (s.startswith("lldltojobs=")) { 1621 StringRef jobs = s.substr(11); 1622 if (!get_threadpool_strategy(jobs)) 1623 error("/opt:lldltojobs: invalid job count: " + jobs); 1624 config->thinLTOJobs = jobs.str(); 1625 } else if (s.startswith("lldltopartitions=")) { 1626 StringRef n = s.substr(17); 1627 if (n.getAsInteger(10, config->ltoPartitions) || 1628 config->ltoPartitions == 0) 1629 error("/opt:lldltopartitions: invalid partition count: " + n); 1630 } else if (s != "lbr" && s != "nolbr") 1631 error("/opt: unknown option: " + s); 1632 } 1633 } 1634 1635 if (!icfLevel) 1636 icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 1637 config->doGC = doGC; 1638 config->doICF = icfLevel.getValue(); 1639 config->tailMerge = 1640 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1641 config->ltoNewPassManager = ltoNewPM; 1642 config->ltoDebugPassManager = ltoDebugPM; 1643 1644 // Handle /lldsavetemps 1645 if (args.hasArg(OPT_lldsavetemps)) 1646 config->saveTemps = true; 1647 1648 // Handle /kill-at 1649 if (args.hasArg(OPT_kill_at)) 1650 config->killAt = true; 1651 1652 // Handle /lldltocache 1653 if (auto *arg = args.getLastArg(OPT_lldltocache)) 1654 config->ltoCache = arg->getValue(); 1655 1656 // Handle /lldsavecachepolicy 1657 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 1658 config->ltoCachePolicy = CHECK( 1659 parseCachePruningPolicy(arg->getValue()), 1660 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 1661 1662 // Handle /failifmismatch 1663 for (auto *arg : args.filtered(OPT_failifmismatch)) 1664 checkFailIfMismatch(arg->getValue(), nullptr); 1665 1666 // Handle /merge 1667 for (auto *arg : args.filtered(OPT_merge)) 1668 parseMerge(arg->getValue()); 1669 1670 // Add default section merging rules after user rules. User rules take 1671 // precedence, but we will emit a warning if there is a conflict. 1672 parseMerge(".idata=.rdata"); 1673 parseMerge(".didat=.rdata"); 1674 parseMerge(".edata=.rdata"); 1675 parseMerge(".xdata=.rdata"); 1676 parseMerge(".bss=.data"); 1677 1678 if (config->mingw) { 1679 parseMerge(".ctors=.rdata"); 1680 parseMerge(".dtors=.rdata"); 1681 parseMerge(".CRT=.rdata"); 1682 } 1683 1684 // Handle /section 1685 for (auto *arg : args.filtered(OPT_section)) 1686 parseSection(arg->getValue()); 1687 1688 // Handle /align 1689 if (auto *arg = args.getLastArg(OPT_align)) { 1690 parseNumbers(arg->getValue(), &config->align); 1691 if (!isPowerOf2_64(config->align)) 1692 error("/align: not a power of two: " + StringRef(arg->getValue())); 1693 if (!args.hasArg(OPT_driver)) 1694 warn("/align specified without /driver; image may not run"); 1695 } 1696 1697 // Handle /aligncomm 1698 for (auto *arg : args.filtered(OPT_aligncomm)) 1699 parseAligncomm(arg->getValue()); 1700 1701 // Handle /manifestdependency. 1702 for (auto *arg : args.filtered(OPT_manifestdependency)) 1703 config->manifestDependencies.insert(arg->getValue()); 1704 1705 // Handle /manifest and /manifest: 1706 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 1707 if (arg->getOption().getID() == OPT_manifest) 1708 config->manifest = Configuration::SideBySide; 1709 else 1710 parseManifest(arg->getValue()); 1711 } 1712 1713 // Handle /manifestuac 1714 if (auto *arg = args.getLastArg(OPT_manifestuac)) 1715 parseManifestUAC(arg->getValue()); 1716 1717 // Handle /manifestfile 1718 if (auto *arg = args.getLastArg(OPT_manifestfile)) 1719 config->manifestFile = arg->getValue(); 1720 1721 // Handle /manifestinput 1722 for (auto *arg : args.filtered(OPT_manifestinput)) 1723 config->manifestInput.push_back(arg->getValue()); 1724 1725 if (!config->manifestInput.empty() && 1726 config->manifest != Configuration::Embed) { 1727 fatal("/manifestinput: requires /manifest:embed"); 1728 } 1729 1730 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 1731 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 1732 args.hasArg(OPT_thinlto_index_only_arg); 1733 config->thinLTOIndexOnlyArg = 1734 args.getLastArgValue(OPT_thinlto_index_only_arg); 1735 config->thinLTOPrefixReplace = 1736 getOldNewOptions(args, OPT_thinlto_prefix_replace); 1737 config->thinLTOObjectSuffixReplace = 1738 getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 1739 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1740 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1741 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 1742 // Handle miscellaneous boolean flags. 1743 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1744 OPT_lto_pgo_warn_mismatch_no, true); 1745 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1746 config->allowIsolation = 1747 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1748 config->incremental = 1749 args.hasFlag(OPT_incremental, OPT_incremental_no, 1750 !config->doGC && config->doICF == ICFLevel::None && 1751 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 1752 config->integrityCheck = 1753 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 1754 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 1755 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1756 for (auto *arg : args.filtered(OPT_swaprun)) 1757 parseSwaprun(arg->getValue()); 1758 config->terminalServerAware = 1759 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1760 config->debugDwarf = debug == DebugKind::Dwarf; 1761 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 1762 config->debugSymtab = debug == DebugKind::Symtab; 1763 config->autoImport = 1764 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 1765 config->pseudoRelocs = args.hasFlag( 1766 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1767 config->callGraphProfileSort = args.hasFlag( 1768 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1769 config->stdcallFixup = 1770 args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1771 config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 1772 1773 // Don't warn about long section names, such as .debug_info, for mingw or 1774 // when -debug:dwarf is requested. 1775 if (config->mingw || config->debugDwarf) 1776 config->warnLongSectionNames = false; 1777 1778 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 1779 config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 1780 1781 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 1782 warn("/lldmap and /map have the same output file '" + config->mapFile + 1783 "'.\n>>> ignoring /lldmap"); 1784 config->lldmapFile.clear(); 1785 } 1786 1787 if (config->incremental && args.hasArg(OPT_profile)) { 1788 warn("ignoring '/incremental' due to '/profile' specification"); 1789 config->incremental = false; 1790 } 1791 1792 if (config->incremental && args.hasArg(OPT_order)) { 1793 warn("ignoring '/incremental' due to '/order' specification"); 1794 config->incremental = false; 1795 } 1796 1797 if (config->incremental && config->doGC) { 1798 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 1799 "disable"); 1800 config->incremental = false; 1801 } 1802 1803 if (config->incremental && config->doICF != ICFLevel::None) { 1804 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 1805 "disable"); 1806 config->incremental = false; 1807 } 1808 1809 if (errorCount()) 1810 return; 1811 1812 std::set<sys::fs::UniqueID> wholeArchives; 1813 for (auto *arg : args.filtered(OPT_wholearchive_file)) 1814 if (Optional<StringRef> path = doFindFile(arg->getValue())) 1815 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 1816 wholeArchives.insert(*id); 1817 1818 // A predicate returning true if a given path is an argument for 1819 // /wholearchive:, or /wholearchive is enabled globally. 1820 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 1821 // needs to be handled as "/wholearchive:foo.obj foo.obj". 1822 auto isWholeArchive = [&](StringRef path) -> bool { 1823 if (args.hasArg(OPT_wholearchive_flag)) 1824 return true; 1825 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 1826 return wholeArchives.count(*id); 1827 return false; 1828 }; 1829 1830 // Create a list of input files. These can be given as OPT_INPUT options 1831 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 1832 // and OPT_end_lib. 1833 bool inLib = false; 1834 for (auto *arg : args) { 1835 switch (arg->getOption().getID()) { 1836 case OPT_end_lib: 1837 if (!inLib) 1838 error("stray " + arg->getSpelling()); 1839 inLib = false; 1840 break; 1841 case OPT_start_lib: 1842 if (inLib) 1843 error("nested " + arg->getSpelling()); 1844 inLib = true; 1845 break; 1846 case OPT_wholearchive_file: 1847 if (Optional<StringRef> path = findFile(arg->getValue())) 1848 enqueuePath(*path, true, inLib); 1849 break; 1850 case OPT_INPUT: 1851 if (Optional<StringRef> path = findFile(arg->getValue())) 1852 enqueuePath(*path, isWholeArchive(*path), inLib); 1853 break; 1854 default: 1855 // Ignore other options. 1856 break; 1857 } 1858 } 1859 1860 // Process files specified as /defaultlib. These should be enequeued after 1861 // other files, which is why they are in a separate loop. 1862 for (auto *arg : args.filtered(OPT_defaultlib)) 1863 if (Optional<StringRef> path = findLib(arg->getValue())) 1864 enqueuePath(*path, false, false); 1865 1866 // Read all input files given via the command line. 1867 run(); 1868 1869 if (errorCount()) 1870 return; 1871 1872 // We should have inferred a machine type by now from the input files, but if 1873 // not we assume x64. 1874 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1875 warn("/machine is not specified. x64 is assumed"); 1876 config->machine = AMD64; 1877 } 1878 config->wordsize = config->is64() ? 8 : 4; 1879 1880 // Handle /safeseh, x86 only, on by default, except for mingw. 1881 if (config->machine == I386) { 1882 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1883 config->noSEH = args.hasArg(OPT_noseh); 1884 } 1885 1886 // Handle /functionpadmin 1887 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 1888 parseFunctionPadMin(arg, config->machine); 1889 1890 if (tar) 1891 tar->append("response.txt", 1892 createResponseFile(args, filePaths, 1893 ArrayRef<StringRef>(searchPaths).slice(1))); 1894 1895 // Handle /largeaddressaware 1896 config->largeAddressAware = args.hasFlag( 1897 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 1898 1899 // Handle /highentropyva 1900 config->highEntropyVA = 1901 config->is64() && 1902 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1903 1904 if (!config->dynamicBase && 1905 (config->machine == ARMNT || config->machine == ARM64)) 1906 error("/dynamicbase:no is not compatible with " + 1907 machineToStr(config->machine)); 1908 1909 // Handle /export 1910 for (auto *arg : args.filtered(OPT_export)) { 1911 Export e = parseExport(arg->getValue()); 1912 if (config->machine == I386) { 1913 if (!isDecorated(e.name)) 1914 e.name = saver.save("_" + e.name); 1915 if (!e.extName.empty() && !isDecorated(e.extName)) 1916 e.extName = saver.save("_" + e.extName); 1917 } 1918 config->exports.push_back(e); 1919 } 1920 1921 // Handle /def 1922 if (auto *arg = args.getLastArg(OPT_deffile)) { 1923 // parseModuleDefs mutates Config object. 1924 parseModuleDefs(arg->getValue()); 1925 } 1926 1927 // Handle generation of import library from a def file. 1928 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 1929 fixupExports(); 1930 createImportLibrary(/*asLib=*/true); 1931 return; 1932 } 1933 1934 // Windows specific -- if no /subsystem is given, we need to infer 1935 // that from entry point name. Must happen before /entry handling, 1936 // and after the early return when just writing an import library. 1937 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1938 config->subsystem = inferSubsystem(); 1939 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1940 fatal("subsystem must be defined"); 1941 } 1942 1943 // Handle /entry and /dll 1944 if (auto *arg = args.getLastArg(OPT_entry)) { 1945 config->entry = addUndefined(mangle(arg->getValue())); 1946 } else if (!config->entry && !config->noEntry) { 1947 if (args.hasArg(OPT_dll)) { 1948 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 1949 : "_DllMainCRTStartup"; 1950 config->entry = addUndefined(s); 1951 } else if (config->driverWdm) { 1952 // /driver:wdm implies /entry:_NtProcessStartup 1953 config->entry = addUndefined(mangle("_NtProcessStartup")); 1954 } else { 1955 // Windows specific -- If entry point name is not given, we need to 1956 // infer that from user-defined entry name. 1957 StringRef s = findDefaultEntry(); 1958 if (s.empty()) 1959 fatal("entry point must be defined"); 1960 config->entry = addUndefined(s); 1961 log("Entry name inferred: " + s); 1962 } 1963 } 1964 1965 // Handle /delayload 1966 for (auto *arg : args.filtered(OPT_delayload)) { 1967 config->delayLoads.insert(StringRef(arg->getValue()).lower()); 1968 if (config->machine == I386) { 1969 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1970 } else { 1971 config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 1972 } 1973 } 1974 1975 // Set default image name if neither /out or /def set it. 1976 if (config->outputFile.empty()) { 1977 config->outputFile = getOutputPath( 1978 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 1979 } 1980 1981 // Fail early if an output file is not writable. 1982 if (auto e = tryCreateFile(config->outputFile)) { 1983 error("cannot open output file " + config->outputFile + ": " + e.message()); 1984 return; 1985 } 1986 1987 if (shouldCreatePDB) { 1988 // Put the PDB next to the image if no /pdb flag was passed. 1989 if (config->pdbPath.empty()) { 1990 config->pdbPath = config->outputFile; 1991 sys::path::replace_extension(config->pdbPath, ".pdb"); 1992 } 1993 1994 // The embedded PDB path should be the absolute path to the PDB if no 1995 // /pdbaltpath flag was passed. 1996 if (config->pdbAltPath.empty()) { 1997 config->pdbAltPath = config->pdbPath; 1998 1999 // It's important to make the path absolute and remove dots. This path 2000 // will eventually be written into the PE header, and certain Microsoft 2001 // tools won't work correctly if these assumptions are not held. 2002 sys::fs::make_absolute(config->pdbAltPath); 2003 sys::path::remove_dots(config->pdbAltPath); 2004 } else { 2005 // Don't do this earlier, so that Config->OutputFile is ready. 2006 parsePDBAltPath(config->pdbAltPath); 2007 } 2008 } 2009 2010 // Set default image base if /base is not given. 2011 if (config->imageBase == uint64_t(-1)) 2012 config->imageBase = getDefaultImageBase(); 2013 2014 ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 2015 if (config->machine == I386) { 2016 ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 2017 ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 2018 } 2019 2020 ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2021 ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2022 ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2023 ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2024 ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2025 ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2026 ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 2027 // Needed for MSVC 2017 15.5 CRT. 2028 ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2029 // Needed for MSVC 2019 16.8 CRT. 2030 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2031 ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 2032 2033 if (config->pseudoRelocs) { 2034 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2035 ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 2036 } 2037 if (config->mingw) { 2038 ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2039 ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 2040 } 2041 2042 // This code may add new undefined symbols to the link, which may enqueue more 2043 // symbol resolution tasks, so we need to continue executing tasks until we 2044 // converge. 2045 do { 2046 // Windows specific -- if entry point is not found, 2047 // search for its mangled names. 2048 if (config->entry) 2049 mangleMaybe(config->entry); 2050 2051 // Windows specific -- Make sure we resolve all dllexported symbols. 2052 for (Export &e : config->exports) { 2053 if (!e.forwardTo.empty()) 2054 continue; 2055 e.sym = addUndefined(e.name); 2056 if (!e.directives) 2057 e.symbolName = mangleMaybe(e.sym); 2058 } 2059 2060 // Add weak aliases. Weak aliases is a mechanism to give remaining 2061 // undefined symbols final chance to be resolved successfully. 2062 for (auto pair : config->alternateNames) { 2063 StringRef from = pair.first; 2064 StringRef to = pair.second; 2065 Symbol *sym = ctx.symtab.find(from); 2066 if (!sym) 2067 continue; 2068 if (auto *u = dyn_cast<Undefined>(sym)) 2069 if (!u->weakAlias) 2070 u->weakAlias = ctx.symtab.addUndefined(to); 2071 } 2072 2073 // If any inputs are bitcode files, the LTO code generator may create 2074 // references to library functions that are not explicit in the bitcode 2075 // file's symbol table. If any of those library functions are defined in a 2076 // bitcode file in an archive member, we need to arrange to use LTO to 2077 // compile those archive members by adding them to the link beforehand. 2078 if (!ctx.bitcodeFileInstances.empty()) 2079 for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2080 ctx.symtab.addLibcall(s); 2081 2082 // Windows specific -- if __load_config_used can be resolved, resolve it. 2083 if (ctx.symtab.findUnderscore("_load_config_used")) 2084 addUndefined(mangle("_load_config_used")); 2085 } while (run()); 2086 2087 if (args.hasArg(OPT_include_optional)) { 2088 // Handle /includeoptional 2089 for (auto *arg : args.filtered(OPT_include_optional)) 2090 if (dyn_cast_or_null<LazyArchive>(ctx.symtab.find(arg->getValue()))) 2091 addUndefined(arg->getValue()); 2092 while (run()); 2093 } 2094 2095 // Create wrapped symbols for -wrap option. 2096 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2097 // Load more object files that might be needed for wrapped symbols. 2098 if (!wrapped.empty()) 2099 while (run()); 2100 2101 if (config->autoImport || config->stdcallFixup) { 2102 // MinGW specific. 2103 // Load any further object files that might be needed for doing automatic 2104 // imports, and do stdcall fixups. 2105 // 2106 // For cases with no automatically imported symbols, this iterates once 2107 // over the symbol table and doesn't do anything. 2108 // 2109 // For the normal case with a few automatically imported symbols, this 2110 // should only need to be run once, since each new object file imported 2111 // is an import library and wouldn't add any new undefined references, 2112 // but there's nothing stopping the __imp_ symbols from coming from a 2113 // normal object file as well (although that won't be used for the 2114 // actual autoimport later on). If this pass adds new undefined references, 2115 // we won't iterate further to resolve them. 2116 // 2117 // If stdcall fixups only are needed for loading import entries from 2118 // a DLL without import library, this also just needs running once. 2119 // If it ends up pulling in more object files from static libraries, 2120 // (and maybe doing more stdcall fixups along the way), this would need 2121 // to loop these two calls. 2122 ctx.symtab.loadMinGWSymbols(); 2123 run(); 2124 } 2125 2126 // At this point, we should not have any symbols that cannot be resolved. 2127 // If we are going to do codegen for link-time optimization, check for 2128 // unresolvable symbols first, so we don't spend time generating code that 2129 // will fail to link anyway. 2130 if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2131 ctx.symtab.reportUnresolvable(); 2132 if (errorCount()) 2133 return; 2134 2135 config->hadExplicitExports = !config->exports.empty(); 2136 if (config->mingw) { 2137 // In MinGW, all symbols are automatically exported if no symbols 2138 // are chosen to be exported. 2139 maybeExportMinGWSymbols(args); 2140 } 2141 2142 // Do LTO by compiling bitcode input files to a set of native COFF files then 2143 // link those files (unless -thinlto-index-only was given, in which case we 2144 // resolve symbols and write indices, but don't generate native code or link). 2145 ctx.symtab.addCombinedLTOObjects(); 2146 2147 // If -thinlto-index-only is given, we should create only "index 2148 // files" and not object files. Index file creation is already done 2149 // in addCombinedLTOObject, so we are done if that's the case. 2150 if (config->thinLTOIndexOnly) 2151 return; 2152 2153 // If we generated native object files from bitcode files, this resolves 2154 // references to the symbols we use from them. 2155 run(); 2156 2157 // Apply symbol renames for -wrap. 2158 if (!wrapped.empty()) 2159 wrapSymbols(ctx, wrapped); 2160 2161 // Resolve remaining undefined symbols and warn about imported locals. 2162 ctx.symtab.resolveRemainingUndefines(); 2163 if (errorCount()) 2164 return; 2165 2166 if (config->mingw) { 2167 // Make sure the crtend.o object is the last object file. This object 2168 // file can contain terminating section chunks that need to be placed 2169 // last. GNU ld processes files and static libraries explicitly in the 2170 // order provided on the command line, while lld will pull in needed 2171 // files from static libraries only after the last object file on the 2172 // command line. 2173 for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 2174 i != e; i++) { 2175 ObjFile *file = *i; 2176 if (isCrtend(file->getName())) { 2177 ctx.objFileInstances.erase(i); 2178 ctx.objFileInstances.push_back(file); 2179 break; 2180 } 2181 } 2182 } 2183 2184 // Windows specific -- when we are creating a .dll file, we also 2185 // need to create a .lib file. In MinGW mode, we only do that when the 2186 // -implib option is given explicitly, for compatibility with GNU ld. 2187 if (!config->exports.empty() || config->dll) { 2188 fixupExports(); 2189 if (!config->mingw || !config->implib.empty()) 2190 createImportLibrary(/*asLib=*/false); 2191 assignExportOrdinals(); 2192 } 2193 2194 // Handle /output-def (MinGW specific). 2195 if (auto *arg = args.getLastArg(OPT_output_def)) 2196 writeDefFile(arg->getValue()); 2197 2198 // Set extra alignment for .comm symbols 2199 for (auto pair : config->alignComm) { 2200 StringRef name = pair.first; 2201 uint32_t alignment = pair.second; 2202 2203 Symbol *sym = ctx.symtab.find(name); 2204 if (!sym) { 2205 warn("/aligncomm symbol " + name + " not found"); 2206 continue; 2207 } 2208 2209 // If the symbol isn't common, it must have been replaced with a regular 2210 // symbol, which will carry its own alignment. 2211 auto *dc = dyn_cast<DefinedCommon>(sym); 2212 if (!dc) 2213 continue; 2214 2215 CommonChunk *c = dc->getChunk(); 2216 c->setAlignment(std::max(c->getAlignment(), alignment)); 2217 } 2218 2219 // Windows specific -- Create an embedded or side-by-side manifest. 2220 // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2221 // also passed. 2222 if (config->manifest == Configuration::Embed) 2223 addBuffer(createManifestRes(), false, false); 2224 else if (config->manifest == Configuration::SideBySide || 2225 (config->manifest == Configuration::Default && 2226 !config->manifestDependencies.empty())) 2227 createSideBySideManifest(); 2228 2229 // Handle /order. We want to do this at this moment because we 2230 // need a complete list of comdat sections to warn on nonexistent 2231 // functions. 2232 if (auto *arg = args.getLastArg(OPT_order)) { 2233 if (args.hasArg(OPT_call_graph_ordering_file)) 2234 error("/order and /call-graph-order-file may not be used together"); 2235 parseOrderFile(ctx, arg->getValue()); 2236 config->callGraphProfileSort = false; 2237 } 2238 2239 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2240 if (config->callGraphProfileSort) { 2241 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2242 parseCallGraphFile(ctx, arg->getValue()); 2243 } 2244 readCallGraphsFromObjectFiles(ctx); 2245 } 2246 2247 // Handle /print-symbol-order. 2248 if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2249 config->printSymbolOrder = arg->getValue(); 2250 2251 // Identify unreferenced COMDAT sections. 2252 if (config->doGC) { 2253 if (config->mingw) { 2254 // markLive doesn't traverse .eh_frame, but the personality function is 2255 // only reached that way. The proper solution would be to parse and 2256 // traverse the .eh_frame section, like the ELF linker does. 2257 // For now, just manually try to retain the known possible personality 2258 // functions. This doesn't bring in more object files, but only marks 2259 // functions that already have been included to be retained. 2260 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2261 Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2262 if (d && !d->isGCRoot) { 2263 d->isGCRoot = true; 2264 config->gcroot.push_back(d); 2265 } 2266 } 2267 } 2268 2269 markLive(ctx); 2270 } 2271 2272 // Needs to happen after the last call to addFile(). 2273 convertResources(); 2274 2275 // Identify identical COMDAT sections to merge them. 2276 if (config->doICF != ICFLevel::None) { 2277 findKeepUniqueSections(ctx); 2278 doICF(ctx, config->doICF); 2279 } 2280 2281 // Write the result. 2282 writeResult(ctx); 2283 2284 // Stop early so we can print the results. 2285 rootTimer.stop(); 2286 if (config->showTiming) 2287 ctx.rootTimer.print(); 2288 } 2289 2290 } // namespace coff 2291 } // namespace lld 2292