1 //===- DriverUtils.cpp ----------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file contains utility functions for the driver. Because there
10 // are so many small functions, we created this separate file to make
11 // Driver.cpp less cluttered.
13 //===----------------------------------------------------------------------===//
15 #include "COFFLinkerContext.h"
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "llvm/ADT/STLExtras.h"
21 #include "llvm/ADT/StringExtras.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/BinaryFormat/COFF.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/WindowsResource.h"
26 #include "llvm/Option/Arg.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/raw_ostream.h"
35 #include "llvm/WindowsManifest/WindowsManifestMerger.h"
40 using namespace llvm::COFF
;
41 using namespace llvm::opt
;
43 using llvm::sys::Process
;
49 const uint16_t SUBLANG_ENGLISH_US
= 0x0409;
50 const uint16_t RT_MANIFEST
= 24;
54 explicit Executor(StringRef s
) : prog(saver().save(s
)) {}
55 void add(StringRef s
) { args
.push_back(saver().save(s
)); }
56 void add(std::string
&s
) { args
.push_back(saver().save(s
)); }
57 void add(Twine s
) { args
.push_back(saver().save(s
)); }
58 void add(const char *s
) { args
.push_back(saver().save(s
)); }
61 ErrorOr
<std::string
> exeOrErr
= sys::findProgramByName(prog
);
62 if (auto ec
= exeOrErr
.getError())
63 fatal("unable to find " + prog
+ " in PATH: " + ec
.message());
64 StringRef exe
= saver().save(*exeOrErr
);
65 args
.insert(args
.begin(), exe
);
67 if (sys::ExecuteAndWait(args
[0], args
) != 0)
68 fatal("ExecuteAndWait failed: " +
69 llvm::join(args
.begin(), args
.end(), " "));
74 std::vector
<StringRef
> args
;
77 } // anonymous namespace
79 // Parses a string in the form of "<integer>[,<integer>]".
80 void LinkerDriver::parseNumbers(StringRef arg
, uint64_t *addr
, uint64_t *size
) {
81 auto [s1
, s2
] = arg
.split(',');
82 if (s1
.getAsInteger(0, *addr
))
83 fatal("invalid number: " + s1
);
84 if (size
&& !s2
.empty() && s2
.getAsInteger(0, *size
))
85 fatal("invalid number: " + s2
);
88 // Parses a string in the form of "<integer>[.<integer>]".
89 // If second number is not present, Minor is set to 0.
90 void LinkerDriver::parseVersion(StringRef arg
, uint32_t *major
,
92 auto [s1
, s2
] = arg
.split('.');
93 if (s1
.getAsInteger(10, *major
))
94 fatal("invalid number: " + s1
);
96 if (!s2
.empty() && s2
.getAsInteger(10, *minor
))
97 fatal("invalid number: " + s2
);
100 void LinkerDriver::parseGuard(StringRef fullArg
) {
101 SmallVector
<StringRef
, 1> splitArgs
;
102 fullArg
.split(splitArgs
, ",");
103 for (StringRef arg
: splitArgs
) {
104 if (arg
.equals_insensitive("no"))
105 ctx
.config
.guardCF
= GuardCFLevel::Off
;
106 else if (arg
.equals_insensitive("nolongjmp"))
107 ctx
.config
.guardCF
&= ~GuardCFLevel::LongJmp
;
108 else if (arg
.equals_insensitive("noehcont"))
109 ctx
.config
.guardCF
&= ~GuardCFLevel::EHCont
;
110 else if (arg
.equals_insensitive("cf") || arg
.equals_insensitive("longjmp"))
111 ctx
.config
.guardCF
|= GuardCFLevel::CF
| GuardCFLevel::LongJmp
;
112 else if (arg
.equals_insensitive("ehcont"))
113 ctx
.config
.guardCF
|= GuardCFLevel::CF
| GuardCFLevel::EHCont
;
115 fatal("invalid argument to /guard: " + arg
);
119 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
120 void LinkerDriver::parseSubsystem(StringRef arg
, WindowsSubsystem
*sys
,
121 uint32_t *major
, uint32_t *minor
,
123 auto [sysStr
, ver
] = arg
.split(',');
124 std::string sysStrLower
= sysStr
.lower();
125 *sys
= StringSwitch
<WindowsSubsystem
>(sysStrLower
)
126 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION
)
127 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI
)
128 .Case("default", IMAGE_SUBSYSTEM_UNKNOWN
)
129 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION
)
130 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER
)
131 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM
)
132 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER
)
133 .Case("native", IMAGE_SUBSYSTEM_NATIVE
)
134 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI
)
135 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI
)
136 .Default(IMAGE_SUBSYSTEM_UNKNOWN
);
137 if (*sys
== IMAGE_SUBSYSTEM_UNKNOWN
&& sysStrLower
!= "default")
138 fatal("unknown subsystem: " + sysStr
);
140 parseVersion(ver
, major
, minor
);
142 *gotVersion
= !ver
.empty();
145 // Parse a string of the form of "<from>=<to>".
146 // Results are directly written to Config.
147 void LinkerDriver::parseAlternateName(StringRef s
) {
148 auto [from
, to
] = s
.split('=');
149 if (from
.empty() || to
.empty())
150 fatal("/alternatename: invalid argument: " + s
);
151 auto it
= ctx
.config
.alternateNames
.find(from
);
152 if (it
!= ctx
.config
.alternateNames
.end() && it
->second
!= to
)
153 fatal("/alternatename: conflicts: " + s
);
154 ctx
.config
.alternateNames
.insert(it
, std::make_pair(from
, to
));
157 // Parse a string of the form of "<from>=<to>".
158 // Results are directly written to Config.
159 void LinkerDriver::parseMerge(StringRef s
) {
160 auto [from
, to
] = s
.split('=');
161 if (from
.empty() || to
.empty())
162 fatal("/merge: invalid argument: " + s
);
163 if (from
== ".rsrc" || to
== ".rsrc")
164 fatal("/merge: cannot merge '.rsrc' with any section");
165 if (from
== ".reloc" || to
== ".reloc")
166 fatal("/merge: cannot merge '.reloc' with any section");
167 auto pair
= ctx
.config
.merge
.insert(std::make_pair(from
, to
));
168 bool inserted
= pair
.second
;
170 StringRef existing
= pair
.first
->second
;
172 warn(s
+ ": already merged into " + existing
);
176 void LinkerDriver::parsePDBPageSize(StringRef s
) {
178 if (s
.getAsInteger(0, v
)) {
179 error("/pdbpagesize: invalid argument: " + s
);
182 if (v
!= 4096 && v
!= 8192 && v
!= 16384 && v
!= 32768) {
183 error("/pdbpagesize: invalid argument: " + s
);
187 ctx
.config
.pdbPageSize
= v
;
190 static uint32_t parseSectionAttributes(StringRef s
) {
192 for (char c
: s
.lower()) {
195 ret
|= IMAGE_SCN_MEM_DISCARDABLE
;
198 ret
|= IMAGE_SCN_MEM_EXECUTE
;
201 ret
|= IMAGE_SCN_MEM_NOT_CACHED
;
204 ret
|= IMAGE_SCN_MEM_NOT_PAGED
;
207 ret
|= IMAGE_SCN_MEM_READ
;
210 ret
|= IMAGE_SCN_MEM_SHARED
;
213 ret
|= IMAGE_SCN_MEM_WRITE
;
216 fatal("/section: invalid argument: " + s
);
222 // Parses /section option argument.
223 void LinkerDriver::parseSection(StringRef s
) {
224 auto [name
, attrs
] = s
.split(',');
225 if (name
.empty() || attrs
.empty())
226 fatal("/section: invalid argument: " + s
);
227 ctx
.config
.section
[name
] = parseSectionAttributes(attrs
);
230 // Parses /aligncomm option argument.
231 void LinkerDriver::parseAligncomm(StringRef s
) {
232 auto [name
, align
] = s
.split(',');
233 if (name
.empty() || align
.empty()) {
234 error("/aligncomm: invalid argument: " + s
);
238 if (align
.getAsInteger(0, v
)) {
239 error("/aligncomm: invalid argument: " + s
);
242 ctx
.config
.alignComm
[std::string(name
)] =
243 std::max(ctx
.config
.alignComm
[std::string(name
)], 1 << v
);
246 // Parses /functionpadmin option argument.
247 void LinkerDriver::parseFunctionPadMin(llvm::opt::Arg
*a
) {
248 StringRef arg
= a
->getNumValues() ? a
->getValue() : "";
250 // Optional padding in bytes is given.
251 if (arg
.getAsInteger(0, ctx
.config
.functionPadMin
))
252 error("/functionpadmin: invalid argument: " + arg
);
255 // No optional argument given.
256 // Set default padding based on machine, similar to link.exe.
257 // There is no default padding for ARM platforms.
258 if (ctx
.config
.machine
== I386
) {
259 ctx
.config
.functionPadMin
= 5;
260 } else if (ctx
.config
.machine
== AMD64
) {
261 ctx
.config
.functionPadMin
= 6;
263 error("/functionpadmin: invalid argument for this machine: " + arg
);
267 // Parses a string in the form of "EMBED[,=<integer>]|NO".
268 // Results are directly written to
270 void LinkerDriver::parseManifest(StringRef arg
) {
271 if (arg
.equals_insensitive("no")) {
272 ctx
.config
.manifest
= Configuration::No
;
275 if (!arg
.starts_with_insensitive("embed"))
276 fatal("invalid option " + arg
);
277 ctx
.config
.manifest
= Configuration::Embed
;
278 arg
= arg
.substr(strlen("embed"));
281 if (!arg
.starts_with_insensitive(",id="))
282 fatal("invalid option " + arg
);
283 arg
= arg
.substr(strlen(",id="));
284 if (arg
.getAsInteger(0, ctx
.config
.manifestID
))
285 fatal("invalid option " + arg
);
288 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
289 // Results are directly written to Config.
290 void LinkerDriver::parseManifestUAC(StringRef arg
) {
291 if (arg
.equals_insensitive("no")) {
292 ctx
.config
.manifestUAC
= false;
299 if (arg
.starts_with_insensitive("level=")) {
300 arg
= arg
.substr(strlen("level="));
301 std::tie(ctx
.config
.manifestLevel
, arg
) = arg
.split(" ");
304 if (arg
.starts_with_insensitive("uiaccess=")) {
305 arg
= arg
.substr(strlen("uiaccess="));
306 std::tie(ctx
.config
.manifestUIAccess
, arg
) = arg
.split(" ");
309 fatal("invalid option " + arg
);
313 // Parses a string in the form of "cd|net[,(cd|net)]*"
314 // Results are directly written to Config.
315 void LinkerDriver::parseSwaprun(StringRef arg
) {
317 auto [swaprun
, newArg
] = arg
.split(',');
318 if (swaprun
.equals_insensitive("cd"))
319 ctx
.config
.swaprunCD
= true;
320 else if (swaprun
.equals_insensitive("net"))
321 ctx
.config
.swaprunNet
= true;
322 else if (swaprun
.empty())
323 error("/swaprun: missing argument");
325 error("/swaprun: invalid argument: " + swaprun
);
326 // To catch trailing commas, e.g. `/spawrun:cd,`
327 if (newArg
.empty() && arg
.ends_with(","))
328 error("/swaprun: missing argument");
330 } while (!arg
.empty());
333 // An RAII temporary file class that automatically removes a temporary file.
335 class TemporaryFile
{
337 TemporaryFile(StringRef prefix
, StringRef extn
, StringRef contents
= "") {
339 if (auto ec
= sys::fs::createTemporaryFile("lld-" + prefix
, extn
, s
))
340 fatal("cannot create a temporary file: " + ec
.message());
341 path
= std::string(s
.str());
343 if (!contents
.empty()) {
345 raw_fd_ostream
os(path
, ec
, sys::fs::OF_None
);
347 fatal("failed to open " + path
+ ": " + ec
.message());
352 TemporaryFile(TemporaryFile
&&obj
) noexcept
{ std::swap(path
, obj
.path
); }
357 if (sys::fs::remove(path
))
358 fatal("failed to remove " + path
);
361 // Returns a memory buffer of this temporary file.
362 // Note that this function does not leave the file open,
363 // so it is safe to remove the file immediately after this function
364 // is called (you cannot remove an opened file on Windows.)
365 std::unique_ptr
<MemoryBuffer
> getMemoryBuffer() {
366 // IsVolatile=true forces MemoryBuffer to not use mmap().
367 return CHECK(MemoryBuffer::getFile(path
, /*IsText=*/false,
368 /*RequiresNullTerminator=*/false,
369 /*IsVolatile=*/true),
370 "could not open " + path
);
377 std::string
LinkerDriver::createDefaultXml() {
379 raw_string_ostream
os(ret
);
381 // Emit the XML. Note that we do *not* verify that the XML attributes are
382 // syntactically correct. This is intentional for link.exe compatibility.
383 os
<< "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
384 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
385 << " manifestVersion=\"1.0\">\n";
386 if (ctx
.config
.manifestUAC
) {
387 os
<< " <trustInfo>\n"
389 << " <requestedPrivileges>\n"
390 << " <requestedExecutionLevel level=" << ctx
.config
.manifestLevel
391 << " uiAccess=" << ctx
.config
.manifestUIAccess
<< "/>\n"
392 << " </requestedPrivileges>\n"
394 << " </trustInfo>\n";
396 for (auto manifestDependency
: ctx
.config
.manifestDependencies
) {
397 os
<< " <dependency>\n"
398 << " <dependentAssembly>\n"
399 << " <assemblyIdentity " << manifestDependency
<< " />\n"
400 << " </dependentAssembly>\n"
401 << " </dependency>\n";
403 os
<< "</assembly>\n";
408 LinkerDriver::createManifestXmlWithInternalMt(StringRef defaultXml
) {
409 std::unique_ptr
<MemoryBuffer
> defaultXmlCopy
=
410 MemoryBuffer::getMemBufferCopy(defaultXml
);
412 windows_manifest::WindowsManifestMerger merger
;
413 if (auto e
= merger
.merge(*defaultXmlCopy
.get()))
414 fatal("internal manifest tool failed on default xml: " +
415 toString(std::move(e
)));
417 for (StringRef filename
: ctx
.config
.manifestInput
) {
418 std::unique_ptr
<MemoryBuffer
> manifest
=
419 check(MemoryBuffer::getFile(filename
));
420 // Call takeBuffer to include in /reproduce: output if applicable.
421 if (auto e
= merger
.merge(takeBuffer(std::move(manifest
))))
422 fatal("internal manifest tool failed on file " + filename
+ ": " +
423 toString(std::move(e
)));
426 return std::string(merger
.getMergedManifest().get()->getBuffer());
430 LinkerDriver::createManifestXmlWithExternalMt(StringRef defaultXml
) {
431 // Create the default manifest file as a temporary file.
432 TemporaryFile
Default("defaultxml", "manifest");
434 raw_fd_ostream
os(Default
.path
, ec
, sys::fs::OF_TextWithCRLF
);
436 fatal("failed to open " + Default
.path
+ ": " + ec
.message());
440 // Merge user-supplied manifests if they are given. Since libxml2 is not
441 // enabled, we must shell out to Microsoft's mt.exe tool.
442 TemporaryFile
user("user", "manifest");
444 Executor
e("mt.exe");
447 for (StringRef filename
: ctx
.config
.manifestInput
) {
451 // Manually add the file to the /reproduce: tar if needed.
453 if (auto mbOrErr
= MemoryBuffer::getFile(filename
))
454 takeBuffer(std::move(*mbOrErr
));
457 e
.add("/out:" + StringRef(user
.path
));
461 CHECK(MemoryBuffer::getFile(user
.path
), "could not open " + user
.path
)
466 std::string
LinkerDriver::createManifestXml() {
467 std::string defaultXml
= createDefaultXml();
468 if (ctx
.config
.manifestInput
.empty())
471 if (windows_manifest::isAvailable())
472 return createManifestXmlWithInternalMt(defaultXml
);
474 return createManifestXmlWithExternalMt(defaultXml
);
477 std::unique_ptr
<WritableMemoryBuffer
>
478 LinkerDriver::createMemoryBufferForManifestRes(size_t manifestSize
) {
479 size_t resSize
= alignTo(
480 object::WIN_RES_MAGIC_SIZE
+ object::WIN_RES_NULL_ENTRY_SIZE
+
481 sizeof(object::WinResHeaderPrefix
) + sizeof(object::WinResIDs
) +
482 sizeof(object::WinResHeaderSuffix
) + manifestSize
,
483 object::WIN_RES_DATA_ALIGNMENT
);
484 return WritableMemoryBuffer::getNewMemBuffer(resSize
, ctx
.config
.outputFile
+
488 static void writeResFileHeader(char *&buf
) {
489 memcpy(buf
, COFF::WinResMagic
, sizeof(COFF::WinResMagic
));
490 buf
+= sizeof(COFF::WinResMagic
);
491 memset(buf
, 0, object::WIN_RES_NULL_ENTRY_SIZE
);
492 buf
+= object::WIN_RES_NULL_ENTRY_SIZE
;
495 static void writeResEntryHeader(char *&buf
, size_t manifestSize
,
498 auto *prefix
= reinterpret_cast<object::WinResHeaderPrefix
*>(buf
);
499 prefix
->DataSize
= manifestSize
;
500 prefix
->HeaderSize
= sizeof(object::WinResHeaderPrefix
) +
501 sizeof(object::WinResIDs
) +
502 sizeof(object::WinResHeaderSuffix
);
503 buf
+= sizeof(object::WinResHeaderPrefix
);
505 // Write the Type/Name IDs.
506 auto *iDs
= reinterpret_cast<object::WinResIDs
*>(buf
);
507 iDs
->setType(RT_MANIFEST
);
508 iDs
->setName(manifestID
);
509 buf
+= sizeof(object::WinResIDs
);
512 auto *suffix
= reinterpret_cast<object::WinResHeaderSuffix
*>(buf
);
513 suffix
->DataVersion
= 0;
514 suffix
->MemoryFlags
= object::WIN_RES_PURE_MOVEABLE
;
515 suffix
->Language
= SUBLANG_ENGLISH_US
;
517 suffix
->Characteristics
= 0;
518 buf
+= sizeof(object::WinResHeaderSuffix
);
521 // Create a resource file containing a manifest XML.
522 std::unique_ptr
<MemoryBuffer
> LinkerDriver::createManifestRes() {
523 std::string manifest
= createManifestXml();
525 std::unique_ptr
<WritableMemoryBuffer
> res
=
526 createMemoryBufferForManifestRes(manifest
.size());
528 char *buf
= res
->getBufferStart();
529 writeResFileHeader(buf
);
530 writeResEntryHeader(buf
, manifest
.size(), ctx
.config
.manifestID
);
532 // Copy the manifest data into the .res file.
533 std::copy(manifest
.begin(), manifest
.end(), buf
);
534 return std::move(res
);
537 void LinkerDriver::createSideBySideManifest() {
538 std::string path
= std::string(ctx
.config
.manifestFile
);
540 path
= ctx
.config
.outputFile
+ ".manifest";
542 raw_fd_ostream
out(path
, ec
, sys::fs::OF_TextWithCRLF
);
544 fatal("failed to create manifest: " + ec
.message());
545 out
<< createManifestXml();
548 // Parse a string in the form of
549 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
550 // or "<name>=<dllname>.<name>".
551 // Used for parsing /export arguments.
552 Export
LinkerDriver::parseExport(StringRef arg
) {
554 e
.source
= ExportSource::Export
;
557 std::tie(e
.name
, rest
) = arg
.split(",");
561 if (e
.name
.contains('=')) {
562 auto [x
, y
] = e
.name
.split("=");
564 // If "<name>=<dllname>.<name>".
565 if (y
.contains(".")) {
577 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
578 while (!rest
.empty()) {
580 std::tie(tok
, rest
) = rest
.split(",");
581 if (tok
.equals_insensitive("noname")) {
587 if (tok
.equals_insensitive("data")) {
591 if (tok
.equals_insensitive("constant")) {
595 if (tok
.equals_insensitive("private")) {
599 if (tok
.starts_with("@")) {
601 if (tok
.substr(1).getAsInteger(0, ord
))
603 if (ord
<= 0 || 65535 < ord
)
613 fatal("invalid /export: " + arg
);
616 static StringRef
undecorate(COFFLinkerContext
&ctx
, StringRef sym
) {
617 if (ctx
.config
.machine
!= I386
)
619 // In MSVC mode, a fully decorated stdcall function is exported
620 // as-is with the leading underscore (with type IMPORT_NAME).
621 // In MinGW mode, a decorated stdcall function gets the underscore
622 // removed, just like normal cdecl functions.
623 if (sym
.starts_with("_") && sym
.contains('@') && !ctx
.config
.mingw
)
625 return sym
.starts_with("_") ? sym
.substr(1) : sym
;
628 // Convert stdcall/fastcall style symbols into unsuffixed symbols,
629 // with or without a leading underscore. (MinGW specific.)
630 static StringRef
killAt(StringRef sym
, bool prefix
) {
633 // Strip any trailing stdcall suffix
634 sym
= sym
.substr(0, sym
.find('@', 1));
635 if (!sym
.starts_with("@")) {
636 if (prefix
&& !sym
.starts_with("_"))
637 return saver().save("_" + sym
);
640 // For fastcall, remove the leading @ and replace it with an
641 // underscore, if prefixes are used.
644 sym
= saver().save("_" + sym
);
648 static StringRef
exportSourceName(ExportSource s
) {
650 case ExportSource::Directives
:
651 return "source file (directives)";
652 case ExportSource::Export
:
654 case ExportSource::ModuleDefinition
:
657 llvm_unreachable("unknown ExportSource");
661 // Performs error checking on all /export arguments.
662 // It also sets ordinals.
663 void LinkerDriver::fixupExports() {
664 // Symbol ordinals must be unique.
665 std::set
<uint16_t> ords
;
666 for (Export
&e
: ctx
.config
.exports
) {
669 if (!ords
.insert(e
.ordinal
).second
)
670 fatal("duplicate export ordinal: " + e
.name
);
673 for (Export
&e
: ctx
.config
.exports
) {
674 if (!e
.forwardTo
.empty()) {
675 e
.exportName
= undecorate(ctx
, e
.name
);
677 e
.exportName
= undecorate(ctx
, e
.extName
.empty() ? e
.name
: e
.extName
);
681 if (ctx
.config
.killAt
&& ctx
.config
.machine
== I386
) {
682 for (Export
&e
: ctx
.config
.exports
) {
683 e
.name
= killAt(e
.name
, true);
684 e
.exportName
= killAt(e
.exportName
, false);
685 e
.extName
= killAt(e
.extName
, true);
686 e
.symbolName
= killAt(e
.symbolName
, true);
691 DenseMap
<StringRef
, std::pair
<Export
*, unsigned>> map(
692 ctx
.config
.exports
.size());
693 std::vector
<Export
> v
;
694 for (Export
&e
: ctx
.config
.exports
) {
695 auto pair
= map
.insert(std::make_pair(e
.exportName
, std::make_pair(&e
, 0)));
696 bool inserted
= pair
.second
;
698 pair
.first
->second
.second
= v
.size();
702 Export
*existing
= pair
.first
->second
.first
;
703 if (e
== *existing
|| e
.name
!= existing
->name
)
705 // If the existing export comes from .OBJ directives, we are allowed to
706 // overwrite it with /DEF: or /EXPORT without any warning, as MSVC link.exe
708 if (existing
->source
== ExportSource::Directives
) {
710 v
[pair
.first
->second
.second
] = e
;
713 if (existing
->source
== e
.source
) {
714 warn(Twine("duplicate ") + exportSourceName(existing
->source
) +
715 " option: " + e
.name
);
717 warn("duplicate export: " + e
.name
+
718 Twine(" first seen in " + exportSourceName(existing
->source
) +
719 Twine(", now in " + exportSourceName(e
.source
))));
722 ctx
.config
.exports
= std::move(v
);
725 llvm::sort(ctx
.config
.exports
, [](const Export
&a
, const Export
&b
) {
726 return a
.exportName
< b
.exportName
;
730 void LinkerDriver::assignExportOrdinals() {
731 // Assign unique ordinals if default (= 0).
733 for (Export
&e
: ctx
.config
.exports
)
734 max
= std::max(max
, (uint32_t)e
.ordinal
);
735 for (Export
&e
: ctx
.config
.exports
)
738 if (max
> std::numeric_limits
<uint16_t>::max())
739 fatal("too many exported symbols (got " + Twine(max
) + ", max " +
740 Twine(std::numeric_limits
<uint16_t>::max()) + ")");
743 // Parses a string in the form of "key=value" and check
744 // if value matches previous values for the same key.
745 void LinkerDriver::checkFailIfMismatch(StringRef arg
, InputFile
*source
) {
746 auto [k
, v
] = arg
.split('=');
747 if (k
.empty() || v
.empty())
748 fatal("/failifmismatch: invalid argument: " + arg
);
749 std::pair
<StringRef
, InputFile
*> existing
= ctx
.config
.mustMatch
[k
];
750 if (!existing
.first
.empty() && v
!= existing
.first
) {
751 std::string sourceStr
= source
? toString(source
) : "cmd-line";
752 std::string existingStr
=
753 existing
.second
? toString(existing
.second
) : "cmd-line";
754 fatal("/failifmismatch: mismatch detected for '" + k
+ "':\n>>> " +
755 existingStr
+ " has value " + existing
.first
+ "\n>>> " + sourceStr
+
758 ctx
.config
.mustMatch
[k
] = {v
, source
};
761 // Convert Windows resource files (.res files) to a .obj file.
762 // Does what cvtres.exe does, but in-process and cross-platform.
763 MemoryBufferRef
LinkerDriver::convertResToCOFF(ArrayRef
<MemoryBufferRef
> mbs
,
764 ArrayRef
<ObjFile
*> objs
) {
765 object::WindowsResourceParser
parser(/* MinGW */ ctx
.config
.mingw
);
767 std::vector
<std::string
> duplicates
;
768 for (MemoryBufferRef mb
: mbs
) {
769 std::unique_ptr
<object::Binary
> bin
= check(object::createBinary(mb
));
770 object::WindowsResource
*rf
= dyn_cast
<object::WindowsResource
>(bin
.get());
772 fatal("cannot compile non-resource file as resource");
774 if (auto ec
= parser
.parse(rf
, duplicates
))
775 fatal(toString(std::move(ec
)));
778 // Note: This processes all .res files before all objs. Ideally they'd be
779 // handled in the same order they were linked (to keep the right one, if
780 // there are duplicates that are tolerated due to forceMultipleRes).
781 for (ObjFile
*f
: objs
) {
782 object::ResourceSectionRef rsf
;
783 if (auto ec
= rsf
.load(f
->getCOFFObj()))
784 fatal(toString(f
) + ": " + toString(std::move(ec
)));
786 if (auto ec
= parser
.parse(rsf
, f
->getName(), duplicates
))
787 fatal(toString(std::move(ec
)));
790 if (ctx
.config
.mingw
)
791 parser
.cleanUpManifests(duplicates
);
793 for (const auto &dupeDiag
: duplicates
)
794 if (ctx
.config
.forceMultipleRes
)
799 Expected
<std::unique_ptr
<MemoryBuffer
>> e
=
800 llvm::object::writeWindowsResourceCOFF(ctx
.config
.machine
, parser
,
801 ctx
.config
.timestamp
);
803 fatal("failed to write .res to COFF: " + toString(e
.takeError()));
805 MemoryBufferRef mbref
= **e
;
806 make
<std::unique_ptr
<MemoryBuffer
>>(std::move(*e
)); // take ownership
812 // Create prefix string literals used in Options.td
813 #define PREFIX(NAME, VALUE) \
814 static constexpr llvm::StringLiteral NAME##_init[] = VALUE; \
815 static constexpr llvm::ArrayRef<llvm::StringLiteral> NAME( \
816 NAME##_init, std::size(NAME##_init) - 1);
817 #include "Options.inc"
820 // Create table mapping all options defined in Options.td
821 static constexpr llvm::opt::OptTable::Info infoTable
[] = {
822 #define OPTION(...) LLVM_CONSTRUCT_OPT_INFO(__VA_ARGS__),
823 #include "Options.inc"
827 COFFOptTable::COFFOptTable() : GenericOptTable(infoTable
, true) {}
829 // Set color diagnostics according to --color-diagnostics={auto,always,never}
830 // or --no-color-diagnostics flags.
831 static void handleColorDiagnostics(opt::InputArgList
&args
) {
832 auto *arg
= args
.getLastArg(OPT_color_diagnostics
, OPT_color_diagnostics_eq
,
833 OPT_no_color_diagnostics
);
836 if (arg
->getOption().getID() == OPT_color_diagnostics
) {
837 lld::errs().enable_colors(true);
838 } else if (arg
->getOption().getID() == OPT_no_color_diagnostics
) {
839 lld::errs().enable_colors(false);
841 StringRef s
= arg
->getValue();
843 lld::errs().enable_colors(true);
844 else if (s
== "never")
845 lld::errs().enable_colors(false);
846 else if (s
!= "auto")
847 error("unknown option: --color-diagnostics=" + s
);
851 static cl::TokenizerCallback
getQuotingStyle(opt::InputArgList
&args
) {
852 if (auto *arg
= args
.getLastArg(OPT_rsp_quoting
)) {
853 StringRef s
= arg
->getValue();
854 if (s
!= "windows" && s
!= "posix")
855 error("invalid response file quoting: " + s
);
857 return cl::TokenizeWindowsCommandLine
;
858 return cl::TokenizeGNUCommandLine
;
860 // The COFF linker always defaults to Windows quoting.
861 return cl::TokenizeWindowsCommandLine
;
864 ArgParser::ArgParser(COFFLinkerContext
&c
) : ctx(c
) {}
866 // Parses a given list of options.
867 opt::InputArgList
ArgParser::parse(ArrayRef
<const char *> argv
) {
868 // Make InputArgList from string vectors.
869 unsigned missingIndex
;
870 unsigned missingCount
;
872 // We need to get the quoting style for response files before parsing all
873 // options so we parse here before and ignore all the options but
874 // --rsp-quoting and /lldignoreenv.
875 // (This means --rsp-quoting can't be added through %LINK%.)
876 opt::InputArgList args
=
877 ctx
.optTable
.ParseArgs(argv
, missingIndex
, missingCount
);
879 // Expand response files (arguments in the form of @<filename>) and insert
880 // flags from %LINK% and %_LINK_%, and then parse the argument again.
881 SmallVector
<const char *, 256> expandedArgv(argv
.data(),
882 argv
.data() + argv
.size());
883 if (!args
.hasArg(OPT_lldignoreenv
))
884 addLINK(expandedArgv
);
885 cl::ExpandResponseFiles(saver(), getQuotingStyle(args
), expandedArgv
);
886 args
= ctx
.optTable
.ParseArgs(ArrayRef(expandedArgv
).drop_front(),
887 missingIndex
, missingCount
);
889 // Print the real command line if response files are expanded.
890 if (args
.hasArg(OPT_verbose
) && argv
.size() != expandedArgv
.size()) {
891 std::string msg
= "Command line:";
892 for (const char *s
: expandedArgv
)
893 msg
+= " " + std::string(s
);
897 // Save the command line after response file expansion so we can write it to
898 // the PDB if necessary. Mimic MSVC, which skips input files.
899 ctx
.config
.argv
= {argv
[0]};
900 for (opt::Arg
*arg
: args
) {
901 if (arg
->getOption().getKind() != opt::Option::InputClass
) {
902 ctx
.config
.argv
.emplace_back(args
.getArgString(arg
->getIndex()));
906 // Handle /WX early since it converts missing argument warnings to errors.
907 errorHandler().fatalWarnings
= args
.hasFlag(OPT_WX
, OPT_WX_no
, false);
910 fatal(Twine(args
.getArgString(missingIndex
)) + ": missing argument");
912 handleColorDiagnostics(args
);
914 for (opt::Arg
*arg
: args
.filtered(OPT_UNKNOWN
)) {
916 if (ctx
.optTable
.findNearest(arg
->getAsString(args
), nearest
) > 1)
917 warn("ignoring unknown argument '" + arg
->getAsString(args
) + "'");
919 warn("ignoring unknown argument '" + arg
->getAsString(args
) +
920 "', did you mean '" + nearest
+ "'");
923 if (args
.hasArg(OPT_lib
))
924 warn("ignoring /lib since it's not the first argument");
929 // Tokenizes and parses a given string as command line in .drective section.
930 ParsedDirectives
ArgParser::parseDirectives(StringRef s
) {
931 ParsedDirectives result
;
932 SmallVector
<const char *, 16> rest
;
934 // Handle /EXPORT and /INCLUDE in a fast path. These directives can appear for
935 // potentially every symbol in the object, so they must be handled quickly.
936 SmallVector
<StringRef
, 16> tokens
;
937 cl::TokenizeWindowsCommandLineNoCopy(s
, saver(), tokens
);
938 for (StringRef tok
: tokens
) {
939 if (tok
.starts_with_insensitive("/export:") ||
940 tok
.starts_with_insensitive("-export:"))
941 result
.exports
.push_back(tok
.substr(strlen("/export:")));
942 else if (tok
.starts_with_insensitive("/include:") ||
943 tok
.starts_with_insensitive("-include:"))
944 result
.includes
.push_back(tok
.substr(strlen("/include:")));
945 else if (tok
.starts_with_insensitive("/exclude-symbols:") ||
946 tok
.starts_with_insensitive("-exclude-symbols:"))
947 result
.excludes
.push_back(tok
.substr(strlen("/exclude-symbols:")));
949 // Copy substrings that are not valid C strings. The tokenizer may have
950 // already copied quoted arguments for us, so those do not need to be
952 bool HasNul
= tok
.end() != s
.end() && tok
.data()[tok
.size()] == '\0';
953 rest
.push_back(HasNul
? tok
.data() : saver().save(tok
).data());
957 // Make InputArgList from unparsed string vectors.
958 unsigned missingIndex
;
959 unsigned missingCount
;
961 result
.args
= ctx
.optTable
.ParseArgs(rest
, missingIndex
, missingCount
);
964 fatal(Twine(result
.args
.getArgString(missingIndex
)) + ": missing argument");
965 for (auto *arg
: result
.args
.filtered(OPT_UNKNOWN
))
966 warn("ignoring unknown argument: " + arg
->getAsString(result
.args
));
970 // link.exe has an interesting feature. If LINK or _LINK_ environment
971 // variables exist, their contents are handled as command line strings.
972 // So you can pass extra arguments using them.
973 void ArgParser::addLINK(SmallVector
<const char *, 256> &argv
) {
974 // Concatenate LINK env and command line arguments, and then parse them.
975 if (std::optional
<std::string
> s
= Process::GetEnv("LINK")) {
976 std::vector
<const char *> v
= tokenize(*s
);
977 argv
.insert(std::next(argv
.begin()), v
.begin(), v
.end());
979 if (std::optional
<std::string
> s
= Process::GetEnv("_LINK_")) {
980 std::vector
<const char *> v
= tokenize(*s
);
981 argv
.insert(std::next(argv
.begin()), v
.begin(), v
.end());
985 std::vector
<const char *> ArgParser::tokenize(StringRef s
) {
986 SmallVector
<const char *, 16> tokens
;
987 cl::TokenizeWindowsCommandLine(s
, saver(), tokens
);
988 return std::vector
<const char *>(tokens
.begin(), tokens
.end());
991 void LinkerDriver::printHelp(const char *argv0
) {
992 ctx
.optTable
.printHelp(lld::outs(),
993 (std::string(argv0
) + " [options] file...").c_str(),
994 "LLVM Linker", false);