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