blob: d73a9efd19438dc8a5e19ce836410eae93594a73 [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 Ueyamace86c992015-06-18 23:22:39 +0000124 case OPT_merge:
125 // Ignore /merge for now.
126 break;
127 case OPT_nodefaultlib:
128 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
129 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000130 default:
131 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
132 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000133 }
134 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000135 return std::error_code();
136}
137
Rui Ueyama54b71da2015-05-31 19:17:12 +0000138// Find file from search paths. You can omit ".obj", this function takes
139// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000140StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000141 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
142 if (hasPathSep)
143 return Filename;
144 bool hasExt = (Filename.find('.') != StringRef::npos);
145 for (StringRef Dir : SearchPaths) {
146 SmallString<128> Path = Dir;
147 llvm::sys::path::append(Path, Filename);
148 if (llvm::sys::fs::exists(Path.str()))
149 return Alloc.save(Path.str());
150 if (!hasExt) {
151 Path.append(".obj");
152 if (llvm::sys::fs::exists(Path.str()))
153 return Alloc.save(Path.str());
154 }
155 }
156 return Filename;
157}
158
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000159// Resolves a file path. This never returns the same path
160// (in that case, it returns None).
161Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
162 StringRef Path = doFindFile(Filename);
163 bool Seen = !VisitedFiles.insert(Path.lower()).second;
164 if (Seen)
165 return None;
166 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000167}
168
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000169// Find library file from search path.
170StringRef LinkerDriver::doFindLib(StringRef Filename) {
171 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000172 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000173 if (!hasExt)
174 Filename = Alloc.save(Filename + ".lib");
175 return doFindFile(Filename);
176}
177
178// Resolves a library path. /nodefaultlib options are taken into
179// consideration. This never returns the same path (in that case,
180// it returns None).
181Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
182 if (Config->NoDefaultLibAll)
183 return None;
184 StringRef Path = doFindLib(Filename);
185 if (Config->NoDefaultLibs.count(Path))
186 return None;
187 bool Seen = !VisitedFiles.insert(Path.lower()).second;
188 if (Seen)
189 return None;
190 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000191}
192
193// Parses LIB environment which contains a list of search paths.
194std::vector<StringRef> LinkerDriver::getSearchPaths() {
195 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000196 // Add current directory as first item of the search paths.
197 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000198 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
199 if (!EnvOpt.hasValue())
200 return Ret;
201 StringRef Env = Alloc.save(*EnvOpt);
202 while (!Env.empty()) {
203 StringRef Path;
204 std::tie(Path, Env) = Env.split(';');
205 Ret.push_back(Path);
206 }
207 return Ret;
208}
209
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000210static WindowsSubsystem inferSubsystem() {
211 if (Config->DLL)
212 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
213 return StringSwitch<WindowsSubsystem>(Config->EntryName)
214 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
215 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
216 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
217 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
218 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
219}
220
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000221bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000222 // Needed for LTO.
223 llvm::InitializeAllTargetInfos();
224 llvm::InitializeAllTargets();
225 llvm::InitializeAllTargetMCs();
226 llvm::InitializeAllAsmParsers();
227 llvm::InitializeAllAsmPrinters();
228 llvm::InitializeAllDisassemblers();
229
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000230 // If the first command line argument is "/lib", link.exe acts like lib.exe.
231 // We call our own implementation of lib.exe that understands bitcode files.
232 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
233 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
234
Rui Ueyama411c63602015-05-28 19:09:30 +0000235 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000236 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000237 if (auto EC = ArgsOrErr.getError()) {
238 llvm::errs() << EC.message() << "\n";
239 return false;
240 }
241 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
242
Rui Ueyama5c726432015-05-29 16:11:52 +0000243 // Handle /help
244 if (Args->hasArg(OPT_help)) {
245 printHelp(Argv[0]);
246 return true;
247 }
248
Rui Ueyama411c63602015-05-28 19:09:30 +0000249 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
250 llvm::errs() << "no input files.\n";
251 return false;
252 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000253
Rui Ueyamaad660982015-06-07 00:20:32 +0000254 // Handle /out
255 if (auto *Arg = Args->getLastArg(OPT_out))
256 Config->OutputFile = Arg->getValue();
257
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000258 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000259 if (Args->hasArg(OPT_verbose))
260 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000261
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000262 // Handle /dll
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000263 if (Args->hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000264 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000265 Config->ManifestID = 2;
266 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000267
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000268 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000269 if (auto *Arg = Args->getLastArg(OPT_entry))
270 Config->EntryName = Arg->getValue();
271
Rui Ueyama588e8322015-06-15 01:23:58 +0000272 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000273 if (Args->hasArg(OPT_fixed)) {
274 if (Args->hasArg(OPT_dynamicbase)) {
275 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
276 return false;
277 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000278 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000279 Config->DynamicBase = false;
280 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000281
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000282 // Handle /machine
283 auto MTOrErr = getMachineType(Args.get());
284 if (auto EC = MTOrErr.getError()) {
285 llvm::errs() << EC.message() << "\n";
286 return false;
287 }
288 Config->MachineType = MTOrErr.get();
289
Rui Ueyama06137472015-05-31 20:10:11 +0000290 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000291 for (auto *Arg : Args->filtered(OPT_libpath)) {
292 // Inserting at front of a vector is okay because it's short.
293 // +1 because the first entry is always "." (current directory).
294 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
295 }
Rui Ueyama06137472015-05-31 20:10:11 +0000296
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000297 // Handle /nodefaultlib:<filename>
298 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
299 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
300
301 // Handle /nodefaultlib
302 if (Args->hasArg(OPT_nodefaultlib_all))
303 Config->NoDefaultLibAll = true;
304
Rui Ueyama804a8b62015-05-29 16:18:15 +0000305 // Handle /base
306 if (auto *Arg = Args->getLastArg(OPT_base)) {
307 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000308 llvm::errs() << "/base: " << EC.message() << "\n";
309 return false;
310 }
311 }
312
313 // Handle /stack
314 if (auto *Arg = Args->getLastArg(OPT_stack)) {
315 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
316 &Config->StackCommit)) {
317 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000318 return false;
319 }
320 }
321
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000322 // Handle /heap
323 if (auto *Arg = Args->getLastArg(OPT_heap)) {
324 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
325 &Config->HeapCommit)) {
326 llvm::errs() << "/heap: " << EC.message() << "\n";
327 return false;
328 }
329 }
330
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000331 // Handle /version
332 if (auto *Arg = Args->getLastArg(OPT_version)) {
333 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
334 &Config->MinorImageVersion)) {
335 llvm::errs() << "/version: " << EC.message() << "\n";
336 return false;
337 }
338 }
339
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000340 // Handle /subsystem
341 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
342 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
343 &Config->MajorOSVersion,
344 &Config->MinorOSVersion)) {
345 llvm::errs() << "/subsystem: " << EC.message() << "\n";
346 return false;
347 }
348 }
349
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000350 // Handle /alternatename
351 for (auto *Arg : Args->filtered(OPT_alternatename))
352 if (parseAlternateName(Arg->getValue()))
353 return false;
354
Rui Ueyama08d5e182015-06-18 23:20:11 +0000355 // Handle /include
356 for (auto *Arg : Args->filtered(OPT_incl))
357 Config->Includes.insert(Arg->getValue());
358
Rui Ueyamab95188c2015-06-18 20:27:09 +0000359 // Handle /implib
360 if (auto *Arg = Args->getLastArg(OPT_implib))
361 Config->Implib = Arg->getValue();
362
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000363 // Handle /opt
364 for (auto *Arg : Args->filtered(OPT_opt)) {
365 std::string S = StringRef(Arg->getValue()).lower();
366 if (S == "noref") {
367 Config->DoGC = false;
368 continue;
369 }
370 if (S != "ref" && S != "icf" && S != "noicf" &&
371 S != "lbr" && S != "nolbr" &&
372 !StringRef(S).startswith("icf=")) {
373 llvm::errs() << "/opt: unknown option: " << S << "\n";
374 return false;
375 }
376 }
377
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000378 // Handle /export
379 for (auto *Arg : Args->filtered(OPT_export)) {
380 ErrorOr<Export> E = parseExport(Arg->getValue());
381 if (E.getError())
382 return false;
383 Config->Exports.push_back(E.get());
384 }
385
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000386 // Handle /failifmismatch
Rui Ueyama75b098b2015-06-18 21:23:34 +0000387 for (auto *Arg : Args->filtered(OPT_failifmismatch))
388 if (checkFailIfMismatch(Arg->getValue()))
389 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000390
Rui Ueyama1f373702015-06-17 19:19:25 +0000391 // Handle /def
392 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
393 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
394 if (auto EC = MBOrErr.getError()) {
395 llvm::errs() << "/def: " << EC.message() << "\n";
396 return false;
397 }
398 // parseModuleDefs mutates Config object.
399 if (parseModuleDefs(MBOrErr.get()))
400 return false;
401 }
402
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000403 // Handle /manifest
404 if (auto *Arg = Args->getLastArg(OPT_manifest_colon)) {
405 if (auto EC = parseManifest(Arg->getValue())) {
406 llvm::errs() << "/manifest: " << EC.message() << "\n";
407 return false;
408 }
409 }
410
411 // Handle /manifestuac
412 if (auto *Arg = Args->getLastArg(OPT_manifestuac)) {
413 if (auto EC = parseManifestUAC(Arg->getValue())) {
414 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
415 return false;
416 }
417 }
418
419 // Handle /manifestdependency
420 if (auto *Arg = Args->getLastArg(OPT_manifestdependency))
421 Config->ManifestDependency = Arg->getValue();
422
423 // Handle /manifestfile
424 if (auto *Arg = Args->getLastArg(OPT_manifestfile))
425 Config->ManifestFile = Arg->getValue();
426
Rui Ueyama6592ff82015-06-16 23:13:00 +0000427 // Handle miscellaneous boolean flags.
428 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
429 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
430 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
431 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
432 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
433 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
434
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000435 // Create a list of input files. Files can be given as arguments
436 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000437 std::vector<StringRef> InputPaths;
438 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000439 for (auto *Arg : Args->filtered(OPT_INPUT))
440 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000441 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000442 for (auto *Arg : Args->filtered(OPT_defaultlib))
443 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000444 InputPaths.push_back(*Path);
445 for (StringRef Path : InputPaths) {
446 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
447 if (auto EC = MBOrErr.getError()) {
448 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
449 return false;
450 }
451 Inputs.push_back(MBOrErr.get());
452 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000453
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000454 // Create a symbol table.
455 SymbolTable Symtab;
456
457 // Add undefined symbols given via the command line.
458 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyama08d5e182015-06-18 23:20:11 +0000459 for (StringRef Sym : Config->Includes)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000460 Symtab.addUndefined(Sym);
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000461
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000462 // Windows specific -- Create a resource file containing a manifest file.
463 if (Config->Manifest == Configuration::Embed) {
464 auto MBOrErr = createManifestRes();
465 if (MBOrErr.getError())
466 return false;
467 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
468 Inputs.push_back(MB->getMemBufferRef());
469 OwningMBs.push_back(std::move(MB)); // take ownership
470 }
471
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000472 // Windows specific -- Input files can be Windows resource files (.res files).
473 // We invoke cvtres.exe to convert resource files to a regular COFF file
474 // then link the result file normally.
475 auto IsResource = [](MemoryBufferRef MB) {
476 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
477 };
478 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
479 if (It != Inputs.begin()) {
480 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
481 auto MBOrErr = convertResToCOFF(Files);
482 if (MBOrErr.getError())
483 return false;
484 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
485 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
486 Inputs.push_back(MB->getMemBufferRef());
487 OwningMBs.push_back(std::move(MB)); // take ownership
488 }
489
Rui Ueyama411c63602015-05-28 19:09:30 +0000490 // Parse all input files and put all symbols to the symbol table.
491 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000492 for (MemoryBufferRef MB : Inputs) {
493 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000494 if (Config->Verbose)
495 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000496 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000497 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000498 return false;
499 }
500 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000501
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000502 // Windows specific -- Make sure we resolve all dllexported symbols.
503 // (We don't cache the size here because Symtab.resolve() may add
504 // new entries to Config->Exports.)
505 for (size_t I = 0; I < Config->Exports.size(); ++I) {
506 StringRef Sym = Config->Exports[I].Name;
507 Symtab.addUndefined(Sym);
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000508 }
509
Rui Ueyama5cff6852015-05-31 03:34:08 +0000510 // Windows specific -- If entry point name is not given, we need to
511 // infer that from user-defined entry name. The symbol table takes
512 // care of details.
513 if (Config->EntryName.empty()) {
514 auto EntryOrErr = Symtab.findDefaultEntry();
515 if (auto EC = EntryOrErr.getError()) {
516 llvm::errs() << EC.message() << "\n";
517 return false;
518 }
519 Config->EntryName = EntryOrErr.get();
520 }
521
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000522 // Add weak aliases. Weak aliases is a mechanism to give remaining
523 // undefined symbols final chance to be resolved successfully.
524 // This is symbol renaming.
Rui Ueyamae8d56b52015-06-18 23:04:26 +0000525 for (auto &P : Config->AlternateNames) {
526 StringRef From = P.first;
527 StringRef To = P.second;
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000528 // If From is already resolved to a Defined type, do nothing.
529 // Otherwise, rename it to see if To can be resolved instead.
530 if (Symtab.find(From))
531 continue;
532 if (Config->Verbose)
533 llvm::outs() << "/alternatename:" << From << "=" << To << "\n";
534 if (auto EC = Symtab.rename(From, To)) {
535 llvm::errs() << EC.message() << "\n";
536 return false;
537 }
538 }
539
Rui Ueyama5cff6852015-05-31 03:34:08 +0000540 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000541 if (Symtab.reportRemainingUndefines())
542 return false;
543
Rui Ueyama08d5e182015-06-18 23:20:11 +0000544 // Initialize a list of GC root.
545 for (StringRef Sym : Config->Includes)
546 Config->GCRoots.insert(Sym);
547 for (Export &E : Config->Exports)
548 Config->GCRoots.insert(E.Name);
549 Config->GCRoots.insert(Config->EntryName);
550
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000551 // Do LTO by compiling bitcode input files to a native COFF file
552 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000553 if (auto EC = Symtab.addCombinedLTOObject()) {
554 llvm::errs() << EC.message() << "\n";
555 return false;
556 }
557
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000558 // Windows specific -- if no /subsystem is given, we need to infer
559 // that from entry point name.
560 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000561 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000562 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
563 llvm::errs() << "subsystem must be defined\n";
564 return false;
565 }
566 }
567
Rui Ueyama151d8622015-06-17 20:40:43 +0000568 // Windows specific -- when we are creating a .dll file, we also
569 // need to create a .lib file.
570 if (!Config->Exports.empty())
571 writeImportLibrary();
572
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000573 // Windows specific -- fix up dllexported symbols.
574 if (!Config->Exports.empty()) {
575 for (Export &E : Config->Exports)
576 E.Sym = Symtab.find(E.Name);
577 if (fixupExports())
578 return false;
579 }
580
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000581 // Windows specific -- Create a side-by-side manifest file.
582 if (Config->Manifest == Configuration::SideBySide)
583 if (createSideBySideManifest())
584 return false;
585
Rui Ueyama411c63602015-05-28 19:09:30 +0000586 // Write the result.
587 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000588 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000589 llvm::errs() << EC.message() << "\n";
590 return false;
591 }
592 return true;
593}
594
Rui Ueyama411c63602015-05-28 19:09:30 +0000595} // namespace coff
596} // namespace lld