blob: 7a965fa87f298e175d4d7b025857bdfc7ebbb69c [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()};
Rui Ueyama8bee41e2017-08-24 20:32:58 +000060 Config->ColorDiagnostics = ErrorOS->has_colors();
Rui Ueyama7fed58c2016-12-08 19:10:28 +000061 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000062 Driver->link(Args);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +000063 return !ErrorCount;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000064}
Rui Ueyama411c63602015-05-28 19:09:30 +000065
Nico Weber5660de72016-04-20 22:34:15 +000066// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000067static std::string getOutputPath(StringRef Path) {
68 auto P = Path.find_last_of("\\/");
69 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000070 const char* E = Config->DLL ? ".dll" : ".exe";
71 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000072}
73
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000074// ErrorOr is not default constructible, so it cannot be used as the type
75// parameter of a future.
76// FIXME: We could open the file in createFutureForFile and avoid needing to
77// return an error here, but for the moment that would cost us a file descriptor
78// (a limited resource on Windows) for the duration that the future is pending.
79typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
80
81// Create a std::future that opens and maps a file using the best strategy for
82// the host platform.
83static std::future<MBErrPair> createFutureForFile(std::string Path) {
84#if LLVM_ON_WIN32
85 // On Windows, file I/O is relatively slow so it is best to do this
86 // asynchronously.
87 auto Strategy = std::launch::async;
88#else
89 auto Strategy = std::launch::deferred;
90#endif
91 return std::async(Strategy, [=]() {
92 auto MBOrErr = MemoryBuffer::getFile(Path);
93 if (!MBOrErr)
94 return MBErrPair{nullptr, MBOrErr.getError()};
95 return MBErrPair{std::move(*MBOrErr), std::error_code()};
96 });
97}
98
99MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
100 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000101 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000102
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000103 if (Driver->Tar)
104 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
105 MBRef.getBuffer());
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));
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000124
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000125 if (Magic == file_magic::coff_cl_gl_object)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000126 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000127 "Recompile without /GL");
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000128 else
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000129 Symtab.addFile(make<ObjFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000130}
131
132void LinkerDriver::enqueuePath(StringRef Path) {
133 auto Future =
134 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
135 std::string PathStr = Path;
136 enqueueTask([=]() {
137 auto MBOrErr = Future->get();
138 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000139 error("could not open " + PathStr + ": " + MBOrErr.second.message());
140 else
141 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000142 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000143}
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;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000154 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000155 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000156 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000157 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000158 } else {
159 error("unknown file type: " + MB.getBufferIdentifier());
160 return;
161 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000162
163 Obj->ParentName = ParentName;
164 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000165 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000166}
167
168void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
169 StringRef SymName,
170 StringRef ParentName) {
171 if (!C.getParent()->isThin()) {
172 MemoryBufferRef MB = check(
173 C.getMemoryBufferRef(),
174 "could not get the buffer for the member defining symbol " + SymName);
175 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
176 return;
177 }
178
179 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
180 check(C.getFullName(),
181 "could not get the filename for the member defining symbol " +
182 SymName)));
183 enqueueTask([=]() {
184 auto MBOrErr = Future->get();
185 if (MBOrErr.second)
186 fatal(MBOrErr.second,
187 "could not get the buffer for the member defining " + SymName);
188 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
189 ParentName);
190 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000191}
192
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000193static bool isDecorated(StringRef Sym) {
194 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
195}
196
Rui Ueyama411c63602015-05-28 19:09:30 +0000197// Parses .drectve section contents and returns a list of files
198// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000199void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000200 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000201
David Blaikie6521ed92015-06-22 22:06:52 +0000202 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000203 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000204 case OPT_aligncomm:
205 parseAligncomm(Arg->getValue());
206 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000207 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000208 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000209 break;
210 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000211 if (Optional<StringRef> Path = findLib(Arg->getValue()))
212 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000213 break;
214 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000215 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000216 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000217 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000218 break;
219 }
220 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000221 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000222 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000223 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000224 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000225 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000226 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000227 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000228 break;
229 case OPT_nodefaultlib:
230 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
231 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000232 case OPT_section:
233 parseSection(Arg->getValue());
234 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000235 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000236 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000237 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000238 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000239 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000240 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000241 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000242 }
243 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000244}
245
Rui Ueyama54b71da2015-05-31 19:17:12 +0000246// Find file from search paths. You can omit ".obj", this function takes
247// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000248StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000249 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
250 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000251 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000252 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000253 for (StringRef Dir : SearchPaths) {
254 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000255 sys::path::append(Path, Filename);
256 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000257 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000258 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000259 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000260 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000261 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000262 }
263 }
264 return Filename;
265}
266
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000267// Resolves a file path. This never returns the same path
268// (in that case, it returns None).
269Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
270 StringRef Path = doFindFile(Filename);
271 bool Seen = !VisitedFiles.insert(Path.lower()).second;
272 if (Seen)
273 return None;
274 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000275}
276
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000277// Find library file from search path.
278StringRef LinkerDriver::doFindLib(StringRef Filename) {
279 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000280 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000281 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000282 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000283 return doFindFile(Filename);
284}
285
286// Resolves a library path. /nodefaultlib options are taken into
287// consideration. This never returns the same path (in that case,
288// it returns None).
289Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
290 if (Config->NoDefaultLibAll)
291 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000292 if (!VisitedLibs.insert(Filename.lower()).second)
293 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000294 StringRef Path = doFindLib(Filename);
295 if (Config->NoDefaultLibs.count(Path))
296 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000297 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000298 return None;
299 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000300}
301
302// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000303void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000304 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
305 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000306 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000307 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000308 while (!Env.empty()) {
309 StringRef Path;
310 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000311 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000312 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000313}
314
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000315SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
316 SymbolBody *B = Symtab.addUndefined(Name);
317 Config->GCRoot.insert(B);
318 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000319}
320
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000321// Symbol names are mangled by appending "_" prefix on x86.
322StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000323 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
324 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000325 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000326 return Sym;
327}
328
Rui Ueyama45044f42015-06-29 01:03:53 +0000329// Windows specific -- find default entry point name.
330StringRef LinkerDriver::findDefaultEntry() {
331 // User-defined main functions and their corresponding entry points.
332 static const char *Entries[][2] = {
333 {"main", "mainCRTStartup"},
334 {"wmain", "wmainCRTStartup"},
335 {"WinMain", "WinMainCRTStartup"},
336 {"wWinMain", "wWinMainCRTStartup"},
337 };
338 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000339 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000340 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000341 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000342 }
343 return "";
344}
345
346WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000347 if (Config->DLL)
348 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000349 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000350 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000351 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000352 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
353 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000354}
355
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000356static uint64_t getDefaultImageBase() {
357 if (Config->is64())
358 return Config->DLL ? 0x180000000 : 0x140000000;
359 return Config->DLL ? 0x10000000 : 0x400000;
360}
361
Rui Ueyama8fe17672016-12-08 20:50:47 +0000362static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000363 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000364 ArrayRef<StringRef> SearchPaths) {
365 SmallString<0> Data;
366 raw_svector_ostream OS(Data);
367
368 for (auto *Arg : Args) {
369 switch (Arg->getOption().getID()) {
370 case OPT_linkrepro:
371 case OPT_INPUT:
372 case OPT_defaultlib:
373 case OPT_libpath:
374 break;
375 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000376 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000377 }
378 }
379
380 for (StringRef Path : SearchPaths) {
381 std::string RelPath = relativeToRoot(Path);
382 OS << "/libpath:" << quote(RelPath) << "\n";
383 }
384
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000385 for (StringRef Path : FilePaths)
386 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000387
388 return Data.str();
389}
390
Rui Ueyama8fe17672016-12-08 20:50:47 +0000391static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000392 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
393 if (Args.hasArg(OPT_driver))
394 DebugTypes |= static_cast<unsigned>(DebugType::PData);
395 if (Args.hasArg(OPT_profile))
396 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
397 return DebugTypes;
398}
399
400static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000401 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000402 Arg.split(Types, ',', /*KeepEmpty=*/false);
403
404 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
405 for (StringRef Type : Types)
406 DebugTypes |= StringSwitch<unsigned>(Type.lower())
407 .Case("cv", static_cast<unsigned>(DebugType::CV))
408 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000409 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
410 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000411 return DebugTypes;
412}
413
Hans Wennborg1818e652016-12-09 20:54:44 +0000414static std::string getMapFile(const opt::InputArgList &Args) {
415 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
416 if (!Arg)
417 return "";
418 if (Arg->getOption().getID() == OPT_lldmap_file)
419 return Arg->getValue();
420
421 assert(Arg->getOption().getID() == OPT_lldmap);
422 StringRef OutFile = Config->OutputFile;
423 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
424}
425
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000426static std::string getImplibPath() {
427 if (!Config->Implib.empty())
428 return Config->Implib;
429 SmallString<128> Out = StringRef(Config->OutputFile);
430 sys::path::replace_extension(Out, ".lib");
431 return Out.str();
432}
433
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000434//
435// The import name is caculated as the following:
436//
437// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
438// -----+----------------+---------------------+------------------
439// LINK | {value} | {value}.{.dll/.exe} | {output name}
440// LIB | {value} | {value}.dll | {output name}.dll
441//
442static std::string getImportName(bool AsLib) {
443 SmallString<128> Out;
444
445 if (Config->ImportName.empty()) {
446 Out.assign(sys::path::filename(Config->OutputFile));
447 if (AsLib)
448 sys::path::replace_extension(Out, ".dll");
449 } else {
450 Out.assign(Config->ImportName);
451 if (!sys::path::has_extension(Out))
452 sys::path::replace_extension(Out,
453 (Config->DLL || AsLib) ? ".dll" : ".exe");
454 }
455
456 return Out.str();
457}
458
459static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000460 std::vector<COFFShortExport> Exports;
461 for (Export &E1 : Config->Exports) {
462 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000463 E2.Name = E1.Name;
464 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000465 E2.ExtName = E1.ExtName;
466 E2.Ordinal = E1.Ordinal;
467 E2.Noname = E1.Noname;
468 E2.Data = E1.Data;
469 E2.Private = E1.Private;
470 E2.Constant = E1.Constant;
471 Exports.push_back(E2);
472 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000473
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000474 writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
Martin Storsjo92f32d02017-08-16 05:23:00 +0000475 Config->Machine, false);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000476}
477
478static void parseModuleDefs(StringRef Path) {
479 std::unique_ptr<MemoryBuffer> MB = check(
480 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyama67aea7372017-06-08 23:43:44 +0000481 COFFModuleDefinition M =
482 check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000483
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000484 if (Config->OutputFile.empty())
485 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000486 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000487 if (M.ImageBase)
488 Config->ImageBase = M.ImageBase;
489 if (M.StackReserve)
490 Config->StackReserve = M.StackReserve;
491 if (M.StackCommit)
492 Config->StackCommit = M.StackCommit;
493 if (M.HeapReserve)
494 Config->HeapReserve = M.HeapReserve;
495 if (M.HeapCommit)
496 Config->HeapCommit = M.HeapCommit;
497 if (M.MajorImageVersion)
498 Config->MajorImageVersion = M.MajorImageVersion;
499 if (M.MinorImageVersion)
500 Config->MinorImageVersion = M.MinorImageVersion;
501 if (M.MajorOSVersion)
502 Config->MajorOSVersion = M.MajorOSVersion;
503 if (M.MinorOSVersion)
504 Config->MinorOSVersion = M.MinorOSVersion;
505
506 for (COFFShortExport E1 : M.Exports) {
507 Export E2;
508 E2.Name = Saver.save(E1.Name);
509 if (E1.isWeak())
510 E2.ExtName = Saver.save(E1.ExtName);
511 E2.Ordinal = E1.Ordinal;
512 E2.Noname = E1.Noname;
513 E2.Data = E1.Data;
514 E2.Private = E1.Private;
515 E2.Constant = E1.Constant;
516 Config->Exports.push_back(E2);
517 }
518}
519
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000520std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000521 std::vector<MemoryBufferRef> V;
522 Error Err = Error::success();
523 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
524 Archive::Child C =
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000525 check(COrErr,
526 File->getFileName() + ": could not get the child of the archive");
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000527 MemoryBufferRef MBRef =
528 check(C.getMemoryBufferRef(),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000529 File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000530 ": could not get the buffer for a child of the archive");
531 V.push_back(MBRef);
532 }
533 if (Err)
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000534 fatal(File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000535 ": Archive::children failed: " + toString(std::move(Err)));
536 return V;
537}
538
539// A helper function for filterBitcodeFiles.
540static bool needsRebuilding(MemoryBufferRef MB) {
541 // The MSVC linker doesn't support thin archives, so if it's a thin
542 // archive, we always need to rebuild it.
543 std::unique_ptr<Archive> File =
544 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
545 if (File->isThin())
546 return true;
547
548 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000549 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000550 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
551 return true;
552 return false;
553}
554
555// Opens a given path as an archive file and removes bitcode files
556// from them if exists. This function is to appease the MSVC linker as
557// their linker doesn't like archive files containing non-native
558// object files.
559//
560// If a given archive doesn't contain bitcode files, the archive path
561// is returned as-is. Otherwise, a new temporary file is created and
562// its path is returned.
563static Optional<std::string>
564filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000565 std::unique_ptr<MemoryBuffer> MB = check(
566 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000567 MemoryBufferRef MBRef = MB->getMemBufferRef();
568 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000569
570 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000571 return None;
572 if (Magic != file_magic::archive)
573 return Path.str();
574 if (!needsRebuilding(MBRef))
575 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000576
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000577 std::unique_ptr<Archive> File =
578 check(Archive::create(MBRef),
579 MBRef.getBufferIdentifier() + ": failed to parse archive");
580
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000581 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000582 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000583 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
584 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000585
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000586 if (New.empty())
587 return None;
588
589 log("Creating a temporary archive for " + Path + " to remove bitcode files");
590
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000591 SmallString<128> S;
592 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
593 ".lib", S))
594 fatal(EC, "cannot create a temporary file");
595 std::string Temp = S.str();
596 TemporaryFiles.push_back(Temp);
597
598 std::pair<StringRef, std::error_code> Ret =
599 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
600 /*Deterministics=*/true,
601 /*Thin=*/false);
602 if (Ret.second)
603 error("failed to create a new archive " + S.str() + ": " + Ret.first);
604 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000605}
606
607// Create response file contents and invoke the MSVC linker.
608void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000609 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000610 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000611
Bob Haarman41108162017-04-21 21:38:01 +0000612 // Write out archive members that we used in symbol resolution and pass these
613 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
614 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000615 for (ObjFile *Obj : ObjFile::Instances) {
616 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000617 continue;
618 SmallString<128> S;
619 int Fd;
620 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000621 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarman41108162017-04-21 21:38:01 +0000622 fatal(EC, "cannot create a temporary file");
623 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000624 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000625 Temps.push_back(S.str());
626 Rsp += quote(S) + "\n";
627 }
628
Rui Ueyama85d54b02017-02-23 00:26:42 +0000629 for (auto *Arg : Args) {
630 switch (Arg->getOption().getID()) {
631 case OPT_linkrepro:
632 case OPT_lldmap:
633 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000634 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000635 case OPT_msvclto:
636 // LLD-specific options are stripped.
637 break;
638 case OPT_opt:
639 if (!StringRef(Arg->getValue()).startswith("lld"))
640 Rsp += toString(Arg) + " ";
641 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000642 case OPT_INPUT: {
643 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
644 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000645 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000646 continue;
647 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000648 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000649 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000650 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000651 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000652 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000653 }
654 }
655
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000656 std::vector<StringRef> ObjFiles = Symtab.compileBitcodeFiles();
657 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000658
659 for (StringRef Path : Temps)
660 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000661}
662
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000663void LinkerDriver::enqueueTask(std::function<void()> Task) {
664 TaskQueue.push_back(std::move(Task));
665}
666
667bool LinkerDriver::run() {
668 bool DidWork = !TaskQueue.empty();
669 while (!TaskQueue.empty()) {
670 TaskQueue.front()();
671 TaskQueue.pop_front();
672 }
673 return DidWork;
674}
675
Rui Ueyama8fe17672016-12-08 20:50:47 +0000676void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000677 // If the first command line argument is "/lib", link.exe acts like lib.exe.
678 // We call our own implementation of lib.exe that understands bitcode files.
679 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
680 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000681 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000682 return;
683 }
684
Peter Collingbourne60c16162015-06-01 20:10:10 +0000685 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000686 InitializeAllTargetInfos();
687 InitializeAllTargets();
688 InitializeAllTargetMCs();
689 InitializeAllAsmParsers();
690 InitializeAllAsmPrinters();
691 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000692
Rui Ueyama411c63602015-05-28 19:09:30 +0000693 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000694 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000695
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000696 // Parse and evaluate -mllvm options.
697 std::vector<const char *> V;
698 V.push_back("lld-link (LLVM option parsing)");
699 for (auto *Arg : Args.filtered(OPT_mllvm))
700 V.push_back(Arg->getValue());
701 cl::ParseCommandLineOptions(V.size(), V.data());
702
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000703 // Handle /errorlimit early, because error() depends on it.
704 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
705 int N = 20;
706 StringRef S = Arg->getValue();
707 if (S.getAsInteger(10, N))
708 error(Arg->getSpelling() + " number expected, but got " + S);
709 Config->ErrorLimit = N;
710 }
711
Rui Ueyama5c726432015-05-29 16:11:52 +0000712 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000713 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000714 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000715 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000716 }
717
Peter Collingbournefeee2102016-07-26 02:00:42 +0000718 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
719 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000720 sys::path::append(Path, "repro.tar");
721
722 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
723 TarWriter::create(Path, "repro");
724
725 if (ErrOrWriter) {
726 Tar = std::move(*ErrOrWriter);
727 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000728 error("/linkrepro: failed to open " + Path + ": " +
729 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000730 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000731 }
732
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000733 if (!Args.hasArgNoClaim(OPT_INPUT)) {
734 if (Args.hasArgNoClaim(OPT_deffile))
735 Config->NoEntry = true;
736 else
737 fatal("no input files");
738 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000739
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000740 // Construct search path list.
741 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000742 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000743 SearchPaths.push_back(Arg->getValue());
744 addLibSearchPaths();
745
Rui Ueyamaad660982015-06-07 00:20:32 +0000746 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000747 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000748 Config->OutputFile = Arg->getValue();
749
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000750 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000751 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000752 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000753
Rui Ueyama95925fd2015-06-28 19:35:15 +0000754 // Handle /force or /force:unresolved
755 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
756 Config->Force = true;
757
Rui Ueyama6600eb12015-07-04 23:37:32 +0000758 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000759 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000760 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000761 if (auto *Arg = Args.getLastArg(OPT_debugtype))
762 Config->DebugTypes = parseDebugType(Arg->getValue());
763 else
764 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000765 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000766
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000767 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000768 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000769 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000770
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000771 // Handle /noentry
772 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000773 if (Args.hasArg(OPT_dll))
774 Config->NoEntry = true;
775 else
776 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000777 }
778
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000779 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000780 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000781 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000782 Config->ManifestID = 2;
783 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000784
Rui Ueyama588e8322015-06-15 01:23:58 +0000785 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000786 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000787 if (Args.hasArg(OPT_dynamicbase)) {
788 error("/fixed must not be specified with /dynamicbase");
789 } else {
790 Config->Relocatable = false;
791 Config->DynamicBase = false;
792 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000793 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000794
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000795 if (Args.hasArg(OPT_appcontainer))
796 Config->AppContainer = true;
797
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000798 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000799 if (auto *Arg = Args.getLastArg(OPT_machine))
800 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000801
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000802 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000803 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000804 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
805
806 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000807 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000808 Config->NoDefaultLibAll = true;
809
Rui Ueyama804a8b62015-05-29 16:18:15 +0000810 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000811 if (auto *Arg = Args.getLastArg(OPT_base))
812 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000813
814 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000815 if (auto *Arg = Args.getLastArg(OPT_stack))
816 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000817
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000818 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000819 if (auto *Arg = Args.getLastArg(OPT_heap))
820 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000821
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000822 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000823 if (auto *Arg = Args.getLastArg(OPT_version))
824 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
825 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000826
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000827 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000828 if (auto *Arg = Args.getLastArg(OPT_subsystem))
829 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
830 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000831
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000832 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000833 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000834 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000835
Rui Ueyama08d5e182015-06-18 23:20:11 +0000836 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000837 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000838 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000839
Rui Ueyamab95188c2015-06-18 20:27:09 +0000840 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000841 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000842 Config->Implib = Arg->getValue();
843
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000844 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000845 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000846 std::string Str = StringRef(Arg->getValue()).lower();
847 SmallVector<StringRef, 1> Vec;
848 StringRef(Str).split(Vec, ',');
849 for (StringRef S : Vec) {
850 if (S == "noref") {
851 Config->DoGC = false;
852 Config->DoICF = false;
853 continue;
854 }
855 if (S == "icf" || StringRef(S).startswith("icf=")) {
856 Config->DoICF = true;
857 continue;
858 }
859 if (S == "noicf") {
860 Config->DoICF = false;
861 continue;
862 }
863 if (StringRef(S).startswith("lldlto=")) {
864 StringRef OptLevel = StringRef(S).substr(7);
865 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
866 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000867 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000868 continue;
869 }
870 if (StringRef(S).startswith("lldltojobs=")) {
871 StringRef Jobs = StringRef(S).substr(11);
872 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000873 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000874 continue;
875 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000876 if (StringRef(S).startswith("lldltopartitions=")) {
877 StringRef N = StringRef(S).substr(17);
878 if (N.getAsInteger(10, Config->LTOPartitions) ||
879 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000880 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000881 continue;
882 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000883 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000884 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000885 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000886 }
887
Bob Haarman69b196d2017-02-08 18:36:41 +0000888 // Handle /lldsavetemps
889 if (Args.hasArg(OPT_lldsavetemps))
890 Config->SaveTemps = true;
891
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000892 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000893 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000894 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000895
Rui Ueyama6600eb12015-07-04 23:37:32 +0000896 // Handle /merge
897 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000898 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000899
Rui Ueyama440138c2016-06-20 03:39:39 +0000900 // Handle /section
901 for (auto *Arg : Args.filtered(OPT_section))
902 parseSection(Arg->getValue());
903
Martin Storsjod2752aa2017-08-14 19:07:27 +0000904 // Handle /aligncomm
905 for (auto *Arg : Args.filtered(OPT_aligncomm))
906 parseAligncomm(Arg->getValue());
907
Nico Webera7a2c442017-07-25 18:08:03 +0000908 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
909 // also passed.
910 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
911 Config->ManifestDependency = Arg->getValue();
912 Config->Manifest = Configuration::SideBySide;
913 }
914
915 // Handle /manifest and /manifest:
916 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
917 if (Arg->getOption().getID() == OPT_manifest)
918 Config->Manifest = Configuration::SideBySide;
919 else
920 parseManifest(Arg->getValue());
921 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000922
923 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000924 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
925 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000926
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000927 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000928 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000929 Config->ManifestFile = Arg->getValue();
930
Rui Ueyamaafb19012016-04-19 01:21:58 +0000931 // Handle /manifestinput
932 for (auto *Arg : Args.filtered(OPT_manifestinput))
933 Config->ManifestInput.push_back(Arg->getValue());
934
Nico Webera7a2c442017-07-25 18:08:03 +0000935 if (!Config->ManifestInput.empty() &&
936 Config->Manifest != Configuration::Embed) {
937 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
938 }
939
Rui Ueyama6592ff82015-06-16 23:13:00 +0000940 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000941 if (Args.hasArg(OPT_allowisolation_no))
942 Config->AllowIsolation = false;
943 if (Args.hasArg(OPT_dynamicbase_no))
944 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000945 if (Args.hasArg(OPT_nxcompat_no))
946 Config->NxCompat = false;
947 if (Args.hasArg(OPT_tsaware_no))
948 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000949 if (Args.hasArg(OPT_nosymtab))
950 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000951
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000952 Config->MapFile = getMapFile(Args);
953
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000954 if (ErrorCount)
955 return;
956
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000957 // Create a list of input files. Files can be given as arguments
958 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000959 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000960 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000961 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000962 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000963 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000964 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000965 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000966
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000967 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000968 if (Config->Manifest == Configuration::Embed)
969 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000970
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000971 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000972 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000973
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000974 // We should have inferred a machine type by now from the input files, but if
975 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000976 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000977 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000978 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000979 }
980
Eric Beckmann9e19d792017-06-17 02:26:27 +0000981 // Input files can be Windows resource files (.res files). We use
982 // WindowsResource to convert resource files to a regular COFF file,
983 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000984 if (!Resources.empty())
985 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000986
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000987 if (Tar)
988 Tar->append("response.txt",
989 createResponseFile(Args, FilePaths,
990 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000991
Rui Ueyama4d545342015-07-28 03:12:00 +0000992 // Handle /largeaddressaware
993 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
994 Config->LargeAddressAware = true;
995
Rui Ueyamad68e2112015-07-28 03:15:57 +0000996 // Handle /highentropyva
997 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
998 Config->HighEntropyVA = true;
999
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001000 // Handle /entry and /dll
1001 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1002 Config->Entry = addUndefined(mangle(Arg->getValue()));
1003 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +00001004 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1005 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001006 Config->Entry = addUndefined(S);
1007 } else if (!Config->NoEntry) {
1008 // Windows specific -- If entry point name is not given, we need to
1009 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001010 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001011 if (S.empty())
1012 fatal("entry point must be defined");
1013 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001014 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001015 }
1016
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001017 // Handle /export
1018 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001019 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001020 if (Config->Machine == I386) {
1021 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001022 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001023 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001024 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001025 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001026 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001027 }
1028
1029 // Handle /def
1030 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001031 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001032 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001033 }
1034
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001035 // Handle generation of import library from a def file.
1036 if (!Args.hasArgNoClaim(OPT_INPUT)) {
1037 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001038 createImportLibrary(/*AsLib=*/true);
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001039 exit(0);
1040 }
1041
Rui Ueyama6d249082015-07-13 22:31:45 +00001042 // Handle /delayload
1043 for (auto *Arg : Args.filtered(OPT_delayload)) {
1044 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001045 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001046 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001047 } else {
1048 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001049 }
1050 }
1051
Reid Kleckner7668182e2017-03-21 00:12:51 +00001052 // Set default image name if neither /out or /def set it.
1053 if (Config->OutputFile.empty()) {
1054 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001055 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001056 }
1057
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001058 // Put the PDB next to the image if no /pdb flag was passed.
1059 if (Config->Debug && Config->PDBPath.empty()) {
1060 Config->PDBPath = Config->OutputFile;
1061 sys::path::replace_extension(Config->PDBPath, ".pdb");
1062 }
1063
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001064 // Disable PDB generation if the user requested it.
1065 if (Args.hasArg(OPT_nopdb))
1066 Config->PDBPath = "";
1067
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001068 // Set default image base if /base is not given.
1069 if (Config->ImageBase == uint64_t(-1))
1070 Config->ImageBase = getDefaultImageBase();
1071
Reid Kleckner502d4ce2017-06-26 15:39:52 +00001072 Symtab.addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001073 if (Config->Machine == I386) {
Reid Kleckner502d4ce2017-06-26 15:39:52 +00001074 Symtab.addAbsolute("___safe_se_handler_table", 0);
1075 Symtab.addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001076 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001077
Rui Ueyama107db552015-08-09 21:01:06 +00001078 // We do not support /guard:cf (control flow protection) yet.
1079 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyama107db552015-08-09 21:01:06 +00001080 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
Rui Ueyama2f740f72017-06-21 02:26:19 +00001081 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001082 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
Rui Ueyama2f740f72017-06-21 02:26:19 +00001083 Symtab.addAbsolute(mangle("__guard_iat_count"), 0);
1084 Symtab.addAbsolute(mangle("__guard_iat_table"), 0);
1085 Symtab.addAbsolute(mangle("__guard_longjmp_count"), 0);
1086 Symtab.addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001087
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001088 // This code may add new undefined symbols to the link, which may enqueue more
1089 // symbol resolution tasks, so we need to continue executing tasks until we
1090 // converge.
1091 do {
1092 // Windows specific -- if entry point is not found,
1093 // search for its mangled names.
1094 if (Config->Entry)
1095 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001096
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001097 // Windows specific -- Make sure we resolve all dllexported symbols.
1098 for (Export &E : Config->Exports) {
1099 if (!E.ForwardTo.empty())
1100 continue;
1101 E.Sym = addUndefined(E.Name);
1102 if (!E.Directives)
1103 Symtab.mangleMaybe(E.Sym);
1104 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001105
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001106 // Add weak aliases. Weak aliases is a mechanism to give remaining
1107 // undefined symbols final chance to be resolved successfully.
1108 for (auto Pair : Config->AlternateNames) {
1109 StringRef From = Pair.first;
1110 StringRef To = Pair.second;
1111 Symbol *Sym = Symtab.find(From);
1112 if (!Sym)
1113 continue;
1114 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1115 if (!U->WeakAlias)
1116 U->WeakAlias = Symtab.addUndefined(To);
1117 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001118
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001119 // Windows specific -- if __load_config_used can be resolved, resolve it.
1120 if (Symtab.findUnderscore("_load_config_used"))
1121 addUndefined(mangle("_load_config_used"));
1122 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001123
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001124 if (ErrorCount)
1125 return;
1126
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001127 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1128 // This is useful because MSVC link.exe can generate complete PDBs.
1129 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001130 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001131 exit(0);
1132 }
1133
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001134 // Do LTO by compiling bitcode input files to a set of native COFF files then
1135 // link those files.
1136 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001137 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001138
Peter Collingbourne2612a322015-07-04 05:28:41 +00001139 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +00001140 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +00001141
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001142 // Windows specific -- if no /subsystem is given, we need to infer
1143 // that from entry point name.
1144 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001145 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001146 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001147 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001148 }
1149
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001150 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001151 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001152 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001153 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001154 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1155 if (ErrorCount)
1156 return;
1157 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001158
Rui Ueyama151d8622015-06-17 20:40:43 +00001159 // Windows specific -- when we are creating a .dll file, we also
1160 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001161 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001162 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001163 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001164 assignExportOrdinals();
1165 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001166
Martin Storsjod2752aa2017-08-14 19:07:27 +00001167 // Set extra alignment for .comm symbols
1168 for (auto Pair : Config->AlignComm) {
1169 StringRef Name = Pair.first;
1170 int Align = Pair.second;
1171 Symbol *Sym = Symtab.find(Name);
1172 if (!Sym) {
1173 warn("/aligncomm symbol " + Name + " not found");
1174 continue;
1175 }
1176 auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1177 if (!DC) {
1178 warn("/aligncomm symbol " + Name + " of wrong kind");
1179 continue;
1180 }
1181 DC->getChunk()->setAlign(Align);
1182 }
1183
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001184 // Windows specific -- Create a side-by-side manifest file.
1185 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001186 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001187
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001188 // Identify unreferenced COMDAT sections.
1189 if (Config->DoGC)
1190 markLive(Symtab.getChunks());
1191
1192 // Identify identical COMDAT sections to merge them.
1193 if (Config->DoICF)
1194 doICF(Symtab.getChunks());
1195
Rui Ueyama411c63602015-05-28 19:09:30 +00001196 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +00001197 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +00001198
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001199 // Call exit to avoid calling destructors.
1200 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001201}
1202
Rui Ueyama411c63602015-05-28 19:09:30 +00001203} // namespace coff
1204} // namespace lld