[ELF][ARM] Increase default max-page-size from 4096 to 6536
[llvm-project.git] / lld / COFF / DriverUtils.cpp
blobf1b50e6142e1de72669a5e3d193064f5583e4729
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.
13 //===----------------------------------------------------------------------===//
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>
37 using namespace llvm::COFF;
38 using namespace llvm;
39 using llvm::sys::Process;
41 namespace lld {
42 namespace coff {
43 namespace {
45 const uint16_t SUBLANG_ENGLISH_US = 0x0409;
46 const uint16_t RT_MANIFEST = 24;
48 class Executor {
49 public:
50 explicit Executor(StringRef s) : prog(saver.save(s)) {}
51 void add(StringRef s) { args.push_back(saver.save(s)); }
52 void add(std::string &s) { args.push_back(saver.save(s)); }
53 void add(Twine s) { args.push_back(saver.save(s)); }
54 void add(const char *s) { args.push_back(saver.save(s)); }
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);
63 if (sys::ExecuteAndWait(args[0], args) != 0)
64 fatal("ExecuteAndWait failed: " +
65 llvm::join(args.begin(), args.end(), " "));
68 private:
69 StringRef prog;
70 std::vector<StringRef> args;
73 } // anonymous namespace
75 // Parses a string in the form of "<integer>[,<integer>]".
76 void 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);
85 // Parses a string in the form of "<integer>[.<integer>]".
86 // If second number is not present, Minor is set to 0.
87 void 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);
97 void 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);
112 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
113 void 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);
136 // Parse a string of the form of "<from>=<to>".
137 // Results are directly written to Config.
138 void 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));
149 // Parse a string of the form of "<from>=<to>".
150 // Results are directly written to Config.
151 void 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);
169 static 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);
198 return ret;
201 // Parses /section option argument.
202 void 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);
210 // Parses /aligncomm option argument.
211 void 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;
218 int v;
219 if (align.getAsInteger(0, v)) {
220 error("/aligncomm: invalid argument: " + s);
221 return;
223 config->alignComm[std::string(name)] =
224 std::max(config->alignComm[std::string(name)], 1 << v);
227 // Parses /functionpadmin option argument.
228 void 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;
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);
248 // Parses a string in the form of "EMBED[,=<integer>]|NO".
249 // Results are directly written to Config.
250 void parseManifest(StringRef arg) {
251 if (arg.equals_lower("no")) {
252 config->manifest = Configuration::No;
253 return;
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);
268 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
269 // Results are directly written to Config.
270 void parseManifestUAC(StringRef arg) {
271 if (arg.equals_lower("no")) {
272 config->manifestUAC = false;
273 return;
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;
284 if (arg.startswith_lower("uiaccess=")) {
285 arg = arg.substr(strlen("uiaccess="));
286 std::tie(config->manifestUIAccess, arg) = arg.split(" ");
287 continue;
289 fatal("invalid option " + arg);
293 // Parses a string in the form of "cd|net[,(cd|net)]*"
294 // Results are directly written to Config.
295 void 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());
314 // An RAII temporary file class that automatically removes a temporary file.
315 namespace {
316 class TemporaryFile {
317 public:
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());
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;
333 TemporaryFile(TemporaryFile &&obj) {
334 std::swap(path, obj.path);
337 ~TemporaryFile() {
338 if (path.empty())
339 return;
340 if (sys::fs::remove(path))
341 fatal("failed to remove " + path);
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);
356 std::string path;
360 static std::string createDefaultXml() {
361 std::string ret;
362 raw_string_ostream os(ret);
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";
379 if (!config->manifestDependency.empty()) {
380 os << " <dependency>\n"
381 << " <dependentAssembly>\n"
382 << " <assemblyIdentity " << config->manifestDependency << " />\n"
383 << " </dependentAssembly>\n"
384 << " </dependency>\n";
386 os << "</assembly>\n";
387 return os.str();
390 static std::string createManifestXmlWithInternalMt(StringRef defaultXml) {
391 std::unique_ptr<MemoryBuffer> defaultXmlCopy =
392 MemoryBuffer::getMemBufferCopy(defaultXml);
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)));
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)));
407 return std::string(merger.getMergedManifest().get()->getBuffer());
410 static 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();
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");
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);
431 e.add("/nologo");
432 e.add("/out:" + StringRef(user.path));
433 e.run();
435 return std::string(
436 CHECK(MemoryBuffer::getFile(user.path), "could not open " + user.path)
437 .get()
438 ->getBuffer());
441 static std::string createManifestXml() {
442 std::string defaultXml = createDefaultXml();
443 if (config->manifestInput.empty())
444 return defaultXml;
446 if (windows_manifest::isAvailable())
447 return createManifestXmlWithInternalMt(defaultXml);
449 return createManifestXmlWithExternalMt(defaultXml);
452 static std::unique_ptr<WritableMemoryBuffer>
453 createMemoryBufferForManifestRes(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");
463 static 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;
470 static 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);
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);
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);
495 // Create a resource file containing a manifest XML.
496 std::unique_ptr<MemoryBuffer> createManifestRes() {
497 std::string manifest = createManifestXml();
499 std::unique_ptr<WritableMemoryBuffer> res =
500 createMemoryBufferForManifestRes(manifest.size());
502 char *buf = res->getBufferStart();
503 writeResFileHeader(buf);
504 writeResEntryHeader(buf, manifest.size());
506 // Copy the manifest data into the .res file.
507 std::copy(manifest.begin(), manifest.end(), buf);
508 return std::move(res);
511 void 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();
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.
526 Export 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;
533 if (e.name.contains('=')) {
534 StringRef x, y;
535 std::tie(x, y) = e.name.split("=");
537 // If "<name>=<dllname>.<name>".
538 if (y.contains(".")) {
539 e.name = x;
540 e.forwardTo = y;
541 return e;
544 e.extName = x;
545 e.name = y;
546 if (e.name.empty())
547 goto err;
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;
560 if (tok.equals_lower("data")) {
561 e.data = true;
562 continue;
564 if (tok.equals_lower("constant")) {
565 e.constant = true;
566 continue;
568 if (tok.equals_lower("private")) {
569 e.isPrivate = true;
570 continue;
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;
581 goto err;
583 return e;
585 err:
586 fatal("invalid /export: " + arg);
589 static 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;
601 // Convert stdcall/fastcall style symbols into unsuffixed symbols,
602 // with or without a leading underscore. (MinGW specific.)
603 static 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;
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;
621 // Performs error checking on all /export arguments.
622 // It also sets ordinals.
623 void 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);
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);
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);
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;
660 Export *existing = pair.first->second;
661 if (e == *existing || e.name != existing->name)
662 continue;
663 warn("duplicate /export option: " + e.name);
665 config->exports = std::move(v);
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;
674 void assignExportOrdinals() {
675 // Assign unique ordinals if default (= 0).
676 uint16_t max = 0;
677 for (Export &e : config->exports)
678 max = std::max(max, e.ordinal);
679 for (Export &e : config->exports)
680 if (e.ordinal == 0)
681 e.ordinal = ++max;
684 // Parses a string in the form of "key=value" and check
685 // if value matches previous values for the same key.
686 void checkFailIfMismatch(StringRef arg, 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);
700 config->mustMatch[k] = {v, source};
703 // Convert Windows resource files (.res files) to a .obj file.
704 // Does what cvtres.exe does, but in-process and cross-platform.
705 MemoryBufferRef convertResToCOFF(ArrayRef<MemoryBufferRef> mbs,
706 ArrayRef<ObjFile *> objs) {
707 object::WindowsResourceParser parser(/* MinGW */ config->mingw);
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");
716 if (auto ec = parser.parse(rf, duplicates))
717 fatal(toString(std::move(ec)));
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)));
728 if (auto ec = parser.parse(rsf, f->getName(), duplicates))
729 fatal(toString(std::move(ec)));
732 if (config->mingw)
733 parser.cleanUpManifests(duplicates);
735 for (const auto &dupeDiag : duplicates)
736 if (config->forceMultipleRes)
737 warn(dupeDiag);
738 else
739 error(dupeDiag);
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()));
747 MemoryBufferRef mbref = **e;
748 make<std::unique_ptr<MemoryBuffer>>(std::move(*e)); // take ownership
749 return mbref;
752 // Create OptTable
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
759 // Create table mapping all options defined in Options.td
760 static 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
768 COFFOptTable::COFFOptTable() : OptTable(infoTable, true) {}
770 // Set color diagnostics according to --color-diagnostics={auto,always,never}
771 // or --no-color-diagnostics flags.
772 static void handleColorDiagnostics(opt::InputArgList &args) {
773 auto *arg = args.getLastArg(OPT_color_diagnostics, OPT_color_diagnostics_eq,
774 OPT_no_color_diagnostics);
775 if (!arg)
776 return;
777 if (arg->getOption().getID() == OPT_color_diagnostics) {
778 lld::errs().enable_colors(true);
779 } else if (arg->getOption().getID() == OPT_no_color_diagnostics) {
780 lld::errs().enable_colors(false);
781 } else {
782 StringRef s = arg->getValue();
783 if (s == "always")
784 lld::errs().enable_colors(true);
785 else if (s == "never")
786 lld::errs().enable_colors(false);
787 else if (s != "auto")
788 error("unknown option: --color-diagnostics=" + s);
792 static cl::TokenizerCallback getQuotingStyle(opt::InputArgList &args) {
793 if (auto *arg = args.getLastArg(OPT_rsp_quoting)) {
794 StringRef s = arg->getValue();
795 if (s != "windows" && s != "posix")
796 error("invalid response file quoting: " + s);
797 if (s == "windows")
798 return cl::TokenizeWindowsCommandLine;
799 return cl::TokenizeGNUCommandLine;
801 // The COFF linker always defaults to Windows quoting.
802 return cl::TokenizeWindowsCommandLine;
805 // Parses a given list of options.
806 opt::InputArgList ArgParser::parse(ArrayRef<const char *> argv) {
807 // Make InputArgList from string vectors.
808 unsigned missingIndex;
809 unsigned missingCount;
811 // We need to get the quoting style for response files before parsing all
812 // options so we parse here before and ignore all the options but
813 // --rsp-quoting and /lldignoreenv.
814 // (This means --rsp-quoting can't be added through %LINK%.)
815 opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
818 // Expand response files (arguments in the form of @<filename>) and insert
819 // flags from %LINK% and %_LINK_%, and then parse the argument again.
820 SmallVector<const char *, 256> expandedArgv(argv.data(),
821 argv.data() + argv.size());
822 if (!args.hasArg(OPT_lldignoreenv))
823 addLINK(expandedArgv);
824 cl::ExpandResponseFiles(saver, getQuotingStyle(args), expandedArgv);
825 args = table.ParseArgs(makeArrayRef(expandedArgv).drop_front(), missingIndex,
826 missingCount);
828 // Print the real command line if response files are expanded.
829 if (args.hasArg(OPT_verbose) && argv.size() != expandedArgv.size()) {
830 std::string msg = "Command line:";
831 for (const char *s : expandedArgv)
832 msg += " " + std::string(s);
833 message(msg);
836 // Save the command line after response file expansion so we can write it to
837 // the PDB if necessary.
838 config->argv = {expandedArgv.begin(), expandedArgv.end()};
840 // Handle /WX early since it converts missing argument warnings to errors.
841 errorHandler().fatalWarnings = args.hasFlag(OPT_WX, OPT_WX_no, false);
843 if (missingCount)
844 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
846 handleColorDiagnostics(args);
848 for (auto *arg : args.filtered(OPT_UNKNOWN)) {
849 std::string nearest;
850 if (table.findNearest(arg->getAsString(args), nearest) > 1)
851 warn("ignoring unknown argument '" + arg->getAsString(args) + "'");
852 else
853 warn("ignoring unknown argument '" + arg->getAsString(args) +
854 "', did you mean '" + nearest + "'");
857 if (args.hasArg(OPT_lib))
858 warn("ignoring /lib since it's not the first argument");
860 return args;
863 // Tokenizes and parses a given string as command line in .drective section.
864 // /EXPORT options are processed in fastpath.
865 std::pair<opt::InputArgList, std::vector<StringRef>>
866 ArgParser::parseDirectives(StringRef s) {
867 std::vector<StringRef> exports;
868 SmallVector<const char *, 16> rest;
870 for (StringRef tok : tokenize(s)) {
871 if (tok.startswith_lower("/export:") || tok.startswith_lower("-export:"))
872 exports.push_back(tok.substr(strlen("/export:")));
873 else
874 rest.push_back(tok.data());
877 // Make InputArgList from unparsed string vectors.
878 unsigned missingIndex;
879 unsigned missingCount;
881 opt::InputArgList args = table.ParseArgs(rest, missingIndex, missingCount);
883 if (missingCount)
884 fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
885 for (auto *arg : args.filtered(OPT_UNKNOWN))
886 warn("ignoring unknown argument: " + arg->getAsString(args));
887 return {std::move(args), std::move(exports)};
890 // link.exe has an interesting feature. If LINK or _LINK_ environment
891 // variables exist, their contents are handled as command line strings.
892 // So you can pass extra arguments using them.
893 void ArgParser::addLINK(SmallVector<const char *, 256> &argv) {
894 // Concatenate LINK env and command line arguments, and then parse them.
895 if (Optional<std::string> s = Process::GetEnv("LINK")) {
896 std::vector<const char *> v = tokenize(*s);
897 argv.insert(std::next(argv.begin()), v.begin(), v.end());
899 if (Optional<std::string> s = Process::GetEnv("_LINK_")) {
900 std::vector<const char *> v = tokenize(*s);
901 argv.insert(std::next(argv.begin()), v.begin(), v.end());
905 std::vector<const char *> ArgParser::tokenize(StringRef s) {
906 SmallVector<const char *, 16> tokens;
907 cl::TokenizeWindowsCommandLine(s, saver, tokens);
908 return std::vector<const char *>(tokens.begin(), tokens.end());
911 void printHelp(const char *argv0) {
912 COFFOptTable().PrintHelp(lld::outs(),
913 (std::string(argv0) + " [options] file...").c_str(),
914 "LLVM Linker", false);
917 } // namespace coff
918 } // namespace lld