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

source code of lld/COFF/Driver.cpp