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