blob: 971d94cf6925406ad538f731e7b32aecf5f8853f [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);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +000062 return !ErrorCount;
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));
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000124
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000125 if (Magic == file_magic::coff_cl_gl_object)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000126 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000127 "Recompile without /GL");
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000128 else
129 Symtab.addFile(make<ObjectFile>(MBRef));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000130}
131
132void LinkerDriver::enqueuePath(StringRef Path) {
133 auto Future =
134 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
135 std::string PathStr = Path;
136 enqueueTask([=]() {
137 auto MBOrErr = Future->get();
138 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000139 error("could not open " + PathStr + ": " + MBOrErr.second.message());
140 else
141 Driver->addBuffer(std::move(MBOrErr.first));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000142 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000143}
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;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000154 if (Magic == file_magic::coff_object) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000155 Obj = make<ObjectFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000156 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000157 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000158 } else {
159 error("unknown file type: " + MB.getBufferIdentifier());
160 return;
161 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000162
163 Obj->ParentName = ParentName;
164 Symtab.addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000165 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000166}
167
168void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
169 StringRef SymName,
170 StringRef ParentName) {
171 if (!C.getParent()->isThin()) {
172 MemoryBufferRef MB = check(
173 C.getMemoryBufferRef(),
174 "could not get the buffer for the member defining symbol " + SymName);
175 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
176 return;
177 }
178
179 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
180 check(C.getFullName(),
181 "could not get the filename for the member defining symbol " +
182 SymName)));
183 enqueueTask([=]() {
184 auto MBOrErr = Future->get();
185 if (MBOrErr.second)
186 fatal(MBOrErr.second,
187 "could not get the buffer for the member defining " + SymName);
188 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
189 ParentName);
190 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000191}
192
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000193static bool isDecorated(StringRef Sym) {
194 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
195}
196
Rui Ueyama411c63602015-05-28 19:09:30 +0000197// Parses .drectve section contents and returns a list of files
198// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000199void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000200 opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +0000201
David Blaikie6521ed92015-06-22 22:06:52 +0000202 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +0000203 switch (Arg->getOption().getID()) {
204 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000205 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000206 break;
207 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000208 if (Optional<StringRef> Path = findLib(Arg->getValue()))
209 enqueuePath(*Path);
Rui Ueyama562daa82015-06-18 21:50:38 +0000210 break;
211 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000212 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000213 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000214 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000215 break;
216 }
217 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000218 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000219 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000220 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000221 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000222 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000223 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000224 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000225 break;
226 case OPT_nodefaultlib:
227 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
228 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000229 case OPT_section:
230 parseSection(Arg->getValue());
231 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000232 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000233 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000234 case OPT_guardsym:
Rui Ueyama432383172015-07-29 21:01:15 +0000235 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000236 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000237 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000238 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000239 }
240 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000241}
242
Rui Ueyama54b71da2015-05-31 19:17:12 +0000243// Find file from search paths. You can omit ".obj", this function takes
244// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000245StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000246 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
247 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000248 return Filename;
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000249 bool HasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000250 for (StringRef Dir : SearchPaths) {
251 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000252 sys::path::append(Path, Filename);
253 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000254 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000255 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000256 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000257 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000258 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000259 }
260 }
261 return Filename;
262}
263
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000264// Resolves a file path. This never returns the same path
265// (in that case, it returns None).
266Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
267 StringRef Path = doFindFile(Filename);
268 bool Seen = !VisitedFiles.insert(Path.lower()).second;
269 if (Seen)
270 return None;
271 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000272}
273
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000274// Find library file from search path.
275StringRef LinkerDriver::doFindLib(StringRef Filename) {
276 // Add ".lib" to Filename if that has no file extension.
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000277 bool HasExt = (Filename.find('.') != StringRef::npos);
278 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000279 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000280 return doFindFile(Filename);
281}
282
283// Resolves a library path. /nodefaultlib options are taken into
284// consideration. This never returns the same path (in that case,
285// it returns None).
286Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
287 if (Config->NoDefaultLibAll)
288 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000289 if (!VisitedLibs.insert(Filename.lower()).second)
290 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000291 StringRef Path = doFindLib(Filename);
292 if (Config->NoDefaultLibs.count(Path))
293 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000294 if (!VisitedFiles.insert(Path.lower()).second)
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000295 return None;
296 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000297}
298
299// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000300void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000301 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
302 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000303 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000304 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000305 while (!Env.empty()) {
306 StringRef Path;
307 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000308 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000309 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000310}
311
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000312SymbolBody *LinkerDriver::addUndefined(StringRef Name) {
313 SymbolBody *B = Symtab.addUndefined(Name);
314 Config->GCRoot.insert(B);
315 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000316}
317
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000318// Symbol names are mangled by appending "_" prefix on x86.
319StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000320 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
321 if (Config->Machine == I386)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000322 return Saver.save("_" + Sym);
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000323 return Sym;
324}
325
Rui Ueyama45044f42015-06-29 01:03:53 +0000326// Windows specific -- find default entry point name.
327StringRef LinkerDriver::findDefaultEntry() {
328 // User-defined main functions and their corresponding entry points.
329 static const char *Entries[][2] = {
330 {"main", "mainCRTStartup"},
331 {"wmain", "wmainCRTStartup"},
332 {"WinMain", "WinMainCRTStartup"},
333 {"wWinMain", "wWinMainCRTStartup"},
334 };
335 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000336 StringRef Entry = Symtab.findMangle(mangle(E[0]));
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000337 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->body()))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000338 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000339 }
340 return "";
341}
342
343WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000344 if (Config->DLL)
345 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000346 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000347 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000348 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000349 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
350 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000351}
352
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000353static uint64_t getDefaultImageBase() {
354 if (Config->is64())
355 return Config->DLL ? 0x180000000 : 0x140000000;
356 return Config->DLL ? 0x10000000 : 0x400000;
357}
358
Rui Ueyama8fe17672016-12-08 20:50:47 +0000359static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000360 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000361 ArrayRef<StringRef> SearchPaths) {
362 SmallString<0> Data;
363 raw_svector_ostream OS(Data);
364
365 for (auto *Arg : Args) {
366 switch (Arg->getOption().getID()) {
367 case OPT_linkrepro:
368 case OPT_INPUT:
369 case OPT_defaultlib:
370 case OPT_libpath:
371 break;
372 default:
Rui Ueyamab4c63ca2017-01-06 10:04:35 +0000373 OS << toString(Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000374 }
375 }
376
377 for (StringRef Path : SearchPaths) {
378 std::string RelPath = relativeToRoot(Path);
379 OS << "/libpath:" << quote(RelPath) << "\n";
380 }
381
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000382 for (StringRef Path : FilePaths)
383 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000384
385 return Data.str();
386}
387
Rui Ueyama8fe17672016-12-08 20:50:47 +0000388static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000389 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
390 if (Args.hasArg(OPT_driver))
391 DebugTypes |= static_cast<unsigned>(DebugType::PData);
392 if (Args.hasArg(OPT_profile))
393 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
394 return DebugTypes;
395}
396
397static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000398 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000399 Arg.split(Types, ',', /*KeepEmpty=*/false);
400
401 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
402 for (StringRef Type : Types)
403 DebugTypes |= StringSwitch<unsigned>(Type.lower())
404 .Case("cv", static_cast<unsigned>(DebugType::CV))
405 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000406 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
407 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000408 return DebugTypes;
409}
410
Hans Wennborg1818e652016-12-09 20:54:44 +0000411static std::string getMapFile(const opt::InputArgList &Args) {
412 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
413 if (!Arg)
414 return "";
415 if (Arg->getOption().getID() == OPT_lldmap_file)
416 return Arg->getValue();
417
418 assert(Arg->getOption().getID() == OPT_lldmap);
419 StringRef OutFile = Config->OutputFile;
420 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
421}
422
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000423std::vector<MemoryBufferRef> getArchiveMembers(Archive *File) {
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000424 std::vector<MemoryBufferRef> V;
425 Error Err = Error::success();
426 for (const ErrorOr<Archive::Child> &COrErr : File->children(Err)) {
427 Archive::Child C =
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000428 check(COrErr,
429 File->getFileName() + ": could not get the child of the archive");
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000430 MemoryBufferRef MBRef =
431 check(C.getMemoryBufferRef(),
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000432 File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000433 ": could not get the buffer for a child of the archive");
434 V.push_back(MBRef);
435 }
436 if (Err)
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000437 fatal(File->getFileName() +
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000438 ": Archive::children failed: " + toString(std::move(Err)));
439 return V;
440}
441
442// A helper function for filterBitcodeFiles.
443static bool needsRebuilding(MemoryBufferRef MB) {
444 // The MSVC linker doesn't support thin archives, so if it's a thin
445 // archive, we always need to rebuild it.
446 std::unique_ptr<Archive> File =
447 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
448 if (File->isThin())
449 return true;
450
451 // Returns true if the archive contains at least one bitcode file.
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000452 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000453 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
454 return true;
455 return false;
456}
457
458// Opens a given path as an archive file and removes bitcode files
459// from them if exists. This function is to appease the MSVC linker as
460// their linker doesn't like archive files containing non-native
461// object files.
462//
463// If a given archive doesn't contain bitcode files, the archive path
464// is returned as-is. Otherwise, a new temporary file is created and
465// its path is returned.
466static Optional<std::string>
467filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000468 std::unique_ptr<MemoryBuffer> MB = check(
469 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000470 MemoryBufferRef MBRef = MB->getMemBufferRef();
471 file_magic Magic = identify_magic(MBRef.getBuffer());
Rui Ueyamae0341db2017-03-07 19:45:53 +0000472
473 if (Magic == file_magic::bitcode)
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000474 return None;
475 if (Magic != file_magic::archive)
476 return Path.str();
477 if (!needsRebuilding(MBRef))
478 return Path.str();
Rui Ueyamae0341db2017-03-07 19:45:53 +0000479
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000480 std::unique_ptr<Archive> File =
481 check(Archive::create(MBRef),
482 MBRef.getBufferIdentifier() + ": failed to parse archive");
483
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000484 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000485 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000486 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
487 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000488
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000489 if (New.empty())
490 return None;
491
492 log("Creating a temporary archive for " + Path + " to remove bitcode files");
493
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000494 SmallString<128> S;
495 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
496 ".lib", S))
497 fatal(EC, "cannot create a temporary file");
498 std::string Temp = S.str();
499 TemporaryFiles.push_back(Temp);
500
501 std::pair<StringRef, std::error_code> Ret =
502 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
503 /*Deterministics=*/true,
504 /*Thin=*/false);
505 if (Ret.second)
506 error("failed to create a new archive " + S.str() + ": " + Ret.first);
507 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000508}
509
510// Create response file contents and invoke the MSVC linker.
511void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
512 std::string Rsp = "/nologo ";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000513 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000514
515 for (auto *Arg : Args) {
516 switch (Arg->getOption().getID()) {
517 case OPT_linkrepro:
518 case OPT_lldmap:
519 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000520 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000521 case OPT_msvclto:
522 // LLD-specific options are stripped.
523 break;
524 case OPT_opt:
525 if (!StringRef(Arg->getValue()).startswith("lld"))
526 Rsp += toString(Arg) + " ";
527 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000528 case OPT_INPUT: {
529 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
530 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
531 Rsp += quote(*S) + " ";
532 continue;
533 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000534 Rsp += quote(Arg->getValue()) + " ";
535 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000536 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000537 default:
538 Rsp += toString(Arg) + " ";
539 }
540 }
541
542 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
543 runMSVCLinker(Rsp, ObjectFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000544
545 for (StringRef Path : Temps)
546 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000547}
548
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000549void LinkerDriver::enqueueTask(std::function<void()> Task) {
550 TaskQueue.push_back(std::move(Task));
551}
552
553bool LinkerDriver::run() {
554 bool DidWork = !TaskQueue.empty();
555 while (!TaskQueue.empty()) {
556 TaskQueue.front()();
557 TaskQueue.pop_front();
558 }
559 return DidWork;
560}
561
Rui Ueyama8fe17672016-12-08 20:50:47 +0000562void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000563 // If the first command line argument is "/lib", link.exe acts like lib.exe.
564 // We call our own implementation of lib.exe that understands bitcode files.
565 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
566 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000567 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000568 return;
569 }
570
Peter Collingbourne60c16162015-06-01 20:10:10 +0000571 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000572 InitializeAllTargetInfos();
573 InitializeAllTargets();
574 InitializeAllTargetMCs();
575 InitializeAllAsmParsers();
576 InitializeAllAsmPrinters();
577 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000578
Rui Ueyama411c63602015-05-28 19:09:30 +0000579 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000580 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000581
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000582 // Parse and evaluate -mllvm options.
583 std::vector<const char *> V;
584 V.push_back("lld-link (LLVM option parsing)");
585 for (auto *Arg : Args.filtered(OPT_mllvm))
586 V.push_back(Arg->getValue());
587 cl::ParseCommandLineOptions(V.size(), V.data());
588
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000589 // Handle /errorlimit early, because error() depends on it.
590 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
591 int N = 20;
592 StringRef S = Arg->getValue();
593 if (S.getAsInteger(10, N))
594 error(Arg->getSpelling() + " number expected, but got " + S);
595 Config->ErrorLimit = N;
596 }
597
Rui Ueyama5c726432015-05-29 16:11:52 +0000598 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000599 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000600 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000601 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000602 }
603
Peter Collingbournefeee2102016-07-26 02:00:42 +0000604 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
605 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000606 sys::path::append(Path, "repro.tar");
607
608 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
609 TarWriter::create(Path, "repro");
610
611 if (ErrOrWriter) {
612 Tar = std::move(*ErrOrWriter);
613 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000614 error("/linkrepro: failed to open " + Path + ": " +
615 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000616 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000617 }
618
Rafael Espindolab835ae82015-08-06 14:58:50 +0000619 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000620 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000621
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000622 // Construct search path list.
623 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000624 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000625 SearchPaths.push_back(Arg->getValue());
626 addLibSearchPaths();
627
Rui Ueyamaad660982015-06-07 00:20:32 +0000628 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000629 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000630 Config->OutputFile = Arg->getValue();
631
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000632 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000633 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000634 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000635
Rui Ueyama95925fd2015-06-28 19:35:15 +0000636 // Handle /force or /force:unresolved
637 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
638 Config->Force = true;
639
Rui Ueyama6600eb12015-07-04 23:37:32 +0000640 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000641 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000642 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000643 Config->DebugTypes =
644 Args.hasArg(OPT_debugtype)
645 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
646 : getDefaultDebugType(Args);
647 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000648
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000649 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000650 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000651 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000652
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000653 // Handle /noentry
654 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000655 if (Args.hasArg(OPT_dll))
656 Config->NoEntry = true;
657 else
658 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000659 }
660
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000661 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000662 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000663 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000664 Config->ManifestID = 2;
665 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000666
Rui Ueyama588e8322015-06-15 01:23:58 +0000667 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000668 if (Args.hasArg(OPT_fixed)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000669 if (Args.hasArg(OPT_dynamicbase)) {
670 error("/fixed must not be specified with /dynamicbase");
671 } else {
672 Config->Relocatable = false;
673 Config->DynamicBase = false;
674 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000675 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000676
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000677 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000678 if (auto *Arg = Args.getLastArg(OPT_machine))
679 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000680
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000681 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000682 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000683 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
684
685 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000686 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000687 Config->NoDefaultLibAll = true;
688
Rui Ueyama804a8b62015-05-29 16:18:15 +0000689 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000690 if (auto *Arg = Args.getLastArg(OPT_base))
691 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000692
693 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000694 if (auto *Arg = Args.getLastArg(OPT_stack))
695 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000696
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000697 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000698 if (auto *Arg = Args.getLastArg(OPT_heap))
699 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000700
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000701 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000702 if (auto *Arg = Args.getLastArg(OPT_version))
703 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
704 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000705
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000706 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000707 if (auto *Arg = Args.getLastArg(OPT_subsystem))
708 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
709 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000710
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000711 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000712 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000713 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000714
Rui Ueyama08d5e182015-06-18 23:20:11 +0000715 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000716 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000717 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000718
Rui Ueyamab95188c2015-06-18 20:27:09 +0000719 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000720 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000721 Config->Implib = Arg->getValue();
722
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000723 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000724 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000725 std::string Str = StringRef(Arg->getValue()).lower();
726 SmallVector<StringRef, 1> Vec;
727 StringRef(Str).split(Vec, ',');
728 for (StringRef S : Vec) {
729 if (S == "noref") {
730 Config->DoGC = false;
731 Config->DoICF = false;
732 continue;
733 }
734 if (S == "icf" || StringRef(S).startswith("icf=")) {
735 Config->DoICF = true;
736 continue;
737 }
738 if (S == "noicf") {
739 Config->DoICF = false;
740 continue;
741 }
742 if (StringRef(S).startswith("lldlto=")) {
743 StringRef OptLevel = StringRef(S).substr(7);
744 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
745 Config->LTOOptLevel > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000746 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000747 continue;
748 }
749 if (StringRef(S).startswith("lldltojobs=")) {
750 StringRef Jobs = StringRef(S).substr(11);
751 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000752 error("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000753 continue;
754 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000755 if (StringRef(S).startswith("lldltopartitions=")) {
756 StringRef N = StringRef(S).substr(17);
757 if (N.getAsInteger(10, Config->LTOPartitions) ||
758 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000759 error("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000760 continue;
761 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000762 if (S != "ref" && S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000763 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000764 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000765 }
766
Bob Haarman69b196d2017-02-08 18:36:41 +0000767 // Handle /lldsavetemps
768 if (Args.hasArg(OPT_lldsavetemps))
769 Config->SaveTemps = true;
770
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000771 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000772 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000773 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000774
Rui Ueyama6600eb12015-07-04 23:37:32 +0000775 // Handle /merge
776 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000777 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000778
Rui Ueyama440138c2016-06-20 03:39:39 +0000779 // Handle /section
780 for (auto *Arg : Args.filtered(OPT_section))
781 parseSection(Arg->getValue());
782
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000783 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000784 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
785 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000786
787 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000788 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
789 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000790
791 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000792 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000793 Config->ManifestDependency = Arg->getValue();
794
795 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000796 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000797 Config->ManifestFile = Arg->getValue();
798
Rui Ueyamaafb19012016-04-19 01:21:58 +0000799 // Handle /manifestinput
800 for (auto *Arg : Args.filtered(OPT_manifestinput))
801 Config->ManifestInput.push_back(Arg->getValue());
802
Rui Ueyama6592ff82015-06-16 23:13:00 +0000803 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000804 if (Args.hasArg(OPT_allowbind_no))
805 Config->AllowBind = false;
806 if (Args.hasArg(OPT_allowisolation_no))
807 Config->AllowIsolation = false;
808 if (Args.hasArg(OPT_dynamicbase_no))
809 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000810 if (Args.hasArg(OPT_nxcompat_no))
811 Config->NxCompat = false;
812 if (Args.hasArg(OPT_tsaware_no))
813 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000814 if (Args.hasArg(OPT_nosymtab))
815 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000816 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000817 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000818
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000819 Config->MapFile = getMapFile(Args);
820
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000821 if (ErrorCount)
822 return;
823
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000824 // Create a list of input files. Files can be given as arguments
825 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000826 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000827 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000828 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000829 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000830 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000831 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000832 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000833
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000834 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000835 if (Config->Manifest == Configuration::Embed)
836 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000837
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000838 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000839 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000840
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000841 // We should have inferred a machine type by now from the input files, but if
842 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000843 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000844 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000845 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000846 }
847
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000848 // Windows specific -- Input files can be Windows resource files (.res files).
849 // We invoke cvtres.exe to convert resource files to a regular COFF file
850 // then link the result file normally.
851 if (!Resources.empty())
852 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000853
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000854 if (Tar)
855 Tar->append("response.txt",
856 createResponseFile(Args, FilePaths,
857 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000858
Rui Ueyama4d545342015-07-28 03:12:00 +0000859 // Handle /largeaddressaware
860 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
861 Config->LargeAddressAware = true;
862
Rui Ueyamad68e2112015-07-28 03:15:57 +0000863 // Handle /highentropyva
864 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
865 Config->HighEntropyVA = true;
866
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000867 // Handle /entry and /dll
868 if (auto *Arg = Args.getLastArg(OPT_entry)) {
869 Config->Entry = addUndefined(mangle(Arg->getValue()));
870 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000871 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
872 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000873 Config->Entry = addUndefined(S);
874 } else if (!Config->NoEntry) {
875 // Windows specific -- If entry point name is not given, we need to
876 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000877 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +0000878 if (S.empty())
879 fatal("entry point must be defined");
880 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000881 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +0000882 }
883
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000884 // Handle /export
885 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000886 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000887 if (Config->Machine == I386) {
888 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000889 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000890 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000891 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000892 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000893 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000894 }
895
896 // Handle /def
897 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000898 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000899 parseModuleDefs(
900 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
901 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000902 }
903
Rui Ueyama6d249082015-07-13 22:31:45 +0000904 // Handle /delayload
905 for (auto *Arg : Args.filtered(OPT_delayload)) {
906 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000907 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000908 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000909 } else {
910 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000911 }
912 }
913
Reid Kleckner7668182e2017-03-21 00:12:51 +0000914 // Set default image name if neither /out or /def set it.
915 if (Config->OutputFile.empty()) {
916 Config->OutputFile =
917 getOutputPath((*Args.filtered_begin(OPT_INPUT))->getValue());
918 }
919
Reid Kleckner13bdbfb2017-03-22 00:57:14 +0000920 // Put the PDB next to the image if no /pdb flag was passed.
921 if (Config->Debug && Config->PDBPath.empty()) {
922 Config->PDBPath = Config->OutputFile;
923 sys::path::replace_extension(Config->PDBPath, ".pdb");
924 }
925
Reid Kleckner77d3aa42017-03-22 19:49:12 +0000926 // Disable PDB generation if the user requested it.
927 if (Args.hasArg(OPT_nopdb))
928 Config->PDBPath = "";
929
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000930 // Set default image base if /base is not given.
931 if (Config->ImageBase == uint64_t(-1))
932 Config->ImageBase = getDefaultImageBase();
933
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000934 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000935 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000936 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
937 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
938 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000939
Rui Ueyama107db552015-08-09 21:01:06 +0000940 // We do not support /guard:cf (control flow protection) yet.
941 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
942 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
943 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
944 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
945
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000946 // This code may add new undefined symbols to the link, which may enqueue more
947 // symbol resolution tasks, so we need to continue executing tasks until we
948 // converge.
949 do {
950 // Windows specific -- if entry point is not found,
951 // search for its mangled names.
952 if (Config->Entry)
953 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000954
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000955 // Windows specific -- Make sure we resolve all dllexported symbols.
956 for (Export &E : Config->Exports) {
957 if (!E.ForwardTo.empty())
958 continue;
959 E.Sym = addUndefined(E.Name);
960 if (!E.Directives)
961 Symtab.mangleMaybe(E.Sym);
962 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000963
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000964 // Add weak aliases. Weak aliases is a mechanism to give remaining
965 // undefined symbols final chance to be resolved successfully.
966 for (auto Pair : Config->AlternateNames) {
967 StringRef From = Pair.first;
968 StringRef To = Pair.second;
969 Symbol *Sym = Symtab.find(From);
970 if (!Sym)
971 continue;
972 if (auto *U = dyn_cast<Undefined>(Sym->body()))
973 if (!U->WeakAlias)
974 U->WeakAlias = Symtab.addUndefined(To);
975 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000976
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000977 // Windows specific -- if __load_config_used can be resolved, resolve it.
978 if (Symtab.findUnderscore("_load_config_used"))
979 addUndefined(mangle("_load_config_used"));
980 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000981
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000982 if (ErrorCount)
983 return;
984
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000985 // If /msvclto is given, we use the MSVC linker to link LTO output files.
986 // This is useful because MSVC link.exe can generate complete PDBs.
987 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000988 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000989 exit(0);
990 }
991
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000992 // Do LTO by compiling bitcode input files to a set of native COFF files then
993 // link those files.
994 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000995 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000996
Peter Collingbourne2612a322015-07-04 05:28:41 +0000997 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000998 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000999
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001000 // Windows specific -- if no /subsystem is given, we need to infer
1001 // that from entry point name.
1002 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001003 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +00001004 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +00001005 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +00001006 }
1007
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001008 // Handle /safeseh.
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001009 if (Args.hasArg(OPT_safeseh)) {
Rui Ueyama13563d82015-09-15 00:33:11 +00001010 for (ObjectFile *File : Symtab.ObjectFiles)
1011 if (!File->SEHCompat)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001012 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1013 if (ErrorCount)
1014 return;
1015 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001016
Rui Ueyama151d8622015-06-17 20:40:43 +00001017 // Windows specific -- when we are creating a .dll file, we also
1018 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001019 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001020 fixupExports();
1021 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +00001022 assignExportOrdinals();
1023 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001024
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001025 // Windows specific -- Create a side-by-side manifest file.
1026 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001027 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001028
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001029 // Identify unreferenced COMDAT sections.
1030 if (Config->DoGC)
1031 markLive(Symtab.getChunks());
1032
1033 // Identify identical COMDAT sections to merge them.
1034 if (Config->DoICF)
1035 doICF(Symtab.getChunks());
1036
Rui Ueyama411c63602015-05-28 19:09:30 +00001037 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +00001038 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +00001039
Rui Ueyamaa51ce712015-07-03 05:31:35 +00001040 // Call exit to avoid calling destructors.
1041 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +00001042}
1043
Rui Ueyama411c63602015-05-28 19:09:30 +00001044} // namespace coff
1045} // namespace lld