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