1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
15 #include "SymbolTable.h"
18 #include "lld/Driver/Driver.h"
19 #include "llvm/ADT/Optional.h"
20 #include "llvm/ADT/StringSwitch.h"
21 #include "llvm/LibDriver/LibDriver.h"
22 #include "llvm/Option/Arg.h"
23 #include "llvm/Option/ArgList.h"
24 #include "llvm/Option/Option.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/Path.h"
27 #include "llvm/Support/Process.h"
28 #include "llvm/Support/TarWriter.h"
29 #include "llvm/Support/TargetSelect.h"
30 #include "llvm/Support/raw_ostream.h"
35 // <future> depends on <eh.h> for __uncaught_exception.
42 using namespace llvm::COFF;
43 using llvm::sys::Process;
44 using llvm::sys::fs::OpenFlags;
45 using llvm::sys::fs::file_magic;
46 using llvm::sys::fs::identify_magic;
51 Configuration *Config;
54 BumpPtrAllocator BAlloc;
55 StringSaver Saver{BAlloc};
56 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
58 bool link(ArrayRef<const char *> Args) {
59 Config = make<Configuration>();
60 Driver = make<LinkerDriver>();
65 // Drop directory components and replace extension with ".exe" or ".dll".
66 static std::string getOutputPath(StringRef Path) {
67 auto P = Path.find_last_of("\\/");
68 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
69 const char* E = Config->DLL ? ".dll" : ".exe";
70 return (S.substr(0, S.rfind('.')) + E).str();
73 // ErrorOr is not default constructible, so it cannot be used as the type
74 // parameter of a future.
75 // FIXME: We could open the file in createFutureForFile and avoid needing to
76 // return an error here, but for the moment that would cost us a file descriptor
77 // (a limited resource on Windows) for the duration that the future is pending.
78 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
80 // Create a std::future that opens and maps a file using the best strategy for
82 static std::future<MBErrPair> createFutureForFile(std::string Path) {
84 // On Windows, file I/O is relatively slow so it is best to do this
86 auto Strategy = std::launch::async;
88 auto Strategy = std::launch::deferred;
90 return std::async(Strategy, [=]() {
91 auto MBOrErr = MemoryBuffer::getFile(Path);
93 return MBErrPair{nullptr, MBOrErr.getError()};
94 return MBErrPair{std::move(*MBOrErr), std::error_code()};
98 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
99 MemoryBufferRef MBRef = *MB;
100 OwningMBs.push_back(std::move(MB));
103 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
110 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
112 // File type is detected by contents, not by file extension.
113 file_magic Magic = identify_magic(MBRef.getBuffer());
114 if (Magic == file_magic::windows_resource) {
115 Resources.push_back(MBRef);
119 FilePaths.push_back(MBRef.getBufferIdentifier());
120 if (Magic == file_magic::archive)
121 return Symtab.addFile(make<ArchiveFile>(MBRef));
122 if (Magic == file_magic::bitcode)
123 return Symtab.addFile(make<BitcodeFile>(MBRef));
124 if (Magic == file_magic::coff_cl_gl_object)
125 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
126 "Recompile without /GL");
127 Symtab.addFile(make<ObjectFile>(MBRef));
130 void LinkerDriver::enqueuePath(StringRef Path) {
132 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
133 std::string PathStr = Path;
135 auto MBOrErr = Future->get();
137 fatal(MBOrErr.second, "could not open " + PathStr);
138 Driver->addBuffer(std::move(MBOrErr.first));
141 if (Config->OutputFile == "")
142 Config->OutputFile = getOutputPath(Path);
145 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
146 StringRef ParentName) {
147 file_magic Magic = identify_magic(MB.getBuffer());
148 if (Magic == file_magic::coff_import_library) {
149 Symtab.addFile(make<ImportFile>(MB));
154 if (Magic == file_magic::coff_object)
155 Obj = make<ObjectFile>(MB);
156 else if (Magic == file_magic::bitcode)
157 Obj = make<BitcodeFile>(MB);
159 fatal("unknown file type: " + MB.getBufferIdentifier());
161 Obj->ParentName = ParentName;
164 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
167 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
169 StringRef ParentName) {
170 if (!C.getParent()->isThin()) {
171 MemoryBufferRef MB = check(
172 C.getMemoryBufferRef(),
173 "could not get the buffer for the member defining symbol " + SymName);
174 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
178 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
179 check(C.getFullName(),
180 "could not get the filename for the member defining symbol " +
183 auto MBOrErr = Future->get();
185 fatal(MBOrErr.second,
186 "could not get the buffer for the member defining " + SymName);
187 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
192 static bool isDecorated(StringRef Sym) {
193 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
196 // Parses .drectve section contents and returns a list of files
197 // specified by /defaultlib.
198 void LinkerDriver::parseDirectives(StringRef S) {
199 opt::InputArgList Args = Parser.parse(S);
201 for (auto *Arg : Args) {
202 switch (Arg->getOption().getID()) {
203 case OPT_alternatename:
204 parseAlternateName(Arg->getValue());
207 if (Optional<StringRef> Path = findLib(Arg->getValue()))
211 Export E = parseExport(Arg->getValue());
213 Config->Exports.push_back(E);
216 case OPT_failifmismatch:
217 checkFailIfMismatch(Arg->getValue());
220 addUndefined(Arg->getValue());
223 parseMerge(Arg->getValue());
225 case OPT_nodefaultlib:
226 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
229 parseSection(Arg->getValue());
231 case OPT_editandcontinue:
234 case OPT_throwingnew:
237 fatal(Arg->getSpelling() + " is not allowed in .drectve");
242 // Find file from search paths. You can omit ".obj", this function takes
243 // care of that. Note that the returned path is not guaranteed to exist.
244 StringRef LinkerDriver::doFindFile(StringRef Filename) {
245 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
248 bool HasExt = (Filename.find('.') != StringRef::npos);
249 for (StringRef Dir : SearchPaths) {
250 SmallString<128> Path = Dir;
251 sys::path::append(Path, Filename);
252 if (sys::fs::exists(Path.str()))
253 return Saver.save(Path.str());
256 if (sys::fs::exists(Path.str()))
257 return Saver.save(Path.str());
263 // Resolves a file path. This never returns the same path
264 // (in that case, it returns None).
265 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
266 StringRef Path = doFindFile(Filename);
267 bool Seen = !VisitedFiles.insert(Path.lower()).second;
273 // Find library file from search path.
274 StringRef LinkerDriver::doFindLib(StringRef Filename) {
275 // Add ".lib" to Filename if that has no file extension.
276 bool HasExt = (Filename.find('.') != StringRef::npos);
278 Filename = Saver.save(Filename + ".lib");
279 return doFindFile(Filename);
282 // Resolves a library path. /nodefaultlib options are taken into
283 // consideration. This never returns the same path (in that case,
285 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
286 if (Config->NoDefaultLibAll)
288 if (!VisitedLibs.insert(Filename.lower()).second)
290 StringRef Path = doFindLib(Filename);
291 if (Config->NoDefaultLibs.count(Path))
293 if (!VisitedFiles.insert(Path.lower()).second)
298 // Parses LIB environment which contains a list of search paths.
299 void LinkerDriver::addLibSearchPaths() {
300 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
301 if (!EnvOpt.hasValue())
303 StringRef Env = Saver.save(*EnvOpt);
304 while (!Env.empty()) {
306 std::tie(Path, Env) = Env.split(';');
307 SearchPaths.push_back(Path);
311 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
312 SymbolBody *B = Symtab.addUndefined(Name);
313 Config->GCRoot.insert(B);
317 // Symbol names are mangled by appending "_" prefix on x86.
318 StringRef LinkerDriver::mangle(StringRef Sym) {
319 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
320 if (Config->Machine == I386)
321 return Saver.save("_" + Sym);
325 // Windows specific -- find default entry point name.
326 StringRef LinkerDriver::findDefaultEntry() {
327 // User-defined main functions and their corresponding entry points.
328 static const char *Entries[][2] = {
329 {"main", "mainCRTStartup"},
330 {"wmain", "wmainCRTStartup"},
331 {"WinMain", "WinMainCRTStartup"},
332 {"wWinMain", "wWinMainCRTStartup"},
334 for (auto E : Entries) {
335 StringRef Entry = Symtab.findMangle(mangle(E[0]));
336 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
342 WindowsSubsystem LinkerDriver::inferSubsystem() {
344 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
345 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
346 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
347 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
348 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
349 return IMAGE_SUBSYSTEM_UNKNOWN;
352 static uint64_t getDefaultImageBase() {
354 return Config->DLL ? 0x180000000 : 0x140000000;
355 return Config->DLL ? 0x10000000 : 0x400000;
358 static std::string createResponseFile(const opt::InputArgList &Args,
359 ArrayRef<StringRef> FilePaths,
360 ArrayRef<StringRef> SearchPaths) {
362 raw_svector_ostream OS(Data);
364 for (auto *Arg : Args) {
365 switch (Arg->getOption().getID()) {
372 OS << toString(Arg) << "\n";
376 for (StringRef Path : SearchPaths) {
377 std::string RelPath = relativeToRoot(Path);
378 OS << "/libpath:" << quote(RelPath) << "\n";
381 for (StringRef Path : FilePaths)
382 OS << quote(relativeToRoot(Path)) << "\n";
387 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
388 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
389 if (Args.hasArg(OPT_driver))
390 DebugTypes |= static_cast<unsigned>(DebugType::PData);
391 if (Args.hasArg(OPT_profile))
392 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
396 static unsigned parseDebugType(StringRef Arg) {
397 SmallVector<StringRef, 3> Types;
398 Arg.split(Types, ',', /*KeepEmpty=*/false);
400 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
401 for (StringRef Type : Types)
402 DebugTypes |= StringSwitch<unsigned>(Type.lower())
403 .Case("cv", static_cast<unsigned>(DebugType::CV))
404 .Case("pdata", static_cast<unsigned>(DebugType::PData))
405 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
409 static std::string getMapFile(const opt::InputArgList &Args) {
410 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
413 if (Arg->getOption().getID() == OPT_lldmap_file)
414 return Arg->getValue();
416 assert(Arg->getOption().getID() == OPT_lldmap);
417 StringRef OutFile = Config->OutputFile;
418 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
421 void LinkerDriver::enqueueTask(std::function<void()> Task) {
422 TaskQueue.push_back(std::move(Task));
425 bool LinkerDriver::run() {
426 bool DidWork = !TaskQueue.empty();
427 while (!TaskQueue.empty()) {
429 TaskQueue.pop_front();
434 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
435 // If the first command line argument is "/lib", link.exe acts like lib.exe.
436 // We call our own implementation of lib.exe that understands bitcode files.
437 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
438 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
444 InitializeAllTargetInfos();
445 InitializeAllTargets();
446 InitializeAllTargetMCs();
447 InitializeAllAsmParsers();
448 InitializeAllAsmPrinters();
449 InitializeAllDisassemblers();
451 // Parse command line options.
452 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
455 if (Args.hasArg(OPT_help)) {
456 printHelp(ArgsArr[0]);
460 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
461 SmallString<64> Path = StringRef(Arg->getValue());
462 sys::path::append(Path, "repro.tar");
464 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
465 TarWriter::create(Path, "repro");
468 Tar = std::move(*ErrOrWriter);
470 errs() << "/linkrepro: failed to open " << Path << ": "
471 << toString(ErrOrWriter.takeError()) << '\n';
475 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
476 fatal("no input files");
478 // Construct search path list.
479 SearchPaths.push_back("");
480 for (auto *Arg : Args.filtered(OPT_libpath))
481 SearchPaths.push_back(Arg->getValue());
485 if (auto *Arg = Args.getLastArg(OPT_out))
486 Config->OutputFile = Arg->getValue();
489 if (Args.hasArg(OPT_verbose))
490 Config->Verbose = true;
492 // Handle /force or /force:unresolved
493 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
494 Config->Force = true;
497 if (Args.hasArg(OPT_debug)) {
498 Config->Debug = true;
500 Args.hasArg(OPT_debugtype)
501 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
502 : getDefaultDebugType(Args);
505 // Create a dummy PDB file to satisfy build sytem rules.
506 if (auto *Arg = Args.getLastArg(OPT_pdb))
507 Config->PDBPath = Arg->getValue();
510 if (Args.hasArg(OPT_noentry)) {
511 if (!Args.hasArg(OPT_dll))
512 fatal("/noentry must be specified with /dll");
513 Config->NoEntry = true;
517 if (Args.hasArg(OPT_dll)) {
519 Config->ManifestID = 2;
523 if (Args.hasArg(OPT_fixed)) {
524 if (Args.hasArg(OPT_dynamicbase))
525 fatal("/fixed must not be specified with /dynamicbase");
526 Config->Relocatable = false;
527 Config->DynamicBase = false;
531 if (auto *Arg = Args.getLastArg(OPT_machine))
532 Config->Machine = getMachineType(Arg->getValue());
534 // Handle /nodefaultlib:<filename>
535 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
536 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
538 // Handle /nodefaultlib
539 if (Args.hasArg(OPT_nodefaultlib_all))
540 Config->NoDefaultLibAll = true;
543 if (auto *Arg = Args.getLastArg(OPT_base))
544 parseNumbers(Arg->getValue(), &Config->ImageBase);
547 if (auto *Arg = Args.getLastArg(OPT_stack))
548 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
551 if (auto *Arg = Args.getLastArg(OPT_heap))
552 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
555 if (auto *Arg = Args.getLastArg(OPT_version))
556 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
557 &Config->MinorImageVersion);
560 if (auto *Arg = Args.getLastArg(OPT_subsystem))
561 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
562 &Config->MinorOSVersion);
564 // Handle /alternatename
565 for (auto *Arg : Args.filtered(OPT_alternatename))
566 parseAlternateName(Arg->getValue());
569 for (auto *Arg : Args.filtered(OPT_incl))
570 addUndefined(Arg->getValue());
573 if (auto *Arg = Args.getLastArg(OPT_implib))
574 Config->Implib = Arg->getValue();
577 for (auto *Arg : Args.filtered(OPT_opt)) {
578 std::string Str = StringRef(Arg->getValue()).lower();
579 SmallVector<StringRef, 1> Vec;
580 StringRef(Str).split(Vec, ',');
581 for (StringRef S : Vec) {
583 Config->DoGC = false;
584 Config->DoICF = false;
587 if (S == "icf" || StringRef(S).startswith("icf=")) {
588 Config->DoICF = true;
592 Config->DoICF = false;
595 if (StringRef(S).startswith("lldlto=")) {
596 StringRef OptLevel = StringRef(S).substr(7);
597 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
598 Config->LTOOptLevel > 3)
599 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
602 if (StringRef(S).startswith("lldltojobs=")) {
603 StringRef Jobs = StringRef(S).substr(11);
604 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
605 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
608 if (S != "ref" && S != "lbr" && S != "nolbr")
609 fatal("/opt: unknown option: " + S);
613 // Handle /failifmismatch
614 for (auto *Arg : Args.filtered(OPT_failifmismatch))
615 checkFailIfMismatch(Arg->getValue());
618 for (auto *Arg : Args.filtered(OPT_merge))
619 parseMerge(Arg->getValue());
622 for (auto *Arg : Args.filtered(OPT_section))
623 parseSection(Arg->getValue());
626 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
627 parseManifest(Arg->getValue());
629 // Handle /manifestuac
630 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
631 parseManifestUAC(Arg->getValue());
633 // Handle /manifestdependency
634 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
635 Config->ManifestDependency = Arg->getValue();
637 // Handle /manifestfile
638 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
639 Config->ManifestFile = Arg->getValue();
641 // Handle /manifestinput
642 for (auto *Arg : Args.filtered(OPT_manifestinput))
643 Config->ManifestInput.push_back(Arg->getValue());
645 // Handle miscellaneous boolean flags.
646 if (Args.hasArg(OPT_allowbind_no))
647 Config->AllowBind = false;
648 if (Args.hasArg(OPT_allowisolation_no))
649 Config->AllowIsolation = false;
650 if (Args.hasArg(OPT_dynamicbase_no))
651 Config->DynamicBase = false;
652 if (Args.hasArg(OPT_nxcompat_no))
653 Config->NxCompat = false;
654 if (Args.hasArg(OPT_tsaware_no))
655 Config->TerminalServerAware = false;
656 if (Args.hasArg(OPT_nosymtab))
657 Config->WriteSymtab = false;
658 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
659 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
661 // Create a list of input files. Files can be given as arguments
662 // for /defaultlib option.
663 std::vector<MemoryBufferRef> MBs;
664 for (auto *Arg : Args.filtered(OPT_INPUT))
665 if (Optional<StringRef> Path = findFile(Arg->getValue()))
667 for (auto *Arg : Args.filtered(OPT_defaultlib))
668 if (Optional<StringRef> Path = findLib(Arg->getValue()))
671 // Windows specific -- Create a resource file containing a manifest file.
672 if (Config->Manifest == Configuration::Embed)
673 addBuffer(createManifestRes());
675 // Read all input files given via the command line.
678 // We should have inferred a machine type by now from the input files, but if
679 // not we assume x64.
680 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
681 errs() << "warning: /machine is not specified. x64 is assumed.\n";
682 Config->Machine = AMD64;
685 // Windows specific -- Input files can be Windows resource files (.res files).
686 // We invoke cvtres.exe to convert resource files to a regular COFF file
687 // then link the result file normally.
688 if (!Resources.empty())
689 addBuffer(convertResToCOFF(Resources));
692 Tar->append("response.txt",
693 createResponseFile(Args, FilePaths,
694 ArrayRef<StringRef>(SearchPaths).slice(1)));
696 // Handle /largeaddressaware
697 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
698 Config->LargeAddressAware = true;
700 // Handle /highentropyva
701 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
702 Config->HighEntropyVA = true;
704 // Handle /entry and /dll
705 if (auto *Arg = Args.getLastArg(OPT_entry)) {
706 Config->Entry = addUndefined(mangle(Arg->getValue()));
707 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
708 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
709 : "_DllMainCRTStartup";
710 Config->Entry = addUndefined(S);
711 } else if (!Config->NoEntry) {
712 // Windows specific -- If entry point name is not given, we need to
713 // infer that from user-defined entry name.
714 StringRef S = findDefaultEntry();
716 fatal("entry point must be defined");
717 Config->Entry = addUndefined(S);
719 outs() << "Entry name inferred: " << S << "\n";
723 for (auto *Arg : Args.filtered(OPT_export)) {
724 Export E = parseExport(Arg->getValue());
725 if (Config->Machine == I386) {
726 if (!isDecorated(E.Name))
727 E.Name = Saver.save("_" + E.Name);
728 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
729 E.ExtName = Saver.save("_" + E.ExtName);
731 Config->Exports.push_back(E);
735 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
736 // parseModuleDefs mutates Config object.
738 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
739 Twine("could not open ") + Arg->getValue())));
743 for (auto *Arg : Args.filtered(OPT_delayload)) {
744 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
745 if (Config->Machine == I386) {
746 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
748 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
752 // Set default image base if /base is not given.
753 if (Config->ImageBase == uint64_t(-1))
754 Config->ImageBase = getDefaultImageBase();
756 Symtab.addRelative(mangle("__ImageBase"), 0);
757 if (Config->Machine == I386) {
758 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
759 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
762 // We do not support /guard:cf (control flow protection) yet.
763 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
764 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
765 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
766 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
768 // This code may add new undefined symbols to the link, which may enqueue more
769 // symbol resolution tasks, so we need to continue executing tasks until we
772 // Windows specific -- if entry point is not found,
773 // search for its mangled names.
775 Symtab.mangleMaybe(Config->Entry);
777 // Windows specific -- Make sure we resolve all dllexported symbols.
778 for (Export &E : Config->Exports) {
779 if (!E.ForwardTo.empty())
781 E.Sym = addUndefined(E.Name);
783 Symtab.mangleMaybe(E.Sym);
786 // Add weak aliases. Weak aliases is a mechanism to give remaining
787 // undefined symbols final chance to be resolved successfully.
788 for (auto Pair : Config->AlternateNames) {
789 StringRef From = Pair.first;
790 StringRef To = Pair.second;
791 Symbol *Sym = Symtab.find(From);
794 if (auto *U = dyn_cast<Undefined>(Sym->body()))
796 U->WeakAlias = Symtab.addUndefined(To);
799 // Windows specific -- if __load_config_used can be resolved, resolve it.
800 if (Symtab.findUnderscore("_load_config_used"))
801 addUndefined(mangle("_load_config_used"));
804 // Do LTO by compiling bitcode input files to a set of native COFF files then
806 Symtab.addCombinedLTOObjects();
809 // Make sure we have resolved all symbols.
810 Symtab.reportRemainingUndefines();
812 // Windows specific -- if no /subsystem is given, we need to infer
813 // that from entry point name.
814 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
815 Config->Subsystem = inferSubsystem();
816 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
817 fatal("subsystem must be defined");
821 if (Args.hasArg(OPT_safeseh))
822 for (ObjectFile *File : Symtab.ObjectFiles)
823 if (!File->SEHCompat)
824 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
826 // Windows specific -- when we are creating a .dll file, we also
827 // need to create a .lib file.
828 if (!Config->Exports.empty() || Config->DLL) {
830 writeImportLibrary();
831 assignExportOrdinals();
834 // Windows specific -- Create a side-by-side manifest file.
835 if (Config->Manifest == Configuration::SideBySide)
836 createSideBySideManifest();
838 // Identify unreferenced COMDAT sections.
840 markLive(Symtab.getChunks());
842 // Identify identical COMDAT sections to merge them.
844 doICF(Symtab.getChunks());
847 writeResult(&Symtab);
849 // Create a symbol map file containing symbol VAs and their names
850 // to help debugging.
851 std::string MapFile = getMapFile(Args);
852 if (!MapFile.empty()) {
854 raw_fd_ostream Out(MapFile, EC, OpenFlags::F_Text);
856 fatal(EC, "could not create the symbol map " + MapFile);
857 Symtab.printMap(Out);
860 // Call exit to avoid calling destructors.