blob: cba89a83cd7e2be18b40d474d8b28da608e49874 [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 Ueyama4eed6cc2018-06-12 21:47:31 +0000335static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
336 sys::fs::UniqueID Ret;
337 if (sys::fs::getUniqueID(Path, Ret))
338 return None;
339 return Ret;
340}
341
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000342// Resolves a file path. This never returns the same path
343// (in that case, it returns None).
344Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
345 StringRef Path = doFindFile(Filename);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000346
347 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
348 bool Seen = !VisitedFiles.insert(*ID).second;
349 if (Seen)
350 return None;
351 }
352
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000353 if (Path.endswith_lower(".lib"))
354 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000355 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000356}
357
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000358// Find library file from search path.
359StringRef LinkerDriver::doFindLib(StringRef Filename) {
360 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000361 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000362 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000363 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000364 return doFindFile(Filename);
365}
366
367// Resolves a library path. /nodefaultlib options are taken into
368// consideration. This never returns the same path (in that case,
369// it returns None).
370Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
371 if (Config->NoDefaultLibAll)
372 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000373 if (!VisitedLibs.insert(Filename.lower()).second)
374 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000375
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000376 StringRef Path = doFindLib(Filename);
377 if (Config->NoDefaultLibs.count(Path))
378 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000379
380 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
381 if (!VisitedFiles.insert(*ID).second)
382 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000383 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000384}
385
386// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000387void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000388 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
389 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000390 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000391 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000392 while (!Env.empty()) {
393 StringRef Path;
394 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000395 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000396 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000397}
398
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000399Symbol *LinkerDriver::addUndefined(StringRef Name) {
400 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000401 if (!B->IsGCRoot) {
402 B->IsGCRoot = true;
403 Config->GCRoot.push_back(B);
404 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000405 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000406}
407
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000408// Symbol names are mangled by appending "_" prefix on x86.
409StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000410 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
411 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000412 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000413 return Sym;
414}
415
Rui Ueyama45044f42015-06-29 01:03:53 +0000416// Windows specific -- find default entry point name.
417StringRef LinkerDriver::findDefaultEntry() {
418 // User-defined main functions and their corresponding entry points.
419 static const char *Entries[][2] = {
420 {"main", "mainCRTStartup"},
421 {"wmain", "wmainCRTStartup"},
422 {"WinMain", "WinMainCRTStartup"},
423 {"wWinMain", "wWinMainCRTStartup"},
424 };
425 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000426 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000427 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000428 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000429 }
430 return "";
431}
432
433WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000434 if (Config->DLL)
435 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000436 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000437 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000438 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000439 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
440 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000441}
442
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000443static uint64_t getDefaultImageBase() {
444 if (Config->is64())
445 return Config->DLL ? 0x180000000 : 0x140000000;
446 return Config->DLL ? 0x10000000 : 0x400000;
447}
448
Rui Ueyama8fe17672016-12-08 20:50:47 +0000449static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000450 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000451 ArrayRef<StringRef> SearchPaths) {
452 SmallString<0> Data;
453 raw_svector_ostream OS(Data);
454
455 for (auto *Arg : Args) {
456 switch (Arg->getOption().getID()) {
457 case OPT_linkrepro:
458 case OPT_INPUT:
459 case OPT_defaultlib:
460 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000461 case OPT_manifest:
462 case OPT_manifest_colon:
463 case OPT_manifestdependency:
464 case OPT_manifestfile:
465 case OPT_manifestinput:
466 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000467 break;
468 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000469 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000470 }
471 }
472
473 for (StringRef Path : SearchPaths) {
474 std::string RelPath = relativeToRoot(Path);
475 OS << "/libpath:" << quote(RelPath) << "\n";
476 }
477
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000478 for (StringRef Path : FilePaths)
479 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000480
481 return Data.str();
482}
483
Rui Ueyama8fe17672016-12-08 20:50:47 +0000484static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000485 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
486 if (Args.hasArg(OPT_driver))
487 DebugTypes |= static_cast<unsigned>(DebugType::PData);
488 if (Args.hasArg(OPT_profile))
489 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
490 return DebugTypes;
491}
492
493static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000494 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000495 Arg.split(Types, ',', /*KeepEmpty=*/false);
496
497 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
498 for (StringRef Type : Types)
499 DebugTypes |= StringSwitch<unsigned>(Type.lower())
500 .Case("cv", static_cast<unsigned>(DebugType::CV))
501 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000502 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
503 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000504 return DebugTypes;
505}
506
Hans Wennborg1818e652016-12-09 20:54:44 +0000507static std::string getMapFile(const opt::InputArgList &Args) {
508 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
509 if (!Arg)
510 return "";
511 if (Arg->getOption().getID() == OPT_lldmap_file)
512 return Arg->getValue();
513
514 assert(Arg->getOption().getID() == OPT_lldmap);
515 StringRef OutFile = Config->OutputFile;
516 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
517}
518
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000519static std::string getImplibPath() {
520 if (!Config->Implib.empty())
521 return Config->Implib;
522 SmallString<128> Out = StringRef(Config->OutputFile);
523 sys::path::replace_extension(Out, ".lib");
524 return Out.str();
525}
526
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000527//
528// The import name is caculated as the following:
529//
530// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
531// -----+----------------+---------------------+------------------
532// LINK | {value} | {value}.{.dll/.exe} | {output name}
533// LIB | {value} | {value}.dll | {output name}.dll
534//
535static std::string getImportName(bool AsLib) {
536 SmallString<128> Out;
537
538 if (Config->ImportName.empty()) {
539 Out.assign(sys::path::filename(Config->OutputFile));
540 if (AsLib)
541 sys::path::replace_extension(Out, ".dll");
542 } else {
543 Out.assign(Config->ImportName);
544 if (!sys::path::has_extension(Out))
545 sys::path::replace_extension(Out,
546 (Config->DLL || AsLib) ? ".dll" : ".exe");
547 }
548
549 return Out.str();
550}
551
552static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000553 std::vector<COFFShortExport> Exports;
554 for (Export &E1 : Config->Exports) {
555 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000556 E2.Name = E1.Name;
557 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000558 E2.ExtName = E1.ExtName;
559 E2.Ordinal = E1.Ordinal;
560 E2.Noname = E1.Noname;
561 E2.Data = E1.Data;
562 E2.Private = E1.Private;
563 E2.Constant = E1.Constant;
564 Exports.push_back(E2);
565 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000566
Bob Haarman4ce341f2018-01-23 00:36:42 +0000567 auto HandleError = [](Error &&E) {
568 handleAllErrors(std::move(E),
569 [](ErrorInfoBase &EIB) { error(EIB.message()); });
570 };
571 std::string LibName = getImportName(AsLib);
572 std::string Path = getImplibPath();
573
Bob Haarman5ec44852018-01-31 23:44:00 +0000574 if (!Config->Incremental) {
575 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000576 Config->MinGW));
Bob Haarman5ec44852018-01-31 23:44:00 +0000577 return;
578 }
579
Bob Haarman4ce341f2018-01-23 00:36:42 +0000580 // If the import library already exists, replace it only if the contents
581 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000582 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
583 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000584 if (!OldBuf) {
585 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000586 Config->MinGW));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000587 return;
588 }
589
590 SmallString<128> TmpName;
591 if (std::error_code EC =
592 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
593 fatal("cannot create temporary file for import library " + Path + ": " +
594 EC.message());
595
596 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000597 Config->MinGW)) {
Bob Haarman4ce341f2018-01-23 00:36:42 +0000598 HandleError(std::move(E));
599 return;
600 }
601
Bob Haarman8832f882018-04-24 23:16:39 +0000602 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
603 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000604 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
605 OldBuf->reset();
606 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000607 } else {
608 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000609 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000610}
611
612static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000613 std::unique_ptr<MemoryBuffer> MB = CHECK(
614 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000615 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
616 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000617
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000618 if (Config->OutputFile.empty())
619 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000620 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000621 if (M.ImageBase)
622 Config->ImageBase = M.ImageBase;
623 if (M.StackReserve)
624 Config->StackReserve = M.StackReserve;
625 if (M.StackCommit)
626 Config->StackCommit = M.StackCommit;
627 if (M.HeapReserve)
628 Config->HeapReserve = M.HeapReserve;
629 if (M.HeapCommit)
630 Config->HeapCommit = M.HeapCommit;
631 if (M.MajorImageVersion)
632 Config->MajorImageVersion = M.MajorImageVersion;
633 if (M.MinorImageVersion)
634 Config->MinorImageVersion = M.MinorImageVersion;
635 if (M.MajorOSVersion)
636 Config->MajorOSVersion = M.MajorOSVersion;
637 if (M.MinorOSVersion)
638 Config->MinorOSVersion = M.MinorOSVersion;
639
640 for (COFFShortExport E1 : M.Exports) {
641 Export E2;
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000642 // In simple cases, only Name is set. Renamed exports are parsed
643 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
644 // it shouldn't be a normal exported function but a forward to another
645 // DLL instead. This is supported by both MS and GNU linkers.
646 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
Martin Storsjo5c84d442018-05-09 19:07:10 +0000647 E2.Name = Saver.save(E1.ExtName);
648 E2.ForwardTo = Saver.save(E1.Name);
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000649 Config->Exports.push_back(E2);
650 continue;
651 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000652 E2.Name = Saver.save(E1.Name);
Martin Storsjo97379ff2018-05-09 09:22:03 +0000653 E2.ExtName = Saver.save(E1.ExtName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000654 E2.Ordinal = E1.Ordinal;
655 E2.Noname = E1.Noname;
656 E2.Data = E1.Data;
657 E2.Private = E1.Private;
658 E2.Constant = E1.Constant;
659 Config->Exports.push_back(E2);
660 }
661}
662
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000663// A helper function for filterBitcodeFiles.
664static bool needsRebuilding(MemoryBufferRef MB) {
665 // The MSVC linker doesn't support thin archives, so if it's a thin
666 // archive, we always need to rebuild it.
667 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000668 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000669 if (File->isThin())
670 return true;
671
672 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000673 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000674 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
675 return true;
676 return false;
677}
678
679// Opens a given path as an archive file and removes bitcode files
680// from them if exists. This function is to appease the MSVC linker as
681// their linker doesn't like archive files containing non-native
682// object files.
683//
684// If a given archive doesn't contain bitcode files, the archive path
685// is returned as-is. Otherwise, a new temporary file is created and
686// its path is returned.
687static Optional<std::string>
688filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000689 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000690 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000691 MemoryBufferRef MBRef = MB->getMemBufferRef();
692 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000693
694 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000695 return None;
696 if (Magic != file_magic::archive)
697 return Path.str();
698 if (!needsRebuilding(MBRef))
699 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000700
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000701 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000702 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000703 MBRef.getBufferIdentifier() + ": failed to parse archive");
704
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000705 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000706 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000707 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
708 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000709
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000710 if (New.empty())
711 return None;
712
713 log("Creating a temporary archive for " + Path + " to remove bitcode files");
714
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000715 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000716 if (std::error_code EC = sys::fs::createTemporaryFile(
717 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000718 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000719 std::string Temp = S.str();
720 TemporaryFiles.push_back(Temp);
721
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000722 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000723 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
724 /*Deterministics=*/true,
725 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000726 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
727 error("failed to create a new archive " + S.str() + ": " + EI.message());
728 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000729 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000730}
731
732// Create response file contents and invoke the MSVC linker.
733void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000734 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000735 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000736
Bob Haarman41108162017-04-21 21:38:01 +0000737 // Write out archive members that we used in symbol resolution and pass these
738 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
739 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000740 for (ObjFile *Obj : ObjFile::Instances) {
741 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000742 continue;
743 SmallString<128> S;
744 int Fd;
745 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000746 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000747 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000748 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000749 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000750 Temps.push_back(S.str());
751 Rsp += quote(S) + "\n";
752 }
753
Rui Ueyama85d54b02017-02-23 00:26:42 +0000754 for (auto *Arg : Args) {
755 switch (Arg->getOption().getID()) {
756 case OPT_linkrepro:
757 case OPT_lldmap:
758 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000759 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000760 case OPT_msvclto:
761 // LLD-specific options are stripped.
762 break;
763 case OPT_opt:
764 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000765 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000766 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000767 case OPT_INPUT: {
768 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
769 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000770 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000771 continue;
772 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000773 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000774 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000775 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000776 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000777 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000778 }
779 }
780
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000781 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000782 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000783
784 for (StringRef Path : Temps)
785 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000786}
787
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000788void LinkerDriver::enqueueTask(std::function<void()> Task) {
789 TaskQueue.push_back(std::move(Task));
790}
791
792bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000793 ScopedTimer T(InputFileTimer);
794
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000795 bool DidWork = !TaskQueue.empty();
796 while (!TaskQueue.empty()) {
797 TaskQueue.front()();
798 TaskQueue.pop_front();
799 }
800 return DidWork;
801}
802
Rui Ueyama57175aa2018-01-27 00:34:46 +0000803// Parse an /order file. If an option is given, the linker places
804// COMDAT sections in the same order as their names appear in the
805// given file.
806static void parseOrderFile(StringRef Arg) {
807 // For some reason, the MSVC linker requires a filename to be
808 // preceded by "@".
809 if (!Arg.startswith("@")) {
810 error("malformed /order option: '@' missing");
811 return;
812 }
813
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000814 // Get a list of all comdat sections for error checking.
815 DenseSet<StringRef> Set;
816 for (Chunk *C : Symtab->getChunks())
817 if (auto *Sec = dyn_cast<SectionChunk>(C))
818 if (Sec->Sym)
819 Set.insert(Sec->Sym->getName());
820
Rui Ueyama57175aa2018-01-27 00:34:46 +0000821 // Open a file.
822 StringRef Path = Arg.substr(1);
823 std::unique_ptr<MemoryBuffer> MB = CHECK(
824 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
825
826 // Parse a file. An order file contains one symbol per line.
827 // All symbols that were not present in a given order file are
828 // considered to have the lowest priority 0 and are placed at
829 // end of an output section.
830 for (std::string S : args::getLines(MB->getMemBufferRef())) {
831 if (Config->Machine == I386 && !isDecorated(S))
832 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000833
Nico Weber0771c602018-03-09 12:41:04 +0000834 if (Set.count(S) == 0) {
835 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000836 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000837 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000838 else
839 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000840 }
841}
842
Rui Ueyama8fe17672016-12-08 20:50:47 +0000843void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000844 // If the first command line argument is "/lib", link.exe acts like lib.exe.
845 // We call our own implementation of lib.exe that understands bitcode files.
846 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
847 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000848 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000849 return;
850 }
851
Peter Collingbourne60c16162015-06-01 20:10:10 +0000852 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000853 InitializeAllTargetInfos();
854 InitializeAllTargets();
855 InitializeAllTargetMCs();
856 InitializeAllAsmParsers();
857 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000858
Rui Ueyama411c63602015-05-28 19:09:30 +0000859 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000860 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000861 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000862
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000863 // Parse and evaluate -mllvm options.
864 std::vector<const char *> V;
865 V.push_back("lld-link (LLVM option parsing)");
866 for (auto *Arg : Args.filtered(OPT_mllvm))
867 V.push_back(Arg->getValue());
868 cl::ParseCommandLineOptions(V.size(), V.data());
869
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000870 // Handle /errorlimit early, because error() depends on it.
871 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
872 int N = 20;
873 StringRef S = Arg->getValue();
874 if (S.getAsInteger(10, N))
875 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000876 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000877 }
878
Rui Ueyama5c726432015-05-29 16:11:52 +0000879 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000880 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000881 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000882 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000883 }
884
Zachary Turner727f1532018-01-17 19:16:26 +0000885 if (Args.hasArg(OPT_show_timing))
886 Config->ShowTiming = true;
887
888 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000889 // Handle --version, which is an lld extension. This option is a bit odd
890 // because it doesn't start with "/", but we deliberately chose "--" to
891 // avoid conflict with /version and for compatibility with clang-cl.
892 if (Args.hasArg(OPT_dash_dash_version)) {
893 outs() << getLLDVersion() << "\n";
894 return;
895 }
896
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000897 // Handle /lldmingw early, since it can potentially affect how other
898 // options are handled.
899 Config->MinGW = Args.hasArg(OPT_lldmingw);
900
Peter Collingbournefeee2102016-07-26 02:00:42 +0000901 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
902 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000903 sys::path::append(Path, "repro.tar");
904
905 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
906 TarWriter::create(Path, "repro");
907
908 if (ErrOrWriter) {
909 Tar = std::move(*ErrOrWriter);
910 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000911 error("/linkrepro: failed to open " + Path + ": " +
912 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000913 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000914 }
915
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000916 if (!Args.hasArg(OPT_INPUT)) {
917 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000918 Config->NoEntry = true;
919 else
920 fatal("no input files");
921 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000922
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000923 // Construct search path list.
924 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000925 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000926 SearchPaths.push_back(Arg->getValue());
927 addLibSearchPaths();
928
Bob Haarmane90ac012017-12-28 07:02:13 +0000929 // Handle /ignore
930 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000931 if (StringRef(Arg->getValue()) == "4037")
932 Config->WarnMissingOrderSymbol = false;
933 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000934 Config->WarnLocallyDefinedImported = false;
935 // Other warning numbers are ignored.
936 }
937
Rui Ueyamaad660982015-06-07 00:20:32 +0000938 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000939 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000940 Config->OutputFile = Arg->getValue();
941
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000942 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000943 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000944 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000945 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000946
Rui Ueyama95925fd2015-06-28 19:35:15 +0000947 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000948 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000949 Config->Force = true;
950
Rui Ueyama6600eb12015-07-04 23:37:32 +0000951 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000952 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000953 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000954 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000955 if (auto *Arg = Args.getLastArg(OPT_debugtype))
956 Config->DebugTypes = parseDebugType(Arg->getValue());
957 else
958 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000959 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000960
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000961 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000962 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000963 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000964 if (auto *Arg = Args.getLastArg(OPT_pdb))
965 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000966 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
967 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000968 if (Args.hasArg(OPT_natvis))
969 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
970 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000971
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000972 // Handle /noentry
973 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000974 if (Args.hasArg(OPT_dll))
975 Config->NoEntry = true;
976 else
977 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000978 }
979
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000980 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000981 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000982 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000983 Config->ManifestID = 2;
984 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000985
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000986 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
987 // because we need to explicitly check whether that option or its inverse was
988 // present in the argument list in order to handle /fixed.
989 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
990 if (DynamicBaseArg &&
991 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
992 Config->DynamicBase = false;
993
Nico Webera7643792018-03-30 17:17:04 +0000994 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
995 // default setting for any other project type.", but link.exe defaults to
996 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000997 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
998 if (Fixed) {
999 if (DynamicBaseArg &&
1000 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001001 error("/fixed must not be specified with /dynamicbase");
1002 } else {
1003 Config->Relocatable = false;
1004 Config->DynamicBase = false;
1005 }
Rui Ueyama6592ff82015-06-16 23:13:00 +00001006 }
Rui Ueyama588e8322015-06-15 01:23:58 +00001007
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001008 // Handle /appcontainer
1009 Config->AppContainer =
1010 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +00001011
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +00001012 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +00001013 if (auto *Arg = Args.getLastArg(OPT_machine))
1014 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +00001015
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001016 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +00001017 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001018 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1019
1020 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +00001021 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001022 Config->NoDefaultLibAll = true;
1023
Rui Ueyama804a8b62015-05-29 16:18:15 +00001024 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +00001025 if (auto *Arg = Args.getLastArg(OPT_base))
1026 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +00001027
1028 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +00001029 if (auto *Arg = Args.getLastArg(OPT_stack))
1030 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +00001031
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001032 // Handle /guard:cf
1033 if (auto *Arg = Args.getLastArg(OPT_guard))
1034 parseGuard(Arg->getValue());
1035
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001036 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +00001037 if (auto *Arg = Args.getLastArg(OPT_heap))
1038 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001039
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001040 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +00001041 if (auto *Arg = Args.getLastArg(OPT_version))
1042 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1043 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001044
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001045 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +00001046 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1047 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1048 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001049
Zachary Turnerc8dd6cc2018-05-17 15:11:01 +00001050 // Handle /timestamp
1051 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1052 if (Arg->getOption().getID() == OPT_repro) {
1053 Config->Timestamp = 0;
1054 Config->Repro = true;
1055 } else {
1056 Config->Repro = false;
1057 StringRef Value(Arg->getValue());
1058 if (Value.getAsInteger(0, Config->Timestamp))
1059 fatal(Twine("invalid timestamp: ") + Value +
1060 ". Expected 32-bit integer");
1061 }
1062 } else {
1063 Config->Repro = false;
1064 Config->Timestamp = time(nullptr);
1065 }
1066
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001067 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001068 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001069 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001070
Rui Ueyama08d5e182015-06-18 23:20:11 +00001071 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001072 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001073 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001074
Rui Ueyamab95188c2015-06-18 20:27:09 +00001075 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001076 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001077 Config->Implib = Arg->getValue();
1078
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001079 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001080 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1081 unsigned ICFLevel =
1082 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001083 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +00001084 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001085 std::string Str = StringRef(Arg->getValue()).lower();
1086 SmallVector<StringRef, 1> Vec;
1087 StringRef(Str).split(Vec, ',');
1088 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001089 if (S == "ref") {
1090 DoGC = true;
1091 } else if (S == "noref") {
1092 DoGC = false;
1093 } else if (S == "icf" || S.startswith("icf=")) {
1094 ICFLevel = 2;
1095 } else if (S == "noicf") {
1096 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001097 } else if (S == "lldtailmerge") {
1098 TailMerge = 2;
1099 } else if (S == "nolldtailmerge") {
1100 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001101 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001102 StringRef OptLevel = S.substr(7);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001103 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001104 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001105 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001106 StringRef Jobs = S.substr(11);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001107 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1108 Config->ThinLTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001109 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001110 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001111 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001112 if (N.getAsInteger(10, Config->LTOPartitions) ||
1113 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001114 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001115 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001116 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001117 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001118 }
1119
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001120 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1121 // explicitly.
1122 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1123 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1124 // comdat readonly data.
1125 if (ICFLevel == 1 && !DoGC)
1126 ICFLevel = 0;
1127 Config->DoGC = DoGC;
1128 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001129 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001130
Bob Haarman69b196d2017-02-08 18:36:41 +00001131 // Handle /lldsavetemps
1132 if (Args.hasArg(OPT_lldsavetemps))
1133 Config->SaveTemps = true;
1134
Martin Storsjo53518912018-03-14 20:17:16 +00001135 // Handle /kill-at
1136 if (Args.hasArg(OPT_kill_at))
1137 Config->KillAt = true;
1138
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001139 // Handle /lldltocache
1140 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1141 Config->LTOCache = Arg->getValue();
1142
1143 // Handle /lldsavecachepolicy
1144 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001145 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001146 parseCachePruningPolicy(Arg->getValue()),
1147 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1148
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001149 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001150 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001151 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001152
Rui Ueyama6600eb12015-07-04 23:37:32 +00001153 // Handle /merge
1154 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001155 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001156
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001157 // Add default section merging rules after user rules. User rules take
1158 // precedence, but we will emit a warning if there is a conflict.
1159 parseMerge(".idata=.rdata");
1160 parseMerge(".didat=.rdata");
1161 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001162 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001163 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001164
Rui Ueyama440138c2016-06-20 03:39:39 +00001165 // Handle /section
1166 for (auto *Arg : Args.filtered(OPT_section))
1167 parseSection(Arg->getValue());
1168
Martin Storsjod2752aa2017-08-14 19:07:27 +00001169 // Handle /aligncomm
1170 for (auto *Arg : Args.filtered(OPT_aligncomm))
1171 parseAligncomm(Arg->getValue());
1172
Nico Webera7a2c442017-07-25 18:08:03 +00001173 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1174 // also passed.
1175 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1176 Config->ManifestDependency = Arg->getValue();
1177 Config->Manifest = Configuration::SideBySide;
1178 }
1179
1180 // Handle /manifest and /manifest:
1181 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1182 if (Arg->getOption().getID() == OPT_manifest)
1183 Config->Manifest = Configuration::SideBySide;
1184 else
1185 parseManifest(Arg->getValue());
1186 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001187
1188 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001189 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1190 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001191
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001192 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001193 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001194 Config->ManifestFile = Arg->getValue();
1195
Rui Ueyamaafb19012016-04-19 01:21:58 +00001196 // Handle /manifestinput
1197 for (auto *Arg : Args.filtered(OPT_manifestinput))
1198 Config->ManifestInput.push_back(Arg->getValue());
1199
Nico Webera7a2c442017-07-25 18:08:03 +00001200 if (!Config->ManifestInput.empty() &&
1201 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001202 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001203 }
1204
Rui Ueyama6592ff82015-06-16 23:13:00 +00001205 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001206 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1207 Config->AllowIsolation =
1208 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001209 Config->Incremental =
1210 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001211 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1212 !Args.hasArg(OPT_profile));
Nico Weberd657c252018-05-31 13:43:02 +00001213 Config->IntegrityCheck =
1214 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001215 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001216 Config->TerminalServerAware =
1217 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001218 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001219 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Martin Storsjo3a7905b2018-06-29 06:08:25 +00001220 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001221
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001222 Config->MapFile = getMapFile(Args);
1223
Nico Weber0945ad62018-03-30 17:14:50 +00001224 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1225 warn("ignoring '/incremental' due to '/profile' specification");
1226 Config->Incremental = false;
1227 }
1228
1229 if (Config->Incremental && Args.hasArg(OPT_order)) {
1230 warn("ignoring '/incremental' due to '/order' specification");
1231 Config->Incremental = false;
1232 }
1233
Bob Haarman5ec44852018-01-31 23:44:00 +00001234 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001235 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001236 "disable");
1237 Config->Incremental = false;
1238 }
1239
1240 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001241 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001242 "disable");
1243 Config->Incremental = false;
1244 }
1245
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001246 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001247 return;
1248
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001249 std::set<sys::fs::UniqueID> WholeArchives;
1250 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
Reid Kleckner34085682018-06-14 19:56:03 +00001251 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1252 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1253 WholeArchives.insert(*ID);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001254
1255 // A predicate returning true if a given path is an argument for
1256 // /wholearchive:, or /wholearchive is enabled globally.
1257 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1258 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1259 auto IsWholeArchive = [&](StringRef Path) -> bool {
1260 if (Args.hasArg(OPT_wholearchive_flag))
1261 return true;
1262 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1263 return WholeArchives.count(*ID);
1264 return false;
1265 };
1266
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001267 // Create a list of input files. Files can be given as arguments
1268 // for /defaultlib option.
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001269 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1270 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Reid Kleckner34085682018-06-14 19:56:03 +00001271 enqueuePath(*Path, IsWholeArchive(*Path));
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001272
David Blaikie6521ed92015-06-22 22:06:52 +00001273 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001274 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001275 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001276
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001277 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001278 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001279 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001280
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001281 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001282 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001283
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001284 // We should have inferred a machine type by now from the input files, but if
1285 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001286 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001287 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001288 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001289 }
1290
Eric Beckmann9e19d792017-06-17 02:26:27 +00001291 // Input files can be Windows resource files (.res files). We use
1292 // WindowsResource to convert resource files to a regular COFF file,
1293 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001294 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001295 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001296
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001297 if (Tar)
1298 Tar->append("response.txt",
1299 createResponseFile(Args, FilePaths,
1300 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001301
Rui Ueyama4d545342015-07-28 03:12:00 +00001302 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001303 Config->LargeAddressAware = Args.hasFlag(
1304 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001305
Rui Ueyamad68e2112015-07-28 03:15:57 +00001306 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001307 Config->HighEntropyVA =
1308 Config->is64() &&
1309 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001310
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001311 if (!Config->DynamicBase &&
1312 (Config->Machine == ARMNT || Config->Machine == ARM64))
1313 error("/dynamicbase:no is not compatible with " +
1314 machineToStr(Config->Machine));
1315
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001316 // Handle /entry and /dll
1317 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1318 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001319 } else if (!Config->Entry && !Config->NoEntry) {
1320 if (Args.hasArg(OPT_dll)) {
1321 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1322 : "_DllMainCRTStartup";
1323 Config->Entry = addUndefined(S);
1324 } else {
1325 // Windows specific -- If entry point name is not given, we need to
1326 // infer that from user-defined entry name.
1327 StringRef S = findDefaultEntry();
1328 if (S.empty())
1329 fatal("entry point must be defined");
1330 Config->Entry = addUndefined(S);
1331 log("Entry name inferred: " + S);
1332 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001333 }
1334
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001335 // Handle /export
1336 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001337 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001338 if (Config->Machine == I386) {
1339 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001340 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001341 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001342 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001343 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001344 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001345 }
1346
1347 // Handle /def
1348 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001349 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001350 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001351 }
1352
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001353 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001354 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001355 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001356 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001357 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001358 }
1359
Rui Ueyama6d249082015-07-13 22:31:45 +00001360 // Handle /delayload
1361 for (auto *Arg : Args.filtered(OPT_delayload)) {
1362 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001363 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001364 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001365 } else {
1366 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001367 }
1368 }
1369
Reid Kleckner7668182e2017-03-21 00:12:51 +00001370 // Set default image name if neither /out or /def set it.
1371 if (Config->OutputFile.empty()) {
1372 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001373 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001374 }
1375
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001376 if (ShouldCreatePDB) {
1377 // Put the PDB next to the image if no /pdb flag was passed.
1378 if (Config->PDBPath.empty()) {
1379 Config->PDBPath = Config->OutputFile;
1380 sys::path::replace_extension(Config->PDBPath, ".pdb");
1381 }
1382
1383 // The embedded PDB path should be the absolute path to the PDB if no
1384 // /pdbaltpath flag was passed.
1385 if (Config->PDBAltPath.empty()) {
1386 Config->PDBAltPath = Config->PDBPath;
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001387
1388 // It's important to make the path absolute and remove dots. This path
1389 // will eventually be written into the PE header, and certain Microsoft
1390 // tools won't work correctly if these assumptions are not held.
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001391 sys::fs::make_absolute(Config->PDBAltPath);
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001392 sys::path::remove_dots(Config->PDBAltPath);
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001393 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001394 }
1395
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001396 // Set default image base if /base is not given.
1397 if (Config->ImageBase == uint64_t(-1))
1398 Config->ImageBase = getDefaultImageBase();
1399
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001400 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001401 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001402 Symtab->addAbsolute("___safe_se_handler_table", 0);
1403 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001404 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001405
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001406 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1407 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001408 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001409 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1410 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1411 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1412 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001413 // Needed for MSVC 2017 15.5 CRT.
1414 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001415
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001416 // This code may add new undefined symbols to the link, which may enqueue more
1417 // symbol resolution tasks, so we need to continue executing tasks until we
1418 // converge.
1419 do {
1420 // Windows specific -- if entry point is not found,
1421 // search for its mangled names.
1422 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001423 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001424
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001425 // Windows specific -- Make sure we resolve all dllexported symbols.
1426 for (Export &E : Config->Exports) {
1427 if (!E.ForwardTo.empty())
1428 continue;
1429 E.Sym = addUndefined(E.Name);
1430 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001431 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001432 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001433
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001434 // Add weak aliases. Weak aliases is a mechanism to give remaining
1435 // undefined symbols final chance to be resolved successfully.
1436 for (auto Pair : Config->AlternateNames) {
1437 StringRef From = Pair.first;
1438 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001439 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001440 if (!Sym)
1441 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001442 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001443 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001444 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001445 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001446
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001447 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001448 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001449 addUndefined(mangle("_load_config_used"));
1450 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001451
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001452 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001453 return;
1454
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001455 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1456 // This is useful because MSVC link.exe can generate complete PDBs.
1457 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001458 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001459 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001460 }
1461
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001462 // Do LTO by compiling bitcode input files to a set of native COFF files then
1463 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001464 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001465 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001466
Peter Collingbourne2612a322015-07-04 05:28:41 +00001467 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001468 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001469 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001470 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001471
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001472 // Windows specific -- if no /subsystem is given, we need to infer
1473 // that from entry point name.
1474 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001475 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001476 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001477 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001478 }
1479
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001480 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001481 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001482 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001483 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001484 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001485 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001486 return;
1487 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001488
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001489 // In MinGW, all symbols are automatically exported if no symbols
1490 // are chosen to be exported.
1491 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1492 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001493 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001494
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001495 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001496 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001497 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001498 return;
1499 Export E;
1500 E.Name = Def->getName();
1501 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001502 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001503 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001504 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001505 Config->Exports.push_back(E);
1506 });
1507 }
1508
Rui Ueyama151d8622015-06-17 20:40:43 +00001509 // Windows specific -- when we are creating a .dll file, we also
1510 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001511 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001512 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001513 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001514 assignExportOrdinals();
1515 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001516
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001517 // Handle /output-def (MinGW specific).
1518 if (auto *Arg = Args.getLastArg(OPT_output_def))
1519 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001520
Martin Storsjod2752aa2017-08-14 19:07:27 +00001521 // Set extra alignment for .comm symbols
1522 for (auto Pair : Config->AlignComm) {
1523 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001524 uint32_t Alignment = Pair.second;
1525
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001526 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001527 if (!Sym) {
1528 warn("/aligncomm symbol " + Name + " not found");
1529 continue;
1530 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001531
Rui Ueyama616cd992017-10-31 16:10:24 +00001532 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001533 if (!DC) {
1534 warn("/aligncomm symbol " + Name + " of wrong kind");
1535 continue;
1536 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001537
1538 CommonChunk *C = DC->getChunk();
1539 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001540 }
1541
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001542 // Windows specific -- Create a side-by-side manifest file.
1543 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001544 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001545
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001546 // Handle /order. We want to do this at this moment because we
1547 // need a complete list of comdat sections to warn on nonexistent
1548 // functions.
1549 if (auto *Arg = Args.getLastArg(OPT_order))
1550 parseOrderFile(Arg->getValue());
1551
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001552 // Identify unreferenced COMDAT sections.
1553 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001554 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001555
1556 // Identify identical COMDAT sections to merge them.
1557 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001558 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001559
Rui Ueyama411c63602015-05-28 19:09:30 +00001560 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001561 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001562
1563 // Stop early so we can print the results.
1564 Timer::root().stop();
1565 if (Config->ShowTiming)
1566 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001567}
1568
Rui Ueyama411c63602015-05-28 19:09:30 +00001569} // namespace coff
1570} // namespace lld