· 6 years ago · Jan 04, 2020, 04:02 AM
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//===----------------------------------------------------------------------===//
8
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/Threads.h"
25#include "lld/Common/Timer.h"
26#include "lld/Common/Version.h"
27#include "llvm/ADT/Optional.h"
28#include "llvm/ADT/StringSwitch.h"
29#include "llvm/BinaryFormat/Magic.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/CommandLine.h"
39#include "llvm/Support/Debug.h"
40#include "llvm/Support/LEB128.h"
41#include "llvm/Support/MathExtras.h"
42#include "llvm/Support/Path.h"
43#include "llvm/Support/Process.h"
44#include "llvm/Support/TarWriter.h"
45#include "llvm/Support/TargetSelect.h"
46#include "llvm/Support/raw_ostream.h"
47#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
48#include <algorithm>
49#include <future>
50#include <memory>
51#include "llvm/Passes/PassPlugin.h"
52
53using namespace llvm;
54using namespace llvm::object;
55using namespace llvm::COFF;
56using llvm::sys::Process;
57
58#define HANDLE_EXTENSION(Ext) \
59 llvm::PassPluginLibraryInfo get##Ext##PluginInfo();
60#include "llvm/Support/Extension.def"
61
62namespace lld {
63namespace coff {
64
65static Timer inputFileTimer("Input File Reading", Timer::root());
66
67Configuration *config;
68LinkerDriver *driver;
69
70bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS,
71 raw_ostream &stderrOS) {
72 lld::stdoutOS = &stdoutOS;
73 lld::stderrOS = &stderrOS;
74
75 errorHandler().logName = args::getFilenameWithoutExe(args[0]);
76 errorHandler().errorLimitExceededMsg =
77 "too many errors emitted, stopping now"
78 " (use /errorlimit:0 to see all errors)";
79 errorHandler().exitEarly = canExitEarly;
80 stderrOS.enable_colors(stderrOS.has_colors());
81
82 config = make<Configuration>();
83 symtab = make<SymbolTable>();
84 driver = make<LinkerDriver>();
85
86 driver->link(args);
87
88 // Call exit() if we can to avoid calling destructors.
89 if (canExitEarly)
90 exitLld(errorCount() ? 1 : 0);
91
92 freeArena();
93 ObjFile::instances.clear();
94 ImportFile::instances.clear();
95 BitcodeFile::instances.clear();
96 memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances));
97 return !errorCount();
98}
99
100// Parse options of the form "old;new".
101static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
102 unsigned id) {
103 auto *arg = args.getLastArg(id);
104 if (!arg)
105 return {"", ""};
106
107 StringRef s = arg->getValue();
108 std::pair<StringRef, StringRef> ret = s.split(';');
109 if (ret.second.empty())
110 error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
111 return ret;
112}
113
114// Drop directory components and replace extension with
115// ".exe", ".dll" or ".sys".
116static std::string getOutputPath(StringRef path) {
117 StringRef ext = ".exe";
118 if (config->dll)
119 ext = ".dll";
120 else if (config->driver)
121 ext = ".sys";
122
123 return (sys::path::stem(path) + ext).str();
124}
125
126// Returns true if S matches /crtend.?\.o$/.
127static bool isCrtend(StringRef s) {
128 if (!s.endswith(".o"))
129 return false;
130 s = s.drop_back(2);
131 if (s.endswith("crtend"))
132 return true;
133 return !s.empty() && s.drop_back().endswith("crtend");
134}
135
136// ErrorOr is not default constructible, so it cannot be used as the type
137// parameter of a future.
138// FIXME: We could open the file in createFutureForFile and avoid needing to
139// return an error here, but for the moment that would cost us a file descriptor
140// (a limited resource on Windows) for the duration that the future is pending.
141using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>;
142
143// Create a std::future that opens and maps a file using the best strategy for
144// the host platform.
145static std::future<MBErrPair> createFutureForFile(std::string path) {
146#if _WIN32
147 // On Windows, file I/O is relatively slow so it is best to do this
148 // asynchronously.
149 auto strategy = std::launch::async;
150#else
151 auto strategy = std::launch::deferred;
152#endif
153 return std::async(strategy, [=]() {
154 auto mbOrErr = MemoryBuffer::getFile(path,
155 /*FileSize*/ -1,
156 /*RequiresNullTerminator*/ false);
157 if (!mbOrErr)
158 return MBErrPair{nullptr, mbOrErr.getError()};
159 return MBErrPair{std::move(*mbOrErr), std::error_code()};
160 });
161}
162
163// Symbol names are mangled by prepending "_" on x86.
164static StringRef mangle(StringRef sym) {
165 assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN);
166 if (config->machine == I386)
167 return saver.save("_" + sym);
168 return sym;
169}
170
171static bool findUnderscoreMangle(StringRef sym) {
172 Symbol *s = symtab->findMangle(mangle(sym));
173 return s && !isa<Undefined>(s);
174}
175
176MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) {
177 MemoryBufferRef mbref = *mb;
178 make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership
179
180 if (driver->tar)
181 driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()),
182 mbref.getBuffer());
183 return mbref;
184}
185
186void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb,
187 bool wholeArchive, bool lazy) {
188 StringRef filename = mb->getBufferIdentifier();
189
190 MemoryBufferRef mbref = takeBuffer(std::move(mb));
191 filePaths.push_back(filename);
192
193 // File type is detected by contents, not by file extension.
194 switch (identify_magic(mbref.getBuffer())) {
195 case file_magic::windows_resource:
196 resources.push_back(mbref);
197 break;
198 case file_magic::archive:
199 if (wholeArchive) {
200 std::unique_ptr<Archive> file =
201 CHECK(Archive::create(mbref), filename + ": failed to parse archive");
202 Archive *archive = file.get();
203 make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
204
205 int memberIndex = 0;
206 for (MemoryBufferRef m : getArchiveMembers(archive))
207 addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++);
208 return;
209 }
210 symtab->addFile(make<ArchiveFile>(mbref));
211 break;
212 case file_magic::bitcode:
213 if (lazy)
214 symtab->addFile(make<LazyObjFile>(mbref));
215 else
216 symtab->addFile(make<BitcodeFile>(mbref, "", 0));
217 break;
218 case file_magic::coff_object:
219 case file_magic::coff_import_library:
220 if (lazy)
221 symtab->addFile(make<LazyObjFile>(mbref));
222 else
223 symtab->addFile(make<ObjFile>(mbref));
224 break;
225 case file_magic::pdb:
226 loadTypeServerSource(mbref);
227 break;
228 case file_magic::coff_cl_gl_object:
229 error(filename + ": is not a native COFF file. Recompile without /GL");
230 break;
231 case file_magic::pecoff_executable:
232 if (filename.endswith_lower(".dll")) {
233 error(filename + ": bad file type. Did you specify a DLL instead of an "
234 "import library?");
235 break;
236 }
237 LLVM_FALLTHROUGH;
238 default:
239 error(mbref.getBufferIdentifier() + ": unknown file type");
240 break;
241 }
242}
243
244void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) {
245 auto future =
246 std::make_shared<std::future<MBErrPair>>(createFutureForFile(path));
247 std::string pathStr = path;
248 enqueueTask([=]() {
249 auto mbOrErr = future->get();
250 if (mbOrErr.second) {
251 std::string msg =
252 "could not open '" + pathStr + "': " + mbOrErr.second.message();
253 // Check if the filename is a typo for an option flag. OptTable thinks
254 // that all args that are not known options and that start with / are
255 // filenames, but e.g. `/nodefaultlibs` is more likely a typo for
256 // the option `/nodefaultlib` than a reference to a file in the root
257 // directory.
258 std::string nearest;
259 if (COFFOptTable().findNearest(pathStr, nearest) > 1)
260 error(msg);
261 else
262 error(msg + "; did you mean '" + nearest + "'");
263 } else
264 driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy);
265 });
266}
267
268void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName,
269 StringRef parentName,
270 uint64_t offsetInArchive) {
271 file_magic magic = identify_magic(mb.getBuffer());
272 if (magic == file_magic::coff_import_library) {
273 InputFile *imp = make<ImportFile>(mb);
274 imp->parentName = parentName;
275 symtab->addFile(imp);
276 return;
277 }
278
279 InputFile *obj;
280 if (magic == file_magic::coff_object) {
281 obj = make<ObjFile>(mb);
282 } else if (magic == file_magic::bitcode) {
283 obj = make<BitcodeFile>(mb, parentName, offsetInArchive);
284 } else {
285 error("unknown file type: " + mb.getBufferIdentifier());
286 return;
287 }
288
289 obj->parentName = parentName;
290 symtab->addFile(obj);
291 log("Loaded " + toString(obj) + " for " + symName);
292}
293
294void LinkerDriver::enqueueArchiveMember(const Archive::Child &c,
295 const Archive::Symbol &sym,
296 StringRef parentName) {
297
298 auto reportBufferError = [=](Error &&e, StringRef childName) {
299 fatal("could not get the buffer for the member defining symbol " +
300 toCOFFString(sym) + ": " + parentName + "(" + childName + "): " +
301 toString(std::move(e)));
302 };
303
304 if (!c.getParent()->isThin()) {
305 uint64_t offsetInArchive = c.getChildOffset();
306 Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef();
307 if (!mbOrErr)
308 reportBufferError(mbOrErr.takeError(), check(c.getFullName()));
309 MemoryBufferRef mb = mbOrErr.get();
310 enqueueTask([=]() {
311 driver->addArchiveBuffer(mb, toCOFFString(sym), parentName,
312 offsetInArchive);
313 });
314 return;
315 }
316
317 std::string childName = CHECK(
318 c.getFullName(),
319 "could not get the filename for the member defining symbol " +
320 toCOFFString(sym));
321 auto future = std::make_shared<std::future<MBErrPair>>(
322 createFutureForFile(childName));
323 enqueueTask([=]() {
324 auto mbOrErr = future->get();
325 if (mbOrErr.second)
326 reportBufferError(errorCodeToError(mbOrErr.second), childName);
327 // Pass empty string as archive name so that the original filename is
328 // used as the buffer identifier.
329 driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)),
330 toCOFFString(sym), "", /*OffsetInArchive=*/0);
331 });
332}
333
334static bool isDecorated(StringRef sym) {
335 return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") ||
336 (!config->mingw && sym.contains('@'));
337}
338
339// Parses .drectve section contents and returns a list of files
340// specified by /defaultlib.
341void LinkerDriver::parseDirectives(InputFile *file) {
342 StringRef s = file->getDirectives();
343 if (s.empty())
344 return;
345
346 log("Directives: " + toString(file) + ": " + s);
347
348 ArgParser parser;
349 // .drectve is always tokenized using Windows shell rules.
350 // /EXPORT: option can appear too many times, processing in fastpath.
351 opt::InputArgList args;
352 std::vector<StringRef> exports;
353 std::tie(args, exports) = parser.parseDirectives(s);
354
355 for (StringRef e : exports) {
356 // If a common header file contains dllexported function
357 // declarations, many object files may end up with having the
358 // same /EXPORT options. In order to save cost of parsing them,
359 // we dedup them first.
360 if (!directivesExports.insert(e).second)
361 continue;
362
363 Export exp = parseExport(e);
364 if (config->machine == I386 && config->mingw) {
365 if (!isDecorated(exp.name))
366 exp.name = saver.save("_" + exp.name);
367 if (!exp.extName.empty() && !isDecorated(exp.extName))
368 exp.extName = saver.save("_" + exp.extName);
369 }
370 exp.directives = true;
371 config->exports.push_back(exp);
372 }
373
374 for (auto *arg : args) {
375 switch (arg->getOption().getID()) {
376 case OPT_aligncomm:
377 parseAligncomm(arg->getValue());
378 break;
379 case OPT_alternatename:
380 parseAlternateName(arg->getValue());
381 break;
382 case OPT_defaultlib:
383 if (Optional<StringRef> path = findLib(arg->getValue()))
384 enqueuePath(*path, false, false);
385 break;
386 case OPT_entry:
387 config->entry = addUndefined(mangle(arg->getValue()));
388 break;
389 case OPT_failifmismatch:
390 checkFailIfMismatch(arg->getValue(), file);
391 break;
392 case OPT_incl:
393 addUndefined(arg->getValue());
394 break;
395 case OPT_merge:
396 parseMerge(arg->getValue());
397 break;
398 case OPT_nodefaultlib:
399 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
400 break;
401 case OPT_section:
402 parseSection(arg->getValue());
403 break;
404 case OPT_subsystem:
405 parseSubsystem(arg->getValue(), &config->subsystem,
406 &config->majorOSVersion, &config->minorOSVersion);
407 break;
408 // Only add flags here that link.exe accepts in
409 // `#pragma comment(linker, "/flag")`-generated sections.
410 case OPT_editandcontinue:
411 case OPT_guardsym:
412 case OPT_throwingnew:
413 break;
414 default:
415 error(arg->getSpelling() + " is not allowed in .drectve");
416 }
417 }
418}
419
420// Find file from search paths. You can omit ".obj", this function takes
421// care of that. Note that the returned path is not guaranteed to exist.
422StringRef LinkerDriver::doFindFile(StringRef filename) {
423 bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos);
424 if (hasPathSep)
425 return filename;
426 bool hasExt = filename.contains('.');
427 for (StringRef dir : searchPaths) {
428 SmallString<128> path = dir;
429 sys::path::append(path, filename);
430 if (sys::fs::exists(path.str()))
431 return saver.save(path.str());
432 if (!hasExt) {
433 path.append(".obj");
434 if (sys::fs::exists(path.str()))
435 return saver.save(path.str());
436 }
437 }
438 return filename;
439}
440
441static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) {
442 sys::fs::UniqueID ret;
443 if (sys::fs::getUniqueID(path, ret))
444 return None;
445 return ret;
446}
447
448// Resolves a file path. This never returns the same path
449// (in that case, it returns None).
450Optional<StringRef> LinkerDriver::findFile(StringRef filename) {
451 StringRef path = doFindFile(filename);
452
453 if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) {
454 bool seen = !visitedFiles.insert(*id).second;
455 if (seen)
456 return None;
457 }
458
459 if (path.endswith_lower(".lib"))
460 visitedLibs.insert(sys::path::filename(path));
461 return path;
462}
463
464// MinGW specific. If an embedded directive specified to link to
465// foo.lib, but it isn't found, try libfoo.a instead.
466StringRef LinkerDriver::doFindLibMinGW(StringRef filename) {
467 if (filename.contains('/') || filename.contains('\\'))
468 return filename;
469
470 SmallString<128> s = filename;
471 sys::path::replace_extension(s, ".a");
472 StringRef libName = saver.save("lib" + s.str());
473 return doFindFile(libName);
474}
475
476// Find library file from search path.
477StringRef LinkerDriver::doFindLib(StringRef filename) {
478 // Add ".lib" to Filename if that has no file extension.
479 bool hasExt = filename.contains('.');
480 if (!hasExt)
481 filename = saver.save(filename + ".lib");
482 StringRef ret = doFindFile(filename);
483 // For MinGW, if the find above didn't turn up anything, try
484 // looking for a MinGW formatted library name.
485 if (config->mingw && ret == filename)
486 return doFindLibMinGW(filename);
487 return ret;
488}
489
490// Resolves a library path. /nodefaultlib options are taken into
491// consideration. This never returns the same path (in that case,
492// it returns None).
493Optional<StringRef> LinkerDriver::findLib(StringRef filename) {
494 if (config->noDefaultLibAll)
495 return None;
496 if (!visitedLibs.insert(filename.lower()).second)
497 return None;
498
499 StringRef path = doFindLib(filename);
500 if (config->noDefaultLibs.count(path.lower()))
501 return None;
502
503 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
504 if (!visitedFiles.insert(*id).second)
505 return None;
506 return path;
507}
508
509// Parses LIB environment which contains a list of search paths.
510void LinkerDriver::addLibSearchPaths() {
511 Optional<std::string> envOpt = Process::GetEnv("LIB");
512 if (!envOpt.hasValue())
513 return;
514 StringRef env = saver.save(*envOpt);
515 while (!env.empty()) {
516 StringRef path;
517 std::tie(path, env) = env.split(';');
518 searchPaths.push_back(path);
519 }
520}
521
522Symbol *LinkerDriver::addUndefined(StringRef name) {
523 Symbol *b = symtab->addUndefined(name);
524 if (!b->isGCRoot) {
525 b->isGCRoot = true;
526 config->gcroot.push_back(b);
527 }
528 return b;
529}
530
531StringRef LinkerDriver::mangleMaybe(Symbol *s) {
532 // If the plain symbol name has already been resolved, do nothing.
533 Undefined *unmangled = dyn_cast<Undefined>(s);
534 if (!unmangled)
535 return "";
536
537 // Otherwise, see if a similar, mangled symbol exists in the symbol table.
538 Symbol *mangled = symtab->findMangle(unmangled->getName());
539 if (!mangled)
540 return "";
541
542 // If we find a similar mangled symbol, make this an alias to it and return
543 // its name.
544 log(unmangled->getName() + " aliased to " + mangled->getName());
545 unmangled->weakAlias = symtab->addUndefined(mangled->getName());
546 return mangled->getName();
547}
548
549// Windows specific -- find default entry point name.
550//
551// There are four different entry point functions for Windows executables,
552// each of which corresponds to a user-defined "main" function. This function
553// infers an entry point from a user-defined "main" function.
554StringRef LinkerDriver::findDefaultEntry() {
555 assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
556 "must handle /subsystem before calling this");
557
558 if (config->mingw)
559 return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI
560 ? "WinMainCRTStartup"
561 : "mainCRTStartup");
562
563 if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
564 if (findUnderscoreMangle("wWinMain")) {
565 if (!findUnderscoreMangle("WinMain"))
566 return mangle("wWinMainCRTStartup");
567 warn("found both wWinMain and WinMain; using latter");
568 }
569 return mangle("WinMainCRTStartup");
570 }
571 if (findUnderscoreMangle("wmain")) {
572 if (!findUnderscoreMangle("main"))
573 return mangle("wmainCRTStartup");
574 warn("found both wmain and main; using latter");
575 }
576 return mangle("mainCRTStartup");
577}
578
579WindowsSubsystem LinkerDriver::inferSubsystem() {
580 if (config->dll)
581 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
582 if (config->mingw)
583 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
584 // Note that link.exe infers the subsystem from the presence of these
585 // functions even if /entry: or /nodefaultlib are passed which causes them
586 // to not be called.
587 bool haveMain = findUnderscoreMangle("main");
588 bool haveWMain = findUnderscoreMangle("wmain");
589 bool haveWinMain = findUnderscoreMangle("WinMain");
590 bool haveWWinMain = findUnderscoreMangle("wWinMain");
591 if (haveMain || haveWMain) {
592 if (haveWinMain || haveWWinMain) {
593 warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " +
594 (haveWinMain ? "WinMain" : "wWinMain") +
595 "; defaulting to /subsystem:console");
596 }
597 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
598 }
599 if (haveWinMain || haveWWinMain)
600 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
601 return IMAGE_SUBSYSTEM_UNKNOWN;
602}
603
604static uint64_t getDefaultImageBase() {
605 if (config->is64())
606 return config->dll ? 0x180000000 : 0x140000000;
607 return config->dll ? 0x10000000 : 0x400000;
608}
609
610static std::string createResponseFile(const opt::InputArgList &args,
611 ArrayRef<StringRef> filePaths,
612 ArrayRef<StringRef> searchPaths) {
613 SmallString<0> data;
614 raw_svector_ostream os(data);
615
616 for (auto *arg : args) {
617 switch (arg->getOption().getID()) {
618 case OPT_linkrepro:
619 case OPT_reproduce:
620 case OPT_INPUT:
621 case OPT_defaultlib:
622 case OPT_libpath:
623 case OPT_manifest:
624 case OPT_manifest_colon:
625 case OPT_manifestdependency:
626 case OPT_manifestfile:
627 case OPT_manifestinput:
628 case OPT_manifestuac:
629 break;
630 case OPT_implib:
631 case OPT_pdb:
632 case OPT_out:
633 os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n";
634 break;
635 default:
636 os << toString(*arg) << "\n";
637 }
638 }
639
640 for (StringRef path : searchPaths) {
641 std::string relPath = relativeToRoot(path);
642 os << "/libpath:" << quote(relPath) << "\n";
643 }
644
645 for (StringRef path : filePaths)
646 os << quote(relativeToRoot(path)) << "\n";
647
648 return data.str();
649}
650
651enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab };
652
653static DebugKind parseDebugKind(const opt::InputArgList &args) {
654 auto *a = args.getLastArg(OPT_debug, OPT_debug_opt);
655 if (!a)
656 return DebugKind::None;
657 if (a->getNumValues() == 0)
658 return DebugKind::Full;
659
660 DebugKind debug = StringSwitch<DebugKind>(a->getValue())
661 .CaseLower("none", DebugKind::None)
662 .CaseLower("full", DebugKind::Full)
663 .CaseLower("fastlink", DebugKind::FastLink)
664 // LLD extensions
665 .CaseLower("ghash", DebugKind::GHash)
666 .CaseLower("dwarf", DebugKind::Dwarf)
667 .CaseLower("symtab", DebugKind::Symtab)
668 .Default(DebugKind::Unknown);
669
670 if (debug == DebugKind::FastLink) {
671 warn("/debug:fastlink unsupported; using /debug:full");
672 return DebugKind::Full;
673 }
674 if (debug == DebugKind::Unknown) {
675 error("/debug: unknown option: " + Twine(a->getValue()));
676 return DebugKind::None;
677 }
678 return debug;
679}
680
681static unsigned parseDebugTypes(const opt::InputArgList &args) {
682 unsigned debugTypes = static_cast<unsigned>(DebugType::None);
683
684 if (auto *a = args.getLastArg(OPT_debugtype)) {
685 SmallVector<StringRef, 3> types;
686 StringRef(a->getValue())
687 .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false);
688
689 for (StringRef type : types) {
690 unsigned v = StringSwitch<unsigned>(type.lower())
691 .Case("cv", static_cast<unsigned>(DebugType::CV))
692 .Case("pdata", static_cast<unsigned>(DebugType::PData))
693 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
694 .Default(0);
695 if (v == 0) {
696 warn("/debugtype: unknown option '" + type + "'");
697 continue;
698 }
699 debugTypes |= v;
700 }
701 return debugTypes;
702 }
703
704 // Default debug types
705 debugTypes = static_cast<unsigned>(DebugType::CV);
706 if (args.hasArg(OPT_driver))
707 debugTypes |= static_cast<unsigned>(DebugType::PData);
708 if (args.hasArg(OPT_profile))
709 debugTypes |= static_cast<unsigned>(DebugType::Fixup);
710
711 return debugTypes;
712}
713
714static std::string getMapFile(const opt::InputArgList &args) {
715 auto *arg = args.getLastArg(OPT_lldmap, OPT_lldmap_file);
716 if (!arg)
717 return "";
718 if (arg->getOption().getID() == OPT_lldmap_file)
719 return arg->getValue();
720
721 assert(arg->getOption().getID() == OPT_lldmap);
722 StringRef outFile = config->outputFile;
723 return (outFile.substr(0, outFile.rfind('.')) + ".map").str();
724}
725
726static std::string getImplibPath() {
727 if (!config->implib.empty())
728 return config->implib;
729 SmallString<128> out = StringRef(config->outputFile);
730 sys::path::replace_extension(out, ".lib");
731 return out.str();
732}
733
734// The import name is calculated as follows:
735//
736// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
737// -----+----------------+---------------------+------------------
738// LINK | {value} | {value}.{.dll/.exe} | {output name}
739// LIB | {value} | {value}.dll | {output name}.dll
740//
741static std::string getImportName(bool asLib) {
742 SmallString<128> out;
743
744 if (config->importName.empty()) {
745 out.assign(sys::path::filename(config->outputFile));
746 if (asLib)
747 sys::path::replace_extension(out, ".dll");
748 } else {
749 out.assign(config->importName);
750 if (!sys::path::has_extension(out))
751 sys::path::replace_extension(out,
752 (config->dll || asLib) ? ".dll" : ".exe");
753 }
754
755 return out.str();
756}
757
758static void createImportLibrary(bool asLib) {
759 std::vector<COFFShortExport> exports;
760 for (Export &e1 : config->exports) {
761 COFFShortExport e2;
762 e2.Name = e1.name;
763 e2.SymbolName = e1.symbolName;
764 e2.ExtName = e1.extName;
765 e2.Ordinal = e1.ordinal;
766 e2.Noname = e1.noname;
767 e2.Data = e1.data;
768 e2.Private = e1.isPrivate;
769 e2.Constant = e1.constant;
770 exports.push_back(e2);
771 }
772
773 auto handleError = [](Error &&e) {
774 handleAllErrors(std::move(e),
775 [](ErrorInfoBase &eib) { error(eib.message()); });
776 };
777 std::string libName = getImportName(asLib);
778 std::string path = getImplibPath();
779
780 if (!config->incremental) {
781 handleError(writeImportLibrary(libName, path, exports, config->machine,
782 config->mingw));
783 return;
784 }
785
786 // If the import library already exists, replace it only if the contents
787 // have changed.
788 ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile(
789 path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
790 if (!oldBuf) {
791 handleError(writeImportLibrary(libName, path, exports, config->machine,
792 config->mingw));
793 return;
794 }
795
796 SmallString<128> tmpName;
797 if (std::error_code ec =
798 sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName))
799 fatal("cannot create temporary file for import library " + path + ": " +
800 ec.message());
801
802 if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine,
803 config->mingw)) {
804 handleError(std::move(e));
805 return;
806 }
807
808 std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile(
809 tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
810 if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) {
811 oldBuf->reset();
812 handleError(errorCodeToError(sys::fs::rename(tmpName, path)));
813 } else {
814 sys::fs::remove(tmpName);
815 }
816}
817
818static void parseModuleDefs(StringRef path) {
819 std::unique_ptr<MemoryBuffer> mb = CHECK(
820 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
821 COFFModuleDefinition m = check(parseCOFFModuleDefinition(
822 mb->getMemBufferRef(), config->machine, config->mingw));
823
824 if (config->outputFile.empty())
825 config->outputFile = saver.save(m.OutputFile);
826 config->importName = saver.save(m.ImportName);
827 if (m.ImageBase)
828 config->imageBase = m.ImageBase;
829 if (m.StackReserve)
830 config->stackReserve = m.StackReserve;
831 if (m.StackCommit)
832 config->stackCommit = m.StackCommit;
833 if (m.HeapReserve)
834 config->heapReserve = m.HeapReserve;
835 if (m.HeapCommit)
836 config->heapCommit = m.HeapCommit;
837 if (m.MajorImageVersion)
838 config->majorImageVersion = m.MajorImageVersion;
839 if (m.MinorImageVersion)
840 config->minorImageVersion = m.MinorImageVersion;
841 if (m.MajorOSVersion)
842 config->majorOSVersion = m.MajorOSVersion;
843 if (m.MinorOSVersion)
844 config->minorOSVersion = m.MinorOSVersion;
845
846 for (COFFShortExport e1 : m.Exports) {
847 Export e2;
848 // In simple cases, only Name is set. Renamed exports are parsed
849 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
850 // it shouldn't be a normal exported function but a forward to another
851 // DLL instead. This is supported by both MS and GNU linkers.
852 if (e1.ExtName != e1.Name && StringRef(e1.Name).contains('.')) {
853 e2.name = saver.save(e1.ExtName);
854 e2.forwardTo = saver.save(e1.Name);
855 config->exports.push_back(e2);
856 continue;
857 }
858 e2.name = saver.save(e1.Name);
859 e2.extName = saver.save(e1.ExtName);
860 e2.ordinal = e1.Ordinal;
861 e2.noname = e1.Noname;
862 e2.data = e1.Data;
863 e2.isPrivate = e1.Private;
864 e2.constant = e1.Constant;
865 config->exports.push_back(e2);
866 }
867}
868
869void LinkerDriver::enqueueTask(std::function<void()> task) {
870 taskQueue.push_back(std::move(task));
871}
872
873bool LinkerDriver::run() {
874 ScopedTimer t(inputFileTimer);
875
876 bool didWork = !taskQueue.empty();
877 while (!taskQueue.empty()) {
878 taskQueue.front()();
879 taskQueue.pop_front();
880 }
881 return didWork;
882}
883
884// Parse an /order file. If an option is given, the linker places
885// COMDAT sections in the same order as their names appear in the
886// given file.
887static void parseOrderFile(StringRef arg) {
888 // For some reason, the MSVC linker requires a filename to be
889 // preceded by "@".
890 if (!arg.startswith("@")) {
891 error("malformed /order option: '@' missing");
892 return;
893 }
894
895 // Get a list of all comdat sections for error checking.
896 DenseSet<StringRef> set;
897 for (Chunk *c : symtab->getChunks())
898 if (auto *sec = dyn_cast<SectionChunk>(c))
899 if (sec->sym)
900 set.insert(sec->sym->getName());
901
902 // Open a file.
903 StringRef path = arg.substr(1);
904 std::unique_ptr<MemoryBuffer> mb = CHECK(
905 MemoryBuffer::getFile(path, -1, false, true), "could not open " + path);
906
907 // Parse a file. An order file contains one symbol per line.
908 // All symbols that were not present in a given order file are
909 // considered to have the lowest priority 0 and are placed at
910 // end of an output section.
911 for (std::string s : args::getLines(mb->getMemBufferRef())) {
912 if (config->machine == I386 && !isDecorated(s))
913 s = "_" + s;
914
915 if (set.count(s) == 0) {
916 if (config->warnMissingOrderSymbol)
917 warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]");
918 }
919 else
920 config->order[s] = INT_MIN + config->order.size();
921 }
922}
923
924static void markAddrsig(Symbol *s) {
925 if (auto *d = dyn_cast_or_null<Defined>(s))
926 if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk()))
927 c->keepUnique = true;
928}
929
930static void findKeepUniqueSections() {
931 // Exported symbols could be address-significant in other executables or DSOs,
932 // so we conservatively mark them as address-significant.
933 for (Export &r : config->exports)
934 markAddrsig(r.sym);
935
936 // Visit the address-significance table in each object file and mark each
937 // referenced symbol as address-significant.
938 for (ObjFile *obj : ObjFile::instances) {
939 ArrayRef<Symbol *> syms = obj->getSymbols();
940 if (obj->addrsigSec) {
941 ArrayRef<uint8_t> contents;
942 cantFail(
943 obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents));
944 const uint8_t *cur = contents.begin();
945 while (cur != contents.end()) {
946 unsigned size;
947 const char *err;
948 uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err);
949 if (err)
950 fatal(toString(obj) + ": could not decode addrsig section: " + err);
951 if (symIndex >= syms.size())
952 fatal(toString(obj) + ": invalid symbol index in addrsig section");
953 markAddrsig(syms[symIndex]);
954 cur += size;
955 }
956 } else {
957 // If an object file does not have an address-significance table,
958 // conservatively mark all of its symbols as address-significant.
959 for (Symbol *s : syms)
960 markAddrsig(s);
961 }
962 }
963}
964
965// link.exe replaces each %foo% in altPath with the contents of environment
966// variable foo, and adds the two magic env vars _PDB (expands to the basename
967// of pdb's output path) and _EXT (expands to the extension of the output
968// binary).
969// lld only supports %_PDB% and %_EXT% and warns on references to all other env
970// vars.
971static void parsePDBAltPath(StringRef altPath) {
972 SmallString<128> buf;
973 StringRef pdbBasename =
974 sys::path::filename(config->pdbPath, sys::path::Style::windows);
975 StringRef binaryExtension =
976 sys::path::extension(config->outputFile, sys::path::Style::windows);
977 if (!binaryExtension.empty())
978 binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'.
979
980 // Invariant:
981 // +--------- cursor ('a...' might be the empty string).
982 // | +----- firstMark
983 // | | +- secondMark
984 // v v v
985 // a...%...%...
986 size_t cursor = 0;
987 while (cursor < altPath.size()) {
988 size_t firstMark, secondMark;
989 if ((firstMark = altPath.find('%', cursor)) == StringRef::npos ||
990 (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) {
991 // Didn't find another full fragment, treat rest of string as literal.
992 buf.append(altPath.substr(cursor));
993 break;
994 }
995
996 // Found a full fragment. Append text in front of first %, and interpret
997 // text between first and second % as variable name.
998 buf.append(altPath.substr(cursor, firstMark - cursor));
999 StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1);
1000 if (var.equals_lower("%_pdb%"))
1001 buf.append(pdbBasename);
1002 else if (var.equals_lower("%_ext%"))
1003 buf.append(binaryExtension);
1004 else {
1005 warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " +
1006 var + " as literal");
1007 buf.append(var);
1008 }
1009
1010 cursor = secondMark + 1;
1011 }
1012
1013 config->pdbAltPath = buf;
1014}
1015
1016/// Convert resource files and potentially merge input resource object
1017/// trees into one resource tree.
1018/// Call after ObjFile::Instances is complete.
1019void LinkerDriver::convertResources() {
1020 std::vector<ObjFile *> resourceObjFiles;
1021
1022 for (ObjFile *f : ObjFile::instances) {
1023 if (f->isResourceObjFile())
1024 resourceObjFiles.push_back(f);
1025 }
1026
1027 if (!config->mingw &&
1028 (resourceObjFiles.size() > 1 ||
1029 (resourceObjFiles.size() == 1 && !resources.empty()))) {
1030 error((!resources.empty() ? "internal .obj file created from .res files"
1031 : toString(resourceObjFiles[1])) +
1032 ": more than one resource obj file not allowed, already got " +
1033 toString(resourceObjFiles.front()));
1034 return;
1035 }
1036
1037 if (resources.empty() && resourceObjFiles.size() <= 1) {
1038 // No resources to convert, and max one resource object file in
1039 // the input. Keep that preconverted resource section as is.
1040 for (ObjFile *f : resourceObjFiles)
1041 f->includeResourceChunks();
1042 return;
1043 }
1044 ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles));
1045 symtab->addFile(f);
1046 f->includeResourceChunks();
1047}
1048
1049// In MinGW, if no symbols are chosen to be exported, then all symbols are
1050// automatically exported by default. This behavior can be forced by the
1051// -export-all-symbols option, so that it happens even when exports are
1052// explicitly specified. The automatic behavior can be disabled using the
1053// -exclude-all-symbols option, so that lld-link behaves like link.exe rather
1054// than MinGW in the case that nothing is explicitly exported.
1055void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) {
1056 if (!config->dll)
1057 return;
1058
1059 if (!args.hasArg(OPT_export_all_symbols)) {
1060 if (!config->exports.empty())
1061 return;
1062 if (args.hasArg(OPT_exclude_all_symbols))
1063 return;
1064 }
1065
1066 AutoExporter exporter;
1067
1068 for (auto *arg : args.filtered(OPT_wholearchive_file))
1069 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1070 exporter.addWholeArchive(*path);
1071
1072 symtab->forEachSymbol([&](Symbol *s) {
1073 auto *def = dyn_cast<Defined>(s);
1074 if (!exporter.shouldExport(def))
1075 return;
1076
1077 Export e;
1078 e.name = def->getName();
1079 e.sym = def;
1080 if (Chunk *c = def->getChunk())
1081 if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1082 e.data = true;
1083 config->exports.push_back(e);
1084 });
1085}
1086
1087// lld has a feature to create a tar file containing all input files as well as
1088// all command line options, so that other people can run lld again with exactly
1089// the same inputs. This feature is accessible via /linkrepro and /reproduce.
1090//
1091// /linkrepro and /reproduce are very similar, but /linkrepro takes a directory
1092// name while /reproduce takes a full path. We have /linkrepro for compatibility
1093// with Microsoft link.exe.
1094Optional<std::string> getReproduceFile(const opt::InputArgList &args) {
1095 if (auto *arg = args.getLastArg(OPT_reproduce))
1096 return std::string(arg->getValue());
1097
1098 if (auto *arg = args.getLastArg(OPT_linkrepro)) {
1099 SmallString<64> path = StringRef(arg->getValue());
1100 sys::path::append(path, "repro.tar");
1101 return path.str().str();
1102 }
1103
1104 return None;
1105}
1106
1107void LinkerDriver::link(ArrayRef<const char *> argsArr) {
1108 // Needed for LTO.
1109 InitializeAllTargetInfos();
1110 InitializeAllTargets();
1111 InitializeAllTargetMCs();
1112 InitializeAllAsmParsers();
1113 InitializeAllAsmPrinters();
1114
1115 // If the first command line argument is "/lib", link.exe acts like lib.exe.
1116 // We call our own implementation of lib.exe that understands bitcode files.
1117 if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) {
1118 if (llvm::libDriverMain(argsArr.slice(1)) != 0)
1119 fatal("lib failed");
1120 return;
1121 }
1122
1123 // Parse command line options.
1124 ArgParser parser;
1125 opt::InputArgList args = parser.parse(argsArr);
1126
1127 // Parse and evaluate -mllvm options.
1128 std::vector<const char *> v;
1129 v.push_back("lld-link (LLVM option parsing)");
1130 for (auto *arg : args.filtered(OPT_mllvm))
1131 v.push_back(arg->getValue());
1132 cl::ParseCommandLineOptions(v.size(), v.data());
1133
1134 // Handle /errorlimit early, because error() depends on it.
1135 if (auto *arg = args.getLastArg(OPT_errorlimit)) {
1136 int n = 20;
1137 StringRef s = arg->getValue();
1138 if (s.getAsInteger(10, n))
1139 error(arg->getSpelling() + " number expected, but got " + s);
1140 errorHandler().errorLimit = n;
1141 }
1142
1143 // Handle /help
1144 if (args.hasArg(OPT_help)) {
1145 printHelp(argsArr[0]);
1146 return;
1147 }
1148
1149 lld::threadsEnabled = args.hasFlag(OPT_threads, OPT_threads_no, true);
1150
1151 if (args.hasArg(OPT_show_timing))
1152 config->showTiming = true;
1153
1154 config->showSummary = args.hasArg(OPT_summary);
1155
1156 ScopedTimer t(Timer::root());
1157 // Handle --version, which is an lld extension. This option is a bit odd
1158 // because it doesn't start with "/", but we deliberately chose "--" to
1159 // avoid conflict with /version and for compatibility with clang-cl.
1160 if (args.hasArg(OPT_dash_dash_version)) {
1161 lld::outs() << getLLDVersion() << "\n";
1162 return;
1163 }
1164
1165 // Handle /lldmingw early, since it can potentially affect how other
1166 // options are handled.
1167 config->mingw = args.hasArg(OPT_lldmingw);
1168
1169 // Handle /linkrepro and /reproduce.
1170 if (Optional<std::string> path = getReproduceFile(args)) {
1171 Expected<std::unique_ptr<TarWriter>> errOrWriter =
1172 TarWriter::create(*path, sys::path::stem(*path));
1173
1174 if (errOrWriter) {
1175 tar = std::move(*errOrWriter);
1176 } else {
1177 error("/linkrepro: failed to open " + *path + ": " +
1178 toString(errOrWriter.takeError()));
1179 }
1180 }
1181
1182 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1183 if (args.hasArg(OPT_deffile))
1184 config->noEntry = true;
1185 else
1186 fatal("no input files");
1187 }
1188
1189 // Construct search path list.
1190 searchPaths.push_back("");
1191 for (auto *arg : args.filtered(OPT_libpath))
1192 searchPaths.push_back(arg->getValue());
1193 if (!args.hasArg(OPT_lldignoreenv))
1194 addLibSearchPaths();
1195
1196 // Handle /ignore
1197 for (auto *arg : args.filtered(OPT_ignore)) {
1198 SmallVector<StringRef, 8> vec;
1199 StringRef(arg->getValue()).split(vec, ',');
1200 for (StringRef s : vec) {
1201 if (s == "4037")
1202 config->warnMissingOrderSymbol = false;
1203 else if (s == "4099")
1204 config->warnDebugInfoUnusable = false;
1205 else if (s == "4217")
1206 config->warnLocallyDefinedImported = false;
1207 else if (s == "longsections")
1208 config->warnLongSectionNames = false;
1209 // Other warning numbers are ignored.
1210 }
1211 }
1212
1213 // Handle /out
1214 if (auto *arg = args.getLastArg(OPT_out))
1215 config->outputFile = arg->getValue();
1216
1217 // Handle /verbose
1218 if (args.hasArg(OPT_verbose))
1219 config->verbose = true;
1220 errorHandler().verbose = config->verbose;
1221
1222 // Handle /force or /force:unresolved
1223 if (args.hasArg(OPT_force, OPT_force_unresolved))
1224 config->forceUnresolved = true;
1225
1226 // Handle /force or /force:multiple
1227 if (args.hasArg(OPT_force, OPT_force_multiple))
1228 config->forceMultiple = true;
1229
1230 // Handle /force or /force:multipleres
1231 if (args.hasArg(OPT_force, OPT_force_multipleres))
1232 config->forceMultipleRes = true;
1233
1234 // Handle /debug
1235 DebugKind debug = parseDebugKind(args);
1236 if (debug == DebugKind::Full || debug == DebugKind::Dwarf ||
1237 debug == DebugKind::GHash) {
1238 config->debug = true;
1239 config->incremental = true;
1240 }
1241
1242 // Handle /demangle
1243 config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no);
1244
1245 // Handle /debugtype
1246 config->debugTypes = parseDebugTypes(args);
1247
1248 // Handle /driver[:uponly|:wdm].
1249 config->driverUponly = args.hasArg(OPT_driver_uponly) ||
1250 args.hasArg(OPT_driver_uponly_wdm) ||
1251 args.hasArg(OPT_driver_wdm_uponly);
1252 config->driverWdm = args.hasArg(OPT_driver_wdm) ||
1253 args.hasArg(OPT_driver_uponly_wdm) ||
1254 args.hasArg(OPT_driver_wdm_uponly);
1255 config->driver =
1256 config->driverUponly || config->driverWdm || args.hasArg(OPT_driver);
1257
1258 // Handle /pdb
1259 bool shouldCreatePDB =
1260 (debug == DebugKind::Full || debug == DebugKind::GHash);
1261 if (shouldCreatePDB) {
1262 if (auto *arg = args.getLastArg(OPT_pdb))
1263 config->pdbPath = arg->getValue();
1264 if (auto *arg = args.getLastArg(OPT_pdbaltpath))
1265 config->pdbAltPath = arg->getValue();
1266 if (args.hasArg(OPT_natvis))
1267 config->natvisFiles = args.getAllArgValues(OPT_natvis);
1268
1269 if (auto *arg = args.getLastArg(OPT_pdb_source_path))
1270 config->pdbSourcePath = arg->getValue();
1271 }
1272
1273 // Handle /noentry
1274 if (args.hasArg(OPT_noentry)) {
1275 if (args.hasArg(OPT_dll))
1276 config->noEntry = true;
1277 else
1278 error("/noentry must be specified with /dll");
1279 }
1280
1281 // Handle /dll
1282 if (args.hasArg(OPT_dll)) {
1283 config->dll = true;
1284 config->manifestID = 2;
1285 }
1286
1287 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1288 // because we need to explicitly check whether that option or its inverse was
1289 // present in the argument list in order to handle /fixed.
1290 auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1291 if (dynamicBaseArg &&
1292 dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1293 config->dynamicBase = false;
1294
1295 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1296 // default setting for any other project type.", but link.exe defaults to
1297 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1298 bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1299 if (fixed) {
1300 if (dynamicBaseArg &&
1301 dynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1302 error("/fixed must not be specified with /dynamicbase");
1303 } else {
1304 config->relocatable = false;
1305 config->dynamicBase = false;
1306 }
1307 }
1308
1309 // Handle /appcontainer
1310 config->appContainer =
1311 args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1312
1313 // Handle /machine
1314 if (auto *arg = args.getLastArg(OPT_machine)) {
1315 config->machine = getMachineType(arg->getValue());
1316 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN)
1317 fatal(Twine("unknown /machine argument: ") + arg->getValue());
1318 }
1319
1320 // Handle /nodefaultlib:<filename>
1321 for (auto *arg : args.filtered(OPT_nodefaultlib))
1322 config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower());
1323
1324 // Handle /nodefaultlib
1325 if (args.hasArg(OPT_nodefaultlib_all))
1326 config->noDefaultLibAll = true;
1327
1328 // Handle /base
1329 if (auto *arg = args.getLastArg(OPT_base))
1330 parseNumbers(arg->getValue(), &config->imageBase);
1331
1332 // Handle /filealign
1333 if (auto *arg = args.getLastArg(OPT_filealign)) {
1334 parseNumbers(arg->getValue(), &config->fileAlign);
1335 if (!isPowerOf2_64(config->fileAlign))
1336 error("/filealign: not a power of two: " + Twine(config->fileAlign));
1337 }
1338
1339 // Handle /stack
1340 if (auto *arg = args.getLastArg(OPT_stack))
1341 parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit);
1342
1343 // Handle /guard:cf
1344 if (auto *arg = args.getLastArg(OPT_guard))
1345 parseGuard(arg->getValue());
1346
1347 // Handle /heap
1348 if (auto *arg = args.getLastArg(OPT_heap))
1349 parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit);
1350
1351 // Handle /version
1352 if (auto *arg = args.getLastArg(OPT_version))
1353 parseVersion(arg->getValue(), &config->majorImageVersion,
1354 &config->minorImageVersion);
1355
1356 // Handle /subsystem
1357 if (auto *arg = args.getLastArg(OPT_subsystem))
1358 parseSubsystem(arg->getValue(), &config->subsystem, &config->majorOSVersion,
1359 &config->minorOSVersion);
1360
1361 // Handle /timestamp
1362 if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) {
1363 if (arg->getOption().getID() == OPT_repro) {
1364 config->timestamp = 0;
1365 config->repro = true;
1366 } else {
1367 config->repro = false;
1368 StringRef value(arg->getValue());
1369 if (value.getAsInteger(0, config->timestamp))
1370 fatal(Twine("invalid timestamp: ") + value +
1371 ". Expected 32-bit integer");
1372 }
1373 } else {
1374 config->repro = false;
1375 config->timestamp = time(nullptr);
1376 }
1377
1378 // Handle /alternatename
1379 for (auto *arg : args.filtered(OPT_alternatename))
1380 parseAlternateName(arg->getValue());
1381
1382 // Handle /include
1383 for (auto *arg : args.filtered(OPT_incl))
1384 addUndefined(arg->getValue());
1385
1386 // Handle /implib
1387 if (auto *arg = args.getLastArg(OPT_implib))
1388 config->implib = arg->getValue();
1389
1390 // Handle /opt.
1391 bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile);
1392 unsigned icfLevel =
1393 args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1394 unsigned tailMerge = 1;
1395 for (auto *arg : args.filtered(OPT_opt)) {
1396 std::string str = StringRef(arg->getValue()).lower();
1397 SmallVector<StringRef, 1> vec;
1398 StringRef(str).split(vec, ',');
1399 for (StringRef s : vec) {
1400 if (s == "ref") {
1401 doGC = true;
1402 } else if (s == "noref") {
1403 doGC = false;
1404 } else if (s == "icf" || s.startswith("icf=")) {
1405 icfLevel = 2;
1406 } else if (s == "noicf") {
1407 icfLevel = 0;
1408 } else if (s == "lldtailmerge") {
1409 tailMerge = 2;
1410 } else if (s == "nolldtailmerge") {
1411 tailMerge = 0;
1412 } else if (s.startswith("lldlto=")) {
1413 StringRef optLevel = s.substr(7);
1414 if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3)
1415 error("/opt:lldlto: invalid optimization level: " + optLevel);
1416 } else if (s.startswith("lldltojobs=")) {
1417 StringRef jobs = s.substr(11);
1418 if (jobs.getAsInteger(10, config->thinLTOJobs) ||
1419 config->thinLTOJobs == 0)
1420 error("/opt:lldltojobs: invalid job count: " + jobs);
1421 } else if (s.startswith("lldltopartitions=")) {
1422 StringRef n = s.substr(17);
1423 if (n.getAsInteger(10, config->ltoPartitions) ||
1424 config->ltoPartitions == 0)
1425 error("/opt:lldltopartitions: invalid partition count: " + n);
1426 } else if (s != "lbr" && s != "nolbr")
1427 error("/opt: unknown option: " + s);
1428 }
1429 }
1430
1431 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1432 // explicitly.
1433 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1434 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1435 // comdat readonly data.
1436 if (icfLevel == 1 && !doGC)
1437 icfLevel = 0;
1438 config->doGC = doGC;
1439 config->doICF = icfLevel > 0;
1440 config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2;
1441
1442 // Handle /lldsavetemps
1443 if (args.hasArg(OPT_lldsavetemps))
1444 config->saveTemps = true;
1445
1446 // Handle /kill-at
1447 if (args.hasArg(OPT_kill_at))
1448 config->killAt = true;
1449
1450 // Handle /lldltocache
1451 if (auto *arg = args.getLastArg(OPT_lldltocache))
1452 config->ltoCache = arg->getValue();
1453
1454 // Handle /lldsavecachepolicy
1455 if (auto *arg = args.getLastArg(OPT_lldltocachepolicy))
1456 config->ltoCachePolicy = CHECK(
1457 parseCachePruningPolicy(arg->getValue()),
1458 Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue());
1459
1460 // Handle /failifmismatch
1461 for (auto *arg : args.filtered(OPT_failifmismatch))
1462 checkFailIfMismatch(arg->getValue(), nullptr);
1463
1464 // Handle /merge
1465 for (auto *arg : args.filtered(OPT_merge))
1466 parseMerge(arg->getValue());
1467
1468 // Add default section merging rules after user rules. User rules take
1469 // precedence, but we will emit a warning if there is a conflict.
1470 parseMerge(".idata=.rdata");
1471 parseMerge(".didat=.rdata");
1472 parseMerge(".edata=.rdata");
1473 parseMerge(".xdata=.rdata");
1474 parseMerge(".bss=.data");
1475
1476 if (config->mingw) {
1477 parseMerge(".ctors=.rdata");
1478 parseMerge(".dtors=.rdata");
1479 parseMerge(".CRT=.rdata");
1480 }
1481
1482 // Handle /section
1483 for (auto *arg : args.filtered(OPT_section))
1484 parseSection(arg->getValue());
1485
1486 // Handle /align
1487 if (auto *arg = args.getLastArg(OPT_align)) {
1488 parseNumbers(arg->getValue(), &config->align);
1489 if (!isPowerOf2_64(config->align))
1490 error("/align: not a power of two: " + StringRef(arg->getValue()));
1491 if (!args.hasArg(OPT_driver))
1492 warn("/align specified without /driver; image may not run");
1493 }
1494
1495 // Handle /aligncomm
1496 for (auto *arg : args.filtered(OPT_aligncomm))
1497 parseAligncomm(arg->getValue());
1498
1499 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1500 // also passed.
1501 if (auto *arg = args.getLastArg(OPT_manifestdependency)) {
1502 config->manifestDependency = arg->getValue();
1503 config->manifest = Configuration::SideBySide;
1504 }
1505
1506 // Handle /manifest and /manifest:
1507 if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1508 if (arg->getOption().getID() == OPT_manifest)
1509 config->manifest = Configuration::SideBySide;
1510 else
1511 parseManifest(arg->getValue());
1512 }
1513
1514 // Handle /manifestuac
1515 if (auto *arg = args.getLastArg(OPT_manifestuac))
1516 parseManifestUAC(arg->getValue());
1517
1518 // Handle /manifestfile
1519 if (auto *arg = args.getLastArg(OPT_manifestfile))
1520 config->manifestFile = arg->getValue();
1521
1522 // Handle /manifestinput
1523 for (auto *arg : args.filtered(OPT_manifestinput))
1524 config->manifestInput.push_back(arg->getValue());
1525
1526 if (!config->manifestInput.empty() &&
1527 config->manifest != Configuration::Embed) {
1528 fatal("/manifestinput: requires /manifest:embed");
1529 }
1530
1531 config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1532 config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1533 args.hasArg(OPT_thinlto_index_only_arg);
1534 config->thinLTOIndexOnlyArg =
1535 args.getLastArgValue(OPT_thinlto_index_only_arg);
1536 config->thinLTOPrefixReplace =
1537 getOldNewOptions(args, OPT_thinlto_prefix_replace);
1538 config->thinLTOObjectSuffixReplace =
1539 getOldNewOptions(args, OPT_thinlto_object_suffix_replace);
1540 config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path);
1541 // Handle miscellaneous boolean flags.
1542 config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1543 config->allowIsolation =
1544 args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1545 config->incremental =
1546 args.hasFlag(OPT_incremental, OPT_incremental_no,
1547 !config->doGC && !config->doICF && !args.hasArg(OPT_order) &&
1548 !args.hasArg(OPT_profile));
1549 config->integrityCheck =
1550 args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1551 config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1552 for (auto *arg : args.filtered(OPT_swaprun))
1553 parseSwaprun(arg->getValue());
1554 config->terminalServerAware =
1555 !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1556 config->debugDwarf = debug == DebugKind::Dwarf;
1557 config->debugGHashes = debug == DebugKind::GHash;
1558 config->debugSymtab = debug == DebugKind::Symtab;
1559
1560 // Don't warn about long section names, such as .debug_info, for mingw or when
1561 // -debug:dwarf is requested.
1562 if (config->mingw || config->debugDwarf)
1563 config->warnLongSectionNames = false;
1564
1565 config->mapFile = getMapFile(args);
1566
1567 if (config->incremental && args.hasArg(OPT_profile)) {
1568 warn("ignoring '/incremental' due to '/profile' specification");
1569 config->incremental = false;
1570 }
1571
1572 if (config->incremental && args.hasArg(OPT_order)) {
1573 warn("ignoring '/incremental' due to '/order' specification");
1574 config->incremental = false;
1575 }
1576
1577 if (config->incremental && config->doGC) {
1578 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1579 "disable");
1580 config->incremental = false;
1581 }
1582
1583 if (config->incremental && config->doICF) {
1584 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1585 "disable");
1586 config->incremental = false;
1587 }
1588
1589 if (errorCount())
1590 return;
1591
1592 std::set<sys::fs::UniqueID> wholeArchives;
1593 for (auto *arg : args.filtered(OPT_wholearchive_file))
1594 if (Optional<StringRef> path = doFindFile(arg->getValue()))
1595 if (Optional<sys::fs::UniqueID> id = getUniqueID(*path))
1596 wholeArchives.insert(*id);
1597
1598 // A predicate returning true if a given path is an argument for
1599 // /wholearchive:, or /wholearchive is enabled globally.
1600 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1601 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1602 auto isWholeArchive = [&](StringRef path) -> bool {
1603 if (args.hasArg(OPT_wholearchive_flag))
1604 return true;
1605 if (Optional<sys::fs::UniqueID> id = getUniqueID(path))
1606 return wholeArchives.count(*id);
1607 return false;
1608 };
1609
1610 // Create a list of input files. These can be given as OPT_INPUT options
1611 // and OPT_wholearchive_file options, and we also need to track OPT_start_lib
1612 // and OPT_end_lib.
1613 bool inLib = false;
1614 for (auto *arg : args) {
1615 switch (arg->getOption().getID()) {
1616 case OPT_end_lib:
1617 if (!inLib)
1618 error("stray " + arg->getSpelling());
1619 inLib = false;
1620 break;
1621 case OPT_start_lib:
1622 if (inLib)
1623 error("nested " + arg->getSpelling());
1624 inLib = true;
1625 break;
1626 case OPT_wholearchive_file:
1627 if (Optional<StringRef> path = findFile(arg->getValue()))
1628 enqueuePath(*path, true, inLib);
1629 break;
1630 case OPT_INPUT:
1631 if (Optional<StringRef> path = findFile(arg->getValue()))
1632 enqueuePath(*path, isWholeArchive(*path), inLib);
1633 break;
1634 default:
1635 // Ignore other options.
1636 break;
1637 }
1638 }
1639
1640 // Process files specified as /defaultlib. These should be enequeued after
1641 // other files, which is why they are in a separate loop.
1642 for (auto *arg : args.filtered(OPT_defaultlib))
1643 if (Optional<StringRef> path = findLib(arg->getValue()))
1644 enqueuePath(*path, false, false);
1645
1646 // Windows specific -- Create a resource file containing a manifest file.
1647 if (config->manifest == Configuration::Embed)
1648 addBuffer(createManifestRes(), false, false);
1649
1650 // Read all input files given via the command line.
1651 run();
1652
1653 if (errorCount())
1654 return;
1655
1656 // We should have inferred a machine type by now from the input files, but if
1657 // not we assume x64.
1658 if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1659 warn("/machine is not specified. x64 is assumed");
1660 config->machine = AMD64;
1661 }
1662 config->wordsize = config->is64() ? 8 : 4;
1663
1664 // Handle /safeseh, x86 only, on by default, except for mingw.
1665 if (config->machine == I386 &&
1666 args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw))
1667 config->safeSEH = true;
1668
1669 // Handle /functionpadmin
1670 for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt))
1671 parseFunctionPadMin(arg, config->machine);
1672
1673 if (tar)
1674 tar->append("response.txt",
1675 createResponseFile(args, filePaths,
1676 ArrayRef<StringRef>(searchPaths).slice(1)));
1677
1678 // Handle /largeaddressaware
1679 config->largeAddressAware = args.hasFlag(
1680 OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64());
1681
1682 // Handle /highentropyva
1683 config->highEntropyVA =
1684 config->is64() &&
1685 args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1686
1687 if (!config->dynamicBase &&
1688 (config->machine == ARMNT || config->machine == ARM64))
1689 error("/dynamicbase:no is not compatible with " +
1690 machineToStr(config->machine));
1691
1692 // Handle /export
1693 for (auto *arg : args.filtered(OPT_export)) {
1694 Export e = parseExport(arg->getValue());
1695 if (config->machine == I386) {
1696 if (!isDecorated(e.name))
1697 e.name = saver.save("_" + e.name);
1698 if (!e.extName.empty() && !isDecorated(e.extName))
1699 e.extName = saver.save("_" + e.extName);
1700 }
1701 config->exports.push_back(e);
1702 }
1703
1704 // Handle /def
1705 if (auto *arg = args.getLastArg(OPT_deffile)) {
1706 // parseModuleDefs mutates Config object.
1707 parseModuleDefs(arg->getValue());
1708 }
1709
1710 // Handle generation of import library from a def file.
1711 if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) {
1712 fixupExports();
1713 createImportLibrary(/*asLib=*/true);
1714 return;
1715 }
1716
1717 // Windows specific -- if no /subsystem is given, we need to infer
1718 // that from entry point name. Must happen before /entry handling,
1719 // and after the early return when just writing an import library.
1720 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1721 config->subsystem = inferSubsystem();
1722 if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1723 fatal("subsystem must be defined");
1724 }
1725
1726 // Handle /entry and /dll
1727 if (auto *arg = args.getLastArg(OPT_entry)) {
1728 config->entry = addUndefined(mangle(arg->getValue()));
1729 } else if (!config->entry && !config->noEntry) {
1730 if (args.hasArg(OPT_dll)) {
1731 StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12"
1732 : "_DllMainCRTStartup";
1733 config->entry = addUndefined(s);
1734 } else if (config->driverWdm) {
1735 // /driver:wdm implies /entry:_NtProcessStartup
1736 config->entry = addUndefined(mangle("_NtProcessStartup"));
1737 } else {
1738 // Windows specific -- If entry point name is not given, we need to
1739 // infer that from user-defined entry name.
1740 StringRef s = findDefaultEntry();
1741 if (s.empty())
1742 fatal("entry point must be defined");
1743 config->entry = addUndefined(s);
1744 log("Entry name inferred: " + s);
1745 }
1746 }
1747
1748 // Handle /delayload
1749 for (auto *arg : args.filtered(OPT_delayload)) {
1750 config->delayLoads.insert(StringRef(arg->getValue()).lower());
1751 if (config->machine == I386) {
1752 config->delayLoadHelper = addUndefined("___delayLoadHelper2@8");
1753 } else {
1754 config->delayLoadHelper = addUndefined("__delayLoadHelper2");
1755 }
1756 }
1757
1758 // Set default image name if neither /out or /def set it.
1759 if (config->outputFile.empty()) {
1760 config->outputFile = getOutputPath(
1761 (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue());
1762 }
1763
1764 // Fail early if an output file is not writable.
1765 if (auto e = tryCreateFile(config->outputFile)) {
1766 error("cannot open output file " + config->outputFile + ": " + e.message());
1767 return;
1768 }
1769
1770 if (shouldCreatePDB) {
1771 // Put the PDB next to the image if no /pdb flag was passed.
1772 if (config->pdbPath.empty()) {
1773 config->pdbPath = config->outputFile;
1774 sys::path::replace_extension(config->pdbPath, ".pdb");
1775 }
1776
1777 // The embedded PDB path should be the absolute path to the PDB if no
1778 // /pdbaltpath flag was passed.
1779 if (config->pdbAltPath.empty()) {
1780 config->pdbAltPath = config->pdbPath;
1781
1782 // It's important to make the path absolute and remove dots. This path
1783 // will eventually be written into the PE header, and certain Microsoft
1784 // tools won't work correctly if these assumptions are not held.
1785 sys::fs::make_absolute(config->pdbAltPath);
1786 sys::path::remove_dots(config->pdbAltPath);
1787 } else {
1788 // Don't do this earlier, so that Config->OutputFile is ready.
1789 parsePDBAltPath(config->pdbAltPath);
1790 }
1791 }
1792
1793 // Set default image base if /base is not given.
1794 if (config->imageBase == uint64_t(-1))
1795 config->imageBase = getDefaultImageBase();
1796
1797 symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1798 if (config->machine == I386) {
1799 symtab->addAbsolute("___safe_se_handler_table", 0);
1800 symtab->addAbsolute("___safe_se_handler_count", 0);
1801 }
1802
1803 symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1804 symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1805 symtab->addAbsolute(mangle("__guard_flags"), 0);
1806 symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1807 symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1808 symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1809 symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1810 // Needed for MSVC 2017 15.5 CRT.
1811 symtab->addAbsolute(mangle("__enclave_config"), 0);
1812
1813 if (config->mingw) {
1814 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1815 symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1816 symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1817 symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
1818 }
1819
1820 // This code may add new undefined symbols to the link, which may enqueue more
1821 // symbol resolution tasks, so we need to continue executing tasks until we
1822 // converge.
1823 do {
1824 // Windows specific -- if entry point is not found,
1825 // search for its mangled names.
1826 if (config->entry)
1827 mangleMaybe(config->entry);
1828
1829 // Windows specific -- Make sure we resolve all dllexported symbols.
1830 for (Export &e : config->exports) {
1831 if (!e.forwardTo.empty())
1832 continue;
1833 e.sym = addUndefined(e.name);
1834 if (!e.directives)
1835 e.symbolName = mangleMaybe(e.sym);
1836 }
1837
1838 // Add weak aliases. Weak aliases is a mechanism to give remaining
1839 // undefined symbols final chance to be resolved successfully.
1840 for (auto pair : config->alternateNames) {
1841 StringRef from = pair.first;
1842 StringRef to = pair.second;
1843 Symbol *sym = symtab->find(from);
1844 if (!sym)
1845 continue;
1846 if (auto *u = dyn_cast<Undefined>(sym))
1847 if (!u->weakAlias)
1848 u->weakAlias = symtab->addUndefined(to);
1849 }
1850
1851 // If any inputs are bitcode files, the LTO code generator may create
1852 // references to library functions that are not explicit in the bitcode
1853 // file's symbol table. If any of those library functions are defined in a
1854 // bitcode file in an archive member, we need to arrange to use LTO to
1855 // compile those archive members by adding them to the link beforehand.
1856 if (!BitcodeFile::instances.empty())
1857 for (auto *s : lto::LTO::getRuntimeLibcallSymbols())
1858 symtab->addLibcall(s);
1859
1860 // Windows specific -- if __load_config_used can be resolved, resolve it.
1861 if (symtab->findUnderscore("_load_config_used"))
1862 addUndefined(mangle("_load_config_used"));
1863 } while (run());
1864
1865 if (args.hasArg(OPT_include_optional)) {
1866 // Handle /includeoptional
1867 for (auto *arg : args.filtered(OPT_include_optional))
1868 if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue())))
1869 addUndefined(arg->getValue());
1870 while (run());
1871 }
1872
1873 if (config->mingw) {
1874 // Load any further object files that might be needed for doing automatic
1875 // imports.
1876 //
1877 // For cases with no automatically imported symbols, this iterates once
1878 // over the symbol table and doesn't do anything.
1879 //
1880 // For the normal case with a few automatically imported symbols, this
1881 // should only need to be run once, since each new object file imported
1882 // is an import library and wouldn't add any new undefined references,
1883 // but there's nothing stopping the __imp_ symbols from coming from a
1884 // normal object file as well (although that won't be used for the
1885 // actual autoimport later on). If this pass adds new undefined references,
1886 // we won't iterate further to resolve them.
1887 symtab->loadMinGWAutomaticImports();
1888 run();
1889 }
1890
1891 // At this point, we should not have any symbols that cannot be resolved.
1892 // If we are going to do codegen for link-time optimization, check for
1893 // unresolvable symbols first, so we don't spend time generating code that
1894 // will fail to link anyway.
1895 if (!BitcodeFile::instances.empty() && !config->forceUnresolved)
1896 symtab->reportUnresolvable();
1897 if (errorCount())
1898 return;
1899
1900 // Do LTO by compiling bitcode input files to a set of native COFF files then
1901 // link those files (unless -thinlto-index-only was given, in which case we
1902 // resolve symbols and write indices, but don't generate native code or link).
1903 symtab->addCombinedLTOObjects();
1904
1905 // If -thinlto-index-only is given, we should create only "index
1906 // files" and not object files. Index file creation is already done
1907 // in addCombinedLTOObject, so we are done if that's the case.
1908 if (config->thinLTOIndexOnly)
1909 return;
1910
1911 // If we generated native object files from bitcode files, this resolves
1912 // references to the symbols we use from them.
1913 run();
1914
1915 // Resolve remaining undefined symbols and warn about imported locals.
1916 symtab->resolveRemainingUndefines();
1917 if (errorCount())
1918 return;
1919
1920 config->hadExplicitExports = !config->exports.empty();
1921 if (config->mingw) {
1922 // In MinGW, all symbols are automatically exported if no symbols
1923 // are chosen to be exported.
1924 maybeExportMinGWSymbols(args);
1925
1926 // Make sure the crtend.o object is the last object file. This object
1927 // file can contain terminating section chunks that need to be placed
1928 // last. GNU ld processes files and static libraries explicitly in the
1929 // order provided on the command line, while lld will pull in needed
1930 // files from static libraries only after the last object file on the
1931 // command line.
1932 for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end();
1933 i != e; i++) {
1934 ObjFile *file = *i;
1935 if (isCrtend(file->getName())) {
1936 ObjFile::instances.erase(i);
1937 ObjFile::instances.push_back(file);
1938 break;
1939 }
1940 }
1941 }
1942
1943 // Windows specific -- when we are creating a .dll file, we also
1944 // need to create a .lib file. In MinGW mode, we only do that when the
1945 // -implib option is given explicitly, for compatibility with GNU ld.
1946 if (!config->exports.empty() || config->dll) {
1947 fixupExports();
1948 if (!config->mingw || !config->implib.empty())
1949 createImportLibrary(/*asLib=*/false);
1950 assignExportOrdinals();
1951 }
1952
1953 // Handle /output-def (MinGW specific).
1954 if (auto *arg = args.getLastArg(OPT_output_def))
1955 writeDefFile(arg->getValue());
1956
1957 // Set extra alignment for .comm symbols
1958 for (auto pair : config->alignComm) {
1959 StringRef name = pair.first;
1960 uint32_t alignment = pair.second;
1961
1962 Symbol *sym = symtab->find(name);
1963 if (!sym) {
1964 warn("/aligncomm symbol " + name + " not found");
1965 continue;
1966 }
1967
1968 // If the symbol isn't common, it must have been replaced with a regular
1969 // symbol, which will carry its own alignment.
1970 auto *dc = dyn_cast<DefinedCommon>(sym);
1971 if (!dc)
1972 continue;
1973
1974 CommonChunk *c = dc->getChunk();
1975 c->setAlignment(std::max(c->getAlignment(), alignment));
1976 }
1977
1978 // Windows specific -- Create a side-by-side manifest file.
1979 if (config->manifest == Configuration::SideBySide)
1980 createSideBySideManifest();
1981
1982 // Handle /order. We want to do this at this moment because we
1983 // need a complete list of comdat sections to warn on nonexistent
1984 // functions.
1985 if (auto *arg = args.getLastArg(OPT_order))
1986 parseOrderFile(arg->getValue());
1987
1988 // Identify unreferenced COMDAT sections.
1989 if (config->doGC)
1990 markLive(symtab->getChunks());
1991
1992 // Needs to happen after the last call to addFile().
1993 convertResources();
1994
1995 // Identify identical COMDAT sections to merge them.
1996 if (config->doICF) {
1997 findKeepUniqueSections();
1998 doICF(symtab->getChunks());
1999 }
2000
2001 // Write the result.
2002 writeResult();
2003
2004 // Stop early so we can print the results.
2005 Timer::root().stop();
2006 if (config->showTiming)
2007 Timer::root().print();
2008}
2009
2010} // namespace coff
2011} // namespace lld