]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/COFF/DriverUtils.cpp
Merge ^/head r316992 through r317215.
[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("private")) {
483       E.Private = true;
484       continue;
485     }
486     if (Tok.startswith("@")) {
487       int32_t Ord;
488       if (Tok.substr(1).getAsInteger(0, Ord))
489         goto err;
490       if (Ord <= 0 || 65535 < Ord)
491         goto err;
492       E.Ordinal = Ord;
493       continue;
494     }
495     goto err;
496   }
497   return E;
498
499 err:
500   fatal("invalid /export: " + Arg);
501 }
502
503 static StringRef undecorate(StringRef Sym) {
504   if (Config->Machine != I386)
505     return Sym;
506   return Sym.startswith("_") ? Sym.substr(1) : Sym;
507 }
508
509 // Performs error checking on all /export arguments.
510 // It also sets ordinals.
511 void fixupExports() {
512   // Symbol ordinals must be unique.
513   std::set<uint16_t> Ords;
514   for (Export &E : Config->Exports) {
515     if (E.Ordinal == 0)
516       continue;
517     if (!Ords.insert(E.Ordinal).second)
518       fatal("duplicate export ordinal: " + E.Name);
519   }
520
521   for (Export &E : Config->Exports) {
522     SymbolBody *Sym = E.Sym;
523     if (!E.ForwardTo.empty()) {
524       E.SymbolName = E.Name;
525     } else {
526       if (auto *U = dyn_cast<Undefined>(Sym))
527         if (U->WeakAlias)
528           Sym = U->WeakAlias;
529       E.SymbolName = Sym->getName();
530     }
531   }
532
533   for (Export &E : Config->Exports) {
534     if (!E.ForwardTo.empty()) {
535       E.ExportName = undecorate(E.Name);
536     } else {
537       E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
538     }
539   }
540
541   // Uniquefy by name.
542   std::map<StringRef, Export *> Map;
543   std::vector<Export> V;
544   for (Export &E : Config->Exports) {
545     auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
546     bool Inserted = Pair.second;
547     if (Inserted) {
548       V.push_back(E);
549       continue;
550     }
551     Export *Existing = Pair.first->second;
552     if (E == *Existing || E.Name != Existing->Name)
553       continue;
554     warn("duplicate /export option: " + E.Name);
555   }
556   Config->Exports = std::move(V);
557
558   // Sort by name.
559   std::sort(Config->Exports.begin(), Config->Exports.end(),
560             [](const Export &A, const Export &B) {
561               return A.ExportName < B.ExportName;
562             });
563 }
564
565 void assignExportOrdinals() {
566   // Assign unique ordinals if default (= 0).
567   uint16_t Max = 0;
568   for (Export &E : Config->Exports)
569     Max = std::max(Max, E.Ordinal);
570   for (Export &E : Config->Exports)
571     if (E.Ordinal == 0)
572       E.Ordinal = ++Max;
573 }
574
575 // Parses a string in the form of "key=value" and check
576 // if value matches previous values for the same key.
577 void checkFailIfMismatch(StringRef Arg) {
578   StringRef K, V;
579   std::tie(K, V) = Arg.split('=');
580   if (K.empty() || V.empty())
581     fatal("/failifmismatch: invalid argument: " + Arg);
582   StringRef Existing = Config->MustMatch[K];
583   if (!Existing.empty() && V != Existing)
584     fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
585           " for key " + K);
586   Config->MustMatch[K] = V;
587 }
588
589 // Convert Windows resource files (.res files) to a .obj file
590 // using cvtres.exe.
591 std::unique_ptr<MemoryBuffer>
592 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
593   // Create an output file path.
594   TemporaryFile File("resource-file", "obj");
595
596   // Execute cvtres.exe.
597   Executor E("cvtres.exe");
598   E.add("/machine:" + machineToStr(Config->Machine));
599   E.add("/readonly");
600   E.add("/nologo");
601   E.add("/out:" + Twine(File.Path));
602
603   // We must create new files because the memory buffers we have may have no
604   // underlying file still existing on the disk.
605   // It happens if it was created from a TemporaryFile, which usually delete
606   // the file just after creating the MemoryBuffer.
607   std::vector<TemporaryFile> ResFiles;
608   ResFiles.reserve(MBs.size());
609   for (MemoryBufferRef MB : MBs) {
610     // We store the temporary file in a vector to avoid deletion
611     // before running cvtres
612     ResFiles.emplace_back("resource-file", "res");
613     TemporaryFile& ResFile = ResFiles.back();
614     // Write the content of the resource in a temporary file
615     std::error_code EC;
616     raw_fd_ostream OS(ResFile.Path, EC, sys::fs::F_None);
617     if (EC)
618       fatal(EC, "failed to open " + ResFile.Path);
619     OS << MB.getBuffer();
620     OS.close();
621
622     E.add(ResFile.Path);
623   }
624
625   E.run();
626   return File.getMemoryBuffer();
627 }
628
629 // Run MSVC link.exe for given in-memory object files.
630 // Command line options are copied from those given to LLD.
631 // This is for the /msvclto option.
632 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
633   // Write the in-memory object files to disk.
634   std::vector<TemporaryFile> Temps;
635   for (StringRef S : Objects) {
636     Temps.emplace_back("lto", "obj", S);
637     Rsp += quote(Temps.back().Path) + " ";
638   }
639
640   log("link.exe " + Rsp);
641
642   // Run MSVC link.exe.
643   Temps.emplace_back("lto", "rsp", Rsp);
644   Executor E("link.exe");
645   E.add(Twine("@" + Temps.back().Path));
646   E.run();
647 }
648
649 // Create OptTable
650
651 // Create prefix string literals used in Options.td
652 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
653 #include "Options.inc"
654 #undef PREFIX
655
656 // Create table mapping all options defined in Options.td
657 static const llvm::opt::OptTable::Info infoTable[] = {
658 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10)    \
659   {                                                                    \
660     X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
661     OPT_##GROUP, OPT_##ALIAS, X6                                       \
662   },
663 #include "Options.inc"
664 #undef OPTION
665 };
666
667 class COFFOptTable : public llvm::opt::OptTable {
668 public:
669   COFFOptTable() : OptTable(infoTable, true) {}
670 };
671
672 // Parses a given list of options.
673 opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
674   // First, replace respnose files (@<file>-style options).
675   std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
676
677   // Make InputArgList from string vectors.
678   COFFOptTable Table;
679   unsigned MissingIndex;
680   unsigned MissingCount;
681   opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
682
683   // Print the real command line if response files are expanded.
684   if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
685     std::string Msg = "Command line:";
686     for (const char *S : Argv)
687       Msg += " " + std::string(S);
688     message(Msg);
689   }
690
691   if (MissingCount)
692     fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
693   for (auto *Arg : Args.filtered(OPT_UNKNOWN))
694     warn("ignoring unknown argument: " + Arg->getSpelling());
695   return Args;
696 }
697
698 // link.exe has an interesting feature. If LINK environment exists,
699 // its contents are handled as a command line string. So you can pass
700 // extra arguments using the environment variable.
701 opt::InputArgList ArgParser::parseLINK(ArrayRef<const char *> Args) {
702   // Concatenate LINK env and command line arguments, and then parse them.
703   Optional<std::string> Env = Process::GetEnv("LINK");
704   if (!Env)
705     return parse(Args);
706   std::vector<const char *> V = tokenize(*Env);
707   V.insert(V.end(), Args.begin(), Args.end());
708   return parse(V);
709 }
710
711 std::vector<const char *> ArgParser::tokenize(StringRef S) {
712   SmallVector<const char *, 16> Tokens;
713   cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
714   return std::vector<const char *>(Tokens.begin(), Tokens.end());
715 }
716
717 // Creates a new command line by replacing options starting with '@'
718 // character. '@<filename>' is replaced by the file's contents.
719 std::vector<const char *>
720 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
721   SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
722   ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
723   return std::vector<const char *>(Tokens.begin(), Tokens.end());
724 }
725
726 void printHelp(const char *Argv0) {
727   COFFOptTable Table;
728   Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);
729 }
730
731 } // namespace coff
732 } // namespace lld