blob: 80581bdfb00ec5987ffe1ad699afc96ad483d935 [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"
Rui Ueyama562daa82015-06-18 21:50:38 +000012#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "SymbolTable.h"
15#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000018#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000019#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Option/Option.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000026#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000027#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000028#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000029#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include <memory>
31
32using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000033using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
34using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
35using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000036using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000037using llvm::sys::fs::file_magic;
38using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000039
Rui Ueyama3500f662015-05-28 20:30:06 +000040namespace lld {
41namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000042
Rui Ueyama3500f662015-05-28 20:30:06 +000043Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000044LinkerDriver *Driver;
45
46bool link(int Argc, const char *Argv[]) {
47 auto C = make_unique<Configuration>();
48 Config = C.get();
49 auto D = make_unique<LinkerDriver>();
50 Driver = D.get();
51 return Driver->link(Argc, Argv);
52}
Rui Ueyama411c63602015-05-28 19:09:30 +000053
Rui Ueyamaad660982015-06-07 00:20:32 +000054// Drop directory components and replace extension with ".exe".
55static std::string getOutputPath(StringRef Path) {
56 auto P = Path.find_last_of("\\/");
57 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
58 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000059}
60
Rui Ueyamad7c2f582015-05-31 21:04:56 +000061// Opens a file. Path has to be resolved already.
62// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000063ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000064 auto MBOrErr = MemoryBuffer::getFile(Path);
65 if (auto EC = MBOrErr.getError())
66 return EC;
67 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
68 MemoryBufferRef MBRef = MB->getMemBufferRef();
69 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000070 return MBRef;
71}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000072
Rui Ueyama2bf6a122015-06-14 21:50:50 +000073static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000074 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000075 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000076 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000077 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000078 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000079 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000080 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000081 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
82 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000083}
84
Rui Ueyama411c63602015-05-28 19:09:30 +000085// Parses .drectve section contents and returns a list of files
86// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000087std::error_code
88LinkerDriver::parseDirectives(StringRef S,
89 std::vector<std::unique_ptr<InputFile>> *Res) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000090 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000091 if (auto EC = ArgsOrErr.getError())
92 return EC;
93 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
94
Rui Ueyama562daa82015-06-18 21:50:38 +000095 for (auto *Arg : *Args) {
96 switch (Arg->getOption().getID()) {
97 case OPT_alternatename:
98 if (auto EC = parseAlternateName(Arg->getValue()))
Rui Ueyamad7c2f582015-05-31 21:04:56 +000099 return EC;
Rui Ueyama562daa82015-06-18 21:50:38 +0000100 break;
101 case OPT_defaultlib:
102 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
103 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
104 if (auto EC = MBOrErr.getError())
105 return EC;
106 std::unique_ptr<InputFile> File = createFile(MBOrErr.get());
107 Res->push_back(std::move(File));
108 }
109 break;
110 case OPT_export: {
111 ErrorOr<Export> E = parseExport(Arg->getValue());
112 if (auto EC = E.getError())
113 return EC;
114 Config->Exports.push_back(E.get());
115 break;
116 }
117 case OPT_failifmismatch:
118 if (auto EC = checkFailIfMismatch(Arg->getValue()))
119 return EC;
120 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000121 case OPT_incl:
122 Config->Includes.insert(Arg->getValue());
123 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000124 default:
125 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
126 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000127 }
128 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000129 return std::error_code();
130}
131
Rui Ueyama54b71da2015-05-31 19:17:12 +0000132// Find file from search paths. You can omit ".obj", this function takes
133// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000134StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000135 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
136 if (hasPathSep)
137 return Filename;
138 bool hasExt = (Filename.find('.') != StringRef::npos);
139 for (StringRef Dir : SearchPaths) {
140 SmallString<128> Path = Dir;
141 llvm::sys::path::append(Path, Filename);
142 if (llvm::sys::fs::exists(Path.str()))
143 return Alloc.save(Path.str());
144 if (!hasExt) {
145 Path.append(".obj");
146 if (llvm::sys::fs::exists(Path.str()))
147 return Alloc.save(Path.str());
148 }
149 }
150 return Filename;
151}
152
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000153// Resolves a file path. This never returns the same path
154// (in that case, it returns None).
155Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
156 StringRef Path = doFindFile(Filename);
157 bool Seen = !VisitedFiles.insert(Path.lower()).second;
158 if (Seen)
159 return None;
160 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000161}
162
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000163// Find library file from search path.
164StringRef LinkerDriver::doFindLib(StringRef Filename) {
165 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000166 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000167 if (!hasExt)
168 Filename = Alloc.save(Filename + ".lib");
169 return doFindFile(Filename);
170}
171
172// Resolves a library path. /nodefaultlib options are taken into
173// consideration. This never returns the same path (in that case,
174// it returns None).
175Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
176 if (Config->NoDefaultLibAll)
177 return None;
178 StringRef Path = doFindLib(Filename);
179 if (Config->NoDefaultLibs.count(Path))
180 return None;
181 bool Seen = !VisitedFiles.insert(Path.lower()).second;
182 if (Seen)
183 return None;
184 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000185}
186
187// Parses LIB environment which contains a list of search paths.
188std::vector<StringRef> LinkerDriver::getSearchPaths() {
189 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000190 // Add current directory as first item of the search paths.
191 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000192 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
193 if (!EnvOpt.hasValue())
194 return Ret;
195 StringRef Env = Alloc.save(*EnvOpt);
196 while (!Env.empty()) {
197 StringRef Path;
198 std::tie(Path, Env) = Env.split(';');
199 Ret.push_back(Path);
200 }
201 return Ret;
202}
203
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000204static WindowsSubsystem inferSubsystem() {
205 if (Config->DLL)
206 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
207 return StringSwitch<WindowsSubsystem>(Config->EntryName)
208 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
209 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
210 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
211 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
212 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
213}
214
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000215bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000216 // Needed for LTO.
217 llvm::InitializeAllTargetInfos();
218 llvm::InitializeAllTargets();
219 llvm::InitializeAllTargetMCs();
220 llvm::InitializeAllAsmParsers();
221 llvm::InitializeAllAsmPrinters();
222 llvm::InitializeAllDisassemblers();
223
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000224 // If the first command line argument is "/lib", link.exe acts like lib.exe.
225 // We call our own implementation of lib.exe that understands bitcode files.
226 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
227 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
228
Rui Ueyama411c63602015-05-28 19:09:30 +0000229 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000230 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000231 if (auto EC = ArgsOrErr.getError()) {
232 llvm::errs() << EC.message() << "\n";
233 return false;
234 }
235 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
236
Rui Ueyama5c726432015-05-29 16:11:52 +0000237 // Handle /help
238 if (Args->hasArg(OPT_help)) {
239 printHelp(Argv[0]);
240 return true;
241 }
242
Rui Ueyama411c63602015-05-28 19:09:30 +0000243 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
244 llvm::errs() << "no input files.\n";
245 return false;
246 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000247
Rui Ueyamaad660982015-06-07 00:20:32 +0000248 // Handle /out
249 if (auto *Arg = Args->getLastArg(OPT_out))
250 Config->OutputFile = Arg->getValue();
251
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000252 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000253 if (Args->hasArg(OPT_verbose))
254 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000255
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000256 // Handle /dll
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000257 if (Args->hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000258 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000259 Config->ManifestID = 2;
260 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000261
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000262 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000263 if (auto *Arg = Args->getLastArg(OPT_entry))
264 Config->EntryName = Arg->getValue();
265
Rui Ueyama588e8322015-06-15 01:23:58 +0000266 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000267 if (Args->hasArg(OPT_fixed)) {
268 if (Args->hasArg(OPT_dynamicbase)) {
269 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
270 return false;
271 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000272 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000273 Config->DynamicBase = false;
274 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000275
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000276 // Handle /machine
277 auto MTOrErr = getMachineType(Args.get());
278 if (auto EC = MTOrErr.getError()) {
279 llvm::errs() << EC.message() << "\n";
280 return false;
281 }
282 Config->MachineType = MTOrErr.get();
283
Rui Ueyama06137472015-05-31 20:10:11 +0000284 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000285 for (auto *Arg : Args->filtered(OPT_libpath)) {
286 // Inserting at front of a vector is okay because it's short.
287 // +1 because the first entry is always "." (current directory).
288 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
289 }
Rui Ueyama06137472015-05-31 20:10:11 +0000290
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000291 // Handle /nodefaultlib:<filename>
292 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
293 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
294
295 // Handle /nodefaultlib
296 if (Args->hasArg(OPT_nodefaultlib_all))
297 Config->NoDefaultLibAll = true;
298
Rui Ueyama804a8b62015-05-29 16:18:15 +0000299 // Handle /base
300 if (auto *Arg = Args->getLastArg(OPT_base)) {
301 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000302 llvm::errs() << "/base: " << EC.message() << "\n";
303 return false;
304 }
305 }
306
307 // Handle /stack
308 if (auto *Arg = Args->getLastArg(OPT_stack)) {
309 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
310 &Config->StackCommit)) {
311 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000312 return false;
313 }
314 }
315
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000316 // Handle /heap
317 if (auto *Arg = Args->getLastArg(OPT_heap)) {
318 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
319 &Config->HeapCommit)) {
320 llvm::errs() << "/heap: " << EC.message() << "\n";
321 return false;
322 }
323 }
324
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000325 // Handle /version
326 if (auto *Arg = Args->getLastArg(OPT_version)) {
327 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
328 &Config->MinorImageVersion)) {
329 llvm::errs() << "/version: " << EC.message() << "\n";
330 return false;
331 }
332 }
333
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000334 // Handle /subsystem
335 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
336 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
337 &Config->MajorOSVersion,
338 &Config->MinorOSVersion)) {
339 llvm::errs() << "/subsystem: " << EC.message() << "\n";
340 return false;
341 }
342 }
343
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000344 // Handle /alternatename
345 for (auto *Arg : Args->filtered(OPT_alternatename))
346 if (parseAlternateName(Arg->getValue()))
347 return false;
348
Rui Ueyama08d5e182015-06-18 23:20:11 +0000349 // Handle /include
350 for (auto *Arg : Args->filtered(OPT_incl))
351 Config->Includes.insert(Arg->getValue());
352
Rui Ueyamab95188c2015-06-18 20:27:09 +0000353 // Handle /implib
354 if (auto *Arg = Args->getLastArg(OPT_implib))
355 Config->Implib = Arg->getValue();
356
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000357 // Handle /opt
358 for (auto *Arg : Args->filtered(OPT_opt)) {
359 std::string S = StringRef(Arg->getValue()).lower();
360 if (S == "noref") {
361 Config->DoGC = false;
362 continue;
363 }
364 if (S != "ref" && S != "icf" && S != "noicf" &&
365 S != "lbr" && S != "nolbr" &&
366 !StringRef(S).startswith("icf=")) {
367 llvm::errs() << "/opt: unknown option: " << S << "\n";
368 return false;
369 }
370 }
371
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000372 // Handle /export
373 for (auto *Arg : Args->filtered(OPT_export)) {
374 ErrorOr<Export> E = parseExport(Arg->getValue());
375 if (E.getError())
376 return false;
377 Config->Exports.push_back(E.get());
378 }
379
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000380 // Handle /failifmismatch
Rui Ueyama75b098b2015-06-18 21:23:34 +0000381 for (auto *Arg : Args->filtered(OPT_failifmismatch))
382 if (checkFailIfMismatch(Arg->getValue()))
383 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000384
Rui Ueyama1f373702015-06-17 19:19:25 +0000385 // Handle /def
386 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
387 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
388 if (auto EC = MBOrErr.getError()) {
389 llvm::errs() << "/def: " << EC.message() << "\n";
390 return false;
391 }
392 // parseModuleDefs mutates Config object.
393 if (parseModuleDefs(MBOrErr.get()))
394 return false;
395 }
396
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000397 // Handle /manifest
398 if (auto *Arg = Args->getLastArg(OPT_manifest_colon)) {
399 if (auto EC = parseManifest(Arg->getValue())) {
400 llvm::errs() << "/manifest: " << EC.message() << "\n";
401 return false;
402 }
403 }
404
405 // Handle /manifestuac
406 if (auto *Arg = Args->getLastArg(OPT_manifestuac)) {
407 if (auto EC = parseManifestUAC(Arg->getValue())) {
408 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
409 return false;
410 }
411 }
412
413 // Handle /manifestdependency
414 if (auto *Arg = Args->getLastArg(OPT_manifestdependency))
415 Config->ManifestDependency = Arg->getValue();
416
417 // Handle /manifestfile
418 if (auto *Arg = Args->getLastArg(OPT_manifestfile))
419 Config->ManifestFile = Arg->getValue();
420
Rui Ueyama6592ff82015-06-16 23:13:00 +0000421 // Handle miscellaneous boolean flags.
422 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
423 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
424 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
425 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
426 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
427 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
428
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000429 // Create a list of input files. Files can be given as arguments
430 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000431 std::vector<StringRef> InputPaths;
432 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000433 for (auto *Arg : Args->filtered(OPT_INPUT))
434 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000435 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000436 for (auto *Arg : Args->filtered(OPT_defaultlib))
437 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000438 InputPaths.push_back(*Path);
439 for (StringRef Path : InputPaths) {
440 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
441 if (auto EC = MBOrErr.getError()) {
442 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
443 return false;
444 }
445 Inputs.push_back(MBOrErr.get());
446 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000447
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000448 // Create a symbol table.
449 SymbolTable Symtab;
450
451 // Add undefined symbols given via the command line.
452 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyama08d5e182015-06-18 23:20:11 +0000453 for (StringRef Sym : Config->Includes)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000454 Symtab.addUndefined(Sym);
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000455
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000456 // Windows specific -- Create a resource file containing a manifest file.
457 if (Config->Manifest == Configuration::Embed) {
458 auto MBOrErr = createManifestRes();
459 if (MBOrErr.getError())
460 return false;
461 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
462 Inputs.push_back(MB->getMemBufferRef());
463 OwningMBs.push_back(std::move(MB)); // take ownership
464 }
465
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000466 // Windows specific -- Input files can be Windows resource files (.res files).
467 // We invoke cvtres.exe to convert resource files to a regular COFF file
468 // then link the result file normally.
469 auto IsResource = [](MemoryBufferRef MB) {
470 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
471 };
472 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
473 if (It != Inputs.begin()) {
474 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
475 auto MBOrErr = convertResToCOFF(Files);
476 if (MBOrErr.getError())
477 return false;
478 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
479 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
480 Inputs.push_back(MB->getMemBufferRef());
481 OwningMBs.push_back(std::move(MB)); // take ownership
482 }
483
Rui Ueyama411c63602015-05-28 19:09:30 +0000484 // Parse all input files and put all symbols to the symbol table.
485 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000486 for (MemoryBufferRef MB : Inputs) {
487 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000488 if (Config->Verbose)
489 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000490 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000491 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000492 return false;
493 }
494 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000495
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);
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000502 }
503
Rui Ueyama5cff6852015-05-31 03:34:08 +0000504 // Windows specific -- If entry point name is not given, we need to
505 // infer that from user-defined entry name. The symbol table takes
506 // care of details.
507 if (Config->EntryName.empty()) {
508 auto EntryOrErr = Symtab.findDefaultEntry();
509 if (auto EC = EntryOrErr.getError()) {
510 llvm::errs() << EC.message() << "\n";
511 return false;
512 }
513 Config->EntryName = EntryOrErr.get();
514 }
515
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000516 // Add weak aliases. Weak aliases is a mechanism to give remaining
517 // undefined symbols final chance to be resolved successfully.
518 // This is symbol renaming.
Rui Ueyamae8d56b52015-06-18 23:04:26 +0000519 for (auto &P : Config->AlternateNames) {
520 StringRef From = P.first;
521 StringRef To = P.second;
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000522 // If From is already resolved to a Defined type, do nothing.
523 // Otherwise, rename it to see if To can be resolved instead.
524 if (Symtab.find(From))
525 continue;
526 if (Config->Verbose)
527 llvm::outs() << "/alternatename:" << From << "=" << To << "\n";
528 if (auto EC = Symtab.rename(From, To)) {
529 llvm::errs() << EC.message() << "\n";
530 return false;
531 }
532 }
533
Rui Ueyama5cff6852015-05-31 03:34:08 +0000534 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000535 if (Symtab.reportRemainingUndefines())
536 return false;
537
Rui Ueyama08d5e182015-06-18 23:20:11 +0000538 // Initialize a list of GC root.
539 for (StringRef Sym : Config->Includes)
540 Config->GCRoots.insert(Sym);
541 for (Export &E : Config->Exports)
542 Config->GCRoots.insert(E.Name);
543 Config->GCRoots.insert(Config->EntryName);
544
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000545 // Do LTO by compiling bitcode input files to a native COFF file
546 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000547 if (auto EC = Symtab.addCombinedLTOObject()) {
548 llvm::errs() << EC.message() << "\n";
549 return false;
550 }
551
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000552 // Windows specific -- if no /subsystem is given, we need to infer
553 // that from entry point name.
554 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000555 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000556 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
557 llvm::errs() << "subsystem must be defined\n";
558 return false;
559 }
560 }
561
Rui Ueyama151d8622015-06-17 20:40:43 +0000562 // Windows specific -- when we are creating a .dll file, we also
563 // need to create a .lib file.
564 if (!Config->Exports.empty())
565 writeImportLibrary();
566
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000567 // Windows specific -- fix up dllexported symbols.
568 if (!Config->Exports.empty()) {
569 for (Export &E : Config->Exports)
570 E.Sym = Symtab.find(E.Name);
571 if (fixupExports())
572 return false;
573 }
574
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000575 // Windows specific -- Create a side-by-side manifest file.
576 if (Config->Manifest == Configuration::SideBySide)
577 if (createSideBySideManifest())
578 return false;
579
Rui Ueyama411c63602015-05-28 19:09:30 +0000580 // Write the result.
581 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000582 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000583 llvm::errs() << EC.message() << "\n";
584 return false;
585 }
586 return true;
587}
588
Rui Ueyama411c63602015-05-28 19:09:30 +0000589} // namespace coff
590} // namespace lld