blob: a2beb76b8e742e6f0c5823c74e21440433c774ac [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;
165 Ret.push_back(".");
166 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
167 if (!EnvOpt.hasValue())
168 return Ret;
169 StringRef Env = Alloc.save(*EnvOpt);
170 while (!Env.empty()) {
171 StringRef Path;
172 std::tie(Path, Env) = Env.split(';');
173 Ret.push_back(Path);
174 }
175 return Ret;
176}
177
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +0000178bool LinkerDriver::link(int Argc, const char *Argv[]) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000179 // Needed for LTO.
180 llvm::InitializeAllTargetInfos();
181 llvm::InitializeAllTargets();
182 llvm::InitializeAllTargetMCs();
183 llvm::InitializeAllAsmParsers();
184 llvm::InitializeAllAsmPrinters();
185 llvm::InitializeAllDisassemblers();
186
Rui Ueyama411c63602015-05-28 19:09:30 +0000187 // Parse command line options.
Rui Ueyama115d7c12015-06-07 02:55:19 +0000188 auto ArgsOrErr = Parser.parse(Argc, Argv);
Rui Ueyama411c63602015-05-28 19:09:30 +0000189 if (auto EC = ArgsOrErr.getError()) {
190 llvm::errs() << EC.message() << "\n";
191 return false;
192 }
193 std::unique_ptr<llvm::opt::InputArgList> Args = std::move(ArgsOrErr.get());
194
Rui Ueyama5c726432015-05-29 16:11:52 +0000195 // Handle /help
196 if (Args->hasArg(OPT_help)) {
197 printHelp(Argv[0]);
198 return true;
199 }
200
Rui Ueyama411c63602015-05-28 19:09:30 +0000201 if (Args->filtered_begin(OPT_INPUT) == Args->filtered_end()) {
202 llvm::errs() << "no input files.\n";
203 return false;
204 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000205
Rui Ueyamaad660982015-06-07 00:20:32 +0000206 // Handle /out
207 if (auto *Arg = Args->getLastArg(OPT_out))
208 Config->OutputFile = Arg->getValue();
209
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000210 // Handle /verbose
Rui Ueyama411c63602015-05-28 19:09:30 +0000211 if (Args->hasArg(OPT_verbose))
212 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000213
214 // Handle /entry
Rui Ueyama411c63602015-05-28 19:09:30 +0000215 if (auto *Arg = Args->getLastArg(OPT_entry))
216 Config->EntryName = Arg->getValue();
217
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000218 // Handle /machine
219 auto MTOrErr = getMachineType(Args.get());
220 if (auto EC = MTOrErr.getError()) {
221 llvm::errs() << EC.message() << "\n";
222 return false;
223 }
224 Config->MachineType = MTOrErr.get();
225
Rui Ueyama06137472015-05-31 20:10:11 +0000226 // Handle /libpath
Rui Ueyamaf4784cc2015-05-31 20:20:37 +0000227 for (auto *Arg : Args->filtered(OPT_libpath)) {
228 // Inserting at front of a vector is okay because it's short.
229 // +1 because the first entry is always "." (current directory).
230 SearchPaths.insert(SearchPaths.begin() + 1, Arg->getValue());
231 }
Rui Ueyama06137472015-05-31 20:10:11 +0000232
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000233 // Handle /nodefaultlib:<filename>
234 for (auto *Arg : Args->filtered(OPT_nodefaultlib))
235 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
236
237 // Handle /nodefaultlib
238 if (Args->hasArg(OPT_nodefaultlib_all))
239 Config->NoDefaultLibAll = true;
240
Rui Ueyama804a8b62015-05-29 16:18:15 +0000241 // Handle /base
242 if (auto *Arg = Args->getLastArg(OPT_base)) {
243 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000244 llvm::errs() << "/base: " << EC.message() << "\n";
245 return false;
246 }
247 }
248
249 // Handle /stack
250 if (auto *Arg = Args->getLastArg(OPT_stack)) {
251 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
252 &Config->StackCommit)) {
253 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000254 return false;
255 }
256 }
257
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000258 // Handle /heap
259 if (auto *Arg = Args->getLastArg(OPT_heap)) {
260 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
261 &Config->HeapCommit)) {
262 llvm::errs() << "/heap: " << EC.message() << "\n";
263 return false;
264 }
265 }
266
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000267 // Handle /version
268 if (auto *Arg = Args->getLastArg(OPT_version)) {
269 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
270 &Config->MinorImageVersion)) {
271 llvm::errs() << "/version: " << EC.message() << "\n";
272 return false;
273 }
274 }
275
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000276 // Handle /subsystem
277 if (auto *Arg = Args->getLastArg(OPT_subsystem)) {
278 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
279 &Config->MajorOSVersion,
280 &Config->MinorOSVersion)) {
281 llvm::errs() << "/subsystem: " << EC.message() << "\n";
282 return false;
283 }
284 }
285
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000286 // Handle /opt
287 for (auto *Arg : Args->filtered(OPT_opt)) {
288 std::string S = StringRef(Arg->getValue()).lower();
289 if (S == "noref") {
290 Config->DoGC = false;
291 continue;
292 }
293 if (S != "ref" && S != "icf" && S != "noicf" &&
294 S != "lbr" && S != "nolbr" &&
295 !StringRef(S).startswith("icf=")) {
296 llvm::errs() << "/opt: unknown option: " << S << "\n";
297 return false;
298 }
299 }
300
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000301 // Handle /failifmismatch
302 if (auto EC = checkFailIfMismatch(Args.get())) {
303 llvm::errs() << "/failifmismatch: " << EC.message() << "\n";
304 return false;
305 }
306
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000307 // Create a list of input files. Files can be given as arguments
308 // for /defaultlib option.
309 std::vector<StringRef> Inputs;
310 for (auto *Arg : Args->filtered(OPT_INPUT))
311 if (Optional<StringRef> Path = findFile(Arg->getValue()))
312 Inputs.push_back(*Path);
313 for (auto *Arg : Args->filtered(OPT_defaultlib))
314 if (Optional<StringRef> Path = findLib(Arg->getValue()))
315 Inputs.push_back(*Path);
316
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000317 // Create a symbol table.
318 SymbolTable Symtab;
319
320 // Add undefined symbols given via the command line.
321 // (/include is equivalent to Unix linker's -u option.)
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000322 for (auto *Arg : Args->filtered(OPT_incl)) {
323 StringRef Sym = Arg->getValue();
324 Symtab.addUndefined(Sym);
325 Config->GCRoots.insert(Sym);
326 }
Rui Ueyamae042fa9a2015-05-31 19:55:40 +0000327
Rui Ueyama411c63602015-05-28 19:09:30 +0000328 // Parse all input files and put all symbols to the symbol table.
329 // The symbol table will take care of name resolution.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000330 for (StringRef Path : Inputs) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000331 auto FileOrErr = openFile(Path);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000332 if (auto EC = FileOrErr.getError()) {
333 llvm::errs() << Path << ": " << EC.message() << "\n";
334 return false;
335 }
336 std::unique_ptr<InputFile> File = std::move(FileOrErr.get());
Rui Ueyamaeeae5dd2015-06-08 06:00:10 +0000337 if (Config->Verbose)
338 llvm::outs() << "Reading " << File->getName() << "\n";
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000339 if (auto EC = Symtab.addFile(std::move(File))) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000340 llvm::errs() << Path << ": " << EC.message() << "\n";
341 return false;
342 }
343 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000344
Rui Ueyama360bace2015-05-31 22:31:31 +0000345 // Add weak aliases. Weak aliases is a mechanism to give remaining
346 // undefined symbols final chance to be resolved successfully.
347 // This is symbol renaming.
348 for (auto *Arg : Args->filtered(OPT_alternatename)) {
Rui Ueyama2ba79082015-06-04 19:21:22 +0000349 // Parse a string of the form of "/alternatename:From=To".
Rui Ueyama360bace2015-05-31 22:31:31 +0000350 StringRef From, To;
351 std::tie(From, To) = StringRef(Arg->getValue()).split('=');
352 if (From.empty() || To.empty()) {
353 llvm::errs() << "/alternatename: invalid argument: "
354 << Arg->getValue() << "\n";
355 return false;
356 }
Rui Ueyama2ba79082015-06-04 19:21:22 +0000357 // If From is already resolved to a Defined type, do nothing.
Rui Ueyama68216c62015-06-01 03:55:02 +0000358 // Otherwise, rename it to see if To can be resolved instead.
Rui Ueyama360bace2015-05-31 22:31:31 +0000359 if (Symtab.find(From))
360 continue;
361 if (auto EC = Symtab.rename(From, To)) {
362 llvm::errs() << EC.message() << "\n";
363 return false;
364 }
365 }
366
Rui Ueyama5cff6852015-05-31 03:34:08 +0000367 // Windows specific -- If entry point name is not given, we need to
368 // infer that from user-defined entry name. The symbol table takes
369 // care of details.
370 if (Config->EntryName.empty()) {
371 auto EntryOrErr = Symtab.findDefaultEntry();
372 if (auto EC = EntryOrErr.getError()) {
373 llvm::errs() << EC.message() << "\n";
374 return false;
375 }
376 Config->EntryName = EntryOrErr.get();
377 }
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000378 Config->GCRoots.insert(Config->EntryName);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000379
380 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000381 if (Symtab.reportRemainingUndefines())
382 return false;
383
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000384 // Do LTO by compiling bitcode input files to a native COFF file
385 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000386 if (auto EC = Symtab.addCombinedLTOObject()) {
387 llvm::errs() << EC.message() << "\n";
388 return false;
389 }
390
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000391 // Windows specific -- if no /subsystem is given, we need to infer
392 // that from entry point name.
393 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
394 Config->Subsystem =
395 StringSwitch<WindowsSubsystem>(Config->EntryName)
396 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
397 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
398 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
399 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
400 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
401 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
402 llvm::errs() << "subsystem must be defined\n";
403 return false;
404 }
405 }
406
Rui Ueyama411c63602015-05-28 19:09:30 +0000407 // Write the result.
408 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000409 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000410 llvm::errs() << EC.message() << "\n";
411 return false;
412 }
413 return true;
414}
415
Rui Ueyama411c63602015-05-28 19:09:30 +0000416} // namespace coff
417} // namespace lld