blob: 014fee7fefd76d789eee7d2e18129d0343a97fec [file] [log] [blame]
Rui Ueyama3500f662015-05-28 20:30:06 +00001//===- DriverUtils.cpp ----------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
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.
13//
14//===----------------------------------------------------------------------===//
15
Rui Ueyama8854d8a2015-06-04 19:21:24 +000016#include "Config.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000017#include "Driver.h"
Rui Ueyama8fd9fb92015-06-01 02:58:15 +000018#include "Error.h"
Rui Ueyama8765fba2015-07-15 22:21:08 +000019#include "Symbols.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000020#include "llvm/ADT/Optional.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000021#include "llvm/ADT/StringSwitch.h"
Rui Ueyama40f4d862015-08-28 10:52:05 +000022#include "llvm/Object/Archive.h"
23#include "llvm/Object/ArchiveWriter.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000024#include "llvm/Object/COFF.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"
Rui Ueyama151d8622015-06-17 20:40:43 +000029#include "llvm/Support/FileUtilities.h"
30#include "llvm/Support/Path.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000031#include "llvm/Support/Process.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000032#include "llvm/Support/Program.h"
Rui Ueyama3500f662015-05-28 20:30:06 +000033#include "llvm/Support/raw_ostream.h"
34#include <memory>
35
36using namespace llvm::COFF;
37using namespace llvm;
Rui Ueyamab51f67a2015-06-07 23:00:29 +000038using llvm::cl::ExpandResponseFiles;
39using llvm::cl::TokenizeWindowsCommandLine;
Rui Ueyama3500f662015-05-28 20:30:06 +000040using llvm::sys::Process;
Rui Ueyama3500f662015-05-28 20:30:06 +000041
42namespace lld {
43namespace coff {
Rui Ueyamaa9c88382015-06-17 21:01:56 +000044namespace {
45
46class Executor {
47public:
48 explicit Executor(StringRef S) : Saver(Alloc), Prog(Saver.save(S)) {}
49 void add(StringRef S) { Args.push_back(Saver.save(S)); }
50 void add(std::string &S) { Args.push_back(Saver.save(S)); }
51 void add(Twine S) { Args.push_back(Saver.save(S)); }
52 void add(const char *S) { Args.push_back(Saver.save(S)); }
53
Rafael Espindolab835ae82015-08-06 14:58:50 +000054 void run() {
Rui Ueyamaa9c88382015-06-17 21:01:56 +000055 ErrorOr<std::string> ExeOrErr = llvm::sys::findProgramByName(Prog);
Rafael Espindolab835ae82015-08-06 14:58:50 +000056 error(ExeOrErr, Twine("unable to find ") + Prog + " in PATH: ");
Rui Ueyama04ec69aa2015-08-18 09:18:15 +000057 const char *Exe = Saver.save(*ExeOrErr);
Rui Ueyamaa9c88382015-06-17 21:01:56 +000058 Args.insert(Args.begin(), Exe);
59 Args.push_back(nullptr);
60 if (llvm::sys::ExecuteAndWait(Args[0], Args.data()) != 0) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +000061 for (const char *S : Args)
62 if (S)
63 llvm::errs() << S << " ";
Rafael Espindolab835ae82015-08-06 14:58:50 +000064 error("failed");
Rui Ueyamaa9c88382015-06-17 21:01:56 +000065 }
Rui Ueyamaa9c88382015-06-17 21:01:56 +000066 }
67
68private:
69 llvm::BumpPtrAllocator Alloc;
Rafael Espindolaf0461ba2015-08-13 01:07:08 +000070 llvm::StringSaver Saver;
Rui Ueyamaa9c88382015-06-17 21:01:56 +000071 StringRef Prog;
72 std::vector<const char *> Args;
73};
74
75} // anonymous namespace
Rui Ueyama3500f662015-05-28 20:30:06 +000076
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +000077// Returns /machine's value.
Rafael Espindolab835ae82015-08-06 14:58:50 +000078MachineTypes getMachineType(StringRef S) {
Rui Ueyamae16a75d52015-07-08 18:14:51 +000079 MachineTypes MT = StringSwitch<MachineTypes>(S.lower())
Rui Ueyama5e706b32015-07-25 21:54:50 +000080 .Case("x64", AMD64)
81 .Case("amd64", AMD64)
82 .Case("x86", I386)
83 .Case("i386", I386)
84 .Case("arm", ARMNT)
Rui Ueyamae16a75d52015-07-08 18:14:51 +000085 .Default(IMAGE_FILE_MACHINE_UNKNOWN);
86 if (MT != IMAGE_FILE_MACHINE_UNKNOWN)
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +000087 return MT;
Rafael Espindolab835ae82015-08-06 14:58:50 +000088 error(Twine("unknown /machine argument: ") + S);
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +000089}
90
Rui Ueyama5e706b32015-07-25 21:54:50 +000091StringRef machineToStr(MachineTypes MT) {
Rui Ueyama84936e02015-07-07 23:39:18 +000092 switch (MT) {
Rui Ueyama5e706b32015-07-25 21:54:50 +000093 case ARMNT:
Rui Ueyama84936e02015-07-07 23:39:18 +000094 return "arm";
Rui Ueyama5e706b32015-07-25 21:54:50 +000095 case AMD64:
Rui Ueyama84936e02015-07-07 23:39:18 +000096 return "x64";
Rui Ueyama5e706b32015-07-25 21:54:50 +000097 case I386:
Rui Ueyama84936e02015-07-07 23:39:18 +000098 return "x86";
99 default:
100 llvm_unreachable("unknown machine type");
101 }
102}
103
Rui Ueyama804a8b62015-05-29 16:18:15 +0000104// Parses a string in the form of "<integer>[,<integer>]".
Rafael Espindolab835ae82015-08-06 14:58:50 +0000105void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000106 StringRef S1, S2;
107 std::tie(S1, S2) = Arg.split(',');
Rafael Espindolab835ae82015-08-06 14:58:50 +0000108 if (S1.getAsInteger(0, *Addr))
109 error(Twine("invalid number: ") + S1);
110 if (Size && !S2.empty() && S2.getAsInteger(0, *Size))
111 error(Twine("invalid number: ") + S2);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000112}
113
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000114// Parses a string in the form of "<integer>[.<integer>]".
115// If second number is not present, Minor is set to 0.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000116void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000117 StringRef S1, S2;
118 std::tie(S1, S2) = Arg.split('.');
Rafael Espindolab835ae82015-08-06 14:58:50 +0000119 if (S1.getAsInteger(0, *Major))
120 error(Twine("invalid number: ") + S1);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000121 *Minor = 0;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000122 if (!S2.empty() && S2.getAsInteger(0, *Minor))
123 error(Twine("invalid number: ") + S2);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000124}
125
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000126// Parses a string in the form of "<subsystem>[,<integer>[.<integer>]]".
Rafael Espindolab835ae82015-08-06 14:58:50 +0000127void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major,
128 uint32_t *Minor) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000129 StringRef SysStr, Ver;
130 std::tie(SysStr, Ver) = Arg.split(',');
131 *Sys = StringSwitch<WindowsSubsystem>(SysStr.lower())
132 .Case("boot_application", IMAGE_SUBSYSTEM_WINDOWS_BOOT_APPLICATION)
133 .Case("console", IMAGE_SUBSYSTEM_WINDOWS_CUI)
134 .Case("efi_application", IMAGE_SUBSYSTEM_EFI_APPLICATION)
135 .Case("efi_boot_service_driver", IMAGE_SUBSYSTEM_EFI_BOOT_SERVICE_DRIVER)
136 .Case("efi_rom", IMAGE_SUBSYSTEM_EFI_ROM)
137 .Case("efi_runtime_driver", IMAGE_SUBSYSTEM_EFI_RUNTIME_DRIVER)
138 .Case("native", IMAGE_SUBSYSTEM_NATIVE)
139 .Case("posix", IMAGE_SUBSYSTEM_POSIX_CUI)
140 .Case("windows", IMAGE_SUBSYSTEM_WINDOWS_GUI)
141 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000142 if (*Sys == IMAGE_SUBSYSTEM_UNKNOWN)
143 error(Twine("unknown subsystem: ") + SysStr);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000144 if (!Ver.empty())
Rafael Espindolab835ae82015-08-06 14:58:50 +0000145 parseVersion(Ver, Major, Minor);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000146}
147
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000148// Parse a string of the form of "<from>=<to>".
149// Results are directly written to Config.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000150void parseAlternateName(StringRef S) {
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000151 StringRef From, To;
152 std::tie(From, To) = S.split('=');
Rafael Espindolab835ae82015-08-06 14:58:50 +0000153 if (From.empty() || To.empty())
154 error(Twine("/alternatename: invalid argument: ") + S);
Rui Ueyamae8d56b52015-06-18 23:04:26 +0000155 auto It = Config->AlternateNames.find(From);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000156 if (It != Config->AlternateNames.end() && It->second != To)
157 error(Twine("/alternatename: conflicts: ") + S);
Rui Ueyamae8d56b52015-06-18 23:04:26 +0000158 Config->AlternateNames.insert(It, std::make_pair(From, To));
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000159}
160
Rui Ueyama6600eb12015-07-04 23:37:32 +0000161// Parse a string of the form of "<from>=<to>".
162// Results are directly written to Config.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000163void parseMerge(StringRef S) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000164 StringRef From, To;
165 std::tie(From, To) = S.split('=');
Rafael Espindolab835ae82015-08-06 14:58:50 +0000166 if (From.empty() || To.empty())
167 error(Twine("/merge: invalid argument: ") + S);
Rui Ueyama6600eb12015-07-04 23:37:32 +0000168 auto Pair = Config->Merge.insert(std::make_pair(From, To));
169 bool Inserted = Pair.second;
Rui Ueyama2b82d5f2015-07-04 23:54:52 +0000170 if (!Inserted) {
171 StringRef Existing = Pair.first->second;
172 if (Existing != To)
173 llvm::errs() << "warning: " << S << ": already merged into "
174 << Existing << "\n";
175 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000176}
177
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000178// Parses a string in the form of "EMBED[,=<integer>]|NO".
179// Results are directly written to Config.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000180void parseManifest(StringRef Arg) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000181 if (Arg.equals_lower("no")) {
182 Config->Manifest = Configuration::No;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000183 return;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000184 }
185 if (!Arg.startswith_lower("embed"))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000186 error(Twine("Invalid option ") + Arg);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000187 Config->Manifest = Configuration::Embed;
188 Arg = Arg.substr(strlen("embed"));
189 if (Arg.empty())
Rafael Espindolab835ae82015-08-06 14:58:50 +0000190 return;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000191 if (!Arg.startswith_lower(",id="))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000192 error(Twine("Invalid option ") + Arg);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000193 Arg = Arg.substr(strlen(",id="));
194 if (Arg.getAsInteger(0, Config->ManifestID))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000195 error(Twine("Invalid option ") + Arg);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000196}
197
198// Parses a string in the form of "level=<string>|uiAccess=<string>|NO".
199// Results are directly written to Config.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000200void parseManifestUAC(StringRef Arg) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000201 if (Arg.equals_lower("no")) {
202 Config->ManifestUAC = false;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000203 return;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000204 }
205 for (;;) {
206 Arg = Arg.ltrim();
207 if (Arg.empty())
Rafael Espindolab835ae82015-08-06 14:58:50 +0000208 return;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000209 if (Arg.startswith_lower("level=")) {
210 Arg = Arg.substr(strlen("level="));
211 std::tie(Config->ManifestLevel, Arg) = Arg.split(" ");
212 continue;
213 }
214 if (Arg.startswith_lower("uiaccess=")) {
215 Arg = Arg.substr(strlen("uiaccess="));
216 std::tie(Config->ManifestUIAccess, Arg) = Arg.split(" ");
217 continue;
218 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000219 error(Twine("Invalid option ") + Arg);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000220 }
221}
222
223// Quote each line with "". Existing double-quote is converted
224// to two double-quotes.
225static void quoteAndPrint(raw_ostream &Out, StringRef S) {
226 while (!S.empty()) {
227 StringRef Line;
228 std::tie(Line, S) = S.split("\n");
229 if (Line.empty())
230 continue;
231 Out << '\"';
232 for (int I = 0, E = Line.size(); I != E; ++I) {
233 if (Line[I] == '\"') {
234 Out << "\"\"";
235 } else {
236 Out << Line[I];
237 }
238 }
239 Out << "\"\n";
240 }
241}
242
243// Create a manifest file contents.
244static std::string createManifestXml() {
245 std::string S;
246 llvm::raw_string_ostream OS(S);
247 // Emit the XML. Note that we do *not* verify that the XML attributes are
248 // syntactically correct. This is intentional for link.exe compatibility.
249 OS << "<?xml version=\"1.0\" standalone=\"yes\"?>\n"
250 << "<assembly xmlns=\"urn:schemas-microsoft-com:asm.v1\"\n"
251 << " manifestVersion=\"1.0\">\n";
252 if (Config->ManifestUAC) {
253 OS << " <trustInfo>\n"
254 << " <security>\n"
255 << " <requestedPrivileges>\n"
256 << " <requestedExecutionLevel level=" << Config->ManifestLevel
257 << " uiAccess=" << Config->ManifestUIAccess << "/>\n"
258 << " </requestedPrivileges>\n"
259 << " </security>\n"
260 << " </trustInfo>\n";
261 if (!Config->ManifestDependency.empty()) {
262 OS << " <dependency>\n"
263 << " <dependentAssembly>\n"
264 << " <assemblyIdentity " << Config->ManifestDependency << " />\n"
265 << " </dependentAssembly>\n"
266 << " </dependency>\n";
267 }
268 }
269 OS << "</assembly>\n";
270 OS.flush();
271 return S;
272}
273
274// Create a resource file containing a manifest XML.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000275std::unique_ptr<MemoryBuffer> createManifestRes() {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000276 // Create a temporary file for the resource script file.
277 SmallString<128> RCPath;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000278 std::error_code EC = sys::fs::createTemporaryFile("tmp", "rc", RCPath);
279 error(EC, "cannot create a temporary file");
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000280 FileRemover RCRemover(RCPath);
281
282 // Open the temporary file for writing.
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000283 llvm::raw_fd_ostream Out(RCPath, EC, sys::fs::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000284 error(EC, Twine("failed to open ") + RCPath);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000285
286 // Write resource script to the RC file.
287 Out << "#define LANG_ENGLISH 9\n"
288 << "#define SUBLANG_DEFAULT 1\n"
289 << "#define APP_MANIFEST " << Config->ManifestID << "\n"
290 << "#define RT_MANIFEST 24\n"
291 << "LANGUAGE LANG_ENGLISH, SUBLANG_DEFAULT\n"
292 << "APP_MANIFEST RT_MANIFEST {\n";
293 quoteAndPrint(Out, createManifestXml());
294 Out << "}\n";
295 Out.close();
296
297 // Create output resource file.
298 SmallString<128> ResPath;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000299 EC = sys::fs::createTemporaryFile("tmp", "res", ResPath);
300 error(EC, "cannot create a temporary file");
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000301
302 Executor E("rc.exe");
303 E.add("/fo");
304 E.add(ResPath.str());
305 E.add("/nologo");
306 E.add(RCPath.str());
Rafael Espindolab835ae82015-08-06 14:58:50 +0000307 E.run();
308 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = MemoryBuffer::getFile(ResPath);
309 error(Ret, Twine("Could not open ") + ResPath);
310 return std::move(*Ret);
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000311}
312
Rafael Espindolab835ae82015-08-06 14:58:50 +0000313void createSideBySideManifest() {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000314 std::string Path = Config->ManifestFile;
315 if (Path == "")
316 Path = (Twine(Config->OutputFile) + ".manifest").str();
317 std::error_code EC;
318 llvm::raw_fd_ostream Out(Path, EC, llvm::sys::fs::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000319 error(EC, "failed to create manifest");
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000320 Out << createManifestXml();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000321}
322
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000323// Parse a string in the form of
Rui Ueyama84425d72016-01-09 01:22:00 +0000324// "<name>[=<internalname>][,@ordinal[,NONAME]][,DATA][,PRIVATE]"
325// or "<name>=<dllname>.<name>".
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000326// Used for parsing /export arguments.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000327Export parseExport(StringRef Arg) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000328 Export E;
329 StringRef Rest;
330 std::tie(E.Name, Rest) = Arg.split(",");
331 if (E.Name.empty())
332 goto err;
Rui Ueyama84425d72016-01-09 01:22:00 +0000333
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000334 if (E.Name.find('=') != StringRef::npos) {
Rui Ueyama84425d72016-01-09 01:22:00 +0000335 StringRef X, Y;
336 std::tie(X, Y) = E.Name.split("=");
337
338 // If "<name>=<dllname>.<name>".
339 if (Y.find(".") != StringRef::npos) {
340 E.Name = X;
341 E.ForwardTo = Y;
342 return E;
343 }
344
345 E.ExtName = X;
346 E.Name = Y;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000347 if (E.Name.empty())
348 goto err;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000349 }
350
Rui Ueyama84425d72016-01-09 01:22:00 +0000351 // If "<name>=<internalname>[,@ordinal[,NONAME]][,DATA][,PRIVATE]"
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000352 while (!Rest.empty()) {
353 StringRef Tok;
354 std::tie(Tok, Rest) = Rest.split(",");
355 if (Tok.equals_lower("noname")) {
356 if (E.Ordinal == 0)
357 goto err;
358 E.Noname = true;
359 continue;
360 }
361 if (Tok.equals_lower("data")) {
362 E.Data = true;
363 continue;
364 }
365 if (Tok.equals_lower("private")) {
366 E.Private = true;
367 continue;
368 }
369 if (Tok.startswith("@")) {
370 int32_t Ord;
371 if (Tok.substr(1).getAsInteger(0, Ord))
372 goto err;
373 if (Ord <= 0 || 65535 < Ord)
374 goto err;
375 E.Ordinal = Ord;
376 continue;
377 }
378 goto err;
379 }
380 return E;
381
382err:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000383 error(Twine("invalid /export: ") + Arg);
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000384}
385
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000386static StringRef undecorate(StringRef Sym) {
387 if (Config->Machine != I386)
388 return Sym;
389 return Sym.startswith("_") ? Sym.substr(1) : Sym;
390}
391
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000392// Performs error checking on all /export arguments.
393// It also sets ordinals.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000394void fixupExports() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000395 // Symbol ordinals must be unique.
396 std::set<uint16_t> Ords;
397 for (Export &E : Config->Exports) {
398 if (E.Ordinal == 0)
399 continue;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000400 if (!Ords.insert(E.Ordinal).second)
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000401 error("duplicate export ordinal: " + E.Name);
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000402 }
403
Rui Ueyama8765fba2015-07-15 22:21:08 +0000404 for (Export &E : Config->Exports) {
Rui Ueyama84425d72016-01-09 01:22:00 +0000405 if (!E.ForwardTo.empty()) {
406 E.SymbolName = E.Name;
407 } else if (Undefined *U = cast_or_null<Undefined>(E.Sym->WeakAlias)) {
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000408 E.SymbolName = U->getName();
409 } else {
410 E.SymbolName = E.Sym->getName();
Rui Ueyama9420dee2015-07-28 22:34:24 +0000411 }
Rui Ueyama8765fba2015-07-15 22:21:08 +0000412 }
413
Rui Ueyama84425d72016-01-09 01:22:00 +0000414 for (Export &E : Config->Exports) {
415 if (!E.ForwardTo.empty()) {
416 E.ExportName = undecorate(E.Name);
417 } else {
418 E.ExportName = undecorate(E.ExtName.empty() ? E.Name : E.ExtName);
419 }
420 }
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000421
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000422 // Uniquefy by name.
Rui Ueyama4b8cdd22015-07-03 23:23:29 +0000423 std::map<StringRef, Export *> Map;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000424 std::vector<Export> V;
425 for (Export &E : Config->Exports) {
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000426 auto Pair = Map.insert(std::make_pair(E.ExportName, &E));
Rui Ueyama3126c6c2015-07-04 02:00:22 +0000427 bool Inserted = Pair.second;
428 if (Inserted) {
Rui Ueyama4b8cdd22015-07-03 23:23:29 +0000429 V.push_back(E);
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000430 continue;
431 }
Rui Ueyama3126c6c2015-07-04 02:00:22 +0000432 Export *Existing = Pair.first->second;
Rui Ueyama966acb22015-07-29 22:38:27 +0000433 if (E == *Existing || E.Name != Existing->Name)
Rui Ueyama4b8cdd22015-07-03 23:23:29 +0000434 continue;
435 llvm::errs() << "warning: duplicate /export option: " << E.Name << "\n";
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000436 }
437 Config->Exports = std::move(V);
438
439 // Sort by name.
Rui Ueyama9420dee2015-07-28 22:34:24 +0000440 std::sort(Config->Exports.begin(), Config->Exports.end(),
441 [](const Export &A, const Export &B) {
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000442 return A.ExportName < B.ExportName;
Rui Ueyama9420dee2015-07-28 22:34:24 +0000443 });
Rui Ueyama8765fba2015-07-15 22:21:08 +0000444}
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000445
Rui Ueyama8765fba2015-07-15 22:21:08 +0000446void assignExportOrdinals() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000447 // Assign unique ordinals if default (= 0).
448 uint16_t Max = 0;
449 for (Export &E : Config->Exports)
450 Max = std::max(Max, E.Ordinal);
451 for (Export &E : Config->Exports)
452 if (E.Ordinal == 0)
453 E.Ordinal = ++Max;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000454}
455
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000456// Parses a string in the form of "key=value" and check
457// if value matches previous values for the same key.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000458void checkFailIfMismatch(StringRef Arg) {
Rui Ueyama75b098b2015-06-18 21:23:34 +0000459 StringRef K, V;
460 std::tie(K, V) = Arg.split('=');
Rafael Espindolab835ae82015-08-06 14:58:50 +0000461 if (K.empty() || V.empty())
462 error(Twine("/failifmismatch: invalid argument: ") + Arg);
Rui Ueyama75b098b2015-06-18 21:23:34 +0000463 StringRef Existing = Config->MustMatch[K];
Rafael Espindolab835ae82015-08-06 14:58:50 +0000464 if (!Existing.empty() && V != Existing)
465 error(Twine("/failifmismatch: mismatch detected: ") + Existing + " and " +
466 V + " for key " + K);
Rui Ueyama75b098b2015-06-18 21:23:34 +0000467 Config->MustMatch[K] = V;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000468}
469
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000470// Convert Windows resource files (.res files) to a .obj file
471// using cvtres.exe.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000472std::unique_ptr<MemoryBuffer>
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000473convertResToCOFF(const std::vector<MemoryBufferRef> &MBs) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000474 // Create an output file path.
475 SmallString<128> Path;
476 if (llvm::sys::fs::createTemporaryFile("resource", "obj", Path))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000477 error("Could not create temporary file");
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000478
479 // Execute cvtres.exe.
Rui Ueyamaa9c88382015-06-17 21:01:56 +0000480 Executor E("cvtres.exe");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000481 E.add("/machine:" + machineToStr(Config->Machine));
Rui Ueyamaa9c88382015-06-17 21:01:56 +0000482 E.add("/readonly");
483 E.add("/nologo");
484 E.add("/out:" + Path);
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000485 for (MemoryBufferRef MB : MBs)
Rui Ueyamaa9c88382015-06-17 21:01:56 +0000486 E.add(MB.getBufferIdentifier());
Rafael Espindolab835ae82015-08-06 14:58:50 +0000487 E.run();
488 ErrorOr<std::unique_ptr<MemoryBuffer>> Ret = MemoryBuffer::getFile(Path);
489 error(Ret, Twine("Could not open ") + Path);
490 return std::move(*Ret);
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000491}
492
Rui Ueyama151d8622015-06-17 20:40:43 +0000493static std::string writeToTempFile(StringRef Contents) {
494 SmallString<128> Path;
495 int FD;
496 if (llvm::sys::fs::createTemporaryFile("tmp", "def", FD, Path)) {
497 llvm::errs() << "failed to create a temporary file\n";
498 return "";
499 }
500 llvm::raw_fd_ostream OS(FD, /*shouldClose*/ true);
501 OS << Contents;
502 return Path.str();
503}
504
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000505void touchFile(StringRef Path) {
506 int FD;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000507 std::error_code EC = sys::fs::openFileForWrite(Path, FD, sys::fs::F_Append);
508 error(EC, "failed to create a file");
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000509 sys::Process::SafelyCloseFileDescriptor(FD);
510}
511
Rui Ueyama40f4d862015-08-28 10:52:05 +0000512static std::string getImplibPath() {
513 if (!Config->Implib.empty())
514 return Config->Implib;
515 SmallString<128> Out = StringRef(Config->OutputFile);
516 sys::path::replace_extension(Out, ".lib");
517 return Out.str();
518}
519
520static std::unique_ptr<MemoryBuffer> createEmptyImportLibrary() {
521 std::string S = (Twine("LIBRARY \"") +
522 llvm::sys::path::filename(Config->OutputFile) + "\"\n")
523 .str();
524 std::string Path1 = writeToTempFile(S);
525 std::string Path2 = getImplibPath();
526 llvm::FileRemover Remover1(Path1);
527 llvm::FileRemover Remover2(Path2);
528
529 Executor E("lib.exe");
530 E.add("/nologo");
531 E.add("/machine:" + machineToStr(Config->Machine));
532 E.add(Twine("/def:") + Path1);
533 E.add(Twine("/out:") + Path2);
534 E.run();
535
536 ErrorOr<std::unique_ptr<MemoryBuffer>> BufOrErr =
537 MemoryBuffer::getFile(Path2, -1, false);
538 error(BufOrErr, Twine("Failed to open ") + Path2);
539 return MemoryBuffer::getMemBufferCopy((*BufOrErr)->getBuffer());
540}
541
542static std::vector<NewArchiveIterator>
543readMembers(const object::Archive &Archive) {
544 std::vector<NewArchiveIterator> V;
Kevin Enderby35dfc952015-11-05 19:25:47 +0000545 for (const auto &ChildOrErr : Archive.children()) {
546 error(ChildOrErr, "Archive::Child::getName failed");
547 const object::Archive::Child C(*ChildOrErr);
Rui Ueyama40f4d862015-08-28 10:52:05 +0000548 ErrorOr<StringRef> NameOrErr = C.getName();
549 error(NameOrErr, "Archive::Child::getName failed");
550 V.emplace_back(C, *NameOrErr);
551 }
552 return V;
553}
554
555// This class creates short import files which is described in
556// PE/COFF spec 7. Import Library Format.
557class ShortImportCreator {
558public:
559 ShortImportCreator(object::Archive *A, StringRef S) : Parent(A), DLLName(S) {}
560
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000561 NewArchiveIterator create(StringRef Sym, uint16_t Ordinal,
562 ImportNameType NameType, bool isData) {
Rui Ueyama40f4d862015-08-28 10:52:05 +0000563 size_t ImpSize = DLLName.size() + Sym.size() + 2; // +2 for NULs
564 size_t Size = sizeof(object::ArchiveMemberHeader) +
565 sizeof(coff_import_header) + ImpSize;
566 char *Buf = Alloc.Allocate<char>(Size);
567 memset(Buf, 0, Size);
568 char *P = Buf;
569
570 // Write archive member header
571 auto *Hdr = reinterpret_cast<object::ArchiveMemberHeader *>(P);
572 P += sizeof(*Hdr);
573 sprintf(Hdr->Name, "%-12s", "dummy");
574 sprintf(Hdr->LastModified, "%-12d", 0);
575 sprintf(Hdr->UID, "%-6d", 0);
576 sprintf(Hdr->GID, "%-6d", 0);
577 sprintf(Hdr->AccessMode, "%-8d", 0644);
578 sprintf(Hdr->Size, "%-10d", int(sizeof(coff_import_header) + ImpSize));
579
580 // Write short import library.
581 auto *Imp = reinterpret_cast<coff_import_header *>(P);
582 P += sizeof(*Imp);
583 Imp->Sig2 = 0xFFFF;
584 Imp->Machine = Config->Machine;
585 Imp->SizeOfData = ImpSize;
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000586 if (Ordinal > 0)
587 Imp->OrdinalHint = Ordinal;
588 Imp->TypeInfo = (isData ? IMPORT_DATA : IMPORT_CODE);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000589 Imp->TypeInfo |= NameType << 2;
Rui Ueyama40f4d862015-08-28 10:52:05 +0000590
591 // Write symbol name and DLL name.
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000592 memcpy(P, Sym.data(), Sym.size());
Rui Ueyama40f4d862015-08-28 10:52:05 +0000593 P += Sym.size() + 1;
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000594 memcpy(P, DLLName.data(), DLLName.size());
Rui Ueyama40f4d862015-08-28 10:52:05 +0000595
Rafael Espindola7bcaec82015-11-06 19:57:37 +0000596 std::error_code EC;
597 object::Archive::Child C(Parent, Buf, &EC);
598 assert(!EC && "We created an invalid buffer");
Rui Ueyamadfff2542015-09-01 08:08:57 +0000599 return NewArchiveIterator(C, DLLName);
Rui Ueyama40f4d862015-08-28 10:52:05 +0000600 }
601
602private:
Rui Ueyama40f4d862015-08-28 10:52:05 +0000603 BumpPtrAllocator Alloc;
604 object::Archive *Parent;
605 StringRef DLLName;
Rui Ueyama40f4d862015-08-28 10:52:05 +0000606};
607
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000608static ImportNameType getNameType(StringRef Sym, StringRef ExtName) {
609 if (Sym != ExtName)
610 return IMPORT_NAME_UNDECORATE;
611 if (Config->Machine == I386 && Sym.startswith("_"))
612 return IMPORT_NAME_NOPREFIX;
613 return IMPORT_NAME;
614}
615
616static std::string replace(StringRef S, StringRef From, StringRef To) {
617 size_t Pos = S.find(From);
618 assert(Pos != StringRef::npos);
619 return (Twine(S.substr(0, Pos)) + To + S.substr(Pos + From.size())).str();
620}
621
Rui Ueyama40f4d862015-08-28 10:52:05 +0000622// Creates an import library for a DLL. In this function, we first
623// create an empty import library using lib.exe and then adds short
624// import files to that file.
625void writeImportLibrary() {
626 std::unique_ptr<MemoryBuffer> Buf = createEmptyImportLibrary();
627 std::error_code EC;
628 object::Archive Archive(Buf->getMemBufferRef(), EC);
629 error(EC, "Error reading an empty import file");
630 std::vector<NewArchiveIterator> Members = readMembers(Archive);
631
632 std::string DLLName = llvm::sys::path::filename(Config->OutputFile);
633 ShortImportCreator ShortImport(&Archive, DLLName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000634 for (Export &E : Config->Exports) {
635 if (E.Private)
636 continue;
637 if (E.ExtName.empty()) {
638 Members.push_back(ShortImport.create(
639 E.SymbolName, E.Ordinal, getNameType(E.SymbolName, E.Name), E.Data));
640 } else {
641 Members.push_back(ShortImport.create(
642 replace(E.SymbolName, E.Name, E.ExtName), E.Ordinal,
643 getNameType(E.SymbolName, E.Name), E.Data));
644 }
645 }
Rui Ueyama40f4d862015-08-28 10:52:05 +0000646
647 std::string Path = getImplibPath();
648 std::pair<StringRef, std::error_code> Result =
649 writeArchive(Path, Members, /*WriteSymtab*/ true, object::Archive::K_GNU,
650 /*Deterministic*/ true, /*Thin*/ false);
651 error(Result.second, Twine("Failed to write ") + Path);
652}
653
Rui Ueyama3500f662015-05-28 20:30:06 +0000654// Create OptTable
655
656// Create prefix string literals used in Options.td
657#define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
658#include "Options.inc"
659#undef PREFIX
660
661// Create table mapping all options defined in Options.td
662static const llvm::opt::OptTable::Info infoTable[] = {
663#define OPTION(X1, X2, ID, KIND, GROUP, ALIAS, X6, X7, X8, X9, X10) \
664 { \
665 X1, X2, X9, X10, OPT_##ID, llvm::opt::Option::KIND##Class, X8, X7, \
666 OPT_##GROUP, OPT_##ALIAS, X6 \
667 },
668#include "Options.inc"
669#undef OPTION
670};
671
672class COFFOptTable : public llvm::opt::OptTable {
673public:
Craig Topperf88d22972015-10-21 16:31:56 +0000674 COFFOptTable() : OptTable(infoTable, true) {}
Rui Ueyama3500f662015-05-28 20:30:06 +0000675};
676
Rui Ueyama115d7c12015-06-07 02:55:19 +0000677// Parses a given list of options.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000678llvm::opt::InputArgList ArgParser::parse(ArrayRef<const char *> ArgsArr) {
Rui Ueyama115d7c12015-06-07 02:55:19 +0000679 // First, replace respnose files (@<file>-style options).
Rafael Espindolab835ae82015-08-06 14:58:50 +0000680 std::vector<const char *> Argv = replaceResponseFiles(ArgsArr);
Rui Ueyama115d7c12015-06-07 02:55:19 +0000681
682 // Make InputArgList from string vectors.
Rui Ueyama3500f662015-05-28 20:30:06 +0000683 COFFOptTable Table;
684 unsigned MissingIndex;
685 unsigned MissingCount;
David Blaikie6521ed92015-06-22 22:06:52 +0000686 llvm::opt::InputArgList Args =
687 Table.ParseArgs(Argv, MissingIndex, MissingCount);
Rui Ueyama2caf4072015-08-26 07:12:08 +0000688
689 // Print the real command line if response files are expanded.
690 if (Args.hasArg(OPT_verbose) && ArgsArr.size() != Argv.size()) {
691 llvm::outs() << "Command line:";
692 for (const char *S : Argv)
693 llvm::outs() << " " << S;
694 llvm::outs() << "\n";
695 }
696
Rafael Espindolab835ae82015-08-06 14:58:50 +0000697 if (MissingCount)
698 error(Twine("missing arg value for \"") + Args.getArgString(MissingIndex) +
699 "\", expected " + Twine(MissingCount) +
700 (MissingCount == 1 ? " argument." : " arguments."));
David Blaikie6521ed92015-06-22 22:06:52 +0000701 for (auto *Arg : Args.filtered(OPT_UNKNOWN))
Rui Ueyama3500f662015-05-28 20:30:06 +0000702 llvm::errs() << "ignoring unknown argument: " << Arg->getSpelling() << "\n";
Rafael Espindolab835ae82015-08-06 14:58:50 +0000703 return Args;
Rui Ueyama3500f662015-05-28 20:30:06 +0000704}
705
Rafael Espindolab835ae82015-08-06 14:58:50 +0000706llvm::opt::InputArgList ArgParser::parseLINK(ArrayRef<const char *> Args) {
Rui Ueyama06cf3df2015-06-28 02:35:31 +0000707 // Concatenate LINK env and given arguments and parse them.
708 Optional<std::string> Env = Process::GetEnv("LINK");
709 if (!Env)
710 return parse(Args);
711 std::vector<const char *> V = tokenize(*Env);
Rui Ueyama9d72f092015-06-28 03:05:38 +0000712 V.insert(V.end(), Args.begin(), Args.end());
Rui Ueyama06cf3df2015-06-28 02:35:31 +0000713 return parse(V);
714}
715
Rui Ueyama115d7c12015-06-07 02:55:19 +0000716std::vector<const char *> ArgParser::tokenize(StringRef S) {
717 SmallVector<const char *, 16> Tokens;
Rafael Espindolaf0461ba2015-08-13 01:07:08 +0000718 StringSaver Saver(AllocAux);
Rui Ueyama115d7c12015-06-07 02:55:19 +0000719 llvm::cl::TokenizeWindowsCommandLine(S, Saver, Tokens);
Rui Ueyamaaace5772015-06-07 23:02:50 +0000720 return std::vector<const char *>(Tokens.begin(), Tokens.end());
Rui Ueyama115d7c12015-06-07 02:55:19 +0000721}
722
Rui Ueyamab51f67a2015-06-07 23:00:29 +0000723// Creates a new command line by replacing options starting with '@'
Rui Ueyama115d7c12015-06-07 02:55:19 +0000724// character. '@<filename>' is replaced by the file's contents.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000725std::vector<const char *>
Rui Ueyama115d7c12015-06-07 02:55:19 +0000726ArgParser::replaceResponseFiles(std::vector<const char *> Argv) {
Peter Collingbourne74ecc892015-06-19 22:40:05 +0000727 SmallVector<const char *, 256> Tokens(Argv.data(), Argv.data() + Argv.size());
Rafael Espindolaf0461ba2015-08-13 01:07:08 +0000728 StringSaver Saver(AllocAux);
Rui Ueyamab51f67a2015-06-07 23:00:29 +0000729 ExpandResponseFiles(Saver, TokenizeWindowsCommandLine, Tokens);
730 return std::vector<const char *>(Tokens.begin(), Tokens.end());
Rui Ueyama115d7c12015-06-07 02:55:19 +0000731}
732
Rui Ueyama5c726432015-05-29 16:11:52 +0000733void printHelp(const char *Argv0) {
734 COFFOptTable Table;
735 Table.PrintHelp(llvm::outs(), Argv0, "LLVM Linker", false);
736}
737
Rui Ueyama3500f662015-05-28 20:30:06 +0000738} // namespace coff
739} // namespace lld