blob: c3cb1d95d8db46ce6ec6b729fb745f3ef6ac82d5 [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"
Rui Ueyama9381eb12016-12-18 14:06:06 +000013#include "Memory.h"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000014#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000015#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000016#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000017#include "Writer.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 Ueyamaa4cf97b2017-10-23 14:57:53 +000020#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000021#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000022#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000023#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000024#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000025#include "llvm/Object/COFFImportFile.h"
26#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000027#include "llvm/Option/Arg.h"
28#include "llvm/Option/ArgList.h"
29#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000032#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000033#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000034#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000036#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000037#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000038#include <memory>
39
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000040#include <future>
41
Rui Ueyama411c63602015-05-28 19:09:30 +000042using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000043using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000044using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000045using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000046
Rui Ueyama3500f662015-05-28 20:30:06 +000047namespace lld {
48namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000051LinkerDriver *Driver;
52
Rui Ueyama9381eb12016-12-18 14:06:06 +000053BumpPtrAllocator BAlloc;
54StringSaver Saver{BAlloc};
55std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
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)";
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 Ueyama6f4e2552017-10-23 20:03:32 +000066 Config->CanExitEarly = CanExitEarly;
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 =
138 check(Archive::create(MBRef),
139 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()) {
203 MemoryBufferRef MB = check(
204 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(
211 check(C.getFullName(),
212 "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 Ueyama8fe17672016-12-08 20:50:47 +0000234 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000235
David Blaikie6521ed92015-06-22 22:06:52 +0000236 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000237 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000238 case OPT_aligncomm:
239 parseAligncomm(Arg->getValue());
240 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000241 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000242 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000243 break;
244 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000245 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000246 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000247 break;
248 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000249 Export E = parseExport(Arg->getValue());
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000250 if (Config->Machine == I386 && Config->MinGW) {
251 if (!isDecorated(E.Name))
252 E.Name = Saver.save("_" + E.Name);
253 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
254 E.ExtName = Saver.save("_" + E.ExtName);
255 }
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000256 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000257 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000258 break;
259 }
260 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000261 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000262 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000263 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000264 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000265 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000266 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000267 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000268 break;
269 case OPT_nodefaultlib:
270 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
271 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000272 case OPT_section:
273 parseSection(Arg->getValue());
274 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000275 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000276 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000277 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000278 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000279 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000280 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000281 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000282 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000283 }
284 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000285}
286
Rui Ueyama54b71da2015-05-31 19:17:12 +0000287// Find file from search paths. You can omit ".obj", this function takes
288// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000289StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000290 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
291 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000292 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000293 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000294 for (StringRef Dir : SearchPaths) {
295 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000296 sys::path::append(Path, Filename);
297 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000298 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000299 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000300 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000301 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000302 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000303 }
304 }
305 return Filename;
306}
307
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000308// Resolves a file path. This never returns the same path
309// (in that case, it returns None).
310Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
311 StringRef Path = doFindFile(Filename);
312 bool Seen = !VisitedFiles.insert(Path.lower()).second;
313 if (Seen)
314 return None;
315 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000316}
317
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000318// Find library file from search path.
319StringRef LinkerDriver::doFindLib(StringRef Filename) {
320 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000321 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000322 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000323 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000324 return doFindFile(Filename);
325}
326
327// Resolves a library path. /nodefaultlib options are taken into
328// consideration. This never returns the same path (in that case,
329// it returns None).
330Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
331 if (Config->NoDefaultLibAll)
332 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000333 if (!VisitedLibs.insert(Filename.lower()).second)
334 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000335 StringRef Path = doFindLib(Filename);
336 if (Config->NoDefaultLibs.count(Path))
337 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000338 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000339 return None;
340 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000341}
342
343// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000344void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000345 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
346 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000347 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000348 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000349 while (!Env.empty()) {
350 StringRef Path;
351 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000352 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000353 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000354}
355
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000356SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000357 SymbolBody *B = Symtab->addUndefined(Name);
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000358 Config->GCRoot.insert(B);
359 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000360}
361
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000362// Symbol names are mangled by appending "_" prefix on x86.
363StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000364 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
365 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000366 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000367 return Sym;
368}
369
Rui Ueyama45044f42015-06-29 01:03:53 +0000370// Windows specific -- find default entry point name.
371StringRef LinkerDriver::findDefaultEntry() {
372 // User-defined main functions and their corresponding entry points.
373 static const char *Entries[][2] = {
374 {"main", "mainCRTStartup"},
375 {"wmain", "wmainCRTStartup"},
376 {"WinMain", "WinMainCRTStartup"},
377 {"wWinMain", "wWinMainCRTStartup"},
378 };
379 for (auto E : Entries) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000380 StringRef Entry = Symtab->findMangle(mangle(E[0]));
381 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000382 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000383 }
384 return "";
385}
386
387WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000388 if (Config->DLL)
389 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000390 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000391 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000392 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000393 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
394 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000395}
396
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000397static uint64_t getDefaultImageBase() {
398 if (Config->is64())
399 return Config->DLL ? 0x180000000 : 0x140000000;
400 return Config->DLL ? 0x10000000 : 0x400000;
401}
402
Rui Ueyama8fe17672016-12-08 20:50:47 +0000403static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000404 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000405 ArrayRef<StringRef> SearchPaths) {
406 SmallString<0> Data;
407 raw_svector_ostream OS(Data);
408
409 for (auto *Arg : Args) {
410 switch (Arg->getOption().getID()) {
411 case OPT_linkrepro:
412 case OPT_INPUT:
413 case OPT_defaultlib:
414 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000415 case OPT_manifest:
416 case OPT_manifest_colon:
417 case OPT_manifestdependency:
418 case OPT_manifestfile:
419 case OPT_manifestinput:
420 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000421 break;
422 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000423 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000424 }
425 }
426
427 for (StringRef Path : SearchPaths) {
428 std::string RelPath = relativeToRoot(Path);
429 OS << "/libpath:" << quote(RelPath) << "\n";
430 }
431
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000432 for (StringRef Path : FilePaths)
433 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000434
435 return Data.str();
436}
437
Rui Ueyama8fe17672016-12-08 20:50:47 +0000438static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000439 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
440 if (Args.hasArg(OPT_driver))
441 DebugTypes |= static_cast<unsigned>(DebugType::PData);
442 if (Args.hasArg(OPT_profile))
443 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
444 return DebugTypes;
445}
446
447static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000448 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000449 Arg.split(Types, ',', /*KeepEmpty=*/false);
450
451 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
452 for (StringRef Type : Types)
453 DebugTypes |= StringSwitch<unsigned>(Type.lower())
454 .Case("cv", static_cast<unsigned>(DebugType::CV))
455 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000456 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
457 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000458 return DebugTypes;
459}
460
Hans Wennborg1818e652016-12-09 20:54:44 +0000461static std::string getMapFile(const opt::InputArgList &Args) {
462 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
463 if (!Arg)
464 return "";
465 if (Arg->getOption().getID() == OPT_lldmap_file)
466 return Arg->getValue();
467
468 assert(Arg->getOption().getID() == OPT_lldmap);
469 StringRef OutFile = Config->OutputFile;
470 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
471}
472
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000473static std::string getImplibPath() {
474 if (!Config->Implib.empty())
475 return Config->Implib;
476 SmallString<128> Out = StringRef(Config->OutputFile);
477 sys::path::replace_extension(Out, ".lib");
478 return Out.str();
479}
480
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000481//
482// The import name is caculated as the following:
483//
484// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
485// -----+----------------+---------------------+------------------
486// LINK | {value} | {value}.{.dll/.exe} | {output name}
487// LIB | {value} | {value}.dll | {output name}.dll
488//
489static std::string getImportName(bool AsLib) {
490 SmallString<128> Out;
491
492 if (Config->ImportName.empty()) {
493 Out.assign(sys::path::filename(Config->OutputFile));
494 if (AsLib)
495 sys::path::replace_extension(Out, ".dll");
496 } else {
497 Out.assign(Config->ImportName);
498 if (!sys::path::has_extension(Out))
499 sys::path::replace_extension(Out,
500 (Config->DLL || AsLib) ? ".dll" : ".exe");
501 }
502
503 return Out.str();
504}
505
506static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000507 std::vector<COFFShortExport> Exports;
508 for (Export &E1 : Config->Exports) {
509 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000510 E2.Name = E1.Name;
511 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000512 E2.ExtName = E1.ExtName;
513 E2.Ordinal = E1.Ordinal;
514 E2.Noname = E1.Noname;
515 E2.Data = E1.Data;
516 E2.Private = E1.Private;
517 E2.Constant = E1.Constant;
518 Exports.push_back(E2);
519 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000520
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000521 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports,
522 Config->Machine, false);
523 handleAllErrors(std::move(E),
524 [&](ErrorInfoBase &EIB) { error(EIB.message()); });
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000525}
526
527static void parseModuleDefs(StringRef Path) {
528 std::unique_ptr<MemoryBuffer> MB = check(
529 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000530 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
531 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000532
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000533 if (Config->OutputFile.empty())
534 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000535 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000536 if (M.ImageBase)
537 Config->ImageBase = M.ImageBase;
538 if (M.StackReserve)
539 Config->StackReserve = M.StackReserve;
540 if (M.StackCommit)
541 Config->StackCommit = M.StackCommit;
542 if (M.HeapReserve)
543 Config->HeapReserve = M.HeapReserve;
544 if (M.HeapCommit)
545 Config->HeapCommit = M.HeapCommit;
546 if (M.MajorImageVersion)
547 Config->MajorImageVersion = M.MajorImageVersion;
548 if (M.MinorImageVersion)
549 Config->MinorImageVersion = M.MinorImageVersion;
550 if (M.MajorOSVersion)
551 Config->MajorOSVersion = M.MajorOSVersion;
552 if (M.MinorOSVersion)
553 Config->MinorOSVersion = M.MinorOSVersion;
554
555 for (COFFShortExport E1 : M.Exports) {
556 Export E2;
557 E2.Name = Saver.save(E1.Name);
558 if (E1.isWeak())
559 E2.ExtName = Saver.save(E1.ExtName);
560 E2.Ordinal = E1.Ordinal;
561 E2.Noname = E1.Noname;
562 E2.Data = E1.Data;
563 E2.Private = E1.Private;
564 E2.Constant = E1.Constant;
565 Config->Exports.push_back(E2);
566 }
567}
568
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000569// A helper function for filterBitcodeFiles.
570static bool needsRebuilding(MemoryBufferRef MB) {
571 // The MSVC linker doesn't support thin archives, so if it's a thin
572 // archive, we always need to rebuild it.
573 std::unique_ptr<Archive> File =
574 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
575 if (File->isThin())
576 return true;
577
578 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000579 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000580 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
581 return true;
582 return false;
583}
584
585// Opens a given path as an archive file and removes bitcode files
586// from them if exists. This function is to appease the MSVC linker as
587// their linker doesn't like archive files containing non-native
588// object files.
589//
590// If a given archive doesn't contain bitcode files, the archive path
591// is returned as-is. Otherwise, a new temporary file is created and
592// its path is returned.
593static Optional<std::string>
594filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000595 std::unique_ptr<MemoryBuffer> MB = check(
596 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000597 MemoryBufferRef MBRef = MB->getMemBufferRef();
598 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000599
600 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000601 return None;
602 if (Magic != file_magic::archive)
603 return Path.str();
604 if (!needsRebuilding(MBRef))
605 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000606
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000607 std::unique_ptr<Archive> File =
608 check(Archive::create(MBRef),
609 MBRef.getBufferIdentifier() + ": failed to parse archive");
610
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000611 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000612 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000613 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
614 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000615
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000616 if (New.empty())
617 return None;
618
619 log("Creating a temporary archive for " + Path + " to remove bitcode files");
620
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000621 SmallString<128> S;
622 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
623 ".lib", S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000624 fatal("cannot create a temporary file: " + EC.message());
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000625 std::string Temp = S.str();
626 TemporaryFiles.push_back(Temp);
627
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000628 Error E =
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000629 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
630 /*Deterministics=*/true,
631 /*Thin=*/false);
Rafael Espindola474f2bd2017-09-21 23:13:40 +0000632 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
633 error("failed to create a new archive " + S.str() + ": " + EI.message());
634 });
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000635 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000636}
637
638// Create response file contents and invoke the MSVC linker.
639void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
Bob Haarman630d0c02017-04-18 22:00:29 +0000640 std::string Rsp = "/nologo\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000641 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000642
Bob Haarman41108162017-04-21 21:38:01 +0000643 // Write out archive members that we used in symbol resolution and pass these
644 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
645 // references.
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000646 for (ObjFile *Obj : ObjFile::Instances) {
647 if (Obj->ParentName.empty())
Bob Haarman41108162017-04-21 21:38:01 +0000648 continue;
649 SmallString<128> S;
650 int Fd;
651 if (auto EC = sys::fs::createTemporaryFile(
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000652 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000653 fatal("cannot create a temporary file: " + EC.message());
Bob Haarman41108162017-04-21 21:38:01 +0000654 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
Rui Ueyamaacd632d2017-07-27 00:45:26 +0000655 OS << Obj->MB.getBuffer();
Bob Haarman41108162017-04-21 21:38:01 +0000656 Temps.push_back(S.str());
657 Rsp += quote(S) + "\n";
658 }
659
Rui Ueyama85d54b02017-02-23 00:26:42 +0000660 for (auto *Arg : Args) {
661 switch (Arg->getOption().getID()) {
662 case OPT_linkrepro:
663 case OPT_lldmap:
664 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000665 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000666 case OPT_msvclto:
667 // LLD-specific options are stripped.
668 break;
669 case OPT_opt:
670 if (!StringRef(Arg->getValue()).startswith("lld"))
671 Rsp += toString(Arg) + " ";
672 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000673 case OPT_INPUT: {
674 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
675 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
Bob Haarman630d0c02017-04-18 22:00:29 +0000676 Rsp += quote(*S) + "\n";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000677 continue;
678 }
Bob Haarman630d0c02017-04-18 22:00:29 +0000679 Rsp += quote(Arg->getValue()) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000680 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000681 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000682 default:
Bob Haarman630d0c02017-04-18 22:00:29 +0000683 Rsp += toString(Arg) + "\n";
Rui Ueyama85d54b02017-02-23 00:26:42 +0000684 }
685 }
686
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000687 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000688 runMSVCLinker(Rsp, ObjFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000689
690 for (StringRef Path : Temps)
691 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000692}
693
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000694void LinkerDriver::enqueueTask(std::function<void()> Task) {
695 TaskQueue.push_back(std::move(Task));
696}
697
698bool LinkerDriver::run() {
699 bool DidWork = !TaskQueue.empty();
700 while (!TaskQueue.empty()) {
701 TaskQueue.front()();
702 TaskQueue.pop_front();
703 }
704 return DidWork;
705}
706
Rui Ueyama8fe17672016-12-08 20:50:47 +0000707void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000708 // If the first command line argument is "/lib", link.exe acts like lib.exe.
709 // We call our own implementation of lib.exe that understands bitcode files.
710 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
711 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000712 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000713 return;
714 }
715
Peter Collingbourne60c16162015-06-01 20:10:10 +0000716 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000717 InitializeAllTargetInfos();
718 InitializeAllTargets();
719 InitializeAllTargetMCs();
720 InitializeAllAsmParsers();
721 InitializeAllAsmPrinters();
722 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000723
Rui Ueyama411c63602015-05-28 19:09:30 +0000724 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000725 ArgParser Parser;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000726 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000727
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000728 // Parse and evaluate -mllvm options.
729 std::vector<const char *> V;
730 V.push_back("lld-link (LLVM option parsing)");
731 for (auto *Arg : Args.filtered(OPT_mllvm))
732 V.push_back(Arg->getValue());
733 cl::ParseCommandLineOptions(V.size(), V.data());
734
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000735 // Handle /errorlimit early, because error() depends on it.
736 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
737 int N = 20;
738 StringRef S = Arg->getValue();
739 if (S.getAsInteger(10, N))
740 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000741 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000742 }
743
Rui Ueyama5c726432015-05-29 16:11:52 +0000744 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000745 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000746 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000747 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000748 }
749
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000750 // Handle --version, which is an lld extension. This option is a bit odd
751 // because it doesn't start with "/", but we deliberately chose "--" to
752 // avoid conflict with /version and for compatibility with clang-cl.
753 if (Args.hasArg(OPT_dash_dash_version)) {
754 outs() << getLLDVersion() << "\n";
755 return;
756 }
757
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000758 // Handle /lldmingw early, since it can potentially affect how other
759 // options are handled.
760 Config->MinGW = Args.hasArg(OPT_lldmingw);
761
Peter Collingbournefeee2102016-07-26 02:00:42 +0000762 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
763 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000764 sys::path::append(Path, "repro.tar");
765
766 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
767 TarWriter::create(Path, "repro");
768
769 if (ErrOrWriter) {
770 Tar = std::move(*ErrOrWriter);
771 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000772 error("/linkrepro: failed to open " + Path + ": " +
773 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000774 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000775 }
776
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000777 if (!Args.hasArg(OPT_INPUT)) {
778 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000779 Config->NoEntry = true;
780 else
781 fatal("no input files");
782 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000783
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000784 // Construct search path list.
785 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000786 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000787 SearchPaths.push_back(Arg->getValue());
788 addLibSearchPaths();
789
Rui Ueyamaad660982015-06-07 00:20:32 +0000790 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000791 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000792 Config->OutputFile = Arg->getValue();
793
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000794 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000795 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000796 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000797 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000798
Rui Ueyama95925fd2015-06-28 19:35:15 +0000799 // Handle /force or /force:unresolved
800 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
801 Config->Force = true;
802
Rui Ueyama6600eb12015-07-04 23:37:32 +0000803 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000804 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000805 Config->Debug = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000806 if (auto *Arg = Args.getLastArg(OPT_debugtype))
807 Config->DebugTypes = parseDebugType(Arg->getValue());
808 else
809 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000810 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000811
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000812 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000813 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000814 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000815
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000816 // Handle /noentry
817 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000818 if (Args.hasArg(OPT_dll))
819 Config->NoEntry = true;
820 else
821 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000822 }
823
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000824 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000825 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000826 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000827 Config->ManifestID = 2;
828 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000829
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000830 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
831 // because we need to explicitly check whether that option or its inverse was
832 // present in the argument list in order to handle /fixed.
833 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
834 if (DynamicBaseArg &&
835 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
836 Config->DynamicBase = false;
837
838 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
839 if (Fixed) {
840 if (DynamicBaseArg &&
841 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000842 error("/fixed must not be specified with /dynamicbase");
843 } else {
844 Config->Relocatable = false;
845 Config->DynamicBase = false;
846 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000847 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000848
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000849 // Handle /appcontainer
850 Config->AppContainer =
851 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000852
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000853 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000854 if (auto *Arg = Args.getLastArg(OPT_machine))
855 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000856
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000857 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000858 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000859 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
860
861 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000862 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000863 Config->NoDefaultLibAll = true;
864
Rui Ueyama804a8b62015-05-29 16:18:15 +0000865 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000866 if (auto *Arg = Args.getLastArg(OPT_base))
867 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000868
869 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000870 if (auto *Arg = Args.getLastArg(OPT_stack))
871 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000872
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000873 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000874 if (auto *Arg = Args.getLastArg(OPT_heap))
875 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000876
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000877 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000878 if (auto *Arg = Args.getLastArg(OPT_version))
879 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
880 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000881
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000882 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000883 if (auto *Arg = Args.getLastArg(OPT_subsystem))
884 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
885 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000886
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000887 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000888 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000889 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000890
Rui Ueyama08d5e182015-06-18 23:20:11 +0000891 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000892 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000893 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000894
Rui Ueyamab95188c2015-06-18 20:27:09 +0000895 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000896 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000897 Config->Implib = Arg->getValue();
898
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000899 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000900 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000901 std::string Str = StringRef(Arg->getValue()).lower();
902 SmallVector<StringRef, 1> Vec;
903 StringRef(Str).split(Vec, ',');
904 for (StringRef S : Vec) {
905 if (S == "noref") {
906 Config->DoGC = false;
907 Config->DoICF = false;
908 continue;
909 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000910 if (S == "icf" || S.startswith("icf=")) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000911 Config->DoICF = true;
912 continue;
913 }
914 if (S == "noicf") {
915 Config->DoICF = false;
916 continue;
917 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000918 if (S.startswith("lldlto=")) {
919 StringRef OptLevel = S.substr(7);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000920 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
921 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000922 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000923 continue;
924 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000925 if (S.startswith("lldltojobs=")) {
926 StringRef Jobs = S.substr(11);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000927 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000928 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000929 continue;
930 }
Peter Collingbournecef80992017-09-07 23:49:09 +0000931 if (S.startswith("lldltopartitions=")) {
932 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000933 if (N.getAsInteger(10, Config->LTOPartitions) ||
934 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000935 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000936 continue;
937 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000938 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000939 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000940 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000941 }
942
Bob Haarman69b196d2017-02-08 18:36:41 +0000943 // Handle /lldsavetemps
944 if (Args.hasArg(OPT_lldsavetemps))
945 Config->SaveTemps = true;
946
Peter Collingbourne052e855e2017-09-08 00:50:50 +0000947 // Handle /lldltocache
948 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
949 Config->LTOCache = Arg->getValue();
950
951 // Handle /lldsavecachepolicy
952 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
953 Config->LTOCachePolicy = check(
954 parseCachePruningPolicy(Arg->getValue()),
955 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
956
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000957 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000958 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000959 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000960
Rui Ueyama6600eb12015-07-04 23:37:32 +0000961 // Handle /merge
962 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000963 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000964
Rui Ueyama440138c2016-06-20 03:39:39 +0000965 // Handle /section
966 for (auto *Arg : Args.filtered(OPT_section))
967 parseSection(Arg->getValue());
968
Martin Storsjod2752aa2017-08-14 19:07:27 +0000969 // Handle /aligncomm
970 for (auto *Arg : Args.filtered(OPT_aligncomm))
971 parseAligncomm(Arg->getValue());
972
Nico Webera7a2c442017-07-25 18:08:03 +0000973 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
974 // also passed.
975 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
976 Config->ManifestDependency = Arg->getValue();
977 Config->Manifest = Configuration::SideBySide;
978 }
979
980 // Handle /manifest and /manifest:
981 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
982 if (Arg->getOption().getID() == OPT_manifest)
983 Config->Manifest = Configuration::SideBySide;
984 else
985 parseManifest(Arg->getValue());
986 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000987
988 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000989 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
990 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000991
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000992 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000993 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000994 Config->ManifestFile = Arg->getValue();
995
Rui Ueyamaafb19012016-04-19 01:21:58 +0000996 // Handle /manifestinput
997 for (auto *Arg : Args.filtered(OPT_manifestinput))
998 Config->ManifestInput.push_back(Arg->getValue());
999
Nico Webera7a2c442017-07-25 18:08:03 +00001000 if (!Config->ManifestInput.empty() &&
1001 Config->Manifest != Configuration::Embed) {
1002 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED");
1003 }
1004
Rui Ueyama6592ff82015-06-16 23:13:00 +00001005 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001006 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1007 Config->AllowIsolation =
1008 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1009 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1010 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Rui Ueyama96401732015-09-21 23:43:31 +00001011 if (Args.hasArg(OPT_nosymtab))
1012 Config->WriteSymtab = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +00001013
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001014 Config->MapFile = getMapFile(Args);
1015
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001016 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001017 return;
1018
Martin Storsjo8278ba52017-09-13 07:28:03 +00001019 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001020 // Create a list of input files. Files can be given as arguments
1021 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001022 std::vector<MemoryBufferRef> MBs;
Martin Storsjo8278ba52017-09-13 07:28:03 +00001023 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) {
1024 switch (Arg->getOption().getID()) {
1025 case OPT_INPUT:
1026 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1027 enqueuePath(*Path, WholeArchiveFlag);
1028 break;
1029 case OPT_wholearchive_file:
1030 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1031 enqueuePath(*Path, true);
1032 break;
1033 }
1034 }
David Blaikie6521ed92015-06-22 22:06:52 +00001035 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001036 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001037 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001038
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001039 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001040 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001041 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001042
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001043 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001044 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001045
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001046 // We should have inferred a machine type by now from the input files, but if
1047 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001048 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001049 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001050 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001051 }
1052
Eric Beckmann9e19d792017-06-17 02:26:27 +00001053 // Input files can be Windows resource files (.res files). We use
1054 // WindowsResource to convert resource files to a regular COFF file,
1055 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001056 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001057 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001058
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001059 if (Tar)
1060 Tar->append("response.txt",
1061 createResponseFile(Args, FilePaths,
1062 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001063
Rui Ueyama4d545342015-07-28 03:12:00 +00001064 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001065 Config->LargeAddressAware = Args.hasFlag(
1066 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001067
Rui Ueyamad68e2112015-07-28 03:15:57 +00001068 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001069 Config->HighEntropyVA =
1070 Config->is64() &&
1071 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001072
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001073 // Handle /entry and /dll
1074 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1075 Config->Entry = addUndefined(mangle(Arg->getValue()));
1076 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +00001077 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1078 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001079 Config->Entry = addUndefined(S);
1080 } else if (!Config->NoEntry) {
1081 // Windows specific -- If entry point name is not given, we need to
1082 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +00001083 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +00001084 if (S.empty())
1085 fatal("entry point must be defined");
1086 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001087 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +00001088 }
1089
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001090 // Handle /export
1091 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001092 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001093 if (Config->Machine == I386) {
1094 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001095 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001096 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001097 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001098 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001099 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001100 }
1101
1102 // Handle /def
1103 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001104 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001105 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001106 }
1107
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001108 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001109 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001110 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001111 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001112 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001113 }
1114
Rui Ueyama6d249082015-07-13 22:31:45 +00001115 // Handle /delayload
1116 for (auto *Arg : Args.filtered(OPT_delayload)) {
1117 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001118 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001119 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001120 } else {
1121 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001122 }
1123 }
1124
Reid Kleckner7668182e2017-03-21 00:12:51 +00001125 // Set default image name if neither /out or /def set it.
1126 if (Config->OutputFile.empty()) {
1127 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001128 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001129 }
1130
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001131 // Put the PDB next to the image if no /pdb flag was passed.
1132 if (Config->Debug && Config->PDBPath.empty()) {
1133 Config->PDBPath = Config->OutputFile;
1134 sys::path::replace_extension(Config->PDBPath, ".pdb");
1135 }
1136
Reid Kleckner77d3aa42017-03-22 19:49:12 +00001137 // Disable PDB generation if the user requested it.
1138 if (Args.hasArg(OPT_nopdb))
1139 Config->PDBPath = "";
1140
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001141 // Set default image base if /base is not given.
1142 if (Config->ImageBase == uint64_t(-1))
1143 Config->ImageBase = getDefaultImageBase();
1144
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001145 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001146 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001147 Symtab->addAbsolute("___safe_se_handler_table", 0);
1148 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001149 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001150
Rui Ueyama107db552015-08-09 21:01:06 +00001151 // We do not support /guard:cf (control flow protection) yet.
1152 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001153 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1154 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1155 Symtab->addAbsolute(mangle("__guard_flags"), 0x100);
1156 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1157 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1158 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1159 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001160
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001161 // This code may add new undefined symbols to the link, which may enqueue more
1162 // symbol resolution tasks, so we need to continue executing tasks until we
1163 // converge.
1164 do {
1165 // Windows specific -- if entry point is not found,
1166 // search for its mangled names.
1167 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001168 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001169
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001170 // Windows specific -- Make sure we resolve all dllexported symbols.
1171 for (Export &E : Config->Exports) {
1172 if (!E.ForwardTo.empty())
1173 continue;
1174 E.Sym = addUndefined(E.Name);
1175 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001176 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001177 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001178
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001179 // Add weak aliases. Weak aliases is a mechanism to give remaining
1180 // undefined symbols final chance to be resolved successfully.
1181 for (auto Pair : Config->AlternateNames) {
1182 StringRef From = Pair.first;
1183 StringRef To = Pair.second;
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001184 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001185 if (!Sym)
1186 continue;
1187 if (auto *U = dyn_cast<Undefined>(Sym->body()))
1188 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001189 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001190 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001191
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001192 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001193 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001194 addUndefined(mangle("_load_config_used"));
1195 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001196
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001197 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001198 return;
1199
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001200 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1201 // This is useful because MSVC link.exe can generate complete PDBs.
1202 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +00001203 invokeMSVC(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001204 return;
Rui Ueyama1e0b1582017-02-06 20:47:55 +00001205 }
1206
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001207 // Do LTO by compiling bitcode input files to a set of native COFF files then
1208 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001209 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001210 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001211
Peter Collingbourne2612a322015-07-04 05:28:41 +00001212 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001213 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001214 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001215 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001216
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001217 // Windows specific -- if no /subsystem is given, we need to infer
1218 // that from entry point name.
1219 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001220 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001221 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001222 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001223 }
1224
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001225 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001226 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001227 for (ObjFile *File : ObjFile::Instances)
Rui Ueyama13563d82015-09-15 00:33:11 +00001228 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001229 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001230 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001231 return;
1232 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001233
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001234 // In MinGW, all symbols are automatically exported if no symbols
1235 // are chosen to be exported.
1236 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1237 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001238 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001239
1240 Symtab->forEachSymbol([=](Symbol *S) {
1241 auto *Def = dyn_cast<Defined>(S->body());
Martin Storsjob40ccc12017-10-19 06:56:04 +00001242 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001243 return;
1244 Export E;
1245 E.Name = Def->getName();
1246 E.Sym = Def;
1247 Config->Exports.push_back(E);
1248 });
1249 }
1250
Rui Ueyama151d8622015-06-17 20:40:43 +00001251 // Windows specific -- when we are creating a .dll file, we also
1252 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001253 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001254 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001255 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001256 assignExportOrdinals();
1257 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001258
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001259 // Handle /output-def (MinGW specific).
1260 if (auto *Arg = Args.getLastArg(OPT_output_def))
1261 writeDefFile(Arg->getValue());
1262
Martin Storsjod2752aa2017-08-14 19:07:27 +00001263 // Set extra alignment for .comm symbols
1264 for (auto Pair : Config->AlignComm) {
1265 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001266 uint32_t Alignment = Pair.second;
1267
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001268 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001269 if (!Sym) {
1270 warn("/aligncomm symbol " + Name + " not found");
1271 continue;
1272 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001273
Martin Storsjod2752aa2017-08-14 19:07:27 +00001274 auto *DC = dyn_cast<DefinedCommon>(Sym->body());
1275 if (!DC) {
1276 warn("/aligncomm symbol " + Name + " of wrong kind");
1277 continue;
1278 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001279
1280 CommonChunk *C = DC->getChunk();
1281 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001282 }
1283
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001284 // Windows specific -- Create a side-by-side manifest file.
1285 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001286 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001287
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001288 // Identify unreferenced COMDAT sections.
1289 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001290 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001291
1292 // Identify identical COMDAT sections to merge them.
1293 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001294 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001295
Rui Ueyama411c63602015-05-28 19:09:30 +00001296 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001297 writeResult();
Rui Ueyama411c63602015-05-28 19:09:30 +00001298}
1299
Rui Ueyama411c63602015-05-28 19:09:30 +00001300} // namespace coff
1301} // namespace lld