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