blob: 8076efe51bf86b06069a8ab3629f93638295b73a [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"
Sam Cleggf187c4d2018-02-20 22:09:59 +000012#include "ICF.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000014#include "MarkLive.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 Ueyama57175aa2018-01-27 00:34:46 +000019#include "lld/Common/Args.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000020#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000021#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000022#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000023#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000024#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000026#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000027#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000028#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000029#include "llvm/Object/COFFImportFile.h"
30#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Option/Arg.h"
32#include "llvm/Option/ArgList.h"
33#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000034#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000036#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000037#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000038#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000039#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000040#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000041#include <algorithm>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000042#include <future>
Sam Cleggf187c4d2018-02-20 22:09:59 +000043#include <memory>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000044
Rui Ueyama411c63602015-05-28 19:09:30 +000045using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000046using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000047using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000048using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050namespace lld {
51namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Zachary Turner727f1532018-01-17 19:16:26 +000053static Timer InputFileTimer("Input File Reading", Timer::root());
54
Rui Ueyama3500f662015-05-28 20:30:06 +000055Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000056LinkerDriver *Driver;
57
Rui Ueyama6f4e2552017-10-23 20:03:32 +000058bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Bob Haarmanb8a59c82017-10-25 22:28:38 +000059 errorHandler().LogName = Args[0];
60 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
Nico Weberf06ae4f2018-03-12 12:45:40 +000064 " (use /errorlimit:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000065 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000066 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000067 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyamacbf969e2017-08-28 21:51:07 +000068
69 Symtab = make<SymbolTable>();
70
Rui Ueyama7fed58c2016-12-08 19:10:28 +000071 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000072 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000073
74 // Call exit() if we can to avoid calling destructors.
75 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000076 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000077
78 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000079 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000080}
Rui Ueyama411c63602015-05-28 19:09:30 +000081
Nico Weber5660de72016-04-20 22:34:15 +000082// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000083static std::string getOutputPath(StringRef Path) {
84 auto P = Path.find_last_of("\\/");
85 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000086 const char* E = Config->DLL ? ".dll" : ".exe";
87 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000088}
89
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000090// ErrorOr is not default constructible, so it cannot be used as the type
91// parameter of a future.
92// FIXME: We could open the file in createFutureForFile and avoid needing to
93// return an error here, but for the moment that would cost us a file descriptor
94// (a limited resource on Windows) for the duration that the future is pending.
95typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
96
97// Create a std::future that opens and maps a file using the best strategy for
98// the host platform.
99static std::future<MBErrPair> createFutureForFile(std::string Path) {
Nico Weberfb647302018-04-10 13:15:21 +0000100#if _WIN32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000101 // On Windows, file I/O is relatively slow so it is best to do this
102 // asynchronously.
103 auto Strategy = std::launch::async;
104#else
105 auto Strategy = std::launch::deferred;
106#endif
107 return std::async(Strategy, [=]() {
Bob Haarman8832f882018-04-24 23:16:39 +0000108 auto MBOrErr = MemoryBuffer::getFile(Path,
109 /*FileSize*/ -1,
110 /*RequiresNullTerminator*/ false);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000111 if (!MBOrErr)
112 return MBErrPair{nullptr, MBOrErr.getError()};
113 return MBErrPair{std::move(*MBOrErr), std::error_code()};
114 });
115}
116
117MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
118 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000119 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000120
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000121 if (Driver->Tar)
122 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
123 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000124 return MBRef;
125}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000126
Martin Storsjo8278ba52017-09-13 07:28:03 +0000127void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
128 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000129 StringRef Filename = MB->getBufferIdentifier();
130
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000131 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000132 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000133
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000134 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000135 switch (identify_magic(MBRef.getBuffer())) {
136 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000137 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000138 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000139 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000140 if (WholeArchive) {
141 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000142 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000143
144 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000145 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000146 return;
147 }
148 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000149 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000151 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000152 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000153 case file_magic::coff_object:
154 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000155 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000156 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000157 case file_magic::coff_cl_gl_object:
158 error(Filename + ": is not a native COFF file. Recompile without /GL");
159 break;
160 case file_magic::pecoff_executable:
161 if (Filename.endswith_lower(".dll")) {
162 error(Filename + ": bad file type. Did you specify a DLL instead of an "
163 "import library?");
164 break;
165 }
166 LLVM_FALLTHROUGH;
167 default:
168 error(MBRef.getBufferIdentifier() + ": unknown file type");
169 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000170 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000171}
172
Martin Storsjo8278ba52017-09-13 07:28:03 +0000173void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000174 auto Future =
175 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
176 std::string PathStr = Path;
177 enqueueTask([=]() {
178 auto MBOrErr = Future->get();
179 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000180 error("could not open " + PathStr + ": " + MBOrErr.second.message());
181 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000182 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000183 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000184}
185
186void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
187 StringRef ParentName) {
188 file_magic Magic = identify_magic(MB.getBuffer());
189 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000190 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000191 return;
192 }
193
194 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000195 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000196 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000197 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000198 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000199 } else {
200 error("unknown file type: " + MB.getBufferIdentifier());
201 return;
202 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000203
204 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000205 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000206 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000207}
208
209void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
210 StringRef SymName,
211 StringRef ParentName) {
212 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000213 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000214 C.getMemoryBufferRef(),
215 "could not get the buffer for the member defining symbol " + SymName);
216 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
217 return;
218 }
219
220 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000221 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000222 "could not get the filename for the member defining symbol " +
223 SymName)));
224 enqueueTask([=]() {
225 auto MBOrErr = Future->get();
226 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000227 fatal("could not get the buffer for the member defining " + SymName +
228 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000229 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
230 ParentName);
231 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000232}
233
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000234static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000235 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
236 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000237}
238
Rui Ueyama411c63602015-05-28 19:09:30 +0000239// Parses .drectve section contents and returns a list of files
240// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000241void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000242 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000243 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000244 // /EXPORT: option can appear too many times, processing in fastpath.
245 opt::InputArgList Args;
246 std::vector<StringRef> Exports;
247 std::tie(Args, Exports) = Parser.parseDirectives(S);
248
249 for (StringRef E : Exports) {
250 // If a common header file contains dllexported function
251 // declarations, many object files may end up with having the
252 // same /EXPORT options. In order to save cost of parsing them,
253 // we dedup them first.
254 if (!DirectivesExports.insert(E).second)
255 continue;
256
257 Export Exp = parseExport(E);
258 if (Config->Machine == I386 && Config->MinGW) {
259 if (!isDecorated(Exp.Name))
260 Exp.Name = Saver.save("_" + Exp.Name);
261 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
262 Exp.ExtName = Saver.save("_" + Exp.ExtName);
263 }
264 Exp.Directives = true;
265 Config->Exports.push_back(Exp);
266 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000267
David Blaikie6521ed92015-06-22 22:06:52 +0000268 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000269 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000270 case OPT_aligncomm:
271 parseAligncomm(Arg->getValue());
272 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000273 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000274 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000275 break;
276 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000277 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000278 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000279 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000280 case OPT_entry:
281 Config->Entry = addUndefined(mangle(Arg->getValue()));
282 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000283 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000284 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000285 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000286 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000287 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000288 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000289 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000290 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000291 break;
292 case OPT_nodefaultlib:
293 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
294 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000295 case OPT_section:
296 parseSection(Arg->getValue());
297 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000298 case OPT_subsystem:
299 parseSubsystem(Arg->getValue(), &Config->Subsystem,
300 &Config->MajorOSVersion, &Config->MinorOSVersion);
301 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000302 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000303 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000304 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000305 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000306 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000307 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000308 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000309 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000310 }
311 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000312}
313
Rui Ueyama54b71da2015-05-31 19:17:12 +0000314// Find file from search paths. You can omit ".obj", this function takes
315// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000316StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000317 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
318 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000319 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000320 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000321 for (StringRef Dir : SearchPaths) {
322 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000323 sys::path::append(Path, Filename);
324 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000325 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000326 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000327 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000328 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000329 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000330 }
331 }
332 return Filename;
333}
334
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000335// Resolves a file path. This never returns the same path
336// (in that case, it returns None).
337Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
338 StringRef Path = doFindFile(Filename);
339 bool Seen = !VisitedFiles.insert(Path.lower()).second;
340 if (Seen)
341 return None;
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000342 if (Path.endswith_lower(".lib"))
343 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000344 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000345}
346
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000347// Find library file from search path.
348StringRef LinkerDriver::doFindLib(StringRef Filename) {
349 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000350 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000351 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000352 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000353 return doFindFile(Filename);
354}
355
356// Resolves a library path. /nodefaultlib options are taken into
357// consideration. This never returns the same path (in that case,
358// it returns None).
359Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
360 if (Config->NoDefaultLibAll)
361 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000362 if (!VisitedLibs.insert(Filename.lower()).second)
363 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000364 StringRef Path = doFindLib(Filename);
365 if (Config->NoDefaultLibs.count(Path))
366 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000367 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000368 return None;
369 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000370}
371
372// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000373void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000374 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
375 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000376 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000377 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000378 while (!Env.empty()) {
379 StringRef Path;
380 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000381 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000382 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000383}
384
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000385Symbol *LinkerDriver::addUndefined(StringRef Name) {
386 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000387 if (!B->IsGCRoot) {
388 B->IsGCRoot = true;
389 Config->GCRoot.push_back(B);
390 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000391 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000392}
393
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000394// Symbol names are mangled by appending "_" prefix on x86.
395StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000396 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
397 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000398 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000399 return Sym;
400}
401
Rui Ueyama45044f42015-06-29 01:03:53 +0000402// Windows specific -- find default entry point name.
403StringRef LinkerDriver::findDefaultEntry() {
404 // User-defined main functions and their corresponding entry points.
405 static const char *Entries[][2] = {
406 {"main", "mainCRTStartup"},
407 {"wmain", "wmainCRTStartup"},
408 {"WinMain", "WinMainCRTStartup"},
409 {"wWinMain", "wWinMainCRTStartup"},
410 };
411 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000412 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000413 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000414 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000415 }
416 return "";
417}
418
419WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000420 if (Config->DLL)
421 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000422 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000423 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000424 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000425 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
426 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000427}
428
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000429static uint64_t getDefaultImageBase() {
430 if (Config->is64())
431 return Config->DLL ? 0x180000000 : 0x140000000;
432 return Config->DLL ? 0x10000000 : 0x400000;
433}
434
Rui Ueyama8fe17672016-12-08 20:50:47 +0000435static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000436 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000437 ArrayRef<StringRef> SearchPaths) {
438 SmallString<0> Data;
439 raw_svector_ostream OS(Data);
440
441 for (auto *Arg : Args) {
442 switch (Arg->getOption().getID()) {
443 case OPT_linkrepro:
444 case OPT_INPUT:
445 case OPT_defaultlib:
446 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000447 case OPT_manifest:
448 case OPT_manifest_colon:
449 case OPT_manifestdependency:
450 case OPT_manifestfile:
451 case OPT_manifestinput:
452 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000453 break;
454 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000455 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000456 }
457 }
458
459 for (StringRef Path : SearchPaths) {
460 std::string RelPath = relativeToRoot(Path);
461 OS << "/libpath:" << quote(RelPath) << "\n";
462 }
463
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000464 for (StringRef Path : FilePaths)
465 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000466
467 return Data.str();
468}
469
Rui Ueyama8fe17672016-12-08 20:50:47 +0000470static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000471 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
472 if (Args.hasArg(OPT_driver))
473 DebugTypes |= static_cast<unsigned>(DebugType::PData);
474 if (Args.hasArg(OPT_profile))
475 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
476 return DebugTypes;
477}
478
479static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000480 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000481 Arg.split(Types, ',', /*KeepEmpty=*/false);
482
483 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
484 for (StringRef Type : Types)
485 DebugTypes |= StringSwitch<unsigned>(Type.lower())
486 .Case("cv", static_cast<unsigned>(DebugType::CV))
487 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000488 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
489 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000490 return DebugTypes;
491}
492
Hans Wennborg1818e652016-12-09 20:54:44 +0000493static std::string getMapFile(const opt::InputArgList &Args) {
494 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
495 if (!Arg)
496 return "";
497 if (Arg->getOption().getID() == OPT_lldmap_file)
498 return Arg->getValue();
499
500 assert(Arg->getOption().getID() == OPT_lldmap);
501 StringRef OutFile = Config->OutputFile;
502 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
503}
504
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000505static std::string getImplibPath() {
506 if (!Config->Implib.empty())
507 return Config->Implib;
508 SmallString<128> Out = StringRef(Config->OutputFile);
509 sys::path::replace_extension(Out, ".lib");
510 return Out.str();
511}
512
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000513//
514// The import name is caculated as the following:
515//
516// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
517// -----+----------------+---------------------+------------------
518// LINK | {value} | {value}.{.dll/.exe} | {output name}
519// LIB | {value} | {value}.dll | {output name}.dll
520//
521static std::string getImportName(bool AsLib) {
522 SmallString<128> Out;
523
524 if (Config->ImportName.empty()) {
525 Out.assign(sys::path::filename(Config->OutputFile));
526 if (AsLib)
527 sys::path::replace_extension(Out, ".dll");
528 } else {
529 Out.assign(Config->ImportName);
530 if (!sys::path::has_extension(Out))
531 sys::path::replace_extension(Out,
532 (Config->DLL || AsLib) ? ".dll" : ".exe");
533 }
534
535 return Out.str();
536}
537
538static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000539 std::vector<COFFShortExport> Exports;
540 for (Export &E1 : Config->Exports) {
541 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000542 E2.Name = E1.Name;
543 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000544 E2.ExtName = 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 Exports.push_back(E2);
551 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000552
Bob Haarman4ce341f2018-01-23 00:36:42 +0000553 auto HandleError = [](Error &&E) {
554 handleAllErrors(std::move(E),
555 [](ErrorInfoBase &EIB) { error(EIB.message()); });
556 };
557 std::string LibName = getImportName(AsLib);
558 std::string Path = getImplibPath();
559
Bob Haarman5ec44852018-01-31 23:44:00 +0000560 if (!Config->Incremental) {
561 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000562 Config->MinGW));
Bob Haarman5ec44852018-01-31 23:44:00 +0000563 return;
564 }
565
Bob Haarman4ce341f2018-01-23 00:36:42 +0000566 // If the import library already exists, replace it only if the contents
567 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000568 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
569 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000570 if (!OldBuf) {
571 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000572 Config->MinGW));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000573 return;
574 }
575
576 SmallString<128> TmpName;
577 if (std::error_code EC =
578 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
579 fatal("cannot create temporary file for import library " + Path + ": " +
580 EC.message());
581
582 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000583 Config->MinGW)) {
Bob Haarman4ce341f2018-01-23 00:36:42 +0000584 HandleError(std::move(E));
585 return;
586 }
587
Bob Haarman8832f882018-04-24 23:16:39 +0000588 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
589 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000590 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
591 OldBuf->reset();
592 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000593 } else {
594 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000595 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000596}
597
598static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000599 std::unique_ptr<MemoryBuffer> MB = CHECK(
600 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000601 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
602 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000603
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000604 if (Config->OutputFile.empty())
605 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000606 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000607 if (M.ImageBase)
608 Config->ImageBase = M.ImageBase;
609 if (M.StackReserve)
610 Config->StackReserve = M.StackReserve;
611 if (M.StackCommit)
612 Config->StackCommit = M.StackCommit;
613 if (M.HeapReserve)
614 Config->HeapReserve = M.HeapReserve;
615 if (M.HeapCommit)
616 Config->HeapCommit = M.HeapCommit;
617 if (M.MajorImageVersion)
618 Config->MajorImageVersion = M.MajorImageVersion;
619 if (M.MinorImageVersion)
620 Config->MinorImageVersion = M.MinorImageVersion;
621 if (M.MajorOSVersion)
622 Config->MajorOSVersion = M.MajorOSVersion;
623 if (M.MinorOSVersion)
624 Config->MinorOSVersion = M.MinorOSVersion;
625
626 for (COFFShortExport E1 : M.Exports) {
627 Export E2;
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000628 // In simple cases, only Name is set. Renamed exports are parsed
629 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
630 // it shouldn't be a normal exported function but a forward to another
631 // DLL instead. This is supported by both MS and GNU linkers.
632 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
Martin Storsjo5c84d442018-05-09 19:07:10 +0000633 E2.Name = Saver.save(E1.ExtName);
634 E2.ForwardTo = Saver.save(E1.Name);
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000635 Config->Exports.push_back(E2);
636 continue;
637 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000638 E2.Name = Saver.save(E1.Name);
Martin Storsjo97379ff2018-05-09 09:22:03 +0000639 E2.ExtName = Saver.save(E1.ExtName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000640 E2.Ordinal = E1.Ordinal;
641 E2.Noname = E1.Noname;
642 E2.Data = E1.Data;
643 E2.Private = E1.Private;
644 E2.Constant = E1.Constant;
645 Config->Exports.push_back(E2);
646 }
647}
648
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000649// A helper function for filterBitcodeFiles.
650static bool needsRebuilding(MemoryBufferRef MB) {
651 // The MSVC linker doesn't support thin archives, so if it's a thin
652 // archive, we always need to rebuild it.
653 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000654 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000655 if (File->isThin())
656 return true;
657
658 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000659 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000660 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
661 return true;
662 return false;
663}
664
665// Opens a given path as an archive file and removes bitcode files
666// from them if exists. This function is to appease the MSVC linker as
667// their linker doesn't like archive files containing non-native
668// object files.
669//
670// If a given archive doesn't contain bitcode files, the archive path
671// is returned as-is. Otherwise, a new temporary file is created and
672// its path is returned.
673static Optional<std::string>
674filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000675 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000676 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000677 MemoryBufferRef MBRef = MB->getMemBufferRef();
678 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000679
680 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000681 return None;
682 if (Magic != file_magic::archive)
683 return Path.str();
684 if (!needsRebuilding(MBRef))
685 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000686
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000687 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000688 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000689 MBRef.getBufferIdentifier() + ": failed to parse archive");
690
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000691 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000692 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000693 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
694 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000695
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000696 if (New.empty())
697 return None;
698
699 log("Creating a temporary archive for " + Path + " to remove bitcode files");
700
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000701 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000702 if (std::error_code EC = sys::fs::createTemporaryFile(
703 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000704 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000705 std::string Temp = S.str();
706 TemporaryFiles.push_back(Temp);
707
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000708 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000709 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
710 /*Deterministics=*/true,
711 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000712 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
713 error("failed to create a new archive " + S.str() + ": " + EI.message());
714 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000715 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000716}
717
718// Create response file contents and invoke the MSVC linker.
719void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000720 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000721 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000722
Bob Haarman41108162017-04-21 21:38:01 +0000723 // Write out archive members that we used in symbol resolution and pass these
724 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
725 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000726 for (ObjFile *Obj : ObjFile::Instances) {
727 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000728 continue;
729 SmallString<128> S;
730 int Fd;
731 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000732 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000733 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000734 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000735 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000736 Temps.push_back(S.str());
737 Rsp += quote(S) + "\n";
738 }
739
Rui Ueyama85d54b02017-02-23 00:26:42 +0000740 for (auto *Arg : Args) {
741 switch (Arg->getOption().getID()) {
742 case OPT_linkrepro:
743 case OPT_lldmap:
744 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000745 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000746 case OPT_msvclto:
747 // LLD-specific options are stripped.
748 break;
749 case OPT_opt:
750 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000751 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000752 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000753 case OPT_INPUT: {
754 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
755 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000756 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000757 continue;
758 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000759 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000760 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000761 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000762 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000763 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000764 }
765 }
766
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000767 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000768 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000769
770 for (StringRef Path : Temps)
771 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000772}
773
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000774void LinkerDriver::enqueueTask(std::function<void()> Task) {
775 TaskQueue.push_back(std::move(Task));
776}
777
778bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000779 ScopedTimer T(InputFileTimer);
780
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000781 bool DidWork = !TaskQueue.empty();
782 while (!TaskQueue.empty()) {
783 TaskQueue.front()();
784 TaskQueue.pop_front();
785 }
786 return DidWork;
787}
788
Rui Ueyama57175aa2018-01-27 00:34:46 +0000789// Parse an /order file. If an option is given, the linker places
790// COMDAT sections in the same order as their names appear in the
791// given file.
792static void parseOrderFile(StringRef Arg) {
793 // For some reason, the MSVC linker requires a filename to be
794 // preceded by "@".
795 if (!Arg.startswith("@")) {
796 error("malformed /order option: '@' missing");
797 return;
798 }
799
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000800 // Get a list of all comdat sections for error checking.
801 DenseSet<StringRef> Set;
802 for (Chunk *C : Symtab->getChunks())
803 if (auto *Sec = dyn_cast<SectionChunk>(C))
804 if (Sec->Sym)
805 Set.insert(Sec->Sym->getName());
806
Rui Ueyama57175aa2018-01-27 00:34:46 +0000807 // Open a file.
808 StringRef Path = Arg.substr(1);
809 std::unique_ptr<MemoryBuffer> MB = CHECK(
810 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
811
812 // Parse a file. An order file contains one symbol per line.
813 // All symbols that were not present in a given order file are
814 // considered to have the lowest priority 0 and are placed at
815 // end of an output section.
816 for (std::string S : args::getLines(MB->getMemBufferRef())) {
817 if (Config->Machine == I386 && !isDecorated(S))
818 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000819
Nico Weber0771c602018-03-09 12:41:04 +0000820 if (Set.count(S) == 0) {
821 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000822 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000823 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000824 else
825 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000826 }
827}
828
Rui Ueyama8fe17672016-12-08 20:50:47 +0000829void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000830 // If the first command line argument is "/lib", link.exe acts like lib.exe.
831 // We call our own implementation of lib.exe that understands bitcode files.
832 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
833 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000834 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000835 return;
836 }
837
Peter Collingbourne60c16162015-06-01 20:10:10 +0000838 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000839 InitializeAllTargetInfos();
840 InitializeAllTargets();
841 InitializeAllTargetMCs();
842 InitializeAllAsmParsers();
843 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000844
Rui Ueyama411c63602015-05-28 19:09:30 +0000845 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000846 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000847 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000848
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000849 // Parse and evaluate -mllvm options.
850 std::vector<const char *> V;
851 V.push_back("lld-link (LLVM option parsing)");
852 for (auto *Arg : Args.filtered(OPT_mllvm))
853 V.push_back(Arg->getValue());
854 cl::ParseCommandLineOptions(V.size(), V.data());
855
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000856 // Handle /errorlimit early, because error() depends on it.
857 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
858 int N = 20;
859 StringRef S = Arg->getValue();
860 if (S.getAsInteger(10, N))
861 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000862 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000863 }
864
Rui Ueyama5c726432015-05-29 16:11:52 +0000865 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000866 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000867 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000868 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000869 }
870
Zachary Turner727f1532018-01-17 19:16:26 +0000871 if (Args.hasArg(OPT_show_timing))
872 Config->ShowTiming = true;
873
874 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000875 // Handle --version, which is an lld extension. This option is a bit odd
876 // because it doesn't start with "/", but we deliberately chose "--" to
877 // avoid conflict with /version and for compatibility with clang-cl.
878 if (Args.hasArg(OPT_dash_dash_version)) {
879 outs() << getLLDVersion() << "\n";
880 return;
881 }
882
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000883 // Handle /lldmingw early, since it can potentially affect how other
884 // options are handled.
885 Config->MinGW = Args.hasArg(OPT_lldmingw);
886
Peter Collingbournefeee2102016-07-26 02:00:42 +0000887 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
888 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000889 sys::path::append(Path, "repro.tar");
890
891 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
892 TarWriter::create(Path, "repro");
893
894 if (ErrOrWriter) {
895 Tar = std::move(*ErrOrWriter);
896 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000897 error("/linkrepro: failed to open " + Path + ": " +
898 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000899 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000900 }
901
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000902 if (!Args.hasArg(OPT_INPUT)) {
903 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000904 Config->NoEntry = true;
905 else
906 fatal("no input files");
907 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000908
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000909 // Construct search path list.
910 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000911 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000912 SearchPaths.push_back(Arg->getValue());
913 addLibSearchPaths();
914
Bob Haarmane90ac012017-12-28 07:02:13 +0000915 // Handle /ignore
916 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000917 if (StringRef(Arg->getValue()) == "4037")
918 Config->WarnMissingOrderSymbol = false;
919 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000920 Config->WarnLocallyDefinedImported = false;
921 // Other warning numbers are ignored.
922 }
923
Rui Ueyamaad660982015-06-07 00:20:32 +0000924 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000925 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000926 Config->OutputFile = Arg->getValue();
927
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000928 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000929 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000930 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000931 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000932
Rui Ueyama95925fd2015-06-28 19:35:15 +0000933 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000934 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000935 Config->Force = true;
936
Rui Ueyama6600eb12015-07-04 23:37:32 +0000937 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000938 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000939 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000940 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000941 if (auto *Arg = Args.getLastArg(OPT_debugtype))
942 Config->DebugTypes = parseDebugType(Arg->getValue());
943 else
944 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000945 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000946
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000947 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000948 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000949 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000950 if (auto *Arg = Args.getLastArg(OPT_pdb))
951 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000952 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
953 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000954 if (Args.hasArg(OPT_natvis))
955 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
956 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000957
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000958 // Handle /noentry
959 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000960 if (Args.hasArg(OPT_dll))
961 Config->NoEntry = true;
962 else
963 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000964 }
965
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000966 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000967 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000968 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000969 Config->ManifestID = 2;
970 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000971
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000972 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
973 // because we need to explicitly check whether that option or its inverse was
974 // present in the argument list in order to handle /fixed.
975 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
976 if (DynamicBaseArg &&
977 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
978 Config->DynamicBase = false;
979
Nico Webera7643792018-03-30 17:17:04 +0000980 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
981 // default setting for any other project type.", but link.exe defaults to
982 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000983 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
984 if (Fixed) {
985 if (DynamicBaseArg &&
986 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000987 error("/fixed must not be specified with /dynamicbase");
988 } else {
989 Config->Relocatable = false;
990 Config->DynamicBase = false;
991 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000992 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000993
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000994 // Handle /appcontainer
995 Config->AppContainer =
996 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000997
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000998 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000999 if (auto *Arg = Args.getLastArg(OPT_machine))
1000 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +00001001
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001002 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +00001003 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001004 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1005
1006 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +00001007 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001008 Config->NoDefaultLibAll = true;
1009
Rui Ueyama804a8b62015-05-29 16:18:15 +00001010 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +00001011 if (auto *Arg = Args.getLastArg(OPT_base))
1012 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +00001013
1014 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +00001015 if (auto *Arg = Args.getLastArg(OPT_stack))
1016 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +00001017
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001018 // Handle /guard:cf
1019 if (auto *Arg = Args.getLastArg(OPT_guard))
1020 parseGuard(Arg->getValue());
1021
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001022 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +00001023 if (auto *Arg = Args.getLastArg(OPT_heap))
1024 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001025
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001026 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +00001027 if (auto *Arg = Args.getLastArg(OPT_version))
1028 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1029 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001030
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001031 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +00001032 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1033 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1034 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001035
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001036 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001037 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001038 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001039
Rui Ueyama08d5e182015-06-18 23:20:11 +00001040 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001041 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001042 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001043
Rui Ueyamab95188c2015-06-18 20:27:09 +00001044 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001045 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001046 Config->Implib = Arg->getValue();
1047
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001048 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001049 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1050 unsigned ICFLevel =
1051 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001052 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +00001053 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001054 std::string Str = StringRef(Arg->getValue()).lower();
1055 SmallVector<StringRef, 1> Vec;
1056 StringRef(Str).split(Vec, ',');
1057 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001058 if (S == "ref") {
1059 DoGC = true;
1060 } else if (S == "noref") {
1061 DoGC = false;
1062 } else if (S == "icf" || S.startswith("icf=")) {
1063 ICFLevel = 2;
1064 } else if (S == "noicf") {
1065 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001066 } else if (S == "lldtailmerge") {
1067 TailMerge = 2;
1068 } else if (S == "nolldtailmerge") {
1069 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001070 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001071 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001072 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
1073 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001074 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001075 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001076 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001077 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001078 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001079 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001080 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001081 if (N.getAsInteger(10, Config->LTOPartitions) ||
1082 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001083 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001084 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001085 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001086 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001087 }
1088
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001089 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1090 // explicitly.
1091 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1092 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1093 // comdat readonly data.
1094 if (ICFLevel == 1 && !DoGC)
1095 ICFLevel = 0;
1096 Config->DoGC = DoGC;
1097 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001098 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001099
Bob Haarman69b196d2017-02-08 18:36:41 +00001100 // Handle /lldsavetemps
1101 if (Args.hasArg(OPT_lldsavetemps))
1102 Config->SaveTemps = true;
1103
Martin Storsjo53518912018-03-14 20:17:16 +00001104 // Handle /kill-at
1105 if (Args.hasArg(OPT_kill_at))
1106 Config->KillAt = true;
1107
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001108 // Handle /lldltocache
1109 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1110 Config->LTOCache = Arg->getValue();
1111
1112 // Handle /lldsavecachepolicy
1113 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001114 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001115 parseCachePruningPolicy(Arg->getValue()),
1116 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1117
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001118 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001119 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001120 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001121
Rui Ueyama6600eb12015-07-04 23:37:32 +00001122 // Handle /merge
1123 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001124 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001125
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001126 // Add default section merging rules after user rules. User rules take
1127 // precedence, but we will emit a warning if there is a conflict.
1128 parseMerge(".idata=.rdata");
1129 parseMerge(".didat=.rdata");
1130 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001131 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001132 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001133
Rui Ueyama440138c2016-06-20 03:39:39 +00001134 // Handle /section
1135 for (auto *Arg : Args.filtered(OPT_section))
1136 parseSection(Arg->getValue());
1137
Martin Storsjod2752aa2017-08-14 19:07:27 +00001138 // Handle /aligncomm
1139 for (auto *Arg : Args.filtered(OPT_aligncomm))
1140 parseAligncomm(Arg->getValue());
1141
Nico Webera7a2c442017-07-25 18:08:03 +00001142 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1143 // also passed.
1144 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1145 Config->ManifestDependency = Arg->getValue();
1146 Config->Manifest = Configuration::SideBySide;
1147 }
1148
1149 // Handle /manifest and /manifest:
1150 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1151 if (Arg->getOption().getID() == OPT_manifest)
1152 Config->Manifest = Configuration::SideBySide;
1153 else
1154 parseManifest(Arg->getValue());
1155 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001156
1157 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001158 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1159 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001160
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001161 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001162 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001163 Config->ManifestFile = Arg->getValue();
1164
Rui Ueyamaafb19012016-04-19 01:21:58 +00001165 // Handle /manifestinput
1166 for (auto *Arg : Args.filtered(OPT_manifestinput))
1167 Config->ManifestInput.push_back(Arg->getValue());
1168
Nico Webera7a2c442017-07-25 18:08:03 +00001169 if (!Config->ManifestInput.empty() &&
1170 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001171 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001172 }
1173
Rui Ueyama6592ff82015-06-16 23:13:00 +00001174 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001175 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1176 Config->AllowIsolation =
1177 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001178 Config->Incremental =
1179 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001180 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1181 !Args.hasArg(OPT_profile));
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001182 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001183 Config->TerminalServerAware =
1184 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001185 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001186 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001187
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001188 Config->MapFile = getMapFile(Args);
1189
Nico Weber0945ad62018-03-30 17:14:50 +00001190 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1191 warn("ignoring '/incremental' due to '/profile' specification");
1192 Config->Incremental = false;
1193 }
1194
1195 if (Config->Incremental && Args.hasArg(OPT_order)) {
1196 warn("ignoring '/incremental' due to '/order' specification");
1197 Config->Incremental = false;
1198 }
1199
Bob Haarman5ec44852018-01-31 23:44:00 +00001200 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001201 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001202 "disable");
1203 Config->Incremental = false;
1204 }
1205
1206 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001207 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001208 "disable");
1209 Config->Incremental = false;
1210 }
1211
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001212 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001213 return;
1214
Martin Storsjo8278ba52017-09-13 07:28:03 +00001215 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001216 // Create a list of input files. Files can be given as arguments
1217 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001218 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001219 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1220 switch (Arg->getOption().getID()) {
1221 case OPT_INPUT:
1222 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1223 enqueuePath(*Path, WholeArchiveFlag);
1224 break;
1225 case OPT_wholearchive_file:
1226 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1227 enqueuePath(*Path, true);
1228 break;
1229 }
1230 }
David Blaikie6521ed92015-06-22 22:06:52 +00001231 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001232 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001233 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001234
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001235 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001236 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001237 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001238
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001239 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001240 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001241
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001242 // We should have inferred a machine type by now from the input files, but if
1243 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001244 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001245 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001246 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001247 }
1248
Eric Beckmann9e19d792017-06-17 02:26:27 +00001249 // Input files can be Windows resource files (.res files). We use
1250 // WindowsResource to convert resource files to a regular COFF file,
1251 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001252 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001253 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001254
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001255 if (Tar)
1256 Tar->append("response.txt",
1257 createResponseFile(Args, FilePaths,
1258 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001259
Rui Ueyama4d545342015-07-28 03:12:00 +00001260 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001261 Config->LargeAddressAware = Args.hasFlag(
1262 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001263
Rui Ueyamad68e2112015-07-28 03:15:57 +00001264 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001265 Config->HighEntropyVA =
1266 Config->is64() &&
1267 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001268
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001269 if (!Config->DynamicBase &&
1270 (Config->Machine == ARMNT || Config->Machine == ARM64))
1271 error("/dynamicbase:no is not compatible with " +
1272 machineToStr(Config->Machine));
1273
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001274 // Handle /entry and /dll
1275 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1276 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001277 } else if (!Config->Entry && !Config->NoEntry) {
1278 if (Args.hasArg(OPT_dll)) {
1279 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1280 : "_DllMainCRTStartup";
1281 Config->Entry = addUndefined(S);
1282 } else {
1283 // Windows specific -- If entry point name is not given, we need to
1284 // infer that from user-defined entry name.
1285 StringRef S = findDefaultEntry();
1286 if (S.empty())
1287 fatal("entry point must be defined");
1288 Config->Entry = addUndefined(S);
1289 log("Entry name inferred: " + S);
1290 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001291 }
1292
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001293 // Handle /export
1294 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001295 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001296 if (Config->Machine == I386) {
1297 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001298 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001299 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001300 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001301 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001302 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001303 }
1304
1305 // Handle /def
1306 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001307 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001308 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001309 }
1310
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001311 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001312 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001313 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001314 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001315 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001316 }
1317
Rui Ueyama6d249082015-07-13 22:31:45 +00001318 // Handle /delayload
1319 for (auto *Arg : Args.filtered(OPT_delayload)) {
1320 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001321 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001322 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001323 } else {
1324 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001325 }
1326 }
1327
Reid Kleckner7668182e2017-03-21 00:12:51 +00001328 // Set default image name if neither /out or /def set it.
1329 if (Config->OutputFile.empty()) {
1330 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001331 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001332 }
1333
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001334 if (ShouldCreatePDB) {
1335 // Put the PDB next to the image if no /pdb flag was passed.
1336 if (Config->PDBPath.empty()) {
1337 Config->PDBPath = Config->OutputFile;
1338 sys::path::replace_extension(Config->PDBPath, ".pdb");
1339 }
1340
1341 // The embedded PDB path should be the absolute path to the PDB if no
1342 // /pdbaltpath flag was passed.
1343 if (Config->PDBAltPath.empty()) {
1344 Config->PDBAltPath = Config->PDBPath;
1345 sys::fs::make_absolute(Config->PDBAltPath);
1346 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001347 }
1348
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001349 // Set default image base if /base is not given.
1350 if (Config->ImageBase == uint64_t(-1))
1351 Config->ImageBase = getDefaultImageBase();
1352
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001353 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001354 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001355 Symtab->addAbsolute("___safe_se_handler_table", 0);
1356 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001357 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001358
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001359 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1360 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001361 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001362 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1363 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1364 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1365 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001366 // Needed for MSVC 2017 15.5 CRT.
1367 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001368
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001369 // This code may add new undefined symbols to the link, which may enqueue more
1370 // symbol resolution tasks, so we need to continue executing tasks until we
1371 // converge.
1372 do {
1373 // Windows specific -- if entry point is not found,
1374 // search for its mangled names.
1375 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001376 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001377
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001378 // Windows specific -- Make sure we resolve all dllexported symbols.
1379 for (Export &E : Config->Exports) {
1380 if (!E.ForwardTo.empty())
1381 continue;
1382 E.Sym = addUndefined(E.Name);
1383 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001384 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001385 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001386
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001387 // Add weak aliases. Weak aliases is a mechanism to give remaining
1388 // undefined symbols final chance to be resolved successfully.
1389 for (auto Pair : Config->AlternateNames) {
1390 StringRef From = Pair.first;
1391 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001392 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001393 if (!Sym)
1394 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001395 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001396 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001397 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001398 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001399
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001400 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001401 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001402 addUndefined(mangle("_load_config_used"));
1403 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001404
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001405 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001406 return;
1407
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001408 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1409 // This is useful because MSVC link.exe can generate complete PDBs.
1410 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001411 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001412 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001413 }
1414
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001415 // Do LTO by compiling bitcode input files to a set of native COFF files then
1416 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001417 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001418 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001419
Peter Collingbourne2612a322015-07-04 05:28:41 +00001420 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001421 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001422 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001423 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001424
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001425 // Windows specific -- if no /subsystem is given, we need to infer
1426 // that from entry point name.
1427 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001428 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001429 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001430 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001431 }
1432
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001433 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001434 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001435 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001436 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001437 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001438 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001439 return;
1440 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001441
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001442 // In MinGW, all symbols are automatically exported if no symbols
1443 // are chosen to be exported.
1444 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1445 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001446 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001447
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001448 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001449 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001450 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001451 return;
1452 Export E;
1453 E.Name = Def->getName();
1454 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001455 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001456 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001457 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001458 Config->Exports.push_back(E);
1459 });
1460 }
1461
Rui Ueyama151d8622015-06-17 20:40:43 +00001462 // Windows specific -- when we are creating a .dll file, we also
1463 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001464 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001465 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001466 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001467 assignExportOrdinals();
1468 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001469
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001470 // Handle /output-def (MinGW specific).
1471 if (auto *Arg = Args.getLastArg(OPT_output_def))
1472 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001473
Martin Storsjod2752aa2017-08-14 19:07:27 +00001474 // Set extra alignment for .comm symbols
1475 for (auto Pair : Config->AlignComm) {
1476 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001477 uint32_t Alignment = Pair.second;
1478
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001479 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001480 if (!Sym) {
1481 warn("/aligncomm symbol " + Name + " not found");
1482 continue;
1483 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001484
Rui Ueyama616cd992017-10-31 16:10:24 +00001485 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001486 if (!DC) {
1487 warn("/aligncomm symbol " + Name + " of wrong kind");
1488 continue;
1489 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001490
1491 CommonChunk *C = DC->getChunk();
1492 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001493 }
1494
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001495 // Windows specific -- Create a side-by-side manifest file.
1496 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001497 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001498
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001499 // Handle /order. We want to do this at this moment because we
1500 // need a complete list of comdat sections to warn on nonexistent
1501 // functions.
1502 if (auto *Arg = Args.getLastArg(OPT_order))
1503 parseOrderFile(Arg->getValue());
1504
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001505 // Identify unreferenced COMDAT sections.
1506 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001507 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001508
1509 // Identify identical COMDAT sections to merge them.
1510 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001511 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001512
Rui Ueyama411c63602015-05-28 19:09:30 +00001513 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001514 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001515
1516 // Stop early so we can print the results.
1517 Timer::root().stop();
1518 if (Config->ShowTiming)
1519 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001520}
1521
Rui Ueyama411c63602015-05-28 19:09:30 +00001522} // namespace coff
1523} // namespace lld