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