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[name] = std::max(config->alignComm[name], 1 << v);
224}
225
226// Parses /functionpadmin option argument.
227void parseFunctionPadMin(llvm::opt::Arg *a, llvm::COFF::MachineTypes machine) {
228  StringRef arg = a->getNumValues() ? a->getValue() : "";
229  if (!arg.empty()) {
230    // Optional padding in bytes is given.
231    if (arg.getAsInteger(0, config->functionPadMin))
232      error("/functionpadmin: invalid argument: " + arg);
233    return;
234  }
235  // No optional argument given.
236  // Set default padding based on machine, similar to link.exe.
237  // There is no default padding for ARM platforms.
238  if (machine == I386) {
239    config->functionPadMin = 5;
240  } else if (machine == AMD64) {
241    config->functionPadMin = 6;
242  } else {
243    error("/functionpadmin: invalid argument for this machine: " + arg);
244  }
245}
246
247// Parses a string in the form of "EMBED[,=<integer>]|NO".
248// Results are directly written to Config.
249void parseManifest(StringRef arg) {
250  if (arg.equals_lower("no")) {
251    config->manifest = Configuration::No;
252    return;
253  }
254  if (!arg.startswith_lower("embed"))
255    fatal("invalid option " + arg);
256  config->manifest = Configuration::Embed;
257  arg = arg.substr(strlen("embed"));
258  if (arg.empty())
259    return;
260  if (!arg.startswith_lower(",id="))
261    fatal("invalid option " + arg);
262  arg = arg.substr(strlen(",id="));
263  if (arg.getAsInteger(0, config->manifestID))
264    fatal("invalid option " + arg);
265}
266
267// Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
268// Results are directly written to Config.
269void parseManifestUAC(StringRef arg) {
270  if (arg.equals_lower("no")) {
271    config->manifestUAC = false;
272    return;
273  }
274  for (;;) {
275    arg = arg.ltrim();
276    if (arg.empty())
277      return;
278    if (arg.startswith_lower("level=")) {
279      arg = arg.substr(strlen("level="));
280      std::tie(config->manifestLevel, arg) = arg.split(" ");
281      continue;
282    }
283    if (arg.startswith_lower("uiaccess=")) {
284      arg = arg.substr(strlen("uiaccess="));
285      std::tie(config->manifestUIAccess, arg) = arg.split(" ");
286      continue;
287    }
288    fatal("invalid option " + arg);
289  }
290}
291
292// Parses a string in the form of "cd|net[,(cd|net)]*"
293// Results are directly written to Config.
294void parseSwaprun(StringRef arg) {
295  do {
296    StringRef swaprun, newArg;
297    std::tie(swaprun, newArg) = arg.split(',');
298    if (swaprun.equals_lower("cd"))
299      config->swaprunCD = true;
300    else if (swaprun.equals_lower("net"))
301      config->swaprunNet = true;
302    else if (swaprun.empty())
303      error("/swaprun: missing argument");
304    else
305      error("/swaprun: invalid argument: " + swaprun);
306    // To catch trailing commas, e.g. `/spawrun:cd,`
307    if (newArg.empty() && arg.endswith(","))
308      error("/swaprun: missing argument");
309    arg = newArg;
310  } while (!arg.empty());
311}
312
313// An RAII temporary file class that automatically removes a temporary file.
314namespace {
315class TemporaryFile {
316public:
317  TemporaryFile(StringRef prefix, StringRef extn, StringRef contents = "") {
318    SmallString<128> s;
319    if (auto ec = sys::fs::createTemporaryFile("lld-" + prefix, extn, s))
320      fatal("cannot create a temporary file: " + ec.message());
321    path = s.str();
322
323    if (!contents.empty()) {
324      std::error_code ec;
325      raw_fd_ostream os(path, ec, sys::fs::OF_None);
326      if (ec)
327        fatal("failed to open " + path + ": " + ec.message());
328      os << contents;
329    }
330  }
331
332  TemporaryFile(TemporaryFile &&obj) {
333    std::swap(path, obj.path);
334  }
335
336  ~TemporaryFile() {
337    if (path.empty())
338      return;
339    if (sys::fs::remove(path))
340      fatal("failed to remove " + path);
341  }
342
343  // Returns a memory buffer of this temporary file.
344  // Note that this function does not leave the file open,
345  // so it is safe to remove the file immediately after this function
346  // is called (you cannot remove an opened file on Windows.)
347  std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
348    // IsVolatile=true forces MemoryBuffer to not use mmap().
349    return CHECK(MemoryBuffer::getFile(path, /*FileSize=*/-1,
350                                       /*RequiresNullTerminator=*/false,
351                                       /*IsVolatile=*/true),
352                 "could not open " + path);
353  }
354
355  std::string path;
356};
357}
358
359static std::string createDefaultXml() {
360  std::string ret;
361  raw_string_ostream os(ret);
362
363  // Emit the XML. Note that we do *not* verify that the XML attributes are
364  // syntactically correct. This is intentional for link.exe compatibility.
365  os << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
366     << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
367     << "          manifestVersion=\"1.0\">\n";
368  if (config->manifestUAC) {
369    os << "  <trustInfo>\n"
370       << "    <security>\n"
371       << "      <requestedPrivileges>\n"
372       << "         <requestedExecutionLevel level=" << config->manifestLevel
373       << " uiAccess=" << config->manifestUIAccess << "/>\n"
374       << "      </requestedPrivileges>\n"
375       << "    </security>\n"
376       << "  </trustInfo>\n";
377  }
378  if (!config->manifestDependency.empty()) {
379    os << "  <dependency>\n"
380       << "    <dependentAssembly>\n"
381       << "      <assemblyIdentity " << config->manifestDependency << " />\n"
382       << "    </dependentAssembly>\n"
383       << "  </dependency>\n";
384  }
385  os << "</assembly>\n";
386  return os.str();
387}
388
389static std::string createManifestXmlWithInternalMt(StringRef defaultXml) {
390  std::unique_ptr<MemoryBuffer> defaultXmlCopy =
391      MemoryBuffer::getMemBufferCopy(defaultXml);
392
393  windows_manifest::WindowsManifestMerger merger;
394  if (auto e = merger.merge(*defaultXmlCopy.get()))
395    fatal("internal manifest tool failed on default xml: " +
396          toString(std::move(e)));
397
398  for (StringRef filename : config->manifestInput) {
399    std::unique_ptr<MemoryBuffer> manifest =
400        check(MemoryBuffer::getFile(filename));
401    if (auto e = merger.merge(*manifest.get()))
402      fatal("internal manifest tool failed on file " + filename + ": " +
403            toString(std::move(e)));
404  }
405
406  return merger.getMergedManifest().get()->getBuffer();
407}
408
409static std::string createManifestXmlWithExternalMt(StringRef defaultXml) {
410  // Create the default manifest file as a temporary file.
411  TemporaryFile Default("defaultxml", "manifest");
412  std::error_code ec;
413  raw_fd_ostream os(Default.path, ec, sys::fs::OF_Text);
414  if (ec)
415    fatal("failed to open " + Default.path + ": " + ec.message());
416  os << defaultXml;
417  os.close();
418
419  // Merge user-supplied manifests if they are given.  Since libxml2 is not
420  // enabled, we must shell out to Microsoft's mt.exe tool.
421  TemporaryFile user("user", "manifest");
422
423  Executor e("mt.exe");
424  e.add("/manifest");
425  e.add(Default.path);
426  for (StringRef filename : config->manifestInput) {
427    e.add("/manifest");
428    e.add(filename);
429  }
430  e.add("/nologo");
431  e.add("/out:" + StringRef(user.path));
432  e.run();
433
434  return CHECK(MemoryBuffer::getFile(user.path), "could not open " + user.path)
435      .get()
436      ->getBuffer();
437}
438
439static std::string createManifestXml() {
440  std::string defaultXml = createDefaultXml();
441  if (config->manifestInput.empty())
442    return defaultXml;
443
444  if (windows_manifest::isAvailable())
445    return createManifestXmlWithInternalMt(defaultXml);
446
447  return createManifestXmlWithExternalMt(defaultXml);
448}
449
450static std::unique_ptr<WritableMemoryBuffer>
451createMemoryBufferForManifestRes(size_t manifestSize) {
452  size_t resSize = alignTo(
453      object::WIN_RES_MAGIC_SIZE + object::WIN_RES_NULL_ENTRY_SIZE +
454          sizeof(object::WinResHeaderPrefix) + sizeof(object::WinResIDs) +
455          sizeof(object::WinResHeaderSuffix) + manifestSize,
456      object::WIN_RES_DATA_ALIGNMENT);
457  return WritableMemoryBuffer::getNewMemBuffer(resSize, config->outputFile +
458                                                            ".manifest.res");
459}
460
461static void writeResFileHeader(char *&buf) {
462  memcpy(buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
463  buf += sizeof(COFF::WinResMagic);
464  memset(buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
465  buf += object::WIN_RES_NULL_ENTRY_SIZE;
466}
467
468static void writeResEntryHeader(char *&buf, size_t manifestSize) {
469  // Write the prefix.
470  auto *prefix = reinterpret_cast<object::WinResHeaderPrefix *>(buf);
471  prefix->DataSize = manifestSize;
472  prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
473                       sizeof(object::WinResIDs) +
474                       sizeof(object::WinResHeaderSuffix);
475  buf += sizeof(object::WinResHeaderPrefix);
476
477  // Write the Type/Name IDs.
478  auto *iDs = reinterpret_cast<object::WinResIDs *>(buf);
479  iDs->setType(RT_MANIFEST);
480  iDs->setName(config->manifestID);
481  buf += sizeof(object::WinResIDs);
482
483  // Write the suffix.
484  auto *suffix = reinterpret_cast<object::WinResHeaderSuffix *>(buf);
485  suffix->DataVersion = 0;
486  suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
487  suffix->Language = SUBLANG_ENGLISH_US;
488  suffix->Version = 0;
489  suffix->Characteristics = 0;
490  buf += sizeof(object::WinResHeaderSuffix);
491}
492
493// Create a resource file containing a manifest XML.
494std::unique_ptr<MemoryBuffer> createManifestRes() {
495  std::string manifest = createManifestXml();
496
497  std::unique_ptr<WritableMemoryBuffer> res =
498      createMemoryBufferForManifestRes(manifest.size());
499
500  char *buf = res->getBufferStart();
501  writeResFileHeader(buf);
502  writeResEntryHeader(buf, manifest.size());
503
504  // Copy the manifest data into the .res file.
505  std::copy(manifest.begin(), manifest.end(), buf);
506  return std::move(res);
507}
508
509void createSideBySideManifest() {
510  std::string path = config->manifestFile;
511  if (path == "")
512    path = config->outputFile + ".manifest";
513  std::error_code ec;
514  raw_fd_ostream out(path, ec, sys::fs::OF_Text);
515  if (ec)
516    fatal("failed to create manifest: " + ec.message());
517  out << createManifestXml();
518}
519
520// Parse a string in the form of
521// "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
522// or "<name>=<dllname>.<name>".
523// Used for parsing /export arguments.
524Export parseExport(StringRef arg) {
525  Export e;
526  StringRef rest;
527  std::tie(e.name, rest) = arg.split(",");
528  if (e.name.empty())
529    goto err;
530
531  if (e.name.contains('=')) {
532    StringRef x, y;
533    std::tie(x, y) = e.name.split("=");
534
535    // If "<name>=<dllname>.<name>".
536    if (y.contains(".")) {
537      e.name = x;
538      e.forwardTo = y;
539      return e;
540    }
541
542    e.extName = x;
543    e.name = y;
544    if (e.name.empty())
545      goto err;
546  }
547
548  // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
549  while (!rest.empty()) {
550    StringRef tok;
551    std::tie(tok, rest) = rest.split(",");
552    if (tok.equals_lower("noname")) {
553      if (e.ordinal == 0)
554        goto err;
555      e.noname = true;
556      continue;
557    }
558    if (tok.equals_lower("data")) {
559      e.data = true;
560      continue;
561    }
562    if (tok.equals_lower("constant")) {
563      e.constant = true;
564      continue;
565    }
566    if (tok.equals_lower("private")) {
567      e.isPrivate = true;
568      continue;
569    }
570    if (tok.startswith("@")) {
571      int32_t ord;
572      if (tok.substr(1).getAsInteger(0, ord))
573        goto err;
574      if (ord <= 0 || 65535 < ord)
575        goto err;
576      e.ordinal = ord;
577      continue;
578    }
579    goto err;
580  }
581  return e;
582
583err:
584  fatal("invalid /export: " + arg);
585}
586
587static StringRef undecorate(StringRef sym) {
588  if (config->machine != I386)
589    return sym;
590  // In MSVC mode, a fully decorated stdcall function is exported
591  // as-is with the leading underscore (with type IMPORT_NAME).
592  // In MinGW mode, a decorated stdcall function gets the underscore
593  // removed, just like normal cdecl functions.
594  if (sym.startswith("_") && sym.contains('@') && !config->mingw)
595    return sym;
596  return sym.startswith("_") ? sym.substr(1) : sym;
597}
598
599// Convert stdcall/fastcall style symbols into unsuffixed symbols,
600// with or without a leading underscore. (MinGW specific.)
601static StringRef killAt(StringRef sym, bool prefix) {
602  if (sym.empty())
603    return sym;
604  // Strip any trailing stdcall suffix
605  sym = sym.substr(0, sym.find('@', 1));
606  if (!sym.startswith("@")) {
607    if (prefix && !sym.startswith("_"))
608      return saver.save("_" + sym);
609    return sym;
610  }
611  // For fastcall, remove the leading @ and replace it with an
612  // underscore, if prefixes are used.
613  sym = sym.substr(1);
614  if (prefix)
615    sym = saver.save("_" + sym);
616  return sym;
617}
618
619// Performs error checking on all /export arguments.
620// It also sets ordinals.
621void fixupExports() {
622  // Symbol ordinals must be unique.
623  std::set<uint16_t> ords;
624  for (Export &e : config->exports) {
625    if (e.ordinal == 0)
626      continue;
627    if (!ords.insert(e.ordinal).second)
628      fatal("duplicate export ordinal: " + e.name);
629  }
630
631  for (Export &e : config->exports) {
632    if (!e.forwardTo.empty()) {
633      e.exportName = undecorate(e.name);
634    } else {
635      e.exportName = undecorate(e.extName.empty() ? e.name : e.extName);
636    }
637  }
638
639  if (config->killAt && config->machine == I386) {
640    for (Export &e : config->exports) {
641      e.name = killAt(e.name, true);
642      e.exportName = killAt(e.exportName, false);
643      e.extName = killAt(e.extName, true);
644      e.symbolName = killAt(e.symbolName, true);
645    }
646  }
647
648  // Uniquefy by name.
649  DenseMap<StringRef, Export *> map(config->exports.size());
650  std::vector<Export> v;
651  for (Export &e : config->exports) {
652    auto pair = map.insert(std::make_pair(e.exportName, &e));
653    bool inserted = pair.second;
654    if (inserted) {
655      v.push_back(e);
656      continue;
657    }
658    Export *existing = pair.first->second;
659    if (e == *existing || e.name != existing->name)
660      continue;
661    warn("duplicate /export option: " + e.name);
662  }
663  config->exports = std::move(v);
664
665  // Sort by name.
666  std::sort(config->exports.begin(), config->exports.end(),
667            [](const Export &a, const Export &b) {
668              return a.exportName < b.exportName;
669            });
670}
671
672void assignExportOrdinals() {
673  // Assign unique ordinals if default (= 0).
674  uint16_t max = 0;
675  for (Export &e : config->exports)
676    max = std::max(max, e.ordinal);
677  for (Export &e : config->exports)
678    if (e.ordinal == 0)
679      e.ordinal = ++max;
680}
681
682// Parses a string in the form of "key=value" and check
683// if value matches previous values for the same key.
684void checkFailIfMismatch(StringRef arg, InputFile *source) {
685  StringRef k, v;
686  std::tie(k, v) = arg.split('=');
687  if (k.empty() || v.empty())
688    fatal("/failifmismatch: invalid argument: " + arg);
689  std::pair<StringRef, InputFile *> existing = config->mustMatch[k];
690  if (!existing.first.empty() && v != existing.first) {
691    std::string sourceStr = source ? toString(source) : "cmd-line";
692    std::string existingStr =
693        existing.second ? toString(existing.second) : "cmd-line";
694    fatal("/failifmismatch: mismatch detected for '" + k + "':\n>>> " +
695          existingStr + " has value " + existing.first + "\n>>> " + sourceStr +
696          " has value " + v);
697  }
698  config->mustMatch[k] = {v, source};
699}
700
701// Convert Windows resource files (.res files) to a .obj file.
702// Does what cvtres.exe does, but in-process and cross-platform.
703MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
704                                 ArrayRef<ObjFile *> objs) {
705  object::WindowsResourceParser parser(/* MinGW */ config->mingw);
706
707  std::vector<std::string> duplicates;
708  for (MemoryBufferRef mb : mbs) {
709    std::unique_ptr<object::Binary> bin = check(object::createBinary(mb));
710    object::WindowsResource *rf = dyn_cast<object::WindowsResource>(bin.get());
711    if (!rf)
712      fatal("cannot compile non-resource file as resource");
713
714    if (auto ec = parser.parse(rf, duplicates))
715      fatal(toString(std::move(ec)));
716  }
717
718  // Note: This processes all .res files before all objs. Ideally they'd be
719  // handled in the same order they were linked (to keep the right one, if
720  // there are duplicates that are tolerated due to forceMultipleRes).
721  for (ObjFile *f : objs) {
722    object::ResourceSectionRef rsf;
723    if (auto ec = rsf.load(f->getCOFFObj()))
724      fatal(toString(f) + ": " + toString(std::move(ec)));
725
726    if (auto ec = parser.parse(rsf, f->getName(), duplicates))
727      fatal(toString(std::move(ec)));
728  }
729
730  if (config->mingw)
731    parser.cleanUpManifests(duplicates);
732
733  for (const auto &dupeDiag : duplicates)
734    if (config->forceMultipleRes)
735      warn(dupeDiag);
736    else
737      error(dupeDiag);
738
739  Expected<std::unique_ptr<MemoryBuffer>> e =
740      llvm::object::writeWindowsResourceCOFF(config->machine, parser,
741                                             config->timestamp);
742  if (!e)
743    fatal("failed to write .res to COFF: " + toString(e.takeError()));
744
745  MemoryBufferRef mbref = **e;
746  make<std::unique_ptr<MemoryBuffer>>(std::move(*e)); // take ownership
747  return mbref;
748}
749
750// Create OptTable
751
752// Create prefix string literals used in Options.td
753#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
754#include "Options.inc"
755#undef PREFIX
756
757// Create table mapping all options defined in Options.td
758static const llvm::opt::OptTable::Info infoTable[] = {
759#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12)      \
760  {X1, X2, X10,         X11,         OPT_##ID, llvm::opt::Option::KIND##Class, \
761   X9, X8, OPT_##GROUP, OPT_##ALIAS, X7,       X12},
762#include "Options.inc"
763#undef OPTION
764};
765
766COFFOptTable::COFFOptTable() : OptTable(infoTable, true) {}
767
768// Set color diagnostics according to --color-diagnostics={auto,always,never}
769// or --no-color-diagnostics flags.
770static void handleColorDiagnostics(opt::InputArgList &args) {
771  auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
772                              OPT_no_color_diagnostics);
773  if (!arg)
774    return;
775  if (arg->getOption().getID() == OPT_color_diagnostics) {
776    lld::errs().enable_colors(true);
777  } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
778    lld::errs().enable_colors(false);
779  } else {
780    StringRef s = arg->getValue();
781    if (s == "always")
782      lld::errs().enable_colors(true);
783    else if (s == "never")
784      lld::errs().enable_colors(false);
785    else if (s != "auto")
786      error("unknown option: --color-diagnostics=" + s);
787  }
788}
789
790static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
791  if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
792    StringRef s = arg->getValue();
793    if (s != "windows" && s != "posix")
794      error("invalid response file quoting: " + s);
795    if (s == "windows")
796      return cl::TokenizeWindowsCommandLine;
797    return cl::TokenizeGNUCommandLine;
798  }
799  // The COFF linker always defaults to Windows quoting.
800  return cl::TokenizeWindowsCommandLine;
801}
802
803// Parses a given list of options.
804opt::InputArgList ArgParser::parse(ArrayRef<const char *> argv) {
805  // Make InputArgList from string vectors.
806  unsigned missingIndex;
807  unsigned missingCount;
808
809  // We need to get the quoting style for response files before parsing all
810  // options so we parse here before and ignore all the options but
811  // --rsp-quoting and /lldignoreenv.
812  // (This means --rsp-quoting can't be added through %LINK%.)
813  opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
814
815
816  // Expand response files (arguments in the form of @<filename>) and insert
817  // flags from %LINK% and %_LINK_%, and then parse the argument again.
818  SmallVector<const char *, 256> expandedArgv(argv.data(),
819                                              argv.data() + argv.size());
820  if (!args.hasArg(OPT_lldignoreenv))
821    addLINK(expandedArgv);
822  cl::ExpandResponseFiles(saver, getQuotingStyle(args), expandedArgv);
823  args = table.ParseArgs(makeArrayRef(expandedArgv).drop_front(), missingIndex,
824                         missingCount);
825
826  // Print the real command line if response files are expanded.
827  if (args.hasArg(OPT_verbose) && argv.size() != expandedArgv.size()) {
828    std::string msg = "Command line:";
829    for (const char *s : expandedArgv)
830      msg += " " + std::string(s);
831    message(msg);
832  }
833
834  // Save the command line after response file expansion so we can write it to
835  // the PDB if necessary.
836  config->argv = {expandedArgv.begin(), expandedArgv.end()};
837
838  // Handle /WX early since it converts missing argument warnings to errors.
839  errorHandler().fatalWarnings = args.hasFlag(OPT_WX, OPT_WX_no, false);
840
841  if (missingCount)
842    fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
843
844  handleColorDiagnostics(args);
845
846  for (auto *arg : args.filtered(OPT_UNKNOWN)) {
847    std::string nearest;
848    if (table.findNearest(arg->getAsString(args), nearest) > 1)
849      warn("ignoring unknown argument '" + arg->getAsString(args) + "'");
850    else
851      warn("ignoring unknown argument '" + arg->getAsString(args) +
852           "', did you mean '" + nearest + "'");
853  }
854
855  if (args.hasArg(OPT_lib))
856    warn("ignoring /lib since it's not the first argument");
857
858  return args;
859}
860
861// Tokenizes and parses a given string as command line in .drective section.
862// /EXPORT options are processed in fastpath.
863std::pair<opt::InputArgList, std::vector<StringRef>>
864ArgParser::parseDirectives(StringRef s) {
865  std::vector<StringRef> exports;
866  SmallVector<const char *, 16> rest;
867
868  for (StringRef tok : tokenize(s)) {
869    if (tok.startswith_lower("/export:") || tok.startswith_lower("-export:"))
870      exports.push_back(tok.substr(strlen("/export:")));
871    else
872      rest.push_back(tok.data());
873  }
874
875  // Make InputArgList from unparsed string vectors.
876  unsigned missingIndex;
877  unsigned missingCount;
878
879  opt::InputArgList args = table.ParseArgs(rest, missingIndex, missingCount);
880
881  if (missingCount)
882    fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
883  for (auto *arg : args.filtered(OPT_UNKNOWN))
884    warn("ignoring unknown argument: " + arg->getAsString(args));
885  return {std::move(args), std::move(exports)};
886}
887
888// link.exe has an interesting feature. If LINK or _LINK_ environment
889// variables exist, their contents are handled as command line strings.
890// So you can pass extra arguments using them.
891void ArgParser::addLINK(SmallVector<const char *, 256> &argv) {
892  // Concatenate LINK env and command line arguments, and then parse them.
893  if (Optional<std::string> s = Process::GetEnv("LINK")) {
894    std::vector<const char *> v = tokenize(*s);
895    argv.insert(std::next(argv.begin()), v.begin(), v.end());
896  }
897  if (Optional<std::string> s = Process::GetEnv("_LINK_")) {
898    std::vector<const char *> v = tokenize(*s);
899    argv.insert(std::next(argv.begin()), v.begin(), v.end());
900  }
901}
902
903std::vector<const char *> ArgParser::tokenize(StringRef s) {
904  SmallVector<const char *, 16> tokens;
905  cl::TokenizeWindowsCommandLine(s, saver, tokens);
906  return std::vector<const char *>(tokens.begin(), tokens.end());
907}
908
909void printHelp(const char *argv0) {
910  COFFOptTable().PrintHelp(lld::outs(),
911                           (std::string(argv0) + " [options] file...").c_str(),
912                           "LLVM Linker", false);
913}
914
915} // namespace coff
916} // namespace lld
917