blob: 2f7afaa1458b6fe3b00a09e9203f1baaf24d1bad [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) {
Nico Weberbbfe0b72018-07-20 23:09:12 +000059 errorHandler().LogName = sys::path::filename(Args[0]);
Bob Haarmanb8a59c82017-10-25 22:28:38 +000060 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>();
Rui Ueyamacbf969e2017-08-28 21:51:07 +000067
68 Symtab = make<SymbolTable>();
69
Rui Ueyama7fed58c2016-12-08 19:10:28 +000070 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000071 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000072
73 // Call exit() if we can to avoid calling destructors.
74 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000075 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000076
77 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000078 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000079}
Rui Ueyama411c63602015-05-28 19:09:30 +000080
Nico Weber5660de72016-04-20 22:34:15 +000081// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000082static std::string getOutputPath(StringRef Path) {
83 auto P = Path.find_last_of("\\/");
84 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000085 const char* E = Config->DLL ? ".dll" : ".exe";
86 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000087}
88
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000089// ErrorOr is not default constructible, so it cannot be used as the type
90// parameter of a future.
91// FIXME: We could open the file in createFutureForFile and avoid needing to
92// return an error here, but for the moment that would cost us a file descriptor
93// (a limited resource on Windows) for the duration that the future is pending.
94typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
95
96// Create a std::future that opens and maps a file using the best strategy for
97// the host platform.
98static std::future<MBErrPair> createFutureForFile(std::string Path) {
Nico Weberfb647302018-04-10 13:15:21 +000099#if _WIN32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000100 // On Windows, file I/O is relatively slow so it is best to do this
101 // asynchronously.
102 auto Strategy = std::launch::async;
103#else
104 auto Strategy = std::launch::deferred;
105#endif
106 return std::async(Strategy, [=]() {
Bob Haarman8832f882018-04-24 23:16:39 +0000107 auto MBOrErr = MemoryBuffer::getFile(Path,
108 /*FileSize*/ -1,
109 /*RequiresNullTerminator*/ false);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000110 if (!MBOrErr)
111 return MBErrPair{nullptr, MBOrErr.getError()};
112 return MBErrPair{std::move(*MBOrErr), std::error_code()};
113 });
114}
115
116MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
117 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000118 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000119
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000120 if (Driver->Tar)
121 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
122 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000123 return MBRef;
124}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000125
Martin Storsjo8278ba52017-09-13 07:28:03 +0000126void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
127 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000128 StringRef Filename = MB->getBufferIdentifier();
129
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000130 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000131 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000132
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000133 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000134 switch (identify_magic(MBRef.getBuffer())) {
135 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000136 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000137 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000138 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000139 if (WholeArchive) {
140 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000141 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000142
143 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000144 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000145 return;
146 }
147 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000148 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000149 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000150 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000151 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000152 case file_magic::coff_object:
153 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000154 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000155 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000156 case file_magic::coff_cl_gl_object:
157 error(Filename + ": is not a native COFF file. Recompile without /GL");
158 break;
159 case file_magic::pecoff_executable:
160 if (Filename.endswith_lower(".dll")) {
161 error(Filename + ": bad file type. Did you specify a DLL instead of an "
162 "import library?");
163 break;
164 }
165 LLVM_FALLTHROUGH;
166 default:
167 error(MBRef.getBufferIdentifier() + ": unknown file type");
168 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000169 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000170}
171
Martin Storsjo8278ba52017-09-13 07:28:03 +0000172void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000173 auto Future =
174 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
175 std::string PathStr = Path;
176 enqueueTask([=]() {
177 auto MBOrErr = Future->get();
178 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000179 error("could not open " + PathStr + ": " + MBOrErr.second.message());
180 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000181 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000182 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000183}
184
185void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
186 StringRef ParentName) {
187 file_magic Magic = identify_magic(MB.getBuffer());
188 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000189 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000190 return;
191 }
192
193 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000194 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000195 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000196 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000197 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000198 } else {
199 error("unknown file type: " + MB.getBufferIdentifier());
200 return;
201 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000202
203 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000204 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000205 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000206}
207
208void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
209 StringRef SymName,
210 StringRef ParentName) {
211 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000212 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000213 C.getMemoryBufferRef(),
214 "could not get the buffer for the member defining symbol " + SymName);
215 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
216 return;
217 }
218
219 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000220 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000221 "could not get the filename for the member defining symbol " +
222 SymName)));
223 enqueueTask([=]() {
224 auto MBOrErr = Future->get();
225 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000226 fatal("could not get the buffer for the member defining " + SymName +
227 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000228 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
229 ParentName);
230 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000231}
232
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000233static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000234 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
235 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000236}
237
Rui Ueyama411c63602015-05-28 19:09:30 +0000238// Parses .drectve section contents and returns a list of files
239// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000240void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000241 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000242 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000243 // /EXPORT: option can appear too many times, processing in fastpath.
244 opt::InputArgList Args;
245 std::vector<StringRef> Exports;
246 std::tie(Args, Exports) = Parser.parseDirectives(S);
247
248 for (StringRef E : Exports) {
249 // If a common header file contains dllexported function
250 // declarations, many object files may end up with having the
251 // same /EXPORT options. In order to save cost of parsing them,
252 // we dedup them first.
253 if (!DirectivesExports.insert(E).second)
254 continue;
255
256 Export Exp = parseExport(E);
257 if (Config->Machine == I386 && Config->MinGW) {
258 if (!isDecorated(Exp.Name))
259 Exp.Name = Saver.save("_" + Exp.Name);
260 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
261 Exp.ExtName = Saver.save("_" + Exp.ExtName);
262 }
263 Exp.Directives = true;
264 Config->Exports.push_back(Exp);
265 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000266
David Blaikie6521ed92015-06-22 22:06:52 +0000267 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000268 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000269 case OPT_aligncomm:
270 parseAligncomm(Arg->getValue());
271 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000272 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000273 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000274 break;
275 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000276 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000277 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000278 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000279 case OPT_entry:
280 Config->Entry = addUndefined(mangle(Arg->getValue()));
281 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000282 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000283 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000284 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000285 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000286 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000287 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000288 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000289 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000290 break;
291 case OPT_nodefaultlib:
292 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
293 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000294 case OPT_section:
295 parseSection(Arg->getValue());
296 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000297 case OPT_subsystem:
298 parseSubsystem(Arg->getValue(), &Config->Subsystem,
299 &Config->MajorOSVersion, &Config->MinorOSVersion);
300 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000301 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000302 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000303 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000304 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000305 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000306 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000307 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000308 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000309 }
310 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000311}
312
Rui Ueyama54b71da2015-05-31 19:17:12 +0000313// Find file from search paths. You can omit ".obj", this function takes
314// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000315StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000316 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
317 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000318 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000319 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000320 for (StringRef Dir : SearchPaths) {
321 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000322 sys::path::append(Path, Filename);
323 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000324 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000325 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000326 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000327 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000328 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000329 }
330 }
331 return Filename;
332}
333
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000334static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
335 sys::fs::UniqueID Ret;
336 if (sys::fs::getUniqueID(Path, Ret))
337 return None;
338 return Ret;
339}
340
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000341// Resolves a file path. This never returns the same path
342// (in that case, it returns None).
343Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
344 StringRef Path = doFindFile(Filename);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000345
346 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
347 bool Seen = !VisitedFiles.insert(*ID).second;
348 if (Seen)
349 return None;
350 }
351
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000352 if (Path.endswith_lower(".lib"))
353 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000354 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000355}
356
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000357// Find library file from search path.
358StringRef LinkerDriver::doFindLib(StringRef Filename) {
359 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000360 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000361 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000362 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000363 return doFindFile(Filename);
364}
365
366// Resolves a library path. /nodefaultlib options are taken into
367// consideration. This never returns the same path (in that case,
368// it returns None).
369Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
370 if (Config->NoDefaultLibAll)
371 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000372 if (!VisitedLibs.insert(Filename.lower()).second)
373 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000374
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000375 StringRef Path = doFindLib(Filename);
376 if (Config->NoDefaultLibs.count(Path))
377 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000378
379 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
380 if (!VisitedFiles.insert(*ID).second)
381 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000382 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000383}
384
385// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000386void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000387 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
388 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000389 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000390 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000391 while (!Env.empty()) {
392 StringRef Path;
393 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000394 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000395 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000396}
397
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000398Symbol *LinkerDriver::addUndefined(StringRef Name) {
399 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000400 if (!B->IsGCRoot) {
401 B->IsGCRoot = true;
402 Config->GCRoot.push_back(B);
403 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000404 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000405}
406
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000407// Symbol names are mangled by appending "_" prefix on x86.
408StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000409 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
410 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000411 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000412 return Sym;
413}
414
Rui Ueyama45044f42015-06-29 01:03:53 +0000415// Windows specific -- find default entry point name.
Rui Ueyamac93530d2018-07-18 17:48:14 +0000416//
417// There are four different entry point functions for Windows executables,
418// each of which corresponds to a user-defined "main" function. This function
419// infers an entry point from a user-defined "main" function.
Rui Ueyama45044f42015-06-29 01:03:53 +0000420StringRef LinkerDriver::findDefaultEntry() {
Rui Ueyamac93530d2018-07-18 17:48:14 +0000421 // As a special case, if /nodefaultlib is given, we directly look for an
422 // entry point. This is because, if no default library is linked, users
423 // need to define an entry point instead of a "main".
424 if (Config->NoDefaultLibAll) {
425 for (StringRef S : {"mainCRTStartup", "wmainCRTStartup",
426 "WinMainCRTStartup", "wWinMainCRTStartup"}) {
427 StringRef Entry = Symtab->findMangle(S);
428 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
429 return mangle(S);
430 }
431 return "";
432 }
433
Rui Ueyama45044f42015-06-29 01:03:53 +0000434 // User-defined main functions and their corresponding entry points.
435 static const char *Entries[][2] = {
436 {"main", "mainCRTStartup"},
437 {"wmain", "wmainCRTStartup"},
438 {"WinMain", "WinMainCRTStartup"},
439 {"wWinMain", "wWinMainCRTStartup"},
440 };
441 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000442 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000443 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000444 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000445 }
446 return "";
447}
448
449WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000450 if (Config->DLL)
451 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000452 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000453 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000454 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000455 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
456 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000457}
458
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000459static uint64_t getDefaultImageBase() {
460 if (Config->is64())
461 return Config->DLL ? 0x180000000 : 0x140000000;
462 return Config->DLL ? 0x10000000 : 0x400000;
463}
464
Rui Ueyama8fe17672016-12-08 20:50:47 +0000465static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000466 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000467 ArrayRef<StringRef> SearchPaths) {
468 SmallString<0> Data;
469 raw_svector_ostream OS(Data);
470
471 for (auto *Arg : Args) {
472 switch (Arg->getOption().getID()) {
473 case OPT_linkrepro:
474 case OPT_INPUT:
475 case OPT_defaultlib:
476 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000477 case OPT_manifest:
478 case OPT_manifest_colon:
479 case OPT_manifestdependency:
480 case OPT_manifestfile:
481 case OPT_manifestinput:
482 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000483 break;
484 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000485 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000486 }
487 }
488
489 for (StringRef Path : SearchPaths) {
490 std::string RelPath = relativeToRoot(Path);
491 OS << "/libpath:" << quote(RelPath) << "\n";
492 }
493
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000494 for (StringRef Path : FilePaths)
495 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000496
497 return Data.str();
498}
499
Rui Ueyama8fe17672016-12-08 20:50:47 +0000500static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000501 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
502 if (Args.hasArg(OPT_driver))
503 DebugTypes |= static_cast<unsigned>(DebugType::PData);
504 if (Args.hasArg(OPT_profile))
505 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
506 return DebugTypes;
507}
508
509static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000510 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000511 Arg.split(Types, ',', /*KeepEmpty=*/false);
512
513 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
514 for (StringRef Type : Types)
515 DebugTypes |= StringSwitch<unsigned>(Type.lower())
516 .Case("cv", static_cast<unsigned>(DebugType::CV))
517 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000518 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
519 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000520 return DebugTypes;
521}
522
Hans Wennborg1818e652016-12-09 20:54:44 +0000523static std::string getMapFile(const opt::InputArgList &Args) {
524 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
525 if (!Arg)
526 return "";
527 if (Arg->getOption().getID() == OPT_lldmap_file)
528 return Arg->getValue();
529
530 assert(Arg->getOption().getID() == OPT_lldmap);
531 StringRef OutFile = Config->OutputFile;
532 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
533}
534
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000535static std::string getImplibPath() {
536 if (!Config->Implib.empty())
537 return Config->Implib;
538 SmallString<128> Out = StringRef(Config->OutputFile);
539 sys::path::replace_extension(Out, ".lib");
540 return Out.str();
541}
542
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000543//
544// The import name is caculated as the following:
545//
546// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
547// -----+----------------+---------------------+------------------
548// LINK | {value} | {value}.{.dll/.exe} | {output name}
549// LIB | {value} | {value}.dll | {output name}.dll
550//
551static std::string getImportName(bool AsLib) {
552 SmallString<128> Out;
553
554 if (Config->ImportName.empty()) {
555 Out.assign(sys::path::filename(Config->OutputFile));
556 if (AsLib)
557 sys::path::replace_extension(Out, ".dll");
558 } else {
559 Out.assign(Config->ImportName);
560 if (!sys::path::has_extension(Out))
561 sys::path::replace_extension(Out,
562 (Config->DLL || AsLib) ? ".dll" : ".exe");
563 }
564
565 return Out.str();
566}
567
568static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000569 std::vector<COFFShortExport> Exports;
570 for (Export &E1 : Config->Exports) {
571 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000572 E2.Name = E1.Name;
573 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000574 E2.ExtName = E1.ExtName;
575 E2.Ordinal = E1.Ordinal;
576 E2.Noname = E1.Noname;
577 E2.Data = E1.Data;
578 E2.Private = E1.Private;
579 E2.Constant = E1.Constant;
580 Exports.push_back(E2);
581 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000582
Bob Haarman4ce341f2018-01-23 00:36:42 +0000583 auto HandleError = [](Error &&E) {
584 handleAllErrors(std::move(E),
585 [](ErrorInfoBase &EIB) { error(EIB.message()); });
586 };
587 std::string LibName = getImportName(AsLib);
588 std::string Path = getImplibPath();
589
Bob Haarman5ec44852018-01-31 23:44:00 +0000590 if (!Config->Incremental) {
591 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000592 Config->MinGW));
Bob Haarman5ec44852018-01-31 23:44:00 +0000593 return;
594 }
595
Bob Haarman4ce341f2018-01-23 00:36:42 +0000596 // If the import library already exists, replace it only if the contents
597 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000598 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
599 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000600 if (!OldBuf) {
601 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000602 Config->MinGW));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000603 return;
604 }
605
606 SmallString<128> TmpName;
607 if (std::error_code EC =
608 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
609 fatal("cannot create temporary file for import library " + Path + ": " +
610 EC.message());
611
612 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000613 Config->MinGW)) {
Bob Haarman4ce341f2018-01-23 00:36:42 +0000614 HandleError(std::move(E));
615 return;
616 }
617
Bob Haarman8832f882018-04-24 23:16:39 +0000618 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
619 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000620 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
621 OldBuf->reset();
622 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000623 } else {
624 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000625 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000626}
627
628static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000629 std::unique_ptr<MemoryBuffer> MB = CHECK(
630 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000631 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
632 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000633
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000634 if (Config->OutputFile.empty())
635 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000636 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000637 if (M.ImageBase)
638 Config->ImageBase = M.ImageBase;
639 if (M.StackReserve)
640 Config->StackReserve = M.StackReserve;
641 if (M.StackCommit)
642 Config->StackCommit = M.StackCommit;
643 if (M.HeapReserve)
644 Config->HeapReserve = M.HeapReserve;
645 if (M.HeapCommit)
646 Config->HeapCommit = M.HeapCommit;
647 if (M.MajorImageVersion)
648 Config->MajorImageVersion = M.MajorImageVersion;
649 if (M.MinorImageVersion)
650 Config->MinorImageVersion = M.MinorImageVersion;
651 if (M.MajorOSVersion)
652 Config->MajorOSVersion = M.MajorOSVersion;
653 if (M.MinorOSVersion)
654 Config->MinorOSVersion = M.MinorOSVersion;
655
656 for (COFFShortExport E1 : M.Exports) {
657 Export E2;
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000658 // In simple cases, only Name is set. Renamed exports are parsed
659 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
660 // it shouldn't be a normal exported function but a forward to another
661 // DLL instead. This is supported by both MS and GNU linkers.
662 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
Martin Storsjo5c84d442018-05-09 19:07:10 +0000663 E2.Name = Saver.save(E1.ExtName);
664 E2.ForwardTo = Saver.save(E1.Name);
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000665 Config->Exports.push_back(E2);
666 continue;
667 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000668 E2.Name = Saver.save(E1.Name);
Martin Storsjo97379ff2018-05-09 09:22:03 +0000669 E2.ExtName = Saver.save(E1.ExtName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000670 E2.Ordinal = E1.Ordinal;
671 E2.Noname = E1.Noname;
672 E2.Data = E1.Data;
673 E2.Private = E1.Private;
674 E2.Constant = E1.Constant;
675 Config->Exports.push_back(E2);
676 }
677}
678
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000679// A helper function for filterBitcodeFiles.
680static bool needsRebuilding(MemoryBufferRef MB) {
681 // The MSVC linker doesn't support thin archives, so if it's a thin
682 // archive, we always need to rebuild it.
683 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000684 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000685 if (File->isThin())
686 return true;
687
688 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000689 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000690 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
691 return true;
692 return false;
693}
694
695// Opens a given path as an archive file and removes bitcode files
696// from them if exists. This function is to appease the MSVC linker as
697// their linker doesn't like archive files containing non-native
698// object files.
699//
700// If a given archive doesn't contain bitcode files, the archive path
701// is returned as-is. Otherwise, a new temporary file is created and
702// its path is returned.
703static Optional<std::string>
704filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000705 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000706 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000707 MemoryBufferRef MBRef = MB->getMemBufferRef();
708 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000709
710 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000711 return None;
712 if (Magic != file_magic::archive)
713 return Path.str();
714 if (!needsRebuilding(MBRef))
715 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000716
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000717 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000718 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000719 MBRef.getBufferIdentifier() + ": failed to parse archive");
720
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000721 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000722 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000723 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
724 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000725
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000726 if (New.empty())
727 return None;
728
729 log("Creating a temporary archive for " + Path + " to remove bitcode files");
730
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000731 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000732 if (std::error_code EC = sys::fs::createTemporaryFile(
733 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000734 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000735 std::string Temp = S.str();
736 TemporaryFiles.push_back(Temp);
737
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000738 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000739 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
740 /*Deterministics=*/true,
741 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000742 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
743 error("failed to create a new archive " + S.str() + ": " + EI.message());
744 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000745 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000746}
747
748// Create response file contents and invoke the MSVC linker.
749void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000750 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000751 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000752
Bob Haarman41108162017-04-21 21:38:01 +0000753 // Write out archive members that we used in symbol resolution and pass these
754 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
755 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000756 for (ObjFile *Obj : ObjFile::Instances) {
757 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000758 continue;
759 SmallString<128> S;
760 int Fd;
761 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000762 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000763 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000764 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000765 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000766 Temps.push_back(S.str());
767 Rsp += quote(S) + "\n";
768 }
769
Rui Ueyama85d54b02017-02-23 00:26:42 +0000770 for (auto *Arg : Args) {
771 switch (Arg->getOption().getID()) {
772 case OPT_linkrepro:
773 case OPT_lldmap:
774 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000775 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000776 case OPT_msvclto:
777 // LLD-specific options are stripped.
778 break;
779 case OPT_opt:
780 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000781 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000782 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000783 case OPT_INPUT: {
784 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
785 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000786 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000787 continue;
788 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000789 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000790 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000791 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000792 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000793 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000794 }
795 }
796
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000797 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000798 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000799
800 for (StringRef Path : Temps)
801 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000802}
803
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000804void LinkerDriver::enqueueTask(std::function<void()> Task) {
805 TaskQueue.push_back(std::move(Task));
806}
807
808bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000809 ScopedTimer T(InputFileTimer);
810
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000811 bool DidWork = !TaskQueue.empty();
812 while (!TaskQueue.empty()) {
813 TaskQueue.front()();
814 TaskQueue.pop_front();
815 }
816 return DidWork;
817}
818
Rui Ueyama57175aa2018-01-27 00:34:46 +0000819// Parse an /order file. If an option is given, the linker places
820// COMDAT sections in the same order as their names appear in the
821// given file.
822static void parseOrderFile(StringRef Arg) {
823 // For some reason, the MSVC linker requires a filename to be
824 // preceded by "@".
825 if (!Arg.startswith("@")) {
826 error("malformed /order option: '@' missing");
827 return;
828 }
829
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000830 // Get a list of all comdat sections for error checking.
831 DenseSet<StringRef> Set;
832 for (Chunk *C : Symtab->getChunks())
833 if (auto *Sec = dyn_cast<SectionChunk>(C))
834 if (Sec->Sym)
835 Set.insert(Sec->Sym->getName());
836
Rui Ueyama57175aa2018-01-27 00:34:46 +0000837 // Open a file.
838 StringRef Path = Arg.substr(1);
839 std::unique_ptr<MemoryBuffer> MB = CHECK(
840 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
841
842 // Parse a file. An order file contains one symbol per line.
843 // All symbols that were not present in a given order file are
844 // considered to have the lowest priority 0 and are placed at
845 // end of an output section.
846 for (std::string S : args::getLines(MB->getMemBufferRef())) {
847 if (Config->Machine == I386 && !isDecorated(S))
848 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000849
Nico Weber0771c602018-03-09 12:41:04 +0000850 if (Set.count(S) == 0) {
851 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000852 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000853 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000854 else
855 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000856 }
857}
858
Rui Ueyama8fe17672016-12-08 20:50:47 +0000859void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000860 // If the first command line argument is "/lib", link.exe acts like lib.exe.
861 // We call our own implementation of lib.exe that understands bitcode files.
862 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
863 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000864 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000865 return;
866 }
867
Peter Collingbourne60c16162015-06-01 20:10:10 +0000868 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000869 InitializeAllTargetInfos();
870 InitializeAllTargets();
871 InitializeAllTargetMCs();
872 InitializeAllAsmParsers();
873 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000874
Rui Ueyama411c63602015-05-28 19:09:30 +0000875 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000876 ArgParser Parser;
Reid Kleckner276d7162018-07-20 22:34:20 +0000877 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000878
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000879 // Parse and evaluate -mllvm options.
880 std::vector<const char *> V;
881 V.push_back("lld-link (LLVM option parsing)");
882 for (auto *Arg : Args.filtered(OPT_mllvm))
883 V.push_back(Arg->getValue());
884 cl::ParseCommandLineOptions(V.size(), V.data());
885
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000886 // Handle /errorlimit early, because error() depends on it.
887 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
888 int N = 20;
889 StringRef S = Arg->getValue();
890 if (S.getAsInteger(10, N))
891 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000892 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000893 }
894
Rui Ueyama5c726432015-05-29 16:11:52 +0000895 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000896 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000897 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000898 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000899 }
900
Zachary Turner727f1532018-01-17 19:16:26 +0000901 if (Args.hasArg(OPT_show_timing))
902 Config->ShowTiming = true;
903
904 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000905 // Handle --version, which is an lld extension. This option is a bit odd
906 // because it doesn't start with "/", but we deliberately chose "--" to
907 // avoid conflict with /version and for compatibility with clang-cl.
908 if (Args.hasArg(OPT_dash_dash_version)) {
909 outs() << getLLDVersion() << "\n";
910 return;
911 }
912
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000913 // Handle /lldmingw early, since it can potentially affect how other
914 // options are handled.
915 Config->MinGW = Args.hasArg(OPT_lldmingw);
916
Peter Collingbournefeee2102016-07-26 02:00:42 +0000917 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
918 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000919 sys::path::append(Path, "repro.tar");
920
921 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
922 TarWriter::create(Path, "repro");
923
924 if (ErrOrWriter) {
925 Tar = std::move(*ErrOrWriter);
926 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000927 error("/linkrepro: failed to open " + Path + ": " +
928 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000929 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000930 }
931
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000932 if (!Args.hasArg(OPT_INPUT)) {
933 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000934 Config->NoEntry = true;
935 else
936 fatal("no input files");
937 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000938
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000939 // Construct search path list.
940 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000941 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000942 SearchPaths.push_back(Arg->getValue());
943 addLibSearchPaths();
944
Bob Haarmane90ac012017-12-28 07:02:13 +0000945 // Handle /ignore
946 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000947 if (StringRef(Arg->getValue()) == "4037")
948 Config->WarnMissingOrderSymbol = false;
949 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000950 Config->WarnLocallyDefinedImported = false;
951 // Other warning numbers are ignored.
952 }
953
Rui Ueyamaad660982015-06-07 00:20:32 +0000954 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000955 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000956 Config->OutputFile = Arg->getValue();
957
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000958 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000959 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000960 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000961 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000962
Rui Ueyama95925fd2015-06-28 19:35:15 +0000963 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000964 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000965 Config->Force = true;
966
Rui Ueyama6600eb12015-07-04 23:37:32 +0000967 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000968 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000969 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000970 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000971 if (auto *Arg = Args.getLastArg(OPT_debugtype))
972 Config->DebugTypes = parseDebugType(Arg->getValue());
973 else
974 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000975 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000976
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000977 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000978 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000979 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000980 if (auto *Arg = Args.getLastArg(OPT_pdb))
981 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000982 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
983 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000984 if (Args.hasArg(OPT_natvis))
985 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
Takuto Ikutad8559282018-07-19 04:56:22 +0000986
987 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
988 Config->PDBSourcePath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000989 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000990
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000991 // Handle /noentry
992 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000993 if (Args.hasArg(OPT_dll))
994 Config->NoEntry = true;
995 else
996 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000997 }
998
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000999 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +00001000 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001001 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001002 Config->ManifestID = 2;
1003 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001004
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001005 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1006 // because we need to explicitly check whether that option or its inverse was
1007 // present in the argument list in order to handle /fixed.
1008 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1009 if (DynamicBaseArg &&
1010 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1011 Config->DynamicBase = false;
1012
Nico Webera7643792018-03-30 17:17:04 +00001013 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1014 // default setting for any other project type.", but link.exe defaults to
1015 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001016 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1017 if (Fixed) {
1018 if (DynamicBaseArg &&
1019 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001020 error("/fixed must not be specified with /dynamicbase");
1021 } else {
1022 Config->Relocatable = false;
1023 Config->DynamicBase = false;
1024 }
Rui Ueyama6592ff82015-06-16 23:13:00 +00001025 }
Rui Ueyama588e8322015-06-15 01:23:58 +00001026
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001027 // Handle /appcontainer
1028 Config->AppContainer =
1029 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +00001030
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +00001031 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +00001032 if (auto *Arg = Args.getLastArg(OPT_machine))
1033 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +00001034
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001035 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +00001036 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001037 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1038
1039 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +00001040 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001041 Config->NoDefaultLibAll = true;
1042
Rui Ueyama804a8b62015-05-29 16:18:15 +00001043 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +00001044 if (auto *Arg = Args.getLastArg(OPT_base))
1045 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +00001046
1047 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +00001048 if (auto *Arg = Args.getLastArg(OPT_stack))
1049 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +00001050
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001051 // Handle /guard:cf
1052 if (auto *Arg = Args.getLastArg(OPT_guard))
1053 parseGuard(Arg->getValue());
1054
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001055 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +00001056 if (auto *Arg = Args.getLastArg(OPT_heap))
1057 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001058
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001059 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +00001060 if (auto *Arg = Args.getLastArg(OPT_version))
1061 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1062 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001063
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001064 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +00001065 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1066 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1067 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001068
Zachary Turnerc8dd6cc2018-05-17 15:11:01 +00001069 // Handle /timestamp
1070 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1071 if (Arg->getOption().getID() == OPT_repro) {
1072 Config->Timestamp = 0;
1073 Config->Repro = true;
1074 } else {
1075 Config->Repro = false;
1076 StringRef Value(Arg->getValue());
1077 if (Value.getAsInteger(0, Config->Timestamp))
1078 fatal(Twine("invalid timestamp: ") + Value +
1079 ". Expected 32-bit integer");
1080 }
1081 } else {
1082 Config->Repro = false;
1083 Config->Timestamp = time(nullptr);
1084 }
1085
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001086 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001087 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001088 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001089
Rui Ueyama08d5e182015-06-18 23:20:11 +00001090 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001091 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001092 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001093
Rui Ueyamab95188c2015-06-18 20:27:09 +00001094 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001095 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001096 Config->Implib = Arg->getValue();
1097
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001098 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001099 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1100 unsigned ICFLevel =
1101 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001102 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +00001103 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001104 std::string Str = StringRef(Arg->getValue()).lower();
1105 SmallVector<StringRef, 1> Vec;
1106 StringRef(Str).split(Vec, ',');
1107 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001108 if (S == "ref") {
1109 DoGC = true;
1110 } else if (S == "noref") {
1111 DoGC = false;
1112 } else if (S == "icf" || S.startswith("icf=")) {
1113 ICFLevel = 2;
1114 } else if (S == "noicf") {
1115 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001116 } else if (S == "lldtailmerge") {
1117 TailMerge = 2;
1118 } else if (S == "nolldtailmerge") {
1119 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001120 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001121 StringRef OptLevel = S.substr(7);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001122 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001123 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001124 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001125 StringRef Jobs = S.substr(11);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001126 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1127 Config->ThinLTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001128 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001129 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001130 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001131 if (N.getAsInteger(10, Config->LTOPartitions) ||
1132 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001133 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001134 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001135 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001136 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001137 }
1138
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001139 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1140 // explicitly.
1141 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1142 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1143 // comdat readonly data.
1144 if (ICFLevel == 1 && !DoGC)
1145 ICFLevel = 0;
1146 Config->DoGC = DoGC;
1147 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001148 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001149
Bob Haarman69b196d2017-02-08 18:36:41 +00001150 // Handle /lldsavetemps
1151 if (Args.hasArg(OPT_lldsavetemps))
1152 Config->SaveTemps = true;
1153
Martin Storsjo53518912018-03-14 20:17:16 +00001154 // Handle /kill-at
1155 if (Args.hasArg(OPT_kill_at))
1156 Config->KillAt = true;
1157
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001158 // Handle /lldltocache
1159 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1160 Config->LTOCache = Arg->getValue();
1161
1162 // Handle /lldsavecachepolicy
1163 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001164 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001165 parseCachePruningPolicy(Arg->getValue()),
1166 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1167
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001168 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001169 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001170 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001171
Rui Ueyama6600eb12015-07-04 23:37:32 +00001172 // Handle /merge
1173 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001174 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001175
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001176 // Add default section merging rules after user rules. User rules take
1177 // precedence, but we will emit a warning if there is a conflict.
1178 parseMerge(".idata=.rdata");
1179 parseMerge(".didat=.rdata");
1180 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001181 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001182 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001183
Rui Ueyama440138c2016-06-20 03:39:39 +00001184 // Handle /section
1185 for (auto *Arg : Args.filtered(OPT_section))
1186 parseSection(Arg->getValue());
1187
Martin Storsjod2752aa2017-08-14 19:07:27 +00001188 // Handle /aligncomm
1189 for (auto *Arg : Args.filtered(OPT_aligncomm))
1190 parseAligncomm(Arg->getValue());
1191
Nico Webera7a2c442017-07-25 18:08:03 +00001192 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1193 // also passed.
1194 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1195 Config->ManifestDependency = Arg->getValue();
1196 Config->Manifest = Configuration::SideBySide;
1197 }
1198
1199 // Handle /manifest and /manifest:
1200 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1201 if (Arg->getOption().getID() == OPT_manifest)
1202 Config->Manifest = Configuration::SideBySide;
1203 else
1204 parseManifest(Arg->getValue());
1205 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001206
1207 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001208 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1209 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001210
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001211 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001212 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001213 Config->ManifestFile = Arg->getValue();
1214
Rui Ueyamaafb19012016-04-19 01:21:58 +00001215 // Handle /manifestinput
1216 for (auto *Arg : Args.filtered(OPT_manifestinput))
1217 Config->ManifestInput.push_back(Arg->getValue());
1218
Nico Webera7a2c442017-07-25 18:08:03 +00001219 if (!Config->ManifestInput.empty() &&
1220 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001221 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001222 }
1223
Rui Ueyama6592ff82015-06-16 23:13:00 +00001224 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001225 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1226 Config->AllowIsolation =
1227 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001228 Config->Incremental =
1229 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001230 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1231 !Args.hasArg(OPT_profile));
Nico Weberd657c252018-05-31 13:43:02 +00001232 Config->IntegrityCheck =
1233 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001234 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001235 Config->TerminalServerAware =
1236 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001237 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001238 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Martin Storsjo3a7905b2018-06-29 06:08:25 +00001239 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001240
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001241 Config->MapFile = getMapFile(Args);
1242
Nico Weber0945ad62018-03-30 17:14:50 +00001243 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1244 warn("ignoring '/incremental' due to '/profile' specification");
1245 Config->Incremental = false;
1246 }
1247
1248 if (Config->Incremental && Args.hasArg(OPT_order)) {
1249 warn("ignoring '/incremental' due to '/order' specification");
1250 Config->Incremental = false;
1251 }
1252
Bob Haarman5ec44852018-01-31 23:44:00 +00001253 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001254 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001255 "disable");
1256 Config->Incremental = false;
1257 }
1258
1259 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001260 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001261 "disable");
1262 Config->Incremental = false;
1263 }
1264
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001265 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001266 return;
1267
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001268 std::set<sys::fs::UniqueID> WholeArchives;
1269 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
Reid Kleckner34085682018-06-14 19:56:03 +00001270 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1271 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1272 WholeArchives.insert(*ID);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001273
1274 // A predicate returning true if a given path is an argument for
1275 // /wholearchive:, or /wholearchive is enabled globally.
1276 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1277 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1278 auto IsWholeArchive = [&](StringRef Path) -> bool {
1279 if (Args.hasArg(OPT_wholearchive_flag))
1280 return true;
1281 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1282 return WholeArchives.count(*ID);
1283 return false;
1284 };
1285
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001286 // Create a list of input files. Files can be given as arguments
1287 // for /defaultlib option.
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001288 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1289 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Reid Kleckner34085682018-06-14 19:56:03 +00001290 enqueuePath(*Path, IsWholeArchive(*Path));
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001291
David Blaikie6521ed92015-06-22 22:06:52 +00001292 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001293 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001294 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001295
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001296 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001297 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001298 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001299
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001300 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001301 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001302
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001303 // We should have inferred a machine type by now from the input files, but if
1304 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001305 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001306 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001307 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001308 }
1309
Eric Beckmann9e19d792017-06-17 02:26:27 +00001310 // Input files can be Windows resource files (.res files). We use
1311 // WindowsResource to convert resource files to a regular COFF file,
1312 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001313 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001314 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001315
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001316 if (Tar)
1317 Tar->append("response.txt",
1318 createResponseFile(Args, FilePaths,
1319 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001320
Rui Ueyama4d545342015-07-28 03:12:00 +00001321 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001322 Config->LargeAddressAware = Args.hasFlag(
1323 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001324
Rui Ueyamad68e2112015-07-28 03:15:57 +00001325 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001326 Config->HighEntropyVA =
1327 Config->is64() &&
1328 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001329
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001330 if (!Config->DynamicBase &&
1331 (Config->Machine == ARMNT || Config->Machine == ARM64))
1332 error("/dynamicbase:no is not compatible with " +
1333 machineToStr(Config->Machine));
1334
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001335 // Handle /entry and /dll
1336 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1337 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001338 } else if (!Config->Entry && !Config->NoEntry) {
1339 if (Args.hasArg(OPT_dll)) {
1340 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1341 : "_DllMainCRTStartup";
1342 Config->Entry = addUndefined(S);
1343 } else {
1344 // Windows specific -- If entry point name is not given, we need to
1345 // infer that from user-defined entry name.
1346 StringRef S = findDefaultEntry();
1347 if (S.empty())
1348 fatal("entry point must be defined");
1349 Config->Entry = addUndefined(S);
1350 log("Entry name inferred: " + S);
1351 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001352 }
1353
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001354 // Handle /export
1355 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001356 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001357 if (Config->Machine == I386) {
1358 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001359 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001360 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001361 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001362 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001363 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001364 }
1365
1366 // Handle /def
1367 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001368 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001369 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001370 }
1371
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001372 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001373 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001374 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001375 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001376 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001377 }
1378
Rui Ueyama6d249082015-07-13 22:31:45 +00001379 // Handle /delayload
1380 for (auto *Arg : Args.filtered(OPT_delayload)) {
1381 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001382 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001383 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001384 } else {
1385 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001386 }
1387 }
1388
Reid Kleckner7668182e2017-03-21 00:12:51 +00001389 // Set default image name if neither /out or /def set it.
1390 if (Config->OutputFile.empty()) {
1391 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001392 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001393 }
1394
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001395 if (ShouldCreatePDB) {
1396 // Put the PDB next to the image if no /pdb flag was passed.
1397 if (Config->PDBPath.empty()) {
1398 Config->PDBPath = Config->OutputFile;
1399 sys::path::replace_extension(Config->PDBPath, ".pdb");
1400 }
1401
1402 // The embedded PDB path should be the absolute path to the PDB if no
1403 // /pdbaltpath flag was passed.
1404 if (Config->PDBAltPath.empty()) {
1405 Config->PDBAltPath = Config->PDBPath;
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001406
1407 // It's important to make the path absolute and remove dots. This path
1408 // will eventually be written into the PE header, and certain Microsoft
1409 // tools won't work correctly if these assumptions are not held.
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001410 sys::fs::make_absolute(Config->PDBAltPath);
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001411 sys::path::remove_dots(Config->PDBAltPath);
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001412 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001413 }
1414
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001415 // Set default image base if /base is not given.
1416 if (Config->ImageBase == uint64_t(-1))
1417 Config->ImageBase = getDefaultImageBase();
1418
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001419 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001420 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001421 Symtab->addAbsolute("___safe_se_handler_table", 0);
1422 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001423 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001424
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001425 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1426 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001427 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001428 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1429 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1430 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1431 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001432 // Needed for MSVC 2017 15.5 CRT.
1433 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001434
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001435 // This code may add new undefined symbols to the link, which may enqueue more
1436 // symbol resolution tasks, so we need to continue executing tasks until we
1437 // converge.
1438 do {
1439 // Windows specific -- if entry point is not found,
1440 // search for its mangled names.
1441 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001442 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001443
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001444 // Windows specific -- Make sure we resolve all dllexported symbols.
1445 for (Export &E : Config->Exports) {
1446 if (!E.ForwardTo.empty())
1447 continue;
1448 E.Sym = addUndefined(E.Name);
1449 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001450 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001451 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001452
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001453 // Add weak aliases. Weak aliases is a mechanism to give remaining
1454 // undefined symbols final chance to be resolved successfully.
1455 for (auto Pair : Config->AlternateNames) {
1456 StringRef From = Pair.first;
1457 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001458 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001459 if (!Sym)
1460 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001461 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001462 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001463 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001464 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001465
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001466 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001467 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001468 addUndefined(mangle("_load_config_used"));
1469 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001470
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001471 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001472 return;
1473
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001474 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1475 // This is useful because MSVC link.exe can generate complete PDBs.
1476 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001477 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001478 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001479 }
1480
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001481 // Do LTO by compiling bitcode input files to a set of native COFF files then
1482 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001483 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001484 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001485
Peter Collingbourne2612a322015-07-04 05:28:41 +00001486 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001487 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001488 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001489 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001490
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001491 // Windows specific -- if no /subsystem is given, we need to infer
1492 // that from entry point name.
1493 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001494 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001495 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001496 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001497 }
1498
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001499 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001500 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001501 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001502 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001503 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001504 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001505 return;
1506 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001507
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001508 // In MinGW, all symbols are automatically exported if no symbols
1509 // are chosen to be exported.
1510 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1511 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001512 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001513
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001514 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001515 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001516 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001517 return;
1518 Export E;
1519 E.Name = Def->getName();
1520 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001521 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001522 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001523 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001524 Config->Exports.push_back(E);
1525 });
1526 }
1527
Rui Ueyama151d8622015-06-17 20:40:43 +00001528 // Windows specific -- when we are creating a .dll file, we also
1529 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001530 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001531 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001532 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001533 assignExportOrdinals();
1534 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001535
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001536 // Handle /output-def (MinGW specific).
1537 if (auto *Arg = Args.getLastArg(OPT_output_def))
1538 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001539
Martin Storsjod2752aa2017-08-14 19:07:27 +00001540 // Set extra alignment for .comm symbols
1541 for (auto Pair : Config->AlignComm) {
1542 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001543 uint32_t Alignment = Pair.second;
1544
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001545 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001546 if (!Sym) {
1547 warn("/aligncomm symbol " + Name + " not found");
1548 continue;
1549 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001550
Rui Ueyama616cd992017-10-31 16:10:24 +00001551 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001552 if (!DC) {
1553 warn("/aligncomm symbol " + Name + " of wrong kind");
1554 continue;
1555 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001556
1557 CommonChunk *C = DC->getChunk();
1558 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001559 }
1560
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001561 // Windows specific -- Create a side-by-side manifest file.
1562 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001563 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001564
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001565 // Handle /order. We want to do this at this moment because we
1566 // need a complete list of comdat sections to warn on nonexistent
1567 // functions.
1568 if (auto *Arg = Args.getLastArg(OPT_order))
1569 parseOrderFile(Arg->getValue());
1570
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001571 // Identify unreferenced COMDAT sections.
1572 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001573 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001574
1575 // Identify identical COMDAT sections to merge them.
1576 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001577 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001578
Rui Ueyama411c63602015-05-28 19:09:30 +00001579 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001580 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001581
1582 // Stop early so we can print the results.
1583 Timer::root().stop();
1584 if (Config->ShowTiming)
1585 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001586}
1587
Rui Ueyama411c63602015-05-28 19:09:30 +00001588} // namespace coff
1589} // namespace lld