blob: 133cf40a83bffd324ca9c0441f06e063dbb44a39 [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"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000015#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000017#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000018#include "Writer.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000019#include "lld/Common/Driver.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000020#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000021#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000022#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000023#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000024#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000025#include "llvm/Object/COFFImportFile.h"
26#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000027#include "llvm/Option/Arg.h"
28#include "llvm/Option/ArgList.h"
29#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000032#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000033#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000034#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000036#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000037#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000038#include <memory>
39
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000040#include <future>
41
Rui Ueyama411c63602015-05-28 19:09:30 +000042using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000043using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000044using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000045using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000046
Rui Ueyama3500f662015-05-28 20:30:06 +000047namespace lld {
48namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000051LinkerDriver *Driver;
52
Rui Ueyama9381eb12016-12-18 14:06:06 +000053BumpPtrAllocator BAlloc;
54StringSaver Saver{BAlloc};
55std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
56
Bob Haarman6c8f7362017-01-17 19:07:42 +000057bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
58 ErrorCount = 0;
59 ErrorOS = &Diag;
Rui Ueyamacbf969e2017-08-28 21:51:07 +000060
Rui Ueyama7fed58c2016-12-08 19:10:28 +000061 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000062 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyama8bee41e2017-08-24 20:32:58 +000063 Config->ColorDiagnostics = ErrorOS->has_colors();
Rui Ueyamacbf969e2017-08-28 21:51:07 +000064
65 Symtab = make<SymbolTable>();
66
Rui Ueyama7fed58c2016-12-08 19:10:28 +000067 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000068 Driver->link(Args);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +000069 return !ErrorCount;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000070}
Rui Ueyama411c63602015-05-28 19:09:30 +000071
Nico Weber5660de72016-04-20 22:34:15 +000072// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000073static std::string getOutputPath(StringRef Path) {
74 auto P = Path.find_last_of("\\/");
75 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000076 const char* E = Config->DLL ? ".dll" : ".exe";
77 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000078}
79
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000080// ErrorOr is not default constructible, so it cannot be used as the type
81// parameter of a future.
82// FIXME: We could open the file in createFutureForFile and avoid needing to
83// return an error here, but for the moment that would cost us a file descriptor
84// (a limited resource on Windows) for the duration that the future is pending.
85typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
86
87// Create a std::future that opens and maps a file using the best strategy for
88// the host platform.
89static std::future<MBErrPair> createFutureForFile(std::string Path) {
90#if LLVM_ON_WIN32
91 // On Windows, file I/O is relatively slow so it is best to do this
92 // asynchronously.
93 auto Strategy = std::launch::async;
94#else
95 auto Strategy = std::launch::deferred;
96#endif
97 return std::async(Strategy, [=]() {
98 auto MBOrErr = MemoryBuffer::getFile(Path);
99 if (!MBOrErr)
100 return MBErrPair{nullptr, MBOrErr.getError()};
101 return MBErrPair{std::move(*MBOrErr), std::error_code()};
102 });
103}
104
105MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
106 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000107 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000108
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000109 if (Driver->Tar)
110 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
111 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000112 return MBRef;
113}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000114
Martin Storsjo8278ba52017-09-13 07:28:03 +0000115void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
116 bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000117 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000118 FilePaths.push_back(MBRef.getBufferIdentifier());
Peter Collingbournefeee2102016-07-26 02:00:42 +0000119
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000120 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000121 switch (identify_magic(MBRef.getBuffer())) {
122 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000123 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000124 break;
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000125
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000126 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000127 if (WholeArchive) {
128 std::unique_ptr<Archive> File =
129 check(Archive::create(MBRef),
130 MBRef.getBufferIdentifier() + ": failed to parse archive");
131
132 for (MemoryBufferRef M : getArchiveMembers(File.get()))
133 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
134 return;
135 }
136 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000137 break;
Martin Storsjo8278ba52017-09-13 07:28:03 +0000138
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000139 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000140 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000141 break;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000142
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000143 case file_magic::coff_cl_gl_object:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000144 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000145 "Recompile without /GL");
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000146 break;
147
148 default:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000149 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 break;
151 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000152}
153
Martin Storsjo8278ba52017-09-13 07:28:03 +0000154void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000155 auto Future =
156 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
157 std::string PathStr = Path;
158 enqueueTask([=]() {
159 auto MBOrErr = Future->get();
160 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000161 error("could not open " + PathStr + ": " + MBOrErr.second.message());
162 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000163 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000164 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000165}
166
167void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
168 StringRef ParentName) {
169 file_magic Magic = identify_magic(MB.getBuffer());
170 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000171 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000172 return;
173 }
174
175 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000176 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000177 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000178 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000179 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000180 } else {
181 error("unknown file type: " + MB.getBufferIdentifier());
182 return;
183 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000184
185 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000186 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000187 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000188}
189
190void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
191 StringRef SymName,
192 StringRef ParentName) {
193 if (!C.getParent()->isThin()) {
194 MemoryBufferRef MB = check(
195 C.getMemoryBufferRef(),
196 "could not get the buffer for the member defining symbol " + SymName);
197 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
198 return;
199 }
200
201 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
202 check(C.getFullName(),
203 "could not get the filename for the member defining symbol " +
204 SymName)));
205 enqueueTask([=]() {
206 auto MBOrErr = Future->get();
207 if (MBOrErr.second)
208 fatal(MBOrErr.second,
209 "could not get the buffer for the member defining " + SymName);
210 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
211 ParentName);
212 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000213}
214
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000215static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000216 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
217 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000218}
219
Rui Ueyama411c63602015-05-28 19:09:30 +0000220// Parses .drectve section contents and returns a list of files
221// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000222void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000223 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000224 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000225 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000226
David Blaikie6521ed92015-06-22 22:06:52 +0000227 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000228 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000229 case OPT_aligncomm:
230 parseAligncomm(Arg->getValue());
231 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000232 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000233 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000234 break;
235 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000236 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000237 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000238 break;
239 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000240 Export E = parseExport(Arg->getValue());
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000241 if (Config->Machine == I386 && Config->MinGW) {
242 if (!isDecorated(E.Name))
243 E.Name = Saver.save("_" + E.Name);
244 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
245 E.ExtName = Saver.save("_" + E.ExtName);
246 }
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000247 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000248 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000249 break;
250 }
251 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000252 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000253 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000254 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000255 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000256 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000257 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000258 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000259 break;
260 case OPT_nodefaultlib:
261 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
262 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000263 case OPT_section:
264 parseSection(Arg->getValue());
265 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000266 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000267 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000268 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000269 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000270 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000271 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000272 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000273 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000274 }
275 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000276}
277
Rui Ueyama54b71da2015-05-31 19:17:12 +0000278// Find file from search paths. You can omit ".obj", this function takes
279// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000280StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000281 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
282 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000283 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000284 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000285 for (StringRef Dir : SearchPaths) {
286 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000287 sys::path::append(Path, Filename);
288 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000289 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000290 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000291 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000292 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000293 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000294 }
295 }
296 return Filename;
297}
298
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000299// Resolves a file path. This never returns the same path
300// (in that case, it returns None).
301Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
302 StringRef Path = doFindFile(Filename);
303 bool Seen = !VisitedFiles.insert(Path.lower()).second;
304 if (Seen)
305 return None;
306 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000307}
308
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000309// Find library file from search path.
310StringRef LinkerDriver::doFindLib(StringRef Filename) {
311 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000312 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000313 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000314 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000315 return doFindFile(Filename);
316}
317
318// Resolves a library path. /nodefaultlib options are taken into
319// consideration. This never returns the same path (in that case,
320// it returns None).
321Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
322 if (Config->NoDefaultLibAll)
323 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000324 if (!VisitedLibs.insert(Filename.lower()).second)
325 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000326 StringRef Path = doFindLib(Filename);
327 if (Config->NoDefaultLibs.count(Path))
328 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000329 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000330 return None;
331 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000332}
333
334// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000335void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000336 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
337 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000338 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000339 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000340 while (!Env.empty()) {
341 StringRef Path;
342 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000343 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000344 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000345}
346
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000347SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000348 SymbolBody *B = Symtab->addUndefined(Name);
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000349 Config->GCRoot.insert(B);
350 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000351}
352
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000353// Symbol names are mangled by appending "_" prefix on x86.
354StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000355 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
356 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000357 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000358 return Sym;
359}
360
Rui Ueyama45044f42015-06-29 01:03:53 +0000361// Windows specific -- find default entry point name.
362StringRef LinkerDriver::findDefaultEntry() {
363 // User-defined main functions and their corresponding entry points.
364 static const char *Entries[][2] = {
365 {"main", "mainCRTStartup"},
366 {"wmain", "wmainCRTStartup"},
367 {"WinMain", "WinMainCRTStartup"},
368 {"wWinMain", "wWinMainCRTStartup"},
369 };
370 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000371 StringRef Entry = Symtab->findMangle(mangle(E[0]));
372 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000373 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000374 }
375 return "";
376}
377
378WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000379 if (Config->DLL)
380 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000381 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000382 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000383 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000384 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
385 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000386}
387
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000388static uint64_t getDefaultImageBase() {
389 if (Config->is64())
390 return Config->DLL ? 0x180000000 : 0x140000000;
391 return Config->DLL ? 0x10000000 : 0x400000;
392}
393
Rui Ueyama8fe17672016-12-08 20:50:47 +0000394static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000395 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000396 ArrayRef<StringRef> SearchPaths) {
397 SmallString<0> Data;
398 raw_svector_ostream OS(Data);
399
400 for (auto *Arg : Args) {
401 switch (Arg->getOption().getID()) {
402 case OPT_linkrepro:
403 case OPT_INPUT:
404 case OPT_defaultlib:
405 case OPT_libpath:
406 break;
407 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000408 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000409 }
410 }
411
412 for (StringRef Path : SearchPaths) {
413 std::string RelPath = relativeToRoot(Path);
414 OS << "/libpath:" << quote(RelPath) << "\n";
415 }
416
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000417 for (StringRef Path : FilePaths)
418 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000419
420 return Data.str();
421}
422
Rui Ueyama8fe17672016-12-08 20:50:47 +0000423static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000424 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
425 if (Args.hasArg(OPT_driver))
426 DebugTypes |= static_cast<unsigned>(DebugType::PData);
427 if (Args.hasArg(OPT_profile))
428 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
429 return DebugTypes;
430}
431
432static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000433 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000434 Arg.split(Types, ',', /*KeepEmpty=*/false);
435
436 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
437 for (StringRef Type : Types)
438 DebugTypes |= StringSwitch<unsigned>(Type.lower())
439 .Case("cv", static_cast<unsigned>(DebugType::CV))
440 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000441 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
442 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000443 return DebugTypes;
444}
445
Hans Wennborg1818e652016-12-09 20:54:44 +0000446static std::string getMapFile(const opt::InputArgList &Args) {
447 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
448 if (!Arg)
449 return "";
450 if (Arg->getOption().getID() == OPT_lldmap_file)
451 return Arg->getValue();
452
453 assert(Arg->getOption().getID() == OPT_lldmap);
454 StringRef OutFile = Config->OutputFile;
455 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
456}
457
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000458static std::string getImplibPath() {
459 if (!Config->Implib.empty())
460 return Config->Implib;
461 SmallString<128> Out = StringRef(Config->OutputFile);
462 sys::path::replace_extension(Out, ".lib");
463 return Out.str();
464}
465
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000466//
467// The import name is caculated as the following:
468//
469// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
470// -----+----------------+---------------------+------------------
471// LINK | {value} | {value}.{.dll/.exe} | {output name}
472// LIB | {value} | {value}.dll | {output name}.dll
473//
474static std::string getImportName(bool AsLib) {
475 SmallString<128> Out;
476
477 if (Config->ImportName.empty()) {
478 Out.assign(sys::path::filename(Config->OutputFile));
479 if (AsLib)
480 sys::path::replace_extension(Out, ".dll");
481 } else {
482 Out.assign(Config->ImportName);
483 if (!sys::path::has_extension(Out))
484 sys::path::replace_extension(Out,
485 (Config->DLL || AsLib) ? ".dll" : ".exe");
486 }
487
488 return Out.str();
489}
490
491static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000492 std::vector<COFFShortExport> Exports;
493 for (Export &E1 : Config->Exports) {
494 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000495 E2.Name = E1.Name;
496 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000497 E2.ExtName = E1.ExtName;
498 E2.Ordinal = E1.Ordinal;
499 E2.Noname = E1.Noname;
500 E2.Data = E1.Data;
501 E2.Private = E1.Private;
502 E2.Constant = E1.Constant;
503 Exports.push_back(E2);
504 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000505
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000506 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
507 Config->Machine, false);
508 handleAllErrors(std::move(E),
509 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000510}
511
512static void parseModuleDefs(StringRef Path) {
513 std::unique_ptr<MemoryBuffer> MB = check(
514 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000515 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
516 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000517
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000518 if (Config->OutputFile.empty())
519 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000520 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000521 if (M.ImageBase)
522 Config->ImageBase = M.ImageBase;
523 if (M.StackReserve)
524 Config->StackReserve = M.StackReserve;
525 if (M.StackCommit)
526 Config->StackCommit = M.StackCommit;
527 if (M.HeapReserve)
528 Config->HeapReserve = M.HeapReserve;
529 if (M.HeapCommit)
530 Config->HeapCommit = M.HeapCommit;
531 if (M.MajorImageVersion)
532 Config->MajorImageVersion = M.MajorImageVersion;
533 if (M.MinorImageVersion)
534 Config->MinorImageVersion = M.MinorImageVersion;
535 if (M.MajorOSVersion)
536 Config->MajorOSVersion = M.MajorOSVersion;
537 if (M.MinorOSVersion)
538 Config->MinorOSVersion = M.MinorOSVersion;
539
540 for (COFFShortExport E1 : M.Exports) {
541 Export E2;
542 E2.Name = Saver.save(E1.Name);
543 if (E1.isWeak())
544 E2.ExtName = Saver.save(E1.ExtName);
545 E2.Ordinal = E1.Ordinal;
546 E2.Noname = E1.Noname;
547 E2.Data = E1.Data;
548 E2.Private = E1.Private;
549 E2.Constant = E1.Constant;
550 Config->Exports.push_back(E2);
551 }
552}
553
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000554// A helper function for filterBitcodeFiles.
555static bool needsRebuilding(MemoryBufferRef MB) {
556 // The MSVC linker doesn't support thin archives, so if it's a thin
557 // archive, we always need to rebuild it.
558 std::unique_ptr<Archive> File =
559 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
560 if (File->isThin())
561 return true;
562
563 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000564 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000565 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
566 return true;
567 return false;
568}
569
570// Opens a given path as an archive file and removes bitcode files
571// from them if exists. This function is to appease the MSVC linker as
572// their linker doesn't like archive files containing non-native
573// object files.
574//
575// If a given archive doesn't contain bitcode files, the archive path
576// is returned as-is. Otherwise, a new temporary file is created and
577// its path is returned.
578static Optional<std::string>
579filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000580 std::unique_ptr<MemoryBuffer> MB = check(
581 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000582 MemoryBufferRef MBRef = MB->getMemBufferRef();
583 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000584
585 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000586 return None;
587 if (Magic != file_magic::archive)
588 return Path.str();
589 if (!needsRebuilding(MBRef))
590 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000591
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000592 std::unique_ptr<Archive> File =
593 check(Archive::create(MBRef),
594 MBRef.getBufferIdentifier() + ": failed to parse archive");
595
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000596 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000597 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000598 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
599 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000600
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000601 if (New.empty())
602 return None;
603
604 log("Creating a temporary archive for " + Path + " to remove bitcode files");
605
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000606 SmallString<128> S;
607 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
608 ".lib", S))
609 fatal(EC, "cannot create a temporary file");
610 std::string Temp = S.str();
611 TemporaryFiles.push_back(Temp);
612
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000613 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000614 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
615 /*Deterministics=*/true,
616 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000617 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
618 error("failed to create a new archive " + S.str() + ": " + EI.message());
619 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000620 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000621}
622
623// Create response file contents and invoke the MSVC linker.
624void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000625 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000626 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000627
Bob Haarman41108162017-04-21 21:38:01 +0000628 // Write out archive members that we used in symbol resolution and pass these
629 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
630 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000631 for (ObjFile *Obj : ObjFile::Instances) {
632 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000633 continue;
634 SmallString<128> S;
635 int Fd;
636 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000637 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarman41108162017-04-21 21:38:01 +0000638 fatal(EC, "cannot create a temporary file");
639 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000640 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000641 Temps.push_back(S.str());
642 Rsp += quote(S) + "\n";
643 }
644
Rui Ueyama85d54b02017-02-23 00:26:42 +0000645 for (auto *Arg : Args) {
646 switch (Arg->getOption().getID()) {
647 case OPT_linkrepro:
648 case OPT_lldmap:
649 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000650 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000651 case OPT_msvclto:
652 // LLD-specific options are stripped.
653 break;
654 case OPT_opt:
655 if (!StringRef(Arg->getValue()).startswith("lld"))
656 Rsp += toString(Arg) + " ";
657 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000658 case OPT_INPUT: {
659 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
660 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000661 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000662 continue;
663 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000664 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000665 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000666 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000667 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000668 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000669 }
670 }
671
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000672 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000673 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000674
675 for (StringRef Path : Temps)
676 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000677}
678
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000679void LinkerDriver::enqueueTask(std::function<void()> Task) {
680 TaskQueue.push_back(std::move(Task));
681}
682
683bool LinkerDriver::run() {
684 bool DidWork = !TaskQueue.empty();
685 while (!TaskQueue.empty()) {
686 TaskQueue.front()();
687 TaskQueue.pop_front();
688 }
689 return DidWork;
690}
691
Rui Ueyama8fe17672016-12-08 20:50:47 +0000692void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000693 // If the first command line argument is "/lib", link.exe acts like lib.exe.
694 // We call our own implementation of lib.exe that understands bitcode files.
695 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
696 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000697 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000698 return;
699 }
700
Peter Collingbourne60c16162015-06-01 20:10:10 +0000701 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000702 InitializeAllTargetInfos();
703 InitializeAllTargets();
704 InitializeAllTargetMCs();
705 InitializeAllAsmParsers();
706 InitializeAllAsmPrinters();
707 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000708
Rui Ueyama411c63602015-05-28 19:09:30 +0000709 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000710 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000711 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000712
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000713 // Parse and evaluate -mllvm options.
714 std::vector<const char *> V;
715 V.push_back("lld-link (LLVM option parsing)");
716 for (auto *Arg : Args.filtered(OPT_mllvm))
717 V.push_back(Arg->getValue());
718 cl::ParseCommandLineOptions(V.size(), V.data());
719
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000720 // Handle /errorlimit early, because error() depends on it.
721 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
722 int N = 20;
723 StringRef S = Arg->getValue();
724 if (S.getAsInteger(10, N))
725 error(Arg->getSpelling() + " number expected, but got " + S);
726 Config->ErrorLimit = N;
727 }
728
Rui Ueyama5c726432015-05-29 16:11:52 +0000729 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000730 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000731 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000732 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000733 }
734
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000735 // Handle --version, which is an lld extension. This option is a bit odd
736 // because it doesn't start with "/", but we deliberately chose "--" to
737 // avoid conflict with /version and for compatibility with clang-cl.
738 if (Args.hasArg(OPT_dash_dash_version)) {
739 outs() << getLLDVersion() << "\n";
740 return;
741 }
742
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000743 // Handle /lldmingw early, since it can potentially affect how other
744 // options are handled.
745 Config->MinGW = Args.hasArg(OPT_lldmingw);
746
Peter Collingbournefeee2102016-07-26 02:00:42 +0000747 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
748 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000749 sys::path::append(Path, "repro.tar");
750
751 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
752 TarWriter::create(Path, "repro");
753
754 if (ErrOrWriter) {
755 Tar = std::move(*ErrOrWriter);
756 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000757 error("/linkrepro: failed to open " + Path + ": " +
758 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000759 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000760 }
761
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000762 if (!Args.hasArg(OPT_INPUT)) {
763 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000764 Config->NoEntry = true;
765 else
766 fatal("no input files");
767 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000768
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000769 // Construct search path list.
770 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000771 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000772 SearchPaths.push_back(Arg->getValue());
773 addLibSearchPaths();
774
Rui Ueyamaad660982015-06-07 00:20:32 +0000775 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000776 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000777 Config->OutputFile = Arg->getValue();
778
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000779 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000780 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000781 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000782
Rui Ueyama95925fd2015-06-28 19:35:15 +0000783 // Handle /force or /force:unresolved
784 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
785 Config->Force = true;
786
Rui Ueyama6600eb12015-07-04 23:37:32 +0000787 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000788 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000789 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000790 if (auto *Arg = Args.getLastArg(OPT_debugtype))
791 Config->DebugTypes = parseDebugType(Arg->getValue());
792 else
793 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000794 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000795
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000796 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000797 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000798 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000799
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000800 // Handle /noentry
801 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000802 if (Args.hasArg(OPT_dll))
803 Config->NoEntry = true;
804 else
805 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000806 }
807
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000808 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000809 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000810 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000811 Config->ManifestID = 2;
812 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000813
Rui Ueyama588e8322015-06-15 01:23:58 +0000814 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000815 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000816 if (Args.hasArg(OPT_dynamicbase)) {
817 error("/fixed must not be specified with /dynamicbase");
818 } else {
819 Config->Relocatable = false;
820 Config->DynamicBase = false;
821 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000822 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000823
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000824 if (Args.hasArg(OPT_appcontainer))
825 Config->AppContainer = true;
826
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000827 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000828 if (auto *Arg = Args.getLastArg(OPT_machine))
829 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000830
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000831 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000832 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000833 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
834
835 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000836 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000837 Config->NoDefaultLibAll = true;
838
Rui Ueyama804a8b62015-05-29 16:18:15 +0000839 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000840 if (auto *Arg = Args.getLastArg(OPT_base))
841 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000842
843 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000844 if (auto *Arg = Args.getLastArg(OPT_stack))
845 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000846
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000847 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000848 if (auto *Arg = Args.getLastArg(OPT_heap))
849 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000850
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000851 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000852 if (auto *Arg = Args.getLastArg(OPT_version))
853 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
854 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000855
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000856 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000857 if (auto *Arg = Args.getLastArg(OPT_subsystem))
858 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
859 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000860
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000861 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000862 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000863 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000864
Rui Ueyama08d5e182015-06-18 23:20:11 +0000865 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000866 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000867 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000868
Rui Ueyamab95188c2015-06-18 20:27:09 +0000869 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000870 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000871 Config->Implib = Arg->getValue();
872
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000873 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000874 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000875 std::string Str = StringRef(Arg->getValue()).lower();
876 SmallVector<StringRef, 1> Vec;
877 StringRef(Str).split(Vec, ',');
878 for (StringRef S : Vec) {
879 if (S == "noref") {
880 Config->DoGC = false;
881 Config->DoICF = false;
882 continue;
883 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000884 if (S == "icf" || S.startswith("icf=")) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000885 Config->DoICF = true;
886 continue;
887 }
888 if (S == "noicf") {
889 Config->DoICF = false;
890 continue;
891 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000892 if (S.startswith("lldlto=")) {
893 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000894 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
895 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000896 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000897 continue;
898 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000899 if (S.startswith("lldltojobs=")) {
900 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000901 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000902 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000903 continue;
904 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000905 if (S.startswith("lldltopartitions=")) {
906 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000907 if (N.getAsInteger(10, Config->LTOPartitions) ||
908 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000909 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000910 continue;
911 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000912 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000913 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000914 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000915 }
916
Bob Haarman69b196d2017-02-08 18:36:41 +0000917 // Handle /lldsavetemps
918 if (Args.hasArg(OPT_lldsavetemps))
919 Config->SaveTemps = true;
920
Peter Collingbourne052e855e2017-09-08 00:50:50 +0000921 // Handle /lldltocache
922 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
923 Config->LTOCache = Arg->getValue();
924
925 // Handle /lldsavecachepolicy
926 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
927 Config->LTOCachePolicy = check(
928 parseCachePruningPolicy(Arg->getValue()),
929 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
930
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000931 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000932 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000933 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000934
Rui Ueyama6600eb12015-07-04 23:37:32 +0000935 // Handle /merge
936 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000937 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000938
Rui Ueyama440138c2016-06-20 03:39:39 +0000939 // Handle /section
940 for (auto *Arg : Args.filtered(OPT_section))
941 parseSection(Arg->getValue());
942
Martin Storsjod2752aa2017-08-14 19:07:27 +0000943 // Handle /aligncomm
944 for (auto *Arg : Args.filtered(OPT_aligncomm))
945 parseAligncomm(Arg->getValue());
946
Nico Webera7a2c442017-07-25 18:08:03 +0000947 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
948 // also passed.
949 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
950 Config->ManifestDependency = Arg->getValue();
951 Config->Manifest = Configuration::SideBySide;
952 }
953
954 // Handle /manifest and /manifest:
955 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
956 if (Arg->getOption().getID() == OPT_manifest)
957 Config->Manifest = Configuration::SideBySide;
958 else
959 parseManifest(Arg->getValue());
960 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000961
962 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000963 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
964 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000965
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000966 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000967 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000968 Config->ManifestFile = Arg->getValue();
969
Rui Ueyamaafb19012016-04-19 01:21:58 +0000970 // Handle /manifestinput
971 for (auto *Arg : Args.filtered(OPT_manifestinput))
972 Config->ManifestInput.push_back(Arg->getValue());
973
Nico Webera7a2c442017-07-25 18:08:03 +0000974 if (!Config->ManifestInput.empty() &&
975 Config->Manifest != Configuration::Embed) {
976 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
977 }
978
Rui Ueyama6592ff82015-06-16 23:13:00 +0000979 // Handle miscellaneous boolean flags.
Rui Ueyamaeef6b2a2017-09-15 22:49:13 +0000980 if (Args.hasArg(OPT_allowbind_no))
981 Config->AllowBind = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000982 if (Args.hasArg(OPT_allowisolation_no))
983 Config->AllowIsolation = false;
984 if (Args.hasArg(OPT_dynamicbase_no))
985 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000986 if (Args.hasArg(OPT_nxcompat_no))
987 Config->NxCompat = false;
988 if (Args.hasArg(OPT_tsaware_no))
989 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000990 if (Args.hasArg(OPT_nosymtab))
991 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000992
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000993 Config->MapFile = getMapFile(Args);
994
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000995 if (ErrorCount)
996 return;
997
Martin Storsjo8278ba52017-09-13 07:28:03 +0000998 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000999 // Create a list of input files. Files can be given as arguments
1000 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001001 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001002 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1003 switch (Arg->getOption().getID()) {
1004 case OPT_INPUT:
1005 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1006 enqueuePath(*Path, WholeArchiveFlag);
1007 break;
1008 case OPT_wholearchive_file:
1009 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1010 enqueuePath(*Path, true);
1011 break;
1012 }
1013 }
David Blaikie6521ed92015-06-22 22:06:52 +00001014 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001015 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001016 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001017
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001018 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001019 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001020 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001021
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001022 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001023 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001024
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001025 // We should have inferred a machine type by now from the input files, but if
1026 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001027 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001028 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001029 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001030 }
1031
Eric Beckmann9e19d792017-06-17 02:26:27 +00001032 // Input files can be Windows resource files (.res files). We use
1033 // WindowsResource to convert resource files to a regular COFF file,
1034 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001035 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001036 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001037
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001038 if (Tar)
1039 Tar->append("response.txt",
1040 createResponseFile(Args, FilePaths,
1041 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001042
Rui Ueyama4d545342015-07-28 03:12:00 +00001043 // Handle /largeaddressaware
1044 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
1045 Config->LargeAddressAware = true;
1046
Rui Ueyamad68e2112015-07-28 03:15:57 +00001047 // Handle /highentropyva
1048 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
1049 Config->HighEntropyVA = true;
1050
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001051 // Handle /entry and /dll
1052 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1053 Config->Entry = addUndefined(mangle(Arg->getValue()));
1054 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +00001055 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1056 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001057 Config->Entry = addUndefined(S);
1058 } else if (!Config->NoEntry) {
1059 // Windows specific -- If entry point name is not given, we need to
1060 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001061 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001062 if (S.empty())
1063 fatal("entry point must be defined");
1064 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001065 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001066 }
1067
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001068 // Handle /export
1069 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001070 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001071 if (Config->Machine == I386) {
1072 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001073 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001074 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001075 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001076 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001077 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001078 }
1079
1080 // Handle /def
1081 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001082 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001083 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001084 }
1085
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001086 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001087 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001088 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001089 createImportLibrary(/*AsLib=*/true);
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001090 exit(0);
1091 }
1092
Rui Ueyama6d249082015-07-13 22:31:45 +00001093 // Handle /delayload
1094 for (auto *Arg : Args.filtered(OPT_delayload)) {
1095 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001096 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001097 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001098 } else {
1099 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001100 }
1101 }
1102
Reid Kleckner7668182e2017-03-21 00:12:51 +00001103 // Set default image name if neither /out or /def set it.
1104 if (Config->OutputFile.empty()) {
1105 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001106 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001107 }
1108
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001109 // Put the PDB next to the image if no /pdb flag was passed.
1110 if (Config->Debug && Config->PDBPath.empty()) {
1111 Config->PDBPath = Config->OutputFile;
1112 sys::path::replace_extension(Config->PDBPath, ".pdb");
1113 }
1114
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001115 // Disable PDB generation if the user requested it.
1116 if (Args.hasArg(OPT_nopdb))
1117 Config->PDBPath = "";
1118
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001119 // Set default image base if /base is not given.
1120 if (Config->ImageBase == uint64_t(-1))
1121 Config->ImageBase = getDefaultImageBase();
1122
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001123 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001124 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001125 Symtab->addAbsolute("___safe_se_handler_table", 0);
1126 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001127 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001128
Rui Ueyama107db552015-08-09 21:01:06 +00001129 // We do not support /guard:cf (control flow protection) yet.
1130 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001131 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1132 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1133 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1134 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1135 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1136 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1137 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001138
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001139 // This code may add new undefined symbols to the link, which may enqueue more
1140 // symbol resolution tasks, so we need to continue executing tasks until we
1141 // converge.
1142 do {
1143 // Windows specific -- if entry point is not found,
1144 // search for its mangled names.
1145 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001146 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001147
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001148 // Windows specific -- Make sure we resolve all dllexported symbols.
1149 for (Export &E : Config->Exports) {
1150 if (!E.ForwardTo.empty())
1151 continue;
1152 E.Sym = addUndefined(E.Name);
1153 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001154 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001155 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001156
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001157 // Add weak aliases. Weak aliases is a mechanism to give remaining
1158 // undefined symbols final chance to be resolved successfully.
1159 for (auto Pair : Config->AlternateNames) {
1160 StringRef From = Pair.first;
1161 StringRef To = Pair.second;
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001162 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001163 if (!Sym)
1164 continue;
1165 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1166 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001167 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001168 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001169
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001170 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001171 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001172 addUndefined(mangle("_load_config_used"));
1173 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001174
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001175 if (ErrorCount)
1176 return;
1177
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001178 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1179 // This is useful because MSVC link.exe can generate complete PDBs.
1180 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001181 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001182 exit(0);
1183 }
1184
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001185 // Do LTO by compiling bitcode input files to a set of native COFF files then
1186 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001187 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001188 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001189
Peter Collingbourne2612a322015-07-04 05:28:41 +00001190 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001191 Symtab->reportRemainingUndefines();
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001192 if (ErrorCount)
1193 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001194
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001195 // Windows specific -- if no /subsystem is given, we need to infer
1196 // that from entry point name.
1197 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001198 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001199 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001200 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001201 }
1202
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001203 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001204 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001205 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001206 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001207 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1208 if (ErrorCount)
1209 return;
1210 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001211
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001212 // In MinGW, all symbols are automatically exported if no symbols
1213 // are chosen to be exported.
1214 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1215 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001216 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001217
1218 Symtab->forEachSymbol([=](Symbol *S) {
1219 auto *Def = dyn_cast<Defined>(S->body());
Martin Storsjob40ccc12017-10-19 06:56:04 +00001220 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001221 return;
1222 Export E;
1223 E.Name = Def->getName();
1224 E.Sym = Def;
1225 Config->Exports.push_back(E);
1226 });
1227 }
1228
Rui Ueyama151d8622015-06-17 20:40:43 +00001229 // Windows specific -- when we are creating a .dll file, we also
1230 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001231 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001232 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001233 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001234 assignExportOrdinals();
1235 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001236
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001237 // Handle /output-def (MinGW specific).
1238 if (auto *Arg = Args.getLastArg(OPT_output_def))
1239 writeDefFile(Arg->getValue());
1240
Martin Storsjod2752aa2017-08-14 19:07:27 +00001241 // Set extra alignment for .comm symbols
1242 for (auto Pair : Config->AlignComm) {
1243 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001244 uint32_t Alignment = Pair.second;
1245
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001246 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001247 if (!Sym) {
1248 warn("/aligncomm symbol " + Name + " not found");
1249 continue;
1250 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001251
Martin Storsjod2752aa2017-08-14 19:07:27 +00001252 auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1253 if (!DC) {
1254 warn("/aligncomm symbol " + Name + " of wrong kind");
1255 continue;
1256 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001257
1258 CommonChunk *C = DC->getChunk();
1259 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001260 }
1261
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001262 // Windows specific -- Create a side-by-side manifest file.
1263 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001264 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001265
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001266 // Identify unreferenced COMDAT sections.
1267 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001268 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001269
1270 // Identify identical COMDAT sections to merge them.
1271 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001272 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001273
Rui Ueyama411c63602015-05-28 19:09:30 +00001274 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001275 writeResult();
Peter Collingbournebe549552015-06-26 18:58:24 +00001276
Shoaib Meenai4aa7f8a2017-09-19 23:58:05 +00001277 if (ErrorCount)
1278 return;
1279
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001280 // Call exit to avoid calling destructors.
1281 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001282}
1283
Rui Ueyama411c63602015-05-28 19:09:30 +00001284} // namespace coff
1285} // namespace lld