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