blob: 8b5eb40ec36de31ee8a228f89ad28e19115a804b [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
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000478 std::unique_ptr<Archive> File =
479 check(Archive::create(MBRef),
480 MBRef.getBufferIdentifier() + ": failed to parse archive");
481
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000482 std::vector<NewArchiveMember> New;
Peter Collingbournea6ffbdd2017-03-17 02:03:20 +0000483 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000484 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
485 New.emplace_back(Member);
Rui Ueyamae0341db2017-03-07 19:45:53 +0000486
Peter Collingbournedb7447d2017-03-17 02:04:22 +0000487 if (New.empty())
488 return None;
489
490 log("Creating a temporary archive for " + Path + " to remove bitcode files");
491
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000492 SmallString<128> S;
493 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path),
494 ".lib", S))
495 fatal(EC, "cannot create a temporary file");
496 std::string Temp = S.str();
497 TemporaryFiles.push_back(Temp);
498
499 std::pair<StringRef, std::error_code> Ret =
500 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
501 /*Deterministics=*/true,
502 /*Thin=*/false);
503 if (Ret.second)
504 error("failed to create a new archive " + S.str() + ": " + Ret.first);
505 return Temp;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000506}
507
508// Create response file contents and invoke the MSVC linker.
509void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
510 std::string Rsp = "/nologo ";
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000511 std::vector<std::string> Temps;
Rui Ueyama85d54b02017-02-23 00:26:42 +0000512
513 for (auto *Arg : Args) {
514 switch (Arg->getOption().getID()) {
515 case OPT_linkrepro:
516 case OPT_lldmap:
517 case OPT_lldmap_file:
Peter Collingbourne8713bf62017-03-17 02:11:09 +0000518 case OPT_lldsavetemps:
Rui Ueyama85d54b02017-02-23 00:26:42 +0000519 case OPT_msvclto:
520 // LLD-specific options are stripped.
521 break;
522 case OPT_opt:
523 if (!StringRef(Arg->getValue()).startswith("lld"))
524 Rsp += toString(Arg) + " ";
525 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000526 case OPT_INPUT: {
527 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
528 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
529 Rsp += quote(*S) + " ";
530 continue;
531 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000532 Rsp += quote(Arg->getValue()) + " ";
533 break;
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000534 }
Rui Ueyama85d54b02017-02-23 00:26:42 +0000535 default:
536 Rsp += toString(Arg) + " ";
537 }
538 }
539
540 std::vector<StringRef> ObjectFiles = Symtab.compileBitcodeFiles();
541 runMSVCLinker(Rsp, ObjectFiles);
Rui Ueyamae1bf1362017-03-16 21:19:36 +0000542
543 for (StringRef Path : Temps)
544 sys::fs::remove(Path);
Rui Ueyama85d54b02017-02-23 00:26:42 +0000545}
546
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000547void LinkerDriver::enqueueTask(std::function<void()> Task) {
548 TaskQueue.push_back(std::move(Task));
549}
550
551bool LinkerDriver::run() {
552 bool DidWork = !TaskQueue.empty();
553 while (!TaskQueue.empty()) {
554 TaskQueue.front()();
555 TaskQueue.pop_front();
556 }
557 return DidWork;
558}
559
Rui Ueyama8fe17672016-12-08 20:50:47 +0000560void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000561 // If the first command line argument is "/lib", link.exe acts like lib.exe.
562 // We call our own implementation of lib.exe that understands bitcode files.
563 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
564 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000565 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000566 return;
567 }
568
Peter Collingbourne60c16162015-06-01 20:10:10 +0000569 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000570 InitializeAllTargetInfos();
571 InitializeAllTargets();
572 InitializeAllTargetMCs();
573 InitializeAllAsmParsers();
574 InitializeAllAsmPrinters();
575 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000576
Rui Ueyama411c63602015-05-28 19:09:30 +0000577 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000578 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000579
Rui Ueyama5c726432015-05-29 16:11:52 +0000580 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000581 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000582 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000583 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000584 }
585
Peter Collingbournefeee2102016-07-26 02:00:42 +0000586 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
587 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000588 sys::path::append(Path, "repro.tar");
589
590 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
591 TarWriter::create(Path, "repro");
592
593 if (ErrOrWriter) {
594 Tar = std::move(*ErrOrWriter);
595 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000596 error("/linkrepro: failed to open " + Path + ": " +
597 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000598 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000599 }
600
Rafael Espindolab835ae82015-08-06 14:58:50 +0000601 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000602 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000603
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000604 // Construct search path list.
605 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000606 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000607 SearchPaths.push_back(Arg->getValue());
608 addLibSearchPaths();
609
Rui Ueyamaad660982015-06-07 00:20:32 +0000610 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000611 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000612 Config->OutputFile = Arg->getValue();
613
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000614 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000615 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000616 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000617
Rui Ueyama95925fd2015-06-28 19:35:15 +0000618 // Handle /force or /force:unresolved
619 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
620 Config->Force = true;
621
Rui Ueyama6600eb12015-07-04 23:37:32 +0000622 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000623 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000624 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000625 Config->DebugTypes =
626 Args.hasArg(OPT_debugtype)
627 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
628 : getDefaultDebugType(Args);
629 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000630
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000631 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000632 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000633 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000634
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000635 // Handle /noentry
636 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000637 if (!Args.hasArg(OPT_dll))
David Blaikie4cdfe692017-02-19 02:25:47 +0000638 fatal("/noentry must be specified with /dll");
639 Config->NoEntry = true;
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000640 }
641
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000642 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000643 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000644 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000645 Config->ManifestID = 2;
646 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000647
Rui Ueyama588e8322015-06-15 01:23:58 +0000648 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000649 if (Args.hasArg(OPT_fixed)) {
David Blaikie4cdfe692017-02-19 02:25:47 +0000650 if (Args.hasArg(OPT_dynamicbase))
651 fatal("/fixed must not be specified with /dynamicbase");
652 Config->Relocatable = false;
653 Config->DynamicBase = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000654 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000655
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000656 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000657 if (auto *Arg = Args.getLastArg(OPT_machine))
658 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000659
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000660 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000661 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000662 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
663
664 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000665 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000666 Config->NoDefaultLibAll = true;
667
Rui Ueyama804a8b62015-05-29 16:18:15 +0000668 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000669 if (auto *Arg = Args.getLastArg(OPT_base))
670 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000671
672 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000673 if (auto *Arg = Args.getLastArg(OPT_stack))
674 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000675
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000676 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000677 if (auto *Arg = Args.getLastArg(OPT_heap))
678 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000679
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000680 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000681 if (auto *Arg = Args.getLastArg(OPT_version))
682 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
683 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000684
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000685 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000686 if (auto *Arg = Args.getLastArg(OPT_subsystem))
687 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
688 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000689
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000690 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000691 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000692 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000693
Rui Ueyama08d5e182015-06-18 23:20:11 +0000694 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000695 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000696 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000697
Rui Ueyamab95188c2015-06-18 20:27:09 +0000698 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000699 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000700 Config->Implib = Arg->getValue();
701
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000702 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000703 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000704 std::string Str = StringRef(Arg->getValue()).lower();
705 SmallVector<StringRef, 1> Vec;
706 StringRef(Str).split(Vec, ',');
707 for (StringRef S : Vec) {
708 if (S == "noref") {
709 Config->DoGC = false;
710 Config->DoICF = false;
711 continue;
712 }
713 if (S == "icf" || StringRef(S).startswith("icf=")) {
714 Config->DoICF = true;
715 continue;
716 }
717 if (S == "noicf") {
718 Config->DoICF = false;
719 continue;
720 }
721 if (StringRef(S).startswith("lldlto=")) {
722 StringRef OptLevel = StringRef(S).substr(7);
723 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
724 Config->LTOOptLevel > 3)
David Blaikie4cdfe692017-02-19 02:25:47 +0000725 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000726 continue;
727 }
728 if (StringRef(S).startswith("lldltojobs=")) {
729 StringRef Jobs = StringRef(S).substr(11);
730 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000731 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000732 continue;
733 }
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000734 if (StringRef(S).startswith("lldltopartitions=")) {
735 StringRef N = StringRef(S).substr(17);
736 if (N.getAsInteger(10, Config->LTOPartitions) ||
737 Config->LTOPartitions == 0)
David Blaikie4cdfe692017-02-19 02:25:47 +0000738 fatal("/opt:lldltopartitions: invalid partition count: " + N);
Bob Haarmancde5e5b2017-02-02 23:58:14 +0000739 continue;
740 }
Rui Ueyama75656ee2015-10-19 19:40:43 +0000741 if (S != "ref" && S != "lbr" && S != "nolbr")
David Blaikie4cdfe692017-02-19 02:25:47 +0000742 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000743 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000744 }
745
Bob Haarman69b196d2017-02-08 18:36:41 +0000746 // Handle /lldsavetemps
747 if (Args.hasArg(OPT_lldsavetemps))
748 Config->SaveTemps = true;
749
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000750 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000751 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000752 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000753
Rui Ueyama6600eb12015-07-04 23:37:32 +0000754 // Handle /merge
755 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000756 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000757
Rui Ueyama440138c2016-06-20 03:39:39 +0000758 // Handle /section
759 for (auto *Arg : Args.filtered(OPT_section))
760 parseSection(Arg->getValue());
761
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000762 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000763 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
764 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000765
766 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000767 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
768 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000769
770 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000771 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000772 Config->ManifestDependency = Arg->getValue();
773
774 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000775 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000776 Config->ManifestFile = Arg->getValue();
777
Rui Ueyamaafb19012016-04-19 01:21:58 +0000778 // Handle /manifestinput
779 for (auto *Arg : Args.filtered(OPT_manifestinput))
780 Config->ManifestInput.push_back(Arg->getValue());
781
Rui Ueyama6592ff82015-06-16 23:13:00 +0000782 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000783 if (Args.hasArg(OPT_allowbind_no))
784 Config->AllowBind = false;
785 if (Args.hasArg(OPT_allowisolation_no))
786 Config->AllowIsolation = false;
787 if (Args.hasArg(OPT_dynamicbase_no))
788 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000789 if (Args.hasArg(OPT_nxcompat_no))
790 Config->NxCompat = false;
791 if (Args.hasArg(OPT_tsaware_no))
792 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000793 if (Args.hasArg(OPT_nosymtab))
794 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000795 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000796 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000797
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +0000798 Config->MapFile = getMapFile(Args);
799
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000800 // Create a list of input files. Files can be given as arguments
801 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000802 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000803 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000804 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000805 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000806 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000807 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000808 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000809
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000810 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000811 if (Config->Manifest == Configuration::Embed)
812 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000813
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000814 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000815 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000816
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000817 // We should have inferred a machine type by now from the input files, but if
818 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000819 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000820 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +0000821 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000822 }
823
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000824 // Windows specific -- Input files can be Windows resource files (.res files).
825 // We invoke cvtres.exe to convert resource files to a regular COFF file
826 // then link the result file normally.
827 if (!Resources.empty())
828 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000829
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000830 if (Tar)
831 Tar->append("response.txt",
832 createResponseFile(Args, FilePaths,
833 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000834
Rui Ueyama4d545342015-07-28 03:12:00 +0000835 // Handle /largeaddressaware
836 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
837 Config->LargeAddressAware = true;
838
Rui Ueyamad68e2112015-07-28 03:15:57 +0000839 // Handle /highentropyva
840 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
841 Config->HighEntropyVA = true;
842
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000843 // Handle /entry and /dll
844 if (auto *Arg = Args.getLastArg(OPT_entry)) {
845 Config->Entry = addUndefined(mangle(Arg->getValue()));
846 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000847 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
848 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000849 Config->Entry = addUndefined(S);
850 } else if (!Config->NoEntry) {
851 // Windows specific -- If entry point name is not given, we need to
852 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000853 StringRef S = findDefaultEntry();
David Blaikie4cdfe692017-02-19 02:25:47 +0000854 if (S.empty())
855 fatal("entry point must be defined");
856 Config->Entry = addUndefined(S);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000857 log("Entry name inferred: " + S);
Rui Ueyama45044f42015-06-29 01:03:53 +0000858 }
859
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000860 // Handle /export
861 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000862 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000863 if (Config->Machine == I386) {
864 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000865 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000866 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000867 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000868 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000869 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000870 }
871
872 // Handle /def
873 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000874 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000875 parseModuleDefs(
876 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
877 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000878 }
879
Rui Ueyama6d249082015-07-13 22:31:45 +0000880 // Handle /delayload
881 for (auto *Arg : Args.filtered(OPT_delayload)) {
882 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000883 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000884 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000885 } else {
886 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000887 }
888 }
889
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000890 // Set default image base if /base is not given.
891 if (Config->ImageBase == uint64_t(-1))
892 Config->ImageBase = getDefaultImageBase();
893
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000894 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000895 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000896 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
897 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
898 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000899
Rui Ueyama107db552015-08-09 21:01:06 +0000900 // We do not support /guard:cf (control flow protection) yet.
901 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
902 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
903 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
904 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
905
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000906 // This code may add new undefined symbols to the link, which may enqueue more
907 // symbol resolution tasks, so we need to continue executing tasks until we
908 // converge.
909 do {
910 // Windows specific -- if entry point is not found,
911 // search for its mangled names.
912 if (Config->Entry)
913 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000914
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000915 // Windows specific -- Make sure we resolve all dllexported symbols.
916 for (Export &E : Config->Exports) {
917 if (!E.ForwardTo.empty())
918 continue;
919 E.Sym = addUndefined(E.Name);
920 if (!E.Directives)
921 Symtab.mangleMaybe(E.Sym);
922 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000923
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000924 // Add weak aliases. Weak aliases is a mechanism to give remaining
925 // undefined symbols final chance to be resolved successfully.
926 for (auto Pair : Config->AlternateNames) {
927 StringRef From = Pair.first;
928 StringRef To = Pair.second;
929 Symbol *Sym = Symtab.find(From);
930 if (!Sym)
931 continue;
932 if (auto *U = dyn_cast<Undefined>(Sym->body()))
933 if (!U->WeakAlias)
934 U->WeakAlias = Symtab.addUndefined(To);
935 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000936
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000937 // Windows specific -- if __load_config_used can be resolved, resolve it.
938 if (Symtab.findUnderscore("_load_config_used"))
939 addUndefined(mangle("_load_config_used"));
940 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000941
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000942 // If /msvclto is given, we use the MSVC linker to link LTO output files.
943 // This is useful because MSVC link.exe can generate complete PDBs.
944 if (Args.hasArg(OPT_msvclto)) {
Rui Ueyama85d54b02017-02-23 00:26:42 +0000945 invokeMSVC(Args);
Rui Ueyama1e0b1582017-02-06 20:47:55 +0000946 exit(0);
947 }
948
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000949 // Do LTO by compiling bitcode input files to a set of native COFF files then
950 // link those files.
951 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000952 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000953
Peter Collingbourne2612a322015-07-04 05:28:41 +0000954 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000955 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000956
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000957 // Windows specific -- if no /subsystem is given, we need to infer
958 // that from entry point name.
959 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000960 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000961 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000962 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000963 }
964
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000965 // Handle /safeseh.
David Blaikie4cdfe692017-02-19 02:25:47 +0000966 if (Args.hasArg(OPT_safeseh))
Rui Ueyama13563d82015-09-15 00:33:11 +0000967 for (ObjectFile *File : Symtab.ObjectFiles)
968 if (!File->SEHCompat)
David Blaikie4cdfe692017-02-19 02:25:47 +0000969 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000970
Rui Ueyama151d8622015-06-17 20:40:43 +0000971 // Windows specific -- when we are creating a .dll file, we also
972 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000973 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000974 fixupExports();
975 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000976 assignExportOrdinals();
977 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000978
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000979 // Windows specific -- Create a side-by-side manifest file.
980 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000981 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000982
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000983 // Identify unreferenced COMDAT sections.
984 if (Config->DoGC)
985 markLive(Symtab.getChunks());
986
987 // Identify identical COMDAT sections to merge them.
988 if (Config->DoICF)
989 doICF(Symtab.getChunks());
990
Rui Ueyama411c63602015-05-28 19:09:30 +0000991 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000992 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000993
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000994 // Call exit to avoid calling destructors.
995 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000996}
997
Rui Ueyama411c63602015-05-28 19:09:30 +0000998} // namespace coff
999} // namespace lld