blob: 0f9ba79b8ddabe16c8ae77f0878d748f3523e5a0 [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- Driver.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Rui Ueyama411c63602015-05-28 19:09:30 +000010#include "Driver.h"
Rui Ueyama1d99ab32016-09-15 22:24:51 +000011#include "Config.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000012#include "ICF.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000014#include "MarkLive.h"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000015#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000017#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000018#include "Writer.h"
Rui Ueyama57175aa2018-01-27 00:34:46 +000019#include "lld/Common/Args.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000020#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000021#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000022#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000023#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000024#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000026#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000027#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000028#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000029#include "llvm/Object/COFFImportFile.h"
30#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Option/Arg.h"
32#include "llvm/Option/ArgList.h"
33#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000034#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000036#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000037#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000038#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000039#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000040#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000041#include <algorithm>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000042#include <future>
Sam Cleggf187c4d2018-02-20 22:09:59 +000043#include <memory>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000044
Rui Ueyama411c63602015-05-28 19:09:30 +000045using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000046using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000047using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000048using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050namespace lld {
51namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Zachary Turner727f1532018-01-17 19:16:26 +000053static Timer InputFileTimer("Input File Reading", Timer::root());
54
Rui Ueyama3500f662015-05-28 20:30:06 +000055Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000056LinkerDriver *Driver;
57
Rui Ueyama6f4e2552017-10-23 20:03:32 +000058bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Bob Haarmanb8a59c82017-10-25 22:28:38 +000059 errorHandler().LogName = Args[0];
60 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
Nico Weberf06ae4f2018-03-12 12:45:40 +000064 " (use /errorlimit:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000065 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000066 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000067 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyamacbf969e2017-08-28 21:51:07 +000068
69 Symtab = make<SymbolTable>();
70
Rui Ueyama7fed58c2016-12-08 19:10:28 +000071 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000072 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000073
74 // Call exit() if we can to avoid calling destructors.
75 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000076 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000077
78 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000079 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000080}
Rui Ueyama411c63602015-05-28 19:09:30 +000081
Nico Weber5660de72016-04-20 22:34:15 +000082// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000083static std::string getOutputPath(StringRef Path) {
84 auto P = Path.find_last_of("\\/");
85 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000086 const char* E = Config->DLL ? ".dll" : ".exe";
87 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000088}
89
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000090// ErrorOr is not default constructible, so it cannot be used as the type
91// parameter of a future.
92// FIXME: We could open the file in createFutureForFile and avoid needing to
93// return an error here, but for the moment that would cost us a file descriptor
94// (a limited resource on Windows) for the duration that the future is pending.
95typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
96
97// Create a std::future that opens and maps a file using the best strategy for
98// the host platform.
99static std::future<MBErrPair> createFutureForFile(std::string Path) {
Nico Weberfb647302018-04-10 13:15:21 +0000100#if _WIN32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000101 // On Windows, file I/O is relatively slow so it is best to do this
102 // asynchronously.
103 auto Strategy = std::launch::async;
104#else
105 auto Strategy = std::launch::deferred;
106#endif
107 return std::async(Strategy, [=]() {
Bob Haarman8832f882018-04-24 23:16:39 +0000108 auto MBOrErr = MemoryBuffer::getFile(Path,
109 /*FileSize*/ -1,
110 /*RequiresNullTerminator*/ false);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000111 if (!MBOrErr)
112 return MBErrPair{nullptr, MBOrErr.getError()};
113 return MBErrPair{std::move(*MBOrErr), std::error_code()};
114 });
115}
116
117MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
118 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000119 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000120
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000121 if (Driver->Tar)
122 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
123 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000124 return MBRef;
125}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000126
Martin Storsjo8278ba52017-09-13 07:28:03 +0000127void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
128 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000129 StringRef Filename = MB->getBufferIdentifier();
130
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000131 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000132 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000133
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000134 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000135 switch (identify_magic(MBRef.getBuffer())) {
136 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000137 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000138 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000139 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000140 if (WholeArchive) {
141 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000142 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000143
144 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000145 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000146 return;
147 }
148 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000149 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000151 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000152 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000153 case file_magic::coff_object:
154 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000155 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000156 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000157 case file_magic::coff_cl_gl_object:
158 error(Filename + ": is not a native COFF file. Recompile without /GL");
159 break;
160 case file_magic::pecoff_executable:
161 if (Filename.endswith_lower(".dll")) {
162 error(Filename + ": bad file type. Did you specify a DLL instead of an "
163 "import library?");
164 break;
165 }
166 LLVM_FALLTHROUGH;
167 default:
168 error(MBRef.getBufferIdentifier() + ": unknown file type");
169 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000170 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000171}
172
Martin Storsjo8278ba52017-09-13 07:28:03 +0000173void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000174 auto Future =
175 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
176 std::string PathStr = Path;
177 enqueueTask([=]() {
178 auto MBOrErr = Future->get();
179 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000180 error("could not open " + PathStr + ": " + MBOrErr.second.message());
181 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000182 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000183 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000184}
185
186void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
187 StringRef ParentName) {
188 file_magic Magic = identify_magic(MB.getBuffer());
189 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000190 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000191 return;
192 }
193
194 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000195 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000196 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000197 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000198 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000199 } else {
200 error("unknown file type: " + MB.getBufferIdentifier());
201 return;
202 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000203
204 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000205 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000206 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000207}
208
209void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
210 StringRef SymName,
211 StringRef ParentName) {
212 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000213 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000214 C.getMemoryBufferRef(),
215 "could not get the buffer for the member defining symbol " + SymName);
216 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
217 return;
218 }
219
220 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000221 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000222 "could not get the filename for the member defining symbol " +
223 SymName)));
224 enqueueTask([=]() {
225 auto MBOrErr = Future->get();
226 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000227 fatal("could not get the buffer for the member defining " + SymName +
228 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000229 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
230 ParentName);
231 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000232}
233
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000234static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000235 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
236 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000237}
238
Rui Ueyama411c63602015-05-28 19:09:30 +0000239// Parses .drectve section contents and returns a list of files
240// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000241void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000242 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000243 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000244 // /EXPORT: option can appear too many times, processing in fastpath.
245 opt::InputArgList Args;
246 std::vector<StringRef> Exports;
247 std::tie(Args, Exports) = Parser.parseDirectives(S);
248
249 for (StringRef E : Exports) {
250 // If a common header file contains dllexported function
251 // declarations, many object files may end up with having the
252 // same /EXPORT options. In order to save cost of parsing them,
253 // we dedup them first.
254 if (!DirectivesExports.insert(E).second)
255 continue;
256
257 Export Exp = parseExport(E);
258 if (Config->Machine == I386 && Config->MinGW) {
259 if (!isDecorated(Exp.Name))
260 Exp.Name = Saver.save("_" + Exp.Name);
261 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
262 Exp.ExtName = Saver.save("_" + Exp.ExtName);
263 }
264 Exp.Directives = true;
265 Config->Exports.push_back(Exp);
266 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000267
David Blaikie6521ed92015-06-22 22:06:52 +0000268 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000269 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000270 case OPT_aligncomm:
271 parseAligncomm(Arg->getValue());
272 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000273 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000274 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000275 break;
276 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000277 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000278 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000279 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000280 case OPT_entry:
281 Config->Entry = addUndefined(mangle(Arg->getValue()));
282 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000283 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000284 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000285 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000286 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000287 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000288 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000289 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000290 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000291 break;
292 case OPT_nodefaultlib:
293 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
294 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000295 case OPT_section:
296 parseSection(Arg->getValue());
297 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000298 case OPT_subsystem:
299 parseSubsystem(Arg->getValue(), &Config->Subsystem,
300 &Config->MajorOSVersion, &Config->MinorOSVersion);
301 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000302 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000303 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000304 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000305 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000306 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000307 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000308 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000309 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000310 }
311 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000312}
313
Rui Ueyama54b71da2015-05-31 19:17:12 +0000314// Find file from search paths. You can omit ".obj", this function takes
315// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000316StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000317 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
318 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000319 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000320 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000321 for (StringRef Dir : SearchPaths) {
322 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000323 sys::path::append(Path, Filename);
324 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000325 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000326 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000327 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000328 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000329 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000330 }
331 }
332 return Filename;
333}
334
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000335// Resolves a file path. This never returns the same path
336// (in that case, it returns None).
337Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
338 StringRef Path = doFindFile(Filename);
339 bool Seen = !VisitedFiles.insert(Path.lower()).second;
340 if (Seen)
341 return None;
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000342 if (Path.endswith_lower(".lib"))
343 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000344 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000345}
346
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000347// Find library file from search path.
348StringRef LinkerDriver::doFindLib(StringRef Filename) {
349 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000350 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000351 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000352 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000353 return doFindFile(Filename);
354}
355
356// Resolves a library path. /nodefaultlib options are taken into
357// consideration. This never returns the same path (in that case,
358// it returns None).
359Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
360 if (Config->NoDefaultLibAll)
361 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000362 if (!VisitedLibs.insert(Filename.lower()).second)
363 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000364 StringRef Path = doFindLib(Filename);
365 if (Config->NoDefaultLibs.count(Path))
366 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000367 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000368 return None;
369 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000370}
371
372// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000373void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000374 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
375 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000376 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000377 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000378 while (!Env.empty()) {
379 StringRef Path;
380 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000381 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000382 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000383}
384
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000385Symbol *LinkerDriver::addUndefined(StringRef Name) {
386 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000387 if (!B->IsGCRoot) {
388 B->IsGCRoot = true;
389 Config->GCRoot.push_back(B);
390 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000391 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000392}
393
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000394// Symbol names are mangled by appending "_" prefix on x86.
395StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000396 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
397 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000398 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000399 return Sym;
400}
401
Rui Ueyama45044f42015-06-29 01:03:53 +0000402// Windows specific -- find default entry point name.
403StringRef LinkerDriver::findDefaultEntry() {
404 // User-defined main functions and their corresponding entry points.
405 static const char *Entries[][2] = {
406 {"main", "mainCRTStartup"},
407 {"wmain", "wmainCRTStartup"},
408 {"WinMain", "WinMainCRTStartup"},
409 {"wWinMain", "wWinMainCRTStartup"},
410 };
411 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000412 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000413 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000414 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000415 }
416 return "";
417}
418
419WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000420 if (Config->DLL)
421 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000422 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000423 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000424 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000425 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
426 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000427}
428
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000429static uint64_t getDefaultImageBase() {
430 if (Config->is64())
431 return Config->DLL ? 0x180000000 : 0x140000000;
432 return Config->DLL ? 0x10000000 : 0x400000;
433}
434
Rui Ueyama8fe17672016-12-08 20:50:47 +0000435static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000436 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000437 ArrayRef<StringRef> SearchPaths) {
438 SmallString<0> Data;
439 raw_svector_ostream OS(Data);
440
441 for (auto *Arg : Args) {
442 switch (Arg->getOption().getID()) {
443 case OPT_linkrepro:
444 case OPT_INPUT:
445 case OPT_defaultlib:
446 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000447 case OPT_manifest:
448 case OPT_manifest_colon:
449 case OPT_manifestdependency:
450 case OPT_manifestfile:
451 case OPT_manifestinput:
452 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000453 break;
454 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000455 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000456 }
457 }
458
459 for (StringRef Path : SearchPaths) {
460 std::string RelPath = relativeToRoot(Path);
461 OS << "/libpath:" << quote(RelPath) << "\n";
462 }
463
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000464 for (StringRef Path : FilePaths)
465 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000466
467 return Data.str();
468}
469
Rui Ueyama8fe17672016-12-08 20:50:47 +0000470static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000471 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
472 if (Args.hasArg(OPT_driver))
473 DebugTypes |= static_cast<unsigned>(DebugType::PData);
474 if (Args.hasArg(OPT_profile))
475 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
476 return DebugTypes;
477}
478
479static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000480 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000481 Arg.split(Types, ',', /*KeepEmpty=*/false);
482
483 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
484 for (StringRef Type : Types)
485 DebugTypes |= StringSwitch<unsigned>(Type.lower())
486 .Case("cv", static_cast<unsigned>(DebugType::CV))
487 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000488 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
489 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000490 return DebugTypes;
491}
492
Hans Wennborg1818e652016-12-09 20:54:44 +0000493static std::string getMapFile(const opt::InputArgList &Args) {
494 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
495 if (!Arg)
496 return "";
497 if (Arg->getOption().getID() == OPT_lldmap_file)
498 return Arg->getValue();
499
500 assert(Arg->getOption().getID() == OPT_lldmap);
501 StringRef OutFile = Config->OutputFile;
502 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
503}
504
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000505static std::string getImplibPath() {
506 if (!Config->Implib.empty())
507 return Config->Implib;
508 SmallString<128> Out = StringRef(Config->OutputFile);
509 sys::path::replace_extension(Out, ".lib");
510 return Out.str();
511}
512
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000513//
514// The import name is caculated as the following:
515//
516// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
517// -----+----------------+---------------------+------------------
518// LINK | {value} | {value}.{.dll/.exe} | {output name}
519// LIB | {value} | {value}.dll | {output name}.dll
520//
521static std::string getImportName(bool AsLib) {
522 SmallString<128> Out;
523
524 if (Config->ImportName.empty()) {
525 Out.assign(sys::path::filename(Config->OutputFile));
526 if (AsLib)
527 sys::path::replace_extension(Out, ".dll");
528 } else {
529 Out.assign(Config->ImportName);
530 if (!sys::path::has_extension(Out))
531 sys::path::replace_extension(Out,
532 (Config->DLL || AsLib) ? ".dll" : ".exe");
533 }
534
535 return Out.str();
536}
537
538static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000539 std::vector<COFFShortExport> Exports;
540 for (Export &E1 : Config->Exports) {
541 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000542 E2.Name = E1.Name;
543 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000544 E2.ExtName = E1.ExtName;
545 E2.Ordinal = E1.Ordinal;
546 E2.Noname = E1.Noname;
547 E2.Data = E1.Data;
548 E2.Private = E1.Private;
549 E2.Constant = E1.Constant;
550 Exports.push_back(E2);
551 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000552
Bob Haarman4ce341f2018-01-23 00:36:42 +0000553 auto HandleError = [](Error &&E) {
554 handleAllErrors(std::move(E),
555 [](ErrorInfoBase &EIB) { error(EIB.message()); });
556 };
557 std::string LibName = getImportName(AsLib);
558 std::string Path = getImplibPath();
559
Bob Haarman5ec44852018-01-31 23:44:00 +0000560 if (!Config->Incremental) {
561 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
562 false, Config->MinGW));
563 return;
564 }
565
Bob Haarman4ce341f2018-01-23 00:36:42 +0000566 // If the import library already exists, replace it only if the contents
567 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000568 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
569 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000570 if (!OldBuf) {
571 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
572 false, Config->MinGW));
573 return;
574 }
575
576 SmallString<128> TmpName;
577 if (std::error_code EC =
578 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
579 fatal("cannot create temporary file for import library " + Path + ": " +
580 EC.message());
581
582 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
583 false, Config->MinGW)) {
584 HandleError(std::move(E));
585 return;
586 }
587
Bob Haarman8832f882018-04-24 23:16:39 +0000588 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
589 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000590 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
591 OldBuf->reset();
592 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000593 } else {
594 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000595 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000596}
597
598static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000599 std::unique_ptr<MemoryBuffer> MB = CHECK(
600 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000601 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
602 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000603
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000604 if (Config->OutputFile.empty())
605 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000606 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000607 if (M.ImageBase)
608 Config->ImageBase = M.ImageBase;
609 if (M.StackReserve)
610 Config->StackReserve = M.StackReserve;
611 if (M.StackCommit)
612 Config->StackCommit = M.StackCommit;
613 if (M.HeapReserve)
614 Config->HeapReserve = M.HeapReserve;
615 if (M.HeapCommit)
616 Config->HeapCommit = M.HeapCommit;
617 if (M.MajorImageVersion)
618 Config->MajorImageVersion = M.MajorImageVersion;
619 if (M.MinorImageVersion)
620 Config->MinorImageVersion = M.MinorImageVersion;
621 if (M.MajorOSVersion)
622 Config->MajorOSVersion = M.MajorOSVersion;
623 if (M.MinorOSVersion)
624 Config->MinorOSVersion = M.MinorOSVersion;
625
626 for (COFFShortExport E1 : M.Exports) {
627 Export E2;
628 E2.Name = Saver.save(E1.Name);
629 if (E1.isWeak())
630 E2.ExtName = Saver.save(E1.ExtName);
631 E2.Ordinal = E1.Ordinal;
632 E2.Noname = E1.Noname;
633 E2.Data = E1.Data;
634 E2.Private = E1.Private;
635 E2.Constant = E1.Constant;
636 Config->Exports.push_back(E2);
637 }
638}
639
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000640// A helper function for filterBitcodeFiles.
641static bool needsRebuilding(MemoryBufferRef MB) {
642 // The MSVC linker doesn't support thin archives, so if it's a thin
643 // archive, we always need to rebuild it.
644 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000645 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000646 if (File->isThin())
647 return true;
648
649 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000650 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000651 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
652 return true;
653 return false;
654}
655
656// Opens a given path as an archive file and removes bitcode files
657// from them if exists. This function is to appease the MSVC linker as
658// their linker doesn't like archive files containing non-native
659// object files.
660//
661// If a given archive doesn't contain bitcode files, the archive path
662// is returned as-is. Otherwise, a new temporary file is created and
663// its path is returned.
664static Optional<std::string>
665filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000666 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000667 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000668 MemoryBufferRef MBRef = MB->getMemBufferRef();
669 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000670
671 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000672 return None;
673 if (Magic != file_magic::archive)
674 return Path.str();
675 if (!needsRebuilding(MBRef))
676 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000677
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000678 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000679 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000680 MBRef.getBufferIdentifier() + ": failed to parse archive");
681
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000682 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000683 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000684 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
685 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000686
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000687 if (New.empty())
688 return None;
689
690 log("Creating a temporary archive for " + Path + " to remove bitcode files");
691
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000692 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000693 if (std::error_code EC = sys::fs::createTemporaryFile(
694 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000695 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000696 std::string Temp = S.str();
697 TemporaryFiles.push_back(Temp);
698
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000699 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000700 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
701 /*Deterministics=*/true,
702 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000703 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
704 error("failed to create a new archive " + S.str() + ": " + EI.message());
705 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000706 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000707}
708
709// Create response file contents and invoke the MSVC linker.
710void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000711 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000712 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000713
Bob Haarman41108162017-04-21 21:38:01 +0000714 // Write out archive members that we used in symbol resolution and pass these
715 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
716 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000717 for (ObjFile *Obj : ObjFile::Instances) {
718 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000719 continue;
720 SmallString<128> S;
721 int Fd;
722 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000723 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000724 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000725 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000726 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000727 Temps.push_back(S.str());
728 Rsp += quote(S) + "\n";
729 }
730
Rui Ueyama85d54b02017-02-23 00:26:42 +0000731 for (auto *Arg : Args) {
732 switch (Arg->getOption().getID()) {
733 case OPT_linkrepro:
734 case OPT_lldmap:
735 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000736 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000737 case OPT_msvclto:
738 // LLD-specific options are stripped.
739 break;
740 case OPT_opt:
741 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000742 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000743 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000744 case OPT_INPUT: {
745 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
746 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000747 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000748 continue;
749 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000750 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000751 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000752 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000753 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000754 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000755 }
756 }
757
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000758 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000759 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000760
761 for (StringRef Path : Temps)
762 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000763}
764
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000765void LinkerDriver::enqueueTask(std::function<void()> Task) {
766 TaskQueue.push_back(std::move(Task));
767}
768
769bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000770 ScopedTimer T(InputFileTimer);
771
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000772 bool DidWork = !TaskQueue.empty();
773 while (!TaskQueue.empty()) {
774 TaskQueue.front()();
775 TaskQueue.pop_front();
776 }
777 return DidWork;
778}
779
Rui Ueyama57175aa2018-01-27 00:34:46 +0000780// Parse an /order file. If an option is given, the linker places
781// COMDAT sections in the same order as their names appear in the
782// given file.
783static void parseOrderFile(StringRef Arg) {
784 // For some reason, the MSVC linker requires a filename to be
785 // preceded by "@".
786 if (!Arg.startswith("@")) {
787 error("malformed /order option: '@' missing");
788 return;
789 }
790
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000791 // Get a list of all comdat sections for error checking.
792 DenseSet<StringRef> Set;
793 for (Chunk *C : Symtab->getChunks())
794 if (auto *Sec = dyn_cast<SectionChunk>(C))
795 if (Sec->Sym)
796 Set.insert(Sec->Sym->getName());
797
Rui Ueyama57175aa2018-01-27 00:34:46 +0000798 // Open a file.
799 StringRef Path = Arg.substr(1);
800 std::unique_ptr<MemoryBuffer> MB = CHECK(
801 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
802
803 // Parse a file. An order file contains one symbol per line.
804 // All symbols that were not present in a given order file are
805 // considered to have the lowest priority 0 and are placed at
806 // end of an output section.
807 for (std::string S : args::getLines(MB->getMemBufferRef())) {
808 if (Config->Machine == I386 && !isDecorated(S))
809 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000810
Nico Weber0771c602018-03-09 12:41:04 +0000811 if (Set.count(S) == 0) {
812 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000813 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000814 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000815 else
816 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000817 }
818}
819
Rui Ueyama8fe17672016-12-08 20:50:47 +0000820void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000821 // If the first command line argument is "/lib", link.exe acts like lib.exe.
822 // We call our own implementation of lib.exe that understands bitcode files.
823 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
824 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000825 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000826 return;
827 }
828
Peter Collingbourne60c16162015-06-01 20:10:10 +0000829 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000830 InitializeAllTargetInfos();
831 InitializeAllTargets();
832 InitializeAllTargetMCs();
833 InitializeAllAsmParsers();
834 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000835
Rui Ueyama411c63602015-05-28 19:09:30 +0000836 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000837 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000838 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000839
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000840 // Parse and evaluate -mllvm options.
841 std::vector<const char *> V;
842 V.push_back("lld-link (LLVM option parsing)");
843 for (auto *Arg : Args.filtered(OPT_mllvm))
844 V.push_back(Arg->getValue());
845 cl::ParseCommandLineOptions(V.size(), V.data());
846
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000847 // Handle /errorlimit early, because error() depends on it.
848 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
849 int N = 20;
850 StringRef S = Arg->getValue();
851 if (S.getAsInteger(10, N))
852 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000853 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000854 }
855
Rui Ueyama5c726432015-05-29 16:11:52 +0000856 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000857 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000858 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000859 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000860 }
861
Zachary Turner727f1532018-01-17 19:16:26 +0000862 if (Args.hasArg(OPT_show_timing))
863 Config->ShowTiming = true;
864
865 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000866 // Handle --version, which is an lld extension. This option is a bit odd
867 // because it doesn't start with "/", but we deliberately chose "--" to
868 // avoid conflict with /version and for compatibility with clang-cl.
869 if (Args.hasArg(OPT_dash_dash_version)) {
870 outs() << getLLDVersion() << "\n";
871 return;
872 }
873
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000874 // Handle /lldmingw early, since it can potentially affect how other
875 // options are handled.
876 Config->MinGW = Args.hasArg(OPT_lldmingw);
877
Peter Collingbournefeee2102016-07-26 02:00:42 +0000878 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
879 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000880 sys::path::append(Path, "repro.tar");
881
882 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
883 TarWriter::create(Path, "repro");
884
885 if (ErrOrWriter) {
886 Tar = std::move(*ErrOrWriter);
887 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000888 error("/linkrepro: failed to open " + Path + ": " +
889 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000890 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000891 }
892
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000893 if (!Args.hasArg(OPT_INPUT)) {
894 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000895 Config->NoEntry = true;
896 else
897 fatal("no input files");
898 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000899
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000900 // Construct search path list.
901 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000902 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000903 SearchPaths.push_back(Arg->getValue());
904 addLibSearchPaths();
905
Bob Haarmane90ac012017-12-28 07:02:13 +0000906 // Handle /ignore
907 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000908 if (StringRef(Arg->getValue()) == "4037")
909 Config->WarnMissingOrderSymbol = false;
910 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000911 Config->WarnLocallyDefinedImported = false;
912 // Other warning numbers are ignored.
913 }
914
Rui Ueyamaad660982015-06-07 00:20:32 +0000915 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000916 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000917 Config->OutputFile = Arg->getValue();
918
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000919 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000920 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000921 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000922 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000923
Rui Ueyama95925fd2015-06-28 19:35:15 +0000924 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000925 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000926 Config->Force = true;
927
Rui Ueyama6600eb12015-07-04 23:37:32 +0000928 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000929 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000930 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000931 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000932 if (auto *Arg = Args.getLastArg(OPT_debugtype))
933 Config->DebugTypes = parseDebugType(Arg->getValue());
934 else
935 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000936 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000937
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000938 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000939 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000940 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000941 if (auto *Arg = Args.getLastArg(OPT_pdb))
942 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000943 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
944 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000945 if (Args.hasArg(OPT_natvis))
946 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
947 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000948
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000949 // Handle /noentry
950 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000951 if (Args.hasArg(OPT_dll))
952 Config->NoEntry = true;
953 else
954 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000955 }
956
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000957 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000958 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000959 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000960 Config->ManifestID = 2;
961 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000962
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000963 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
964 // because we need to explicitly check whether that option or its inverse was
965 // present in the argument list in order to handle /fixed.
966 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
967 if (DynamicBaseArg &&
968 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
969 Config->DynamicBase = false;
970
Nico Webera7643792018-03-30 17:17:04 +0000971 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
972 // default setting for any other project type.", but link.exe defaults to
973 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000974 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
975 if (Fixed) {
976 if (DynamicBaseArg &&
977 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000978 error("/fixed must not be specified with /dynamicbase");
979 } else {
980 Config->Relocatable = false;
981 Config->DynamicBase = false;
982 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000983 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000984
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000985 // Handle /appcontainer
986 Config->AppContainer =
987 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000988
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000989 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000990 if (auto *Arg = Args.getLastArg(OPT_machine))
991 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000992
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000993 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000994 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000995 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
996
997 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000998 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000999 Config->NoDefaultLibAll = true;
1000
Rui Ueyama804a8b62015-05-29 16:18:15 +00001001 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +00001002 if (auto *Arg = Args.getLastArg(OPT_base))
1003 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +00001004
1005 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +00001006 if (auto *Arg = Args.getLastArg(OPT_stack))
1007 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +00001008
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001009 // Handle /guard:cf
1010 if (auto *Arg = Args.getLastArg(OPT_guard))
1011 parseGuard(Arg->getValue());
1012
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001013 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +00001014 if (auto *Arg = Args.getLastArg(OPT_heap))
1015 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +00001016
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001017 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +00001018 if (auto *Arg = Args.getLastArg(OPT_version))
1019 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1020 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +00001021
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001022 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +00001023 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1024 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1025 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +00001026
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001027 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001028 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001029 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001030
Rui Ueyama08d5e182015-06-18 23:20:11 +00001031 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001032 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001033 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001034
Rui Ueyamab95188c2015-06-18 20:27:09 +00001035 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001036 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001037 Config->Implib = Arg->getValue();
1038
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001039 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001040 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1041 unsigned ICFLevel =
1042 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
David Blaikie6521ed92015-06-22 22:06:52 +00001043 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001044 std::string Str = StringRef(Arg->getValue()).lower();
1045 SmallVector<StringRef, 1> Vec;
1046 StringRef(Str).split(Vec, ',');
1047 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001048 if (S == "ref") {
1049 DoGC = true;
1050 } else if (S == "noref") {
1051 DoGC = false;
1052 } else if (S == "icf" || S.startswith("icf=")) {
1053 ICFLevel = 2;
1054 } else if (S == "noicf") {
1055 ICFLevel = 0;
1056 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001057 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001058 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
1059 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001060 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001061 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001062 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001063 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001064 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001065 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001066 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001067 if (N.getAsInteger(10, Config->LTOPartitions) ||
1068 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001069 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001070 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001071 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001072 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001073 }
1074
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001075 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1076 // explicitly.
1077 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1078 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1079 // comdat readonly data.
1080 if (ICFLevel == 1 && !DoGC)
1081 ICFLevel = 0;
1082 Config->DoGC = DoGC;
1083 Config->DoICF = ICFLevel > 0;
1084
Bob Haarman69b196d2017-02-08 18:36:41 +00001085 // Handle /lldsavetemps
1086 if (Args.hasArg(OPT_lldsavetemps))
1087 Config->SaveTemps = true;
1088
Martin Storsjo53518912018-03-14 20:17:16 +00001089 // Handle /kill-at
1090 if (Args.hasArg(OPT_kill_at))
1091 Config->KillAt = true;
1092
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001093 // Handle /lldltocache
1094 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1095 Config->LTOCache = Arg->getValue();
1096
1097 // Handle /lldsavecachepolicy
1098 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001099 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001100 parseCachePruningPolicy(Arg->getValue()),
1101 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1102
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001103 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001104 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001105 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001106
Rui Ueyama6600eb12015-07-04 23:37:32 +00001107 // Handle /merge
1108 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001109 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001110
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001111 // Add default section merging rules after user rules. User rules take
1112 // precedence, but we will emit a warning if there is a conflict.
1113 parseMerge(".idata=.rdata");
1114 parseMerge(".didat=.rdata");
1115 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001116 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001117 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001118
Rui Ueyama440138c2016-06-20 03:39:39 +00001119 // Handle /section
1120 for (auto *Arg : Args.filtered(OPT_section))
1121 parseSection(Arg->getValue());
1122
Martin Storsjod2752aa2017-08-14 19:07:27 +00001123 // Handle /aligncomm
1124 for (auto *Arg : Args.filtered(OPT_aligncomm))
1125 parseAligncomm(Arg->getValue());
1126
Nico Webera7a2c442017-07-25 18:08:03 +00001127 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1128 // also passed.
1129 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1130 Config->ManifestDependency = Arg->getValue();
1131 Config->Manifest = Configuration::SideBySide;
1132 }
1133
1134 // Handle /manifest and /manifest:
1135 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1136 if (Arg->getOption().getID() == OPT_manifest)
1137 Config->Manifest = Configuration::SideBySide;
1138 else
1139 parseManifest(Arg->getValue());
1140 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001141
1142 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001143 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1144 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001145
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001146 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001147 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001148 Config->ManifestFile = Arg->getValue();
1149
Rui Ueyamaafb19012016-04-19 01:21:58 +00001150 // Handle /manifestinput
1151 for (auto *Arg : Args.filtered(OPT_manifestinput))
1152 Config->ManifestInput.push_back(Arg->getValue());
1153
Nico Webera7a2c442017-07-25 18:08:03 +00001154 if (!Config->ManifestInput.empty() &&
1155 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001156 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001157 }
1158
Rui Ueyama6592ff82015-06-16 23:13:00 +00001159 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001160 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1161 Config->AllowIsolation =
1162 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001163 Config->Incremental =
1164 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001165 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1166 !Args.hasArg(OPT_profile));
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001167 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001168 Config->TerminalServerAware =
1169 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001170 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001171 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001172
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001173 Config->MapFile = getMapFile(Args);
1174
Nico Weber0945ad62018-03-30 17:14:50 +00001175 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1176 warn("ignoring '/incremental' due to '/profile' specification");
1177 Config->Incremental = false;
1178 }
1179
1180 if (Config->Incremental && Args.hasArg(OPT_order)) {
1181 warn("ignoring '/incremental' due to '/order' specification");
1182 Config->Incremental = false;
1183 }
1184
Bob Haarman5ec44852018-01-31 23:44:00 +00001185 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001186 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001187 "disable");
1188 Config->Incremental = false;
1189 }
1190
1191 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001192 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001193 "disable");
1194 Config->Incremental = false;
1195 }
1196
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001197 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001198 return;
1199
Martin Storsjo8278ba52017-09-13 07:28:03 +00001200 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001201 // Create a list of input files. Files can be given as arguments
1202 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001203 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001204 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1205 switch (Arg->getOption().getID()) {
1206 case OPT_INPUT:
1207 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1208 enqueuePath(*Path, WholeArchiveFlag);
1209 break;
1210 case OPT_wholearchive_file:
1211 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1212 enqueuePath(*Path, true);
1213 break;
1214 }
1215 }
David Blaikie6521ed92015-06-22 22:06:52 +00001216 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001217 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001218 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001219
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001220 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001221 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001222 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001223
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001224 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001225 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001226
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001227 // We should have inferred a machine type by now from the input files, but if
1228 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001229 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001230 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001231 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001232 }
1233
Eric Beckmann9e19d792017-06-17 02:26:27 +00001234 // Input files can be Windows resource files (.res files). We use
1235 // WindowsResource to convert resource files to a regular COFF file,
1236 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001237 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001238 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001239
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001240 if (Tar)
1241 Tar->append("response.txt",
1242 createResponseFile(Args, FilePaths,
1243 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001244
Rui Ueyama4d545342015-07-28 03:12:00 +00001245 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001246 Config->LargeAddressAware = Args.hasFlag(
1247 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001248
Rui Ueyamad68e2112015-07-28 03:15:57 +00001249 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001250 Config->HighEntropyVA =
1251 Config->is64() &&
1252 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001253
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001254 if (!Config->DynamicBase &&
1255 (Config->Machine == ARMNT || Config->Machine == ARM64))
1256 error("/dynamicbase:no is not compatible with " +
1257 machineToStr(Config->Machine));
1258
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001259 // Handle /entry and /dll
1260 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1261 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001262 } else if (!Config->Entry && !Config->NoEntry) {
1263 if (Args.hasArg(OPT_dll)) {
1264 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1265 : "_DllMainCRTStartup";
1266 Config->Entry = addUndefined(S);
1267 } else {
1268 // Windows specific -- If entry point name is not given, we need to
1269 // infer that from user-defined entry name.
1270 StringRef S = findDefaultEntry();
1271 if (S.empty())
1272 fatal("entry point must be defined");
1273 Config->Entry = addUndefined(S);
1274 log("Entry name inferred: " + S);
1275 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001276 }
1277
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001278 // Handle /export
1279 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001280 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001281 if (Config->Machine == I386) {
1282 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001283 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001284 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001285 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001286 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001287 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001288 }
1289
1290 // Handle /def
1291 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001292 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001293 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001294 }
1295
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001296 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001297 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001298 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001299 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001300 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001301 }
1302
Rui Ueyama6d249082015-07-13 22:31:45 +00001303 // Handle /delayload
1304 for (auto *Arg : Args.filtered(OPT_delayload)) {
1305 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001306 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001307 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001308 } else {
1309 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001310 }
1311 }
1312
Reid Kleckner7668182e2017-03-21 00:12:51 +00001313 // Set default image name if neither /out or /def set it.
1314 if (Config->OutputFile.empty()) {
1315 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001316 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001317 }
1318
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001319 if (ShouldCreatePDB) {
1320 // Put the PDB next to the image if no /pdb flag was passed.
1321 if (Config->PDBPath.empty()) {
1322 Config->PDBPath = Config->OutputFile;
1323 sys::path::replace_extension(Config->PDBPath, ".pdb");
1324 }
1325
1326 // The embedded PDB path should be the absolute path to the PDB if no
1327 // /pdbaltpath flag was passed.
1328 if (Config->PDBAltPath.empty()) {
1329 Config->PDBAltPath = Config->PDBPath;
1330 sys::fs::make_absolute(Config->PDBAltPath);
1331 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001332 }
1333
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001334 // Set default image base if /base is not given.
1335 if (Config->ImageBase == uint64_t(-1))
1336 Config->ImageBase = getDefaultImageBase();
1337
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001338 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001339 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001340 Symtab->addAbsolute("___safe_se_handler_table", 0);
1341 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001342 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001343
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001344 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1345 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001346 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001347 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1348 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1349 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1350 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001351 // Needed for MSVC 2017 15.5 CRT.
1352 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001353
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001354 // This code may add new undefined symbols to the link, which may enqueue more
1355 // symbol resolution tasks, so we need to continue executing tasks until we
1356 // converge.
1357 do {
1358 // Windows specific -- if entry point is not found,
1359 // search for its mangled names.
1360 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001361 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001362
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001363 // Windows specific -- Make sure we resolve all dllexported symbols.
1364 for (Export &E : Config->Exports) {
1365 if (!E.ForwardTo.empty())
1366 continue;
1367 E.Sym = addUndefined(E.Name);
1368 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001369 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001370 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001371
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001372 // Add weak aliases. Weak aliases is a mechanism to give remaining
1373 // undefined symbols final chance to be resolved successfully.
1374 for (auto Pair : Config->AlternateNames) {
1375 StringRef From = Pair.first;
1376 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001377 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001378 if (!Sym)
1379 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001380 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001381 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001382 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001383 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001384
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001385 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001386 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001387 addUndefined(mangle("_load_config_used"));
1388 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001389
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001390 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001391 return;
1392
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001393 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1394 // This is useful because MSVC link.exe can generate complete PDBs.
1395 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001396 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001397 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001398 }
1399
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001400 // Do LTO by compiling bitcode input files to a set of native COFF files then
1401 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001402 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001403 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001404
Peter Collingbourne2612a322015-07-04 05:28:41 +00001405 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001406 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001407 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001408 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001409
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001410 // Windows specific -- if no /subsystem is given, we need to infer
1411 // that from entry point name.
1412 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001413 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001414 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001415 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001416 }
1417
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001418 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001419 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001420 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001421 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001422 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001423 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001424 return;
1425 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001426
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001427 // In MinGW, all symbols are automatically exported if no symbols
1428 // are chosen to be exported.
1429 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1430 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001431 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001432
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001433 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001434 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001435 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001436 return;
1437 Export E;
1438 E.Name = Def->getName();
1439 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001440 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001441 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001442 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001443 Config->Exports.push_back(E);
1444 });
1445 }
1446
Rui Ueyama151d8622015-06-17 20:40:43 +00001447 // Windows specific -- when we are creating a .dll file, we also
1448 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001449 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001450 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001451 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001452 assignExportOrdinals();
1453 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001454
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001455 // Handle /output-def (MinGW specific).
1456 if (auto *Arg = Args.getLastArg(OPT_output_def))
1457 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001458
Martin Storsjod2752aa2017-08-14 19:07:27 +00001459 // Set extra alignment for .comm symbols
1460 for (auto Pair : Config->AlignComm) {
1461 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001462 uint32_t Alignment = Pair.second;
1463
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001464 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001465 if (!Sym) {
1466 warn("/aligncomm symbol " + Name + " not found");
1467 continue;
1468 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001469
Rui Ueyama616cd992017-10-31 16:10:24 +00001470 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001471 if (!DC) {
1472 warn("/aligncomm symbol " + Name + " of wrong kind");
1473 continue;
1474 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001475
1476 CommonChunk *C = DC->getChunk();
1477 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001478 }
1479
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001480 // Windows specific -- Create a side-by-side manifest file.
1481 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001482 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001483
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001484 // Handle /order. We want to do this at this moment because we
1485 // need a complete list of comdat sections to warn on nonexistent
1486 // functions.
1487 if (auto *Arg = Args.getLastArg(OPT_order))
1488 parseOrderFile(Arg->getValue());
1489
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001490 // Identify unreferenced COMDAT sections.
1491 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001492 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001493
1494 // Identify identical COMDAT sections to merge them.
1495 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001496 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001497
Rui Ueyama411c63602015-05-28 19:09:30 +00001498 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001499 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001500
1501 // Stop early so we can print the results.
1502 Timer::root().stop();
1503 if (Config->ShowTiming)
1504 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001505}
1506
Rui Ueyama411c63602015-05-28 19:09:30 +00001507} // namespace coff
1508} // namespace lld