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/TargetSelect.h"
29 #include "llvm/Support/raw_ostream.h"
34 // <future> depends on <eh.h> for __uncaught_exception.
41 using namespace llvm::COFF;
42 using llvm::sys::Process;
43 using llvm::sys::fs::OpenFlags;
44 using llvm::sys::fs::file_magic;
45 using llvm::sys::fs::identify_magic;
50 Configuration *Config;
53 BumpPtrAllocator BAlloc;
54 StringSaver Saver{BAlloc};
55 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
57 bool link(ArrayRef<const char *> Args) {
58 Config = make<Configuration>();
59 Driver = make<LinkerDriver>();
64 // Drop directory components and replace extension with ".exe" or ".dll".
65 static std::string getOutputPath(StringRef Path) {
66 auto P = Path.find_last_of("\\/");
67 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
68 const char* E = Config->DLL ? ".dll" : ".exe";
69 return (S.substr(0, S.rfind('.')) + E).str();
72 // ErrorOr is not default constructible, so it cannot be used as the type
73 // parameter of a future.
74 // FIXME: We could open the file in createFutureForFile and avoid needing to
75 // return an error here, but for the moment that would cost us a file descriptor
76 // (a limited resource on Windows) for the duration that the future is pending.
77 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
79 // Create a std::future that opens and maps a file using the best strategy for
81 static std::future<MBErrPair> createFutureForFile(std::string Path) {
83 // On Windows, file I/O is relatively slow so it is best to do this
85 auto Strategy = std::launch::async;
87 auto Strategy = std::launch::deferred;
89 return std::async(Strategy, [=]() {
90 auto MBOrErr = MemoryBuffer::getFile(Path);
92 return MBErrPair{nullptr, MBOrErr.getError()};
93 return MBErrPair{std::move(*MBOrErr), std::error_code()};
97 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
98 MemoryBufferRef MBRef = *MB;
99 OwningMBs.push_back(std::move(MB));
102 Driver->Cpio->append(relativeToRoot(MBRef.getBufferIdentifier()),
108 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
109 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
111 // File type is detected by contents, not by file extension.
112 file_magic Magic = identify_magic(MBRef.getBuffer());
113 if (Magic == file_magic::windows_resource) {
114 Resources.push_back(MBRef);
118 FilePaths.push_back(MBRef.getBufferIdentifier());
119 if (Magic == file_magic::archive)
120 return Symtab.addFile(make<ArchiveFile>(MBRef));
121 if (Magic == file_magic::bitcode)
122 return Symtab.addFile(make<BitcodeFile>(MBRef));
123 if (Magic == file_magic::coff_cl_gl_object)
124 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
125 "Recompile without /GL");
126 Symtab.addFile(make<ObjectFile>(MBRef));
129 void LinkerDriver::enqueuePath(StringRef Path) {
131 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
132 std::string PathStr = Path;
134 auto MBOrErr = Future->get();
136 fatal(MBOrErr.second, "could not open " + PathStr);
137 Driver->addBuffer(std::move(MBOrErr.first));
140 if (Config->OutputFile == "")
141 Config->OutputFile = getOutputPath(Path);
144 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
145 StringRef ParentName) {
146 file_magic Magic = identify_magic(MB.getBuffer());
147 if (Magic == file_magic::coff_import_library) {
148 Symtab.addFile(make<ImportFile>(MB));
153 if (Magic == file_magic::coff_object)
154 Obj = make<ObjectFile>(MB);
155 else if (Magic == file_magic::bitcode)
156 Obj = make<BitcodeFile>(MB);
158 fatal("unknown file type: " + MB.getBufferIdentifier());
160 Obj->ParentName = ParentName;
163 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
166 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
168 StringRef ParentName) {
169 if (!C.getParent()->isThin()) {
170 MemoryBufferRef MB = check(
171 C.getMemoryBufferRef(),
172 "could not get the buffer for the member defining symbol " + SymName);
173 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
177 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
178 check(C.getFullName(),
179 "could not get the filename for the member defining symbol " +
182 auto MBOrErr = Future->get();
184 fatal(MBOrErr.second,
185 "could not get the buffer for the member defining " + SymName);
186 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
191 static bool isDecorated(StringRef Sym) {
192 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
195 // Parses .drectve section contents and returns a list of files
196 // specified by /defaultlib.
197 void LinkerDriver::parseDirectives(StringRef S) {
198 opt::InputArgList Args = Parser.parse(S);
200 for (auto *Arg : Args) {
201 switch (Arg->getOption().getID()) {
202 case OPT_alternatename:
203 parseAlternateName(Arg->getValue());
206 if (Optional<StringRef> Path = findLib(Arg->getValue()))
210 Export E = parseExport(Arg->getValue());
212 Config->Exports.push_back(E);
215 case OPT_failifmismatch:
216 checkFailIfMismatch(Arg->getValue());
219 addUndefined(Arg->getValue());
222 parseMerge(Arg->getValue());
224 case OPT_nodefaultlib:
225 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
228 parseSection(Arg->getValue());
230 case OPT_editandcontinue:
233 case OPT_throwingnew:
236 fatal(Arg->getSpelling() + " is not allowed in .drectve");
241 // Find file from search paths. You can omit ".obj", this function takes
242 // care of that. Note that the returned path is not guaranteed to exist.
243 StringRef LinkerDriver::doFindFile(StringRef Filename) {
244 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
247 bool HasExt = (Filename.find('.') != StringRef::npos);
248 for (StringRef Dir : SearchPaths) {
249 SmallString<128> Path = Dir;
250 sys::path::append(Path, Filename);
251 if (sys::fs::exists(Path.str()))
252 return Saver.save(Path.str());
255 if (sys::fs::exists(Path.str()))
256 return Saver.save(Path.str());
262 // Resolves a file path. This never returns the same path
263 // (in that case, it returns None).
264 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
265 StringRef Path = doFindFile(Filename);
266 bool Seen = !VisitedFiles.insert(Path.lower()).second;
272 // Find library file from search path.
273 StringRef LinkerDriver::doFindLib(StringRef Filename) {
274 // Add ".lib" to Filename if that has no file extension.
275 bool HasExt = (Filename.find('.') != StringRef::npos);
277 Filename = Saver.save(Filename + ".lib");
278 return doFindFile(Filename);
281 // Resolves a library path. /nodefaultlib options are taken into
282 // consideration. This never returns the same path (in that case,
284 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
285 if (Config->NoDefaultLibAll)
287 if (!VisitedLibs.insert(Filename.lower()).second)
289 StringRef Path = doFindLib(Filename);
290 if (Config->NoDefaultLibs.count(Path))
292 if (!VisitedFiles.insert(Path.lower()).second)
297 // Parses LIB environment which contains a list of search paths.
298 void LinkerDriver::addLibSearchPaths() {
299 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
300 if (!EnvOpt.hasValue())
302 StringRef Env = Saver.save(*EnvOpt);
303 while (!Env.empty()) {
305 std::tie(Path, Env) = Env.split(';');
306 SearchPaths.push_back(Path);
310 SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
311 SymbolBody *B = Symtab.addUndefined(Name);
312 Config->GCRoot.insert(B);
316 // Symbol names are mangled by appending "_" prefix on x86.
317 StringRef LinkerDriver::mangle(StringRef Sym) {
318 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
319 if (Config->Machine == I386)
320 return Saver.save("_" + Sym);
324 // Windows specific -- find default entry point name.
325 StringRef LinkerDriver::findDefaultEntry() {
326 // User-defined main functions and their corresponding entry points.
327 static const char *Entries[][2] = {
328 {"main", "mainCRTStartup"},
329 {"wmain", "wmainCRTStartup"},
330 {"WinMain", "WinMainCRTStartup"},
331 {"wWinMain", "wWinMainCRTStartup"},
333 for (auto E : Entries) {
334 StringRef Entry = Symtab.findMangle(mangle(E[0]));
335 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
341 WindowsSubsystem LinkerDriver::inferSubsystem() {
343 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
344 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
345 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
346 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
347 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
348 return IMAGE_SUBSYSTEM_UNKNOWN;
351 static uint64_t getDefaultImageBase() {
353 return Config->DLL ? 0x180000000 : 0x140000000;
354 return Config->DLL ? 0x10000000 : 0x400000;
357 static std::string createResponseFile(const opt::InputArgList &Args,
358 ArrayRef<StringRef> FilePaths,
359 ArrayRef<StringRef> SearchPaths) {
361 raw_svector_ostream OS(Data);
363 for (auto *Arg : Args) {
364 switch (Arg->getOption().getID()) {
371 OS << stringize(Arg) << "\n";
375 for (StringRef Path : SearchPaths) {
376 std::string RelPath = relativeToRoot(Path);
377 OS << "/libpath:" << quote(RelPath) << "\n";
380 for (StringRef Path : FilePaths)
381 OS << quote(relativeToRoot(Path)) << "\n";
386 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
387 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
388 if (Args.hasArg(OPT_driver))
389 DebugTypes |= static_cast<unsigned>(DebugType::PData);
390 if (Args.hasArg(OPT_profile))
391 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
395 static unsigned parseDebugType(StringRef Arg) {
396 SmallVector<StringRef, 3> Types;
397 Arg.split(Types, ',', /*KeepEmpty=*/false);
399 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
400 for (StringRef Type : Types)
401 DebugTypes |= StringSwitch<unsigned>(Type.lower())
402 .Case("cv", static_cast<unsigned>(DebugType::CV))
403 .Case("pdata", static_cast<unsigned>(DebugType::PData))
404 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
408 static std::string getMapFile(const opt::InputArgList &Args) {
409 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
412 if (Arg->getOption().getID() == OPT_lldmap_file)
413 return Arg->getValue();
415 assert(Arg->getOption().getID() == OPT_lldmap);
416 StringRef OutFile = Config->OutputFile;
417 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
420 void LinkerDriver::enqueueTask(std::function<void()> Task) {
421 TaskQueue.push_back(std::move(Task));
424 bool LinkerDriver::run() {
425 bool DidWork = !TaskQueue.empty();
426 while (!TaskQueue.empty()) {
428 TaskQueue.pop_front();
433 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
434 // If the first command line argument is "/lib", link.exe acts like lib.exe.
435 // We call our own implementation of lib.exe that understands bitcode files.
436 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
437 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
443 InitializeAllTargetInfos();
444 InitializeAllTargets();
445 InitializeAllTargetMCs();
446 InitializeAllAsmParsers();
447 InitializeAllAsmPrinters();
448 InitializeAllDisassemblers();
450 // Parse command line options.
451 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
454 if (Args.hasArg(OPT_help)) {
455 printHelp(ArgsArr[0]);
459 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
460 SmallString<64> Path = StringRef(Arg->getValue());
461 sys::path::append(Path, "repro");
462 ErrorOr<CpioFile *> F = CpioFile::create(Path);
466 errs() << "/linkrepro: failed to open " << Path
467 << ".cpio: " << F.getError().message() << '\n';
470 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
471 fatal("no input files");
473 // Construct search path list.
474 SearchPaths.push_back("");
475 for (auto *Arg : Args.filtered(OPT_libpath))
476 SearchPaths.push_back(Arg->getValue());
480 if (auto *Arg = Args.getLastArg(OPT_out))
481 Config->OutputFile = Arg->getValue();
484 if (Args.hasArg(OPT_verbose))
485 Config->Verbose = true;
487 // Handle /force or /force:unresolved
488 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
489 Config->Force = true;
492 if (Args.hasArg(OPT_debug)) {
493 Config->Debug = true;
495 Args.hasArg(OPT_debugtype)
496 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
497 : getDefaultDebugType(Args);
500 // Create a dummy PDB file to satisfy build sytem rules.
501 if (auto *Arg = Args.getLastArg(OPT_pdb))
502 Config->PDBPath = Arg->getValue();
505 if (Args.hasArg(OPT_noentry)) {
506 if (!Args.hasArg(OPT_dll))
507 fatal("/noentry must be specified with /dll");
508 Config->NoEntry = true;
512 if (Args.hasArg(OPT_dll)) {
514 Config->ManifestID = 2;
518 if (Args.hasArg(OPT_fixed)) {
519 if (Args.hasArg(OPT_dynamicbase))
520 fatal("/fixed must not be specified with /dynamicbase");
521 Config->Relocatable = false;
522 Config->DynamicBase = false;
526 if (auto *Arg = Args.getLastArg(OPT_machine))
527 Config->Machine = getMachineType(Arg->getValue());
529 // Handle /nodefaultlib:<filename>
530 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
531 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
533 // Handle /nodefaultlib
534 if (Args.hasArg(OPT_nodefaultlib_all))
535 Config->NoDefaultLibAll = true;
538 if (auto *Arg = Args.getLastArg(OPT_base))
539 parseNumbers(Arg->getValue(), &Config->ImageBase);
542 if (auto *Arg = Args.getLastArg(OPT_stack))
543 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
546 if (auto *Arg = Args.getLastArg(OPT_heap))
547 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
550 if (auto *Arg = Args.getLastArg(OPT_version))
551 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
552 &Config->MinorImageVersion);
555 if (auto *Arg = Args.getLastArg(OPT_subsystem))
556 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
557 &Config->MinorOSVersion);
559 // Handle /alternatename
560 for (auto *Arg : Args.filtered(OPT_alternatename))
561 parseAlternateName(Arg->getValue());
564 for (auto *Arg : Args.filtered(OPT_incl))
565 addUndefined(Arg->getValue());
568 if (auto *Arg = Args.getLastArg(OPT_implib))
569 Config->Implib = Arg->getValue();
572 for (auto *Arg : Args.filtered(OPT_opt)) {
573 std::string Str = StringRef(Arg->getValue()).lower();
574 SmallVector<StringRef, 1> Vec;
575 StringRef(Str).split(Vec, ',');
576 for (StringRef S : Vec) {
578 Config->DoGC = false;
579 Config->DoICF = false;
582 if (S == "icf" || StringRef(S).startswith("icf=")) {
583 Config->DoICF = true;
587 Config->DoICF = false;
590 if (StringRef(S).startswith("lldlto=")) {
591 StringRef OptLevel = StringRef(S).substr(7);
592 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
593 Config->LTOOptLevel > 3)
594 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
597 if (StringRef(S).startswith("lldltojobs=")) {
598 StringRef Jobs = StringRef(S).substr(11);
599 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
600 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
603 if (S != "ref" && S != "lbr" && S != "nolbr")
604 fatal("/opt: unknown option: " + S);
608 // Handle /failifmismatch
609 for (auto *Arg : Args.filtered(OPT_failifmismatch))
610 checkFailIfMismatch(Arg->getValue());
613 for (auto *Arg : Args.filtered(OPT_merge))
614 parseMerge(Arg->getValue());
617 for (auto *Arg : Args.filtered(OPT_section))
618 parseSection(Arg->getValue());
621 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
622 parseManifest(Arg->getValue());
624 // Handle /manifestuac
625 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
626 parseManifestUAC(Arg->getValue());
628 // Handle /manifestdependency
629 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
630 Config->ManifestDependency = Arg->getValue();
632 // Handle /manifestfile
633 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
634 Config->ManifestFile = Arg->getValue();
636 // Handle /manifestinput
637 for (auto *Arg : Args.filtered(OPT_manifestinput))
638 Config->ManifestInput.push_back(Arg->getValue());
640 // Handle miscellaneous boolean flags.
641 if (Args.hasArg(OPT_allowbind_no))
642 Config->AllowBind = false;
643 if (Args.hasArg(OPT_allowisolation_no))
644 Config->AllowIsolation = false;
645 if (Args.hasArg(OPT_dynamicbase_no))
646 Config->DynamicBase = false;
647 if (Args.hasArg(OPT_nxcompat_no))
648 Config->NxCompat = false;
649 if (Args.hasArg(OPT_tsaware_no))
650 Config->TerminalServerAware = false;
651 if (Args.hasArg(OPT_nosymtab))
652 Config->WriteSymtab = false;
653 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
654 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
656 // Create a list of input files. Files can be given as arguments
657 // for /defaultlib option.
658 std::vector<MemoryBufferRef> MBs;
659 for (auto *Arg : Args.filtered(OPT_INPUT))
660 if (Optional<StringRef> Path = findFile(Arg->getValue()))
662 for (auto *Arg : Args.filtered(OPT_defaultlib))
663 if (Optional<StringRef> Path = findLib(Arg->getValue()))
666 // Windows specific -- Create a resource file containing a manifest file.
667 if (Config->Manifest == Configuration::Embed)
668 addBuffer(createManifestRes());
670 // Read all input files given via the command line.
673 // We should have inferred a machine type by now from the input files, but if
674 // not we assume x64.
675 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
676 errs() << "warning: /machine is not specified. x64 is assumed.\n";
677 Config->Machine = AMD64;
680 // Windows specific -- Input files can be Windows resource files (.res files).
681 // We invoke cvtres.exe to convert resource files to a regular COFF file
682 // then link the result file normally.
683 if (!Resources.empty())
684 addBuffer(convertResToCOFF(Resources));
687 Cpio->append("response.txt",
688 createResponseFile(Args, FilePaths,
689 ArrayRef<StringRef>(SearchPaths).slice(1)));
691 // Handle /largeaddressaware
692 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
693 Config->LargeAddressAware = true;
695 // Handle /highentropyva
696 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
697 Config->HighEntropyVA = true;
699 // Handle /entry and /dll
700 if (auto *Arg = Args.getLastArg(OPT_entry)) {
701 Config->Entry = addUndefined(mangle(Arg->getValue()));
702 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
703 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
704 : "_DllMainCRTStartup";
705 Config->Entry = addUndefined(S);
706 } else if (!Config->NoEntry) {
707 // Windows specific -- If entry point name is not given, we need to
708 // infer that from user-defined entry name.
709 StringRef S = findDefaultEntry();
711 fatal("entry point must be defined");
712 Config->Entry = addUndefined(S);
714 outs() << "Entry name inferred: " << S << "\n";
718 for (auto *Arg : Args.filtered(OPT_export)) {
719 Export E = parseExport(Arg->getValue());
720 if (Config->Machine == I386) {
721 if (!isDecorated(E.Name))
722 E.Name = Saver.save("_" + E.Name);
723 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
724 E.ExtName = Saver.save("_" + E.ExtName);
726 Config->Exports.push_back(E);
730 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
731 // parseModuleDefs mutates Config object.
733 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
734 Twine("could not open ") + Arg->getValue())));
738 for (auto *Arg : Args.filtered(OPT_delayload)) {
739 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
740 if (Config->Machine == I386) {
741 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
743 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
747 // Set default image base if /base is not given.
748 if (Config->ImageBase == uint64_t(-1))
749 Config->ImageBase = getDefaultImageBase();
751 Symtab.addRelative(mangle("__ImageBase"), 0);
752 if (Config->Machine == I386) {
753 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
754 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
757 // We do not support /guard:cf (control flow protection) yet.
758 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
759 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
760 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
761 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
763 // This code may add new undefined symbols to the link, which may enqueue more
764 // symbol resolution tasks, so we need to continue executing tasks until we
767 // Windows specific -- if entry point is not found,
768 // search for its mangled names.
770 Symtab.mangleMaybe(Config->Entry);
772 // Windows specific -- Make sure we resolve all dllexported symbols.
773 for (Export &E : Config->Exports) {
774 if (!E.ForwardTo.empty())
776 E.Sym = addUndefined(E.Name);
778 Symtab.mangleMaybe(E.Sym);
781 // Add weak aliases. Weak aliases is a mechanism to give remaining
782 // undefined symbols final chance to be resolved successfully.
783 for (auto Pair : Config->AlternateNames) {
784 StringRef From = Pair.first;
785 StringRef To = Pair.second;
786 Symbol *Sym = Symtab.find(From);
789 if (auto *U = dyn_cast<Undefined>(Sym->body()))
791 U->WeakAlias = Symtab.addUndefined(To);
794 // Windows specific -- if __load_config_used can be resolved, resolve it.
795 if (Symtab.findUnderscore("_load_config_used"))
796 addUndefined(mangle("_load_config_used"));
799 // Do LTO by compiling bitcode input files to a set of native COFF files then
801 Symtab.addCombinedLTOObjects();
804 // Make sure we have resolved all symbols.
805 Symtab.reportRemainingUndefines();
807 // Windows specific -- if no /subsystem is given, we need to infer
808 // that from entry point name.
809 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
810 Config->Subsystem = inferSubsystem();
811 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
812 fatal("subsystem must be defined");
816 if (Args.hasArg(OPT_safeseh))
817 for (ObjectFile *File : Symtab.ObjectFiles)
818 if (!File->SEHCompat)
819 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
821 // Windows specific -- when we are creating a .dll file, we also
822 // need to create a .lib file.
823 if (!Config->Exports.empty() || Config->DLL) {
825 writeImportLibrary();
826 assignExportOrdinals();
829 // Windows specific -- Create a side-by-side manifest file.
830 if (Config->Manifest == Configuration::SideBySide)
831 createSideBySideManifest();
833 // Identify unreferenced COMDAT sections.
835 markLive(Symtab.getChunks());
837 // Identify identical COMDAT sections to merge them.
839 doICF(Symtab.getChunks());
842 writeResult(&Symtab);
844 // Create a symbol map file containing symbol VAs and their names
845 // to help debugging.
846 std::string MapFile = getMapFile(Args);
847 if (!MapFile.empty()) {
849 raw_fd_ostream Out(MapFile, EC, OpenFlags::F_Text);
851 fatal(EC, "could not create the symbol map " + MapFile);
852 Symtab.printMap(Out);
855 // Call exit to avoid calling destructors.