blob: 1cc635be18f6c9458fda4e33e0993c842896f21f [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"
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
Rui Ueyama411c63602015-05-28 19:09:30 +0000188 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000189 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000190 if (auto EC = ArgsOrErr.getError()) {
191 llvm::errs() << EC.message() << "\n";
192 return false;
193 }
194 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
195
Rui Ueyama5c726432015-05-29 16:11:52 +0000196 // Handle /help
197 if (Args->hasArg(OPT_help)) {
198 printHelp(Argv[0]);
199 return true;
200 }
201
Rui Ueyama411c63602015-05-28 19:09:30 +0000202 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
203 llvm::errs() << "no input files.\n";
204 return false;
205 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000206
Rui Ueyamaad660982015-06-07 00:20:32 +0000207 // Handle /out
208 if (auto *Arg = Args->getLastArg(OPT_out))
209 Config->OutputFile = Arg->getValue();
210
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000211 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000212 if (Args->hasArg(OPT_verbose))
213 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000214
215 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000216 if (auto *Arg = Args->getLastArg(OPT_entry))
217 Config->EntryName = Arg->getValue();
218
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000219 // Handle /machine
220 auto MTOrErr = getMachineType(Args.get());
221 if (auto EC = MTOrErr.getError()) {
222 llvm::errs() << EC.message() << "\n";
223 return false;
224 }
225 Config->MachineType = MTOrErr.get();
226
Rui Ueyama06137472015-05-31 20:10:11 +0000227 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000228 for (auto *Arg : Args->filtered(OPT_libpath)) {
229 // Inserting at front of a vector is okay because it's short.
230 // +1 because the first entry is always "." (current directory).
231 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
232 }
Rui Ueyama06137472015-05-31 20:10:11 +0000233
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000234 // Handle /nodefaultlib:<filename>
235 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
236 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
237
238 // Handle /nodefaultlib
239 if (Args->hasArg(OPT_nodefaultlib_all))
240 Config->NoDefaultLibAll = true;
241
Rui Ueyama804a8b62015-05-29 16:18:15 +0000242 // Handle /base
243 if (auto *Arg = Args->getLastArg(OPT_base)) {
244 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000245 llvm::errs() << "/base: " << EC.message() << "\n";
246 return false;
247 }
248 }
249
250 // Handle /stack
251 if (auto *Arg = Args->getLastArg(OPT_stack)) {
252 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
253 &Config->StackCommit)) {
254 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000255 return false;
256 }
257 }
258
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000259 // Handle /heap
260 if (auto *Arg = Args->getLastArg(OPT_heap)) {
261 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
262 &Config->HeapCommit)) {
263 llvm::errs() << "/heap: " << EC.message() << "\n";
264 return false;
265 }
266 }
267
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000268 // Handle /version
269 if (auto *Arg = Args->getLastArg(OPT_version)) {
270 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
271 &Config->MinorImageVersion)) {
272 llvm::errs() << "/version: " << EC.message() << "\n";
273 return false;
274 }
275 }
276
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000277 // Handle /subsystem
278 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
279 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
280 &Config->MajorOSVersion,
281 &Config->MinorOSVersion)) {
282 llvm::errs() << "/subsystem: " << EC.message() << "\n";
283 return false;
284 }
285 }
286
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000287 // Handle /opt
288 for (auto *Arg : Args->filtered(OPT_opt)) {
289 std::string S = StringRef(Arg->getValue()).lower();
290 if (S == "noref") {
291 Config->DoGC = false;
292 continue;
293 }
294 if (S != "ref" && S != "icf" && S != "noicf" &&
295 S != "lbr" && S != "nolbr" &&
296 !StringRef(S).startswith("icf=")) {
297 llvm::errs() << "/opt: unknown option: " << S << "\n";
298 return false;
299 }
300 }
301
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000302 // Handle /failifmismatch
303 if (auto EC = checkFailIfMismatch(Args.get())) {
304 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
305 return false;
306 }
307
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000308 // Create a list of input files. Files can be given as arguments
309 // for /defaultlib option.
310 std::vector<StringRef> Inputs;
311 for (auto *Arg : Args->filtered(OPT_INPUT))
312 if (Optional<StringRef> Path = findFile(Arg->getValue()))
313 Inputs.push_back(*Path);
314 for (auto *Arg : Args->filtered(OPT_defaultlib))
315 if (Optional<StringRef> Path = findLib(Arg->getValue()))
316 Inputs.push_back(*Path);
317
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000318 // Create a symbol table.
319 SymbolTable Symtab;
320
321 // Add undefined symbols given via the command line.
322 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000323 for (auto *Arg : Args->filtered(OPT_incl)) {
324 StringRef Sym = Arg->getValue();
325 Symtab.addUndefined(Sym);
326 Config->GCRoots.insert(Sym);
327 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000328
Rui Ueyama411c63602015-05-28 19:09:30 +0000329 // Parse all input files and put all symbols to the symbol table.
330 // The symbol table will take care of name resolution.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000331 for (StringRef Path : Inputs) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000332 auto FileOrErr = openFile(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000333 if (auto EC = FileOrErr.getError()) {
334 llvm::errs() << Path << ": " << EC.message() << "\n";
335 return false;
336 }
337 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000338 if (Config->Verbose)
339 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000340 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000341 llvm::errs() << Path << ": " << EC.message() << "\n";
342 return false;
343 }
344 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000345
Rui Ueyama360bace2015-05-31 22:31:31 +0000346 // Add weak aliases. Weak aliases is a mechanism to give remaining
347 // undefined symbols final chance to be resolved successfully.
348 // This is symbol renaming.
349 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000350 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000351 StringRef From, To;
352 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
353 if (From.empty() || To.empty()) {
354 llvm::errs() << "/alternatename: invalid argument: "
355 << Arg->getValue() << "\n";
356 return false;
357 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000358 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000359 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000360 if (Symtab.find(From))
361 continue;
362 if (auto EC = Symtab.rename(From, To)) {
363 llvm::errs() << EC.message() << "\n";
364 return false;
365 }
366 }
367
Rui Ueyama5cff6852015-05-31 03:34:08 +0000368 // Windows specific -- If entry point name is not given, we need to
369 // infer that from user-defined entry name. The symbol table takes
370 // care of details.
371 if (Config->EntryName.empty()) {
372 auto EntryOrErr = Symtab.findDefaultEntry();
373 if (auto EC = EntryOrErr.getError()) {
374 llvm::errs() << EC.message() << "\n";
375 return false;
376 }
377 Config->EntryName = EntryOrErr.get();
378 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000379 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000380
381 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000382 if (Symtab.reportRemainingUndefines())
383 return false;
384
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000385 // Do LTO by compiling bitcode input files to a native COFF file
386 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000387 if (auto EC = Symtab.addCombinedLTOObject()) {
388 llvm::errs() << EC.message() << "\n";
389 return false;
390 }
391
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000392 // Windows specific -- if no /subsystem is given, we need to infer
393 // that from entry point name.
394 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
395 Config->Subsystem =
396 StringSwitch<WindowsSubsystem>(Config->EntryName)
397 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
398 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
399 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
400 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
401 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
402 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
403 llvm::errs() << "subsystem must be defined\n";
404 return false;
405 }
406 }
407
Rui Ueyama411c63602015-05-28 19:09:30 +0000408 // Write the result.
409 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000410 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000411 llvm::errs() << EC.message() << "\n";
412 return false;
413 }
414 return true;
415}
416
Rui Ueyama411c63602015-05-28 19:09:30 +0000417} // namespace coff
418} // namespace lld