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