blob: ef1600f2f78ea726288591731554a37b0f9574be [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;
121 default:
122 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
123 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000124 }
125 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000126 return std::error_code();
127}
128
Rui Ueyama54b71da2015-05-31 19:17:12 +0000129// Find file from search paths. You can omit ".obj", this function takes
130// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000131StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000132 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
133 if (hasPathSep)
134 return Filename;
135 bool hasExt = (Filename.find('.') != StringRef::npos);
136 for (StringRef Dir : SearchPaths) {
137 SmallString<128> Path = Dir;
138 llvm::sys::path::append(Path, Filename);
139 if (llvm::sys::fs::exists(Path.str()))
140 return Alloc.save(Path.str());
141 if (!hasExt) {
142 Path.append(".obj");
143 if (llvm::sys::fs::exists(Path.str()))
144 return Alloc.save(Path.str());
145 }
146 }
147 return Filename;
148}
149
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000150// Resolves a file path. This never returns the same path
151// (in that case, it returns None).
152Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
153 StringRef Path = doFindFile(Filename);
154 bool Seen = !VisitedFiles.insert(Path.lower()).second;
155 if (Seen)
156 return None;
157 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000158}
159
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000160// Find library file from search path.
161StringRef LinkerDriver::doFindLib(StringRef Filename) {
162 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000163 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000164 if (!hasExt)
165 Filename = Alloc.save(Filename + ".lib");
166 return doFindFile(Filename);
167}
168
169// Resolves a library path. /nodefaultlib options are taken into
170// consideration. This never returns the same path (in that case,
171// it returns None).
172Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
173 if (Config->NoDefaultLibAll)
174 return None;
175 StringRef Path = doFindLib(Filename);
176 if (Config->NoDefaultLibs.count(Path))
177 return None;
178 bool Seen = !VisitedFiles.insert(Path.lower()).second;
179 if (Seen)
180 return None;
181 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000182}
183
184// Parses LIB environment which contains a list of search paths.
185std::vector<StringRef> LinkerDriver::getSearchPaths() {
186 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000187 // Add current directory as first item of the search paths.
188 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000189 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
190 if (!EnvOpt.hasValue())
191 return Ret;
192 StringRef Env = Alloc.save(*EnvOpt);
193 while (!Env.empty()) {
194 StringRef Path;
195 std::tie(Path, Env) = Env.split(';');
196 Ret.push_back(Path);
197 }
198 return Ret;
199}
200
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000201static WindowsSubsystem inferSubsystem() {
202 if (Config->DLL)
203 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
204 return StringSwitch<WindowsSubsystem>(Config->EntryName)
205 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
206 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
207 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
208 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
209 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
210}
211
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000212bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000213 // Needed for LTO.
214 llvm::InitializeAllTargetInfos();
215 llvm::InitializeAllTargets();
216 llvm::InitializeAllTargetMCs();
217 llvm::InitializeAllAsmParsers();
218 llvm::InitializeAllAsmPrinters();
219 llvm::InitializeAllDisassemblers();
220
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000221 // If the first command line argument is "/lib", link.exe acts like lib.exe.
222 // We call our own implementation of lib.exe that understands bitcode files.
223 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
224 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
225
Rui Ueyama411c63602015-05-28 19:09:30 +0000226 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000227 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000228 if (auto EC = ArgsOrErr.getError()) {
229 llvm::errs() << EC.message() << "\n";
230 return false;
231 }
232 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
233
Rui Ueyama5c726432015-05-29 16:11:52 +0000234 // Handle /help
235 if (Args->hasArg(OPT_help)) {
236 printHelp(Argv[0]);
237 return true;
238 }
239
Rui Ueyama411c63602015-05-28 19:09:30 +0000240 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
241 llvm::errs() << "no input files.\n";
242 return false;
243 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000244
Rui Ueyamaad660982015-06-07 00:20:32 +0000245 // Handle /out
246 if (auto *Arg = Args->getLastArg(OPT_out))
247 Config->OutputFile = Arg->getValue();
248
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000249 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000250 if (Args->hasArg(OPT_verbose))
251 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000252
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000253 // Handle /dll
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000254 if (Args->hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000255 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000256 Config->ManifestID = 2;
257 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000258
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000259 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000260 if (auto *Arg = Args->getLastArg(OPT_entry))
261 Config->EntryName = Arg->getValue();
262
Rui Ueyama588e8322015-06-15 01:23:58 +0000263 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000264 if (Args->hasArg(OPT_fixed)) {
265 if (Args->hasArg(OPT_dynamicbase)) {
266 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
267 return false;
268 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000269 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000270 Config->DynamicBase = false;
271 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000272
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000273 // Handle /machine
274 auto MTOrErr = getMachineType(Args.get());
275 if (auto EC = MTOrErr.getError()) {
276 llvm::errs() << EC.message() << "\n";
277 return false;
278 }
279 Config->MachineType = MTOrErr.get();
280
Rui Ueyama06137472015-05-31 20:10:11 +0000281 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000282 for (auto *Arg : Args->filtered(OPT_libpath)) {
283 // Inserting at front of a vector is okay because it's short.
284 // +1 because the first entry is always "." (current directory).
285 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
286 }
Rui Ueyama06137472015-05-31 20:10:11 +0000287
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000288 // Handle /nodefaultlib:<filename>
289 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
290 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
291
292 // Handle /nodefaultlib
293 if (Args->hasArg(OPT_nodefaultlib_all))
294 Config->NoDefaultLibAll = true;
295
Rui Ueyama804a8b62015-05-29 16:18:15 +0000296 // Handle /base
297 if (auto *Arg = Args->getLastArg(OPT_base)) {
298 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000299 llvm::errs() << "/base: " << EC.message() << "\n";
300 return false;
301 }
302 }
303
304 // Handle /stack
305 if (auto *Arg = Args->getLastArg(OPT_stack)) {
306 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
307 &Config->StackCommit)) {
308 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000309 return false;
310 }
311 }
312
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000313 // Handle /heap
314 if (auto *Arg = Args->getLastArg(OPT_heap)) {
315 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
316 &Config->HeapCommit)) {
317 llvm::errs() << "/heap: " << EC.message() << "\n";
318 return false;
319 }
320 }
321
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000322 // Handle /version
323 if (auto *Arg = Args->getLastArg(OPT_version)) {
324 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
325 &Config->MinorImageVersion)) {
326 llvm::errs() << "/version: " << EC.message() << "\n";
327 return false;
328 }
329 }
330
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000331 // Handle /subsystem
332 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
333 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
334 &Config->MajorOSVersion,
335 &Config->MinorOSVersion)) {
336 llvm::errs() << "/subsystem: " << EC.message() << "\n";
337 return false;
338 }
339 }
340
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000341 // Handle /alternatename
342 for (auto *Arg : Args->filtered(OPT_alternatename))
343 if (parseAlternateName(Arg->getValue()))
344 return false;
345
Rui Ueyamab95188c2015-06-18 20:27:09 +0000346 // Handle /implib
347 if (auto *Arg = Args->getLastArg(OPT_implib))
348 Config->Implib = Arg->getValue();
349
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000350 // Handle /opt
351 for (auto *Arg : Args->filtered(OPT_opt)) {
352 std::string S = StringRef(Arg->getValue()).lower();
353 if (S == "noref") {
354 Config->DoGC = false;
355 continue;
356 }
357 if (S != "ref" && S != "icf" && S != "noicf" &&
358 S != "lbr" && S != "nolbr" &&
359 !StringRef(S).startswith("icf=")) {
360 llvm::errs() << "/opt: unknown option: " << S << "\n";
361 return false;
362 }
363 }
364
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000365 // Handle /export
366 for (auto *Arg : Args->filtered(OPT_export)) {
367 ErrorOr<Export> E = parseExport(Arg->getValue());
368 if (E.getError())
369 return false;
370 Config->Exports.push_back(E.get());
371 }
372
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000373 // Handle /failifmismatch
Rui Ueyama75b098b2015-06-18 21:23:34 +0000374 for (auto *Arg : Args->filtered(OPT_failifmismatch))
375 if (checkFailIfMismatch(Arg->getValue()))
376 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000377
Rui Ueyama1f373702015-06-17 19:19:25 +0000378 // Handle /def
379 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
380 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
381 if (auto EC = MBOrErr.getError()) {
382 llvm::errs() << "/def: " << EC.message() << "\n";
383 return false;
384 }
385 // parseModuleDefs mutates Config object.
386 if (parseModuleDefs(MBOrErr.get()))
387 return false;
388 }
389
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000390 // Handle /manifest
391 if (auto *Arg = Args->getLastArg(OPT_manifest_colon)) {
392 if (auto EC = parseManifest(Arg->getValue())) {
393 llvm::errs() << "/manifest: " << EC.message() << "\n";
394 return false;
395 }
396 }
397
398 // Handle /manifestuac
399 if (auto *Arg = Args->getLastArg(OPT_manifestuac)) {
400 if (auto EC = parseManifestUAC(Arg->getValue())) {
401 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
402 return false;
403 }
404 }
405
406 // Handle /manifestdependency
407 if (auto *Arg = Args->getLastArg(OPT_manifestdependency))
408 Config->ManifestDependency = Arg->getValue();
409
410 // Handle /manifestfile
411 if (auto *Arg = Args->getLastArg(OPT_manifestfile))
412 Config->ManifestFile = Arg->getValue();
413
Rui Ueyama6592ff82015-06-16 23:13:00 +0000414 // Handle miscellaneous boolean flags.
415 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
416 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
417 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
418 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
419 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
420 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
421
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000422 // Create a list of input files. Files can be given as arguments
423 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000424 std::vector<StringRef> InputPaths;
425 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000426 for (auto *Arg : Args->filtered(OPT_INPUT))
427 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000428 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000429 for (auto *Arg : Args->filtered(OPT_defaultlib))
430 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000431 InputPaths.push_back(*Path);
432 for (StringRef Path : InputPaths) {
433 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
434 if (auto EC = MBOrErr.getError()) {
435 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
436 return false;
437 }
438 Inputs.push_back(MBOrErr.get());
439 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000440
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000441 // Create a symbol table.
442 SymbolTable Symtab;
443
444 // Add undefined symbols given via the command line.
445 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000446 for (auto *Arg : Args->filtered(OPT_incl)) {
447 StringRef Sym = Arg->getValue();
448 Symtab.addUndefined(Sym);
449 Config->GCRoots.insert(Sym);
450 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000451
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000452 // Windows specific -- Create a resource file containing a manifest file.
453 if (Config->Manifest == Configuration::Embed) {
454 auto MBOrErr = createManifestRes();
455 if (MBOrErr.getError())
456 return false;
457 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
458 Inputs.push_back(MB->getMemBufferRef());
459 OwningMBs.push_back(std::move(MB)); // take ownership
460 }
461
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000462 // Windows specific -- Input files can be Windows resource files (.res files).
463 // We invoke cvtres.exe to convert resource files to a regular COFF file
464 // then link the result file normally.
465 auto IsResource = [](MemoryBufferRef MB) {
466 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
467 };
468 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
469 if (It != Inputs.begin()) {
470 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
471 auto MBOrErr = convertResToCOFF(Files);
472 if (MBOrErr.getError())
473 return false;
474 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
475 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
476 Inputs.push_back(MB->getMemBufferRef());
477 OwningMBs.push_back(std::move(MB)); // take ownership
478 }
479
Rui Ueyama411c63602015-05-28 19:09:30 +0000480 // Parse all input files and put all symbols to the symbol table.
481 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000482 for (MemoryBufferRef MB : Inputs) {
483 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000484 if (Config->Verbose)
485 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000486 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000487 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000488 return false;
489 }
490 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000491
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000492 // Windows specific -- Make sure we resolve all dllexported symbols.
493 // (We don't cache the size here because Symtab.resolve() may add
494 // new entries to Config->Exports.)
495 for (size_t I = 0; I < Config->Exports.size(); ++I) {
496 StringRef Sym = Config->Exports[I].Name;
497 Symtab.addUndefined(Sym);
498 Config->GCRoots.insert(Sym);
499 }
500
Rui Ueyama5cff6852015-05-31 03:34:08 +0000501 // Windows specific -- If entry point name is not given, we need to
502 // infer that from user-defined entry name. The symbol table takes
503 // care of details.
504 if (Config->EntryName.empty()) {
505 auto EntryOrErr = Symtab.findDefaultEntry();
506 if (auto EC = EntryOrErr.getError()) {
507 llvm::errs() << EC.message() << "\n";
508 return false;
509 }
510 Config->EntryName = EntryOrErr.get();
511 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000512 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000513
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000514 // Add weak aliases. Weak aliases is a mechanism to give remaining
515 // undefined symbols final chance to be resolved successfully.
516 // This is symbol renaming.
Rui Ueyamae8d56b52015-06-18 23:04:26 +0000517 for (auto &P : Config->AlternateNames) {
518 StringRef From = P.first;
519 StringRef To = P.second;
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000520 // If From is already resolved to a Defined type, do nothing.
521 // Otherwise, rename it to see if To can be resolved instead.
522 if (Symtab.find(From))
523 continue;
524 if (Config->Verbose)
525 llvm::outs() << "/alternatename:" << From << "=" << To << "\n";
526 if (auto EC = Symtab.rename(From, To)) {
527 llvm::errs() << EC.message() << "\n";
528 return false;
529 }
530 }
531
Rui Ueyama5cff6852015-05-31 03:34:08 +0000532 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000533 if (Symtab.reportRemainingUndefines())
534 return false;
535
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000536 // Do LTO by compiling bitcode input files to a native COFF file
537 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000538 if (auto EC = Symtab.addCombinedLTOObject()) {
539 llvm::errs() << EC.message() << "\n";
540 return false;
541 }
542
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000543 // Windows specific -- if no /subsystem is given, we need to infer
544 // that from entry point name.
545 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000546 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000547 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
548 llvm::errs() << "subsystem must be defined\n";
549 return false;
550 }
551 }
552
Rui Ueyama151d8622015-06-17 20:40:43 +0000553 // Windows specific -- when we are creating a .dll file, we also
554 // need to create a .lib file.
555 if (!Config->Exports.empty())
556 writeImportLibrary();
557
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000558 // Windows specific -- fix up dllexported symbols.
559 if (!Config->Exports.empty()) {
560 for (Export &E : Config->Exports)
561 E.Sym = Symtab.find(E.Name);
562 if (fixupExports())
563 return false;
564 }
565
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000566 // Windows specific -- Create a side-by-side manifest file.
567 if (Config->Manifest == Configuration::SideBySide)
568 if (createSideBySideManifest())
569 return false;
570
Rui Ueyama411c63602015-05-28 19:09:30 +0000571 // Write the result.
572 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000573 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000574 llvm::errs() << EC.message() << "\n";
575 return false;
576 }
577 return true;
578}
579
Rui Ueyama411c63602015-05-28 19:09:30 +0000580} // namespace coff
581} // namespace lld