blob: 3bf9b7613500ddee9f2e9fce0a8e53e3decd3d6d [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 Ueyama562daa82015-06-18 21:50:38 +000012#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Rui Ueyama9381eb12016-12-18 14:06:06 +000014#include "Memory.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 Ueyamaa453c0a2016-03-02 19:08:05 +000018#include "lld/Driver/Driver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000019#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000020#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000021#include "llvm/LibDriver/LibDriver.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000022#include "llvm/Object/ArchiveWriter.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000023#include "llvm/Option/Arg.h"
24#include "llvm/Option/ArgList.h"
25#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000026#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000027#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000028#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000029#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000030#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000032#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000033#include <memory>
34
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000035#include <future>
36
Rui Ueyama411c63602015-05-28 19:09:30 +000037using namespace llvm;
Rui Ueyama84936e02015-07-07 23:39:18 +000038using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000039using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000040using llvm::sys::fs::file_magic;
41using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000042
Rui Ueyama3500f662015-05-28 20:30:06 +000043namespace lld {
44namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000045
Rui Ueyama3500f662015-05-28 20:30:06 +000046Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000047LinkerDriver *Driver;
48
Rui Ueyama9381eb12016-12-18 14:06:06 +000049BumpPtrAllocator BAlloc;
50StringSaver Saver{BAlloc};
51std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
52
Bob Haarman6c8f7362017-01-17 19:07:42 +000053bool link(ArrayRef<const char *> Args, raw_ostream &Diag) {
54 ErrorCount = 0;
55 ErrorOS = &Diag;
56 Argv0 = Args[0];
Rui Ueyama7fed58c2016-12-08 19:10:28 +000057 Config = make<Configuration>();
Bob Haarman6c8f7362017-01-17 19:07:42 +000058 Config->ColorDiagnostics =
59 (ErrorOS == &llvm::errs() && Process::StandardErrHasColors());
Rui Ueyama7fed58c2016-12-08 19:10:28 +000060 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000061 Driver->link(Args);
David Blaikie4cdfe692017-02-19 02:25:47 +000062 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000063}
Rui Ueyama411c63602015-05-28 19:09:30 +000064
Nico Weber5660de72016-04-20 22:34:15 +000065// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000066static std::string getOutputPath(StringRef Path) {
67 auto P = Path.find_last_of("\\/");
68 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000069 const char* E = Config->DLL ? ".dll" : ".exe";
70 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000071}
72
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000073// ErrorOr is not default constructible, so it cannot be used as the type
74// parameter of a future.
75// FIXME: We could open the file in createFutureForFile and avoid needing to
76// return an error here, but for the moment that would cost us a file descriptor
77// (a limited resource on Windows) for the duration that the future is pending.
78typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
79
80// Create a std::future that opens and maps a file using the best strategy for
81// the host platform.
82static std::future<MBErrPair> createFutureForFile(std::string Path) {
83#if LLVM_ON_WIN32
84 // On Windows, file I/O is relatively slow so it is best to do this
85 // asynchronously.
86 auto Strategy = std::launch::async;
87#else
88 auto Strategy = std::launch::deferred;
89#endif
90 return std::async(Strategy, [=]() {
91 auto MBOrErr = MemoryBuffer::getFile(Path);
92 if (!MBOrErr)
93 return MBErrPair{nullptr, MBOrErr.getError()};
94 return MBErrPair{std::move(*MBOrErr), std::error_code()};
95 });
96}
97
98MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
99 MemoryBufferRef MBRef = *MB;
100 OwningMBs.push_back(std::move(MB));
101
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000102 if (Driver->Tar)
103 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
104 MBRef.getBuffer());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000105
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000106 return MBRef;
107}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000108
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000109void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
110 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000111
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000112 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000113 file_magic Magic = identify_magic(MBRef.getBuffer());
114 if (Magic == file_magic::windows_resource) {
115 Resources.push_back(MBRef);
116 return;
117 }
118
119 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000120 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000121 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000122 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000123 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000124 if (Magic == file_magic::coff_cl_gl_object)
David Blaikie4cdfe692017-02-19 02:25:47 +0000125 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000126 "Recompile without /GL");
David Blaikie4cdfe692017-02-19 02:25:47 +0000127 Symtab.addFile(make<ObjectFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000128}
129
130void LinkerDriver::enqueuePath(StringRef Path) {
131 auto Future =
132 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
133 std::string PathStr = Path;
134 enqueueTask([=]() {
135 auto MBOrErr = Future->get();
136 if (MBOrErr.second)
David Blaikie4cdfe692017-02-19 02:25:47 +0000137 fatal(MBOrErr.second, "could not open " + PathStr);
138 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000139 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000140}
141
142void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
143 StringRef ParentName) {
144 file_magic Magic = identify_magic(MB.getBuffer());
145 if (Magic == file_magic::coff_import_library) {
146 Symtab.addFile(make<ImportFile>(MB));
147 return;
148 }
149
150 InputFile *Obj;
David Blaikie4cdfe692017-02-19 02:25:47 +0000151 if (Magic == file_magic::coff_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000152 Obj = make<ObjectFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000153 else if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000154 Obj = make<BitcodeFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000155 else
156 fatal("unknown file type: " + MB.getBufferIdentifier());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000157
158 Obj->ParentName = ParentName;
159 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000160 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000161}
162
163void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
164 StringRef SymName,
165 StringRef ParentName) {
166 if (!C.getParent()->isThin()) {
167 MemoryBufferRef MB = check(
168 C.getMemoryBufferRef(),
169 "could not get the buffer for the member defining symbol " + SymName);
170 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
171 return;
172 }
173
174 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
175 check(C.getFullName(),
176 "could not get the filename for the member defining symbol " +
177 SymName)));
178 enqueueTask([=]() {
179 auto MBOrErr = Future->get();
180 if (MBOrErr.second)
181 fatal(MBOrErr.second,
182 "could not get the buffer for the member defining " + SymName);
183 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
184 ParentName);
185 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000186}
187
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000188static bool isDecorated(StringRef Sym) {
189 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
190}
191
Rui Ueyama411c63602015-05-28 19:09:30 +0000192// Parses .drectve section contents and returns a list of files
193// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000194void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000195 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000196
David Blaikie6521ed92015-06-22 22:06:52 +0000197 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000198 switch (Arg->getOption().getID()) {
199 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000200 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000201 break;
202 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000203 if (Optional<StringRef> Path = findLib(Arg->getValue()))
204 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000205 break;
206 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000207 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000208 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000209 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000210 break;
211 }
212 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000213 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000214 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000215 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000216 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000217 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000218 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000219 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000220 break;
221 case OPT_nodefaultlib:
222 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
223 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000224 case OPT_section:
225 parseSection(Arg->getValue());
226 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000227 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000228 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000229 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000230 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000231 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000232 default:
David Blaikie4cdfe692017-02-19 02:25:47 +0000233 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000234 }
235 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000236}
237
Rui Ueyama54b71da2015-05-31 19:17:12 +0000238// Find file from search paths. You can omit ".obj", this function takes
239// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000240StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000241 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
242 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000243 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000244 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000245 for (StringRef Dir : SearchPaths) {
246 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000247 sys::path::append(Path, Filename);
248 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000249 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000250 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000251 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000252 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000253 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000254 }
255 }
256 return Filename;
257}
258
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000259// Resolves a file path. This never returns the same path
260// (in that case, it returns None).
261Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
262 StringRef Path = doFindFile(Filename);
263 bool Seen = !VisitedFiles.insert(Path.lower()).second;
264 if (Seen)
265 return None;
266 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000267}
268
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000269// Find library file from search path.
270StringRef LinkerDriver::doFindLib(StringRef Filename) {
271 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000272 bool HasExt = (Filename.find('.') != StringRef::npos);
273 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000274 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000275 return doFindFile(Filename);
276}
277
278// Resolves a library path. /nodefaultlib options are taken into
279// consideration. This never returns the same path (in that case,
280// it returns None).
281Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
282 if (Config->NoDefaultLibAll)
283 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000284 if (!VisitedLibs.insert(Filename.lower()).second)
285 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000286 StringRef Path = doFindLib(Filename);
287 if (Config->NoDefaultLibs.count(Path))
288 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000289 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000290 return None;
291 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000292}
293
294// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000295void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000296 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
297 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000298 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000299 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000300 while (!Env.empty()) {
301 StringRef Path;
302 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000303 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000304 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000305}
306
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000307SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
308 SymbolBody *B = Symtab.addUndefined(Name);
309 Config->GCRoot.insert(B);
310 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000311}
312
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000313// Symbol names are mangled by appending "_" prefix on x86.
314StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000315 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
316 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000317 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000318 return Sym;
319}
320
Rui Ueyama45044f42015-06-29 01:03:53 +0000321// Windows specific -- find default entry point name.
322StringRef LinkerDriver::findDefaultEntry() {
323 // User-defined main functions and their corresponding entry points.
324 static const char *Entries[][2] = {
325 {"main", "mainCRTStartup"},
326 {"wmain", "wmainCRTStartup"},
327 {"WinMain", "WinMainCRTStartup"},
328 {"wWinMain", "wWinMainCRTStartup"},
329 };
330 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000331 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000332 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000333 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000334 }
335 return "";
336}
337
338WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000339 if (Config->DLL)
340 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000341 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000342 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000343 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000344 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
345 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000346}
347
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000348static uint64_t getDefaultImageBase() {
349 if (Config->is64())
350 return Config->DLL ? 0x180000000 : 0x140000000;
351 return Config->DLL ? 0x10000000 : 0x400000;
352}
353
Rui Ueyama8fe17672016-12-08 20:50:47 +0000354static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000355 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000356 ArrayRef<StringRef> SearchPaths) {
357 SmallString<0> Data;
358 raw_svector_ostream OS(Data);
359
360 for (auto *Arg : Args) {
361 switch (Arg->getOption().getID()) {
362 case OPT_linkrepro:
363 case OPT_INPUT:
364 case OPT_defaultlib:
365 case OPT_libpath:
366 break;
367 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000368 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000369 }
370 }
371
372 for (StringRef Path : SearchPaths) {
373 std::string RelPath = relativeToRoot(Path);
374 OS << "/libpath:" << quote(RelPath) << "\n";
375 }
376
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000377 for (StringRef Path : FilePaths)
378 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000379
380 return Data.str();
381}
382
Rui Ueyama8fe17672016-12-08 20:50:47 +0000383static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000384 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
385 if (Args.hasArg(OPT_driver))
386 DebugTypes |= static_cast<unsigned>(DebugType::PData);
387 if (Args.hasArg(OPT_profile))
388 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
389 return DebugTypes;
390}
391
392static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000393 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000394 Arg.split(Types, ',', /*KeepEmpty=*/false);
395
396 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
397 for (StringRef Type : Types)
398 DebugTypes |= StringSwitch<unsigned>(Type.lower())
399 .Case("cv", static_cast<unsigned>(DebugType::CV))
400 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000401 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
402 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000403 return DebugTypes;
404}
405
Hans Wennborg1818e652016-12-09 20:54:44 +0000406static std::string getMapFile(const opt::InputArgList &Args) {
407 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
408 if (!Arg)
409 return "";
410 if (Arg->getOption().getID() == OPT_lldmap_file)
411 return Arg->getValue();
412
413 assert(Arg->getOption().getID() == OPT_lldmap);
414 StringRef OutFile = Config->OutputFile;
415 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
416}
417
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000418std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000419 std::vector<MemoryBufferRef> V;
420 Error Err = Error::success();
421 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
422 Archive::Child C =
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000423 check(COrErr,
424 File->getFileName() + ": could not get the child of the archive");
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000425 MemoryBufferRef MBRef =
426 check(C.getMemoryBufferRef(),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000427 File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000428 ": could not get the buffer for a child of the archive");
429 V.push_back(MBRef);
430 }
431 if (Err)
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000432 fatal(File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000433 ": Archive::children failed: " + toString(std::move(Err)));
434 return V;
435}
436
437// A helper function for filterBitcodeFiles.
438static bool needsRebuilding(MemoryBufferRef MB) {
439 // The MSVC linker doesn't support thin archives, so if it's a thin
440 // archive, we always need to rebuild it.
441 std::unique_ptr<Archive> File =
442 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
443 if (File->isThin())
444 return true;
445
446 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000447 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000448 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
449 return true;
450 return false;
451}
452
453// Opens a given path as an archive file and removes bitcode files
454// from them if exists. This function is to appease the MSVC linker as
455// their linker doesn't like archive files containing non-native
456// object files.
457//
458// If a given archive doesn't contain bitcode files, the archive path
459// is returned as-is. Otherwise, a new temporary file is created and
460// its path is returned.
461static Optional<std::string>
462filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000463 std::unique_ptr<MemoryBuffer> MB = check(
464 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000465 MemoryBufferRef MBRef = MB->getMemBufferRef();
466 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000467
468 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000469 return None;
470 if (Magic != file_magic::archive)
471 return Path.str();
472 if (!needsRebuilding(MBRef))
473 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000474
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000475 std::unique_ptr<Archive> File =
476 check(Archive::create(MBRef),
477 MBRef.getBufferIdentifier() + ": failed to parse archive");
478
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000479 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000480 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000481 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
482 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000483
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000484 if (New.empty())
485 return None;
486
487 log("Creating a temporary archive for " + Path + " to remove bitcode files");
488
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000489 SmallString<128> S;
490 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
491 ".lib", S))
492 fatal(EC, "cannot create a temporary file");
493 std::string Temp = S.str();
494 TemporaryFiles.push_back(Temp);
495
496 std::pair<StringRef, std::error_code> Ret =
497 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
498 /*Deterministics=*/true,
499 /*Thin=*/false);
500 if (Ret.second)
501 error("failed to create a new archive " + S.str() + ": " + Ret.first);
502 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000503}
504
505// Create response file contents and invoke the MSVC linker.
506void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
507 std::string Rsp = "/nologo ";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000508 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000509
510 for (auto *Arg : Args) {
511 switch (Arg->getOption().getID()) {
512 case OPT_linkrepro:
513 case OPT_lldmap:
514 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000515 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000516 case OPT_msvclto:
517 // LLD-specific options are stripped.
518 break;
519 case OPT_opt:
520 if (!StringRef(Arg->getValue()).startswith("lld"))
521 Rsp += toString(Arg) + " ";
522 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000523 case OPT_INPUT: {
524 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
525 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
526 Rsp += quote(*S) + " ";
527 continue;
528 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000529 Rsp += quote(Arg->getValue()) + " ";
530 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000531 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000532 default:
533 Rsp += toString(Arg) + " ";
534 }
535 }
536
537 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
538 runMSVCLinker(Rsp, ObjectFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000539
540 for (StringRef Path : Temps)
541 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000542}
543
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000544void LinkerDriver::enqueueTask(std::function<void()> Task) {
545 TaskQueue.push_back(std::move(Task));
546}
547
548bool LinkerDriver::run() {
549 bool DidWork = !TaskQueue.empty();
550 while (!TaskQueue.empty()) {
551 TaskQueue.front()();
552 TaskQueue.pop_front();
553 }
554 return DidWork;
555}
556
Rui Ueyama8fe17672016-12-08 20:50:47 +0000557void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000558 // If the first command line argument is "/lib", link.exe acts like lib.exe.
559 // We call our own implementation of lib.exe that understands bitcode files.
560 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
561 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000562 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000563 return;
564 }
565
Peter Collingbourne60c16162015-06-01 20:10:10 +0000566 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000567 InitializeAllTargetInfos();
568 InitializeAllTargets();
569 InitializeAllTargetMCs();
570 InitializeAllAsmParsers();
571 InitializeAllAsmPrinters();
572 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000573
Rui Ueyama411c63602015-05-28 19:09:30 +0000574 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000575 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000576
Rui Ueyama5c726432015-05-29 16:11:52 +0000577 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000578 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000579 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000580 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000581 }
582
Peter Collingbournefeee2102016-07-26 02:00:42 +0000583 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
584 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000585 sys::path::append(Path, "repro.tar");
586
587 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
588 TarWriter::create(Path, "repro");
589
590 if (ErrOrWriter) {
591 Tar = std::move(*ErrOrWriter);
592 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000593 error("/linkrepro: failed to open " + Path + ": " +
594 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000595 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000596 }
597
Rafael Espindolab835ae82015-08-06 14:58:50 +0000598 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000599 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000600
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000601 // Construct search path list.
602 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000603 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000604 SearchPaths.push_back(Arg->getValue());
605 addLibSearchPaths();
606
Rui Ueyamaad660982015-06-07 00:20:32 +0000607 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000608 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000609 Config->OutputFile = Arg->getValue();
610
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000611 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000612 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000613 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000614
Rui Ueyama95925fd2015-06-28 19:35:15 +0000615 // Handle /force or /force:unresolved
616 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
617 Config->Force = true;
618
Rui Ueyama6600eb12015-07-04 23:37:32 +0000619 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000620 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000621 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000622 Config->DebugTypes =
623 Args.hasArg(OPT_debugtype)
624 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
625 : getDefaultDebugType(Args);
626 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000627
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000628 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000629 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000630 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000631
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000632 // Handle /noentry
633 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000634 if (!Args.hasArg(OPT_dll))
David Blaikie4cdfe692017-02-19 02:25:47 +0000635 fatal("/noentry must be specified with /dll");
636 Config->NoEntry = true;
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000637 }
638
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000639 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000640 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000641 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000642 Config->ManifestID = 2;
643 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000644
Rui Ueyama588e8322015-06-15 01:23:58 +0000645 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000646 if (Args.hasArg(OPT_fixed)) {
David Blaikie4cdfe692017-02-19 02:25:47 +0000647 if (Args.hasArg(OPT_dynamicbase))
648 fatal("/fixed must not be specified with /dynamicbase");
649 Config->Relocatable = false;
650 Config->DynamicBase = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000651 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000652
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000653 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000654 if (auto *Arg = Args.getLastArg(OPT_machine))
655 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000656
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000657 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000658 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000659 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
660
661 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000662 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000663 Config->NoDefaultLibAll = true;
664
Rui Ueyama804a8b62015-05-29 16:18:15 +0000665 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000666 if (auto *Arg = Args.getLastArg(OPT_base))
667 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000668
669 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000670 if (auto *Arg = Args.getLastArg(OPT_stack))
671 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000672
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000673 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000674 if (auto *Arg = Args.getLastArg(OPT_heap))
675 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000676
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000677 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000678 if (auto *Arg = Args.getLastArg(OPT_version))
679 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
680 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000681
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000682 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000683 if (auto *Arg = Args.getLastArg(OPT_subsystem))
684 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
685 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000686
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000687 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000688 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000689 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000690
Rui Ueyama08d5e182015-06-18 23:20:11 +0000691 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000692 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000693 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000694
Rui Ueyamab95188c2015-06-18 20:27:09 +0000695 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000696 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000697 Config->Implib = Arg->getValue();
698
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000699 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000700 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000701 std::string Str = StringRef(Arg->getValue()).lower();
702 SmallVector<StringRef, 1> Vec;
703 StringRef(Str).split(Vec, ',');
704 for (StringRef S : Vec) {
705 if (S == "noref") {
706 Config->DoGC = false;
707 Config->DoICF = false;
708 continue;
709 }
710 if (S == "icf" || StringRef(S).startswith("icf=")) {
711 Config->DoICF = true;
712 continue;
713 }
714 if (S == "noicf") {
715 Config->DoICF = false;
716 continue;
717 }
718 if (StringRef(S).startswith("lldlto=")) {
719 StringRef OptLevel = StringRef(S).substr(7);
720 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
721 Config->LTOOptLevel > 3)
David Blaikie4cdfe692017-02-19 02:25:47 +0000722 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000723 continue;
724 }
725 if (StringRef(S).startswith("lldltojobs=")) {
726 StringRef Jobs = StringRef(S).substr(11);
727 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000728 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000729 continue;
730 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000731 if (StringRef(S).startswith("lldltopartitions=")) {
732 StringRef N = StringRef(S).substr(17);
733 if (N.getAsInteger(10, Config->LTOPartitions) ||
734 Config->LTOPartitions == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000735 fatal("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000736 continue;
737 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000738 if (S != "ref" && S != "lbr" && S != "nolbr")
David Blaikie4cdfe692017-02-19 02:25:47 +0000739 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000740 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000741 }
742
Bob Haarman69b196d2017-02-08 18:36:41 +0000743 // Handle /lldsavetemps
744 if (Args.hasArg(OPT_lldsavetemps))
745 Config->SaveTemps = true;
746
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000747 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000748 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000749 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000750
Rui Ueyama6600eb12015-07-04 23:37:32 +0000751 // Handle /merge
752 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000753 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000754
Rui Ueyama440138c2016-06-20 03:39:39 +0000755 // Handle /section
756 for (auto *Arg : Args.filtered(OPT_section))
757 parseSection(Arg->getValue());
758
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000759 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000760 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
761 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000762
763 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000764 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
765 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000766
767 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000768 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000769 Config->ManifestDependency = Arg->getValue();
770
771 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000772 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000773 Config->ManifestFile = Arg->getValue();
774
Rui Ueyamaafb19012016-04-19 01:21:58 +0000775 // Handle /manifestinput
776 for (auto *Arg : Args.filtered(OPT_manifestinput))
777 Config->ManifestInput.push_back(Arg->getValue());
778
Rui Ueyama6592ff82015-06-16 23:13:00 +0000779 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000780 if (Args.hasArg(OPT_allowbind_no))
781 Config->AllowBind = false;
782 if (Args.hasArg(OPT_allowisolation_no))
783 Config->AllowIsolation = false;
784 if (Args.hasArg(OPT_dynamicbase_no))
785 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000786 if (Args.hasArg(OPT_nxcompat_no))
787 Config->NxCompat = false;
788 if (Args.hasArg(OPT_tsaware_no))
789 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000790 if (Args.hasArg(OPT_nosymtab))
791 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000792 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000793 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000794
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000795 Config->MapFile = getMapFile(Args);
796
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000797 // Create a list of input files. Files can be given as arguments
798 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000799 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000800 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000801 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000802 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000803 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000804 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000805 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000806
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000807 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000808 if (Config->Manifest == Configuration::Embed)
809 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000810
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000811 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000812 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000813
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000814 // We should have inferred a machine type by now from the input files, but if
815 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000816 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000817 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000818 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000819 }
820
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000821 // Windows specific -- Input files can be Windows resource files (.res files).
822 // We invoke cvtres.exe to convert resource files to a regular COFF file
823 // then link the result file normally.
824 if (!Resources.empty())
825 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000826
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000827 if (Tar)
828 Tar->append("response.txt",
829 createResponseFile(Args, FilePaths,
830 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000831
Rui Ueyama4d545342015-07-28 03:12:00 +0000832 // Handle /largeaddressaware
833 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
834 Config->LargeAddressAware = true;
835
Rui Ueyamad68e2112015-07-28 03:15:57 +0000836 // Handle /highentropyva
837 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
838 Config->HighEntropyVA = true;
839
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000840 // Handle /entry and /dll
841 if (auto *Arg = Args.getLastArg(OPT_entry)) {
842 Config->Entry = addUndefined(mangle(Arg->getValue()));
843 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000844 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
845 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000846 Config->Entry = addUndefined(S);
847 } else if (!Config->NoEntry) {
848 // Windows specific -- If entry point name is not given, we need to
849 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000850 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +0000851 if (S.empty())
852 fatal("entry point must be defined");
853 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000854 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +0000855 }
856
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000857 // Handle /export
858 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000859 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000860 if (Config->Machine == I386) {
861 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000862 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000863 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000864 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000865 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000866 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000867 }
868
869 // Handle /def
870 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000871 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000872 parseModuleDefs(
873 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
874 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000875 }
876
Rui Ueyama6d249082015-07-13 22:31:45 +0000877 // Handle /delayload
878 for (auto *Arg : Args.filtered(OPT_delayload)) {
879 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000880 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000881 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000882 } else {
883 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000884 }
885 }
886
Reid Kleckner7668182e2017-03-21 00:12:51 +0000887 // Set default image name if neither /out or /def set it.
888 if (Config->OutputFile.empty()) {
889 Config->OutputFile =
890 getOutputPath((*Args.filtered_begin(OPT_INPUT))->getValue());
891 }
892
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000893 // Set default image base if /base is not given.
894 if (Config->ImageBase == uint64_t(-1))
895 Config->ImageBase = getDefaultImageBase();
896
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000897 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000898 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000899 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
900 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
901 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000902
Rui Ueyama107db552015-08-09 21:01:06 +0000903 // We do not support /guard:cf (control flow protection) yet.
904 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
905 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
906 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
907 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
908
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000909 // This code may add new undefined symbols to the link, which may enqueue more
910 // symbol resolution tasks, so we need to continue executing tasks until we
911 // converge.
912 do {
913 // Windows specific -- if entry point is not found,
914 // search for its mangled names.
915 if (Config->Entry)
916 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000917
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000918 // Windows specific -- Make sure we resolve all dllexported symbols.
919 for (Export &E : Config->Exports) {
920 if (!E.ForwardTo.empty())
921 continue;
922 E.Sym = addUndefined(E.Name);
923 if (!E.Directives)
924 Symtab.mangleMaybe(E.Sym);
925 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000926
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000927 // Add weak aliases. Weak aliases is a mechanism to give remaining
928 // undefined symbols final chance to be resolved successfully.
929 for (auto Pair : Config->AlternateNames) {
930 StringRef From = Pair.first;
931 StringRef To = Pair.second;
932 Symbol *Sym = Symtab.find(From);
933 if (!Sym)
934 continue;
935 if (auto *U = dyn_cast<Undefined>(Sym->body()))
936 if (!U->WeakAlias)
937 U->WeakAlias = Symtab.addUndefined(To);
938 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000939
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000940 // Windows specific -- if __load_config_used can be resolved, resolve it.
941 if (Symtab.findUnderscore("_load_config_used"))
942 addUndefined(mangle("_load_config_used"));
943 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000944
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000945 // If /msvclto is given, we use the MSVC linker to link LTO output files.
946 // This is useful because MSVC link.exe can generate complete PDBs.
947 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000948 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000949 exit(0);
950 }
951
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000952 // Do LTO by compiling bitcode input files to a set of native COFF files then
953 // link those files.
954 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000955 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000956
Peter Collingbourne2612a322015-07-04 05:28:41 +0000957 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000958 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000959
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000960 // Windows specific -- if no /subsystem is given, we need to infer
961 // that from entry point name.
962 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000963 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000964 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000965 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000966 }
967
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000968 // Handle /safeseh.
David Blaikie4cdfe692017-02-19 02:25:47 +0000969 if (Args.hasArg(OPT_safeseh))
Rui Ueyama13563d82015-09-15 00:33:11 +0000970 for (ObjectFile *File : Symtab.ObjectFiles)
971 if (!File->SEHCompat)
David Blaikie4cdfe692017-02-19 02:25:47 +0000972 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000973
Rui Ueyama151d8622015-06-17 20:40:43 +0000974 // Windows specific -- when we are creating a .dll file, we also
975 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000976 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000977 fixupExports();
978 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000979 assignExportOrdinals();
980 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000981
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000982 // Windows specific -- Create a side-by-side manifest file.
983 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000984 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000985
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000986 // Identify unreferenced COMDAT sections.
987 if (Config->DoGC)
988 markLive(Symtab.getChunks());
989
990 // Identify identical COMDAT sections to merge them.
991 if (Config->DoICF)
992 doICF(Symtab.getChunks());
993
Rui Ueyama411c63602015-05-28 19:09:30 +0000994 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000995 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000996
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000997 // Call exit to avoid calling destructors.
998 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000999}
1000
Rui Ueyama411c63602015-05-28 19:09:30 +00001001} // namespace coff
1002} // namespace lld