[DAGCombiner] Add target hook function to decide folding (mul (add x, c1), c2)
[llvm-project.git] / lld / COFF / Driver.cpp
blob5f6bc91c90487b249a313f960b25292d1d2f75e9
1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
9 #include "Driver.h"
10 #include "Config.h"
11 #include "DebugTypes.h"
12 #include "ICF.h"
13 #include "InputFiles.h"
14 #include "MarkLive.h"
15 #include "MinGW.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.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"
50 #include <algorithm>
51 #include <future>
52 #include <memory>
54 using namespace llvm;
55 using namespace llvm::object;
56 using namespace llvm::COFF;
57 using namespace llvm::sys;
59 namespace lld {
60 namespace coff {
62 static Timer inputFileTimer("Input File Reading", Timer::root());
64 Configuration *config;
65 LinkerDriver *driver;
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 = []() {
73 TpiSource::clear();
74 freeArena();
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>();
94 driver->linkerMain(args);
96 // Call exit() if we can to avoid calling destructors.
97 if (canExitEarly)
98 exitLld(errorCount() ? 1 : 0);
100 bool ret = errorCount() == 0;
101 if (!canExitEarly)
102 errorHandler().reset();
103 return ret;
106 // Parse options of the form "old;new".
107 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
108 unsigned id) {
109 auto *arg = args.getLastArg(id);
110 if (!arg)
111 return {"", ""};
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);
117 return ret;
120 // Drop directory components and replace extension with
121 // ".exe", ".dll" or ".sys".
122 static std::string getOutputPath(StringRef path) {
123 StringRef ext = ".exe";
124 if (config->dll)
125 ext = ".dll";
126 else if (config->driver)
127 ext = ".sys";
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"))
135 return false;
136 s = s.drop_back(2);
137 if (s.endswith("crtend"))
138 return true;
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) {
152 #if _WIN64
153 // On Windows, file I/O is relatively slow so it is best to do this
154 // asynchronously. But 32-bit has issues with potentially launching tons
155 // of threads
156 auto strategy = std::launch::async;
157 #else
158 auto strategy = std::launch::deferred;
159 #endif
160 return std::async(strategy, [=]() {
161 auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false,
162 /*RequiresNullTerminator=*/false);
163 if (!mbOrErr)
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);
174 return 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
186 if (driver->tar)
187 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
188 mbref.getBuffer());
189 return mbref;
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);
203 break;
204 case file_magic::archive:
205 if (wholeArchive) {
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
211 int memberIndex = 0;
212 for (MemoryBufferRef m : getArchiveMembers(archive))
213 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
214 return;
216 symtab->addFile(make<ArchiveFile>(mbref));
217 break;
218 case file_magic::bitcode:
219 if (lazy)
220 symtab->addFile(make<LazyObjFile>(mbref));
221 else
222 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
223 break;
224 case file_magic::coff_object:
225 case file_magic::coff_import_library:
226 if (lazy)
227 symtab->addFile(make<LazyObjFile>(mbref));
228 else
229 symtab->addFile(make<ObjFile>(mbref));
230 break;
231 case file_magic::pdb:
232 symtab->addFile(make<PDBInputFile>(mbref));
233 break;
234 case file_magic::coff_cl_gl_object:
235 error(filename + ": is not a native COFF file. Recompile without /GL");
236 break;
237 case file_magic::pecoff_executable:
238 if (config->mingw) {
239 symtab->addFile(make<DLLFile>(mbref));
240 break;
242 if (filename.endswith_insensitive(".dll")) {
243 error(filename + ": bad file type. Did you specify a DLL instead of an "
244 "import library?");
245 break;
247 LLVM_FALLTHROUGH;
248 default:
249 error(mbref.getBufferIdentifier() + ": unknown file type");
250 break;
254 void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
255 auto future = std::make_shared<std::future<MBErrPair>>(
256 createFutureForFile(std::string(path)));
257 std::string pathStr = std::string(path);
258 enqueueTask([=]() {
259 auto mbOrErr = future->get();
260 if (mbOrErr.second) {
261 std::string msg =
262 "could not open '" + pathStr + "': " + mbOrErr.second.message();
263 // Check if the filename is a typo for an option flag. OptTable thinks
264 // that all args that are not known options and that start with / are
265 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
266 // the option `/nodefaultlib` than a reference to a file in the root
267 // directory.
268 std::string nearest;
269 if (optTable.findNearest(pathStr, nearest) > 1)
270 error(msg);
271 else
272 error(msg + "; did you mean '" + nearest + "'");
273 } else
274 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
278 void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
279 StringRef parentName,
280 uint64_t offsetInArchive) {
281 file_magic magic = identify_magic(mb.getBuffer());
282 if (magic == file_magic::coff_import_library) {
283 InputFile *imp = make<ImportFile>(mb);
284 imp->parentName = parentName;
285 symtab->addFile(imp);
286 return;
289 InputFile *obj;
290 if (magic == file_magic::coff_object) {
291 obj = make<ObjFile>(mb);
292 } else if (magic == file_magic::bitcode) {
293 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
294 } else {
295 error("unknown file type: " + mb.getBufferIdentifier());
296 return;
299 obj->parentName = parentName;
300 symtab->addFile(obj);
301 log("Loaded " + toString(obj) + " for " + symName);
304 void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
305 const Archive::Symbol &sym,
306 StringRef parentName) {
308 auto reportBufferError = [=](Error &&e, StringRef childName) {
309 fatal("could not get the buffer for the member defining symbol " +
310 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
311 toString(std::move(e)));
314 if (!c.getParent()->isThin()) {
315 uint64_t offsetInArchive = c.getChildOffset();
316 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
317 if (!mbOrErr)
318 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
319 MemoryBufferRef mb = mbOrErr.get();
320 enqueueTask([=]() {
321 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
322 offsetInArchive);
324 return;
327 std::string childName = CHECK(
328 c.getFullName(),
329 "could not get the filename for the member defining symbol " +
330 toCOFFString(sym));
331 auto future = std::make_shared<std::future<MBErrPair>>(
332 createFutureForFile(childName));
333 enqueueTask([=]() {
334 auto mbOrErr = future->get();
335 if (mbOrErr.second)
336 reportBufferError(errorCodeToError(mbOrErr.second), childName);
337 // Pass empty string as archive name so that the original filename is
338 // used as the buffer identifier.
339 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
340 toCOFFString(sym), "", /*OffsetInArchive=*/0);
344 static bool isDecorated(StringRef sym) {
345 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
346 (!config->mingw && sym.contains('@'));
349 // Parses .drectve section contents and returns a list of files
350 // specified by /defaultlib.
351 void LinkerDriver::parseDirectives(InputFile *file) {
352 StringRef s = file->getDirectives();
353 if (s.empty())
354 return;
356 log("Directives: " + toString(file) + ": " + s);
358 ArgParser parser;
359 // .drectve is always tokenized using Windows shell rules.
360 // /EXPORT: option can appear too many times, processing in fastpath.
361 ParsedDirectives directives = parser.parseDirectives(s);
363 for (StringRef e : directives.exports) {
364 // If a common header file contains dllexported function
365 // declarations, many object files may end up with having the
366 // same /EXPORT options. In order to save cost of parsing them,
367 // we dedup them first.
368 if (!directivesExports.insert(e).second)
369 continue;
371 Export exp = parseExport(e);
372 if (config->machine == I386 && config->mingw) {
373 if (!isDecorated(exp.name))
374 exp.name = saver.save("_" + exp.name);
375 if (!exp.extName.empty() && !isDecorated(exp.extName))
376 exp.extName = saver.save("_" + exp.extName);
378 exp.directives = true;
379 config->exports.push_back(exp);
382 // Handle /include: in bulk.
383 for (StringRef inc : directives.includes)
384 addUndefined(inc);
386 for (auto *arg : directives.args) {
387 switch (arg->getOption().getID()) {
388 case OPT_aligncomm:
389 parseAligncomm(arg->getValue());
390 break;
391 case OPT_alternatename:
392 parseAlternateName(arg->getValue());
393 break;
394 case OPT_defaultlib:
395 if (Optional<StringRef> path = findLib(arg->getValue()))
396 enqueuePath(*path, false, false);
397 break;
398 case OPT_entry:
399 config->entry = addUndefined(mangle(arg->getValue()));
400 break;
401 case OPT_failifmismatch:
402 checkFailIfMismatch(arg->getValue(), file);
403 break;
404 case OPT_incl:
405 addUndefined(arg->getValue());
406 break;
407 case OPT_merge:
408 parseMerge(arg->getValue());
409 break;
410 case OPT_nodefaultlib:
411 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
412 break;
413 case OPT_section:
414 parseSection(arg->getValue());
415 break;
416 case OPT_stack:
417 parseNumbers(arg->getValue(), &config->stackReserve,
418 &config->stackCommit);
419 break;
420 case OPT_subsystem: {
421 bool gotVersion = false;
422 parseSubsystem(arg->getValue(), &config->subsystem,
423 &config->majorSubsystemVersion,
424 &config->minorSubsystemVersion, &gotVersion);
425 if (gotVersion) {
426 config->majorOSVersion = config->majorSubsystemVersion;
427 config->minorOSVersion = config->minorSubsystemVersion;
429 break;
431 // Only add flags here that link.exe accepts in
432 // `#pragma comment(linker, "/flag")`-generated sections.
433 case OPT_editandcontinue:
434 case OPT_guardsym:
435 case OPT_throwingnew:
436 break;
437 default:
438 error(arg->getSpelling() + " is not allowed in .drectve");
443 // Find file from search paths. You can omit ".obj", this function takes
444 // care of that. Note that the returned path is not guaranteed to exist.
445 StringRef LinkerDriver::doFindFile(StringRef filename) {
446 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
447 if (hasPathSep)
448 return filename;
449 bool hasExt = filename.contains('.');
450 for (StringRef dir : searchPaths) {
451 SmallString<128> path = dir;
452 sys::path::append(path, filename);
453 if (sys::fs::exists(path.str()))
454 return saver.save(path.str());
455 if (!hasExt) {
456 path.append(".obj");
457 if (sys::fs::exists(path.str()))
458 return saver.save(path.str());
461 return filename;
464 static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
465 sys::fs::UniqueID ret;
466 if (sys::fs::getUniqueID(path, ret))
467 return None;
468 return ret;
471 // Resolves a file path. This never returns the same path
472 // (in that case, it returns None).
473 Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
474 StringRef path = doFindFile(filename);
476 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
477 bool seen = !visitedFiles.insert(*id).second;
478 if (seen)
479 return None;
482 if (path.endswith_insensitive(".lib"))
483 visitedLibs.insert(std::string(sys::path::filename(path)));
484 return path;
487 // MinGW specific. If an embedded directive specified to link to
488 // foo.lib, but it isn't found, try libfoo.a instead.
489 StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
490 if (filename.contains('/') || filename.contains('\\'))
491 return filename;
493 SmallString<128> s = filename;
494 sys::path::replace_extension(s, ".a");
495 StringRef libName = saver.save("lib" + s.str());
496 return doFindFile(libName);
499 // Find library file from search path.
500 StringRef LinkerDriver::doFindLib(StringRef filename) {
501 // Add ".lib" to Filename if that has no file extension.
502 bool hasExt = filename.contains('.');
503 if (!hasExt)
504 filename = saver.save(filename + ".lib");
505 StringRef ret = doFindFile(filename);
506 // For MinGW, if the find above didn't turn up anything, try
507 // looking for a MinGW formatted library name.
508 if (config->mingw && ret == filename)
509 return doFindLibMinGW(filename);
510 return ret;
513 // Resolves a library path. /nodefaultlib options are taken into
514 // consideration. This never returns the same path (in that case,
515 // it returns None).
516 Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
517 if (config->noDefaultLibAll)
518 return None;
519 if (!visitedLibs.insert(filename.lower()).second)
520 return None;
522 StringRef path = doFindLib(filename);
523 if (config->noDefaultLibs.count(path.lower()))
524 return None;
526 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
527 if (!visitedFiles.insert(*id).second)
528 return None;
529 return path;
532 // Parses LIB environment which contains a list of search paths.
533 void LinkerDriver::addLibSearchPaths() {
534 Optional<std::string> envOpt = Process::GetEnv("LIB");
535 if (!envOpt.hasValue())
536 return;
537 StringRef env = saver.save(*envOpt);
538 while (!env.empty()) {
539 StringRef path;
540 std::tie(path, env) = env.split(';');
541 searchPaths.push_back(path);
545 Symbol *LinkerDriver::addUndefined(StringRef name) {
546 Symbol *b = symtab->addUndefined(name);
547 if (!b->isGCRoot) {
548 b->isGCRoot = true;
549 config->gcroot.push_back(b);
551 return b;
554 StringRef LinkerDriver::mangleMaybe(Symbol *s) {
555 // If the plain symbol name has already been resolved, do nothing.
556 Undefined *unmangled = dyn_cast<Undefined>(s);
557 if (!unmangled)
558 return "";
560 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
561 Symbol *mangled = symtab->findMangle(unmangled->getName());
562 if (!mangled)
563 return "";
565 // If we find a similar mangled symbol, make this an alias to it and return
566 // its name.
567 log(unmangled->getName() + " aliased to " + mangled->getName());
568 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
569 return mangled->getName();
572 // Windows specific -- find default entry point name.
574 // There are four different entry point functions for Windows executables,
575 // each of which corresponds to a user-defined "main" function. This function
576 // infers an entry point from a user-defined "main" function.
577 StringRef LinkerDriver::findDefaultEntry() {
578 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
579 "must handle /subsystem before calling this");
581 if (config->mingw)
582 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
583 ? "WinMainCRTStartup"
584 : "mainCRTStartup");
586 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
587 if (findUnderscoreMangle("wWinMain")) {
588 if (!findUnderscoreMangle("WinMain"))
589 return mangle("wWinMainCRTStartup");
590 warn("found both wWinMain and WinMain; using latter");
592 return mangle("WinMainCRTStartup");
594 if (findUnderscoreMangle("wmain")) {
595 if (!findUnderscoreMangle("main"))
596 return mangle("wmainCRTStartup");
597 warn("found both wmain and main; using latter");
599 return mangle("mainCRTStartup");
602 WindowsSubsystem LinkerDriver::inferSubsystem() {
603 if (config->dll)
604 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
605 if (config->mingw)
606 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
607 // Note that link.exe infers the subsystem from the presence of these
608 // functions even if /entry: or /nodefaultlib are passed which causes them
609 // to not be called.
610 bool haveMain = findUnderscoreMangle("main");
611 bool haveWMain = findUnderscoreMangle("wmain");
612 bool haveWinMain = findUnderscoreMangle("WinMain");
613 bool haveWWinMain = findUnderscoreMangle("wWinMain");
614 if (haveMain || haveWMain) {
615 if (haveWinMain || haveWWinMain) {
616 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
617 (haveWinMain ? "WinMain" : "wWinMain") +
618 "; defaulting to /subsystem:console");
620 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
622 if (haveWinMain || haveWWinMain)
623 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
624 return IMAGE_SUBSYSTEM_UNKNOWN;
627 static uint64_t getDefaultImageBase() {
628 if (config->is64())
629 return config->dll ? 0x180000000 : 0x140000000;
630 return config->dll ? 0x10000000 : 0x400000;
633 static std::string rewritePath(StringRef s) {
634 if (fs::exists(s))
635 return relativeToRoot(s);
636 return std::string(s);
639 // Reconstructs command line arguments so that so that you can re-run
640 // the same command with the same inputs. This is for --reproduce.
641 static std::string createResponseFile(const opt::InputArgList &args,
642 ArrayRef<StringRef> filePaths,
643 ArrayRef<StringRef> searchPaths) {
644 SmallString<0> data;
645 raw_svector_ostream os(data);
647 for (auto *arg : args) {
648 switch (arg->getOption().getID()) {
649 case OPT_linkrepro:
650 case OPT_reproduce:
651 case OPT_INPUT:
652 case OPT_defaultlib:
653 case OPT_libpath:
654 case OPT_manifest:
655 case OPT_manifest_colon:
656 case OPT_manifestdependency:
657 case OPT_manifestfile:
658 case OPT_manifestinput:
659 case OPT_manifestuac:
660 break;
661 case OPT_call_graph_ordering_file:
662 case OPT_deffile:
663 case OPT_natvis:
664 os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n';
665 break;
666 case OPT_order: {
667 StringRef orderFile = arg->getValue();
668 orderFile.consume_front("@");
669 os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n';
670 break;
672 case OPT_pdbstream: {
673 const std::pair<StringRef, StringRef> nameFile =
674 StringRef(arg->getValue()).split("=");
675 os << arg->getSpelling() << nameFile.first << '='
676 << quote(rewritePath(nameFile.second)) << '\n';
677 break;
679 case OPT_implib:
680 case OPT_pdb:
681 case OPT_pdbstripped:
682 case OPT_out:
683 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
684 break;
685 default:
686 os << toString(*arg) << "\n";
690 for (StringRef path : searchPaths) {
691 std::string relPath = relativeToRoot(path);
692 os << "/libpath:" << quote(relPath) << "\n";
695 for (StringRef path : filePaths)
696 os << quote(relativeToRoot(path)) << "\n";
698 return std::string(data.str());
701 enum class DebugKind {
702 Unknown,
703 None,
704 Full,
705 FastLink,
706 GHash,
707 NoGHash,
708 Dwarf,
709 Symtab
712 static DebugKind parseDebugKind(const opt::InputArgList &args) {
713 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
714 if (!a)
715 return DebugKind::None;
716 if (a->getNumValues() == 0)
717 return DebugKind::Full;
719 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
720 .CaseLower("none", DebugKind::None)
721 .CaseLower("full", DebugKind::Full)
722 .CaseLower("fastlink", DebugKind::FastLink)
723 // LLD extensions
724 .CaseLower("ghash", DebugKind::GHash)
725 .CaseLower("noghash", DebugKind::NoGHash)
726 .CaseLower("dwarf", DebugKind::Dwarf)
727 .CaseLower("symtab", DebugKind::Symtab)
728 .Default(DebugKind::Unknown);
730 if (debug == DebugKind::FastLink) {
731 warn("/debug:fastlink unsupported; using /debug:full");
732 return DebugKind::Full;
734 if (debug == DebugKind::Unknown) {
735 error("/debug: unknown option: " + Twine(a->getValue()));
736 return DebugKind::None;
738 return debug;
741 static unsigned parseDebugTypes(const opt::InputArgList &args) {
742 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
744 if (auto *a = args.getLastArg(OPT_debugtype)) {
745 SmallVector<StringRef, 3> types;
746 StringRef(a->getValue())
747 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
749 for (StringRef type : types) {
750 unsigned v = StringSwitch<unsigned>(type.lower())
751 .Case("cv", static_cast<unsigned>(DebugType::CV))
752 .Case("pdata", static_cast<unsigned>(DebugType::PData))
753 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
754 .Default(0);
755 if (v == 0) {
756 warn("/debugtype: unknown option '" + type + "'");
757 continue;
759 debugTypes |= v;
761 return debugTypes;
764 // Default debug types
765 debugTypes = static_cast<unsigned>(DebugType::CV);
766 if (args.hasArg(OPT_driver))
767 debugTypes |= static_cast<unsigned>(DebugType::PData);
768 if (args.hasArg(OPT_profile))
769 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
771 return debugTypes;
774 static std::string getMapFile(const opt::InputArgList &args,
775 opt::OptSpecifier os, opt::OptSpecifier osFile) {
776 auto *arg = args.getLastArg(os, osFile);
777 if (!arg)
778 return "";
779 if (arg->getOption().getID() == osFile.getID())
780 return arg->getValue();
782 assert(arg->getOption().getID() == os.getID());
783 StringRef outFile = config->outputFile;
784 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
787 static std::string getImplibPath() {
788 if (!config->implib.empty())
789 return std::string(config->implib);
790 SmallString<128> out = StringRef(config->outputFile);
791 sys::path::replace_extension(out, ".lib");
792 return std::string(out.str());
795 // The import name is calculated as follows:
797 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
798 // -----+----------------+---------------------+------------------
799 // LINK | {value} | {value}.{.dll/.exe} | {output name}
800 // LIB | {value} | {value}.dll | {output name}.dll
802 static std::string getImportName(bool asLib) {
803 SmallString<128> out;
805 if (config->importName.empty()) {
806 out.assign(sys::path::filename(config->outputFile));
807 if (asLib)
808 sys::path::replace_extension(out, ".dll");
809 } else {
810 out.assign(config->importName);
811 if (!sys::path::has_extension(out))
812 sys::path::replace_extension(out,
813 (config->dll || asLib) ? ".dll" : ".exe");
816 return std::string(out.str());
819 static void createImportLibrary(bool asLib) {
820 std::vector<COFFShortExport> exports;
821 for (Export &e1 : config->exports) {
822 COFFShortExport e2;
823 e2.Name = std::string(e1.name);
824 e2.SymbolName = std::string(e1.symbolName);
825 e2.ExtName = std::string(e1.extName);
826 e2.Ordinal = e1.ordinal;
827 e2.Noname = e1.noname;
828 e2.Data = e1.data;
829 e2.Private = e1.isPrivate;
830 e2.Constant = e1.constant;
831 exports.push_back(e2);
834 auto handleError = [](Error &&e) {
835 handleAllErrors(std::move(e),
836 [](ErrorInfoBase &eib) { error(eib.message()); });
838 std::string libName = getImportName(asLib);
839 std::string path = getImplibPath();
841 if (!config->incremental) {
842 handleError(writeImportLibrary(libName, path, exports, config->machine,
843 config->mingw));
844 return;
847 // If the import library already exists, replace it only if the contents
848 // have changed.
849 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
850 path, /*IsText=*/false, /*RequiresNullTerminator=*/false);
851 if (!oldBuf) {
852 handleError(writeImportLibrary(libName, path, exports, config->machine,
853 config->mingw));
854 return;
857 SmallString<128> tmpName;
858 if (std::error_code ec =
859 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
860 fatal("cannot create temporary file for import library " + path + ": " +
861 ec.message());
863 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
864 config->mingw)) {
865 handleError(std::move(e));
866 return;
869 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
870 tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false));
871 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
872 oldBuf->reset();
873 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
874 } else {
875 sys::fs::remove(tmpName);
879 static void parseModuleDefs(StringRef path) {
880 std::unique_ptr<MemoryBuffer> mb =
881 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
882 /*RequiresNullTerminator=*/false,
883 /*IsVolatile=*/true),
884 "could not open " + path);
885 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
886 mb->getMemBufferRef(), config->machine, config->mingw));
888 // Include in /reproduce: output if applicable.
889 driver->takeBuffer(std::move(mb));
891 if (config->outputFile.empty())
892 config->outputFile = std::string(saver.save(m.OutputFile));
893 config->importName = std::string(saver.save(m.ImportName));
894 if (m.ImageBase)
895 config->imageBase = m.ImageBase;
896 if (m.StackReserve)
897 config->stackReserve = m.StackReserve;
898 if (m.StackCommit)
899 config->stackCommit = m.StackCommit;
900 if (m.HeapReserve)
901 config->heapReserve = m.HeapReserve;
902 if (m.HeapCommit)
903 config->heapCommit = m.HeapCommit;
904 if (m.MajorImageVersion)
905 config->majorImageVersion = m.MajorImageVersion;
906 if (m.MinorImageVersion)
907 config->minorImageVersion = m.MinorImageVersion;
908 if (m.MajorOSVersion)
909 config->majorOSVersion = m.MajorOSVersion;
910 if (m.MinorOSVersion)
911 config->minorOSVersion = m.MinorOSVersion;
913 for (COFFShortExport e1 : m.Exports) {
914 Export e2;
915 // In simple cases, only Name is set. Renamed exports are parsed
916 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
917 // it shouldn't be a normal exported function but a forward to another
918 // DLL instead. This is supported by both MS and GNU linkers.
919 if (!e1.ExtName.empty() && e1.ExtName != e1.Name &&
920 StringRef(e1.Name).contains('.')) {
921 e2.name = saver.save(e1.ExtName);
922 e2.forwardTo = saver.save(e1.Name);
923 config->exports.push_back(e2);
924 continue;
926 e2.name = saver.save(e1.Name);
927 e2.extName = saver.save(e1.ExtName);
928 e2.ordinal = e1.Ordinal;
929 e2.noname = e1.Noname;
930 e2.data = e1.Data;
931 e2.isPrivate = e1.Private;
932 e2.constant = e1.Constant;
933 config->exports.push_back(e2);
937 void LinkerDriver::enqueueTask(std::function<void()> task) {
938 taskQueue.push_back(std::move(task));
941 bool LinkerDriver::run() {
942 ScopedTimer t(inputFileTimer);
944 bool didWork = !taskQueue.empty();
945 while (!taskQueue.empty()) {
946 taskQueue.front()();
947 taskQueue.pop_front();
949 return didWork;
952 // Parse an /order file. If an option is given, the linker places
953 // COMDAT sections in the same order as their names appear in the
954 // given file.
955 static void parseOrderFile(StringRef arg) {
956 // For some reason, the MSVC linker requires a filename to be
957 // preceded by "@".
958 if (!arg.startswith("@")) {
959 error("malformed /order option: '@' missing");
960 return;
963 // Get a list of all comdat sections for error checking.
964 DenseSet<StringRef> set;
965 for (Chunk *c : symtab->getChunks())
966 if (auto *sec = dyn_cast<SectionChunk>(c))
967 if (sec->sym)
968 set.insert(sec->sym->getName());
970 // Open a file.
971 StringRef path = arg.substr(1);
972 std::unique_ptr<MemoryBuffer> mb =
973 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
974 /*RequiresNullTerminator=*/false,
975 /*IsVolatile=*/true),
976 "could not open " + path);
978 // Parse a file. An order file contains one symbol per line.
979 // All symbols that were not present in a given order file are
980 // considered to have the lowest priority 0 and are placed at
981 // end of an output section.
982 for (StringRef arg : args::getLines(mb->getMemBufferRef())) {
983 std::string s(arg);
984 if (config->machine == I386 && !isDecorated(s))
985 s = "_" + s;
987 if (set.count(s) == 0) {
988 if (config->warnMissingOrderSymbol)
989 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
991 else
992 config->order[s] = INT_MIN + config->order.size();
995 // Include in /reproduce: output if applicable.
996 driver->takeBuffer(std::move(mb));
999 static void parseCallGraphFile(StringRef path) {
1000 std::unique_ptr<MemoryBuffer> mb =
1001 CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
1002 /*RequiresNullTerminator=*/false,
1003 /*IsVolatile=*/true),
1004 "could not open " + path);
1006 // Build a map from symbol name to section.
1007 DenseMap<StringRef, Symbol *> map;
1008 for (ObjFile *file : ObjFile::instances)
1009 for (Symbol *sym : file->getSymbols())
1010 if (sym)
1011 map[sym->getName()] = sym;
1013 auto findSection = [&](StringRef name) -> SectionChunk * {
1014 Symbol *sym = map.lookup(name);
1015 if (!sym) {
1016 if (config->warnMissingOrderSymbol)
1017 warn(path + ": no such symbol: " + name);
1018 return nullptr;
1021 if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym))
1022 return dyn_cast_or_null<SectionChunk>(dr->getChunk());
1023 return nullptr;
1026 for (StringRef line : args::getLines(*mb)) {
1027 SmallVector<StringRef, 3> fields;
1028 line.split(fields, ' ');
1029 uint64_t count;
1031 if (fields.size() != 3 || !to_integer(fields[2], count)) {
1032 error(path + ": parse error");
1033 return;
1036 if (SectionChunk *from = findSection(fields[0]))
1037 if (SectionChunk *to = findSection(fields[1]))
1038 config->callGraphProfile[{from, to}] += count;
1041 // Include in /reproduce: output if applicable.
1042 driver->takeBuffer(std::move(mb));
1045 static void readCallGraphsFromObjectFiles() {
1046 for (ObjFile *obj : ObjFile::instances) {
1047 if (obj->callgraphSec) {
1048 ArrayRef<uint8_t> contents;
1049 cantFail(
1050 obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents));
1051 BinaryStreamReader reader(contents, support::little);
1052 while (!reader.empty()) {
1053 uint32_t fromIndex, toIndex;
1054 uint64_t count;
1055 if (Error err = reader.readInteger(fromIndex))
1056 fatal(toString(obj) + ": Expected 32-bit integer");
1057 if (Error err = reader.readInteger(toIndex))
1058 fatal(toString(obj) + ": Expected 32-bit integer");
1059 if (Error err = reader.readInteger(count))
1060 fatal(toString(obj) + ": Expected 64-bit integer");
1061 auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex));
1062 auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex));
1063 if (!fromSym || !toSym)
1064 continue;
1065 auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk());
1066 auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk());
1067 if (from && to)
1068 config->callGraphProfile[{from, to}] += count;
1074 static void markAddrsig(Symbol *s) {
1075 if (auto *d = dyn_cast_or_null<Defined>(s))
1076 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
1077 c->keepUnique = true;
1080 static void findKeepUniqueSections() {
1081 // Exported symbols could be address-significant in other executables or DSOs,
1082 // so we conservatively mark them as address-significant.
1083 for (Export &r : config->exports)
1084 markAddrsig(r.sym);
1086 // Visit the address-significance table in each object file and mark each
1087 // referenced symbol as address-significant.
1088 for (ObjFile *obj : ObjFile::instances) {
1089 ArrayRef<Symbol *> syms = obj->getSymbols();
1090 if (obj->addrsigSec) {
1091 ArrayRef<uint8_t> contents;
1092 cantFail(
1093 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
1094 const uint8_t *cur = contents.begin();
1095 while (cur != contents.end()) {
1096 unsigned size;
1097 const char *err;
1098 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
1099 if (err)
1100 fatal(toString(obj) + ": could not decode addrsig section: " + err);
1101 if (symIndex >= syms.size())
1102 fatal(toString(obj) + ": invalid symbol index in addrsig section");
1103 markAddrsig(syms[symIndex]);
1104 cur += size;
1106 } else {
1107 // If an object file does not have an address-significance table,
1108 // conservatively mark all of its symbols as address-significant.
1109 for (Symbol *s : syms)
1110 markAddrsig(s);
1115 // link.exe replaces each %foo% in altPath with the contents of environment
1116 // variable foo, and adds the two magic env vars _PDB (expands to the basename
1117 // of pdb's output path) and _EXT (expands to the extension of the output
1118 // binary).
1119 // lld only supports %_PDB% and %_EXT% and warns on references to all other env
1120 // vars.
1121 static void parsePDBAltPath(StringRef altPath) {
1122 SmallString<128> buf;
1123 StringRef pdbBasename =
1124 sys::path::filename(config->pdbPath, sys::path::Style::windows);
1125 StringRef binaryExtension =
1126 sys::path::extension(config->outputFile, sys::path::Style::windows);
1127 if (!binaryExtension.empty())
1128 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
1130 // Invariant:
1131 // +--------- cursor ('a...' might be the empty string).
1132 // | +----- firstMark
1133 // | | +- secondMark
1134 // v v v
1135 // a...%...%...
1136 size_t cursor = 0;
1137 while (cursor < altPath.size()) {
1138 size_t firstMark, secondMark;
1139 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
1140 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
1141 // Didn't find another full fragment, treat rest of string as literal.
1142 buf.append(altPath.substr(cursor));
1143 break;
1146 // Found a full fragment. Append text in front of first %, and interpret
1147 // text between first and second % as variable name.
1148 buf.append(altPath.substr(cursor, firstMark - cursor));
1149 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1150 if (var.equals_insensitive("%_pdb%"))
1151 buf.append(pdbBasename);
1152 else if (var.equals_insensitive("%_ext%"))
1153 buf.append(binaryExtension);
1154 else {
1155 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1156 var + " as literal");
1157 buf.append(var);
1160 cursor = secondMark + 1;
1163 config->pdbAltPath = buf;
1166 /// Convert resource files and potentially merge input resource object
1167 /// trees into one resource tree.
1168 /// Call after ObjFile::Instances is complete.
1169 void LinkerDriver::convertResources() {
1170 std::vector<ObjFile *> resourceObjFiles;
1172 for (ObjFile *f : ObjFile::instances) {
1173 if (f->isResourceObjFile())
1174 resourceObjFiles.push_back(f);
1177 if (!config->mingw &&
1178 (resourceObjFiles.size() > 1 ||
1179 (resourceObjFiles.size() == 1 && !resources.empty()))) {
1180 error((!resources.empty() ? "internal .obj file created from .res files"
1181 : toString(resourceObjFiles[1])) +
1182 ": more than one resource obj file not allowed, already got " +
1183 toString(resourceObjFiles.front()));
1184 return;
1187 if (resources.empty() && resourceObjFiles.size() <= 1) {
1188 // No resources to convert, and max one resource object file in
1189 // the input. Keep that preconverted resource section as is.
1190 for (ObjFile *f : resourceObjFiles)
1191 f->includeResourceChunks();
1192 return;
1194 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
1195 symtab->addFile(f);
1196 f->includeResourceChunks();
1199 // In MinGW, if no symbols are chosen to be exported, then all symbols are
1200 // automatically exported by default. This behavior can be forced by the
1201 // -export-all-symbols option, so that it happens even when exports are
1202 // explicitly specified. The automatic behavior can be disabled using the
1203 // -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1204 // than MinGW in the case that nothing is explicitly exported.
1205 void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1206 if (!args.hasArg(OPT_export_all_symbols)) {
1207 if (!config->dll)
1208 return;
1210 if (!config->exports.empty())
1211 return;
1212 if (args.hasArg(OPT_exclude_all_symbols))
1213 return;
1216 AutoExporter exporter;
1218 for (auto *arg : args.filtered(OPT_wholearchive_file))
1219 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1220 exporter.addWholeArchive(*path);
1222 symtab->forEachSymbol([&](Symbol *s) {
1223 auto *def = dyn_cast<Defined>(s);
1224 if (!exporter.shouldExport(def))
1225 return;
1227 if (!def->isGCRoot) {
1228 def->isGCRoot = true;
1229 config->gcroot.push_back(def);
1232 Export e;
1233 e.name = def->getName();
1234 e.sym = def;
1235 if (Chunk *c = def->getChunk())
1236 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1237 e.data = true;
1238 s->isUsedInRegularObj = true;
1239 config->exports.push_back(e);
1243 // lld has a feature to create a tar file containing all input files as well as
1244 // all command line options, so that other people can run lld again with exactly
1245 // the same inputs. This feature is accessible via /linkrepro and /reproduce.
1247 // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1248 // name while /reproduce takes a full path. We have /linkrepro for compatibility
1249 // with Microsoft link.exe.
1250 Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1251 if (auto *arg = args.getLastArg(OPT_reproduce))
1252 return std::string(arg->getValue());
1254 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1255 SmallString<64> path = StringRef(arg->getValue());
1256 sys::path::append(path, "repro.tar");
1257 return std::string(path);
1260 // This is intentionally not guarded by OPT_lldignoreenv since writing
1261 // a repro tar file doesn't affect the main output.
1262 if (auto *path = getenv("LLD_REPRODUCE"))
1263 return std::string(path);
1265 return None;
1268 void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) {
1269 ScopedTimer rootTimer(Timer::root());
1271 // Needed for LTO.
1272 InitializeAllTargetInfos();
1273 InitializeAllTargets();
1274 InitializeAllTargetMCs();
1275 InitializeAllAsmParsers();
1276 InitializeAllAsmPrinters();
1278 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1279 // We call our own implementation of lib.exe that understands bitcode files.
1280 if (argsArr.size() > 1 &&
1281 (StringRef(argsArr[1]).equals_insensitive("/lib") ||
1282 StringRef(argsArr[1]).equals_insensitive("-lib"))) {
1283 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1284 fatal("lib failed");
1285 return;
1288 // Parse command line options.
1289 ArgParser parser;
1290 opt::InputArgList args = parser.parse(argsArr);
1292 // Parse and evaluate -mllvm options.
1293 std::vector<const char *> v;
1294 v.push_back("lld-link (LLVM option parsing)");
1295 for (auto *arg : args.filtered(OPT_mllvm))
1296 v.push_back(arg->getValue());
1297 cl::ResetAllOptionOccurrences();
1298 cl::ParseCommandLineOptions(v.size(), v.data());
1300 // Handle /errorlimit early, because error() depends on it.
1301 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1302 int n = 20;
1303 StringRef s = arg->getValue();
1304 if (s.getAsInteger(10, n))
1305 error(arg->getSpelling() + " number expected, but got " + s);
1306 errorHandler().errorLimit = n;
1309 // Handle /help
1310 if (args.hasArg(OPT_help)) {
1311 printHelp(argsArr[0]);
1312 return;
1315 // /threads: takes a positive integer and provides the default value for
1316 // /opt:lldltojobs=.
1317 if (auto *arg = args.getLastArg(OPT_threads)) {
1318 StringRef v(arg->getValue());
1319 unsigned threads = 0;
1320 if (!llvm::to_integer(v, threads, 0) || threads == 0)
1321 error(arg->getSpelling() + ": expected a positive integer, but got '" +
1322 arg->getValue() + "'");
1323 parallel::strategy = hardware_concurrency(threads);
1324 config->thinLTOJobs = v.str();
1327 if (args.hasArg(OPT_show_timing))
1328 config->showTiming = true;
1330 config->showSummary = args.hasArg(OPT_summary);
1332 // Handle --version, which is an lld extension. This option is a bit odd
1333 // because it doesn't start with "/", but we deliberately chose "--" to
1334 // avoid conflict with /version and for compatibility with clang-cl.
1335 if (args.hasArg(OPT_dash_dash_version)) {
1336 message(getLLDVersion());
1337 return;
1340 // Handle /lldmingw early, since it can potentially affect how other
1341 // options are handled.
1342 config->mingw = args.hasArg(OPT_lldmingw);
1344 // Handle /linkrepro and /reproduce.
1345 if (Optional<std::string> path = getReproduceFile(args)) {
1346 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1347 TarWriter::create(*path, sys::path::stem(*path));
1349 if (errOrWriter) {
1350 tar = std::move(*errOrWriter);
1351 } else {
1352 error("/linkrepro: failed to open " + *path + ": " +
1353 toString(errOrWriter.takeError()));
1357 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1358 if (args.hasArg(OPT_deffile))
1359 config->noEntry = true;
1360 else
1361 fatal("no input files");
1364 // Construct search path list.
1365 searchPaths.push_back("");
1366 for (auto *arg : args.filtered(OPT_libpath))
1367 searchPaths.push_back(arg->getValue());
1368 if (!args.hasArg(OPT_lldignoreenv))
1369 addLibSearchPaths();
1371 // Handle /ignore
1372 for (auto *arg : args.filtered(OPT_ignore)) {
1373 SmallVector<StringRef, 8> vec;
1374 StringRef(arg->getValue()).split(vec, ',');
1375 for (StringRef s : vec) {
1376 if (s == "4037")
1377 config->warnMissingOrderSymbol = false;
1378 else if (s == "4099")
1379 config->warnDebugInfoUnusable = false;
1380 else if (s == "4217")
1381 config->warnLocallyDefinedImported = false;
1382 else if (s == "longsections")
1383 config->warnLongSectionNames = false;
1384 // Other warning numbers are ignored.
1388 // Handle /out
1389 if (auto *arg = args.getLastArg(OPT_out))
1390 config->outputFile = arg->getValue();
1392 // Handle /verbose
1393 if (args.hasArg(OPT_verbose))
1394 config->verbose = true;
1395 errorHandler().verbose = config->verbose;
1397 // Handle /force or /force:unresolved
1398 if (args.hasArg(OPT_force, OPT_force_unresolved))
1399 config->forceUnresolved = true;
1401 // Handle /force or /force:multiple
1402 if (args.hasArg(OPT_force, OPT_force_multiple))
1403 config->forceMultiple = true;
1405 // Handle /force or /force:multipleres
1406 if (args.hasArg(OPT_force, OPT_force_multipleres))
1407 config->forceMultipleRes = true;
1409 // Handle /debug
1410 DebugKind debug = parseDebugKind(args);
1411 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1412 debug == DebugKind::GHash || debug == DebugKind::NoGHash) {
1413 config->debug = true;
1414 config->incremental = true;
1417 // Handle /demangle
1418 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1420 // Handle /debugtype
1421 config->debugTypes = parseDebugTypes(args);
1423 // Handle /driver[:uponly|:wdm].
1424 config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1425 args.hasArg(OPT_driver_uponly_wdm) ||
1426 args.hasArg(OPT_driver_wdm_uponly);
1427 config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1428 args.hasArg(OPT_driver_uponly_wdm) ||
1429 args.hasArg(OPT_driver_wdm_uponly);
1430 config->driver =
1431 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1433 // Handle /pdb
1434 bool shouldCreatePDB =
1435 (debug == DebugKind::Full || debug == DebugKind::GHash ||
1436 debug == DebugKind::NoGHash);
1437 if (shouldCreatePDB) {
1438 if (auto *arg = args.getLastArg(OPT_pdb))
1439 config->pdbPath = arg->getValue();
1440 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1441 config->pdbAltPath = arg->getValue();
1442 if (args.hasArg(OPT_natvis))
1443 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1444 if (args.hasArg(OPT_pdbstream)) {
1445 for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) {
1446 const std::pair<StringRef, StringRef> nameFile = value.split("=");
1447 const StringRef name = nameFile.first;
1448 const std::string file = nameFile.second.str();
1449 config->namedStreams[name] = file;
1453 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1454 config->pdbSourcePath = arg->getValue();
1457 // Handle /pdbstripped
1458 if (args.hasArg(OPT_pdbstripped))
1459 warn("ignoring /pdbstripped flag, it is not yet supported");
1461 // Handle /noentry
1462 if (args.hasArg(OPT_noentry)) {
1463 if (args.hasArg(OPT_dll))
1464 config->noEntry = true;
1465 else
1466 error("/noentry must be specified with /dll");
1469 // Handle /dll
1470 if (args.hasArg(OPT_dll)) {
1471 config->dll = true;
1472 config->manifestID = 2;
1475 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1476 // because we need to explicitly check whether that option or its inverse was
1477 // present in the argument list in order to handle /fixed.
1478 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1479 if (dynamicBaseArg &&
1480 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1481 config->dynamicBase = false;
1483 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1484 // default setting for any other project type.", but link.exe defaults to
1485 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1486 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1487 if (fixed) {
1488 if (dynamicBaseArg &&
1489 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1490 error("/fixed must not be specified with /dynamicbase");
1491 } else {
1492 config->relocatable = false;
1493 config->dynamicBase = false;
1497 // Handle /appcontainer
1498 config->appContainer =
1499 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1501 // Handle /machine
1502 if (auto *arg = args.getLastArg(OPT_machine)) {
1503 config->machine = getMachineType(arg->getValue());
1504 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1505 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1508 // Handle /nodefaultlib:<filename>
1509 for (auto *arg : args.filtered(OPT_nodefaultlib))
1510 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1512 // Handle /nodefaultlib
1513 if (args.hasArg(OPT_nodefaultlib_all))
1514 config->noDefaultLibAll = true;
1516 // Handle /base
1517 if (auto *arg = args.getLastArg(OPT_base))
1518 parseNumbers(arg->getValue(), &config->imageBase);
1520 // Handle /filealign
1521 if (auto *arg = args.getLastArg(OPT_filealign)) {
1522 parseNumbers(arg->getValue(), &config->fileAlign);
1523 if (!isPowerOf2_64(config->fileAlign))
1524 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1527 // Handle /stack
1528 if (auto *arg = args.getLastArg(OPT_stack))
1529 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1531 // Handle /guard:cf
1532 if (auto *arg = args.getLastArg(OPT_guard))
1533 parseGuard(arg->getValue());
1535 // Handle /heap
1536 if (auto *arg = args.getLastArg(OPT_heap))
1537 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1539 // Handle /version
1540 if (auto *arg = args.getLastArg(OPT_version))
1541 parseVersion(arg->getValue(), &config->majorImageVersion,
1542 &config->minorImageVersion);
1544 // Handle /subsystem
1545 if (auto *arg = args.getLastArg(OPT_subsystem))
1546 parseSubsystem(arg->getValue(), &config->subsystem,
1547 &config->majorSubsystemVersion,
1548 &config->minorSubsystemVersion);
1550 // Handle /osversion
1551 if (auto *arg = args.getLastArg(OPT_osversion)) {
1552 parseVersion(arg->getValue(), &config->majorOSVersion,
1553 &config->minorOSVersion);
1554 } else {
1555 config->majorOSVersion = config->majorSubsystemVersion;
1556 config->minorOSVersion = config->minorSubsystemVersion;
1559 // Handle /timestamp
1560 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1561 if (arg->getOption().getID() == OPT_repro) {
1562 config->timestamp = 0;
1563 config->repro = true;
1564 } else {
1565 config->repro = false;
1566 StringRef value(arg->getValue());
1567 if (value.getAsInteger(0, config->timestamp))
1568 fatal(Twine("invalid timestamp: ") + value +
1569 ". Expected 32-bit integer");
1571 } else {
1572 config->repro = false;
1573 config->timestamp = time(nullptr);
1576 // Handle /alternatename
1577 for (auto *arg : args.filtered(OPT_alternatename))
1578 parseAlternateName(arg->getValue());
1580 // Handle /include
1581 for (auto *arg : args.filtered(OPT_incl))
1582 addUndefined(arg->getValue());
1584 // Handle /implib
1585 if (auto *arg = args.getLastArg(OPT_implib))
1586 config->implib = arg->getValue();
1588 // Handle /opt.
1589 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1590 Optional<ICFLevel> icfLevel = None;
1591 if (args.hasArg(OPT_profile))
1592 icfLevel = ICFLevel::None;
1593 unsigned tailMerge = 1;
1594 bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER;
1595 bool ltoDebugPM = false;
1596 for (auto *arg : args.filtered(OPT_opt)) {
1597 std::string str = StringRef(arg->getValue()).lower();
1598 SmallVector<StringRef, 1> vec;
1599 StringRef(str).split(vec, ',');
1600 for (StringRef s : vec) {
1601 if (s == "ref") {
1602 doGC = true;
1603 } else if (s == "noref") {
1604 doGC = false;
1605 } else if (s == "icf" || s.startswith("icf=")) {
1606 icfLevel = ICFLevel::All;
1607 } else if (s == "safeicf") {
1608 icfLevel = ICFLevel::Safe;
1609 } else if (s == "noicf") {
1610 icfLevel = ICFLevel::None;
1611 } else if (s == "lldtailmerge") {
1612 tailMerge = 2;
1613 } else if (s == "nolldtailmerge") {
1614 tailMerge = 0;
1615 } else if (s == "ltonewpassmanager") {
1616 ltoNewPM = true;
1617 } else if (s == "noltonewpassmanager") {
1618 ltoNewPM = false;
1619 } else if (s == "ltodebugpassmanager") {
1620 ltoDebugPM = true;
1621 } else if (s == "noltodebugpassmanager") {
1622 ltoDebugPM = false;
1623 } else if (s.startswith("lldlto=")) {
1624 StringRef optLevel = s.substr(7);
1625 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1626 error("/opt:lldlto: invalid optimization level: " + optLevel);
1627 } else if (s.startswith("lldltojobs=")) {
1628 StringRef jobs = s.substr(11);
1629 if (!get_threadpool_strategy(jobs))
1630 error("/opt:lldltojobs: invalid job count: " + jobs);
1631 config->thinLTOJobs = jobs.str();
1632 } else if (s.startswith("lldltopartitions=")) {
1633 StringRef n = s.substr(17);
1634 if (n.getAsInteger(10, config->ltoPartitions) ||
1635 config->ltoPartitions == 0)
1636 error("/opt:lldltopartitions: invalid partition count: " + n);
1637 } else if (s != "lbr" && s != "nolbr")
1638 error("/opt: unknown option: " + s);
1642 if (!icfLevel)
1643 icfLevel = doGC ? ICFLevel::All : ICFLevel::None;
1644 config->doGC = doGC;
1645 config->doICF = icfLevel.getValue();
1646 config->tailMerge =
1647 (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2;
1648 config->ltoNewPassManager = ltoNewPM;
1649 config->ltoDebugPassManager = ltoDebugPM;
1651 // Handle /lldsavetemps
1652 if (args.hasArg(OPT_lldsavetemps))
1653 config->saveTemps = true;
1655 // Handle /kill-at
1656 if (args.hasArg(OPT_kill_at))
1657 config->killAt = true;
1659 // Handle /lldltocache
1660 if (auto *arg = args.getLastArg(OPT_lldltocache))
1661 config->ltoCache = arg->getValue();
1663 // Handle /lldsavecachepolicy
1664 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1665 config->ltoCachePolicy = CHECK(
1666 parseCachePruningPolicy(arg->getValue()),
1667 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1669 // Handle /failifmismatch
1670 for (auto *arg : args.filtered(OPT_failifmismatch))
1671 checkFailIfMismatch(arg->getValue(), nullptr);
1673 // Handle /merge
1674 for (auto *arg : args.filtered(OPT_merge))
1675 parseMerge(arg->getValue());
1677 // Add default section merging rules after user rules. User rules take
1678 // precedence, but we will emit a warning if there is a conflict.
1679 parseMerge(".idata=.rdata");
1680 parseMerge(".didat=.rdata");
1681 parseMerge(".edata=.rdata");
1682 parseMerge(".xdata=.rdata");
1683 parseMerge(".bss=.data");
1685 if (config->mingw) {
1686 parseMerge(".ctors=.rdata");
1687 parseMerge(".dtors=.rdata");
1688 parseMerge(".CRT=.rdata");
1691 // Handle /section
1692 for (auto *arg : args.filtered(OPT_section))
1693 parseSection(arg->getValue());
1695 // Handle /align
1696 if (auto *arg = args.getLastArg(OPT_align)) {
1697 parseNumbers(arg->getValue(), &config->align);
1698 if (!isPowerOf2_64(config->align))
1699 error("/align: not a power of two: " + StringRef(arg->getValue()));
1700 if (!args.hasArg(OPT_driver))
1701 warn("/align specified without /driver; image may not run");
1704 // Handle /aligncomm
1705 for (auto *arg : args.filtered(OPT_aligncomm))
1706 parseAligncomm(arg->getValue());
1708 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1709 // also passed.
1710 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1711 config->manifestDependency = arg->getValue();
1712 config->manifest = Configuration::SideBySide;
1715 // Handle /manifest and /manifest:
1716 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1717 if (arg->getOption().getID() == OPT_manifest)
1718 config->manifest = Configuration::SideBySide;
1719 else
1720 parseManifest(arg->getValue());
1723 // Handle /manifestuac
1724 if (auto *arg = args.getLastArg(OPT_manifestuac))
1725 parseManifestUAC(arg->getValue());
1727 // Handle /manifestfile
1728 if (auto *arg = args.getLastArg(OPT_manifestfile))
1729 config->manifestFile = arg->getValue();
1731 // Handle /manifestinput
1732 for (auto *arg : args.filtered(OPT_manifestinput))
1733 config->manifestInput.push_back(arg->getValue());
1735 if (!config->manifestInput.empty() &&
1736 config->manifest != Configuration::Embed) {
1737 fatal("/manifestinput: requires /manifest:embed");
1740 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1741 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1742 args.hasArg(OPT_thinlto_index_only_arg);
1743 config->thinLTOIndexOnlyArg =
1744 args.getLastArgValue(OPT_thinlto_index_only_arg);
1745 config->thinLTOPrefixReplace =
1746 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1747 config->thinLTOObjectSuffixReplace =
1748 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1749 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1750 config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate);
1751 config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file);
1752 // Handle miscellaneous boolean flags.
1753 config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch,
1754 OPT_lto_pgo_warn_mismatch_no, true);
1755 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1756 config->allowIsolation =
1757 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1758 config->incremental =
1759 args.hasFlag(OPT_incremental, OPT_incremental_no,
1760 !config->doGC && config->doICF == ICFLevel::None &&
1761 !args.hasArg(OPT_order) && !args.hasArg(OPT_profile));
1762 config->integrityCheck =
1763 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1764 config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false);
1765 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1766 for (auto *arg : args.filtered(OPT_swaprun))
1767 parseSwaprun(arg->getValue());
1768 config->terminalServerAware =
1769 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1770 config->debugDwarf = debug == DebugKind::Dwarf;
1771 config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full;
1772 config->debugSymtab = debug == DebugKind::Symtab;
1773 config->autoImport =
1774 args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw);
1775 config->pseudoRelocs = args.hasFlag(
1776 OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw);
1777 config->callGraphProfileSort = args.hasFlag(
1778 OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true);
1779 config->stdcallFixup =
1780 args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw);
1781 config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup);
1783 // Don't warn about long section names, such as .debug_info, for mingw or
1784 // when -debug:dwarf is requested.
1785 if (config->mingw || config->debugDwarf)
1786 config->warnLongSectionNames = false;
1788 config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file);
1789 config->mapFile = getMapFile(args, OPT_map, OPT_map_file);
1791 if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) {
1792 warn("/lldmap and /map have the same output file '" + config->mapFile +
1793 "'.\n>>> ignoring /lldmap");
1794 config->lldmapFile.clear();
1797 if (config->incremental && args.hasArg(OPT_profile)) {
1798 warn("ignoring '/incremental' due to '/profile' specification");
1799 config->incremental = false;
1802 if (config->incremental && args.hasArg(OPT_order)) {
1803 warn("ignoring '/incremental' due to '/order' specification");
1804 config->incremental = false;
1807 if (config->incremental && config->doGC) {
1808 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1809 "disable");
1810 config->incremental = false;
1813 if (config->incremental && config->doICF != ICFLevel::None) {
1814 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1815 "disable");
1816 config->incremental = false;
1819 if (errorCount())
1820 return;
1822 std::set<sys::fs::UniqueID> wholeArchives;
1823 for (auto *arg : args.filtered(OPT_wholearchive_file))
1824 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1825 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1826 wholeArchives.insert(*id);
1828 // A predicate returning true if a given path is an argument for
1829 // /wholearchive:, or /wholearchive is enabled globally.
1830 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1831 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1832 auto isWholeArchive = [&](StringRef path) -> bool {
1833 if (args.hasArg(OPT_wholearchive_flag))
1834 return true;
1835 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1836 return wholeArchives.count(*id);
1837 return false;
1840 // Create a list of input files. These can be given as OPT_INPUT options
1841 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1842 // and OPT_end_lib.
1843 bool inLib = false;
1844 for (auto *arg : args) {
1845 switch (arg->getOption().getID()) {
1846 case OPT_end_lib:
1847 if (!inLib)
1848 error("stray " + arg->getSpelling());
1849 inLib = false;
1850 break;
1851 case OPT_start_lib:
1852 if (inLib)
1853 error("nested " + arg->getSpelling());
1854 inLib = true;
1855 break;
1856 case OPT_wholearchive_file:
1857 if (Optional<StringRef> path = findFile(arg->getValue()))
1858 enqueuePath(*path, true, inLib);
1859 break;
1860 case OPT_INPUT:
1861 if (Optional<StringRef> path = findFile(arg->getValue()))
1862 enqueuePath(*path, isWholeArchive(*path), inLib);
1863 break;
1864 default:
1865 // Ignore other options.
1866 break;
1870 // Process files specified as /defaultlib. These should be enequeued after
1871 // other files, which is why they are in a separate loop.
1872 for (auto *arg : args.filtered(OPT_defaultlib))
1873 if (Optional<StringRef> path = findLib(arg->getValue()))
1874 enqueuePath(*path, false, false);
1876 // Windows specific -- Create a resource file containing a manifest file.
1877 if (config->manifest == Configuration::Embed)
1878 addBuffer(createManifestRes(), false, false);
1880 // Read all input files given via the command line.
1881 run();
1883 if (errorCount())
1884 return;
1886 // We should have inferred a machine type by now from the input files, but if
1887 // not we assume x64.
1888 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1889 warn("/machine is not specified. x64 is assumed");
1890 config->machine = AMD64;
1892 config->wordsize = config->is64() ? 8 : 4;
1894 // Handle /safeseh, x86 only, on by default, except for mingw.
1895 if (config->machine == I386) {
1896 config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw);
1897 config->noSEH = args.hasArg(OPT_noseh);
1900 // Handle /functionpadmin
1901 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1902 parseFunctionPadMin(arg, config->machine);
1904 if (tar)
1905 tar->append("response.txt",
1906 createResponseFile(args, filePaths,
1907 ArrayRef<StringRef>(searchPaths).slice(1)));
1909 // Handle /largeaddressaware
1910 config->largeAddressAware = args.hasFlag(
1911 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1913 // Handle /highentropyva
1914 config->highEntropyVA =
1915 config->is64() &&
1916 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1918 if (!config->dynamicBase &&
1919 (config->machine == ARMNT || config->machine == ARM64))
1920 error("/dynamicbase:no is not compatible with " +
1921 machineToStr(config->machine));
1923 // Handle /export
1924 for (auto *arg : args.filtered(OPT_export)) {
1925 Export e = parseExport(arg->getValue());
1926 if (config->machine == I386) {
1927 if (!isDecorated(e.name))
1928 e.name = saver.save("_" + e.name);
1929 if (!e.extName.empty() && !isDecorated(e.extName))
1930 e.extName = saver.save("_" + e.extName);
1932 config->exports.push_back(e);
1935 // Handle /def
1936 if (auto *arg = args.getLastArg(OPT_deffile)) {
1937 // parseModuleDefs mutates Config object.
1938 parseModuleDefs(arg->getValue());
1941 // Handle generation of import library from a def file.
1942 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1943 fixupExports();
1944 createImportLibrary(/*asLib=*/true);
1945 return;
1948 // Windows specific -- if no /subsystem is given, we need to infer
1949 // that from entry point name. Must happen before /entry handling,
1950 // and after the early return when just writing an import library.
1951 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1952 config->subsystem = inferSubsystem();
1953 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1954 fatal("subsystem must be defined");
1957 // Handle /entry and /dll
1958 if (auto *arg = args.getLastArg(OPT_entry)) {
1959 config->entry = addUndefined(mangle(arg->getValue()));
1960 } else if (!config->entry && !config->noEntry) {
1961 if (args.hasArg(OPT_dll)) {
1962 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1963 : "_DllMainCRTStartup";
1964 config->entry = addUndefined(s);
1965 } else if (config->driverWdm) {
1966 // /driver:wdm implies /entry:_NtProcessStartup
1967 config->entry = addUndefined(mangle("_NtProcessStartup"));
1968 } else {
1969 // Windows specific -- If entry point name is not given, we need to
1970 // infer that from user-defined entry name.
1971 StringRef s = findDefaultEntry();
1972 if (s.empty())
1973 fatal("entry point must be defined");
1974 config->entry = addUndefined(s);
1975 log("Entry name inferred: " + s);
1979 // Handle /delayload
1980 for (auto *arg : args.filtered(OPT_delayload)) {
1981 config->delayLoads.insert(StringRef(arg->getValue()).lower());
1982 if (config->machine == I386) {
1983 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1984 } else {
1985 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1989 // Set default image name if neither /out or /def set it.
1990 if (config->outputFile.empty()) {
1991 config->outputFile = getOutputPath(
1992 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
1995 // Fail early if an output file is not writable.
1996 if (auto e = tryCreateFile(config->outputFile)) {
1997 error("cannot open output file " + config->outputFile + ": " + e.message());
1998 return;
2001 if (shouldCreatePDB) {
2002 // Put the PDB next to the image if no /pdb flag was passed.
2003 if (config->pdbPath.empty()) {
2004 config->pdbPath = config->outputFile;
2005 sys::path::replace_extension(config->pdbPath, ".pdb");
2008 // The embedded PDB path should be the absolute path to the PDB if no
2009 // /pdbaltpath flag was passed.
2010 if (config->pdbAltPath.empty()) {
2011 config->pdbAltPath = config->pdbPath;
2013 // It's important to make the path absolute and remove dots. This path
2014 // will eventually be written into the PE header, and certain Microsoft
2015 // tools won't work correctly if these assumptions are not held.
2016 sys::fs::make_absolute(config->pdbAltPath);
2017 sys::path::remove_dots(config->pdbAltPath);
2018 } else {
2019 // Don't do this earlier, so that Config->OutputFile is ready.
2020 parsePDBAltPath(config->pdbAltPath);
2024 // Set default image base if /base is not given.
2025 if (config->imageBase == uint64_t(-1))
2026 config->imageBase = getDefaultImageBase();
2028 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
2029 if (config->machine == I386) {
2030 symtab->addAbsolute("___safe_se_handler_table", 0);
2031 symtab->addAbsolute("___safe_se_handler_count", 0);
2034 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
2035 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
2036 symtab->addAbsolute(mangle("__guard_flags"), 0);
2037 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
2038 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
2039 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
2040 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
2041 // Needed for MSVC 2017 15.5 CRT.
2042 symtab->addAbsolute(mangle("__enclave_config"), 0);
2043 // Needed for MSVC 2019 16.8 CRT.
2044 symtab->addAbsolute(mangle("__guard_eh_cont_count"), 0);
2045 symtab->addAbsolute(mangle("__guard_eh_cont_table"), 0);
2047 if (config->pseudoRelocs) {
2048 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
2049 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
2051 if (config->mingw) {
2052 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
2053 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
2056 // This code may add new undefined symbols to the link, which may enqueue more
2057 // symbol resolution tasks, so we need to continue executing tasks until we
2058 // converge.
2059 do {
2060 // Windows specific -- if entry point is not found,
2061 // search for its mangled names.
2062 if (config->entry)
2063 mangleMaybe(config->entry);
2065 // Windows specific -- Make sure we resolve all dllexported symbols.
2066 for (Export &e : config->exports) {
2067 if (!e.forwardTo.empty())
2068 continue;
2069 e.sym = addUndefined(e.name);
2070 if (!e.directives)
2071 e.symbolName = mangleMaybe(e.sym);
2074 // Add weak aliases. Weak aliases is a mechanism to give remaining
2075 // undefined symbols final chance to be resolved successfully.
2076 for (auto pair : config->alternateNames) {
2077 StringRef from = pair.first;
2078 StringRef to = pair.second;
2079 Symbol *sym = symtab->find(from);
2080 if (!sym)
2081 continue;
2082 if (auto *u = dyn_cast<Undefined>(sym))
2083 if (!u->weakAlias)
2084 u->weakAlias = symtab->addUndefined(to);
2087 // If any inputs are bitcode files, the LTO code generator may create
2088 // references to library functions that are not explicit in the bitcode
2089 // file's symbol table. If any of those library functions are defined in a
2090 // bitcode file in an archive member, we need to arrange to use LTO to
2091 // compile those archive members by adding them to the link beforehand.
2092 if (!BitcodeFile::instances.empty())
2093 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
2094 symtab->addLibcall(s);
2096 // Windows specific -- if __load_config_used can be resolved, resolve it.
2097 if (symtab->findUnderscore("_load_config_used"))
2098 addUndefined(mangle("_load_config_used"));
2099 } while (run());
2101 if (args.hasArg(OPT_include_optional)) {
2102 // Handle /includeoptional
2103 for (auto *arg : args.filtered(OPT_include_optional))
2104 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
2105 addUndefined(arg->getValue());
2106 while (run());
2109 // Create wrapped symbols for -wrap option.
2110 std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args);
2111 // Load more object files that might be needed for wrapped symbols.
2112 if (!wrapped.empty())
2113 while (run());
2115 if (config->autoImport || config->stdcallFixup) {
2116 // MinGW specific.
2117 // Load any further object files that might be needed for doing automatic
2118 // imports, and do stdcall fixups.
2120 // For cases with no automatically imported symbols, this iterates once
2121 // over the symbol table and doesn't do anything.
2123 // For the normal case with a few automatically imported symbols, this
2124 // should only need to be run once, since each new object file imported
2125 // is an import library and wouldn't add any new undefined references,
2126 // but there's nothing stopping the __imp_ symbols from coming from a
2127 // normal object file as well (although that won't be used for the
2128 // actual autoimport later on). If this pass adds new undefined references,
2129 // we won't iterate further to resolve them.
2131 // If stdcall fixups only are needed for loading import entries from
2132 // a DLL without import library, this also just needs running once.
2133 // If it ends up pulling in more object files from static libraries,
2134 // (and maybe doing more stdcall fixups along the way), this would need
2135 // to loop these two calls.
2136 symtab->loadMinGWSymbols();
2137 run();
2140 // At this point, we should not have any symbols that cannot be resolved.
2141 // If we are going to do codegen for link-time optimization, check for
2142 // unresolvable symbols first, so we don't spend time generating code that
2143 // will fail to link anyway.
2144 if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
2145 symtab->reportUnresolvable();
2146 if (errorCount())
2147 return;
2149 config->hadExplicitExports = !config->exports.empty();
2150 if (config->mingw) {
2151 // In MinGW, all symbols are automatically exported if no symbols
2152 // are chosen to be exported.
2153 maybeExportMinGWSymbols(args);
2156 // Do LTO by compiling bitcode input files to a set of native COFF files then
2157 // link those files (unless -thinlto-index-only was given, in which case we
2158 // resolve symbols and write indices, but don't generate native code or link).
2159 symtab->addCombinedLTOObjects();
2161 // If -thinlto-index-only is given, we should create only "index
2162 // files" and not object files. Index file creation is already done
2163 // in addCombinedLTOObject, so we are done if that's the case.
2164 if (config->thinLTOIndexOnly)
2165 return;
2167 // If we generated native object files from bitcode files, this resolves
2168 // references to the symbols we use from them.
2169 run();
2171 // Apply symbol renames for -wrap.
2172 if (!wrapped.empty())
2173 wrapSymbols(wrapped);
2175 // Resolve remaining undefined symbols and warn about imported locals.
2176 symtab->resolveRemainingUndefines();
2177 if (errorCount())
2178 return;
2180 if (config->mingw) {
2181 // Make sure the crtend.o object is the last object file. This object
2182 // file can contain terminating section chunks that need to be placed
2183 // last. GNU ld processes files and static libraries explicitly in the
2184 // order provided on the command line, while lld will pull in needed
2185 // files from static libraries only after the last object file on the
2186 // command line.
2187 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
2188 i != e; i++) {
2189 ObjFile *file = *i;
2190 if (isCrtend(file->getName())) {
2191 ObjFile::instances.erase(i);
2192 ObjFile::instances.push_back(file);
2193 break;
2198 // Windows specific -- when we are creating a .dll file, we also
2199 // need to create a .lib file. In MinGW mode, we only do that when the
2200 // -implib option is given explicitly, for compatibility with GNU ld.
2201 if (!config->exports.empty() || config->dll) {
2202 fixupExports();
2203 if (!config->mingw || !config->implib.empty())
2204 createImportLibrary(/*asLib=*/false);
2205 assignExportOrdinals();
2208 // Handle /output-def (MinGW specific).
2209 if (auto *arg = args.getLastArg(OPT_output_def))
2210 writeDefFile(arg->getValue());
2212 // Set extra alignment for .comm symbols
2213 for (auto pair : config->alignComm) {
2214 StringRef name = pair.first;
2215 uint32_t alignment = pair.second;
2217 Symbol *sym = symtab->find(name);
2218 if (!sym) {
2219 warn("/aligncomm symbol " + name + " not found");
2220 continue;
2223 // If the symbol isn't common, it must have been replaced with a regular
2224 // symbol, which will carry its own alignment.
2225 auto *dc = dyn_cast<DefinedCommon>(sym);
2226 if (!dc)
2227 continue;
2229 CommonChunk *c = dc->getChunk();
2230 c->setAlignment(std::max(c->getAlignment(), alignment));
2233 // Windows specific -- Create a side-by-side manifest file.
2234 if (config->manifest == Configuration::SideBySide)
2235 createSideBySideManifest();
2237 // Handle /order. We want to do this at this moment because we
2238 // need a complete list of comdat sections to warn on nonexistent
2239 // functions.
2240 if (auto *arg = args.getLastArg(OPT_order)) {
2241 if (args.hasArg(OPT_call_graph_ordering_file))
2242 error("/order and /call-graph-order-file may not be used together");
2243 parseOrderFile(arg->getValue());
2244 config->callGraphProfileSort = false;
2247 // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on).
2248 if (config->callGraphProfileSort) {
2249 if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) {
2250 parseCallGraphFile(arg->getValue());
2252 readCallGraphsFromObjectFiles();
2255 // Handle /print-symbol-order.
2256 if (auto *arg = args.getLastArg(OPT_print_symbol_order))
2257 config->printSymbolOrder = arg->getValue();
2259 // Identify unreferenced COMDAT sections.
2260 if (config->doGC) {
2261 if (config->mingw) {
2262 // markLive doesn't traverse .eh_frame, but the personality function is
2263 // only reached that way. The proper solution would be to parse and
2264 // traverse the .eh_frame section, like the ELF linker does.
2265 // For now, just manually try to retain the known possible personality
2266 // functions. This doesn't bring in more object files, but only marks
2267 // functions that already have been included to be retained.
2268 for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) {
2269 Defined *d = dyn_cast_or_null<Defined>(symtab->findUnderscore(n));
2270 if (d && !d->isGCRoot) {
2271 d->isGCRoot = true;
2272 config->gcroot.push_back(d);
2277 markLive(symtab->getChunks());
2280 // Needs to happen after the last call to addFile().
2281 convertResources();
2283 // Identify identical COMDAT sections to merge them.
2284 if (config->doICF != ICFLevel::None) {
2285 findKeepUniqueSections();
2286 doICF(symtab->getChunks(), config->doICF);
2289 // Write the result.
2290 writeResult();
2292 // Stop early so we can print the results.
2293 rootTimer.stop();
2294 if (config->showTiming)
2295 Timer::root().print();
2298 } // namespace coff
2299 } // namespace lld