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 //===----------------------------------------------------------------------===//
18 #include "lld/Common/ErrorHandler.h"
19 #include "lld/Common/Memory.h"
20 #include "llvm/ADT/Optional.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/BinaryFormat/COFF.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Object/WindowsResource.h"
25 #include "llvm/Option/Arg.h"
26 #include "llvm/Option/ArgList.h"
27 #include "llvm/Option/Option.h"
28 #include "llvm/Support/CommandLine.h"
29 #include "llvm/Support/FileUtilities.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Process.h"
32 #include "llvm/Support/Program.h"
33 #include "llvm/Support/raw_ostream.h"
34 #include "llvm/WindowsManifest/WindowsManifestMerger.h"
37 using namespace llvm::COFF;
39 using llvm::sys::Process;
45 const uint16_t SUBLANG_ENGLISH_US = 0x0409;
46 const uint16_t RT_MANIFEST = 24;
50 explicit Executor(StringRef s) : prog(saver.save(s)) {}
51 void add(StringRef s) { args.push_back(saver.save(s)); }
52 void add(std::string &s) { args.push_back(saver.save(s)); }
53 void add(Twine s) { args.push_back(saver.save(s)); }
54 void add(const char *s) { args.push_back(saver.save(s)); }
57 ErrorOr<std::string> exeOrErr = sys::findProgramByName(prog);
58 if (auto ec = exeOrErr.getError())
59 fatal("unable to find " + prog + " in PATH: " + ec.message());
60 StringRef exe = saver.save(*exeOrErr);
61 args.insert(args.begin(), exe);
63 if (sys::ExecuteAndWait(args[0], args) != 0)
64 fatal("ExecuteAndWait failed: " +
65 llvm::join(args.begin(), args.end(), " "));
70 std::vector<StringRef> args;
73 } // anonymous namespace
75 // Parses a string in the form of "<integer>[,<integer>]".
76 void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size) {
78 std::tie(s1, s2) = arg.split(',');
79 if (s1.getAsInteger(0, *addr))
80 fatal("invalid number: " + s1);
81 if (size && !s2.empty() && s2.getAsInteger(0, *size))
82 fatal("invalid number: " + s2);
85 // Parses a string in the form of "<integer>[.<integer>]".
86 // If second number is not present, Minor is set to 0.
87 void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor) {
89 std::tie(s1, s2) = arg.split('.');
90 if (s1.getAsInteger(0, *major))
91 fatal("invalid number: " + s1);
93 if (!s2.empty() && s2.getAsInteger(0, *minor))
94 fatal("invalid number: " + s2);
97 void parseGuard(StringRef fullArg) {
98 SmallVector<StringRef, 1> splitArgs;
99 fullArg.split(splitArgs, ",");
100 for (StringRef arg : splitArgs) {
101 if (arg.equals_lower("no"))
102 config->guardCF = GuardCFLevel::Off;
103 else if (arg.equals_lower("nolongjmp"))
104 config->guardCF = GuardCFLevel::NoLongJmp;
105 else if (arg.equals_lower("cf") || arg.equals_lower("longjmp"))
106 config->guardCF = GuardCFLevel::Full;
108 fatal("invalid argument to /guard: " + arg);
112 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
113 void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
115 StringRef sysStr, ver;
116 std::tie(sysStr, ver) = arg.split(',');
117 std::string sysStrLower = sysStr.lower();
118 *sys = StringSwitch<WindowsSubsystem>(sysStrLower)
119 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
120 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
121 .Case("default", IMAGE_SUBSYSTEM_UNKNOWN)
122 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
123 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
124 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
125 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
126 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
127 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
128 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
129 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
130 if (*sys == IMAGE_SUBSYSTEM_UNKNOWN && sysStrLower != "default")
131 fatal("unknown subsystem: " + sysStr);
133 parseVersion(ver, major, minor);
136 // Parse a string of the form of "<from>=<to>".
137 // Results are directly written to Config.
138 void parseAlternateName(StringRef s) {
140 std::tie(from, to) = s.split('=');
141 if (from.empty() || to.empty())
142 fatal("/alternatename: invalid argument: " + s);
143 auto it = config->alternateNames.find(from);
144 if (it != config->alternateNames.end() && it->second != to)
145 fatal("/alternatename: conflicts: " + s);
146 config->alternateNames.insert(it, std::make_pair(from, to));
149 // Parse a string of the form of "<from>=<to>".
150 // Results are directly written to Config.
151 void parseMerge(StringRef s) {
153 std::tie(from, to) = s.split('=');
154 if (from.empty() || to.empty())
155 fatal("/merge: invalid argument: " + s);
156 if (from == ".rsrc" || to == ".rsrc")
157 fatal("/merge: cannot merge '.rsrc' with any section");
158 if (from == ".reloc" || to == ".reloc")
159 fatal("/merge: cannot merge '.reloc' with any section");
160 auto pair = config->merge.insert(std::make_pair(from, to));
161 bool inserted = pair.second;
163 StringRef existing = pair.first->second;
165 warn(s + ": already merged into " + existing);
169 static uint32_t parseSectionAttributes(StringRef s) {
171 for (char c : s.lower()) {
174 ret |= IMAGE_SCN_MEM_DISCARDABLE;
177 ret |= IMAGE_SCN_MEM_EXECUTE;
180 ret |= IMAGE_SCN_MEM_NOT_CACHED;
183 ret |= IMAGE_SCN_MEM_NOT_PAGED;
186 ret |= IMAGE_SCN_MEM_READ;
189 ret |= IMAGE_SCN_MEM_SHARED;
192 ret |= IMAGE_SCN_MEM_WRITE;
195 fatal("/section: invalid argument: " + s);
201 // Parses /section option argument.
202 void parseSection(StringRef s) {
203 StringRef name, attrs;
204 std::tie(name, attrs) = s.split(',');
205 if (name.empty() || attrs.empty())
206 fatal("/section: invalid argument: " + s);
207 config->section[name] = parseSectionAttributes(attrs);
210 // Parses /aligncomm option argument.
211 void parseAligncomm(StringRef s) {
212 StringRef name, align;
213 std::tie(name, align) = s.split(',');
214 if (name.empty() || align.empty()) {
215 error("/aligncomm: invalid argument: " + s);
219 if (align.getAsInteger(0, v)) {
220 error("/aligncomm: invalid argument: " + s);
223 config->alignComm[name] = std::max(config->alignComm[name], 1 << v);
226 // Parses /functionpadmin option argument.
227 void parseFunctionPadMin(llvm::opt::Arg *a, llvm::COFF::MachineTypes machine) {
228 StringRef arg = a->getNumValues() ? a->getValue() : "";
230 // Optional padding in bytes is given.
231 if (arg.getAsInteger(0, config->functionPadMin))
232 error("/functionpadmin: invalid argument: " + arg);
235 // No optional argument given.
236 // Set default padding based on machine, similar to link.exe.
237 // There is no default padding for ARM platforms.
238 if (machine == I386) {
239 config->functionPadMin = 5;
240 } else if (machine == AMD64) {
241 config->functionPadMin = 6;
243 error("/functionpadmin: invalid argument for this machine: " + arg);
247 // Parses a string in the form of "EMBED[,=<integer>]|NO".
248 // Results are directly written to Config.
249 void parseManifest(StringRef arg) {
250 if (arg.equals_lower("no")) {
251 config->manifest = Configuration::No;
254 if (!arg.startswith_lower("embed"))
255 fatal("invalid option " + arg);
256 config->manifest = Configuration::Embed;
257 arg = arg.substr(strlen("embed"));
260 if (!arg.startswith_lower(",id="))
261 fatal("invalid option " + arg);
262 arg = arg.substr(strlen(",id="));
263 if (arg.getAsInteger(0, config->manifestID))
264 fatal("invalid option " + arg);
267 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
268 // Results are directly written to Config.
269 void parseManifestUAC(StringRef arg) {
270 if (arg.equals_lower("no")) {
271 config->manifestUAC = false;
278 if (arg.startswith_lower("level=")) {
279 arg = arg.substr(strlen("level="));
280 std::tie(config->manifestLevel, arg) = arg.split(" ");
283 if (arg.startswith_lower("uiaccess=")) {
284 arg = arg.substr(strlen("uiaccess="));
285 std::tie(config->manifestUIAccess, arg) = arg.split(" ");
288 fatal("invalid option " + arg);
292 // Parses a string in the form of "cd|net[,(cd|net)]*"
293 // Results are directly written to Config.
294 void parseSwaprun(StringRef arg) {
296 StringRef swaprun, newArg;
297 std::tie(swaprun, newArg) = arg.split(',');
298 if (swaprun.equals_lower("cd"))
299 config->swaprunCD = true;
300 else if (swaprun.equals_lower("net"))
301 config->swaprunNet = true;
302 else if (swaprun.empty())
303 error("/swaprun: missing argument");
305 error("/swaprun: invalid argument: " + swaprun);
306 // To catch trailing commas, e.g. `/spawrun:cd,`
307 if (newArg.empty() && arg.endswith(","))
308 error("/swaprun: missing argument");
310 } while (!arg.empty());
313 // An RAII temporary file class that automatically removes a temporary file.
315 class TemporaryFile {
317 TemporaryFile(StringRef prefix, StringRef extn, StringRef contents = "") {
319 if (auto ec = sys::fs::createTemporaryFile("lld-" + prefix, extn, s))
320 fatal("cannot create a temporary file: " + ec.message());
323 if (!contents.empty()) {
325 raw_fd_ostream os(path, ec, sys::fs::OF_None);
327 fatal("failed to open " + path + ": " + ec.message());
332 TemporaryFile(TemporaryFile &&obj) {
333 std::swap(path, obj.path);
339 if (sys::fs::remove(path))
340 fatal("failed to remove " + path);
343 // Returns a memory buffer of this temporary file.
344 // Note that this function does not leave the file open,
345 // so it is safe to remove the file immediately after this function
346 // is called (you cannot remove an opened file on Windows.)
347 std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
348 // IsVolatile=true forces MemoryBuffer to not use mmap().
349 return CHECK(MemoryBuffer::getFile(path, /*FileSize=*/-1,
350 /*RequiresNullTerminator=*/false,
351 /*IsVolatile=*/true),
352 "could not open " + path);
359 static std::string createDefaultXml() {
361 raw_string_ostream os(ret);
363 // Emit the XML. Note that we do *not* verify that the XML attributes are
364 // syntactically correct. This is intentional for link.exe compatibility.
365 os << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
366 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
367 << " manifestVersion=\"1.0\">\n";
368 if (config->manifestUAC) {
369 os << " <trustInfo>\n"
371 << " <requestedPrivileges>\n"
372 << " <requestedExecutionLevel level=" << config->manifestLevel
373 << " uiAccess=" << config->manifestUIAccess << "/>\n"
374 << " </requestedPrivileges>\n"
376 << " </trustInfo>\n";
378 if (!config->manifestDependency.empty()) {
379 os << " <dependency>\n"
380 << " <dependentAssembly>\n"
381 << " <assemblyIdentity " << config->manifestDependency << " />\n"
382 << " </dependentAssembly>\n"
383 << " </dependency>\n";
385 os << "</assembly>\n";
389 static std::string createManifestXmlWithInternalMt(StringRef defaultXml) {
390 std::unique_ptr<MemoryBuffer> defaultXmlCopy =
391 MemoryBuffer::getMemBufferCopy(defaultXml);
393 windows_manifest::WindowsManifestMerger merger;
394 if (auto e = merger.merge(*defaultXmlCopy.get()))
395 fatal("internal manifest tool failed on default xml: " +
396 toString(std::move(e)));
398 for (StringRef filename : config->manifestInput) {
399 std::unique_ptr<MemoryBuffer> manifest =
400 check(MemoryBuffer::getFile(filename));
401 if (auto e = merger.merge(*manifest.get()))
402 fatal("internal manifest tool failed on file " + filename + ": " +
403 toString(std::move(e)));
406 return merger.getMergedManifest().get()->getBuffer();
409 static std::string createManifestXmlWithExternalMt(StringRef defaultXml) {
410 // Create the default manifest file as a temporary file.
411 TemporaryFile Default("defaultxml", "manifest");
413 raw_fd_ostream os(Default.path, ec, sys::fs::OF_Text);
415 fatal("failed to open " + Default.path + ": " + ec.message());
419 // Merge user-supplied manifests if they are given. Since libxml2 is not
420 // enabled, we must shell out to Microsoft's mt.exe tool.
421 TemporaryFile user("user", "manifest");
423 Executor e("mt.exe");
426 for (StringRef filename : config->manifestInput) {
431 e.add("/out:" + StringRef(user.path));
434 return CHECK(MemoryBuffer::getFile(user.path), "could not open " + user.path)
439 static std::string createManifestXml() {
440 std::string defaultXml = createDefaultXml();
441 if (config->manifestInput.empty())
444 if (windows_manifest::isAvailable())
445 return createManifestXmlWithInternalMt(defaultXml);
447 return createManifestXmlWithExternalMt(defaultXml);
450 static std::unique_ptr<WritableMemoryBuffer>
451 createMemoryBufferForManifestRes(size_t manifestSize) {
452 size_t resSize = alignTo(
453 object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +
454 sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +
455 sizeof(object::WinResHeaderSuffix) + manifestSize,
456 object::WIN_RES_DATA_ALIGNMENT);
457 return WritableMemoryBuffer::getNewMemBuffer(resSize, config->outputFile +
461 static void writeResFileHeader(char *&buf) {
462 memcpy(buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
463 buf += sizeof(COFF::WinResMagic);
464 memset(buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
465 buf += object::WIN_RES_NULL_ENTRY_SIZE;
468 static void writeResEntryHeader(char *&buf, size_t manifestSize) {
470 auto *prefix = reinterpret_cast<object::WinResHeaderPrefix *>(buf);
471 prefix->DataSize = manifestSize;
472 prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
473 sizeof(object::WinResIDs) +
474 sizeof(object::WinResHeaderSuffix);
475 buf += sizeof(object::WinResHeaderPrefix);
477 // Write the Type/Name IDs.
478 auto *iDs = reinterpret_cast<object::WinResIDs *>(buf);
479 iDs->setType(RT_MANIFEST);
480 iDs->setName(config->manifestID);
481 buf += sizeof(object::WinResIDs);
484 auto *suffix = reinterpret_cast<object::WinResHeaderSuffix *>(buf);
485 suffix->DataVersion = 0;
486 suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
487 suffix->Language = SUBLANG_ENGLISH_US;
489 suffix->Characteristics = 0;
490 buf += sizeof(object::WinResHeaderSuffix);
493 // Create a resource file containing a manifest XML.
494 std::unique_ptr<MemoryBuffer> createManifestRes() {
495 std::string manifest = createManifestXml();
497 std::unique_ptr<WritableMemoryBuffer> res =
498 createMemoryBufferForManifestRes(manifest.size());
500 char *buf = res->getBufferStart();
501 writeResFileHeader(buf);
502 writeResEntryHeader(buf, manifest.size());
504 // Copy the manifest data into the .res file.
505 std::copy(manifest.begin(), manifest.end(), buf);
506 return std::move(res);
509 void createSideBySideManifest() {
510 std::string path = config->manifestFile;
512 path = config->outputFile + ".manifest";
514 raw_fd_ostream out(path, ec, sys::fs::OF_Text);
516 fatal("failed to create manifest: " + ec.message());
517 out << createManifestXml();
520 // Parse a string in the form of
521 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
522 // or "<name>=<dllname>.<name>".
523 // Used for parsing /export arguments.
524 Export parseExport(StringRef arg) {
527 std::tie(e.name, rest) = arg.split(",");
531 if (e.name.contains('=')) {
533 std::tie(x, y) = e.name.split("=");
535 // If "<name>=<dllname>.<name>".
536 if (y.contains(".")) {
548 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
549 while (!rest.empty()) {
551 std::tie(tok, rest) = rest.split(",");
552 if (tok.equals_lower("noname")) {
558 if (tok.equals_lower("data")) {
562 if (tok.equals_lower("constant")) {
566 if (tok.equals_lower("private")) {
570 if (tok.startswith("@")) {
572 if (tok.substr(1).getAsInteger(0, ord))
574 if (ord <= 0 || 65535 < ord)
584 fatal("invalid /export: " + arg);
587 static StringRef undecorate(StringRef sym) {
588 if (config->machine != I386)
590 // In MSVC mode, a fully decorated stdcall function is exported
591 // as-is with the leading underscore (with type IMPORT_NAME).
592 // In MinGW mode, a decorated stdcall function gets the underscore
593 // removed, just like normal cdecl functions.
594 if (sym.startswith("_") && sym.contains('@') && !config->mingw)
596 return sym.startswith("_") ? sym.substr(1) : sym;
599 // Convert stdcall/fastcall style symbols into unsuffixed symbols,
600 // with or without a leading underscore. (MinGW specific.)
601 static StringRef killAt(StringRef sym, bool prefix) {
604 // Strip any trailing stdcall suffix
605 sym = sym.substr(0, sym.find('@', 1));
606 if (!sym.startswith("@")) {
607 if (prefix && !sym.startswith("_"))
608 return saver.save("_" + sym);
611 // For fastcall, remove the leading @ and replace it with an
612 // underscore, if prefixes are used.
615 sym = saver.save("_" + sym);
619 // Performs error checking on all /export arguments.
620 // It also sets ordinals.
621 void fixupExports() {
622 // Symbol ordinals must be unique.
623 std::set<uint16_t> ords;
624 for (Export &e : config->exports) {
627 if (!ords.insert(e.ordinal).second)
628 fatal("duplicate export ordinal: " + e.name);
631 for (Export &e : config->exports) {
632 if (!e.forwardTo.empty()) {
633 e.exportName = undecorate(e.name);
635 e.exportName = undecorate(e.extName.empty() ? e.name : e.extName);
639 if (config->killAt && config->machine == I386) {
640 for (Export &e : config->exports) {
641 e.name = killAt(e.name, true);
642 e.exportName = killAt(e.exportName, false);
643 e.extName = killAt(e.extName, true);
644 e.symbolName = killAt(e.symbolName, true);
649 DenseMap<StringRef, Export *> map(config->exports.size());
650 std::vector<Export> v;
651 for (Export &e : config->exports) {
652 auto pair = map.insert(std::make_pair(e.exportName, &e));
653 bool inserted = pair.second;
658 Export *existing = pair.first->second;
659 if (e == *existing || e.name != existing->name)
661 warn("duplicate /export option: " + e.name);
663 config->exports = std::move(v);
666 std::sort(config->exports.begin(), config->exports.end(),
667 [](const Export &a, const Export &b) {
668 return a.exportName < b.exportName;
672 void assignExportOrdinals() {
673 // Assign unique ordinals if default (= 0).
675 for (Export &e : config->exports)
676 max = std::max(max, e.ordinal);
677 for (Export &e : config->exports)
682 // Parses a string in the form of "key=value" and check
683 // if value matches previous values for the same key.
684 void checkFailIfMismatch(StringRef arg, InputFile *source) {
686 std::tie(k, v) = arg.split('=');
687 if (k.empty() || v.empty())
688 fatal("/failifmismatch: invalid argument: " + arg);
689 std::pair<StringRef, InputFile *> existing = config->mustMatch[k];
690 if (!existing.first.empty() && v != existing.first) {
691 std::string sourceStr = source ? toString(source) : "cmd-line";
692 std::string existingStr =
693 existing.second ? toString(existing.second) : "cmd-line";
694 fatal("/failifmismatch: mismatch detected for '" + k + "':\n>>> " +
695 existingStr + " has value " + existing.first + "\n>>> " + sourceStr +
698 config->mustMatch[k] = {v, source};
701 // Convert Windows resource files (.res files) to a .obj file.
702 // Does what cvtres.exe does, but in-process and cross-platform.
703 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
704 ArrayRef<ObjFile *> objs) {
705 object::WindowsResourceParser parser(/* MinGW */ config->mingw);
707 std::vector<std::string> duplicates;
708 for (MemoryBufferRef mb : mbs) {
709 std::unique_ptr<object::Binary> bin = check(object::createBinary(mb));
710 object::WindowsResource *rf = dyn_cast<object::WindowsResource>(bin.get());
712 fatal("cannot compile non-resource file as resource");
714 if (auto ec = parser.parse(rf, duplicates))
715 fatal(toString(std::move(ec)));
718 // Note: This processes all .res files before all objs. Ideally they'd be
719 // handled in the same order they were linked (to keep the right one, if
720 // there are duplicates that are tolerated due to forceMultipleRes).
721 for (ObjFile *f : objs) {
722 object::ResourceSectionRef rsf;
723 if (auto ec = rsf.load(f->getCOFFObj()))
724 fatal(toString(f) + ": " + toString(std::move(ec)));
726 if (auto ec = parser.parse(rsf, f->getName(), duplicates))
727 fatal(toString(std::move(ec)));
731 parser.cleanUpManifests(duplicates);
733 for (const auto &dupeDiag : duplicates)
734 if (config->forceMultipleRes)
739 Expected<std::unique_ptr<MemoryBuffer>> e =
740 llvm::object::writeWindowsResourceCOFF(config->machine, parser,
743 fatal("failed to write .res to COFF: " + toString(e.takeError()));
745 MemoryBufferRef mbref = **e;
746 make<std::unique_ptr<MemoryBuffer>>(std::move(*e)); // take ownership
752 // Create prefix string literals used in Options.td
753 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
754 #include "Options.inc"
757 // Create table mapping all options defined in Options.td
758 static const llvm::opt::OptTable::Info infoTable[] = {
759 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
760 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
761 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
762 #include "Options.inc"
766 COFFOptTable::COFFOptTable() : OptTable(infoTable, true) {}
768 // Set color diagnostics according to --color-diagnostics={auto,always,never}
769 // or --no-color-diagnostics flags.
770 static void handleColorDiagnostics(opt::InputArgList &args) {
771 auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
772 OPT_no_color_diagnostics);
775 if (arg->getOption().getID() == OPT_color_diagnostics) {
776 lld::errs().enable_colors(true);
777 } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
778 lld::errs().enable_colors(false);
780 StringRef s = arg->getValue();
782 lld::errs().enable_colors(true);
783 else if (s == "never")
784 lld::errs().enable_colors(false);
785 else if (s != "auto")
786 error("unknown option: --color-diagnostics=" + s);
790 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
791 if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
792 StringRef s = arg->getValue();
793 if (s != "windows" && s != "posix")
794 error("invalid response file quoting: " + s);
796 return cl::TokenizeWindowsCommandLine;
797 return cl::TokenizeGNUCommandLine;
799 // The COFF linker always defaults to Windows quoting.
800 return cl::TokenizeWindowsCommandLine;
803 // Parses a given list of options.
804 opt::InputArgList ArgParser::parse(ArrayRef<const char *> argv) {
805 // Make InputArgList from string vectors.
806 unsigned missingIndex;
807 unsigned missingCount;
809 // We need to get the quoting style for response files before parsing all
810 // options so we parse here before and ignore all the options but
811 // --rsp-quoting and /lldignoreenv.
812 // (This means --rsp-quoting can't be added through %LINK%.)
813 opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
816 // Expand response files (arguments in the form of @<filename>) and insert
817 // flags from %LINK% and %_LINK_%, and then parse the argument again.
818 SmallVector<const char *, 256> expandedArgv(argv.data(),
819 argv.data() + argv.size());
820 if (!args.hasArg(OPT_lldignoreenv))
821 addLINK(expandedArgv);
822 cl::ExpandResponseFiles(saver, getQuotingStyle(args), expandedArgv);
823 args = table.ParseArgs(makeArrayRef(expandedArgv).drop_front(), missingIndex,
826 // Print the real command line if response files are expanded.
827 if (args.hasArg(OPT_verbose) && argv.size() != expandedArgv.size()) {
828 std::string msg = "Command line:";
829 for (const char *s : expandedArgv)
830 msg += " " + std::string(s);
834 // Save the command line after response file expansion so we can write it to
835 // the PDB if necessary.
836 config->argv = {expandedArgv.begin(), expandedArgv.end()};
838 // Handle /WX early since it converts missing argument warnings to errors.
839 errorHandler().fatalWarnings = args.hasFlag(OPT_WX, OPT_WX_no, false);
842 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
844 handleColorDiagnostics(args);
846 for (auto *arg : args.filtered(OPT_UNKNOWN)) {
848 if (table.findNearest(arg->getAsString(args), nearest) > 1)
849 warn("ignoring unknown argument '" + arg->getAsString(args) + "'");
851 warn("ignoring unknown argument '" + arg->getAsString(args) +
852 "', did you mean '" + nearest + "'");
855 if (args.hasArg(OPT_lib))
856 warn("ignoring /lib since it's not the first argument");
861 // Tokenizes and parses a given string as command line in .drective section.
862 // /EXPORT options are processed in fastpath.
863 std::pair<opt::InputArgList, std::vector<StringRef>>
864 ArgParser::parseDirectives(StringRef s) {
865 std::vector<StringRef> exports;
866 SmallVector<const char *, 16> rest;
868 for (StringRef tok : tokenize(s)) {
869 if (tok.startswith_lower("/export:") || tok.startswith_lower("-export:"))
870 exports.push_back(tok.substr(strlen("/export:")));
872 rest.push_back(tok.data());
875 // Make InputArgList from unparsed string vectors.
876 unsigned missingIndex;
877 unsigned missingCount;
879 opt::InputArgList args = table.ParseArgs(rest, missingIndex, missingCount);
882 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
883 for (auto *arg : args.filtered(OPT_UNKNOWN))
884 warn("ignoring unknown argument: " + arg->getAsString(args));
885 return {std::move(args), std::move(exports)};
888 // link.exe has an interesting feature. If LINK or _LINK_ environment
889 // variables exist, their contents are handled as command line strings.
890 // So you can pass extra arguments using them.
891 void ArgParser::addLINK(SmallVector<const char *, 256> &argv) {
892 // Concatenate LINK env and command line arguments, and then parse them.
893 if (Optional<std::string> s = Process::GetEnv("LINK")) {
894 std::vector<const char *> v = tokenize(*s);
895 argv.insert(std::next(argv.begin()), v.begin(), v.end());
897 if (Optional<std::string> s = Process::GetEnv("_LINK_")) {
898 std::vector<const char *> v = tokenize(*s);
899 argv.insert(std::next(argv.begin()), v.begin(), v.end());
903 std::vector<const char *> ArgParser::tokenize(StringRef s) {
904 SmallVector<const char *, 16> tokens;
905 cl::TokenizeWindowsCommandLine(s, saver, tokens);
906 return std::vector<const char *>(tokens.begin(), tokens.end());
909 void printHelp(const char *argv0) {
910 COFFOptTable().PrintHelp(lld::outs(),
911 (std::string(argv0) + " [options] file...").c_str(),
912 "LLVM Linker", false);