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