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/Object/WindowsMachineFlag.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Support/BinaryStreamReader.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/LEB128.h"
42 #include "llvm/Support/MathExtras.h"
43 #include "llvm/Support/Parallel.h"
44 #include "llvm/Support/Path.h"
45 #include "llvm/Support/Process.h"
46 #include "llvm/Support/TarWriter.h"
47 #include "llvm/Support/TargetSelect.h"
48 #include "llvm/Support/VirtualFileSystem.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include "llvm/TargetParser/Triple.h"
51 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
59 using namespace llvm::object
;
60 using namespace llvm::COFF
;
61 using namespace llvm::sys
;
65 bool link(ArrayRef
<const char *> args
, llvm::raw_ostream
&stdoutOS
,
66 llvm::raw_ostream
&stderrOS
, bool exitEarly
, bool disableOutput
) {
67 // This driver-specific context will be freed later by unsafeLldMain().
68 auto *ctx
= new COFFLinkerContext
;
70 ctx
->e
.initialize(stdoutOS
, stderrOS
, exitEarly
, disableOutput
);
71 ctx
->e
.logName
= args::getFilenameWithoutExe(args
[0]);
72 ctx
->e
.errorLimitExceededMsg
= "too many errors emitted, stopping now"
73 " (use /errorlimit:0 to see all errors)";
75 ctx
->driver
.linkerMain(args
);
77 return errorCount() == 0;
80 // Parse options of the form "old;new".
81 static std::pair
<StringRef
, StringRef
> getOldNewOptions(opt::InputArgList
&args
,
83 auto *arg
= args
.getLastArg(id
);
87 StringRef s
= arg
->getValue();
88 std::pair
<StringRef
, StringRef
> ret
= s
.split(';');
89 if (ret
.second
.empty())
90 error(arg
->getSpelling() + " expects 'old;new' format, but got " + s
);
94 // Parse options of the form "old;new[;extra]".
95 static std::tuple
<StringRef
, StringRef
, StringRef
>
96 getOldNewOptionsExtra(opt::InputArgList
&args
, unsigned id
) {
97 auto [oldDir
, second
] = getOldNewOptions(args
, id
);
98 auto [newDir
, extraDir
] = second
.split(';');
99 return {oldDir
, newDir
, extraDir
};
102 // Drop directory components and replace extension with
103 // ".exe", ".dll" or ".sys".
104 static std::string
getOutputPath(StringRef path
, bool isDll
, bool isDriver
) {
105 StringRef ext
= ".exe";
111 return (sys::path::stem(path
) + ext
).str();
114 // Returns true if S matches /crtend.?\.o$/.
115 static bool isCrtend(StringRef s
) {
116 if (!s
.ends_with(".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 switch (ctx
.config
.machine
) {
162 return llvm::Triple::ArchType::x86
;
164 return llvm::Triple::ArchType::x86_64
;
166 return llvm::Triple::ArchType::arm
;
168 return llvm::Triple::ArchType::aarch64
;
170 return llvm::Triple::ArchType::UnknownArch
;
174 bool LinkerDriver::findUnderscoreMangle(StringRef sym
) {
175 Symbol
*s
= ctx
.symtab
.findMangle(mangle(sym
));
176 return s
&& !isa
<Undefined
>(s
);
179 MemoryBufferRef
LinkerDriver::takeBuffer(std::unique_ptr
<MemoryBuffer
> mb
) {
180 MemoryBufferRef mbref
= *mb
;
181 make
<std::unique_ptr
<MemoryBuffer
>>(std::move(mb
)); // take ownership
184 ctx
.driver
.tar
->append(relativeToRoot(mbref
.getBufferIdentifier()),
189 void LinkerDriver::addBuffer(std::unique_ptr
<MemoryBuffer
> mb
,
190 bool wholeArchive
, bool lazy
) {
191 StringRef filename
= mb
->getBufferIdentifier();
193 MemoryBufferRef mbref
= takeBuffer(std::move(mb
));
194 filePaths
.push_back(filename
);
196 // File type is detected by contents, not by file extension.
197 switch (identify_magic(mbref
.getBuffer())) {
198 case file_magic::windows_resource
:
199 resources
.push_back(mbref
);
201 case file_magic::archive
:
203 std::unique_ptr
<Archive
> file
=
204 CHECK(Archive::create(mbref
), filename
+ ": failed to parse archive");
205 Archive
*archive
= file
.get();
206 make
<std::unique_ptr
<Archive
>>(std::move(file
)); // take ownership
209 for (MemoryBufferRef m
: getArchiveMembers(archive
))
210 addArchiveBuffer(m
, "<whole-archive>", filename
, memberIndex
++);
213 ctx
.symtab
.addFile(make
<ArchiveFile
>(ctx
, mbref
));
215 case file_magic::bitcode
:
216 ctx
.symtab
.addFile(make
<BitcodeFile
>(ctx
, mbref
, "", 0, lazy
));
218 case file_magic::coff_object
:
219 case file_magic::coff_import_library
:
220 ctx
.symtab
.addFile(make
<ObjFile
>(ctx
, mbref
, lazy
));
222 case file_magic::pdb
:
223 ctx
.symtab
.addFile(make
<PDBInputFile
>(ctx
, mbref
));
225 case file_magic::coff_cl_gl_object
:
226 error(filename
+ ": is not a native COFF file. Recompile without /GL");
228 case file_magic::pecoff_executable
:
229 if (ctx
.config
.mingw
) {
230 ctx
.symtab
.addFile(make
<DLLFile
>(ctx
, mbref
));
233 if (filename
.ends_with_insensitive(".dll")) {
234 error(filename
+ ": bad file type. Did you specify a DLL instead of an "
240 error(mbref
.getBufferIdentifier() + ": unknown file type");
245 void LinkerDriver::enqueuePath(StringRef path
, bool wholeArchive
, bool lazy
) {
246 auto future
= std::make_shared
<std::future
<MBErrPair
>>(
247 createFutureForFile(std::string(path
)));
248 std::string pathStr
= std::string(path
);
250 llvm::TimeTraceScope
timeScope("File: ", path
);
251 auto [mb
, ec
] = future
->get();
253 // Retry reading the file (synchronously) now that we may have added
254 // winsysroot search paths from SymbolTable::addFile().
255 // Retrying synchronously is important for keeping the order of inputs
257 // This makes it so that if the user passes something in the winsysroot
258 // before something we can find with an architecture, we won't find the
260 if (std::optional
<StringRef
> retryPath
= findFileIfNew(pathStr
)) {
261 auto retryMb
= MemoryBuffer::getFile(*retryPath
, /*IsText=*/false,
262 /*RequiresNullTerminator=*/false);
263 ec
= retryMb
.getError();
265 mb
= std::move(*retryMb
);
267 // We've already handled this file.
272 std::string msg
= "could not open '" + pathStr
+ "': " + ec
.message();
273 // Check if the filename is a typo for an option flag. OptTable thinks
274 // that all args that are not known options and that start with / are
275 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
276 // the option `/nodefaultlib` than a reference to a file in the root
279 if (ctx
.optTable
.findNearest(pathStr
, nearest
) > 1)
282 error(msg
+ "; did you mean '" + nearest
+ "'");
284 ctx
.driver
.addBuffer(std::move(mb
), wholeArchive
, lazy
);
288 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb
, StringRef symName
,
289 StringRef parentName
,
290 uint64_t offsetInArchive
) {
291 file_magic magic
= identify_magic(mb
.getBuffer());
292 if (magic
== file_magic::coff_import_library
) {
293 InputFile
*imp
= make
<ImportFile
>(ctx
, mb
);
294 imp
->parentName
= parentName
;
295 ctx
.symtab
.addFile(imp
);
300 if (magic
== file_magic::coff_object
) {
301 obj
= make
<ObjFile
>(ctx
, mb
);
302 } else if (magic
== file_magic::bitcode
) {
304 make
<BitcodeFile
>(ctx
, mb
, parentName
, offsetInArchive
, /*lazy=*/false);
305 } else if (magic
== file_magic::coff_cl_gl_object
) {
306 error(mb
.getBufferIdentifier() +
307 ": is not a native COFF file. Recompile without /GL?");
310 error("unknown file type: " + mb
.getBufferIdentifier());
314 obj
->parentName
= parentName
;
315 ctx
.symtab
.addFile(obj
);
316 log("Loaded " + toString(obj
) + " for " + symName
);
319 void LinkerDriver::enqueueArchiveMember(const Archive::Child
&c
,
320 const Archive::Symbol
&sym
,
321 StringRef parentName
) {
323 auto reportBufferError
= [=](Error
&&e
, StringRef childName
) {
324 fatal("could not get the buffer for the member defining symbol " +
325 toCOFFString(ctx
, sym
) + ": " + parentName
+ "(" + childName
+
326 "): " + toString(std::move(e
)));
329 if (!c
.getParent()->isThin()) {
330 uint64_t offsetInArchive
= c
.getChildOffset();
331 Expected
<MemoryBufferRef
> mbOrErr
= c
.getMemoryBufferRef();
333 reportBufferError(mbOrErr
.takeError(), check(c
.getFullName()));
334 MemoryBufferRef mb
= mbOrErr
.get();
336 llvm::TimeTraceScope
timeScope("Archive: ", mb
.getBufferIdentifier());
337 ctx
.driver
.addArchiveBuffer(mb
, toCOFFString(ctx
, sym
), parentName
,
343 std::string childName
=
344 CHECK(c
.getFullName(),
345 "could not get the filename for the member defining symbol " +
346 toCOFFString(ctx
, sym
));
348 std::make_shared
<std::future
<MBErrPair
>>(createFutureForFile(childName
));
350 auto mbOrErr
= future
->get();
352 reportBufferError(errorCodeToError(mbOrErr
.second
), childName
);
353 llvm::TimeTraceScope
timeScope("Archive: ",
354 mbOrErr
.first
->getBufferIdentifier());
355 // Pass empty string as archive name so that the original filename is
356 // used as the buffer identifier.
357 ctx
.driver
.addArchiveBuffer(takeBuffer(std::move(mbOrErr
.first
)),
358 toCOFFString(ctx
, sym
), "",
359 /*OffsetInArchive=*/0);
363 bool LinkerDriver::isDecorated(StringRef sym
) {
364 return sym
.starts_with("@") || sym
.contains("@@") || sym
.starts_with("?") ||
365 (!ctx
.config
.mingw
&& sym
.contains('@'));
368 // Parses .drectve section contents and returns a list of files
369 // specified by /defaultlib.
370 void LinkerDriver::parseDirectives(InputFile
*file
) {
371 StringRef s
= file
->getDirectives();
375 log("Directives: " + toString(file
) + ": " + s
);
377 ArgParser
parser(ctx
);
378 // .drectve is always tokenized using Windows shell rules.
379 // /EXPORT: option can appear too many times, processing in fastpath.
380 ParsedDirectives directives
= parser
.parseDirectives(s
);
382 for (StringRef e
: directives
.exports
) {
383 // If a common header file contains dllexported function
384 // declarations, many object files may end up with having the
385 // same /EXPORT options. In order to save cost of parsing them,
386 // we dedup them first.
387 if (!directivesExports
.insert(e
).second
)
390 Export exp
= parseExport(e
);
391 if (ctx
.config
.machine
== I386
&& ctx
.config
.mingw
) {
392 if (!isDecorated(exp
.name
))
393 exp
.name
= saver().save("_" + exp
.name
);
394 if (!exp
.extName
.empty() && !isDecorated(exp
.extName
))
395 exp
.extName
= saver().save("_" + exp
.extName
);
397 exp
.source
= ExportSource::Directives
;
398 ctx
.config
.exports
.push_back(exp
);
401 // Handle /include: in bulk.
402 for (StringRef inc
: directives
.includes
)
405 // Handle /exclude-symbols: in bulk.
406 for (StringRef e
: directives
.excludes
) {
407 SmallVector
<StringRef
, 2> vec
;
409 for (StringRef sym
: vec
)
410 excludedSymbols
.insert(mangle(sym
));
413 // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160
414 for (auto *arg
: directives
.args
) {
415 switch (arg
->getOption().getID()) {
417 parseAligncomm(arg
->getValue());
419 case OPT_alternatename
:
420 parseAlternateName(arg
->getValue());
423 if (std::optional
<StringRef
> path
= findLibIfNew(arg
->getValue()))
424 enqueuePath(*path
, false, false);
427 ctx
.config
.entry
= addUndefined(mangle(arg
->getValue()));
429 case OPT_failifmismatch
:
430 checkFailIfMismatch(arg
->getValue(), file
);
433 addUndefined(arg
->getValue());
435 case OPT_manifestdependency
:
436 ctx
.config
.manifestDependencies
.insert(arg
->getValue());
439 parseMerge(arg
->getValue());
441 case OPT_nodefaultlib
:
442 ctx
.config
.noDefaultLibs
.insert(findLib(arg
->getValue()).lower());
445 ctx
.config
.writeCheckSum
= true;
448 parseSection(arg
->getValue());
451 parseNumbers(arg
->getValue(), &ctx
.config
.stackReserve
,
452 &ctx
.config
.stackCommit
);
454 case OPT_subsystem
: {
455 bool gotVersion
= false;
456 parseSubsystem(arg
->getValue(), &ctx
.config
.subsystem
,
457 &ctx
.config
.majorSubsystemVersion
,
458 &ctx
.config
.minorSubsystemVersion
, &gotVersion
);
460 ctx
.config
.majorOSVersion
= ctx
.config
.majorSubsystemVersion
;
461 ctx
.config
.minorOSVersion
= ctx
.config
.minorSubsystemVersion
;
465 // Only add flags here that link.exe accepts in
466 // `#pragma comment(linker, "/flag")`-generated sections.
467 case OPT_editandcontinue
:
469 case OPT_throwingnew
:
470 case OPT_inferasanlibs
:
471 case OPT_inferasanlibs_no
:
474 error(arg
->getSpelling() + " is not allowed in .drectve (" +
475 toString(file
) + ")");
480 // Find file from search paths. You can omit ".obj", this function takes
481 // care of that. Note that the returned path is not guaranteed to exist.
482 StringRef
LinkerDriver::findFile(StringRef filename
) {
483 auto getFilename
= [this](StringRef filename
) -> StringRef
{
485 if (auto statOrErr
= ctx
.config
.vfs
->status(filename
))
486 return saver().save(statOrErr
->getName());
490 if (sys::path::is_absolute(filename
))
491 return getFilename(filename
);
492 bool hasExt
= filename
.contains('.');
493 for (StringRef dir
: searchPaths
) {
494 SmallString
<128> path
= dir
;
495 sys::path::append(path
, filename
);
496 path
= SmallString
<128>{getFilename(path
.str())};
497 if (sys::fs::exists(path
.str()))
498 return saver().save(path
.str());
501 path
= SmallString
<128>{getFilename(path
.str())};
502 if (sys::fs::exists(path
.str()))
503 return saver().save(path
.str());
509 static std::optional
<sys::fs::UniqueID
> getUniqueID(StringRef path
) {
510 sys::fs::UniqueID ret
;
511 if (sys::fs::getUniqueID(path
, ret
))
516 // Resolves a file path. This never returns the same path
517 // (in that case, it returns std::nullopt).
518 std::optional
<StringRef
> LinkerDriver::findFileIfNew(StringRef filename
) {
519 StringRef path
= findFile(filename
);
521 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
)) {
522 bool seen
= !visitedFiles
.insert(*id
).second
;
527 if (path
.ends_with_insensitive(".lib"))
528 visitedLibs
.insert(std::string(sys::path::filename(path
).lower()));
532 // MinGW specific. If an embedded directive specified to link to
533 // foo.lib, but it isn't found, try libfoo.a instead.
534 StringRef
LinkerDriver::findLibMinGW(StringRef filename
) {
535 if (filename
.contains('/') || filename
.contains('\\'))
538 SmallString
<128> s
= filename
;
539 sys::path::replace_extension(s
, ".a");
540 StringRef libName
= saver().save("lib" + s
.str());
541 return findFile(libName
);
544 // Find library file from search path.
545 StringRef
LinkerDriver::findLib(StringRef filename
) {
546 // Add ".lib" to Filename if that has no file extension.
547 bool hasExt
= filename
.contains('.');
549 filename
= saver().save(filename
+ ".lib");
550 StringRef ret
= findFile(filename
);
551 // For MinGW, if the find above didn't turn up anything, try
552 // looking for a MinGW formatted library name.
553 if (ctx
.config
.mingw
&& ret
== filename
)
554 return findLibMinGW(filename
);
558 // Resolves a library path. /nodefaultlib options are taken into
559 // consideration. This never returns the same path (in that case,
560 // it returns std::nullopt).
561 std::optional
<StringRef
> LinkerDriver::findLibIfNew(StringRef filename
) {
562 if (ctx
.config
.noDefaultLibAll
)
564 if (!visitedLibs
.insert(filename
.lower()).second
)
567 StringRef path
= findLib(filename
);
568 if (ctx
.config
.noDefaultLibs
.count(path
.lower()))
571 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
572 if (!visitedFiles
.insert(*id
).second
)
577 void LinkerDriver::detectWinSysRoot(const opt::InputArgList
&Args
) {
578 IntrusiveRefCntPtr
<vfs::FileSystem
> VFS
= vfs::getRealFileSystem();
580 // Check the command line first, that's the user explicitly telling us what to
581 // use. Check the environment next, in case we're being invoked from a VS
582 // command prompt. Failing that, just try to find the newest Visual Studio
583 // version we can and use its default VC toolchain.
584 std::optional
<StringRef
> VCToolsDir
, VCToolsVersion
, WinSysRoot
;
585 if (auto *A
= Args
.getLastArg(OPT_vctoolsdir
))
586 VCToolsDir
= A
->getValue();
587 if (auto *A
= Args
.getLastArg(OPT_vctoolsversion
))
588 VCToolsVersion
= A
->getValue();
589 if (auto *A
= Args
.getLastArg(OPT_winsysroot
))
590 WinSysRoot
= A
->getValue();
591 if (!findVCToolChainViaCommandLine(*VFS
, VCToolsDir
, VCToolsVersion
,
592 WinSysRoot
, vcToolChainPath
, vsLayout
) &&
593 (Args
.hasArg(OPT_lldignoreenv
) ||
594 !findVCToolChainViaEnvironment(*VFS
, vcToolChainPath
, vsLayout
)) &&
595 !findVCToolChainViaSetupConfig(*VFS
, {}, vcToolChainPath
, vsLayout
) &&
596 !findVCToolChainViaRegistry(vcToolChainPath
, vsLayout
))
599 // If the VC environment hasn't been configured (perhaps because the user did
600 // not run vcvarsall), try to build a consistent link environment. If the
601 // environment variable is set however, assume the user knows what they're
602 // doing. If the user passes /vctoolsdir or /winsdkdir, trust that over env
604 if (const auto *A
= Args
.getLastArg(OPT_diasdkdir
, OPT_winsysroot
)) {
605 diaPath
= A
->getValue();
606 if (A
->getOption().getID() == OPT_winsysroot
)
607 path::append(diaPath
, "DIA SDK");
609 useWinSysRootLibPath
= Args
.hasArg(OPT_lldignoreenv
) ||
610 !Process::GetEnv("LIB") ||
611 Args
.getLastArg(OPT_vctoolsdir
, OPT_winsysroot
);
612 if (Args
.hasArg(OPT_lldignoreenv
) || !Process::GetEnv("LIB") ||
613 Args
.getLastArg(OPT_winsdkdir
, OPT_winsysroot
)) {
614 std::optional
<StringRef
> WinSdkDir
, WinSdkVersion
;
615 if (auto *A
= Args
.getLastArg(OPT_winsdkdir
))
616 WinSdkDir
= A
->getValue();
617 if (auto *A
= Args
.getLastArg(OPT_winsdkversion
))
618 WinSdkVersion
= A
->getValue();
620 if (useUniversalCRT(vsLayout
, vcToolChainPath
, getArch(), *VFS
)) {
621 std::string UniversalCRTSdkPath
;
622 std::string UCRTVersion
;
623 if (getUniversalCRTSdkDir(*VFS
, WinSdkDir
, WinSdkVersion
, WinSysRoot
,
624 UniversalCRTSdkPath
, UCRTVersion
)) {
625 universalCRTLibPath
= UniversalCRTSdkPath
;
626 path::append(universalCRTLibPath
, "Lib", UCRTVersion
, "ucrt");
631 std::string windowsSDKIncludeVersion
;
632 std::string windowsSDKLibVersion
;
633 if (getWindowsSDKDir(*VFS
, WinSdkDir
, WinSdkVersion
, WinSysRoot
, sdkPath
,
634 sdkMajor
, windowsSDKIncludeVersion
,
635 windowsSDKLibVersion
)) {
636 windowsSdkLibPath
= sdkPath
;
637 path::append(windowsSdkLibPath
, "Lib");
639 path::append(windowsSdkLibPath
, windowsSDKLibVersion
, "um");
644 void LinkerDriver::addClangLibSearchPaths(const std::string
&argv0
) {
645 std::string lldBinary
= sys::fs::getMainExecutable(argv0
.c_str(), nullptr);
646 SmallString
<128> binDir(lldBinary
);
647 sys::path::remove_filename(binDir
); // remove lld-link.exe
648 StringRef rootDir
= sys::path::parent_path(binDir
); // remove 'bin'
650 SmallString
<128> libDir(rootDir
);
651 sys::path::append(libDir
, "lib");
653 // Add the resource dir library path
654 SmallString
<128> runtimeLibDir(rootDir
);
655 sys::path::append(runtimeLibDir
, "lib", "clang",
656 std::to_string(LLVM_VERSION_MAJOR
), "lib");
657 // Resource dir + osname, which is hardcoded to windows since we are in the
659 SmallString
<128> runtimeLibDirWithOS(runtimeLibDir
);
660 sys::path::append(runtimeLibDirWithOS
, "windows");
662 searchPaths
.push_back(saver().save(runtimeLibDirWithOS
.str()));
663 searchPaths
.push_back(saver().save(runtimeLibDir
.str()));
664 searchPaths
.push_back(saver().save(libDir
.str()));
667 void LinkerDriver::addWinSysRootLibSearchPaths() {
668 if (!diaPath
.empty()) {
669 // The DIA SDK always uses the legacy vc arch, even in new MSVC versions.
670 path::append(diaPath
, "lib", archToLegacyVCArch(getArch()));
671 searchPaths
.push_back(saver().save(diaPath
.str()));
673 if (useWinSysRootLibPath
) {
674 searchPaths
.push_back(saver().save(getSubDirectoryPath(
675 SubDirectoryType::Lib
, vsLayout
, vcToolChainPath
, getArch())));
676 searchPaths
.push_back(saver().save(
677 getSubDirectoryPath(SubDirectoryType::Lib
, vsLayout
, vcToolChainPath
,
678 getArch(), "atlmfc")));
680 if (!universalCRTLibPath
.empty()) {
681 StringRef ArchName
= archToWindowsSDKArch(getArch());
682 if (!ArchName
.empty()) {
683 path::append(universalCRTLibPath
, ArchName
);
684 searchPaths
.push_back(saver().save(universalCRTLibPath
.str()));
687 if (!windowsSdkLibPath
.empty()) {
689 if (appendArchToWindowsSDKLibPath(sdkMajor
, windowsSdkLibPath
, getArch(),
691 searchPaths
.push_back(saver().save(path
));
695 // Parses LIB environment which contains a list of search paths.
696 void LinkerDriver::addLibSearchPaths() {
697 std::optional
<std::string
> envOpt
= Process::GetEnv("LIB");
700 StringRef env
= saver().save(*envOpt
);
701 while (!env
.empty()) {
703 std::tie(path
, env
) = env
.split(';');
704 searchPaths
.push_back(path
);
708 Symbol
*LinkerDriver::addUndefined(StringRef name
) {
709 Symbol
*b
= ctx
.symtab
.addUndefined(name
);
712 ctx
.config
.gcroot
.push_back(b
);
717 StringRef
LinkerDriver::mangleMaybe(Symbol
*s
) {
718 // If the plain symbol name has already been resolved, do nothing.
719 Undefined
*unmangled
= dyn_cast
<Undefined
>(s
);
723 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
724 Symbol
*mangled
= ctx
.symtab
.findMangle(unmangled
->getName());
728 // If we find a similar mangled symbol, make this an alias to it and return
730 log(unmangled
->getName() + " aliased to " + mangled
->getName());
731 unmangled
->weakAlias
= ctx
.symtab
.addUndefined(mangled
->getName());
732 return mangled
->getName();
735 // Windows specific -- find default entry point name.
737 // There are four different entry point functions for Windows executables,
738 // each of which corresponds to a user-defined "main" function. This function
739 // infers an entry point from a user-defined "main" function.
740 StringRef
LinkerDriver::findDefaultEntry() {
741 assert(ctx
.config
.subsystem
!= IMAGE_SUBSYSTEM_UNKNOWN
&&
742 "must handle /subsystem before calling this");
744 if (ctx
.config
.mingw
)
745 return mangle(ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
746 ? "WinMainCRTStartup"
749 if (ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
) {
750 if (findUnderscoreMangle("wWinMain")) {
751 if (!findUnderscoreMangle("WinMain"))
752 return mangle("wWinMainCRTStartup");
753 warn("found both wWinMain and WinMain; using latter");
755 return mangle("WinMainCRTStartup");
757 if (findUnderscoreMangle("wmain")) {
758 if (!findUnderscoreMangle("main"))
759 return mangle("wmainCRTStartup");
760 warn("found both wmain and main; using latter");
762 return mangle("mainCRTStartup");
765 WindowsSubsystem
LinkerDriver::inferSubsystem() {
767 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
768 if (ctx
.config
.mingw
)
769 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
770 // Note that link.exe infers the subsystem from the presence of these
771 // functions even if /entry: or /nodefaultlib are passed which causes them
773 bool haveMain
= findUnderscoreMangle("main");
774 bool haveWMain
= findUnderscoreMangle("wmain");
775 bool haveWinMain
= findUnderscoreMangle("WinMain");
776 bool haveWWinMain
= findUnderscoreMangle("wWinMain");
777 if (haveMain
|| haveWMain
) {
778 if (haveWinMain
|| haveWWinMain
) {
779 warn(std::string("found ") + (haveMain
? "main" : "wmain") + " and " +
780 (haveWinMain
? "WinMain" : "wWinMain") +
781 "; defaulting to /subsystem:console");
783 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
785 if (haveWinMain
|| haveWWinMain
)
786 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
787 return IMAGE_SUBSYSTEM_UNKNOWN
;
790 uint64_t LinkerDriver::getDefaultImageBase() {
791 if (ctx
.config
.is64())
792 return ctx
.config
.dll
? 0x180000000 : 0x140000000;
793 return ctx
.config
.dll
? 0x10000000 : 0x400000;
796 static std::string
rewritePath(StringRef s
) {
798 return relativeToRoot(s
);
799 return std::string(s
);
802 // Reconstructs command line arguments so that so that you can re-run
803 // the same command with the same inputs. This is for --reproduce.
804 static std::string
createResponseFile(const opt::InputArgList
&args
,
805 ArrayRef
<StringRef
> filePaths
,
806 ArrayRef
<StringRef
> searchPaths
) {
808 raw_svector_ostream
os(data
);
810 for (auto *arg
: args
) {
811 switch (arg
->getOption().getID()) {
819 case OPT_call_graph_ordering_file
:
821 case OPT_manifestinput
:
823 os
<< arg
->getSpelling() << quote(rewritePath(arg
->getValue())) << '\n';
826 StringRef orderFile
= arg
->getValue();
827 orderFile
.consume_front("@");
828 os
<< arg
->getSpelling() << '@' << quote(rewritePath(orderFile
)) << '\n';
831 case OPT_pdbstream
: {
832 const std::pair
<StringRef
, StringRef
> nameFile
=
833 StringRef(arg
->getValue()).split("=");
834 os
<< arg
->getSpelling() << nameFile
.first
<< '='
835 << quote(rewritePath(nameFile
.second
)) << '\n';
839 case OPT_manifestfile
:
841 case OPT_pdbstripped
:
843 os
<< arg
->getSpelling() << sys::path::filename(arg
->getValue()) << "\n";
846 os
<< toString(*arg
) << "\n";
850 for (StringRef path
: searchPaths
) {
851 std::string relPath
= relativeToRoot(path
);
852 os
<< "/libpath:" << quote(relPath
) << "\n";
855 for (StringRef path
: filePaths
)
856 os
<< quote(relativeToRoot(path
)) << "\n";
858 return std::string(data
.str());
861 enum class DebugKind
{
872 static DebugKind
parseDebugKind(const opt::InputArgList
&args
) {
873 auto *a
= args
.getLastArg(OPT_debug
, OPT_debug_opt
);
875 return DebugKind::None
;
876 if (a
->getNumValues() == 0)
877 return DebugKind::Full
;
879 DebugKind debug
= StringSwitch
<DebugKind
>(a
->getValue())
880 .CaseLower("none", DebugKind::None
)
881 .CaseLower("full", DebugKind::Full
)
882 .CaseLower("fastlink", DebugKind::FastLink
)
884 .CaseLower("ghash", DebugKind::GHash
)
885 .CaseLower("noghash", DebugKind::NoGHash
)
886 .CaseLower("dwarf", DebugKind::Dwarf
)
887 .CaseLower("symtab", DebugKind::Symtab
)
888 .Default(DebugKind::Unknown
);
890 if (debug
== DebugKind::FastLink
) {
891 warn("/debug:fastlink unsupported; using /debug:full");
892 return DebugKind::Full
;
894 if (debug
== DebugKind::Unknown
) {
895 error("/debug: unknown option: " + Twine(a
->getValue()));
896 return DebugKind::None
;
901 static unsigned parseDebugTypes(const opt::InputArgList
&args
) {
902 unsigned debugTypes
= static_cast<unsigned>(DebugType::None
);
904 if (auto *a
= args
.getLastArg(OPT_debugtype
)) {
905 SmallVector
<StringRef
, 3> types
;
906 StringRef(a
->getValue())
907 .split(types
, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
909 for (StringRef type
: types
) {
910 unsigned v
= StringSwitch
<unsigned>(type
.lower())
911 .Case("cv", static_cast<unsigned>(DebugType::CV
))
912 .Case("pdata", static_cast<unsigned>(DebugType::PData
))
913 .Case("fixup", static_cast<unsigned>(DebugType::Fixup
))
916 warn("/debugtype: unknown option '" + type
+ "'");
924 // Default debug types
925 debugTypes
= static_cast<unsigned>(DebugType::CV
);
926 if (args
.hasArg(OPT_driver
))
927 debugTypes
|= static_cast<unsigned>(DebugType::PData
);
928 if (args
.hasArg(OPT_profile
))
929 debugTypes
|= static_cast<unsigned>(DebugType::Fixup
);
934 std::string
LinkerDriver::getMapFile(const opt::InputArgList
&args
,
935 opt::OptSpecifier os
,
936 opt::OptSpecifier osFile
) {
937 auto *arg
= args
.getLastArg(os
, osFile
);
940 if (arg
->getOption().getID() == osFile
.getID())
941 return arg
->getValue();
943 assert(arg
->getOption().getID() == os
.getID());
944 StringRef outFile
= ctx
.config
.outputFile
;
945 return (outFile
.substr(0, outFile
.rfind('.')) + ".map").str();
948 std::string
LinkerDriver::getImplibPath() {
949 if (!ctx
.config
.implib
.empty())
950 return std::string(ctx
.config
.implib
);
951 SmallString
<128> out
= StringRef(ctx
.config
.outputFile
);
952 sys::path::replace_extension(out
, ".lib");
953 return std::string(out
.str());
956 // The import name is calculated as follows:
958 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
959 // -----+----------------+---------------------+------------------
960 // LINK | {value} | {value}.{.dll/.exe} | {output name}
961 // LIB | {value} | {value}.dll | {output name}.dll
963 std::string
LinkerDriver::getImportName(bool asLib
) {
964 SmallString
<128> out
;
966 if (ctx
.config
.importName
.empty()) {
967 out
.assign(sys::path::filename(ctx
.config
.outputFile
));
969 sys::path::replace_extension(out
, ".dll");
971 out
.assign(ctx
.config
.importName
);
972 if (!sys::path::has_extension(out
))
973 sys::path::replace_extension(out
,
974 (ctx
.config
.dll
|| asLib
) ? ".dll" : ".exe");
977 return std::string(out
.str());
980 void LinkerDriver::createImportLibrary(bool asLib
) {
981 llvm::TimeTraceScope
timeScope("Create import library");
982 std::vector
<COFFShortExport
> exports
;
983 for (Export
&e1
: ctx
.config
.exports
) {
985 e2
.Name
= std::string(e1
.name
);
986 e2
.SymbolName
= std::string(e1
.symbolName
);
987 e2
.ExtName
= std::string(e1
.extName
);
988 e2
.AliasTarget
= std::string(e1
.aliasTarget
);
989 e2
.Ordinal
= e1
.ordinal
;
990 e2
.Noname
= e1
.noname
;
992 e2
.Private
= e1
.isPrivate
;
993 e2
.Constant
= e1
.constant
;
994 exports
.push_back(e2
);
997 std::string libName
= getImportName(asLib
);
998 std::string path
= getImplibPath();
1000 if (!ctx
.config
.incremental
) {
1001 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
1006 // If the import library already exists, replace it only if the contents
1008 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> oldBuf
= MemoryBuffer::getFile(
1009 path
, /*IsText=*/false, /*RequiresNullTerminator=*/false);
1011 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
1016 SmallString
<128> tmpName
;
1017 if (std::error_code ec
=
1018 sys::fs::createUniqueFile(path
+ ".tmp-%%%%%%%%.lib", tmpName
))
1019 fatal("cannot create temporary file for import library " + path
+ ": " +
1022 if (Error e
= writeImportLibrary(libName
, tmpName
, exports
,
1023 ctx
.config
.machine
, ctx
.config
.mingw
)) {
1024 checkError(std::move(e
));
1028 std::unique_ptr
<MemoryBuffer
> newBuf
= check(MemoryBuffer::getFile(
1029 tmpName
, /*IsText=*/false, /*RequiresNullTerminator=*/false));
1030 if ((*oldBuf
)->getBuffer() != newBuf
->getBuffer()) {
1032 checkError(errorCodeToError(sys::fs::rename(tmpName
, path
)));
1034 sys::fs::remove(tmpName
);
1038 void LinkerDriver::parseModuleDefs(StringRef path
) {
1039 llvm::TimeTraceScope
timeScope("Parse def file");
1040 std::unique_ptr
<MemoryBuffer
> mb
=
1041 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1042 /*RequiresNullTerminator=*/false,
1043 /*IsVolatile=*/true),
1044 "could not open " + path
);
1045 COFFModuleDefinition m
= check(parseCOFFModuleDefinition(
1046 mb
->getMemBufferRef(), ctx
.config
.machine
, ctx
.config
.mingw
));
1048 // Include in /reproduce: output if applicable.
1049 ctx
.driver
.takeBuffer(std::move(mb
));
1051 if (ctx
.config
.outputFile
.empty())
1052 ctx
.config
.outputFile
= std::string(saver().save(m
.OutputFile
));
1053 ctx
.config
.importName
= std::string(saver().save(m
.ImportName
));
1055 ctx
.config
.imageBase
= m
.ImageBase
;
1057 ctx
.config
.stackReserve
= m
.StackReserve
;
1059 ctx
.config
.stackCommit
= m
.StackCommit
;
1061 ctx
.config
.heapReserve
= m
.HeapReserve
;
1063 ctx
.config
.heapCommit
= m
.HeapCommit
;
1064 if (m
.MajorImageVersion
)
1065 ctx
.config
.majorImageVersion
= m
.MajorImageVersion
;
1066 if (m
.MinorImageVersion
)
1067 ctx
.config
.minorImageVersion
= m
.MinorImageVersion
;
1068 if (m
.MajorOSVersion
)
1069 ctx
.config
.majorOSVersion
= m
.MajorOSVersion
;
1070 if (m
.MinorOSVersion
)
1071 ctx
.config
.minorOSVersion
= m
.MinorOSVersion
;
1073 for (COFFShortExport e1
: m
.Exports
) {
1075 // In simple cases, only Name is set. Renamed exports are parsed
1076 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
1077 // it shouldn't be a normal exported function but a forward to another
1078 // DLL instead. This is supported by both MS and GNU linkers.
1079 if (!e1
.ExtName
.empty() && e1
.ExtName
!= e1
.Name
&&
1080 StringRef(e1
.Name
).contains('.')) {
1081 e2
.name
= saver().save(e1
.ExtName
);
1082 e2
.forwardTo
= saver().save(e1
.Name
);
1083 ctx
.config
.exports
.push_back(e2
);
1086 e2
.name
= saver().save(e1
.Name
);
1087 e2
.extName
= saver().save(e1
.ExtName
);
1088 e2
.aliasTarget
= saver().save(e1
.AliasTarget
);
1089 e2
.ordinal
= e1
.Ordinal
;
1090 e2
.noname
= e1
.Noname
;
1092 e2
.isPrivate
= e1
.Private
;
1093 e2
.constant
= e1
.Constant
;
1094 e2
.source
= ExportSource::ModuleDefinition
;
1095 ctx
.config
.exports
.push_back(e2
);
1099 void LinkerDriver::enqueueTask(std::function
<void()> task
) {
1100 taskQueue
.push_back(std::move(task
));
1103 bool LinkerDriver::run() {
1104 llvm::TimeTraceScope
timeScope("Read input files");
1105 ScopedTimer
t(ctx
.inputFileTimer
);
1107 bool didWork
= !taskQueue
.empty();
1108 while (!taskQueue
.empty()) {
1109 taskQueue
.front()();
1110 taskQueue
.pop_front();
1115 // Parse an /order file. If an option is given, the linker places
1116 // COMDAT sections in the same order as their names appear in the
1118 void LinkerDriver::parseOrderFile(StringRef arg
) {
1119 // For some reason, the MSVC linker requires a filename to be
1121 if (!arg
.starts_with("@")) {
1122 error("malformed /order option: '@' missing");
1126 // Get a list of all comdat sections for error checking.
1127 DenseSet
<StringRef
> set
;
1128 for (Chunk
*c
: ctx
.symtab
.getChunks())
1129 if (auto *sec
= dyn_cast
<SectionChunk
>(c
))
1131 set
.insert(sec
->sym
->getName());
1134 StringRef path
= arg
.substr(1);
1135 std::unique_ptr
<MemoryBuffer
> mb
=
1136 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1137 /*RequiresNullTerminator=*/false,
1138 /*IsVolatile=*/true),
1139 "could not open " + path
);
1141 // Parse a file. An order file contains one symbol per line.
1142 // All symbols that were not present in a given order file are
1143 // considered to have the lowest priority 0 and are placed at
1144 // end of an output section.
1145 for (StringRef arg
: args::getLines(mb
->getMemBufferRef())) {
1147 if (ctx
.config
.machine
== I386
&& !isDecorated(s
))
1150 if (set
.count(s
) == 0) {
1151 if (ctx
.config
.warnMissingOrderSymbol
)
1152 warn("/order:" + arg
+ ": missing symbol: " + s
+ " [LNK4037]");
1154 ctx
.config
.order
[s
] = INT_MIN
+ ctx
.config
.order
.size();
1157 // Include in /reproduce: output if applicable.
1158 ctx
.driver
.takeBuffer(std::move(mb
));
1161 void LinkerDriver::parseCallGraphFile(StringRef path
) {
1162 std::unique_ptr
<MemoryBuffer
> mb
=
1163 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1164 /*RequiresNullTerminator=*/false,
1165 /*IsVolatile=*/true),
1166 "could not open " + path
);
1168 // Build a map from symbol name to section.
1169 DenseMap
<StringRef
, Symbol
*> map
;
1170 for (ObjFile
*file
: ctx
.objFileInstances
)
1171 for (Symbol
*sym
: file
->getSymbols())
1173 map
[sym
->getName()] = sym
;
1175 auto findSection
= [&](StringRef name
) -> SectionChunk
* {
1176 Symbol
*sym
= map
.lookup(name
);
1178 if (ctx
.config
.warnMissingOrderSymbol
)
1179 warn(path
+ ": no such symbol: " + name
);
1183 if (DefinedCOFF
*dr
= dyn_cast_or_null
<DefinedCOFF
>(sym
))
1184 return dyn_cast_or_null
<SectionChunk
>(dr
->getChunk());
1188 for (StringRef line
: args::getLines(*mb
)) {
1189 SmallVector
<StringRef
, 3> fields
;
1190 line
.split(fields
, ' ');
1193 if (fields
.size() != 3 || !to_integer(fields
[2], count
)) {
1194 error(path
+ ": parse error");
1198 if (SectionChunk
*from
= findSection(fields
[0]))
1199 if (SectionChunk
*to
= findSection(fields
[1]))
1200 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1203 // Include in /reproduce: output if applicable.
1204 ctx
.driver
.takeBuffer(std::move(mb
));
1207 static void readCallGraphsFromObjectFiles(COFFLinkerContext
&ctx
) {
1208 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1209 if (obj
->callgraphSec
) {
1210 ArrayRef
<uint8_t> contents
;
1212 obj
->getCOFFObj()->getSectionContents(obj
->callgraphSec
, contents
));
1213 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
1214 while (!reader
.empty()) {
1215 uint32_t fromIndex
, toIndex
;
1217 if (Error err
= reader
.readInteger(fromIndex
))
1218 fatal(toString(obj
) + ": Expected 32-bit integer");
1219 if (Error err
= reader
.readInteger(toIndex
))
1220 fatal(toString(obj
) + ": Expected 32-bit integer");
1221 if (Error err
= reader
.readInteger(count
))
1222 fatal(toString(obj
) + ": Expected 64-bit integer");
1223 auto *fromSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(fromIndex
));
1224 auto *toSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(toIndex
));
1225 if (!fromSym
|| !toSym
)
1227 auto *from
= dyn_cast_or_null
<SectionChunk
>(fromSym
->getChunk());
1228 auto *to
= dyn_cast_or_null
<SectionChunk
>(toSym
->getChunk());
1230 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1236 static void markAddrsig(Symbol
*s
) {
1237 if (auto *d
= dyn_cast_or_null
<Defined
>(s
))
1238 if (SectionChunk
*c
= dyn_cast_or_null
<SectionChunk
>(d
->getChunk()))
1239 c
->keepUnique
= true;
1242 static void findKeepUniqueSections(COFFLinkerContext
&ctx
) {
1243 llvm::TimeTraceScope
timeScope("Find keep unique sections");
1245 // Exported symbols could be address-significant in other executables or DSOs,
1246 // so we conservatively mark them as address-significant.
1247 for (Export
&r
: ctx
.config
.exports
)
1250 // Visit the address-significance table in each object file and mark each
1251 // referenced symbol as address-significant.
1252 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1253 ArrayRef
<Symbol
*> syms
= obj
->getSymbols();
1254 if (obj
->addrsigSec
) {
1255 ArrayRef
<uint8_t> contents
;
1257 obj
->getCOFFObj()->getSectionContents(obj
->addrsigSec
, contents
));
1258 const uint8_t *cur
= contents
.begin();
1259 while (cur
!= contents
.end()) {
1262 uint64_t symIndex
= decodeULEB128(cur
, &size
, contents
.end(), &err
);
1264 fatal(toString(obj
) + ": could not decode addrsig section: " + err
);
1265 if (symIndex
>= syms
.size())
1266 fatal(toString(obj
) + ": invalid symbol index in addrsig section");
1267 markAddrsig(syms
[symIndex
]);
1271 // If an object file does not have an address-significance table,
1272 // conservatively mark all of its symbols as address-significant.
1273 for (Symbol
*s
: syms
)
1279 // link.exe replaces each %foo% in altPath with the contents of environment
1280 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1281 // of pdb's output path) and _EXT (expands to the extension of the output
1283 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1285 void LinkerDriver::parsePDBAltPath() {
1286 SmallString
<128> buf
;
1287 StringRef pdbBasename
=
1288 sys::path::filename(ctx
.config
.pdbPath
, sys::path::Style::windows
);
1289 StringRef binaryExtension
=
1290 sys::path::extension(ctx
.config
.outputFile
, sys::path::Style::windows
);
1291 if (!binaryExtension
.empty())
1292 binaryExtension
= binaryExtension
.substr(1); // %_EXT% does not include '.'.
1295 // +--------- cursor ('a...' might be the empty string).
1296 // | +----- firstMark
1297 // | | +- secondMark
1301 while (cursor
< ctx
.config
.pdbAltPath
.size()) {
1302 size_t firstMark
, secondMark
;
1303 if ((firstMark
= ctx
.config
.pdbAltPath
.find('%', cursor
)) ==
1305 (secondMark
= ctx
.config
.pdbAltPath
.find('%', firstMark
+ 1)) ==
1307 // Didn't find another full fragment, treat rest of string as literal.
1308 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
));
1312 // Found a full fragment. Append text in front of first %, and interpret
1313 // text between first and second % as variable name.
1314 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
, firstMark
- cursor
));
1316 ctx
.config
.pdbAltPath
.substr(firstMark
, secondMark
- firstMark
+ 1);
1317 if (var
.equals_insensitive("%_pdb%"))
1318 buf
.append(pdbBasename
);
1319 else if (var
.equals_insensitive("%_ext%"))
1320 buf
.append(binaryExtension
);
1322 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var
+
1327 cursor
= secondMark
+ 1;
1330 ctx
.config
.pdbAltPath
= buf
;
1333 /// Convert resource files and potentially merge input resource object
1334 /// trees into one resource tree.
1335 /// Call after ObjFile::Instances is complete.
1336 void LinkerDriver::convertResources() {
1337 llvm::TimeTraceScope
timeScope("Convert resources");
1338 std::vector
<ObjFile
*> resourceObjFiles
;
1340 for (ObjFile
*f
: ctx
.objFileInstances
) {
1341 if (f
->isResourceObjFile())
1342 resourceObjFiles
.push_back(f
);
1345 if (!ctx
.config
.mingw
&&
1346 (resourceObjFiles
.size() > 1 ||
1347 (resourceObjFiles
.size() == 1 && !resources
.empty()))) {
1348 error((!resources
.empty() ? "internal .obj file created from .res files"
1349 : toString(resourceObjFiles
[1])) +
1350 ": more than one resource obj file not allowed, already got " +
1351 toString(resourceObjFiles
.front()));
1355 if (resources
.empty() && resourceObjFiles
.size() <= 1) {
1356 // No resources to convert, and max one resource object file in
1357 // the input. Keep that preconverted resource section as is.
1358 for (ObjFile
*f
: resourceObjFiles
)
1359 f
->includeResourceChunks();
1363 make
<ObjFile
>(ctx
, convertResToCOFF(resources
, resourceObjFiles
));
1364 ctx
.symtab
.addFile(f
);
1365 f
->includeResourceChunks();
1368 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1369 // automatically exported by default. This behavior can be forced by the
1370 // -export-all-symbols option, so that it happens even when exports are
1371 // explicitly specified. The automatic behavior can be disabled using the
1372 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1373 // than MinGW in the case that nothing is explicitly exported.
1374 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList
&args
) {
1375 if (!args
.hasArg(OPT_export_all_symbols
)) {
1376 if (!ctx
.config
.dll
)
1379 if (!ctx
.config
.exports
.empty())
1381 if (args
.hasArg(OPT_exclude_all_symbols
))
1385 AutoExporter
exporter(ctx
, excludedSymbols
);
1387 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
1388 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
1389 exporter
.addWholeArchive(*path
);
1391 for (auto *arg
: args
.filtered(OPT_exclude_symbols
)) {
1392 SmallVector
<StringRef
, 2> vec
;
1393 StringRef(arg
->getValue()).split(vec
, ',');
1394 for (StringRef sym
: vec
)
1395 exporter
.addExcludedSymbol(mangle(sym
));
1398 ctx
.symtab
.forEachSymbol([&](Symbol
*s
) {
1399 auto *def
= dyn_cast
<Defined
>(s
);
1400 if (!exporter
.shouldExport(def
))
1403 if (!def
->isGCRoot
) {
1404 def
->isGCRoot
= true;
1405 ctx
.config
.gcroot
.push_back(def
);
1409 e
.name
= def
->getName();
1411 if (Chunk
*c
= def
->getChunk())
1412 if (!(c
->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE
))
1414 s
->isUsedInRegularObj
= true;
1415 ctx
.config
.exports
.push_back(e
);
1419 // lld has a feature to create a tar file containing all input files as well as
1420 // all command line options, so that other people can run lld again with exactly
1421 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1423 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1424 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1425 // with Microsoft link.exe.
1426 std::optional
<std::string
> getReproduceFile(const opt::InputArgList
&args
) {
1427 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
1428 return std::string(arg
->getValue());
1430 if (auto *arg
= args
.getLastArg(OPT_linkrepro
)) {
1431 SmallString
<64> path
= StringRef(arg
->getValue());
1432 sys::path::append(path
, "repro.tar");
1433 return std::string(path
);
1436 // This is intentionally not guarded by OPT_lldignoreenv since writing
1437 // a repro tar file doesn't affect the main output.
1438 if (auto *path
= getenv("LLD_REPRODUCE"))
1439 return std::string(path
);
1441 return std::nullopt
;
1444 static std::unique_ptr
<llvm::vfs::FileSystem
>
1445 getVFS(const opt::InputArgList
&args
) {
1446 using namespace llvm::vfs
;
1448 const opt::Arg
*arg
= args
.getLastArg(OPT_vfsoverlay
);
1452 auto bufOrErr
= llvm::MemoryBuffer::getFile(arg
->getValue());
1454 checkError(errorCodeToError(bufOrErr
.getError()));
1458 if (auto ret
= vfs::getVFSFromYAML(std::move(*bufOrErr
),
1459 /*DiagHandler*/ nullptr, arg
->getValue()))
1462 error("Invalid vfs overlay");
1466 void LinkerDriver::linkerMain(ArrayRef
<const char *> argsArr
) {
1467 ScopedTimer
rootTimer(ctx
.rootTimer
);
1468 Configuration
*config
= &ctx
.config
;
1471 InitializeAllTargetInfos();
1472 InitializeAllTargets();
1473 InitializeAllTargetMCs();
1474 InitializeAllAsmParsers();
1475 InitializeAllAsmPrinters();
1477 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1478 // We call our own implementation of lib.exe that understands bitcode files.
1479 if (argsArr
.size() > 1 &&
1480 (StringRef(argsArr
[1]).equals_insensitive("/lib") ||
1481 StringRef(argsArr
[1]).equals_insensitive("-lib"))) {
1482 if (llvm::libDriverMain(argsArr
.slice(1)) != 0)
1483 fatal("lib failed");
1487 // Parse command line options.
1488 ArgParser
parser(ctx
);
1489 opt::InputArgList args
= parser
.parse(argsArr
);
1491 // Initialize time trace profiler.
1492 config
->timeTraceEnabled
= args
.hasArg(OPT_time_trace_eq
);
1493 config
->timeTraceGranularity
=
1494 args::getInteger(args
, OPT_time_trace_granularity_eq
, 500);
1496 if (config
->timeTraceEnabled
)
1497 timeTraceProfilerInitialize(config
->timeTraceGranularity
, argsArr
[0]);
1499 llvm::TimeTraceScope
timeScope("COFF link");
1501 // Parse and evaluate -mllvm options.
1502 std::vector
<const char *> v
;
1503 v
.push_back("lld-link (LLVM option parsing)");
1504 for (const auto *arg
: args
.filtered(OPT_mllvm
)) {
1505 v
.push_back(arg
->getValue());
1506 config
->mllvmOpts
.emplace_back(arg
->getValue());
1509 llvm::TimeTraceScope
timeScope2("Parse cl::opt");
1510 cl::ResetAllOptionOccurrences();
1511 cl::ParseCommandLineOptions(v
.size(), v
.data());
1514 // Handle /errorlimit early, because error() depends on it.
1515 if (auto *arg
= args
.getLastArg(OPT_errorlimit
)) {
1517 StringRef s
= arg
->getValue();
1518 if (s
.getAsInteger(10, n
))
1519 error(arg
->getSpelling() + " number expected, but got " + s
);
1520 errorHandler().errorLimit
= n
;
1523 config
->vfs
= getVFS(args
);
1526 if (args
.hasArg(OPT_help
)) {
1527 printHelp(argsArr
[0]);
1531 // /threads: takes a positive integer and provides the default value for
1532 // /opt:lldltojobs=.
1533 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
1534 StringRef
v(arg
->getValue());
1535 unsigned threads
= 0;
1536 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
1537 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
1538 arg
->getValue() + "'");
1539 parallel::strategy
= hardware_concurrency(threads
);
1540 config
->thinLTOJobs
= v
.str();
1543 if (args
.hasArg(OPT_show_timing
))
1544 config
->showTiming
= true;
1546 config
->showSummary
= args
.hasArg(OPT_summary
);
1547 config
->printSearchPaths
= args
.hasArg(OPT_print_search_paths
);
1549 // Handle --version, which is an lld extension. This option is a bit odd
1550 // because it doesn't start with "/", but we deliberately chose "--" to
1551 // avoid conflict with /version and for compatibility with clang-cl.
1552 if (args
.hasArg(OPT_dash_dash_version
)) {
1553 message(getLLDVersion());
1557 // Handle /lldmingw early, since it can potentially affect how other
1558 // options are handled.
1559 config
->mingw
= args
.hasArg(OPT_lldmingw
);
1561 ctx
.e
.errorLimitExceededMsg
= "too many errors emitted, stopping now"
1562 " (use --error-limit=0 to see all errors)";
1564 // Handle /linkrepro and /reproduce.
1566 llvm::TimeTraceScope
timeScope2("Reproducer");
1567 if (std::optional
<std::string
> path
= getReproduceFile(args
)) {
1568 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
1569 TarWriter::create(*path
, sys::path::stem(*path
));
1572 tar
= std::move(*errOrWriter
);
1574 error("/linkrepro: failed to open " + *path
+ ": " +
1575 toString(errOrWriter
.takeError()));
1580 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
1581 if (args
.hasArg(OPT_deffile
))
1582 config
->noEntry
= true;
1584 fatal("no input files");
1587 // Construct search path list.
1589 llvm::TimeTraceScope
timeScope2("Search paths");
1590 searchPaths
.emplace_back("");
1591 if (!config
->mingw
) {
1592 // Prefer the Clang provided builtins over the ones bundled with MSVC.
1593 // In MinGW mode, the compiler driver passes the necessary libpath
1594 // options explicitly.
1595 addClangLibSearchPaths(argsArr
[0]);
1597 for (auto *arg
: args
.filtered(OPT_libpath
))
1598 searchPaths
.push_back(arg
->getValue());
1599 if (!config
->mingw
) {
1600 // Don't automatically deduce the lib path from the environment or MSVC
1601 // installations when operating in mingw mode. (This also makes LLD ignore
1602 // winsysroot and vctoolsdir arguments.)
1603 detectWinSysRoot(args
);
1604 if (!args
.hasArg(OPT_lldignoreenv
) && !args
.hasArg(OPT_winsysroot
))
1605 addLibSearchPaths();
1607 if (args
.hasArg(OPT_vctoolsdir
, OPT_winsysroot
))
1608 warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
1613 for (auto *arg
: args
.filtered(OPT_ignore
)) {
1614 SmallVector
<StringRef
, 8> vec
;
1615 StringRef(arg
->getValue()).split(vec
, ',');
1616 for (StringRef s
: vec
) {
1618 config
->warnMissingOrderSymbol
= false;
1619 else if (s
== "4099")
1620 config
->warnDebugInfoUnusable
= false;
1621 else if (s
== "4217")
1622 config
->warnLocallyDefinedImported
= false;
1623 else if (s
== "longsections")
1624 config
->warnLongSectionNames
= false;
1625 // Other warning numbers are ignored.
1630 if (auto *arg
= args
.getLastArg(OPT_out
))
1631 config
->outputFile
= arg
->getValue();
1634 if (args
.hasArg(OPT_verbose
))
1635 config
->verbose
= true;
1636 errorHandler().verbose
= config
->verbose
;
1638 // Handle /force or /force:unresolved
1639 if (args
.hasArg(OPT_force
, OPT_force_unresolved
))
1640 config
->forceUnresolved
= true;
1642 // Handle /force or /force:multiple
1643 if (args
.hasArg(OPT_force
, OPT_force_multiple
))
1644 config
->forceMultiple
= true;
1646 // Handle /force or /force:multipleres
1647 if (args
.hasArg(OPT_force
, OPT_force_multipleres
))
1648 config
->forceMultipleRes
= true;
1651 DebugKind debug
= parseDebugKind(args
);
1652 if (debug
== DebugKind::Full
|| debug
== DebugKind::Dwarf
||
1653 debug
== DebugKind::GHash
|| debug
== DebugKind::NoGHash
) {
1654 config
->debug
= true;
1655 config
->incremental
= true;
1659 config
->demangle
= args
.hasFlag(OPT_demangle
, OPT_demangle_no
, true);
1661 // Handle /debugtype
1662 config
->debugTypes
= parseDebugTypes(args
);
1664 // Handle /driver[:uponly|:wdm].
1665 config
->driverUponly
= args
.hasArg(OPT_driver_uponly
) ||
1666 args
.hasArg(OPT_driver_uponly_wdm
) ||
1667 args
.hasArg(OPT_driver_wdm_uponly
);
1668 config
->driverWdm
= args
.hasArg(OPT_driver_wdm
) ||
1669 args
.hasArg(OPT_driver_uponly_wdm
) ||
1670 args
.hasArg(OPT_driver_wdm_uponly
);
1672 config
->driverUponly
|| config
->driverWdm
|| args
.hasArg(OPT_driver
);
1675 bool shouldCreatePDB
=
1676 (debug
== DebugKind::Full
|| debug
== DebugKind::GHash
||
1677 debug
== DebugKind::NoGHash
);
1678 if (shouldCreatePDB
) {
1679 if (auto *arg
= args
.getLastArg(OPT_pdb
))
1680 config
->pdbPath
= arg
->getValue();
1681 if (auto *arg
= args
.getLastArg(OPT_pdbaltpath
))
1682 config
->pdbAltPath
= arg
->getValue();
1683 if (auto *arg
= args
.getLastArg(OPT_pdbpagesize
))
1684 parsePDBPageSize(arg
->getValue());
1685 if (args
.hasArg(OPT_natvis
))
1686 config
->natvisFiles
= args
.getAllArgValues(OPT_natvis
);
1687 if (args
.hasArg(OPT_pdbstream
)) {
1688 for (const StringRef value
: args
.getAllArgValues(OPT_pdbstream
)) {
1689 const std::pair
<StringRef
, StringRef
> nameFile
= value
.split("=");
1690 const StringRef name
= nameFile
.first
;
1691 const std::string file
= nameFile
.second
.str();
1692 config
->namedStreams
[name
] = file
;
1696 if (auto *arg
= args
.getLastArg(OPT_pdb_source_path
))
1697 config
->pdbSourcePath
= arg
->getValue();
1700 // Handle /pdbstripped
1701 if (args
.hasArg(OPT_pdbstripped
))
1702 warn("ignoring /pdbstripped flag, it is not yet supported");
1705 if (args
.hasArg(OPT_noentry
)) {
1706 if (args
.hasArg(OPT_dll
))
1707 config
->noEntry
= true;
1709 error("/noentry must be specified with /dll");
1713 if (args
.hasArg(OPT_dll
)) {
1715 config
->manifestID
= 2;
1718 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1719 // because we need to explicitly check whether that option or its inverse was
1720 // present in the argument list in order to handle /fixed.
1721 auto *dynamicBaseArg
= args
.getLastArg(OPT_dynamicbase
, OPT_dynamicbase_no
);
1722 if (dynamicBaseArg
&&
1723 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase_no
)
1724 config
->dynamicBase
= false;
1726 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1727 // default setting for any other project type.", but link.exe defaults to
1728 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1729 bool fixed
= args
.hasFlag(OPT_fixed
, OPT_fixed_no
, false);
1731 if (dynamicBaseArg
&&
1732 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase
) {
1733 error("/fixed must not be specified with /dynamicbase");
1735 config
->relocatable
= false;
1736 config
->dynamicBase
= false;
1740 // Handle /appcontainer
1741 config
->appContainer
=
1742 args
.hasFlag(OPT_appcontainer
, OPT_appcontainer_no
, false);
1746 llvm::TimeTraceScope
timeScope2("Machine arg");
1747 if (auto *arg
= args
.getLastArg(OPT_machine
)) {
1748 config
->machine
= getMachineType(arg
->getValue());
1749 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
)
1750 fatal(Twine("unknown /machine argument: ") + arg
->getValue());
1751 addWinSysRootLibSearchPaths();
1755 // Handle /nodefaultlib:<filename>
1757 llvm::TimeTraceScope
timeScope2("Nodefaultlib");
1758 for (auto *arg
: args
.filtered(OPT_nodefaultlib
))
1759 config
->noDefaultLibs
.insert(findLib(arg
->getValue()).lower());
1762 // Handle /nodefaultlib
1763 if (args
.hasArg(OPT_nodefaultlib_all
))
1764 config
->noDefaultLibAll
= true;
1767 if (auto *arg
= args
.getLastArg(OPT_base
))
1768 parseNumbers(arg
->getValue(), &config
->imageBase
);
1770 // Handle /filealign
1771 if (auto *arg
= args
.getLastArg(OPT_filealign
)) {
1772 parseNumbers(arg
->getValue(), &config
->fileAlign
);
1773 if (!isPowerOf2_64(config
->fileAlign
))
1774 error("/filealign: not a power of two: " + Twine(config
->fileAlign
));
1778 if (auto *arg
= args
.getLastArg(OPT_stack
))
1779 parseNumbers(arg
->getValue(), &config
->stackReserve
, &config
->stackCommit
);
1782 if (auto *arg
= args
.getLastArg(OPT_guard
))
1783 parseGuard(arg
->getValue());
1786 if (auto *arg
= args
.getLastArg(OPT_heap
))
1787 parseNumbers(arg
->getValue(), &config
->heapReserve
, &config
->heapCommit
);
1790 if (auto *arg
= args
.getLastArg(OPT_version
))
1791 parseVersion(arg
->getValue(), &config
->majorImageVersion
,
1792 &config
->minorImageVersion
);
1794 // Handle /subsystem
1795 if (auto *arg
= args
.getLastArg(OPT_subsystem
))
1796 parseSubsystem(arg
->getValue(), &config
->subsystem
,
1797 &config
->majorSubsystemVersion
,
1798 &config
->minorSubsystemVersion
);
1800 // Handle /osversion
1801 if (auto *arg
= args
.getLastArg(OPT_osversion
)) {
1802 parseVersion(arg
->getValue(), &config
->majorOSVersion
,
1803 &config
->minorOSVersion
);
1805 config
->majorOSVersion
= config
->majorSubsystemVersion
;
1806 config
->minorOSVersion
= config
->minorSubsystemVersion
;
1809 // Handle /timestamp
1810 if (llvm::opt::Arg
*arg
= args
.getLastArg(OPT_timestamp
, OPT_repro
)) {
1811 if (arg
->getOption().getID() == OPT_repro
) {
1812 config
->timestamp
= 0;
1813 config
->repro
= true;
1815 config
->repro
= false;
1816 StringRef
value(arg
->getValue());
1817 if (value
.getAsInteger(0, config
->timestamp
))
1818 fatal(Twine("invalid timestamp: ") + value
+
1819 ". Expected 32-bit integer");
1822 config
->repro
= false;
1823 config
->timestamp
= time(nullptr);
1826 // Handle /alternatename
1827 for (auto *arg
: args
.filtered(OPT_alternatename
))
1828 parseAlternateName(arg
->getValue());
1831 for (auto *arg
: args
.filtered(OPT_incl
))
1832 addUndefined(arg
->getValue());
1835 if (auto *arg
= args
.getLastArg(OPT_implib
))
1836 config
->implib
= arg
->getValue();
1838 config
->noimplib
= args
.hasArg(OPT_noimplib
);
1841 bool doGC
= debug
== DebugKind::None
|| args
.hasArg(OPT_profile
);
1842 std::optional
<ICFLevel
> icfLevel
;
1843 if (args
.hasArg(OPT_profile
))
1844 icfLevel
= ICFLevel::None
;
1845 unsigned tailMerge
= 1;
1846 bool ltoDebugPM
= false;
1847 for (auto *arg
: args
.filtered(OPT_opt
)) {
1848 std::string str
= StringRef(arg
->getValue()).lower();
1849 SmallVector
<StringRef
, 1> vec
;
1850 StringRef(str
).split(vec
, ',');
1851 for (StringRef s
: vec
) {
1854 } else if (s
== "noref") {
1856 } else if (s
== "icf" || s
.starts_with("icf=")) {
1857 icfLevel
= ICFLevel::All
;
1858 } else if (s
== "safeicf") {
1859 icfLevel
= ICFLevel::Safe
;
1860 } else if (s
== "noicf") {
1861 icfLevel
= ICFLevel::None
;
1862 } else if (s
== "lldtailmerge") {
1864 } else if (s
== "nolldtailmerge") {
1866 } else if (s
== "ltodebugpassmanager") {
1868 } else if (s
== "noltodebugpassmanager") {
1870 } else if (s
.consume_front("lldlto=")) {
1871 if (s
.getAsInteger(10, config
->ltoo
) || config
->ltoo
> 3)
1872 error("/opt:lldlto: invalid optimization level: " + s
);
1873 } else if (s
.consume_front("lldltocgo=")) {
1874 config
->ltoCgo
.emplace();
1875 if (s
.getAsInteger(10, *config
->ltoCgo
) || *config
->ltoCgo
> 3)
1876 error("/opt:lldltocgo: invalid codegen optimization level: " + s
);
1877 } else if (s
.consume_front("lldltojobs=")) {
1878 if (!get_threadpool_strategy(s
))
1879 error("/opt:lldltojobs: invalid job count: " + s
);
1880 config
->thinLTOJobs
= s
.str();
1881 } else if (s
.consume_front("lldltopartitions=")) {
1882 if (s
.getAsInteger(10, config
->ltoPartitions
) ||
1883 config
->ltoPartitions
== 0)
1884 error("/opt:lldltopartitions: invalid partition count: " + s
);
1885 } else if (s
!= "lbr" && s
!= "nolbr")
1886 error("/opt: unknown option: " + s
);
1891 icfLevel
= doGC
? ICFLevel::All
: ICFLevel::None
;
1892 config
->doGC
= doGC
;
1893 config
->doICF
= *icfLevel
;
1895 (tailMerge
== 1 && config
->doICF
!= ICFLevel::None
) || tailMerge
== 2;
1896 config
->ltoDebugPassManager
= ltoDebugPM
;
1898 // Handle /lldsavetemps
1899 if (args
.hasArg(OPT_lldsavetemps
))
1900 config
->saveTemps
= true;
1903 if (auto *arg
= args
.getLastArg(OPT_lldemit
)) {
1904 StringRef s
= arg
->getValue();
1906 config
->emit
= EmitKind::Obj
;
1907 else if (s
== "llvm")
1908 config
->emit
= EmitKind::LLVM
;
1909 else if (s
== "asm")
1910 config
->emit
= EmitKind::ASM
;
1912 error("/lldemit: unknown option: " + s
);
1916 if (args
.hasArg(OPT_kill_at
))
1917 config
->killAt
= true;
1919 // Handle /lldltocache
1920 if (auto *arg
= args
.getLastArg(OPT_lldltocache
))
1921 config
->ltoCache
= arg
->getValue();
1923 // Handle /lldsavecachepolicy
1924 if (auto *arg
= args
.getLastArg(OPT_lldltocachepolicy
))
1925 config
->ltoCachePolicy
= CHECK(
1926 parseCachePruningPolicy(arg
->getValue()),
1927 Twine("/lldltocachepolicy: invalid cache policy: ") + arg
->getValue());
1929 // Handle /failifmismatch
1930 for (auto *arg
: args
.filtered(OPT_failifmismatch
))
1931 checkFailIfMismatch(arg
->getValue(), nullptr);
1934 for (auto *arg
: args
.filtered(OPT_merge
))
1935 parseMerge(arg
->getValue());
1937 // Add default section merging rules after user rules. User rules take
1938 // precedence, but we will emit a warning if there is a conflict.
1939 parseMerge(".idata=.rdata");
1940 parseMerge(".didat=.rdata");
1941 parseMerge(".edata=.rdata");
1942 parseMerge(".xdata=.rdata");
1943 parseMerge(".bss=.data");
1945 if (config
->mingw
) {
1946 parseMerge(".ctors=.rdata");
1947 parseMerge(".dtors=.rdata");
1948 parseMerge(".CRT=.rdata");
1952 for (auto *arg
: args
.filtered(OPT_section
))
1953 parseSection(arg
->getValue());
1956 if (auto *arg
= args
.getLastArg(OPT_align
)) {
1957 parseNumbers(arg
->getValue(), &config
->align
);
1958 if (!isPowerOf2_64(config
->align
))
1959 error("/align: not a power of two: " + StringRef(arg
->getValue()));
1960 if (!args
.hasArg(OPT_driver
))
1961 warn("/align specified without /driver; image may not run");
1964 // Handle /aligncomm
1965 for (auto *arg
: args
.filtered(OPT_aligncomm
))
1966 parseAligncomm(arg
->getValue());
1968 // Handle /manifestdependency.
1969 for (auto *arg
: args
.filtered(OPT_manifestdependency
))
1970 config
->manifestDependencies
.insert(arg
->getValue());
1972 // Handle /manifest and /manifest:
1973 if (auto *arg
= args
.getLastArg(OPT_manifest
, OPT_manifest_colon
)) {
1974 if (arg
->getOption().getID() == OPT_manifest
)
1975 config
->manifest
= Configuration::SideBySide
;
1977 parseManifest(arg
->getValue());
1980 // Handle /manifestuac
1981 if (auto *arg
= args
.getLastArg(OPT_manifestuac
))
1982 parseManifestUAC(arg
->getValue());
1984 // Handle /manifestfile
1985 if (auto *arg
= args
.getLastArg(OPT_manifestfile
))
1986 config
->manifestFile
= arg
->getValue();
1988 // Handle /manifestinput
1989 for (auto *arg
: args
.filtered(OPT_manifestinput
))
1990 config
->manifestInput
.push_back(arg
->getValue());
1992 if (!config
->manifestInput
.empty() &&
1993 config
->manifest
!= Configuration::Embed
) {
1994 fatal("/manifestinput: requires /manifest:embed");
1998 config
->dwoDir
= args
.getLastArgValue(OPT_dwodir
);
2000 config
->thinLTOEmitImportsFiles
= args
.hasArg(OPT_thinlto_emit_imports_files
);
2001 config
->thinLTOIndexOnly
= args
.hasArg(OPT_thinlto_index_only
) ||
2002 args
.hasArg(OPT_thinlto_index_only_arg
);
2003 config
->thinLTOIndexOnlyArg
=
2004 args
.getLastArgValue(OPT_thinlto_index_only_arg
);
2005 std::tie(config
->thinLTOPrefixReplaceOld
, config
->thinLTOPrefixReplaceNew
,
2006 config
->thinLTOPrefixReplaceNativeObject
) =
2007 getOldNewOptionsExtra(args
, OPT_thinlto_prefix_replace
);
2008 config
->thinLTOObjectSuffixReplace
=
2009 getOldNewOptions(args
, OPT_thinlto_object_suffix_replace
);
2010 config
->ltoObjPath
= args
.getLastArgValue(OPT_lto_obj_path
);
2011 config
->ltoCSProfileGenerate
= args
.hasArg(OPT_lto_cs_profile_generate
);
2012 config
->ltoCSProfileFile
= args
.getLastArgValue(OPT_lto_cs_profile_file
);
2013 // Handle miscellaneous boolean flags.
2014 config
->ltoPGOWarnMismatch
= args
.hasFlag(OPT_lto_pgo_warn_mismatch
,
2015 OPT_lto_pgo_warn_mismatch_no
, true);
2016 config
->allowBind
= args
.hasFlag(OPT_allowbind
, OPT_allowbind_no
, true);
2017 config
->allowIsolation
=
2018 args
.hasFlag(OPT_allowisolation
, OPT_allowisolation_no
, true);
2019 config
->incremental
=
2020 args
.hasFlag(OPT_incremental
, OPT_incremental_no
,
2021 !config
->doGC
&& config
->doICF
== ICFLevel::None
&&
2022 !args
.hasArg(OPT_order
) && !args
.hasArg(OPT_profile
));
2023 config
->integrityCheck
=
2024 args
.hasFlag(OPT_integritycheck
, OPT_integritycheck_no
, false);
2025 config
->cetCompat
= args
.hasFlag(OPT_cetcompat
, OPT_cetcompat_no
, false);
2026 config
->nxCompat
= args
.hasFlag(OPT_nxcompat
, OPT_nxcompat_no
, true);
2027 for (auto *arg
: args
.filtered(OPT_swaprun
))
2028 parseSwaprun(arg
->getValue());
2029 config
->terminalServerAware
=
2030 !config
->dll
&& args
.hasFlag(OPT_tsaware
, OPT_tsaware_no
, true);
2031 config
->debugDwarf
= debug
== DebugKind::Dwarf
;
2032 config
->debugGHashes
= debug
== DebugKind::GHash
|| debug
== DebugKind::Full
;
2033 config
->debugSymtab
= debug
== DebugKind::Symtab
;
2034 config
->autoImport
=
2035 args
.hasFlag(OPT_auto_import
, OPT_auto_import_no
, config
->mingw
);
2036 config
->pseudoRelocs
= args
.hasFlag(
2037 OPT_runtime_pseudo_reloc
, OPT_runtime_pseudo_reloc_no
, config
->mingw
);
2038 config
->callGraphProfileSort
= args
.hasFlag(
2039 OPT_call_graph_profile_sort
, OPT_call_graph_profile_sort_no
, true);
2040 config
->stdcallFixup
=
2041 args
.hasFlag(OPT_stdcall_fixup
, OPT_stdcall_fixup_no
, config
->mingw
);
2042 config
->warnStdcallFixup
= !args
.hasArg(OPT_stdcall_fixup
);
2043 config
->allowDuplicateWeak
=
2044 args
.hasFlag(OPT_lld_allow_duplicate_weak
,
2045 OPT_lld_allow_duplicate_weak_no
, config
->mingw
);
2047 if (args
.hasFlag(OPT_inferasanlibs
, OPT_inferasanlibs_no
, false))
2048 warn("ignoring '/inferasanlibs', this flag is not supported");
2050 // Don't warn about long section names, such as .debug_info, for mingw or
2051 // when -debug:dwarf is requested.
2052 if (config
->mingw
|| config
->debugDwarf
)
2053 config
->warnLongSectionNames
= false;
2055 if (config
->incremental
&& args
.hasArg(OPT_profile
)) {
2056 warn("ignoring '/incremental' due to '/profile' specification");
2057 config
->incremental
= false;
2060 if (config
->incremental
&& args
.hasArg(OPT_order
)) {
2061 warn("ignoring '/incremental' due to '/order' specification");
2062 config
->incremental
= false;
2065 if (config
->incremental
&& config
->doGC
) {
2066 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
2068 config
->incremental
= false;
2071 if (config
->incremental
&& config
->doICF
!= ICFLevel::None
) {
2072 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
2074 config
->incremental
= false;
2080 std::set
<sys::fs::UniqueID
> wholeArchives
;
2081 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
2082 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
2083 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(*path
))
2084 wholeArchives
.insert(*id
);
2086 // A predicate returning true if a given path is an argument for
2087 // /wholearchive:, or /wholearchive is enabled globally.
2088 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
2089 // needs to be handled as "/wholearchive:foo.obj foo.obj".
2090 auto isWholeArchive
= [&](StringRef path
) -> bool {
2091 if (args
.hasArg(OPT_wholearchive_flag
))
2093 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
2094 return wholeArchives
.count(*id
);
2098 // Create a list of input files. These can be given as OPT_INPUT options
2099 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
2102 llvm::TimeTraceScope
timeScope2("Parse & queue inputs");
2104 for (auto *arg
: args
) {
2105 switch (arg
->getOption().getID()) {
2108 error("stray " + arg
->getSpelling());
2113 error("nested " + arg
->getSpelling());
2116 case OPT_wholearchive_file
:
2117 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2118 enqueuePath(*path
, true, inLib
);
2121 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2122 enqueuePath(*path
, isWholeArchive(*path
), inLib
);
2125 // Ignore other options.
2131 // Read all input files given via the command line.
2136 // We should have inferred a machine type by now from the input files, but if
2137 // not we assume x64.
2138 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
) {
2139 warn("/machine is not specified. x64 is assumed");
2140 config
->machine
= AMD64
;
2141 addWinSysRootLibSearchPaths();
2143 config
->wordsize
= config
->is64() ? 8 : 4;
2145 if (config
->printSearchPaths
) {
2146 SmallString
<256> buffer
;
2147 raw_svector_ostream
stream(buffer
);
2148 stream
<< "Library search paths:\n";
2150 for (StringRef path
: searchPaths
) {
2153 stream
<< " " << path
<< "\n";
2159 // Process files specified as /defaultlib. These must be processed after
2160 // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
2161 for (auto *arg
: args
.filtered(OPT_defaultlib
))
2162 if (std::optional
<StringRef
> path
= findLibIfNew(arg
->getValue()))
2163 enqueuePath(*path
, false, false);
2169 if (args
.hasArg(OPT_release
))
2170 config
->writeCheckSum
= true;
2172 // Handle /safeseh, x86 only, on by default, except for mingw.
2173 if (config
->machine
== I386
) {
2174 config
->safeSEH
= args
.hasFlag(OPT_safeseh
, OPT_safeseh_no
, !config
->mingw
);
2175 config
->noSEH
= args
.hasArg(OPT_noseh
);
2178 // Handle /functionpadmin
2179 for (auto *arg
: args
.filtered(OPT_functionpadmin
, OPT_functionpadmin_opt
))
2180 parseFunctionPadMin(arg
);
2183 llvm::TimeTraceScope
timeScope("Reproducer: response file");
2184 tar
->append("response.txt",
2185 createResponseFile(args
, filePaths
,
2186 ArrayRef
<StringRef
>(searchPaths
).slice(1)));
2189 // Handle /largeaddressaware
2190 config
->largeAddressAware
= args
.hasFlag(
2191 OPT_largeaddressaware
, OPT_largeaddressaware_no
, config
->is64());
2193 // Handle /highentropyva
2194 config
->highEntropyVA
=
2196 args
.hasFlag(OPT_highentropyva
, OPT_highentropyva_no
, true);
2198 if (!config
->dynamicBase
&&
2199 (config
->machine
== ARMNT
|| isAnyArm64(config
->machine
)))
2200 error("/dynamicbase:no is not compatible with " +
2201 machineToStr(config
->machine
));
2205 llvm::TimeTraceScope
timeScope("Parse /export");
2206 for (auto *arg
: args
.filtered(OPT_export
)) {
2207 Export e
= parseExport(arg
->getValue());
2208 if (config
->machine
== I386
) {
2209 if (!isDecorated(e
.name
))
2210 e
.name
= saver().save("_" + e
.name
);
2211 if (!e
.extName
.empty() && !isDecorated(e
.extName
))
2212 e
.extName
= saver().save("_" + e
.extName
);
2214 config
->exports
.push_back(e
);
2219 if (auto *arg
= args
.getLastArg(OPT_deffile
)) {
2220 // parseModuleDefs mutates Config object.
2221 parseModuleDefs(arg
->getValue());
2224 // Handle generation of import library from a def file.
2225 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
2227 if (!config
->noimplib
)
2228 createImportLibrary(/*asLib=*/true);
2232 // Windows specific -- if no /subsystem is given, we need to infer
2233 // that from entry point name. Must happen before /entry handling,
2234 // and after the early return when just writing an import library.
2235 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
) {
2236 llvm::TimeTraceScope
timeScope("Infer subsystem");
2237 config
->subsystem
= inferSubsystem();
2238 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
)
2239 fatal("subsystem must be defined");
2242 // Handle /entry and /dll
2244 llvm::TimeTraceScope
timeScope("Entry point");
2245 if (auto *arg
= args
.getLastArg(OPT_entry
)) {
2246 config
->entry
= addUndefined(mangle(arg
->getValue()));
2247 } else if (!config
->entry
&& !config
->noEntry
) {
2248 if (args
.hasArg(OPT_dll
)) {
2249 StringRef s
= (config
->machine
== I386
) ? "__DllMainCRTStartup@12"
2250 : "_DllMainCRTStartup";
2251 config
->entry
= addUndefined(s
);
2252 } else if (config
->driverWdm
) {
2253 // /driver:wdm implies /entry:_NtProcessStartup
2254 config
->entry
= addUndefined(mangle("_NtProcessStartup"));
2256 // Windows specific -- If entry point name is not given, we need to
2257 // infer that from user-defined entry name.
2258 StringRef s
= findDefaultEntry();
2260 fatal("entry point must be defined");
2261 config
->entry
= addUndefined(s
);
2262 log("Entry name inferred: " + s
);
2267 // Handle /delayload
2269 llvm::TimeTraceScope
timeScope("Delay load");
2270 for (auto *arg
: args
.filtered(OPT_delayload
)) {
2271 config
->delayLoads
.insert(StringRef(arg
->getValue()).lower());
2272 if (config
->machine
== I386
) {
2273 config
->delayLoadHelper
= addUndefined("___delayLoadHelper2@8");
2275 config
->delayLoadHelper
= addUndefined("__delayLoadHelper2");
2280 // Set default image name if neither /out or /def set it.
2281 if (config
->outputFile
.empty()) {
2282 config
->outputFile
= getOutputPath(
2283 (*args
.filtered(OPT_INPUT
, OPT_wholearchive_file
).begin())->getValue(),
2284 config
->dll
, config
->driver
);
2287 // Fail early if an output file is not writable.
2288 if (auto e
= tryCreateFile(config
->outputFile
)) {
2289 error("cannot open output file " + config
->outputFile
+ ": " + e
.message());
2293 config
->lldmapFile
= getMapFile(args
, OPT_lldmap
, OPT_lldmap_file
);
2294 config
->mapFile
= getMapFile(args
, OPT_map
, OPT_map_file
);
2296 if (config
->mapFile
!= "" && args
.hasArg(OPT_map_info
)) {
2297 for (auto *arg
: args
.filtered(OPT_map_info
)) {
2298 std::string s
= StringRef(arg
->getValue()).lower();
2300 config
->mapInfo
= true;
2302 error("unknown option: /mapinfo:" + s
);
2306 if (config
->lldmapFile
!= "" && config
->lldmapFile
== config
->mapFile
) {
2307 warn("/lldmap and /map have the same output file '" + config
->mapFile
+
2308 "'.\n>>> ignoring /lldmap");
2309 config
->lldmapFile
.clear();
2312 if (shouldCreatePDB
) {
2313 // Put the PDB next to the image if no /pdb flag was passed.
2314 if (config
->pdbPath
.empty()) {
2315 config
->pdbPath
= config
->outputFile
;
2316 sys::path::replace_extension(config
->pdbPath
, ".pdb");
2319 // The embedded PDB path should be the absolute path to the PDB if no
2320 // /pdbaltpath flag was passed.
2321 if (config
->pdbAltPath
.empty()) {
2322 config
->pdbAltPath
= config
->pdbPath
;
2324 // It's important to make the path absolute and remove dots. This path
2325 // will eventually be written into the PE header, and certain Microsoft
2326 // tools won't work correctly if these assumptions are not held.
2327 sys::fs::make_absolute(config
->pdbAltPath
);
2328 sys::path::remove_dots(config
->pdbAltPath
);
2330 // Don't do this earlier, so that ctx.OutputFile is ready.
2335 // Set default image base if /base is not given.
2336 if (config
->imageBase
== uint64_t(-1))
2337 config
->imageBase
= getDefaultImageBase();
2339 ctx
.symtab
.addSynthetic(mangle("__ImageBase"), nullptr);
2340 if (config
->machine
== I386
) {
2341 ctx
.symtab
.addAbsolute("___safe_se_handler_table", 0);
2342 ctx
.symtab
.addAbsolute("___safe_se_handler_count", 0);
2345 ctx
.symtab
.addAbsolute(mangle("__guard_fids_count"), 0);
2346 ctx
.symtab
.addAbsolute(mangle("__guard_fids_table"), 0);
2347 ctx
.symtab
.addAbsolute(mangle("__guard_flags"), 0);
2348 ctx
.symtab
.addAbsolute(mangle("__guard_iat_count"), 0);
2349 ctx
.symtab
.addAbsolute(mangle("__guard_iat_table"), 0);
2350 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_count"), 0);
2351 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_table"), 0);
2352 // Needed for MSVC 2017 15.5 CRT.
2353 ctx
.symtab
.addAbsolute(mangle("__enclave_config"), 0);
2354 // Needed for MSVC 2019 16.8 CRT.
2355 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2356 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2358 if (config
->pseudoRelocs
) {
2359 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2360 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2362 if (config
->mingw
) {
2363 ctx
.symtab
.addAbsolute(mangle("__CTOR_LIST__"), 0);
2364 ctx
.symtab
.addAbsolute(mangle("__DTOR_LIST__"), 0);
2367 // This code may add new undefined symbols to the link, which may enqueue more
2368 // symbol resolution tasks, so we need to continue executing tasks until we
2371 llvm::TimeTraceScope
timeScope("Add unresolved symbols");
2373 // Windows specific -- if entry point is not found,
2374 // search for its mangled names.
2376 mangleMaybe(config
->entry
);
2378 // Windows specific -- Make sure we resolve all dllexported symbols.
2379 for (Export
&e
: config
->exports
) {
2380 if (!e
.forwardTo
.empty())
2382 e
.sym
= addUndefined(e
.name
);
2383 if (e
.source
!= ExportSource::Directives
)
2384 e
.symbolName
= mangleMaybe(e
.sym
);
2387 // Add weak aliases. Weak aliases is a mechanism to give remaining
2388 // undefined symbols final chance to be resolved successfully.
2389 for (auto pair
: config
->alternateNames
) {
2390 StringRef from
= pair
.first
;
2391 StringRef to
= pair
.second
;
2392 Symbol
*sym
= ctx
.symtab
.find(from
);
2395 if (auto *u
= dyn_cast
<Undefined
>(sym
))
2397 u
->weakAlias
= ctx
.symtab
.addUndefined(to
);
2400 // If any inputs are bitcode files, the LTO code generator may create
2401 // references to library functions that are not explicit in the bitcode
2402 // file's symbol table. If any of those library functions are defined in a
2403 // bitcode file in an archive member, we need to arrange to use LTO to
2404 // compile those archive members by adding them to the link beforehand.
2405 if (!ctx
.bitcodeFileInstances
.empty())
2406 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols())
2407 ctx
.symtab
.addLibcall(s
);
2409 // Windows specific -- if __load_config_used can be resolved, resolve it.
2410 if (ctx
.symtab
.findUnderscore("_load_config_used"))
2411 addUndefined(mangle("_load_config_used"));
2413 if (args
.hasArg(OPT_include_optional
)) {
2414 // Handle /includeoptional
2415 for (auto *arg
: args
.filtered(OPT_include_optional
))
2416 if (isa_and_nonnull
<LazyArchive
>(ctx
.symtab
.find(arg
->getValue())))
2417 addUndefined(arg
->getValue());
2422 // Create wrapped symbols for -wrap option.
2423 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(ctx
, args
);
2424 // Load more object files that might be needed for wrapped symbols.
2425 if (!wrapped
.empty())
2429 if (config
->autoImport
|| config
->stdcallFixup
) {
2431 // Load any further object files that might be needed for doing automatic
2432 // imports, and do stdcall fixups.
2434 // For cases with no automatically imported symbols, this iterates once
2435 // over the symbol table and doesn't do anything.
2437 // For the normal case with a few automatically imported symbols, this
2438 // should only need to be run once, since each new object file imported
2439 // is an import library and wouldn't add any new undefined references,
2440 // but there's nothing stopping the __imp_ symbols from coming from a
2441 // normal object file as well (although that won't be used for the
2442 // actual autoimport later on). If this pass adds new undefined references,
2443 // we won't iterate further to resolve them.
2445 // If stdcall fixups only are needed for loading import entries from
2446 // a DLL without import library, this also just needs running once.
2447 // If it ends up pulling in more object files from static libraries,
2448 // (and maybe doing more stdcall fixups along the way), this would need
2449 // to loop these two calls.
2450 ctx
.symtab
.loadMinGWSymbols();
2454 // At this point, we should not have any symbols that cannot be resolved.
2455 // If we are going to do codegen for link-time optimization, check for
2456 // unresolvable symbols first, so we don't spend time generating code that
2457 // will fail to link anyway.
2458 if (!ctx
.bitcodeFileInstances
.empty() && !config
->forceUnresolved
)
2459 ctx
.symtab
.reportUnresolvable();
2463 config
->hadExplicitExports
= !config
->exports
.empty();
2464 if (config
->mingw
) {
2465 // In MinGW, all symbols are automatically exported if no symbols
2466 // are chosen to be exported.
2467 maybeExportMinGWSymbols(args
);
2470 // Do LTO by compiling bitcode input files to a set of native COFF files then
2471 // link those files (unless -thinlto-index-only was given, in which case we
2472 // resolve symbols and write indices, but don't generate native code or link).
2473 ctx
.symtab
.compileBitcodeFiles();
2475 // If -thinlto-index-only is given, we should create only "index
2476 // files" and not object files. Index file creation is already done
2477 // in addCombinedLTOObject, so we are done if that's the case.
2478 // Likewise, don't emit object files for other /lldemit options.
2479 if (config
->emit
!= EmitKind::Obj
|| config
->thinLTOIndexOnly
)
2482 // If we generated native object files from bitcode files, this resolves
2483 // references to the symbols we use from them.
2486 // Apply symbol renames for -wrap.
2487 if (!wrapped
.empty())
2488 wrapSymbols(ctx
, wrapped
);
2490 // Resolve remaining undefined symbols and warn about imported locals.
2491 ctx
.symtab
.resolveRemainingUndefines();
2495 if (config
->mingw
) {
2496 // Make sure the crtend.o object is the last object file. This object
2497 // file can contain terminating section chunks that need to be placed
2498 // last. GNU ld processes files and static libraries explicitly in the
2499 // order provided on the command line, while lld will pull in needed
2500 // files from static libraries only after the last object file on the
2502 for (auto i
= ctx
.objFileInstances
.begin(), e
= ctx
.objFileInstances
.end();
2505 if (isCrtend(file
->getName())) {
2506 ctx
.objFileInstances
.erase(i
);
2507 ctx
.objFileInstances
.push_back(file
);
2513 // Windows specific -- when we are creating a .dll file, we also
2514 // need to create a .lib file. In MinGW mode, we only do that when the
2515 // -implib option is given explicitly, for compatibility with GNU ld.
2516 if (!config
->exports
.empty() || config
->dll
) {
2517 llvm::TimeTraceScope
timeScope("Create .lib exports");
2519 if (!config
->noimplib
&& (!config
->mingw
|| !config
->implib
.empty()))
2520 createImportLibrary(/*asLib=*/false);
2521 assignExportOrdinals();
2524 // Handle /output-def (MinGW specific).
2525 if (auto *arg
= args
.getLastArg(OPT_output_def
))
2526 writeDefFile(arg
->getValue(), config
->exports
);
2528 // Set extra alignment for .comm symbols
2529 for (auto pair
: config
->alignComm
) {
2530 StringRef name
= pair
.first
;
2531 uint32_t alignment
= pair
.second
;
2533 Symbol
*sym
= ctx
.symtab
.find(name
);
2535 warn("/aligncomm symbol " + name
+ " not found");
2539 // If the symbol isn't common, it must have been replaced with a regular
2540 // symbol, which will carry its own alignment.
2541 auto *dc
= dyn_cast
<DefinedCommon
>(sym
);
2545 CommonChunk
*c
= dc
->getChunk();
2546 c
->setAlignment(std::max(c
->getAlignment(), alignment
));
2549 // Windows specific -- Create an embedded or side-by-side manifest.
2550 // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2552 if (config
->manifest
== Configuration::Embed
)
2553 addBuffer(createManifestRes(), false, false);
2554 else if (config
->manifest
== Configuration::SideBySide
||
2555 (config
->manifest
== Configuration::Default
&&
2556 !config
->manifestDependencies
.empty()))
2557 createSideBySideManifest();
2559 // Handle /order. We want to do this at this moment because we
2560 // need a complete list of comdat sections to warn on nonexistent
2562 if (auto *arg
= args
.getLastArg(OPT_order
)) {
2563 if (args
.hasArg(OPT_call_graph_ordering_file
))
2564 error("/order and /call-graph-order-file may not be used together");
2565 parseOrderFile(arg
->getValue());
2566 config
->callGraphProfileSort
= false;
2569 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2570 if (config
->callGraphProfileSort
) {
2571 llvm::TimeTraceScope
timeScope("Call graph");
2572 if (auto *arg
= args
.getLastArg(OPT_call_graph_ordering_file
)) {
2573 parseCallGraphFile(arg
->getValue());
2575 readCallGraphsFromObjectFiles(ctx
);
2578 // Handle /print-symbol-order.
2579 if (auto *arg
= args
.getLastArg(OPT_print_symbol_order
))
2580 config
->printSymbolOrder
= arg
->getValue();
2582 // Identify unreferenced COMDAT sections.
2584 if (config
->mingw
) {
2585 // markLive doesn't traverse .eh_frame, but the personality function is
2586 // only reached that way. The proper solution would be to parse and
2587 // traverse the .eh_frame section, like the ELF linker does.
2588 // For now, just manually try to retain the known possible personality
2589 // functions. This doesn't bring in more object files, but only marks
2590 // functions that already have been included to be retained.
2591 for (const char *n
: {"__gxx_personality_v0", "__gcc_personality_v0",
2592 "rust_eh_personality"}) {
2593 Defined
*d
= dyn_cast_or_null
<Defined
>(ctx
.symtab
.findUnderscore(n
));
2594 if (d
&& !d
->isGCRoot
) {
2596 config
->gcroot
.push_back(d
);
2604 // Needs to happen after the last call to addFile().
2607 // Identify identical COMDAT sections to merge them.
2608 if (config
->doICF
!= ICFLevel::None
) {
2609 findKeepUniqueSections(ctx
);
2613 // Write the result.
2616 // Stop early so we can print the results.
2618 if (config
->showTiming
)
2619 ctx
.rootTimer
.print();
2621 if (config
->timeTraceEnabled
) {
2622 // Manually stop the topmost "COFF link" scope, since we're shutting down.
2623 timeTraceProfilerEnd();
2625 checkError(timeTraceProfilerWrite(
2626 args
.getLastArgValue(OPT_time_trace_eq
).str(), config
->outputFile
));
2627 timeTraceProfilerCleanup();
2631 } // namespace lld::coff