blob: 4462e6e6c7891df2b56e43ed518b078f65edaa7b [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"
Sam Cleggf187c4d2018-02-20 22:09:59 +000012#include "ICF.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Sam Cleggf187c4d2018-02-20 22:09:59 +000014#include "MarkLive.h"
Martin Storsjoe1f894d2017-10-19 19:49:38 +000015#include "MinGW.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "SymbolTable.h"
Rui Ueyama685c41c2015-08-05 23:43:53 +000017#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000018#include "Writer.h"
Rui Ueyama57175aa2018-01-27 00:34:46 +000019#include "lld/Common/Args.h"
Rui Ueyama3f851702017-10-02 21:00:41 +000020#include "lld/Common/Driver.h"
Bob Haarmanb8a59c82017-10-25 22:28:38 +000021#include "lld/Common/ErrorHandler.h"
Rui Ueyama2017d522017-11-28 20:39:17 +000022#include "lld/Common/Memory.h"
Zachary Turner727f1532018-01-17 19:16:26 +000023#include "lld/Common/Timer.h"
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +000024#include "lld/Common/Version.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/ADT/Optional.h"
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +000026#include "llvm/ADT/StringSwitch.h"
Zachary Turner264b5d92017-06-07 03:48:56 +000027#include "llvm/BinaryFormat/Magic.h"
Rui Ueyamae1bf1362017-03-16 21:19:36 +000028#include "llvm/Object/ArchiveWriter.h"
Reid Kleckner146eb7a2017-06-02 17:53:06 +000029#include "llvm/Object/COFFImportFile.h"
30#include "llvm/Object/COFFModuleDefinition.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include "llvm/Option/Arg.h"
32#include "llvm/Option/ArgList.h"
33#include "llvm/Option/Option.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000034#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000035#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000036#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000037#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000038#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000039#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000040#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000041#include <algorithm>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000042#include <future>
Sam Cleggf187c4d2018-02-20 22:09:59 +000043#include <memory>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000044
Rui Ueyama411c63602015-05-28 19:09:30 +000045using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000046using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000047using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000048using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000049
Rui Ueyama3500f662015-05-28 20:30:06 +000050namespace lld {
51namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Zachary Turner727f1532018-01-17 19:16:26 +000053static Timer InputFileTimer("Input File Reading", Timer::root());
54
Rui Ueyama3500f662015-05-28 20:30:06 +000055Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000056LinkerDriver *Driver;
57
Rui Ueyama6f4e2552017-10-23 20:03:32 +000058bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Nico Weber386bf122018-08-22 23:52:13 +000059 errorHandler().LogName = args::FilenameWithoutExe(Args[0]);
Bob Haarmanb8a59c82017-10-25 22:28:38 +000060 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
Nico Weberf06ae4f2018-03-12 12:45:40 +000064 " (use /errorlimit:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000065 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000066 Config = make<Configuration>();
Rui Ueyamacbf969e2017-08-28 21:51:07 +000067
68 Symtab = make<SymbolTable>();
69
Rui Ueyama7fed58c2016-12-08 19:10:28 +000070 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000071 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000072
73 // Call exit() if we can to avoid calling destructors.
74 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000075 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000076
77 freeArena();
Rui Ueyama279621f2018-07-26 17:11:24 +000078 ObjFile::Instances.clear();
79 ImportFile::Instances.clear();
80 BitcodeFile::Instances.clear();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000081 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000082}
Rui Ueyama411c63602015-05-28 19:09:30 +000083
Nico Weber5660de72016-04-20 22:34:15 +000084// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000085static std::string getOutputPath(StringRef Path) {
86 auto P = Path.find_last_of("\\/");
87 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000088 const char* E = Config->DLL ? ".dll" : ".exe";
89 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000090}
91
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000092// ErrorOr is not default constructible, so it cannot be used as the type
93// parameter of a future.
94// FIXME: We could open the file in createFutureForFile and avoid needing to
95// return an error here, but for the moment that would cost us a file descriptor
96// (a limited resource on Windows) for the duration that the future is pending.
97typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
98
99// Create a std::future that opens and maps a file using the best strategy for
100// the host platform.
101static std::future<MBErrPair> createFutureForFile(std::string Path) {
Nico Weberfb647302018-04-10 13:15:21 +0000102#if _WIN32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000103 // On Windows, file I/O is relatively slow so it is best to do this
104 // asynchronously.
105 auto Strategy = std::launch::async;
106#else
107 auto Strategy = std::launch::deferred;
108#endif
109 return std::async(Strategy, [=]() {
Bob Haarman8832f882018-04-24 23:16:39 +0000110 auto MBOrErr = MemoryBuffer::getFile(Path,
111 /*FileSize*/ -1,
112 /*RequiresNullTerminator*/ false);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000113 if (!MBOrErr)
114 return MBErrPair{nullptr, MBOrErr.getError()};
115 return MBErrPair{std::move(*MBOrErr), std::error_code()};
116 });
117}
118
Nico Weberd48d5f02018-08-03 12:00:12 +0000119// Symbol names are mangled by prepending "_" on x86.
120static StringRef mangle(StringRef Sym) {
121 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
122 if (Config->Machine == I386)
123 return Saver.save("_" + Sym);
124 return Sym;
125}
126
127static bool findUnderscoreMangle(StringRef Sym) {
128 StringRef Entry = Symtab->findMangle(mangle(Sym));
129 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry));
130}
131
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000132MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
133 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000134 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000135
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000136 if (Driver->Tar)
137 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
138 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000139 return MBRef;
140}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000141
Martin Storsjo8278ba52017-09-13 07:28:03 +0000142void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
143 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000144 StringRef Filename = MB->getBufferIdentifier();
145
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000146 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000147 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000148
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000149 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000150 switch (identify_magic(MBRef.getBuffer())) {
151 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000152 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000153 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000154 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000155 if (WholeArchive) {
156 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000157 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000158
159 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000160 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000161 return;
162 }
163 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000164 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000165 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000166 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000167 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000168 case file_magic::coff_object:
169 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000170 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000171 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000172 case file_magic::coff_cl_gl_object:
173 error(Filename + ": is not a native COFF file. Recompile without /GL");
174 break;
175 case file_magic::pecoff_executable:
176 if (Filename.endswith_lower(".dll")) {
177 error(Filename + ": bad file type. Did you specify a DLL instead of an "
178 "import library?");
179 break;
180 }
181 LLVM_FALLTHROUGH;
182 default:
183 error(MBRef.getBufferIdentifier() + ": unknown file type");
184 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000185 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000186}
187
Martin Storsjo8278ba52017-09-13 07:28:03 +0000188void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000189 auto Future =
190 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
191 std::string PathStr = Path;
192 enqueueTask([=]() {
193 auto MBOrErr = Future->get();
194 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000195 error("could not open " + PathStr + ": " + MBOrErr.second.message());
196 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000197 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000198 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000199}
200
201void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
202 StringRef ParentName) {
203 file_magic Magic = identify_magic(MB.getBuffer());
204 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000205 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000206 return;
207 }
208
209 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000210 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000211 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000212 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000213 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000214 } else {
215 error("unknown file type: " + MB.getBufferIdentifier());
216 return;
217 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000218
219 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000220 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000221 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000222}
223
224void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
225 StringRef SymName,
226 StringRef ParentName) {
227 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000228 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000229 C.getMemoryBufferRef(),
230 "could not get the buffer for the member defining symbol " + SymName);
231 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
232 return;
233 }
234
235 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000236 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000237 "could not get the filename for the member defining symbol " +
238 SymName)));
239 enqueueTask([=]() {
240 auto MBOrErr = Future->get();
241 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000242 fatal("could not get the buffer for the member defining " + SymName +
243 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000244 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
245 ParentName);
246 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000247}
248
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000249static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000250 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
251 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000252}
253
Rui Ueyama411c63602015-05-28 19:09:30 +0000254// Parses .drectve section contents and returns a list of files
255// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000256void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000257 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000258 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000259 // /EXPORT: option can appear too many times, processing in fastpath.
260 opt::InputArgList Args;
261 std::vector<StringRef> Exports;
262 std::tie(Args, Exports) = Parser.parseDirectives(S);
263
264 for (StringRef E : Exports) {
265 // If a common header file contains dllexported function
266 // declarations, many object files may end up with having the
267 // same /EXPORT options. In order to save cost of parsing them,
268 // we dedup them first.
269 if (!DirectivesExports.insert(E).second)
270 continue;
271
272 Export Exp = parseExport(E);
273 if (Config->Machine == I386 && Config->MinGW) {
274 if (!isDecorated(Exp.Name))
275 Exp.Name = Saver.save("_" + Exp.Name);
276 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
277 Exp.ExtName = Saver.save("_" + Exp.ExtName);
278 }
279 Exp.Directives = true;
280 Config->Exports.push_back(Exp);
281 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000282
David Blaikie6521ed92015-06-22 22:06:52 +0000283 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000284 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000285 case OPT_aligncomm:
286 parseAligncomm(Arg->getValue());
287 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000288 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000289 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000290 break;
291 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000292 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000293 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000294 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000295 case OPT_entry:
296 Config->Entry = addUndefined(mangle(Arg->getValue()));
297 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000298 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000299 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000300 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000301 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000302 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000303 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000304 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000305 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000306 break;
307 case OPT_nodefaultlib:
308 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
309 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000310 case OPT_section:
311 parseSection(Arg->getValue());
312 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000313 case OPT_subsystem:
314 parseSubsystem(Arg->getValue(), &Config->Subsystem,
315 &Config->MajorOSVersion, &Config->MinorOSVersion);
316 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000317 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000318 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000319 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000320 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000321 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000322 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000323 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000324 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000325 }
326 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000327}
328
Rui Ueyama54b71da2015-05-31 19:17:12 +0000329// Find file from search paths. You can omit ".obj", this function takes
330// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000331StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000332 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
333 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000334 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000335 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000336 for (StringRef Dir : SearchPaths) {
337 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000338 sys::path::append(Path, Filename);
339 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000340 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000341 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000342 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000343 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000344 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000345 }
346 }
347 return Filename;
348}
349
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000350static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
351 sys::fs::UniqueID Ret;
352 if (sys::fs::getUniqueID(Path, Ret))
353 return None;
354 return Ret;
355}
356
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000357// Resolves a file path. This never returns the same path
358// (in that case, it returns None).
359Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
360 StringRef Path = doFindFile(Filename);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000361
362 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
363 bool Seen = !VisitedFiles.insert(*ID).second;
364 if (Seen)
365 return None;
366 }
367
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000368 if (Path.endswith_lower(".lib"))
369 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000370 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000371}
372
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000373// Find library file from search path.
374StringRef LinkerDriver::doFindLib(StringRef Filename) {
375 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000376 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000377 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000378 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000379 return doFindFile(Filename);
380}
381
382// Resolves a library path. /nodefaultlib options are taken into
383// consideration. This never returns the same path (in that case,
384// it returns None).
385Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
386 if (Config->NoDefaultLibAll)
387 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000388 if (!VisitedLibs.insert(Filename.lower()).second)
389 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000390
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000391 StringRef Path = doFindLib(Filename);
392 if (Config->NoDefaultLibs.count(Path))
393 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000394
395 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
396 if (!VisitedFiles.insert(*ID).second)
397 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000398 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000399}
400
401// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000402void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000403 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
404 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000405 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000406 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000407 while (!Env.empty()) {
408 StringRef Path;
409 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000410 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000411 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000412}
413
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000414Symbol *LinkerDriver::addUndefined(StringRef Name) {
415 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000416 if (!B->IsGCRoot) {
417 B->IsGCRoot = true;
418 Config->GCRoot.push_back(B);
419 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000420 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000421}
422
Rui Ueyama45044f42015-06-29 01:03:53 +0000423// Windows specific -- find default entry point name.
Rui Ueyamac93530d2018-07-18 17:48:14 +0000424//
425// There are four different entry point functions for Windows executables,
426// each of which corresponds to a user-defined "main" function. This function
427// infers an entry point from a user-defined "main" function.
Rui Ueyama45044f42015-06-29 01:03:53 +0000428StringRef LinkerDriver::findDefaultEntry() {
Nico Weberf4f5b7e2018-08-07 19:10:28 +0000429 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
430 "must handle /subsystem before calling this");
431
432 // As a special case, if /nodefaultlib is given, we directly look for an
433 // entry point. This is because, if no default library is linked, users
434 // need to define an entry point instead of a "main".
435 bool FindMain = !Config->NoDefaultLibAll;
436 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
437 if (findUnderscoreMangle(FindMain ? "WinMain" : "WinMainCRTStartup"))
438 return mangle("WinMainCRTStartup");
439 if (findUnderscoreMangle(FindMain ? "wWinMain" : "wWinMainCRTStartup"))
440 return mangle("wWinMainCRTStartup");
Rui Ueyama45044f42015-06-29 01:03:53 +0000441 }
Nico Weberf4f5b7e2018-08-07 19:10:28 +0000442 if (findUnderscoreMangle(FindMain ? "main" : "mainCRTStartup"))
443 return mangle("mainCRTStartup");
444 if (findUnderscoreMangle(FindMain ? "wmain" : "wmainCRTStartup"))
445 return mangle("wmainCRTStartup");
Rui Ueyama45044f42015-06-29 01:03:53 +0000446 return "";
447}
448
449WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000450 if (Config->DLL)
451 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Nico Weberebc27c42018-08-22 16:47:16 +0000452 bool HaveMain = findUnderscoreMangle("main");
453 bool HaveWMain = findUnderscoreMangle("wmain");
454 bool HaveWinMain = findUnderscoreMangle("WinMain");
455 bool HaveWWinMain = findUnderscoreMangle("wWinMain");
456 if (HaveMain || HaveWMain) {
457 if (HaveWinMain || HaveWWinMain) {
458 warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " +
459 (HaveWinMain ? "WinMain" : "wWinMain") +
460 "; defaulting to /subsystem:console");
461 }
Rui Ueyama45044f42015-06-29 01:03:53 +0000462 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Nico Weberebc27c42018-08-22 16:47:16 +0000463 }
464 if (HaveWinMain || HaveWWinMain)
Rui Ueyama45044f42015-06-29 01:03:53 +0000465 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
466 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000467}
468
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000469static uint64_t getDefaultImageBase() {
470 if (Config->is64())
471 return Config->DLL ? 0x180000000 : 0x140000000;
472 return Config->DLL ? 0x10000000 : 0x400000;
473}
474
Rui Ueyama8fe17672016-12-08 20:50:47 +0000475static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000476 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000477 ArrayRef<StringRef> SearchPaths) {
478 SmallString<0> Data;
479 raw_svector_ostream OS(Data);
480
481 for (auto *Arg : Args) {
482 switch (Arg->getOption().getID()) {
483 case OPT_linkrepro:
484 case OPT_INPUT:
485 case OPT_defaultlib:
486 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000487 case OPT_manifest:
488 case OPT_manifest_colon:
489 case OPT_manifestdependency:
490 case OPT_manifestfile:
491 case OPT_manifestinput:
492 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000493 break;
494 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000495 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000496 }
497 }
498
499 for (StringRef Path : SearchPaths) {
500 std::string RelPath = relativeToRoot(Path);
501 OS << "/libpath:" << quote(RelPath) << "\n";
502 }
503
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000504 for (StringRef Path : FilePaths)
505 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000506
507 return Data.str();
508}
509
Rui Ueyama8fe17672016-12-08 20:50:47 +0000510static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000511 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
512 if (Args.hasArg(OPT_driver))
513 DebugTypes |= static_cast<unsigned>(DebugType::PData);
514 if (Args.hasArg(OPT_profile))
515 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
516 return DebugTypes;
517}
518
519static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000520 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000521 Arg.split(Types, ',', /*KeepEmpty=*/false);
522
523 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
524 for (StringRef Type : Types)
525 DebugTypes |= StringSwitch<unsigned>(Type.lower())
526 .Case("cv", static_cast<unsigned>(DebugType::CV))
527 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000528 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
529 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000530 return DebugTypes;
531}
532
Hans Wennborg1818e652016-12-09 20:54:44 +0000533static std::string getMapFile(const opt::InputArgList &Args) {
534 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
535 if (!Arg)
536 return "";
537 if (Arg->getOption().getID() == OPT_lldmap_file)
538 return Arg->getValue();
539
540 assert(Arg->getOption().getID() == OPT_lldmap);
541 StringRef OutFile = Config->OutputFile;
542 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
543}
544
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000545static std::string getImplibPath() {
546 if (!Config->Implib.empty())
547 return Config->Implib;
548 SmallString<128> Out = StringRef(Config->OutputFile);
549 sys::path::replace_extension(Out, ".lib");
550 return Out.str();
551}
552
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000553//
554// The import name is caculated as the following:
555//
556// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
557// -----+----------------+---------------------+------------------
558// LINK | {value} | {value}.{.dll/.exe} | {output name}
559// LIB | {value} | {value}.dll | {output name}.dll
560//
561static std::string getImportName(bool AsLib) {
562 SmallString<128> Out;
563
564 if (Config->ImportName.empty()) {
565 Out.assign(sys::path::filename(Config->OutputFile));
566 if (AsLib)
567 sys::path::replace_extension(Out, ".dll");
568 } else {
569 Out.assign(Config->ImportName);
570 if (!sys::path::has_extension(Out))
571 sys::path::replace_extension(Out,
572 (Config->DLL || AsLib) ? ".dll" : ".exe");
573 }
574
575 return Out.str();
576}
577
578static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000579 std::vector<COFFShortExport> Exports;
580 for (Export &E1 : Config->Exports) {
581 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000582 E2.Name = E1.Name;
583 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000584 E2.ExtName = E1.ExtName;
585 E2.Ordinal = E1.Ordinal;
586 E2.Noname = E1.Noname;
587 E2.Data = E1.Data;
588 E2.Private = E1.Private;
589 E2.Constant = E1.Constant;
590 Exports.push_back(E2);
591 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000592
Bob Haarman4ce341f2018-01-23 00:36:42 +0000593 auto HandleError = [](Error &&E) {
594 handleAllErrors(std::move(E),
595 [](ErrorInfoBase &EIB) { error(EIB.message()); });
596 };
597 std::string LibName = getImportName(AsLib);
598 std::string Path = getImplibPath();
599
Bob Haarman5ec44852018-01-31 23:44:00 +0000600 if (!Config->Incremental) {
601 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000602 Config->MinGW));
Bob Haarman5ec44852018-01-31 23:44:00 +0000603 return;
604 }
605
Bob Haarman4ce341f2018-01-23 00:36:42 +0000606 // If the import library already exists, replace it only if the contents
607 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000608 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
609 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000610 if (!OldBuf) {
611 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000612 Config->MinGW));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000613 return;
614 }
615
616 SmallString<128> TmpName;
617 if (std::error_code EC =
618 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
619 fatal("cannot create temporary file for import library " + Path + ": " +
620 EC.message());
621
622 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000623 Config->MinGW)) {
Bob Haarman4ce341f2018-01-23 00:36:42 +0000624 HandleError(std::move(E));
625 return;
626 }
627
Bob Haarman8832f882018-04-24 23:16:39 +0000628 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
629 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000630 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
631 OldBuf->reset();
632 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000633 } else {
634 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000635 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000636}
637
638static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000639 std::unique_ptr<MemoryBuffer> MB = CHECK(
640 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000641 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
642 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000643
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000644 if (Config->OutputFile.empty())
645 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000646 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000647 if (M.ImageBase)
648 Config->ImageBase = M.ImageBase;
649 if (M.StackReserve)
650 Config->StackReserve = M.StackReserve;
651 if (M.StackCommit)
652 Config->StackCommit = M.StackCommit;
653 if (M.HeapReserve)
654 Config->HeapReserve = M.HeapReserve;
655 if (M.HeapCommit)
656 Config->HeapCommit = M.HeapCommit;
657 if (M.MajorImageVersion)
658 Config->MajorImageVersion = M.MajorImageVersion;
659 if (M.MinorImageVersion)
660 Config->MinorImageVersion = M.MinorImageVersion;
661 if (M.MajorOSVersion)
662 Config->MajorOSVersion = M.MajorOSVersion;
663 if (M.MinorOSVersion)
664 Config->MinorOSVersion = M.MinorOSVersion;
665
666 for (COFFShortExport E1 : M.Exports) {
667 Export E2;
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000668 // In simple cases, only Name is set. Renamed exports are parsed
669 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
670 // it shouldn't be a normal exported function but a forward to another
671 // DLL instead. This is supported by both MS and GNU linkers.
672 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
Martin Storsjo5c84d442018-05-09 19:07:10 +0000673 E2.Name = Saver.save(E1.ExtName);
674 E2.ForwardTo = Saver.save(E1.Name);
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000675 Config->Exports.push_back(E2);
676 continue;
677 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000678 E2.Name = Saver.save(E1.Name);
Martin Storsjo97379ff2018-05-09 09:22:03 +0000679 E2.ExtName = Saver.save(E1.ExtName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000680 E2.Ordinal = E1.Ordinal;
681 E2.Noname = E1.Noname;
682 E2.Data = E1.Data;
683 E2.Private = E1.Private;
684 E2.Constant = E1.Constant;
685 Config->Exports.push_back(E2);
686 }
687}
688
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000689void LinkerDriver::enqueueTask(std::function<void()> Task) {
690 TaskQueue.push_back(std::move(Task));
691}
692
693bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000694 ScopedTimer T(InputFileTimer);
695
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000696 bool DidWork = !TaskQueue.empty();
697 while (!TaskQueue.empty()) {
698 TaskQueue.front()();
699 TaskQueue.pop_front();
700 }
701 return DidWork;
702}
703
Rui Ueyama57175aa2018-01-27 00:34:46 +0000704// Parse an /order file. If an option is given, the linker places
705// COMDAT sections in the same order as their names appear in the
706// given file.
707static void parseOrderFile(StringRef Arg) {
708 // For some reason, the MSVC linker requires a filename to be
709 // preceded by "@".
710 if (!Arg.startswith("@")) {
711 error("malformed /order option: '@' missing");
712 return;
713 }
714
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000715 // Get a list of all comdat sections for error checking.
716 DenseSet<StringRef> Set;
717 for (Chunk *C : Symtab->getChunks())
718 if (auto *Sec = dyn_cast<SectionChunk>(C))
719 if (Sec->Sym)
720 Set.insert(Sec->Sym->getName());
721
Rui Ueyama57175aa2018-01-27 00:34:46 +0000722 // Open a file.
723 StringRef Path = Arg.substr(1);
724 std::unique_ptr<MemoryBuffer> MB = CHECK(
725 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
726
727 // Parse a file. An order file contains one symbol per line.
728 // All symbols that were not present in a given order file are
729 // considered to have the lowest priority 0 and are placed at
730 // end of an output section.
731 for (std::string S : args::getLines(MB->getMemBufferRef())) {
732 if (Config->Machine == I386 && !isDecorated(S))
733 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000734
Nico Weber0771c602018-03-09 12:41:04 +0000735 if (Set.count(S) == 0) {
736 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000737 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000738 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000739 else
740 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000741 }
742}
743
Rui Ueyama8fe17672016-12-08 20:50:47 +0000744void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000745 // If the first command line argument is "/lib", link.exe acts like lib.exe.
746 // We call our own implementation of lib.exe that understands bitcode files.
747 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
748 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000749 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000750 return;
751 }
752
Peter Collingbourne60c16162015-06-01 20:10:10 +0000753 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000754 InitializeAllTargetInfos();
755 InitializeAllTargets();
756 InitializeAllTargetMCs();
757 InitializeAllAsmParsers();
758 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000759
Rui Ueyama411c63602015-05-28 19:09:30 +0000760 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000761 ArgParser Parser;
Reid Kleckner276d7162018-07-20 22:34:20 +0000762 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000763
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000764 // Parse and evaluate -mllvm options.
765 std::vector<const char *> V;
766 V.push_back("lld-link (LLVM option parsing)");
767 for (auto *Arg : Args.filtered(OPT_mllvm))
768 V.push_back(Arg->getValue());
769 cl::ParseCommandLineOptions(V.size(), V.data());
770
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000771 // Handle /errorlimit early, because error() depends on it.
772 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
773 int N = 20;
774 StringRef S = Arg->getValue();
775 if (S.getAsInteger(10, N))
776 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000777 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000778 }
779
Rui Ueyama5c726432015-05-29 16:11:52 +0000780 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000781 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000782 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000783 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000784 }
785
Zachary Turner727f1532018-01-17 19:16:26 +0000786 if (Args.hasArg(OPT_show_timing))
787 Config->ShowTiming = true;
788
789 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000790 // Handle --version, which is an lld extension. This option is a bit odd
791 // because it doesn't start with "/", but we deliberately chose "--" to
792 // avoid conflict with /version and for compatibility with clang-cl.
793 if (Args.hasArg(OPT_dash_dash_version)) {
794 outs() << getLLDVersion() << "\n";
795 return;
796 }
797
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000798 // Handle /lldmingw early, since it can potentially affect how other
799 // options are handled.
800 Config->MinGW = Args.hasArg(OPT_lldmingw);
801
Peter Collingbournefeee2102016-07-26 02:00:42 +0000802 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
803 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000804 sys::path::append(Path, "repro.tar");
805
806 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
807 TarWriter::create(Path, "repro");
808
809 if (ErrOrWriter) {
810 Tar = std::move(*ErrOrWriter);
811 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000812 error("/linkrepro: failed to open " + Path + ": " +
813 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000814 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000815 }
816
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000817 if (!Args.hasArg(OPT_INPUT)) {
818 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000819 Config->NoEntry = true;
820 else
821 fatal("no input files");
822 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000823
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000824 // Construct search path list.
825 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000826 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000827 SearchPaths.push_back(Arg->getValue());
828 addLibSearchPaths();
829
Bob Haarmane90ac012017-12-28 07:02:13 +0000830 // Handle /ignore
831 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000832 if (StringRef(Arg->getValue()) == "4037")
833 Config->WarnMissingOrderSymbol = false;
834 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000835 Config->WarnLocallyDefinedImported = false;
836 // Other warning numbers are ignored.
837 }
838
Rui Ueyamaad660982015-06-07 00:20:32 +0000839 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000840 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000841 Config->OutputFile = Arg->getValue();
842
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000843 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000844 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000845 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000846 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000847
Rui Ueyama95925fd2015-06-28 19:35:15 +0000848 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000849 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama95925fd2015-06-28 19:35:15 +0000850 Config->Force = true;
851
Rui Ueyama6600eb12015-07-04 23:37:32 +0000852 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000853 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000854 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000855 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000856 if (auto *Arg = Args.getLastArg(OPT_debugtype))
857 Config->DebugTypes = parseDebugType(Arg->getValue());
858 else
859 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000860 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000861
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000862 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000863 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000864 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000865 if (auto *Arg = Args.getLastArg(OPT_pdb))
866 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000867 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
868 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000869 if (Args.hasArg(OPT_natvis))
870 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
Takuto Ikutad8559282018-07-19 04:56:22 +0000871
872 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
873 Config->PDBSourcePath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000874 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000875
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000876 // Handle /noentry
877 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000878 if (Args.hasArg(OPT_dll))
879 Config->NoEntry = true;
880 else
881 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000882 }
883
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000884 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000885 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000886 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000887 Config->ManifestID = 2;
888 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000889
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000890 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
891 // because we need to explicitly check whether that option or its inverse was
892 // present in the argument list in order to handle /fixed.
893 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
894 if (DynamicBaseArg &&
895 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
896 Config->DynamicBase = false;
897
Nico Webera7643792018-03-30 17:17:04 +0000898 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
899 // default setting for any other project type.", but link.exe defaults to
900 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000901 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
902 if (Fixed) {
903 if (DynamicBaseArg &&
904 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000905 error("/fixed must not be specified with /dynamicbase");
906 } else {
907 Config->Relocatable = false;
908 Config->DynamicBase = false;
909 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000910 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000911
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000912 // Handle /appcontainer
913 Config->AppContainer =
914 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000915
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000916 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000917 if (auto *Arg = Args.getLastArg(OPT_machine))
918 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000919
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000920 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000921 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000922 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
923
924 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000925 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000926 Config->NoDefaultLibAll = true;
927
Rui Ueyama804a8b62015-05-29 16:18:15 +0000928 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000929 if (auto *Arg = Args.getLastArg(OPT_base))
930 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000931
932 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000933 if (auto *Arg = Args.getLastArg(OPT_stack))
934 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000935
Reid Kleckneraf2f7da2018-02-06 01:58:26 +0000936 // Handle /guard:cf
937 if (auto *Arg = Args.getLastArg(OPT_guard))
938 parseGuard(Arg->getValue());
939
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000940 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000941 if (auto *Arg = Args.getLastArg(OPT_heap))
942 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000943
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000944 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000945 if (auto *Arg = Args.getLastArg(OPT_version))
946 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
947 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000948
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000949 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000950 if (auto *Arg = Args.getLastArg(OPT_subsystem))
951 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
952 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000953
Zachary Turnerc8dd6cc2018-05-17 15:11:01 +0000954 // Handle /timestamp
955 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
956 if (Arg->getOption().getID() == OPT_repro) {
957 Config->Timestamp = 0;
958 Config->Repro = true;
959 } else {
960 Config->Repro = false;
961 StringRef Value(Arg->getValue());
962 if (Value.getAsInteger(0, Config->Timestamp))
963 fatal(Twine("invalid timestamp: ") + Value +
964 ". Expected 32-bit integer");
965 }
966 } else {
967 Config->Repro = false;
968 Config->Timestamp = time(nullptr);
969 }
970
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000971 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000972 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000973 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000974
Rui Ueyama08d5e182015-06-18 23:20:11 +0000975 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000976 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000977 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000978
Rui Ueyamab95188c2015-06-18 20:27:09 +0000979 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000980 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000981 Config->Implib = Arg->getValue();
982
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000983 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +0000984 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
985 unsigned ICFLevel =
986 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +0000987 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +0000988 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +0000989 std::string Str = StringRef(Arg->getValue()).lower();
990 SmallVector<StringRef, 1> Vec;
991 StringRef(Str).split(Vec, ',');
992 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +0000993 if (S == "ref") {
994 DoGC = true;
995 } else if (S == "noref") {
996 DoGC = false;
997 } else if (S == "icf" || S.startswith("icf=")) {
998 ICFLevel = 2;
999 } else if (S == "noicf") {
1000 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001001 } else if (S == "lldtailmerge") {
1002 TailMerge = 2;
1003 } else if (S == "nolldtailmerge") {
1004 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001005 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001006 StringRef OptLevel = S.substr(7);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001007 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001008 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001009 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001010 StringRef Jobs = S.substr(11);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001011 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1012 Config->ThinLTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001013 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001014 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001015 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001016 if (N.getAsInteger(10, Config->LTOPartitions) ||
1017 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001018 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001019 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001020 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001021 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001022 }
1023
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001024 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1025 // explicitly.
1026 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1027 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1028 // comdat readonly data.
1029 if (ICFLevel == 1 && !DoGC)
1030 ICFLevel = 0;
1031 Config->DoGC = DoGC;
1032 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001033 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001034
Bob Haarman69b196d2017-02-08 18:36:41 +00001035 // Handle /lldsavetemps
1036 if (Args.hasArg(OPT_lldsavetemps))
1037 Config->SaveTemps = true;
1038
Martin Storsjo53518912018-03-14 20:17:16 +00001039 // Handle /kill-at
1040 if (Args.hasArg(OPT_kill_at))
1041 Config->KillAt = true;
1042
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001043 // Handle /lldltocache
1044 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1045 Config->LTOCache = Arg->getValue();
1046
1047 // Handle /lldsavecachepolicy
1048 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001049 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001050 parseCachePruningPolicy(Arg->getValue()),
1051 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1052
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001053 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001054 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001055 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001056
Rui Ueyama6600eb12015-07-04 23:37:32 +00001057 // Handle /merge
1058 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001059 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001060
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001061 // Add default section merging rules after user rules. User rules take
1062 // precedence, but we will emit a warning if there is a conflict.
1063 parseMerge(".idata=.rdata");
1064 parseMerge(".didat=.rdata");
1065 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001066 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001067 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001068
Rui Ueyama440138c2016-06-20 03:39:39 +00001069 // Handle /section
1070 for (auto *Arg : Args.filtered(OPT_section))
1071 parseSection(Arg->getValue());
1072
Martin Storsjod2752aa2017-08-14 19:07:27 +00001073 // Handle /aligncomm
1074 for (auto *Arg : Args.filtered(OPT_aligncomm))
1075 parseAligncomm(Arg->getValue());
1076
Nico Webera7a2c442017-07-25 18:08:03 +00001077 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1078 // also passed.
1079 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1080 Config->ManifestDependency = Arg->getValue();
1081 Config->Manifest = Configuration::SideBySide;
1082 }
1083
1084 // Handle /manifest and /manifest:
1085 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1086 if (Arg->getOption().getID() == OPT_manifest)
1087 Config->Manifest = Configuration::SideBySide;
1088 else
1089 parseManifest(Arg->getValue());
1090 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001091
1092 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001093 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1094 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001095
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001096 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001097 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001098 Config->ManifestFile = Arg->getValue();
1099
Rui Ueyamaafb19012016-04-19 01:21:58 +00001100 // Handle /manifestinput
1101 for (auto *Arg : Args.filtered(OPT_manifestinput))
1102 Config->ManifestInput.push_back(Arg->getValue());
1103
Nico Webera7a2c442017-07-25 18:08:03 +00001104 if (!Config->ManifestInput.empty() &&
1105 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001106 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001107 }
1108
Rui Ueyama6592ff82015-06-16 23:13:00 +00001109 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001110 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1111 Config->AllowIsolation =
1112 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001113 Config->Incremental =
1114 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001115 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1116 !Args.hasArg(OPT_profile));
Nico Weberd657c252018-05-31 13:43:02 +00001117 Config->IntegrityCheck =
1118 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001119 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001120 Config->TerminalServerAware =
1121 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001122 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001123 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Martin Storsjo3a7905b2018-06-29 06:08:25 +00001124 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001125
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001126 Config->MapFile = getMapFile(Args);
1127
Nico Weber0945ad62018-03-30 17:14:50 +00001128 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1129 warn("ignoring '/incremental' due to '/profile' specification");
1130 Config->Incremental = false;
1131 }
1132
1133 if (Config->Incremental && Args.hasArg(OPT_order)) {
1134 warn("ignoring '/incremental' due to '/order' specification");
1135 Config->Incremental = false;
1136 }
1137
Bob Haarman5ec44852018-01-31 23:44:00 +00001138 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001139 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001140 "disable");
1141 Config->Incremental = false;
1142 }
1143
1144 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001145 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001146 "disable");
1147 Config->Incremental = false;
1148 }
1149
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001150 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001151 return;
1152
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001153 std::set<sys::fs::UniqueID> WholeArchives;
1154 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
Reid Kleckner34085682018-06-14 19:56:03 +00001155 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1156 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1157 WholeArchives.insert(*ID);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001158
1159 // A predicate returning true if a given path is an argument for
1160 // /wholearchive:, or /wholearchive is enabled globally.
1161 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1162 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1163 auto IsWholeArchive = [&](StringRef Path) -> bool {
1164 if (Args.hasArg(OPT_wholearchive_flag))
1165 return true;
1166 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1167 return WholeArchives.count(*ID);
1168 return false;
1169 };
1170
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001171 // Create a list of input files. Files can be given as arguments
1172 // for /defaultlib option.
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001173 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1174 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Reid Kleckner34085682018-06-14 19:56:03 +00001175 enqueuePath(*Path, IsWholeArchive(*Path));
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001176
David Blaikie6521ed92015-06-22 22:06:52 +00001177 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001178 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001179 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001180
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001181 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001182 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001183 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001184
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001185 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001186 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001187
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001188 // We should have inferred a machine type by now from the input files, but if
1189 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001190 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001191 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001192 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001193 }
1194
Eric Beckmann9e19d792017-06-17 02:26:27 +00001195 // Input files can be Windows resource files (.res files). We use
1196 // WindowsResource to convert resource files to a regular COFF file,
1197 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001198 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001199 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001200
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001201 if (Tar)
1202 Tar->append("response.txt",
1203 createResponseFile(Args, FilePaths,
1204 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001205
Rui Ueyama4d545342015-07-28 03:12:00 +00001206 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001207 Config->LargeAddressAware = Args.hasFlag(
1208 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001209
Rui Ueyamad68e2112015-07-28 03:15:57 +00001210 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001211 Config->HighEntropyVA =
1212 Config->is64() &&
1213 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001214
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001215 if (!Config->DynamicBase &&
1216 (Config->Machine == ARMNT || Config->Machine == ARM64))
1217 error("/dynamicbase:no is not compatible with " +
1218 machineToStr(Config->Machine));
1219
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001220 // Handle /export
1221 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001222 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001223 if (Config->Machine == I386) {
1224 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001225 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001226 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001227 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001228 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001229 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001230 }
1231
1232 // Handle /def
1233 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001234 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001235 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001236 }
1237
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001238 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001239 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001240 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001241 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001242 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001243 }
1244
Nico Weberf4f5b7e2018-08-07 19:10:28 +00001245 // Windows specific -- if no /subsystem is given, we need to infer
1246 // that from entry point name. Must happen before /entry handling,
1247 // and after the early return when just writing an import library.
1248 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1249 Config->Subsystem = inferSubsystem();
1250 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1251 fatal("subsystem must be defined");
1252 }
1253
1254 // Handle /entry and /dll
1255 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1256 Config->Entry = addUndefined(mangle(Arg->getValue()));
1257 } else if (!Config->Entry && !Config->NoEntry) {
1258 if (Args.hasArg(OPT_dll)) {
1259 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1260 : "_DllMainCRTStartup";
1261 Config->Entry = addUndefined(S);
1262 } else {
1263 // Windows specific -- If entry point name is not given, we need to
1264 // infer that from user-defined entry name.
1265 StringRef S = findDefaultEntry();
1266 if (S.empty())
1267 fatal("entry point must be defined");
1268 Config->Entry = addUndefined(S);
1269 log("Entry name inferred: " + S);
1270 }
1271 }
1272
Rui Ueyama6d249082015-07-13 22:31:45 +00001273 // Handle /delayload
1274 for (auto *Arg : Args.filtered(OPT_delayload)) {
1275 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001276 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001277 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001278 } else {
1279 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001280 }
1281 }
1282
Reid Kleckner7668182e2017-03-21 00:12:51 +00001283 // Set default image name if neither /out or /def set it.
1284 if (Config->OutputFile.empty()) {
1285 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001286 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001287 }
1288
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001289 if (ShouldCreatePDB) {
1290 // Put the PDB next to the image if no /pdb flag was passed.
1291 if (Config->PDBPath.empty()) {
1292 Config->PDBPath = Config->OutputFile;
1293 sys::path::replace_extension(Config->PDBPath, ".pdb");
1294 }
1295
1296 // The embedded PDB path should be the absolute path to the PDB if no
1297 // /pdbaltpath flag was passed.
1298 if (Config->PDBAltPath.empty()) {
1299 Config->PDBAltPath = Config->PDBPath;
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001300
1301 // It's important to make the path absolute and remove dots. This path
1302 // will eventually be written into the PE header, and certain Microsoft
1303 // tools won't work correctly if these assumptions are not held.
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001304 sys::fs::make_absolute(Config->PDBAltPath);
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001305 sys::path::remove_dots(Config->PDBAltPath);
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001306 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001307 }
1308
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001309 // Set default image base if /base is not given.
1310 if (Config->ImageBase == uint64_t(-1))
1311 Config->ImageBase = getDefaultImageBase();
1312
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001313 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001314 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001315 Symtab->addAbsolute("___safe_se_handler_table", 0);
1316 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001317 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001318
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001319 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1320 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001321 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001322 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1323 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1324 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1325 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001326 // Needed for MSVC 2017 15.5 CRT.
1327 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001328
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001329 // This code may add new undefined symbols to the link, which may enqueue more
1330 // symbol resolution tasks, so we need to continue executing tasks until we
1331 // converge.
1332 do {
1333 // Windows specific -- if entry point is not found,
1334 // search for its mangled names.
1335 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001336 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001337
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001338 // Windows specific -- Make sure we resolve all dllexported symbols.
1339 for (Export &E : Config->Exports) {
1340 if (!E.ForwardTo.empty())
1341 continue;
1342 E.Sym = addUndefined(E.Name);
1343 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001344 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001345 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001346
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001347 // Add weak aliases. Weak aliases is a mechanism to give remaining
1348 // undefined symbols final chance to be resolved successfully.
1349 for (auto Pair : Config->AlternateNames) {
1350 StringRef From = Pair.first;
1351 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001352 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001353 if (!Sym)
1354 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001355 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001356 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001357 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001358 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001359
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001360 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001361 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001362 addUndefined(mangle("_load_config_used"));
1363 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001364
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001365 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001366 return;
1367
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001368 // Do LTO by compiling bitcode input files to a set of native COFF files then
1369 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001370 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001371 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001372
Peter Collingbourne2612a322015-07-04 05:28:41 +00001373 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001374 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001375 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001376 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001377
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001378 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001379 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001380 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001381 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001382 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001383 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001384 return;
1385 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001386
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001387 // In MinGW, all symbols are automatically exported if no symbols
1388 // are chosen to be exported.
1389 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1390 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001391 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001392
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001393 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001394 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001395 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001396 return;
1397 Export E;
1398 E.Name = Def->getName();
1399 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001400 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001401 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001402 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001403 Config->Exports.push_back(E);
1404 });
1405 }
1406
Rui Ueyama151d8622015-06-17 20:40:43 +00001407 // Windows specific -- when we are creating a .dll file, we also
1408 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001409 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001410 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001411 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001412 assignExportOrdinals();
1413 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001414
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001415 // Handle /output-def (MinGW specific).
1416 if (auto *Arg = Args.getLastArg(OPT_output_def))
1417 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001418
Martin Storsjod2752aa2017-08-14 19:07:27 +00001419 // Set extra alignment for .comm symbols
1420 for (auto Pair : Config->AlignComm) {
1421 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001422 uint32_t Alignment = Pair.second;
1423
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001424 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001425 if (!Sym) {
1426 warn("/aligncomm symbol " + Name + " not found");
1427 continue;
1428 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001429
Martin Storsjo214d6992018-08-06 19:49:18 +00001430 // If the symbol isn't common, it must have been replaced with a regular
1431 // symbol, which will carry its own alignment.
Rui Ueyama616cd992017-10-31 16:10:24 +00001432 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjo214d6992018-08-06 19:49:18 +00001433 if (!DC)
Martin Storsjod2752aa2017-08-14 19:07:27 +00001434 continue;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001435
1436 CommonChunk *C = DC->getChunk();
1437 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001438 }
1439
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001440 // Windows specific -- Create a side-by-side manifest file.
1441 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001442 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001443
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001444 // Handle /order. We want to do this at this moment because we
1445 // need a complete list of comdat sections to warn on nonexistent
1446 // functions.
1447 if (auto *Arg = Args.getLastArg(OPT_order))
1448 parseOrderFile(Arg->getValue());
1449
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001450 // Identify unreferenced COMDAT sections.
1451 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001452 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001453
1454 // Identify identical COMDAT sections to merge them.
1455 if (Config->DoICF)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001456 doICF(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001457
Rui Ueyama411c63602015-05-28 19:09:30 +00001458 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001459 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001460
1461 // Stop early so we can print the results.
1462 Timer::root().stop();
1463 if (Config->ShowTiming)
1464 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001465}
1466
Rui Ueyama411c63602015-05-28 19:09:30 +00001467} // namespace coff
1468} // namespace lld