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