1 //===- Driver.cpp ---------------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
10 #include "COFFLinkerContext.h"
12 #include "DebugTypes.h"
14 #include "InputFiles.h"
17 #include "SymbolTable.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"
60 using namespace llvm::object
;
61 using namespace llvm::COFF
;
62 using namespace llvm::sys
;
66 bool link(ArrayRef
<const char *> args
, llvm::raw_ostream
&stdoutOS
,
67 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
) {
68 // This driver-specific context will be freed later by unsafeLldMain().
69 auto *ctx
= new COFFLinkerContext
;
71 ctx
->e
.initialize(stdoutOS
, stderrOS
, exitEarly
, disableOutput
);
72 ctx
->e
.logName
= args::getFilenameWithoutExe(args
[0]);
73 ctx
->e
.errorLimitExceededMsg
= "too many errors emitted, stopping now"
74 " (use /errorlimit:0 to see all errors)";
76 ctx
->driver
.linkerMain(args
);
78 return errorCount() == 0;
81 // Parse options of the form "old;new".
82 static std::pair
<StringRef
, StringRef
> getOldNewOptions(opt::InputArgList
&args
,
84 auto *arg
= args
.getLastArg(id
);
88 StringRef s
= arg
->getValue();
89 std::pair
<StringRef
, StringRef
> ret
= s
.split(';');
90 if (ret
.second
.empty())
91 error(arg
->getSpelling() + " expects 'old;new' format, but got " + s
);
95 // Parse options of the form "old;new[;extra]".
96 static std::tuple
<StringRef
, StringRef
, StringRef
>
97 getOldNewOptionsExtra(opt::InputArgList
&args
, unsigned id
) {
98 auto [oldDir
, second
] = getOldNewOptions(args
, id
);
99 auto [newDir
, extraDir
] = second
.split(';');
100 return {oldDir
, newDir
, extraDir
};
103 // Drop directory components and replace extension with
104 // ".exe", ".dll" or ".sys".
105 static std::string
getOutputPath(StringRef path
, bool isDll
, bool isDriver
) {
106 StringRef ext
= ".exe";
112 return (sys::path::stem(path
) + ext
).str();
115 // Returns true if S matches /crtend.?\.o$/.
116 static bool isCrtend(StringRef s
) {
117 if (!s
.consume_back(".o"))
119 if (s
.ends_with("crtend"))
121 return !s
.empty() && s
.drop_back().ends_with("crtend");
124 // ErrorOr is not default constructible, so it cannot be used as the type
125 // parameter of a future.
126 // FIXME: We could open the file in createFutureForFile and avoid needing to
127 // return an error here, but for the moment that would cost us a file descriptor
128 // (a limited resource on Windows) for the duration that the future is pending.
129 using MBErrPair
= std::pair
<std::unique_ptr
<MemoryBuffer
>, std::error_code
>;
131 // Create a std::future that opens and maps a file using the best strategy for
132 // the host platform.
133 static std::future
<MBErrPair
> createFutureForFile(std::string path
) {
135 // On Windows, file I/O is relatively slow so it is best to do this
136 // asynchronously. But 32-bit has issues with potentially launching tons
138 auto strategy
= std::launch::async
;
140 auto strategy
= std::launch::deferred
;
142 return std::async(strategy
, [=]() {
143 auto mbOrErr
= MemoryBuffer::getFile(path
, /*IsText=*/false,
144 /*RequiresNullTerminator=*/false);
146 return MBErrPair
{nullptr, mbOrErr
.getError()};
147 return MBErrPair
{std::move(*mbOrErr
), std::error_code()};
151 // Symbol names are mangled by prepending "_" on x86.
152 StringRef
LinkerDriver::mangle(StringRef sym
) {
153 assert(ctx
.config
.machine
!= IMAGE_FILE_MACHINE_UNKNOWN
);
154 if (ctx
.config
.machine
== I386
)
155 return saver().save("_" + sym
);
159 llvm::Triple::ArchType
LinkerDriver::getArch() {
160 return getMachineArchType(ctx
.config
.machine
);
163 bool LinkerDriver::findUnderscoreMangle(StringRef sym
) {
164 Symbol
*s
= ctx
.symtab
.findMangle(mangle(sym
));
165 return s
&& !isa
<Undefined
>(s
);
168 MemoryBufferRef
LinkerDriver::takeBuffer(std::unique_ptr
<MemoryBuffer
> mb
) {
169 MemoryBufferRef mbref
= *mb
;
170 make
<std::unique_ptr
<MemoryBuffer
>>(std::move(mb
)); // take ownership
173 ctx
.driver
.tar
->append(relativeToRoot(mbref
.getBufferIdentifier()),
178 void LinkerDriver::addBuffer(std::unique_ptr
<MemoryBuffer
> mb
,
179 bool wholeArchive
, bool lazy
) {
180 StringRef filename
= mb
->getBufferIdentifier();
182 MemoryBufferRef mbref
= takeBuffer(std::move(mb
));
183 filePaths
.push_back(filename
);
185 // File type is detected by contents, not by file extension.
186 switch (identify_magic(mbref
.getBuffer())) {
187 case file_magic::windows_resource
:
188 resources
.push_back(mbref
);
190 case file_magic::archive
:
192 std::unique_ptr
<Archive
> file
=
193 CHECK(Archive::create(mbref
), filename
+ ": failed to parse archive");
194 Archive
*archive
= file
.get();
195 make
<std::unique_ptr
<Archive
>>(std::move(file
)); // take ownership
198 for (MemoryBufferRef m
: getArchiveMembers(archive
))
199 addArchiveBuffer(m
, "<whole-archive>", filename
, memberIndex
++);
202 ctx
.symtab
.addFile(make
<ArchiveFile
>(ctx
, mbref
));
204 case file_magic::bitcode
:
205 ctx
.symtab
.addFile(make
<BitcodeFile
>(ctx
, mbref
, "", 0, lazy
));
207 case file_magic::coff_object
:
208 case file_magic::coff_import_library
:
209 ctx
.symtab
.addFile(make
<ObjFile
>(ctx
, mbref
, lazy
));
211 case file_magic::pdb
:
212 ctx
.symtab
.addFile(make
<PDBInputFile
>(ctx
, mbref
));
214 case file_magic::coff_cl_gl_object
:
215 error(filename
+ ": is not a native COFF file. Recompile without /GL");
217 case file_magic::pecoff_executable
:
218 if (ctx
.config
.mingw
) {
219 ctx
.symtab
.addFile(make
<DLLFile
>(ctx
, mbref
));
222 if (filename
.ends_with_insensitive(".dll")) {
223 error(filename
+ ": bad file type. Did you specify a DLL instead of an "
229 error(mbref
.getBufferIdentifier() + ": unknown file type");
234 void LinkerDriver::enqueuePath(StringRef path
, bool wholeArchive
, bool lazy
) {
235 auto future
= std::make_shared
<std::future
<MBErrPair
>>(
236 createFutureForFile(std::string(path
)));
237 std::string pathStr
= std::string(path
);
239 llvm::TimeTraceScope
timeScope("File: ", path
);
240 auto [mb
, ec
] = future
->get();
242 // Retry reading the file (synchronously) now that we may have added
243 // winsysroot search paths from SymbolTable::addFile().
244 // Retrying synchronously is important for keeping the order of inputs
246 // This makes it so that if the user passes something in the winsysroot
247 // before something we can find with an architecture, we won't find the
249 if (std::optional
<StringRef
> retryPath
= findFileIfNew(pathStr
)) {
250 auto retryMb
= MemoryBuffer::getFile(*retryPath
, /*IsText=*/false,
251 /*RequiresNullTerminator=*/false);
252 ec
= retryMb
.getError();
254 mb
= std::move(*retryMb
);
256 // We've already handled this file.
261 std::string msg
= "could not open '" + pathStr
+ "': " + ec
.message();
262 // Check if the filename is a typo for an option flag. OptTable thinks
263 // that all args that are not known options and that start with / are
264 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
265 // the option `/nodefaultlib` than a reference to a file in the root
268 if (ctx
.optTable
.findNearest(pathStr
, nearest
) > 1)
271 error(msg
+ "; did you mean '" + nearest
+ "'");
273 ctx
.driver
.addBuffer(std::move(mb
), wholeArchive
, lazy
);
277 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb
, StringRef symName
,
278 StringRef parentName
,
279 uint64_t offsetInArchive
) {
280 file_magic magic
= identify_magic(mb
.getBuffer());
281 if (magic
== file_magic::coff_import_library
) {
282 InputFile
*imp
= make
<ImportFile
>(ctx
, mb
);
283 imp
->parentName
= parentName
;
284 ctx
.symtab
.addFile(imp
);
289 if (magic
== file_magic::coff_object
) {
290 obj
= make
<ObjFile
>(ctx
, mb
);
291 } else if (magic
== file_magic::bitcode
) {
293 make
<BitcodeFile
>(ctx
, mb
, parentName
, offsetInArchive
, /*lazy=*/false);
294 } else if (magic
== file_magic::coff_cl_gl_object
) {
295 error(mb
.getBufferIdentifier() +
296 ": is not a native COFF file. Recompile without /GL?");
299 error("unknown file type: " + mb
.getBufferIdentifier());
303 obj
->parentName
= parentName
;
304 ctx
.symtab
.addFile(obj
);
305 log("Loaded " + toString(obj
) + " for " + symName
);
308 void LinkerDriver::enqueueArchiveMember(const Archive::Child
&c
,
309 const Archive::Symbol
&sym
,
310 StringRef parentName
) {
312 auto reportBufferError
= [=](Error
&&e
, StringRef childName
) {
313 fatal("could not get the buffer for the member defining symbol " +
314 toCOFFString(ctx
, sym
) + ": " + parentName
+ "(" + childName
+
315 "): " + toString(std::move(e
)));
318 if (!c
.getParent()->isThin()) {
319 uint64_t offsetInArchive
= c
.getChildOffset();
320 Expected
<MemoryBufferRef
> mbOrErr
= c
.getMemoryBufferRef();
322 reportBufferError(mbOrErr
.takeError(), check(c
.getFullName()));
323 MemoryBufferRef mb
= mbOrErr
.get();
325 llvm::TimeTraceScope
timeScope("Archive: ", mb
.getBufferIdentifier());
326 ctx
.driver
.addArchiveBuffer(mb
, toCOFFString(ctx
, sym
), parentName
,
332 std::string childName
=
333 CHECK(c
.getFullName(),
334 "could not get the filename for the member defining symbol " +
335 toCOFFString(ctx
, sym
));
337 std::make_shared
<std::future
<MBErrPair
>>(createFutureForFile(childName
));
339 auto mbOrErr
= future
->get();
341 reportBufferError(errorCodeToError(mbOrErr
.second
), childName
);
342 llvm::TimeTraceScope
timeScope("Archive: ",
343 mbOrErr
.first
->getBufferIdentifier());
344 // Pass empty string as archive name so that the original filename is
345 // used as the buffer identifier.
346 ctx
.driver
.addArchiveBuffer(takeBuffer(std::move(mbOrErr
.first
)),
347 toCOFFString(ctx
, sym
), "",
348 /*OffsetInArchive=*/0);
352 bool LinkerDriver::isDecorated(StringRef sym
) {
353 return sym
.starts_with("@") || sym
.contains("@@") || sym
.starts_with("?") ||
354 (!ctx
.config
.mingw
&& sym
.contains('@'));
357 // Parses .drectve section contents and returns a list of files
358 // specified by /defaultlib.
359 void LinkerDriver::parseDirectives(InputFile
*file
) {
360 StringRef s
= file
->getDirectives();
364 log("Directives: " + toString(file
) + ": " + s
);
366 ArgParser
parser(ctx
);
367 // .drectve is always tokenized using Windows shell rules.
368 // /EXPORT: option can appear too many times, processing in fastpath.
369 ParsedDirectives directives
= parser
.parseDirectives(s
);
371 for (StringRef e
: directives
.exports
) {
372 // If a common header file contains dllexported function
373 // declarations, many object files may end up with having the
374 // same /EXPORT options. In order to save cost of parsing them,
375 // we dedup them first.
376 if (!directivesExports
.insert(e
).second
)
379 Export exp
= parseExport(e
);
380 if (ctx
.config
.machine
== I386
&& ctx
.config
.mingw
) {
381 if (!isDecorated(exp
.name
))
382 exp
.name
= saver().save("_" + exp
.name
);
383 if (!exp
.extName
.empty() && !isDecorated(exp
.extName
))
384 exp
.extName
= saver().save("_" + exp
.extName
);
386 exp
.source
= ExportSource::Directives
;
387 ctx
.config
.exports
.push_back(exp
);
390 // Handle /include: in bulk.
391 for (StringRef inc
: directives
.includes
)
394 // Handle /exclude-symbols: in bulk.
395 for (StringRef e
: directives
.excludes
) {
396 SmallVector
<StringRef
, 2> vec
;
398 for (StringRef sym
: vec
)
399 excludedSymbols
.insert(mangle(sym
));
402 // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
403 for (auto *arg
: directives
.args
) {
404 switch (arg
->getOption().getID()) {
406 parseAligncomm(arg
->getValue());
408 case OPT_alternatename
:
409 parseAlternateName(arg
->getValue());
412 if (std::optional
<StringRef
> path
= findLibIfNew(arg
->getValue()))
413 enqueuePath(*path
, false, false);
416 if (!arg
->getValue()[0])
417 fatal("missing entry point symbol name");
418 ctx
.config
.entry
= addUndefined(mangle(arg
->getValue()), true);
420 case OPT_failifmismatch
:
421 checkFailIfMismatch(arg
->getValue(), file
);
424 addUndefined(arg
->getValue());
426 case OPT_manifestdependency
:
427 ctx
.config
.manifestDependencies
.insert(arg
->getValue());
430 parseMerge(arg
->getValue());
432 case OPT_nodefaultlib
:
433 ctx
.config
.noDefaultLibs
.insert(findLib(arg
->getValue()).lower());
436 ctx
.config
.writeCheckSum
= true;
439 parseSection(arg
->getValue());
442 parseNumbers(arg
->getValue(), &ctx
.config
.stackReserve
,
443 &ctx
.config
.stackCommit
);
445 case OPT_subsystem
: {
446 bool gotVersion
= false;
447 parseSubsystem(arg
->getValue(), &ctx
.config
.subsystem
,
448 &ctx
.config
.majorSubsystemVersion
,
449 &ctx
.config
.minorSubsystemVersion
, &gotVersion
);
451 ctx
.config
.majorOSVersion
= ctx
.config
.majorSubsystemVersion
;
452 ctx
.config
.minorOSVersion
= ctx
.config
.minorSubsystemVersion
;
456 // Only add flags here that link.exe accepts in
457 // `#pragma comment(linker, "/flag")`-generated sections.
458 case OPT_editandcontinue
:
460 case OPT_throwingnew
:
461 case OPT_inferasanlibs
:
462 case OPT_inferasanlibs_no
:
465 error(arg
->getSpelling() + " is not allowed in .drectve (" +
466 toString(file
) + ")");
471 // Find file from search paths. You can omit ".obj", this function takes
472 // care of that. Note that the returned path is not guaranteed to exist.
473 StringRef
LinkerDriver::findFile(StringRef filename
) {
474 auto getFilename
= [this](StringRef filename
) -> StringRef
{
476 if (auto statOrErr
= ctx
.config
.vfs
->status(filename
))
477 return saver().save(statOrErr
->getName());
481 if (sys::path::is_absolute(filename
))
482 return getFilename(filename
);
483 bool hasExt
= filename
.contains('.');
484 for (StringRef dir
: searchPaths
) {
485 SmallString
<128> path
= dir
;
486 sys::path::append(path
, filename
);
487 path
= SmallString
<128>{getFilename(path
.str())};
488 if (sys::fs::exists(path
.str()))
489 return saver().save(path
.str());
492 path
= SmallString
<128>{getFilename(path
.str())};
493 if (sys::fs::exists(path
.str()))
494 return saver().save(path
.str());
500 static std::optional
<sys::fs::UniqueID
> getUniqueID(StringRef path
) {
501 sys::fs::UniqueID ret
;
502 if (sys::fs::getUniqueID(path
, ret
))
507 // Resolves a file path. This never returns the same path
508 // (in that case, it returns std::nullopt).
509 std::optional
<StringRef
> LinkerDriver::findFileIfNew(StringRef filename
) {
510 StringRef path
= findFile(filename
);
512 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
)) {
513 bool seen
= !visitedFiles
.insert(*id
).second
;
518 if (path
.ends_with_insensitive(".lib"))
519 visitedLibs
.insert(std::string(sys::path::filename(path
).lower()));
523 // MinGW specific. If an embedded directive specified to link to
524 // foo.lib, but it isn't found, try libfoo.a instead.
525 StringRef
LinkerDriver::findLibMinGW(StringRef filename
) {
526 if (filename
.contains('/') || filename
.contains('\\'))
529 SmallString
<128> s
= filename
;
530 sys::path::replace_extension(s
, ".a");
531 StringRef libName
= saver().save("lib" + s
.str());
532 return findFile(libName
);
535 // Find library file from search path.
536 StringRef
LinkerDriver::findLib(StringRef filename
) {
537 // Add ".lib" to Filename if that has no file extension.
538 bool hasExt
= filename
.contains('.');
540 filename
= saver().save(filename
+ ".lib");
541 StringRef ret
= findFile(filename
);
542 // For MinGW, if the find above didn't turn up anything, try
543 // looking for a MinGW formatted library name.
544 if (ctx
.config
.mingw
&& ret
== filename
)
545 return findLibMinGW(filename
);
549 // Resolves a library path. /nodefaultlib options are taken into
550 // consideration. This never returns the same path (in that case,
551 // it returns std::nullopt).
552 std::optional
<StringRef
> LinkerDriver::findLibIfNew(StringRef filename
) {
553 if (ctx
.config
.noDefaultLibAll
)
555 if (!visitedLibs
.insert(filename
.lower()).second
)
558 StringRef path
= findLib(filename
);
559 if (ctx
.config
.noDefaultLibs
.count(path
.lower()))
562 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
563 if (!visitedFiles
.insert(*id
).second
)
568 void LinkerDriver::detectWinSysRoot(const opt::InputArgList
&Args
) {
569 IntrusiveRefCntPtr
<vfs::FileSystem
> VFS
= vfs::getRealFileSystem();
571 // Check the command line first, that's the user explicitly telling us what to
572 // use. Check the environment next, in case we're being invoked from a VS
573 // command prompt. Failing that, just try to find the newest Visual Studio
574 // version we can and use its default VC toolchain.
575 std::optional
<StringRef
> VCToolsDir
, VCToolsVersion
, WinSysRoot
;
576 if (auto *A
= Args
.getLastArg(OPT_vctoolsdir
))
577 VCToolsDir
= A
->getValue();
578 if (auto *A
= Args
.getLastArg(OPT_vctoolsversion
))
579 VCToolsVersion
= A
->getValue();
580 if (auto *A
= Args
.getLastArg(OPT_winsysroot
))
581 WinSysRoot
= A
->getValue();
582 if (!findVCToolChainViaCommandLine(*VFS
, VCToolsDir
, VCToolsVersion
,
583 WinSysRoot
, vcToolChainPath
, vsLayout
) &&
584 (Args
.hasArg(OPT_lldignoreenv
) ||
585 !findVCToolChainViaEnvironment(*VFS
, vcToolChainPath
, vsLayout
)) &&
586 !findVCToolChainViaSetupConfig(*VFS
, {}, vcToolChainPath
, vsLayout
) &&
587 !findVCToolChainViaRegistry(vcToolChainPath
, vsLayout
))
590 // If the VC environment hasn't been configured (perhaps because the user did
591 // not run vcvarsall), try to build a consistent link environment. If the
592 // environment variable is set however, assume the user knows what they're
593 // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
595 if (const auto *A
= Args
.getLastArg(OPT_diasdkdir
, OPT_winsysroot
)) {
596 diaPath
= A
->getValue();
597 if (A
->getOption().getID() == OPT_winsysroot
)
598 path::append(diaPath
, "DIA SDK");
600 useWinSysRootLibPath
= Args
.hasArg(OPT_lldignoreenv
) ||
601 !Process::GetEnv("LIB") ||
602 Args
.getLastArg(OPT_vctoolsdir
, OPT_winsysroot
);
603 if (Args
.hasArg(OPT_lldignoreenv
) || !Process::GetEnv("LIB") ||
604 Args
.getLastArg(OPT_winsdkdir
, OPT_winsysroot
)) {
605 std::optional
<StringRef
> WinSdkDir
, WinSdkVersion
;
606 if (auto *A
= Args
.getLastArg(OPT_winsdkdir
))
607 WinSdkDir
= A
->getValue();
608 if (auto *A
= Args
.getLastArg(OPT_winsdkversion
))
609 WinSdkVersion
= A
->getValue();
611 if (useUniversalCRT(vsLayout
, vcToolChainPath
, getArch(), *VFS
)) {
612 std::string UniversalCRTSdkPath
;
613 std::string UCRTVersion
;
614 if (getUniversalCRTSdkDir(*VFS
, WinSdkDir
, WinSdkVersion
, WinSysRoot
,
615 UniversalCRTSdkPath
, UCRTVersion
)) {
616 universalCRTLibPath
= UniversalCRTSdkPath
;
617 path::append(universalCRTLibPath
, "Lib", UCRTVersion
, "ucrt");
622 std::string windowsSDKIncludeVersion
;
623 std::string windowsSDKLibVersion
;
624 if (getWindowsSDKDir(*VFS
, WinSdkDir
, WinSdkVersion
, WinSysRoot
, sdkPath
,
625 sdkMajor
, windowsSDKIncludeVersion
,
626 windowsSDKLibVersion
)) {
627 windowsSdkLibPath
= sdkPath
;
628 path::append(windowsSdkLibPath
, "Lib");
630 path::append(windowsSdkLibPath
, windowsSDKLibVersion
, "um");
635 void LinkerDriver::addClangLibSearchPaths(const std::string
&argv0
) {
636 std::string lldBinary
= sys::fs::getMainExecutable(argv0
.c_str(), nullptr);
637 SmallString
<128> binDir(lldBinary
);
638 sys::path::remove_filename(binDir
); // remove lld-link.exe
639 StringRef rootDir
= sys::path::parent_path(binDir
); // remove 'bin'
641 SmallString
<128> libDir(rootDir
);
642 sys::path::append(libDir
, "lib");
644 // Add the resource dir library path
645 SmallString
<128> runtimeLibDir(rootDir
);
646 sys::path::append(runtimeLibDir
, "lib", "clang",
647 std::to_string(LLVM_VERSION_MAJOR
), "lib");
648 // Resource dir + osname, which is hardcoded to windows since we are in the
650 SmallString
<128> runtimeLibDirWithOS(runtimeLibDir
);
651 sys::path::append(runtimeLibDirWithOS
, "windows");
653 searchPaths
.push_back(saver().save(runtimeLibDirWithOS
.str()));
654 searchPaths
.push_back(saver().save(runtimeLibDir
.str()));
655 searchPaths
.push_back(saver().save(libDir
.str()));
658 void LinkerDriver::addWinSysRootLibSearchPaths() {
659 if (!diaPath
.empty()) {
660 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
661 path::append(diaPath
, "lib", archToLegacyVCArch(getArch()));
662 searchPaths
.push_back(saver().save(diaPath
.str()));
664 if (useWinSysRootLibPath
) {
665 searchPaths
.push_back(saver().save(getSubDirectoryPath(
666 SubDirectoryType::Lib
, vsLayout
, vcToolChainPath
, getArch())));
667 searchPaths
.push_back(saver().save(
668 getSubDirectoryPath(SubDirectoryType::Lib
, vsLayout
, vcToolChainPath
,
669 getArch(), "atlmfc")));
671 if (!universalCRTLibPath
.empty()) {
672 StringRef ArchName
= archToWindowsSDKArch(getArch());
673 if (!ArchName
.empty()) {
674 path::append(universalCRTLibPath
, ArchName
);
675 searchPaths
.push_back(saver().save(universalCRTLibPath
.str()));
678 if (!windowsSdkLibPath
.empty()) {
680 if (appendArchToWindowsSDKLibPath(sdkMajor
, windowsSdkLibPath
, getArch(),
682 searchPaths
.push_back(saver().save(path
));
686 // Parses LIB environment which contains a list of search paths.
687 void LinkerDriver::addLibSearchPaths() {
688 std::optional
<std::string
> envOpt
= Process::GetEnv("LIB");
691 StringRef env
= saver().save(*envOpt
);
692 while (!env
.empty()) {
694 std::tie(path
, env
) = env
.split(';');
695 searchPaths
.push_back(path
);
699 Symbol
*LinkerDriver::addUndefined(StringRef name
, bool aliasEC
) {
700 Symbol
*b
= ctx
.symtab
.addUndefined(name
);
703 ctx
.config
.gcroot
.push_back(b
);
706 // On ARM64EC, a symbol may be defined in either its mangled or demangled form
707 // (or both). Define an anti-dependency symbol that binds both forms, similar
708 // to how compiler-generated code references external functions.
709 if (aliasEC
&& isArm64EC(ctx
.config
.machine
)) {
710 if (std::optional
<std::string
> mangledName
=
711 getArm64ECMangledFunctionName(name
)) {
712 auto u
= dyn_cast
<Undefined
>(b
);
713 if (u
&& !u
->weakAlias
) {
714 Symbol
*t
= ctx
.symtab
.addUndefined(saver().save(*mangledName
));
715 u
->setWeakAlias(t
, true);
717 } else if (std::optional
<std::string
> demangledName
=
718 getArm64ECDemangledFunctionName(name
)) {
719 Symbol
*us
= ctx
.symtab
.addUndefined(saver().save(*demangledName
));
720 auto u
= dyn_cast
<Undefined
>(us
);
721 if (u
&& !u
->weakAlias
)
722 u
->setWeakAlias(b
, true);
728 void LinkerDriver::addUndefinedGlob(StringRef arg
) {
729 Expected
<GlobPattern
> pat
= GlobPattern::create(arg
);
731 error("/includeglob: " + toString(pat
.takeError()));
735 SmallVector
<Symbol
*, 0> syms
;
736 ctx
.symtab
.forEachSymbol([&syms
, &pat
](Symbol
*sym
) {
737 if (pat
->match(sym
->getName())) {
742 for (Symbol
*sym
: syms
)
743 addUndefined(sym
->getName());
746 StringRef
LinkerDriver::mangleMaybe(Symbol
*s
) {
747 // If the plain symbol name has already been resolved, do nothing.
748 Undefined
*unmangled
= dyn_cast
<Undefined
>(s
);
752 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
753 Symbol
*mangled
= ctx
.symtab
.findMangle(unmangled
->getName());
757 // If we find a similar mangled symbol, make this an alias to it and return
759 log(unmangled
->getName() + " aliased to " + mangled
->getName());
760 unmangled
->setWeakAlias(ctx
.symtab
.addUndefined(mangled
->getName()));
761 return mangled
->getName();
764 // Windows specific -- find default entry point name.
766 // There are four different entry point functions for Windows executables,
767 // each of which corresponds to a user-defined "main" function. This function
768 // infers an entry point from a user-defined "main" function.
769 StringRef
LinkerDriver::findDefaultEntry() {
770 assert(ctx
.config
.subsystem
!= IMAGE_SUBSYSTEM_UNKNOWN
&&
771 "must handle /subsystem before calling this");
773 if (ctx
.config
.mingw
)
774 return mangle(ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
775 ? "WinMainCRTStartup"
778 if (ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
) {
779 if (findUnderscoreMangle("wWinMain")) {
780 if (!findUnderscoreMangle("WinMain"))
781 return mangle("wWinMainCRTStartup");
782 warn("found both wWinMain and WinMain; using latter");
784 return mangle("WinMainCRTStartup");
786 if (findUnderscoreMangle("wmain")) {
787 if (!findUnderscoreMangle("main"))
788 return mangle("wmainCRTStartup");
789 warn("found both wmain and main; using latter");
791 return mangle("mainCRTStartup");
794 WindowsSubsystem
LinkerDriver::inferSubsystem() {
796 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
797 if (ctx
.config
.mingw
)
798 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
799 // Note that link.exe infers the subsystem from the presence of these
800 // functions even if /entry: or /nodefaultlib are passed which causes them
802 bool haveMain
= findUnderscoreMangle("main");
803 bool haveWMain
= findUnderscoreMangle("wmain");
804 bool haveWinMain
= findUnderscoreMangle("WinMain");
805 bool haveWWinMain
= findUnderscoreMangle("wWinMain");
806 if (haveMain
|| haveWMain
) {
807 if (haveWinMain
|| haveWWinMain
) {
808 warn(std::string("found ") + (haveMain
? "main" : "wmain") + " and " +
809 (haveWinMain
? "WinMain" : "wWinMain") +
810 "; defaulting to /subsystem:console");
812 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
814 if (haveWinMain
|| haveWWinMain
)
815 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
816 return IMAGE_SUBSYSTEM_UNKNOWN
;
819 uint64_t LinkerDriver::getDefaultImageBase() {
820 if (ctx
.config
.is64())
821 return ctx
.config
.dll
? 0x180000000 : 0x140000000;
822 return ctx
.config
.dll
? 0x10000000 : 0x400000;
825 static std::string
rewritePath(StringRef s
) {
827 return relativeToRoot(s
);
828 return std::string(s
);
831 // Reconstructs command line arguments so that so that you can re-run
832 // the same command with the same inputs. This is for --reproduce.
833 static std::string
createResponseFile(const opt::InputArgList
&args
,
834 ArrayRef
<StringRef
> filePaths
,
835 ArrayRef
<StringRef
> searchPaths
) {
837 raw_svector_ostream
os(data
);
839 for (auto *arg
: args
) {
840 switch (arg
->getOption().getID()) {
848 case OPT_call_graph_ordering_file
:
850 case OPT_manifestinput
:
852 os
<< arg
->getSpelling() << quote(rewritePath(arg
->getValue())) << '\n';
855 StringRef orderFile
= arg
->getValue();
856 orderFile
.consume_front("@");
857 os
<< arg
->getSpelling() << '@' << quote(rewritePath(orderFile
)) << '\n';
860 case OPT_pdbstream
: {
861 const std::pair
<StringRef
, StringRef
> nameFile
=
862 StringRef(arg
->getValue()).split("=");
863 os
<< arg
->getSpelling() << nameFile
.first
<< '='
864 << quote(rewritePath(nameFile
.second
)) << '\n';
868 case OPT_manifestfile
:
870 case OPT_pdbstripped
:
872 os
<< arg
->getSpelling() << sys::path::filename(arg
->getValue()) << "\n";
875 os
<< toString(*arg
) << "\n";
879 for (StringRef path
: searchPaths
) {
880 std::string relPath
= relativeToRoot(path
);
881 os
<< "/libpath:" << quote(relPath
) << "\n";
884 for (StringRef path
: filePaths
)
885 os
<< quote(relativeToRoot(path
)) << "\n";
887 return std::string(data
);
890 static unsigned parseDebugTypes(const opt::InputArgList
&args
) {
891 unsigned debugTypes
= static_cast<unsigned>(DebugType::None
);
893 if (auto *a
= args
.getLastArg(OPT_debugtype
)) {
894 SmallVector
<StringRef
, 3> types
;
895 StringRef(a
->getValue())
896 .split(types
, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
898 for (StringRef type
: types
) {
899 unsigned v
= StringSwitch
<unsigned>(type
.lower())
900 .Case("cv", static_cast<unsigned>(DebugType::CV
))
901 .Case("pdata", static_cast<unsigned>(DebugType::PData
))
902 .Case("fixup", static_cast<unsigned>(DebugType::Fixup
))
905 warn("/debugtype: unknown option '" + type
+ "'");
913 // Default debug types
914 debugTypes
= static_cast<unsigned>(DebugType::CV
);
915 if (args
.hasArg(OPT_driver
))
916 debugTypes
|= static_cast<unsigned>(DebugType::PData
);
917 if (args
.hasArg(OPT_profile
))
918 debugTypes
|= static_cast<unsigned>(DebugType::Fixup
);
923 std::string
LinkerDriver::getMapFile(const opt::InputArgList
&args
,
924 opt::OptSpecifier os
,
925 opt::OptSpecifier osFile
) {
926 auto *arg
= args
.getLastArg(os
, osFile
);
929 if (arg
->getOption().getID() == osFile
.getID())
930 return arg
->getValue();
932 assert(arg
->getOption().getID() == os
.getID());
933 StringRef outFile
= ctx
.config
.outputFile
;
934 return (outFile
.substr(0, outFile
.rfind('.')) + ".map").str();
937 std::string
LinkerDriver::getImplibPath() {
938 if (!ctx
.config
.implib
.empty())
939 return std::string(ctx
.config
.implib
);
940 SmallString
<128> out
= StringRef(ctx
.config
.outputFile
);
941 sys::path::replace_extension(out
, ".lib");
942 return std::string(out
);
945 // The import name is calculated as follows:
947 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
948 // -----+----------------+---------------------+------------------
949 // LINK | {value} | {value}.{.dll/.exe} | {output name}
950 // LIB | {value} | {value}.dll | {output name}.dll
952 std::string
LinkerDriver::getImportName(bool asLib
) {
953 SmallString
<128> out
;
955 if (ctx
.config
.importName
.empty()) {
956 out
.assign(sys::path::filename(ctx
.config
.outputFile
));
958 sys::path::replace_extension(out
, ".dll");
960 out
.assign(ctx
.config
.importName
);
961 if (!sys::path::has_extension(out
))
962 sys::path::replace_extension(out
,
963 (ctx
.config
.dll
|| asLib
) ? ".dll" : ".exe");
966 return std::string(out
);
969 void LinkerDriver::createImportLibrary(bool asLib
) {
970 llvm::TimeTraceScope
timeScope("Create import library");
971 std::vector
<COFFShortExport
> exports
;
972 for (Export
&e1
: ctx
.config
.exports
) {
974 e2
.Name
= std::string(e1
.name
);
975 e2
.SymbolName
= std::string(e1
.symbolName
);
976 e2
.ExtName
= std::string(e1
.extName
);
977 e2
.ExportAs
= std::string(e1
.exportAs
);
978 e2
.ImportName
= std::string(e1
.importName
);
979 e2
.Ordinal
= e1
.ordinal
;
980 e2
.Noname
= e1
.noname
;
982 e2
.Private
= e1
.isPrivate
;
983 e2
.Constant
= e1
.constant
;
984 exports
.push_back(e2
);
987 std::string libName
= getImportName(asLib
);
988 std::string path
= getImplibPath();
990 if (!ctx
.config
.incremental
) {
991 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
996 // If the import library already exists, replace it only if the contents
998 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> oldBuf
= MemoryBuffer::getFile(
999 path
, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1001 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
1006 SmallString
<128> tmpName
;
1007 if (std::error_code ec
=
1008 sys::fs::createUniqueFile(path
+ ".tmp-%%%%%%%%.lib", tmpName
))
1009 fatal("cannot create temporary file for import library " + path
+ ": " +
1012 if (Error e
= writeImportLibrary(libName
, tmpName
, exports
,
1013 ctx
.config
.machine
, ctx
.config
.mingw
)) {
1014 checkError(std::move(e
));
1018 std::unique_ptr
<MemoryBuffer
> newBuf
= check(MemoryBuffer::getFile(
1019 tmpName
, /*IsText=*/false, /*RequiresNullTerminator=*/false));
1020 if ((*oldBuf
)->getBuffer() != newBuf
->getBuffer()) {
1022 checkError(errorCodeToError(sys::fs::rename(tmpName
, path
)));
1024 sys::fs::remove(tmpName
);
1028 void LinkerDriver::parseModuleDefs(StringRef path
) {
1029 llvm::TimeTraceScope
timeScope("Parse def file");
1030 std::unique_ptr
<MemoryBuffer
> mb
=
1031 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1032 /*RequiresNullTerminator=*/false,
1033 /*IsVolatile=*/true),
1034 "could not open " + path
);
1035 COFFModuleDefinition m
= check(parseCOFFModuleDefinition(
1036 mb
->getMemBufferRef(), ctx
.config
.machine
, ctx
.config
.mingw
));
1038 // Include in /reproduce: output if applicable.
1039 ctx
.driver
.takeBuffer(std::move(mb
));
1041 if (ctx
.config
.outputFile
.empty())
1042 ctx
.config
.outputFile
= std::string(saver().save(m
.OutputFile
));
1043 ctx
.config
.importName
= std::string(saver().save(m
.ImportName
));
1045 ctx
.config
.imageBase
= m
.ImageBase
;
1047 ctx
.config
.stackReserve
= m
.StackReserve
;
1049 ctx
.config
.stackCommit
= m
.StackCommit
;
1051 ctx
.config
.heapReserve
= m
.HeapReserve
;
1053 ctx
.config
.heapCommit
= m
.HeapCommit
;
1054 if (m
.MajorImageVersion
)
1055 ctx
.config
.majorImageVersion
= m
.MajorImageVersion
;
1056 if (m
.MinorImageVersion
)
1057 ctx
.config
.minorImageVersion
= m
.MinorImageVersion
;
1058 if (m
.MajorOSVersion
)
1059 ctx
.config
.majorOSVersion
= m
.MajorOSVersion
;
1060 if (m
.MinorOSVersion
)
1061 ctx
.config
.minorOSVersion
= m
.MinorOSVersion
;
1063 for (COFFShortExport e1
: m
.Exports
) {
1065 // Renamed exports are parsed and set as "ExtName = Name". If Name has
1066 // the form "OtherDll.Func", it shouldn't be a normal exported
1067 // function but a forward to another DLL instead. This is supported
1068 // by both MS and GNU linkers.
1069 if (!e1
.ExtName
.empty() && e1
.ExtName
!= e1
.Name
&&
1070 StringRef(e1
.Name
).contains('.')) {
1071 e2
.name
= saver().save(e1
.ExtName
);
1072 e2
.forwardTo
= saver().save(e1
.Name
);
1074 e2
.name
= saver().save(e1
.Name
);
1075 e2
.extName
= saver().save(e1
.ExtName
);
1077 e2
.exportAs
= saver().save(e1
.ExportAs
);
1078 e2
.importName
= saver().save(e1
.ImportName
);
1079 e2
.ordinal
= e1
.Ordinal
;
1080 e2
.noname
= e1
.Noname
;
1082 e2
.isPrivate
= e1
.Private
;
1083 e2
.constant
= e1
.Constant
;
1084 e2
.source
= ExportSource::ModuleDefinition
;
1085 ctx
.config
.exports
.push_back(e2
);
1089 void LinkerDriver::enqueueTask(std::function
<void()> task
) {
1090 taskQueue
.push_back(std::move(task
));
1093 bool LinkerDriver::run() {
1094 llvm::TimeTraceScope
timeScope("Read input files");
1095 ScopedTimer
t(ctx
.inputFileTimer
);
1097 bool didWork
= !taskQueue
.empty();
1098 while (!taskQueue
.empty()) {
1099 taskQueue
.front()();
1100 taskQueue
.pop_front();
1105 // Parse an /order file. If an option is given, the linker places
1106 // COMDAT sections in the same order as their names appear in the
1108 void LinkerDriver::parseOrderFile(StringRef arg
) {
1109 // For some reason, the MSVC linker requires a filename to be
1111 if (!arg
.starts_with("@")) {
1112 error("malformed /order option: '@' missing");
1116 // Get a list of all comdat sections for error checking.
1117 DenseSet
<StringRef
> set
;
1118 for (Chunk
*c
: ctx
.symtab
.getChunks())
1119 if (auto *sec
= dyn_cast
<SectionChunk
>(c
))
1121 set
.insert(sec
->sym
->getName());
1124 StringRef path
= arg
.substr(1);
1125 std::unique_ptr
<MemoryBuffer
> mb
=
1126 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1127 /*RequiresNullTerminator=*/false,
1128 /*IsVolatile=*/true),
1129 "could not open " + path
);
1131 // Parse a file. An order file contains one symbol per line.
1132 // All symbols that were not present in a given order file are
1133 // considered to have the lowest priority 0 and are placed at
1134 // end of an output section.
1135 for (StringRef arg
: args::getLines(mb
->getMemBufferRef())) {
1137 if (ctx
.config
.machine
== I386
&& !isDecorated(s
))
1140 if (set
.count(s
) == 0) {
1141 if (ctx
.config
.warnMissingOrderSymbol
)
1142 warn("/order:" + arg
+ ": missing symbol: " + s
+ " [LNK4037]");
1144 ctx
.config
.order
[s
] = INT_MIN
+ ctx
.config
.order
.size();
1147 // Include in /reproduce: output if applicable.
1148 ctx
.driver
.takeBuffer(std::move(mb
));
1151 void LinkerDriver::parseCallGraphFile(StringRef path
) {
1152 std::unique_ptr
<MemoryBuffer
> mb
=
1153 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1154 /*RequiresNullTerminator=*/false,
1155 /*IsVolatile=*/true),
1156 "could not open " + path
);
1158 // Build a map from symbol name to section.
1159 DenseMap
<StringRef
, Symbol
*> map
;
1160 for (ObjFile
*file
: ctx
.objFileInstances
)
1161 for (Symbol
*sym
: file
->getSymbols())
1163 map
[sym
->getName()] = sym
;
1165 auto findSection
= [&](StringRef name
) -> SectionChunk
* {
1166 Symbol
*sym
= map
.lookup(name
);
1168 if (ctx
.config
.warnMissingOrderSymbol
)
1169 warn(path
+ ": no such symbol: " + name
);
1173 if (DefinedCOFF
*dr
= dyn_cast_or_null
<DefinedCOFF
>(sym
))
1174 return dyn_cast_or_null
<SectionChunk
>(dr
->getChunk());
1178 for (StringRef line
: args::getLines(*mb
)) {
1179 SmallVector
<StringRef
, 3> fields
;
1180 line
.split(fields
, ' ');
1183 if (fields
.size() != 3 || !to_integer(fields
[2], count
)) {
1184 error(path
+ ": parse error");
1188 if (SectionChunk
*from
= findSection(fields
[0]))
1189 if (SectionChunk
*to
= findSection(fields
[1]))
1190 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1193 // Include in /reproduce: output if applicable.
1194 ctx
.driver
.takeBuffer(std::move(mb
));
1197 static void readCallGraphsFromObjectFiles(COFFLinkerContext
&ctx
) {
1198 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1199 if (obj
->callgraphSec
) {
1200 ArrayRef
<uint8_t> contents
;
1202 obj
->getCOFFObj()->getSectionContents(obj
->callgraphSec
, contents
));
1203 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
1204 while (!reader
.empty()) {
1205 uint32_t fromIndex
, toIndex
;
1207 if (Error err
= reader
.readInteger(fromIndex
))
1208 fatal(toString(obj
) + ": Expected 32-bit integer");
1209 if (Error err
= reader
.readInteger(toIndex
))
1210 fatal(toString(obj
) + ": Expected 32-bit integer");
1211 if (Error err
= reader
.readInteger(count
))
1212 fatal(toString(obj
) + ": Expected 64-bit integer");
1213 auto *fromSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(fromIndex
));
1214 auto *toSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(toIndex
));
1215 if (!fromSym
|| !toSym
)
1217 auto *from
= dyn_cast_or_null
<SectionChunk
>(fromSym
->getChunk());
1218 auto *to
= dyn_cast_or_null
<SectionChunk
>(toSym
->getChunk());
1220 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1226 static void markAddrsig(Symbol
*s
) {
1227 if (auto *d
= dyn_cast_or_null
<Defined
>(s
))
1228 if (SectionChunk
*c
= dyn_cast_or_null
<SectionChunk
>(d
->getChunk()))
1229 c
->keepUnique
= true;
1232 static void findKeepUniqueSections(COFFLinkerContext
&ctx
) {
1233 llvm::TimeTraceScope
timeScope("Find keep unique sections");
1235 // Exported symbols could be address-significant in other executables or DSOs,
1236 // so we conservatively mark them as address-significant.
1237 for (Export
&r
: ctx
.config
.exports
)
1240 // Visit the address-significance table in each object file and mark each
1241 // referenced symbol as address-significant.
1242 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1243 ArrayRef
<Symbol
*> syms
= obj
->getSymbols();
1244 if (obj
->addrsigSec
) {
1245 ArrayRef
<uint8_t> contents
;
1247 obj
->getCOFFObj()->getSectionContents(obj
->addrsigSec
, contents
));
1248 const uint8_t *cur
= contents
.begin();
1249 while (cur
!= contents
.end()) {
1251 const char *err
= nullptr;
1252 uint64_t symIndex
= decodeULEB128(cur
, &size
, contents
.end(), &err
);
1254 fatal(toString(obj
) + ": could not decode addrsig section: " + err
);
1255 if (symIndex
>= syms
.size())
1256 fatal(toString(obj
) + ": invalid symbol index in addrsig section");
1257 markAddrsig(syms
[symIndex
]);
1261 // If an object file does not have an address-significance table,
1262 // conservatively mark all of its symbols as address-significant.
1263 for (Symbol
*s
: syms
)
1269 // link.exe replaces each %foo% in altPath with the contents of environment
1270 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1271 // of pdb's output path) and _EXT (expands to the extension of the output
1273 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1275 void LinkerDriver::parsePDBAltPath() {
1276 SmallString
<128> buf
;
1277 StringRef pdbBasename
=
1278 sys::path::filename(ctx
.config
.pdbPath
, sys::path::Style::windows
);
1279 StringRef binaryExtension
=
1280 sys::path::extension(ctx
.config
.outputFile
, sys::path::Style::windows
);
1281 if (!binaryExtension
.empty())
1282 binaryExtension
= binaryExtension
.substr(1); // %_EXT% does not include '.'.
1285 // +--------- cursor ('a...' might be the empty string).
1286 // | +----- firstMark
1287 // | | +- secondMark
1291 while (cursor
< ctx
.config
.pdbAltPath
.size()) {
1292 size_t firstMark
, secondMark
;
1293 if ((firstMark
= ctx
.config
.pdbAltPath
.find('%', cursor
)) ==
1295 (secondMark
= ctx
.config
.pdbAltPath
.find('%', firstMark
+ 1)) ==
1297 // Didn't find another full fragment, treat rest of string as literal.
1298 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
));
1302 // Found a full fragment. Append text in front of first %, and interpret
1303 // text between first and second % as variable name.
1304 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
, firstMark
- cursor
));
1306 ctx
.config
.pdbAltPath
.substr(firstMark
, secondMark
- firstMark
+ 1);
1307 if (var
.equals_insensitive("%_pdb%"))
1308 buf
.append(pdbBasename
);
1309 else if (var
.equals_insensitive("%_ext%"))
1310 buf
.append(binaryExtension
);
1312 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var
+
1317 cursor
= secondMark
+ 1;
1320 ctx
.config
.pdbAltPath
= buf
;
1323 /// Convert resource files and potentially merge input resource object
1324 /// trees into one resource tree.
1325 /// Call after ObjFile::Instances is complete.
1326 void LinkerDriver::convertResources() {
1327 llvm::TimeTraceScope
timeScope("Convert resources");
1328 std::vector
<ObjFile
*> resourceObjFiles
;
1330 for (ObjFile
*f
: ctx
.objFileInstances
) {
1331 if (f
->isResourceObjFile())
1332 resourceObjFiles
.push_back(f
);
1335 if (!ctx
.config
.mingw
&&
1336 (resourceObjFiles
.size() > 1 ||
1337 (resourceObjFiles
.size() == 1 && !resources
.empty()))) {
1338 error((!resources
.empty() ? "internal .obj file created from .res files"
1339 : toString(resourceObjFiles
[1])) +
1340 ": more than one resource obj file not allowed, already got " +
1341 toString(resourceObjFiles
.front()));
1345 if (resources
.empty() && resourceObjFiles
.size() <= 1) {
1346 // No resources to convert, and max one resource object file in
1347 // the input. Keep that preconverted resource section as is.
1348 for (ObjFile
*f
: resourceObjFiles
)
1349 f
->includeResourceChunks();
1353 make
<ObjFile
>(ctx
, convertResToCOFF(resources
, resourceObjFiles
));
1354 ctx
.symtab
.addFile(f
);
1355 f
->includeResourceChunks();
1358 void LinkerDriver::maybeCreateECExportThunk(StringRef name
, Symbol
*&sym
) {
1362 if (auto undef
= dyn_cast
<Undefined
>(sym
))
1363 def
= undef
->getDefinedWeakAlias();
1365 def
= dyn_cast
<Defined
>(sym
);
1369 if (def
->getChunk()->getArm64ECRangeType() != chpe_range_type::Arm64EC
)
1372 if (auto mangledName
= getArm64ECMangledFunctionName(name
))
1373 expName
= saver().save("EXP+" + *mangledName
);
1375 expName
= saver().save("EXP+" + name
);
1376 sym
= addUndefined(expName
);
1377 if (auto undef
= dyn_cast
<Undefined
>(sym
)) {
1378 if (!undef
->getWeakAlias()) {
1379 auto thunk
= make
<ECExportThunkChunk
>(def
);
1380 replaceSymbol
<DefinedSynthetic
>(undef
, undef
->getName(), thunk
);
1385 void LinkerDriver::createECExportThunks() {
1386 // Check if EXP+ symbols have corresponding $hp_target symbols and use them
1387 // to create export thunks when available.
1388 for (Symbol
*s
: ctx
.symtab
.expSymbols
) {
1389 if (!s
->isUsedInRegularObj
)
1391 assert(s
->getName().starts_with("EXP+"));
1392 std::string targetName
=
1393 (s
->getName().substr(strlen("EXP+")) + "$hp_target").str();
1394 Symbol
*sym
= ctx
.symtab
.find(targetName
);
1398 if (auto undef
= dyn_cast
<Undefined
>(sym
))
1399 targetSym
= undef
->getDefinedWeakAlias();
1401 targetSym
= dyn_cast
<Defined
>(sym
);
1405 auto *undef
= dyn_cast
<Undefined
>(s
);
1406 if (undef
&& !undef
->getWeakAlias()) {
1407 auto thunk
= make
<ECExportThunkChunk
>(targetSym
);
1408 replaceSymbol
<DefinedSynthetic
>(undef
, undef
->getName(), thunk
);
1410 if (!targetSym
->isGCRoot
) {
1411 targetSym
->isGCRoot
= true;
1412 ctx
.config
.gcroot
.push_back(targetSym
);
1416 if (ctx
.config
.entry
)
1417 maybeCreateECExportThunk(ctx
.config
.entry
->getName(), ctx
.config
.entry
);
1418 for (Export
&e
: ctx
.config
.exports
) {
1420 maybeCreateECExportThunk(e
.extName
.empty() ? e
.name
: e
.extName
, e
.sym
);
1424 void LinkerDriver::pullArm64ECIcallHelper() {
1425 if (!ctx
.config
.arm64ECIcallHelper
)
1426 ctx
.config
.arm64ECIcallHelper
= addUndefined("__icall_helper_arm64ec");
1429 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1430 // automatically exported by default. This behavior can be forced by the
1431 // -export-all-symbols option, so that it happens even when exports are
1432 // explicitly specified. The automatic behavior can be disabled using the
1433 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1434 // than MinGW in the case that nothing is explicitly exported.
1435 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList
&args
) {
1436 if (!args
.hasArg(OPT_export_all_symbols
)) {
1437 if (!ctx
.config
.dll
)
1440 if (!ctx
.config
.exports
.empty())
1442 if (args
.hasArg(OPT_exclude_all_symbols
))
1446 AutoExporter
exporter(ctx
, excludedSymbols
);
1448 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
1449 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
1450 exporter
.addWholeArchive(*path
);
1452 for (auto *arg
: args
.filtered(OPT_exclude_symbols
)) {
1453 SmallVector
<StringRef
, 2> vec
;
1454 StringRef(arg
->getValue()).split(vec
, ',');
1455 for (StringRef sym
: vec
)
1456 exporter
.addExcludedSymbol(mangle(sym
));
1459 ctx
.symtab
.forEachSymbol([&](Symbol
*s
) {
1460 auto *def
= dyn_cast
<Defined
>(s
);
1461 if (!exporter
.shouldExport(def
))
1464 if (!def
->isGCRoot
) {
1465 def
->isGCRoot
= true;
1466 ctx
.config
.gcroot
.push_back(def
);
1470 e
.name
= def
->getName();
1472 if (Chunk
*c
= def
->getChunk())
1473 if (!(c
->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE
))
1475 s
->isUsedInRegularObj
= true;
1476 ctx
.config
.exports
.push_back(e
);
1480 // lld has a feature to create a tar file containing all input files as well as
1481 // all command line options, so that other people can run lld again with exactly
1482 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1484 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1485 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1486 // with Microsoft link.exe.
1487 std::optional
<std::string
> getReproduceFile(const opt::InputArgList
&args
) {
1488 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
1489 return std::string(arg
->getValue());
1491 if (auto *arg
= args
.getLastArg(OPT_linkrepro
)) {
1492 SmallString
<64> path
= StringRef(arg
->getValue());
1493 sys::path::append(path
, "repro.tar");
1494 return std::string(path
);
1497 // This is intentionally not guarded by OPT_lldignoreenv since writing
1498 // a repro tar file doesn't affect the main output.
1499 if (auto *path
= getenv("LLD_REPRODUCE"))
1500 return std::string(path
);
1502 return std::nullopt
;
1505 static std::unique_ptr
<llvm::vfs::FileSystem
>
1506 getVFS(const opt::InputArgList
&args
) {
1507 using namespace llvm::vfs
;
1509 const opt::Arg
*arg
= args
.getLastArg(OPT_vfsoverlay
);
1513 auto bufOrErr
= llvm::MemoryBuffer::getFile(arg
->getValue());
1515 checkError(errorCodeToError(bufOrErr
.getError()));
1519 if (auto ret
= vfs::getVFSFromYAML(std::move(*bufOrErr
),
1520 /*DiagHandler*/ nullptr, arg
->getValue()))
1523 error("Invalid vfs overlay");
1527 constexpr const char *lldsaveTempsValues
[] = {
1528 "resolution", "preopt", "promote", "internalize", "import",
1529 "opt", "precodegen", "prelink", "combinedindex"};
1531 void LinkerDriver::linkerMain(ArrayRef
<const char *> argsArr
) {
1532 ScopedTimer
rootTimer(ctx
.rootTimer
);
1533 Configuration
*config
= &ctx
.config
;
1536 InitializeAllTargetInfos();
1537 InitializeAllTargets();
1538 InitializeAllTargetMCs();
1539 InitializeAllAsmParsers();
1540 InitializeAllAsmPrinters();
1542 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1543 // We call our own implementation of lib.exe that understands bitcode files.
1544 if (argsArr
.size() > 1 &&
1545 (StringRef(argsArr
[1]).equals_insensitive("/lib") ||
1546 StringRef(argsArr
[1]).equals_insensitive("-lib"))) {
1547 if (llvm::libDriverMain(argsArr
.slice(1)) != 0)
1548 fatal("lib failed");
1552 // Parse command line options.
1553 ArgParser
parser(ctx
);
1554 opt::InputArgList args
= parser
.parse(argsArr
);
1556 // Initialize time trace profiler.
1557 config
->timeTraceEnabled
= args
.hasArg(OPT_time_trace_eq
);
1558 config
->timeTraceGranularity
=
1559 args::getInteger(args
, OPT_time_trace_granularity_eq
, 500);
1561 if (config
->timeTraceEnabled
)
1562 timeTraceProfilerInitialize(config
->timeTraceGranularity
, argsArr
[0]);
1564 llvm::TimeTraceScope
timeScope("COFF link");
1566 // Parse and evaluate -mllvm options.
1567 std::vector
<const char *> v
;
1568 v
.push_back("lld-link (LLVM option parsing)");
1569 for (const auto *arg
: args
.filtered(OPT_mllvm
)) {
1570 v
.push_back(arg
->getValue());
1571 config
->mllvmOpts
.emplace_back(arg
->getValue());
1574 llvm::TimeTraceScope
timeScope2("Parse cl::opt");
1575 cl::ResetAllOptionOccurrences();
1576 cl::ParseCommandLineOptions(v
.size(), v
.data());
1579 // Handle /errorlimit early, because error() depends on it.
1580 if (auto *arg
= args
.getLastArg(OPT_errorlimit
)) {
1582 StringRef s
= arg
->getValue();
1583 if (s
.getAsInteger(10, n
))
1584 error(arg
->getSpelling() + " number expected, but got " + s
);
1585 ctx
.e
.errorLimit
= n
;
1588 config
->vfs
= getVFS(args
);
1591 if (args
.hasArg(OPT_help
)) {
1592 printHelp(argsArr
[0]);
1596 // /threads: takes a positive integer and provides the default value for
1597 // /opt:lldltojobs=.
1598 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
1599 StringRef
v(arg
->getValue());
1600 unsigned threads
= 0;
1601 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
1602 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
1603 arg
->getValue() + "'");
1604 parallel::strategy
= hardware_concurrency(threads
);
1605 config
->thinLTOJobs
= v
.str();
1608 if (args
.hasArg(OPT_show_timing
))
1609 config
->showTiming
= true;
1611 config
->showSummary
= args
.hasArg(OPT_summary
);
1612 config
->printSearchPaths
= args
.hasArg(OPT_print_search_paths
);
1614 // Handle --version, which is an lld extension. This option is a bit odd
1615 // because it doesn't start with "/", but we deliberately chose "--" to
1616 // avoid conflict with /version and for compatibility with clang-cl.
1617 if (args
.hasArg(OPT_dash_dash_version
)) {
1618 message(getLLDVersion());
1622 // Handle /lldmingw early, since it can potentially affect how other
1623 // options are handled.
1624 config
->mingw
= args
.hasArg(OPT_lldmingw
);
1626 ctx
.e
.errorLimitExceededMsg
= "too many errors emitted, stopping now"
1627 " (use --error-limit=0 to see all errors)";
1629 // Handle /linkrepro and /reproduce.
1631 llvm::TimeTraceScope
timeScope2("Reproducer");
1632 if (std::optional
<std::string
> path
= getReproduceFile(args
)) {
1633 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
1634 TarWriter::create(*path
, sys::path::stem(*path
));
1637 tar
= std::move(*errOrWriter
);
1639 error("/linkrepro: failed to open " + *path
+ ": " +
1640 toString(errOrWriter
.takeError()));
1645 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
1646 if (args
.hasArg(OPT_deffile
))
1647 config
->noEntry
= true;
1649 fatal("no input files");
1652 // Construct search path list.
1654 llvm::TimeTraceScope
timeScope2("Search paths");
1655 searchPaths
.emplace_back("");
1656 for (auto *arg
: args
.filtered(OPT_libpath
))
1657 searchPaths
.push_back(arg
->getValue());
1658 if (!config
->mingw
) {
1659 // Prefer the Clang provided builtins over the ones bundled with MSVC.
1660 // In MinGW mode, the compiler driver passes the necessary libpath
1661 // options explicitly.
1662 addClangLibSearchPaths(argsArr
[0]);
1663 // Don't automatically deduce the lib path from the environment or MSVC
1664 // installations when operating in mingw mode. (This also makes LLD ignore
1665 // winsysroot and vctoolsdir arguments.)
1666 detectWinSysRoot(args
);
1667 if (!args
.hasArg(OPT_lldignoreenv
) && !args
.hasArg(OPT_winsysroot
))
1668 addLibSearchPaths();
1670 if (args
.hasArg(OPT_vctoolsdir
, OPT_winsysroot
))
1671 warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
1676 for (auto *arg
: args
.filtered(OPT_ignore
)) {
1677 SmallVector
<StringRef
, 8> vec
;
1678 StringRef(arg
->getValue()).split(vec
, ',');
1679 for (StringRef s
: vec
) {
1681 config
->warnMissingOrderSymbol
= false;
1682 else if (s
== "4099")
1683 config
->warnDebugInfoUnusable
= false;
1684 else if (s
== "4217")
1685 config
->warnLocallyDefinedImported
= false;
1686 else if (s
== "longsections")
1687 config
->warnLongSectionNames
= false;
1688 // Other warning numbers are ignored.
1693 if (auto *arg
= args
.getLastArg(OPT_out
))
1694 config
->outputFile
= arg
->getValue();
1697 if (args
.hasArg(OPT_verbose
))
1698 config
->verbose
= true;
1699 ctx
.e
.verbose
= config
->verbose
;
1701 // Handle /force or /force:unresolved
1702 if (args
.hasArg(OPT_force
, OPT_force_unresolved
))
1703 config
->forceUnresolved
= true;
1705 // Handle /force or /force:multiple
1706 if (args
.hasArg(OPT_force
, OPT_force_multiple
))
1707 config
->forceMultiple
= true;
1709 // Handle /force or /force:multipleres
1710 if (args
.hasArg(OPT_force
, OPT_force_multipleres
))
1711 config
->forceMultipleRes
= true;
1713 // Don't warn about long section names, such as .debug_info, for mingw (or
1714 // when -debug:dwarf is requested, handled below).
1716 config
->warnLongSectionNames
= false;
1721 bool shouldCreatePDB
= false;
1722 for (auto *arg
: args
.filtered(OPT_debug
, OPT_debug_opt
)) {
1724 if (arg
->getOption().getID() == OPT_debug
)
1727 str
= StringRef(arg
->getValue()).lower();
1728 SmallVector
<StringRef
, 1> vec
;
1729 StringRef(str
).split(vec
, ',');
1730 for (StringRef s
: vec
) {
1731 if (s
== "fastlink") {
1732 warn("/debug:fastlink unsupported; using /debug:full");
1736 config
->debug
= false;
1737 config
->incremental
= false;
1738 config
->includeDwarfChunks
= false;
1739 config
->debugGHashes
= false;
1740 config
->writeSymtab
= false;
1741 shouldCreatePDB
= false;
1743 } else if (s
== "full" || s
== "ghash" || s
== "noghash") {
1744 config
->debug
= true;
1745 config
->incremental
= true;
1746 config
->includeDwarfChunks
= true;
1747 if (s
== "full" || s
== "ghash")
1748 config
->debugGHashes
= true;
1749 shouldCreatePDB
= true;
1751 } else if (s
== "dwarf") {
1752 config
->debug
= true;
1753 config
->incremental
= true;
1754 config
->includeDwarfChunks
= true;
1755 config
->writeSymtab
= true;
1756 config
->warnLongSectionNames
= false;
1758 } else if (s
== "nodwarf") {
1759 config
->includeDwarfChunks
= false;
1760 } else if (s
== "symtab") {
1761 config
->writeSymtab
= true;
1763 } else if (s
== "nosymtab") {
1764 config
->writeSymtab
= false;
1766 error("/debug: unknown option: " + s
);
1772 config
->demangle
= args
.hasFlag(OPT_demangle
, OPT_demangle_no
, true);
1774 // Handle /debugtype
1775 config
->debugTypes
= parseDebugTypes(args
);
1777 // Handle /driver[:uponly|:wdm].
1778 config
->driverUponly
= args
.hasArg(OPT_driver_uponly
) ||
1779 args
.hasArg(OPT_driver_uponly_wdm
) ||
1780 args
.hasArg(OPT_driver_wdm_uponly
);
1781 config
->driverWdm
= args
.hasArg(OPT_driver_wdm
) ||
1782 args
.hasArg(OPT_driver_uponly_wdm
) ||
1783 args
.hasArg(OPT_driver_wdm_uponly
);
1785 config
->driverUponly
|| config
->driverWdm
|| args
.hasArg(OPT_driver
);
1788 if (shouldCreatePDB
) {
1789 if (auto *arg
= args
.getLastArg(OPT_pdb
))
1790 config
->pdbPath
= arg
->getValue();
1791 if (auto *arg
= args
.getLastArg(OPT_pdbaltpath
))
1792 config
->pdbAltPath
= arg
->getValue();
1793 if (auto *arg
= args
.getLastArg(OPT_pdbpagesize
))
1794 parsePDBPageSize(arg
->getValue());
1795 if (args
.hasArg(OPT_natvis
))
1796 config
->natvisFiles
= args
.getAllArgValues(OPT_natvis
);
1797 if (args
.hasArg(OPT_pdbstream
)) {
1798 for (const StringRef value
: args
.getAllArgValues(OPT_pdbstream
)) {
1799 const std::pair
<StringRef
, StringRef
> nameFile
= value
.split("=");
1800 const StringRef name
= nameFile
.first
;
1801 const std::string file
= nameFile
.second
.str();
1802 config
->namedStreams
[name
] = file
;
1806 if (auto *arg
= args
.getLastArg(OPT_pdb_source_path
))
1807 config
->pdbSourcePath
= arg
->getValue();
1810 // Handle /pdbstripped
1811 if (args
.hasArg(OPT_pdbstripped
))
1812 warn("ignoring /pdbstripped flag, it is not yet supported");
1815 if (args
.hasArg(OPT_noentry
)) {
1816 if (args
.hasArg(OPT_dll
))
1817 config
->noEntry
= true;
1819 error("/noentry must be specified with /dll");
1823 if (args
.hasArg(OPT_dll
)) {
1825 config
->manifestID
= 2;
1828 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1829 // because we need to explicitly check whether that option or its inverse was
1830 // present in the argument list in order to handle /fixed.
1831 auto *dynamicBaseArg
= args
.getLastArg(OPT_dynamicbase
, OPT_dynamicbase_no
);
1832 if (dynamicBaseArg
&&
1833 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase_no
)
1834 config
->dynamicBase
= false;
1836 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1837 // default setting for any other project type.", but link.exe defaults to
1838 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1839 bool fixed
= args
.hasFlag(OPT_fixed
, OPT_fixed_no
, false);
1841 if (dynamicBaseArg
&&
1842 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase
) {
1843 error("/fixed must not be specified with /dynamicbase");
1845 config
->relocatable
= false;
1846 config
->dynamicBase
= false;
1850 // Handle /appcontainer
1851 config
->appContainer
=
1852 args
.hasFlag(OPT_appcontainer
, OPT_appcontainer_no
, false);
1856 llvm::TimeTraceScope
timeScope2("Machine arg");
1857 if (auto *arg
= args
.getLastArg(OPT_machine
)) {
1858 config
->machine
= getMachineType(arg
->getValue());
1859 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
)
1860 fatal(Twine("unknown /machine argument: ") + arg
->getValue());
1861 addWinSysRootLibSearchPaths();
1865 // Handle /nodefaultlib:<filename>
1867 llvm::TimeTraceScope
timeScope2("Nodefaultlib");
1868 for (auto *arg
: args
.filtered(OPT_nodefaultlib
))
1869 config
->noDefaultLibs
.insert(findLib(arg
->getValue()).lower());
1872 // Handle /nodefaultlib
1873 if (args
.hasArg(OPT_nodefaultlib_all
))
1874 config
->noDefaultLibAll
= true;
1877 if (auto *arg
= args
.getLastArg(OPT_base
))
1878 parseNumbers(arg
->getValue(), &config
->imageBase
);
1880 // Handle /filealign
1881 if (auto *arg
= args
.getLastArg(OPT_filealign
)) {
1882 parseNumbers(arg
->getValue(), &config
->fileAlign
);
1883 if (!isPowerOf2_64(config
->fileAlign
))
1884 error("/filealign: not a power of two: " + Twine(config
->fileAlign
));
1888 if (auto *arg
= args
.getLastArg(OPT_stack
))
1889 parseNumbers(arg
->getValue(), &config
->stackReserve
, &config
->stackCommit
);
1892 if (auto *arg
= args
.getLastArg(OPT_guard
))
1893 parseGuard(arg
->getValue());
1896 if (auto *arg
= args
.getLastArg(OPT_heap
))
1897 parseNumbers(arg
->getValue(), &config
->heapReserve
, &config
->heapCommit
);
1900 if (auto *arg
= args
.getLastArg(OPT_version
))
1901 parseVersion(arg
->getValue(), &config
->majorImageVersion
,
1902 &config
->minorImageVersion
);
1904 // Handle /subsystem
1905 if (auto *arg
= args
.getLastArg(OPT_subsystem
))
1906 parseSubsystem(arg
->getValue(), &config
->subsystem
,
1907 &config
->majorSubsystemVersion
,
1908 &config
->minorSubsystemVersion
);
1910 // Handle /osversion
1911 if (auto *arg
= args
.getLastArg(OPT_osversion
)) {
1912 parseVersion(arg
->getValue(), &config
->majorOSVersion
,
1913 &config
->minorOSVersion
);
1915 config
->majorOSVersion
= config
->majorSubsystemVersion
;
1916 config
->minorOSVersion
= config
->minorSubsystemVersion
;
1919 // Handle /timestamp
1920 if (llvm::opt::Arg
*arg
= args
.getLastArg(OPT_timestamp
, OPT_repro
)) {
1921 if (arg
->getOption().getID() == OPT_repro
) {
1922 config
->timestamp
= 0;
1923 config
->repro
= true;
1925 config
->repro
= false;
1926 StringRef
value(arg
->getValue());
1927 if (value
.getAsInteger(0, config
->timestamp
))
1928 fatal(Twine("invalid timestamp: ") + value
+
1929 ". Expected 32-bit integer");
1932 config
->repro
= false;
1933 if (std::optional
<std::string
> epoch
=
1934 Process::GetEnv("SOURCE_DATE_EPOCH")) {
1935 StringRef
value(*epoch
);
1936 if (value
.getAsInteger(0, config
->timestamp
))
1937 fatal(Twine("invalid SOURCE_DATE_EPOCH timestamp: ") + value
+
1938 ". Expected 32-bit integer");
1940 config
->timestamp
= time(nullptr);
1944 // Handle /alternatename
1945 for (auto *arg
: args
.filtered(OPT_alternatename
))
1946 parseAlternateName(arg
->getValue());
1949 for (auto *arg
: args
.filtered(OPT_incl
))
1950 addUndefined(arg
->getValue());
1953 if (auto *arg
= args
.getLastArg(OPT_implib
))
1954 config
->implib
= arg
->getValue();
1956 config
->noimplib
= args
.hasArg(OPT_noimplib
);
1958 if (args
.hasArg(OPT_profile
))
1961 std::optional
<ICFLevel
> icfLevel
;
1962 if (args
.hasArg(OPT_profile
))
1963 icfLevel
= ICFLevel::None
;
1964 unsigned tailMerge
= 1;
1965 bool ltoDebugPM
= false;
1966 for (auto *arg
: args
.filtered(OPT_opt
)) {
1967 std::string str
= StringRef(arg
->getValue()).lower();
1968 SmallVector
<StringRef
, 1> vec
;
1969 StringRef(str
).split(vec
, ',');
1970 for (StringRef s
: vec
) {
1973 } else if (s
== "noref") {
1975 } else if (s
== "icf" || s
.starts_with("icf=")) {
1976 icfLevel
= ICFLevel::All
;
1977 } else if (s
== "safeicf") {
1978 icfLevel
= ICFLevel::Safe
;
1979 } else if (s
== "noicf") {
1980 icfLevel
= ICFLevel::None
;
1981 } else if (s
== "lldtailmerge") {
1983 } else if (s
== "nolldtailmerge") {
1985 } else if (s
== "ltodebugpassmanager") {
1987 } else if (s
== "noltodebugpassmanager") {
1989 } else if (s
.consume_front("lldlto=")) {
1990 if (s
.getAsInteger(10, config
->ltoo
) || config
->ltoo
> 3)
1991 error("/opt:lldlto: invalid optimization level: " + s
);
1992 } else if (s
.consume_front("lldltocgo=")) {
1993 config
->ltoCgo
.emplace();
1994 if (s
.getAsInteger(10, *config
->ltoCgo
) || *config
->ltoCgo
> 3)
1995 error("/opt:lldltocgo: invalid codegen optimization level: " + s
);
1996 } else if (s
.consume_front("lldltojobs=")) {
1997 if (!get_threadpool_strategy(s
))
1998 error("/opt:lldltojobs: invalid job count: " + s
);
1999 config
->thinLTOJobs
= s
.str();
2000 } else if (s
.consume_front("lldltopartitions=")) {
2001 if (s
.getAsInteger(10, config
->ltoPartitions
) ||
2002 config
->ltoPartitions
== 0)
2003 error("/opt:lldltopartitions: invalid partition count: " + s
);
2004 } else if (s
!= "lbr" && s
!= "nolbr")
2005 error("/opt: unknown option: " + s
);
2010 icfLevel
= doGC
? ICFLevel::All
: ICFLevel::None
;
2011 config
->doGC
= doGC
;
2012 config
->doICF
= *icfLevel
;
2014 (tailMerge
== 1 && config
->doICF
!= ICFLevel::None
) || tailMerge
== 2;
2015 config
->ltoDebugPassManager
= ltoDebugPM
;
2017 // Handle /lldsavetemps
2018 if (args
.hasArg(OPT_lldsavetemps
)) {
2019 for (const char *s
: lldsaveTempsValues
)
2020 config
->saveTempsArgs
.insert(s
);
2022 for (auto *arg
: args
.filtered(OPT_lldsavetemps_colon
)) {
2023 StringRef s
= arg
->getValue();
2024 if (llvm::is_contained(lldsaveTempsValues
, s
))
2025 config
->saveTempsArgs
.insert(s
);
2027 error("unknown /lldsavetemps value: " + s
);
2032 if (auto *arg
= args
.getLastArg(OPT_lldemit
)) {
2033 StringRef s
= arg
->getValue();
2035 config
->emit
= EmitKind::Obj
;
2036 else if (s
== "llvm")
2037 config
->emit
= EmitKind::LLVM
;
2038 else if (s
== "asm")
2039 config
->emit
= EmitKind::ASM
;
2041 error("/lldemit: unknown option: " + s
);
2045 if (args
.hasArg(OPT_kill_at
))
2046 config
->killAt
= true;
2048 // Handle /lldltocache
2049 if (auto *arg
= args
.getLastArg(OPT_lldltocache
))
2050 config
->ltoCache
= arg
->getValue();
2052 // Handle /lldsavecachepolicy
2053 if (auto *arg
= args
.getLastArg(OPT_lldltocachepolicy
))
2054 config
->ltoCachePolicy
= CHECK(
2055 parseCachePruningPolicy(arg
->getValue()),
2056 Twine("/lldltocachepolicy: invalid cache policy: ") + arg
->getValue());
2058 // Handle /failifmismatch
2059 for (auto *arg
: args
.filtered(OPT_failifmismatch
))
2060 checkFailIfMismatch(arg
->getValue(), nullptr);
2063 for (auto *arg
: args
.filtered(OPT_merge
))
2064 parseMerge(arg
->getValue());
2066 // Add default section merging rules after user rules. User rules take
2067 // precedence, but we will emit a warning if there is a conflict.
2068 parseMerge(".idata=.rdata");
2069 parseMerge(".didat=.rdata");
2070 parseMerge(".edata=.rdata");
2071 parseMerge(".xdata=.rdata");
2072 parseMerge(".00cfg=.rdata");
2073 parseMerge(".bss=.data");
2075 if (isArm64EC(config
->machine
))
2076 parseMerge(".wowthk=.text");
2078 if (config
->mingw
) {
2079 parseMerge(".ctors=.rdata");
2080 parseMerge(".dtors=.rdata");
2081 parseMerge(".CRT=.rdata");
2085 for (auto *arg
: args
.filtered(OPT_section
))
2086 parseSection(arg
->getValue());
2089 if (auto *arg
= args
.getLastArg(OPT_align
)) {
2090 parseNumbers(arg
->getValue(), &config
->align
);
2091 if (!isPowerOf2_64(config
->align
))
2092 error("/align: not a power of two: " + StringRef(arg
->getValue()));
2093 if (!args
.hasArg(OPT_driver
))
2094 warn("/align specified without /driver; image may not run");
2097 // Handle /aligncomm
2098 for (auto *arg
: args
.filtered(OPT_aligncomm
))
2099 parseAligncomm(arg
->getValue());
2101 // Handle /manifestdependency.
2102 for (auto *arg
: args
.filtered(OPT_manifestdependency
))
2103 config
->manifestDependencies
.insert(arg
->getValue());
2105 // Handle /manifest and /manifest:
2106 if (auto *arg
= args
.getLastArg(OPT_manifest
, OPT_manifest_colon
)) {
2107 if (arg
->getOption().getID() == OPT_manifest
)
2108 config
->manifest
= Configuration::SideBySide
;
2110 parseManifest(arg
->getValue());
2113 // Handle /manifestuac
2114 if (auto *arg
= args
.getLastArg(OPT_manifestuac
))
2115 parseManifestUAC(arg
->getValue());
2117 // Handle /manifestfile
2118 if (auto *arg
= args
.getLastArg(OPT_manifestfile
))
2119 config
->manifestFile
= arg
->getValue();
2121 // Handle /manifestinput
2122 for (auto *arg
: args
.filtered(OPT_manifestinput
))
2123 config
->manifestInput
.push_back(arg
->getValue());
2125 if (!config
->manifestInput
.empty() &&
2126 config
->manifest
!= Configuration::Embed
) {
2127 fatal("/manifestinput: requires /manifest:embed");
2131 config
->dwoDir
= args
.getLastArgValue(OPT_dwodir
);
2133 config
->thinLTOEmitImportsFiles
= args
.hasArg(OPT_thinlto_emit_imports_files
);
2134 config
->thinLTOIndexOnly
= args
.hasArg(OPT_thinlto_index_only
) ||
2135 args
.hasArg(OPT_thinlto_index_only_arg
);
2136 config
->thinLTOIndexOnlyArg
=
2137 args
.getLastArgValue(OPT_thinlto_index_only_arg
);
2138 std::tie(config
->thinLTOPrefixReplaceOld
, config
->thinLTOPrefixReplaceNew
,
2139 config
->thinLTOPrefixReplaceNativeObject
) =
2140 getOldNewOptionsExtra(args
, OPT_thinlto_prefix_replace
);
2141 config
->thinLTOObjectSuffixReplace
=
2142 getOldNewOptions(args
, OPT_thinlto_object_suffix_replace
);
2143 config
->ltoObjPath
= args
.getLastArgValue(OPT_lto_obj_path
);
2144 config
->ltoCSProfileGenerate
= args
.hasArg(OPT_lto_cs_profile_generate
);
2145 config
->ltoCSProfileFile
= args
.getLastArgValue(OPT_lto_cs_profile_file
);
2146 config
->ltoSampleProfileName
= args
.getLastArgValue(OPT_lto_sample_profile
);
2147 // Handle miscellaneous boolean flags.
2148 config
->ltoPGOWarnMismatch
= args
.hasFlag(OPT_lto_pgo_warn_mismatch
,
2149 OPT_lto_pgo_warn_mismatch_no
, true);
2150 config
->allowBind
= args
.hasFlag(OPT_allowbind
, OPT_allowbind_no
, true);
2151 config
->allowIsolation
=
2152 args
.hasFlag(OPT_allowisolation
, OPT_allowisolation_no
, true);
2153 config
->incremental
=
2154 args
.hasFlag(OPT_incremental
, OPT_incremental_no
,
2155 !config
->doGC
&& config
->doICF
== ICFLevel::None
&&
2156 !args
.hasArg(OPT_order
) && !args
.hasArg(OPT_profile
));
2157 config
->integrityCheck
=
2158 args
.hasFlag(OPT_integritycheck
, OPT_integritycheck_no
, false);
2159 config
->cetCompat
= args
.hasFlag(OPT_cetcompat
, OPT_cetcompat_no
, false);
2160 config
->nxCompat
= args
.hasFlag(OPT_nxcompat
, OPT_nxcompat_no
, true);
2161 for (auto *arg
: args
.filtered(OPT_swaprun
))
2162 parseSwaprun(arg
->getValue());
2163 config
->terminalServerAware
=
2164 !config
->dll
&& args
.hasFlag(OPT_tsaware
, OPT_tsaware_no
, true);
2165 config
->autoImport
=
2166 args
.hasFlag(OPT_auto_import
, OPT_auto_import_no
, config
->mingw
);
2167 config
->pseudoRelocs
= args
.hasFlag(
2168 OPT_runtime_pseudo_reloc
, OPT_runtime_pseudo_reloc_no
, config
->mingw
);
2169 config
->callGraphProfileSort
= args
.hasFlag(
2170 OPT_call_graph_profile_sort
, OPT_call_graph_profile_sort_no
, true);
2171 config
->stdcallFixup
=
2172 args
.hasFlag(OPT_stdcall_fixup
, OPT_stdcall_fixup_no
, config
->mingw
);
2173 config
->warnStdcallFixup
= !args
.hasArg(OPT_stdcall_fixup
);
2174 config
->allowDuplicateWeak
=
2175 args
.hasFlag(OPT_lld_allow_duplicate_weak
,
2176 OPT_lld_allow_duplicate_weak_no
, config
->mingw
);
2178 if (args
.hasFlag(OPT_inferasanlibs
, OPT_inferasanlibs_no
, false))
2179 warn("ignoring '/inferasanlibs', this flag is not supported");
2181 if (config
->incremental
&& args
.hasArg(OPT_profile
)) {
2182 warn("ignoring '/incremental' due to '/profile' specification");
2183 config
->incremental
= false;
2186 if (config
->incremental
&& args
.hasArg(OPT_order
)) {
2187 warn("ignoring '/incremental' due to '/order' specification");
2188 config
->incremental
= false;
2191 if (config
->incremental
&& config
->doGC
) {
2192 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
2194 config
->incremental
= false;
2197 if (config
->incremental
&& config
->doICF
!= ICFLevel::None
) {
2198 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
2200 config
->incremental
= false;
2206 std::set
<sys::fs::UniqueID
> wholeArchives
;
2207 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
2208 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
2209 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(*path
))
2210 wholeArchives
.insert(*id
);
2212 // A predicate returning true if a given path is an argument for
2213 // /wholearchive:, or /wholearchive is enabled globally.
2214 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
2215 // needs to be handled as "/wholearchive:foo.obj foo.obj".
2216 auto isWholeArchive
= [&](StringRef path
) -> bool {
2217 if (args
.hasArg(OPT_wholearchive_flag
))
2219 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
2220 return wholeArchives
.count(*id
);
2224 // Create a list of input files. These can be given as OPT_INPUT options
2225 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
2228 llvm::TimeTraceScope
timeScope2("Parse & queue inputs");
2230 for (auto *arg
: args
) {
2231 switch (arg
->getOption().getID()) {
2234 error("stray " + arg
->getSpelling());
2239 error("nested " + arg
->getSpelling());
2242 case OPT_wholearchive_file
:
2243 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2244 enqueuePath(*path
, true, inLib
);
2247 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2248 enqueuePath(*path
, isWholeArchive(*path
), inLib
);
2251 // Ignore other options.
2257 // Read all input files given via the command line.
2262 // We should have inferred a machine type by now from the input files, but if
2263 // not we assume x64.
2264 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
) {
2265 warn("/machine is not specified. x64 is assumed");
2266 config
->machine
= AMD64
;
2267 addWinSysRootLibSearchPaths();
2269 config
->wordsize
= config
->is64() ? 8 : 4;
2271 if (config
->printSearchPaths
) {
2272 SmallString
<256> buffer
;
2273 raw_svector_ostream
stream(buffer
);
2274 stream
<< "Library search paths:\n";
2276 for (StringRef path
: searchPaths
) {
2279 stream
<< " " << path
<< "\n";
2285 // Process files specified as /defaultlib. These must be processed after
2286 // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
2287 for (auto *arg
: args
.filtered(OPT_defaultlib
))
2288 if (std::optional
<StringRef
> path
= findLibIfNew(arg
->getValue()))
2289 enqueuePath(*path
, false, false);
2295 if (args
.hasArg(OPT_release
))
2296 config
->writeCheckSum
= true;
2298 // Handle /safeseh, x86 only, on by default, except for mingw.
2299 if (config
->machine
== I386
) {
2300 config
->safeSEH
= args
.hasFlag(OPT_safeseh
, OPT_safeseh_no
, !config
->mingw
);
2301 config
->noSEH
= args
.hasArg(OPT_noseh
);
2304 // Handle /functionpadmin
2305 for (auto *arg
: args
.filtered(OPT_functionpadmin
, OPT_functionpadmin_opt
))
2306 parseFunctionPadMin(arg
);
2308 // Handle /dependentloadflag
2310 args
.filtered(OPT_dependentloadflag
, OPT_dependentloadflag_opt
))
2311 parseDependentLoadFlags(arg
);
2314 llvm::TimeTraceScope
timeScope("Reproducer: response file");
2315 tar
->append("response.txt",
2316 createResponseFile(args
, filePaths
,
2317 ArrayRef
<StringRef
>(searchPaths
).slice(1)));
2320 // Handle /largeaddressaware
2321 config
->largeAddressAware
= args
.hasFlag(
2322 OPT_largeaddressaware
, OPT_largeaddressaware_no
, config
->is64());
2324 // Handle /highentropyva
2325 config
->highEntropyVA
=
2327 args
.hasFlag(OPT_highentropyva
, OPT_highentropyva_no
, true);
2329 if (!config
->dynamicBase
&&
2330 (config
->machine
== ARMNT
|| isAnyArm64(config
->machine
)))
2331 error("/dynamicbase:no is not compatible with " +
2332 machineToStr(config
->machine
));
2336 llvm::TimeTraceScope
timeScope("Parse /export");
2337 for (auto *arg
: args
.filtered(OPT_export
)) {
2338 Export e
= parseExport(arg
->getValue());
2339 if (config
->machine
== I386
) {
2340 if (!isDecorated(e
.name
))
2341 e
.name
= saver().save("_" + e
.name
);
2342 if (!e
.extName
.empty() && !isDecorated(e
.extName
))
2343 e
.extName
= saver().save("_" + e
.extName
);
2345 config
->exports
.push_back(e
);
2350 if (auto *arg
= args
.getLastArg(OPT_deffile
)) {
2351 // parseModuleDefs mutates Config object.
2352 parseModuleDefs(arg
->getValue());
2355 // Handle generation of import library from a def file.
2356 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
2358 if (!config
->noimplib
)
2359 createImportLibrary(/*asLib=*/true);
2363 // Windows specific -- if no /subsystem is given, we need to infer
2364 // that from entry point name. Must happen before /entry handling,
2365 // and after the early return when just writing an import library.
2366 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
) {
2367 llvm::TimeTraceScope
timeScope("Infer subsystem");
2368 config
->subsystem
= inferSubsystem();
2369 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
)
2370 fatal("subsystem must be defined");
2373 // Handle /entry and /dll
2375 llvm::TimeTraceScope
timeScope("Entry point");
2376 if (auto *arg
= args
.getLastArg(OPT_entry
)) {
2377 if (!arg
->getValue()[0])
2378 fatal("missing entry point symbol name");
2379 config
->entry
= addUndefined(mangle(arg
->getValue()), true);
2380 } else if (!config
->entry
&& !config
->noEntry
) {
2381 if (args
.hasArg(OPT_dll
)) {
2382 StringRef s
= (config
->machine
== I386
) ? "__DllMainCRTStartup@12"
2383 : "_DllMainCRTStartup";
2384 config
->entry
= addUndefined(s
, true);
2385 } else if (config
->driverWdm
) {
2386 // /driver:wdm implies /entry:_NtProcessStartup
2387 config
->entry
= addUndefined(mangle("_NtProcessStartup"), true);
2389 // Windows specific -- If entry point name is not given, we need to
2390 // infer that from user-defined entry name.
2391 StringRef s
= findDefaultEntry();
2393 fatal("entry point must be defined");
2394 config
->entry
= addUndefined(s
, true);
2395 log("Entry name inferred: " + s
);
2400 // Handle /delayload
2402 llvm::TimeTraceScope
timeScope("Delay load");
2403 for (auto *arg
: args
.filtered(OPT_delayload
)) {
2404 config
->delayLoads
.insert(StringRef(arg
->getValue()).lower());
2405 if (config
->machine
== I386
) {
2406 config
->delayLoadHelper
= addUndefined("___delayLoadHelper2@8");
2408 config
->delayLoadHelper
= addUndefined("__delayLoadHelper2", true);
2413 // Set default image name if neither /out or /def set it.
2414 if (config
->outputFile
.empty()) {
2415 config
->outputFile
= getOutputPath(
2416 (*args
.filtered(OPT_INPUT
, OPT_wholearchive_file
).begin())->getValue(),
2417 config
->dll
, config
->driver
);
2420 // Fail early if an output file is not writable.
2421 if (auto e
= tryCreateFile(config
->outputFile
)) {
2422 error("cannot open output file " + config
->outputFile
+ ": " + e
.message());
2426 config
->lldmapFile
= getMapFile(args
, OPT_lldmap
, OPT_lldmap_file
);
2427 config
->mapFile
= getMapFile(args
, OPT_map
, OPT_map_file
);
2429 if (config
->mapFile
!= "" && args
.hasArg(OPT_map_info
)) {
2430 for (auto *arg
: args
.filtered(OPT_map_info
)) {
2431 std::string s
= StringRef(arg
->getValue()).lower();
2433 config
->mapInfo
= true;
2435 error("unknown option: /mapinfo:" + s
);
2439 if (config
->lldmapFile
!= "" && config
->lldmapFile
== config
->mapFile
) {
2440 warn("/lldmap and /map have the same output file '" + config
->mapFile
+
2441 "'.\n>>> ignoring /lldmap");
2442 config
->lldmapFile
.clear();
2445 // If should create PDB, use the hash of PDB content for build id. Otherwise,
2446 // generate using the hash of executable content.
2447 if (args
.hasFlag(OPT_build_id
, OPT_build_id_no
, false))
2448 config
->buildIDHash
= BuildIDHash::Binary
;
2450 if (shouldCreatePDB
) {
2451 // Put the PDB next to the image if no /pdb flag was passed.
2452 if (config
->pdbPath
.empty()) {
2453 config
->pdbPath
= config
->outputFile
;
2454 sys::path::replace_extension(config
->pdbPath
, ".pdb");
2457 // The embedded PDB path should be the absolute path to the PDB if no
2458 // /pdbaltpath flag was passed.
2459 if (config
->pdbAltPath
.empty()) {
2460 config
->pdbAltPath
= config
->pdbPath
;
2462 // It's important to make the path absolute and remove dots. This path
2463 // will eventually be written into the PE header, and certain Microsoft
2464 // tools won't work correctly if these assumptions are not held.
2465 sys::fs::make_absolute(config
->pdbAltPath
);
2466 sys::path::remove_dots(config
->pdbAltPath
);
2468 // Don't do this earlier, so that ctx.OutputFile is ready.
2471 config
->buildIDHash
= BuildIDHash::PDB
;
2474 // Set default image base if /base is not given.
2475 if (config
->imageBase
== uint64_t(-1))
2476 config
->imageBase
= getDefaultImageBase();
2478 ctx
.symtab
.addSynthetic(mangle("__ImageBase"), nullptr);
2479 if (config
->machine
== I386
) {
2480 ctx
.symtab
.addAbsolute("___safe_se_handler_table", 0);
2481 ctx
.symtab
.addAbsolute("___safe_se_handler_count", 0);
2484 ctx
.symtab
.addAbsolute(mangle("__guard_fids_count"), 0);
2485 ctx
.symtab
.addAbsolute(mangle("__guard_fids_table"), 0);
2486 ctx
.symtab
.addAbsolute(mangle("__guard_flags"), 0);
2487 ctx
.symtab
.addAbsolute(mangle("__guard_iat_count"), 0);
2488 ctx
.symtab
.addAbsolute(mangle("__guard_iat_table"), 0);
2489 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_count"), 0);
2490 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_table"), 0);
2491 // Needed for MSVC 2017 15.5 CRT.
2492 ctx
.symtab
.addAbsolute(mangle("__enclave_config"), 0);
2493 // Needed for MSVC 2019 16.8 CRT.
2494 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2495 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2497 if (isArm64EC(config
->machine
)) {
2498 ctx
.symtab
.addAbsolute("__arm64x_extra_rfe_table", 0);
2499 ctx
.symtab
.addAbsolute("__arm64x_extra_rfe_table_size", 0);
2500 ctx
.symtab
.addAbsolute("__arm64x_redirection_metadata", 0);
2501 ctx
.symtab
.addAbsolute("__arm64x_redirection_metadata_count", 0);
2502 ctx
.symtab
.addAbsolute("__hybrid_auxiliary_delayload_iat_copy", 0);
2503 ctx
.symtab
.addAbsolute("__hybrid_auxiliary_delayload_iat", 0);
2504 ctx
.symtab
.addAbsolute("__hybrid_auxiliary_iat", 0);
2505 ctx
.symtab
.addAbsolute("__hybrid_auxiliary_iat_copy", 0);
2506 ctx
.symtab
.addAbsolute("__hybrid_code_map", 0);
2507 ctx
.symtab
.addAbsolute("__hybrid_code_map_count", 0);
2508 ctx
.symtab
.addAbsolute("__hybrid_image_info_bitfield", 0);
2509 ctx
.symtab
.addAbsolute("__x64_code_ranges_to_entry_points", 0);
2510 ctx
.symtab
.addAbsolute("__x64_code_ranges_to_entry_points_count", 0);
2511 ctx
.symtab
.addSynthetic("__guard_check_icall_a64n_fptr", nullptr);
2512 ctx
.symtab
.addSynthetic("__arm64x_native_entrypoint", nullptr);
2515 if (config
->pseudoRelocs
) {
2516 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2517 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2519 if (config
->mingw
) {
2520 ctx
.symtab
.addAbsolute(mangle("__CTOR_LIST__"), 0);
2521 ctx
.symtab
.addAbsolute(mangle("__DTOR_LIST__"), 0);
2523 if (config
->debug
|| config
->buildIDHash
!= BuildIDHash::None
)
2524 if (ctx
.symtab
.findUnderscore("__buildid"))
2525 ctx
.symtab
.addUndefined(mangle("__buildid"));
2527 // This code may add new undefined symbols to the link, which may enqueue more
2528 // symbol resolution tasks, so we need to continue executing tasks until we
2531 llvm::TimeTraceScope
timeScope("Add unresolved symbols");
2533 // Windows specific -- if entry point is not found,
2534 // search for its mangled names.
2536 mangleMaybe(config
->entry
);
2538 // Windows specific -- Make sure we resolve all dllexported symbols.
2539 for (Export
&e
: config
->exports
) {
2540 if (!e
.forwardTo
.empty())
2542 e
.sym
= addUndefined(e
.name
, !e
.data
);
2543 if (e
.source
!= ExportSource::Directives
)
2544 e
.symbolName
= mangleMaybe(e
.sym
);
2547 // Add weak aliases. Weak aliases is a mechanism to give remaining
2548 // undefined symbols final chance to be resolved successfully.
2549 for (auto pair
: config
->alternateNames
) {
2550 StringRef from
= pair
.first
;
2551 StringRef to
= pair
.second
;
2552 Symbol
*sym
= ctx
.symtab
.find(from
);
2555 if (auto *u
= dyn_cast
<Undefined
>(sym
)) {
2557 // On ARM64EC, anti-dependency aliases are treated as undefined
2558 // symbols unless a demangled symbol aliases a defined one, which is
2559 // part of the implementation.
2560 if (!isArm64EC(ctx
.config
.machine
) || !u
->isAntiDep
)
2562 if (!isa
<Undefined
>(u
->weakAlias
) &&
2563 !isArm64ECMangledFunctionName(u
->getName()))
2566 u
->setWeakAlias(ctx
.symtab
.addUndefined(to
));
2570 // If any inputs are bitcode files, the LTO code generator may create
2571 // references to library functions that are not explicit in the bitcode
2572 // file's symbol table. If any of those library functions are defined in a
2573 // bitcode file in an archive member, we need to arrange to use LTO to
2574 // compile those archive members by adding them to the link beforehand.
2575 if (!ctx
.bitcodeFileInstances
.empty()) {
2577 ctx
.bitcodeFileInstances
.front()->obj
->getTargetTriple());
2578 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols(TT
))
2579 ctx
.symtab
.addLibcall(s
);
2582 // Windows specific -- if __load_config_used can be resolved, resolve it.
2583 if (ctx
.symtab
.findUnderscore("_load_config_used"))
2584 addUndefined(mangle("_load_config_used"));
2586 if (args
.hasArg(OPT_include_optional
)) {
2587 // Handle /includeoptional
2588 for (auto *arg
: args
.filtered(OPT_include_optional
))
2589 if (isa_and_nonnull
<LazyArchive
>(ctx
.symtab
.find(arg
->getValue())))
2590 addUndefined(arg
->getValue());
2595 // Handle /includeglob
2596 for (StringRef pat
: args::getStrings(args
, OPT_incl_glob
))
2597 addUndefinedGlob(pat
);
2599 // Create wrapped symbols for -wrap option.
2600 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(ctx
, args
);
2601 // Load more object files that might be needed for wrapped symbols.
2602 if (!wrapped
.empty())
2606 if (config
->autoImport
|| config
->stdcallFixup
) {
2608 // Load any further object files that might be needed for doing automatic
2609 // imports, and do stdcall fixups.
2611 // For cases with no automatically imported symbols, this iterates once
2612 // over the symbol table and doesn't do anything.
2614 // For the normal case with a few automatically imported symbols, this
2615 // should only need to be run once, since each new object file imported
2616 // is an import library and wouldn't add any new undefined references,
2617 // but there's nothing stopping the __imp_ symbols from coming from a
2618 // normal object file as well (although that won't be used for the
2619 // actual autoimport later on). If this pass adds new undefined references,
2620 // we won't iterate further to resolve them.
2622 // If stdcall fixups only are needed for loading import entries from
2623 // a DLL without import library, this also just needs running once.
2624 // If it ends up pulling in more object files from static libraries,
2625 // (and maybe doing more stdcall fixups along the way), this would need
2626 // to loop these two calls.
2627 ctx
.symtab
.loadMinGWSymbols();
2631 // At this point, we should not have any symbols that cannot be resolved.
2632 // If we are going to do codegen for link-time optimization, check for
2633 // unresolvable symbols first, so we don't spend time generating code that
2634 // will fail to link anyway.
2635 if (!ctx
.bitcodeFileInstances
.empty() && !config
->forceUnresolved
)
2636 ctx
.symtab
.reportUnresolvable();
2640 config
->hadExplicitExports
= !config
->exports
.empty();
2641 if (config
->mingw
) {
2642 // In MinGW, all symbols are automatically exported if no symbols
2643 // are chosen to be exported.
2644 maybeExportMinGWSymbols(args
);
2647 // Do LTO by compiling bitcode input files to a set of native COFF files then
2648 // link those files (unless -thinlto-index-only was given, in which case we
2649 // resolve symbols and write indices, but don't generate native code or link).
2650 ctx
.symtab
.compileBitcodeFiles();
2653 dyn_cast_or_null
<Defined
>(ctx
.symtab
.findUnderscore("_tls_used")))
2654 config
->gcroot
.push_back(d
);
2656 // If -thinlto-index-only is given, we should create only "index
2657 // files" and not object files. Index file creation is already done
2658 // in addCombinedLTOObject, so we are done if that's the case.
2659 // Likewise, don't emit object files for other /lldemit options.
2660 if (config
->emit
!= EmitKind::Obj
|| config
->thinLTOIndexOnly
)
2663 // If we generated native object files from bitcode files, this resolves
2664 // references to the symbols we use from them.
2667 // Apply symbol renames for -wrap.
2668 if (!wrapped
.empty())
2669 wrapSymbols(ctx
, wrapped
);
2671 if (isArm64EC(config
->machine
))
2672 createECExportThunks();
2674 // Resolve remaining undefined symbols and warn about imported locals.
2675 while (ctx
.symtab
.resolveRemainingUndefines())
2681 if (config
->mingw
) {
2682 // Make sure the crtend.o object is the last object file. This object
2683 // file can contain terminating section chunks that need to be placed
2684 // last. GNU ld processes files and static libraries explicitly in the
2685 // order provided on the command line, while lld will pull in needed
2686 // files from static libraries only after the last object file on the
2688 for (auto i
= ctx
.objFileInstances
.begin(), e
= ctx
.objFileInstances
.end();
2691 if (isCrtend(file
->getName())) {
2692 ctx
.objFileInstances
.erase(i
);
2693 ctx
.objFileInstances
.push_back(file
);
2699 // Windows specific -- when we are creating a .dll file, we also
2700 // need to create a .lib file. In MinGW mode, we only do that when the
2701 // -implib option is given explicitly, for compatibility with GNU ld.
2702 if (!config
->exports
.empty() || config
->dll
) {
2703 llvm::TimeTraceScope
timeScope("Create .lib exports");
2705 if (!config
->noimplib
&& (!config
->mingw
|| !config
->implib
.empty()))
2706 createImportLibrary(/*asLib=*/false);
2707 assignExportOrdinals();
2710 // Handle /output-def (MinGW specific).
2711 if (auto *arg
= args
.getLastArg(OPT_output_def
))
2712 writeDefFile(arg
->getValue(), config
->exports
);
2714 // Set extra alignment for .comm symbols
2715 for (auto pair
: config
->alignComm
) {
2716 StringRef name
= pair
.first
;
2717 uint32_t alignment
= pair
.second
;
2719 Symbol
*sym
= ctx
.symtab
.find(name
);
2721 warn("/aligncomm symbol " + name
+ " not found");
2725 // If the symbol isn't common, it must have been replaced with a regular
2726 // symbol, which will carry its own alignment.
2727 auto *dc
= dyn_cast
<DefinedCommon
>(sym
);
2731 CommonChunk
*c
= dc
->getChunk();
2732 c
->setAlignment(std::max(c
->getAlignment(), alignment
));
2735 // Windows specific -- Create an embedded or side-by-side manifest.
2736 // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2738 if (config
->manifest
== Configuration::Embed
)
2739 addBuffer(createManifestRes(), false, false);
2740 else if (config
->manifest
== Configuration::SideBySide
||
2741 (config
->manifest
== Configuration::Default
&&
2742 !config
->manifestDependencies
.empty()))
2743 createSideBySideManifest();
2745 // Handle /order. We want to do this at this moment because we
2746 // need a complete list of comdat sections to warn on nonexistent
2748 if (auto *arg
= args
.getLastArg(OPT_order
)) {
2749 if (args
.hasArg(OPT_call_graph_ordering_file
))
2750 error("/order and /call-graph-order-file may not be used together");
2751 parseOrderFile(arg
->getValue());
2752 config
->callGraphProfileSort
= false;
2755 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2756 if (config
->callGraphProfileSort
) {
2757 llvm::TimeTraceScope
timeScope("Call graph");
2758 if (auto *arg
= args
.getLastArg(OPT_call_graph_ordering_file
)) {
2759 parseCallGraphFile(arg
->getValue());
2761 readCallGraphsFromObjectFiles(ctx
);
2764 // Handle /print-symbol-order.
2765 if (auto *arg
= args
.getLastArg(OPT_print_symbol_order
))
2766 config
->printSymbolOrder
= arg
->getValue();
2768 ctx
.symtab
.initializeECThunks();
2770 // Identify unreferenced COMDAT sections.
2772 if (config
->mingw
) {
2773 // markLive doesn't traverse .eh_frame, but the personality function is
2774 // only reached that way. The proper solution would be to parse and
2775 // traverse the .eh_frame section, like the ELF linker does.
2776 // For now, just manually try to retain the known possible personality
2777 // functions. This doesn't bring in more object files, but only marks
2778 // functions that already have been included to be retained.
2779 for (const char *n
: {"__gxx_personality_v0", "__gcc_personality_v0",
2780 "rust_eh_personality"}) {
2781 Defined
*d
= dyn_cast_or_null
<Defined
>(ctx
.symtab
.findUnderscore(n
));
2782 if (d
&& !d
->isGCRoot
) {
2784 config
->gcroot
.push_back(d
);
2792 // Needs to happen after the last call to addFile().
2795 // Identify identical COMDAT sections to merge them.
2796 if (config
->doICF
!= ICFLevel::None
) {
2797 findKeepUniqueSections(ctx
);
2801 // Write the result.
2804 // Stop early so we can print the results.
2806 if (config
->showTiming
)
2807 ctx
.rootTimer
.print();
2809 if (config
->timeTraceEnabled
) {
2810 // Manually stop the topmost "COFF link" scope, since we're shutting down.
2811 timeTraceProfilerEnd();
2813 checkError(timeTraceProfilerWrite(
2814 args
.getLastArgValue(OPT_time_trace_eq
).str(), config
->outputFile
));
2815 timeTraceProfilerCleanup();
2819 } // namespace lld::coff