blob: eb2ee6e3f0786cbed30ec879aae870053822c2ee [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#ifdef _MSC_VER
35// <future> depends on <eh.h> for __uncaught_exception.
36#include <eh.h>
37#endif
38
39#include <future>
40
Rui Ueyama411c63602015-05-28 19:09:30 +000041using namespace llvm;
Rui Ueyama84936e02015-07-07 23:39:18 +000042using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000043using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000044using llvm::sys::fs::file_magic;
45using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000046
Rui Ueyama3500f662015-05-28 20:30:06 +000047namespace lld {
48namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000051LinkerDriver *Driver;
52
Rui Ueyama9381eb12016-12-18 14:06:06 +000053BumpPtrAllocator BAlloc;
54StringSaver Saver{BAlloc};
55std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
56
Bob Haarman6c8f7362017-01-17 19:07:42 +000057bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
58 ErrorCount = 0;
59 ErrorOS = &Diag;
60 Argv0 = Args[0];
Rui Ueyama7fed58c2016-12-08 19:10:28 +000061 Config = make<Configuration>();
Bob Haarman6c8f7362017-01-17 19:07:42 +000062 Config->ColorDiagnostics =
63 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
Rui Ueyama7fed58c2016-12-08 19:10:28 +000064 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000065 Driver->link(Args);
66 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000067}
Rui Ueyama411c63602015-05-28 19:09:30 +000068
Nico Weber5660de72016-04-20 22:34:15 +000069// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000070static std::string getOutputPath(StringRef Path) {
71 auto P = Path.find_last_of("\\/");
72 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000073 const char* E = Config->DLL ? ".dll" : ".exe";
74 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000075}
76
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000077// ErrorOr is not default constructible, so it cannot be used as the type
78// parameter of a future.
79// FIXME: We could open the file in createFutureForFile and avoid needing to
80// return an error here, but for the moment that would cost us a file descriptor
81// (a limited resource on Windows) for the duration that the future is pending.
82typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
83
84// Create a std::future that opens and maps a file using the best strategy for
85// the host platform.
86static std::future<MBErrPair> createFutureForFile(std::string Path) {
87#if LLVM_ON_WIN32
88 // On Windows, file I/O is relatively slow so it is best to do this
89 // asynchronously.
90 auto Strategy = std::launch::async;
91#else
92 auto Strategy = std::launch::deferred;
93#endif
94 return std::async(Strategy, [=]() {
95 auto MBOrErr = MemoryBuffer::getFile(Path);
96 if (!MBOrErr)
97 return MBErrPair{nullptr, MBOrErr.getError()};
98 return MBErrPair{std::move(*MBOrErr), std::error_code()};
99 });
100}
101
102MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
103 MemoryBufferRef MBRef = *MB;
104 OwningMBs.push_back(std::move(MB));
105
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000106 if (Driver->Tar)
107 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
108 MBRef.getBuffer());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000109
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000110 return MBRef;
111}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000112
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000113void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
114 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000115
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000116 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000117 file_magic Magic = identify_magic(MBRef.getBuffer());
118 if (Magic == file_magic::windows_resource) {
119 Resources.push_back(MBRef);
120 return;
121 }
122
123 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000124 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000125 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000126 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000127 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000128 if (Magic == file_magic::coff_cl_gl_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000129 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000130 "Recompile without /GL");
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000131 Symtab.addFile(make<ObjectFile>(MBRef));
132}
133
134void LinkerDriver::enqueuePath(StringRef Path) {
135 auto Future =
136 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
137 std::string PathStr = Path;
138 enqueueTask([=]() {
139 auto MBOrErr = Future->get();
140 if (MBOrErr.second)
141 fatal(MBOrErr.second, "could not open " + PathStr);
142 Driver->addBuffer(std::move(MBOrErr.first));
143 });
144
Rui Ueyamaad660982015-06-07 00:20:32 +0000145 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000146 Config->OutputFile = getOutputPath(Path);
147}
148
149void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
150 StringRef ParentName) {
151 file_magic Magic = identify_magic(MB.getBuffer());
152 if (Magic == file_magic::coff_import_library) {
153 Symtab.addFile(make<ImportFile>(MB));
154 return;
155 }
156
157 InputFile *Obj;
158 if (Magic == file_magic::coff_object)
159 Obj = make<ObjectFile>(MB);
160 else if (Magic == file_magic::bitcode)
161 Obj = make<BitcodeFile>(MB);
162 else
163 fatal("unknown file type: " + MB.getBufferIdentifier());
164
165 Obj->ParentName = ParentName;
166 Symtab.addFile(Obj);
167 if (Config->Verbose)
168 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
169}
170
171void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
172 StringRef SymName,
173 StringRef ParentName) {
174 if (!C.getParent()->isThin()) {
175 MemoryBufferRef MB = check(
176 C.getMemoryBufferRef(),
177 "could not get the buffer for the member defining symbol " + SymName);
178 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
179 return;
180 }
181
182 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
183 check(C.getFullName(),
184 "could not get the filename for the member defining symbol " +
185 SymName)));
186 enqueueTask([=]() {
187 auto MBOrErr = Future->get();
188 if (MBOrErr.second)
189 fatal(MBOrErr.second,
190 "could not get the buffer for the member defining " + SymName);
191 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
192 ParentName);
193 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000194}
195
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000196static bool isDecorated(StringRef Sym) {
197 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
198}
199
Rui Ueyama411c63602015-05-28 19:09:30 +0000200// Parses .drectve section contents and returns a list of files
201// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000202void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000203 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000204
David Blaikie6521ed92015-06-22 22:06:52 +0000205 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000206 switch (Arg->getOption().getID()) {
207 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000208 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000209 break;
210 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000211 if (Optional<StringRef> Path = findLib(Arg->getValue()))
212 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000213 break;
214 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000215 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000216 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000217 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000218 break;
219 }
220 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000221 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000222 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000223 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000224 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000225 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000226 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000227 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000228 break;
229 case OPT_nodefaultlib:
230 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
231 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000232 case OPT_section:
233 parseSection(Arg->getValue());
234 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000235 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000236 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000237 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000238 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000239 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000240 default:
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000241 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000242 }
243 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000244}
245
Rui Ueyama54b71da2015-05-31 19:17:12 +0000246// Find file from search paths. You can omit ".obj", this function takes
247// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000248StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000249 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
250 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000251 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000252 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000253 for (StringRef Dir : SearchPaths) {
254 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000255 sys::path::append(Path, Filename);
256 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000257 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000258 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000259 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000260 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000261 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000262 }
263 }
264 return Filename;
265}
266
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000267// Resolves a file path. This never returns the same path
268// (in that case, it returns None).
269Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
270 StringRef Path = doFindFile(Filename);
271 bool Seen = !VisitedFiles.insert(Path.lower()).second;
272 if (Seen)
273 return None;
274 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000275}
276
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000277// Find library file from search path.
278StringRef LinkerDriver::doFindLib(StringRef Filename) {
279 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000280 bool HasExt = (Filename.find('.') != StringRef::npos);
281 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000282 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000283 return doFindFile(Filename);
284}
285
286// Resolves a library path. /nodefaultlib options are taken into
287// consideration. This never returns the same path (in that case,
288// it returns None).
289Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
290 if (Config->NoDefaultLibAll)
291 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000292 if (!VisitedLibs.insert(Filename.lower()).second)
293 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000294 StringRef Path = doFindLib(Filename);
295 if (Config->NoDefaultLibs.count(Path))
296 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000297 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000298 return None;
299 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000300}
301
302// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000303void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000304 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
305 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000306 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000307 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000308 while (!Env.empty()) {
309 StringRef Path;
310 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000311 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000312 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000313}
314
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000315SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
316 SymbolBody *B = Symtab.addUndefined(Name);
317 Config->GCRoot.insert(B);
318 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000319}
320
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000321// Symbol names are mangled by appending "_" prefix on x86.
322StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000323 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
324 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000325 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000326 return Sym;
327}
328
Rui Ueyama45044f42015-06-29 01:03:53 +0000329// Windows specific -- find default entry point name.
330StringRef LinkerDriver::findDefaultEntry() {
331 // User-defined main functions and their corresponding entry points.
332 static const char *Entries[][2] = {
333 {"main", "mainCRTStartup"},
334 {"wmain", "wmainCRTStartup"},
335 {"WinMain", "WinMainCRTStartup"},
336 {"wWinMain", "wWinMainCRTStartup"},
337 };
338 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000339 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000340 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000341 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000342 }
343 return "";
344}
345
346WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000347 if (Config->DLL)
348 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000349 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000350 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000351 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000352 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
353 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000354}
355
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000356static uint64_t getDefaultImageBase() {
357 if (Config->is64())
358 return Config->DLL ? 0x180000000 : 0x140000000;
359 return Config->DLL ? 0x10000000 : 0x400000;
360}
361
Rui Ueyama8fe17672016-12-08 20:50:47 +0000362static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000363 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000364 ArrayRef<StringRef> SearchPaths) {
365 SmallString<0> Data;
366 raw_svector_ostream OS(Data);
367
368 for (auto *Arg : Args) {
369 switch (Arg->getOption().getID()) {
370 case OPT_linkrepro:
371 case OPT_INPUT:
372 case OPT_defaultlib:
373 case OPT_libpath:
374 break;
375 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000376 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000377 }
378 }
379
380 for (StringRef Path : SearchPaths) {
381 std::string RelPath = relativeToRoot(Path);
382 OS << "/libpath:" << quote(RelPath) << "\n";
383 }
384
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000385 for (StringRef Path : FilePaths)
386 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000387
388 return Data.str();
389}
390
Rui Ueyama8fe17672016-12-08 20:50:47 +0000391static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000392 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
393 if (Args.hasArg(OPT_driver))
394 DebugTypes |= static_cast<unsigned>(DebugType::PData);
395 if (Args.hasArg(OPT_profile))
396 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
397 return DebugTypes;
398}
399
400static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000401 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000402 Arg.split(Types, ',', /*KeepEmpty=*/false);
403
404 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
405 for (StringRef Type : Types)
406 DebugTypes |= StringSwitch<unsigned>(Type.lower())
407 .Case("cv", static_cast<unsigned>(DebugType::CV))
408 .Case("pdata", static_cast<unsigned>(DebugType::PData))
409 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
410 return DebugTypes;
411}
412
Hans Wennborg1818e652016-12-09 20:54:44 +0000413static std::string getMapFile(const opt::InputArgList &Args) {
414 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
415 if (!Arg)
416 return "";
417 if (Arg->getOption().getID() == OPT_lldmap_file)
418 return Arg->getValue();
419
420 assert(Arg->getOption().getID() == OPT_lldmap);
421 StringRef OutFile = Config->OutputFile;
422 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
423}
424
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000425void LinkerDriver::enqueueTask(std::function<void()> Task) {
426 TaskQueue.push_back(std::move(Task));
427}
428
429bool LinkerDriver::run() {
430 bool DidWork = !TaskQueue.empty();
431 while (!TaskQueue.empty()) {
432 TaskQueue.front()();
433 TaskQueue.pop_front();
434 }
435 return DidWork;
436}
437
Rui Ueyama8fe17672016-12-08 20:50:47 +0000438void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000439 // If the first command line argument is "/lib", link.exe acts like lib.exe.
440 // We call our own implementation of lib.exe that understands bitcode files.
441 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
442 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000443 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000444 return;
445 }
446
Peter Collingbourne60c16162015-06-01 20:10:10 +0000447 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000448 InitializeAllTargetInfos();
449 InitializeAllTargets();
450 InitializeAllTargetMCs();
451 InitializeAllAsmParsers();
452 InitializeAllAsmPrinters();
453 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000454
Rui Ueyama411c63602015-05-28 19:09:30 +0000455 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000456 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000457
Rui Ueyama5c726432015-05-29 16:11:52 +0000458 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000459 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000460 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000461 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000462 }
463
Peter Collingbournefeee2102016-07-26 02:00:42 +0000464 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
465 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000466 sys::path::append(Path, "repro.tar");
467
468 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
469 TarWriter::create(Path, "repro");
470
471 if (ErrOrWriter) {
472 Tar = std::move(*ErrOrWriter);
473 } else {
474 errs() << "/linkrepro: failed to open " << Path << ": "
475 << toString(ErrOrWriter.takeError()) << '\n';
476 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000477 }
478
Rafael Espindolab835ae82015-08-06 14:58:50 +0000479 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000480 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000481
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000482 // Construct search path list.
483 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000484 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000485 SearchPaths.push_back(Arg->getValue());
486 addLibSearchPaths();
487
Rui Ueyamaad660982015-06-07 00:20:32 +0000488 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000489 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000490 Config->OutputFile = Arg->getValue();
491
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000492 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000493 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000494 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000495
Rui Ueyama95925fd2015-06-28 19:35:15 +0000496 // Handle /force or /force:unresolved
497 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
498 Config->Force = true;
499
Rui Ueyama6600eb12015-07-04 23:37:32 +0000500 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000501 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000502 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000503 Config->DebugTypes =
504 Args.hasArg(OPT_debugtype)
505 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
506 : getDefaultDebugType(Args);
507 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000508
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000509 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000510 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000511 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000512
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000513 // Handle /noentry
514 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000515 if (!Args.hasArg(OPT_dll))
Rui Ueyama60604792016-07-14 23:37:14 +0000516 fatal("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000517 Config->NoEntry = true;
518 }
519
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000520 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000521 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000522 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000523 Config->ManifestID = 2;
524 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000525
Rui Ueyama588e8322015-06-15 01:23:58 +0000526 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000527 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000528 if (Args.hasArg(OPT_dynamicbase))
Rui Ueyama60604792016-07-14 23:37:14 +0000529 fatal("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000530 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000531 Config->DynamicBase = false;
532 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000533
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000534 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000535 if (auto *Arg = Args.getLastArg(OPT_machine))
536 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000537
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000538 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000539 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000540 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
541
542 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000543 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000544 Config->NoDefaultLibAll = true;
545
Rui Ueyama804a8b62015-05-29 16:18:15 +0000546 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000547 if (auto *Arg = Args.getLastArg(OPT_base))
548 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000549
550 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000551 if (auto *Arg = Args.getLastArg(OPT_stack))
552 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000553
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000554 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000555 if (auto *Arg = Args.getLastArg(OPT_heap))
556 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000557
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000558 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000559 if (auto *Arg = Args.getLastArg(OPT_version))
560 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
561 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000562
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000563 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000564 if (auto *Arg = Args.getLastArg(OPT_subsystem))
565 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
566 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000567
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000568 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000569 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000570 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000571
Rui Ueyama08d5e182015-06-18 23:20:11 +0000572 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000573 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000574 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000575
Rui Ueyamab95188c2015-06-18 20:27:09 +0000576 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000577 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000578 Config->Implib = Arg->getValue();
579
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000580 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000581 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000582 std::string Str = StringRef(Arg->getValue()).lower();
583 SmallVector<StringRef, 1> Vec;
584 StringRef(Str).split(Vec, ',');
585 for (StringRef S : Vec) {
586 if (S == "noref") {
587 Config->DoGC = false;
588 Config->DoICF = false;
589 continue;
590 }
591 if (S == "icf" || StringRef(S).startswith("icf=")) {
592 Config->DoICF = true;
593 continue;
594 }
595 if (S == "noicf") {
596 Config->DoICF = false;
597 continue;
598 }
599 if (StringRef(S).startswith("lldlto=")) {
600 StringRef OptLevel = StringRef(S).substr(7);
601 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
602 Config->LTOOptLevel > 3)
Rui Ueyama60604792016-07-14 23:37:14 +0000603 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000604 continue;
605 }
606 if (StringRef(S).startswith("lldltojobs=")) {
607 StringRef Jobs = StringRef(S).substr(11);
608 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000609 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000610 continue;
611 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000612 if (StringRef(S).startswith("lldltopartitions=")) {
613 StringRef N = StringRef(S).substr(17);
614 if (N.getAsInteger(10, Config->LTOPartitions) ||
615 Config->LTOPartitions == 0)
616 fatal("/opt:lldltopartitions: invalid partition count: " + N);
617 continue;
618 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000619 if (S != "ref" && S != "lbr" && S != "nolbr")
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000620 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000621 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000622 }
623
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000624 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000625 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000626 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000627
Rui Ueyama6600eb12015-07-04 23:37:32 +0000628 // Handle /merge
629 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000630 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000631
Rui Ueyama440138c2016-06-20 03:39:39 +0000632 // Handle /section
633 for (auto *Arg : Args.filtered(OPT_section))
634 parseSection(Arg->getValue());
635
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000636 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000637 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
638 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000639
640 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000641 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
642 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000643
644 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000645 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000646 Config->ManifestDependency = Arg->getValue();
647
648 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000649 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000650 Config->ManifestFile = Arg->getValue();
651
Rui Ueyamaafb19012016-04-19 01:21:58 +0000652 // Handle /manifestinput
653 for (auto *Arg : Args.filtered(OPT_manifestinput))
654 Config->ManifestInput.push_back(Arg->getValue());
655
Rui Ueyama6592ff82015-06-16 23:13:00 +0000656 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000657 if (Args.hasArg(OPT_allowbind_no))
658 Config->AllowBind = false;
659 if (Args.hasArg(OPT_allowisolation_no))
660 Config->AllowIsolation = false;
661 if (Args.hasArg(OPT_dynamicbase_no))
662 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000663 if (Args.hasArg(OPT_nxcompat_no))
664 Config->NxCompat = false;
665 if (Args.hasArg(OPT_tsaware_no))
666 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000667 if (Args.hasArg(OPT_nosymtab))
668 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000669 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000670 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000671
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000672 Config->MapFile = getMapFile(Args);
673
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000674 // Create a list of input files. Files can be given as arguments
675 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000676 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000677 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000678 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000679 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000680 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000681 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000682 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000683
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000684 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000685 if (Config->Manifest == Configuration::Embed)
686 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000687
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000688 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000689 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000690
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000691 // We should have inferred a machine type by now from the input files, but if
692 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000693 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000694 errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000695 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000696 }
697
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000698 // Windows specific -- Input files can be Windows resource files (.res files).
699 // We invoke cvtres.exe to convert resource files to a regular COFF file
700 // then link the result file normally.
701 if (!Resources.empty())
702 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000703
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000704 if (Tar)
705 Tar->append("response.txt",
706 createResponseFile(Args, FilePaths,
707 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000708
Rui Ueyama4d545342015-07-28 03:12:00 +0000709 // Handle /largeaddressaware
710 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
711 Config->LargeAddressAware = true;
712
Rui Ueyamad68e2112015-07-28 03:15:57 +0000713 // Handle /highentropyva
714 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
715 Config->HighEntropyVA = true;
716
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000717 // Handle /entry and /dll
718 if (auto *Arg = Args.getLastArg(OPT_entry)) {
719 Config->Entry = addUndefined(mangle(Arg->getValue()));
720 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000721 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
722 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000723 Config->Entry = addUndefined(S);
724 } else if (!Config->NoEntry) {
725 // Windows specific -- If entry point name is not given, we need to
726 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000727 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000728 if (S.empty())
Rui Ueyama60604792016-07-14 23:37:14 +0000729 fatal("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000730 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000731 if (Config->Verbose)
Rui Ueyama8fe17672016-12-08 20:50:47 +0000732 outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000733 }
734
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000735 // Handle /export
736 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000737 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000738 if (Config->Machine == I386) {
739 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000740 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000741 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000742 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000743 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000744 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000745 }
746
747 // Handle /def
748 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000749 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000750 parseModuleDefs(
751 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
752 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000753 }
754
Rui Ueyama6d249082015-07-13 22:31:45 +0000755 // Handle /delayload
756 for (auto *Arg : Args.filtered(OPT_delayload)) {
757 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000758 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000759 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000760 } else {
761 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000762 }
763 }
764
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000765 // Set default image base if /base is not given.
766 if (Config->ImageBase == uint64_t(-1))
767 Config->ImageBase = getDefaultImageBase();
768
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000769 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000770 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000771 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
772 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
773 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000774
Rui Ueyama107db552015-08-09 21:01:06 +0000775 // We do not support /guard:cf (control flow protection) yet.
776 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
777 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
778 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
779 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
780
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000781 // This code may add new undefined symbols to the link, which may enqueue more
782 // symbol resolution tasks, so we need to continue executing tasks until we
783 // converge.
784 do {
785 // Windows specific -- if entry point is not found,
786 // search for its mangled names.
787 if (Config->Entry)
788 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000789
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000790 // Windows specific -- Make sure we resolve all dllexported symbols.
791 for (Export &E : Config->Exports) {
792 if (!E.ForwardTo.empty())
793 continue;
794 E.Sym = addUndefined(E.Name);
795 if (!E.Directives)
796 Symtab.mangleMaybe(E.Sym);
797 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000798
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000799 // Add weak aliases. Weak aliases is a mechanism to give remaining
800 // undefined symbols final chance to be resolved successfully.
801 for (auto Pair : Config->AlternateNames) {
802 StringRef From = Pair.first;
803 StringRef To = Pair.second;
804 Symbol *Sym = Symtab.find(From);
805 if (!Sym)
806 continue;
807 if (auto *U = dyn_cast<Undefined>(Sym->body()))
808 if (!U->WeakAlias)
809 U->WeakAlias = Symtab.addUndefined(To);
810 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000811
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000812 // Windows specific -- if __load_config_used can be resolved, resolve it.
813 if (Symtab.findUnderscore("_load_config_used"))
814 addUndefined(mangle("_load_config_used"));
815 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000816
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000817 // Do LTO by compiling bitcode input files to a set of native COFF files then
818 // link those files.
819 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000820 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000821
Peter Collingbourne2612a322015-07-04 05:28:41 +0000822 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000823 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000824
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000825 // Windows specific -- if no /subsystem is given, we need to infer
826 // that from entry point name.
827 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000828 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000829 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000830 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000831 }
832
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000833 // Handle /safeseh.
Rui Ueyama13563d82015-09-15 00:33:11 +0000834 if (Args.hasArg(OPT_safeseh))
835 for (ObjectFile *File : Symtab.ObjectFiles)
836 if (!File->SEHCompat)
Rui Ueyama60604792016-07-14 23:37:14 +0000837 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000838
Rui Ueyama151d8622015-06-17 20:40:43 +0000839 // Windows specific -- when we are creating a .dll file, we also
840 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000841 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000842 fixupExports();
843 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000844 assignExportOrdinals();
845 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000846
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000847 // Windows specific -- Create a side-by-side manifest file.
848 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000849 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000850
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000851 // Identify unreferenced COMDAT sections.
852 if (Config->DoGC)
853 markLive(Symtab.getChunks());
854
855 // Identify identical COMDAT sections to merge them.
856 if (Config->DoICF)
857 doICF(Symtab.getChunks());
858
Rui Ueyama411c63602015-05-28 19:09:30 +0000859 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000860 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000861
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000862 // Call exit to avoid calling destructors.
863 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000864}
865
Rui Ueyama411c63602015-05-28 19:09:30 +0000866} // namespace coff
867} // namespace lld