blob: 00686d98487dd6a9e11312228beab6913af401ad [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;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000044using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000045using llvm::sys::fs::file_magic;
46using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000047
Rui Ueyama3500f662015-05-28 20:30:06 +000048namespace lld {
49namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000050
Rui Ueyama3500f662015-05-28 20:30:06 +000051Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000052LinkerDriver *Driver;
53
Rui Ueyama9381eb12016-12-18 14:06:06 +000054BumpPtrAllocator BAlloc;
55StringSaver Saver{BAlloc};
56std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
57
Bob Haarman6c8f7362017-01-17 19:07:42 +000058bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
59 ErrorCount = 0;
60 ErrorOS = &Diag;
61 Argv0 = Args[0];
Rui Ueyama7fed58c2016-12-08 19:10:28 +000062 Config = make<Configuration>();
Bob Haarman6c8f7362017-01-17 19:07:42 +000063 Config->ColorDiagnostics =
64 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
Rui Ueyama7fed58c2016-12-08 19:10:28 +000065 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000066 Driver->link(Args);
67 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000068}
Rui Ueyama411c63602015-05-28 19:09:30 +000069
Nico Weber5660de72016-04-20 22:34:15 +000070// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000071static std::string getOutputPath(StringRef Path) {
72 auto P = Path.find_last_of("\\/");
73 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000074 const char* E = Config->DLL ? ".dll" : ".exe";
75 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000076}
77
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000078// ErrorOr is not default constructible, so it cannot be used as the type
79// parameter of a future.
80// FIXME: We could open the file in createFutureForFile and avoid needing to
81// return an error here, but for the moment that would cost us a file descriptor
82// (a limited resource on Windows) for the duration that the future is pending.
83typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
84
85// Create a std::future that opens and maps a file using the best strategy for
86// the host platform.
87static std::future<MBErrPair> createFutureForFile(std::string Path) {
88#if LLVM_ON_WIN32
89 // On Windows, file I/O is relatively slow so it is best to do this
90 // asynchronously.
91 auto Strategy = std::launch::async;
92#else
93 auto Strategy = std::launch::deferred;
94#endif
95 return std::async(Strategy, [=]() {
96 auto MBOrErr = MemoryBuffer::getFile(Path);
97 if (!MBOrErr)
98 return MBErrPair{nullptr, MBOrErr.getError()};
99 return MBErrPair{std::move(*MBOrErr), std::error_code()};
100 });
101}
102
103MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
104 MemoryBufferRef MBRef = *MB;
105 OwningMBs.push_back(std::move(MB));
106
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000107 if (Driver->Tar)
108 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109 MBRef.getBuffer());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000110
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000111 return MBRef;
112}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000113
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000114void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
115 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000116
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000117 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000118 file_magic Magic = identify_magic(MBRef.getBuffer());
119 if (Magic == file_magic::windows_resource) {
120 Resources.push_back(MBRef);
121 return;
122 }
123
124 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000125 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000126 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000127 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000128 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000129 if (Magic == file_magic::coff_cl_gl_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000130 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000131 "Recompile without /GL");
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000132 Symtab.addFile(make<ObjectFile>(MBRef));
133}
134
135void LinkerDriver::enqueuePath(StringRef Path) {
136 auto Future =
137 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
138 std::string PathStr = Path;
139 enqueueTask([=]() {
140 auto MBOrErr = Future->get();
141 if (MBOrErr.second)
142 fatal(MBOrErr.second, "could not open " + PathStr);
143 Driver->addBuffer(std::move(MBOrErr.first));
144 });
145
Rui Ueyamaad660982015-06-07 00:20:32 +0000146 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000147 Config->OutputFile = getOutputPath(Path);
148}
149
150void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
151 StringRef ParentName) {
152 file_magic Magic = identify_magic(MB.getBuffer());
153 if (Magic == file_magic::coff_import_library) {
154 Symtab.addFile(make<ImportFile>(MB));
155 return;
156 }
157
158 InputFile *Obj;
159 if (Magic == file_magic::coff_object)
160 Obj = make<ObjectFile>(MB);
161 else if (Magic == file_magic::bitcode)
162 Obj = make<BitcodeFile>(MB);
163 else
164 fatal("unknown file type: " + MB.getBufferIdentifier());
165
166 Obj->ParentName = ParentName;
167 Symtab.addFile(Obj);
168 if (Config->Verbose)
169 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
170}
171
172void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
173 StringRef SymName,
174 StringRef ParentName) {
175 if (!C.getParent()->isThin()) {
176 MemoryBufferRef MB = check(
177 C.getMemoryBufferRef(),
178 "could not get the buffer for the member defining symbol " + SymName);
179 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
180 return;
181 }
182
183 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
184 check(C.getFullName(),
185 "could not get the filename for the member defining symbol " +
186 SymName)));
187 enqueueTask([=]() {
188 auto MBOrErr = Future->get();
189 if (MBOrErr.second)
190 fatal(MBOrErr.second,
191 "could not get the buffer for the member defining " + SymName);
192 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
193 ParentName);
194 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000195}
196
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000197static bool isDecorated(StringRef Sym) {
198 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
199}
200
Rui Ueyama411c63602015-05-28 19:09:30 +0000201// Parses .drectve section contents and returns a list of files
202// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000203void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000204 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000205
David Blaikie6521ed92015-06-22 22:06:52 +0000206 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000207 switch (Arg->getOption().getID()) {
208 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000209 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000210 break;
211 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000212 if (Optional<StringRef> Path = findLib(Arg->getValue()))
213 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000214 break;
215 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000216 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000217 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000218 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000219 break;
220 }
221 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000222 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000223 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000224 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000225 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000226 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000227 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000228 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000229 break;
230 case OPT_nodefaultlib:
231 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
232 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000233 case OPT_section:
234 parseSection(Arg->getValue());
235 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000236 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000237 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000238 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000239 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000240 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000241 default:
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000242 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000243 }
244 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000245}
246
Rui Ueyama54b71da2015-05-31 19:17:12 +0000247// Find file from search paths. You can omit ".obj", this function takes
248// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000249StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000250 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
251 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000252 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000253 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000254 for (StringRef Dir : SearchPaths) {
255 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000256 sys::path::append(Path, Filename);
257 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000258 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000259 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000260 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000261 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000262 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000263 }
264 }
265 return Filename;
266}
267
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000268// Resolves a file path. This never returns the same path
269// (in that case, it returns None).
270Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
271 StringRef Path = doFindFile(Filename);
272 bool Seen = !VisitedFiles.insert(Path.lower()).second;
273 if (Seen)
274 return None;
275 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000276}
277
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000278// Find library file from search path.
279StringRef LinkerDriver::doFindLib(StringRef Filename) {
280 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000281 bool HasExt = (Filename.find('.') != StringRef::npos);
282 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000283 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000284 return doFindFile(Filename);
285}
286
287// Resolves a library path. /nodefaultlib options are taken into
288// consideration. This never returns the same path (in that case,
289// it returns None).
290Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
291 if (Config->NoDefaultLibAll)
292 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000293 if (!VisitedLibs.insert(Filename.lower()).second)
294 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000295 StringRef Path = doFindLib(Filename);
296 if (Config->NoDefaultLibs.count(Path))
297 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000298 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000299 return None;
300 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000301}
302
303// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000304void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000305 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
306 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000307 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000308 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000309 while (!Env.empty()) {
310 StringRef Path;
311 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000312 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000313 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000314}
315
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000316SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
317 SymbolBody *B = Symtab.addUndefined(Name);
318 Config->GCRoot.insert(B);
319 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000320}
321
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000322// Symbol names are mangled by appending "_" prefix on x86.
323StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000324 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
325 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000326 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000327 return Sym;
328}
329
Rui Ueyama45044f42015-06-29 01:03:53 +0000330// Windows specific -- find default entry point name.
331StringRef LinkerDriver::findDefaultEntry() {
332 // User-defined main functions and their corresponding entry points.
333 static const char *Entries[][2] = {
334 {"main", "mainCRTStartup"},
335 {"wmain", "wmainCRTStartup"},
336 {"WinMain", "WinMainCRTStartup"},
337 {"wWinMain", "wWinMainCRTStartup"},
338 };
339 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000340 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000341 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000342 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000343 }
344 return "";
345}
346
347WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000348 if (Config->DLL)
349 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000350 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000351 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000352 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000353 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
354 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000355}
356
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000357static uint64_t getDefaultImageBase() {
358 if (Config->is64())
359 return Config->DLL ? 0x180000000 : 0x140000000;
360 return Config->DLL ? 0x10000000 : 0x400000;
361}
362
Rui Ueyama8fe17672016-12-08 20:50:47 +0000363static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000364 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000365 ArrayRef<StringRef> SearchPaths) {
366 SmallString<0> Data;
367 raw_svector_ostream OS(Data);
368
369 for (auto *Arg : Args) {
370 switch (Arg->getOption().getID()) {
371 case OPT_linkrepro:
372 case OPT_INPUT:
373 case OPT_defaultlib:
374 case OPT_libpath:
375 break;
376 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000377 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000378 }
379 }
380
381 for (StringRef Path : SearchPaths) {
382 std::string RelPath = relativeToRoot(Path);
383 OS << "/libpath:" << quote(RelPath) << "\n";
384 }
385
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000386 for (StringRef Path : FilePaths)
387 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000388
389 return Data.str();
390}
391
Rui Ueyama8fe17672016-12-08 20:50:47 +0000392static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000393 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
394 if (Args.hasArg(OPT_driver))
395 DebugTypes |= static_cast<unsigned>(DebugType::PData);
396 if (Args.hasArg(OPT_profile))
397 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
398 return DebugTypes;
399}
400
401static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000402 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000403 Arg.split(Types, ',', /*KeepEmpty=*/false);
404
405 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
406 for (StringRef Type : Types)
407 DebugTypes |= StringSwitch<unsigned>(Type.lower())
408 .Case("cv", static_cast<unsigned>(DebugType::CV))
409 .Case("pdata", static_cast<unsigned>(DebugType::PData))
410 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
411 return DebugTypes;
412}
413
Hans Wennborg1818e652016-12-09 20:54:44 +0000414static std::string getMapFile(const opt::InputArgList &Args) {
415 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
416 if (!Arg)
417 return "";
418 if (Arg->getOption().getID() == OPT_lldmap_file)
419 return Arg->getValue();
420
421 assert(Arg->getOption().getID() == OPT_lldmap);
422 StringRef OutFile = Config->OutputFile;
423 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
424}
425
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000426void LinkerDriver::enqueueTask(std::function<void()> Task) {
427 TaskQueue.push_back(std::move(Task));
428}
429
430bool LinkerDriver::run() {
431 bool DidWork = !TaskQueue.empty();
432 while (!TaskQueue.empty()) {
433 TaskQueue.front()();
434 TaskQueue.pop_front();
435 }
436 return DidWork;
437}
438
Rui Ueyama8fe17672016-12-08 20:50:47 +0000439void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000440 // If the first command line argument is "/lib", link.exe acts like lib.exe.
441 // We call our own implementation of lib.exe that understands bitcode files.
442 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
443 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000444 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000445 return;
446 }
447
Peter Collingbourne60c16162015-06-01 20:10:10 +0000448 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000449 InitializeAllTargetInfos();
450 InitializeAllTargets();
451 InitializeAllTargetMCs();
452 InitializeAllAsmParsers();
453 InitializeAllAsmPrinters();
454 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000455
Rui Ueyama411c63602015-05-28 19:09:30 +0000456 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000457 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000458
Rui Ueyama5c726432015-05-29 16:11:52 +0000459 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000460 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000461 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000462 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000463 }
464
Peter Collingbournefeee2102016-07-26 02:00:42 +0000465 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
466 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000467 sys::path::append(Path, "repro.tar");
468
469 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
470 TarWriter::create(Path, "repro");
471
472 if (ErrOrWriter) {
473 Tar = std::move(*ErrOrWriter);
474 } else {
475 errs() << "/linkrepro: failed to open " << Path << ": "
476 << toString(ErrOrWriter.takeError()) << '\n';
477 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000478 }
479
Rafael Espindolab835ae82015-08-06 14:58:50 +0000480 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000481 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000482
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000483 // Construct search path list.
484 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000485 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000486 SearchPaths.push_back(Arg->getValue());
487 addLibSearchPaths();
488
Rui Ueyamaad660982015-06-07 00:20:32 +0000489 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000490 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000491 Config->OutputFile = Arg->getValue();
492
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000493 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000494 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000495 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000496
Rui Ueyama95925fd2015-06-28 19:35:15 +0000497 // Handle /force or /force:unresolved
498 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
499 Config->Force = true;
500
Rui Ueyama6600eb12015-07-04 23:37:32 +0000501 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000502 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000503 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000504 Config->DebugTypes =
505 Args.hasArg(OPT_debugtype)
506 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
507 : getDefaultDebugType(Args);
508 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000509
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000510 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000511 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000512 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000513
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000514 // Handle /noentry
515 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000516 if (!Args.hasArg(OPT_dll))
Rui Ueyama60604792016-07-14 23:37:14 +0000517 fatal("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000518 Config->NoEntry = true;
519 }
520
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000521 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000522 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000523 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000524 Config->ManifestID = 2;
525 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000526
Rui Ueyama588e8322015-06-15 01:23:58 +0000527 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000528 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000529 if (Args.hasArg(OPT_dynamicbase))
Rui Ueyama60604792016-07-14 23:37:14 +0000530 fatal("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000531 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000532 Config->DynamicBase = false;
533 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000534
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000535 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000536 if (auto *Arg = Args.getLastArg(OPT_machine))
537 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000538
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000539 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000540 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000541 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
542
543 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000544 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000545 Config->NoDefaultLibAll = true;
546
Rui Ueyama804a8b62015-05-29 16:18:15 +0000547 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000548 if (auto *Arg = Args.getLastArg(OPT_base))
549 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000550
551 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000552 if (auto *Arg = Args.getLastArg(OPT_stack))
553 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000554
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000555 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000556 if (auto *Arg = Args.getLastArg(OPT_heap))
557 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000558
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000559 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000560 if (auto *Arg = Args.getLastArg(OPT_version))
561 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
562 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000563
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000564 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000565 if (auto *Arg = Args.getLastArg(OPT_subsystem))
566 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
567 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000568
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000569 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000570 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000571 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000572
Rui Ueyama08d5e182015-06-18 23:20:11 +0000573 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000574 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000575 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000576
Rui Ueyamab95188c2015-06-18 20:27:09 +0000577 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000578 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000579 Config->Implib = Arg->getValue();
580
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000581 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000582 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000583 std::string Str = StringRef(Arg->getValue()).lower();
584 SmallVector<StringRef, 1> Vec;
585 StringRef(Str).split(Vec, ',');
586 for (StringRef S : Vec) {
587 if (S == "noref") {
588 Config->DoGC = false;
589 Config->DoICF = false;
590 continue;
591 }
592 if (S == "icf" || StringRef(S).startswith("icf=")) {
593 Config->DoICF = true;
594 continue;
595 }
596 if (S == "noicf") {
597 Config->DoICF = false;
598 continue;
599 }
600 if (StringRef(S).startswith("lldlto=")) {
601 StringRef OptLevel = StringRef(S).substr(7);
602 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
603 Config->LTOOptLevel > 3)
Rui Ueyama60604792016-07-14 23:37:14 +0000604 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000605 continue;
606 }
607 if (StringRef(S).startswith("lldltojobs=")) {
608 StringRef Jobs = StringRef(S).substr(11);
609 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000610 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000611 continue;
612 }
613 if (S != "ref" && S != "lbr" && S != "nolbr")
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000614 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000615 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000616 }
617
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000618 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000619 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000620 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000621
Rui Ueyama6600eb12015-07-04 23:37:32 +0000622 // Handle /merge
623 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000624 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000625
Rui Ueyama440138c2016-06-20 03:39:39 +0000626 // Handle /section
627 for (auto *Arg : Args.filtered(OPT_section))
628 parseSection(Arg->getValue());
629
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000630 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000631 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
632 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000633
634 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000635 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
636 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000637
638 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000639 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000640 Config->ManifestDependency = Arg->getValue();
641
642 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000643 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000644 Config->ManifestFile = Arg->getValue();
645
Rui Ueyamaafb19012016-04-19 01:21:58 +0000646 // Handle /manifestinput
647 for (auto *Arg : Args.filtered(OPT_manifestinput))
648 Config->ManifestInput.push_back(Arg->getValue());
649
Rui Ueyama6592ff82015-06-16 23:13:00 +0000650 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000651 if (Args.hasArg(OPT_allowbind_no))
652 Config->AllowBind = false;
653 if (Args.hasArg(OPT_allowisolation_no))
654 Config->AllowIsolation = false;
655 if (Args.hasArg(OPT_dynamicbase_no))
656 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000657 if (Args.hasArg(OPT_nxcompat_no))
658 Config->NxCompat = false;
659 if (Args.hasArg(OPT_tsaware_no))
660 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000661 if (Args.hasArg(OPT_nosymtab))
662 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000663 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000664 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000665
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000666 Config->MapFile = getMapFile(Args);
667
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000668 // Create a list of input files. Files can be given as arguments
669 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000670 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000671 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000672 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000673 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000674 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000675 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000676 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000677
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000678 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000679 if (Config->Manifest == Configuration::Embed)
680 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000681
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000682 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000683 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000684
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000685 // We should have inferred a machine type by now from the input files, but if
686 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000687 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000688 errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000689 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000690 }
691
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000692 // Windows specific -- Input files can be Windows resource files (.res files).
693 // We invoke cvtres.exe to convert resource files to a regular COFF file
694 // then link the result file normally.
695 if (!Resources.empty())
696 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000697
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000698 if (Tar)
699 Tar->append("response.txt",
700 createResponseFile(Args, FilePaths,
701 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000702
Rui Ueyama4d545342015-07-28 03:12:00 +0000703 // Handle /largeaddressaware
704 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
705 Config->LargeAddressAware = true;
706
Rui Ueyamad68e2112015-07-28 03:15:57 +0000707 // Handle /highentropyva
708 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
709 Config->HighEntropyVA = true;
710
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000711 // Handle /entry and /dll
712 if (auto *Arg = Args.getLastArg(OPT_entry)) {
713 Config->Entry = addUndefined(mangle(Arg->getValue()));
714 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000715 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
716 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000717 Config->Entry = addUndefined(S);
718 } else if (!Config->NoEntry) {
719 // Windows specific -- If entry point name is not given, we need to
720 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000721 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000722 if (S.empty())
Rui Ueyama60604792016-07-14 23:37:14 +0000723 fatal("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000724 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000725 if (Config->Verbose)
Rui Ueyama8fe17672016-12-08 20:50:47 +0000726 outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000727 }
728
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000729 // Handle /export
730 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000731 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000732 if (Config->Machine == I386) {
733 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000734 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000735 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000736 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000737 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000738 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000739 }
740
741 // Handle /def
742 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000743 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000744 parseModuleDefs(
745 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
746 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000747 }
748
Rui Ueyama6d249082015-07-13 22:31:45 +0000749 // Handle /delayload
750 for (auto *Arg : Args.filtered(OPT_delayload)) {
751 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000752 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000753 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000754 } else {
755 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000756 }
757 }
758
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000759 // Set default image base if /base is not given.
760 if (Config->ImageBase == uint64_t(-1))
761 Config->ImageBase = getDefaultImageBase();
762
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000763 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000764 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000765 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
766 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
767 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000768
Rui Ueyama107db552015-08-09 21:01:06 +0000769 // We do not support /guard:cf (control flow protection) yet.
770 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
771 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
772 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
773 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
774
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000775 // This code may add new undefined symbols to the link, which may enqueue more
776 // symbol resolution tasks, so we need to continue executing tasks until we
777 // converge.
778 do {
779 // Windows specific -- if entry point is not found,
780 // search for its mangled names.
781 if (Config->Entry)
782 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000783
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000784 // Windows specific -- Make sure we resolve all dllexported symbols.
785 for (Export &E : Config->Exports) {
786 if (!E.ForwardTo.empty())
787 continue;
788 E.Sym = addUndefined(E.Name);
789 if (!E.Directives)
790 Symtab.mangleMaybe(E.Sym);
791 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000792
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000793 // Add weak aliases. Weak aliases is a mechanism to give remaining
794 // undefined symbols final chance to be resolved successfully.
795 for (auto Pair : Config->AlternateNames) {
796 StringRef From = Pair.first;
797 StringRef To = Pair.second;
798 Symbol *Sym = Symtab.find(From);
799 if (!Sym)
800 continue;
801 if (auto *U = dyn_cast<Undefined>(Sym->body()))
802 if (!U->WeakAlias)
803 U->WeakAlias = Symtab.addUndefined(To);
804 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000805
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000806 // Windows specific -- if __load_config_used can be resolved, resolve it.
807 if (Symtab.findUnderscore("_load_config_used"))
808 addUndefined(mangle("_load_config_used"));
809 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000810
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000811 // Do LTO by compiling bitcode input files to a set of native COFF files then
812 // link those files.
813 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000814 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000815
Peter Collingbourne2612a322015-07-04 05:28:41 +0000816 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000817 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000818
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000819 // Windows specific -- if no /subsystem is given, we need to infer
820 // that from entry point name.
821 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000822 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000823 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000824 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000825 }
826
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000827 // Handle /safeseh.
Rui Ueyama13563d82015-09-15 00:33:11 +0000828 if (Args.hasArg(OPT_safeseh))
829 for (ObjectFile *File : Symtab.ObjectFiles)
830 if (!File->SEHCompat)
Rui Ueyama60604792016-07-14 23:37:14 +0000831 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000832
Rui Ueyama151d8622015-06-17 20:40:43 +0000833 // Windows specific -- when we are creating a .dll file, we also
834 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000835 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000836 fixupExports();
837 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000838 assignExportOrdinals();
839 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000840
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000841 // Windows specific -- Create a side-by-side manifest file.
842 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000843 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000844
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000845 // Identify unreferenced COMDAT sections.
846 if (Config->DoGC)
847 markLive(Symtab.getChunks());
848
849 // Identify identical COMDAT sections to merge them.
850 if (Config->DoICF)
851 doICF(Symtab.getChunks());
852
Rui Ueyama411c63602015-05-28 19:09:30 +0000853 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000854 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000855
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000856 // Call exit to avoid calling destructors.
857 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000858}
859
Rui Ueyama411c63602015-05-28 19:09:30 +0000860} // namespace coff
861} // namespace lld