1 //===- DriverUtils.cpp ----------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file contains utility functions for the driver. Because there
11 // are so many small functions, we created this separate file to make
12 // Driver.cpp less cluttered.
14 //===----------------------------------------------------------------------===//
21 #include "llvm/ADT/Optional.h"
22 #include "llvm/ADT/StringSwitch.h"
23 #include "llvm/BinaryFormat/COFF.h"
24 #include "llvm/Object/COFF.h"
25 #include "llvm/Object/WindowsResource.h"
26 #include "llvm/Option/Arg.h"
27 #include "llvm/Option/ArgList.h"
28 #include "llvm/Option/Option.h"
29 #include "llvm/Support/CommandLine.h"
30 #include "llvm/Support/FileUtilities.h"
31 #include "llvm/Support/MathExtras.h"
32 #include "llvm/Support/Process.h"
33 #include "llvm/Support/Program.h"
34 #include "llvm/Support/raw_ostream.h"
37 using namespace llvm::COFF;
39 using llvm::cl::ExpandResponseFiles;
40 using llvm::cl::TokenizeWindowsCommandLine;
41 using llvm::sys::Process;
47 const uint16_t SUBLANG_ENGLISH_US = 0x0409;
48 const uint16_t RT_MANIFEST = 24;
52 explicit Executor(StringRef S) : Prog(Saver.save(S)) {}
53 void add(StringRef S) { Args.push_back(Saver.save(S)); }
54 void add(std::string &S) { Args.push_back(Saver.save(S)); }
55 void add(Twine S) { Args.push_back(Saver.save(S)); }
56 void add(const char *S) { Args.push_back(Saver.save(S)); }
59 ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
60 if (auto EC = ExeOrErr.getError())
61 fatal(EC, "unable to find " + Prog + " in PATH: ");
62 StringRef Exe = Saver.save(*ExeOrErr);
63 Args.insert(Args.begin(), Exe);
65 std::vector<const char *> Vec;
66 for (StringRef S : Args)
67 Vec.push_back(S.data());
68 Vec.push_back(nullptr);
70 if (sys::ExecuteAndWait(Args[0], Vec.data()) != 0)
71 fatal("ExecuteAndWait failed: " +
72 llvm::join(Args.begin(), Args.end(), " "));
77 std::vector<StringRef> Args;
80 } // anonymous namespace
82 // Returns /machine's value.
83 MachineTypes getMachineType(StringRef S) {
84 MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
85 .Cases("x64", "amd64", AMD64)
86 .Cases("x86", "i386", I386)
88 .Default(IMAGE_FILE_MACHINE_UNKNOWN);
89 if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
91 fatal("unknown /machine argument: " + S);
94 StringRef machineToStr(MachineTypes MT) {
103 llvm_unreachable("unknown machine type");
107 // Parses a string in the form of "<integer>[,<integer>]".
108 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
110 std::tie(S1, S2) = Arg.split(',');
111 if (S1.getAsInteger(0, *Addr))
112 fatal("invalid number: " + S1);
113 if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
114 fatal("invalid number: " + S2);
117 // Parses a string in the form of "<integer>[.<integer>]".
118 // If second number is not present, Minor is set to 0.
119 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
121 std::tie(S1, S2) = Arg.split('.');
122 if (S1.getAsInteger(0, *Major))
123 fatal("invalid number: " + S1);
125 if (!S2.empty() && S2.getAsInteger(0, *Minor))
126 fatal("invalid number: " + S2);
129 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
130 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
132 StringRef SysStr, Ver;
133 std::tie(SysStr, Ver) = Arg.split(',');
134 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
135 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
136 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
137 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
138 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
139 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
140 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
141 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
142 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
143 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
144 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
145 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
146 fatal("unknown subsystem: " + SysStr);
148 parseVersion(Ver, Major, Minor);
151 // Parse a string of the form of "<from>=<to>".
152 // Results are directly written to Config.
153 void parseAlternateName(StringRef S) {
155 std::tie(From, To) = S.split('=');
156 if (From.empty() || To.empty())
157 fatal("/alternatename: invalid argument: " + S);
158 auto It = Config->AlternateNames.find(From);
159 if (It != Config->AlternateNames.end() && It->second != To)
160 fatal("/alternatename: conflicts: " + S);
161 Config->AlternateNames.insert(It, std::make_pair(From, To));
164 // Parse a string of the form of "<from>=<to>".
165 // Results are directly written to Config.
166 void parseMerge(StringRef S) {
168 std::tie(From, To) = S.split('=');
169 if (From.empty() || To.empty())
170 fatal("/merge: invalid argument: " + S);
171 auto Pair = Config->Merge.insert(std::make_pair(From, To));
172 bool Inserted = Pair.second;
174 StringRef Existing = Pair.first->second;
176 warn(S + ": already merged into " + Existing);
180 static uint32_t parseSectionAttributes(StringRef S) {
182 for (char C : S.lower()) {
185 Ret |= IMAGE_SCN_MEM_DISCARDABLE;
188 Ret |= IMAGE_SCN_MEM_EXECUTE;
191 Ret |= IMAGE_SCN_MEM_NOT_CACHED;
194 Ret |= IMAGE_SCN_MEM_NOT_PAGED;
197 Ret |= IMAGE_SCN_MEM_READ;
200 Ret |= IMAGE_SCN_MEM_SHARED;
203 Ret |= IMAGE_SCN_MEM_WRITE;
206 fatal("/section: invalid argument: " + S);
212 // Parses /section option argument.
213 void parseSection(StringRef S) {
214 StringRef Name, Attrs;
215 std::tie(Name, Attrs) = S.split(',');
216 if (Name.empty() || Attrs.empty())
217 fatal("/section: invalid argument: " + S);
218 Config->Section[Name] = parseSectionAttributes(Attrs);
221 // Parses a string in the form of "EMBED[,=<integer>]|NO".
222 // Results are directly written to Config.
223 void parseManifest(StringRef Arg) {
224 if (Arg.equals_lower("no")) {
225 Config->Manifest = Configuration::No;
228 if (!Arg.startswith_lower("embed"))
229 fatal("invalid option " + Arg);
230 Config->Manifest = Configuration::Embed;
231 Arg = Arg.substr(strlen("embed"));
234 if (!Arg.startswith_lower(",id="))
235 fatal("invalid option " + Arg);
236 Arg = Arg.substr(strlen(",id="));
237 if (Arg.getAsInteger(0, Config->ManifestID))
238 fatal("invalid option " + Arg);
241 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
242 // Results are directly written to Config.
243 void parseManifestUAC(StringRef Arg) {
244 if (Arg.equals_lower("no")) {
245 Config->ManifestUAC = false;
252 if (Arg.startswith_lower("level=")) {
253 Arg = Arg.substr(strlen("level="));
254 std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
257 if (Arg.startswith_lower("uiaccess=")) {
258 Arg = Arg.substr(strlen("uiaccess="));
259 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
262 fatal("invalid option " + Arg);
266 // An RAII temporary file class that automatically removes a temporary file.
268 class TemporaryFile {
270 TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") {
272 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
273 fatal(EC, "cannot create a temporary file");
276 if (!Contents.empty()) {
278 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
280 fatal(EC, "failed to open " + Path);
285 TemporaryFile(TemporaryFile &&Obj) {
286 std::swap(Path, Obj.Path);
292 if (sys::fs::remove(Path))
293 fatal("failed to remove " + Path);
296 // Returns a memory buffer of this temporary file.
297 // Note that this function does not leave the file open,
298 // so it is safe to remove the file immediately after this function
299 // is called (you cannot remove an opened file on Windows.)
300 std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
301 // IsVolatileSize=true forces MemoryBuffer to not use mmap().
302 return check(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
303 /*RequiresNullTerminator=*/false,
304 /*IsVolatileSize=*/true),
305 "could not open " + Path);
312 // Create the default manifest file as a temporary file.
313 TemporaryFile createDefaultXml() {
314 // Create a temporary file.
315 TemporaryFile File("defaultxml", "manifest");
317 // Open the temporary file for writing.
319 raw_fd_ostream OS(File.Path, EC, sys::fs::F_Text);
321 fatal(EC, "failed to open " + File.Path);
323 // Emit the XML. Note that we do *not* verify that the XML attributes are
324 // syntactically correct. This is intentional for link.exe compatibility.
325 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
326 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
327 << " manifestVersion=\"1.0\">\n";
328 if (Config->ManifestUAC) {
329 OS << " <trustInfo>\n"
331 << " <requestedPrivileges>\n"
332 << " <requestedExecutionLevel level=" << Config->ManifestLevel
333 << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
334 << " </requestedPrivileges>\n"
336 << " </trustInfo>\n";
337 if (!Config->ManifestDependency.empty()) {
338 OS << " <dependency>\n"
339 << " <dependentAssembly>\n"
340 << " <assemblyIdentity " << Config->ManifestDependency << " />\n"
341 << " </dependentAssembly>\n"
342 << " </dependency>\n";
345 OS << "</assembly>\n";
350 static std::string readFile(StringRef Path) {
351 std::unique_ptr<MemoryBuffer> MB =
352 check(MemoryBuffer::getFile(Path), "could not open " + Path);
353 return MB->getBuffer();
356 static std::string createManifestXml() {
357 // Create the default manifest file.
358 TemporaryFile File1 = createDefaultXml();
359 if (Config->ManifestInput.empty())
360 return readFile(File1.Path);
362 // If manifest files are supplied by the user using /MANIFESTINPUT
363 // option, we need to merge them with the default manifest.
364 TemporaryFile File2("user", "manifest");
366 Executor E("mt.exe");
369 for (StringRef Filename : Config->ManifestInput) {
374 E.add("/out:" + StringRef(File2.Path));
376 return readFile(File2.Path);
379 static std::unique_ptr<MemoryBuffer>
380 createMemoryBufferForManifestRes(size_t ManifestSize) {
381 size_t ResSize = alignTo(object::WIN_RES_MAGIC_SIZE +
382 object::WIN_RES_NULL_ENTRY_SIZE +
383 sizeof(object::WinResHeaderPrefix) +
384 sizeof(object::WinResIDs) +
385 sizeof(object::WinResHeaderSuffix) +
387 object::WIN_RES_DATA_ALIGNMENT);
388 return MemoryBuffer::getNewMemBuffer(ResSize);
391 static void writeResFileHeader(char *&Buf) {
392 memcpy(Buf, COFF::WinResMagic, sizeof(COFF::WinResMagic));
393 Buf += sizeof(COFF::WinResMagic);
394 memset(Buf, 0, object::WIN_RES_NULL_ENTRY_SIZE);
395 Buf += object::WIN_RES_NULL_ENTRY_SIZE;
398 static void writeResEntryHeader(char *&Buf, size_t ManifestSize) {
400 auto *Prefix = reinterpret_cast<object::WinResHeaderPrefix *>(Buf);
401 Prefix->DataSize = ManifestSize;
402 Prefix->HeaderSize = sizeof(object::WinResHeaderPrefix) +
403 sizeof(object::WinResIDs) +
404 sizeof(object::WinResHeaderSuffix);
405 Buf += sizeof(object::WinResHeaderPrefix);
407 // Write the Type/Name IDs.
408 auto *IDs = reinterpret_cast<object::WinResIDs *>(Buf);
409 IDs->setType(RT_MANIFEST);
410 IDs->setName(Config->ManifestID);
411 Buf += sizeof(object::WinResIDs);
414 auto *Suffix = reinterpret_cast<object::WinResHeaderSuffix *>(Buf);
415 Suffix->DataVersion = 0;
416 Suffix->MemoryFlags = object::WIN_RES_PURE_MOVEABLE;
417 Suffix->Language = SUBLANG_ENGLISH_US;
419 Suffix->Characteristics = 0;
420 Buf += sizeof(object::WinResHeaderSuffix);
423 // Create a resource file containing a manifest XML.
424 std::unique_ptr<MemoryBuffer> createManifestRes() {
425 std::string Manifest = createManifestXml();
427 std::unique_ptr<MemoryBuffer> Res =
428 createMemoryBufferForManifestRes(Manifest.size());
430 char *Buf = const_cast<char *>(Res->getBufferStart());
431 writeResFileHeader(Buf);
432 writeResEntryHeader(Buf, Manifest.size());
434 // Copy the manifest data into the .res file.
435 std::copy(Manifest.begin(), Manifest.end(), Buf);
439 void createSideBySideManifest() {
440 std::string Path = Config->ManifestFile;
442 Path = Config->OutputFile + ".manifest";
444 raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
446 fatal(EC, "failed to create manifest");
447 Out << createManifestXml();
450 // Parse a string in the form of
451 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
452 // or "<name>=<dllname>.<name>".
453 // Used for parsing /export arguments.
454 Export parseExport(StringRef Arg) {
457 std::tie(E.Name, Rest) = Arg.split(",");
461 if (E.Name.find('=') != StringRef::npos) {
463 std::tie(X, Y) = E.Name.split("=");
465 // If "<name>=<dllname>.<name>".
466 if (Y.find(".") != StringRef::npos) {
478 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
479 while (!Rest.empty()) {
481 std::tie(Tok, Rest) = Rest.split(",");
482 if (Tok.equals_lower("noname")) {
488 if (Tok.equals_lower("data")) {
492 if (Tok.equals_lower("constant")) {
496 if (Tok.equals_lower("private")) {
500 if (Tok.startswith("@")) {
502 if (Tok.substr(1).getAsInteger(0, Ord))
504 if (Ord <= 0 || 65535 < Ord)
514 fatal("invalid /export: " + Arg);
517 static StringRef undecorate(StringRef Sym) {
518 if (Config->Machine != I386)
520 return Sym.startswith("_") ? Sym.substr(1) : Sym;
523 // Performs error checking on all /export arguments.
524 // It also sets ordinals.
525 void fixupExports() {
526 // Symbol ordinals must be unique.
527 std::set<uint16_t> Ords;
528 for (Export &E : Config->Exports) {
531 if (!Ords.insert(E.Ordinal).second)
532 fatal("duplicate export ordinal: " + E.Name);
535 for (Export &E : Config->Exports) {
536 SymbolBody *Sym = E.Sym;
537 if (!E.ForwardTo.empty() || !Sym) {
538 E.SymbolName = E.Name;
540 if (auto *U = dyn_cast<Undefined>(Sym))
543 E.SymbolName = Sym->getName();
547 for (Export &E : Config->Exports) {
548 if (!E.ForwardTo.empty()) {
549 E.ExportName = undecorate(E.Name);
551 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
556 std::map<StringRef, Export *> Map;
557 std::vector<Export> V;
558 for (Export &E : Config->Exports) {
559 auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
560 bool Inserted = Pair.second;
565 Export *Existing = Pair.first->second;
566 if (E == *Existing || E.Name != Existing->Name)
568 warn("duplicate /export option: " + E.Name);
570 Config->Exports = std::move(V);
573 std::sort(Config->Exports.begin(), Config->Exports.end(),
574 [](const Export &A, const Export &B) {
575 return A.ExportName < B.ExportName;
579 void assignExportOrdinals() {
580 // Assign unique ordinals if default (= 0).
582 for (Export &E : Config->Exports)
583 Max = std::max(Max, E.Ordinal);
584 for (Export &E : Config->Exports)
589 // Parses a string in the form of "key=value" and check
590 // if value matches previous values for the same key.
591 void checkFailIfMismatch(StringRef Arg) {
593 std::tie(K, V) = Arg.split('=');
594 if (K.empty() || V.empty())
595 fatal("/failifmismatch: invalid argument: " + Arg);
596 StringRef Existing = Config->MustMatch[K];
597 if (!Existing.empty() && V != Existing)
598 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
600 Config->MustMatch[K] = V;
603 // Convert Windows resource files (.res files) to a .obj file
605 std::unique_ptr<MemoryBuffer>
606 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
607 object::WindowsResourceParser Parser;
609 for (MemoryBufferRef MB : MBs) {
610 std::unique_ptr<object::Binary> Bin = check(object::createBinary(MB));
611 object::WindowsResource *RF = dyn_cast<object::WindowsResource>(Bin.get());
613 fatal("cannot compile non-resource file as resource");
614 if (auto EC = Parser.parse(RF))
615 fatal(EC, "failed to parse .res file");
618 Expected<std::unique_ptr<MemoryBuffer>> E =
619 llvm::object::writeWindowsResourceCOFF(Config->Machine, Parser);
621 fatal(errorToErrorCode(E.takeError()), "failed to write .res to COFF");
622 return std::move(E.get());
625 // Run MSVC link.exe for given in-memory object files.
626 // Command line options are copied from those given to LLD.
627 // This is for the /msvclto option.
628 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
629 // Write the in-memory object files to disk.
630 std::vector<TemporaryFile> Temps;
631 for (StringRef S : Objects) {
632 Temps.emplace_back("lto", "obj", S);
633 Rsp += quote(Temps.back().Path) + "\n";
636 log("link.exe " + Rsp);
638 // Run MSVC link.exe.
639 Temps.emplace_back("lto", "rsp", Rsp);
640 Executor E("link.exe");
641 E.add(Twine("@" + Temps.back().Path));
647 // Create prefix string literals used in Options.td
648 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
649 #include "Options.inc"
652 // Create table mapping all options defined in Options.td
653 static const llvm::opt::OptTable::Info infoTable[] = {
654 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X7, X8, X9, X10, X11, X12) \
655 {X1, X2, X10, X11, OPT_##ID, llvm::opt::Option::KIND##Class, \
656 X9, X8, OPT_##GROUP, OPT_##ALIAS, X7, X12},
657 #include "Options.inc"
661 class COFFOptTable : public llvm::opt::OptTable {
663 COFFOptTable() : OptTable(infoTable, true) {}
666 // Parses a given list of options.
667 opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
668 // First, replace respnose files (@<file>-style options).
669 std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
671 // Make InputArgList from string vectors.
673 unsigned MissingIndex;
674 unsigned MissingCount;
675 opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
677 // Print the real command line if response files are expanded.
678 if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
679 std::string Msg = "Command line:";
680 for (const char *S : Argv)
681 Msg += " " + std::string(S);
686 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
687 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
688 warn("ignoring unknown argument: " + Arg->getSpelling());
692 // link.exe has an interesting feature. If LINK or _LINK_ environment
693 // variables exist, their contents are handled as command line strings.
694 // So you can pass extra arguments using them.
695 opt::InputArgList ArgParser::parseLINK(std::vector<const char *> Args) {
696 // Concatenate LINK env and command line arguments, and then parse them.
697 if (Optional<std::string> S = Process::GetEnv("LINK")) {
698 std::vector<const char *> V = tokenize(*S);
699 Args.insert(Args.begin(), V.begin(), V.end());
701 if (Optional<std::string> S = Process::GetEnv("_LINK_")) {
702 std::vector<const char *> V = tokenize(*S);
703 Args.insert(Args.begin(), V.begin(), V.end());
708 std::vector<const char *> ArgParser::tokenize(StringRef S) {
709 SmallVector<const char *, 16> Tokens;
710 cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
711 return std::vector<const char *>(Tokens.begin(), Tokens.end());
714 // Creates a new command line by replacing options starting with '@'
715 // character. '@<filename>' is replaced by the file's contents.
716 std::vector<const char *>
717 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
718 SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
719 ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
720 return std::vector<const char *>(Tokens.begin(), Tokens.end());
723 void printHelp(const char *Argv0) {
725 Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);