blob: e22925a1db9e5e630431303d7317c603231d912d [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 });
140
Rui Ueyamaad660982015-06-07 00:20:32 +0000141 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000142 Config->OutputFile = getOutputPath(Path);
143}
144
145void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
146 StringRef ParentName) {
147 file_magic Magic = identify_magic(MB.getBuffer());
148 if (Magic == file_magic::coff_import_library) {
149 Symtab.addFile(make<ImportFile>(MB));
150 return;
151 }
152
153 InputFile *Obj;
David Blaikie4cdfe692017-02-19 02:25:47 +0000154 if (Magic == file_magic::coff_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000155 Obj = make<ObjectFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000156 else if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000157 Obj = make<BitcodeFile>(MB);
David Blaikie4cdfe692017-02-19 02:25:47 +0000158 else
159 fatal("unknown file type: " + MB.getBufferIdentifier());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000160
161 Obj->ParentName = ParentName;
162 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000163 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000164}
165
166void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
167 StringRef SymName,
168 StringRef ParentName) {
169 if (!C.getParent()->isThin()) {
170 MemoryBufferRef MB = check(
171 C.getMemoryBufferRef(),
172 "could not get the buffer for the member defining symbol " + SymName);
173 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
174 return;
175 }
176
177 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
178 check(C.getFullName(),
179 "could not get the filename for the member defining symbol " +
180 SymName)));
181 enqueueTask([=]() {
182 auto MBOrErr = Future->get();
183 if (MBOrErr.second)
184 fatal(MBOrErr.second,
185 "could not get the buffer for the member defining " + SymName);
186 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
187 ParentName);
188 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000189}
190
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000191static bool isDecorated(StringRef Sym) {
192 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
193}
194
Rui Ueyama411c63602015-05-28 19:09:30 +0000195// Parses .drectve section contents and returns a list of files
196// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000197void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000198 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000199
David Blaikie6521ed92015-06-22 22:06:52 +0000200 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000201 switch (Arg->getOption().getID()) {
202 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000203 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000204 break;
205 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000206 if (Optional<StringRef> Path = findLib(Arg->getValue()))
207 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000208 break;
209 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000210 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000211 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000212 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000213 break;
214 }
215 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000216 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000217 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000218 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000219 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000220 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000221 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000222 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000223 break;
224 case OPT_nodefaultlib:
225 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
226 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000227 case OPT_section:
228 parseSection(Arg->getValue());
229 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000230 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000231 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000232 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000233 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000234 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000235 default:
David Blaikie4cdfe692017-02-19 02:25:47 +0000236 fatal(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000237 }
238 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000239}
240
Rui Ueyama54b71da2015-05-31 19:17:12 +0000241// Find file from search paths. You can omit ".obj", this function takes
242// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000243StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000244 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
245 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000246 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000247 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000248 for (StringRef Dir : SearchPaths) {
249 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000250 sys::path::append(Path, Filename);
251 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000252 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000253 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000254 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000255 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000256 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000257 }
258 }
259 return Filename;
260}
261
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000262// Resolves a file path. This never returns the same path
263// (in that case, it returns None).
264Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
265 StringRef Path = doFindFile(Filename);
266 bool Seen = !VisitedFiles.insert(Path.lower()).second;
267 if (Seen)
268 return None;
269 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000270}
271
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000272// Find library file from search path.
273StringRef LinkerDriver::doFindLib(StringRef Filename) {
274 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000275 bool HasExt = (Filename.find('.') != StringRef::npos);
276 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000277 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000278 return doFindFile(Filename);
279}
280
281// Resolves a library path. /nodefaultlib options are taken into
282// consideration. This never returns the same path (in that case,
283// it returns None).
284Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
285 if (Config->NoDefaultLibAll)
286 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000287 if (!VisitedLibs.insert(Filename.lower()).second)
288 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000289 StringRef Path = doFindLib(Filename);
290 if (Config->NoDefaultLibs.count(Path))
291 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000292 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000293 return None;
294 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000295}
296
297// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000298void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000299 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
300 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000301 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000302 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000303 while (!Env.empty()) {
304 StringRef Path;
305 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000306 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000307 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000308}
309
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000310SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
311 SymbolBody *B = Symtab.addUndefined(Name);
312 Config->GCRoot.insert(B);
313 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000314}
315
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000316// Symbol names are mangled by appending "_" prefix on x86.
317StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000318 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
319 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000320 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000321 return Sym;
322}
323
Rui Ueyama45044f42015-06-29 01:03:53 +0000324// Windows specific -- find default entry point name.
325StringRef LinkerDriver::findDefaultEntry() {
326 // User-defined main functions and their corresponding entry points.
327 static const char *Entries[][2] = {
328 {"main", "mainCRTStartup"},
329 {"wmain", "wmainCRTStartup"},
330 {"WinMain", "WinMainCRTStartup"},
331 {"wWinMain", "wWinMainCRTStartup"},
332 };
333 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000334 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000335 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000336 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000337 }
338 return "";
339}
340
341WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000342 if (Config->DLL)
343 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000344 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000345 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000346 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000347 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
348 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000349}
350
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000351static uint64_t getDefaultImageBase() {
352 if (Config->is64())
353 return Config->DLL ? 0x180000000 : 0x140000000;
354 return Config->DLL ? 0x10000000 : 0x400000;
355}
356
Rui Ueyama8fe17672016-12-08 20:50:47 +0000357static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000358 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000359 ArrayRef<StringRef> SearchPaths) {
360 SmallString<0> Data;
361 raw_svector_ostream OS(Data);
362
363 for (auto *Arg : Args) {
364 switch (Arg->getOption().getID()) {
365 case OPT_linkrepro:
366 case OPT_INPUT:
367 case OPT_defaultlib:
368 case OPT_libpath:
369 break;
370 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000371 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000372 }
373 }
374
375 for (StringRef Path : SearchPaths) {
376 std::string RelPath = relativeToRoot(Path);
377 OS << "/libpath:" << quote(RelPath) << "\n";
378 }
379
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000380 for (StringRef Path : FilePaths)
381 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000382
383 return Data.str();
384}
385
Rui Ueyama8fe17672016-12-08 20:50:47 +0000386static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000387 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
388 if (Args.hasArg(OPT_driver))
389 DebugTypes |= static_cast<unsigned>(DebugType::PData);
390 if (Args.hasArg(OPT_profile))
391 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
392 return DebugTypes;
393}
394
395static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000396 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000397 Arg.split(Types, ',', /*KeepEmpty=*/false);
398
399 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
400 for (StringRef Type : Types)
401 DebugTypes |= StringSwitch<unsigned>(Type.lower())
402 .Case("cv", static_cast<unsigned>(DebugType::CV))
403 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000404 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
405 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000406 return DebugTypes;
407}
408
Hans Wennborg1818e652016-12-09 20:54:44 +0000409static std::string getMapFile(const opt::InputArgList &Args) {
410 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
411 if (!Arg)
412 return "";
413 if (Arg->getOption().getID() == OPT_lldmap_file)
414 return Arg->getValue();
415
416 assert(Arg->getOption().getID() == OPT_lldmap);
417 StringRef OutFile = Config->OutputFile;
418 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
419}
420
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000421std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000422 std::vector<MemoryBufferRef> V;
423 Error Err = Error::success();
424 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
425 Archive::Child C =
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000426 check(COrErr,
427 File->getFileName() + ": could not get the child of the archive");
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000428 MemoryBufferRef MBRef =
429 check(C.getMemoryBufferRef(),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000430 File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000431 ": could not get the buffer for a child of the archive");
432 V.push_back(MBRef);
433 }
434 if (Err)
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000435 fatal(File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000436 ": Archive::children failed: " + toString(std::move(Err)));
437 return V;
438}
439
440// A helper function for filterBitcodeFiles.
441static bool needsRebuilding(MemoryBufferRef MB) {
442 // The MSVC linker doesn't support thin archives, so if it's a thin
443 // archive, we always need to rebuild it.
444 std::unique_ptr<Archive> File =
445 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
446 if (File->isThin())
447 return true;
448
449 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000450 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000451 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
452 return true;
453 return false;
454}
455
456// Opens a given path as an archive file and removes bitcode files
457// from them if exists. This function is to appease the MSVC linker as
458// their linker doesn't like archive files containing non-native
459// object files.
460//
461// If a given archive doesn't contain bitcode files, the archive path
462// is returned as-is. Otherwise, a new temporary file is created and
463// its path is returned.
464static Optional<std::string>
465filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000466 std::unique_ptr<MemoryBuffer> MB = check(
467 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000468 MemoryBufferRef MBRef = MB->getMemBufferRef();
469 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000470
471 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000472 return None;
473 if (Magic != file_magic::archive)
474 return Path.str();
475 if (!needsRebuilding(MBRef))
476 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000477
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000478 log("Creating a temporary archive for " + Path +
479 " to remove bitcode files");
Rui Ueyama9accea62017-03-07 21:26:10 +0000480
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000481 std::unique_ptr<Archive> File =
482 check(Archive::create(MBRef),
483 MBRef.getBufferIdentifier() + ": failed to parse archive");
484
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000485 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000486 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000487 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
488 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000489
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000490 SmallString<128> S;
491 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
492 ".lib", S))
493 fatal(EC, "cannot create a temporary file");
494 std::string Temp = S.str();
495 TemporaryFiles.push_back(Temp);
496
497 std::pair<StringRef, std::error_code> Ret =
498 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
499 /*Deterministics=*/true,
500 /*Thin=*/false);
501 if (Ret.second)
502 error("failed to create a new archive " + S.str() + ": " + Ret.first);
503 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000504}
505
506// Create response file contents and invoke the MSVC linker.
507void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
508 std::string Rsp = "/nologo ";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000509 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000510
511 for (auto *Arg : Args) {
512 switch (Arg->getOption().getID()) {
513 case OPT_linkrepro:
514 case OPT_lldmap:
515 case OPT_lldmap_file:
516 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
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000887 // Set default image base if /base is not given.
888 if (Config->ImageBase == uint64_t(-1))
889 Config->ImageBase = getDefaultImageBase();
890
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000891 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000892 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000893 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
894 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
895 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000896
Rui Ueyama107db552015-08-09 21:01:06 +0000897 // We do not support /guard:cf (control flow protection) yet.
898 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
899 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
900 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
901 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
902
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000903 // This code may add new undefined symbols to the link, which may enqueue more
904 // symbol resolution tasks, so we need to continue executing tasks until we
905 // converge.
906 do {
907 // Windows specific -- if entry point is not found,
908 // search for its mangled names.
909 if (Config->Entry)
910 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000911
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000912 // Windows specific -- Make sure we resolve all dllexported symbols.
913 for (Export &E : Config->Exports) {
914 if (!E.ForwardTo.empty())
915 continue;
916 E.Sym = addUndefined(E.Name);
917 if (!E.Directives)
918 Symtab.mangleMaybe(E.Sym);
919 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000920
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000921 // Add weak aliases. Weak aliases is a mechanism to give remaining
922 // undefined symbols final chance to be resolved successfully.
923 for (auto Pair : Config->AlternateNames) {
924 StringRef From = Pair.first;
925 StringRef To = Pair.second;
926 Symbol *Sym = Symtab.find(From);
927 if (!Sym)
928 continue;
929 if (auto *U = dyn_cast<Undefined>(Sym->body()))
930 if (!U->WeakAlias)
931 U->WeakAlias = Symtab.addUndefined(To);
932 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000933
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000934 // Windows specific -- if __load_config_used can be resolved, resolve it.
935 if (Symtab.findUnderscore("_load_config_used"))
936 addUndefined(mangle("_load_config_used"));
937 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000938
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000939 // If /msvclto is given, we use the MSVC linker to link LTO output files.
940 // This is useful because MSVC link.exe can generate complete PDBs.
941 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000942 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000943 exit(0);
944 }
945
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000946 // Do LTO by compiling bitcode input files to a set of native COFF files then
947 // link those files.
948 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000949 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000950
Peter Collingbourne2612a322015-07-04 05:28:41 +0000951 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000952 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000953
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000954 // Windows specific -- if no /subsystem is given, we need to infer
955 // that from entry point name.
956 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000957 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000958 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000959 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000960 }
961
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000962 // Handle /safeseh.
David Blaikie4cdfe692017-02-19 02:25:47 +0000963 if (Args.hasArg(OPT_safeseh))
Rui Ueyama13563d82015-09-15 00:33:11 +0000964 for (ObjectFile *File : Symtab.ObjectFiles)
965 if (!File->SEHCompat)
David Blaikie4cdfe692017-02-19 02:25:47 +0000966 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000967
Rui Ueyama151d8622015-06-17 20:40:43 +0000968 // Windows specific -- when we are creating a .dll file, we also
969 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000970 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000971 fixupExports();
972 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000973 assignExportOrdinals();
974 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000975
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000976 // Windows specific -- Create a side-by-side manifest file.
977 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000978 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000979
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000980 // Identify unreferenced COMDAT sections.
981 if (Config->DoGC)
982 markLive(Symtab.getChunks());
983
984 // Identify identical COMDAT sections to merge them.
985 if (Config->DoICF)
986 doICF(Symtab.getChunks());
987
Rui Ueyama411c63602015-05-28 19:09:30 +0000988 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000989 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000990
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000991 // Call exit to avoid calling destructors.
992 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000993}
994
Rui Ueyama411c63602015-05-28 19:09:30 +0000995} // namespace coff
996} // namespace lld