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