blob: be13aa971b88c40d07674fae04488d24641107de [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- Driver.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Config.h"
11#include "Driver.h"
12#include "InputFiles.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "SymbolTable.h"
14#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000015#include "llvm/ADT/Optional.h"
16#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000017#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000018#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000019#include "llvm/Option/Arg.h"
20#include "llvm/Option/ArgList.h"
21#include "llvm/Option/Option.h"
22#include "llvm/Support/CommandLine.h"
23#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000024#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000025#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000026#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000027#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000028#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include <memory>
30
31using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000032using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
33using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
34using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000035using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000036using llvm::sys::fs::file_magic;
37using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000038
Rui Ueyama3500f662015-05-28 20:30:06 +000039namespace lld {
40namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000041
Rui Ueyama3500f662015-05-28 20:30:06 +000042Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000043LinkerDriver *Driver;
44
45bool link(int Argc, const char *Argv[]) {
46 auto C = make_unique<Configuration>();
47 Config = C.get();
48 auto D = make_unique<LinkerDriver>();
49 Driver = D.get();
50 return Driver->link(Argc, Argv);
51}
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Rui Ueyamaad660982015-06-07 00:20:32 +000053// Drop directory components and replace extension with ".exe".
54static std::string getOutputPath(StringRef Path) {
55 auto P = Path.find_last_of("\\/");
56 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
57 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000058}
59
Rui Ueyamad7c2f582015-05-31 21:04:56 +000060// Opens a file. Path has to be resolved already.
61// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000062ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000063 auto MBOrErr = MemoryBuffer::getFile(Path);
64 if (auto EC = MBOrErr.getError())
65 return EC;
66 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
67 MemoryBufferRef MBRef = MB->getMemBufferRef();
68 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000069 return MBRef;
70}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000071
Rui Ueyama2bf6a122015-06-14 21:50:50 +000072static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000073 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000074 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000075 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000076 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000077 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000078 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000079 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000080 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
81 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000082}
83
Rui Ueyama411c63602015-05-28 19:09:30 +000084// Parses .drectve section contents and returns a list of files
85// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000086std::error_code
87LinkerDriver::parseDirectives(StringRef S,
88 std::vector<std::unique_ptr<InputFile>> *Res) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000089 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000090 if (auto EC = ArgsOrErr.getError())
91 return EC;
92 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
93
Rui Ueyama97dff9e2015-06-17 00:16:33 +000094 // Handle /export
95 for (auto *Arg : Args->filtered(OPT_export)) {
96 ErrorOr<Export> E = parseExport(Arg->getValue());
97 if (auto EC = E.getError())
98 return EC;
99 Config->Exports.push_back(E.get());
100 }
101
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000102 // Handle /failifmismatch
103 if (auto EC = checkFailIfMismatch(Args.get()))
104 return EC;
105
106 // Handle /defaultlib
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000107 for (auto *Arg : Args->filtered(OPT_defaultlib)) {
108 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000109 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
110 if (auto EC = MBOrErr.getError())
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000111 return EC;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000112 std::unique_ptr<InputFile> File = createFile(MBOrErr.get());
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000113 Res->push_back(std::move(File));
114 }
115 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000116 return std::error_code();
117}
118
Rui Ueyama54b71da2015-05-31 19:17:12 +0000119// Find file from search paths. You can omit ".obj", this function takes
120// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000121StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000122 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
123 if (hasPathSep)
124 return Filename;
125 bool hasExt = (Filename.find('.') != StringRef::npos);
126 for (StringRef Dir : SearchPaths) {
127 SmallString<128> Path = Dir;
128 llvm::sys::path::append(Path, Filename);
129 if (llvm::sys::fs::exists(Path.str()))
130 return Alloc.save(Path.str());
131 if (!hasExt) {
132 Path.append(".obj");
133 if (llvm::sys::fs::exists(Path.str()))
134 return Alloc.save(Path.str());
135 }
136 }
137 return Filename;
138}
139
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000140// Resolves a file path. This never returns the same path
141// (in that case, it returns None).
142Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
143 StringRef Path = doFindFile(Filename);
144 bool Seen = !VisitedFiles.insert(Path.lower()).second;
145 if (Seen)
146 return None;
147 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000148}
149
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000150// Find library file from search path.
151StringRef LinkerDriver::doFindLib(StringRef Filename) {
152 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000153 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000154 if (!hasExt)
155 Filename = Alloc.save(Filename + ".lib");
156 return doFindFile(Filename);
157}
158
159// Resolves a library path. /nodefaultlib options are taken into
160// consideration. This never returns the same path (in that case,
161// it returns None).
162Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
163 if (Config->NoDefaultLibAll)
164 return None;
165 StringRef Path = doFindLib(Filename);
166 if (Config->NoDefaultLibs.count(Path))
167 return None;
168 bool Seen = !VisitedFiles.insert(Path.lower()).second;
169 if (Seen)
170 return None;
171 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000172}
173
174// Parses LIB environment which contains a list of search paths.
175std::vector<StringRef> LinkerDriver::getSearchPaths() {
176 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000177 // Add current directory as first item of the search paths.
178 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000179 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
180 if (!EnvOpt.hasValue())
181 return Ret;
182 StringRef Env = Alloc.save(*EnvOpt);
183 while (!Env.empty()) {
184 StringRef Path;
185 std::tie(Path, Env) = Env.split(';');
186 Ret.push_back(Path);
187 }
188 return Ret;
189}
190
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000191static WindowsSubsystem inferSubsystem() {
192 if (Config->DLL)
193 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
194 return StringSwitch<WindowsSubsystem>(Config->EntryName)
195 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
196 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
197 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
198 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
199 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
200}
201
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000202bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000203 // Needed for LTO.
204 llvm::InitializeAllTargetInfos();
205 llvm::InitializeAllTargets();
206 llvm::InitializeAllTargetMCs();
207 llvm::InitializeAllAsmParsers();
208 llvm::InitializeAllAsmPrinters();
209 llvm::InitializeAllDisassemblers();
210
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000211 // If the first command line argument is "/lib", link.exe acts like lib.exe.
212 // We call our own implementation of lib.exe that understands bitcode files.
213 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
214 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
215
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000217 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000218 if (auto EC = ArgsOrErr.getError()) {
219 llvm::errs() << EC.message() << "\n";
220 return false;
221 }
222 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
223
Rui Ueyama5c726432015-05-29 16:11:52 +0000224 // Handle /help
225 if (Args->hasArg(OPT_help)) {
226 printHelp(Argv[0]);
227 return true;
228 }
229
Rui Ueyama411c63602015-05-28 19:09:30 +0000230 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
231 llvm::errs() << "no input files.\n";
232 return false;
233 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000234
Rui Ueyamaad660982015-06-07 00:20:32 +0000235 // Handle /out
236 if (auto *Arg = Args->getLastArg(OPT_out))
237 Config->OutputFile = Arg->getValue();
238
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000239 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000240 if (Args->hasArg(OPT_verbose))
241 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000242
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000243 // Handle /dll
244 if (Args->hasArg(OPT_dll))
245 Config->DLL = true;
246
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000247 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000248 if (auto *Arg = Args->getLastArg(OPT_entry))
249 Config->EntryName = Arg->getValue();
250
Rui Ueyama588e8322015-06-15 01:23:58 +0000251 // Handle /fixed
Rui Ueyama6592ff82015-06-16 23:13:00 +0000252 if (Args->hasArg(OPT_fixed)) {
253 if (Args->hasArg(OPT_dynamicbase)) {
254 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
255 return false;
256 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000257 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000258 Config->DynamicBase = false;
259 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000260
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000261 // Handle /machine
262 auto MTOrErr = getMachineType(Args.get());
263 if (auto EC = MTOrErr.getError()) {
264 llvm::errs() << EC.message() << "\n";
265 return false;
266 }
267 Config->MachineType = MTOrErr.get();
268
Rui Ueyama06137472015-05-31 20:10:11 +0000269 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000270 for (auto *Arg : Args->filtered(OPT_libpath)) {
271 // Inserting at front of a vector is okay because it's short.
272 // +1 because the first entry is always "." (current directory).
273 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
274 }
Rui Ueyama06137472015-05-31 20:10:11 +0000275
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000276 // Handle /nodefaultlib:<filename>
277 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
278 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
279
280 // Handle /nodefaultlib
281 if (Args->hasArg(OPT_nodefaultlib_all))
282 Config->NoDefaultLibAll = true;
283
Rui Ueyama804a8b62015-05-29 16:18:15 +0000284 // Handle /base
285 if (auto *Arg = Args->getLastArg(OPT_base)) {
286 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000287 llvm::errs() << "/base: " << EC.message() << "\n";
288 return false;
289 }
290 }
291
292 // Handle /stack
293 if (auto *Arg = Args->getLastArg(OPT_stack)) {
294 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
295 &Config->StackCommit)) {
296 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000297 return false;
298 }
299 }
300
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000301 // Handle /heap
302 if (auto *Arg = Args->getLastArg(OPT_heap)) {
303 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
304 &Config->HeapCommit)) {
305 llvm::errs() << "/heap: " << EC.message() << "\n";
306 return false;
307 }
308 }
309
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000310 // Handle /version
311 if (auto *Arg = Args->getLastArg(OPT_version)) {
312 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
313 &Config->MinorImageVersion)) {
314 llvm::errs() << "/version: " << EC.message() << "\n";
315 return false;
316 }
317 }
318
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000319 // Handle /subsystem
320 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
321 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
322 &Config->MajorOSVersion,
323 &Config->MinorOSVersion)) {
324 llvm::errs() << "/subsystem: " << EC.message() << "\n";
325 return false;
326 }
327 }
328
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000329 // Handle /opt
330 for (auto *Arg : Args->filtered(OPT_opt)) {
331 std::string S = StringRef(Arg->getValue()).lower();
332 if (S == "noref") {
333 Config->DoGC = false;
334 continue;
335 }
336 if (S != "ref" && S != "icf" && S != "noicf" &&
337 S != "lbr" && S != "nolbr" &&
338 !StringRef(S).startswith("icf=")) {
339 llvm::errs() << "/opt: unknown option: " << S << "\n";
340 return false;
341 }
342 }
343
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000344 // Handle /export
345 for (auto *Arg : Args->filtered(OPT_export)) {
346 ErrorOr<Export> E = parseExport(Arg->getValue());
347 if (E.getError())
348 return false;
349 Config->Exports.push_back(E.get());
350 }
351
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000352 // Handle /failifmismatch
353 if (auto EC = checkFailIfMismatch(Args.get())) {
354 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
355 return false;
356 }
357
Rui Ueyama1f373702015-06-17 19:19:25 +0000358 // Handle /def
359 if (auto *Arg = Args->getLastArg(OPT_deffile)) {
360 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
361 if (auto EC = MBOrErr.getError()) {
362 llvm::errs() << "/def: " << EC.message() << "\n";
363 return false;
364 }
365 // parseModuleDefs mutates Config object.
366 if (parseModuleDefs(MBOrErr.get()))
367 return false;
368 }
369
Rui Ueyama6592ff82015-06-16 23:13:00 +0000370 // Handle miscellaneous boolean flags.
371 if (Args->hasArg(OPT_allowbind_no)) Config->AllowBind = false;
372 if (Args->hasArg(OPT_allowisolation_no)) Config->AllowIsolation = false;
373 if (Args->hasArg(OPT_dynamicbase_no)) Config->DynamicBase = false;
374 if (Args->hasArg(OPT_highentropyva_no)) Config->HighEntropyVA = false;
375 if (Args->hasArg(OPT_nxcompat_no)) Config->NxCompat = false;
376 if (Args->hasArg(OPT_tsaware_no)) Config->TerminalServerAware = false;
377
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000378 // Create a list of input files. Files can be given as arguments
379 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000380 std::vector<StringRef> InputPaths;
381 std::vector<MemoryBufferRef> Inputs;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000382 for (auto *Arg : Args->filtered(OPT_INPUT))
383 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000384 InputPaths.push_back(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000385 for (auto *Arg : Args->filtered(OPT_defaultlib))
386 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000387 InputPaths.push_back(*Path);
388 for (StringRef Path : InputPaths) {
389 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
390 if (auto EC = MBOrErr.getError()) {
391 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
392 return false;
393 }
394 Inputs.push_back(MBOrErr.get());
395 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000396
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000397 // Create a symbol table.
398 SymbolTable Symtab;
399
400 // Add undefined symbols given via the command line.
401 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000402 for (auto *Arg : Args->filtered(OPT_incl)) {
403 StringRef Sym = Arg->getValue();
404 Symtab.addUndefined(Sym);
405 Config->GCRoots.insert(Sym);
406 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000407
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000408 // Windows specific -- Input files can be Windows resource files (.res files).
409 // We invoke cvtres.exe to convert resource files to a regular COFF file
410 // then link the result file normally.
411 auto IsResource = [](MemoryBufferRef MB) {
412 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
413 };
414 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
415 if (It != Inputs.begin()) {
416 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
417 auto MBOrErr = convertResToCOFF(Files);
418 if (MBOrErr.getError())
419 return false;
420 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
421 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
422 Inputs.push_back(MB->getMemBufferRef());
423 OwningMBs.push_back(std::move(MB)); // take ownership
424 }
425
Rui Ueyama411c63602015-05-28 19:09:30 +0000426 // Parse all input files and put all symbols to the symbol table.
427 // The symbol table will take care of name resolution.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000428 for (MemoryBufferRef MB : Inputs) {
429 std::unique_ptr<InputFile> File = createFile(MB);
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000430 if (Config->Verbose)
431 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000432 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000433 llvm::errs() << File->getName() << ": " << EC.message() << "\n";
Rui Ueyama411c63602015-05-28 19:09:30 +0000434 return false;
435 }
436 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000437
Rui Ueyama360bace2015-05-31 22:31:31 +0000438 // Add weak aliases. Weak aliases is a mechanism to give remaining
439 // undefined symbols final chance to be resolved successfully.
440 // This is symbol renaming.
441 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000442 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000443 StringRef From, To;
444 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
445 if (From.empty() || To.empty()) {
446 llvm::errs() << "/alternatename: invalid argument: "
447 << Arg->getValue() << "\n";
448 return false;
449 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000450 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000451 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000452 if (Symtab.find(From))
453 continue;
454 if (auto EC = Symtab.rename(From, To)) {
455 llvm::errs() << EC.message() << "\n";
456 return false;
457 }
458 }
459
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000460 // Windows specific -- Make sure we resolve all dllexported symbols.
461 // (We don't cache the size here because Symtab.resolve() may add
462 // new entries to Config->Exports.)
463 for (size_t I = 0; I < Config->Exports.size(); ++I) {
464 StringRef Sym = Config->Exports[I].Name;
465 Symtab.addUndefined(Sym);
466 Config->GCRoots.insert(Sym);
467 }
468
Rui Ueyama5cff6852015-05-31 03:34:08 +0000469 // Windows specific -- If entry point name is not given, we need to
470 // infer that from user-defined entry name. The symbol table takes
471 // care of details.
472 if (Config->EntryName.empty()) {
473 auto EntryOrErr = Symtab.findDefaultEntry();
474 if (auto EC = EntryOrErr.getError()) {
475 llvm::errs() << EC.message() << "\n";
476 return false;
477 }
478 Config->EntryName = EntryOrErr.get();
479 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000480 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000481
482 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000483 if (Symtab.reportRemainingUndefines())
484 return false;
485
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000486 // Do LTO by compiling bitcode input files to a native COFF file
487 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000488 if (auto EC = Symtab.addCombinedLTOObject()) {
489 llvm::errs() << EC.message() << "\n";
490 return false;
491 }
492
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000493 // Windows specific -- if no /subsystem is given, we need to infer
494 // that from entry point name.
495 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000496 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000497 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
498 llvm::errs() << "subsystem must be defined\n";
499 return false;
500 }
501 }
502
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000503 // Windows specific -- fix up dllexported symbols.
504 if (!Config->Exports.empty()) {
505 for (Export &E : Config->Exports)
506 E.Sym = Symtab.find(E.Name);
507 if (fixupExports())
508 return false;
509 }
510
Rui Ueyama411c63602015-05-28 19:09:30 +0000511 // Write the result.
512 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000513 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000514 llvm::errs() << EC.message() << "\n";
515 return false;
516 }
517 return true;
518}
519
Rui Ueyama411c63602015-05-28 19:09:30 +0000520} // namespace coff
521} // namespace lld