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