blob: e9a76f7a6a33fa468b0684102c5d130d7122d9e0 [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- Driver.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Rui Ueyama411c63602015-05-28 19:09:30 +000010#include "Driver.h"
Rui Ueyama1d99ab32016-09-15 22:24:51 +000011#include "Config.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000012#include "InputFiles.h"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000013#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000015#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "Writer.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000017#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000018#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000019#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000020#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000021#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000022#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000023#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000024#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000025#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000026#include "llvm/Object/COFFImportFile.h"
27#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000028#include "llvm/Option/Arg.h"
29#include "llvm/Option/ArgList.h"
30#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000032#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000033#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000034#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000035#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000036#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000037#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000038#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000039#include <memory>
40
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000041#include <future>
42
Rui Ueyama411c63602015-05-28 19:09:30 +000043using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000044using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000045using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000046using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000047
Rui Ueyama3500f662015-05-28 20:30:06 +000048namespace lld {
49namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000050
Zachary Turner727f1532018-01-17 19:16:26 +000051static Timer InputFileTimer("Input File Reading", Timer::root());
52
Rui Ueyama3500f662015-05-28 20:30:06 +000053Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000054LinkerDriver *Driver;
55
Rui Ueyama6f4e2552017-10-23 20:03:32 +000056bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Bob Haarmanb8a59c82017-10-25 22:28:38 +000057 errorHandler().LogName = Args[0];
58 errorHandler().ErrorOS = &Diag;
59 errorHandler().ColorDiagnostics = Diag.has_colors();
60 errorHandler().ErrorLimitExceededMsg =
61 "too many errors emitted, stopping now"
62 " (use /ERRORLIMIT:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000063 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000064 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000065 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyamacbf969e2017-08-28 21:51:07 +000066
67 Symtab = make<SymbolTable>();
68
Rui Ueyama7fed58c2016-12-08 19:10:28 +000069 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000070 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000071
72 // Call exit() if we can to avoid calling destructors.
73 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000074 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000075
76 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000077 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000078}
Rui Ueyama411c63602015-05-28 19:09:30 +000079
Nico Weber5660de72016-04-20 22:34:15 +000080// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000081static std::string getOutputPath(StringRef Path) {
82 auto P = Path.find_last_of("\\/");
83 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000084 const char* E = Config->DLL ? ".dll" : ".exe";
85 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000086}
87
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000088// ErrorOr is not default constructible, so it cannot be used as the type
89// parameter of a future.
90// FIXME: We could open the file in createFutureForFile and avoid needing to
91// return an error here, but for the moment that would cost us a file descriptor
92// (a limited resource on Windows) for the duration that the future is pending.
93typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
94
95// Create a std::future that opens and maps a file using the best strategy for
96// the host platform.
97static std::future<MBErrPair> createFutureForFile(std::string Path) {
98#if LLVM_ON_WIN32
99 // On Windows, file I/O is relatively slow so it is best to do this
100 // asynchronously.
101 auto Strategy = std::launch::async;
102#else
103 auto Strategy = std::launch::deferred;
104#endif
105 return std::async(Strategy, [=]() {
106 auto MBOrErr = MemoryBuffer::getFile(Path);
107 if (!MBOrErr)
108 return MBErrPair{nullptr, MBOrErr.getError()};
109 return MBErrPair{std::move(*MBOrErr), std::error_code()};
110 });
111}
112
113MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
114 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000115 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000116
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000117 if (Driver->Tar)
118 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
119 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000120 return MBRef;
121}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000122
Martin Storsjo8278ba52017-09-13 07:28:03 +0000123void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
124 bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000125 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000126 FilePaths.push_back(MBRef.getBufferIdentifier());
Peter Collingbournefeee2102016-07-26 02:00:42 +0000127
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000128 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000129 switch (identify_magic(MBRef.getBuffer())) {
130 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000131 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000132 break;
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000133
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000134 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000135 if (WholeArchive) {
136 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000137 CHECK(Archive::create(MBRef),
Martin Storsjo8278ba52017-09-13 07:28:03 +0000138 MBRef.getBufferIdentifier() + ": failed to parse archive");
139
140 for (MemoryBufferRef M : getArchiveMembers(File.get()))
141 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
142 return;
143 }
144 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000145 break;
Martin Storsjo8278ba52017-09-13 07:28:03 +0000146
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000147 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000148 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000149 break;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000150
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000151 case file_magic::coff_cl_gl_object:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000152 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000153 "Recompile without /GL");
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000154 break;
155
156 default:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000157 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000158 break;
159 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000160}
161
Martin Storsjo8278ba52017-09-13 07:28:03 +0000162void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000163 auto Future =
164 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
165 std::string PathStr = Path;
166 enqueueTask([=]() {
167 auto MBOrErr = Future->get();
168 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000169 error("could not open " + PathStr + ": " + MBOrErr.second.message());
170 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000171 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000172 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000173}
174
175void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
176 StringRef ParentName) {
177 file_magic Magic = identify_magic(MB.getBuffer());
178 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000179 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000180 return;
181 }
182
183 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000184 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000185 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000186 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000187 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000188 } else {
189 error("unknown file type: " + MB.getBufferIdentifier());
190 return;
191 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000192
193 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000194 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000195 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000196}
197
198void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
199 StringRef SymName,
200 StringRef ParentName) {
201 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000202 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000203 C.getMemoryBufferRef(),
204 "could not get the buffer for the member defining symbol " + SymName);
205 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
206 return;
207 }
208
209 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000210 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000211 "could not get the filename for the member defining symbol " +
212 SymName)));
213 enqueueTask([=]() {
214 auto MBOrErr = Future->get();
215 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000216 fatal("could not get the buffer for the member defining " + SymName +
217 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000218 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
219 ParentName);
220 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000221}
222
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000223static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000224 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
225 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000226}
227
Rui Ueyama411c63602015-05-28 19:09:30 +0000228// Parses .drectve section contents and returns a list of files
229// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000230void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000231 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000232 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000233 // /EXPORT: option can appear too many times, processing in fastpath.
234 opt::InputArgList Args;
235 std::vector<StringRef> Exports;
236 std::tie(Args, Exports) = Parser.parseDirectives(S);
237
238 for (StringRef E : Exports) {
239 // If a common header file contains dllexported function
240 // declarations, many object files may end up with having the
241 // same /EXPORT options. In order to save cost of parsing them,
242 // we dedup them first.
243 if (!DirectivesExports.insert(E).second)
244 continue;
245
246 Export Exp = parseExport(E);
247 if (Config->Machine == I386 && Config->MinGW) {
248 if (!isDecorated(Exp.Name))
249 Exp.Name = Saver.save("_" + Exp.Name);
250 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
251 Exp.ExtName = Saver.save("_" + Exp.ExtName);
252 }
253 Exp.Directives = true;
254 Config->Exports.push_back(Exp);
255 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000256
David Blaikie6521ed92015-06-22 22:06:52 +0000257 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000258 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000259 case OPT_aligncomm:
260 parseAligncomm(Arg->getValue());
261 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000262 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000263 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000264 break;
265 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000266 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000267 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000268 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000269 case OPT_entry:
270 Config->Entry = addUndefined(mangle(Arg->getValue()));
271 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000272 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000273 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000274 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000275 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000276 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000277 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000278 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000279 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000280 break;
281 case OPT_nodefaultlib:
282 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
283 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000284 case OPT_section:
285 parseSection(Arg->getValue());
286 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000287 case OPT_subsystem:
288 parseSubsystem(Arg->getValue(), &Config->Subsystem,
289 &Config->MajorOSVersion, &Config->MinorOSVersion);
290 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000291 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000292 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000293 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000294 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000295 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000296 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000297 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000298 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000299 }
300 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000301}
302
Rui Ueyama54b71da2015-05-31 19:17:12 +0000303// Find file from search paths. You can omit ".obj", this function takes
304// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000305StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000306 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
307 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000308 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000309 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000310 for (StringRef Dir : SearchPaths) {
311 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000312 sys::path::append(Path, Filename);
313 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000314 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000315 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000316 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000317 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000318 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000319 }
320 }
321 return Filename;
322}
323
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000324// Resolves a file path. This never returns the same path
325// (in that case, it returns None).
326Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
327 StringRef Path = doFindFile(Filename);
328 bool Seen = !VisitedFiles.insert(Path.lower()).second;
329 if (Seen)
330 return None;
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000331 if (Path.endswith_lower(".lib"))
332 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000333 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000334}
335
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000336// Find library file from search path.
337StringRef LinkerDriver::doFindLib(StringRef Filename) {
338 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000339 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000340 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000341 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000342 return doFindFile(Filename);
343}
344
345// Resolves a library path. /nodefaultlib options are taken into
346// consideration. This never returns the same path (in that case,
347// it returns None).
348Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
349 if (Config->NoDefaultLibAll)
350 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000351 if (!VisitedLibs.insert(Filename.lower()).second)
352 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000353 StringRef Path = doFindLib(Filename);
354 if (Config->NoDefaultLibs.count(Path))
355 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000356 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000357 return None;
358 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000359}
360
361// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000362void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000363 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
364 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000365 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000366 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000367 while (!Env.empty()) {
368 StringRef Path;
369 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000370 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000371 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000372}
373
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000374Symbol *LinkerDriver::addUndefined(StringRef Name) {
375 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000376 if (!B->IsGCRoot) {
377 B->IsGCRoot = true;
378 Config->GCRoot.push_back(B);
379 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000380 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000381}
382
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000383// Symbol names are mangled by appending "_" prefix on x86.
384StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000385 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
386 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000387 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000388 return Sym;
389}
390
Rui Ueyama45044f42015-06-29 01:03:53 +0000391// Windows specific -- find default entry point name.
392StringRef LinkerDriver::findDefaultEntry() {
393 // User-defined main functions and their corresponding entry points.
394 static const char *Entries[][2] = {
395 {"main", "mainCRTStartup"},
396 {"wmain", "wmainCRTStartup"},
397 {"WinMain", "WinMainCRTStartup"},
398 {"wWinMain", "wWinMainCRTStartup"},
399 };
400 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000401 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000402 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000403 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000404 }
405 return "";
406}
407
408WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000409 if (Config->DLL)
410 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000411 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000412 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000413 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000414 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
415 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000416}
417
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000418static uint64_t getDefaultImageBase() {
419 if (Config->is64())
420 return Config->DLL ? 0x180000000 : 0x140000000;
421 return Config->DLL ? 0x10000000 : 0x400000;
422}
423
Rui Ueyama8fe17672016-12-08 20:50:47 +0000424static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000425 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000426 ArrayRef<StringRef> SearchPaths) {
427 SmallString<0> Data;
428 raw_svector_ostream OS(Data);
429
430 for (auto *Arg : Args) {
431 switch (Arg->getOption().getID()) {
432 case OPT_linkrepro:
433 case OPT_INPUT:
434 case OPT_defaultlib:
435 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000436 case OPT_manifest:
437 case OPT_manifest_colon:
438 case OPT_manifestdependency:
439 case OPT_manifestfile:
440 case OPT_manifestinput:
441 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000442 break;
443 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000444 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000445 }
446 }
447
448 for (StringRef Path : SearchPaths) {
449 std::string RelPath = relativeToRoot(Path);
450 OS << "/libpath:" << quote(RelPath) << "\n";
451 }
452
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000453 for (StringRef Path : FilePaths)
454 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000455
456 return Data.str();
457}
458
Rui Ueyama8fe17672016-12-08 20:50:47 +0000459static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000460 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
461 if (Args.hasArg(OPT_driver))
462 DebugTypes |= static_cast<unsigned>(DebugType::PData);
463 if (Args.hasArg(OPT_profile))
464 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
465 return DebugTypes;
466}
467
468static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000469 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000470 Arg.split(Types, ',', /*KeepEmpty=*/false);
471
472 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
473 for (StringRef Type : Types)
474 DebugTypes |= StringSwitch<unsigned>(Type.lower())
475 .Case("cv", static_cast<unsigned>(DebugType::CV))
476 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000477 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
478 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000479 return DebugTypes;
480}
481
Hans Wennborg1818e652016-12-09 20:54:44 +0000482static std::string getMapFile(const opt::InputArgList &Args) {
483 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
484 if (!Arg)
485 return "";
486 if (Arg->getOption().getID() == OPT_lldmap_file)
487 return Arg->getValue();
488
489 assert(Arg->getOption().getID() == OPT_lldmap);
490 StringRef OutFile = Config->OutputFile;
491 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
492}
493
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000494static std::string getImplibPath() {
495 if (!Config->Implib.empty())
496 return Config->Implib;
497 SmallString<128> Out = StringRef(Config->OutputFile);
498 sys::path::replace_extension(Out, ".lib");
499 return Out.str();
500}
501
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000502//
503// The import name is caculated as the following:
504//
505// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
506// -----+----------------+---------------------+------------------
507// LINK | {value} | {value}.{.dll/.exe} | {output name}
508// LIB | {value} | {value}.dll | {output name}.dll
509//
510static std::string getImportName(bool AsLib) {
511 SmallString<128> Out;
512
513 if (Config->ImportName.empty()) {
514 Out.assign(sys::path::filename(Config->OutputFile));
515 if (AsLib)
516 sys::path::replace_extension(Out, ".dll");
517 } else {
518 Out.assign(Config->ImportName);
519 if (!sys::path::has_extension(Out))
520 sys::path::replace_extension(Out,
521 (Config->DLL || AsLib) ? ".dll" : ".exe");
522 }
523
524 return Out.str();
525}
526
527static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000528 std::vector<COFFShortExport> Exports;
529 for (Export &E1 : Config->Exports) {
530 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000531 E2.Name = E1.Name;
532 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000533 E2.ExtName = E1.ExtName;
534 E2.Ordinal = E1.Ordinal;
535 E2.Noname = E1.Noname;
536 E2.Data = E1.Data;
537 E2.Private = E1.Private;
538 E2.Constant = E1.Constant;
539 Exports.push_back(E2);
540 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000541
Bob Haarman4ce341f2018-01-23 00:36:42 +0000542 auto HandleError = [](Error &&E) {
543 handleAllErrors(std::move(E),
544 [](ErrorInfoBase &EIB) { error(EIB.message()); });
545 };
546 std::string LibName = getImportName(AsLib);
547 std::string Path = getImplibPath();
548
549 // If the import library already exists, replace it only if the contents
550 // have changed.
551 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(Path);
552 if (!OldBuf) {
553 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
554 false, Config->MinGW));
555 return;
556 }
557
558 SmallString<128> TmpName;
559 if (std::error_code EC =
560 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
561 fatal("cannot create temporary file for import library " + Path + ": " +
562 EC.message());
563
564 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
565 false, Config->MinGW)) {
566 HandleError(std::move(E));
567 return;
568 }
569
570 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(TmpName));
571 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
572 OldBuf->reset();
573 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
574 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000575}
576
577static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000578 std::unique_ptr<MemoryBuffer> MB = CHECK(
579 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000580 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
581 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000582
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000583 if (Config->OutputFile.empty())
584 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000585 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000586 if (M.ImageBase)
587 Config->ImageBase = M.ImageBase;
588 if (M.StackReserve)
589 Config->StackReserve = M.StackReserve;
590 if (M.StackCommit)
591 Config->StackCommit = M.StackCommit;
592 if (M.HeapReserve)
593 Config->HeapReserve = M.HeapReserve;
594 if (M.HeapCommit)
595 Config->HeapCommit = M.HeapCommit;
596 if (M.MajorImageVersion)
597 Config->MajorImageVersion = M.MajorImageVersion;
598 if (M.MinorImageVersion)
599 Config->MinorImageVersion = M.MinorImageVersion;
600 if (M.MajorOSVersion)
601 Config->MajorOSVersion = M.MajorOSVersion;
602 if (M.MinorOSVersion)
603 Config->MinorOSVersion = M.MinorOSVersion;
604
605 for (COFFShortExport E1 : M.Exports) {
606 Export E2;
607 E2.Name = Saver.save(E1.Name);
608 if (E1.isWeak())
609 E2.ExtName = Saver.save(E1.ExtName);
610 E2.Ordinal = E1.Ordinal;
611 E2.Noname = E1.Noname;
612 E2.Data = E1.Data;
613 E2.Private = E1.Private;
614 E2.Constant = E1.Constant;
615 Config->Exports.push_back(E2);
616 }
617}
618
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000619// A helper function for filterBitcodeFiles.
620static bool needsRebuilding(MemoryBufferRef MB) {
621 // The MSVC linker doesn't support thin archives, so if it's a thin
622 // archive, we always need to rebuild it.
623 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000624 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000625 if (File->isThin())
626 return true;
627
628 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000629 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000630 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
631 return true;
632 return false;
633}
634
635// Opens a given path as an archive file and removes bitcode files
636// from them if exists. This function is to appease the MSVC linker as
637// their linker doesn't like archive files containing non-native
638// object files.
639//
640// If a given archive doesn't contain bitcode files, the archive path
641// is returned as-is. Otherwise, a new temporary file is created and
642// its path is returned.
643static Optional<std::string>
644filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000645 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000646 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000647 MemoryBufferRef MBRef = MB->getMemBufferRef();
648 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000649
650 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000651 return None;
652 if (Magic != file_magic::archive)
653 return Path.str();
654 if (!needsRebuilding(MBRef))
655 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000656
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000657 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000658 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000659 MBRef.getBufferIdentifier() + ": failed to parse archive");
660
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000661 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000662 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000663 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
664 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000665
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000666 if (New.empty())
667 return None;
668
669 log("Creating a temporary archive for " + Path + " to remove bitcode files");
670
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000671 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000672 if (std::error_code EC = sys::fs::createTemporaryFile(
673 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000674 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000675 std::string Temp = S.str();
676 TemporaryFiles.push_back(Temp);
677
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000678 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000679 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
680 /*Deterministics=*/true,
681 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000682 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
683 error("failed to create a new archive " + S.str() + ": " + EI.message());
684 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000685 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000686}
687
688// Create response file contents and invoke the MSVC linker.
689void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000690 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000691 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000692
Bob Haarman41108162017-04-21 21:38:01 +0000693 // Write out archive members that we used in symbol resolution and pass these
694 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
695 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000696 for (ObjFile *Obj : ObjFile::Instances) {
697 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000698 continue;
699 SmallString<128> S;
700 int Fd;
701 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000702 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000703 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000704 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000705 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000706 Temps.push_back(S.str());
707 Rsp += quote(S) + "\n";
708 }
709
Rui Ueyama85d54b02017-02-23 00:26:42 +0000710 for (auto *Arg : Args) {
711 switch (Arg->getOption().getID()) {
712 case OPT_linkrepro:
713 case OPT_lldmap:
714 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000715 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000716 case OPT_msvclto:
717 // LLD-specific options are stripped.
718 break;
719 case OPT_opt:
720 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000721 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000722 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000723 case OPT_INPUT: {
724 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
725 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000726 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000727 continue;
728 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000729 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000730 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000731 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000732 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000733 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000734 }
735 }
736
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000737 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000738 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000739
740 for (StringRef Path : Temps)
741 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000742}
743
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000744void LinkerDriver::enqueueTask(std::function<void()> Task) {
745 TaskQueue.push_back(std::move(Task));
746}
747
748bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000749 ScopedTimer T(InputFileTimer);
750
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000751 bool DidWork = !TaskQueue.empty();
752 while (!TaskQueue.empty()) {
753 TaskQueue.front()();
754 TaskQueue.pop_front();
755 }
756 return DidWork;
757}
758
Rui Ueyama8fe17672016-12-08 20:50:47 +0000759void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000760 // If the first command line argument is "/lib", link.exe acts like lib.exe.
761 // We call our own implementation of lib.exe that understands bitcode files.
762 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
763 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000764 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000765 return;
766 }
767
Peter Collingbourne60c16162015-06-01 20:10:10 +0000768 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000769 InitializeAllTargetInfos();
770 InitializeAllTargets();
771 InitializeAllTargetMCs();
772 InitializeAllAsmParsers();
773 InitializeAllAsmPrinters();
774 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000775
Rui Ueyama411c63602015-05-28 19:09:30 +0000776 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000777 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000778 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000779
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000780 // Parse and evaluate -mllvm options.
781 std::vector<const char *> V;
782 V.push_back("lld-link (LLVM option parsing)");
783 for (auto *Arg : Args.filtered(OPT_mllvm))
784 V.push_back(Arg->getValue());
785 cl::ParseCommandLineOptions(V.size(), V.data());
786
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000787 // Handle /errorlimit early, because error() depends on it.
788 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
789 int N = 20;
790 StringRef S = Arg->getValue();
791 if (S.getAsInteger(10, N))
792 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000793 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000794 }
795
Rui Ueyama5c726432015-05-29 16:11:52 +0000796 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000797 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000798 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000799 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000800 }
801
Zachary Turner727f1532018-01-17 19:16:26 +0000802 if (Args.hasArg(OPT_show_timing))
803 Config->ShowTiming = true;
804
805 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000806 // Handle --version, which is an lld extension. This option is a bit odd
807 // because it doesn't start with "/", but we deliberately chose "--" to
808 // avoid conflict with /version and for compatibility with clang-cl.
809 if (Args.hasArg(OPT_dash_dash_version)) {
810 outs() << getLLDVersion() << "\n";
811 return;
812 }
813
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000814 // Handle /lldmingw early, since it can potentially affect how other
815 // options are handled.
816 Config->MinGW = Args.hasArg(OPT_lldmingw);
817
Peter Collingbournefeee2102016-07-26 02:00:42 +0000818 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
819 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000820 sys::path::append(Path, "repro.tar");
821
822 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
823 TarWriter::create(Path, "repro");
824
825 if (ErrOrWriter) {
826 Tar = std::move(*ErrOrWriter);
827 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000828 error("/linkrepro: failed to open " + Path + ": " +
829 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000830 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000831 }
832
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000833 if (!Args.hasArg(OPT_INPUT)) {
834 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000835 Config->NoEntry = true;
836 else
837 fatal("no input files");
838 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000839
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000840 // Construct search path list.
841 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000842 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000843 SearchPaths.push_back(Arg->getValue());
844 addLibSearchPaths();
845
Bob Haarmane90ac012017-12-28 07:02:13 +0000846 // Handle /ignore
847 for (auto *Arg : Args.filtered(OPT_ignore)) {
848 if (StringRef(Arg->getValue()) == "4217")
849 Config->WarnLocallyDefinedImported = false;
850 // Other warning numbers are ignored.
851 }
852
Rui Ueyamaad660982015-06-07 00:20:32 +0000853 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000854 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000855 Config->OutputFile = Arg->getValue();
856
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000857 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000858 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000859 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000860 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000861
Rui Ueyama95925fd2015-06-28 19:35:15 +0000862 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000863 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000864 Config->Force = true;
865
Rui Ueyama6600eb12015-07-04 23:37:32 +0000866 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000867 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000868 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000869 if (auto *Arg = Args.getLastArg(OPT_debugtype))
870 Config->DebugTypes = parseDebugType(Arg->getValue());
871 else
872 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000873 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000874
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000875 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000876 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
877 if (ShouldCreatePDB)
878 if (auto *Arg = Args.getLastArg(OPT_pdb))
879 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000880
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000881 // Handle /noentry
882 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000883 if (Args.hasArg(OPT_dll))
884 Config->NoEntry = true;
885 else
886 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000887 }
888
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000889 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000890 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000891 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000892 Config->ManifestID = 2;
893 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000894
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000895 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
896 // because we need to explicitly check whether that option or its inverse was
897 // present in the argument list in order to handle /fixed.
898 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
899 if (DynamicBaseArg &&
900 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
901 Config->DynamicBase = false;
902
903 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
904 if (Fixed) {
905 if (DynamicBaseArg &&
906 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000907 error("/fixed must not be specified with /dynamicbase");
908 } else {
909 Config->Relocatable = false;
910 Config->DynamicBase = false;
911 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000912 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000913
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000914 // Handle /appcontainer
915 Config->AppContainer =
916 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000917
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000918 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000919 if (auto *Arg = Args.getLastArg(OPT_machine))
920 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000921
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000922 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000923 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000924 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
925
926 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000927 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000928 Config->NoDefaultLibAll = true;
929
Rui Ueyama804a8b62015-05-29 16:18:15 +0000930 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000931 if (auto *Arg = Args.getLastArg(OPT_base))
932 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000933
934 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000935 if (auto *Arg = Args.getLastArg(OPT_stack))
936 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000937
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000938 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000939 if (auto *Arg = Args.getLastArg(OPT_heap))
940 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000941
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000942 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000943 if (auto *Arg = Args.getLastArg(OPT_version))
944 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
945 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000946
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000947 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000948 if (auto *Arg = Args.getLastArg(OPT_subsystem))
949 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
950 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000951
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000952 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000953 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000954 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000955
Rui Ueyama08d5e182015-06-18 23:20:11 +0000956 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000957 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000958 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000959
Rui Ueyamab95188c2015-06-18 20:27:09 +0000960 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000961 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000962 Config->Implib = Arg->getValue();
963
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000964 // Handle /opt.
965 bool DoGC = !Args.hasArg(OPT_debug);
966 unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on
David Blaikie6521ed92015-06-22 22:06:52 +0000967 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000968 std::string Str = StringRef(Arg->getValue()).lower();
969 SmallVector<StringRef, 1> Vec;
970 StringRef(Str).split(Vec, ',');
971 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000972 if (S == "ref") {
973 DoGC = true;
974 } else if (S == "noref") {
975 DoGC = false;
976 } else if (S == "icf" || S.startswith("icf=")) {
977 ICFLevel = 2;
978 } else if (S == "noicf") {
979 ICFLevel = 0;
980 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +0000981 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000982 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
983 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000984 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000985 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +0000986 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000987 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000988 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000989 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +0000990 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000991 if (N.getAsInteger(10, Config->LTOPartitions) ||
992 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000993 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000994 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000995 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000996 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000997 }
998
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000999 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1000 // explicitly.
1001 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1002 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1003 // comdat readonly data.
1004 if (ICFLevel == 1 && !DoGC)
1005 ICFLevel = 0;
1006 Config->DoGC = DoGC;
1007 Config->DoICF = ICFLevel > 0;
1008
Bob Haarman69b196d2017-02-08 18:36:41 +00001009 // Handle /lldsavetemps
1010 if (Args.hasArg(OPT_lldsavetemps))
1011 Config->SaveTemps = true;
1012
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001013 // Handle /lldltocache
1014 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1015 Config->LTOCache = Arg->getValue();
1016
1017 // Handle /lldsavecachepolicy
1018 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001019 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001020 parseCachePruningPolicy(Arg->getValue()),
1021 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1022
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001023 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001024 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001025 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001026
Rui Ueyama6600eb12015-07-04 23:37:32 +00001027 // Handle /merge
1028 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001029 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001030
Rui Ueyama440138c2016-06-20 03:39:39 +00001031 // Handle /section
1032 for (auto *Arg : Args.filtered(OPT_section))
1033 parseSection(Arg->getValue());
1034
Martin Storsjod2752aa2017-08-14 19:07:27 +00001035 // Handle /aligncomm
1036 for (auto *Arg : Args.filtered(OPT_aligncomm))
1037 parseAligncomm(Arg->getValue());
1038
Nico Webera7a2c442017-07-25 18:08:03 +00001039 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1040 // also passed.
1041 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1042 Config->ManifestDependency = Arg->getValue();
1043 Config->Manifest = Configuration::SideBySide;
1044 }
1045
1046 // Handle /manifest and /manifest:
1047 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1048 if (Arg->getOption().getID() == OPT_manifest)
1049 Config->Manifest = Configuration::SideBySide;
1050 else
1051 parseManifest(Arg->getValue());
1052 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001053
1054 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001055 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1056 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001057
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001058 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001059 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001060 Config->ManifestFile = Arg->getValue();
1061
Rui Ueyamaafb19012016-04-19 01:21:58 +00001062 // Handle /manifestinput
1063 for (auto *Arg : Args.filtered(OPT_manifestinput))
1064 Config->ManifestInput.push_back(Arg->getValue());
1065
Nico Webera7a2c442017-07-25 18:08:03 +00001066 if (!Config->ManifestInput.empty() &&
1067 Config->Manifest != Configuration::Embed) {
1068 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1069 }
1070
Rui Ueyama6592ff82015-06-16 23:13:00 +00001071 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001072 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1073 Config->AllowIsolation =
1074 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1075 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1076 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001077 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001078 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001079
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001080 Config->MapFile = getMapFile(Args);
1081
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001082 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001083 return;
1084
Martin Storsjo8278ba52017-09-13 07:28:03 +00001085 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001086 // Create a list of input files. Files can be given as arguments
1087 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001088 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001089 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1090 switch (Arg->getOption().getID()) {
1091 case OPT_INPUT:
1092 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1093 enqueuePath(*Path, WholeArchiveFlag);
1094 break;
1095 case OPT_wholearchive_file:
1096 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1097 enqueuePath(*Path, true);
1098 break;
1099 }
1100 }
David Blaikie6521ed92015-06-22 22:06:52 +00001101 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001102 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001103 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001104
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001105 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001106 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001107 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001108
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001109 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001110 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001111
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001112 // We should have inferred a machine type by now from the input files, but if
1113 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001114 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001115 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001116 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001117 }
1118
Eric Beckmann9e19d792017-06-17 02:26:27 +00001119 // Input files can be Windows resource files (.res files). We use
1120 // WindowsResource to convert resource files to a regular COFF file,
1121 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001122 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001123 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001124
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001125 if (Tar)
1126 Tar->append("response.txt",
1127 createResponseFile(Args, FilePaths,
1128 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001129
Rui Ueyama4d545342015-07-28 03:12:00 +00001130 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001131 Config->LargeAddressAware = Args.hasFlag(
1132 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001133
Rui Ueyamad68e2112015-07-28 03:15:57 +00001134 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001135 Config->HighEntropyVA =
1136 Config->is64() &&
1137 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001138
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001139 if (!Config->DynamicBase &&
1140 (Config->Machine == ARMNT || Config->Machine == ARM64))
1141 error("/dynamicbase:no is not compatible with " +
1142 machineToStr(Config->Machine));
1143
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001144 // Handle /entry and /dll
1145 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1146 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001147 } else if (!Config->Entry && !Config->NoEntry) {
1148 if (Args.hasArg(OPT_dll)) {
1149 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1150 : "_DllMainCRTStartup";
1151 Config->Entry = addUndefined(S);
1152 } else {
1153 // Windows specific -- If entry point name is not given, we need to
1154 // infer that from user-defined entry name.
1155 StringRef S = findDefaultEntry();
1156 if (S.empty())
1157 fatal("entry point must be defined");
1158 Config->Entry = addUndefined(S);
1159 log("Entry name inferred: " + S);
1160 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001161 }
1162
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001163 // Handle /export
1164 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001165 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001166 if (Config->Machine == I386) {
1167 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001168 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001169 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001170 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001171 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001172 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001173 }
1174
1175 // Handle /def
1176 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001177 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001178 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001179 }
1180
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001181 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001182 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001183 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001184 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001185 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001186 }
1187
Rui Ueyama6d249082015-07-13 22:31:45 +00001188 // Handle /delayload
1189 for (auto *Arg : Args.filtered(OPT_delayload)) {
1190 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001191 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001192 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001193 } else {
1194 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001195 }
1196 }
1197
Reid Kleckner7668182e2017-03-21 00:12:51 +00001198 // Set default image name if neither /out or /def set it.
1199 if (Config->OutputFile.empty()) {
1200 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001201 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001202 }
1203
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001204 // Put the PDB next to the image if no /pdb flag was passed.
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +00001205 if (ShouldCreatePDB && Config->PDBPath.empty()) {
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001206 Config->PDBPath = Config->OutputFile;
1207 sys::path::replace_extension(Config->PDBPath, ".pdb");
1208 }
1209
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001210 // Set default image base if /base is not given.
1211 if (Config->ImageBase == uint64_t(-1))
1212 Config->ImageBase = getDefaultImageBase();
1213
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001214 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001215 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001216 Symtab->addAbsolute("___safe_se_handler_table", 0);
1217 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001218 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001219
Rui Ueyama107db552015-08-09 21:01:06 +00001220 // We do not support /guard:cf (control flow protection) yet.
1221 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001222 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1223 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1224 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1225 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1226 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1227 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1228 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001229 // Needed for MSVC 2017 15.5 CRT.
1230 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001231
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001232 // This code may add new undefined symbols to the link, which may enqueue more
1233 // symbol resolution tasks, so we need to continue executing tasks until we
1234 // converge.
1235 do {
1236 // Windows specific -- if entry point is not found,
1237 // search for its mangled names.
1238 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001239 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001240
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001241 // Windows specific -- Make sure we resolve all dllexported symbols.
1242 for (Export &E : Config->Exports) {
1243 if (!E.ForwardTo.empty())
1244 continue;
1245 E.Sym = addUndefined(E.Name);
1246 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001247 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001248 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001249
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001250 // Add weak aliases. Weak aliases is a mechanism to give remaining
1251 // undefined symbols final chance to be resolved successfully.
1252 for (auto Pair : Config->AlternateNames) {
1253 StringRef From = Pair.first;
1254 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001255 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001256 if (!Sym)
1257 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001258 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001259 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001260 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001261 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001262
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001263 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001264 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001265 addUndefined(mangle("_load_config_used"));
1266 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001267
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001268 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001269 return;
1270
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001271 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1272 // This is useful because MSVC link.exe can generate complete PDBs.
1273 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001274 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001275 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001276 }
1277
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001278 // Do LTO by compiling bitcode input files to a set of native COFF files then
1279 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001280 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001281 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001282
Peter Collingbourne2612a322015-07-04 05:28:41 +00001283 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001284 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001285 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001286 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001287
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001288 // Windows specific -- if no /subsystem is given, we need to infer
1289 // that from entry point name.
1290 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001291 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001292 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001293 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001294 }
1295
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001296 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001297 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001298 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001299 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001300 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001301 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001302 return;
1303 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001304
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001305 // In MinGW, all symbols are automatically exported if no symbols
1306 // are chosen to be exported.
1307 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1308 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001309 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001310
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001311 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001312 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001313 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001314 return;
1315 Export E;
1316 E.Name = Def->getName();
1317 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001318 if (Def->getChunk() &&
1319 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
1320 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001321 Config->Exports.push_back(E);
1322 });
1323 }
1324
Rui Ueyama151d8622015-06-17 20:40:43 +00001325 // Windows specific -- when we are creating a .dll file, we also
1326 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001327 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001328 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001329 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001330 assignExportOrdinals();
1331 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001332
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001333 // Handle /output-def (MinGW specific).
1334 if (auto *Arg = Args.getLastArg(OPT_output_def))
1335 writeDefFile(Arg->getValue());
Zachary Turner727f1532018-01-17 19:16:26 +00001336
Martin Storsjod2752aa2017-08-14 19:07:27 +00001337 // Set extra alignment for .comm symbols
1338 for (auto Pair : Config->AlignComm) {
1339 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001340 uint32_t Alignment = Pair.second;
1341
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001342 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001343 if (!Sym) {
1344 warn("/aligncomm symbol " + Name + " not found");
1345 continue;
1346 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001347
Rui Ueyama616cd992017-10-31 16:10:24 +00001348 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001349 if (!DC) {
1350 warn("/aligncomm symbol " + Name + " of wrong kind");
1351 continue;
1352 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001353
1354 CommonChunk *C = DC->getChunk();
1355 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001356 }
1357
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001358 // Windows specific -- Create a side-by-side manifest file.
1359 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001360 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001361
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001362 // Identify unreferenced COMDAT sections.
1363 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001364 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001365
1366 // Identify identical COMDAT sections to merge them.
1367 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001368 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001369
Rui Ueyama411c63602015-05-28 19:09:30 +00001370 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001371 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001372
1373 // Stop early so we can print the results.
1374 Timer::root().stop();
1375 if (Config->ShowTiming)
1376 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001377}
1378
Rui Ueyama411c63602015-05-28 19:09:30 +00001379} // namespace coff
1380} // namespace lld