blob: 4dabd9ebcc6d3217cffe1f6975610423a63ff2de [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
Rui Ueyama8fe17672016-12-08 20:50:47 +000058bool link(ArrayRef<const char *> Args) {
Rui Ueyama7fed58c2016-12-08 19:10:28 +000059 Config = make<Configuration>();
60 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000061 Driver->link(Args);
62 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000063}
Rui Ueyama411c63602015-05-28 19:09:30 +000064
Nico Weber5660de72016-04-20 22:34:15 +000065// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000066static std::string getOutputPath(StringRef Path) {
67 auto P = Path.find_last_of("\\/");
68 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000069 const char* E = Config->DLL ? ".dll" : ".exe";
70 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000071}
72
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000073// ErrorOr is not default constructible, so it cannot be used as the type
74// parameter of a future.
75// FIXME: We could open the file in createFutureForFile and avoid needing to
76// return an error here, but for the moment that would cost us a file descriptor
77// (a limited resource on Windows) for the duration that the future is pending.
78typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
79
80// Create a std::future that opens and maps a file using the best strategy for
81// the host platform.
82static std::future<MBErrPair> createFutureForFile(std::string Path) {
83#if LLVM_ON_WIN32
84 // On Windows, file I/O is relatively slow so it is best to do this
85 // asynchronously.
86 auto Strategy = std::launch::async;
87#else
88 auto Strategy = std::launch::deferred;
89#endif
90 return std::async(Strategy, [=]() {
91 auto MBOrErr = MemoryBuffer::getFile(Path);
92 if (!MBOrErr)
93 return MBErrPair{nullptr, MBOrErr.getError()};
94 return MBErrPair{std::move(*MBOrErr), std::error_code()};
95 });
96}
97
98MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
99 MemoryBufferRef MBRef = *MB;
100 OwningMBs.push_back(std::move(MB));
101
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000102 if (Driver->Tar)
103 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
104 MBRef.getBuffer());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000105
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000106 return MBRef;
107}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000108
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000109void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
110 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000111
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000112 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000113 file_magic Magic = identify_magic(MBRef.getBuffer());
114 if (Magic == file_magic::windows_resource) {
115 Resources.push_back(MBRef);
116 return;
117 }
118
119 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000120 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000121 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000122 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000123 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000124 if (Magic == file_magic::coff_cl_gl_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000125 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000126 "Recompile without /GL");
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000127 Symtab.addFile(make<ObjectFile>(MBRef));
128}
129
130void LinkerDriver::enqueuePath(StringRef Path) {
131 auto Future =
132 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
133 std::string PathStr = Path;
134 enqueueTask([=]() {
135 auto MBOrErr = Future->get();
136 if (MBOrErr.second)
137 fatal(MBOrErr.second, "could not open " + PathStr);
138 Driver->addBuffer(std::move(MBOrErr.first));
139 });
140
Rui Ueyamaad660982015-06-07 00:20:32 +0000141 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000142 Config->OutputFile = getOutputPath(Path);
143}
144
145void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
146 StringRef ParentName) {
147 file_magic Magic = identify_magic(MB.getBuffer());
148 if (Magic == file_magic::coff_import_library) {
149 Symtab.addFile(make<ImportFile>(MB));
150 return;
151 }
152
153 InputFile *Obj;
154 if (Magic == file_magic::coff_object)
155 Obj = make<ObjectFile>(MB);
156 else if (Magic == file_magic::bitcode)
157 Obj = make<BitcodeFile>(MB);
158 else
159 fatal("unknown file type: " + MB.getBufferIdentifier());
160
161 Obj->ParentName = ParentName;
162 Symtab.addFile(Obj);
163 if (Config->Verbose)
164 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
165}
166
167void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
168 StringRef SymName,
169 StringRef ParentName) {
170 if (!C.getParent()->isThin()) {
171 MemoryBufferRef MB = check(
172 C.getMemoryBufferRef(),
173 "could not get the buffer for the member defining symbol " + SymName);
174 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
175 return;
176 }
177
178 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
179 check(C.getFullName(),
180 "could not get the filename for the member defining symbol " +
181 SymName)));
182 enqueueTask([=]() {
183 auto MBOrErr = Future->get();
184 if (MBOrErr.second)
185 fatal(MBOrErr.second,
186 "could not get the buffer for the member defining " + SymName);
187 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
188 ParentName);
189 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000190}
191
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000192static bool isDecorated(StringRef Sym) {
193 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
194}
195
Rui Ueyama411c63602015-05-28 19:09:30 +0000196// Parses .drectve section contents and returns a list of files
197// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000198void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000199 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000200
David Blaikie6521ed92015-06-22 22:06:52 +0000201 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000202 switch (Arg->getOption().getID()) {
203 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000204 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000205 break;
206 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000207 if (Optional<StringRef> Path = findLib(Arg->getValue()))
208 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000209 break;
210 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000211 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000212 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000213 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000214 break;
215 }
216 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000217 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000218 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000219 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000220 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000221 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000222 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000223 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000224 break;
225 case OPT_nodefaultlib:
226 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
227 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000228 case OPT_section:
229 parseSection(Arg->getValue());
230 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000231 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000232 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000233 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000234 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000235 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000236 default:
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000237 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000238 }
239 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000240}
241
Rui Ueyama54b71da2015-05-31 19:17:12 +0000242// Find file from search paths. You can omit ".obj", this function takes
243// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000244StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000245 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
246 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000247 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000248 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000249 for (StringRef Dir : SearchPaths) {
250 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000251 sys::path::append(Path, Filename);
252 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000253 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000254 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000255 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000256 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000257 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000258 }
259 }
260 return Filename;
261}
262
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000263// Resolves a file path. This never returns the same path
264// (in that case, it returns None).
265Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
266 StringRef Path = doFindFile(Filename);
267 bool Seen = !VisitedFiles.insert(Path.lower()).second;
268 if (Seen)
269 return None;
270 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000271}
272
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000273// Find library file from search path.
274StringRef LinkerDriver::doFindLib(StringRef Filename) {
275 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000276 bool HasExt = (Filename.find('.') != StringRef::npos);
277 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000278 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000279 return doFindFile(Filename);
280}
281
282// Resolves a library path. /nodefaultlib options are taken into
283// consideration. This never returns the same path (in that case,
284// it returns None).
285Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
286 if (Config->NoDefaultLibAll)
287 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000288 if (!VisitedLibs.insert(Filename.lower()).second)
289 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000290 StringRef Path = doFindLib(Filename);
291 if (Config->NoDefaultLibs.count(Path))
292 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000293 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000294 return None;
295 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000296}
297
298// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000299void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000300 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
301 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000302 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000303 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000304 while (!Env.empty()) {
305 StringRef Path;
306 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000307 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000308 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000309}
310
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000311SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
312 SymbolBody *B = Symtab.addUndefined(Name);
313 Config->GCRoot.insert(B);
314 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000315}
316
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000317// Symbol names are mangled by appending "_" prefix on x86.
318StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000319 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
320 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000321 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000322 return Sym;
323}
324
Rui Ueyama45044f42015-06-29 01:03:53 +0000325// Windows specific -- find default entry point name.
326StringRef LinkerDriver::findDefaultEntry() {
327 // User-defined main functions and their corresponding entry points.
328 static const char *Entries[][2] = {
329 {"main", "mainCRTStartup"},
330 {"wmain", "wmainCRTStartup"},
331 {"WinMain", "WinMainCRTStartup"},
332 {"wWinMain", "wWinMainCRTStartup"},
333 };
334 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000335 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000336 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000337 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000338 }
339 return "";
340}
341
342WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000343 if (Config->DLL)
344 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000345 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000346 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000347 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000348 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
349 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000350}
351
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000352static uint64_t getDefaultImageBase() {
353 if (Config->is64())
354 return Config->DLL ? 0x180000000 : 0x140000000;
355 return Config->DLL ? 0x10000000 : 0x400000;
356}
357
Rui Ueyama8fe17672016-12-08 20:50:47 +0000358static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000359 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000360 ArrayRef<StringRef> SearchPaths) {
361 SmallString<0> Data;
362 raw_svector_ostream OS(Data);
363
364 for (auto *Arg : Args) {
365 switch (Arg->getOption().getID()) {
366 case OPT_linkrepro:
367 case OPT_INPUT:
368 case OPT_defaultlib:
369 case OPT_libpath:
370 break;
371 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000372 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000373 }
374 }
375
376 for (StringRef Path : SearchPaths) {
377 std::string RelPath = relativeToRoot(Path);
378 OS << "/libpath:" << quote(RelPath) << "\n";
379 }
380
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000381 for (StringRef Path : FilePaths)
382 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000383
384 return Data.str();
385}
386
Rui Ueyama8fe17672016-12-08 20:50:47 +0000387static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000388 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
389 if (Args.hasArg(OPT_driver))
390 DebugTypes |= static_cast<unsigned>(DebugType::PData);
391 if (Args.hasArg(OPT_profile))
392 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
393 return DebugTypes;
394}
395
396static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000397 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000398 Arg.split(Types, ',', /*KeepEmpty=*/false);
399
400 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
401 for (StringRef Type : Types)
402 DebugTypes |= StringSwitch<unsigned>(Type.lower())
403 .Case("cv", static_cast<unsigned>(DebugType::CV))
404 .Case("pdata", static_cast<unsigned>(DebugType::PData))
405 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
406 return DebugTypes;
407}
408
Hans Wennborg1818e652016-12-09 20:54:44 +0000409static std::string getMapFile(const opt::InputArgList &Args) {
410 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
411 if (!Arg)
412 return "";
413 if (Arg->getOption().getID() == OPT_lldmap_file)
414 return Arg->getValue();
415
416 assert(Arg->getOption().getID() == OPT_lldmap);
417 StringRef OutFile = Config->OutputFile;
418 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
419}
420
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000421void LinkerDriver::enqueueTask(std::function<void()> Task) {
422 TaskQueue.push_back(std::move(Task));
423}
424
425bool LinkerDriver::run() {
426 bool DidWork = !TaskQueue.empty();
427 while (!TaskQueue.empty()) {
428 TaskQueue.front()();
429 TaskQueue.pop_front();
430 }
431 return DidWork;
432}
433
Rui Ueyama8fe17672016-12-08 20:50:47 +0000434void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000435 // If the first command line argument is "/lib", link.exe acts like lib.exe.
436 // We call our own implementation of lib.exe that understands bitcode files.
437 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
438 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000439 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000440 return;
441 }
442
Peter Collingbourne60c16162015-06-01 20:10:10 +0000443 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000444 InitializeAllTargetInfos();
445 InitializeAllTargets();
446 InitializeAllTargetMCs();
447 InitializeAllAsmParsers();
448 InitializeAllAsmPrinters();
449 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000450
Rui Ueyama411c63602015-05-28 19:09:30 +0000451 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000452 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000453
Rui Ueyama5c726432015-05-29 16:11:52 +0000454 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000455 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000456 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000457 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000458 }
459
Peter Collingbournefeee2102016-07-26 02:00:42 +0000460 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
461 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000462 sys::path::append(Path, "repro.tar");
463
464 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
465 TarWriter::create(Path, "repro");
466
467 if (ErrOrWriter) {
468 Tar = std::move(*ErrOrWriter);
469 } else {
470 errs() << "/linkrepro: failed to open " << Path << ": "
471 << toString(ErrOrWriter.takeError()) << '\n';
472 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000473 }
474
Rafael Espindolab835ae82015-08-06 14:58:50 +0000475 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000476 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000477
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000478 // Construct search path list.
479 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000480 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000481 SearchPaths.push_back(Arg->getValue());
482 addLibSearchPaths();
483
Rui Ueyamaad660982015-06-07 00:20:32 +0000484 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000485 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000486 Config->OutputFile = Arg->getValue();
487
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000488 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000489 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000490 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000491
Rui Ueyama95925fd2015-06-28 19:35:15 +0000492 // Handle /force or /force:unresolved
493 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
494 Config->Force = true;
495
Rui Ueyama6600eb12015-07-04 23:37:32 +0000496 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000497 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000498 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000499 Config->DebugTypes =
500 Args.hasArg(OPT_debugtype)
501 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
502 : getDefaultDebugType(Args);
503 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000504
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000505 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000506 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000507 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000508
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000509 // Handle /noentry
510 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000511 if (!Args.hasArg(OPT_dll))
Rui Ueyama60604792016-07-14 23:37:14 +0000512 fatal("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000513 Config->NoEntry = true;
514 }
515
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000516 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000517 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000518 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000519 Config->ManifestID = 2;
520 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000521
Rui Ueyama588e8322015-06-15 01:23:58 +0000522 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000523 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000524 if (Args.hasArg(OPT_dynamicbase))
Rui Ueyama60604792016-07-14 23:37:14 +0000525 fatal("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000526 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000527 Config->DynamicBase = false;
528 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000529
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000530 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000531 if (auto *Arg = Args.getLastArg(OPT_machine))
532 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000533
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000534 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000535 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000536 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
537
538 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000539 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000540 Config->NoDefaultLibAll = true;
541
Rui Ueyama804a8b62015-05-29 16:18:15 +0000542 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000543 if (auto *Arg = Args.getLastArg(OPT_base))
544 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000545
546 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000547 if (auto *Arg = Args.getLastArg(OPT_stack))
548 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000549
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000550 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000551 if (auto *Arg = Args.getLastArg(OPT_heap))
552 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000553
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000554 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000555 if (auto *Arg = Args.getLastArg(OPT_version))
556 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
557 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000558
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000559 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000560 if (auto *Arg = Args.getLastArg(OPT_subsystem))
561 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
562 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000563
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000564 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000565 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000566 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000567
Rui Ueyama08d5e182015-06-18 23:20:11 +0000568 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000569 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000570 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000571
Rui Ueyamab95188c2015-06-18 20:27:09 +0000572 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000573 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000574 Config->Implib = Arg->getValue();
575
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000576 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000577 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000578 std::string Str = StringRef(Arg->getValue()).lower();
579 SmallVector<StringRef, 1> Vec;
580 StringRef(Str).split(Vec, ',');
581 for (StringRef S : Vec) {
582 if (S == "noref") {
583 Config->DoGC = false;
584 Config->DoICF = false;
585 continue;
586 }
587 if (S == "icf" || StringRef(S).startswith("icf=")) {
588 Config->DoICF = true;
589 continue;
590 }
591 if (S == "noicf") {
592 Config->DoICF = false;
593 continue;
594 }
595 if (StringRef(S).startswith("lldlto=")) {
596 StringRef OptLevel = StringRef(S).substr(7);
597 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
598 Config->LTOOptLevel > 3)
Rui Ueyama60604792016-07-14 23:37:14 +0000599 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000600 continue;
601 }
602 if (StringRef(S).startswith("lldltojobs=")) {
603 StringRef Jobs = StringRef(S).substr(11);
604 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000605 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000606 continue;
607 }
608 if (S != "ref" && S != "lbr" && S != "nolbr")
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000609 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000610 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000611 }
612
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000613 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000614 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000615 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000616
Rui Ueyama6600eb12015-07-04 23:37:32 +0000617 // Handle /merge
618 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000619 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000620
Rui Ueyama440138c2016-06-20 03:39:39 +0000621 // Handle /section
622 for (auto *Arg : Args.filtered(OPT_section))
623 parseSection(Arg->getValue());
624
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000625 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000626 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
627 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000628
629 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000630 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
631 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000632
633 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000634 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000635 Config->ManifestDependency = Arg->getValue();
636
637 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000638 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000639 Config->ManifestFile = Arg->getValue();
640
Rui Ueyamaafb19012016-04-19 01:21:58 +0000641 // Handle /manifestinput
642 for (auto *Arg : Args.filtered(OPT_manifestinput))
643 Config->ManifestInput.push_back(Arg->getValue());
644
Rui Ueyama6592ff82015-06-16 23:13:00 +0000645 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000646 if (Args.hasArg(OPT_allowbind_no))
647 Config->AllowBind = false;
648 if (Args.hasArg(OPT_allowisolation_no))
649 Config->AllowIsolation = false;
650 if (Args.hasArg(OPT_dynamicbase_no))
651 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000652 if (Args.hasArg(OPT_nxcompat_no))
653 Config->NxCompat = false;
654 if (Args.hasArg(OPT_tsaware_no))
655 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000656 if (Args.hasArg(OPT_nosymtab))
657 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000658 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000659 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000660
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000661 // Create a list of input files. Files can be given as arguments
662 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000663 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000664 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000665 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000666 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000667 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000668 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000669 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000670
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000671 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000672 if (Config->Manifest == Configuration::Embed)
673 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000674
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000675 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000676 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000677
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000678 // We should have inferred a machine type by now from the input files, but if
679 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000680 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000681 errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000682 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000683 }
684
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000685 // Windows specific -- Input files can be Windows resource files (.res files).
686 // We invoke cvtres.exe to convert resource files to a regular COFF file
687 // then link the result file normally.
688 if (!Resources.empty())
689 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000690
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000691 if (Tar)
692 Tar->append("response.txt",
693 createResponseFile(Args, FilePaths,
694 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000695
Rui Ueyama4d545342015-07-28 03:12:00 +0000696 // Handle /largeaddressaware
697 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
698 Config->LargeAddressAware = true;
699
Rui Ueyamad68e2112015-07-28 03:15:57 +0000700 // Handle /highentropyva
701 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
702 Config->HighEntropyVA = true;
703
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000704 // Handle /entry and /dll
705 if (auto *Arg = Args.getLastArg(OPT_entry)) {
706 Config->Entry = addUndefined(mangle(Arg->getValue()));
707 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000708 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
709 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000710 Config->Entry = addUndefined(S);
711 } else if (!Config->NoEntry) {
712 // Windows specific -- If entry point name is not given, we need to
713 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000714 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000715 if (S.empty())
Rui Ueyama60604792016-07-14 23:37:14 +0000716 fatal("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000717 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000718 if (Config->Verbose)
Rui Ueyama8fe17672016-12-08 20:50:47 +0000719 outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000720 }
721
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000722 // Handle /export
723 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000724 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000725 if (Config->Machine == I386) {
726 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000727 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000728 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000729 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000730 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000731 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000732 }
733
734 // Handle /def
735 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000736 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000737 parseModuleDefs(
738 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
739 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000740 }
741
Rui Ueyama6d249082015-07-13 22:31:45 +0000742 // Handle /delayload
743 for (auto *Arg : Args.filtered(OPT_delayload)) {
744 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000745 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000746 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000747 } else {
748 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000749 }
750 }
751
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000752 // Set default image base if /base is not given.
753 if (Config->ImageBase == uint64_t(-1))
754 Config->ImageBase = getDefaultImageBase();
755
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000756 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000757 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000758 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
759 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
760 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000761
Rui Ueyama107db552015-08-09 21:01:06 +0000762 // We do not support /guard:cf (control flow protection) yet.
763 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
764 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
765 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
766 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
767
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000768 // This code may add new undefined symbols to the link, which may enqueue more
769 // symbol resolution tasks, so we need to continue executing tasks until we
770 // converge.
771 do {
772 // Windows specific -- if entry point is not found,
773 // search for its mangled names.
774 if (Config->Entry)
775 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000776
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000777 // Windows specific -- Make sure we resolve all dllexported symbols.
778 for (Export &E : Config->Exports) {
779 if (!E.ForwardTo.empty())
780 continue;
781 E.Sym = addUndefined(E.Name);
782 if (!E.Directives)
783 Symtab.mangleMaybe(E.Sym);
784 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000785
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000786 // Add weak aliases. Weak aliases is a mechanism to give remaining
787 // undefined symbols final chance to be resolved successfully.
788 for (auto Pair : Config->AlternateNames) {
789 StringRef From = Pair.first;
790 StringRef To = Pair.second;
791 Symbol *Sym = Symtab.find(From);
792 if (!Sym)
793 continue;
794 if (auto *U = dyn_cast<Undefined>(Sym->body()))
795 if (!U->WeakAlias)
796 U->WeakAlias = Symtab.addUndefined(To);
797 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000798
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000799 // Windows specific -- if __load_config_used can be resolved, resolve it.
800 if (Symtab.findUnderscore("_load_config_used"))
801 addUndefined(mangle("_load_config_used"));
802 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000803
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000804 // Do LTO by compiling bitcode input files to a set of native COFF files then
805 // link those files.
806 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000807 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000808
Peter Collingbourne2612a322015-07-04 05:28:41 +0000809 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000810 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000811
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000812 // Windows specific -- if no /subsystem is given, we need to infer
813 // that from entry point name.
814 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000815 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000816 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000817 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000818 }
819
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000820 // Handle /safeseh.
Rui Ueyama13563d82015-09-15 00:33:11 +0000821 if (Args.hasArg(OPT_safeseh))
822 for (ObjectFile *File : Symtab.ObjectFiles)
823 if (!File->SEHCompat)
Rui Ueyama60604792016-07-14 23:37:14 +0000824 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000825
Rui Ueyama151d8622015-06-17 20:40:43 +0000826 // Windows specific -- when we are creating a .dll file, we also
827 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000828 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000829 fixupExports();
830 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000831 assignExportOrdinals();
832 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000833
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000834 // Windows specific -- Create a side-by-side manifest file.
835 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000836 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000837
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000838 // Identify unreferenced COMDAT sections.
839 if (Config->DoGC)
840 markLive(Symtab.getChunks());
841
842 // Identify identical COMDAT sections to merge them.
843 if (Config->DoICF)
844 doICF(Symtab.getChunks());
845
Rui Ueyama411c63602015-05-28 19:09:30 +0000846 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000847 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000848
Rui Ueyama016414f2015-06-28 20:07:08 +0000849 // Create a symbol map file containing symbol VAs and their names
850 // to help debugging.
Hans Wennborg1818e652016-12-09 20:54:44 +0000851 std::string MapFile = getMapFile(Args);
852 if (!MapFile.empty()) {
Peter Collingbournebe549552015-06-26 18:58:24 +0000853 std::error_code EC;
Hans Wennborg1818e652016-12-09 20:54:44 +0000854 raw_fd_ostream Out(MapFile, EC, OpenFlags::F_Text);
Rui Ueyama0d09a862016-07-15 00:40:46 +0000855 if (EC)
Hans Wennborg1818e652016-12-09 20:54:44 +0000856 fatal(EC, "could not create the symbol map " + MapFile);
Peter Collingbournebe549552015-06-26 18:58:24 +0000857 Symtab.printMap(Out);
858 }
Hans Wennborg1818e652016-12-09 20:54:44 +0000859
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000860 // Call exit to avoid calling destructors.
861 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000862}
863
Rui Ueyama411c63602015-05-28 19:09:30 +0000864} // namespace coff
865} // namespace lld