blob: dc3a00ba55ed0b2648e0c1d8c0adab29d7a3ed65 [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 Ueyama411c63602015-05-28 19:09:30 +000022#include "llvm/Option/Arg.h"
23#include "llvm/Option/ArgList.h"
24#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000026#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000027#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000028#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000030#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include <memory>
32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000033#ifdef _MSC_VER
34// <future> depends on <eh.h> for __uncaught_exception.
35#include <eh.h>
36#endif
37
38#include <future>
39
Rui Ueyama411c63602015-05-28 19:09:30 +000040using namespace llvm;
Rui Ueyama84936e02015-07-07 23:39:18 +000041using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000042using llvm::sys::Process;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000043using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000044using llvm::sys::fs::file_magic;
45using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000046
Rui Ueyama3500f662015-05-28 20:30:06 +000047namespace lld {
48namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000051LinkerDriver *Driver;
52
Rui Ueyama9381eb12016-12-18 14:06:06 +000053BumpPtrAllocator BAlloc;
54StringSaver Saver{BAlloc};
55std::vector<SpecificAllocBase *> SpecificAllocBase::Instances;
56
Rui Ueyama8fe17672016-12-08 20:50:47 +000057bool link(ArrayRef<const char *> Args) {
Rui Ueyama7fed58c2016-12-08 19:10:28 +000058 Config = make<Configuration>();
59 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000060 Driver->link(Args);
61 return true;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000062}
Rui Ueyama411c63602015-05-28 19:09:30 +000063
Nico Weber5660de72016-04-20 22:34:15 +000064// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000065static std::string getOutputPath(StringRef Path) {
66 auto P = Path.find_last_of("\\/");
67 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000068 const char* E = Config->DLL ? ".dll" : ".exe";
69 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000070}
71
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000072// ErrorOr is not default constructible, so it cannot be used as the type
73// parameter of a future.
74// FIXME: We could open the file in createFutureForFile and avoid needing to
75// return an error here, but for the moment that would cost us a file descriptor
76// (a limited resource on Windows) for the duration that the future is pending.
77typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
78
79// Create a std::future that opens and maps a file using the best strategy for
80// the host platform.
81static std::future<MBErrPair> createFutureForFile(std::string Path) {
82#if LLVM_ON_WIN32
83 // On Windows, file I/O is relatively slow so it is best to do this
84 // asynchronously.
85 auto Strategy = std::launch::async;
86#else
87 auto Strategy = std::launch::deferred;
88#endif
89 return std::async(Strategy, [=]() {
90 auto MBOrErr = MemoryBuffer::getFile(Path);
91 if (!MBOrErr)
92 return MBErrPair{nullptr, MBOrErr.getError()};
93 return MBErrPair{std::move(*MBOrErr), std::error_code()};
94 });
95}
96
97MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
98 MemoryBufferRef MBRef = *MB;
99 OwningMBs.push_back(std::move(MB));
100
101 if (Driver->Cpio)
102 Driver->Cpio->append(relativeToRoot(MBRef.getBufferIdentifier()),
103 MBRef.getBuffer());
104
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000105 return MBRef;
106}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000107
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000108void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB) {
109 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Peter Collingbournefeee2102016-07-26 02:00:42 +0000110
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000111 // File type is detected by contents, not by file extension.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000112 file_magic Magic = identify_magic(MBRef.getBuffer());
113 if (Magic == file_magic::windows_resource) {
114 Resources.push_back(MBRef);
115 return;
116 }
117
118 FilePaths.push_back(MBRef.getBufferIdentifier());
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000119 if (Magic == file_magic::archive)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000120 return Symtab.addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne60c16162015-06-01 20:10:10 +0000121 if (Magic == file_magic::bitcode)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000122 return Symtab.addFile(make<BitcodeFile>(MBRef));
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000123 if (Magic == file_magic::coff_cl_gl_object)
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000124 fatal(MBRef.getBufferIdentifier() + ": is not a native COFF file. "
Rui Ueyamaf83806a2016-11-15 01:01:51 +0000125 "Recompile without /GL");
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000126 Symtab.addFile(make<ObjectFile>(MBRef));
127}
128
129void LinkerDriver::enqueuePath(StringRef Path) {
130 auto Future =
131 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
132 std::string PathStr = Path;
133 enqueueTask([=]() {
134 auto MBOrErr = Future->get();
135 if (MBOrErr.second)
136 fatal(MBOrErr.second, "could not open " + PathStr);
137 Driver->addBuffer(std::move(MBOrErr.first));
138 });
139
Rui Ueyamaad660982015-06-07 00:20:32 +0000140 if (Config->OutputFile == "")
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000141 Config->OutputFile = getOutputPath(Path);
142}
143
144void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
145 StringRef ParentName) {
146 file_magic Magic = identify_magic(MB.getBuffer());
147 if (Magic == file_magic::coff_import_library) {
148 Symtab.addFile(make<ImportFile>(MB));
149 return;
150 }
151
152 InputFile *Obj;
153 if (Magic == file_magic::coff_object)
154 Obj = make<ObjectFile>(MB);
155 else if (Magic == file_magic::bitcode)
156 Obj = make<BitcodeFile>(MB);
157 else
158 fatal("unknown file type: " + MB.getBufferIdentifier());
159
160 Obj->ParentName = ParentName;
161 Symtab.addFile(Obj);
162 if (Config->Verbose)
163 outs() << "Loaded " << toString(Obj) << " for " << SymName << "\n";
164}
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:
Rui Ueyama1a3fd132016-07-14 23:43:36 +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:
371 OS << stringize(Arg) << "\n";
372 }
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))
404 .Case("fixup", static_cast<unsigned>(DebugType::Fixup));
405 return DebugTypes;
406}
407
Hans Wennborg1818e652016-12-09 20:54:44 +0000408static std::string getMapFile(const opt::InputArgList &Args) {
409 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
410 if (!Arg)
411 return "";
412 if (Arg->getOption().getID() == OPT_lldmap_file)
413 return Arg->getValue();
414
415 assert(Arg->getOption().getID() == OPT_lldmap);
416 StringRef OutFile = Config->OutputFile;
417 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
418}
419
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000420void LinkerDriver::enqueueTask(std::function<void()> Task) {
421 TaskQueue.push_back(std::move(Task));
422}
423
424bool LinkerDriver::run() {
425 bool DidWork = !TaskQueue.empty();
426 while (!TaskQueue.empty()) {
427 TaskQueue.front()();
428 TaskQueue.pop_front();
429 }
430 return DidWork;
431}
432
Rui Ueyama8fe17672016-12-08 20:50:47 +0000433void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000434 // If the first command line argument is "/lib", link.exe acts like lib.exe.
435 // We call our own implementation of lib.exe that understands bitcode files.
436 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
437 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000438 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000439 return;
440 }
441
Peter Collingbourne60c16162015-06-01 20:10:10 +0000442 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000443 InitializeAllTargetInfos();
444 InitializeAllTargets();
445 InitializeAllTargetMCs();
446 InitializeAllAsmParsers();
447 InitializeAllAsmPrinters();
448 InitializeAllDisassemblers();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000449
Rui Ueyama411c63602015-05-28 19:09:30 +0000450 // Parse command line options.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000451 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000452
Rui Ueyama5c726432015-05-29 16:11:52 +0000453 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000454 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000455 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000456 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000457 }
458
Peter Collingbournefeee2102016-07-26 02:00:42 +0000459 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
460 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama8fe17672016-12-08 20:50:47 +0000461 sys::path::append(Path, "repro");
Peter Collingbournefeee2102016-07-26 02:00:42 +0000462 ErrorOr<CpioFile *> F = CpioFile::create(Path);
463 if (F)
464 Cpio.reset(*F);
465 else
Rui Ueyama8fe17672016-12-08 20:50:47 +0000466 errs() << "/linkrepro: failed to open " << Path
467 << ".cpio: " << F.getError().message() << '\n';
Peter Collingbournefeee2102016-07-26 02:00:42 +0000468 }
469
Rafael Espindolab835ae82015-08-06 14:58:50 +0000470 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
Rui Ueyamabb579542016-07-15 01:12:24 +0000471 fatal("no input files");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000472
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000473 // Construct search path list.
474 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000475 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000476 SearchPaths.push_back(Arg->getValue());
477 addLibSearchPaths();
478
Rui Ueyamaad660982015-06-07 00:20:32 +0000479 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000480 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000481 Config->OutputFile = Arg->getValue();
482
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000483 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000484 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000485 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000486
Rui Ueyama95925fd2015-06-28 19:35:15 +0000487 // Handle /force or /force:unresolved
488 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
489 Config->Force = true;
490
Rui Ueyama6600eb12015-07-04 23:37:32 +0000491 // Handle /debug
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000492 if (Args.hasArg(OPT_debug)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000493 Config->Debug = true;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000494 Config->DebugTypes =
495 Args.hasArg(OPT_debugtype)
496 ? parseDebugType(Args.getLastArg(OPT_debugtype)->getValue())
497 : getDefaultDebugType(Args);
498 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000499
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000500 // Create a dummy PDB file to satisfy build sytem rules.
Rui Ueyama9f66f822016-10-11 19:45:07 +0000501 if (auto *Arg = Args.getLastArg(OPT_pdb))
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000502 Config->PDBPath = Arg->getValue();
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000503
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000504 // Handle /noentry
505 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000506 if (!Args.hasArg(OPT_dll))
Rui Ueyama60604792016-07-14 23:37:14 +0000507 fatal("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000508 Config->NoEntry = true;
509 }
510
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000511 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000512 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000513 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000514 Config->ManifestID = 2;
515 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000516
Rui Ueyama588e8322015-06-15 01:23:58 +0000517 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000518 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000519 if (Args.hasArg(OPT_dynamicbase))
Rui Ueyama60604792016-07-14 23:37:14 +0000520 fatal("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000521 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000522 Config->DynamicBase = false;
523 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000524
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000525 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000526 if (auto *Arg = Args.getLastArg(OPT_machine))
527 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000528
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000529 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000530 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000531 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
532
533 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000534 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000535 Config->NoDefaultLibAll = true;
536
Rui Ueyama804a8b62015-05-29 16:18:15 +0000537 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000538 if (auto *Arg = Args.getLastArg(OPT_base))
539 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000540
541 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000542 if (auto *Arg = Args.getLastArg(OPT_stack))
543 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000544
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000545 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000546 if (auto *Arg = Args.getLastArg(OPT_heap))
547 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000548
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000549 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000550 if (auto *Arg = Args.getLastArg(OPT_version))
551 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
552 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000553
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000554 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000555 if (auto *Arg = Args.getLastArg(OPT_subsystem))
556 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
557 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000558
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000559 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000560 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000561 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000562
Rui Ueyama08d5e182015-06-18 23:20:11 +0000563 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000564 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000565 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000566
Rui Ueyamab95188c2015-06-18 20:27:09 +0000567 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000568 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000569 Config->Implib = Arg->getValue();
570
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000571 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000572 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000573 std::string Str = StringRef(Arg->getValue()).lower();
574 SmallVector<StringRef, 1> Vec;
575 StringRef(Str).split(Vec, ',');
576 for (StringRef S : Vec) {
577 if (S == "noref") {
578 Config->DoGC = false;
579 Config->DoICF = false;
580 continue;
581 }
582 if (S == "icf" || StringRef(S).startswith("icf=")) {
583 Config->DoICF = true;
584 continue;
585 }
586 if (S == "noicf") {
587 Config->DoICF = false;
588 continue;
589 }
590 if (StringRef(S).startswith("lldlto=")) {
591 StringRef OptLevel = StringRef(S).substr(7);
592 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
593 Config->LTOOptLevel > 3)
Rui Ueyama60604792016-07-14 23:37:14 +0000594 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000595 continue;
596 }
597 if (StringRef(S).startswith("lldltojobs=")) {
598 StringRef Jobs = StringRef(S).substr(11);
599 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000600 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
Rui Ueyama75656ee2015-10-19 19:40:43 +0000601 continue;
602 }
603 if (S != "ref" && S != "lbr" && S != "nolbr")
Rui Ueyama1a3fd132016-07-14 23:43:36 +0000604 fatal("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000605 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000606 }
607
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000608 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000609 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000610 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000611
Rui Ueyama6600eb12015-07-04 23:37:32 +0000612 // Handle /merge
613 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000614 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000615
Rui Ueyama440138c2016-06-20 03:39:39 +0000616 // Handle /section
617 for (auto *Arg : Args.filtered(OPT_section))
618 parseSection(Arg->getValue());
619
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000620 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000621 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
622 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000623
624 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000625 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
626 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000627
628 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000629 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000630 Config->ManifestDependency = Arg->getValue();
631
632 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000633 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000634 Config->ManifestFile = Arg->getValue();
635
Rui Ueyamaafb19012016-04-19 01:21:58 +0000636 // Handle /manifestinput
637 for (auto *Arg : Args.filtered(OPT_manifestinput))
638 Config->ManifestInput.push_back(Arg->getValue());
639
Rui Ueyama6592ff82015-06-16 23:13:00 +0000640 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000641 if (Args.hasArg(OPT_allowbind_no))
642 Config->AllowBind = false;
643 if (Args.hasArg(OPT_allowisolation_no))
644 Config->AllowIsolation = false;
645 if (Args.hasArg(OPT_dynamicbase_no))
646 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000647 if (Args.hasArg(OPT_nxcompat_no))
648 Config->NxCompat = false;
649 if (Args.hasArg(OPT_tsaware_no))
650 Config->TerminalServerAware = false;
Rui Ueyama96401732015-09-21 23:43:31 +0000651 if (Args.hasArg(OPT_nosymtab))
652 Config->WriteSymtab = false;
Rui Ueyamabe939b32016-11-21 17:22:35 +0000653 Config->DumpPdb = Args.hasArg(OPT_dumppdb);
Rui Ueyama327705d2016-12-10 17:23:23 +0000654 Config->DebugPdb = Args.hasArg(OPT_debugpdb);
Rui Ueyama6592ff82015-06-16 23:13:00 +0000655
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000656 // Create a list of input files. Files can be given as arguments
657 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000658 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000659 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000660 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000661 enqueuePath(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000662 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000663 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000664 enqueuePath(*Path);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000665
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000666 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000667 if (Config->Manifest == Configuration::Embed)
668 addBuffer(createManifestRes());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000669
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000670 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000671 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000672
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000673 // We should have inferred a machine type by now from the input files, but if
674 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +0000675 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000676 errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000677 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000678 }
679
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000680 // Windows specific -- Input files can be Windows resource files (.res files).
681 // We invoke cvtres.exe to convert resource files to a regular COFF file
682 // then link the result file normally.
683 if (!Resources.empty())
684 addBuffer(convertResToCOFF(Resources));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000685
Peter Collingbournefeee2102016-07-26 02:00:42 +0000686 if (Cpio)
687 Cpio->append("response.txt",
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000688 createResponseFile(Args, FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000689 ArrayRef<StringRef>(SearchPaths).slice(1)));
690
Rui Ueyama4d545342015-07-28 03:12:00 +0000691 // Handle /largeaddressaware
692 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
693 Config->LargeAddressAware = true;
694
Rui Ueyamad68e2112015-07-28 03:15:57 +0000695 // Handle /highentropyva
696 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
697 Config->HighEntropyVA = true;
698
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000699 // Handle /entry and /dll
700 if (auto *Arg = Args.getLastArg(OPT_entry)) {
701 Config->Entry = addUndefined(mangle(Arg->getValue()));
702 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000703 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
704 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000705 Config->Entry = addUndefined(S);
706 } else if (!Config->NoEntry) {
707 // Windows specific -- If entry point name is not given, we need to
708 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000709 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000710 if (S.empty())
Rui Ueyama60604792016-07-14 23:37:14 +0000711 fatal("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000712 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000713 if (Config->Verbose)
Rui Ueyama8fe17672016-12-08 20:50:47 +0000714 outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000715 }
716
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000717 // Handle /export
718 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000719 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000720 if (Config->Machine == I386) {
721 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000722 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000723 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000724 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000725 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000726 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000727 }
728
729 // Handle /def
730 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000731 // parseModuleDefs mutates Config object.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000732 parseModuleDefs(
733 takeBuffer(check(MemoryBuffer::getFile(Arg->getValue()),
734 Twine("could not open ") + Arg->getValue())));
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000735 }
736
Rui Ueyama6d249082015-07-13 22:31:45 +0000737 // Handle /delayload
738 for (auto *Arg : Args.filtered(OPT_delayload)) {
739 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000740 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000741 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000742 } else {
743 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000744 }
745 }
746
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000747 // Set default image base if /base is not given.
748 if (Config->ImageBase == uint64_t(-1))
749 Config->ImageBase = getDefaultImageBase();
750
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000751 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000752 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000753 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
754 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
755 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000756
Rui Ueyama107db552015-08-09 21:01:06 +0000757 // We do not support /guard:cf (control flow protection) yet.
758 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
759 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
760 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
761 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
762
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000763 // This code may add new undefined symbols to the link, which may enqueue more
764 // symbol resolution tasks, so we need to continue executing tasks until we
765 // converge.
766 do {
767 // Windows specific -- if entry point is not found,
768 // search for its mangled names.
769 if (Config->Entry)
770 Symtab.mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +0000771
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000772 // Windows specific -- Make sure we resolve all dllexported symbols.
773 for (Export &E : Config->Exports) {
774 if (!E.ForwardTo.empty())
775 continue;
776 E.Sym = addUndefined(E.Name);
777 if (!E.Directives)
778 Symtab.mangleMaybe(E.Sym);
779 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000780
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000781 // Add weak aliases. Weak aliases is a mechanism to give remaining
782 // undefined symbols final chance to be resolved successfully.
783 for (auto Pair : Config->AlternateNames) {
784 StringRef From = Pair.first;
785 StringRef To = Pair.second;
786 Symbol *Sym = Symtab.find(From);
787 if (!Sym)
788 continue;
789 if (auto *U = dyn_cast<Undefined>(Sym->body()))
790 if (!U->WeakAlias)
791 U->WeakAlias = Symtab.addUndefined(To);
792 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000793
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000794 // Windows specific -- if __load_config_used can be resolved, resolve it.
795 if (Symtab.findUnderscore("_load_config_used"))
796 addUndefined(mangle("_load_config_used"));
797 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +0000798
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000799 // Do LTO by compiling bitcode input files to a set of native COFF files then
800 // link those files.
801 Symtab.addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000802 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000803
Peter Collingbourne2612a322015-07-04 05:28:41 +0000804 // Make sure we have resolved all symbols.
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000805 Symtab.reportRemainingUndefines();
Peter Collingbourne2612a322015-07-04 05:28:41 +0000806
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000807 // Windows specific -- if no /subsystem is given, we need to infer
808 // that from entry point name.
809 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000810 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000811 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
Rui Ueyama60604792016-07-14 23:37:14 +0000812 fatal("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000813 }
814
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000815 // Handle /safeseh.
Rui Ueyama13563d82015-09-15 00:33:11 +0000816 if (Args.hasArg(OPT_safeseh))
817 for (ObjectFile *File : Symtab.ObjectFiles)
818 if (!File->SEHCompat)
Rui Ueyama60604792016-07-14 23:37:14 +0000819 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000820
Rui Ueyama151d8622015-06-17 20:40:43 +0000821 // Windows specific -- when we are creating a .dll file, we also
822 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +0000823 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000824 fixupExports();
825 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000826 assignExportOrdinals();
827 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000828
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000829 // Windows specific -- Create a side-by-side manifest file.
830 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000831 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000832
Rui Ueyamaa5f0f752015-09-19 21:36:28 +0000833 // Identify unreferenced COMDAT sections.
834 if (Config->DoGC)
835 markLive(Symtab.getChunks());
836
837 // Identify identical COMDAT sections to merge them.
838 if (Config->DoICF)
839 doICF(Symtab.getChunks());
840
Rui Ueyama411c63602015-05-28 19:09:30 +0000841 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000842 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000843
Rui Ueyama016414f2015-06-28 20:07:08 +0000844 // Create a symbol map file containing symbol VAs and their names
845 // to help debugging.
Hans Wennborg1818e652016-12-09 20:54:44 +0000846 std::string MapFile = getMapFile(Args);
847 if (!MapFile.empty()) {
Peter Collingbournebe549552015-06-26 18:58:24 +0000848 std::error_code EC;
Hans Wennborg1818e652016-12-09 20:54:44 +0000849 raw_fd_ostream Out(MapFile, EC, OpenFlags::F_Text);
Rui Ueyama0d09a862016-07-15 00:40:46 +0000850 if (EC)
Hans Wennborg1818e652016-12-09 20:54:44 +0000851 fatal(EC, "could not create the symbol map " + MapFile);
Peter Collingbournebe549552015-06-26 18:58:24 +0000852 Symtab.printMap(Out);
853 }
Hans Wennborg1818e652016-12-09 20:54:44 +0000854
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000855 // Call exit to avoid calling destructors.
856 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000857}
858
Rui Ueyama411c63602015-05-28 19:09:30 +0000859} // namespace coff
860} // namespace lld