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).data()); }
48 void add(std::string &S) { Args.push_back(Saver.save(S).data()); }
49 void add(Twine S) { Args.push_back(Saver.save(S).data()); }
50 void add(const char *S) { Args.push_back(Saver.save(S).data()); }
53 ErrorOr<std::string> ExeOrErr = sys::findProgramByName(Prog);
54 if (auto EC = ExeOrErr.getError())
55 fatal(EC, "unable to find " + Prog + " in PATH: ");
56 const char *Exe = Saver.save(*ExeOrErr).data();
57 Args.insert(Args.begin(), Exe);
58 Args.push_back(nullptr);
59 if (sys::ExecuteAndWait(Args[0], Args.data()) != 0) {
60 for (const char *S : Args)
63 fatal("ExecuteAndWait failed");
68 BumpPtrAllocator Alloc;
71 std::vector<const char *> Args;
74 } // anonymous namespace
76 // Returns /machine's value.
77 MachineTypes getMachineType(StringRef S) {
78 MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
79 .Cases("x64", "amd64", AMD64)
80 .Cases("x86", "i386", I386)
82 .Default(IMAGE_FILE_MACHINE_UNKNOWN);
83 if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
85 fatal("unknown /machine argument: " + S);
88 StringRef machineToStr(MachineTypes MT) {
97 llvm_unreachable("unknown machine type");
101 // Parses a string in the form of "<integer>[,<integer>]".
102 void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
104 std::tie(S1, S2) = Arg.split(',');
105 if (S1.getAsInteger(0, *Addr))
106 fatal("invalid number: " + S1);
107 if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
108 fatal("invalid number: " + S2);
111 // Parses a string in the form of "<integer>[.<integer>]".
112 // If second number is not present, Minor is set to 0.
113 void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
115 std::tie(S1, S2) = Arg.split('.');
116 if (S1.getAsInteger(0, *Major))
117 fatal("invalid number: " + S1);
119 if (!S2.empty() && S2.getAsInteger(0, *Minor))
120 fatal("invalid number: " + S2);
123 // Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
124 void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
126 StringRef SysStr, Ver;
127 std::tie(SysStr, Ver) = Arg.split(',');
128 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
129 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
130 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
131 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
132 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
133 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
134 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
135 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
136 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
137 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
138 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
139 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
140 fatal("unknown subsystem: " + SysStr);
142 parseVersion(Ver, Major, Minor);
145 // Parse a string of the form of "<from>=<to>".
146 // Results are directly written to Config.
147 void parseAlternateName(StringRef S) {
149 std::tie(From, To) = S.split('=');
150 if (From.empty() || To.empty())
151 fatal("/alternatename: invalid argument: " + S);
152 auto It = Config->AlternateNames.find(From);
153 if (It != Config->AlternateNames.end() && It->second != To)
154 fatal("/alternatename: conflicts: " + S);
155 Config->AlternateNames.insert(It, std::make_pair(From, To));
158 // Parse a string of the form of "<from>=<to>".
159 // Results are directly written to Config.
160 void parseMerge(StringRef S) {
162 std::tie(From, To) = S.split('=');
163 if (From.empty() || To.empty())
164 fatal("/merge: invalid argument: " + S);
165 auto Pair = Config->Merge.insert(std::make_pair(From, To));
166 bool Inserted = Pair.second;
168 StringRef Existing = Pair.first->second;
170 errs() << "warning: " << S << ": already merged into " << Existing
175 static uint32_t parseSectionAttributes(StringRef S) {
177 for (char C : S.lower()) {
180 Ret |= IMAGE_SCN_MEM_DISCARDABLE;
183 Ret |= IMAGE_SCN_MEM_EXECUTE;
186 Ret |= IMAGE_SCN_MEM_NOT_CACHED;
189 Ret |= IMAGE_SCN_MEM_NOT_PAGED;
192 Ret |= IMAGE_SCN_MEM_READ;
195 Ret |= IMAGE_SCN_MEM_SHARED;
198 Ret |= IMAGE_SCN_MEM_WRITE;
201 fatal("/section: invalid argument: " + S);
207 // Parses /section option argument.
208 void parseSection(StringRef S) {
209 StringRef Name, Attrs;
210 std::tie(Name, Attrs) = S.split(',');
211 if (Name.empty() || Attrs.empty())
212 fatal("/section: invalid argument: " + S);
213 Config->Section[Name] = parseSectionAttributes(Attrs);
216 // Parses a string in the form of "EMBED[,=<integer>]|NO".
217 // Results are directly written to Config.
218 void parseManifest(StringRef Arg) {
219 if (Arg.equals_lower("no")) {
220 Config->Manifest = Configuration::No;
223 if (!Arg.startswith_lower("embed"))
224 fatal("invalid option " + Arg);
225 Config->Manifest = Configuration::Embed;
226 Arg = Arg.substr(strlen("embed"));
229 if (!Arg.startswith_lower(",id="))
230 fatal("invalid option " + Arg);
231 Arg = Arg.substr(strlen(",id="));
232 if (Arg.getAsInteger(0, Config->ManifestID))
233 fatal("invalid option " + Arg);
236 // Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
237 // Results are directly written to Config.
238 void parseManifestUAC(StringRef Arg) {
239 if (Arg.equals_lower("no")) {
240 Config->ManifestUAC = false;
247 if (Arg.startswith_lower("level=")) {
248 Arg = Arg.substr(strlen("level="));
249 std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
252 if (Arg.startswith_lower("uiaccess=")) {
253 Arg = Arg.substr(strlen("uiaccess="));
254 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
257 fatal("invalid option " + Arg);
261 // Quote each line with "". Existing double-quote is converted
262 // to two double-quotes.
263 static void quoteAndPrint(raw_ostream &Out, StringRef S) {
266 std::tie(Line, S) = S.split("\n");
270 for (int I = 0, E = Line.size(); I != E; ++I) {
271 if (Line[I] == '\"') {
281 // An RAII temporary file class that automatically removes a temporary file.
283 class TemporaryFile {
285 TemporaryFile(StringRef Prefix, StringRef Extn) {
287 if (auto EC = sys::fs::createTemporaryFile("lld-" + Prefix, Extn, S))
288 fatal(EC, "cannot create a temporary file");
292 TemporaryFile(TemporaryFile &&Obj) {
293 std::swap(Path, Obj.Path);
299 if (sys::fs::remove(Path))
300 fatal("failed to remove " + Path);
303 // Returns a memory buffer of this temporary file.
304 // Note that this function does not leave the file open,
305 // so it is safe to remove the file immediately after this function
306 // is called (you cannot remove an opened file on Windows.)
307 std::unique_ptr<MemoryBuffer> getMemoryBuffer() {
308 // IsVolatileSize=true forces MemoryBuffer to not use mmap().
309 return check(MemoryBuffer::getFile(Path, /*FileSize=*/-1,
310 /*RequiresNullTerminator=*/false,
311 /*IsVolatileSize=*/true),
312 "could not open " + Path);
319 // Create the default manifest file as a temporary file.
320 TemporaryFile createDefaultXml() {
321 // Create a temporary file.
322 TemporaryFile File("defaultxml", "manifest");
324 // Open the temporary file for writing.
326 raw_fd_ostream OS(File.Path, EC, sys::fs::F_Text);
328 fatal(EC, "failed to open " + File.Path);
330 // Emit the XML. Note that we do *not* verify that the XML attributes are
331 // syntactically correct. This is intentional for link.exe compatibility.
332 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
333 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
334 << " manifestVersion=\"1.0\">\n";
335 if (Config->ManifestUAC) {
336 OS << " <trustInfo>\n"
338 << " <requestedPrivileges>\n"
339 << " <requestedExecutionLevel level=" << Config->ManifestLevel
340 << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
341 << " </requestedPrivileges>\n"
343 << " </trustInfo>\n";
344 if (!Config->ManifestDependency.empty()) {
345 OS << " <dependency>\n"
346 << " <dependentAssembly>\n"
347 << " <assemblyIdentity " << Config->ManifestDependency << " />\n"
348 << " </dependentAssembly>\n"
349 << " </dependency>\n";
352 OS << "</assembly>\n";
357 static std::string readFile(StringRef Path) {
358 std::unique_ptr<MemoryBuffer> MB =
359 check(MemoryBuffer::getFile(Path), "could not open " + Path);
360 return MB->getBuffer();
363 static std::string createManifestXml() {
364 // Create the default manifest file.
365 TemporaryFile File1 = createDefaultXml();
366 if (Config->ManifestInput.empty())
367 return readFile(File1.Path);
369 // If manifest files are supplied by the user using /MANIFESTINPUT
370 // option, we need to merge them with the default manifest.
371 TemporaryFile File2("user", "manifest");
373 Executor E("mt.exe");
376 for (StringRef Filename : Config->ManifestInput) {
381 E.add("/out:" + StringRef(File2.Path));
383 return readFile(File2.Path);
386 // Create a resource file containing a manifest XML.
387 std::unique_ptr<MemoryBuffer> createManifestRes() {
388 // Create a temporary file for the resource script file.
389 TemporaryFile RCFile("manifest", "rc");
391 // Open the temporary file for writing.
393 raw_fd_ostream Out(RCFile.Path, EC, sys::fs::F_Text);
395 fatal(EC, "failed to open " + RCFile.Path);
397 // Write resource script to the RC file.
398 Out << "#define LANG_ENGLISH 9\n"
399 << "#define SUBLANG_DEFAULT 1\n"
400 << "#define APP_MANIFEST " << Config->ManifestID << "\n"
401 << "#define RT_MANIFEST 24\n"
402 << "LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT\n"
403 << "APP_MANIFEST RT_MANIFEST {\n";
404 quoteAndPrint(Out, createManifestXml());
408 // Create output resource file.
409 TemporaryFile ResFile("output-resource", "res");
411 Executor E("rc.exe");
417 return ResFile.getMemoryBuffer();
420 void createSideBySideManifest() {
421 std::string Path = Config->ManifestFile;
423 Path = Config->OutputFile + ".manifest";
425 raw_fd_ostream Out(Path, EC, sys::fs::F_Text);
427 fatal(EC, "failed to create manifest");
428 Out << createManifestXml();
431 // Parse a string in the form of
432 // "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
433 // or "<name>=<dllname>.<name>".
434 // Used for parsing /export arguments.
435 Export parseExport(StringRef Arg) {
438 std::tie(E.Name, Rest) = Arg.split(",");
442 if (E.Name.find('=') != StringRef::npos) {
444 std::tie(X, Y) = E.Name.split("=");
446 // If "<name>=<dllname>.<name>".
447 if (Y.find(".") != StringRef::npos) {
459 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
460 while (!Rest.empty()) {
462 std::tie(Tok, Rest) = Rest.split(",");
463 if (Tok.equals_lower("noname")) {
469 if (Tok.equals_lower("data")) {
473 if (Tok.equals_lower("private")) {
477 if (Tok.startswith("@")) {
479 if (Tok.substr(1).getAsInteger(0, Ord))
481 if (Ord <= 0 || 65535 < Ord)
491 fatal("invalid /export: " + Arg);
494 static StringRef undecorate(StringRef Sym) {
495 if (Config->Machine != I386)
497 return Sym.startswith("_") ? Sym.substr(1) : Sym;
500 // Performs error checking on all /export arguments.
501 // It also sets ordinals.
502 void fixupExports() {
503 // Symbol ordinals must be unique.
504 std::set<uint16_t> Ords;
505 for (Export &E : Config->Exports) {
508 if (!Ords.insert(E.Ordinal).second)
509 fatal("duplicate export ordinal: " + E.Name);
512 for (Export &E : Config->Exports) {
513 SymbolBody *Sym = E.Sym;
514 if (!E.ForwardTo.empty()) {
515 E.SymbolName = E.Name;
517 if (auto *U = dyn_cast<Undefined>(Sym))
520 E.SymbolName = Sym->getName();
524 for (Export &E : Config->Exports) {
525 if (!E.ForwardTo.empty()) {
526 E.ExportName = undecorate(E.Name);
528 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
533 std::map<StringRef, Export *> Map;
534 std::vector<Export> V;
535 for (Export &E : Config->Exports) {
536 auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
537 bool Inserted = Pair.second;
542 Export *Existing = Pair.first->second;
543 if (E == *Existing || E.Name != Existing->Name)
545 errs() << "warning: duplicate /export option: " << E.Name << "\n";
547 Config->Exports = std::move(V);
550 std::sort(Config->Exports.begin(), Config->Exports.end(),
551 [](const Export &A, const Export &B) {
552 return A.ExportName < B.ExportName;
556 void assignExportOrdinals() {
557 // Assign unique ordinals if default (= 0).
559 for (Export &E : Config->Exports)
560 Max = std::max(Max, E.Ordinal);
561 for (Export &E : Config->Exports)
566 // Parses a string in the form of "key=value" and check
567 // if value matches previous values for the same key.
568 void checkFailIfMismatch(StringRef Arg) {
570 std::tie(K, V) = Arg.split('=');
571 if (K.empty() || V.empty())
572 fatal("/failifmismatch: invalid argument: " + Arg);
573 StringRef Existing = Config->MustMatch[K];
574 if (!Existing.empty() && V != Existing)
575 fatal("/failifmismatch: mismatch detected: " + Existing + " and " + V +
577 Config->MustMatch[K] = V;
580 // Convert Windows resource files (.res files) to a .obj file
582 std::unique_ptr<MemoryBuffer>
583 convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
584 // Create an output file path.
585 TemporaryFile File("resource-file", "obj");
587 // Execute cvtres.exe.
588 Executor E("cvtres.exe");
589 E.add("/machine:" + machineToStr(Config->Machine));
592 E.add("/out:" + Twine(File.Path));
594 // We must create new files because the memory buffers we have may have no
595 // underlying file still existing on the disk.
596 // It happens if it was created from a TemporaryFile, which usually delete
597 // the file just after creating the MemoryBuffer.
598 std::vector<TemporaryFile> ResFiles;
599 ResFiles.reserve(MBs.size());
600 for (MemoryBufferRef MB : MBs) {
601 // We store the temporary file in a vector to avoid deletion
602 // before running cvtres
603 ResFiles.emplace_back("resource-file", "res");
604 TemporaryFile& ResFile = ResFiles.back();
605 // Write the content of the resource in a temporary file
607 raw_fd_ostream OS(ResFile.Path, EC, sys::fs::F_None);
609 fatal(EC, "failed to open " + ResFile.Path);
610 OS << MB.getBuffer();
617 return File.getMemoryBuffer();
622 // Create prefix string literals used in Options.td
623 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
624 #include "Options.inc"
627 // Create table mapping all options defined in Options.td
628 static const llvm::opt::OptTable::Info infoTable[] = {
629 #define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \
631 X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
632 OPT_##GROUP, OPT_##ALIAS, X6 \
634 #include "Options.inc"
638 class COFFOptTable : public llvm::opt::OptTable {
640 COFFOptTable() : OptTable(infoTable, true) {}
643 // Parses a given list of options.
644 opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
645 // First, replace respnose files (@<file>-style options).
646 std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
648 // Make InputArgList from string vectors.
650 unsigned MissingIndex;
651 unsigned MissingCount;
652 opt::InputArgList Args = Table.ParseArgs(Argv, MissingIndex, MissingCount);
654 // Print the real command line if response files are expanded.
655 if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
656 outs() << "Command line:";
657 for (const char *S : Argv)
663 fatal(Twine(Args.getArgString(MissingIndex)) + ": missing argument");
664 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
665 errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
669 // link.exe has an interesting feature. If LINK environment exists,
670 // its contents are handled as a command line string. So you can pass
671 // extra arguments using the environment variable.
672 opt::InputArgList ArgParser::parseLINK(ArrayRef<const char *> Args) {
673 // Concatenate LINK env and command line arguments, and then parse them.
674 Optional<std::string> Env = Process::GetEnv("LINK");
677 std::vector<const char *> V = tokenize(*Env);
678 V.insert(V.end(), Args.begin(), Args.end());
682 std::vector<const char *> ArgParser::tokenize(StringRef S) {
683 SmallVector<const char *, 16> Tokens;
684 cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
685 return std::vector<const char *>(Tokens.begin(), Tokens.end());
688 // Creates a new command line by replacing options starting with '@'
689 // character. '@<filename>' is replaced by the file's contents.
690 std::vector<const char *>
691 ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
692 SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
693 ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
694 return std::vector<const char *>(Tokens.begin(), Tokens.end());
697 void printHelp(const char *Argv0) {
699 Table.PrintHelp(outs(), Argv0, "LLVM Linker", false);