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