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