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