blob: 63f680c1481dd392e645c78bb5096937b4ce3eff [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"
13#include "Memory.h"
14#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"
29#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 Ueyama711cd2d2015-05-31 21:17:10 +000062ErrorOr<std::unique_ptr<InputFile>> 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 Ueyama711cd2d2015-05-31 21:17:10 +000069
70 // File type is detected by contents, not by file extension.
71 file_magic Magic = identify_magic(MBRef.getBuffer());
72 if (Magic == file_magic::archive)
Rui Ueyamad7c2f582015-05-31 21:04:56 +000073 return std::unique_ptr<InputFile>(new ArchiveFile(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +000074 if (Magic == file_magic::bitcode)
Rui Ueyama81b030c2015-06-01 21:19:43 +000075 return std::unique_ptr<InputFile>(new BitcodeFile(MBRef));
Rui Ueyamaad660982015-06-07 00:20:32 +000076 if (Config->OutputFile == "")
77 Config->OutputFile = getOutputPath(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +000078 return std::unique_ptr<InputFile>(new ObjectFile(MBRef));
Rui Ueyama411c63602015-05-28 19:09:30 +000079}
80
Rui Ueyama411c63602015-05-28 19:09:30 +000081// Parses .drectve section contents and returns a list of files
82// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000083std::error_code
84LinkerDriver::parseDirectives(StringRef S,
85 std::vector<std::unique_ptr<InputFile>> *Res) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000086 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000087 if (auto EC = ArgsOrErr.getError())
88 return EC;
89 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
90
Rui Ueyama8854d8a2015-06-04 19:21:24 +000091 // Handle /failifmismatch
92 if (auto EC = checkFailIfMismatch(Args.get()))
93 return EC;
94
95 // Handle /defaultlib
Rui Ueyamad7c2f582015-05-31 21:04:56 +000096 for (auto *Arg : Args->filtered(OPT_defaultlib)) {
97 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000098 auto FileOrErr = openFile(*Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +000099 if (auto EC = FileOrErr.getError())
100 return EC;
101 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
102 Res->push_back(std::move(File));
103 }
104 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000105 return std::error_code();
106}
107
Rui Ueyama54b71da2015-05-31 19:17:12 +0000108// Find file from search paths. You can omit ".obj", this function takes
109// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000110StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000111 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
112 if (hasPathSep)
113 return Filename;
114 bool hasExt = (Filename.find('.') != StringRef::npos);
115 for (StringRef Dir : SearchPaths) {
116 SmallString<128> Path = Dir;
117 llvm::sys::path::append(Path, Filename);
118 if (llvm::sys::fs::exists(Path.str()))
119 return Alloc.save(Path.str());
120 if (!hasExt) {
121 Path.append(".obj");
122 if (llvm::sys::fs::exists(Path.str()))
123 return Alloc.save(Path.str());
124 }
125 }
126 return Filename;
127}
128
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000129// Resolves a file path. This never returns the same path
130// (in that case, it returns None).
131Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
132 StringRef Path = doFindFile(Filename);
133 bool Seen = !VisitedFiles.insert(Path.lower()).second;
134 if (Seen)
135 return None;
136 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000137}
138
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000139// Find library file from search path.
140StringRef LinkerDriver::doFindLib(StringRef Filename) {
141 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000142 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000143 if (!hasExt)
144 Filename = Alloc.save(Filename + ".lib");
145 return doFindFile(Filename);
146}
147
148// Resolves a library path. /nodefaultlib options are taken into
149// consideration. This never returns the same path (in that case,
150// it returns None).
151Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
152 if (Config->NoDefaultLibAll)
153 return None;
154 StringRef Path = doFindLib(Filename);
155 if (Config->NoDefaultLibs.count(Path))
156 return None;
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
163// Parses LIB environment which contains a list of search paths.
164std::vector<StringRef> LinkerDriver::getSearchPaths() {
165 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000166 // Add current directory as first item of the search paths.
167 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000168 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
169 if (!EnvOpt.hasValue())
170 return Ret;
171 StringRef Env = Alloc.save(*EnvOpt);
172 while (!Env.empty()) {
173 StringRef Path;
174 std::tie(Path, Env) = Env.split(';');
175 Ret.push_back(Path);
176 }
177 return Ret;
178}
179
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000180bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000181 // Needed for LTO.
182 llvm::InitializeAllTargetInfos();
183 llvm::InitializeAllTargets();
184 llvm::InitializeAllTargetMCs();
185 llvm::InitializeAllAsmParsers();
186 llvm::InitializeAllAsmPrinters();
187 llvm::InitializeAllDisassemblers();
188
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000189 // If the first command line argument is "/lib", link.exe acts like lib.exe.
190 // We call our own implementation of lib.exe that understands bitcode files.
191 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
192 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
193
Rui Ueyama411c63602015-05-28 19:09:30 +0000194 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000195 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000196 if (auto EC = ArgsOrErr.getError()) {
197 llvm::errs() << EC.message() << "\n";
198 return false;
199 }
200 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
201
Rui Ueyama5c726432015-05-29 16:11:52 +0000202 // Handle /help
203 if (Args->hasArg(OPT_help)) {
204 printHelp(Argv[0]);
205 return true;
206 }
207
Rui Ueyama411c63602015-05-28 19:09:30 +0000208 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
209 llvm::errs() << "no input files.\n";
210 return false;
211 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000212
Rui Ueyamaad660982015-06-07 00:20:32 +0000213 // Handle /out
214 if (auto *Arg = Args->getLastArg(OPT_out))
215 Config->OutputFile = Arg->getValue();
216
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000217 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000218 if (Args->hasArg(OPT_verbose))
219 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000220
221 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000222 if (auto *Arg = Args->getLastArg(OPT_entry))
223 Config->EntryName = Arg->getValue();
224
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000225 // Handle /machine
226 auto MTOrErr = getMachineType(Args.get());
227 if (auto EC = MTOrErr.getError()) {
228 llvm::errs() << EC.message() << "\n";
229 return false;
230 }
231 Config->MachineType = MTOrErr.get();
232
Rui Ueyama06137472015-05-31 20:10:11 +0000233 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000234 for (auto *Arg : Args->filtered(OPT_libpath)) {
235 // Inserting at front of a vector is okay because it's short.
236 // +1 because the first entry is always "." (current directory).
237 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
238 }
Rui Ueyama06137472015-05-31 20:10:11 +0000239
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000240 // Handle /nodefaultlib:<filename>
241 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
242 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
243
244 // Handle /nodefaultlib
245 if (Args->hasArg(OPT_nodefaultlib_all))
246 Config->NoDefaultLibAll = true;
247
Rui Ueyama804a8b62015-05-29 16:18:15 +0000248 // Handle /base
249 if (auto *Arg = Args->getLastArg(OPT_base)) {
250 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000251 llvm::errs() << "/base: " << EC.message() << "\n";
252 return false;
253 }
254 }
255
256 // Handle /stack
257 if (auto *Arg = Args->getLastArg(OPT_stack)) {
258 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
259 &Config->StackCommit)) {
260 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000261 return false;
262 }
263 }
264
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000265 // Handle /heap
266 if (auto *Arg = Args->getLastArg(OPT_heap)) {
267 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
268 &Config->HeapCommit)) {
269 llvm::errs() << "/heap: " << EC.message() << "\n";
270 return false;
271 }
272 }
273
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000274 // Handle /version
275 if (auto *Arg = Args->getLastArg(OPT_version)) {
276 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
277 &Config->MinorImageVersion)) {
278 llvm::errs() << "/version: " << EC.message() << "\n";
279 return false;
280 }
281 }
282
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000283 // Handle /subsystem
284 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
285 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
286 &Config->MajorOSVersion,
287 &Config->MinorOSVersion)) {
288 llvm::errs() << "/subsystem: " << EC.message() << "\n";
289 return false;
290 }
291 }
292
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000293 // Handle /opt
294 for (auto *Arg : Args->filtered(OPT_opt)) {
295 std::string S = StringRef(Arg->getValue()).lower();
296 if (S == "noref") {
297 Config->DoGC = false;
298 continue;
299 }
300 if (S != "ref" && S != "icf" && S != "noicf" &&
301 S != "lbr" && S != "nolbr" &&
302 !StringRef(S).startswith("icf=")) {
303 llvm::errs() << "/opt: unknown option: " << S << "\n";
304 return false;
305 }
306 }
307
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000308 // Handle /failifmismatch
309 if (auto EC = checkFailIfMismatch(Args.get())) {
310 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
311 return false;
312 }
313
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000314 // Create a list of input files. Files can be given as arguments
315 // for /defaultlib option.
316 std::vector<StringRef> Inputs;
317 for (auto *Arg : Args->filtered(OPT_INPUT))
318 if (Optional<StringRef> Path = findFile(Arg->getValue()))
319 Inputs.push_back(*Path);
320 for (auto *Arg : Args->filtered(OPT_defaultlib))
321 if (Optional<StringRef> Path = findLib(Arg->getValue()))
322 Inputs.push_back(*Path);
323
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000324 // Create a symbol table.
325 SymbolTable Symtab;
326
327 // Add undefined symbols given via the command line.
328 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000329 for (auto *Arg : Args->filtered(OPT_incl)) {
330 StringRef Sym = Arg->getValue();
331 Symtab.addUndefined(Sym);
332 Config->GCRoots.insert(Sym);
333 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000334
Rui Ueyama411c63602015-05-28 19:09:30 +0000335 // Parse all input files and put all symbols to the symbol table.
336 // The symbol table will take care of name resolution.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000337 for (StringRef Path : Inputs) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000338 auto FileOrErr = openFile(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000339 if (auto EC = FileOrErr.getError()) {
340 llvm::errs() << Path << ": " << EC.message() << "\n";
341 return false;
342 }
343 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000344 if (Config->Verbose)
345 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000346 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000347 llvm::errs() << Path << ": " << EC.message() << "\n";
348 return false;
349 }
350 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000351
Rui Ueyama360bace2015-05-31 22:31:31 +0000352 // Add weak aliases. Weak aliases is a mechanism to give remaining
353 // undefined symbols final chance to be resolved successfully.
354 // This is symbol renaming.
355 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000356 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000357 StringRef From, To;
358 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
359 if (From.empty() || To.empty()) {
360 llvm::errs() << "/alternatename: invalid argument: "
361 << Arg->getValue() << "\n";
362 return false;
363 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000364 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000365 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000366 if (Symtab.find(From))
367 continue;
368 if (auto EC = Symtab.rename(From, To)) {
369 llvm::errs() << EC.message() << "\n";
370 return false;
371 }
372 }
373
Rui Ueyama5cff6852015-05-31 03:34:08 +0000374 // Windows specific -- If entry point name is not given, we need to
375 // infer that from user-defined entry name. The symbol table takes
376 // care of details.
377 if (Config->EntryName.empty()) {
378 auto EntryOrErr = Symtab.findDefaultEntry();
379 if (auto EC = EntryOrErr.getError()) {
380 llvm::errs() << EC.message() << "\n";
381 return false;
382 }
383 Config->EntryName = EntryOrErr.get();
384 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000385 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000386
387 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000388 if (Symtab.reportRemainingUndefines())
389 return false;
390
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000391 // Do LTO by compiling bitcode input files to a native COFF file
392 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000393 if (auto EC = Symtab.addCombinedLTOObject()) {
394 llvm::errs() << EC.message() << "\n";
395 return false;
396 }
397
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000398 // Windows specific -- if no /subsystem is given, we need to infer
399 // that from entry point name.
400 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
401 Config->Subsystem =
402 StringSwitch<WindowsSubsystem>(Config->EntryName)
403 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
404 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
405 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
406 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
407 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
408 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
409 llvm::errs() << "subsystem must be defined\n";
410 return false;
411 }
412 }
413
Rui Ueyama411c63602015-05-28 19:09:30 +0000414 // Write the result.
415 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000416 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000417 llvm::errs() << EC.message() << "\n";
418 return false;
419 }
420 return true;
421}
422
Rui Ueyama411c63602015-05-28 19:09:30 +0000423} // namespace coff
424} // namespace lld