blob: 7e132ca6e9d6f4b4cea47b288faffd23abdcabfc [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 Ueyama3f851702017-10-02 21:00:41 +000018#include "lld/Common/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
Martin Storsjo8278ba52017-09-13 07:28:03 +0000113void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
114 bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000115 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000116
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000117 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000118 file_magic Magic = identify_magic(MBRef.getBuffer());
119 if (Magic == file_magic::windows_resource) {
120 Resources.push_back(MBRef);
121 return;
122 }
123
124 FilePaths.push_back(MBRef.getBufferIdentifier());
Martin Storsjo8278ba52017-09-13 07:28:03 +0000125 if (Magic == file_magic::archive) {
126 if (WholeArchive) {
127 std::unique_ptr<Archive> File =
128 check(Archive::create(MBRef),
129 MBRef.getBufferIdentifier() + ": failed to parse archive");
130
131 for (MemoryBufferRef M : getArchiveMembers(File.get()))
132 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
133 return;
134 }
135 Symtab->addFile(make<ArchiveFile>(MBRef));
136 return;
137 }
138
139 if (Magic == file_magic::bitcode) {
140 Symtab->addFile(make<BitcodeFile>(MBRef));
141 return;
142 }
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000143
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000144 if (Magic == file_magic::coff_cl_gl_object)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000145 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000146 "Recompile without /GL");
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000147 else
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000148 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000149}
150
Martin Storsjo8278ba52017-09-13 07:28:03 +0000151void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000152 auto Future =
153 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
154 std::string PathStr = Path;
155 enqueueTask([=]() {
156 auto MBOrErr = Future->get();
157 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000158 error("could not open " + PathStr + ": " + MBOrErr.second.message());
159 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000160 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000161 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000162}
163
164void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
165 StringRef ParentName) {
166 file_magic Magic = identify_magic(MB.getBuffer());
167 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000168 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000169 return;
170 }
171
172 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000173 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000174 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000175 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000176 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000177 } else {
178 error("unknown file type: " + MB.getBufferIdentifier());
179 return;
180 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000181
182 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000183 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000184 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000185}
186
187void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
188 StringRef SymName,
189 StringRef ParentName) {
190 if (!C.getParent()->isThin()) {
191 MemoryBufferRef MB = check(
192 C.getMemoryBufferRef(),
193 "could not get the buffer for the member defining symbol " + SymName);
194 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
195 return;
196 }
197
198 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
199 check(C.getFullName(),
200 "could not get the filename for the member defining symbol " +
201 SymName)));
202 enqueueTask([=]() {
203 auto MBOrErr = Future->get();
204 if (MBOrErr.second)
205 fatal(MBOrErr.second,
206 "could not get the buffer for the member defining " + SymName);
207 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
208 ParentName);
209 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000210}
211
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000212static bool isDecorated(StringRef Sym) {
213 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
214}
215
Rui Ueyama411c63602015-05-28 19:09:30 +0000216// Parses .drectve section contents and returns a list of files
217// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000218void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000219 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000220 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000221 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000222
David Blaikie6521ed92015-06-22 22:06:52 +0000223 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000224 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000225 case OPT_aligncomm:
226 parseAligncomm(Arg->getValue());
227 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000228 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000229 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000230 break;
231 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000232 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000233 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000234 break;
235 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000236 Export E = parseExport(Arg->getValue());
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000237 if (Config->Machine == I386 && Config->MinGW) {
238 if (!isDecorated(E.Name))
239 E.Name = Saver.save("_" + E.Name);
240 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
241 E.ExtName = Saver.save("_" + E.ExtName);
242 }
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000243 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000244 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000245 break;
246 }
247 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000248 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000249 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000250 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000251 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000252 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000253 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000254 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000255 break;
256 case OPT_nodefaultlib:
257 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
258 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000259 case OPT_section:
260 parseSection(Arg->getValue());
261 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000262 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000263 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000264 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000265 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000266 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000267 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000268 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000269 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000270 }
271 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000272}
273
Rui Ueyama54b71da2015-05-31 19:17:12 +0000274// Find file from search paths. You can omit ".obj", this function takes
275// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000276StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000277 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
278 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000279 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000280 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000281 for (StringRef Dir : SearchPaths) {
282 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000283 sys::path::append(Path, Filename);
284 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000285 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000286 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000287 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000288 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000289 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000290 }
291 }
292 return Filename;
293}
294
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000295// Resolves a file path. This never returns the same path
296// (in that case, it returns None).
297Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
298 StringRef Path = doFindFile(Filename);
299 bool Seen = !VisitedFiles.insert(Path.lower()).second;
300 if (Seen)
301 return None;
302 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000303}
304
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000305// Find library file from search path.
306StringRef LinkerDriver::doFindLib(StringRef Filename) {
307 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000308 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000309 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000310 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000311 return doFindFile(Filename);
312}
313
314// Resolves a library path. /nodefaultlib options are taken into
315// consideration. This never returns the same path (in that case,
316// it returns None).
317Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
318 if (Config->NoDefaultLibAll)
319 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000320 if (!VisitedLibs.insert(Filename.lower()).second)
321 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000322 StringRef Path = doFindLib(Filename);
323 if (Config->NoDefaultLibs.count(Path))
324 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000325 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000326 return None;
327 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000328}
329
330// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000331void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000332 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
333 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000334 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000335 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000336 while (!Env.empty()) {
337 StringRef Path;
338 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000339 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000340 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000341}
342
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000343SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000344 SymbolBody *B = Symtab->addUndefined(Name);
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000345 Config->GCRoot.insert(B);
346 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000347}
348
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000349// Symbol names are mangled by appending "_" prefix on x86.
350StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000351 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
352 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000353 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000354 return Sym;
355}
356
Rui Ueyama45044f42015-06-29 01:03:53 +0000357// Windows specific -- find default entry point name.
358StringRef LinkerDriver::findDefaultEntry() {
359 // User-defined main functions and their corresponding entry points.
360 static const char *Entries[][2] = {
361 {"main", "mainCRTStartup"},
362 {"wmain", "wmainCRTStartup"},
363 {"WinMain", "WinMainCRTStartup"},
364 {"wWinMain", "wWinMainCRTStartup"},
365 };
366 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000367 StringRef Entry = Symtab->findMangle(mangle(E[0]));
368 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000369 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000370 }
371 return "";
372}
373
374WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000375 if (Config->DLL)
376 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000377 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000378 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000379 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000380 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
381 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000382}
383
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000384static uint64_t getDefaultImageBase() {
385 if (Config->is64())
386 return Config->DLL ? 0x180000000 : 0x140000000;
387 return Config->DLL ? 0x10000000 : 0x400000;
388}
389
Rui Ueyama8fe17672016-12-08 20:50:47 +0000390static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000391 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000392 ArrayRef<StringRef> SearchPaths) {
393 SmallString<0> Data;
394 raw_svector_ostream OS(Data);
395
396 for (auto *Arg : Args) {
397 switch (Arg->getOption().getID()) {
398 case OPT_linkrepro:
399 case OPT_INPUT:
400 case OPT_defaultlib:
401 case OPT_libpath:
402 break;
403 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000404 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000405 }
406 }
407
408 for (StringRef Path : SearchPaths) {
409 std::string RelPath = relativeToRoot(Path);
410 OS << "/libpath:" << quote(RelPath) << "\n";
411 }
412
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000413 for (StringRef Path : FilePaths)
414 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000415
416 return Data.str();
417}
418
Rui Ueyama8fe17672016-12-08 20:50:47 +0000419static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000420 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
421 if (Args.hasArg(OPT_driver))
422 DebugTypes |= static_cast<unsigned>(DebugType::PData);
423 if (Args.hasArg(OPT_profile))
424 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
425 return DebugTypes;
426}
427
428static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000429 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000430 Arg.split(Types, ',', /*KeepEmpty=*/false);
431
432 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
433 for (StringRef Type : Types)
434 DebugTypes |= StringSwitch<unsigned>(Type.lower())
435 .Case("cv", static_cast<unsigned>(DebugType::CV))
436 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000437 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
438 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000439 return DebugTypes;
440}
441
Hans Wennborg1818e652016-12-09 20:54:44 +0000442static std::string getMapFile(const opt::InputArgList &Args) {
443 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
444 if (!Arg)
445 return "";
446 if (Arg->getOption().getID() == OPT_lldmap_file)
447 return Arg->getValue();
448
449 assert(Arg->getOption().getID() == OPT_lldmap);
450 StringRef OutFile = Config->OutputFile;
451 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
452}
453
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000454static std::string getImplibPath() {
455 if (!Config->Implib.empty())
456 return Config->Implib;
457 SmallString<128> Out = StringRef(Config->OutputFile);
458 sys::path::replace_extension(Out, ".lib");
459 return Out.str();
460}
461
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000462//
463// The import name is caculated as the following:
464//
465// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
466// -----+----------------+---------------------+------------------
467// LINK | {value} | {value}.{.dll/.exe} | {output name}
468// LIB | {value} | {value}.dll | {output name}.dll
469//
470static std::string getImportName(bool AsLib) {
471 SmallString<128> Out;
472
473 if (Config->ImportName.empty()) {
474 Out.assign(sys::path::filename(Config->OutputFile));
475 if (AsLib)
476 sys::path::replace_extension(Out, ".dll");
477 } else {
478 Out.assign(Config->ImportName);
479 if (!sys::path::has_extension(Out))
480 sys::path::replace_extension(Out,
481 (Config->DLL || AsLib) ? ".dll" : ".exe");
482 }
483
484 return Out.str();
485}
486
487static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000488 std::vector<COFFShortExport> Exports;
489 for (Export &E1 : Config->Exports) {
490 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000491 E2.Name = E1.Name;
492 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000493 E2.ExtName = E1.ExtName;
494 E2.Ordinal = E1.Ordinal;
495 E2.Noname = E1.Noname;
496 E2.Data = E1.Data;
497 E2.Private = E1.Private;
498 E2.Constant = E1.Constant;
499 Exports.push_back(E2);
500 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000501
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000502 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
503 Config->Machine, false);
504 handleAllErrors(std::move(E),
505 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000506}
507
508static void parseModuleDefs(StringRef Path) {
509 std::unique_ptr<MemoryBuffer> MB = check(
510 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyama67aea7372017-06-08 23:43:44 +0000511 COFFModuleDefinition M =
512 check(parseCOFFModuleDefinition(MB->getMemBufferRef(), Config->Machine));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000513
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000514 if (Config->OutputFile.empty())
515 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000516 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000517 if (M.ImageBase)
518 Config->ImageBase = M.ImageBase;
519 if (M.StackReserve)
520 Config->StackReserve = M.StackReserve;
521 if (M.StackCommit)
522 Config->StackCommit = M.StackCommit;
523 if (M.HeapReserve)
524 Config->HeapReserve = M.HeapReserve;
525 if (M.HeapCommit)
526 Config->HeapCommit = M.HeapCommit;
527 if (M.MajorImageVersion)
528 Config->MajorImageVersion = M.MajorImageVersion;
529 if (M.MinorImageVersion)
530 Config->MinorImageVersion = M.MinorImageVersion;
531 if (M.MajorOSVersion)
532 Config->MajorOSVersion = M.MajorOSVersion;
533 if (M.MinorOSVersion)
534 Config->MinorOSVersion = M.MinorOSVersion;
535
536 for (COFFShortExport E1 : M.Exports) {
537 Export E2;
538 E2.Name = Saver.save(E1.Name);
539 if (E1.isWeak())
540 E2.ExtName = Saver.save(E1.ExtName);
541 E2.Ordinal = E1.Ordinal;
542 E2.Noname = E1.Noname;
543 E2.Data = E1.Data;
544 E2.Private = E1.Private;
545 E2.Constant = E1.Constant;
546 Config->Exports.push_back(E2);
547 }
548}
549
Martin Storsjo7f71acd2017-10-12 05:37:13 +0000550// Get a sorted list of symbols not to automatically export
551// when exporting all global symbols for MinGW.
552static StringSet<> getExportExcludeSymbols() {
553 if (Config->Machine == I386)
554 return {
555 "__NULL_IMPORT_DESCRIPTOR",
556 "__pei386_runtime_relocator",
557 "_do_pseudo_reloc",
558 "_impure_ptr",
559 "__impure_ptr",
560 "__fmode",
561 "_environ",
562 "___dso_handle",
563 // These are the MinGW names that differ from the standard
564 // ones (lacking an extra underscore).
565 "_DllMain@12",
566 "_DllEntryPoint@12",
567 "_DllMainCRTStartup@12",
568 };
569
570 return {
571 "_NULL_IMPORT_DESCRIPTOR",
572 "_pei386_runtime_relocator",
573 "do_pseudo_reloc",
574 "impure_ptr",
575 "_impure_ptr",
576 "_fmode",
577 "environ",
578 "__dso_handle",
579 // These are the MinGW names that differ from the standard
580 // ones (lacking an extra underscore).
581 "DllMain",
582 "DllEntryPoint",
583 "DllMainCRTStartup",
584 };
585}
586
587// This is MinGW specific.
588static void writeDefFile(StringRef Name) {
589 std::error_code EC;
590 raw_fd_ostream OS(Name, EC, sys::fs::F_None);
591 if (EC)
592 fatal("cannot open " + Name + ": " + EC.message());
593
594 OS << "EXPORTS\n";
595 for (Export &E : Config->Exports) {
596 OS << " " << E.ExportName << " "
597 << "@" << E.Ordinal;
598 if (auto *Def = dyn_cast_or_null<Defined>(E.Sym)) {
599 if (Def && Def->getChunk() &&
600 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
601 OS << " DATA";
602 }
603 OS << "\n";
604 }
605}
606
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000607// A helper function for filterBitcodeFiles.
608static bool needsRebuilding(MemoryBufferRef MB) {
609 // The MSVC linker doesn't support thin archives, so if it's a thin
610 // archive, we always need to rebuild it.
611 std::unique_ptr<Archive> File =
612 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
613 if (File->isThin())
614 return true;
615
616 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000617 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000618 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
619 return true;
620 return false;
621}
622
623// Opens a given path as an archive file and removes bitcode files
624// from them if exists. This function is to appease the MSVC linker as
625// their linker doesn't like archive files containing non-native
626// object files.
627//
628// If a given archive doesn't contain bitcode files, the archive path
629// is returned as-is. Otherwise, a new temporary file is created and
630// its path is returned.
631static Optional<std::string>
632filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000633 std::unique_ptr<MemoryBuffer> MB = check(
634 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000635 MemoryBufferRef MBRef = MB->getMemBufferRef();
636 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000637
638 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000639 return None;
640 if (Magic != file_magic::archive)
641 return Path.str();
642 if (!needsRebuilding(MBRef))
643 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000644
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000645 std::unique_ptr<Archive> File =
646 check(Archive::create(MBRef),
647 MBRef.getBufferIdentifier() + ": failed to parse archive");
648
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000649 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000650 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000651 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
652 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000653
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000654 if (New.empty())
655 return None;
656
657 log("Creating a temporary archive for " + Path + " to remove bitcode files");
658
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000659 SmallString<128> S;
660 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
661 ".lib", S))
662 fatal(EC, "cannot create a temporary file");
663 std::string Temp = S.str();
664 TemporaryFiles.push_back(Temp);
665
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000666 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000667 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
668 /*Deterministics=*/true,
669 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000670 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
671 error("failed to create a new archive " + S.str() + ": " + EI.message());
672 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000673 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000674}
675
676// Create response file contents and invoke the MSVC linker.
677void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000678 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000679 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000680
Bob Haarman41108162017-04-21 21:38:01 +0000681 // Write out archive members that we used in symbol resolution and pass these
682 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
683 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000684 for (ObjFile *Obj : ObjFile::Instances) {
685 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000686 continue;
687 SmallString<128> S;
688 int Fd;
689 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000690 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarman41108162017-04-21 21:38:01 +0000691 fatal(EC, "cannot create a temporary file");
692 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000693 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000694 Temps.push_back(S.str());
695 Rsp += quote(S) + "\n";
696 }
697
Rui Ueyama85d54b02017-02-23 00:26:42 +0000698 for (auto *Arg : Args) {
699 switch (Arg->getOption().getID()) {
700 case OPT_linkrepro:
701 case OPT_lldmap:
702 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000703 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000704 case OPT_msvclto:
705 // LLD-specific options are stripped.
706 break;
707 case OPT_opt:
708 if (!StringRef(Arg->getValue()).startswith("lld"))
709 Rsp += toString(Arg) + " ";
710 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000711 case OPT_INPUT: {
712 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
713 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000714 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000715 continue;
716 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000717 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000718 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000719 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000720 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000721 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000722 }
723 }
724
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000725 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000726 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000727
728 for (StringRef Path : Temps)
729 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000730}
731
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000732void LinkerDriver::enqueueTask(std::function<void()> Task) {
733 TaskQueue.push_back(std::move(Task));
734}
735
736bool LinkerDriver::run() {
737 bool DidWork = !TaskQueue.empty();
738 while (!TaskQueue.empty()) {
739 TaskQueue.front()();
740 TaskQueue.pop_front();
741 }
742 return DidWork;
743}
744
Rui Ueyama8fe17672016-12-08 20:50:47 +0000745void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000746 // If the first command line argument is "/lib", link.exe acts like lib.exe.
747 // We call our own implementation of lib.exe that understands bitcode files.
748 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
749 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000750 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000751 return;
752 }
753
Peter Collingbourne60c16162015-06-01 20:10:10 +0000754 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000755 InitializeAllTargetInfos();
756 InitializeAllTargets();
757 InitializeAllTargetMCs();
758 InitializeAllAsmParsers();
759 InitializeAllAsmPrinters();
760 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000761
Rui Ueyama411c63602015-05-28 19:09:30 +0000762 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000763 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000764 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000765
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000766 // Parse and evaluate -mllvm options.
767 std::vector<const char *> V;
768 V.push_back("lld-link (LLVM option parsing)");
769 for (auto *Arg : Args.filtered(OPT_mllvm))
770 V.push_back(Arg->getValue());
771 cl::ParseCommandLineOptions(V.size(), V.data());
772
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000773 // Handle /errorlimit early, because error() depends on it.
774 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
775 int N = 20;
776 StringRef S = Arg->getValue();
777 if (S.getAsInteger(10, N))
778 error(Arg->getSpelling() + " number expected, but got " + S);
779 Config->ErrorLimit = N;
780 }
781
Rui Ueyama5c726432015-05-29 16:11:52 +0000782 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000783 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000784 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000785 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000786 }
787
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000788 // Handle /lldmingw early, since it can potentially affect how other
789 // options are handled.
790 Config->MinGW = Args.hasArg(OPT_lldmingw);
791
Peter Collingbournefeee2102016-07-26 02:00:42 +0000792 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
793 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000794 sys::path::append(Path, "repro.tar");
795
796 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
797 TarWriter::create(Path, "repro");
798
799 if (ErrOrWriter) {
800 Tar = std::move(*ErrOrWriter);
801 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000802 error("/linkrepro: failed to open " + Path + ": " +
803 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000804 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000805 }
806
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000807 if (!Args.hasArg(OPT_INPUT)) {
808 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000809 Config->NoEntry = true;
810 else
811 fatal("no input files");
812 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000813
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000814 // Construct search path list.
815 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000816 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000817 SearchPaths.push_back(Arg->getValue());
818 addLibSearchPaths();
819
Rui Ueyamaad660982015-06-07 00:20:32 +0000820 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000821 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000822 Config->OutputFile = Arg->getValue();
823
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000824 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000825 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000826 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000827
Rui Ueyama95925fd2015-06-28 19:35:15 +0000828 // Handle /force or /force:unresolved
829 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
830 Config->Force = true;
831
Rui Ueyama6600eb12015-07-04 23:37:32 +0000832 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000833 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000834 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000835 if (auto *Arg = Args.getLastArg(OPT_debugtype))
836 Config->DebugTypes = parseDebugType(Arg->getValue());
837 else
838 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000839 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000840
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000841 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000842 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000843 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000844
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000845 // Handle /noentry
846 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000847 if (Args.hasArg(OPT_dll))
848 Config->NoEntry = true;
849 else
850 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000851 }
852
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000853 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000854 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000855 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000856 Config->ManifestID = 2;
857 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000858
Rui Ueyama588e8322015-06-15 01:23:58 +0000859 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000860 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000861 if (Args.hasArg(OPT_dynamicbase)) {
862 error("/fixed must not be specified with /dynamicbase");
863 } else {
864 Config->Relocatable = false;
865 Config->DynamicBase = false;
866 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000867 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000868
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000869 if (Args.hasArg(OPT_appcontainer))
870 Config->AppContainer = true;
871
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000872 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000873 if (auto *Arg = Args.getLastArg(OPT_machine))
874 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000875
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000876 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000877 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000878 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
879
880 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000881 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000882 Config->NoDefaultLibAll = true;
883
Rui Ueyama804a8b62015-05-29 16:18:15 +0000884 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000885 if (auto *Arg = Args.getLastArg(OPT_base))
886 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000887
888 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000889 if (auto *Arg = Args.getLastArg(OPT_stack))
890 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000891
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000892 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000893 if (auto *Arg = Args.getLastArg(OPT_heap))
894 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000895
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000896 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000897 if (auto *Arg = Args.getLastArg(OPT_version))
898 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
899 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000900
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000901 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000902 if (auto *Arg = Args.getLastArg(OPT_subsystem))
903 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
904 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000905
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000906 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000907 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000908 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000909
Rui Ueyama08d5e182015-06-18 23:20:11 +0000910 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000911 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000912 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000913
Rui Ueyamab95188c2015-06-18 20:27:09 +0000914 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000915 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000916 Config->Implib = Arg->getValue();
917
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000918 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000919 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000920 std::string Str = StringRef(Arg->getValue()).lower();
921 SmallVector<StringRef, 1> Vec;
922 StringRef(Str).split(Vec, ',');
923 for (StringRef S : Vec) {
924 if (S == "noref") {
925 Config->DoGC = false;
926 Config->DoICF = false;
927 continue;
928 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000929 if (S == "icf" || S.startswith("icf=")) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000930 Config->DoICF = true;
931 continue;
932 }
933 if (S == "noicf") {
934 Config->DoICF = false;
935 continue;
936 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000937 if (S.startswith("lldlto=")) {
938 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000939 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
940 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000941 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000942 continue;
943 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000944 if (S.startswith("lldltojobs=")) {
945 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000946 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000947 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000948 continue;
949 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000950 if (S.startswith("lldltopartitions=")) {
951 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000952 if (N.getAsInteger(10, Config->LTOPartitions) ||
953 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000954 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000955 continue;
956 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000957 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000958 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000959 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000960 }
961
Bob Haarman69b196d2017-02-08 18:36:41 +0000962 // Handle /lldsavetemps
963 if (Args.hasArg(OPT_lldsavetemps))
964 Config->SaveTemps = true;
965
Peter Collingbourne052e855e2017-09-08 00:50:50 +0000966 // Handle /lldltocache
967 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
968 Config->LTOCache = Arg->getValue();
969
970 // Handle /lldsavecachepolicy
971 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
972 Config->LTOCachePolicy = check(
973 parseCachePruningPolicy(Arg->getValue()),
974 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
975
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000976 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000977 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000978 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000979
Rui Ueyama6600eb12015-07-04 23:37:32 +0000980 // Handle /merge
981 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000982 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000983
Rui Ueyama440138c2016-06-20 03:39:39 +0000984 // Handle /section
985 for (auto *Arg : Args.filtered(OPT_section))
986 parseSection(Arg->getValue());
987
Martin Storsjod2752aa2017-08-14 19:07:27 +0000988 // Handle /aligncomm
989 for (auto *Arg : Args.filtered(OPT_aligncomm))
990 parseAligncomm(Arg->getValue());
991
Nico Webera7a2c442017-07-25 18:08:03 +0000992 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
993 // also passed.
994 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
995 Config->ManifestDependency = Arg->getValue();
996 Config->Manifest = Configuration::SideBySide;
997 }
998
999 // Handle /manifest and /manifest:
1000 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1001 if (Arg->getOption().getID() == OPT_manifest)
1002 Config->Manifest = Configuration::SideBySide;
1003 else
1004 parseManifest(Arg->getValue());
1005 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001006
1007 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001008 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1009 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001010
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001011 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001012 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001013 Config->ManifestFile = Arg->getValue();
1014
Rui Ueyamaafb19012016-04-19 01:21:58 +00001015 // Handle /manifestinput
1016 for (auto *Arg : Args.filtered(OPT_manifestinput))
1017 Config->ManifestInput.push_back(Arg->getValue());
1018
Nico Webera7a2c442017-07-25 18:08:03 +00001019 if (!Config->ManifestInput.empty() &&
1020 Config->Manifest != Configuration::Embed) {
1021 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1022 }
1023
Rui Ueyama6592ff82015-06-16 23:13:00 +00001024 // Handle miscellaneous boolean flags.
Rui Ueyamaeef6b2a2017-09-15 22:49:13 +00001025 if (Args.hasArg(OPT_allowbind_no))
1026 Config->AllowBind = false;
David Blaikie6521ed92015-06-22 22:06:52 +00001027 if (Args.hasArg(OPT_allowisolation_no))
1028 Config->AllowIsolation = false;
1029 if (Args.hasArg(OPT_dynamicbase_no))
1030 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +00001031 if (Args.hasArg(OPT_nxcompat_no))
1032 Config->NxCompat = false;
1033 if (Args.hasArg(OPT_tsaware_no))
1034 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +00001035 if (Args.hasArg(OPT_nosymtab))
1036 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +00001037
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001038 Config->MapFile = getMapFile(Args);
1039
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001040 if (ErrorCount)
1041 return;
1042
Martin Storsjo8278ba52017-09-13 07:28:03 +00001043 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001044 // Create a list of input files. Files can be given as arguments
1045 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001046 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001047 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1048 switch (Arg->getOption().getID()) {
1049 case OPT_INPUT:
1050 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1051 enqueuePath(*Path, WholeArchiveFlag);
1052 break;
1053 case OPT_wholearchive_file:
1054 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1055 enqueuePath(*Path, true);
1056 break;
1057 }
1058 }
David Blaikie6521ed92015-06-22 22:06:52 +00001059 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001060 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001061 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001062
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001063 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001064 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001065 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001066
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001067 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001068 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001069
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001070 // We should have inferred a machine type by now from the input files, but if
1071 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001072 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001073 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001074 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001075 }
1076
Eric Beckmann9e19d792017-06-17 02:26:27 +00001077 // Input files can be Windows resource files (.res files). We use
1078 // WindowsResource to convert resource files to a regular COFF file,
1079 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001080 if (!Resources.empty())
Martin Storsjo8278ba52017-09-13 07:28:03 +00001081 addBuffer(convertResToCOFF(Resources), false);
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001082
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001083 if (Tar)
1084 Tar->append("response.txt",
1085 createResponseFile(Args, FilePaths,
1086 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001087
Rui Ueyama4d545342015-07-28 03:12:00 +00001088 // Handle /largeaddressaware
1089 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
1090 Config->LargeAddressAware = true;
1091
Rui Ueyamad68e2112015-07-28 03:15:57 +00001092 // Handle /highentropyva
1093 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
1094 Config->HighEntropyVA = true;
1095
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001096 // Handle /entry and /dll
1097 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1098 Config->Entry = addUndefined(mangle(Arg->getValue()));
1099 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +00001100 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1101 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001102 Config->Entry = addUndefined(S);
1103 } else if (!Config->NoEntry) {
1104 // Windows specific -- If entry point name is not given, we need to
1105 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001106 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001107 if (S.empty())
1108 fatal("entry point must be defined");
1109 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001110 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001111 }
1112
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001113 // Handle /export
1114 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001115 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001116 if (Config->Machine == I386) {
1117 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001118 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001119 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001120 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001121 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001122 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001123 }
1124
1125 // Handle /def
1126 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001127 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001128 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001129 }
1130
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001131 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001132 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001133 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001134 createImportLibrary(/*AsLib=*/true);
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001135 exit(0);
1136 }
1137
Rui Ueyama6d249082015-07-13 22:31:45 +00001138 // Handle /delayload
1139 for (auto *Arg : Args.filtered(OPT_delayload)) {
1140 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001141 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001142 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001143 } else {
1144 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001145 }
1146 }
1147
Reid Kleckner7668182e2017-03-21 00:12:51 +00001148 // Set default image name if neither /out or /def set it.
1149 if (Config->OutputFile.empty()) {
1150 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001151 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001152 }
1153
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001154 // Put the PDB next to the image if no /pdb flag was passed.
1155 if (Config->Debug && Config->PDBPath.empty()) {
1156 Config->PDBPath = Config->OutputFile;
1157 sys::path::replace_extension(Config->PDBPath, ".pdb");
1158 }
1159
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001160 // Disable PDB generation if the user requested it.
1161 if (Args.hasArg(OPT_nopdb))
1162 Config->PDBPath = "";
1163
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001164 // Set default image base if /base is not given.
1165 if (Config->ImageBase == uint64_t(-1))
1166 Config->ImageBase = getDefaultImageBase();
1167
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001168 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001169 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001170 Symtab->addAbsolute("___safe_se_handler_table", 0);
1171 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001172 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001173
Rui Ueyama107db552015-08-09 21:01:06 +00001174 // We do not support /guard:cf (control flow protection) yet.
1175 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001176 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1177 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1178 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1179 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1180 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1181 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1182 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001183
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001184 // This code may add new undefined symbols to the link, which may enqueue more
1185 // symbol resolution tasks, so we need to continue executing tasks until we
1186 // converge.
1187 do {
1188 // Windows specific -- if entry point is not found,
1189 // search for its mangled names.
1190 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001191 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001192
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001193 // Windows specific -- Make sure we resolve all dllexported symbols.
1194 for (Export &E : Config->Exports) {
1195 if (!E.ForwardTo.empty())
1196 continue;
1197 E.Sym = addUndefined(E.Name);
1198 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001199 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001200 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001201
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001202 // Add weak aliases. Weak aliases is a mechanism to give remaining
1203 // undefined symbols final chance to be resolved successfully.
1204 for (auto Pair : Config->AlternateNames) {
1205 StringRef From = Pair.first;
1206 StringRef To = Pair.second;
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001207 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001208 if (!Sym)
1209 continue;
1210 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1211 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001212 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001213 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001214
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001215 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001216 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001217 addUndefined(mangle("_load_config_used"));
1218 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001219
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001220 if (ErrorCount)
1221 return;
1222
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001223 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1224 // This is useful because MSVC link.exe can generate complete PDBs.
1225 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001226 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001227 exit(0);
1228 }
1229
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001230 // Do LTO by compiling bitcode input files to a set of native COFF files then
1231 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001232 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001233 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001234
Peter Collingbourne2612a322015-07-04 05:28:41 +00001235 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001236 Symtab->reportRemainingUndefines();
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001237 if (ErrorCount)
1238 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001239
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001240 // Windows specific -- if no /subsystem is given, we need to infer
1241 // that from entry point name.
1242 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001243 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001244 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001245 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001246 }
1247
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001248 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001249 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001250 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001251 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001252 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1253 if (ErrorCount)
1254 return;
1255 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001256
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001257 // In MinGW, all symbols are automatically exported if no symbols
1258 // are chosen to be exported.
1259 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1260 Args.hasArg(OPT_export_all_symbols))) {
1261 StringSet<> ExcludeSymbols = getExportExcludeSymbols();
1262
1263 Symtab->forEachSymbol([=](Symbol *S) {
1264 auto *Def = dyn_cast<Defined>(S->body());
1265 if (!Def || !Def->isLive() || !Def->getChunk())
1266 return;
1267 if (ExcludeSymbols.count(Def->getName()))
1268 return;
1269 Export E;
1270 E.Name = Def->getName();
1271 E.Sym = Def;
1272 Config->Exports.push_back(E);
1273 });
1274 }
1275
Rui Ueyama151d8622015-06-17 20:40:43 +00001276 // Windows specific -- when we are creating a .dll file, we also
1277 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001278 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001279 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001280 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001281 assignExportOrdinals();
1282 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001283
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001284 // Handle /output-def (MinGW specific).
1285 if (auto *Arg = Args.getLastArg(OPT_output_def))
1286 writeDefFile(Arg->getValue());
1287
Martin Storsjod2752aa2017-08-14 19:07:27 +00001288 // Set extra alignment for .comm symbols
1289 for (auto Pair : Config->AlignComm) {
1290 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001291 uint32_t Alignment = Pair.second;
1292
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001293 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001294 if (!Sym) {
1295 warn("/aligncomm symbol " + Name + " not found");
1296 continue;
1297 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001298
Martin Storsjod2752aa2017-08-14 19:07:27 +00001299 auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1300 if (!DC) {
1301 warn("/aligncomm symbol " + Name + " of wrong kind");
1302 continue;
1303 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001304
1305 CommonChunk *C = DC->getChunk();
1306 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001307 }
1308
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001309 // Windows specific -- Create a side-by-side manifest file.
1310 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001311 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001312
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001313 // Identify unreferenced COMDAT sections.
1314 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001315 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001316
1317 // Identify identical COMDAT sections to merge them.
1318 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001319 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001320
Rui Ueyama411c63602015-05-28 19:09:30 +00001321 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001322 writeResult();
Peter Collingbournebe549552015-06-26 18:58:24 +00001323
Shoaib Meenai4aa7f8a2017-09-19 23:58:05 +00001324 if (ErrorCount)
1325 return;
1326
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001327 // Call exit to avoid calling destructors.
1328 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001329}
1330
Rui Ueyama411c63602015-05-28 19:09:30 +00001331} // namespace coff
1332} // namespace lld