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/LEB128.h"
41 #include "llvm/Support/MathExtras.h"
42 #include "llvm/Support/Parallel.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/Process.h"
45 #include "llvm/Support/TarWriter.h"
46 #include "llvm/Support/TargetSelect.h"
47 #include "llvm/Support/TimeProfiler.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 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()));
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
) {
700 Symbol
*b
= ctx
.symtab
.addUndefined(name
);
703 ctx
.config
.gcroot
.push_back(b
);
708 StringRef
LinkerDriver::mangleMaybe(Symbol
*s
) {
709 // If the plain symbol name has already been resolved, do nothing.
710 Undefined
*unmangled
= dyn_cast
<Undefined
>(s
);
714 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
715 Symbol
*mangled
= ctx
.symtab
.findMangle(unmangled
->getName());
719 // If we find a similar mangled symbol, make this an alias to it and return
721 log(unmangled
->getName() + " aliased to " + mangled
->getName());
722 unmangled
->weakAlias
= ctx
.symtab
.addUndefined(mangled
->getName());
723 return mangled
->getName();
726 // Windows specific -- find default entry point name.
728 // There are four different entry point functions for Windows executables,
729 // each of which corresponds to a user-defined "main" function. This function
730 // infers an entry point from a user-defined "main" function.
731 StringRef
LinkerDriver::findDefaultEntry() {
732 assert(ctx
.config
.subsystem
!= IMAGE_SUBSYSTEM_UNKNOWN
&&
733 "must handle /subsystem before calling this");
735 if (ctx
.config
.mingw
)
736 return mangle(ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
737 ? "WinMainCRTStartup"
740 if (ctx
.config
.subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
) {
741 if (findUnderscoreMangle("wWinMain")) {
742 if (!findUnderscoreMangle("WinMain"))
743 return mangle("wWinMainCRTStartup");
744 warn("found both wWinMain and WinMain; using latter");
746 return mangle("WinMainCRTStartup");
748 if (findUnderscoreMangle("wmain")) {
749 if (!findUnderscoreMangle("main"))
750 return mangle("wmainCRTStartup");
751 warn("found both wmain and main; using latter");
753 return mangle("mainCRTStartup");
756 WindowsSubsystem
LinkerDriver::inferSubsystem() {
758 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
759 if (ctx
.config
.mingw
)
760 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
761 // Note that link.exe infers the subsystem from the presence of these
762 // functions even if /entry: or /nodefaultlib are passed which causes them
764 bool haveMain
= findUnderscoreMangle("main");
765 bool haveWMain
= findUnderscoreMangle("wmain");
766 bool haveWinMain
= findUnderscoreMangle("WinMain");
767 bool haveWWinMain
= findUnderscoreMangle("wWinMain");
768 if (haveMain
|| haveWMain
) {
769 if (haveWinMain
|| haveWWinMain
) {
770 warn(std::string("found ") + (haveMain
? "main" : "wmain") + " and " +
771 (haveWinMain
? "WinMain" : "wWinMain") +
772 "; defaulting to /subsystem:console");
774 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
776 if (haveWinMain
|| haveWWinMain
)
777 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
778 return IMAGE_SUBSYSTEM_UNKNOWN
;
781 uint64_t LinkerDriver::getDefaultImageBase() {
782 if (ctx
.config
.is64())
783 return ctx
.config
.dll
? 0x180000000 : 0x140000000;
784 return ctx
.config
.dll
? 0x10000000 : 0x400000;
787 static std::string
rewritePath(StringRef s
) {
789 return relativeToRoot(s
);
790 return std::string(s
);
793 // Reconstructs command line arguments so that so that you can re-run
794 // the same command with the same inputs. This is for --reproduce.
795 static std::string
createResponseFile(const opt::InputArgList
&args
,
796 ArrayRef
<StringRef
> filePaths
,
797 ArrayRef
<StringRef
> searchPaths
) {
799 raw_svector_ostream
os(data
);
801 for (auto *arg
: args
) {
802 switch (arg
->getOption().getID()) {
810 case OPT_call_graph_ordering_file
:
812 case OPT_manifestinput
:
814 os
<< arg
->getSpelling() << quote(rewritePath(arg
->getValue())) << '\n';
817 StringRef orderFile
= arg
->getValue();
818 orderFile
.consume_front("@");
819 os
<< arg
->getSpelling() << '@' << quote(rewritePath(orderFile
)) << '\n';
822 case OPT_pdbstream
: {
823 const std::pair
<StringRef
, StringRef
> nameFile
=
824 StringRef(arg
->getValue()).split("=");
825 os
<< arg
->getSpelling() << nameFile
.first
<< '='
826 << quote(rewritePath(nameFile
.second
)) << '\n';
830 case OPT_manifestfile
:
832 case OPT_pdbstripped
:
834 os
<< arg
->getSpelling() << sys::path::filename(arg
->getValue()) << "\n";
837 os
<< toString(*arg
) << "\n";
841 for (StringRef path
: searchPaths
) {
842 std::string relPath
= relativeToRoot(path
);
843 os
<< "/libpath:" << quote(relPath
) << "\n";
846 for (StringRef path
: filePaths
)
847 os
<< quote(relativeToRoot(path
)) << "\n";
849 return std::string(data
);
852 static unsigned parseDebugTypes(const opt::InputArgList
&args
) {
853 unsigned debugTypes
= static_cast<unsigned>(DebugType::None
);
855 if (auto *a
= args
.getLastArg(OPT_debugtype
)) {
856 SmallVector
<StringRef
, 3> types
;
857 StringRef(a
->getValue())
858 .split(types
, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
860 for (StringRef type
: types
) {
861 unsigned v
= StringSwitch
<unsigned>(type
.lower())
862 .Case("cv", static_cast<unsigned>(DebugType::CV
))
863 .Case("pdata", static_cast<unsigned>(DebugType::PData
))
864 .Case("fixup", static_cast<unsigned>(DebugType::Fixup
))
867 warn("/debugtype: unknown option '" + type
+ "'");
875 // Default debug types
876 debugTypes
= static_cast<unsigned>(DebugType::CV
);
877 if (args
.hasArg(OPT_driver
))
878 debugTypes
|= static_cast<unsigned>(DebugType::PData
);
879 if (args
.hasArg(OPT_profile
))
880 debugTypes
|= static_cast<unsigned>(DebugType::Fixup
);
885 std::string
LinkerDriver::getMapFile(const opt::InputArgList
&args
,
886 opt::OptSpecifier os
,
887 opt::OptSpecifier osFile
) {
888 auto *arg
= args
.getLastArg(os
, osFile
);
891 if (arg
->getOption().getID() == osFile
.getID())
892 return arg
->getValue();
894 assert(arg
->getOption().getID() == os
.getID());
895 StringRef outFile
= ctx
.config
.outputFile
;
896 return (outFile
.substr(0, outFile
.rfind('.')) + ".map").str();
899 std::string
LinkerDriver::getImplibPath() {
900 if (!ctx
.config
.implib
.empty())
901 return std::string(ctx
.config
.implib
);
902 SmallString
<128> out
= StringRef(ctx
.config
.outputFile
);
903 sys::path::replace_extension(out
, ".lib");
904 return std::string(out
);
907 // The import name is calculated as follows:
909 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
910 // -----+----------------+---------------------+------------------
911 // LINK | {value} | {value}.{.dll/.exe} | {output name}
912 // LIB | {value} | {value}.dll | {output name}.dll
914 std::string
LinkerDriver::getImportName(bool asLib
) {
915 SmallString
<128> out
;
917 if (ctx
.config
.importName
.empty()) {
918 out
.assign(sys::path::filename(ctx
.config
.outputFile
));
920 sys::path::replace_extension(out
, ".dll");
922 out
.assign(ctx
.config
.importName
);
923 if (!sys::path::has_extension(out
))
924 sys::path::replace_extension(out
,
925 (ctx
.config
.dll
|| asLib
) ? ".dll" : ".exe");
928 return std::string(out
);
931 void LinkerDriver::createImportLibrary(bool asLib
) {
932 llvm::TimeTraceScope
timeScope("Create import library");
933 std::vector
<COFFShortExport
> exports
;
934 for (Export
&e1
: ctx
.config
.exports
) {
936 e2
.Name
= std::string(e1
.name
);
937 e2
.SymbolName
= std::string(e1
.symbolName
);
938 e2
.ExtName
= std::string(e1
.extName
);
939 e2
.ExportAs
= std::string(e1
.exportAs
);
940 e2
.ImportName
= std::string(e1
.importName
);
941 e2
.Ordinal
= e1
.ordinal
;
942 e2
.Noname
= e1
.noname
;
944 e2
.Private
= e1
.isPrivate
;
945 e2
.Constant
= e1
.constant
;
946 exports
.push_back(e2
);
949 std::string libName
= getImportName(asLib
);
950 std::string path
= getImplibPath();
952 if (!ctx
.config
.incremental
) {
953 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
958 // If the import library already exists, replace it only if the contents
960 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> oldBuf
= MemoryBuffer::getFile(
961 path
, /*IsText=*/false, /*RequiresNullTerminator=*/false);
963 checkError(writeImportLibrary(libName
, path
, exports
, ctx
.config
.machine
,
968 SmallString
<128> tmpName
;
969 if (std::error_code ec
=
970 sys::fs::createUniqueFile(path
+ ".tmp-%%%%%%%%.lib", tmpName
))
971 fatal("cannot create temporary file for import library " + path
+ ": " +
974 if (Error e
= writeImportLibrary(libName
, tmpName
, exports
,
975 ctx
.config
.machine
, ctx
.config
.mingw
)) {
976 checkError(std::move(e
));
980 std::unique_ptr
<MemoryBuffer
> newBuf
= check(MemoryBuffer::getFile(
981 tmpName
, /*IsText=*/false, /*RequiresNullTerminator=*/false));
982 if ((*oldBuf
)->getBuffer() != newBuf
->getBuffer()) {
984 checkError(errorCodeToError(sys::fs::rename(tmpName
, path
)));
986 sys::fs::remove(tmpName
);
990 void LinkerDriver::parseModuleDefs(StringRef path
) {
991 llvm::TimeTraceScope
timeScope("Parse def file");
992 std::unique_ptr
<MemoryBuffer
> mb
=
993 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
994 /*RequiresNullTerminator=*/false,
995 /*IsVolatile=*/true),
996 "could not open " + path
);
997 COFFModuleDefinition m
= check(parseCOFFModuleDefinition(
998 mb
->getMemBufferRef(), ctx
.config
.machine
, ctx
.config
.mingw
));
1000 // Include in /reproduce: output if applicable.
1001 ctx
.driver
.takeBuffer(std::move(mb
));
1003 if (ctx
.config
.outputFile
.empty())
1004 ctx
.config
.outputFile
= std::string(saver().save(m
.OutputFile
));
1005 ctx
.config
.importName
= std::string(saver().save(m
.ImportName
));
1007 ctx
.config
.imageBase
= m
.ImageBase
;
1009 ctx
.config
.stackReserve
= m
.StackReserve
;
1011 ctx
.config
.stackCommit
= m
.StackCommit
;
1013 ctx
.config
.heapReserve
= m
.HeapReserve
;
1015 ctx
.config
.heapCommit
= m
.HeapCommit
;
1016 if (m
.MajorImageVersion
)
1017 ctx
.config
.majorImageVersion
= m
.MajorImageVersion
;
1018 if (m
.MinorImageVersion
)
1019 ctx
.config
.minorImageVersion
= m
.MinorImageVersion
;
1020 if (m
.MajorOSVersion
)
1021 ctx
.config
.majorOSVersion
= m
.MajorOSVersion
;
1022 if (m
.MinorOSVersion
)
1023 ctx
.config
.minorOSVersion
= m
.MinorOSVersion
;
1025 for (COFFShortExport e1
: m
.Exports
) {
1027 // Renamed exports are parsed and set as "ExtName = Name". If Name has
1028 // the form "OtherDll.Func", it shouldn't be a normal exported
1029 // function but a forward to another DLL instead. This is supported
1030 // by both MS and GNU linkers.
1031 if (!e1
.ExtName
.empty() && e1
.ExtName
!= e1
.Name
&&
1032 StringRef(e1
.Name
).contains('.')) {
1033 e2
.name
= saver().save(e1
.ExtName
);
1034 e2
.forwardTo
= saver().save(e1
.Name
);
1036 e2
.name
= saver().save(e1
.Name
);
1037 e2
.extName
= saver().save(e1
.ExtName
);
1039 e2
.exportAs
= saver().save(e1
.ExportAs
);
1040 e2
.importName
= saver().save(e1
.ImportName
);
1041 e2
.ordinal
= e1
.Ordinal
;
1042 e2
.noname
= e1
.Noname
;
1044 e2
.isPrivate
= e1
.Private
;
1045 e2
.constant
= e1
.Constant
;
1046 e2
.source
= ExportSource::ModuleDefinition
;
1047 ctx
.config
.exports
.push_back(e2
);
1051 void LinkerDriver::enqueueTask(std::function
<void()> task
) {
1052 taskQueue
.push_back(std::move(task
));
1055 bool LinkerDriver::run() {
1056 llvm::TimeTraceScope
timeScope("Read input files");
1057 ScopedTimer
t(ctx
.inputFileTimer
);
1059 bool didWork
= !taskQueue
.empty();
1060 while (!taskQueue
.empty()) {
1061 taskQueue
.front()();
1062 taskQueue
.pop_front();
1067 // Parse an /order file. If an option is given, the linker places
1068 // COMDAT sections in the same order as their names appear in the
1070 void LinkerDriver::parseOrderFile(StringRef arg
) {
1071 // For some reason, the MSVC linker requires a filename to be
1073 if (!arg
.starts_with("@")) {
1074 error("malformed /order option: '@' missing");
1078 // Get a list of all comdat sections for error checking.
1079 DenseSet
<StringRef
> set
;
1080 for (Chunk
*c
: ctx
.symtab
.getChunks())
1081 if (auto *sec
= dyn_cast
<SectionChunk
>(c
))
1083 set
.insert(sec
->sym
->getName());
1086 StringRef path
= arg
.substr(1);
1087 std::unique_ptr
<MemoryBuffer
> mb
=
1088 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1089 /*RequiresNullTerminator=*/false,
1090 /*IsVolatile=*/true),
1091 "could not open " + path
);
1093 // Parse a file. An order file contains one symbol per line.
1094 // All symbols that were not present in a given order file are
1095 // considered to have the lowest priority 0 and are placed at
1096 // end of an output section.
1097 for (StringRef arg
: args::getLines(mb
->getMemBufferRef())) {
1099 if (ctx
.config
.machine
== I386
&& !isDecorated(s
))
1102 if (set
.count(s
) == 0) {
1103 if (ctx
.config
.warnMissingOrderSymbol
)
1104 warn("/order:" + arg
+ ": missing symbol: " + s
+ " [LNK4037]");
1106 ctx
.config
.order
[s
] = INT_MIN
+ ctx
.config
.order
.size();
1109 // Include in /reproduce: output if applicable.
1110 ctx
.driver
.takeBuffer(std::move(mb
));
1113 void LinkerDriver::parseCallGraphFile(StringRef path
) {
1114 std::unique_ptr
<MemoryBuffer
> mb
=
1115 CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
1116 /*RequiresNullTerminator=*/false,
1117 /*IsVolatile=*/true),
1118 "could not open " + path
);
1120 // Build a map from symbol name to section.
1121 DenseMap
<StringRef
, Symbol
*> map
;
1122 for (ObjFile
*file
: ctx
.objFileInstances
)
1123 for (Symbol
*sym
: file
->getSymbols())
1125 map
[sym
->getName()] = sym
;
1127 auto findSection
= [&](StringRef name
) -> SectionChunk
* {
1128 Symbol
*sym
= map
.lookup(name
);
1130 if (ctx
.config
.warnMissingOrderSymbol
)
1131 warn(path
+ ": no such symbol: " + name
);
1135 if (DefinedCOFF
*dr
= dyn_cast_or_null
<DefinedCOFF
>(sym
))
1136 return dyn_cast_or_null
<SectionChunk
>(dr
->getChunk());
1140 for (StringRef line
: args::getLines(*mb
)) {
1141 SmallVector
<StringRef
, 3> fields
;
1142 line
.split(fields
, ' ');
1145 if (fields
.size() != 3 || !to_integer(fields
[2], count
)) {
1146 error(path
+ ": parse error");
1150 if (SectionChunk
*from
= findSection(fields
[0]))
1151 if (SectionChunk
*to
= findSection(fields
[1]))
1152 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1155 // Include in /reproduce: output if applicable.
1156 ctx
.driver
.takeBuffer(std::move(mb
));
1159 static void readCallGraphsFromObjectFiles(COFFLinkerContext
&ctx
) {
1160 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1161 if (obj
->callgraphSec
) {
1162 ArrayRef
<uint8_t> contents
;
1164 obj
->getCOFFObj()->getSectionContents(obj
->callgraphSec
, contents
));
1165 BinaryStreamReader
reader(contents
, llvm::endianness::little
);
1166 while (!reader
.empty()) {
1167 uint32_t fromIndex
, toIndex
;
1169 if (Error err
= reader
.readInteger(fromIndex
))
1170 fatal(toString(obj
) + ": Expected 32-bit integer");
1171 if (Error err
= reader
.readInteger(toIndex
))
1172 fatal(toString(obj
) + ": Expected 32-bit integer");
1173 if (Error err
= reader
.readInteger(count
))
1174 fatal(toString(obj
) + ": Expected 64-bit integer");
1175 auto *fromSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(fromIndex
));
1176 auto *toSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(toIndex
));
1177 if (!fromSym
|| !toSym
)
1179 auto *from
= dyn_cast_or_null
<SectionChunk
>(fromSym
->getChunk());
1180 auto *to
= dyn_cast_or_null
<SectionChunk
>(toSym
->getChunk());
1182 ctx
.config
.callGraphProfile
[{from
, to
}] += count
;
1188 static void markAddrsig(Symbol
*s
) {
1189 if (auto *d
= dyn_cast_or_null
<Defined
>(s
))
1190 if (SectionChunk
*c
= dyn_cast_or_null
<SectionChunk
>(d
->getChunk()))
1191 c
->keepUnique
= true;
1194 static void findKeepUniqueSections(COFFLinkerContext
&ctx
) {
1195 llvm::TimeTraceScope
timeScope("Find keep unique sections");
1197 // Exported symbols could be address-significant in other executables or DSOs,
1198 // so we conservatively mark them as address-significant.
1199 for (Export
&r
: ctx
.config
.exports
)
1202 // Visit the address-significance table in each object file and mark each
1203 // referenced symbol as address-significant.
1204 for (ObjFile
*obj
: ctx
.objFileInstances
) {
1205 ArrayRef
<Symbol
*> syms
= obj
->getSymbols();
1206 if (obj
->addrsigSec
) {
1207 ArrayRef
<uint8_t> contents
;
1209 obj
->getCOFFObj()->getSectionContents(obj
->addrsigSec
, contents
));
1210 const uint8_t *cur
= contents
.begin();
1211 while (cur
!= contents
.end()) {
1213 const char *err
= nullptr;
1214 uint64_t symIndex
= decodeULEB128(cur
, &size
, contents
.end(), &err
);
1216 fatal(toString(obj
) + ": could not decode addrsig section: " + err
);
1217 if (symIndex
>= syms
.size())
1218 fatal(toString(obj
) + ": invalid symbol index in addrsig section");
1219 markAddrsig(syms
[symIndex
]);
1223 // If an object file does not have an address-significance table,
1224 // conservatively mark all of its symbols as address-significant.
1225 for (Symbol
*s
: syms
)
1231 // link.exe replaces each %foo% in altPath with the contents of environment
1232 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1233 // of pdb's output path) and _EXT (expands to the extension of the output
1235 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1237 void LinkerDriver::parsePDBAltPath() {
1238 SmallString
<128> buf
;
1239 StringRef pdbBasename
=
1240 sys::path::filename(ctx
.config
.pdbPath
, sys::path::Style::windows
);
1241 StringRef binaryExtension
=
1242 sys::path::extension(ctx
.config
.outputFile
, sys::path::Style::windows
);
1243 if (!binaryExtension
.empty())
1244 binaryExtension
= binaryExtension
.substr(1); // %_EXT% does not include '.'.
1247 // +--------- cursor ('a...' might be the empty string).
1248 // | +----- firstMark
1249 // | | +- secondMark
1253 while (cursor
< ctx
.config
.pdbAltPath
.size()) {
1254 size_t firstMark
, secondMark
;
1255 if ((firstMark
= ctx
.config
.pdbAltPath
.find('%', cursor
)) ==
1257 (secondMark
= ctx
.config
.pdbAltPath
.find('%', firstMark
+ 1)) ==
1259 // Didn't find another full fragment, treat rest of string as literal.
1260 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
));
1264 // Found a full fragment. Append text in front of first %, and interpret
1265 // text between first and second % as variable name.
1266 buf
.append(ctx
.config
.pdbAltPath
.substr(cursor
, firstMark
- cursor
));
1268 ctx
.config
.pdbAltPath
.substr(firstMark
, secondMark
- firstMark
+ 1);
1269 if (var
.equals_insensitive("%_pdb%"))
1270 buf
.append(pdbBasename
);
1271 else if (var
.equals_insensitive("%_ext%"))
1272 buf
.append(binaryExtension
);
1274 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + var
+
1279 cursor
= secondMark
+ 1;
1282 ctx
.config
.pdbAltPath
= buf
;
1285 /// Convert resource files and potentially merge input resource object
1286 /// trees into one resource tree.
1287 /// Call after ObjFile::Instances is complete.
1288 void LinkerDriver::convertResources() {
1289 llvm::TimeTraceScope
timeScope("Convert resources");
1290 std::vector
<ObjFile
*> resourceObjFiles
;
1292 for (ObjFile
*f
: ctx
.objFileInstances
) {
1293 if (f
->isResourceObjFile())
1294 resourceObjFiles
.push_back(f
);
1297 if (!ctx
.config
.mingw
&&
1298 (resourceObjFiles
.size() > 1 ||
1299 (resourceObjFiles
.size() == 1 && !resources
.empty()))) {
1300 error((!resources
.empty() ? "internal .obj file created from .res files"
1301 : toString(resourceObjFiles
[1])) +
1302 ": more than one resource obj file not allowed, already got " +
1303 toString(resourceObjFiles
.front()));
1307 if (resources
.empty() && resourceObjFiles
.size() <= 1) {
1308 // No resources to convert, and max one resource object file in
1309 // the input. Keep that preconverted resource section as is.
1310 for (ObjFile
*f
: resourceObjFiles
)
1311 f
->includeResourceChunks();
1315 make
<ObjFile
>(ctx
, convertResToCOFF(resources
, resourceObjFiles
));
1316 ctx
.symtab
.addFile(f
);
1317 f
->includeResourceChunks();
1320 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1321 // automatically exported by default. This behavior can be forced by the
1322 // -export-all-symbols option, so that it happens even when exports are
1323 // explicitly specified. The automatic behavior can be disabled using the
1324 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1325 // than MinGW in the case that nothing is explicitly exported.
1326 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList
&args
) {
1327 if (!args
.hasArg(OPT_export_all_symbols
)) {
1328 if (!ctx
.config
.dll
)
1331 if (!ctx
.config
.exports
.empty())
1333 if (args
.hasArg(OPT_exclude_all_symbols
))
1337 AutoExporter
exporter(ctx
, excludedSymbols
);
1339 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
1340 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
1341 exporter
.addWholeArchive(*path
);
1343 for (auto *arg
: args
.filtered(OPT_exclude_symbols
)) {
1344 SmallVector
<StringRef
, 2> vec
;
1345 StringRef(arg
->getValue()).split(vec
, ',');
1346 for (StringRef sym
: vec
)
1347 exporter
.addExcludedSymbol(mangle(sym
));
1350 ctx
.symtab
.forEachSymbol([&](Symbol
*s
) {
1351 auto *def
= dyn_cast
<Defined
>(s
);
1352 if (!exporter
.shouldExport(def
))
1355 if (!def
->isGCRoot
) {
1356 def
->isGCRoot
= true;
1357 ctx
.config
.gcroot
.push_back(def
);
1361 e
.name
= def
->getName();
1363 if (Chunk
*c
= def
->getChunk())
1364 if (!(c
->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE
))
1366 s
->isUsedInRegularObj
= true;
1367 ctx
.config
.exports
.push_back(e
);
1371 // lld has a feature to create a tar file containing all input files as well as
1372 // all command line options, so that other people can run lld again with exactly
1373 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1375 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1376 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1377 // with Microsoft link.exe.
1378 std::optional
<std::string
> getReproduceFile(const opt::InputArgList
&args
) {
1379 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
1380 return std::string(arg
->getValue());
1382 if (auto *arg
= args
.getLastArg(OPT_linkrepro
)) {
1383 SmallString
<64> path
= StringRef(arg
->getValue());
1384 sys::path::append(path
, "repro.tar");
1385 return std::string(path
);
1388 // This is intentionally not guarded by OPT_lldignoreenv since writing
1389 // a repro tar file doesn't affect the main output.
1390 if (auto *path
= getenv("LLD_REPRODUCE"))
1391 return std::string(path
);
1393 return std::nullopt
;
1396 static std::unique_ptr
<llvm::vfs::FileSystem
>
1397 getVFS(const opt::InputArgList
&args
) {
1398 using namespace llvm::vfs
;
1400 const opt::Arg
*arg
= args
.getLastArg(OPT_vfsoverlay
);
1404 auto bufOrErr
= llvm::MemoryBuffer::getFile(arg
->getValue());
1406 checkError(errorCodeToError(bufOrErr
.getError()));
1410 if (auto ret
= vfs::getVFSFromYAML(std::move(*bufOrErr
),
1411 /*DiagHandler*/ nullptr, arg
->getValue()))
1414 error("Invalid vfs overlay");
1418 void LinkerDriver::linkerMain(ArrayRef
<const char *> argsArr
) {
1419 ScopedTimer
rootTimer(ctx
.rootTimer
);
1420 Configuration
*config
= &ctx
.config
;
1423 InitializeAllTargetInfos();
1424 InitializeAllTargets();
1425 InitializeAllTargetMCs();
1426 InitializeAllAsmParsers();
1427 InitializeAllAsmPrinters();
1429 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1430 // We call our own implementation of lib.exe that understands bitcode files.
1431 if (argsArr
.size() > 1 &&
1432 (StringRef(argsArr
[1]).equals_insensitive("/lib") ||
1433 StringRef(argsArr
[1]).equals_insensitive("-lib"))) {
1434 if (llvm::libDriverMain(argsArr
.slice(1)) != 0)
1435 fatal("lib failed");
1439 // Parse command line options.
1440 ArgParser
parser(ctx
);
1441 opt::InputArgList args
= parser
.parse(argsArr
);
1443 // Initialize time trace profiler.
1444 config
->timeTraceEnabled
= args
.hasArg(OPT_time_trace_eq
);
1445 config
->timeTraceGranularity
=
1446 args::getInteger(args
, OPT_time_trace_granularity_eq
, 500);
1448 if (config
->timeTraceEnabled
)
1449 timeTraceProfilerInitialize(config
->timeTraceGranularity
, argsArr
[0]);
1451 llvm::TimeTraceScope
timeScope("COFF link");
1453 // Parse and evaluate -mllvm options.
1454 std::vector
<const char *> v
;
1455 v
.push_back("lld-link (LLVM option parsing)");
1456 for (const auto *arg
: args
.filtered(OPT_mllvm
)) {
1457 v
.push_back(arg
->getValue());
1458 config
->mllvmOpts
.emplace_back(arg
->getValue());
1461 llvm::TimeTraceScope
timeScope2("Parse cl::opt");
1462 cl::ResetAllOptionOccurrences();
1463 cl::ParseCommandLineOptions(v
.size(), v
.data());
1466 // Handle /errorlimit early, because error() depends on it.
1467 if (auto *arg
= args
.getLastArg(OPT_errorlimit
)) {
1469 StringRef s
= arg
->getValue();
1470 if (s
.getAsInteger(10, n
))
1471 error(arg
->getSpelling() + " number expected, but got " + s
);
1472 errorHandler().errorLimit
= n
;
1475 config
->vfs
= getVFS(args
);
1478 if (args
.hasArg(OPT_help
)) {
1479 printHelp(argsArr
[0]);
1483 // /threads: takes a positive integer and provides the default value for
1484 // /opt:lldltojobs=.
1485 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
1486 StringRef
v(arg
->getValue());
1487 unsigned threads
= 0;
1488 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
1489 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
1490 arg
->getValue() + "'");
1491 parallel::strategy
= hardware_concurrency(threads
);
1492 config
->thinLTOJobs
= v
.str();
1495 if (args
.hasArg(OPT_show_timing
))
1496 config
->showTiming
= true;
1498 config
->showSummary
= args
.hasArg(OPT_summary
);
1499 config
->printSearchPaths
= args
.hasArg(OPT_print_search_paths
);
1501 // Handle --version, which is an lld extension. This option is a bit odd
1502 // because it doesn't start with "/", but we deliberately chose "--" to
1503 // avoid conflict with /version and for compatibility with clang-cl.
1504 if (args
.hasArg(OPT_dash_dash_version
)) {
1505 message(getLLDVersion());
1509 // Handle /lldmingw early, since it can potentially affect how other
1510 // options are handled.
1511 config
->mingw
= args
.hasArg(OPT_lldmingw
);
1513 ctx
.e
.errorLimitExceededMsg
= "too many errors emitted, stopping now"
1514 " (use --error-limit=0 to see all errors)";
1516 // Handle /linkrepro and /reproduce.
1518 llvm::TimeTraceScope
timeScope2("Reproducer");
1519 if (std::optional
<std::string
> path
= getReproduceFile(args
)) {
1520 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
1521 TarWriter::create(*path
, sys::path::stem(*path
));
1524 tar
= std::move(*errOrWriter
);
1526 error("/linkrepro: failed to open " + *path
+ ": " +
1527 toString(errOrWriter
.takeError()));
1532 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
1533 if (args
.hasArg(OPT_deffile
))
1534 config
->noEntry
= true;
1536 fatal("no input files");
1539 // Construct search path list.
1541 llvm::TimeTraceScope
timeScope2("Search paths");
1542 searchPaths
.emplace_back("");
1543 for (auto *arg
: args
.filtered(OPT_libpath
))
1544 searchPaths
.push_back(arg
->getValue());
1545 if (!config
->mingw
) {
1546 // Prefer the Clang provided builtins over the ones bundled with MSVC.
1547 // In MinGW mode, the compiler driver passes the necessary libpath
1548 // options explicitly.
1549 addClangLibSearchPaths(argsArr
[0]);
1550 // Don't automatically deduce the lib path from the environment or MSVC
1551 // installations when operating in mingw mode. (This also makes LLD ignore
1552 // winsysroot and vctoolsdir arguments.)
1553 detectWinSysRoot(args
);
1554 if (!args
.hasArg(OPT_lldignoreenv
) && !args
.hasArg(OPT_winsysroot
))
1555 addLibSearchPaths();
1557 if (args
.hasArg(OPT_vctoolsdir
, OPT_winsysroot
))
1558 warn("ignoring /vctoolsdir or /winsysroot flags in MinGW mode");
1563 for (auto *arg
: args
.filtered(OPT_ignore
)) {
1564 SmallVector
<StringRef
, 8> vec
;
1565 StringRef(arg
->getValue()).split(vec
, ',');
1566 for (StringRef s
: vec
) {
1568 config
->warnMissingOrderSymbol
= false;
1569 else if (s
== "4099")
1570 config
->warnDebugInfoUnusable
= false;
1571 else if (s
== "4217")
1572 config
->warnLocallyDefinedImported
= false;
1573 else if (s
== "longsections")
1574 config
->warnLongSectionNames
= false;
1575 // Other warning numbers are ignored.
1580 if (auto *arg
= args
.getLastArg(OPT_out
))
1581 config
->outputFile
= arg
->getValue();
1584 if (args
.hasArg(OPT_verbose
))
1585 config
->verbose
= true;
1586 errorHandler().verbose
= config
->verbose
;
1588 // Handle /force or /force:unresolved
1589 if (args
.hasArg(OPT_force
, OPT_force_unresolved
))
1590 config
->forceUnresolved
= true;
1592 // Handle /force or /force:multiple
1593 if (args
.hasArg(OPT_force
, OPT_force_multiple
))
1594 config
->forceMultiple
= true;
1596 // Handle /force or /force:multipleres
1597 if (args
.hasArg(OPT_force
, OPT_force_multipleres
))
1598 config
->forceMultipleRes
= true;
1600 // Don't warn about long section names, such as .debug_info, for mingw (or
1601 // when -debug:dwarf is requested, handled below).
1603 config
->warnLongSectionNames
= false;
1608 bool shouldCreatePDB
= false;
1609 for (auto *arg
: args
.filtered(OPT_debug
, OPT_debug_opt
)) {
1611 if (arg
->getOption().getID() == OPT_debug
)
1614 str
= StringRef(arg
->getValue()).lower();
1615 SmallVector
<StringRef
, 1> vec
;
1616 StringRef(str
).split(vec
, ',');
1617 for (StringRef s
: vec
) {
1618 if (s
== "fastlink") {
1619 warn("/debug:fastlink unsupported; using /debug:full");
1623 config
->debug
= false;
1624 config
->incremental
= false;
1625 config
->includeDwarfChunks
= false;
1626 config
->debugGHashes
= false;
1627 config
->writeSymtab
= false;
1628 shouldCreatePDB
= false;
1630 } else if (s
== "full" || s
== "ghash" || s
== "noghash") {
1631 config
->debug
= true;
1632 config
->incremental
= true;
1633 config
->includeDwarfChunks
= true;
1634 if (s
== "full" || s
== "ghash")
1635 config
->debugGHashes
= true;
1636 shouldCreatePDB
= true;
1638 } else if (s
== "dwarf") {
1639 config
->debug
= true;
1640 config
->incremental
= true;
1641 config
->includeDwarfChunks
= true;
1642 config
->writeSymtab
= true;
1643 config
->warnLongSectionNames
= false;
1645 } else if (s
== "nodwarf") {
1646 config
->includeDwarfChunks
= false;
1647 } else if (s
== "symtab") {
1648 config
->writeSymtab
= true;
1650 } else if (s
== "nosymtab") {
1651 config
->writeSymtab
= false;
1653 error("/debug: unknown option: " + s
);
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 if (shouldCreatePDB
) {
1676 if (auto *arg
= args
.getLastArg(OPT_pdb
))
1677 config
->pdbPath
= arg
->getValue();
1678 if (auto *arg
= args
.getLastArg(OPT_pdbaltpath
))
1679 config
->pdbAltPath
= arg
->getValue();
1680 if (auto *arg
= args
.getLastArg(OPT_pdbpagesize
))
1681 parsePDBPageSize(arg
->getValue());
1682 if (args
.hasArg(OPT_natvis
))
1683 config
->natvisFiles
= args
.getAllArgValues(OPT_natvis
);
1684 if (args
.hasArg(OPT_pdbstream
)) {
1685 for (const StringRef value
: args
.getAllArgValues(OPT_pdbstream
)) {
1686 const std::pair
<StringRef
, StringRef
> nameFile
= value
.split("=");
1687 const StringRef name
= nameFile
.first
;
1688 const std::string file
= nameFile
.second
.str();
1689 config
->namedStreams
[name
] = file
;
1693 if (auto *arg
= args
.getLastArg(OPT_pdb_source_path
))
1694 config
->pdbSourcePath
= arg
->getValue();
1697 // Handle /pdbstripped
1698 if (args
.hasArg(OPT_pdbstripped
))
1699 warn("ignoring /pdbstripped flag, it is not yet supported");
1702 if (args
.hasArg(OPT_noentry
)) {
1703 if (args
.hasArg(OPT_dll
))
1704 config
->noEntry
= true;
1706 error("/noentry must be specified with /dll");
1710 if (args
.hasArg(OPT_dll
)) {
1712 config
->manifestID
= 2;
1715 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1716 // because we need to explicitly check whether that option or its inverse was
1717 // present in the argument list in order to handle /fixed.
1718 auto *dynamicBaseArg
= args
.getLastArg(OPT_dynamicbase
, OPT_dynamicbase_no
);
1719 if (dynamicBaseArg
&&
1720 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase_no
)
1721 config
->dynamicBase
= false;
1723 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1724 // default setting for any other project type.", but link.exe defaults to
1725 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1726 bool fixed
= args
.hasFlag(OPT_fixed
, OPT_fixed_no
, false);
1728 if (dynamicBaseArg
&&
1729 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase
) {
1730 error("/fixed must not be specified with /dynamicbase");
1732 config
->relocatable
= false;
1733 config
->dynamicBase
= false;
1737 // Handle /appcontainer
1738 config
->appContainer
=
1739 args
.hasFlag(OPT_appcontainer
, OPT_appcontainer_no
, false);
1743 llvm::TimeTraceScope
timeScope2("Machine arg");
1744 if (auto *arg
= args
.getLastArg(OPT_machine
)) {
1745 config
->machine
= getMachineType(arg
->getValue());
1746 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
)
1747 fatal(Twine("unknown /machine argument: ") + arg
->getValue());
1748 addWinSysRootLibSearchPaths();
1752 // Handle /nodefaultlib:<filename>
1754 llvm::TimeTraceScope
timeScope2("Nodefaultlib");
1755 for (auto *arg
: args
.filtered(OPT_nodefaultlib
))
1756 config
->noDefaultLibs
.insert(findLib(arg
->getValue()).lower());
1759 // Handle /nodefaultlib
1760 if (args
.hasArg(OPT_nodefaultlib_all
))
1761 config
->noDefaultLibAll
= true;
1764 if (auto *arg
= args
.getLastArg(OPT_base
))
1765 parseNumbers(arg
->getValue(), &config
->imageBase
);
1767 // Handle /filealign
1768 if (auto *arg
= args
.getLastArg(OPT_filealign
)) {
1769 parseNumbers(arg
->getValue(), &config
->fileAlign
);
1770 if (!isPowerOf2_64(config
->fileAlign
))
1771 error("/filealign: not a power of two: " + Twine(config
->fileAlign
));
1775 if (auto *arg
= args
.getLastArg(OPT_stack
))
1776 parseNumbers(arg
->getValue(), &config
->stackReserve
, &config
->stackCommit
);
1779 if (auto *arg
= args
.getLastArg(OPT_guard
))
1780 parseGuard(arg
->getValue());
1783 if (auto *arg
= args
.getLastArg(OPT_heap
))
1784 parseNumbers(arg
->getValue(), &config
->heapReserve
, &config
->heapCommit
);
1787 if (auto *arg
= args
.getLastArg(OPT_version
))
1788 parseVersion(arg
->getValue(), &config
->majorImageVersion
,
1789 &config
->minorImageVersion
);
1791 // Handle /subsystem
1792 if (auto *arg
= args
.getLastArg(OPT_subsystem
))
1793 parseSubsystem(arg
->getValue(), &config
->subsystem
,
1794 &config
->majorSubsystemVersion
,
1795 &config
->minorSubsystemVersion
);
1797 // Handle /osversion
1798 if (auto *arg
= args
.getLastArg(OPT_osversion
)) {
1799 parseVersion(arg
->getValue(), &config
->majorOSVersion
,
1800 &config
->minorOSVersion
);
1802 config
->majorOSVersion
= config
->majorSubsystemVersion
;
1803 config
->minorOSVersion
= config
->minorSubsystemVersion
;
1806 // Handle /timestamp
1807 if (llvm::opt::Arg
*arg
= args
.getLastArg(OPT_timestamp
, OPT_repro
)) {
1808 if (arg
->getOption().getID() == OPT_repro
) {
1809 config
->timestamp
= 0;
1810 config
->repro
= true;
1812 config
->repro
= false;
1813 StringRef
value(arg
->getValue());
1814 if (value
.getAsInteger(0, config
->timestamp
))
1815 fatal(Twine("invalid timestamp: ") + value
+
1816 ". Expected 32-bit integer");
1819 config
->repro
= false;
1820 if (std::optional
<std::string
> epoch
=
1821 Process::GetEnv("SOURCE_DATE_EPOCH")) {
1822 StringRef
value(*epoch
);
1823 if (value
.getAsInteger(0, config
->timestamp
))
1824 fatal(Twine("invalid SOURCE_DATE_EPOCH timestamp: ") + value
+
1825 ". Expected 32-bit integer");
1827 config
->timestamp
= time(nullptr);
1831 // Handle /alternatename
1832 for (auto *arg
: args
.filtered(OPT_alternatename
))
1833 parseAlternateName(arg
->getValue());
1836 for (auto *arg
: args
.filtered(OPT_incl
))
1837 addUndefined(arg
->getValue());
1840 if (auto *arg
= args
.getLastArg(OPT_implib
))
1841 config
->implib
= arg
->getValue();
1843 config
->noimplib
= args
.hasArg(OPT_noimplib
);
1845 if (args
.hasArg(OPT_profile
))
1848 std::optional
<ICFLevel
> icfLevel
;
1849 if (args
.hasArg(OPT_profile
))
1850 icfLevel
= ICFLevel::None
;
1851 unsigned tailMerge
= 1;
1852 bool ltoDebugPM
= false;
1853 for (auto *arg
: args
.filtered(OPT_opt
)) {
1854 std::string str
= StringRef(arg
->getValue()).lower();
1855 SmallVector
<StringRef
, 1> vec
;
1856 StringRef(str
).split(vec
, ',');
1857 for (StringRef s
: vec
) {
1860 } else if (s
== "noref") {
1862 } else if (s
== "icf" || s
.starts_with("icf=")) {
1863 icfLevel
= ICFLevel::All
;
1864 } else if (s
== "safeicf") {
1865 icfLevel
= ICFLevel::Safe
;
1866 } else if (s
== "noicf") {
1867 icfLevel
= ICFLevel::None
;
1868 } else if (s
== "lldtailmerge") {
1870 } else if (s
== "nolldtailmerge") {
1872 } else if (s
== "ltodebugpassmanager") {
1874 } else if (s
== "noltodebugpassmanager") {
1876 } else if (s
.consume_front("lldlto=")) {
1877 if (s
.getAsInteger(10, config
->ltoo
) || config
->ltoo
> 3)
1878 error("/opt:lldlto: invalid optimization level: " + s
);
1879 } else if (s
.consume_front("lldltocgo=")) {
1880 config
->ltoCgo
.emplace();
1881 if (s
.getAsInteger(10, *config
->ltoCgo
) || *config
->ltoCgo
> 3)
1882 error("/opt:lldltocgo: invalid codegen optimization level: " + s
);
1883 } else if (s
.consume_front("lldltojobs=")) {
1884 if (!get_threadpool_strategy(s
))
1885 error("/opt:lldltojobs: invalid job count: " + s
);
1886 config
->thinLTOJobs
= s
.str();
1887 } else if (s
.consume_front("lldltopartitions=")) {
1888 if (s
.getAsInteger(10, config
->ltoPartitions
) ||
1889 config
->ltoPartitions
== 0)
1890 error("/opt:lldltopartitions: invalid partition count: " + s
);
1891 } else if (s
!= "lbr" && s
!= "nolbr")
1892 error("/opt: unknown option: " + s
);
1897 icfLevel
= doGC
? ICFLevel::All
: ICFLevel::None
;
1898 config
->doGC
= doGC
;
1899 config
->doICF
= *icfLevel
;
1901 (tailMerge
== 1 && config
->doICF
!= ICFLevel::None
) || tailMerge
== 2;
1902 config
->ltoDebugPassManager
= ltoDebugPM
;
1904 // Handle /lldsavetemps
1905 if (args
.hasArg(OPT_lldsavetemps
))
1906 config
->saveTemps
= true;
1909 if (auto *arg
= args
.getLastArg(OPT_lldemit
)) {
1910 StringRef s
= arg
->getValue();
1912 config
->emit
= EmitKind::Obj
;
1913 else if (s
== "llvm")
1914 config
->emit
= EmitKind::LLVM
;
1915 else if (s
== "asm")
1916 config
->emit
= EmitKind::ASM
;
1918 error("/lldemit: unknown option: " + s
);
1922 if (args
.hasArg(OPT_kill_at
))
1923 config
->killAt
= true;
1925 // Handle /lldltocache
1926 if (auto *arg
= args
.getLastArg(OPT_lldltocache
))
1927 config
->ltoCache
= arg
->getValue();
1929 // Handle /lldsavecachepolicy
1930 if (auto *arg
= args
.getLastArg(OPT_lldltocachepolicy
))
1931 config
->ltoCachePolicy
= CHECK(
1932 parseCachePruningPolicy(arg
->getValue()),
1933 Twine("/lldltocachepolicy: invalid cache policy: ") + arg
->getValue());
1935 // Handle /failifmismatch
1936 for (auto *arg
: args
.filtered(OPT_failifmismatch
))
1937 checkFailIfMismatch(arg
->getValue(), nullptr);
1940 for (auto *arg
: args
.filtered(OPT_merge
))
1941 parseMerge(arg
->getValue());
1943 // Add default section merging rules after user rules. User rules take
1944 // precedence, but we will emit a warning if there is a conflict.
1945 parseMerge(".idata=.rdata");
1946 parseMerge(".didat=.rdata");
1947 parseMerge(".edata=.rdata");
1948 parseMerge(".xdata=.rdata");
1949 parseMerge(".00cfg=.rdata");
1950 parseMerge(".bss=.data");
1952 if (isArm64EC(config
->machine
))
1953 parseMerge(".wowthk=.text");
1955 if (config
->mingw
) {
1956 parseMerge(".ctors=.rdata");
1957 parseMerge(".dtors=.rdata");
1958 parseMerge(".CRT=.rdata");
1962 for (auto *arg
: args
.filtered(OPT_section
))
1963 parseSection(arg
->getValue());
1966 if (auto *arg
= args
.getLastArg(OPT_align
)) {
1967 parseNumbers(arg
->getValue(), &config
->align
);
1968 if (!isPowerOf2_64(config
->align
))
1969 error("/align: not a power of two: " + StringRef(arg
->getValue()));
1970 if (!args
.hasArg(OPT_driver
))
1971 warn("/align specified without /driver; image may not run");
1974 // Handle /aligncomm
1975 for (auto *arg
: args
.filtered(OPT_aligncomm
))
1976 parseAligncomm(arg
->getValue());
1978 // Handle /manifestdependency.
1979 for (auto *arg
: args
.filtered(OPT_manifestdependency
))
1980 config
->manifestDependencies
.insert(arg
->getValue());
1982 // Handle /manifest and /manifest:
1983 if (auto *arg
= args
.getLastArg(OPT_manifest
, OPT_manifest_colon
)) {
1984 if (arg
->getOption().getID() == OPT_manifest
)
1985 config
->manifest
= Configuration::SideBySide
;
1987 parseManifest(arg
->getValue());
1990 // Handle /manifestuac
1991 if (auto *arg
= args
.getLastArg(OPT_manifestuac
))
1992 parseManifestUAC(arg
->getValue());
1994 // Handle /manifestfile
1995 if (auto *arg
= args
.getLastArg(OPT_manifestfile
))
1996 config
->manifestFile
= arg
->getValue();
1998 // Handle /manifestinput
1999 for (auto *arg
: args
.filtered(OPT_manifestinput
))
2000 config
->manifestInput
.push_back(arg
->getValue());
2002 if (!config
->manifestInput
.empty() &&
2003 config
->manifest
!= Configuration::Embed
) {
2004 fatal("/manifestinput: requires /manifest:embed");
2008 config
->dwoDir
= args
.getLastArgValue(OPT_dwodir
);
2010 config
->thinLTOEmitImportsFiles
= args
.hasArg(OPT_thinlto_emit_imports_files
);
2011 config
->thinLTOIndexOnly
= args
.hasArg(OPT_thinlto_index_only
) ||
2012 args
.hasArg(OPT_thinlto_index_only_arg
);
2013 config
->thinLTOIndexOnlyArg
=
2014 args
.getLastArgValue(OPT_thinlto_index_only_arg
);
2015 std::tie(config
->thinLTOPrefixReplaceOld
, config
->thinLTOPrefixReplaceNew
,
2016 config
->thinLTOPrefixReplaceNativeObject
) =
2017 getOldNewOptionsExtra(args
, OPT_thinlto_prefix_replace
);
2018 config
->thinLTOObjectSuffixReplace
=
2019 getOldNewOptions(args
, OPT_thinlto_object_suffix_replace
);
2020 config
->ltoObjPath
= args
.getLastArgValue(OPT_lto_obj_path
);
2021 config
->ltoCSProfileGenerate
= args
.hasArg(OPT_lto_cs_profile_generate
);
2022 config
->ltoCSProfileFile
= args
.getLastArgValue(OPT_lto_cs_profile_file
);
2023 config
->ltoSampleProfileName
= args
.getLastArgValue(OPT_lto_sample_profile
);
2024 // Handle miscellaneous boolean flags.
2025 config
->ltoPGOWarnMismatch
= args
.hasFlag(OPT_lto_pgo_warn_mismatch
,
2026 OPT_lto_pgo_warn_mismatch_no
, true);
2027 config
->allowBind
= args
.hasFlag(OPT_allowbind
, OPT_allowbind_no
, true);
2028 config
->allowIsolation
=
2029 args
.hasFlag(OPT_allowisolation
, OPT_allowisolation_no
, true);
2030 config
->incremental
=
2031 args
.hasFlag(OPT_incremental
, OPT_incremental_no
,
2032 !config
->doGC
&& config
->doICF
== ICFLevel::None
&&
2033 !args
.hasArg(OPT_order
) && !args
.hasArg(OPT_profile
));
2034 config
->integrityCheck
=
2035 args
.hasFlag(OPT_integritycheck
, OPT_integritycheck_no
, false);
2036 config
->cetCompat
= args
.hasFlag(OPT_cetcompat
, OPT_cetcompat_no
, false);
2037 config
->nxCompat
= args
.hasFlag(OPT_nxcompat
, OPT_nxcompat_no
, true);
2038 for (auto *arg
: args
.filtered(OPT_swaprun
))
2039 parseSwaprun(arg
->getValue());
2040 config
->terminalServerAware
=
2041 !config
->dll
&& args
.hasFlag(OPT_tsaware
, OPT_tsaware_no
, true);
2042 config
->autoImport
=
2043 args
.hasFlag(OPT_auto_import
, OPT_auto_import_no
, config
->mingw
);
2044 config
->pseudoRelocs
= args
.hasFlag(
2045 OPT_runtime_pseudo_reloc
, OPT_runtime_pseudo_reloc_no
, config
->mingw
);
2046 config
->callGraphProfileSort
= args
.hasFlag(
2047 OPT_call_graph_profile_sort
, OPT_call_graph_profile_sort_no
, true);
2048 config
->stdcallFixup
=
2049 args
.hasFlag(OPT_stdcall_fixup
, OPT_stdcall_fixup_no
, config
->mingw
);
2050 config
->warnStdcallFixup
= !args
.hasArg(OPT_stdcall_fixup
);
2051 config
->allowDuplicateWeak
=
2052 args
.hasFlag(OPT_lld_allow_duplicate_weak
,
2053 OPT_lld_allow_duplicate_weak_no
, config
->mingw
);
2055 if (args
.hasFlag(OPT_inferasanlibs
, OPT_inferasanlibs_no
, false))
2056 warn("ignoring '/inferasanlibs', this flag is not supported");
2058 if (config
->incremental
&& args
.hasArg(OPT_profile
)) {
2059 warn("ignoring '/incremental' due to '/profile' specification");
2060 config
->incremental
= false;
2063 if (config
->incremental
&& args
.hasArg(OPT_order
)) {
2064 warn("ignoring '/incremental' due to '/order' specification");
2065 config
->incremental
= false;
2068 if (config
->incremental
&& config
->doGC
) {
2069 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
2071 config
->incremental
= false;
2074 if (config
->incremental
&& config
->doICF
!= ICFLevel::None
) {
2075 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
2077 config
->incremental
= false;
2083 std::set
<sys::fs::UniqueID
> wholeArchives
;
2084 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
2085 if (std::optional
<StringRef
> path
= findFile(arg
->getValue()))
2086 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(*path
))
2087 wholeArchives
.insert(*id
);
2089 // A predicate returning true if a given path is an argument for
2090 // /wholearchive:, or /wholearchive is enabled globally.
2091 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
2092 // needs to be handled as "/wholearchive:foo.obj foo.obj".
2093 auto isWholeArchive
= [&](StringRef path
) -> bool {
2094 if (args
.hasArg(OPT_wholearchive_flag
))
2096 if (std::optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
2097 return wholeArchives
.count(*id
);
2101 // Create a list of input files. These can be given as OPT_INPUT options
2102 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
2105 llvm::TimeTraceScope
timeScope2("Parse & queue inputs");
2107 for (auto *arg
: args
) {
2108 switch (arg
->getOption().getID()) {
2111 error("stray " + arg
->getSpelling());
2116 error("nested " + arg
->getSpelling());
2119 case OPT_wholearchive_file
:
2120 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2121 enqueuePath(*path
, true, inLib
);
2124 if (std::optional
<StringRef
> path
= findFileIfNew(arg
->getValue()))
2125 enqueuePath(*path
, isWholeArchive(*path
), inLib
);
2128 // Ignore other options.
2134 // Read all input files given via the command line.
2139 // We should have inferred a machine type by now from the input files, but if
2140 // not we assume x64.
2141 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
) {
2142 warn("/machine is not specified. x64 is assumed");
2143 config
->machine
= AMD64
;
2144 addWinSysRootLibSearchPaths();
2146 config
->wordsize
= config
->is64() ? 8 : 4;
2148 if (config
->printSearchPaths
) {
2149 SmallString
<256> buffer
;
2150 raw_svector_ostream
stream(buffer
);
2151 stream
<< "Library search paths:\n";
2153 for (StringRef path
: searchPaths
) {
2156 stream
<< " " << path
<< "\n";
2162 // Process files specified as /defaultlib. These must be processed after
2163 // addWinSysRootLibSearchPaths(), which is why they are in a separate loop.
2164 for (auto *arg
: args
.filtered(OPT_defaultlib
))
2165 if (std::optional
<StringRef
> path
= findLibIfNew(arg
->getValue()))
2166 enqueuePath(*path
, false, false);
2172 if (args
.hasArg(OPT_release
))
2173 config
->writeCheckSum
= true;
2175 // Handle /safeseh, x86 only, on by default, except for mingw.
2176 if (config
->machine
== I386
) {
2177 config
->safeSEH
= args
.hasFlag(OPT_safeseh
, OPT_safeseh_no
, !config
->mingw
);
2178 config
->noSEH
= args
.hasArg(OPT_noseh
);
2181 // Handle /functionpadmin
2182 for (auto *arg
: args
.filtered(OPT_functionpadmin
, OPT_functionpadmin_opt
))
2183 parseFunctionPadMin(arg
);
2185 // Handle /dependentloadflag
2187 args
.filtered(OPT_dependentloadflag
, OPT_dependentloadflag_opt
))
2188 parseDependentLoadFlags(arg
);
2191 llvm::TimeTraceScope
timeScope("Reproducer: response file");
2192 tar
->append("response.txt",
2193 createResponseFile(args
, filePaths
,
2194 ArrayRef
<StringRef
>(searchPaths
).slice(1)));
2197 // Handle /largeaddressaware
2198 config
->largeAddressAware
= args
.hasFlag(
2199 OPT_largeaddressaware
, OPT_largeaddressaware_no
, config
->is64());
2201 // Handle /highentropyva
2202 config
->highEntropyVA
=
2204 args
.hasFlag(OPT_highentropyva
, OPT_highentropyva_no
, true);
2206 if (!config
->dynamicBase
&&
2207 (config
->machine
== ARMNT
|| isAnyArm64(config
->machine
)))
2208 error("/dynamicbase:no is not compatible with " +
2209 machineToStr(config
->machine
));
2213 llvm::TimeTraceScope
timeScope("Parse /export");
2214 for (auto *arg
: args
.filtered(OPT_export
)) {
2215 Export e
= parseExport(arg
->getValue());
2216 if (config
->machine
== I386
) {
2217 if (!isDecorated(e
.name
))
2218 e
.name
= saver().save("_" + e
.name
);
2219 if (!e
.extName
.empty() && !isDecorated(e
.extName
))
2220 e
.extName
= saver().save("_" + e
.extName
);
2222 config
->exports
.push_back(e
);
2227 if (auto *arg
= args
.getLastArg(OPT_deffile
)) {
2228 // parseModuleDefs mutates Config object.
2229 parseModuleDefs(arg
->getValue());
2232 // Handle generation of import library from a def file.
2233 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
2235 if (!config
->noimplib
)
2236 createImportLibrary(/*asLib=*/true);
2240 // Windows specific -- if no /subsystem is given, we need to infer
2241 // that from entry point name. Must happen before /entry handling,
2242 // and after the early return when just writing an import library.
2243 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
) {
2244 llvm::TimeTraceScope
timeScope("Infer subsystem");
2245 config
->subsystem
= inferSubsystem();
2246 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
)
2247 fatal("subsystem must be defined");
2250 // Handle /entry and /dll
2252 llvm::TimeTraceScope
timeScope("Entry point");
2253 if (auto *arg
= args
.getLastArg(OPT_entry
)) {
2254 if (!arg
->getValue()[0])
2255 fatal("missing entry point symbol name");
2256 config
->entry
= addUndefined(mangle(arg
->getValue()));
2257 } else if (!config
->entry
&& !config
->noEntry
) {
2258 if (args
.hasArg(OPT_dll
)) {
2259 StringRef s
= (config
->machine
== I386
) ? "__DllMainCRTStartup@12"
2260 : "_DllMainCRTStartup";
2261 config
->entry
= addUndefined(s
);
2262 } else if (config
->driverWdm
) {
2263 // /driver:wdm implies /entry:_NtProcessStartup
2264 config
->entry
= addUndefined(mangle("_NtProcessStartup"));
2266 // Windows specific -- If entry point name is not given, we need to
2267 // infer that from user-defined entry name.
2268 StringRef s
= findDefaultEntry();
2270 fatal("entry point must be defined");
2271 config
->entry
= addUndefined(s
);
2272 log("Entry name inferred: " + s
);
2277 // Handle /delayload
2279 llvm::TimeTraceScope
timeScope("Delay load");
2280 for (auto *arg
: args
.filtered(OPT_delayload
)) {
2281 config
->delayLoads
.insert(StringRef(arg
->getValue()).lower());
2282 if (config
->machine
== I386
) {
2283 config
->delayLoadHelper
= addUndefined("___delayLoadHelper2@8");
2285 config
->delayLoadHelper
= addUndefined("__delayLoadHelper2");
2290 // Set default image name if neither /out or /def set it.
2291 if (config
->outputFile
.empty()) {
2292 config
->outputFile
= getOutputPath(
2293 (*args
.filtered(OPT_INPUT
, OPT_wholearchive_file
).begin())->getValue(),
2294 config
->dll
, config
->driver
);
2297 // Fail early if an output file is not writable.
2298 if (auto e
= tryCreateFile(config
->outputFile
)) {
2299 error("cannot open output file " + config
->outputFile
+ ": " + e
.message());
2303 config
->lldmapFile
= getMapFile(args
, OPT_lldmap
, OPT_lldmap_file
);
2304 config
->mapFile
= getMapFile(args
, OPT_map
, OPT_map_file
);
2306 if (config
->mapFile
!= "" && args
.hasArg(OPT_map_info
)) {
2307 for (auto *arg
: args
.filtered(OPT_map_info
)) {
2308 std::string s
= StringRef(arg
->getValue()).lower();
2310 config
->mapInfo
= true;
2312 error("unknown option: /mapinfo:" + s
);
2316 if (config
->lldmapFile
!= "" && config
->lldmapFile
== config
->mapFile
) {
2317 warn("/lldmap and /map have the same output file '" + config
->mapFile
+
2318 "'.\n>>> ignoring /lldmap");
2319 config
->lldmapFile
.clear();
2322 // If should create PDB, use the hash of PDB content for build id. Otherwise,
2323 // generate using the hash of executable content.
2324 if (args
.hasFlag(OPT_build_id
, OPT_build_id_no
, false))
2325 config
->buildIDHash
= BuildIDHash::Binary
;
2327 if (shouldCreatePDB
) {
2328 // Put the PDB next to the image if no /pdb flag was passed.
2329 if (config
->pdbPath
.empty()) {
2330 config
->pdbPath
= config
->outputFile
;
2331 sys::path::replace_extension(config
->pdbPath
, ".pdb");
2334 // The embedded PDB path should be the absolute path to the PDB if no
2335 // /pdbaltpath flag was passed.
2336 if (config
->pdbAltPath
.empty()) {
2337 config
->pdbAltPath
= config
->pdbPath
;
2339 // It's important to make the path absolute and remove dots. This path
2340 // will eventually be written into the PE header, and certain Microsoft
2341 // tools won't work correctly if these assumptions are not held.
2342 sys::fs::make_absolute(config
->pdbAltPath
);
2343 sys::path::remove_dots(config
->pdbAltPath
);
2345 // Don't do this earlier, so that ctx.OutputFile is ready.
2348 config
->buildIDHash
= BuildIDHash::PDB
;
2351 // Set default image base if /base is not given.
2352 if (config
->imageBase
== uint64_t(-1))
2353 config
->imageBase
= getDefaultImageBase();
2355 ctx
.symtab
.addSynthetic(mangle("__ImageBase"), nullptr);
2356 if (config
->machine
== I386
) {
2357 ctx
.symtab
.addAbsolute("___safe_se_handler_table", 0);
2358 ctx
.symtab
.addAbsolute("___safe_se_handler_count", 0);
2361 ctx
.symtab
.addAbsolute(mangle("__guard_fids_count"), 0);
2362 ctx
.symtab
.addAbsolute(mangle("__guard_fids_table"), 0);
2363 ctx
.symtab
.addAbsolute(mangle("__guard_flags"), 0);
2364 ctx
.symtab
.addAbsolute(mangle("__guard_iat_count"), 0);
2365 ctx
.symtab
.addAbsolute(mangle("__guard_iat_table"), 0);
2366 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_count"), 0);
2367 ctx
.symtab
.addAbsolute(mangle("__guard_longjmp_table"), 0);
2368 // Needed for MSVC 2017 15.5 CRT.
2369 ctx
.symtab
.addAbsolute(mangle("__enclave_config"), 0);
2370 // Needed for MSVC 2019 16.8 CRT.
2371 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_count"), 0);
2372 ctx
.symtab
.addAbsolute(mangle("__guard_eh_cont_table"), 0);
2374 if (isArm64EC(config
->machine
)) {
2375 ctx
.symtab
.addAbsolute("__arm64x_extra_rfe_table", 0);
2376 ctx
.symtab
.addAbsolute("__arm64x_extra_rfe_table_size", 0);
2377 ctx
.symtab
.addAbsolute("__hybrid_code_map", 0);
2378 ctx
.symtab
.addAbsolute("__hybrid_code_map_count", 0);
2381 if (config
->pseudoRelocs
) {
2382 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2383 ctx
.symtab
.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2385 if (config
->mingw
) {
2386 ctx
.symtab
.addAbsolute(mangle("__CTOR_LIST__"), 0);
2387 ctx
.symtab
.addAbsolute(mangle("__DTOR_LIST__"), 0);
2389 if (config
->debug
|| config
->buildIDHash
!= BuildIDHash::None
)
2390 if (ctx
.symtab
.findUnderscore("__buildid"))
2391 ctx
.symtab
.addUndefined(mangle("__buildid"));
2393 // This code may add new undefined symbols to the link, which may enqueue more
2394 // symbol resolution tasks, so we need to continue executing tasks until we
2397 llvm::TimeTraceScope
timeScope("Add unresolved symbols");
2399 // Windows specific -- if entry point is not found,
2400 // search for its mangled names.
2402 mangleMaybe(config
->entry
);
2404 // Windows specific -- Make sure we resolve all dllexported symbols.
2405 for (Export
&e
: config
->exports
) {
2406 if (!e
.forwardTo
.empty())
2408 e
.sym
= addUndefined(e
.name
);
2409 if (e
.source
!= ExportSource::Directives
)
2410 e
.symbolName
= mangleMaybe(e
.sym
);
2413 // Add weak aliases. Weak aliases is a mechanism to give remaining
2414 // undefined symbols final chance to be resolved successfully.
2415 for (auto pair
: config
->alternateNames
) {
2416 StringRef from
= pair
.first
;
2417 StringRef to
= pair
.second
;
2418 Symbol
*sym
= ctx
.symtab
.find(from
);
2421 if (auto *u
= dyn_cast
<Undefined
>(sym
))
2423 u
->weakAlias
= ctx
.symtab
.addUndefined(to
);
2426 // If any inputs are bitcode files, the LTO code generator may create
2427 // references to library functions that are not explicit in the bitcode
2428 // file's symbol table. If any of those library functions are defined in a
2429 // bitcode file in an archive member, we need to arrange to use LTO to
2430 // compile those archive members by adding them to the link beforehand.
2431 if (!ctx
.bitcodeFileInstances
.empty()) {
2433 ctx
.bitcodeFileInstances
.front()->obj
->getTargetTriple());
2434 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols(TT
))
2435 ctx
.symtab
.addLibcall(s
);
2438 // Windows specific -- if __load_config_used can be resolved, resolve it.
2439 if (ctx
.symtab
.findUnderscore("_load_config_used"))
2440 addUndefined(mangle("_load_config_used"));
2442 if (args
.hasArg(OPT_include_optional
)) {
2443 // Handle /includeoptional
2444 for (auto *arg
: args
.filtered(OPT_include_optional
))
2445 if (isa_and_nonnull
<LazyArchive
>(ctx
.symtab
.find(arg
->getValue())))
2446 addUndefined(arg
->getValue());
2451 // Create wrapped symbols for -wrap option.
2452 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(ctx
, args
);
2453 // Load more object files that might be needed for wrapped symbols.
2454 if (!wrapped
.empty())
2458 if (config
->autoImport
|| config
->stdcallFixup
) {
2460 // Load any further object files that might be needed for doing automatic
2461 // imports, and do stdcall fixups.
2463 // For cases with no automatically imported symbols, this iterates once
2464 // over the symbol table and doesn't do anything.
2466 // For the normal case with a few automatically imported symbols, this
2467 // should only need to be run once, since each new object file imported
2468 // is an import library and wouldn't add any new undefined references,
2469 // but there's nothing stopping the __imp_ symbols from coming from a
2470 // normal object file as well (although that won't be used for the
2471 // actual autoimport later on). If this pass adds new undefined references,
2472 // we won't iterate further to resolve them.
2474 // If stdcall fixups only are needed for loading import entries from
2475 // a DLL without import library, this also just needs running once.
2476 // If it ends up pulling in more object files from static libraries,
2477 // (and maybe doing more stdcall fixups along the way), this would need
2478 // to loop these two calls.
2479 ctx
.symtab
.loadMinGWSymbols();
2483 // At this point, we should not have any symbols that cannot be resolved.
2484 // If we are going to do codegen for link-time optimization, check for
2485 // unresolvable symbols first, so we don't spend time generating code that
2486 // will fail to link anyway.
2487 if (!ctx
.bitcodeFileInstances
.empty() && !config
->forceUnresolved
)
2488 ctx
.symtab
.reportUnresolvable();
2492 config
->hadExplicitExports
= !config
->exports
.empty();
2493 if (config
->mingw
) {
2494 // In MinGW, all symbols are automatically exported if no symbols
2495 // are chosen to be exported.
2496 maybeExportMinGWSymbols(args
);
2499 // Do LTO by compiling bitcode input files to a set of native COFF files then
2500 // link those files (unless -thinlto-index-only was given, in which case we
2501 // resolve symbols and write indices, but don't generate native code or link).
2502 ctx
.symtab
.compileBitcodeFiles();
2505 dyn_cast_or_null
<Defined
>(ctx
.symtab
.findUnderscore("_tls_used")))
2506 config
->gcroot
.push_back(d
);
2508 // If -thinlto-index-only is given, we should create only "index
2509 // files" and not object files. Index file creation is already done
2510 // in addCombinedLTOObject, so we are done if that's the case.
2511 // Likewise, don't emit object files for other /lldemit options.
2512 if (config
->emit
!= EmitKind::Obj
|| config
->thinLTOIndexOnly
)
2515 // If we generated native object files from bitcode files, this resolves
2516 // references to the symbols we use from them.
2519 // Apply symbol renames for -wrap.
2520 if (!wrapped
.empty())
2521 wrapSymbols(ctx
, wrapped
);
2523 // Resolve remaining undefined symbols and warn about imported locals.
2524 ctx
.symtab
.resolveRemainingUndefines();
2528 if (config
->mingw
) {
2529 // Make sure the crtend.o object is the last object file. This object
2530 // file can contain terminating section chunks that need to be placed
2531 // last. GNU ld processes files and static libraries explicitly in the
2532 // order provided on the command line, while lld will pull in needed
2533 // files from static libraries only after the last object file on the
2535 for (auto i
= ctx
.objFileInstances
.begin(), e
= ctx
.objFileInstances
.end();
2538 if (isCrtend(file
->getName())) {
2539 ctx
.objFileInstances
.erase(i
);
2540 ctx
.objFileInstances
.push_back(file
);
2546 // Windows specific -- when we are creating a .dll file, we also
2547 // need to create a .lib file. In MinGW mode, we only do that when the
2548 // -implib option is given explicitly, for compatibility with GNU ld.
2549 if (!config
->exports
.empty() || config
->dll
) {
2550 llvm::TimeTraceScope
timeScope("Create .lib exports");
2552 if (!config
->noimplib
&& (!config
->mingw
|| !config
->implib
.empty()))
2553 createImportLibrary(/*asLib=*/false);
2554 assignExportOrdinals();
2557 // Handle /output-def (MinGW specific).
2558 if (auto *arg
= args
.getLastArg(OPT_output_def
))
2559 writeDefFile(arg
->getValue(), config
->exports
);
2561 // Set extra alignment for .comm symbols
2562 for (auto pair
: config
->alignComm
) {
2563 StringRef name
= pair
.first
;
2564 uint32_t alignment
= pair
.second
;
2566 Symbol
*sym
= ctx
.symtab
.find(name
);
2568 warn("/aligncomm symbol " + name
+ " not found");
2572 // If the symbol isn't common, it must have been replaced with a regular
2573 // symbol, which will carry its own alignment.
2574 auto *dc
= dyn_cast
<DefinedCommon
>(sym
);
2578 CommonChunk
*c
= dc
->getChunk();
2579 c
->setAlignment(std::max(c
->getAlignment(), alignment
));
2582 // Windows specific -- Create an embedded or side-by-side manifest.
2583 // /manifestdependency: enables /manifest unless an explicit /manifest:no is
2585 if (config
->manifest
== Configuration::Embed
)
2586 addBuffer(createManifestRes(), false, false);
2587 else if (config
->manifest
== Configuration::SideBySide
||
2588 (config
->manifest
== Configuration::Default
&&
2589 !config
->manifestDependencies
.empty()))
2590 createSideBySideManifest();
2592 // Handle /order. We want to do this at this moment because we
2593 // need a complete list of comdat sections to warn on nonexistent
2595 if (auto *arg
= args
.getLastArg(OPT_order
)) {
2596 if (args
.hasArg(OPT_call_graph_ordering_file
))
2597 error("/order and /call-graph-order-file may not be used together");
2598 parseOrderFile(arg
->getValue());
2599 config
->callGraphProfileSort
= false;
2602 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2603 if (config
->callGraphProfileSort
) {
2604 llvm::TimeTraceScope
timeScope("Call graph");
2605 if (auto *arg
= args
.getLastArg(OPT_call_graph_ordering_file
)) {
2606 parseCallGraphFile(arg
->getValue());
2608 readCallGraphsFromObjectFiles(ctx
);
2611 // Handle /print-symbol-order.
2612 if (auto *arg
= args
.getLastArg(OPT_print_symbol_order
))
2613 config
->printSymbolOrder
= arg
->getValue();
2615 ctx
.symtab
.initializeEntryThunks();
2617 // Identify unreferenced COMDAT sections.
2619 if (config
->mingw
) {
2620 // markLive doesn't traverse .eh_frame, but the personality function is
2621 // only reached that way. The proper solution would be to parse and
2622 // traverse the .eh_frame section, like the ELF linker does.
2623 // For now, just manually try to retain the known possible personality
2624 // functions. This doesn't bring in more object files, but only marks
2625 // functions that already have been included to be retained.
2626 for (const char *n
: {"__gxx_personality_v0", "__gcc_personality_v0",
2627 "rust_eh_personality"}) {
2628 Defined
*d
= dyn_cast_or_null
<Defined
>(ctx
.symtab
.findUnderscore(n
));
2629 if (d
&& !d
->isGCRoot
) {
2631 config
->gcroot
.push_back(d
);
2639 // Needs to happen after the last call to addFile().
2642 // Identify identical COMDAT sections to merge them.
2643 if (config
->doICF
!= ICFLevel::None
) {
2644 findKeepUniqueSections(ctx
);
2648 // Write the result.
2651 // Stop early so we can print the results.
2653 if (config
->showTiming
)
2654 ctx
.rootTimer
.print();
2656 if (config
->timeTraceEnabled
) {
2657 // Manually stop the topmost "COFF link" scope, since we're shutting down.
2658 timeTraceProfilerEnd();
2660 checkError(timeTraceProfilerWrite(
2661 args
.getLastArgValue(OPT_time_trace_eq
).str(), config
->outputFile
));
2662 timeTraceProfilerCleanup();
2666 } // namespace lld::coff