blob: 58c443afc2e059e30f4dfcb754096eefc96dc680 [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"
Zachary Turner264b5d92017-06-07 03:48:56 +000021#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000022#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000023#include "llvm/Object/COFFImportFile.h"
24#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Option/Arg.h"
26#include "llvm/Option/ArgList.h"
27#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000028#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000030#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000031#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000032#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000033#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000034#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000035#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000036#include <memory>
37
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000038#include <future>
39
Rui Ueyama411c63602015-05-28 19:09:30 +000040using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000041using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000042using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000043using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000044
Rui Ueyama3500f662015-05-28 20:30:06 +000045namespace lld {
46namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000047
Rui Ueyama3500f662015-05-28 20:30:06 +000048Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000049LinkerDriver *Driver;
50
Rui Ueyama9381eb12016-12-18 14:06:06 +000051BumpPtrAllocator BAlloc;
52StringSaver Saver{BAlloc};
53std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
54
Bob Haarman6c8f7362017-01-17 19:07:42 +000055bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
56 ErrorCount = 0;
57 ErrorOS = &Diag;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000058 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000059 Config->Argv = {Args.begin(), Args.end()};
Bob Haarman6c8f7362017-01-17 19:07:42 +000060 Config->ColorDiagnostics =
61 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
Rui Ueyama7fed58c2016-12-08 19:10:28 +000062 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000063 Driver->link(Args);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +000064 return !ErrorCount;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000065}
Rui Ueyama411c63602015-05-28 19:09:30 +000066
Nico Weber5660de72016-04-20 22:34:15 +000067// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000068static std::string getOutputPath(StringRef Path) {
69 auto P = Path.find_last_of("\\/");
70 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000071 const char* E = Config->DLL ? ".dll" : ".exe";
72 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000073}
74
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000075// ErrorOr is not default constructible, so it cannot be used as the type
76// parameter of a future.
77// FIXME: We could open the file in createFutureForFile and avoid needing to
78// return an error here, but for the moment that would cost us a file descriptor
79// (a limited resource on Windows) for the duration that the future is pending.
80typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
81
82// Create a std::future that opens and maps a file using the best strategy for
83// the host platform.
84static std::future<MBErrPair> createFutureForFile(std::string Path) {
85#if LLVM_ON_WIN32
86 // On Windows, file I/O is relatively slow so it is best to do this
87 // asynchronously.
88 auto Strategy = std::launch::async;
89#else
90 auto Strategy = std::launch::deferred;
91#endif
92 return std::async(Strategy, [=]() {
93 auto MBOrErr = MemoryBuffer::getFile(Path);
94 if (!MBOrErr)
95 return MBErrPair{nullptr, MBOrErr.getError()};
96 return MBErrPair{std::move(*MBOrErr), std::error_code()};
97 });
98}
99
100MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
101 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000102 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000103
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000104 if (Driver->Tar)
105 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
106 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000107 return MBRef;
108}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000109
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000110void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
111 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000112
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000113 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000114 file_magic Magic = identify_magic(MBRef.getBuffer());
115 if (Magic == file_magic::windows_resource) {
116 Resources.push_back(MBRef);
117 return;
118 }
119
120 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000121 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000122 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000123 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000124 return Symtab.addFile(make<BitcodeFile>(MBRef));
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000125
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000126 if (Magic == file_magic::coff_cl_gl_object)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000127 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000128 "Recompile without /GL");
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000129 else
130 Symtab.addFile(make<ObjectFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000131}
132
133void LinkerDriver::enqueuePath(StringRef Path) {
134 auto Future =
135 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
136 std::string PathStr = Path;
137 enqueueTask([=]() {
138 auto MBOrErr = Future->get();
139 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000140 error("could not open " + PathStr + ": " + MBOrErr.second.message());
141 else
142 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000143 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000144}
145
146void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
147 StringRef ParentName) {
148 file_magic Magic = identify_magic(MB.getBuffer());
149 if (Magic == file_magic::coff_import_library) {
150 Symtab.addFile(make<ImportFile>(MB));
151 return;
152 }
153
154 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000155 if (Magic == file_magic::coff_object) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000156 Obj = make<ObjectFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000157 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000158 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000159 } else {
160 error("unknown file type: " + MB.getBufferIdentifier());
161 return;
162 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000163
164 Obj->ParentName = ParentName;
165 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000166 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000167}
168
169void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
170 StringRef SymName,
171 StringRef ParentName) {
172 if (!C.getParent()->isThin()) {
173 MemoryBufferRef MB = check(
174 C.getMemoryBufferRef(),
175 "could not get the buffer for the member defining symbol " + SymName);
176 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
177 return;
178 }
179
180 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
181 check(C.getFullName(),
182 "could not get the filename for the member defining symbol " +
183 SymName)));
184 enqueueTask([=]() {
185 auto MBOrErr = Future->get();
186 if (MBOrErr.second)
187 fatal(MBOrErr.second,
188 "could not get the buffer for the member defining " + SymName);
189 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
190 ParentName);
191 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000192}
193
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000194static bool isDecorated(StringRef Sym) {
195 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
196}
197
Rui Ueyama411c63602015-05-28 19:09:30 +0000198// Parses .drectve section contents and returns a list of files
199// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000200void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000201 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000202
David Blaikie6521ed92015-06-22 22:06:52 +0000203 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000204 switch (Arg->getOption().getUnaliasedOption().getID()) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000205 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000206 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000207 break;
208 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000209 if (Optional<StringRef> Path = findLib(Arg->getValue()))
210 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000211 break;
212 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000213 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000214 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000215 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000216 break;
217 }
218 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000219 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000220 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000221 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000222 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000223 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000224 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000225 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000226 break;
227 case OPT_nodefaultlib:
228 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
229 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000230 case OPT_section:
231 parseSection(Arg->getValue());
232 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000233 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000234 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000235 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000236 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000237 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000238 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000239 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000240 }
241 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000242}
243
Rui Ueyama54b71da2015-05-31 19:17:12 +0000244// Find file from search paths. You can omit ".obj", this function takes
245// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000246StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000247 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
248 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000249 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000250 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000251 for (StringRef Dir : SearchPaths) {
252 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000253 sys::path::append(Path, Filename);
254 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000255 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000256 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000257 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000258 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000259 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000260 }
261 }
262 return Filename;
263}
264
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000265// Resolves a file path. This never returns the same path
266// (in that case, it returns None).
267Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
268 StringRef Path = doFindFile(Filename);
269 bool Seen = !VisitedFiles.insert(Path.lower()).second;
270 if (Seen)
271 return None;
272 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000273}
274
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000275// Find library file from search path.
276StringRef LinkerDriver::doFindLib(StringRef Filename) {
277 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000278 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000279 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000280 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000281 return doFindFile(Filename);
282}
283
284// Resolves a library path. /nodefaultlib options are taken into
285// consideration. This never returns the same path (in that case,
286// it returns None).
287Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
288 if (Config->NoDefaultLibAll)
289 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000290 if (!VisitedLibs.insert(Filename.lower()).second)
291 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000292 StringRef Path = doFindLib(Filename);
293 if (Config->NoDefaultLibs.count(Path))
294 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000295 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000296 return None;
297 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000298}
299
300// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000301void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000302 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
303 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000304 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000305 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000306 while (!Env.empty()) {
307 StringRef Path;
308 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000309 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000310 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000311}
312
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000313SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
314 SymbolBody *B = Symtab.addUndefined(Name);
315 Config->GCRoot.insert(B);
316 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000317}
318
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000319// Symbol names are mangled by appending "_" prefix on x86.
320StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000321 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
322 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000323 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000324 return Sym;
325}
326
Rui Ueyama45044f42015-06-29 01:03:53 +0000327// Windows specific -- find default entry point name.
328StringRef LinkerDriver::findDefaultEntry() {
329 // User-defined main functions and their corresponding entry points.
330 static const char *Entries[][2] = {
331 {"main", "mainCRTStartup"},
332 {"wmain", "wmainCRTStartup"},
333 {"WinMain", "WinMainCRTStartup"},
334 {"wWinMain", "wWinMainCRTStartup"},
335 };
336 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000337 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000338 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000339 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000340 }
341 return "";
342}
343
344WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000345 if (Config->DLL)
346 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000347 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000348 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000349 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000350 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
351 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000352}
353
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000354static uint64_t getDefaultImageBase() {
355 if (Config->is64())
356 return Config->DLL ? 0x180000000 : 0x140000000;
357 return Config->DLL ? 0x10000000 : 0x400000;
358}
359
Rui Ueyama8fe17672016-12-08 20:50:47 +0000360static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000361 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000362 ArrayRef<StringRef> SearchPaths) {
363 SmallString<0> Data;
364 raw_svector_ostream OS(Data);
365
366 for (auto *Arg : Args) {
367 switch (Arg->getOption().getID()) {
368 case OPT_linkrepro:
369 case OPT_INPUT:
370 case OPT_defaultlib:
371 case OPT_libpath:
372 break;
373 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000374 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000375 }
376 }
377
378 for (StringRef Path : SearchPaths) {
379 std::string RelPath = relativeToRoot(Path);
380 OS << "/libpath:" << quote(RelPath) << "\n";
381 }
382
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000383 for (StringRef Path : FilePaths)
384 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000385
386 return Data.str();
387}
388
Rui Ueyama8fe17672016-12-08 20:50:47 +0000389static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000390 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
391 if (Args.hasArg(OPT_driver))
392 DebugTypes |= static_cast<unsigned>(DebugType::PData);
393 if (Args.hasArg(OPT_profile))
394 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
395 return DebugTypes;
396}
397
398static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000399 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000400 Arg.split(Types, ',', /*KeepEmpty=*/false);
401
402 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
403 for (StringRef Type : Types)
404 DebugTypes |= StringSwitch<unsigned>(Type.lower())
405 .Case("cv", static_cast<unsigned>(DebugType::CV))
406 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000407 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
408 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000409 return DebugTypes;
410}
411
Hans Wennborg1818e652016-12-09 20:54:44 +0000412static std::string getMapFile(const opt::InputArgList &Args) {
413 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
414 if (!Arg)
415 return "";
416 if (Arg->getOption().getID() == OPT_lldmap_file)
417 return Arg->getValue();
418
419 assert(Arg->getOption().getID() == OPT_lldmap);
420 StringRef OutFile = Config->OutputFile;
421 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
422}
423
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000424static std::string getImplibPath() {
425 if (!Config->Implib.empty())
426 return Config->Implib;
427 SmallString<128> Out = StringRef(Config->OutputFile);
428 sys::path::replace_extension(Out, ".lib");
429 return Out.str();
430}
431
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000432//
433// The import name is caculated as the following:
434//
435// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
436// -----+----------------+---------------------+------------------
437// LINK | {value} | {value}.{.dll/.exe} | {output name}
438// LIB | {value} | {value}.dll | {output name}.dll
439//
440static std::string getImportName(bool AsLib) {
441 SmallString<128> Out;
442
443 if (Config->ImportName.empty()) {
444 Out.assign(sys::path::filename(Config->OutputFile));
445 if (AsLib)
446 sys::path::replace_extension(Out, ".dll");
447 } else {
448 Out.assign(Config->ImportName);
449 if (!sys::path::has_extension(Out))
450 sys::path::replace_extension(Out,
451 (Config->DLL || AsLib) ? ".dll" : ".exe");
452 }
453
454 return Out.str();
455}
456
457static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000458 std::vector<COFFShortExport> Exports;
459 for (Export &E1 : Config->Exports) {
460 COFFShortExport E2;
461 // Use SymbolName, which will have any stdcall or fastcall qualifiers.
462 E2.Name = E1.SymbolName;
463 E2.ExtName = E1.ExtName;
464 E2.Ordinal = E1.Ordinal;
465 E2.Noname = E1.Noname;
466 E2.Data = E1.Data;
467 E2.Private = E1.Private;
468 E2.Constant = E1.Constant;
469 Exports.push_back(E2);
470 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000471
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000472 writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
473 Config->Machine);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000474}
475
476static void parseModuleDefs(StringRef Path) {
477 std::unique_ptr<MemoryBuffer> MB = check(
478 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyama67aea7372017-06-08 23:43:44 +0000479 COFFModuleDefinition M =
480 check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000481
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000482 if (Config->OutputFile.empty())
483 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000484 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000485 if (M.ImageBase)
486 Config->ImageBase = M.ImageBase;
487 if (M.StackReserve)
488 Config->StackReserve = M.StackReserve;
489 if (M.StackCommit)
490 Config->StackCommit = M.StackCommit;
491 if (M.HeapReserve)
492 Config->HeapReserve = M.HeapReserve;
493 if (M.HeapCommit)
494 Config->HeapCommit = M.HeapCommit;
495 if (M.MajorImageVersion)
496 Config->MajorImageVersion = M.MajorImageVersion;
497 if (M.MinorImageVersion)
498 Config->MinorImageVersion = M.MinorImageVersion;
499 if (M.MajorOSVersion)
500 Config->MajorOSVersion = M.MajorOSVersion;
501 if (M.MinorOSVersion)
502 Config->MinorOSVersion = M.MinorOSVersion;
503
504 for (COFFShortExport E1 : M.Exports) {
505 Export E2;
506 E2.Name = Saver.save(E1.Name);
507 if (E1.isWeak())
508 E2.ExtName = Saver.save(E1.ExtName);
509 E2.Ordinal = E1.Ordinal;
510 E2.Noname = E1.Noname;
511 E2.Data = E1.Data;
512 E2.Private = E1.Private;
513 E2.Constant = E1.Constant;
514 Config->Exports.push_back(E2);
515 }
516}
517
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000518std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000519 std::vector<MemoryBufferRef> V;
520 Error Err = Error::success();
521 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
522 Archive::Child C =
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000523 check(COrErr,
524 File->getFileName() + ": could not get the child of the archive");
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000525 MemoryBufferRef MBRef =
526 check(C.getMemoryBufferRef(),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000527 File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000528 ": could not get the buffer for a child of the archive");
529 V.push_back(MBRef);
530 }
531 if (Err)
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000532 fatal(File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000533 ": Archive::children failed: " + toString(std::move(Err)));
534 return V;
535}
536
537// A helper function for filterBitcodeFiles.
538static bool needsRebuilding(MemoryBufferRef MB) {
539 // The MSVC linker doesn't support thin archives, so if it's a thin
540 // archive, we always need to rebuild it.
541 std::unique_ptr<Archive> File =
542 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
543 if (File->isThin())
544 return true;
545
546 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000547 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000548 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
549 return true;
550 return false;
551}
552
553// Opens a given path as an archive file and removes bitcode files
554// from them if exists. This function is to appease the MSVC linker as
555// their linker doesn't like archive files containing non-native
556// object files.
557//
558// If a given archive doesn't contain bitcode files, the archive path
559// is returned as-is. Otherwise, a new temporary file is created and
560// its path is returned.
561static Optional<std::string>
562filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000563 std::unique_ptr<MemoryBuffer> MB = check(
564 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000565 MemoryBufferRef MBRef = MB->getMemBufferRef();
566 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000567
568 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000569 return None;
570 if (Magic != file_magic::archive)
571 return Path.str();
572 if (!needsRebuilding(MBRef))
573 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000574
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000575 std::unique_ptr<Archive> File =
576 check(Archive::create(MBRef),
577 MBRef.getBufferIdentifier() + ": failed to parse archive");
578
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000579 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000580 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000581 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
582 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000583
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000584 if (New.empty())
585 return None;
586
587 log("Creating a temporary archive for " + Path + " to remove bitcode files");
588
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000589 SmallString<128> S;
590 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
591 ".lib", S))
592 fatal(EC, "cannot create a temporary file");
593 std::string Temp = S.str();
594 TemporaryFiles.push_back(Temp);
595
596 std::pair<StringRef, std::error_code> Ret =
597 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
598 /*Deterministics=*/true,
599 /*Thin=*/false);
600 if (Ret.second)
601 error("failed to create a new archive " + S.str() + ": " + Ret.first);
602 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000603}
604
605// Create response file contents and invoke the MSVC linker.
606void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000607 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000608 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000609
Bob Haarman41108162017-04-21 21:38:01 +0000610 // Write out archive members that we used in symbol resolution and pass these
611 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
612 // references.
613 for (const auto *O : Symtab.ObjectFiles) {
614 if (O->ParentName.empty())
615 continue;
616 SmallString<128> S;
617 int Fd;
618 if (auto EC = sys::fs::createTemporaryFile(
619 "lld-" + sys::path::filename(O->ParentName), ".obj", Fd, S))
620 fatal(EC, "cannot create a temporary file");
621 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
622 OS << O->MB.getBuffer();
623 Temps.push_back(S.str());
624 Rsp += quote(S) + "\n";
625 }
626
Rui Ueyama85d54b02017-02-23 00:26:42 +0000627 for (auto *Arg : Args) {
628 switch (Arg->getOption().getID()) {
629 case OPT_linkrepro:
630 case OPT_lldmap:
631 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000632 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000633 case OPT_msvclto:
634 // LLD-specific options are stripped.
635 break;
636 case OPT_opt:
637 if (!StringRef(Arg->getValue()).startswith("lld"))
638 Rsp += toString(Arg) + " ";
639 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000640 case OPT_INPUT: {
641 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
642 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000643 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000644 continue;
645 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000646 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000647 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000648 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000649 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000650 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000651 }
652 }
653
654 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
655 runMSVCLinker(Rsp, ObjectFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000656
657 for (StringRef Path : Temps)
658 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000659}
660
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000661void LinkerDriver::enqueueTask(std::function<void()> Task) {
662 TaskQueue.push_back(std::move(Task));
663}
664
665bool LinkerDriver::run() {
666 bool DidWork = !TaskQueue.empty();
667 while (!TaskQueue.empty()) {
668 TaskQueue.front()();
669 TaskQueue.pop_front();
670 }
671 return DidWork;
672}
673
Rui Ueyama8fe17672016-12-08 20:50:47 +0000674void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000675 // If the first command line argument is "/lib", link.exe acts like lib.exe.
676 // We call our own implementation of lib.exe that understands bitcode files.
677 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
678 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000679 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000680 return;
681 }
682
Peter Collingbourne60c16162015-06-01 20:10:10 +0000683 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000684 InitializeAllTargetInfos();
685 InitializeAllTargets();
686 InitializeAllTargetMCs();
687 InitializeAllAsmParsers();
688 InitializeAllAsmPrinters();
689 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000690
Rui Ueyama411c63602015-05-28 19:09:30 +0000691 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000692 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000693
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000694 // Parse and evaluate -mllvm options.
695 std::vector<const char *> V;
696 V.push_back("lld-link (LLVM option parsing)");
697 for (auto *Arg : Args.filtered(OPT_mllvm))
698 V.push_back(Arg->getValue());
699 cl::ParseCommandLineOptions(V.size(), V.data());
700
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000701 // Handle /errorlimit early, because error() depends on it.
702 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
703 int N = 20;
704 StringRef S = Arg->getValue();
705 if (S.getAsInteger(10, N))
706 error(Arg->getSpelling() + " number expected, but got " + S);
707 Config->ErrorLimit = N;
708 }
709
Rui Ueyama5c726432015-05-29 16:11:52 +0000710 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000711 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000712 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000713 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000714 }
715
Peter Collingbournefeee2102016-07-26 02:00:42 +0000716 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
717 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000718 sys::path::append(Path, "repro.tar");
719
720 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
721 TarWriter::create(Path, "repro");
722
723 if (ErrOrWriter) {
724 Tar = std::move(*ErrOrWriter);
725 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000726 error("/linkrepro: failed to open " + Path + ": " +
727 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000728 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000729 }
730
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000731 if (!Args.hasArgNoClaim(OPT_INPUT)) {
732 if (Args.hasArgNoClaim(OPT_deffile))
733 Config->NoEntry = true;
734 else
735 fatal("no input files");
736 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000737
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000738 // Construct search path list.
739 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000740 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000741 SearchPaths.push_back(Arg->getValue());
742 addLibSearchPaths();
743
Rui Ueyamaad660982015-06-07 00:20:32 +0000744 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000745 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000746 Config->OutputFile = Arg->getValue();
747
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000748 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000749 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000750 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000751
Rui Ueyama95925fd2015-06-28 19:35:15 +0000752 // Handle /force or /force:unresolved
753 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
754 Config->Force = true;
755
Rui Ueyama6600eb12015-07-04 23:37:32 +0000756 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000757 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000758 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000759 Config->DebugTypes =
760 Args.hasArg(OPT_debugtype)
761 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
762 : getDefaultDebugType(Args);
763 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000764
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000765 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000766 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000767 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000768
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000769 // Handle /noentry
770 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000771 if (Args.hasArg(OPT_dll))
772 Config->NoEntry = true;
773 else
774 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000775 }
776
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000777 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000778 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000779 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000780 Config->ManifestID = 2;
781 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000782
Rui Ueyama588e8322015-06-15 01:23:58 +0000783 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000784 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000785 if (Args.hasArg(OPT_dynamicbase)) {
786 error("/fixed must not be specified with /dynamicbase");
787 } else {
788 Config->Relocatable = false;
789 Config->DynamicBase = false;
790 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000791 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000792
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000793 if (Args.hasArg(OPT_appcontainer))
794 Config->AppContainer = true;
795
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000796 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000797 if (auto *Arg = Args.getLastArg(OPT_machine))
798 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000799
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000800 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000801 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000802 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
803
804 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000805 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000806 Config->NoDefaultLibAll = true;
807
Rui Ueyama804a8b62015-05-29 16:18:15 +0000808 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000809 if (auto *Arg = Args.getLastArg(OPT_base))
810 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000811
812 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000813 if (auto *Arg = Args.getLastArg(OPT_stack))
814 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000815
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000816 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000817 if (auto *Arg = Args.getLastArg(OPT_heap))
818 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000819
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000820 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000821 if (auto *Arg = Args.getLastArg(OPT_version))
822 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
823 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000824
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000825 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000826 if (auto *Arg = Args.getLastArg(OPT_subsystem))
827 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
828 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000829
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000830 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000831 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000832 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000833
Rui Ueyama08d5e182015-06-18 23:20:11 +0000834 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000835 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000836 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000837
Rui Ueyamab95188c2015-06-18 20:27:09 +0000838 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000839 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000840 Config->Implib = Arg->getValue();
841
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000842 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000843 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000844 std::string Str = StringRef(Arg->getValue()).lower();
845 SmallVector<StringRef, 1> Vec;
846 StringRef(Str).split(Vec, ',');
847 for (StringRef S : Vec) {
848 if (S == "noref") {
849 Config->DoGC = false;
850 Config->DoICF = false;
851 continue;
852 }
853 if (S == "icf" || StringRef(S).startswith("icf=")) {
854 Config->DoICF = true;
855 continue;
856 }
857 if (S == "noicf") {
858 Config->DoICF = false;
859 continue;
860 }
861 if (StringRef(S).startswith("lldlto=")) {
862 StringRef OptLevel = StringRef(S).substr(7);
863 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
864 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000865 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000866 continue;
867 }
868 if (StringRef(S).startswith("lldltojobs=")) {
869 StringRef Jobs = StringRef(S).substr(11);
870 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000871 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000872 continue;
873 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000874 if (StringRef(S).startswith("lldltopartitions=")) {
875 StringRef N = StringRef(S).substr(17);
876 if (N.getAsInteger(10, Config->LTOPartitions) ||
877 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000878 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000879 continue;
880 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000881 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000882 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000883 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000884 }
885
Bob Haarman69b196d2017-02-08 18:36:41 +0000886 // Handle /lldsavetemps
887 if (Args.hasArg(OPT_lldsavetemps))
888 Config->SaveTemps = true;
889
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000890 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000891 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000892 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000893
Rui Ueyama6600eb12015-07-04 23:37:32 +0000894 // Handle /merge
895 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000896 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000897
Rui Ueyama440138c2016-06-20 03:39:39 +0000898 // Handle /section
899 for (auto *Arg : Args.filtered(OPT_section))
900 parseSection(Arg->getValue());
901
Nico Webera7a2c442017-07-25 18:08:03 +0000902 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
903 // also passed.
904 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
905 Config->ManifestDependency = Arg->getValue();
906 Config->Manifest = Configuration::SideBySide;
907 }
908
909 // Handle /manifest and /manifest:
910 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
911 if (Arg->getOption().getID() == OPT_manifest)
912 Config->Manifest = Configuration::SideBySide;
913 else
914 parseManifest(Arg->getValue());
915 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000916
917 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000918 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
919 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000920
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000921 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000922 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000923 Config->ManifestFile = Arg->getValue();
924
Rui Ueyamaafb19012016-04-19 01:21:58 +0000925 // Handle /manifestinput
926 for (auto *Arg : Args.filtered(OPT_manifestinput))
927 Config->ManifestInput.push_back(Arg->getValue());
928
Nico Webera7a2c442017-07-25 18:08:03 +0000929 if (!Config->ManifestInput.empty() &&
930 Config->Manifest != Configuration::Embed) {
931 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
932 }
933
Rui Ueyama6592ff82015-06-16 23:13:00 +0000934 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000935 if (Args.hasArg(OPT_allowisolation_no))
936 Config->AllowIsolation = false;
937 if (Args.hasArg(OPT_dynamicbase_no))
938 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000939 if (Args.hasArg(OPT_nxcompat_no))
940 Config->NxCompat = false;
941 if (Args.hasArg(OPT_tsaware_no))
942 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000943 if (Args.hasArg(OPT_nosymtab))
944 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000945
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000946 Config->MapFile = getMapFile(Args);
947
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000948 if (ErrorCount)
949 return;
950
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000951 // Create a list of input files. Files can be given as arguments
952 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000953 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000954 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000955 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000956 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000957 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000958 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000959 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000960
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000961 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000962 if (Config->Manifest == Configuration::Embed)
963 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000964
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000965 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000966 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000967
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000968 // We should have inferred a machine type by now from the input files, but if
969 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000970 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000971 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000972 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000973 }
974
Eric Beckmann9e19d792017-06-17 02:26:27 +0000975 // Input files can be Windows resource files (.res files). We use
976 // WindowsResource to convert resource files to a regular COFF file,
977 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000978 if (!Resources.empty())
979 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000980
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000981 if (Tar)
982 Tar->append("response.txt",
983 createResponseFile(Args, FilePaths,
984 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000985
Rui Ueyama4d545342015-07-28 03:12:00 +0000986 // Handle /largeaddressaware
987 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
988 Config->LargeAddressAware = true;
989
Rui Ueyamad68e2112015-07-28 03:15:57 +0000990 // Handle /highentropyva
991 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
992 Config->HighEntropyVA = true;
993
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000994 // Handle /entry and /dll
995 if (auto *Arg = Args.getLastArg(OPT_entry)) {
996 Config->Entry = addUndefined(mangle(Arg->getValue()));
997 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000998 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
999 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001000 Config->Entry = addUndefined(S);
1001 } else if (!Config->NoEntry) {
1002 // Windows specific -- If entry point name is not given, we need to
1003 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001004 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001005 if (S.empty())
1006 fatal("entry point must be defined");
1007 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001008 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001009 }
1010
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001011 // Handle /export
1012 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001013 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001014 if (Config->Machine == I386) {
1015 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001016 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001017 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001018 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001019 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001020 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001021 }
1022
1023 // Handle /def
1024 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001025 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001026 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001027 }
1028
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001029 // Handle generation of import library from a def file.
1030 if (!Args.hasArgNoClaim(OPT_INPUT)) {
1031 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001032 createImportLibrary(/*AsLib=*/true);
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001033 exit(0);
1034 }
1035
Rui Ueyama6d249082015-07-13 22:31:45 +00001036 // Handle /delayload
1037 for (auto *Arg : Args.filtered(OPT_delayload)) {
1038 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001039 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001040 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001041 } else {
1042 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001043 }
1044 }
1045
Reid Kleckner7668182e2017-03-21 00:12:51 +00001046 // Set default image name if neither /out or /def set it.
1047 if (Config->OutputFile.empty()) {
1048 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001049 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001050 }
1051
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001052 // Put the PDB next to the image if no /pdb flag was passed.
1053 if (Config->Debug && Config->PDBPath.empty()) {
1054 Config->PDBPath = Config->OutputFile;
1055 sys::path::replace_extension(Config->PDBPath, ".pdb");
1056 }
1057
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001058 // Disable PDB generation if the user requested it.
1059 if (Args.hasArg(OPT_nopdb))
1060 Config->PDBPath = "";
1061
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001062 // Set default image base if /base is not given.
1063 if (Config->ImageBase == uint64_t(-1))
1064 Config->ImageBase = getDefaultImageBase();
1065
Reid Kleckner502d4ce2017-06-26 15:39:52 +00001066 Symtab.addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001067 if (Config->Machine == I386) {
Reid Kleckner502d4ce2017-06-26 15:39:52 +00001068 Symtab.addAbsolute("___safe_se_handler_table", 0);
1069 Symtab.addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001070 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001071
Rui Ueyama107db552015-08-09 21:01:06 +00001072 // We do not support /guard:cf (control flow protection) yet.
1073 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyama107db552015-08-09 21:01:06 +00001074 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
Rui Ueyama2f740f72017-06-21 02:26:19 +00001075 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001076 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
Rui Ueyama2f740f72017-06-21 02:26:19 +00001077 Symtab.addAbsolute(mangle("__guard_iat_count"), 0);
1078 Symtab.addAbsolute(mangle("__guard_iat_table"), 0);
1079 Symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
1080 Symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001081
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001082 // This code may add new undefined symbols to the link, which may enqueue more
1083 // symbol resolution tasks, so we need to continue executing tasks until we
1084 // converge.
1085 do {
1086 // Windows specific -- if entry point is not found,
1087 // search for its mangled names.
1088 if (Config->Entry)
1089 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001090
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001091 // Windows specific -- Make sure we resolve all dllexported symbols.
1092 for (Export &E : Config->Exports) {
1093 if (!E.ForwardTo.empty())
1094 continue;
1095 E.Sym = addUndefined(E.Name);
1096 if (!E.Directives)
1097 Symtab.mangleMaybe(E.Sym);
1098 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001099
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001100 // Add weak aliases. Weak aliases is a mechanism to give remaining
1101 // undefined symbols final chance to be resolved successfully.
1102 for (auto Pair : Config->AlternateNames) {
1103 StringRef From = Pair.first;
1104 StringRef To = Pair.second;
1105 Symbol *Sym = Symtab.find(From);
1106 if (!Sym)
1107 continue;
1108 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1109 if (!U->WeakAlias)
1110 U->WeakAlias = Symtab.addUndefined(To);
1111 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001112
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001113 // Windows specific -- if __load_config_used can be resolved, resolve it.
1114 if (Symtab.findUnderscore("_load_config_used"))
1115 addUndefined(mangle("_load_config_used"));
1116 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001117
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001118 if (ErrorCount)
1119 return;
1120
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001121 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1122 // This is useful because MSVC link.exe can generate complete PDBs.
1123 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001124 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001125 exit(0);
1126 }
1127
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001128 // Do LTO by compiling bitcode input files to a set of native COFF files then
1129 // link those files.
1130 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001131 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001132
Peter Collingbourne2612a322015-07-04 05:28:41 +00001133 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +00001134 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +00001135
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001136 // Windows specific -- if no /subsystem is given, we need to infer
1137 // that from entry point name.
1138 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001139 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001140 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001141 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001142 }
1143
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001144 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001145 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyama13563d82015-09-15 00:33:11 +00001146 for (ObjectFile *File : Symtab.ObjectFiles)
1147 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001148 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1149 if (ErrorCount)
1150 return;
1151 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001152
Rui Ueyama151d8622015-06-17 20:40:43 +00001153 // Windows specific -- when we are creating a .dll file, we also
1154 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001155 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001156 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001157 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001158 assignExportOrdinals();
1159 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001160
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001161 // Windows specific -- Create a side-by-side manifest file.
1162 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001163 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001164
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001165 // Identify unreferenced COMDAT sections.
1166 if (Config->DoGC)
1167 markLive(Symtab.getChunks());
1168
1169 // Identify identical COMDAT sections to merge them.
1170 if (Config->DoICF)
1171 doICF(Symtab.getChunks());
1172
Rui Ueyama411c63602015-05-28 19:09:30 +00001173 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +00001174 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +00001175
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001176 // Call exit to avoid calling destructors.
1177 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001178}
1179
Rui Ueyama411c63602015-05-28 19:09:30 +00001180} // namespace coff
1181} // namespace lld