blob: 6fde6313ff00ee4cdbf9055cffa77e671be878c3 [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 Ueyamacbf969e2017-08-28 21:51:07 +000058
Rui Ueyama7fed58c2016-12-08 19:10:28 +000059 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000060 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyama8bee41e2017-08-24 20:32:58 +000061 Config->ColorDiagnostics = ErrorOS->has_colors();
Rui Ueyamacbf969e2017-08-28 21:51:07 +000062
63 Symtab = make<SymbolTable>();
64
Rui Ueyama7fed58c2016-12-08 19:10:28 +000065 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000066 Driver->link(Args);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +000067 return !ErrorCount;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000068}
Rui Ueyama411c63602015-05-28 19:09:30 +000069
Nico Weber5660de72016-04-20 22:34:15 +000070// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000071static std::string getOutputPath(StringRef Path) {
72 auto P = Path.find_last_of("\\/");
73 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000074 const char* E = Config->DLL ? ".dll" : ".exe";
75 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000076}
77
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000078// ErrorOr is not default constructible, so it cannot be used as the type
79// parameter of a future.
80// FIXME: We could open the file in createFutureForFile and avoid needing to
81// return an error here, but for the moment that would cost us a file descriptor
82// (a limited resource on Windows) for the duration that the future is pending.
83typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
84
85// Create a std::future that opens and maps a file using the best strategy for
86// the host platform.
87static std::future<MBErrPair> createFutureForFile(std::string Path) {
88#if LLVM_ON_WIN32
89 // On Windows, file I/O is relatively slow so it is best to do this
90 // asynchronously.
91 auto Strategy = std::launch::async;
92#else
93 auto Strategy = std::launch::deferred;
94#endif
95 return std::async(Strategy, [=]() {
96 auto MBOrErr = MemoryBuffer::getFile(Path);
97 if (!MBOrErr)
98 return MBErrPair{nullptr, MBOrErr.getError()};
99 return MBErrPair{std::move(*MBOrErr), std::error_code()};
100 });
101}
102
103MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
104 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000105 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000106
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000107 if (Driver->Tar)
108 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
109 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000110 return MBRef;
111}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000112
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000113void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
114 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000115
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000116 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000117 file_magic Magic = identify_magic(MBRef.getBuffer());
118 if (Magic == file_magic::windows_resource) {
119 Resources.push_back(MBRef);
120 return;
121 }
122
123 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000124 if (Magic == file_magic::archive)
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000125 return Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000126 if (Magic == file_magic::bitcode)
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000127 return Symtab->addFile(make<BitcodeFile>(MBRef));
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000128
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000129 if (Magic == file_magic::coff_cl_gl_object)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000130 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000131 "Recompile without /GL");
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000132 else
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000133 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000134}
135
136void LinkerDriver::enqueuePath(StringRef Path) {
137 auto Future =
138 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
139 std::string PathStr = Path;
140 enqueueTask([=]() {
141 auto MBOrErr = Future->get();
142 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000143 error("could not open " + PathStr + ": " + MBOrErr.second.message());
144 else
145 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000146 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000147}
148
149void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
150 StringRef ParentName) {
151 file_magic Magic = identify_magic(MB.getBuffer());
152 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000153 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000154 return;
155 }
156
157 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000158 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000159 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000160 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000161 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000162 } else {
163 error("unknown file type: " + MB.getBufferIdentifier());
164 return;
165 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000166
167 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000168 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000169 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000170}
171
172void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
173 StringRef SymName,
174 StringRef ParentName) {
175 if (!C.getParent()->isThin()) {
176 MemoryBufferRef MB = check(
177 C.getMemoryBufferRef(),
178 "could not get the buffer for the member defining symbol " + SymName);
179 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
180 return;
181 }
182
183 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
184 check(C.getFullName(),
185 "could not get the filename for the member defining symbol " +
186 SymName)));
187 enqueueTask([=]() {
188 auto MBOrErr = Future->get();
189 if (MBOrErr.second)
190 fatal(MBOrErr.second,
191 "could not get the buffer for the member defining " + SymName);
192 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
193 ParentName);
194 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000195}
196
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000197static bool isDecorated(StringRef Sym) {
198 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
199}
200
Rui Ueyama411c63602015-05-28 19:09:30 +0000201// Parses .drectve section contents and returns a list of files
202// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000203void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000204 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000205 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000206 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000207
David Blaikie6521ed92015-06-22 22:06:52 +0000208 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000209 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000210 case OPT_aligncomm:
211 parseAligncomm(Arg->getValue());
212 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000213 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000214 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000215 break;
216 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000217 if (Optional<StringRef> Path = findLib(Arg->getValue()))
218 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000219 break;
220 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000221 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000222 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000223 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000224 break;
225 }
226 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000227 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000228 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000229 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000230 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000231 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000232 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000233 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000234 break;
235 case OPT_nodefaultlib:
236 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
237 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000238 case OPT_section:
239 parseSection(Arg->getValue());
240 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000241 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000242 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000243 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000244 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000245 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000246 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000247 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000248 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000249 }
250 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000251}
252
Rui Ueyama54b71da2015-05-31 19:17:12 +0000253// Find file from search paths. You can omit ".obj", this function takes
254// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000255StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000256 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
257 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000258 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000259 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000260 for (StringRef Dir : SearchPaths) {
261 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000262 sys::path::append(Path, Filename);
263 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000264 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000265 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000266 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000267 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000268 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000269 }
270 }
271 return Filename;
272}
273
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000274// Resolves a file path. This never returns the same path
275// (in that case, it returns None).
276Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
277 StringRef Path = doFindFile(Filename);
278 bool Seen = !VisitedFiles.insert(Path.lower()).second;
279 if (Seen)
280 return None;
281 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000282}
283
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000284// Find library file from search path.
285StringRef LinkerDriver::doFindLib(StringRef Filename) {
286 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000287 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000288 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000289 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000290 return doFindFile(Filename);
291}
292
293// Resolves a library path. /nodefaultlib options are taken into
294// consideration. This never returns the same path (in that case,
295// it returns None).
296Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
297 if (Config->NoDefaultLibAll)
298 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000299 if (!VisitedLibs.insert(Filename.lower()).second)
300 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000301 StringRef Path = doFindLib(Filename);
302 if (Config->NoDefaultLibs.count(Path))
303 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000304 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000305 return None;
306 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000307}
308
309// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000310void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000311 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
312 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000313 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000314 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000315 while (!Env.empty()) {
316 StringRef Path;
317 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000318 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000319 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000320}
321
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000322SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000323 SymbolBody *B = Symtab->addUndefined(Name);
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000324 Config->GCRoot.insert(B);
325 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000326}
327
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000328// Symbol names are mangled by appending "_" prefix on x86.
329StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000330 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
331 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000332 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000333 return Sym;
334}
335
Rui Ueyama45044f42015-06-29 01:03:53 +0000336// Windows specific -- find default entry point name.
337StringRef LinkerDriver::findDefaultEntry() {
338 // User-defined main functions and their corresponding entry points.
339 static const char *Entries[][2] = {
340 {"main", "mainCRTStartup"},
341 {"wmain", "wmainCRTStartup"},
342 {"WinMain", "WinMainCRTStartup"},
343 {"wWinMain", "wWinMainCRTStartup"},
344 };
345 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000346 StringRef Entry = Symtab->findMangle(mangle(E[0]));
347 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000348 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000349 }
350 return "";
351}
352
353WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000354 if (Config->DLL)
355 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000356 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000357 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000358 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000359 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
360 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000361}
362
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000363static uint64_t getDefaultImageBase() {
364 if (Config->is64())
365 return Config->DLL ? 0x180000000 : 0x140000000;
366 return Config->DLL ? 0x10000000 : 0x400000;
367}
368
Rui Ueyama8fe17672016-12-08 20:50:47 +0000369static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000370 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000371 ArrayRef<StringRef> SearchPaths) {
372 SmallString<0> Data;
373 raw_svector_ostream OS(Data);
374
375 for (auto *Arg : Args) {
376 switch (Arg->getOption().getID()) {
377 case OPT_linkrepro:
378 case OPT_INPUT:
379 case OPT_defaultlib:
380 case OPT_libpath:
381 break;
382 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000383 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000384 }
385 }
386
387 for (StringRef Path : SearchPaths) {
388 std::string RelPath = relativeToRoot(Path);
389 OS << "/libpath:" << quote(RelPath) << "\n";
390 }
391
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000392 for (StringRef Path : FilePaths)
393 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000394
395 return Data.str();
396}
397
Rui Ueyama8fe17672016-12-08 20:50:47 +0000398static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000399 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
400 if (Args.hasArg(OPT_driver))
401 DebugTypes |= static_cast<unsigned>(DebugType::PData);
402 if (Args.hasArg(OPT_profile))
403 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
404 return DebugTypes;
405}
406
407static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000408 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000409 Arg.split(Types, ',', /*KeepEmpty=*/false);
410
411 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
412 for (StringRef Type : Types)
413 DebugTypes |= StringSwitch<unsigned>(Type.lower())
414 .Case("cv", static_cast<unsigned>(DebugType::CV))
415 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000416 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
417 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000418 return DebugTypes;
419}
420
Hans Wennborg1818e652016-12-09 20:54:44 +0000421static std::string getMapFile(const opt::InputArgList &Args) {
422 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
423 if (!Arg)
424 return "";
425 if (Arg->getOption().getID() == OPT_lldmap_file)
426 return Arg->getValue();
427
428 assert(Arg->getOption().getID() == OPT_lldmap);
429 StringRef OutFile = Config->OutputFile;
430 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
431}
432
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000433static std::string getImplibPath() {
434 if (!Config->Implib.empty())
435 return Config->Implib;
436 SmallString<128> Out = StringRef(Config->OutputFile);
437 sys::path::replace_extension(Out, ".lib");
438 return Out.str();
439}
440
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000441//
442// The import name is caculated as the following:
443//
444// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
445// -----+----------------+---------------------+------------------
446// LINK | {value} | {value}.{.dll/.exe} | {output name}
447// LIB | {value} | {value}.dll | {output name}.dll
448//
449static std::string getImportName(bool AsLib) {
450 SmallString<128> Out;
451
452 if (Config->ImportName.empty()) {
453 Out.assign(sys::path::filename(Config->OutputFile));
454 if (AsLib)
455 sys::path::replace_extension(Out, ".dll");
456 } else {
457 Out.assign(Config->ImportName);
458 if (!sys::path::has_extension(Out))
459 sys::path::replace_extension(Out,
460 (Config->DLL || AsLib) ? ".dll" : ".exe");
461 }
462
463 return Out.str();
464}
465
466static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000467 std::vector<COFFShortExport> Exports;
468 for (Export &E1 : Config->Exports) {
469 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000470 E2.Name = E1.Name;
471 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000472 E2.ExtName = E1.ExtName;
473 E2.Ordinal = E1.Ordinal;
474 E2.Noname = E1.Noname;
475 E2.Data = E1.Data;
476 E2.Private = E1.Private;
477 E2.Constant = E1.Constant;
478 Exports.push_back(E2);
479 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000480
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000481 writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
Martin Storsjo92f32d02017-08-16 05:23:00 +0000482 Config->Machine, false);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000483}
484
485static void parseModuleDefs(StringRef Path) {
486 std::unique_ptr<MemoryBuffer> MB = check(
487 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyama67aea7372017-06-08 23:43:44 +0000488 COFFModuleDefinition M =
489 check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000490
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000491 if (Config->OutputFile.empty())
492 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000493 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000494 if (M.ImageBase)
495 Config->ImageBase = M.ImageBase;
496 if (M.StackReserve)
497 Config->StackReserve = M.StackReserve;
498 if (M.StackCommit)
499 Config->StackCommit = M.StackCommit;
500 if (M.HeapReserve)
501 Config->HeapReserve = M.HeapReserve;
502 if (M.HeapCommit)
503 Config->HeapCommit = M.HeapCommit;
504 if (M.MajorImageVersion)
505 Config->MajorImageVersion = M.MajorImageVersion;
506 if (M.MinorImageVersion)
507 Config->MinorImageVersion = M.MinorImageVersion;
508 if (M.MajorOSVersion)
509 Config->MajorOSVersion = M.MajorOSVersion;
510 if (M.MinorOSVersion)
511 Config->MinorOSVersion = M.MinorOSVersion;
512
513 for (COFFShortExport E1 : M.Exports) {
514 Export E2;
515 E2.Name = Saver.save(E1.Name);
516 if (E1.isWeak())
517 E2.ExtName = Saver.save(E1.ExtName);
518 E2.Ordinal = E1.Ordinal;
519 E2.Noname = E1.Noname;
520 E2.Data = E1.Data;
521 E2.Private = E1.Private;
522 E2.Constant = E1.Constant;
523 Config->Exports.push_back(E2);
524 }
525}
526
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000527// A helper function for filterBitcodeFiles.
528static bool needsRebuilding(MemoryBufferRef MB) {
529 // The MSVC linker doesn't support thin archives, so if it's a thin
530 // archive, we always need to rebuild it.
531 std::unique_ptr<Archive> File =
532 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
533 if (File->isThin())
534 return true;
535
536 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000537 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000538 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
539 return true;
540 return false;
541}
542
543// Opens a given path as an archive file and removes bitcode files
544// from them if exists. This function is to appease the MSVC linker as
545// their linker doesn't like archive files containing non-native
546// object files.
547//
548// If a given archive doesn't contain bitcode files, the archive path
549// is returned as-is. Otherwise, a new temporary file is created and
550// its path is returned.
551static Optional<std::string>
552filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000553 std::unique_ptr<MemoryBuffer> MB = check(
554 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000555 MemoryBufferRef MBRef = MB->getMemBufferRef();
556 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000557
558 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000559 return None;
560 if (Magic != file_magic::archive)
561 return Path.str();
562 if (!needsRebuilding(MBRef))
563 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000564
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000565 std::unique_ptr<Archive> File =
566 check(Archive::create(MBRef),
567 MBRef.getBufferIdentifier() + ": failed to parse archive");
568
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000569 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000570 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000571 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
572 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000573
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000574 if (New.empty())
575 return None;
576
577 log("Creating a temporary archive for " + Path + " to remove bitcode files");
578
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000579 SmallString<128> S;
580 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
581 ".lib", S))
582 fatal(EC, "cannot create a temporary file");
583 std::string Temp = S.str();
584 TemporaryFiles.push_back(Temp);
585
Rui Ueyama01d02652017-08-30 22:11:03 +0000586 std::error_code EC =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000587 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
588 /*Deterministics=*/true,
589 /*Thin=*/false);
Rui Ueyama01d02652017-08-30 22:11:03 +0000590 if (EC)
591 error("failed to create a new archive " + S.str() + ": " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000592 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000593}
594
595// Create response file contents and invoke the MSVC linker.
596void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000597 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000598 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000599
Bob Haarman41108162017-04-21 21:38:01 +0000600 // Write out archive members that we used in symbol resolution and pass these
601 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
602 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000603 for (ObjFile *Obj : ObjFile::Instances) {
604 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000605 continue;
606 SmallString<128> S;
607 int Fd;
608 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000609 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarman41108162017-04-21 21:38:01 +0000610 fatal(EC, "cannot create a temporary file");
611 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000612 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000613 Temps.push_back(S.str());
614 Rsp += quote(S) + "\n";
615 }
616
Rui Ueyama85d54b02017-02-23 00:26:42 +0000617 for (auto *Arg : Args) {
618 switch (Arg->getOption().getID()) {
619 case OPT_linkrepro:
620 case OPT_lldmap:
621 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000622 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000623 case OPT_msvclto:
624 // LLD-specific options are stripped.
625 break;
626 case OPT_opt:
627 if (!StringRef(Arg->getValue()).startswith("lld"))
628 Rsp += toString(Arg) + " ";
629 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000630 case OPT_INPUT: {
631 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
632 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000633 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000634 continue;
635 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000636 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000637 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000638 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000639 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000640 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000641 }
642 }
643
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000644 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000645 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000646
647 for (StringRef Path : Temps)
648 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000649}
650
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000651void LinkerDriver::enqueueTask(std::function<void()> Task) {
652 TaskQueue.push_back(std::move(Task));
653}
654
655bool LinkerDriver::run() {
656 bool DidWork = !TaskQueue.empty();
657 while (!TaskQueue.empty()) {
658 TaskQueue.front()();
659 TaskQueue.pop_front();
660 }
661 return DidWork;
662}
663
Rui Ueyama8fe17672016-12-08 20:50:47 +0000664void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000665 // If the first command line argument is "/lib", link.exe acts like lib.exe.
666 // We call our own implementation of lib.exe that understands bitcode files.
667 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
668 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000669 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000670 return;
671 }
672
Peter Collingbourne60c16162015-06-01 20:10:10 +0000673 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000674 InitializeAllTargetInfos();
675 InitializeAllTargets();
676 InitializeAllTargetMCs();
677 InitializeAllAsmParsers();
678 InitializeAllAsmPrinters();
679 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000680
Rui Ueyama411c63602015-05-28 19:09:30 +0000681 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000682 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000683 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000684
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000685 // Parse and evaluate -mllvm options.
686 std::vector<const char *> V;
687 V.push_back("lld-link (LLVM option parsing)");
688 for (auto *Arg : Args.filtered(OPT_mllvm))
689 V.push_back(Arg->getValue());
690 cl::ParseCommandLineOptions(V.size(), V.data());
691
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000692 // Handle /errorlimit early, because error() depends on it.
693 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
694 int N = 20;
695 StringRef S = Arg->getValue();
696 if (S.getAsInteger(10, N))
697 error(Arg->getSpelling() + " number expected, but got " + S);
698 Config->ErrorLimit = N;
699 }
700
Rui Ueyama5c726432015-05-29 16:11:52 +0000701 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000702 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000703 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000704 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000705 }
706
Peter Collingbournefeee2102016-07-26 02:00:42 +0000707 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
708 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000709 sys::path::append(Path, "repro.tar");
710
711 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
712 TarWriter::create(Path, "repro");
713
714 if (ErrOrWriter) {
715 Tar = std::move(*ErrOrWriter);
716 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000717 error("/linkrepro: failed to open " + Path + ": " +
718 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000719 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000720 }
721
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000722 if (!Args.hasArgNoClaim(OPT_INPUT)) {
723 if (Args.hasArgNoClaim(OPT_deffile))
724 Config->NoEntry = true;
725 else
726 fatal("no input files");
727 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000728
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000729 // Construct search path list.
730 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000731 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000732 SearchPaths.push_back(Arg->getValue());
733 addLibSearchPaths();
734
Rui Ueyamaad660982015-06-07 00:20:32 +0000735 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000736 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000737 Config->OutputFile = Arg->getValue();
738
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000739 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000740 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000741 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000742
Rui Ueyama95925fd2015-06-28 19:35:15 +0000743 // Handle /force or /force:unresolved
744 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
745 Config->Force = true;
746
Rui Ueyama6600eb12015-07-04 23:37:32 +0000747 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000748 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000749 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000750 if (auto *Arg = Args.getLastArg(OPT_debugtype))
751 Config->DebugTypes = parseDebugType(Arg->getValue());
752 else
753 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000754 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000755
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000756 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000757 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000758 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000759
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000760 // Handle /noentry
761 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000762 if (Args.hasArg(OPT_dll))
763 Config->NoEntry = true;
764 else
765 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000766 }
767
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000768 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000769 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000770 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000771 Config->ManifestID = 2;
772 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000773
Rui Ueyama588e8322015-06-15 01:23:58 +0000774 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000775 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000776 if (Args.hasArg(OPT_dynamicbase)) {
777 error("/fixed must not be specified with /dynamicbase");
778 } else {
779 Config->Relocatable = false;
780 Config->DynamicBase = false;
781 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000782 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000783
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000784 if (Args.hasArg(OPT_appcontainer))
785 Config->AppContainer = true;
786
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000787 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000788 if (auto *Arg = Args.getLastArg(OPT_machine))
789 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000790
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000791 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000792 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000793 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
794
795 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000796 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000797 Config->NoDefaultLibAll = true;
798
Rui Ueyama804a8b62015-05-29 16:18:15 +0000799 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000800 if (auto *Arg = Args.getLastArg(OPT_base))
801 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000802
803 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000804 if (auto *Arg = Args.getLastArg(OPT_stack))
805 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000806
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000807 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000808 if (auto *Arg = Args.getLastArg(OPT_heap))
809 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000810
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000811 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000812 if (auto *Arg = Args.getLastArg(OPT_version))
813 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
814 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000815
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000816 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000817 if (auto *Arg = Args.getLastArg(OPT_subsystem))
818 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
819 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000820
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000821 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000822 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000823 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000824
Rui Ueyama08d5e182015-06-18 23:20:11 +0000825 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000826 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000827 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000828
Rui Ueyamab95188c2015-06-18 20:27:09 +0000829 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000830 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000831 Config->Implib = Arg->getValue();
832
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000833 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000834 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000835 std::string Str = StringRef(Arg->getValue()).lower();
836 SmallVector<StringRef, 1> Vec;
837 StringRef(Str).split(Vec, ',');
838 for (StringRef S : Vec) {
839 if (S == "noref") {
840 Config->DoGC = false;
841 Config->DoICF = false;
842 continue;
843 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000844 if (S == "icf" || S.startswith("icf=")) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000845 Config->DoICF = true;
846 continue;
847 }
848 if (S == "noicf") {
849 Config->DoICF = false;
850 continue;
851 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000852 if (S.startswith("lldlto=")) {
853 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000854 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
855 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000856 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000857 continue;
858 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000859 if (S.startswith("lldltojobs=")) {
860 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000861 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000862 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000863 continue;
864 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000865 if (S.startswith("lldltopartitions=")) {
866 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000867 if (N.getAsInteger(10, Config->LTOPartitions) ||
868 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000869 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000870 continue;
871 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000872 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000873 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000874 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000875 }
876
Bob Haarman69b196d2017-02-08 18:36:41 +0000877 // Handle /lldsavetemps
878 if (Args.hasArg(OPT_lldsavetemps))
879 Config->SaveTemps = true;
880
Peter Collingbourne052e855e2017-09-08 00:50:50 +0000881 // Handle /lldltocache
882 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
883 Config->LTOCache = Arg->getValue();
884
885 // Handle /lldsavecachepolicy
886 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
887 Config->LTOCachePolicy = check(
888 parseCachePruningPolicy(Arg->getValue()),
889 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
890
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000891 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000892 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000893 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000894
Rui Ueyama6600eb12015-07-04 23:37:32 +0000895 // Handle /merge
896 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000897 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000898
Rui Ueyama440138c2016-06-20 03:39:39 +0000899 // Handle /section
900 for (auto *Arg : Args.filtered(OPT_section))
901 parseSection(Arg->getValue());
902
Martin Storsjod2752aa2017-08-14 19:07:27 +0000903 // Handle /aligncomm
904 for (auto *Arg : Args.filtered(OPT_aligncomm))
905 parseAligncomm(Arg->getValue());
906
Nico Webera7a2c442017-07-25 18:08:03 +0000907 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
908 // also passed.
909 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
910 Config->ManifestDependency = Arg->getValue();
911 Config->Manifest = Configuration::SideBySide;
912 }
913
914 // Handle /manifest and /manifest:
915 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
916 if (Arg->getOption().getID() == OPT_manifest)
917 Config->Manifest = Configuration::SideBySide;
918 else
919 parseManifest(Arg->getValue());
920 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000921
922 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000923 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
924 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000925
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000926 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000927 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000928 Config->ManifestFile = Arg->getValue();
929
Rui Ueyamaafb19012016-04-19 01:21:58 +0000930 // Handle /manifestinput
931 for (auto *Arg : Args.filtered(OPT_manifestinput))
932 Config->ManifestInput.push_back(Arg->getValue());
933
Nico Webera7a2c442017-07-25 18:08:03 +0000934 if (!Config->ManifestInput.empty() &&
935 Config->Manifest != Configuration::Embed) {
936 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
937 }
938
Rui Ueyama6592ff82015-06-16 23:13:00 +0000939 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000940 if (Args.hasArg(OPT_allowisolation_no))
941 Config->AllowIsolation = false;
942 if (Args.hasArg(OPT_dynamicbase_no))
943 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000944 if (Args.hasArg(OPT_nxcompat_no))
945 Config->NxCompat = false;
946 if (Args.hasArg(OPT_tsaware_no))
947 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000948 if (Args.hasArg(OPT_nosymtab))
949 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000950
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000951 Config->MapFile = getMapFile(Args);
952
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000953 if (ErrorCount)
954 return;
955
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000956 // Create a list of input files. Files can be given as arguments
957 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000958 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000959 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000960 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000961 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000962 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000963 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000964 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000965
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000966 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000967 if (Config->Manifest == Configuration::Embed)
968 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000969
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000970 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000971 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000972
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000973 // We should have inferred a machine type by now from the input files, but if
974 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000975 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000976 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000977 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000978 }
979
Eric Beckmann9e19d792017-06-17 02:26:27 +0000980 // Input files can be Windows resource files (.res files). We use
981 // WindowsResource to convert resource files to a regular COFF file,
982 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000983 if (!Resources.empty())
984 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000985
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000986 if (Tar)
987 Tar->append("response.txt",
988 createResponseFile(Args, FilePaths,
989 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000990
Rui Ueyama4d545342015-07-28 03:12:00 +0000991 // Handle /largeaddressaware
992 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
993 Config->LargeAddressAware = true;
994
Rui Ueyamad68e2112015-07-28 03:15:57 +0000995 // Handle /highentropyva
996 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
997 Config->HighEntropyVA = true;
998
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000999 // Handle /entry and /dll
1000 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1001 Config->Entry = addUndefined(mangle(Arg->getValue()));
1002 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +00001003 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1004 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001005 Config->Entry = addUndefined(S);
1006 } else if (!Config->NoEntry) {
1007 // Windows specific -- If entry point name is not given, we need to
1008 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001009 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001010 if (S.empty())
1011 fatal("entry point must be defined");
1012 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001013 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001014 }
1015
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001016 // Handle /export
1017 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001018 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001019 if (Config->Machine == I386) {
1020 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001021 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001022 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001023 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001024 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001025 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001026 }
1027
1028 // Handle /def
1029 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001030 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001031 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001032 }
1033
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001034 // Handle generation of import library from a def file.
1035 if (!Args.hasArgNoClaim(OPT_INPUT)) {
1036 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001037 createImportLibrary(/*AsLib=*/true);
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001038 exit(0);
1039 }
1040
Rui Ueyama6d249082015-07-13 22:31:45 +00001041 // Handle /delayload
1042 for (auto *Arg : Args.filtered(OPT_delayload)) {
1043 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001044 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001045 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001046 } else {
1047 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001048 }
1049 }
1050
Reid Kleckner7668182e2017-03-21 00:12:51 +00001051 // Set default image name if neither /out or /def set it.
1052 if (Config->OutputFile.empty()) {
1053 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001054 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001055 }
1056
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001057 // Put the PDB next to the image if no /pdb flag was passed.
1058 if (Config->Debug && Config->PDBPath.empty()) {
1059 Config->PDBPath = Config->OutputFile;
1060 sys::path::replace_extension(Config->PDBPath, ".pdb");
1061 }
1062
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001063 // Disable PDB generation if the user requested it.
1064 if (Args.hasArg(OPT_nopdb))
1065 Config->PDBPath = "";
1066
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001067 // Set default image base if /base is not given.
1068 if (Config->ImageBase == uint64_t(-1))
1069 Config->ImageBase = getDefaultImageBase();
1070
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001071 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001072 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001073 Symtab->addAbsolute("___safe_se_handler_table", 0);
1074 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001075 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001076
Rui Ueyama107db552015-08-09 21:01:06 +00001077 // We do not support /guard:cf (control flow protection) yet.
1078 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001079 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1080 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1081 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1082 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1083 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1084 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1085 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001086
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001087 // This code may add new undefined symbols to the link, which may enqueue more
1088 // symbol resolution tasks, so we need to continue executing tasks until we
1089 // converge.
1090 do {
1091 // Windows specific -- if entry point is not found,
1092 // search for its mangled names.
1093 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001094 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001095
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001096 // Windows specific -- Make sure we resolve all dllexported symbols.
1097 for (Export &E : Config->Exports) {
1098 if (!E.ForwardTo.empty())
1099 continue;
1100 E.Sym = addUndefined(E.Name);
1101 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001102 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001103 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001104
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001105 // Add weak aliases. Weak aliases is a mechanism to give remaining
1106 // undefined symbols final chance to be resolved successfully.
1107 for (auto Pair : Config->AlternateNames) {
1108 StringRef From = Pair.first;
1109 StringRef To = Pair.second;
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001110 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001111 if (!Sym)
1112 continue;
1113 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1114 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001115 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001116 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001117
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001118 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001119 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001120 addUndefined(mangle("_load_config_used"));
1121 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001122
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001123 if (ErrorCount)
1124 return;
1125
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001126 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1127 // This is useful because MSVC link.exe can generate complete PDBs.
1128 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001129 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001130 exit(0);
1131 }
1132
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001133 // Do LTO by compiling bitcode input files to a set of native COFF files then
1134 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001135 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001136 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001137
Peter Collingbourne2612a322015-07-04 05:28:41 +00001138 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001139 Symtab->reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +00001140
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001141 // Windows specific -- if no /subsystem is given, we need to infer
1142 // that from entry point name.
1143 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001144 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001145 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001146 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001147 }
1148
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001149 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001150 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001151 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001152 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001153 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1154 if (ErrorCount)
1155 return;
1156 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001157
Rui Ueyama151d8622015-06-17 20:40:43 +00001158 // Windows specific -- when we are creating a .dll file, we also
1159 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001160 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001161 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001162 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001163 assignExportOrdinals();
1164 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001165
Martin Storsjod2752aa2017-08-14 19:07:27 +00001166 // Set extra alignment for .comm symbols
1167 for (auto Pair : Config->AlignComm) {
1168 StringRef Name = Pair.first;
1169 int Align = Pair.second;
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001170 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001171 if (!Sym) {
1172 warn("/aligncomm symbol " + Name + " not found");
1173 continue;
1174 }
1175 auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1176 if (!DC) {
1177 warn("/aligncomm symbol " + Name + " of wrong kind");
1178 continue;
1179 }
1180 DC->getChunk()->setAlign(Align);
1181 }
1182
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001183 // Windows specific -- Create a side-by-side manifest file.
1184 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001185 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001186
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001187 // Identify unreferenced COMDAT sections.
1188 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001189 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001190
1191 // Identify identical COMDAT sections to merge them.
1192 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001193 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001194
Rui Ueyama411c63602015-05-28 19:09:30 +00001195 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001196 writeResult();
Peter Collingbournebe549552015-06-26 18:58:24 +00001197
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001198 // Call exit to avoid calling destructors.
1199 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001200}
1201
Rui Ueyama411c63602015-05-28 19:09:30 +00001202} // namespace coff
1203} // namespace lld