]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/DriverUtils.cpp
Merge llvm, clang, lld, lldb, compiler-rt and libc++ r301441, and update
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / COFF / DriverUtils.cpp
1 //===- DriverUtils.cpp ----------------------------------------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
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.
13 //
14 //===----------------------------------------------------------------------===//
15
16 #include "Config.h"
17 #include "Driver.h"
18 #include "Error.h"
19 #include "Memory.h"
20 #include "Symbols.h"
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/Object/COFF.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileUtilities.h"
29 #include "llvm/Support/Process.h"
30 #include "llvm/Support/Program.h"
31 #include "llvm/Support/raw_ostream.h"
32 #include <memory>
33
34 using namespace llvm::COFF;
35 using namespace llvm;
36 using llvm::cl::ExpandResponseFiles;
37 using llvm::cl::TokenizeWindowsCommandLine;
38 using llvm::sys::Process;
39
40 namespace lld {
41 namespace coff {
42 namespace {
43
44 class Executor {
45 public:
46   explicit Executor(StringRef S) : Saver(Alloc), Prog(Saver.save(S)) {}
47   void add(StringRef S) { Args.push_back(Saver.save(S)); }
48   void add(std::string &S) { Args.push_back(Saver.save(S)); }
49   void add(Twine S) { Args.push_back(Saver.save(S)); }
50   void add(const char *S) { Args.push_back(Saver.save(S)); }
51
52   void run() {
53     ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
54     if (auto EC = ExeOrErr.getError())
55       fatal(EC, "unable to find " + Prog + " in PATH: ");
56     StringRef Exe = Saver.save(*ExeOrErr);
57     Args.insert(Args.begin(), Exe);
58
59     std::vector<const char *> Vec;
60     for (StringRef S : Args)
61       Vec.push_back(S.data());
62     Vec.push_back(nullptr);
63
64     if (sys::ExecuteAndWait(Args[0], Vec.data()) != 0)
65       fatal("ExecuteAndWait failed: " +
66             llvm::join(Args.begin(), Args.end(), " "));
67   }
68
69 private:
70   BumpPtrAllocator Alloc;
71   StringSaver Saver;
72   StringRef Prog;
73   std::vector<StringRef> Args;
74 };
75
76 } // anonymous namespace
77
78 // Returns /machine's value.
79 MachineTypes getMachineType(StringRef S) {
80   MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
81                         .Cases("x64", "amd64", AMD64)
82                         .Cases("x86", "i386", I386)
83                         .Case("arm", ARMNT)
84                         .Default(IMAGE_FILE_MACHINE_UNKNOWN);
85   if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
86     return MT;
87   fatal("unknown /machine argument: " + S);
88 }
89
90 StringRef machineToStr(MachineTypes MT) {
91   switch (MT) {
92   case ARMNT:
93     return "arm";
94   case AMD64:
95     return "x64";
96   case I386:
97     return "x86";
98   default:
99     llvm_unreachable("unknown machine type");
100   }
101 }
102
103 // Parses a string in the form of "<integer>[,<integer>]".
104 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
105   StringRef S1, S2;
106   std::tie(S1, S2) = Arg.split(',');
107   if (S1.getAsInteger(0, *Addr))
108     fatal("invalid number: " + S1);
109   if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
110     fatal("invalid number: " + S2);
111 }
112
113 // Parses a string in the form of "<integer>[.<integer>]".
114 // If second number is not present, Minor is set to 0.
115 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
116   StringRef S1, S2;
117   std::tie(S1, S2) = Arg.split('.');
118   if (S1.getAsInteger(0, *Major))
119     fatal("invalid number: " + S1);
120   *Minor = 0;
121   if (!S2.empty() && S2.getAsInteger(0, *Minor))
122     fatal("invalid number: " + S2);
123 }
124
125 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
126 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
127                     uint32_t *Minor) {
128   StringRef SysStr, Ver;
129   std::tie(SysStr, Ver) = Arg.split(',');
130   *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
131     .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
132     .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
133     .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
134     .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
135     .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
136     .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
137     .Case("native", IMAGE_SUBSYSTEM_NATIVE)
138     .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
139     .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
140     .Default(IMAGE_SUBSYSTEM_UNKNOWN);
141   if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
142     fatal("unknown subsystem: " + SysStr);
143   if (!Ver.empty())
144     parseVersion(Ver, Major, Minor);
145 }
146
147 // Parse a string of the form of "<from>=<to>".
148 // Results are directly written to Config.
149 void parseAlternateName(StringRef S) {
150   StringRef From, To;
151   std::tie(From, To) = S.split('=');
152   if (From.empty() || To.empty())
153     fatal("/alternatename: invalid argument: " + S);
154   auto It = Config->AlternateNames.find(From);
155   if (It != Config->AlternateNames.end() && It->second != To)
156     fatal("/alternatename: conflicts: " + S);
157   Config->AlternateNames.insert(It, std::make_pair(From, To));
158 }
159
160 // Parse a string of the form of "<from>=<to>".
161 // Results are directly written to Config.
162 void parseMerge(StringRef S) {
163   StringRef From, To;
164   std::tie(From, To) = S.split('=');
165   if (From.empty() || To.empty())
166     fatal("/merge: invalid argument: " + S);
167   auto Pair = Config->Merge.insert(std::make_pair(From, To));
168   bool Inserted = Pair.second;
169   if (!Inserted) {
170     StringRef Existing = Pair.first->second;
171     if (Existing != To)
172       warn(S + ": already merged into " + Existing);
173   }
174 }
175
176 static uint32_t parseSectionAttributes(StringRef S) {
177   uint32_t Ret = 0;
178   for (char C : S.lower()) {
179     switch (C) {
180     case 'd':
181       Ret |= IMAGE_SCN_MEM_DISCARDABLE;
182       break;
183     case 'e':
184       Ret |= IMAGE_SCN_MEM_EXECUTE;
185       break;
186     case 'k':
187       Ret |= IMAGE_SCN_MEM_NOT_CACHED;
188       break;
189     case 'p':
190       Ret |= IMAGE_SCN_MEM_NOT_PAGED;
191       break;
192     case 'r':
193       Ret |= IMAGE_SCN_MEM_READ;
194       break;
195     case 's':
196       Ret |= IMAGE_SCN_MEM_SHARED;
197       break;
198     case 'w':
199       Ret |= IMAGE_SCN_MEM_WRITE;
200       break;
201     default:
202       fatal("/section: invalid argument: " + S);
203     }
204   }
205   return Ret;
206 }
207
208 // Parses /section option argument.
209 void parseSection(StringRef S) {
210   StringRef Name, Attrs;
211   std::tie(Name, Attrs) = S.split(',');
212   if (Name.empty() || Attrs.empty())
213     fatal("/section: invalid argument: " + S);
214   Config->Section[Name] = parseSectionAttributes(Attrs);
215 }
216
217 // Parses a string in the form of "EMBED[,=<integer>]|NO".
218 // Results are directly written to Config.
219 void parseManifest(StringRef Arg) {
220   if (Arg.equals_lower("no")) {
221     Config->Manifest = Configuration::No;
222     return;
223   }
224   if (!Arg.startswith_lower("embed"))
225     fatal("invalid option " + Arg);
226   Config->Manifest = Configuration::Embed;
227   Arg = Arg.substr(strlen("embed"));
228   if (Arg.empty())
229     return;
230   if (!Arg.startswith_lower(",id="))
231     fatal("invalid option " + Arg);
232   Arg = Arg.substr(strlen(",id="));
233   if (Arg.getAsInteger(0, Config->ManifestID))
234     fatal("invalid option " + Arg);
235 }
236
237 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
238 // Results are directly written to Config.
239 void parseManifestUAC(StringRef Arg) {
240   if (Arg.equals_lower("no")) {
241     Config->ManifestUAC = false;
242     return;
243   }
244   for (;;) {
245     Arg = Arg.ltrim();
246     if (Arg.empty())
247       return;
248     if (Arg.startswith_lower("level=")) {
249       Arg = Arg.substr(strlen("level="));
250       std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
251       continue;
252     }
253     if (Arg.startswith_lower("uiaccess=")) {
254       Arg = Arg.substr(strlen("uiaccess="));
255       std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
256       continue;
257     }
258     fatal("invalid option " + Arg);
259   }
260 }
261
262 // Quote each line with "". Existing double-quote is converted
263 // to two double-quotes.
264 static void quoteAndPrint(raw_ostream &Out, StringRef S) {
265   while (!S.empty()) {
266     StringRef Line;
267     std::tie(Line, S) = S.split("\n");
268     if (Line.empty())
269       continue;
270     Out << '\"';
271     for (int I = 0, E = Line.size(); I != E; ++I) {
272       if (Line[I] == '\"') {
273         Out << "\"\"";
274       } else {
275         Out << Line[I];
276       }
277     }
278     Out << "\"\n";
279   }
280 }
281
282 // An RAII temporary file class that automatically removes a temporary file.
283 namespace {
284 class TemporaryFile {
285 public:
286   TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") {
287     SmallString<128> S;
288     if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
289       fatal(EC, "cannot create a temporary file");
290     Path = S.str();
291
292     if (!Contents.empty()) {
293       std::error_code EC;
294       raw_fd_ostream OS(Path, EC, sys::fs::F_None);
295       if (EC)
296         fatal(EC, "failed to open " + Path);
297       OS << Contents;
298     }
299   }
300
301   TemporaryFile(TemporaryFile &&Obj) {
302     std::swap(Path, Obj.Path);
303   }
304
305   ~TemporaryFile() {
306     if (Path.empty())
307       return;
308     if (sys::fs::remove(Path))
309       fatal("failed to remove " + Path);
310   }
311
312   // Returns a memory buffer of this temporary file.
313   // Note that this function does not leave the file open,
314   // so it is safe to remove the file immediately after this function
315   // is called (you cannot remove an opened file on Windows.)
316   std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
317     // IsVolatileSize=true forces MemoryBuffer to not use mmap().
318     return check(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
319                                        /*RequiresNullTerminator=*/false,
320                                        /*IsVolatileSize=*/true),
321                  "could not open " + Path);
322   }
323
324   std::string Path;
325 };
326 }
327
328 // Create the default manifest file as a temporary file.
329 TemporaryFile createDefaultXml() {
330   // Create a temporary file.
331   TemporaryFile File("defaultxml", "manifest");
332
333   // Open the temporary file for writing.
334   std::error_code EC;
335   raw_fd_ostream OS(File.Path, EC, sys::fs::F_Text);
336   if (EC)
337     fatal(EC, "failed to open " + File.Path);
338
339   // Emit the XML. Note that we do *not* verify that the XML attributes are
340   // syntactically correct. This is intentional for link.exe compatibility.
341   OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
342      << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
343      << "          manifestVersion=\"1.0\">\n";
344   if (Config->ManifestUAC) {
345     OS << "  <trustInfo>\n"
346        << "    <security>\n"
347        << "      <requestedPrivileges>\n"
348        << "         <requestedExecutionLevel level=" << Config->ManifestLevel
349        << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
350        << "      </requestedPrivileges>\n"
351        << "    </security>\n"
352        << "  </trustInfo>\n";
353     if (!Config->ManifestDependency.empty()) {
354       OS << "  <dependency>\n"
355          << "    <dependentAssembly>\n"
356          << "      <assemblyIdentity " << Config->ManifestDependency << " />\n"
357          << "    </dependentAssembly>\n"
358          << "  </dependency>\n";
359     }
360   }
361   OS << "</assembly>\n";
362   OS.close();
363   return File;
364 }
365
366 static std::string readFile(StringRef Path) {
367   std::unique_ptr<MemoryBuffer> MB =
368       check(MemoryBuffer::getFile(Path), "could not open " + Path);
369   return MB->getBuffer();
370 }
371
372 static std::string createManifestXml() {
373   // Create the default manifest file.
374   TemporaryFile File1 = createDefaultXml();
375   if (Config->ManifestInput.empty())
376     return readFile(File1.Path);
377
378   // If manifest files are supplied by the user using /MANIFESTINPUT
379   // option, we need to merge them with the default manifest.
380   TemporaryFile File2("user", "manifest");
381
382   Executor E("mt.exe");
383   E.add("/manifest");
384   E.add(File1.Path);
385   for (StringRef Filename : Config->ManifestInput) {
386     E.add("/manifest");
387     E.add(Filename);
388   }
389   E.add("/nologo");
390   E.add("/out:" + StringRef(File2.Path));
391   E.run();
392   return readFile(File2.Path);
393 }
394
395 // Create a resource file containing a manifest XML.
396 std::unique_ptr<MemoryBuffer> createManifestRes() {
397   // Create a temporary file for the resource script file.
398   TemporaryFile RCFile("manifest", "rc");
399
400   // Open the temporary file for writing.
401   std::error_code EC;
402   raw_fd_ostream Out(RCFile.Path, EC, sys::fs::F_Text);
403   if (EC)
404     fatal(EC, "failed to open " + RCFile.Path);
405
406   // Write resource script to the RC file.
407   Out << "#define LANG_ENGLISH 9\n"
408       << "#define SUBLANG_DEFAULT 1\n"
409       << "#define APP_MANIFEST " << Config->ManifestID << "\n"
410       << "#define RT_MANIFEST 24\n"
411       << "LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT\n"
412       << "APP_MANIFEST RT_MANIFEST {\n";
413   quoteAndPrint(Out, createManifestXml());
414   Out << "}\n";
415   Out.close();
416
417   // Create output resource file.
418   TemporaryFile ResFile("output-resource", "res");
419
420   Executor E("rc.exe");
421   E.add("/fo");
422   E.add(ResFile.Path);
423   E.add("/nologo");
424   E.add(RCFile.Path);
425   E.run();
426   return ResFile.getMemoryBuffer();
427 }
428
429 void createSideBySideManifest() {
430   std::string Path = Config->ManifestFile;
431   if (Path == "")
432     Path = Config->OutputFile + ".manifest";
433   std::error_code EC;
434   raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
435   if (EC)
436     fatal(EC, "failed to create manifest");
437   Out << createManifestXml();
438 }
439
440 // Parse a string in the form of
441 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
442 // or "<name>=<dllname>.<name>".
443 // Used for parsing /export arguments.
444 Export parseExport(StringRef Arg) {
445   Export E;
446   StringRef Rest;
447   std::tie(E.Name, Rest) = Arg.split(",");
448   if (E.Name.empty())
449     goto err;
450
451   if (E.Name.find('=') != StringRef::npos) {
452     StringRef X, Y;
453     std::tie(X, Y) = E.Name.split("=");
454
455     // If "<name>=<dllname>.<name>".
456     if (Y.find(".") != StringRef::npos) {
457       E.Name = X;
458       E.ForwardTo = Y;
459       return E;
460     }
461
462     E.ExtName = X;
463     E.Name = Y;
464     if (E.Name.empty())
465       goto err;
466   }
467
468   // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
469   while (!Rest.empty()) {
470     StringRef Tok;
471     std::tie(Tok, Rest) = Rest.split(",");
472     if (Tok.equals_lower("noname")) {
473       if (E.Ordinal == 0)
474         goto err;
475       E.Noname = true;
476       continue;
477     }
478     if (Tok.equals_lower("data")) {
479       E.Data = true;
480       continue;
481     }
482     if (Tok.equals_lower("constant")) {
483       E.Constant = true;
484       continue;
485     }
486     if (Tok.equals_lower("private")) {
487       E.Private = true;
488       continue;
489     }
490     if (Tok.startswith("@")) {
491       int32_t Ord;
492       if (Tok.substr(1).getAsInteger(0, Ord))
493         goto err;
494       if (Ord <= 0 || 65535 < Ord)
495         goto err;
496       E.Ordinal = Ord;
497       continue;
498     }
499     goto err;
500   }
501   return E;
502
503 err:
504   fatal("invalid /export: " + Arg);
505 }
506
507 static StringRef undecorate(StringRef Sym) {
508   if (Config->Machine != I386)
509     return Sym;
510   return Sym.startswith("_") ? Sym.substr(1) : Sym;
511 }
512
513 // Performs error checking on all /export arguments.
514 // It also sets ordinals.
515 void fixupExports() {
516   // Symbol ordinals must be unique.
517   std::set<uint16_t> Ords;
518   for (Export &E : Config->Exports) {
519     if (E.Ordinal == 0)
520       continue;
521     if (!Ords.insert(E.Ordinal).second)
522       fatal("duplicate export ordinal: " + E.Name);
523   }
524
525   for (Export &E : Config->Exports) {
526     SymbolBody *Sym = E.Sym;
527     if (!E.ForwardTo.empty()) {
528       E.SymbolName = E.Name;
529     } else {
530       if (auto *U = dyn_cast<Undefined>(Sym))
531         if (U->WeakAlias)
532           Sym = U->WeakAlias;
533       E.SymbolName = Sym->getName();
534     }
535   }
536
537   for (Export &E : Config->Exports) {
538     if (!E.ForwardTo.empty()) {
539       E.ExportName = undecorate(E.Name);
540     } else {
541       E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
542     }
543   }
544
545   // Uniquefy by name.
546   std::map<StringRef, Export *> Map;
547   std::vector<Export> V;
548   for (Export &E : Config->Exports) {
549     auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
550     bool Inserted = Pair.second;
551     if (Inserted) {
552       V.push_back(E);
553       continue;
554     }
555     Export *Existing = Pair.first->second;
556     if (E == *Existing || E.Name != Existing->Name)
557       continue;
558     warn("duplicate /export option: " + E.Name);
559   }
560   Config->Exports = std::move(V);
561
562   // Sort by name.
563   std::sort(Config->Exports.begin(), Config->Exports.end(),
564             [](const Export &A, const Export &B) {
565               return A.ExportName < B.ExportName;
566             });
567 }
568
569 void assignExportOrdinals() {
570   // Assign unique ordinals if default (= 0).
571   uint16_t Max = 0;
572   for (Export &E : Config->Exports)
573     Max = std::max(Max, E.Ordinal);
574   for (Export &E : Config->Exports)
575     if (E.Ordinal == 0)
576       E.Ordinal = ++Max;
577 }
578
579 // Parses a string in the form of "key=value" and check
580 // if value matches previous values for the same key.
581 void checkFailIfMismatch(StringRef Arg) {
582   StringRef K, V;
583   std::tie(K, V) = Arg.split('=');
584   if (K.empty() || V.empty())
585     fatal("/failifmismatch: invalid argument: " + Arg);
586   StringRef Existing = Config->MustMatch[K];
587   if (!Existing.empty() && V != Existing)
588     fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
589           " for key " + K);
590   Config->MustMatch[K] = V;
591 }
592
593 // Convert Windows resource files (.res files) to a .obj file
594 // using cvtres.exe.
595 std::unique_ptr<MemoryBuffer>
596 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
597   // Create an output file path.
598   TemporaryFile File("resource-file", "obj");
599
600   // Execute cvtres.exe.
601   Executor E("cvtres.exe");
602   E.add("/machine:" + machineToStr(Config->Machine));
603   E.add("/readonly");
604   E.add("/nologo");
605   E.add("/out:" + Twine(File.Path));
606
607   // We must create new files because the memory buffers we have may have no
608   // underlying file still existing on the disk.
609   // It happens if it was created from a TemporaryFile, which usually delete
610   // the file just after creating the MemoryBuffer.
611   std::vector<TemporaryFile> ResFiles;
612   ResFiles.reserve(MBs.size());
613   for (MemoryBufferRef MB : MBs) {
614     // We store the temporary file in a vector to avoid deletion
615     // before running cvtres
616     ResFiles.emplace_back("resource-file", "res");
617     TemporaryFile& ResFile = ResFiles.back();
618     // Write the content of the resource in a temporary file
619     std::error_code EC;
620     raw_fd_ostream OS(ResFile.Path, EC, sys::fs::F_None);
621     if (EC)
622       fatal(EC, "failed to open " + ResFile.Path);
623     OS << MB.getBuffer();
624     OS.close();
625
626     E.add(ResFile.Path);
627   }
628
629   E.run();
630   return File.getMemoryBuffer();
631 }
632
633 // Run MSVC link.exe for given in-memory object files.
634 // Command line options are copied from those given to LLD.
635 // This is for the /msvclto option.
636 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
637   // Write the in-memory object files to disk.
638   std::vector<TemporaryFile> Temps;
639   for (StringRef S : Objects) {
640     Temps.emplace_back("lto", "obj", S);
641     Rsp += quote(Temps.back().Path) + "\n";
642   }
643
644   log("link.exe " + Rsp);
645
646   // Run MSVC link.exe.
647   Temps.emplace_back("lto", "rsp", Rsp);
648   Executor E("link.exe");
649   E.add(Twine("@" + Temps.back().Path));
650   E.run();
651 }
652
653 // Create OptTable
654
655 // Create prefix string literals used in Options.td
656 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
657 #include "Options.inc"
658 #undef PREFIX
659
660 // Create table mapping all options defined in Options.td
661 static const llvm::opt::OptTable::Info infoTable[] = {
662 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)    \
663   {                                                                    \
664     X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
665     OPT_##GROUP, OPT_##ALIAS, X6                                       \
666   },
667 #include "Options.inc"
668 #undef OPTION
669 };
670
671 class COFFOptTable : public llvm::opt::OptTable {
672 public:
673   COFFOptTable() : OptTable(infoTable, true) {}
674 };
675
676 // Parses a given list of options.
677 opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
678   // First, replace respnose files (@<file>-style options).
679   std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
680
681   // Make InputArgList from string vectors.
682   COFFOptTable Table;
683   unsigned MissingIndex;
684   unsigned MissingCount;
685   opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
686
687   // Print the real command line if response files are expanded.
688   if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
689     std::string Msg = "Command line:";
690     for (const char *S : Argv)
691       Msg += " " + std::string(S);
692     message(Msg);
693   }
694
695   if (MissingCount)
696     fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
697   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
698     warn("ignoring unknown argument: " + Arg->getSpelling());
699   return Args;
700 }
701
702 // link.exe has an interesting feature. If LINK or _LINK_ environment
703 // variables exist, their contents are handled as command line strings.
704 // So you can pass extra arguments using them.
705 opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Args) {
706   // Concatenate LINK env and command line arguments, and then parse them.
707   if (Optional<std::string> S = Process::GetEnv("LINK")) {
708     std::vector<const char *> V = tokenize(*S);
709     Args.insert(Args.begin(), V.begin(), V.end());
710   }
711   if (Optional<std::string> S = Process::GetEnv("_LINK_")) {
712     std::vector<const char *> V = tokenize(*S);
713     Args.insert(Args.begin(), V.begin(), V.end());
714   }
715   return parse(Args);
716 }
717
718 std::vector<const char *> ArgParser::tokenize(StringRef S) {
719   SmallVector<const char *, 16> Tokens;
720   cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
721   return std::vector<const char *>(Tokens.begin(), Tokens.end());
722 }
723
724 // Creates a new command line by replacing options starting with '@'
725 // character. '@<filename>' is replaced by the file's contents.
726 std::vector<const char *>
727 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
728   SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
729   ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
730   return std::vector<const char *>(Tokens.begin(), Tokens.end());
731 }
732
733 void printHelp(const char *Argv0) {
734   COFFOptTable Table;
735   Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);
736 }
737
738 } // namespace coff
739 } // namespace lld