blob: 0b426b3216114ddd9b112180ed367bac8c59a24f [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 Ueyama57175aa2018-01-27 00:34:46 +000017#include "lld/Common/Args.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000018#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000019#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000020#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000021#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000022#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000023#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000024#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000025#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000026#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000027#include "llvm/Object/COFFImportFile.h"
28#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include "llvm/Option/Arg.h"
30#include "llvm/Option/ArgList.h"
31#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000032#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000033#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000034#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000035#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000036#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000037#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000038#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000039#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000040#include <memory>
41
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000042#include <future>
43
Rui Ueyama411c63602015-05-28 19:09:30 +000044using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000045using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000046using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000047using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000048
Rui Ueyama3500f662015-05-28 20:30:06 +000049namespace lld {
50namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000051
Zachary Turner727f1532018-01-17 19:16:26 +000052static Timer InputFileTimer("Input File Reading", Timer::root());
53
Rui Ueyama3500f662015-05-28 20:30:06 +000054Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000055LinkerDriver *Driver;
56
Rui Ueyama6f4e2552017-10-23 20:03:32 +000057bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Bob Haarmanb8a59c82017-10-25 22:28:38 +000058 errorHandler().LogName = Args[0];
59 errorHandler().ErrorOS = &Diag;
60 errorHandler().ColorDiagnostics = Diag.has_colors();
61 errorHandler().ErrorLimitExceededMsg =
62 "too many errors emitted, stopping now"
63 " (use /ERRORLIMIT:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000064 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000065 Config = make<Configuration>();
Zachary Turner6708e0b2017-07-10 21:01:37 +000066 Config->Argv = {Args.begin(), Args.end()};
Rui Ueyamacbf969e2017-08-28 21:51:07 +000067
68 Symtab = make<SymbolTable>();
69
Rui Ueyama7fed58c2016-12-08 19:10:28 +000070 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000071 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000072
73 // Call exit() if we can to avoid calling destructors.
74 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000075 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000076
77 freeArena();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000078 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000079}
Rui Ueyama411c63602015-05-28 19:09:30 +000080
Nico Weber5660de72016-04-20 22:34:15 +000081// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000082static std::string getOutputPath(StringRef Path) {
83 auto P = Path.find_last_of("\\/");
84 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000085 const char* E = Config->DLL ? ".dll" : ".exe";
86 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000087}
88
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000089// ErrorOr is not default constructible, so it cannot be used as the type
90// parameter of a future.
91// FIXME: We could open the file in createFutureForFile and avoid needing to
92// return an error here, but for the moment that would cost us a file descriptor
93// (a limited resource on Windows) for the duration that the future is pending.
94typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
95
96// Create a std::future that opens and maps a file using the best strategy for
97// the host platform.
98static std::future<MBErrPair> createFutureForFile(std::string Path) {
99#if LLVM_ON_WIN32
100 // On Windows, file I/O is relatively slow so it is best to do this
101 // asynchronously.
102 auto Strategy = std::launch::async;
103#else
104 auto Strategy = std::launch::deferred;
105#endif
106 return std::async(Strategy, [=]() {
107 auto MBOrErr = MemoryBuffer::getFile(Path);
108 if (!MBOrErr)
109 return MBErrPair{nullptr, MBOrErr.getError()};
110 return MBErrPair{std::move(*MBOrErr), std::error_code()};
111 });
112}
113
114MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
115 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000116 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000117
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000118 if (Driver->Tar)
119 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
120 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000121 return MBRef;
122}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000123
Martin Storsjo8278ba52017-09-13 07:28:03 +0000124void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
125 bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000126 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000127 FilePaths.push_back(MBRef.getBufferIdentifier());
Peter Collingbournefeee2102016-07-26 02:00:42 +0000128
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000129 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000130 switch (identify_magic(MBRef.getBuffer())) {
131 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000132 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000133 break;
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000134
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000135 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000136 if (WholeArchive) {
137 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000138 CHECK(Archive::create(MBRef),
Martin Storsjo8278ba52017-09-13 07:28:03 +0000139 MBRef.getBufferIdentifier() + ": failed to parse archive");
140
141 for (MemoryBufferRef M : getArchiveMembers(File.get()))
142 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier());
143 return;
144 }
145 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000146 break;
Martin Storsjo8278ba52017-09-13 07:28:03 +0000147
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000148 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000149 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 break;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000151
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000152 case file_magic::coff_cl_gl_object:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000153 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000154 "Recompile without /GL");
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000155 break;
156
157 default:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000158 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000159 break;
160 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000161}
162
Martin Storsjo8278ba52017-09-13 07:28:03 +0000163void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000164 auto Future =
165 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
166 std::string PathStr = Path;
167 enqueueTask([=]() {
168 auto MBOrErr = Future->get();
169 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000170 error("could not open " + PathStr + ": " + MBOrErr.second.message());
171 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000172 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000173 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000174}
175
176void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
177 StringRef ParentName) {
178 file_magic Magic = identify_magic(MB.getBuffer());
179 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000180 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000181 return;
182 }
183
184 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000185 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000186 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000187 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000188 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000189 } else {
190 error("unknown file type: " + MB.getBufferIdentifier());
191 return;
192 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000193
194 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000195 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000196 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000197}
198
199void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
200 StringRef SymName,
201 StringRef ParentName) {
202 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000203 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000204 C.getMemoryBufferRef(),
205 "could not get the buffer for the member defining symbol " + SymName);
206 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
207 return;
208 }
209
210 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000211 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000212 "could not get the filename for the member defining symbol " +
213 SymName)));
214 enqueueTask([=]() {
215 auto MBOrErr = Future->get();
216 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000217 fatal("could not get the buffer for the member defining " + SymName +
218 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000219 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
220 ParentName);
221 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000222}
223
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000224static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000225 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
226 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000227}
228
Rui Ueyama411c63602015-05-28 19:09:30 +0000229// Parses .drectve section contents and returns a list of files
230// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000231void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000232 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000233 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000234 // /EXPORT: option can appear too many times, processing in fastpath.
235 opt::InputArgList Args;
236 std::vector<StringRef> Exports;
237 std::tie(Args, Exports) = Parser.parseDirectives(S);
238
239 for (StringRef E : Exports) {
240 // If a common header file contains dllexported function
241 // declarations, many object files may end up with having the
242 // same /EXPORT options. In order to save cost of parsing them,
243 // we dedup them first.
244 if (!DirectivesExports.insert(E).second)
245 continue;
246
247 Export Exp = parseExport(E);
248 if (Config->Machine == I386 && Config->MinGW) {
249 if (!isDecorated(Exp.Name))
250 Exp.Name = Saver.save("_" + Exp.Name);
251 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
252 Exp.ExtName = Saver.save("_" + Exp.ExtName);
253 }
254 Exp.Directives = true;
255 Config->Exports.push_back(Exp);
256 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000257
David Blaikie6521ed92015-06-22 22:06:52 +0000258 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000259 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000260 case OPT_aligncomm:
261 parseAligncomm(Arg->getValue());
262 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000263 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000264 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000265 break;
266 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000267 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000268 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000269 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000270 case OPT_entry:
271 Config->Entry = addUndefined(mangle(Arg->getValue()));
272 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000273 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000274 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000275 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000276 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000277 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000278 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000279 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000280 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000281 break;
282 case OPT_nodefaultlib:
283 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
284 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000285 case OPT_section:
286 parseSection(Arg->getValue());
287 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000288 case OPT_subsystem:
289 parseSubsystem(Arg->getValue(), &Config->Subsystem,
290 &Config->MajorOSVersion, &Config->MinorOSVersion);
291 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000292 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000293 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000294 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000295 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000296 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000297 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000298 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000299 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000300 }
301 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000302}
303
Rui Ueyama54b71da2015-05-31 19:17:12 +0000304// Find file from search paths. You can omit ".obj", this function takes
305// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000306StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000307 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
308 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000309 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000310 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000311 for (StringRef Dir : SearchPaths) {
312 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000313 sys::path::append(Path, Filename);
314 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000315 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000316 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000317 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000318 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000319 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000320 }
321 }
322 return Filename;
323}
324
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000325// Resolves a file path. This never returns the same path
326// (in that case, it returns None).
327Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
328 StringRef Path = doFindFile(Filename);
329 bool Seen = !VisitedFiles.insert(Path.lower()).second;
330 if (Seen)
331 return None;
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000332 if (Path.endswith_lower(".lib"))
333 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000334 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000335}
336
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000337// Find library file from search path.
338StringRef LinkerDriver::doFindLib(StringRef Filename) {
339 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000340 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000341 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000342 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000343 return doFindFile(Filename);
344}
345
346// Resolves a library path. /nodefaultlib options are taken into
347// consideration. This never returns the same path (in that case,
348// it returns None).
349Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
350 if (Config->NoDefaultLibAll)
351 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000352 if (!VisitedLibs.insert(Filename.lower()).second)
353 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000354 StringRef Path = doFindLib(Filename);
355 if (Config->NoDefaultLibs.count(Path))
356 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000357 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000358 return None;
359 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000360}
361
362// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000363void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000364 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
365 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000366 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000367 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000368 while (!Env.empty()) {
369 StringRef Path;
370 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000371 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000372 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000373}
374
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000375Symbol *LinkerDriver::addUndefined(StringRef Name) {
376 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000377 if (!B->IsGCRoot) {
378 B->IsGCRoot = true;
379 Config->GCRoot.push_back(B);
380 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000381 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000382}
383
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000384// Symbol names are mangled by appending "_" prefix on x86.
385StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000386 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
387 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000388 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000389 return Sym;
390}
391
Rui Ueyama45044f42015-06-29 01:03:53 +0000392// Windows specific -- find default entry point name.
393StringRef LinkerDriver::findDefaultEntry() {
394 // User-defined main functions and their corresponding entry points.
395 static const char *Entries[][2] = {
396 {"main", "mainCRTStartup"},
397 {"wmain", "wmainCRTStartup"},
398 {"WinMain", "WinMainCRTStartup"},
399 {"wWinMain", "wWinMainCRTStartup"},
400 };
401 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000402 StringRef Entry = Symtab->findMangle(mangle(E[0]));
Rui Ueyama616cd992017-10-31 16:10:24 +0000403 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000404 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000405 }
406 return "";
407}
408
409WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000410 if (Config->DLL)
411 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000412 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000413 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000414 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000415 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
416 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000417}
418
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000419static uint64_t getDefaultImageBase() {
420 if (Config->is64())
421 return Config->DLL ? 0x180000000 : 0x140000000;
422 return Config->DLL ? 0x10000000 : 0x400000;
423}
424
Rui Ueyama8fe17672016-12-08 20:50:47 +0000425static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000426 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000427 ArrayRef<StringRef> SearchPaths) {
428 SmallString<0> Data;
429 raw_svector_ostream OS(Data);
430
431 for (auto *Arg : Args) {
432 switch (Arg->getOption().getID()) {
433 case OPT_linkrepro:
434 case OPT_INPUT:
435 case OPT_defaultlib:
436 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000437 case OPT_manifest:
438 case OPT_manifest_colon:
439 case OPT_manifestdependency:
440 case OPT_manifestfile:
441 case OPT_manifestinput:
442 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000443 break;
444 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000445 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000446 }
447 }
448
449 for (StringRef Path : SearchPaths) {
450 std::string RelPath = relativeToRoot(Path);
451 OS << "/libpath:" << quote(RelPath) << "\n";
452 }
453
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000454 for (StringRef Path : FilePaths)
455 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000456
457 return Data.str();
458}
459
Rui Ueyama8fe17672016-12-08 20:50:47 +0000460static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000461 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
462 if (Args.hasArg(OPT_driver))
463 DebugTypes |= static_cast<unsigned>(DebugType::PData);
464 if (Args.hasArg(OPT_profile))
465 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
466 return DebugTypes;
467}
468
469static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000470 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000471 Arg.split(Types, ',', /*KeepEmpty=*/false);
472
473 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
474 for (StringRef Type : Types)
475 DebugTypes |= StringSwitch<unsigned>(Type.lower())
476 .Case("cv", static_cast<unsigned>(DebugType::CV))
477 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000478 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
479 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000480 return DebugTypes;
481}
482
Hans Wennborg1818e652016-12-09 20:54:44 +0000483static std::string getMapFile(const opt::InputArgList &Args) {
484 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
485 if (!Arg)
486 return "";
487 if (Arg->getOption().getID() == OPT_lldmap_file)
488 return Arg->getValue();
489
490 assert(Arg->getOption().getID() == OPT_lldmap);
491 StringRef OutFile = Config->OutputFile;
492 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
493}
494
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000495static std::string getImplibPath() {
496 if (!Config->Implib.empty())
497 return Config->Implib;
498 SmallString<128> Out = StringRef(Config->OutputFile);
499 sys::path::replace_extension(Out, ".lib");
500 return Out.str();
501}
502
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000503//
504// The import name is caculated as the following:
505//
506// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
507// -----+----------------+---------------------+------------------
508// LINK | {value} | {value}.{.dll/.exe} | {output name}
509// LIB | {value} | {value}.dll | {output name}.dll
510//
511static std::string getImportName(bool AsLib) {
512 SmallString<128> Out;
513
514 if (Config->ImportName.empty()) {
515 Out.assign(sys::path::filename(Config->OutputFile));
516 if (AsLib)
517 sys::path::replace_extension(Out, ".dll");
518 } else {
519 Out.assign(Config->ImportName);
520 if (!sys::path::has_extension(Out))
521 sys::path::replace_extension(Out,
522 (Config->DLL || AsLib) ? ".dll" : ".exe");
523 }
524
525 return Out.str();
526}
527
528static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000529 std::vector<COFFShortExport> Exports;
530 for (Export &E1 : Config->Exports) {
531 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000532 E2.Name = E1.Name;
533 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000534 E2.ExtName = E1.ExtName;
535 E2.Ordinal = E1.Ordinal;
536 E2.Noname = E1.Noname;
537 E2.Data = E1.Data;
538 E2.Private = E1.Private;
539 E2.Constant = E1.Constant;
540 Exports.push_back(E2);
541 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000542
Bob Haarman4ce341f2018-01-23 00:36:42 +0000543 auto HandleError = [](Error &&E) {
544 handleAllErrors(std::move(E),
545 [](ErrorInfoBase &EIB) { error(EIB.message()); });
546 };
547 std::string LibName = getImportName(AsLib);
548 std::string Path = getImplibPath();
549
550 // If the import library already exists, replace it only if the contents
551 // have changed.
552 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(Path);
553 if (!OldBuf) {
554 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
555 false, Config->MinGW));
556 return;
557 }
558
559 SmallString<128> TmpName;
560 if (std::error_code EC =
561 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
562 fatal("cannot create temporary file for import library " + Path + ": " +
563 EC.message());
564
565 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
566 false, Config->MinGW)) {
567 HandleError(std::move(E));
568 return;
569 }
570
571 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(TmpName));
572 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
573 OldBuf->reset();
574 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000575 } else {
576 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000577 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000578}
579
580static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000581 std::unique_ptr<MemoryBuffer> MB = CHECK(
582 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000583 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
584 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000585
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000586 if (Config->OutputFile.empty())
587 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000588 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000589 if (M.ImageBase)
590 Config->ImageBase = M.ImageBase;
591 if (M.StackReserve)
592 Config->StackReserve = M.StackReserve;
593 if (M.StackCommit)
594 Config->StackCommit = M.StackCommit;
595 if (M.HeapReserve)
596 Config->HeapReserve = M.HeapReserve;
597 if (M.HeapCommit)
598 Config->HeapCommit = M.HeapCommit;
599 if (M.MajorImageVersion)
600 Config->MajorImageVersion = M.MajorImageVersion;
601 if (M.MinorImageVersion)
602 Config->MinorImageVersion = M.MinorImageVersion;
603 if (M.MajorOSVersion)
604 Config->MajorOSVersion = M.MajorOSVersion;
605 if (M.MinorOSVersion)
606 Config->MinorOSVersion = M.MinorOSVersion;
607
608 for (COFFShortExport E1 : M.Exports) {
609 Export E2;
610 E2.Name = Saver.save(E1.Name);
611 if (E1.isWeak())
612 E2.ExtName = Saver.save(E1.ExtName);
613 E2.Ordinal = E1.Ordinal;
614 E2.Noname = E1.Noname;
615 E2.Data = E1.Data;
616 E2.Private = E1.Private;
617 E2.Constant = E1.Constant;
618 Config->Exports.push_back(E2);
619 }
620}
621
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000622// A helper function for filterBitcodeFiles.
623static bool needsRebuilding(MemoryBufferRef MB) {
624 // The MSVC linker doesn't support thin archives, so if it's a thin
625 // archive, we always need to rebuild it.
626 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000627 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000628 if (File->isThin())
629 return true;
630
631 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000632 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000633 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
634 return true;
635 return false;
636}
637
638// Opens a given path as an archive file and removes bitcode files
639// from them if exists. This function is to appease the MSVC linker as
640// their linker doesn't like archive files containing non-native
641// object files.
642//
643// If a given archive doesn't contain bitcode files, the archive path
644// is returned as-is. Otherwise, a new temporary file is created and
645// its path is returned.
646static Optional<std::string>
647filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000648 std::unique_ptr<MemoryBuffer> MB = CHECK(
Rui Ueyama85d54b02017-02-23 00:26:42 +0000649 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000650 MemoryBufferRef MBRef = MB->getMemBufferRef();
651 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000652
653 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000654 return None;
655 if (Magic != file_magic::archive)
656 return Path.str();
657 if (!needsRebuilding(MBRef))
658 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000659
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000660 std::unique_ptr<Archive> File =
Rui Ueyamabdc51502017-12-06 22:08:17 +0000661 CHECK(Archive::create(MBRef),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000662 MBRef.getBufferIdentifier() + ": failed to parse archive");
663
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000664 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000665 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000666 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
667 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000668
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000669 if (New.empty())
670 return None;
671
672 log("Creating a temporary archive for " + Path + " to remove bitcode files");
673
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000674 SmallString<128> S;
Bob Haarman4ce341f2018-01-23 00:36:42 +0000675 if (std::error_code EC = sys::fs::createTemporaryFile(
676 "lld-" + sys::path::stem(Path), ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000677 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000678 std::string Temp = S.str();
679 TemporaryFiles.push_back(Temp);
680
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000681 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000682 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
683 /*Deterministics=*/true,
684 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000685 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
686 error("failed to create a new archive " + S.str() + ": " + EI.message());
687 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000688 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000689}
690
691// Create response file contents and invoke the MSVC linker.
692void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000693 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000694 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000695
Bob Haarman41108162017-04-21 21:38:01 +0000696 // Write out archive members that we used in symbol resolution and pass these
697 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
698 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000699 for (ObjFile *Obj : ObjFile::Instances) {
700 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000701 continue;
702 SmallString<128> S;
703 int Fd;
704 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000705 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000706 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000707 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000708 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000709 Temps.push_back(S.str());
710 Rsp += quote(S) + "\n";
711 }
712
Rui Ueyama85d54b02017-02-23 00:26:42 +0000713 for (auto *Arg : Args) {
714 switch (Arg->getOption().getID()) {
715 case OPT_linkrepro:
716 case OPT_lldmap:
717 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000718 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000719 case OPT_msvclto:
720 // LLD-specific options are stripped.
721 break;
722 case OPT_opt:
723 if (!StringRef(Arg->getValue()).startswith("lld"))
Sam Clegg7e756632017-12-05 16:50:46 +0000724 Rsp += toString(*Arg) + " ";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000725 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000726 case OPT_INPUT: {
727 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
728 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000729 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000730 continue;
731 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000732 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000733 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000734 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000735 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000736 Rsp += toString(*Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000737 }
738 }
739
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000740 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000741 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000742
743 for (StringRef Path : Temps)
744 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000745}
746
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000747void LinkerDriver::enqueueTask(std::function<void()> Task) {
748 TaskQueue.push_back(std::move(Task));
749}
750
751bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000752 ScopedTimer T(InputFileTimer);
753
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000754 bool DidWork = !TaskQueue.empty();
755 while (!TaskQueue.empty()) {
756 TaskQueue.front()();
757 TaskQueue.pop_front();
758 }
759 return DidWork;
760}
761
Rui Ueyama57175aa2018-01-27 00:34:46 +0000762// Parse an /order file. If an option is given, the linker places
763// COMDAT sections in the same order as their names appear in the
764// given file.
765static void parseOrderFile(StringRef Arg) {
766 // For some reason, the MSVC linker requires a filename to be
767 // preceded by "@".
768 if (!Arg.startswith("@")) {
769 error("malformed /order option: '@' missing");
770 return;
771 }
772
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000773 // Get a list of all comdat sections for error checking.
774 DenseSet<StringRef> Set;
775 for (Chunk *C : Symtab->getChunks())
776 if (auto *Sec = dyn_cast<SectionChunk>(C))
777 if (Sec->Sym)
778 Set.insert(Sec->Sym->getName());
779
Rui Ueyama57175aa2018-01-27 00:34:46 +0000780 // Open a file.
781 StringRef Path = Arg.substr(1);
782 std::unique_ptr<MemoryBuffer> MB = CHECK(
783 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
784
785 // Parse a file. An order file contains one symbol per line.
786 // All symbols that were not present in a given order file are
787 // considered to have the lowest priority 0 and are placed at
788 // end of an output section.
789 for (std::string S : args::getLines(MB->getMemBufferRef())) {
790 if (Config->Machine == I386 && !isDecorated(S))
791 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000792
793 if (Set.count(S) == 0)
794 warn("/order:" + Arg + ": missing symbol: " + S);
795 else
796 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000797 }
798}
799
Rui Ueyama8fe17672016-12-08 20:50:47 +0000800void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000801 // If the first command line argument is "/lib", link.exe acts like lib.exe.
802 // We call our own implementation of lib.exe that understands bitcode files.
803 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
804 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000805 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000806 return;
807 }
808
Peter Collingbourne60c16162015-06-01 20:10:10 +0000809 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000810 InitializeAllTargetInfos();
811 InitializeAllTargets();
812 InitializeAllTargetMCs();
813 InitializeAllAsmParsers();
814 InitializeAllAsmPrinters();
815 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000816
Rui Ueyama411c63602015-05-28 19:09:30 +0000817 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000818 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000819 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000820
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000821 // Parse and evaluate -mllvm options.
822 std::vector<const char *> V;
823 V.push_back("lld-link (LLVM option parsing)");
824 for (auto *Arg : Args.filtered(OPT_mllvm))
825 V.push_back(Arg->getValue());
826 cl::ParseCommandLineOptions(V.size(), V.data());
827
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000828 // Handle /errorlimit early, because error() depends on it.
829 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
830 int N = 20;
831 StringRef S = Arg->getValue();
832 if (S.getAsInteger(10, N))
833 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000834 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000835 }
836
Rui Ueyama5c726432015-05-29 16:11:52 +0000837 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000838 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000839 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000840 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000841 }
842
Zachary Turner727f1532018-01-17 19:16:26 +0000843 if (Args.hasArg(OPT_show_timing))
844 Config->ShowTiming = true;
845
846 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000847 // Handle --version, which is an lld extension. This option is a bit odd
848 // because it doesn't start with "/", but we deliberately chose "--" to
849 // avoid conflict with /version and for compatibility with clang-cl.
850 if (Args.hasArg(OPT_dash_dash_version)) {
851 outs() << getLLDVersion() << "\n";
852 return;
853 }
854
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000855 // Handle /lldmingw early, since it can potentially affect how other
856 // options are handled.
857 Config->MinGW = Args.hasArg(OPT_lldmingw);
858
Peter Collingbournefeee2102016-07-26 02:00:42 +0000859 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
860 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000861 sys::path::append(Path, "repro.tar");
862
863 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
864 TarWriter::create(Path, "repro");
865
866 if (ErrOrWriter) {
867 Tar = std::move(*ErrOrWriter);
868 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000869 error("/linkrepro: failed to open " + Path + ": " +
870 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000871 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000872 }
873
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000874 if (!Args.hasArg(OPT_INPUT)) {
875 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000876 Config->NoEntry = true;
877 else
878 fatal("no input files");
879 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000880
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000881 // Construct search path list.
882 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000883 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000884 SearchPaths.push_back(Arg->getValue());
885 addLibSearchPaths();
886
Bob Haarmane90ac012017-12-28 07:02:13 +0000887 // Handle /ignore
888 for (auto *Arg : Args.filtered(OPT_ignore)) {
889 if (StringRef(Arg->getValue()) == "4217")
890 Config->WarnLocallyDefinedImported = false;
891 // Other warning numbers are ignored.
892 }
893
Rui Ueyamaad660982015-06-07 00:20:32 +0000894 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000895 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000896 Config->OutputFile = Arg->getValue();
897
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000898 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000899 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000900 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000901 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000902
Rui Ueyama95925fd2015-06-28 19:35:15 +0000903 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000904 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000905 Config->Force = true;
906
Rui Ueyama6600eb12015-07-04 23:37:32 +0000907 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000908 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000909 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000910 if (auto *Arg = Args.getLastArg(OPT_debugtype))
911 Config->DebugTypes = parseDebugType(Arg->getValue());
912 else
913 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000914 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000915
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000916 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000917 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
918 if (ShouldCreatePDB)
919 if (auto *Arg = Args.getLastArg(OPT_pdb))
920 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000921
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000922 // Handle /noentry
923 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000924 if (Args.hasArg(OPT_dll))
925 Config->NoEntry = true;
926 else
927 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000928 }
929
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000930 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000931 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000932 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000933 Config->ManifestID = 2;
934 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000935
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000936 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
937 // because we need to explicitly check whether that option or its inverse was
938 // present in the argument list in order to handle /fixed.
939 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
940 if (DynamicBaseArg &&
941 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
942 Config->DynamicBase = false;
943
944 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
945 if (Fixed) {
946 if (DynamicBaseArg &&
947 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000948 error("/fixed must not be specified with /dynamicbase");
949 } else {
950 Config->Relocatable = false;
951 Config->DynamicBase = false;
952 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000953 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000954
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000955 // Handle /appcontainer
956 Config->AppContainer =
957 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000958
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000959 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000960 if (auto *Arg = Args.getLastArg(OPT_machine))
961 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000962
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000963 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000964 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000965 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
966
967 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000968 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000969 Config->NoDefaultLibAll = true;
970
Rui Ueyama804a8b62015-05-29 16:18:15 +0000971 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000972 if (auto *Arg = Args.getLastArg(OPT_base))
973 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000974
975 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000976 if (auto *Arg = Args.getLastArg(OPT_stack))
977 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000978
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000979 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000980 if (auto *Arg = Args.getLastArg(OPT_heap))
981 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000982
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000983 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000984 if (auto *Arg = Args.getLastArg(OPT_version))
985 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
986 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000987
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000988 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000989 if (auto *Arg = Args.getLastArg(OPT_subsystem))
990 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
991 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000992
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000993 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000994 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000995 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000996
Rui Ueyama08d5e182015-06-18 23:20:11 +0000997 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000998 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000999 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001000
Rui Ueyamab95188c2015-06-18 20:27:09 +00001001 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001002 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001003 Config->Implib = Arg->getValue();
1004
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001005 // Handle /opt.
1006 bool DoGC = !Args.hasArg(OPT_debug);
1007 unsigned ICFLevel = 1; // 0: off, 1: limited, 2: on
David Blaikie6521ed92015-06-22 22:06:52 +00001008 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001009 std::string Str = StringRef(Arg->getValue()).lower();
1010 SmallVector<StringRef, 1> Vec;
1011 StringRef(Str).split(Vec, ',');
1012 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001013 if (S == "ref") {
1014 DoGC = true;
1015 } else if (S == "noref") {
1016 DoGC = false;
1017 } else if (S == "icf" || S.startswith("icf=")) {
1018 ICFLevel = 2;
1019 } else if (S == "noicf") {
1020 ICFLevel = 0;
1021 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001022 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001023 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
1024 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001025 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001026 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001027 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +00001028 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001029 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001030 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001031 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001032 if (N.getAsInteger(10, Config->LTOPartitions) ||
1033 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001034 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001035 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001036 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001037 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001038 }
1039
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001040 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1041 // explicitly.
1042 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1043 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1044 // comdat readonly data.
1045 if (ICFLevel == 1 && !DoGC)
1046 ICFLevel = 0;
1047 Config->DoGC = DoGC;
1048 Config->DoICF = ICFLevel > 0;
1049
Bob Haarman69b196d2017-02-08 18:36:41 +00001050 // Handle /lldsavetemps
1051 if (Args.hasArg(OPT_lldsavetemps))
1052 Config->SaveTemps = true;
1053
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001054 // Handle /lldltocache
1055 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1056 Config->LTOCache = Arg->getValue();
1057
1058 // Handle /lldsavecachepolicy
1059 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001060 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001061 parseCachePruningPolicy(Arg->getValue()),
1062 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1063
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001064 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001065 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001066 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001067
Rui Ueyama6600eb12015-07-04 23:37:32 +00001068 // Handle /merge
1069 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001070 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001071
Rui Ueyama440138c2016-06-20 03:39:39 +00001072 // Handle /section
1073 for (auto *Arg : Args.filtered(OPT_section))
1074 parseSection(Arg->getValue());
1075
Martin Storsjod2752aa2017-08-14 19:07:27 +00001076 // Handle /aligncomm
1077 for (auto *Arg : Args.filtered(OPT_aligncomm))
1078 parseAligncomm(Arg->getValue());
1079
Nico Webera7a2c442017-07-25 18:08:03 +00001080 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1081 // also passed.
1082 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1083 Config->ManifestDependency = Arg->getValue();
1084 Config->Manifest = Configuration::SideBySide;
1085 }
1086
1087 // Handle /manifest and /manifest:
1088 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1089 if (Arg->getOption().getID() == OPT_manifest)
1090 Config->Manifest = Configuration::SideBySide;
1091 else
1092 parseManifest(Arg->getValue());
1093 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001094
1095 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001096 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1097 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001098
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001099 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001100 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001101 Config->ManifestFile = Arg->getValue();
1102
Rui Ueyamaafb19012016-04-19 01:21:58 +00001103 // Handle /manifestinput
1104 for (auto *Arg : Args.filtered(OPT_manifestinput))
1105 Config->ManifestInput.push_back(Arg->getValue());
1106
Nico Webera7a2c442017-07-25 18:08:03 +00001107 if (!Config->ManifestInput.empty() &&
1108 Config->Manifest != Configuration::Embed) {
1109 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1110 }
1111
Rui Ueyama6592ff82015-06-16 23:13:00 +00001112 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001113 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1114 Config->AllowIsolation =
1115 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1116 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1117 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001118 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001119 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001120
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001121 Config->MapFile = getMapFile(Args);
1122
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001123 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001124 return;
1125
Martin Storsjo8278ba52017-09-13 07:28:03 +00001126 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001127 // Create a list of input files. Files can be given as arguments
1128 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001129 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001130 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1131 switch (Arg->getOption().getID()) {
1132 case OPT_INPUT:
1133 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1134 enqueuePath(*Path, WholeArchiveFlag);
1135 break;
1136 case OPT_wholearchive_file:
1137 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1138 enqueuePath(*Path, true);
1139 break;
1140 }
1141 }
David Blaikie6521ed92015-06-22 22:06:52 +00001142 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001143 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001144 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001145
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001146 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001147 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001148 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001149
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001150 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001151 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001152
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001153 // We should have inferred a machine type by now from the input files, but if
1154 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001155 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001156 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001157 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001158 }
1159
Eric Beckmann9e19d792017-06-17 02:26:27 +00001160 // Input files can be Windows resource files (.res files). We use
1161 // WindowsResource to convert resource files to a regular COFF file,
1162 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001163 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001164 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001165
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001166 if (Tar)
1167 Tar->append("response.txt",
1168 createResponseFile(Args, FilePaths,
1169 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001170
Rui Ueyama4d545342015-07-28 03:12:00 +00001171 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001172 Config->LargeAddressAware = Args.hasFlag(
1173 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001174
Rui Ueyamad68e2112015-07-28 03:15:57 +00001175 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001176 Config->HighEntropyVA =
1177 Config->is64() &&
1178 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001179
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001180 if (!Config->DynamicBase &&
1181 (Config->Machine == ARMNT || Config->Machine == ARM64))
1182 error("/dynamicbase:no is not compatible with " +
1183 machineToStr(Config->Machine));
1184
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001185 // Handle /entry and /dll
1186 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1187 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama215286f2017-11-29 20:46:13 +00001188 } else if (!Config->Entry && !Config->NoEntry) {
1189 if (Args.hasArg(OPT_dll)) {
1190 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1191 : "_DllMainCRTStartup";
1192 Config->Entry = addUndefined(S);
1193 } else {
1194 // Windows specific -- If entry point name is not given, we need to
1195 // infer that from user-defined entry name.
1196 StringRef S = findDefaultEntry();
1197 if (S.empty())
1198 fatal("entry point must be defined");
1199 Config->Entry = addUndefined(S);
1200 log("Entry name inferred: " + S);
1201 }
Rui Ueyama45044f42015-06-29 01:03:53 +00001202 }
1203
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001204 // Handle /export
1205 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001206 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001207 if (Config->Machine == I386) {
1208 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001209 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001210 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001211 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001212 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001213 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001214 }
1215
1216 // Handle /def
1217 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001218 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001219 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001220 }
1221
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001222 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001223 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001224 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001225 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001226 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001227 }
1228
Rui Ueyama6d249082015-07-13 22:31:45 +00001229 // Handle /delayload
1230 for (auto *Arg : Args.filtered(OPT_delayload)) {
1231 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001232 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001233 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001234 } else {
1235 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001236 }
1237 }
1238
Reid Kleckner7668182e2017-03-21 00:12:51 +00001239 // Set default image name if neither /out or /def set it.
1240 if (Config->OutputFile.empty()) {
1241 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001242 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001243 }
1244
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001245 // Put the PDB next to the image if no /pdb flag was passed.
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +00001246 if (ShouldCreatePDB && Config->PDBPath.empty()) {
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001247 Config->PDBPath = Config->OutputFile;
1248 sys::path::replace_extension(Config->PDBPath, ".pdb");
1249 }
1250
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001251 // Set default image base if /base is not given.
1252 if (Config->ImageBase == uint64_t(-1))
1253 Config->ImageBase = getDefaultImageBase();
1254
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001255 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001256 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001257 Symtab->addAbsolute("___safe_se_handler_table", 0);
1258 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001259 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001260
Rui Ueyama107db552015-08-09 21:01:06 +00001261 // We do not support /guard:cf (control flow protection) yet.
1262 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001263 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1264 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1265 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1266 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1267 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1268 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1269 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001270 // Needed for MSVC 2017 15.5 CRT.
1271 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001272
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001273 // This code may add new undefined symbols to the link, which may enqueue more
1274 // symbol resolution tasks, so we need to continue executing tasks until we
1275 // converge.
1276 do {
1277 // Windows specific -- if entry point is not found,
1278 // search for its mangled names.
1279 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001280 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001281
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001282 // Windows specific -- Make sure we resolve all dllexported symbols.
1283 for (Export &E : Config->Exports) {
1284 if (!E.ForwardTo.empty())
1285 continue;
1286 E.Sym = addUndefined(E.Name);
1287 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001288 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001289 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001290
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001291 // Add weak aliases. Weak aliases is a mechanism to give remaining
1292 // undefined symbols final chance to be resolved successfully.
1293 for (auto Pair : Config->AlternateNames) {
1294 StringRef From = Pair.first;
1295 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001296 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001297 if (!Sym)
1298 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001299 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001300 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001301 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001302 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001303
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001304 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001305 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001306 addUndefined(mangle("_load_config_used"));
1307 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001308
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001309 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001310 return;
1311
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001312 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1313 // This is useful because MSVC link.exe can generate complete PDBs.
1314 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001315 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001316 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001317 }
1318
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001319 // Do LTO by compiling bitcode input files to a set of native COFF files then
1320 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001321 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001322 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001323
Peter Collingbourne2612a322015-07-04 05:28:41 +00001324 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001325 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001326 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001327 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001328
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001329 // Windows specific -- if no /subsystem is given, we need to infer
1330 // that from entry point name.
1331 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001332 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001333 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001334 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001335 }
1336
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001337 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001338 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001339 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001340 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001341 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001342 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001343 return;
1344 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001345
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001346 // In MinGW, all symbols are automatically exported if no symbols
1347 // are chosen to be exported.
1348 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1349 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001350 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001351
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001352 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001353 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001354 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001355 return;
1356 Export E;
1357 E.Name = Def->getName();
1358 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001359 if (Def->getChunk() &&
1360 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE))
1361 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001362 Config->Exports.push_back(E);
1363 });
1364 }
1365
Rui Ueyama151d8622015-06-17 20:40:43 +00001366 // Windows specific -- when we are creating a .dll file, we also
1367 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001368 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001369 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001370 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001371 assignExportOrdinals();
1372 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001373
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001374 // Handle /output-def (MinGW specific).
1375 if (auto *Arg = Args.getLastArg(OPT_output_def))
1376 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001377
Martin Storsjod2752aa2017-08-14 19:07:27 +00001378 // Set extra alignment for .comm symbols
1379 for (auto Pair : Config->AlignComm) {
1380 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001381 uint32_t Alignment = Pair.second;
1382
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001383 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001384 if (!Sym) {
1385 warn("/aligncomm symbol " + Name + " not found");
1386 continue;
1387 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001388
Rui Ueyama616cd992017-10-31 16:10:24 +00001389 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001390 if (!DC) {
1391 warn("/aligncomm symbol " + Name + " of wrong kind");
1392 continue;
1393 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001394
1395 CommonChunk *C = DC->getChunk();
1396 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001397 }
1398
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001399 // Windows specific -- Create a side-by-side manifest file.
1400 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001401 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001402
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001403 // Handle /order. We want to do this at this moment because we
1404 // need a complete list of comdat sections to warn on nonexistent
1405 // functions.
1406 if (auto *Arg = Args.getLastArg(OPT_order))
1407 parseOrderFile(Arg->getValue());
1408
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001409 // Identify unreferenced COMDAT sections.
1410 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001411 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001412
1413 // Identify identical COMDAT sections to merge them.
1414 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001415 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001416
Rui Ueyama411c63602015-05-28 19:09:30 +00001417 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001418 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001419
1420 // Stop early so we can print the results.
1421 Timer::root().stop();
1422 if (Config->ShowTiming)
1423 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001424}
1425
Rui Ueyama411c63602015-05-28 19:09:30 +00001426} // namespace coff
1427} // namespace lld