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/Object/COFF.h"
24 #include "llvm/Option/Arg.h"
25 #include "llvm/Option/ArgList.h"
26 #include "llvm/Option/Option.h"
27 #include "llvm/Support/CommandLine.h"
28 #include "llvm/Support/FileUtilities.h"
29 #include "llvm/Support/Process.h"
30 #include "llvm/Support/Program.h"
31 #include "llvm/Support/raw_ostream.h"
34 using namespace llvm::COFF;
36 using llvm::cl::ExpandResponseFiles;
37 using llvm::cl::TokenizeWindowsCommandLine;
38 using llvm::sys::Process;
46 explicit Executor(StringRef S) : Saver(Alloc), Prog(Saver.save(S)) {}
47 void add(StringRef S) { Args.push_back(Saver.save(S)); }
48 void add(std::string &S) { Args.push_back(Saver.save(S)); }
49 void add(Twine S) { Args.push_back(Saver.save(S)); }
50 void add(const char *S) { Args.push_back(Saver.save(S)); }
53 ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
54 if (auto EC = ExeOrErr.getError())
55 fatal(EC, "unable to find " + Prog + " in PATH: ");
56 StringRef Exe = Saver.save(*ExeOrErr);
57 Args.insert(Args.begin(), Exe);
59 std::vector<const char *> Vec;
60 for (StringRef S : Args)
61 Vec.push_back(S.data());
62 Vec.push_back(nullptr);
64 if (sys::ExecuteAndWait(Args[0], Vec.data()) != 0)
65 fatal("ExecuteAndWait failed: " +
66 llvm::join(Args.begin(), Args.end(), " "));
70 BumpPtrAllocator Alloc;
73 std::vector<StringRef> Args;
76 } // anonymous namespace
78 // Returns /machine's value.
79 MachineTypes getMachineType(StringRef S) {
80 MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
81 .Cases("x64", "amd64", AMD64)
82 .Cases("x86", "i386", I386)
84 .Default(IMAGE_FILE_MACHINE_UNKNOWN);
85 if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
87 fatal("unknown /machine argument: " + S);
90 StringRef machineToStr(MachineTypes MT) {
99 llvm_unreachable("unknown machine type");
103 // Parses a string in the form of "<integer>[,<integer>]".
104 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
106 std::tie(S1, S2) = Arg.split(',');
107 if (S1.getAsInteger(0, *Addr))
108 fatal("invalid number: " + S1);
109 if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
110 fatal("invalid number: " + S2);
113 // Parses a string in the form of "<integer>[.<integer>]".
114 // If second number is not present, Minor is set to 0.
115 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
117 std::tie(S1, S2) = Arg.split('.');
118 if (S1.getAsInteger(0, *Major))
119 fatal("invalid number: " + S1);
121 if (!S2.empty() && S2.getAsInteger(0, *Minor))
122 fatal("invalid number: " + S2);
125 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
126 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
128 StringRef SysStr, Ver;
129 std::tie(SysStr, Ver) = Arg.split(',');
130 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
131 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
132 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
133 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
134 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
135 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
136 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
137 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
138 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
139 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
140 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
141 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
142 fatal("unknown subsystem: " + SysStr);
144 parseVersion(Ver, Major, Minor);
147 // Parse a string of the form of "<from>=<to>".
148 // Results are directly written to Config.
149 void parseAlternateName(StringRef S) {
151 std::tie(From, To) = S.split('=');
152 if (From.empty() || To.empty())
153 fatal("/alternatename: invalid argument: " + S);
154 auto It = Config->AlternateNames.find(From);
155 if (It != Config->AlternateNames.end() && It->second != To)
156 fatal("/alternatename: conflicts: " + S);
157 Config->AlternateNames.insert(It, std::make_pair(From, To));
160 // Parse a string of the form of "<from>=<to>".
161 // Results are directly written to Config.
162 void parseMerge(StringRef S) {
164 std::tie(From, To) = S.split('=');
165 if (From.empty() || To.empty())
166 fatal("/merge: invalid argument: " + S);
167 auto Pair = Config->Merge.insert(std::make_pair(From, To));
168 bool Inserted = Pair.second;
170 StringRef Existing = Pair.first->second;
172 warn(S + ": already merged into " + Existing);
176 static uint32_t parseSectionAttributes(StringRef S) {
178 for (char C : S.lower()) {
181 Ret |= IMAGE_SCN_MEM_DISCARDABLE;
184 Ret |= IMAGE_SCN_MEM_EXECUTE;
187 Ret |= IMAGE_SCN_MEM_NOT_CACHED;
190 Ret |= IMAGE_SCN_MEM_NOT_PAGED;
193 Ret |= IMAGE_SCN_MEM_READ;
196 Ret |= IMAGE_SCN_MEM_SHARED;
199 Ret |= IMAGE_SCN_MEM_WRITE;
202 fatal("/section: invalid argument: " + S);
208 // Parses /section option argument.
209 void parseSection(StringRef S) {
210 StringRef Name, Attrs;
211 std::tie(Name, Attrs) = S.split(',');
212 if (Name.empty() || Attrs.empty())
213 fatal("/section: invalid argument: " + S);
214 Config->Section[Name] = parseSectionAttributes(Attrs);
217 // Parses a string in the form of "EMBED[,=<integer>]|NO".
218 // Results are directly written to Config.
219 void parseManifest(StringRef Arg) {
220 if (Arg.equals_lower("no")) {
221 Config->Manifest = Configuration::No;
224 if (!Arg.startswith_lower("embed"))
225 fatal("invalid option " + Arg);
226 Config->Manifest = Configuration::Embed;
227 Arg = Arg.substr(strlen("embed"));
230 if (!Arg.startswith_lower(",id="))
231 fatal("invalid option " + Arg);
232 Arg = Arg.substr(strlen(",id="));
233 if (Arg.getAsInteger(0, Config->ManifestID))
234 fatal("invalid option " + Arg);
237 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
238 // Results are directly written to Config.
239 void parseManifestUAC(StringRef Arg) {
240 if (Arg.equals_lower("no")) {
241 Config->ManifestUAC = false;
248 if (Arg.startswith_lower("level=")) {
249 Arg = Arg.substr(strlen("level="));
250 std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
253 if (Arg.startswith_lower("uiaccess=")) {
254 Arg = Arg.substr(strlen("uiaccess="));
255 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
258 fatal("invalid option " + Arg);
262 // Quote each line with "". Existing double-quote is converted
263 // to two double-quotes.
264 static void quoteAndPrint(raw_ostream &Out, StringRef S) {
267 std::tie(Line, S) = S.split("\n");
271 for (int I = 0, E = Line.size(); I != E; ++I) {
272 if (Line[I] == '\"') {
282 // An RAII temporary file class that automatically removes a temporary file.
284 class TemporaryFile {
286 TemporaryFile(StringRef Prefix, StringRef Extn, StringRef Contents = "") {
288 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
289 fatal(EC, "cannot create a temporary file");
292 if (!Contents.empty()) {
294 raw_fd_ostream OS(Path, EC, sys::fs::F_None);
296 fatal(EC, "failed to open " + Path);
301 TemporaryFile(TemporaryFile &&Obj) {
302 std::swap(Path, Obj.Path);
308 if (sys::fs::remove(Path))
309 fatal("failed to remove " + Path);
312 // Returns a memory buffer of this temporary file.
313 // Note that this function does not leave the file open,
314 // so it is safe to remove the file immediately after this function
315 // is called (you cannot remove an opened file on Windows.)
316 std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
317 // IsVolatileSize=true forces MemoryBuffer to not use mmap().
318 return check(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
319 /*RequiresNullTerminator=*/false,
320 /*IsVolatileSize=*/true),
321 "could not open " + Path);
328 // Create the default manifest file as a temporary file.
329 TemporaryFile createDefaultXml() {
330 // Create a temporary file.
331 TemporaryFile File("defaultxml", "manifest");
333 // Open the temporary file for writing.
335 raw_fd_ostream OS(File.Path, EC, sys::fs::F_Text);
337 fatal(EC, "failed to open " + File.Path);
339 // Emit the XML. Note that we do *not* verify that the XML attributes are
340 // syntactically correct. This is intentional for link.exe compatibility.
341 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
342 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
343 << " manifestVersion=\"1.0\">\n";
344 if (Config->ManifestUAC) {
345 OS << " <trustInfo>\n"
347 << " <requestedPrivileges>\n"
348 << " <requestedExecutionLevel level=" << Config->ManifestLevel
349 << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
350 << " </requestedPrivileges>\n"
352 << " </trustInfo>\n";
353 if (!Config->ManifestDependency.empty()) {
354 OS << " <dependency>\n"
355 << " <dependentAssembly>\n"
356 << " <assemblyIdentity " << Config->ManifestDependency << " />\n"
357 << " </dependentAssembly>\n"
358 << " </dependency>\n";
361 OS << "</assembly>\n";
366 static std::string readFile(StringRef Path) {
367 std::unique_ptr<MemoryBuffer> MB =
368 check(MemoryBuffer::getFile(Path), "could not open " + Path);
369 return MB->getBuffer();
372 static std::string createManifestXml() {
373 // Create the default manifest file.
374 TemporaryFile File1 = createDefaultXml();
375 if (Config->ManifestInput.empty())
376 return readFile(File1.Path);
378 // If manifest files are supplied by the user using /MANIFESTINPUT
379 // option, we need to merge them with the default manifest.
380 TemporaryFile File2("user", "manifest");
382 Executor E("mt.exe");
385 for (StringRef Filename : Config->ManifestInput) {
390 E.add("/out:" + StringRef(File2.Path));
392 return readFile(File2.Path);
395 // Create a resource file containing a manifest XML.
396 std::unique_ptr<MemoryBuffer> createManifestRes() {
397 // Create a temporary file for the resource script file.
398 TemporaryFile RCFile("manifest", "rc");
400 // Open the temporary file for writing.
402 raw_fd_ostream Out(RCFile.Path, EC, sys::fs::F_Text);
404 fatal(EC, "failed to open " + RCFile.Path);
406 // Write resource script to the RC file.
407 Out << "#define LANG_ENGLISH 9\n"
408 << "#define SUBLANG_DEFAULT 1\n"
409 << "#define APP_MANIFEST " << Config->ManifestID << "\n"
410 << "#define RT_MANIFEST 24\n"
411 << "LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT\n"
412 << "APP_MANIFEST RT_MANIFEST {\n";
413 quoteAndPrint(Out, createManifestXml());
417 // Create output resource file.
418 TemporaryFile ResFile("output-resource", "res");
420 Executor E("rc.exe");
426 return ResFile.getMemoryBuffer();
429 void createSideBySideManifest() {
430 std::string Path = Config->ManifestFile;
432 Path = Config->OutputFile + ".manifest";
434 raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
436 fatal(EC, "failed to create manifest");
437 Out << createManifestXml();
440 // Parse a string in the form of
441 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
442 // or "<name>=<dllname>.<name>".
443 // Used for parsing /export arguments.
444 Export parseExport(StringRef Arg) {
447 std::tie(E.Name, Rest) = Arg.split(",");
451 if (E.Name.find('=') != StringRef::npos) {
453 std::tie(X, Y) = E.Name.split("=");
455 // If "<name>=<dllname>.<name>".
456 if (Y.find(".") != StringRef::npos) {
468 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
469 while (!Rest.empty()) {
471 std::tie(Tok, Rest) = Rest.split(",");
472 if (Tok.equals_lower("noname")) {
478 if (Tok.equals_lower("data")) {
482 if (Tok.equals_lower("private")) {
486 if (Tok.startswith("@")) {
488 if (Tok.substr(1).getAsInteger(0, Ord))
490 if (Ord <= 0 || 65535 < Ord)
500 fatal("invalid /export: " + Arg);
503 static StringRef undecorate(StringRef Sym) {
504 if (Config->Machine != I386)
506 return Sym.startswith("_") ? Sym.substr(1) : Sym;
509 // Performs error checking on all /export arguments.
510 // It also sets ordinals.
511 void fixupExports() {
512 // Symbol ordinals must be unique.
513 std::set<uint16_t> Ords;
514 for (Export &E : Config->Exports) {
517 if (!Ords.insert(E.Ordinal).second)
518 fatal("duplicate export ordinal: " + E.Name);
521 for (Export &E : Config->Exports) {
522 SymbolBody *Sym = E.Sym;
523 if (!E.ForwardTo.empty()) {
524 E.SymbolName = E.Name;
526 if (auto *U = dyn_cast<Undefined>(Sym))
529 E.SymbolName = Sym->getName();
533 for (Export &E : Config->Exports) {
534 if (!E.ForwardTo.empty()) {
535 E.ExportName = undecorate(E.Name);
537 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
542 std::map<StringRef, Export *> Map;
543 std::vector<Export> V;
544 for (Export &E : Config->Exports) {
545 auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
546 bool Inserted = Pair.second;
551 Export *Existing = Pair.first->second;
552 if (E == *Existing || E.Name != Existing->Name)
554 warn("duplicate /export option: " + E.Name);
556 Config->Exports = std::move(V);
559 std::sort(Config->Exports.begin(), Config->Exports.end(),
560 [](const Export &A, const Export &B) {
561 return A.ExportName < B.ExportName;
565 void assignExportOrdinals() {
566 // Assign unique ordinals if default (= 0).
568 for (Export &E : Config->Exports)
569 Max = std::max(Max, E.Ordinal);
570 for (Export &E : Config->Exports)
575 // Parses a string in the form of "key=value" and check
576 // if value matches previous values for the same key.
577 void checkFailIfMismatch(StringRef Arg) {
579 std::tie(K, V) = Arg.split('=');
580 if (K.empty() || V.empty())
581 fatal("/failifmismatch: invalid argument: " + Arg);
582 StringRef Existing = Config->MustMatch[K];
583 if (!Existing.empty() && V != Existing)
584 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
586 Config->MustMatch[K] = V;
589 // Convert Windows resource files (.res files) to a .obj file
591 std::unique_ptr<MemoryBuffer>
592 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
593 // Create an output file path.
594 TemporaryFile File("resource-file", "obj");
596 // Execute cvtres.exe.
597 Executor E("cvtres.exe");
598 E.add("/machine:" + machineToStr(Config->Machine));
601 E.add("/out:" + Twine(File.Path));
603 // We must create new files because the memory buffers we have may have no
604 // underlying file still existing on the disk.
605 // It happens if it was created from a TemporaryFile, which usually delete
606 // the file just after creating the MemoryBuffer.
607 std::vector<TemporaryFile> ResFiles;
608 ResFiles.reserve(MBs.size());
609 for (MemoryBufferRef MB : MBs) {
610 // We store the temporary file in a vector to avoid deletion
611 // before running cvtres
612 ResFiles.emplace_back("resource-file", "res");
613 TemporaryFile& ResFile = ResFiles.back();
614 // Write the content of the resource in a temporary file
616 raw_fd_ostream OS(ResFile.Path, EC, sys::fs::F_None);
618 fatal(EC, "failed to open " + ResFile.Path);
619 OS << MB.getBuffer();
626 return File.getMemoryBuffer();
629 // Run MSVC link.exe for given in-memory object files.
630 // Command line options are copied from those given to LLD.
631 // This is for the /msvclto option.
632 void runMSVCLinker(std::string Rsp, ArrayRef<StringRef> Objects) {
633 // Write the in-memory object files to disk.
634 std::vector<TemporaryFile> Temps;
635 for (StringRef S : Objects) {
636 Temps.emplace_back("lto", "obj", S);
637 Rsp += quote(Temps.back().Path) + " ";
640 log("link.exe " + Rsp);
642 // Run MSVC link.exe.
643 Temps.emplace_back("lto", "rsp", Rsp);
644 Executor E("link.exe");
645 E.add(Twine("@" + Temps.back().Path));
651 // Create prefix string literals used in Options.td
652 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
653 #include "Options.inc"
656 // Create table mapping all options defined in Options.td
657 static const llvm::opt::OptTable::Info infoTable[] = {
658 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \
660 X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
661 OPT_##GROUP, OPT_##ALIAS, X6 \
663 #include "Options.inc"
667 class COFFOptTable : public llvm::opt::OptTable {
669 COFFOptTable() : OptTable(infoTable, true) {}
672 // Parses a given list of options.
673 opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
674 // First, replace respnose files (@<file>-style options).
675 std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
677 // Make InputArgList from string vectors.
679 unsigned MissingIndex;
680 unsigned MissingCount;
681 opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
683 // Print the real command line if response files are expanded.
684 if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
685 std::string Msg = "Command line:";
686 for (const char *S : Argv)
687 Msg += " " + std::string(S);
692 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
693 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
694 warn("ignoring unknown argument: " + Arg->getSpelling());
698 // link.exe has an interesting feature. If LINK environment exists,
699 // its contents are handled as a command line string. So you can pass
700 // extra arguments using the environment variable.
701 opt::InputArgList ArgParser::parseLINK(ArrayRef<const char *> Args) {
702 // Concatenate LINK env and command line arguments, and then parse them.
703 Optional<std::string> Env = Process::GetEnv("LINK");
706 std::vector<const char *> V = tokenize(*Env);
707 V.insert(V.end(), Args.begin(), Args.end());
711 std::vector<const char *> ArgParser::tokenize(StringRef S) {
712 SmallVector<const char *, 16> Tokens;
713 cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
714 return std::vector<const char *>(Tokens.begin(), Tokens.end());
717 // Creates a new command line by replacing options starting with '@'
718 // character. '@<filename>' is replaced by the file's contents.
719 std::vector<const char *>
720 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
721 SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
722 ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
723 return std::vector<const char *>(Tokens.begin(), Tokens.end());
726 void printHelp(const char *Argv0) {
728 Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);