blob: e724a8f55e46d422c11733930cfb44da1c317d7b [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- Driver.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#include "Config.h"
11#include "Driver.h"
12#include "InputFiles.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "SymbolTable.h"
14#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000015#include "llvm/ADT/Optional.h"
16#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000017#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000018#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000019#include "llvm/Option/Arg.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/Option/Option.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000024#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000025#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000026#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000027#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000028#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include <memory>
30
31using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000032using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
33using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
34using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000035using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000036using llvm::sys::fs::file_magic;
37using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000038
Rui Ueyama3500f662015-05-28 20:30:06 +000039namespace lld {
40namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000041
Rui Ueyama3500f662015-05-28 20:30:06 +000042Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000043LinkerDriver *Driver;
44
45bool link(int Argc, const char *Argv[]) {
46 auto C = make_unique<Configuration>();
47 Config = C.get();
48 auto D = make_unique<LinkerDriver>();
49 Driver = D.get();
50 return Driver->link(Argc, Argv);
51}
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Rui Ueyamaad660982015-06-07 00:20:32 +000053// Drop directory components and replace extension with ".exe".
54static std::string getOutputPath(StringRef Path) {
55 auto P = Path.find_last_of("\\/");
56 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
57 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000058}
59
Rui Ueyamad7c2f582015-05-31 21:04:56 +000060// Opens a file. Path has to be resolved already.
61// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000062ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000063 auto MBOrErr = MemoryBuffer::getFile(Path);
64 if (auto EC = MBOrErr.getError())
65 return EC;
66 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
67 MemoryBufferRef MBRef = MB->getMemBufferRef();
68 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000069 return MBRef;
70}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000071
Rui Ueyama2bf6a122015-06-14 21:50:50 +000072static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000073 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000074 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000075 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000076 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000077 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000078 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000079 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000080 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
81 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000082}
83
Rui Ueyama411c63602015-05-28 19:09:30 +000084// Parses .drectve section contents and returns a list of files
85// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000086std::error_code
87LinkerDriver::parseDirectives(StringRef S,
88 std::vector<std::unique_ptr<InputFile>> *Res) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000089 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000090 if (auto EC = ArgsOrErr.getError())
91 return EC;
92 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
93
Rui Ueyama97dff9e2015-06-17 00:16:33 +000094 // Handle /export
95 for (auto *Arg : Args->filtered(OPT_export)) {
96 ErrorOr<Export> E = parseExport(Arg->getValue());
97 if (auto EC = E.getError())
98 return EC;
99 Config->Exports.push_back(E.get());
100 }
101
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000102 // Handle /failifmismatch
103 if (auto EC = checkFailIfMismatch(Args.get()))
104 return EC;
105
106 // Handle /defaultlib
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000107 for (auto *Arg : Args->filtered(OPT_defaultlib)) {
108 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000109 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
110 if (auto EC = MBOrErr.getError())
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000111 return EC;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000112 std::unique_ptr<InputFile> File = createFile(MBOrErr.get());
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000113 Res->push_back(std::move(File));
114 }
115 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000116 return std::error_code();
117}
118
Rui Ueyama54b71da2015-05-31 19:17:12 +0000119// Find file from search paths. You can omit ".obj", this function takes
120// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000121StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000122 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
123 if (hasPathSep)
124 return Filename;
125 bool hasExt = (Filename.find('.') != StringRef::npos);
126 for (StringRef Dir : SearchPaths) {
127 SmallString<128> Path = Dir;
128 llvm::sys::path::append(Path, Filename);
129 if (llvm::sys::fs::exists(Path.str()))
130 return Alloc.save(Path.str());
131 if (!hasExt) {
132 Path.append(".obj");
133 if (llvm::sys::fs::exists(Path.str()))
134 return Alloc.save(Path.str());
135 }
136 }
137 return Filename;
138}
139
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000140// Resolves a file path. This never returns the same path
141// (in that case, it returns None).
142Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
143 StringRef Path = doFindFile(Filename);
144 bool Seen = !VisitedFiles.insert(Path.lower()).second;
145 if (Seen)
146 return None;
147 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000148}
149
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000150// Find library file from search path.
151StringRef LinkerDriver::doFindLib(StringRef Filename) {
152 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000153 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000154 if (!hasExt)
155 Filename = Alloc.save(Filename + ".lib");
156 return doFindFile(Filename);
157}
158
159// Resolves a library path. /nodefaultlib options are taken into
160// consideration. This never returns the same path (in that case,
161// it returns None).
162Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
163 if (Config->NoDefaultLibAll)
164 return None;
165 StringRef Path = doFindLib(Filename);
166 if (Config->NoDefaultLibs.count(Path))
167 return None;
168 bool Seen = !VisitedFiles.insert(Path.lower()).second;
169 if (Seen)
170 return None;
171 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000172}
173
174// Parses LIB environment which contains a list of search paths.
175std::vector<StringRef> LinkerDriver::getSearchPaths() {
176 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000177 // Add current directory as first item of the search paths.
178 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000179 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
180 if (!EnvOpt.hasValue())
181 return Ret;
182 StringRef Env = Alloc.save(*EnvOpt);
183 while (!Env.empty()) {
184 StringRef Path;
185 std::tie(Path, Env) = Env.split(';');
186 Ret.push_back(Path);
187 }
188 return Ret;
189}
190
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000191static WindowsSubsystem inferSubsystem() {
192 if (Config->DLL)
193 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
194 return StringSwitch<WindowsSubsystem>(Config->EntryName)
195 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
196 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
197 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
198 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
199 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
200}
201
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000202bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000203 // Needed for LTO.
204 llvm::InitializeAllTargetInfos();
205 llvm::InitializeAllTargets();
206 llvm::InitializeAllTargetMCs();
207 llvm::InitializeAllAsmParsers();
208 llvm::InitializeAllAsmPrinters();
209 llvm::InitializeAllDisassemblers();
210
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000211 // If the first command line argument is "/lib", link.exe acts like lib.exe.
212 // We call our own implementation of lib.exe that understands bitcode files.
213 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
214 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
215
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000217 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000218 if (auto EC = ArgsOrErr.getError()) {
219 llvm::errs() << EC.message() << "\n";
220 return false;
221 }
222 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
223
Rui Ueyama5c726432015-05-29 16:11:52 +0000224 // Handle /help
225 if (Args->hasArg(OPT_help)) {
226 printHelp(Argv[0]);
227 return true;
228 }
229
Rui Ueyama411c63602015-05-28 19:09:30 +0000230 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
231 llvm::errs() << "no input files.\n";
232 return false;
233 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000234
Rui Ueyamaad660982015-06-07 00:20:32 +0000235 // Handle /out
236 if (auto *Arg = Args->getLastArg(OPT_out))
237 Config->OutputFile = Arg->getValue();
238
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000239 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000240 if (Args->hasArg(OPT_verbose))
241 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000242
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000243 // Handle /dll
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000244 if (Args->hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000245 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000246 Config->ManifestID = 2;
247 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000248
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000249 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000250 if (auto *Arg = Args->getLastArg(OPT_entry))
251 Config->EntryName = Arg->getValue();
252
Rui Ueyama588e8322015-06-15 01:23:58 +0000253 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000254 if (Args->hasArg(OPT_fixed)) {
255 if (Args->hasArg(OPT_dynamicbase)) {
256 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
257 return false;
258 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000259 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000260 Config->DynamicBase = false;
261 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000262
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000263 // Handle /machine
264 auto MTOrErr = getMachineType(Args.get());
265 if (auto EC = MTOrErr.getError()) {
266 llvm::errs() << EC.message() << "\n";
267 return false;
268 }
269 Config->MachineType = MTOrErr.get();
270
Rui Ueyama06137472015-05-31 20:10:11 +0000271 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000272 for (auto *Arg : Args->filtered(OPT_libpath)) {
273 // Inserting at front of a vector is okay because it's short.
274 // +1 because the first entry is always "." (current directory).
275 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
276 }
Rui Ueyama06137472015-05-31 20:10:11 +0000277
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000278 // Handle /nodefaultlib:<filename>
279 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
280 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
281
282 // Handle /nodefaultlib
283 if (Args->hasArg(OPT_nodefaultlib_all))
284 Config->NoDefaultLibAll = true;
285
Rui Ueyama804a8b62015-05-29 16:18:15 +0000286 // Handle /base
287 if (auto *Arg = Args->getLastArg(OPT_base)) {
288 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000289 llvm::errs() << "/base: " << EC.message() << "\n";
290 return false;
291 }
292 }
293
294 // Handle /stack
295 if (auto *Arg = Args->getLastArg(OPT_stack)) {
296 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
297 &Config->StackCommit)) {
298 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000299 return false;
300 }
301 }
302
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000303 // Handle /heap
304 if (auto *Arg = Args->getLastArg(OPT_heap)) {
305 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
306 &Config->HeapCommit)) {
307 llvm::errs() << "/heap: " << EC.message() << "\n";
308 return false;
309 }
310 }
311
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000312 // Handle /version
313 if (auto *Arg = Args->getLastArg(OPT_version)) {
314 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
315 &Config->MinorImageVersion)) {
316 llvm::errs() << "/version: " << EC.message() << "\n";
317 return false;
318 }
319 }
320
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000321 // Handle /subsystem
322 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
323 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
324 &Config->MajorOSVersion,
325 &Config->MinorOSVersion)) {
326 llvm::errs() << "/subsystem: " << EC.message() << "\n";
327 return false;
328 }
329 }
330
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000331 // Handle /opt
332 for (auto *Arg : Args->filtered(OPT_opt)) {
333 std::string S = StringRef(Arg->getValue()).lower();
334 if (S == "noref") {
335 Config->DoGC = false;
336 continue;
337 }
338 if (S != "ref" && S != "icf" && S != "noicf" &&
339 S != "lbr" && S != "nolbr" &&
340 !StringRef(S).startswith("icf=")) {
341 llvm::errs() << "/opt: unknown option: " << S << "\n";
342 return false;
343 }
344 }
345
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000346 // Handle /export
347 for (auto *Arg : Args->filtered(OPT_export)) {
348 ErrorOr<Export> E = parseExport(Arg->getValue());
349 if (E.getError())
350 return false;
351 Config->Exports.push_back(E.get());
352 }
353
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000354 // Handle /failifmismatch
355 if (auto EC = checkFailIfMismatch(Args.get())) {
356 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
357 return false;
358 }
359
Rui Ueyama1f373702015-06-17 19:19:25 +0000360 // Handle /def
361 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
362 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
363 if (auto EC = MBOrErr.getError()) {
364 llvm::errs() << "/def: " << EC.message() << "\n";
365 return false;
366 }
367 // parseModuleDefs mutates Config object.
368 if (parseModuleDefs(MBOrErr.get()))
369 return false;
370 }
371
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000372 // Handle /manifest
373 if (auto *Arg = Args->getLastArg(OPT_manifest_colon)) {
374 if (auto EC = parseManifest(Arg->getValue())) {
375 llvm::errs() << "/manifest: " << EC.message() << "\n";
376 return false;
377 }
378 }
379
380 // Handle /manifestuac
381 if (auto *Arg = Args->getLastArg(OPT_manifestuac)) {
382 if (auto EC = parseManifestUAC(Arg->getValue())) {
383 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
384 return false;
385 }
386 }
387
388 // Handle /manifestdependency
389 if (auto *Arg = Args->getLastArg(OPT_manifestdependency))
390 Config->ManifestDependency = Arg->getValue();
391
392 // Handle /manifestfile
393 if (auto *Arg = Args->getLastArg(OPT_manifestfile))
394 Config->ManifestFile = Arg->getValue();
395
Rui Ueyama6592ff82015-06-16 23:13:00 +0000396 // Handle miscellaneous boolean flags.
397 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
398 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
399 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
400 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
401 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
402 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
403
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000404 // Create a list of input files. Files can be given as arguments
405 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000406 std::vector<StringRef> InputPaths;
407 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000408 for (auto *Arg : Args->filtered(OPT_INPUT))
409 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000410 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000411 for (auto *Arg : Args->filtered(OPT_defaultlib))
412 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000413 InputPaths.push_back(*Path);
414 for (StringRef Path : InputPaths) {
415 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
416 if (auto EC = MBOrErr.getError()) {
417 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
418 return false;
419 }
420 Inputs.push_back(MBOrErr.get());
421 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000422
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000423 // Create a symbol table.
424 SymbolTable Symtab;
425
426 // Add undefined symbols given via the command line.
427 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000428 for (auto *Arg : Args->filtered(OPT_incl)) {
429 StringRef Sym = Arg->getValue();
430 Symtab.addUndefined(Sym);
431 Config->GCRoots.insert(Sym);
432 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000433
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000434 // Windows specific -- Create a resource file containing a manifest file.
435 if (Config->Manifest == Configuration::Embed) {
436 auto MBOrErr = createManifestRes();
437 if (MBOrErr.getError())
438 return false;
439 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
440 Inputs.push_back(MB->getMemBufferRef());
441 OwningMBs.push_back(std::move(MB)); // take ownership
442 }
443
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000444 // Windows specific -- Input files can be Windows resource files (.res files).
445 // We invoke cvtres.exe to convert resource files to a regular COFF file
446 // then link the result file normally.
447 auto IsResource = [](MemoryBufferRef MB) {
448 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
449 };
450 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
451 if (It != Inputs.begin()) {
452 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
453 auto MBOrErr = convertResToCOFF(Files);
454 if (MBOrErr.getError())
455 return false;
456 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
457 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
458 Inputs.push_back(MB->getMemBufferRef());
459 OwningMBs.push_back(std::move(MB)); // take ownership
460 }
461
Rui Ueyama411c63602015-05-28 19:09:30 +0000462 // Parse all input files and put all symbols to the symbol table.
463 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000464 for (MemoryBufferRef MB : Inputs) {
465 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000466 if (Config->Verbose)
467 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000468 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000469 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000470 return false;
471 }
472 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000473
Rui Ueyama360bace2015-05-31 22:31:31 +0000474 // Add weak aliases. Weak aliases is a mechanism to give remaining
475 // undefined symbols final chance to be resolved successfully.
476 // This is symbol renaming.
477 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000478 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000479 StringRef From, To;
480 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
481 if (From.empty() || To.empty()) {
482 llvm::errs() << "/alternatename: invalid argument: "
483 << Arg->getValue() << "\n";
484 return false;
485 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000486 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000487 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000488 if (Symtab.find(From))
489 continue;
490 if (auto EC = Symtab.rename(From, To)) {
491 llvm::errs() << EC.message() << "\n";
492 return false;
493 }
494 }
495
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000496 // Windows specific -- Make sure we resolve all dllexported symbols.
497 // (We don't cache the size here because Symtab.resolve() may add
498 // new entries to Config->Exports.)
499 for (size_t I = 0; I < Config->Exports.size(); ++I) {
500 StringRef Sym = Config->Exports[I].Name;
501 Symtab.addUndefined(Sym);
502 Config->GCRoots.insert(Sym);
503 }
504
Rui Ueyama5cff6852015-05-31 03:34:08 +0000505 // Windows specific -- If entry point name is not given, we need to
506 // infer that from user-defined entry name. The symbol table takes
507 // care of details.
508 if (Config->EntryName.empty()) {
509 auto EntryOrErr = Symtab.findDefaultEntry();
510 if (auto EC = EntryOrErr.getError()) {
511 llvm::errs() << EC.message() << "\n";
512 return false;
513 }
514 Config->EntryName = EntryOrErr.get();
515 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000516 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000517
518 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000519 if (Symtab.reportRemainingUndefines())
520 return false;
521
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000522 // Do LTO by compiling bitcode input files to a native COFF file
523 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000524 if (auto EC = Symtab.addCombinedLTOObject()) {
525 llvm::errs() << EC.message() << "\n";
526 return false;
527 }
528
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000529 // Windows specific -- if no /subsystem is given, we need to infer
530 // that from entry point name.
531 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000532 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000533 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
534 llvm::errs() << "subsystem must be defined\n";
535 return false;
536 }
537 }
538
Rui Ueyama151d8622015-06-17 20:40:43 +0000539 // Windows specific -- when we are creating a .dll file, we also
540 // need to create a .lib file.
541 if (!Config->Exports.empty())
542 writeImportLibrary();
543
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000544 // Windows specific -- fix up dllexported symbols.
545 if (!Config->Exports.empty()) {
546 for (Export &E : Config->Exports)
547 E.Sym = Symtab.find(E.Name);
548 if (fixupExports())
549 return false;
550 }
551
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000552 // Windows specific -- Create a side-by-side manifest file.
553 if (Config->Manifest == Configuration::SideBySide)
554 if (createSideBySideManifest())
555 return false;
556
Rui Ueyama411c63602015-05-28 19:09:30 +0000557 // Write the result.
558 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000559 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000560 llvm::errs() << EC.message() << "\n";
561 return false;
562 }
563 return true;
564}
565
Rui Ueyama411c63602015-05-28 19:09:30 +0000566} // namespace coff
567} // namespace lld