xref: /freebsd/contrib/llvm-project/lld/COFF/DriverUtils.cpp (revision 5e801ac66d24704442eba426ed13c3effb8a34e7)
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 <limits>
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     if (sys::ExecuteAndWait(args[0], args) != 0)
65       fatal("ExecuteAndWait failed: " +
66             llvm::join(args.begin(), args.end(), " "));
67   }
68 
69 private:
70   StringRef prog;
71   std::vector<StringRef> args;
72 };
73 
74 } // anonymous namespace
75 
76 // Parses a string in the form of "<integer>[,<integer>]".
77 void parseNumbers(StringRef arg, uint64_t *addr, uint64_t *size) {
78   StringRef s1, s2;
79   std::tie(s1, s2) = arg.split(',');
80   if (s1.getAsInteger(0, *addr))
81     fatal("invalid number: " + s1);
82   if (size && !s2.empty() && s2.getAsInteger(0, *size))
83     fatal("invalid number: " + s2);
84 }
85 
86 // Parses a string in the form of "<integer>[.<integer>]".
87 // If second number is not present, Minor is set to 0.
88 void parseVersion(StringRef arg, uint32_t *major, uint32_t *minor) {
89   StringRef s1, s2;
90   std::tie(s1, s2) = arg.split('.');
91   if (s1.getAsInteger(10, *major))
92     fatal("invalid number: " + s1);
93   *minor = 0;
94   if (!s2.empty() && s2.getAsInteger(10, *minor))
95     fatal("invalid number: " + s2);
96 }
97 
98 void parseGuard(StringRef fullArg) {
99   SmallVector<StringRef, 1> splitArgs;
100   fullArg.split(splitArgs, ",");
101   for (StringRef arg : splitArgs) {
102     if (arg.equals_insensitive("no"))
103       config->guardCF = GuardCFLevel::Off;
104     else if (arg.equals_insensitive("nolongjmp"))
105       config->guardCF &= ~GuardCFLevel::LongJmp;
106     else if (arg.equals_insensitive("noehcont"))
107       config->guardCF &= ~GuardCFLevel::EHCont;
108     else if (arg.equals_insensitive("cf"))
109       config->guardCF = GuardCFLevel::CF;
110     else if (arg.equals_insensitive("longjmp"))
111       config->guardCF |= GuardCFLevel::CF | GuardCFLevel::LongJmp;
112     else if (arg.equals_insensitive("ehcont"))
113       config->guardCF |= GuardCFLevel::CF | GuardCFLevel::EHCont;
114     else
115       fatal("invalid argument to /guard: " + arg);
116   }
117 }
118 
119 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
120 void parseSubsystem(StringRef arg, WindowsSubsystem *sys, uint32_t *major,
121                     uint32_t *minor, bool *gotVersion) {
122   StringRef sysStr, ver;
123   std::tie(sysStr, ver) = arg.split(',');
124   std::string sysStrLower = sysStr.lower();
125   *sys = StringSwitch<WindowsSubsystem>(sysStrLower)
126     .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
127     .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
128     .Case("default", IMAGE_SUBSYSTEM_UNKNOWN)
129     .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
130     .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
131     .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
132     .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
133     .Case("native", IMAGE_SUBSYSTEM_NATIVE)
134     .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
135     .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
136     .Default(IMAGE_SUBSYSTEM_UNKNOWN);
137   if (*sys == IMAGE_SUBSYSTEM_UNKNOWN && sysStrLower != "default")
138     fatal("unknown subsystem: " + sysStr);
139   if (!ver.empty())
140     parseVersion(ver, major, minor);
141   if (gotVersion)
142     *gotVersion = !ver.empty();
143 }
144 
145 // Parse a string of the form of "<from>=<to>".
146 // Results are directly written to Config.
147 void parseAlternateName(StringRef s) {
148   StringRef from, to;
149   std::tie(from, to) = s.split('=');
150   if (from.empty() || to.empty())
151     fatal("/alternatename: invalid argument: " + s);
152   auto it = config->alternateNames.find(from);
153   if (it != config->alternateNames.end() && it->second != to)
154     fatal("/alternatename: conflicts: " + s);
155   config->alternateNames.insert(it, std::make_pair(from, to));
156 }
157 
158 // Parse a string of the form of "<from>=<to>".
159 // Results are directly written to Config.
160 void parseMerge(StringRef s) {
161   StringRef from, to;
162   std::tie(from, to) = s.split('=');
163   if (from.empty() || to.empty())
164     fatal("/merge: invalid argument: " + s);
165   if (from == ".rsrc" || to == ".rsrc")
166     fatal("/merge: cannot merge '.rsrc' with any section");
167   if (from == ".reloc" || to == ".reloc")
168     fatal("/merge: cannot merge '.reloc' with any section");
169   auto pair = config->merge.insert(std::make_pair(from, to));
170   bool inserted = pair.second;
171   if (!inserted) {
172     StringRef existing = pair.first->second;
173     if (existing != to)
174       warn(s + ": already merged into " + existing);
175   }
176 }
177 
178 void parsePDBPageSize(StringRef s) {
179   int v;
180   if (s.getAsInteger(0, v)) {
181     error("/pdbpagesize: invalid argument: " + s);
182     return;
183   }
184   if (v != 4096 && v != 8192 && v != 16384 && v != 32768) {
185     error("/pdbpagesize: invalid argument: " + s);
186     return;
187   }
188 
189   // FIXME: Remove this once other page sizes work.
190   if (v != 4096) {
191     warn("/pdbpagesize: page sizes != 4096 not yet implemented, ignoring flag");
192     v = 4096;
193   }
194 
195   config->pdbPageSize = v;
196 }
197 
198 static uint32_t parseSectionAttributes(StringRef s) {
199   uint32_t ret = 0;
200   for (char c : s.lower()) {
201     switch (c) {
202     case 'd':
203       ret |= IMAGE_SCN_MEM_DISCARDABLE;
204       break;
205     case 'e':
206       ret |= IMAGE_SCN_MEM_EXECUTE;
207       break;
208     case 'k':
209       ret |= IMAGE_SCN_MEM_NOT_CACHED;
210       break;
211     case 'p':
212       ret |= IMAGE_SCN_MEM_NOT_PAGED;
213       break;
214     case 'r':
215       ret |= IMAGE_SCN_MEM_READ;
216       break;
217     case 's':
218       ret |= IMAGE_SCN_MEM_SHARED;
219       break;
220     case 'w':
221       ret |= IMAGE_SCN_MEM_WRITE;
222       break;
223     default:
224       fatal("/section: invalid argument: " + s);
225     }
226   }
227   return ret;
228 }
229 
230 // Parses /section option argument.
231 void parseSection(StringRef s) {
232   StringRef name, attrs;
233   std::tie(name, attrs) = s.split(',');
234   if (name.empty() || attrs.empty())
235     fatal("/section: invalid argument: " + s);
236   config->section[name] = parseSectionAttributes(attrs);
237 }
238 
239 // Parses /aligncomm option argument.
240 void parseAligncomm(StringRef s) {
241   StringRef name, align;
242   std::tie(name, align) = s.split(',');
243   if (name.empty() || align.empty()) {
244     error("/aligncomm: invalid argument: " + s);
245     return;
246   }
247   int v;
248   if (align.getAsInteger(0, v)) {
249     error("/aligncomm: invalid argument: " + s);
250     return;
251   }
252   config->alignComm[std::string(name)] =
253       std::max(config->alignComm[std::string(name)], 1 << v);
254 }
255 
256 // Parses /functionpadmin option argument.
257 void parseFunctionPadMin(llvm::opt::Arg *a, llvm::COFF::MachineTypes machine) {
258   StringRef arg = a->getNumValues() ? a->getValue() : "";
259   if (!arg.empty()) {
260     // Optional padding in bytes is given.
261     if (arg.getAsInteger(0, config->functionPadMin))
262       error("/functionpadmin: invalid argument: " + arg);
263     return;
264   }
265   // No optional argument given.
266   // Set default padding based on machine, similar to link.exe.
267   // There is no default padding for ARM platforms.
268   if (machine == I386) {
269     config->functionPadMin = 5;
270   } else if (machine == AMD64) {
271     config->functionPadMin = 6;
272   } else {
273     error("/functionpadmin: invalid argument for this machine: " + arg);
274   }
275 }
276 
277 // Parses a string in the form of "EMBED[,=<integer>]|NO".
278 // Results are directly written to Config.
279 void parseManifest(StringRef arg) {
280   if (arg.equals_insensitive("no")) {
281     config->manifest = Configuration::No;
282     return;
283   }
284   if (!arg.startswith_insensitive("embed"))
285     fatal("invalid option " + arg);
286   config->manifest = Configuration::Embed;
287   arg = arg.substr(strlen("embed"));
288   if (arg.empty())
289     return;
290   if (!arg.startswith_insensitive(",id="))
291     fatal("invalid option " + arg);
292   arg = arg.substr(strlen(",id="));
293   if (arg.getAsInteger(0, config->manifestID))
294     fatal("invalid option " + arg);
295 }
296 
297 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
298 // Results are directly written to Config.
299 void parseManifestUAC(StringRef arg) {
300   if (arg.equals_insensitive("no")) {
301     config->manifestUAC = false;
302     return;
303   }
304   for (;;) {
305     arg = arg.ltrim();
306     if (arg.empty())
307       return;
308     if (arg.startswith_insensitive("level=")) {
309       arg = arg.substr(strlen("level="));
310       std::tie(config->manifestLevel, arg) = arg.split(" ");
311       continue;
312     }
313     if (arg.startswith_insensitive("uiaccess=")) {
314       arg = arg.substr(strlen("uiaccess="));
315       std::tie(config->manifestUIAccess, arg) = arg.split(" ");
316       continue;
317     }
318     fatal("invalid option " + arg);
319   }
320 }
321 
322 // Parses a string in the form of "cd|net[,(cd|net)]*"
323 // Results are directly written to Config.
324 void parseSwaprun(StringRef arg) {
325   do {
326     StringRef swaprun, newArg;
327     std::tie(swaprun, newArg) = arg.split(',');
328     if (swaprun.equals_insensitive("cd"))
329       config->swaprunCD = true;
330     else if (swaprun.equals_insensitive("net"))
331       config->swaprunNet = true;
332     else if (swaprun.empty())
333       error("/swaprun: missing argument");
334     else
335       error("/swaprun: invalid argument: " + swaprun);
336     // To catch trailing commas, e.g. `/spawrun:cd,`
337     if (newArg.empty() && arg.endswith(","))
338       error("/swaprun: missing argument");
339     arg = newArg;
340   } while (!arg.empty());
341 }
342 
343 // An RAII temporary file class that automatically removes a temporary file.
344 namespace {
345 class TemporaryFile {
346 public:
347   TemporaryFile(StringRef prefix, StringRef extn, StringRef contents = "") {
348     SmallString<128> s;
349     if (auto ec = sys::fs::createTemporaryFile("lld-" + prefix, extn, s))
350       fatal("cannot create a temporary file: " + ec.message());
351     path = std::string(s.str());
352 
353     if (!contents.empty()) {
354       std::error_code ec;
355       raw_fd_ostream os(path, ec, sys::fs::OF_None);
356       if (ec)
357         fatal("failed to open " + path + ": " + ec.message());
358       os << contents;
359     }
360   }
361 
362   TemporaryFile(TemporaryFile &&obj) {
363     std::swap(path, obj.path);
364   }
365 
366   ~TemporaryFile() {
367     if (path.empty())
368       return;
369     if (sys::fs::remove(path))
370       fatal("failed to remove " + path);
371   }
372 
373   // Returns a memory buffer of this temporary file.
374   // Note that this function does not leave the file open,
375   // so it is safe to remove the file immediately after this function
376   // is called (you cannot remove an opened file on Windows.)
377   std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
378     // IsVolatile=true forces MemoryBuffer to not use mmap().
379     return CHECK(MemoryBuffer::getFile(path, /*IsText=*/false,
380                                        /*RequiresNullTerminator=*/false,
381                                        /*IsVolatile=*/true),
382                  "could not open " + path);
383   }
384 
385   std::string path;
386 };
387 }
388 
389 static std::string createDefaultXml() {
390   std::string ret;
391   raw_string_ostream os(ret);
392 
393   // Emit the XML. Note that we do *not* verify that the XML attributes are
394   // syntactically correct. This is intentional for link.exe compatibility.
395   os << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
396      << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
397      << "          manifestVersion=\"1.0\">\n";
398   if (config->manifestUAC) {
399     os << "  <trustInfo>\n"
400        << "    <security>\n"
401        << "      <requestedPrivileges>\n"
402        << "         <requestedExecutionLevel level=" << config->manifestLevel
403        << " uiAccess=" << config->manifestUIAccess << "/>\n"
404        << "      </requestedPrivileges>\n"
405        << "    </security>\n"
406        << "  </trustInfo>\n";
407   }
408   for (auto manifestDependency : config->manifestDependencies) {
409     os << "  <dependency>\n"
410        << "    <dependentAssembly>\n"
411        << "      <assemblyIdentity " << manifestDependency << " />\n"
412        << "    </dependentAssembly>\n"
413        << "  </dependency>\n";
414   }
415   os << "</assembly>\n";
416   return os.str();
417 }
418 
419 static std::string createManifestXmlWithInternalMt(StringRef defaultXml) {
420   std::unique_ptr<MemoryBuffer> defaultXmlCopy =
421       MemoryBuffer::getMemBufferCopy(defaultXml);
422 
423   windows_manifest::WindowsManifestMerger merger;
424   if (auto e = merger.merge(*defaultXmlCopy.get()))
425     fatal("internal manifest tool failed on default xml: " +
426           toString(std::move(e)));
427 
428   for (StringRef filename : config->manifestInput) {
429     std::unique_ptr<MemoryBuffer> manifest =
430         check(MemoryBuffer::getFile(filename));
431     // Call takeBuffer to include in /reproduce: output if applicable.
432     if (auto e = merger.merge(driver->takeBuffer(std::move(manifest))))
433       fatal("internal manifest tool failed on file " + filename + ": " +
434             toString(std::move(e)));
435   }
436 
437   return std::string(merger.getMergedManifest().get()->getBuffer());
438 }
439 
440 static std::string createManifestXmlWithExternalMt(StringRef defaultXml) {
441   // Create the default manifest file as a temporary file.
442   TemporaryFile Default("defaultxml", "manifest");
443   std::error_code ec;
444   raw_fd_ostream os(Default.path, ec, sys::fs::OF_TextWithCRLF);
445   if (ec)
446     fatal("failed to open " + Default.path + ": " + ec.message());
447   os << defaultXml;
448   os.close();
449 
450   // Merge user-supplied manifests if they are given.  Since libxml2 is not
451   // enabled, we must shell out to Microsoft's mt.exe tool.
452   TemporaryFile user("user", "manifest");
453 
454   Executor e("mt.exe");
455   e.add("/manifest");
456   e.add(Default.path);
457   for (StringRef filename : config->manifestInput) {
458     e.add("/manifest");
459     e.add(filename);
460 
461     // Manually add the file to the /reproduce: tar if needed.
462     if (driver->tar)
463       if (auto mbOrErr = MemoryBuffer::getFile(filename))
464         driver->takeBuffer(std::move(*mbOrErr));
465   }
466   e.add("/nologo");
467   e.add("/out:" + StringRef(user.path));
468   e.run();
469 
470   return std::string(
471       CHECK(MemoryBuffer::getFile(user.path), "could not open " + user.path)
472           .get()
473           ->getBuffer());
474 }
475 
476 static std::string createManifestXml() {
477   std::string defaultXml = createDefaultXml();
478   if (config->manifestInput.empty())
479     return defaultXml;
480 
481   if (windows_manifest::isAvailable())
482     return createManifestXmlWithInternalMt(defaultXml);
483 
484   return createManifestXmlWithExternalMt(defaultXml);
485 }
486 
487 static std::unique_ptr<WritableMemoryBuffer>
488 createMemoryBufferForManifestRes(size_t manifestSize) {
489   size_t resSize = alignTo(
490       object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +
491           sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +
492           sizeof(object::WinResHeaderSuffix) + manifestSize,
493       object::WIN_RES_DATA_ALIGNMENT);
494   return WritableMemoryBuffer::getNewMemBuffer(resSize, config->outputFile +
495                                                             ".manifest.res");
496 }
497 
498 static void writeResFileHeader(char *&buf) {
499   memcpy(buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
500   buf += sizeof(COFF::WinResMagic);
501   memset(buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
502   buf += object::WIN_RES_NULL_ENTRY_SIZE;
503 }
504 
505 static void writeResEntryHeader(char *&buf, size_t manifestSize) {
506   // Write the prefix.
507   auto *prefix = reinterpret_cast<object::WinResHeaderPrefix *>(buf);
508   prefix->DataSize = manifestSize;
509   prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
510                        sizeof(object::WinResIDs) +
511                        sizeof(object::WinResHeaderSuffix);
512   buf += sizeof(object::WinResHeaderPrefix);
513 
514   // Write the Type/Name IDs.
515   auto *iDs = reinterpret_cast<object::WinResIDs *>(buf);
516   iDs->setType(RT_MANIFEST);
517   iDs->setName(config->manifestID);
518   buf += sizeof(object::WinResIDs);
519 
520   // Write the suffix.
521   auto *suffix = reinterpret_cast<object::WinResHeaderSuffix *>(buf);
522   suffix->DataVersion = 0;
523   suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
524   suffix->Language = SUBLANG_ENGLISH_US;
525   suffix->Version = 0;
526   suffix->Characteristics = 0;
527   buf += sizeof(object::WinResHeaderSuffix);
528 }
529 
530 // Create a resource file containing a manifest XML.
531 std::unique_ptr<MemoryBuffer> createManifestRes() {
532   std::string manifest = createManifestXml();
533 
534   std::unique_ptr<WritableMemoryBuffer> res =
535       createMemoryBufferForManifestRes(manifest.size());
536 
537   char *buf = res->getBufferStart();
538   writeResFileHeader(buf);
539   writeResEntryHeader(buf, manifest.size());
540 
541   // Copy the manifest data into the .res file.
542   std::copy(manifest.begin(), manifest.end(), buf);
543   return std::move(res);
544 }
545 
546 void createSideBySideManifest() {
547   std::string path = std::string(config->manifestFile);
548   if (path == "")
549     path = config->outputFile + ".manifest";
550   std::error_code ec;
551   raw_fd_ostream out(path, ec, sys::fs::OF_TextWithCRLF);
552   if (ec)
553     fatal("failed to create manifest: " + ec.message());
554   out << createManifestXml();
555 }
556 
557 // Parse a string in the form of
558 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
559 // or "<name>=<dllname>.<name>".
560 // Used for parsing /export arguments.
561 Export parseExport(StringRef arg) {
562   Export e;
563   StringRef rest;
564   std::tie(e.name, rest) = arg.split(",");
565   if (e.name.empty())
566     goto err;
567 
568   if (e.name.contains('=')) {
569     StringRef x, y;
570     std::tie(x, y) = e.name.split("=");
571 
572     // If "<name>=<dllname>.<name>".
573     if (y.contains(".")) {
574       e.name = x;
575       e.forwardTo = y;
576       return e;
577     }
578 
579     e.extName = x;
580     e.name = y;
581     if (e.name.empty())
582       goto err;
583   }
584 
585   // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
586   while (!rest.empty()) {
587     StringRef tok;
588     std::tie(tok, rest) = rest.split(",");
589     if (tok.equals_insensitive("noname")) {
590       if (e.ordinal == 0)
591         goto err;
592       e.noname = true;
593       continue;
594     }
595     if (tok.equals_insensitive("data")) {
596       e.data = true;
597       continue;
598     }
599     if (tok.equals_insensitive("constant")) {
600       e.constant = true;
601       continue;
602     }
603     if (tok.equals_insensitive("private")) {
604       e.isPrivate = true;
605       continue;
606     }
607     if (tok.startswith("@")) {
608       int32_t ord;
609       if (tok.substr(1).getAsInteger(0, ord))
610         goto err;
611       if (ord <= 0 || 65535 < ord)
612         goto err;
613       e.ordinal = ord;
614       continue;
615     }
616     goto err;
617   }
618   return e;
619 
620 err:
621   fatal("invalid /export: " + arg);
622 }
623 
624 static StringRef undecorate(StringRef sym) {
625   if (config->machine != I386)
626     return sym;
627   // In MSVC mode, a fully decorated stdcall function is exported
628   // as-is with the leading underscore (with type IMPORT_NAME).
629   // In MinGW mode, a decorated stdcall function gets the underscore
630   // removed, just like normal cdecl functions.
631   if (sym.startswith("_") && sym.contains('@') && !config->mingw)
632     return sym;
633   return sym.startswith("_") ? sym.substr(1) : sym;
634 }
635 
636 // Convert stdcall/fastcall style symbols into unsuffixed symbols,
637 // with or without a leading underscore. (MinGW specific.)
638 static StringRef killAt(StringRef sym, bool prefix) {
639   if (sym.empty())
640     return sym;
641   // Strip any trailing stdcall suffix
642   sym = sym.substr(0, sym.find('@', 1));
643   if (!sym.startswith("@")) {
644     if (prefix && !sym.startswith("_"))
645       return saver.save("_" + sym);
646     return sym;
647   }
648   // For fastcall, remove the leading @ and replace it with an
649   // underscore, if prefixes are used.
650   sym = sym.substr(1);
651   if (prefix)
652     sym = saver.save("_" + sym);
653   return sym;
654 }
655 
656 // Performs error checking on all /export arguments.
657 // It also sets ordinals.
658 void fixupExports() {
659   // Symbol ordinals must be unique.
660   std::set<uint16_t> ords;
661   for (Export &e : config->exports) {
662     if (e.ordinal == 0)
663       continue;
664     if (!ords.insert(e.ordinal).second)
665       fatal("duplicate export ordinal: " + e.name);
666   }
667 
668   for (Export &e : config->exports) {
669     if (!e.forwardTo.empty()) {
670       e.exportName = undecorate(e.name);
671     } else {
672       e.exportName = undecorate(e.extName.empty() ? e.name : e.extName);
673     }
674   }
675 
676   if (config->killAt && config->machine == I386) {
677     for (Export &e : config->exports) {
678       e.name = killAt(e.name, true);
679       e.exportName = killAt(e.exportName, false);
680       e.extName = killAt(e.extName, true);
681       e.symbolName = killAt(e.symbolName, true);
682     }
683   }
684 
685   // Uniquefy by name.
686   DenseMap<StringRef, Export *> map(config->exports.size());
687   std::vector<Export> v;
688   for (Export &e : config->exports) {
689     auto pair = map.insert(std::make_pair(e.exportName, &e));
690     bool inserted = pair.second;
691     if (inserted) {
692       v.push_back(e);
693       continue;
694     }
695     Export *existing = pair.first->second;
696     if (e == *existing || e.name != existing->name)
697       continue;
698     warn("duplicate /export option: " + e.name);
699   }
700   config->exports = std::move(v);
701 
702   // Sort by name.
703   std::sort(config->exports.begin(), config->exports.end(),
704             [](const Export &a, const Export &b) {
705               return a.exportName < b.exportName;
706             });
707 }
708 
709 void assignExportOrdinals() {
710   // Assign unique ordinals if default (= 0).
711   uint32_t max = 0;
712   for (Export &e : config->exports)
713     max = std::max(max, (uint32_t)e.ordinal);
714   for (Export &e : config->exports)
715     if (e.ordinal == 0)
716       e.ordinal = ++max;
717   if (max > std::numeric_limits<uint16_t>::max())
718     fatal("too many exported symbols (max " +
719           Twine(std::numeric_limits<uint16_t>::max()) + ")");
720 }
721 
722 // Parses a string in the form of "key=value" and check
723 // if value matches previous values for the same key.
724 void checkFailIfMismatch(StringRef arg, InputFile *source) {
725   StringRef k, v;
726   std::tie(k, v) = arg.split('=');
727   if (k.empty() || v.empty())
728     fatal("/failifmismatch: invalid argument: " + arg);
729   std::pair<StringRef, InputFile *> existing = config->mustMatch[k];
730   if (!existing.first.empty() && v != existing.first) {
731     std::string sourceStr = source ? toString(source) : "cmd-line";
732     std::string existingStr =
733         existing.second ? toString(existing.second) : "cmd-line";
734     fatal("/failifmismatch: mismatch detected for '" + k + "':\n>>> " +
735           existingStr + " has value " + existing.first + "\n>>> " + sourceStr +
736           " has value " + v);
737   }
738   config->mustMatch[k] = {v, source};
739 }
740 
741 // Convert Windows resource files (.res files) to a .obj file.
742 // Does what cvtres.exe does, but in-process and cross-platform.
743 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
744                                  ArrayRef<ObjFile *> objs) {
745   object::WindowsResourceParser parser(/* MinGW */ config->mingw);
746 
747   std::vector<std::string> duplicates;
748   for (MemoryBufferRef mb : mbs) {
749     std::unique_ptr<object::Binary> bin = check(object::createBinary(mb));
750     object::WindowsResource *rf = dyn_cast<object::WindowsResource>(bin.get());
751     if (!rf)
752       fatal("cannot compile non-resource file as resource");
753 
754     if (auto ec = parser.parse(rf, duplicates))
755       fatal(toString(std::move(ec)));
756   }
757 
758   // Note: This processes all .res files before all objs. Ideally they'd be
759   // handled in the same order they were linked (to keep the right one, if
760   // there are duplicates that are tolerated due to forceMultipleRes).
761   for (ObjFile *f : objs) {
762     object::ResourceSectionRef rsf;
763     if (auto ec = rsf.load(f->getCOFFObj()))
764       fatal(toString(f) + ": " + toString(std::move(ec)));
765 
766     if (auto ec = parser.parse(rsf, f->getName(), duplicates))
767       fatal(toString(std::move(ec)));
768   }
769 
770   if (config->mingw)
771     parser.cleanUpManifests(duplicates);
772 
773   for (const auto &dupeDiag : duplicates)
774     if (config->forceMultipleRes)
775       warn(dupeDiag);
776     else
777       error(dupeDiag);
778 
779   Expected<std::unique_ptr<MemoryBuffer>> e =
780       llvm::object::writeWindowsResourceCOFF(config->machine, parser,
781                                              config->timestamp);
782   if (!e)
783     fatal("failed to write .res to COFF: " + toString(e.takeError()));
784 
785   MemoryBufferRef mbref = **e;
786   make<std::unique_ptr<MemoryBuffer>>(std::move(*e)); // take ownership
787   return mbref;
788 }
789 
790 // Create OptTable
791 
792 // Create prefix string literals used in Options.td
793 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
794 #include "Options.inc"
795 #undef PREFIX
796 
797 // Create table mapping all options defined in Options.td
798 static const llvm::opt::OptTable::Info infoTable[] = {
799 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
800   {X1, X2, X10,         X11,         OPT_##ID, llvm::opt::Option::KIND##Class, \
801    X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
802 #include "Options.inc"
803 #undef OPTION
804 };
805 
806 COFFOptTable::COFFOptTable() : OptTable(infoTable, true) {}
807 
808 COFFOptTable optTable;
809 
810 // Set color diagnostics according to --color-diagnostics={auto,always,never}
811 // or --no-color-diagnostics flags.
812 static void handleColorDiagnostics(opt::InputArgList &args) {
813   auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
814                               OPT_no_color_diagnostics);
815   if (!arg)
816     return;
817   if (arg->getOption().getID() == OPT_color_diagnostics) {
818     lld::errs().enable_colors(true);
819   } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
820     lld::errs().enable_colors(false);
821   } else {
822     StringRef s = arg->getValue();
823     if (s == "always")
824       lld::errs().enable_colors(true);
825     else if (s == "never")
826       lld::errs().enable_colors(false);
827     else if (s != "auto")
828       error("unknown option: --color-diagnostics=" + s);
829   }
830 }
831 
832 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
833   if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
834     StringRef s = arg->getValue();
835     if (s != "windows" && s != "posix")
836       error("invalid response file quoting: " + s);
837     if (s == "windows")
838       return cl::TokenizeWindowsCommandLine;
839     return cl::TokenizeGNUCommandLine;
840   }
841   // The COFF linker always defaults to Windows quoting.
842   return cl::TokenizeWindowsCommandLine;
843 }
844 
845 // Parses a given list of options.
846 opt::InputArgList ArgParser::parse(ArrayRef<const char *> argv) {
847   // Make InputArgList from string vectors.
848   unsigned missingIndex;
849   unsigned missingCount;
850 
851   // We need to get the quoting style for response files before parsing all
852   // options so we parse here before and ignore all the options but
853   // --rsp-quoting and /lldignoreenv.
854   // (This means --rsp-quoting can't be added through %LINK%.)
855   opt::InputArgList args = optTable.ParseArgs(argv, missingIndex, missingCount);
856 
857   // Expand response files (arguments in the form of @<filename>) and insert
858   // flags from %LINK% and %_LINK_%, and then parse the argument again.
859   SmallVector<const char *, 256> expandedArgv(argv.data(),
860                                               argv.data() + argv.size());
861   if (!args.hasArg(OPT_lldignoreenv))
862     addLINK(expandedArgv);
863   cl::ExpandResponseFiles(saver, getQuotingStyle(args), expandedArgv);
864   args = optTable.ParseArgs(makeArrayRef(expandedArgv).drop_front(),
865                             missingIndex, missingCount);
866 
867   // Print the real command line if response files are expanded.
868   if (args.hasArg(OPT_verbose) && argv.size() != expandedArgv.size()) {
869     std::string msg = "Command line:";
870     for (const char *s : expandedArgv)
871       msg += " " + std::string(s);
872     message(msg);
873   }
874 
875   // Save the command line after response file expansion so we can write it to
876   // the PDB if necessary.
877   config->argv = {expandedArgv.begin(), expandedArgv.end()};
878 
879   // Handle /WX early since it converts missing argument warnings to errors.
880   errorHandler().fatalWarnings = args.hasFlag(OPT_WX, OPT_WX_no, false);
881 
882   if (missingCount)
883     fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
884 
885   handleColorDiagnostics(args);
886 
887   for (opt::Arg *arg : args.filtered(OPT_UNKNOWN)) {
888     std::string nearest;
889     if (optTable.findNearest(arg->getAsString(args), nearest) > 1)
890       warn("ignoring unknown argument '" + arg->getAsString(args) + "'");
891     else
892       warn("ignoring unknown argument '" + arg->getAsString(args) +
893            "', did you mean '" + nearest + "'");
894   }
895 
896   if (args.hasArg(OPT_lib))
897     warn("ignoring /lib since it's not the first argument");
898 
899   return args;
900 }
901 
902 // Tokenizes and parses a given string as command line in .drective section.
903 ParsedDirectives ArgParser::parseDirectives(StringRef s) {
904   ParsedDirectives result;
905   SmallVector<const char *, 16> rest;
906 
907   // Handle /EXPORT and /INCLUDE in a fast path. These directives can appear for
908   // potentially every symbol in the object, so they must be handled quickly.
909   SmallVector<StringRef, 16> tokens;
910   cl::TokenizeWindowsCommandLineNoCopy(s, saver, tokens);
911   for (StringRef tok : tokens) {
912     if (tok.startswith_insensitive("/export:") ||
913         tok.startswith_insensitive("-export:"))
914       result.exports.push_back(tok.substr(strlen("/export:")));
915     else if (tok.startswith_insensitive("/include:") ||
916              tok.startswith_insensitive("-include:"))
917       result.includes.push_back(tok.substr(strlen("/include:")));
918     else {
919       // Copy substrings that are not valid C strings. The tokenizer may have
920       // already copied quoted arguments for us, so those do not need to be
921       // copied again.
922       bool HasNul = tok.end() != s.end() && tok.data()[tok.size()] == '\0';
923       rest.push_back(HasNul ? tok.data() : saver.save(tok).data());
924     }
925   }
926 
927   // Make InputArgList from unparsed string vectors.
928   unsigned missingIndex;
929   unsigned missingCount;
930 
931   result.args = optTable.ParseArgs(rest, missingIndex, missingCount);
932 
933   if (missingCount)
934     fatal(Twine(result.args.getArgString(missingIndex)) + ": missing argument");
935   for (auto *arg : result.args.filtered(OPT_UNKNOWN))
936     warn("ignoring unknown argument: " + arg->getAsString(result.args));
937   return result;
938 }
939 
940 // link.exe has an interesting feature. If LINK or _LINK_ environment
941 // variables exist, their contents are handled as command line strings.
942 // So you can pass extra arguments using them.
943 void ArgParser::addLINK(SmallVector<const char *, 256> &argv) {
944   // Concatenate LINK env and command line arguments, and then parse them.
945   if (Optional<std::string> s = Process::GetEnv("LINK")) {
946     std::vector<const char *> v = tokenize(*s);
947     argv.insert(std::next(argv.begin()), v.begin(), v.end());
948   }
949   if (Optional<std::string> s = Process::GetEnv("_LINK_")) {
950     std::vector<const char *> v = tokenize(*s);
951     argv.insert(std::next(argv.begin()), v.begin(), v.end());
952   }
953 }
954 
955 std::vector<const char *> ArgParser::tokenize(StringRef s) {
956   SmallVector<const char *, 16> tokens;
957   cl::TokenizeWindowsCommandLine(s, saver, tokens);
958   return std::vector<const char *>(tokens.begin(), tokens.end());
959 }
960 
961 void printHelp(const char *argv0) {
962   optTable.printHelp(lld::outs(),
963                      (std::string(argv0) + " [options] file...").c_str(),
964                      "LLVM Linker", false);
965 }
966 
967 } // namespace coff
968 } // namespace lld
969