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