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 //===----------------------------------------------------------------------===//
11 #include "DebugTypes.h"
13 #include "InputFiles.h"
16 #include "SymbolTable.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Filesystem.h"
23 #include "lld/Common/Memory.h"
24 #include "lld/Common/Timer.h"
25 #include "lld/Common/Version.h"
26 #include "llvm/ADT/Optional.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/raw_ostream.h"
49 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
55 using namespace llvm::object
;
56 using namespace llvm::COFF
;
57 using llvm::sys::Process
;
62 static Timer
inputFileTimer("Input File Reading", Timer::root());
64 Configuration
*config
;
67 bool link(ArrayRef
<const char *> args
, bool canExitEarly
, raw_ostream
&stdoutOS
,
68 raw_ostream
&stderrOS
) {
69 lld::stdoutOS
= &stdoutOS
;
70 lld::stderrOS
= &stderrOS
;
72 errorHandler().cleanupCallback
= []() {
75 ObjFile::instances
.clear();
76 PDBInputFile::instances
.clear();
77 ImportFile::instances
.clear();
78 BitcodeFile::instances
.clear();
79 memset(MergeChunk::instances
, 0, sizeof(MergeChunk::instances
));
80 OutputSection::clear();
83 errorHandler().logName
= args::getFilenameWithoutExe(args
[0]);
84 errorHandler().errorLimitExceededMsg
=
85 "too many errors emitted, stopping now"
86 " (use /errorlimit:0 to see all errors)";
87 errorHandler().exitEarly
= canExitEarly
;
88 stderrOS
.enable_colors(stderrOS
.has_colors());
90 config
= make
<Configuration
>();
91 symtab
= make
<SymbolTable
>();
92 driver
= make
<LinkerDriver
>();
96 // Call exit() if we can to avoid calling destructors.
98 exitLld(errorCount() ? 1 : 0);
100 bool ret
= errorCount() == 0;
102 errorHandler().reset();
106 // Parse options of the form "old;new".
107 static std::pair
<StringRef
, StringRef
> getOldNewOptions(opt::InputArgList
&args
,
109 auto *arg
= args
.getLastArg(id
);
113 StringRef s
= arg
->getValue();
114 std::pair
<StringRef
, StringRef
> ret
= s
.split(';');
115 if (ret
.second
.empty())
116 error(arg
->getSpelling() + " expects 'old;new' format, but got " + s
);
120 // Drop directory components and replace extension with
121 // ".exe", ".dll" or ".sys".
122 static std::string
getOutputPath(StringRef path
) {
123 StringRef ext
= ".exe";
126 else if (config
->driver
)
129 return (sys::path::stem(path
) + ext
).str();
132 // Returns true if S matches /crtend.?\.o$/.
133 static bool isCrtend(StringRef s
) {
134 if (!s
.endswith(".o"))
137 if (s
.endswith("crtend"))
139 return !s
.empty() && s
.drop_back().endswith("crtend");
142 // ErrorOr is not default constructible, so it cannot be used as the type
143 // parameter of a future.
144 // FIXME: We could open the file in createFutureForFile and avoid needing to
145 // return an error here, but for the moment that would cost us a file descriptor
146 // (a limited resource on Windows) for the duration that the future is pending.
147 using MBErrPair
= std::pair
<std::unique_ptr
<MemoryBuffer
>, std::error_code
>;
149 // Create a std::future that opens and maps a file using the best strategy for
150 // the host platform.
151 static std::future
<MBErrPair
> createFutureForFile(std::string path
) {
153 // On Windows, file I/O is relatively slow so it is best to do this
155 auto strategy
= std::launch::async
;
157 auto strategy
= std::launch::deferred
;
159 return std::async(strategy
, [=]() {
160 auto mbOrErr
= MemoryBuffer::getFile(path
,
162 /*RequiresNullTerminator*/ false);
164 return MBErrPair
{nullptr, mbOrErr
.getError()};
165 return MBErrPair
{std::move(*mbOrErr
), std::error_code()};
169 // Symbol names are mangled by prepending "_" on x86.
170 static StringRef
mangle(StringRef sym
) {
171 assert(config
->machine
!= IMAGE_FILE_MACHINE_UNKNOWN
);
172 if (config
->machine
== I386
)
173 return saver
.save("_" + sym
);
177 static bool findUnderscoreMangle(StringRef sym
) {
178 Symbol
*s
= symtab
->findMangle(mangle(sym
));
179 return s
&& !isa
<Undefined
>(s
);
182 MemoryBufferRef
LinkerDriver::takeBuffer(std::unique_ptr
<MemoryBuffer
> mb
) {
183 MemoryBufferRef mbref
= *mb
;
184 make
<std::unique_ptr
<MemoryBuffer
>>(std::move(mb
)); // take ownership
187 driver
->tar
->append(relativeToRoot(mbref
.getBufferIdentifier()),
192 void LinkerDriver::addBuffer(std::unique_ptr
<MemoryBuffer
> mb
,
193 bool wholeArchive
, bool lazy
) {
194 StringRef filename
= mb
->getBufferIdentifier();
196 MemoryBufferRef mbref
= takeBuffer(std::move(mb
));
197 filePaths
.push_back(filename
);
199 // File type is detected by contents, not by file extension.
200 switch (identify_magic(mbref
.getBuffer())) {
201 case file_magic::windows_resource
:
202 resources
.push_back(mbref
);
204 case file_magic::archive
:
206 std::unique_ptr
<Archive
> file
=
207 CHECK(Archive::create(mbref
), filename
+ ": failed to parse archive");
208 Archive
*archive
= file
.get();
209 make
<std::unique_ptr
<Archive
>>(std::move(file
)); // take ownership
212 for (MemoryBufferRef m
: getArchiveMembers(archive
))
213 addArchiveBuffer(m
, "<whole-archive>", filename
, memberIndex
++);
216 symtab
->addFile(make
<ArchiveFile
>(mbref
));
218 case file_magic::bitcode
:
220 symtab
->addFile(make
<LazyObjFile
>(mbref
));
222 symtab
->addFile(make
<BitcodeFile
>(mbref
, "", 0));
224 case file_magic::coff_object
:
225 case file_magic::coff_import_library
:
227 symtab
->addFile(make
<LazyObjFile
>(mbref
));
229 symtab
->addFile(make
<ObjFile
>(mbref
));
231 case file_magic::pdb
:
232 symtab
->addFile(make
<PDBInputFile
>(mbref
));
234 case file_magic::coff_cl_gl_object
:
235 error(filename
+ ": is not a native COFF file. Recompile without /GL");
237 case file_magic::pecoff_executable
:
238 if (filename
.endswith_lower(".dll")) {
239 error(filename
+ ": bad file type. Did you specify a DLL instead of an "
245 error(mbref
.getBufferIdentifier() + ": unknown file type");
250 void LinkerDriver::enqueuePath(StringRef path
, bool wholeArchive
, bool lazy
) {
251 auto future
= std::make_shared
<std::future
<MBErrPair
>>(
252 createFutureForFile(std::string(path
)));
253 std::string pathStr
= std::string(path
);
255 auto mbOrErr
= future
->get();
256 if (mbOrErr
.second
) {
258 "could not open '" + pathStr
+ "': " + mbOrErr
.second
.message();
259 // Check if the filename is a typo for an option flag. OptTable thinks
260 // that all args that are not known options and that start with / are
261 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
262 // the option `/nodefaultlib` than a reference to a file in the root
265 if (optTable
.findNearest(pathStr
, nearest
) > 1)
268 error(msg
+ "; did you mean '" + nearest
+ "'");
270 driver
->addBuffer(std::move(mbOrErr
.first
), wholeArchive
, lazy
);
274 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb
, StringRef symName
,
275 StringRef parentName
,
276 uint64_t offsetInArchive
) {
277 file_magic magic
= identify_magic(mb
.getBuffer());
278 if (magic
== file_magic::coff_import_library
) {
279 InputFile
*imp
= make
<ImportFile
>(mb
);
280 imp
->parentName
= parentName
;
281 symtab
->addFile(imp
);
286 if (magic
== file_magic::coff_object
) {
287 obj
= make
<ObjFile
>(mb
);
288 } else if (magic
== file_magic::bitcode
) {
289 obj
= make
<BitcodeFile
>(mb
, parentName
, offsetInArchive
);
291 error("unknown file type: " + mb
.getBufferIdentifier());
295 obj
->parentName
= parentName
;
296 symtab
->addFile(obj
);
297 log("Loaded " + toString(obj
) + " for " + symName
);
300 void LinkerDriver::enqueueArchiveMember(const Archive::Child
&c
,
301 const Archive::Symbol
&sym
,
302 StringRef parentName
) {
304 auto reportBufferError
= [=](Error
&&e
, StringRef childName
) {
305 fatal("could not get the buffer for the member defining symbol " +
306 toCOFFString(sym
) + ": " + parentName
+ "(" + childName
+ "): " +
307 toString(std::move(e
)));
310 if (!c
.getParent()->isThin()) {
311 uint64_t offsetInArchive
= c
.getChildOffset();
312 Expected
<MemoryBufferRef
> mbOrErr
= c
.getMemoryBufferRef();
314 reportBufferError(mbOrErr
.takeError(), check(c
.getFullName()));
315 MemoryBufferRef mb
= mbOrErr
.get();
317 driver
->addArchiveBuffer(mb
, toCOFFString(sym
), parentName
,
323 std::string childName
= CHECK(
325 "could not get the filename for the member defining symbol " +
327 auto future
= std::make_shared
<std::future
<MBErrPair
>>(
328 createFutureForFile(childName
));
330 auto mbOrErr
= future
->get();
332 reportBufferError(errorCodeToError(mbOrErr
.second
), childName
);
333 // Pass empty string as archive name so that the original filename is
334 // used as the buffer identifier.
335 driver
->addArchiveBuffer(takeBuffer(std::move(mbOrErr
.first
)),
336 toCOFFString(sym
), "", /*OffsetInArchive=*/0);
340 static bool isDecorated(StringRef sym
) {
341 return sym
.startswith("@") || sym
.contains("@@") || sym
.startswith("?") ||
342 (!config
->mingw
&& sym
.contains('@'));
345 // Parses .drectve section contents and returns a list of files
346 // specified by /defaultlib.
347 void LinkerDriver::parseDirectives(InputFile
*file
) {
348 StringRef s
= file
->getDirectives();
352 log("Directives: " + toString(file
) + ": " + s
);
355 // .drectve is always tokenized using Windows shell rules.
356 // /EXPORT: option can appear too many times, processing in fastpath.
357 ParsedDirectives directives
= parser
.parseDirectives(s
);
359 for (StringRef e
: directives
.exports
) {
360 // If a common header file contains dllexported function
361 // declarations, many object files may end up with having the
362 // same /EXPORT options. In order to save cost of parsing them,
363 // we dedup them first.
364 if (!directivesExports
.insert(e
).second
)
367 Export exp
= parseExport(e
);
368 if (config
->machine
== I386
&& config
->mingw
) {
369 if (!isDecorated(exp
.name
))
370 exp
.name
= saver
.save("_" + exp
.name
);
371 if (!exp
.extName
.empty() && !isDecorated(exp
.extName
))
372 exp
.extName
= saver
.save("_" + exp
.extName
);
374 exp
.directives
= true;
375 config
->exports
.push_back(exp
);
378 // Handle /include: in bulk.
379 for (StringRef inc
: directives
.includes
)
382 for (auto *arg
: directives
.args
) {
383 switch (arg
->getOption().getID()) {
385 parseAligncomm(arg
->getValue());
387 case OPT_alternatename
:
388 parseAlternateName(arg
->getValue());
391 if (Optional
<StringRef
> path
= findLib(arg
->getValue()))
392 enqueuePath(*path
, false, false);
395 config
->entry
= addUndefined(mangle(arg
->getValue()));
397 case OPT_failifmismatch
:
398 checkFailIfMismatch(arg
->getValue(), file
);
401 addUndefined(arg
->getValue());
404 parseMerge(arg
->getValue());
406 case OPT_nodefaultlib
:
407 config
->noDefaultLibs
.insert(doFindLib(arg
->getValue()).lower());
410 parseSection(arg
->getValue());
412 case OPT_subsystem
: {
413 bool gotVersion
= false;
414 parseSubsystem(arg
->getValue(), &config
->subsystem
,
415 &config
->majorSubsystemVersion
,
416 &config
->minorSubsystemVersion
, &gotVersion
);
418 config
->majorOSVersion
= config
->majorSubsystemVersion
;
419 config
->minorOSVersion
= config
->minorSubsystemVersion
;
423 // Only add flags here that link.exe accepts in
424 // `#pragma comment(linker, "/flag")`-generated sections.
425 case OPT_editandcontinue
:
427 case OPT_throwingnew
:
430 error(arg
->getSpelling() + " is not allowed in .drectve");
435 // Find file from search paths. You can omit ".obj", this function takes
436 // care of that. Note that the returned path is not guaranteed to exist.
437 StringRef
LinkerDriver::doFindFile(StringRef filename
) {
438 bool hasPathSep
= (filename
.find_first_of("/\\") != StringRef::npos
);
441 bool hasExt
= filename
.contains('.');
442 for (StringRef dir
: searchPaths
) {
443 SmallString
<128> path
= dir
;
444 sys::path::append(path
, filename
);
445 if (sys::fs::exists(path
.str()))
446 return saver
.save(path
.str());
449 if (sys::fs::exists(path
.str()))
450 return saver
.save(path
.str());
456 static Optional
<sys::fs::UniqueID
> getUniqueID(StringRef path
) {
457 sys::fs::UniqueID ret
;
458 if (sys::fs::getUniqueID(path
, ret
))
463 // Resolves a file path. This never returns the same path
464 // (in that case, it returns None).
465 Optional
<StringRef
> LinkerDriver::findFile(StringRef filename
) {
466 StringRef path
= doFindFile(filename
);
468 if (Optional
<sys::fs::UniqueID
> id
= getUniqueID(path
)) {
469 bool seen
= !visitedFiles
.insert(*id
).second
;
474 if (path
.endswith_lower(".lib"))
475 visitedLibs
.insert(std::string(sys::path::filename(path
)));
479 // MinGW specific. If an embedded directive specified to link to
480 // foo.lib, but it isn't found, try libfoo.a instead.
481 StringRef
LinkerDriver::doFindLibMinGW(StringRef filename
) {
482 if (filename
.contains('/') || filename
.contains('\\'))
485 SmallString
<128> s
= filename
;
486 sys::path::replace_extension(s
, ".a");
487 StringRef libName
= saver
.save("lib" + s
.str());
488 return doFindFile(libName
);
491 // Find library file from search path.
492 StringRef
LinkerDriver::doFindLib(StringRef filename
) {
493 // Add ".lib" to Filename if that has no file extension.
494 bool hasExt
= filename
.contains('.');
496 filename
= saver
.save(filename
+ ".lib");
497 StringRef ret
= doFindFile(filename
);
498 // For MinGW, if the find above didn't turn up anything, try
499 // looking for a MinGW formatted library name.
500 if (config
->mingw
&& ret
== filename
)
501 return doFindLibMinGW(filename
);
505 // Resolves a library path. /nodefaultlib options are taken into
506 // consideration. This never returns the same path (in that case,
508 Optional
<StringRef
> LinkerDriver::findLib(StringRef filename
) {
509 if (config
->noDefaultLibAll
)
511 if (!visitedLibs
.insert(filename
.lower()).second
)
514 StringRef path
= doFindLib(filename
);
515 if (config
->noDefaultLibs
.count(path
.lower()))
518 if (Optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
519 if (!visitedFiles
.insert(*id
).second
)
524 // Parses LIB environment which contains a list of search paths.
525 void LinkerDriver::addLibSearchPaths() {
526 Optional
<std::string
> envOpt
= Process::GetEnv("LIB");
527 if (!envOpt
.hasValue())
529 StringRef env
= saver
.save(*envOpt
);
530 while (!env
.empty()) {
532 std::tie(path
, env
) = env
.split(';');
533 searchPaths
.push_back(path
);
537 Symbol
*LinkerDriver::addUndefined(StringRef name
) {
538 Symbol
*b
= symtab
->addUndefined(name
);
541 config
->gcroot
.push_back(b
);
546 StringRef
LinkerDriver::mangleMaybe(Symbol
*s
) {
547 // If the plain symbol name has already been resolved, do nothing.
548 Undefined
*unmangled
= dyn_cast
<Undefined
>(s
);
552 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
553 Symbol
*mangled
= symtab
->findMangle(unmangled
->getName());
557 // If we find a similar mangled symbol, make this an alias to it and return
559 log(unmangled
->getName() + " aliased to " + mangled
->getName());
560 unmangled
->weakAlias
= symtab
->addUndefined(mangled
->getName());
561 return mangled
->getName();
564 // Windows specific -- find default entry point name.
566 // There are four different entry point functions for Windows executables,
567 // each of which corresponds to a user-defined "main" function. This function
568 // infers an entry point from a user-defined "main" function.
569 StringRef
LinkerDriver::findDefaultEntry() {
570 assert(config
->subsystem
!= IMAGE_SUBSYSTEM_UNKNOWN
&&
571 "must handle /subsystem before calling this");
574 return mangle(config
->subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
575 ? "WinMainCRTStartup"
578 if (config
->subsystem
== IMAGE_SUBSYSTEM_WINDOWS_GUI
) {
579 if (findUnderscoreMangle("wWinMain")) {
580 if (!findUnderscoreMangle("WinMain"))
581 return mangle("wWinMainCRTStartup");
582 warn("found both wWinMain and WinMain; using latter");
584 return mangle("WinMainCRTStartup");
586 if (findUnderscoreMangle("wmain")) {
587 if (!findUnderscoreMangle("main"))
588 return mangle("wmainCRTStartup");
589 warn("found both wmain and main; using latter");
591 return mangle("mainCRTStartup");
594 WindowsSubsystem
LinkerDriver::inferSubsystem() {
596 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
598 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
599 // Note that link.exe infers the subsystem from the presence of these
600 // functions even if /entry: or /nodefaultlib are passed which causes them
602 bool haveMain
= findUnderscoreMangle("main");
603 bool haveWMain
= findUnderscoreMangle("wmain");
604 bool haveWinMain
= findUnderscoreMangle("WinMain");
605 bool haveWWinMain
= findUnderscoreMangle("wWinMain");
606 if (haveMain
|| haveWMain
) {
607 if (haveWinMain
|| haveWWinMain
) {
608 warn(std::string("found ") + (haveMain
? "main" : "wmain") + " and " +
609 (haveWinMain
? "WinMain" : "wWinMain") +
610 "; defaulting to /subsystem:console");
612 return IMAGE_SUBSYSTEM_WINDOWS_CUI
;
614 if (haveWinMain
|| haveWWinMain
)
615 return IMAGE_SUBSYSTEM_WINDOWS_GUI
;
616 return IMAGE_SUBSYSTEM_UNKNOWN
;
619 static uint64_t getDefaultImageBase() {
621 return config
->dll
? 0x180000000 : 0x140000000;
622 return config
->dll
? 0x10000000 : 0x400000;
625 static std::string
createResponseFile(const opt::InputArgList
&args
,
626 ArrayRef
<StringRef
> filePaths
,
627 ArrayRef
<StringRef
> searchPaths
) {
629 raw_svector_ostream
os(data
);
631 for (auto *arg
: args
) {
632 switch (arg
->getOption().getID()) {
639 case OPT_manifest_colon
:
640 case OPT_manifestdependency
:
641 case OPT_manifestfile
:
642 case OPT_manifestinput
:
643 case OPT_manifestuac
:
647 case OPT_pdbstripped
:
649 os
<< arg
->getSpelling() << sys::path::filename(arg
->getValue()) << "\n";
652 os
<< toString(*arg
) << "\n";
656 for (StringRef path
: searchPaths
) {
657 std::string relPath
= relativeToRoot(path
);
658 os
<< "/libpath:" << quote(relPath
) << "\n";
661 for (StringRef path
: filePaths
)
662 os
<< quote(relativeToRoot(path
)) << "\n";
664 return std::string(data
.str());
667 enum class DebugKind
{ Unknown
, None
, Full
, FastLink
, GHash
, Dwarf
, Symtab
};
669 static DebugKind
parseDebugKind(const opt::InputArgList
&args
) {
670 auto *a
= args
.getLastArg(OPT_debug
, OPT_debug_opt
);
672 return DebugKind::None
;
673 if (a
->getNumValues() == 0)
674 return DebugKind::Full
;
676 DebugKind debug
= StringSwitch
<DebugKind
>(a
->getValue())
677 .CaseLower("none", DebugKind::None
)
678 .CaseLower("full", DebugKind::Full
)
679 .CaseLower("fastlink", DebugKind::FastLink
)
681 .CaseLower("ghash", DebugKind::GHash
)
682 .CaseLower("dwarf", DebugKind::Dwarf
)
683 .CaseLower("symtab", DebugKind::Symtab
)
684 .Default(DebugKind::Unknown
);
686 if (debug
== DebugKind::FastLink
) {
687 warn("/debug:fastlink unsupported; using /debug:full");
688 return DebugKind::Full
;
690 if (debug
== DebugKind::Unknown
) {
691 error("/debug: unknown option: " + Twine(a
->getValue()));
692 return DebugKind::None
;
697 static unsigned parseDebugTypes(const opt::InputArgList
&args
) {
698 unsigned debugTypes
= static_cast<unsigned>(DebugType::None
);
700 if (auto *a
= args
.getLastArg(OPT_debugtype
)) {
701 SmallVector
<StringRef
, 3> types
;
702 StringRef(a
->getValue())
703 .split(types
, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
705 for (StringRef type
: types
) {
706 unsigned v
= StringSwitch
<unsigned>(type
.lower())
707 .Case("cv", static_cast<unsigned>(DebugType::CV
))
708 .Case("pdata", static_cast<unsigned>(DebugType::PData
))
709 .Case("fixup", static_cast<unsigned>(DebugType::Fixup
))
712 warn("/debugtype: unknown option '" + type
+ "'");
720 // Default debug types
721 debugTypes
= static_cast<unsigned>(DebugType::CV
);
722 if (args
.hasArg(OPT_driver
))
723 debugTypes
|= static_cast<unsigned>(DebugType::PData
);
724 if (args
.hasArg(OPT_profile
))
725 debugTypes
|= static_cast<unsigned>(DebugType::Fixup
);
730 static std::string
getMapFile(const opt::InputArgList
&args
,
731 opt::OptSpecifier os
, opt::OptSpecifier osFile
) {
732 auto *arg
= args
.getLastArg(os
, osFile
);
735 if (arg
->getOption().getID() == osFile
.getID())
736 return arg
->getValue();
738 assert(arg
->getOption().getID() == os
.getID());
739 StringRef outFile
= config
->outputFile
;
740 return (outFile
.substr(0, outFile
.rfind('.')) + ".map").str();
743 static std::string
getImplibPath() {
744 if (!config
->implib
.empty())
745 return std::string(config
->implib
);
746 SmallString
<128> out
= StringRef(config
->outputFile
);
747 sys::path::replace_extension(out
, ".lib");
748 return std::string(out
.str());
751 // The import name is calculated as follows:
753 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
754 // -----+----------------+---------------------+------------------
755 // LINK | {value} | {value}.{.dll/.exe} | {output name}
756 // LIB | {value} | {value}.dll | {output name}.dll
758 static std::string
getImportName(bool asLib
) {
759 SmallString
<128> out
;
761 if (config
->importName
.empty()) {
762 out
.assign(sys::path::filename(config
->outputFile
));
764 sys::path::replace_extension(out
, ".dll");
766 out
.assign(config
->importName
);
767 if (!sys::path::has_extension(out
))
768 sys::path::replace_extension(out
,
769 (config
->dll
|| asLib
) ? ".dll" : ".exe");
772 return std::string(out
.str());
775 static void createImportLibrary(bool asLib
) {
776 std::vector
<COFFShortExport
> exports
;
777 for (Export
&e1
: config
->exports
) {
779 e2
.Name
= std::string(e1
.name
);
780 e2
.SymbolName
= std::string(e1
.symbolName
);
781 e2
.ExtName
= std::string(e1
.extName
);
782 e2
.Ordinal
= e1
.ordinal
;
783 e2
.Noname
= e1
.noname
;
785 e2
.Private
= e1
.isPrivate
;
786 e2
.Constant
= e1
.constant
;
787 exports
.push_back(e2
);
790 auto handleError
= [](Error
&&e
) {
791 handleAllErrors(std::move(e
),
792 [](ErrorInfoBase
&eib
) { error(eib
.message()); });
794 std::string libName
= getImportName(asLib
);
795 std::string path
= getImplibPath();
797 if (!config
->incremental
) {
798 handleError(writeImportLibrary(libName
, path
, exports
, config
->machine
,
803 // If the import library already exists, replace it only if the contents
805 ErrorOr
<std::unique_ptr
<MemoryBuffer
>> oldBuf
= MemoryBuffer::getFile(
806 path
, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
808 handleError(writeImportLibrary(libName
, path
, exports
, config
->machine
,
813 SmallString
<128> tmpName
;
814 if (std::error_code ec
=
815 sys::fs::createUniqueFile(path
+ ".tmp-%%%%%%%%.lib", tmpName
))
816 fatal("cannot create temporary file for import library " + path
+ ": " +
819 if (Error e
= writeImportLibrary(libName
, tmpName
, exports
, config
->machine
,
821 handleError(std::move(e
));
825 std::unique_ptr
<MemoryBuffer
> newBuf
= check(MemoryBuffer::getFile(
826 tmpName
, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
827 if ((*oldBuf
)->getBuffer() != newBuf
->getBuffer()) {
829 handleError(errorCodeToError(sys::fs::rename(tmpName
, path
)));
831 sys::fs::remove(tmpName
);
835 static void parseModuleDefs(StringRef path
) {
836 std::unique_ptr
<MemoryBuffer
> mb
= CHECK(
837 MemoryBuffer::getFile(path
, -1, false, true), "could not open " + path
);
838 COFFModuleDefinition m
= check(parseCOFFModuleDefinition(
839 mb
->getMemBufferRef(), config
->machine
, config
->mingw
));
841 if (config
->outputFile
.empty())
842 config
->outputFile
= std::string(saver
.save(m
.OutputFile
));
843 config
->importName
= std::string(saver
.save(m
.ImportName
));
845 config
->imageBase
= m
.ImageBase
;
847 config
->stackReserve
= m
.StackReserve
;
849 config
->stackCommit
= m
.StackCommit
;
851 config
->heapReserve
= m
.HeapReserve
;
853 config
->heapCommit
= m
.HeapCommit
;
854 if (m
.MajorImageVersion
)
855 config
->majorImageVersion
= m
.MajorImageVersion
;
856 if (m
.MinorImageVersion
)
857 config
->minorImageVersion
= m
.MinorImageVersion
;
858 if (m
.MajorOSVersion
)
859 config
->majorOSVersion
= m
.MajorOSVersion
;
860 if (m
.MinorOSVersion
)
861 config
->minorOSVersion
= m
.MinorOSVersion
;
863 for (COFFShortExport e1
: m
.Exports
) {
865 // In simple cases, only Name is set. Renamed exports are parsed
866 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
867 // it shouldn't be a normal exported function but a forward to another
868 // DLL instead. This is supported by both MS and GNU linkers.
869 if (!e1
.ExtName
.empty() && e1
.ExtName
!= e1
.Name
&&
870 StringRef(e1
.Name
).contains('.')) {
871 e2
.name
= saver
.save(e1
.ExtName
);
872 e2
.forwardTo
= saver
.save(e1
.Name
);
873 config
->exports
.push_back(e2
);
876 e2
.name
= saver
.save(e1
.Name
);
877 e2
.extName
= saver
.save(e1
.ExtName
);
878 e2
.ordinal
= e1
.Ordinal
;
879 e2
.noname
= e1
.Noname
;
881 e2
.isPrivate
= e1
.Private
;
882 e2
.constant
= e1
.Constant
;
883 config
->exports
.push_back(e2
);
887 void LinkerDriver::enqueueTask(std::function
<void()> task
) {
888 taskQueue
.push_back(std::move(task
));
891 bool LinkerDriver::run() {
892 ScopedTimer
t(inputFileTimer
);
894 bool didWork
= !taskQueue
.empty();
895 while (!taskQueue
.empty()) {
897 taskQueue
.pop_front();
902 // Parse an /order file. If an option is given, the linker places
903 // COMDAT sections in the same order as their names appear in the
905 static void parseOrderFile(StringRef arg
) {
906 // For some reason, the MSVC linker requires a filename to be
908 if (!arg
.startswith("@")) {
909 error("malformed /order option: '@' missing");
913 // Get a list of all comdat sections for error checking.
914 DenseSet
<StringRef
> set
;
915 for (Chunk
*c
: symtab
->getChunks())
916 if (auto *sec
= dyn_cast
<SectionChunk
>(c
))
918 set
.insert(sec
->sym
->getName());
921 StringRef path
= arg
.substr(1);
922 std::unique_ptr
<MemoryBuffer
> mb
= CHECK(
923 MemoryBuffer::getFile(path
, -1, false, true), "could not open " + path
);
925 // Parse a file. An order file contains one symbol per line.
926 // All symbols that were not present in a given order file are
927 // considered to have the lowest priority 0 and are placed at
928 // end of an output section.
929 for (StringRef arg
: args::getLines(mb
->getMemBufferRef())) {
931 if (config
->machine
== I386
&& !isDecorated(s
))
934 if (set
.count(s
) == 0) {
935 if (config
->warnMissingOrderSymbol
)
936 warn("/order:" + arg
+ ": missing symbol: " + s
+ " [LNK4037]");
939 config
->order
[s
] = INT_MIN
+ config
->order
.size();
943 static void parseCallGraphFile(StringRef path
) {
944 std::unique_ptr
<MemoryBuffer
> mb
= CHECK(
945 MemoryBuffer::getFile(path
, -1, false, true), "could not open " + path
);
947 // Build a map from symbol name to section.
948 DenseMap
<StringRef
, Symbol
*> map
;
949 for (ObjFile
*file
: ObjFile::instances
)
950 for (Symbol
*sym
: file
->getSymbols())
952 map
[sym
->getName()] = sym
;
954 auto findSection
= [&](StringRef name
) -> SectionChunk
* {
955 Symbol
*sym
= map
.lookup(name
);
957 if (config
->warnMissingOrderSymbol
)
958 warn(path
+ ": no such symbol: " + name
);
962 if (DefinedCOFF
*dr
= dyn_cast_or_null
<DefinedCOFF
>(sym
))
963 return dyn_cast_or_null
<SectionChunk
>(dr
->getChunk());
967 for (StringRef line
: args::getLines(*mb
)) {
968 SmallVector
<StringRef
, 3> fields
;
969 line
.split(fields
, ' ');
972 if (fields
.size() != 3 || !to_integer(fields
[2], count
)) {
973 error(path
+ ": parse error");
977 if (SectionChunk
*from
= findSection(fields
[0]))
978 if (SectionChunk
*to
= findSection(fields
[1]))
979 config
->callGraphProfile
[{from
, to
}] += count
;
983 static void readCallGraphsFromObjectFiles() {
984 for (ObjFile
*obj
: ObjFile::instances
) {
985 if (obj
->callgraphSec
) {
986 ArrayRef
<uint8_t> contents
;
988 obj
->getCOFFObj()->getSectionContents(obj
->callgraphSec
, contents
));
989 BinaryStreamReader
reader(contents
, support::little
);
990 while (!reader
.empty()) {
991 uint32_t fromIndex
, toIndex
;
993 if (Error err
= reader
.readInteger(fromIndex
))
994 fatal(toString(obj
) + ": Expected 32-bit integer");
995 if (Error err
= reader
.readInteger(toIndex
))
996 fatal(toString(obj
) + ": Expected 32-bit integer");
997 if (Error err
= reader
.readInteger(count
))
998 fatal(toString(obj
) + ": Expected 64-bit integer");
999 auto *fromSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(fromIndex
));
1000 auto *toSym
= dyn_cast_or_null
<Defined
>(obj
->getSymbol(toIndex
));
1001 if (!fromSym
|| !toSym
)
1003 auto *from
= dyn_cast_or_null
<SectionChunk
>(fromSym
->getChunk());
1004 auto *to
= dyn_cast_or_null
<SectionChunk
>(toSym
->getChunk());
1006 config
->callGraphProfile
[{from
, to
}] += count
;
1012 static void markAddrsig(Symbol
*s
) {
1013 if (auto *d
= dyn_cast_or_null
<Defined
>(s
))
1014 if (SectionChunk
*c
= dyn_cast_or_null
<SectionChunk
>(d
->getChunk()))
1015 c
->keepUnique
= true;
1018 static void findKeepUniqueSections() {
1019 // Exported symbols could be address-significant in other executables or DSOs,
1020 // so we conservatively mark them as address-significant.
1021 for (Export
&r
: config
->exports
)
1024 // Visit the address-significance table in each object file and mark each
1025 // referenced symbol as address-significant.
1026 for (ObjFile
*obj
: ObjFile::instances
) {
1027 ArrayRef
<Symbol
*> syms
= obj
->getSymbols();
1028 if (obj
->addrsigSec
) {
1029 ArrayRef
<uint8_t> contents
;
1031 obj
->getCOFFObj()->getSectionContents(obj
->addrsigSec
, contents
));
1032 const uint8_t *cur
= contents
.begin();
1033 while (cur
!= contents
.end()) {
1036 uint64_t symIndex
= decodeULEB128(cur
, &size
, contents
.end(), &err
);
1038 fatal(toString(obj
) + ": could not decode addrsig section: " + err
);
1039 if (symIndex
>= syms
.size())
1040 fatal(toString(obj
) + ": invalid symbol index in addrsig section");
1041 markAddrsig(syms
[symIndex
]);
1045 // If an object file does not have an address-significance table,
1046 // conservatively mark all of its symbols as address-significant.
1047 for (Symbol
*s
: syms
)
1053 // link.exe replaces each %foo% in altPath with the contents of environment
1054 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1055 // of pdb's output path) and _EXT (expands to the extension of the output
1057 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1059 static void parsePDBAltPath(StringRef altPath
) {
1060 SmallString
<128> buf
;
1061 StringRef pdbBasename
=
1062 sys::path::filename(config
->pdbPath
, sys::path::Style::windows
);
1063 StringRef binaryExtension
=
1064 sys::path::extension(config
->outputFile
, sys::path::Style::windows
);
1065 if (!binaryExtension
.empty())
1066 binaryExtension
= binaryExtension
.substr(1); // %_EXT% does not include '.'.
1069 // +--------- cursor ('a...' might be the empty string).
1070 // | +----- firstMark
1071 // | | +- secondMark
1075 while (cursor
< altPath
.size()) {
1076 size_t firstMark
, secondMark
;
1077 if ((firstMark
= altPath
.find('%', cursor
)) == StringRef::npos
||
1078 (secondMark
= altPath
.find('%', firstMark
+ 1)) == StringRef::npos
) {
1079 // Didn't find another full fragment, treat rest of string as literal.
1080 buf
.append(altPath
.substr(cursor
));
1084 // Found a full fragment. Append text in front of first %, and interpret
1085 // text between first and second % as variable name.
1086 buf
.append(altPath
.substr(cursor
, firstMark
- cursor
));
1087 StringRef var
= altPath
.substr(firstMark
, secondMark
- firstMark
+ 1);
1088 if (var
.equals_lower("%_pdb%"))
1089 buf
.append(pdbBasename
);
1090 else if (var
.equals_lower("%_ext%"))
1091 buf
.append(binaryExtension
);
1093 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1094 var
+ " as literal");
1098 cursor
= secondMark
+ 1;
1101 config
->pdbAltPath
= buf
;
1104 /// Convert resource files and potentially merge input resource object
1105 /// trees into one resource tree.
1106 /// Call after ObjFile::Instances is complete.
1107 void LinkerDriver::convertResources() {
1108 std::vector
<ObjFile
*> resourceObjFiles
;
1110 for (ObjFile
*f
: ObjFile::instances
) {
1111 if (f
->isResourceObjFile())
1112 resourceObjFiles
.push_back(f
);
1115 if (!config
->mingw
&&
1116 (resourceObjFiles
.size() > 1 ||
1117 (resourceObjFiles
.size() == 1 && !resources
.empty()))) {
1118 error((!resources
.empty() ? "internal .obj file created from .res files"
1119 : toString(resourceObjFiles
[1])) +
1120 ": more than one resource obj file not allowed, already got " +
1121 toString(resourceObjFiles
.front()));
1125 if (resources
.empty() && resourceObjFiles
.size() <= 1) {
1126 // No resources to convert, and max one resource object file in
1127 // the input. Keep that preconverted resource section as is.
1128 for (ObjFile
*f
: resourceObjFiles
)
1129 f
->includeResourceChunks();
1132 ObjFile
*f
= make
<ObjFile
>(convertResToCOFF(resources
, resourceObjFiles
));
1134 f
->includeResourceChunks();
1137 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1138 // automatically exported by default. This behavior can be forced by the
1139 // -export-all-symbols option, so that it happens even when exports are
1140 // explicitly specified. The automatic behavior can be disabled using the
1141 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1142 // than MinGW in the case that nothing is explicitly exported.
1143 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList
&args
) {
1147 if (!args
.hasArg(OPT_export_all_symbols
)) {
1148 if (!config
->exports
.empty())
1150 if (args
.hasArg(OPT_exclude_all_symbols
))
1154 AutoExporter exporter
;
1156 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
1157 if (Optional
<StringRef
> path
= doFindFile(arg
->getValue()))
1158 exporter
.addWholeArchive(*path
);
1160 symtab
->forEachSymbol([&](Symbol
*s
) {
1161 auto *def
= dyn_cast
<Defined
>(s
);
1162 if (!exporter
.shouldExport(def
))
1166 e
.name
= def
->getName();
1168 if (Chunk
*c
= def
->getChunk())
1169 if (!(c
->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE
))
1171 config
->exports
.push_back(e
);
1175 // lld has a feature to create a tar file containing all input files as well as
1176 // all command line options, so that other people can run lld again with exactly
1177 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1179 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1180 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1181 // with Microsoft link.exe.
1182 Optional
<std::string
> getReproduceFile(const opt::InputArgList
&args
) {
1183 if (auto *arg
= args
.getLastArg(OPT_reproduce
))
1184 return std::string(arg
->getValue());
1186 if (auto *arg
= args
.getLastArg(OPT_linkrepro
)) {
1187 SmallString
<64> path
= StringRef(arg
->getValue());
1188 sys::path::append(path
, "repro.tar");
1189 return std::string(path
);
1192 // This is intentionally not guarded by OPT_lldignoreenv since writing
1193 // a repro tar file doesn't affect the main output.
1194 if (auto *path
= getenv("LLD_REPRODUCE"))
1195 return std::string(path
);
1200 void LinkerDriver::link(ArrayRef
<const char *> argsArr
) {
1201 ScopedTimer
rootTimer(Timer::root());
1204 InitializeAllTargetInfos();
1205 InitializeAllTargets();
1206 InitializeAllTargetMCs();
1207 InitializeAllAsmParsers();
1208 InitializeAllAsmPrinters();
1210 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1211 // We call our own implementation of lib.exe that understands bitcode files.
1212 if (argsArr
.size() > 1 && StringRef(argsArr
[1]).equals_lower("/lib")) {
1213 if (llvm::libDriverMain(argsArr
.slice(1)) != 0)
1214 fatal("lib failed");
1218 // Parse command line options.
1220 opt::InputArgList args
= parser
.parse(argsArr
);
1222 // Parse and evaluate -mllvm options.
1223 std::vector
<const char *> v
;
1224 v
.push_back("lld-link (LLVM option parsing)");
1225 for (auto *arg
: args
.filtered(OPT_mllvm
))
1226 v
.push_back(arg
->getValue());
1227 cl::ResetAllOptionOccurrences();
1228 cl::ParseCommandLineOptions(v
.size(), v
.data());
1230 // Handle /errorlimit early, because error() depends on it.
1231 if (auto *arg
= args
.getLastArg(OPT_errorlimit
)) {
1233 StringRef s
= arg
->getValue();
1234 if (s
.getAsInteger(10, n
))
1235 error(arg
->getSpelling() + " number expected, but got " + s
);
1236 errorHandler().errorLimit
= n
;
1240 if (args
.hasArg(OPT_help
)) {
1241 printHelp(argsArr
[0]);
1245 // /threads: takes a positive integer and provides the default value for
1246 // /opt:lldltojobs=.
1247 if (auto *arg
= args
.getLastArg(OPT_threads
)) {
1248 StringRef
v(arg
->getValue());
1249 unsigned threads
= 0;
1250 if (!llvm::to_integer(v
, threads
, 0) || threads
== 0)
1251 error(arg
->getSpelling() + ": expected a positive integer, but got '" +
1252 arg
->getValue() + "'");
1253 parallel::strategy
= hardware_concurrency(threads
);
1254 config
->thinLTOJobs
= v
.str();
1257 if (args
.hasArg(OPT_show_timing
))
1258 config
->showTiming
= true;
1260 config
->showSummary
= args
.hasArg(OPT_summary
);
1262 // Handle --version, which is an lld extension. This option is a bit odd
1263 // because it doesn't start with "/", but we deliberately chose "--" to
1264 // avoid conflict with /version and for compatibility with clang-cl.
1265 if (args
.hasArg(OPT_dash_dash_version
)) {
1266 lld::outs() << getLLDVersion() << "\n";
1270 // Handle /lldmingw early, since it can potentially affect how other
1271 // options are handled.
1272 config
->mingw
= args
.hasArg(OPT_lldmingw
);
1274 // Handle /linkrepro and /reproduce.
1275 if (Optional
<std::string
> path
= getReproduceFile(args
)) {
1276 Expected
<std::unique_ptr
<TarWriter
>> errOrWriter
=
1277 TarWriter::create(*path
, sys::path::stem(*path
));
1280 tar
= std::move(*errOrWriter
);
1282 error("/linkrepro: failed to open " + *path
+ ": " +
1283 toString(errOrWriter
.takeError()));
1287 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
1288 if (args
.hasArg(OPT_deffile
))
1289 config
->noEntry
= true;
1291 fatal("no input files");
1294 // Construct search path list.
1295 searchPaths
.push_back("");
1296 for (auto *arg
: args
.filtered(OPT_libpath
))
1297 searchPaths
.push_back(arg
->getValue());
1298 if (!args
.hasArg(OPT_lldignoreenv
))
1299 addLibSearchPaths();
1302 for (auto *arg
: args
.filtered(OPT_ignore
)) {
1303 SmallVector
<StringRef
, 8> vec
;
1304 StringRef(arg
->getValue()).split(vec
, ',');
1305 for (StringRef s
: vec
) {
1307 config
->warnMissingOrderSymbol
= false;
1308 else if (s
== "4099")
1309 config
->warnDebugInfoUnusable
= false;
1310 else if (s
== "4217")
1311 config
->warnLocallyDefinedImported
= false;
1312 else if (s
== "longsections")
1313 config
->warnLongSectionNames
= false;
1314 // Other warning numbers are ignored.
1319 if (auto *arg
= args
.getLastArg(OPT_out
))
1320 config
->outputFile
= arg
->getValue();
1323 if (args
.hasArg(OPT_verbose
))
1324 config
->verbose
= true;
1325 errorHandler().verbose
= config
->verbose
;
1327 // Handle /force or /force:unresolved
1328 if (args
.hasArg(OPT_force
, OPT_force_unresolved
))
1329 config
->forceUnresolved
= true;
1331 // Handle /force or /force:multiple
1332 if (args
.hasArg(OPT_force
, OPT_force_multiple
))
1333 config
->forceMultiple
= true;
1335 // Handle /force or /force:multipleres
1336 if (args
.hasArg(OPT_force
, OPT_force_multipleres
))
1337 config
->forceMultipleRes
= true;
1340 DebugKind debug
= parseDebugKind(args
);
1341 if (debug
== DebugKind::Full
|| debug
== DebugKind::Dwarf
||
1342 debug
== DebugKind::GHash
) {
1343 config
->debug
= true;
1344 config
->incremental
= true;
1348 config
->demangle
= args
.hasFlag(OPT_demangle
, OPT_demangle_no
);
1350 // Handle /debugtype
1351 config
->debugTypes
= parseDebugTypes(args
);
1353 // Handle /driver[:uponly|:wdm].
1354 config
->driverUponly
= args
.hasArg(OPT_driver_uponly
) ||
1355 args
.hasArg(OPT_driver_uponly_wdm
) ||
1356 args
.hasArg(OPT_driver_wdm_uponly
);
1357 config
->driverWdm
= args
.hasArg(OPT_driver_wdm
) ||
1358 args
.hasArg(OPT_driver_uponly_wdm
) ||
1359 args
.hasArg(OPT_driver_wdm_uponly
);
1361 config
->driverUponly
|| config
->driverWdm
|| args
.hasArg(OPT_driver
);
1364 bool shouldCreatePDB
=
1365 (debug
== DebugKind::Full
|| debug
== DebugKind::GHash
);
1366 if (shouldCreatePDB
) {
1367 if (auto *arg
= args
.getLastArg(OPT_pdb
))
1368 config
->pdbPath
= arg
->getValue();
1369 if (auto *arg
= args
.getLastArg(OPT_pdbaltpath
))
1370 config
->pdbAltPath
= arg
->getValue();
1371 if (args
.hasArg(OPT_natvis
))
1372 config
->natvisFiles
= args
.getAllArgValues(OPT_natvis
);
1373 if (args
.hasArg(OPT_pdbstream
)) {
1374 for (const StringRef value
: args
.getAllArgValues(OPT_pdbstream
)) {
1375 const std::pair
<StringRef
, StringRef
> nameFile
= value
.split("=");
1376 const StringRef name
= nameFile
.first
;
1377 const std::string file
= nameFile
.second
.str();
1378 config
->namedStreams
[name
] = file
;
1382 if (auto *arg
= args
.getLastArg(OPT_pdb_source_path
))
1383 config
->pdbSourcePath
= arg
->getValue();
1386 // Handle /pdbstripped
1387 if (args
.hasArg(OPT_pdbstripped
))
1388 warn("ignoring /pdbstripped flag, it is not yet supported");
1391 if (args
.hasArg(OPT_noentry
)) {
1392 if (args
.hasArg(OPT_dll
))
1393 config
->noEntry
= true;
1395 error("/noentry must be specified with /dll");
1399 if (args
.hasArg(OPT_dll
)) {
1401 config
->manifestID
= 2;
1404 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1405 // because we need to explicitly check whether that option or its inverse was
1406 // present in the argument list in order to handle /fixed.
1407 auto *dynamicBaseArg
= args
.getLastArg(OPT_dynamicbase
, OPT_dynamicbase_no
);
1408 if (dynamicBaseArg
&&
1409 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase_no
)
1410 config
->dynamicBase
= false;
1412 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1413 // default setting for any other project type.", but link.exe defaults to
1414 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1415 bool fixed
= args
.hasFlag(OPT_fixed
, OPT_fixed_no
, false);
1417 if (dynamicBaseArg
&&
1418 dynamicBaseArg
->getOption().getID() == OPT_dynamicbase
) {
1419 error("/fixed must not be specified with /dynamicbase");
1421 config
->relocatable
= false;
1422 config
->dynamicBase
= false;
1426 // Handle /appcontainer
1427 config
->appContainer
=
1428 args
.hasFlag(OPT_appcontainer
, OPT_appcontainer_no
, false);
1431 if (auto *arg
= args
.getLastArg(OPT_machine
)) {
1432 config
->machine
= getMachineType(arg
->getValue());
1433 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
)
1434 fatal(Twine("unknown /machine argument: ") + arg
->getValue());
1437 // Handle /nodefaultlib:<filename>
1438 for (auto *arg
: args
.filtered(OPT_nodefaultlib
))
1439 config
->noDefaultLibs
.insert(doFindLib(arg
->getValue()).lower());
1441 // Handle /nodefaultlib
1442 if (args
.hasArg(OPT_nodefaultlib_all
))
1443 config
->noDefaultLibAll
= true;
1446 if (auto *arg
= args
.getLastArg(OPT_base
))
1447 parseNumbers(arg
->getValue(), &config
->imageBase
);
1449 // Handle /filealign
1450 if (auto *arg
= args
.getLastArg(OPT_filealign
)) {
1451 parseNumbers(arg
->getValue(), &config
->fileAlign
);
1452 if (!isPowerOf2_64(config
->fileAlign
))
1453 error("/filealign: not a power of two: " + Twine(config
->fileAlign
));
1457 if (auto *arg
= args
.getLastArg(OPT_stack
))
1458 parseNumbers(arg
->getValue(), &config
->stackReserve
, &config
->stackCommit
);
1461 if (auto *arg
= args
.getLastArg(OPT_guard
))
1462 parseGuard(arg
->getValue());
1465 if (auto *arg
= args
.getLastArg(OPT_heap
))
1466 parseNumbers(arg
->getValue(), &config
->heapReserve
, &config
->heapCommit
);
1469 if (auto *arg
= args
.getLastArg(OPT_version
))
1470 parseVersion(arg
->getValue(), &config
->majorImageVersion
,
1471 &config
->minorImageVersion
);
1473 // Handle /subsystem
1474 if (auto *arg
= args
.getLastArg(OPT_subsystem
))
1475 parseSubsystem(arg
->getValue(), &config
->subsystem
,
1476 &config
->majorSubsystemVersion
,
1477 &config
->minorSubsystemVersion
);
1479 // Handle /osversion
1480 if (auto *arg
= args
.getLastArg(OPT_osversion
)) {
1481 parseVersion(arg
->getValue(), &config
->majorOSVersion
,
1482 &config
->minorOSVersion
);
1484 config
->majorOSVersion
= config
->majorSubsystemVersion
;
1485 config
->minorOSVersion
= config
->minorSubsystemVersion
;
1488 // Handle /timestamp
1489 if (llvm::opt::Arg
*arg
= args
.getLastArg(OPT_timestamp
, OPT_repro
)) {
1490 if (arg
->getOption().getID() == OPT_repro
) {
1491 config
->timestamp
= 0;
1492 config
->repro
= true;
1494 config
->repro
= false;
1495 StringRef
value(arg
->getValue());
1496 if (value
.getAsInteger(0, config
->timestamp
))
1497 fatal(Twine("invalid timestamp: ") + value
+
1498 ". Expected 32-bit integer");
1501 config
->repro
= false;
1502 config
->timestamp
= time(nullptr);
1505 // Handle /alternatename
1506 for (auto *arg
: args
.filtered(OPT_alternatename
))
1507 parseAlternateName(arg
->getValue());
1510 for (auto *arg
: args
.filtered(OPT_incl
))
1511 addUndefined(arg
->getValue());
1514 if (auto *arg
= args
.getLastArg(OPT_implib
))
1515 config
->implib
= arg
->getValue();
1518 bool doGC
= debug
== DebugKind::None
|| args
.hasArg(OPT_profile
);
1520 args
.hasArg(OPT_profile
) ? 0 : 1; // 0: off, 1: limited, 2: on
1521 unsigned tailMerge
= 1;
1522 bool ltoNewPM
= LLVM_ENABLE_NEW_PASS_MANAGER
;
1523 bool ltoDebugPM
= false;
1524 for (auto *arg
: args
.filtered(OPT_opt
)) {
1525 std::string str
= StringRef(arg
->getValue()).lower();
1526 SmallVector
<StringRef
, 1> vec
;
1527 StringRef(str
).split(vec
, ',');
1528 for (StringRef s
: vec
) {
1531 } else if (s
== "noref") {
1533 } else if (s
== "icf" || s
.startswith("icf=")) {
1535 } else if (s
== "noicf") {
1537 } else if (s
== "lldtailmerge") {
1539 } else if (s
== "nolldtailmerge") {
1541 } else if (s
== "ltonewpassmanager") {
1543 } else if (s
== "noltonewpassmanager") {
1545 } else if (s
== "ltodebugpassmanager") {
1547 } else if (s
== "noltodebugpassmanager") {
1549 } else if (s
.startswith("lldlto=")) {
1550 StringRef optLevel
= s
.substr(7);
1551 if (optLevel
.getAsInteger(10, config
->ltoo
) || config
->ltoo
> 3)
1552 error("/opt:lldlto: invalid optimization level: " + optLevel
);
1553 } else if (s
.startswith("lldltojobs=")) {
1554 StringRef jobs
= s
.substr(11);
1555 if (!get_threadpool_strategy(jobs
))
1556 error("/opt:lldltojobs: invalid job count: " + jobs
);
1557 config
->thinLTOJobs
= jobs
.str();
1558 } else if (s
.startswith("lldltopartitions=")) {
1559 StringRef n
= s
.substr(17);
1560 if (n
.getAsInteger(10, config
->ltoPartitions
) ||
1561 config
->ltoPartitions
== 0)
1562 error("/opt:lldltopartitions: invalid partition count: " + n
);
1563 } else if (s
!= "lbr" && s
!= "nolbr")
1564 error("/opt: unknown option: " + s
);
1568 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1570 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1571 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1572 // comdat readonly data.
1573 if (icfLevel
== 1 && !doGC
)
1575 config
->doGC
= doGC
;
1576 config
->doICF
= icfLevel
> 0;
1577 config
->tailMerge
= (tailMerge
== 1 && config
->doICF
) || tailMerge
== 2;
1578 config
->ltoNewPassManager
= ltoNewPM
;
1579 config
->ltoDebugPassManager
= ltoDebugPM
;
1581 // Handle /lldsavetemps
1582 if (args
.hasArg(OPT_lldsavetemps
))
1583 config
->saveTemps
= true;
1586 if (args
.hasArg(OPT_kill_at
))
1587 config
->killAt
= true;
1589 // Handle /lldltocache
1590 if (auto *arg
= args
.getLastArg(OPT_lldltocache
))
1591 config
->ltoCache
= arg
->getValue();
1593 // Handle /lldsavecachepolicy
1594 if (auto *arg
= args
.getLastArg(OPT_lldltocachepolicy
))
1595 config
->ltoCachePolicy
= CHECK(
1596 parseCachePruningPolicy(arg
->getValue()),
1597 Twine("/lldltocachepolicy: invalid cache policy: ") + arg
->getValue());
1599 // Handle /failifmismatch
1600 for (auto *arg
: args
.filtered(OPT_failifmismatch
))
1601 checkFailIfMismatch(arg
->getValue(), nullptr);
1604 for (auto *arg
: args
.filtered(OPT_merge
))
1605 parseMerge(arg
->getValue());
1607 // Add default section merging rules after user rules. User rules take
1608 // precedence, but we will emit a warning if there is a conflict.
1609 parseMerge(".idata=.rdata");
1610 parseMerge(".didat=.rdata");
1611 parseMerge(".edata=.rdata");
1612 parseMerge(".xdata=.rdata");
1613 parseMerge(".bss=.data");
1615 if (config
->mingw
) {
1616 parseMerge(".ctors=.rdata");
1617 parseMerge(".dtors=.rdata");
1618 parseMerge(".CRT=.rdata");
1622 for (auto *arg
: args
.filtered(OPT_section
))
1623 parseSection(arg
->getValue());
1626 if (auto *arg
= args
.getLastArg(OPT_align
)) {
1627 parseNumbers(arg
->getValue(), &config
->align
);
1628 if (!isPowerOf2_64(config
->align
))
1629 error("/align: not a power of two: " + StringRef(arg
->getValue()));
1630 if (!args
.hasArg(OPT_driver
))
1631 warn("/align specified without /driver; image may not run");
1634 // Handle /aligncomm
1635 for (auto *arg
: args
.filtered(OPT_aligncomm
))
1636 parseAligncomm(arg
->getValue());
1638 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1640 if (auto *arg
= args
.getLastArg(OPT_manifestdependency
)) {
1641 config
->manifestDependency
= arg
->getValue();
1642 config
->manifest
= Configuration::SideBySide
;
1645 // Handle /manifest and /manifest:
1646 if (auto *arg
= args
.getLastArg(OPT_manifest
, OPT_manifest_colon
)) {
1647 if (arg
->getOption().getID() == OPT_manifest
)
1648 config
->manifest
= Configuration::SideBySide
;
1650 parseManifest(arg
->getValue());
1653 // Handle /manifestuac
1654 if (auto *arg
= args
.getLastArg(OPT_manifestuac
))
1655 parseManifestUAC(arg
->getValue());
1657 // Handle /manifestfile
1658 if (auto *arg
= args
.getLastArg(OPT_manifestfile
))
1659 config
->manifestFile
= arg
->getValue();
1661 // Handle /manifestinput
1662 for (auto *arg
: args
.filtered(OPT_manifestinput
))
1663 config
->manifestInput
.push_back(arg
->getValue());
1665 if (!config
->manifestInput
.empty() &&
1666 config
->manifest
!= Configuration::Embed
) {
1667 fatal("/manifestinput: requires /manifest:embed");
1670 config
->thinLTOEmitImportsFiles
= args
.hasArg(OPT_thinlto_emit_imports_files
);
1671 config
->thinLTOIndexOnly
= args
.hasArg(OPT_thinlto_index_only
) ||
1672 args
.hasArg(OPT_thinlto_index_only_arg
);
1673 config
->thinLTOIndexOnlyArg
=
1674 args
.getLastArgValue(OPT_thinlto_index_only_arg
);
1675 config
->thinLTOPrefixReplace
=
1676 getOldNewOptions(args
, OPT_thinlto_prefix_replace
);
1677 config
->thinLTOObjectSuffixReplace
=
1678 getOldNewOptions(args
, OPT_thinlto_object_suffix_replace
);
1679 config
->ltoObjPath
= args
.getLastArgValue(OPT_lto_obj_path
);
1680 // Handle miscellaneous boolean flags.
1681 config
->allowBind
= args
.hasFlag(OPT_allowbind
, OPT_allowbind_no
, true);
1682 config
->allowIsolation
=
1683 args
.hasFlag(OPT_allowisolation
, OPT_allowisolation_no
, true);
1684 config
->incremental
=
1685 args
.hasFlag(OPT_incremental
, OPT_incremental_no
,
1686 !config
->doGC
&& !config
->doICF
&& !args
.hasArg(OPT_order
) &&
1687 !args
.hasArg(OPT_profile
));
1688 config
->integrityCheck
=
1689 args
.hasFlag(OPT_integritycheck
, OPT_integritycheck_no
, false);
1690 config
->cetCompat
= args
.hasFlag(OPT_cetcompat
, OPT_cetcompat_no
, false);
1691 config
->nxCompat
= args
.hasFlag(OPT_nxcompat
, OPT_nxcompat_no
, true);
1692 for (auto *arg
: args
.filtered(OPT_swaprun
))
1693 parseSwaprun(arg
->getValue());
1694 config
->terminalServerAware
=
1695 !config
->dll
&& args
.hasFlag(OPT_tsaware
, OPT_tsaware_no
, true);
1696 config
->debugDwarf
= debug
== DebugKind::Dwarf
;
1697 config
->debugGHashes
= debug
== DebugKind::GHash
;
1698 config
->debugSymtab
= debug
== DebugKind::Symtab
;
1699 config
->autoImport
=
1700 args
.hasFlag(OPT_auto_import
, OPT_auto_import_no
, config
->mingw
);
1701 config
->pseudoRelocs
= args
.hasFlag(
1702 OPT_runtime_pseudo_reloc
, OPT_runtime_pseudo_reloc_no
, config
->mingw
);
1703 config
->callGraphProfileSort
= args
.hasFlag(
1704 OPT_call_graph_profile_sort
, OPT_call_graph_profile_sort_no
, true);
1706 // Don't warn about long section names, such as .debug_info, for mingw or
1707 // when -debug:dwarf is requested.
1708 if (config
->mingw
|| config
->debugDwarf
)
1709 config
->warnLongSectionNames
= false;
1711 config
->lldmapFile
= getMapFile(args
, OPT_lldmap
, OPT_lldmap_file
);
1712 config
->mapFile
= getMapFile(args
, OPT_map
, OPT_map_file
);
1714 if (config
->lldmapFile
!= "" && config
->lldmapFile
== config
->mapFile
) {
1715 warn("/lldmap and /map have the same output file '" + config
->mapFile
+
1716 "'.\n>>> ignoring /lldmap");
1717 config
->lldmapFile
.clear();
1720 if (config
->incremental
&& args
.hasArg(OPT_profile
)) {
1721 warn("ignoring '/incremental' due to '/profile' specification");
1722 config
->incremental
= false;
1725 if (config
->incremental
&& args
.hasArg(OPT_order
)) {
1726 warn("ignoring '/incremental' due to '/order' specification");
1727 config
->incremental
= false;
1730 if (config
->incremental
&& config
->doGC
) {
1731 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1733 config
->incremental
= false;
1736 if (config
->incremental
&& config
->doICF
) {
1737 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1739 config
->incremental
= false;
1745 std::set
<sys::fs::UniqueID
> wholeArchives
;
1746 for (auto *arg
: args
.filtered(OPT_wholearchive_file
))
1747 if (Optional
<StringRef
> path
= doFindFile(arg
->getValue()))
1748 if (Optional
<sys::fs::UniqueID
> id
= getUniqueID(*path
))
1749 wholeArchives
.insert(*id
);
1751 // A predicate returning true if a given path is an argument for
1752 // /wholearchive:, or /wholearchive is enabled globally.
1753 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1754 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1755 auto isWholeArchive
= [&](StringRef path
) -> bool {
1756 if (args
.hasArg(OPT_wholearchive_flag
))
1758 if (Optional
<sys::fs::UniqueID
> id
= getUniqueID(path
))
1759 return wholeArchives
.count(*id
);
1763 // Create a list of input files. These can be given as OPT_INPUT options
1764 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1767 for (auto *arg
: args
) {
1768 switch (arg
->getOption().getID()) {
1771 error("stray " + arg
->getSpelling());
1776 error("nested " + arg
->getSpelling());
1779 case OPT_wholearchive_file
:
1780 if (Optional
<StringRef
> path
= findFile(arg
->getValue()))
1781 enqueuePath(*path
, true, inLib
);
1784 if (Optional
<StringRef
> path
= findFile(arg
->getValue()))
1785 enqueuePath(*path
, isWholeArchive(*path
), inLib
);
1788 // Ignore other options.
1793 // Process files specified as /defaultlib. These should be enequeued after
1794 // other files, which is why they are in a separate loop.
1795 for (auto *arg
: args
.filtered(OPT_defaultlib
))
1796 if (Optional
<StringRef
> path
= findLib(arg
->getValue()))
1797 enqueuePath(*path
, false, false);
1799 // Windows specific -- Create a resource file containing a manifest file.
1800 if (config
->manifest
== Configuration::Embed
)
1801 addBuffer(createManifestRes(), false, false);
1803 // Read all input files given via the command line.
1809 // We should have inferred a machine type by now from the input files, but if
1810 // not we assume x64.
1811 if (config
->machine
== IMAGE_FILE_MACHINE_UNKNOWN
) {
1812 warn("/machine is not specified. x64 is assumed");
1813 config
->machine
= AMD64
;
1815 config
->wordsize
= config
->is64() ? 8 : 4;
1817 // Handle /safeseh, x86 only, on by default, except for mingw.
1818 if (config
->machine
== I386
) {
1819 config
->safeSEH
= args
.hasFlag(OPT_safeseh
, OPT_safeseh_no
, !config
->mingw
);
1820 config
->noSEH
= args
.hasArg(OPT_noseh
);
1823 // Handle /functionpadmin
1824 for (auto *arg
: args
.filtered(OPT_functionpadmin
, OPT_functionpadmin_opt
))
1825 parseFunctionPadMin(arg
, config
->machine
);
1828 tar
->append("response.txt",
1829 createResponseFile(args
, filePaths
,
1830 ArrayRef
<StringRef
>(searchPaths
).slice(1)));
1832 // Handle /largeaddressaware
1833 config
->largeAddressAware
= args
.hasFlag(
1834 OPT_largeaddressaware
, OPT_largeaddressaware_no
, config
->is64());
1836 // Handle /highentropyva
1837 config
->highEntropyVA
=
1839 args
.hasFlag(OPT_highentropyva
, OPT_highentropyva_no
, true);
1841 if (!config
->dynamicBase
&&
1842 (config
->machine
== ARMNT
|| config
->machine
== ARM64
))
1843 error("/dynamicbase:no is not compatible with " +
1844 machineToStr(config
->machine
));
1847 for (auto *arg
: args
.filtered(OPT_export
)) {
1848 Export e
= parseExport(arg
->getValue());
1849 if (config
->machine
== I386
) {
1850 if (!isDecorated(e
.name
))
1851 e
.name
= saver
.save("_" + e
.name
);
1852 if (!e
.extName
.empty() && !isDecorated(e
.extName
))
1853 e
.extName
= saver
.save("_" + e
.extName
);
1855 config
->exports
.push_back(e
);
1859 if (auto *arg
= args
.getLastArg(OPT_deffile
)) {
1860 // parseModuleDefs mutates Config object.
1861 parseModuleDefs(arg
->getValue());
1864 // Handle generation of import library from a def file.
1865 if (!args
.hasArg(OPT_INPUT
, OPT_wholearchive_file
)) {
1867 createImportLibrary(/*asLib=*/true);
1871 // Windows specific -- if no /subsystem is given, we need to infer
1872 // that from entry point name. Must happen before /entry handling,
1873 // and after the early return when just writing an import library.
1874 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
) {
1875 config
->subsystem
= inferSubsystem();
1876 if (config
->subsystem
== IMAGE_SUBSYSTEM_UNKNOWN
)
1877 fatal("subsystem must be defined");
1880 // Handle /entry and /dll
1881 if (auto *arg
= args
.getLastArg(OPT_entry
)) {
1882 config
->entry
= addUndefined(mangle(arg
->getValue()));
1883 } else if (!config
->entry
&& !config
->noEntry
) {
1884 if (args
.hasArg(OPT_dll
)) {
1885 StringRef s
= (config
->machine
== I386
) ? "__DllMainCRTStartup@12"
1886 : "_DllMainCRTStartup";
1887 config
->entry
= addUndefined(s
);
1888 } else if (config
->driverWdm
) {
1889 // /driver:wdm implies /entry:_NtProcessStartup
1890 config
->entry
= addUndefined(mangle("_NtProcessStartup"));
1892 // Windows specific -- If entry point name is not given, we need to
1893 // infer that from user-defined entry name.
1894 StringRef s
= findDefaultEntry();
1896 fatal("entry point must be defined");
1897 config
->entry
= addUndefined(s
);
1898 log("Entry name inferred: " + s
);
1902 // Handle /delayload
1903 for (auto *arg
: args
.filtered(OPT_delayload
)) {
1904 config
->delayLoads
.insert(StringRef(arg
->getValue()).lower());
1905 if (config
->machine
== I386
) {
1906 config
->delayLoadHelper
= addUndefined("___delayLoadHelper2@8");
1908 config
->delayLoadHelper
= addUndefined("__delayLoadHelper2");
1912 // Set default image name if neither /out or /def set it.
1913 if (config
->outputFile
.empty()) {
1914 config
->outputFile
= getOutputPath(
1915 (*args
.filtered(OPT_INPUT
, OPT_wholearchive_file
).begin())->getValue());
1918 // Fail early if an output file is not writable.
1919 if (auto e
= tryCreateFile(config
->outputFile
)) {
1920 error("cannot open output file " + config
->outputFile
+ ": " + e
.message());
1924 if (shouldCreatePDB
) {
1925 // Put the PDB next to the image if no /pdb flag was passed.
1926 if (config
->pdbPath
.empty()) {
1927 config
->pdbPath
= config
->outputFile
;
1928 sys::path::replace_extension(config
->pdbPath
, ".pdb");
1931 // The embedded PDB path should be the absolute path to the PDB if no
1932 // /pdbaltpath flag was passed.
1933 if (config
->pdbAltPath
.empty()) {
1934 config
->pdbAltPath
= config
->pdbPath
;
1936 // It's important to make the path absolute and remove dots. This path
1937 // will eventually be written into the PE header, and certain Microsoft
1938 // tools won't work correctly if these assumptions are not held.
1939 sys::fs::make_absolute(config
->pdbAltPath
);
1940 sys::path::remove_dots(config
->pdbAltPath
);
1942 // Don't do this earlier, so that Config->OutputFile is ready.
1943 parsePDBAltPath(config
->pdbAltPath
);
1947 // Set default image base if /base is not given.
1948 if (config
->imageBase
== uint64_t(-1))
1949 config
->imageBase
= getDefaultImageBase();
1951 symtab
->addSynthetic(mangle("__ImageBase"), nullptr);
1952 if (config
->machine
== I386
) {
1953 symtab
->addAbsolute("___safe_se_handler_table", 0);
1954 symtab
->addAbsolute("___safe_se_handler_count", 0);
1957 symtab
->addAbsolute(mangle("__guard_fids_count"), 0);
1958 symtab
->addAbsolute(mangle("__guard_fids_table"), 0);
1959 symtab
->addAbsolute(mangle("__guard_flags"), 0);
1960 symtab
->addAbsolute(mangle("__guard_iat_count"), 0);
1961 symtab
->addAbsolute(mangle("__guard_iat_table"), 0);
1962 symtab
->addAbsolute(mangle("__guard_longjmp_count"), 0);
1963 symtab
->addAbsolute(mangle("__guard_longjmp_table"), 0);
1964 // Needed for MSVC 2017 15.5 CRT.
1965 symtab
->addAbsolute(mangle("__enclave_config"), 0);
1967 if (config
->pseudoRelocs
) {
1968 symtab
->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1969 symtab
->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1971 if (config
->mingw
) {
1972 symtab
->addAbsolute(mangle("__CTOR_LIST__"), 0);
1973 symtab
->addAbsolute(mangle("__DTOR_LIST__"), 0);
1976 // This code may add new undefined symbols to the link, which may enqueue more
1977 // symbol resolution tasks, so we need to continue executing tasks until we
1980 // Windows specific -- if entry point is not found,
1981 // search for its mangled names.
1983 mangleMaybe(config
->entry
);
1985 // Windows specific -- Make sure we resolve all dllexported symbols.
1986 for (Export
&e
: config
->exports
) {
1987 if (!e
.forwardTo
.empty())
1989 e
.sym
= addUndefined(e
.name
);
1991 e
.symbolName
= mangleMaybe(e
.sym
);
1994 // Add weak aliases. Weak aliases is a mechanism to give remaining
1995 // undefined symbols final chance to be resolved successfully.
1996 for (auto pair
: config
->alternateNames
) {
1997 StringRef from
= pair
.first
;
1998 StringRef to
= pair
.second
;
1999 Symbol
*sym
= symtab
->find(from
);
2002 if (auto *u
= dyn_cast
<Undefined
>(sym
))
2004 u
->weakAlias
= symtab
->addUndefined(to
);
2007 // If any inputs are bitcode files, the LTO code generator may create
2008 // references to library functions that are not explicit in the bitcode
2009 // file's symbol table. If any of those library functions are defined in a
2010 // bitcode file in an archive member, we need to arrange to use LTO to
2011 // compile those archive members by adding them to the link beforehand.
2012 if (!BitcodeFile::instances
.empty())
2013 for (auto *s
: lto::LTO::getRuntimeLibcallSymbols())
2014 symtab
->addLibcall(s
);
2016 // Windows specific -- if __load_config_used can be resolved, resolve it.
2017 if (symtab
->findUnderscore("_load_config_used"))
2018 addUndefined(mangle("_load_config_used"));
2021 if (args
.hasArg(OPT_include_optional
)) {
2022 // Handle /includeoptional
2023 for (auto *arg
: args
.filtered(OPT_include_optional
))
2024 if (dyn_cast_or_null
<LazyArchive
>(symtab
->find(arg
->getValue())))
2025 addUndefined(arg
->getValue());
2029 // Create wrapped symbols for -wrap option.
2030 std::vector
<WrappedSymbol
> wrapped
= addWrappedSymbols(args
);
2031 // Load more object files that might be needed for wrapped symbols.
2032 if (!wrapped
.empty())
2035 if (config
->autoImport
) {
2037 // Load any further object files that might be needed for doing automatic
2040 // For cases with no automatically imported symbols, this iterates once
2041 // over the symbol table and doesn't do anything.
2043 // For the normal case with a few automatically imported symbols, this
2044 // should only need to be run once, since each new object file imported
2045 // is an import library and wouldn't add any new undefined references,
2046 // but there's nothing stopping the __imp_ symbols from coming from a
2047 // normal object file as well (although that won't be used for the
2048 // actual autoimport later on). If this pass adds new undefined references,
2049 // we won't iterate further to resolve them.
2050 symtab
->loadMinGWAutomaticImports();
2054 // At this point, we should not have any symbols that cannot be resolved.
2055 // If we are going to do codegen for link-time optimization, check for
2056 // unresolvable symbols first, so we don't spend time generating code that
2057 // will fail to link anyway.
2058 if (!BitcodeFile::instances
.empty() && !config
->forceUnresolved
)
2059 symtab
->reportUnresolvable();
2063 // Do LTO by compiling bitcode input files to a set of native COFF files then
2064 // link those files (unless -thinlto-index-only was given, in which case we
2065 // resolve symbols and write indices, but don't generate native code or link).
2066 symtab
->addCombinedLTOObjects();
2068 // If -thinlto-index-only is given, we should create only "index
2069 // files" and not object files. Index file creation is already done
2070 // in addCombinedLTOObject, so we are done if that's the case.
2071 if (config
->thinLTOIndexOnly
)
2074 // If we generated native object files from bitcode files, this resolves
2075 // references to the symbols we use from them.
2078 // Apply symbol renames for -wrap.
2079 if (!wrapped
.empty())
2080 wrapSymbols(wrapped
);
2082 // Resolve remaining undefined symbols and warn about imported locals.
2083 symtab
->resolveRemainingUndefines();
2087 config
->hadExplicitExports
= !config
->exports
.empty();
2088 if (config
->mingw
) {
2089 // In MinGW, all symbols are automatically exported if no symbols
2090 // are chosen to be exported.
2091 maybeExportMinGWSymbols(args
);
2093 // Make sure the crtend.o object is the last object file. This object
2094 // file can contain terminating section chunks that need to be placed
2095 // last. GNU ld processes files and static libraries explicitly in the
2096 // order provided on the command line, while lld will pull in needed
2097 // files from static libraries only after the last object file on the
2099 for (auto i
= ObjFile::instances
.begin(), e
= ObjFile::instances
.end();
2102 if (isCrtend(file
->getName())) {
2103 ObjFile::instances
.erase(i
);
2104 ObjFile::instances
.push_back(file
);
2110 // Windows specific -- when we are creating a .dll file, we also
2111 // need to create a .lib file. In MinGW mode, we only do that when the
2112 // -implib option is given explicitly, for compatibility with GNU ld.
2113 if (!config
->exports
.empty() || config
->dll
) {
2115 if (!config
->mingw
|| !config
->implib
.empty())
2116 createImportLibrary(/*asLib=*/false);
2117 assignExportOrdinals();
2120 // Handle /output-def (MinGW specific).
2121 if (auto *arg
= args
.getLastArg(OPT_output_def
))
2122 writeDefFile(arg
->getValue());
2124 // Set extra alignment for .comm symbols
2125 for (auto pair
: config
->alignComm
) {
2126 StringRef name
= pair
.first
;
2127 uint32_t alignment
= pair
.second
;
2129 Symbol
*sym
= symtab
->find(name
);
2131 warn("/aligncomm symbol " + name
+ " not found");
2135 // If the symbol isn't common, it must have been replaced with a regular
2136 // symbol, which will carry its own alignment.
2137 auto *dc
= dyn_cast
<DefinedCommon
>(sym
);
2141 CommonChunk
*c
= dc
->getChunk();
2142 c
->setAlignment(std::max(c
->getAlignment(), alignment
));
2145 // Windows specific -- Create a side-by-side manifest file.
2146 if (config
->manifest
== Configuration::SideBySide
)
2147 createSideBySideManifest();
2149 // Handle /order. We want to do this at this moment because we
2150 // need a complete list of comdat sections to warn on nonexistent
2152 if (auto *arg
= args
.getLastArg(OPT_order
)) {
2153 if (args
.hasArg(OPT_call_graph_ordering_file
))
2154 error("/order and /call-graph-order-file may not be used together");
2155 parseOrderFile(arg
->getValue());
2156 config
->callGraphProfileSort
= false;
2159 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2160 if (config
->callGraphProfileSort
) {
2161 if (auto *arg
= args
.getLastArg(OPT_call_graph_ordering_file
)) {
2162 parseCallGraphFile(arg
->getValue());
2164 readCallGraphsFromObjectFiles();
2167 // Handle /print-symbol-order.
2168 if (auto *arg
= args
.getLastArg(OPT_print_symbol_order
))
2169 config
->printSymbolOrder
= arg
->getValue();
2171 // Identify unreferenced COMDAT sections.
2173 markLive(symtab
->getChunks());
2175 // Needs to happen after the last call to addFile().
2178 // Identify identical COMDAT sections to merge them.
2179 if (config
->doICF
) {
2180 findKeepUniqueSections();
2181 doICF(symtab
->getChunks());
2184 // Write the result.
2187 // Stop early so we can print the results.
2189 if (config
->showTiming
)
2190 Timer::root().print();