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