blob: 257c9b47e1aeb677ee4e52b16fa17641d4d9e055 [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"
28#include <memory>
29
30using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000031using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
32using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
33using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000034using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000035using llvm::sys::fs::file_magic;
36using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000037
Rui Ueyama3500f662015-05-28 20:30:06 +000038namespace lld {
39namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000040
Rui Ueyama3500f662015-05-28 20:30:06 +000041Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000042LinkerDriver *Driver;
43
44bool link(int Argc, const char *Argv[]) {
45 auto C = make_unique<Configuration>();
46 Config = C.get();
47 auto D = make_unique<LinkerDriver>();
48 Driver = D.get();
49 return Driver->link(Argc, Argv);
50}
Rui Ueyama411c63602015-05-28 19:09:30 +000051
Rui Ueyamaad660982015-06-07 00:20:32 +000052// Drop directory components and replace extension with ".exe".
53static std::string getOutputPath(StringRef Path) {
54 auto P = Path.find_last_of("\\/");
55 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
56 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000057}
58
Rui Ueyamad7c2f582015-05-31 21:04:56 +000059// Opens a file. Path has to be resolved already.
60// Newly created memory buffers are owned by this driver.
Rui Ueyama711cd2d2015-05-31 21:17:10 +000061ErrorOr<std::unique_ptr<InputFile>> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000062 auto MBOrErr = MemoryBuffer::getFile(Path);
63 if (auto EC = MBOrErr.getError())
64 return EC;
65 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
66 MemoryBufferRef MBRef = MB->getMemBufferRef();
67 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama711cd2d2015-05-31 21:17:10 +000068
69 // File type is detected by contents, not by file extension.
70 file_magic Magic = identify_magic(MBRef.getBuffer());
71 if (Magic == file_magic::archive)
Rui Ueyamad7c2f582015-05-31 21:04:56 +000072 return std::unique_ptr<InputFile>(new ArchiveFile(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +000073 if (Magic == file_magic::bitcode)
Rui Ueyama81b030c2015-06-01 21:19:43 +000074 return std::unique_ptr<InputFile>(new BitcodeFile(MBRef));
Rui Ueyamaad660982015-06-07 00:20:32 +000075 if (Config->OutputFile == "")
76 Config->OutputFile = getOutputPath(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +000077 return std::unique_ptr<InputFile>(new ObjectFile(MBRef));
Rui Ueyama411c63602015-05-28 19:09:30 +000078}
79
Rui Ueyama411c63602015-05-28 19:09:30 +000080// Parses .drectve section contents and returns a list of files
81// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000082std::error_code
83LinkerDriver::parseDirectives(StringRef S,
84 std::vector<std::unique_ptr<InputFile>> *Res) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000085 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000086 if (auto EC = ArgsOrErr.getError())
87 return EC;
88 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
89
Rui Ueyama8854d8a2015-06-04 19:21:24 +000090 // Handle /failifmismatch
91 if (auto EC = checkFailIfMismatch(Args.get()))
92 return EC;
93
94 // Handle /defaultlib
Rui Ueyamad7c2f582015-05-31 21:04:56 +000095 for (auto *Arg : Args->filtered(OPT_defaultlib)) {
96 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000097 auto FileOrErr = openFile(*Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +000098 if (auto EC = FileOrErr.getError())
99 return EC;
100 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
101 Res->push_back(std::move(File));
102 }
103 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000104 return std::error_code();
105}
106
Rui Ueyama54b71da2015-05-31 19:17:12 +0000107// Find file from search paths. You can omit ".obj", this function takes
108// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000109StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000110 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
111 if (hasPathSep)
112 return Filename;
113 bool hasExt = (Filename.find('.') != StringRef::npos);
114 for (StringRef Dir : SearchPaths) {
115 SmallString<128> Path = Dir;
116 llvm::sys::path::append(Path, Filename);
117 if (llvm::sys::fs::exists(Path.str()))
118 return Alloc.save(Path.str());
119 if (!hasExt) {
120 Path.append(".obj");
121 if (llvm::sys::fs::exists(Path.str()))
122 return Alloc.save(Path.str());
123 }
124 }
125 return Filename;
126}
127
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000128// Resolves a file path. This never returns the same path
129// (in that case, it returns None).
130Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
131 StringRef Path = doFindFile(Filename);
132 bool Seen = !VisitedFiles.insert(Path.lower()).second;
133 if (Seen)
134 return None;
135 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000136}
137
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000138// Find library file from search path.
139StringRef LinkerDriver::doFindLib(StringRef Filename) {
140 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000141 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000142 if (!hasExt)
143 Filename = Alloc.save(Filename + ".lib");
144 return doFindFile(Filename);
145}
146
147// Resolves a library path. /nodefaultlib options are taken into
148// consideration. This never returns the same path (in that case,
149// it returns None).
150Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
151 if (Config->NoDefaultLibAll)
152 return None;
153 StringRef Path = doFindLib(Filename);
154 if (Config->NoDefaultLibs.count(Path))
155 return None;
156 bool Seen = !VisitedFiles.insert(Path.lower()).second;
157 if (Seen)
158 return None;
159 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000160}
161
162// Parses LIB environment which contains a list of search paths.
163std::vector<StringRef> LinkerDriver::getSearchPaths() {
164 std::vector<StringRef> Ret;
Rui Ueyama7d806402015-06-08 06:13:12 +0000165 // Add current directory as first item of the search paths.
166 Ret.push_back("");
Rui Ueyama54b71da2015-05-31 19:17:12 +0000167 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
168 if (!EnvOpt.hasValue())
169 return Ret;
170 StringRef Env = Alloc.save(*EnvOpt);
171 while (!Env.empty()) {
172 StringRef Path;
173 std::tie(Path, Env) = Env.split(';');
174 Ret.push_back(Path);
175 }
176 return Ret;
177}
178
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000179bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000180 // Needed for LTO.
181 llvm::InitializeAllTargetInfos();
182 llvm::InitializeAllTargets();
183 llvm::InitializeAllTargetMCs();
184 llvm::InitializeAllAsmParsers();
185 llvm::InitializeAllAsmPrinters();
186 llvm::InitializeAllDisassemblers();
187
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000188 // If the first command line argument is "/lib", link.exe acts like lib.exe.
189 // We call our own implementation of lib.exe that understands bitcode files.
190 if (Argc > 1 && StringRef(Argv[1]).equals_lower("/lib"))
191 return llvm::libDriverMain(Argc - 1, Argv + 1) == 0;
192
Rui Ueyama411c63602015-05-28 19:09:30 +0000193 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000194 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000195 if (auto EC = ArgsOrErr.getError()) {
196 llvm::errs() << EC.message() << "\n";
197 return false;
198 }
199 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
200
Rui Ueyama5c726432015-05-29 16:11:52 +0000201 // Handle /help
202 if (Args->hasArg(OPT_help)) {
203 printHelp(Argv[0]);
204 return true;
205 }
206
Rui Ueyama411c63602015-05-28 19:09:30 +0000207 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
208 llvm::errs() << "no input files.\n";
209 return false;
210 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000211
Rui Ueyamaad660982015-06-07 00:20:32 +0000212 // Handle /out
213 if (auto *Arg = Args->getLastArg(OPT_out))
214 Config->OutputFile = Arg->getValue();
215
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000216 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000217 if (Args->hasArg(OPT_verbose))
218 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000219
220 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000221 if (auto *Arg = Args->getLastArg(OPT_entry))
222 Config->EntryName = Arg->getValue();
223
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000224 // Handle /machine
225 auto MTOrErr = getMachineType(Args.get());
226 if (auto EC = MTOrErr.getError()) {
227 llvm::errs() << EC.message() << "\n";
228 return false;
229 }
230 Config->MachineType = MTOrErr.get();
231
Rui Ueyama06137472015-05-31 20:10:11 +0000232 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000233 for (auto *Arg : Args->filtered(OPT_libpath)) {
234 // Inserting at front of a vector is okay because it's short.
235 // +1 because the first entry is always "." (current directory).
236 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
237 }
Rui Ueyama06137472015-05-31 20:10:11 +0000238
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000239 // Handle /nodefaultlib:<filename>
240 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
241 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
242
243 // Handle /nodefaultlib
244 if (Args->hasArg(OPT_nodefaultlib_all))
245 Config->NoDefaultLibAll = true;
246
Rui Ueyama804a8b62015-05-29 16:18:15 +0000247 // Handle /base
248 if (auto *Arg = Args->getLastArg(OPT_base)) {
249 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000250 llvm::errs() << "/base: " << EC.message() << "\n";
251 return false;
252 }
253 }
254
255 // Handle /stack
256 if (auto *Arg = Args->getLastArg(OPT_stack)) {
257 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
258 &Config->StackCommit)) {
259 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000260 return false;
261 }
262 }
263
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000264 // Handle /heap
265 if (auto *Arg = Args->getLastArg(OPT_heap)) {
266 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
267 &Config->HeapCommit)) {
268 llvm::errs() << "/heap: " << EC.message() << "\n";
269 return false;
270 }
271 }
272
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000273 // Handle /version
274 if (auto *Arg = Args->getLastArg(OPT_version)) {
275 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
276 &Config->MinorImageVersion)) {
277 llvm::errs() << "/version: " << EC.message() << "\n";
278 return false;
279 }
280 }
281
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000282 // Handle /subsystem
283 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
284 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
285 &Config->MajorOSVersion,
286 &Config->MinorOSVersion)) {
287 llvm::errs() << "/subsystem: " << EC.message() << "\n";
288 return false;
289 }
290 }
291
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000292 // Handle /opt
293 for (auto *Arg : Args->filtered(OPT_opt)) {
294 std::string S = StringRef(Arg->getValue()).lower();
295 if (S == "noref") {
296 Config->DoGC = false;
297 continue;
298 }
299 if (S != "ref" && S != "icf" && S != "noicf" &&
300 S != "lbr" && S != "nolbr" &&
301 !StringRef(S).startswith("icf=")) {
302 llvm::errs() << "/opt: unknown option: " << S << "\n";
303 return false;
304 }
305 }
306
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000307 // Handle /failifmismatch
308 if (auto EC = checkFailIfMismatch(Args.get())) {
309 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
310 return false;
311 }
312
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000313 // Create a list of input files. Files can be given as arguments
314 // for /defaultlib option.
315 std::vector<StringRef> Inputs;
316 for (auto *Arg : Args->filtered(OPT_INPUT))
317 if (Optional<StringRef> Path = findFile(Arg->getValue()))
318 Inputs.push_back(*Path);
319 for (auto *Arg : Args->filtered(OPT_defaultlib))
320 if (Optional<StringRef> Path = findLib(Arg->getValue()))
321 Inputs.push_back(*Path);
322
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000323 // Create a symbol table.
324 SymbolTable Symtab;
325
326 // Add undefined symbols given via the command line.
327 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000328 for (auto *Arg : Args->filtered(OPT_incl)) {
329 StringRef Sym = Arg->getValue();
330 Symtab.addUndefined(Sym);
331 Config->GCRoots.insert(Sym);
332 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000333
Rui Ueyama411c63602015-05-28 19:09:30 +0000334 // Parse all input files and put all symbols to the symbol table.
335 // The symbol table will take care of name resolution.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000336 for (StringRef Path : Inputs) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000337 auto FileOrErr = openFile(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000338 if (auto EC = FileOrErr.getError()) {
339 llvm::errs() << Path << ": " << EC.message() << "\n";
340 return false;
341 }
342 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000343 if (Config->Verbose)
344 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000345 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000346 llvm::errs() << Path << ": " << EC.message() << "\n";
347 return false;
348 }
349 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000350
Rui Ueyama360bace2015-05-31 22:31:31 +0000351 // Add weak aliases. Weak aliases is a mechanism to give remaining
352 // undefined symbols final chance to be resolved successfully.
353 // This is symbol renaming.
354 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000355 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000356 StringRef From, To;
357 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
358 if (From.empty() || To.empty()) {
359 llvm::errs() << "/alternatename: invalid argument: "
360 << Arg->getValue() << "\n";
361 return false;
362 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000363 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000364 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000365 if (Symtab.find(From))
366 continue;
367 if (auto EC = Symtab.rename(From, To)) {
368 llvm::errs() << EC.message() << "\n";
369 return false;
370 }
371 }
372
Rui Ueyama5cff6852015-05-31 03:34:08 +0000373 // Windows specific -- If entry point name is not given, we need to
374 // infer that from user-defined entry name. The symbol table takes
375 // care of details.
376 if (Config->EntryName.empty()) {
377 auto EntryOrErr = Symtab.findDefaultEntry();
378 if (auto EC = EntryOrErr.getError()) {
379 llvm::errs() << EC.message() << "\n";
380 return false;
381 }
382 Config->EntryName = EntryOrErr.get();
383 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000384 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000385
386 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000387 if (Symtab.reportRemainingUndefines())
388 return false;
389
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000390 // Do LTO by compiling bitcode input files to a native COFF file
391 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000392 if (auto EC = Symtab.addCombinedLTOObject()) {
393 llvm::errs() << EC.message() << "\n";
394 return false;
395 }
396
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000397 // Windows specific -- if no /subsystem is given, we need to infer
398 // that from entry point name.
399 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
400 Config->Subsystem =
401 StringSwitch<WindowsSubsystem>(Config->EntryName)
402 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
403 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
404 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
405 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
406 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
407 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
408 llvm::errs() << "subsystem must be defined\n";
409 return false;
410 }
411 }
412
Rui Ueyama411c63602015-05-28 19:09:30 +0000413 // Write the result.
414 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000415 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000416 llvm::errs() << EC.message() << "\n";
417 return false;
418 }
419 return true;
420}
421
Rui Ueyama411c63602015-05-28 19:09:30 +0000422} // namespace coff
423} // namespace lld