1 //===- DriverUtils.cpp ----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains utility functions for the driver. Because there
11 // are so many small functions, we created this separate file to make
12 // Driver.cpp less cluttered.
14 //===----------------------------------------------------------------------===//
19 #include "lld/Common/ErrorHandler.h"
20 #include "lld/Common/Memory.h"
21 #include "llvm/ADT/Optional.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"
38 using namespace llvm::COFF;
40 using llvm::sys::Process;
46 const uint16_t SUBLANG_ENGLISH_US = 0x0409;
47 const uint16_t RT_MANIFEST = 24;
51 explicit Executor(StringRef S) : Prog(Saver.save(S)) {}
52 void add(StringRef S) { Args.push_back(Saver.save(S)); }
53 void add(std::string &S) { Args.push_back(Saver.save(S)); }
54 void add(Twine S) { Args.push_back(Saver.save(S)); }
55 void add(const char *S) { Args.push_back(Saver.save(S)); }
58 ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
59 if (auto EC = ExeOrErr.getError())
60 fatal("unable to find " + Prog + " in PATH: " + EC.message());
61 StringRef Exe = Saver.save(*ExeOrErr);
62 Args.insert(Args.begin(), Exe);
64 if (sys::ExecuteAndWait(Args[0], Args) != 0)
65 fatal("ExecuteAndWait failed: " +
66 llvm::join(Args.begin(), Args.end(), " "));
71 std::vector<StringRef> Args;
74 } // anonymous namespace
76 // Returns /machine's value.
77 MachineTypes getMachineType(StringRef S) {
78 MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
79 .Cases("x64", "amd64", AMD64)
80 .Cases("x86", "i386", I386)
83 .Default(IMAGE_FILE_MACHINE_UNKNOWN);
84 if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
86 fatal("unknown /machine argument: " + S);
89 StringRef machineToStr(MachineTypes MT) {
100 llvm_unreachable("unknown machine type");
104 // Parses a string in the form of "<integer>[,<integer>]".
105 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
107 std::tie(S1, S2) = Arg.split(',');
108 if (S1.getAsInteger(0, *Addr))
109 fatal("invalid number: " + S1);
110 if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
111 fatal("invalid number: " + S2);
114 // Parses a string in the form of "<integer>[.<integer>]".
115 // If second number is not present, Minor is set to 0.
116 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
118 std::tie(S1, S2) = Arg.split('.');
119 if (S1.getAsInteger(0, *Major))
120 fatal("invalid number: " + S1);
122 if (!S2.empty() && S2.getAsInteger(0, *Minor))
123 fatal("invalid number: " + S2);
126 void parseGuard(StringRef FullArg) {
127 SmallVector<StringRef, 1> SplitArgs;
128 FullArg.split(SplitArgs, ",");
129 for (StringRef Arg : SplitArgs) {
130 if (Arg.equals_lower("no"))
131 Config->GuardCF = GuardCFLevel::Off;
132 else if (Arg.equals_lower("nolongjmp"))
133 Config->GuardCF = GuardCFLevel::NoLongJmp;
134 else if (Arg.equals_lower("cf") || Arg.equals_lower("longjmp"))
135 Config->GuardCF = GuardCFLevel::Full;
137 fatal("invalid argument to /guard: " + Arg);
141 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
142 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
144 StringRef SysStr, Ver;
145 std::tie(SysStr, Ver) = Arg.split(',');
146 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
147 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
148 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
149 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
150 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
151 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
152 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
153 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
154 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
155 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
156 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
157 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
158 fatal("unknown subsystem: " + SysStr);
160 parseVersion(Ver, Major, Minor);
163 // Parse a string of the form of "<from>=<to>".
164 // Results are directly written to Config.
165 void parseAlternateName(StringRef S) {
167 std::tie(From, To) = S.split('=');
168 if (From.empty() || To.empty())
169 fatal("/alternatename: invalid argument: " + S);
170 auto It = Config->AlternateNames.find(From);
171 if (It != Config->AlternateNames.end() && It->second != To)
172 fatal("/alternatename: conflicts: " + S);
173 Config->AlternateNames.insert(It, std::make_pair(From, To));
176 // Parse a string of the form of "<from>=<to>".
177 // Results are directly written to Config.
178 void parseMerge(StringRef S) {
180 std::tie(From, To) = S.split('=');
181 if (From.empty() || To.empty())
182 fatal("/merge: invalid argument: " + S);
183 if (From == ".rsrc" || To == ".rsrc")
184 fatal("/merge: cannot merge '.rsrc' with any section");
185 if (From == ".reloc" || To == ".reloc")
186 fatal("/merge: cannot merge '.reloc' with any section");
187 auto Pair = Config->Merge.insert(std::make_pair(From, To));
188 bool Inserted = Pair.second;
190 StringRef Existing = Pair.first->second;
192 warn(S + ": already merged into " + Existing);
196 static uint32_t parseSectionAttributes(StringRef S) {
198 for (char C : S.lower()) {
201 Ret |= IMAGE_SCN_MEM_DISCARDABLE;
204 Ret |= IMAGE_SCN_MEM_EXECUTE;
207 Ret |= IMAGE_SCN_MEM_NOT_CACHED;
210 Ret |= IMAGE_SCN_MEM_NOT_PAGED;
213 Ret |= IMAGE_SCN_MEM_READ;
216 Ret |= IMAGE_SCN_MEM_SHARED;
219 Ret |= IMAGE_SCN_MEM_WRITE;
222 fatal("/section: invalid argument: " + S);
228 // Parses /section option argument.
229 void parseSection(StringRef S) {
230 StringRef Name, Attrs;
231 std::tie(Name, Attrs) = S.split(',');
232 if (Name.empty() || Attrs.empty())
233 fatal("/section: invalid argument: " + S);
234 Config->Section[Name] = parseSectionAttributes(Attrs);
237 // Parses /aligncomm option argument.
238 void parseAligncomm(StringRef S) {
239 StringRef Name, Align;
240 std::tie(Name, Align) = S.split(',');
241 if (Name.empty() || Align.empty()) {
242 error("/aligncomm: invalid argument: " + S);
246 if (Align.getAsInteger(0, V)) {
247 error("/aligncomm: invalid argument: " + S);
250 Config->AlignComm[Name] = std::max(Config->AlignComm[Name], 1 << V);
253 // Parses a string in the form of "EMBED[,=<integer>]|NO".
254 // Results are directly written to Config.
255 void parseManifest(StringRef Arg) {
256 if (Arg.equals_lower("no")) {
257 Config->Manifest = Configuration::No;
260 if (!Arg.startswith_lower("embed"))
261 fatal("invalid option " + Arg);
262 Config->Manifest = Configuration::Embed;
263 Arg = Arg.substr(strlen("embed"));
266 if (!Arg.startswith_lower(",id="))
267 fatal("invalid option " + Arg);
268 Arg = Arg.substr(strlen(",id="));
269 if (Arg.getAsInteger(0, Config->ManifestID))
270 fatal("invalid option " + Arg);
273 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
274 // Results are directly written to Config.
275 void parseManifestUAC(StringRef Arg) {
276 if (Arg.equals_lower("no")) {
277 Config->ManifestUAC = false;
284 if (Arg.startswith_lower("level=")) {
285 Arg = Arg.substr(strlen("level="));
286 std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
289 if (Arg.startswith_lower("uiaccess=")) {
290 Arg = Arg.substr(strlen("uiaccess="));
291 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
294 fatal("invalid option " + Arg);
298 // An RAII temporary file class that automatically removes a temporary file.
300 class TemporaryFile {
302 TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") {
304 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
305 fatal("cannot create a temporary file: " + EC.message());
308 if (!Contents.empty()) {
310 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
312 fatal("failed to open " + Path + ": " + EC.message());
317 TemporaryFile(TemporaryFile &&Obj) {
318 std::swap(Path, Obj.Path);
324 if (sys::fs::remove(Path))
325 fatal("failed to remove " + Path);
328 // Returns a memory buffer of this temporary file.
329 // Note that this function does not leave the file open,
330 // so it is safe to remove the file immediately after this function
331 // is called (you cannot remove an opened file on Windows.)
332 std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
333 // IsVolatileSize=true forces MemoryBuffer to not use mmap().
334 return CHECK(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
335 /*RequiresNullTerminator=*/false,
336 /*IsVolatileSize=*/true),
337 "could not open " + Path);
344 static std::string createDefaultXml() {
346 raw_string_ostream OS(Ret);
348 // Emit the XML. Note that we do *not* verify that the XML attributes are
349 // syntactically correct. This is intentional for link.exe compatibility.
350 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
351 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
352 << " manifestVersion=\"1.0\">\n";
353 if (Config->ManifestUAC) {
354 OS << " <trustInfo>\n"
356 << " <requestedPrivileges>\n"
357 << " <requestedExecutionLevel level=" << Config->ManifestLevel
358 << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
359 << " </requestedPrivileges>\n"
361 << " </trustInfo>\n";
363 if (!Config->ManifestDependency.empty()) {
364 OS << " <dependency>\n"
365 << " <dependentAssembly>\n"
366 << " <assemblyIdentity " << Config->ManifestDependency << " />\n"
367 << " </dependentAssembly>\n"
368 << " </dependency>\n";
370 OS << "</assembly>\n";
374 static std::string createManifestXmlWithInternalMt(StringRef DefaultXml) {
375 std::unique_ptr<MemoryBuffer> DefaultXmlCopy =
376 MemoryBuffer::getMemBufferCopy(DefaultXml);
378 windows_manifest::WindowsManifestMerger Merger;
379 if (auto E = Merger.merge(*DefaultXmlCopy.get()))
380 fatal("internal manifest tool failed on default xml: " +
381 toString(std::move(E)));
383 for (StringRef Filename : Config->ManifestInput) {
384 std::unique_ptr<MemoryBuffer> Manifest =
385 check(MemoryBuffer::getFile(Filename));
386 if (auto E = Merger.merge(*Manifest.get()))
387 fatal("internal manifest tool failed on file " + Filename + ": " +
388 toString(std::move(E)));
391 return Merger.getMergedManifest().get()->getBuffer();
394 static std::string createManifestXmlWithExternalMt(StringRef DefaultXml) {
395 // Create the default manifest file as a temporary file.
396 TemporaryFile Default("defaultxml", "manifest");
398 raw_fd_ostream OS(Default.Path, EC, sys::fs::F_Text);
400 fatal("failed to open " + Default.Path + ": " + EC.message());
404 // Merge user-supplied manifests if they are given. Since libxml2 is not
405 // enabled, we must shell out to Microsoft's mt.exe tool.
406 TemporaryFile User("user", "manifest");
408 Executor E("mt.exe");
411 for (StringRef Filename : Config->ManifestInput) {
416 E.add("/out:" + StringRef(User.Path));
419 return CHECK(MemoryBuffer::getFile(User.Path), "could not open " + User.Path)
424 static std::string createManifestXml() {
425 std::string DefaultXml = createDefaultXml();
426 if (Config->ManifestInput.empty())
429 if (windows_manifest::isAvailable())
430 return createManifestXmlWithInternalMt(DefaultXml);
432 return createManifestXmlWithExternalMt(DefaultXml);
435 static std::unique_ptr<WritableMemoryBuffer>
436 createMemoryBufferForManifestRes(size_t ManifestSize) {
437 size_t ResSize = alignTo(
438 object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +
439 sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +
440 sizeof(object::WinResHeaderSuffix) + ManifestSize,
441 object::WIN_RES_DATA_ALIGNMENT);
442 return WritableMemoryBuffer::getNewMemBuffer(ResSize, Config->OutputFile +
446 static void writeResFileHeader(char *&Buf) {
447 memcpy(Buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
448 Buf += sizeof(COFF::WinResMagic);
449 memset(Buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
450 Buf += object::WIN_RES_NULL_ENTRY_SIZE;
453 static void writeResEntryHeader(char *&Buf, size_t ManifestSize) {
455 auto *Prefix = reinterpret_cast<object::WinResHeaderPrefix *>(Buf);
456 Prefix->DataSize = ManifestSize;
457 Prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
458 sizeof(object::WinResIDs) +
459 sizeof(object::WinResHeaderSuffix);
460 Buf += sizeof(object::WinResHeaderPrefix);
462 // Write the Type/Name IDs.
463 auto *IDs = reinterpret_cast<object::WinResIDs *>(Buf);
464 IDs->setType(RT_MANIFEST);
465 IDs->setName(Config->ManifestID);
466 Buf += sizeof(object::WinResIDs);
469 auto *Suffix = reinterpret_cast<object::WinResHeaderSuffix *>(Buf);
470 Suffix->DataVersion = 0;
471 Suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
472 Suffix->Language = SUBLANG_ENGLISH_US;
474 Suffix->Characteristics = 0;
475 Buf += sizeof(object::WinResHeaderSuffix);
478 // Create a resource file containing a manifest XML.
479 std::unique_ptr<MemoryBuffer> createManifestRes() {
480 std::string Manifest = createManifestXml();
482 std::unique_ptr<WritableMemoryBuffer> Res =
483 createMemoryBufferForManifestRes(Manifest.size());
485 char *Buf = Res->getBufferStart();
486 writeResFileHeader(Buf);
487 writeResEntryHeader(Buf, Manifest.size());
489 // Copy the manifest data into the .res file.
490 std::copy(Manifest.begin(), Manifest.end(), Buf);
491 return std::move(Res);
494 void createSideBySideManifest() {
495 std::string Path = Config->ManifestFile;
497 Path = Config->OutputFile + ".manifest";
499 raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
501 fatal("failed to create manifest: " + EC.message());
502 Out << createManifestXml();
505 // Parse a string in the form of
506 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
507 // or "<name>=<dllname>.<name>".
508 // Used for parsing /export arguments.
509 Export parseExport(StringRef Arg) {
512 std::tie(E.Name, Rest) = Arg.split(",");
516 if (E.Name.contains('=')) {
518 std::tie(X, Y) = E.Name.split("=");
520 // If "<name>=<dllname>.<name>".
521 if (Y.contains(".")) {
533 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
534 while (!Rest.empty()) {
536 std::tie(Tok, Rest) = Rest.split(",");
537 if (Tok.equals_lower("noname")) {
543 if (Tok.equals_lower("data")) {
547 if (Tok.equals_lower("constant")) {
551 if (Tok.equals_lower("private")) {
555 if (Tok.startswith("@")) {
557 if (Tok.substr(1).getAsInteger(0, Ord))
559 if (Ord <= 0 || 65535 < Ord)
569 fatal("invalid /export: " + Arg);
572 static StringRef undecorate(StringRef Sym) {
573 if (Config->Machine != I386)
575 // In MSVC mode, a fully decorated stdcall function is exported
576 // as-is with the leading underscore (with type IMPORT_NAME).
577 // In MinGW mode, a decorated stdcall function gets the underscore
578 // removed, just like normal cdecl functions.
579 if (Sym.startswith("_") && Sym.contains('@') && !Config->MinGW)
581 return Sym.startswith("_") ? Sym.substr(1) : Sym;
584 // Convert stdcall/fastcall style symbols into unsuffixed symbols,
585 // with or without a leading underscore. (MinGW specific.)
586 static StringRef killAt(StringRef Sym, bool Prefix) {
589 // Strip any trailing stdcall suffix
590 Sym = Sym.substr(0, Sym.find('@', 1));
591 if (!Sym.startswith("@")) {
592 if (Prefix && !Sym.startswith("_"))
593 return Saver.save("_" + Sym);
596 // For fastcall, remove the leading @ and replace it with an
597 // underscore, if prefixes are used.
600 Sym = Saver.save("_" + Sym);
604 // Performs error checking on all /export arguments.
605 // It also sets ordinals.
606 void fixupExports() {
607 // Symbol ordinals must be unique.
608 std::set<uint16_t> Ords;
609 for (Export &E : Config->Exports) {
612 if (!Ords.insert(E.Ordinal).second)
613 fatal("duplicate export ordinal: " + E.Name);
616 for (Export &E : Config->Exports) {
618 if (!E.ForwardTo.empty() || !Sym) {
619 E.SymbolName = E.Name;
621 if (auto *U = dyn_cast<Undefined>(Sym))
624 E.SymbolName = Sym->getName();
628 for (Export &E : Config->Exports) {
629 if (!E.ForwardTo.empty()) {
630 E.ExportName = undecorate(E.Name);
632 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
636 if (Config->KillAt && Config->Machine == I386) {
637 for (Export &E : Config->Exports) {
638 E.Name = killAt(E.Name, true);
639 E.ExportName = killAt(E.ExportName, false);
640 E.ExtName = killAt(E.ExtName, true);
641 E.SymbolName = killAt(E.SymbolName, true);
646 DenseMap<StringRef, Export *> Map(Config->Exports.size());
647 std::vector<Export> V;
648 for (Export &E : Config->Exports) {
649 auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
650 bool Inserted = Pair.second;
655 Export *Existing = Pair.first->second;
656 if (E == *Existing || E.Name != Existing->Name)
658 warn("duplicate /export option: " + E.Name);
660 Config->Exports = std::move(V);
663 std::sort(Config->Exports.begin(), Config->Exports.end(),
664 [](const Export &A, const Export &B) {
665 return A.ExportName < B.ExportName;
669 void assignExportOrdinals() {
670 // Assign unique ordinals if default (= 0).
672 for (Export &E : Config->Exports)
673 Max = std::max(Max, E.Ordinal);
674 for (Export &E : Config->Exports)
679 // Parses a string in the form of "key=value" and check
680 // if value matches previous values for the same key.
681 void checkFailIfMismatch(StringRef Arg) {
683 std::tie(K, V) = Arg.split('=');
684 if (K.empty() || V.empty())
685 fatal("/failifmismatch: invalid argument: " + Arg);
686 StringRef Existing = Config->MustMatch[K];
687 if (!Existing.empty() && V != Existing)
688 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
690 Config->MustMatch[K] = V;
693 // Convert Windows resource files (.res files) to a .obj file.
694 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> MBs) {
695 object::WindowsResourceParser Parser;
697 for (MemoryBufferRef MB : MBs) {
698 std::unique_ptr<object::Binary> Bin = check(object::createBinary(MB));
699 object::WindowsResource *RF = dyn_cast<object::WindowsResource>(Bin.get());
701 fatal("cannot compile non-resource file as resource");
702 if (auto EC = Parser.parse(RF))
703 fatal("failed to parse .res file: " + toString(std::move(EC)));
706 Expected<std::unique_ptr<MemoryBuffer>> E =
707 llvm::object::writeWindowsResourceCOFF(Config->Machine, Parser);
709 fatal("failed to write .res to COFF: " + toString(E.takeError()));
711 MemoryBufferRef MBRef = **E;
712 make<std::unique_ptr<MemoryBuffer>>(std::move(*E)); // take ownership
716 // Run MSVC link.exe for given in-memory object files.
717 // Command line options are copied from those given to LLD.
718 // This is for the /msvclto option.
719 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
720 // Write the in-memory object files to disk.
721 std::vector<TemporaryFile> Temps;
722 for (StringRef S : Objects) {
723 Temps.emplace_back("lto", "obj", S);
724 Rsp += quote(Temps.back().Path) + "\n";
727 log("link.exe " + Rsp);
729 // Run MSVC link.exe.
730 Temps.emplace_back("lto", "rsp", Rsp);
731 Executor E("link.exe");
732 E.add(Twine("@" + Temps.back().Path));
738 // Create prefix string literals used in Options.td
739 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
740 #include "Options.inc"
743 // Create table mapping all options defined in Options.td
744 static const llvm::opt::OptTable::Info InfoTable[] = {
745 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
746 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
747 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
748 #include "Options.inc"
752 COFFOptTable::COFFOptTable() : OptTable(InfoTable, true) {}
754 // Set color diagnostics according to --color-diagnostics={auto,always,never}
755 // or --no-color-diagnostics flags.
756 static void handleColorDiagnostics(opt::InputArgList &Args) {
757 auto *Arg = Args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
758 OPT_no_color_diagnostics);
761 if (Arg->getOption().getID() == OPT_color_diagnostics) {
762 errorHandler().ColorDiagnostics = true;
763 } else if (Arg->getOption().getID() == OPT_no_color_diagnostics) {
764 errorHandler().ColorDiagnostics = false;
766 StringRef S = Arg->getValue();
768 errorHandler().ColorDiagnostics = true;
769 else if (S == "never")
770 errorHandler().ColorDiagnostics = false;
771 else if (S != "auto")
772 error("unknown option: --color-diagnostics=" + S);
776 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &Args) {
777 if (auto *Arg = Args.getLastArg(OPT_rsp_quoting)) {
778 StringRef S = Arg->getValue();
779 if (S != "windows" && S != "posix")
780 error("invalid response file quoting: " + S);
782 return cl::TokenizeWindowsCommandLine;
783 return cl::TokenizeGNUCommandLine;
785 // The COFF linker always defaults to Windows quoting.
786 return cl::TokenizeWindowsCommandLine;
789 // Parses a given list of options.
790 opt::InputArgList ArgParser::parse(ArrayRef<const char *> Argv) {
791 // Make InputArgList from string vectors.
792 unsigned MissingIndex;
793 unsigned MissingCount;
795 // We need to get the quoting style for response files before parsing all
796 // options so we parse here before and ignore all the options but
798 opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
800 // Expand response files (arguments in the form of @<filename>)
801 // and then parse the argument again.
802 SmallVector<const char *, 256> ExpandedArgv(Argv.data(), Argv.data() + Argv.size());
803 cl::ExpandResponseFiles(Saver, getQuotingStyle(Args), ExpandedArgv);
804 Args = Table.ParseArgs(makeArrayRef(ExpandedArgv).drop_front(), MissingIndex,
807 // Print the real command line if response files are expanded.
808 if (Args.hasArg(OPT_verbose) && Argv.size() != ExpandedArgv.size()) {
809 std::string Msg = "Command line:";
810 for (const char *S : ExpandedArgv)
811 Msg += " " + std::string(S);
815 // Save the command line after response file expansion so we can write it to
816 // the PDB if necessary.
817 Config->Argv = {ExpandedArgv.begin(), ExpandedArgv.end()};
819 // Handle /WX early since it converts missing argument warnings to errors.
820 errorHandler().FatalWarnings = Args.hasFlag(OPT_WX, OPT_WX_no, false);
823 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
825 handleColorDiagnostics(Args);
827 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
828 warn("ignoring unknown argument: " + Arg->getSpelling());
830 if (Args.hasArg(OPT_lib))
831 warn("ignoring /lib since it's not the first argument");
836 // Tokenizes and parses a given string as command line in .drective section.
837 // /EXPORT options are processed in fastpath.
838 std::pair<opt::InputArgList, std::vector<StringRef>>
839 ArgParser::parseDirectives(StringRef S) {
840 std::vector<StringRef> Exports;
841 SmallVector<const char *, 16> Rest;
843 for (StringRef Tok : tokenize(S)) {
844 if (Tok.startswith_lower("/export:") || Tok.startswith_lower("-export:"))
845 Exports.push_back(Tok.substr(strlen("/export:")));
847 Rest.push_back(Tok.data());
850 // Make InputArgList from unparsed string vectors.
851 unsigned MissingIndex;
852 unsigned MissingCount;
854 opt::InputArgList Args = Table.ParseArgs(Rest, MissingIndex, MissingCount);
857 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
858 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
859 warn("ignoring unknown argument: " + Arg->getSpelling());
860 return {std::move(Args), std::move(Exports)};
863 // link.exe has an interesting feature. If LINK or _LINK_ environment
864 // variables exist, their contents are handled as command line strings.
865 // So you can pass extra arguments using them.
866 opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Argv) {
867 // Concatenate LINK env and command line arguments, and then parse them.
868 if (Optional<std::string> S = Process::GetEnv("LINK")) {
869 std::vector<const char *> V = tokenize(*S);
870 Argv.insert(std::next(Argv.begin()), V.begin(), V.end());
872 if (Optional<std::string> S = Process::GetEnv("_LINK_")) {
873 std::vector<const char *> V = tokenize(*S);
874 Argv.insert(std::next(Argv.begin()), V.begin(), V.end());
879 std::vector<const char *> ArgParser::tokenize(StringRef S) {
880 SmallVector<const char *, 16> Tokens;
881 cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
882 return std::vector<const char *>(Tokens.begin(), Tokens.end());
885 void printHelp(const char *Argv0) {
886 COFFOptTable().PrintHelp(outs(), Argv0, "LLVM Linker", false);