blob: 9c2e53e34cd0e0b8ad5518ac5c6b17defbcd7295 [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 Ueyama2edb35a2015-06-18 19:09:30 +0000102 // Handle /alternatename
103 for (auto *Arg : Args->filtered(OPT_alternatename))
104 if (auto EC = parseAlternateName(Arg->getValue()))
105 return EC;
106
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000107 // Handle /failifmismatch
Rui Ueyama75b098b2015-06-18 21:23:34 +0000108 for (auto *Arg : Args->filtered(OPT_failifmismatch))
109 if (auto EC = checkFailIfMismatch(Arg->getValue()))
110 return EC;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000111
112 // Handle /defaultlib
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000113 for (auto *Arg : Args->filtered(OPT_defaultlib)) {
114 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000115 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
116 if (auto EC = MBOrErr.getError())
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000117 return EC;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000118 std::unique_ptr<InputFile> File = createFile(MBOrErr.get());
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000119 Res->push_back(std::move(File));
120 }
121 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000122 return std::error_code();
123}
124
Rui Ueyama54b71da2015-05-31 19:17:12 +0000125// Find file from search paths. You can omit ".obj", this function takes
126// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000127StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000128 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
129 if (hasPathSep)
130 return Filename;
131 bool hasExt = (Filename.find('.') != StringRef::npos);
132 for (StringRef Dir : SearchPaths) {
133 SmallString<128> Path = Dir;
134 llvm::sys::path::append(Path, Filename);
135 if (llvm::sys::fs::exists(Path.str()))
136 return Alloc.save(Path.str());
137 if (!hasExt) {
138 Path.append(".obj");
139 if (llvm::sys::fs::exists(Path.str()))
140 return Alloc.save(Path.str());
141 }
142 }
143 return Filename;
144}
145
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000146// Resolves a file path. This never returns the same path
147// (in that case, it returns None).
148Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
149 StringRef Path = doFindFile(Filename);
150 bool Seen = !VisitedFiles.insert(Path.lower()).second;
151 if (Seen)
152 return None;
153 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000154}
155
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000156// Find library file from search path.
157StringRef LinkerDriver::doFindLib(StringRef Filename) {
158 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000159 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000160 if (!hasExt)
161 Filename = Alloc.save(Filename + ".lib");
162 return doFindFile(Filename);
163}
164
165// Resolves a library path. /nodefaultlib options are taken into
166// consideration. This never returns the same path (in that case,
167// it returns None).
168Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
169 if (Config->NoDefaultLibAll)
170 return None;
171 StringRef Path = doFindLib(Filename);
172 if (Config->NoDefaultLibs.count(Path))
173 return None;
174 bool Seen = !VisitedFiles.insert(Path.lower()).second;
175 if (Seen)
176 return None;
177 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000178}
179
180// Parses LIB environment which contains a list of search paths.
181std::vector<StringRef> LinkerDriver::getSearchPaths() {
182 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000183 // Add current directory as first item of the search paths.
184 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000185 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
186 if (!EnvOpt.hasValue())
187 return Ret;
188 StringRef Env = Alloc.save(*EnvOpt);
189 while (!Env.empty()) {
190 StringRef Path;
191 std::tie(Path, Env) = Env.split(';');
192 Ret.push_back(Path);
193 }
194 return Ret;
195}
196
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000197static WindowsSubsystem inferSubsystem() {
198 if (Config->DLL)
199 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
200 return StringSwitch<WindowsSubsystem>(Config->EntryName)
201 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
202 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
203 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
204 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
205 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
206}
207
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000208bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000209 // Needed for LTO.
210 llvm::InitializeAllTargetInfos();
211 llvm::InitializeAllTargets();
212 llvm::InitializeAllTargetMCs();
213 llvm::InitializeAllAsmParsers();
214 llvm::InitializeAllAsmPrinters();
215 llvm::InitializeAllDisassemblers();
216
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000217 // If the first command line argument is "/lib", link.exe acts like lib.exe.
218 // We call our own implementation of lib.exe that understands bitcode files.
219 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
220 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
221
Rui Ueyama411c63602015-05-28 19:09:30 +0000222 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000223 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000224 if (auto EC = ArgsOrErr.getError()) {
225 llvm::errs() << EC.message() << "\n";
226 return false;
227 }
228 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
229
Rui Ueyama5c726432015-05-29 16:11:52 +0000230 // Handle /help
231 if (Args->hasArg(OPT_help)) {
232 printHelp(Argv[0]);
233 return true;
234 }
235
Rui Ueyama411c63602015-05-28 19:09:30 +0000236 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
237 llvm::errs() << "no input files.\n";
238 return false;
239 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000240
Rui Ueyamaad660982015-06-07 00:20:32 +0000241 // Handle /out
242 if (auto *Arg = Args->getLastArg(OPT_out))
243 Config->OutputFile = Arg->getValue();
244
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000245 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000246 if (Args->hasArg(OPT_verbose))
247 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000248
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000249 // Handle /dll
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000250 if (Args->hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000251 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000252 Config->ManifestID = 2;
253 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000254
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000255 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000256 if (auto *Arg = Args->getLastArg(OPT_entry))
257 Config->EntryName = Arg->getValue();
258
Rui Ueyama588e8322015-06-15 01:23:58 +0000259 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000260 if (Args->hasArg(OPT_fixed)) {
261 if (Args->hasArg(OPT_dynamicbase)) {
262 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
263 return false;
264 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000265 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000266 Config->DynamicBase = false;
267 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000268
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000269 // Handle /machine
270 auto MTOrErr = getMachineType(Args.get());
271 if (auto EC = MTOrErr.getError()) {
272 llvm::errs() << EC.message() << "\n";
273 return false;
274 }
275 Config->MachineType = MTOrErr.get();
276
Rui Ueyama06137472015-05-31 20:10:11 +0000277 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000278 for (auto *Arg : Args->filtered(OPT_libpath)) {
279 // Inserting at front of a vector is okay because it's short.
280 // +1 because the first entry is always "." (current directory).
281 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
282 }
Rui Ueyama06137472015-05-31 20:10:11 +0000283
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000284 // Handle /nodefaultlib:<filename>
285 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
286 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
287
288 // Handle /nodefaultlib
289 if (Args->hasArg(OPT_nodefaultlib_all))
290 Config->NoDefaultLibAll = true;
291
Rui Ueyama804a8b62015-05-29 16:18:15 +0000292 // Handle /base
293 if (auto *Arg = Args->getLastArg(OPT_base)) {
294 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000295 llvm::errs() << "/base: " << EC.message() << "\n";
296 return false;
297 }
298 }
299
300 // Handle /stack
301 if (auto *Arg = Args->getLastArg(OPT_stack)) {
302 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
303 &Config->StackCommit)) {
304 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000305 return false;
306 }
307 }
308
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000309 // Handle /heap
310 if (auto *Arg = Args->getLastArg(OPT_heap)) {
311 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
312 &Config->HeapCommit)) {
313 llvm::errs() << "/heap: " << EC.message() << "\n";
314 return false;
315 }
316 }
317
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000318 // Handle /version
319 if (auto *Arg = Args->getLastArg(OPT_version)) {
320 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
321 &Config->MinorImageVersion)) {
322 llvm::errs() << "/version: " << EC.message() << "\n";
323 return false;
324 }
325 }
326
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000327 // Handle /subsystem
328 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
329 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
330 &Config->MajorOSVersion,
331 &Config->MinorOSVersion)) {
332 llvm::errs() << "/subsystem: " << EC.message() << "\n";
333 return false;
334 }
335 }
336
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000337 // Handle /alternatename
338 for (auto *Arg : Args->filtered(OPT_alternatename))
339 if (parseAlternateName(Arg->getValue()))
340 return false;
341
Rui Ueyamab95188c2015-06-18 20:27:09 +0000342 // Handle /implib
343 if (auto *Arg = Args->getLastArg(OPT_implib))
344 Config->Implib = Arg->getValue();
345
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000346 // Handle /opt
347 for (auto *Arg : Args->filtered(OPT_opt)) {
348 std::string S = StringRef(Arg->getValue()).lower();
349 if (S == "noref") {
350 Config->DoGC = false;
351 continue;
352 }
353 if (S != "ref" && S != "icf" && S != "noicf" &&
354 S != "lbr" && S != "nolbr" &&
355 !StringRef(S).startswith("icf=")) {
356 llvm::errs() << "/opt: unknown option: " << S << "\n";
357 return false;
358 }
359 }
360
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000361 // Handle /export
362 for (auto *Arg : Args->filtered(OPT_export)) {
363 ErrorOr<Export> E = parseExport(Arg->getValue());
364 if (E.getError())
365 return false;
366 Config->Exports.push_back(E.get());
367 }
368
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000369 // Handle /failifmismatch
Rui Ueyama75b098b2015-06-18 21:23:34 +0000370 for (auto *Arg : Args->filtered(OPT_failifmismatch))
371 if (checkFailIfMismatch(Arg->getValue()))
372 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000373
Rui Ueyama1f373702015-06-17 19:19:25 +0000374 // Handle /def
375 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
376 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
377 if (auto EC = MBOrErr.getError()) {
378 llvm::errs() << "/def: " << EC.message() << "\n";
379 return false;
380 }
381 // parseModuleDefs mutates Config object.
382 if (parseModuleDefs(MBOrErr.get()))
383 return false;
384 }
385
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000386 // Handle /manifest
387 if (auto *Arg = Args->getLastArg(OPT_manifest_colon)) {
388 if (auto EC = parseManifest(Arg->getValue())) {
389 llvm::errs() << "/manifest: " << EC.message() << "\n";
390 return false;
391 }
392 }
393
394 // Handle /manifestuac
395 if (auto *Arg = Args->getLastArg(OPT_manifestuac)) {
396 if (auto EC = parseManifestUAC(Arg->getValue())) {
397 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
398 return false;
399 }
400 }
401
402 // Handle /manifestdependency
403 if (auto *Arg = Args->getLastArg(OPT_manifestdependency))
404 Config->ManifestDependency = Arg->getValue();
405
406 // Handle /manifestfile
407 if (auto *Arg = Args->getLastArg(OPT_manifestfile))
408 Config->ManifestFile = Arg->getValue();
409
Rui Ueyama6592ff82015-06-16 23:13:00 +0000410 // Handle miscellaneous boolean flags.
411 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
412 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
413 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
414 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
415 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
416 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
417
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000418 // Create a list of input files. Files can be given as arguments
419 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000420 std::vector<StringRef> InputPaths;
421 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000422 for (auto *Arg : Args->filtered(OPT_INPUT))
423 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000424 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000425 for (auto *Arg : Args->filtered(OPT_defaultlib))
426 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000427 InputPaths.push_back(*Path);
428 for (StringRef Path : InputPaths) {
429 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
430 if (auto EC = MBOrErr.getError()) {
431 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
432 return false;
433 }
434 Inputs.push_back(MBOrErr.get());
435 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000436
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000437 // Create a symbol table.
438 SymbolTable Symtab;
439
440 // Add undefined symbols given via the command line.
441 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000442 for (auto *Arg : Args->filtered(OPT_incl)) {
443 StringRef Sym = Arg->getValue();
444 Symtab.addUndefined(Sym);
445 Config->GCRoots.insert(Sym);
446 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000447
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000448 // Windows specific -- Create a resource file containing a manifest file.
449 if (Config->Manifest == Configuration::Embed) {
450 auto MBOrErr = createManifestRes();
451 if (MBOrErr.getError())
452 return false;
453 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
454 Inputs.push_back(MB->getMemBufferRef());
455 OwningMBs.push_back(std::move(MB)); // take ownership
456 }
457
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000458 // Windows specific -- Input files can be Windows resource files (.res files).
459 // We invoke cvtres.exe to convert resource files to a regular COFF file
460 // then link the result file normally.
461 auto IsResource = [](MemoryBufferRef MB) {
462 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
463 };
464 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
465 if (It != Inputs.begin()) {
466 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
467 auto MBOrErr = convertResToCOFF(Files);
468 if (MBOrErr.getError())
469 return false;
470 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
471 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
472 Inputs.push_back(MB->getMemBufferRef());
473 OwningMBs.push_back(std::move(MB)); // take ownership
474 }
475
Rui Ueyama411c63602015-05-28 19:09:30 +0000476 // Parse all input files and put all symbols to the symbol table.
477 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000478 for (MemoryBufferRef MB : Inputs) {
479 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000480 if (Config->Verbose)
481 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000482 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000483 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000484 return false;
485 }
486 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000487
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000488 // Windows specific -- Make sure we resolve all dllexported symbols.
489 // (We don't cache the size here because Symtab.resolve() may add
490 // new entries to Config->Exports.)
491 for (size_t I = 0; I < Config->Exports.size(); ++I) {
492 StringRef Sym = Config->Exports[I].Name;
493 Symtab.addUndefined(Sym);
494 Config->GCRoots.insert(Sym);
495 }
496
Rui Ueyama5cff6852015-05-31 03:34:08 +0000497 // Windows specific -- If entry point name is not given, we need to
498 // infer that from user-defined entry name. The symbol table takes
499 // care of details.
500 if (Config->EntryName.empty()) {
501 auto EntryOrErr = Symtab.findDefaultEntry();
502 if (auto EC = EntryOrErr.getError()) {
503 llvm::errs() << EC.message() << "\n";
504 return false;
505 }
506 Config->EntryName = EntryOrErr.get();
507 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000508 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000509
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000510 // Add weak aliases. Weak aliases is a mechanism to give remaining
511 // undefined symbols final chance to be resolved successfully.
512 // This is symbol renaming.
513 for (size_t I = 0; I < Config->AlternateNames.size(); ++I) {
514 StringRef From = Config->AlternateNames[I].first;
515 StringRef To = Config->AlternateNames[I].second;
516 // If From is already resolved to a Defined type, do nothing.
517 // Otherwise, rename it to see if To can be resolved instead.
518 if (Symtab.find(From))
519 continue;
520 if (Config->Verbose)
521 llvm::outs() << "/alternatename:" << From << "=" << To << "\n";
522 if (auto EC = Symtab.rename(From, To)) {
523 llvm::errs() << EC.message() << "\n";
524 return false;
525 }
526 }
527
Rui Ueyama5cff6852015-05-31 03:34:08 +0000528 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000529 if (Symtab.reportRemainingUndefines())
530 return false;
531
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000532 // Do LTO by compiling bitcode input files to a native COFF file
533 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000534 if (auto EC = Symtab.addCombinedLTOObject()) {
535 llvm::errs() << EC.message() << "\n";
536 return false;
537 }
538
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000539 // Windows specific -- if no /subsystem is given, we need to infer
540 // that from entry point name.
541 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000542 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000543 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
544 llvm::errs() << "subsystem must be defined\n";
545 return false;
546 }
547 }
548
Rui Ueyama151d8622015-06-17 20:40:43 +0000549 // Windows specific -- when we are creating a .dll file, we also
550 // need to create a .lib file.
551 if (!Config->Exports.empty())
552 writeImportLibrary();
553
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000554 // Windows specific -- fix up dllexported symbols.
555 if (!Config->Exports.empty()) {
556 for (Export &E : Config->Exports)
557 E.Sym = Symtab.find(E.Name);
558 if (fixupExports())
559 return false;
560 }
561
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000562 // Windows specific -- Create a side-by-side manifest file.
563 if (Config->Manifest == Configuration::SideBySide)
564 if (createSideBySideManifest())
565 return false;
566
Rui Ueyama411c63602015-05-28 19:09:30 +0000567 // Write the result.
568 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000569 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000570 llvm::errs() << EC.message() << "\n";
571 return false;
572 }
573 return true;
574}
575
Rui Ueyama411c63602015-05-28 19:09:30 +0000576} // namespace coff
577} // namespace lld