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