blob: 0d14ca40671b2d44e206ab026833fd5f8159492c [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
Rui Ueyama411c63602015-05-28 19:09:30 +000010#include "Driver.h"
Rui Ueyama1d99ab32016-09-15 22:24:51 +000011#include "Config.h"
Rui Ueyama562daa82015-06-18 21:50:38 +000012#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000014#include "Memory.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000015#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000016#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000017#include "Writer.h"
Rui Ueyamaa453c0a2016-03-02 19:08:05 +000018#include "lld/Driver/Driver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000019#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000020#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000021#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000022#include "llvm/Option/Arg.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000026#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000027#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000028#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000029#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000031#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000032#include <memory>
33
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000034#include <future>
35
Rui Ueyama411c63602015-05-28 19:09:30 +000036using namespace llvm;
Rui Ueyama84936e02015-07-07 23:39:18 +000037using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000038using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000039using llvm::sys::fs::file_magic;
40using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000041
Rui Ueyama3500f662015-05-28 20:30:06 +000042namespace lld {
43namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000044
Rui Ueyama3500f662015-05-28 20:30:06 +000045Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000046LinkerDriver *Driver;
47
Rui Ueyama9381eb12016-12-18 14:06:06 +000048BumpPtrAllocator BAlloc;
49StringSaver Saver{BAlloc};
50std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
51
Bob Haarman6c8f7362017-01-17 19:07:42 +000052bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
53 ErrorCount = 0;
54 ErrorOS = &Diag;
55 Argv0 = Args[0];
Rui Ueyama7fed58c2016-12-08 19:10:28 +000056 Config = make<Configuration>();
Bob Haarman6c8f7362017-01-17 19:07:42 +000057 Config->ColorDiagnostics =
58 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
Rui Ueyama7fed58c2016-12-08 19:10:28 +000059 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000060 Driver->link(Args);
David Blaikie4cdfe692017-02-19 02:25:47 +000061 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000062}
Rui Ueyama411c63602015-05-28 19:09:30 +000063
Nico Weber5660de72016-04-20 22:34:15 +000064// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000065static std::string getOutputPath(StringRef Path) {
66 auto P = Path.find_last_of("\\/");
67 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000068 const char* E = Config->DLL ? ".dll" : ".exe";
69 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000070}
71
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000072// ErrorOr is not default constructible, so it cannot be used as the type
73// parameter of a future.
74// FIXME: We could open the file in createFutureForFile and avoid needing to
75// return an error here, but for the moment that would cost us a file descriptor
76// (a limited resource on Windows) for the duration that the future is pending.
77typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
78
79// Create a std::future that opens and maps a file using the best strategy for
80// the host platform.
81static std::future<MBErrPair> createFutureForFile(std::string Path) {
82#if LLVM_ON_WIN32
83 // On Windows, file I/O is relatively slow so it is best to do this
84 // asynchronously.
85 auto Strategy = std::launch::async;
86#else
87 auto Strategy = std::launch::deferred;
88#endif
89 return std::async(Strategy, [=]() {
90 auto MBOrErr = MemoryBuffer::getFile(Path);
91 if (!MBOrErr)
92 return MBErrPair{nullptr, MBOrErr.getError()};
93 return MBErrPair{std::move(*MBOrErr), std::error_code()};
94 });
95}
96
97MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
98 MemoryBufferRef MBRef = *MB;
99 OwningMBs.push_back(std::move(MB));
100
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000101 if (Driver->Tar)
102 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
103 MBRef.getBuffer());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000104
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000105 return MBRef;
106}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000107
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000108void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
109 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000110
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000111 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000112 file_magic Magic = identify_magic(MBRef.getBuffer());
113 if (Magic == file_magic::windows_resource) {
114 Resources.push_back(MBRef);
115 return;
116 }
117
118 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000119 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000120 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000121 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000122 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000123 if (Magic == file_magic::coff_cl_gl_object)
David Blaikie4cdfe692017-02-19 02:25:47 +0000124 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000125 "Recompile without /GL");
David Blaikie4cdfe692017-02-19 02:25:47 +0000126 Symtab.addFile(make<ObjectFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000127}
128
129void LinkerDriver::enqueuePath(StringRef Path) {
130 auto Future =
131 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
132 std::string PathStr = Path;
133 enqueueTask([=]() {
134 auto MBOrErr = Future->get();
135 if (MBOrErr.second)
David Blaikie4cdfe692017-02-19 02:25:47 +0000136 fatal(MBOrErr.second, "could not open " + PathStr);
137 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000138 });
139
Rui Ueyamaad660982015-06-07 00:20:32 +0000140 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000141 Config->OutputFile = getOutputPath(Path);
142}
143
144void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
145 StringRef ParentName) {
146 file_magic Magic = identify_magic(MB.getBuffer());
147 if (Magic == file_magic::coff_import_library) {
148 Symtab.addFile(make<ImportFile>(MB));
149 return;
150 }
151
152 InputFile *Obj;
David Blaikie4cdfe692017-02-19 02:25:47 +0000153 if (Magic == file_magic::coff_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000154 Obj = make<ObjectFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000155 else if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000156 Obj = make<BitcodeFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000157 else
158 fatal("unknown file type: " + MB.getBufferIdentifier());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000159
160 Obj->ParentName = ParentName;
161 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000162 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000163}
164
165void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
166 StringRef SymName,
167 StringRef ParentName) {
168 if (!C.getParent()->isThin()) {
169 MemoryBufferRef MB = check(
170 C.getMemoryBufferRef(),
171 "could not get the buffer for the member defining symbol " + SymName);
172 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
173 return;
174 }
175
176 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
177 check(C.getFullName(),
178 "could not get the filename for the member defining symbol " +
179 SymName)));
180 enqueueTask([=]() {
181 auto MBOrErr = Future->get();
182 if (MBOrErr.second)
183 fatal(MBOrErr.second,
184 "could not get the buffer for the member defining " + SymName);
185 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
186 ParentName);
187 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000188}
189
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000190static bool isDecorated(StringRef Sym) {
191 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
192}
193
Rui Ueyama411c63602015-05-28 19:09:30 +0000194// Parses .drectve section contents and returns a list of files
195// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000196void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000197 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000198
David Blaikie6521ed92015-06-22 22:06:52 +0000199 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000200 switch (Arg->getOption().getID()) {
201 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000202 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000203 break;
204 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000205 if (Optional<StringRef> Path = findLib(Arg->getValue()))
206 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000207 break;
208 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000209 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000210 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000211 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000212 break;
213 }
214 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000215 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000216 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000217 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000218 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000219 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000220 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000221 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000222 break;
223 case OPT_nodefaultlib:
224 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
225 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000226 case OPT_section:
227 parseSection(Arg->getValue());
228 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000229 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000230 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000231 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000232 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000233 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000234 default:
David Blaikie4cdfe692017-02-19 02:25:47 +0000235 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000236 }
237 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000238}
239
Rui Ueyama54b71da2015-05-31 19:17:12 +0000240// Find file from search paths. You can omit ".obj", this function takes
241// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000242StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000243 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
244 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000245 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000246 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000247 for (StringRef Dir : SearchPaths) {
248 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000249 sys::path::append(Path, Filename);
250 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000251 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000252 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000253 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000254 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000255 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000256 }
257 }
258 return Filename;
259}
260
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000261// Resolves a file path. This never returns the same path
262// (in that case, it returns None).
263Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
264 StringRef Path = doFindFile(Filename);
265 bool Seen = !VisitedFiles.insert(Path.lower()).second;
266 if (Seen)
267 return None;
268 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000269}
270
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000271// Find library file from search path.
272StringRef LinkerDriver::doFindLib(StringRef Filename) {
273 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000274 bool HasExt = (Filename.find('.') != StringRef::npos);
275 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000276 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000277 return doFindFile(Filename);
278}
279
280// Resolves a library path. /nodefaultlib options are taken into
281// consideration. This never returns the same path (in that case,
282// it returns None).
283Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
284 if (Config->NoDefaultLibAll)
285 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000286 if (!VisitedLibs.insert(Filename.lower()).second)
287 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000288 StringRef Path = doFindLib(Filename);
289 if (Config->NoDefaultLibs.count(Path))
290 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000291 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000292 return None;
293 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000294}
295
296// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000297void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000298 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
299 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000300 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000301 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000302 while (!Env.empty()) {
303 StringRef Path;
304 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000305 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000306 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000307}
308
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000309SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
310 SymbolBody *B = Symtab.addUndefined(Name);
311 Config->GCRoot.insert(B);
312 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000313}
314
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000315// Symbol names are mangled by appending "_" prefix on x86.
316StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000317 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
318 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000319 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000320 return Sym;
321}
322
Rui Ueyama45044f42015-06-29 01:03:53 +0000323// Windows specific -- find default entry point name.
324StringRef LinkerDriver::findDefaultEntry() {
325 // User-defined main functions and their corresponding entry points.
326 static const char *Entries[][2] = {
327 {"main", "mainCRTStartup"},
328 {"wmain", "wmainCRTStartup"},
329 {"WinMain", "WinMainCRTStartup"},
330 {"wWinMain", "wWinMainCRTStartup"},
331 };
332 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000333 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000334 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000335 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000336 }
337 return "";
338}
339
340WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000341 if (Config->DLL)
342 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000343 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000344 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000345 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000346 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
347 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000348}
349
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000350static uint64_t getDefaultImageBase() {
351 if (Config->is64())
352 return Config->DLL ? 0x180000000 : 0x140000000;
353 return Config->DLL ? 0x10000000 : 0x400000;
354}
355
Rui Ueyama8fe17672016-12-08 20:50:47 +0000356static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000357 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000358 ArrayRef<StringRef> SearchPaths) {
359 SmallString<0> Data;
360 raw_svector_ostream OS(Data);
361
362 for (auto *Arg : Args) {
363 switch (Arg->getOption().getID()) {
364 case OPT_linkrepro:
365 case OPT_INPUT:
366 case OPT_defaultlib:
367 case OPT_libpath:
368 break;
369 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000370 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000371 }
372 }
373
374 for (StringRef Path : SearchPaths) {
375 std::string RelPath = relativeToRoot(Path);
376 OS << "/libpath:" << quote(RelPath) << "\n";
377 }
378
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000379 for (StringRef Path : FilePaths)
380 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000381
382 return Data.str();
383}
384
Rui Ueyama8fe17672016-12-08 20:50:47 +0000385static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000386 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
387 if (Args.hasArg(OPT_driver))
388 DebugTypes |= static_cast<unsigned>(DebugType::PData);
389 if (Args.hasArg(OPT_profile))
390 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
391 return DebugTypes;
392}
393
394static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000395 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000396 Arg.split(Types, ',', /*KeepEmpty=*/false);
397
398 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
399 for (StringRef Type : Types)
400 DebugTypes |= StringSwitch<unsigned>(Type.lower())
401 .Case("cv", static_cast<unsigned>(DebugType::CV))
402 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000403 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
404 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000405 return DebugTypes;
406}
407
Hans Wennborg1818e652016-12-09 20:54:44 +0000408static std::string getMapFile(const opt::InputArgList &Args) {
409 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
410 if (!Arg)
411 return "";
412 if (Arg->getOption().getID() == OPT_lldmap_file)
413 return Arg->getValue();
414
415 assert(Arg->getOption().getID() == OPT_lldmap);
416 StringRef OutFile = Config->OutputFile;
417 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
418}
419
Rui Ueyamae0341db2017-03-07 19:45:53 +0000420// Returns true if a given file is a LLVM bitcode file. If it is a
421// static library, this function look at the first file in the archive
422// to determine if it's a bitcode file.
Rui Ueyama85d54b02017-02-23 00:26:42 +0000423static bool isBitcodeFile(StringRef Path) {
Rui Ueyamae0341db2017-03-07 19:45:53 +0000424 using namespace sys::fs;
425
Rui Ueyama85d54b02017-02-23 00:26:42 +0000426 std::unique_ptr<MemoryBuffer> MB = check(
427 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000428 file_magic Magic = identify_magic(MB->getBuffer());
429
430 if (Magic == file_magic::bitcode)
431 return true;
432
433 if (Magic == file_magic::archive) {
434 std::unique_ptr<Archive> File =
435 check(Archive::create(MB->getMemBufferRef()));
436 Error Err = Error::success();
437 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
438 if (Err)
439 return true;
440 Archive::Child C = check(COrErr);
441 MemoryBufferRef MBRef = check(C.getMemoryBufferRef());
442 return identify_magic(MBRef.getBuffer()) == file_magic::bitcode;
443 }
444 return true;
445 }
446
447 return false;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000448}
449
450// Create response file contents and invoke the MSVC linker.
451void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
452 std::string Rsp = "/nologo ";
453
454 for (auto *Arg : Args) {
455 switch (Arg->getOption().getID()) {
456 case OPT_linkrepro:
457 case OPT_lldmap:
458 case OPT_lldmap_file:
459 case OPT_msvclto:
460 // LLD-specific options are stripped.
461 break;
462 case OPT_opt:
463 if (!StringRef(Arg->getValue()).startswith("lld"))
464 Rsp += toString(Arg) + " ";
465 break;
466 case OPT_INPUT:
467 // Bitcode files are stripped as they've been compiled to
468 // native object files.
469 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
470 if (isBitcodeFile(*Path))
471 break;
472 Rsp += quote(Arg->getValue()) + " ";
473 break;
474 default:
475 Rsp += toString(Arg) + " ";
476 }
477 }
478
479 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
480 runMSVCLinker(Rsp, ObjectFiles);
481}
482
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000483void LinkerDriver::enqueueTask(std::function<void()> Task) {
484 TaskQueue.push_back(std::move(Task));
485}
486
487bool LinkerDriver::run() {
488 bool DidWork = !TaskQueue.empty();
489 while (!TaskQueue.empty()) {
490 TaskQueue.front()();
491 TaskQueue.pop_front();
492 }
493 return DidWork;
494}
495
Rui Ueyama8fe17672016-12-08 20:50:47 +0000496void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000497 // If the first command line argument is "/lib", link.exe acts like lib.exe.
498 // We call our own implementation of lib.exe that understands bitcode files.
499 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
500 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000501 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000502 return;
503 }
504
Peter Collingbourne60c16162015-06-01 20:10:10 +0000505 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000506 InitializeAllTargetInfos();
507 InitializeAllTargets();
508 InitializeAllTargetMCs();
509 InitializeAllAsmParsers();
510 InitializeAllAsmPrinters();
511 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000512
Rui Ueyama411c63602015-05-28 19:09:30 +0000513 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000514 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000515
Rui Ueyama5c726432015-05-29 16:11:52 +0000516 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000517 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000518 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000519 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000520 }
521
Peter Collingbournefeee2102016-07-26 02:00:42 +0000522 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
523 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000524 sys::path::append(Path, "repro.tar");
525
526 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
527 TarWriter::create(Path, "repro");
528
529 if (ErrOrWriter) {
530 Tar = std::move(*ErrOrWriter);
531 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000532 error("/linkrepro: failed to open " + Path + ": " +
533 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000534 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000535 }
536
Rafael Espindolab835ae82015-08-06 14:58:50 +0000537 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000538 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000539
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000540 // Construct search path list.
541 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000542 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000543 SearchPaths.push_back(Arg->getValue());
544 addLibSearchPaths();
545
Rui Ueyamaad660982015-06-07 00:20:32 +0000546 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000547 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000548 Config->OutputFile = Arg->getValue();
549
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000550 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000551 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000552 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000553
Rui Ueyama95925fd2015-06-28 19:35:15 +0000554 // Handle /force or /force:unresolved
555 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
556 Config->Force = true;
557
Rui Ueyama6600eb12015-07-04 23:37:32 +0000558 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000559 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000560 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000561 Config->DebugTypes =
562 Args.hasArg(OPT_debugtype)
563 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
564 : getDefaultDebugType(Args);
565 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000566
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000567 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000568 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000569 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000570
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000571 // Handle /noentry
572 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000573 if (!Args.hasArg(OPT_dll))
David Blaikie4cdfe692017-02-19 02:25:47 +0000574 fatal("/noentry must be specified with /dll");
575 Config->NoEntry = true;
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000576 }
577
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000578 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000579 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000580 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000581 Config->ManifestID = 2;
582 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000583
Rui Ueyama588e8322015-06-15 01:23:58 +0000584 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000585 if (Args.hasArg(OPT_fixed)) {
David Blaikie4cdfe692017-02-19 02:25:47 +0000586 if (Args.hasArg(OPT_dynamicbase))
587 fatal("/fixed must not be specified with /dynamicbase");
588 Config->Relocatable = false;
589 Config->DynamicBase = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000590 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000591
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000592 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000593 if (auto *Arg = Args.getLastArg(OPT_machine))
594 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000595
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000596 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000597 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000598 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
599
600 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000601 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000602 Config->NoDefaultLibAll = true;
603
Rui Ueyama804a8b62015-05-29 16:18:15 +0000604 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000605 if (auto *Arg = Args.getLastArg(OPT_base))
606 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000607
608 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000609 if (auto *Arg = Args.getLastArg(OPT_stack))
610 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000611
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000612 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000613 if (auto *Arg = Args.getLastArg(OPT_heap))
614 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000615
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000616 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000617 if (auto *Arg = Args.getLastArg(OPT_version))
618 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
619 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000620
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000621 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000622 if (auto *Arg = Args.getLastArg(OPT_subsystem))
623 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
624 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000625
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000626 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000627 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000628 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000629
Rui Ueyama08d5e182015-06-18 23:20:11 +0000630 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000631 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000632 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000633
Rui Ueyamab95188c2015-06-18 20:27:09 +0000634 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000635 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000636 Config->Implib = Arg->getValue();
637
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000638 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000639 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000640 std::string Str = StringRef(Arg->getValue()).lower();
641 SmallVector<StringRef, 1> Vec;
642 StringRef(Str).split(Vec, ',');
643 for (StringRef S : Vec) {
644 if (S == "noref") {
645 Config->DoGC = false;
646 Config->DoICF = false;
647 continue;
648 }
649 if (S == "icf" || StringRef(S).startswith("icf=")) {
650 Config->DoICF = true;
651 continue;
652 }
653 if (S == "noicf") {
654 Config->DoICF = false;
655 continue;
656 }
657 if (StringRef(S).startswith("lldlto=")) {
658 StringRef OptLevel = StringRef(S).substr(7);
659 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
660 Config->LTOOptLevel > 3)
David Blaikie4cdfe692017-02-19 02:25:47 +0000661 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000662 continue;
663 }
664 if (StringRef(S).startswith("lldltojobs=")) {
665 StringRef Jobs = StringRef(S).substr(11);
666 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000667 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000668 continue;
669 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000670 if (StringRef(S).startswith("lldltopartitions=")) {
671 StringRef N = StringRef(S).substr(17);
672 if (N.getAsInteger(10, Config->LTOPartitions) ||
673 Config->LTOPartitions == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000674 fatal("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000675 continue;
676 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000677 if (S != "ref" && S != "lbr" && S != "nolbr")
David Blaikie4cdfe692017-02-19 02:25:47 +0000678 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000679 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000680 }
681
Bob Haarman69b196d2017-02-08 18:36:41 +0000682 // Handle /lldsavetemps
683 if (Args.hasArg(OPT_lldsavetemps))
684 Config->SaveTemps = true;
685
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000686 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000687 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000688 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000689
Rui Ueyama6600eb12015-07-04 23:37:32 +0000690 // Handle /merge
691 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000692 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000693
Rui Ueyama440138c2016-06-20 03:39:39 +0000694 // Handle /section
695 for (auto *Arg : Args.filtered(OPT_section))
696 parseSection(Arg->getValue());
697
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000698 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000699 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
700 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000701
702 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000703 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
704 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000705
706 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000707 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000708 Config->ManifestDependency = Arg->getValue();
709
710 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000711 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000712 Config->ManifestFile = Arg->getValue();
713
Rui Ueyamaafb19012016-04-19 01:21:58 +0000714 // Handle /manifestinput
715 for (auto *Arg : Args.filtered(OPT_manifestinput))
716 Config->ManifestInput.push_back(Arg->getValue());
717
Rui Ueyama6592ff82015-06-16 23:13:00 +0000718 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000719 if (Args.hasArg(OPT_allowbind_no))
720 Config->AllowBind = false;
721 if (Args.hasArg(OPT_allowisolation_no))
722 Config->AllowIsolation = false;
723 if (Args.hasArg(OPT_dynamicbase_no))
724 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000725 if (Args.hasArg(OPT_nxcompat_no))
726 Config->NxCompat = false;
727 if (Args.hasArg(OPT_tsaware_no))
728 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000729 if (Args.hasArg(OPT_nosymtab))
730 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000731 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000732 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000733
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000734 Config->MapFile = getMapFile(Args);
735
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000736 // Create a list of input files. Files can be given as arguments
737 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000738 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000739 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000740 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000741 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000742 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000743 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000744 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000745
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000746 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000747 if (Config->Manifest == Configuration::Embed)
748 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000749
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000750 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000751 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000752
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000753 // We should have inferred a machine type by now from the input files, but if
754 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000755 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000756 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000757 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000758 }
759
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000760 // Windows specific -- Input files can be Windows resource files (.res files).
761 // We invoke cvtres.exe to convert resource files to a regular COFF file
762 // then link the result file normally.
763 if (!Resources.empty())
764 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000765
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000766 if (Tar)
767 Tar->append("response.txt",
768 createResponseFile(Args, FilePaths,
769 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000770
Rui Ueyama4d545342015-07-28 03:12:00 +0000771 // Handle /largeaddressaware
772 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
773 Config->LargeAddressAware = true;
774
Rui Ueyamad68e2112015-07-28 03:15:57 +0000775 // Handle /highentropyva
776 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
777 Config->HighEntropyVA = true;
778
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000779 // Handle /entry and /dll
780 if (auto *Arg = Args.getLastArg(OPT_entry)) {
781 Config->Entry = addUndefined(mangle(Arg->getValue()));
782 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000783 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
784 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000785 Config->Entry = addUndefined(S);
786 } else if (!Config->NoEntry) {
787 // Windows specific -- If entry point name is not given, we need to
788 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000789 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +0000790 if (S.empty())
791 fatal("entry point must be defined");
792 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000793 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +0000794 }
795
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000796 // Handle /export
797 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000798 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000799 if (Config->Machine == I386) {
800 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000801 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000802 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000803 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000804 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000805 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000806 }
807
808 // Handle /def
809 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000810 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000811 parseModuleDefs(
812 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
813 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000814 }
815
Rui Ueyama6d249082015-07-13 22:31:45 +0000816 // Handle /delayload
817 for (auto *Arg : Args.filtered(OPT_delayload)) {
818 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000819 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000820 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000821 } else {
822 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000823 }
824 }
825
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000826 // Set default image base if /base is not given.
827 if (Config->ImageBase == uint64_t(-1))
828 Config->ImageBase = getDefaultImageBase();
829
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000830 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000831 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000832 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
833 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
834 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000835
Rui Ueyama107db552015-08-09 21:01:06 +0000836 // We do not support /guard:cf (control flow protection) yet.
837 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
838 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
839 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
840 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
841
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000842 // This code may add new undefined symbols to the link, which may enqueue more
843 // symbol resolution tasks, so we need to continue executing tasks until we
844 // converge.
845 do {
846 // Windows specific -- if entry point is not found,
847 // search for its mangled names.
848 if (Config->Entry)
849 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000850
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000851 // Windows specific -- Make sure we resolve all dllexported symbols.
852 for (Export &E : Config->Exports) {
853 if (!E.ForwardTo.empty())
854 continue;
855 E.Sym = addUndefined(E.Name);
856 if (!E.Directives)
857 Symtab.mangleMaybe(E.Sym);
858 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000859
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000860 // Add weak aliases. Weak aliases is a mechanism to give remaining
861 // undefined symbols final chance to be resolved successfully.
862 for (auto Pair : Config->AlternateNames) {
863 StringRef From = Pair.first;
864 StringRef To = Pair.second;
865 Symbol *Sym = Symtab.find(From);
866 if (!Sym)
867 continue;
868 if (auto *U = dyn_cast<Undefined>(Sym->body()))
869 if (!U->WeakAlias)
870 U->WeakAlias = Symtab.addUndefined(To);
871 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000872
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000873 // Windows specific -- if __load_config_used can be resolved, resolve it.
874 if (Symtab.findUnderscore("_load_config_used"))
875 addUndefined(mangle("_load_config_used"));
876 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000877
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000878 // If /msvclto is given, we use the MSVC linker to link LTO output files.
879 // This is useful because MSVC link.exe can generate complete PDBs.
880 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000881 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000882 exit(0);
883 }
884
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000885 // Do LTO by compiling bitcode input files to a set of native COFF files then
886 // link those files.
887 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000888 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000889
Peter Collingbourne2612a322015-07-04 05:28:41 +0000890 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000891 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000892
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000893 // Windows specific -- if no /subsystem is given, we need to infer
894 // that from entry point name.
895 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000896 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000897 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000898 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000899 }
900
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000901 // Handle /safeseh.
David Blaikie4cdfe692017-02-19 02:25:47 +0000902 if (Args.hasArg(OPT_safeseh))
Rui Ueyama13563d82015-09-15 00:33:11 +0000903 for (ObjectFile *File : Symtab.ObjectFiles)
904 if (!File->SEHCompat)
David Blaikie4cdfe692017-02-19 02:25:47 +0000905 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000906
Rui Ueyama151d8622015-06-17 20:40:43 +0000907 // Windows specific -- when we are creating a .dll file, we also
908 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000909 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000910 fixupExports();
911 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000912 assignExportOrdinals();
913 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000914
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000915 // Windows specific -- Create a side-by-side manifest file.
916 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000917 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000918
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000919 // Identify unreferenced COMDAT sections.
920 if (Config->DoGC)
921 markLive(Symtab.getChunks());
922
923 // Identify identical COMDAT sections to merge them.
924 if (Config->DoICF)
925 doICF(Symtab.getChunks());
926
Rui Ueyama411c63602015-05-28 19:09:30 +0000927 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000928 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000929
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000930 // Call exit to avoid calling destructors.
931 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000932}
933
Rui Ueyama411c63602015-05-28 19:09:30 +0000934} // namespace coff
935} // namespace lld