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