blob: b2fe804bce676bf802be1cb97437dcbc9ef2db74 [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"
Peter Collingbourneab038022018-08-23 17:44:42 +000035#include "llvm/Support/LEB128.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000036#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000037#include "llvm/Support/Process.h"
Rui Ueyama7f1f9122017-01-06 02:33:53 +000038#include "llvm/Support/TarWriter.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000039#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000040#include "llvm/Support/raw_ostream.h"
Peter Collingbournec6f07c42017-05-13 22:06:46 +000041#include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000042#include <algorithm>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000043#include <future>
Sam Cleggf187c4d2018-02-20 22:09:59 +000044#include <memory>
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000045
Rui Ueyama411c63602015-05-28 19:09:30 +000046using namespace llvm;
Reid Kleckner146eb7a2017-06-02 17:53:06 +000047using namespace llvm::object;
Rui Ueyama84936e02015-07-07 23:39:18 +000048using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000049using llvm::sys::Process;
Rui Ueyama411c63602015-05-28 19:09:30 +000050
Rui Ueyama3500f662015-05-28 20:30:06 +000051namespace lld {
52namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000053
Zachary Turner727f1532018-01-17 19:16:26 +000054static Timer InputFileTimer("Input File Reading", Timer::root());
55
Rui Ueyama3500f662015-05-28 20:30:06 +000056Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000057LinkerDriver *Driver;
58
Rui Ueyama6f4e2552017-10-23 20:03:32 +000059bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
Rui Ueyama41831202018-08-27 06:18:10 +000060 errorHandler().LogName = args::getFilenameWithoutExe(Args[0]);
Bob Haarmanb8a59c82017-10-25 22:28:38 +000061 errorHandler().ErrorOS = &Diag;
62 errorHandler().ColorDiagnostics = Diag.has_colors();
63 errorHandler().ErrorLimitExceededMsg =
64 "too many errors emitted, stopping now"
Nico Weberf06ae4f2018-03-12 12:45:40 +000065 " (use /errorlimit:0 to see all errors)";
Shoaib Meenaifd3e4b02018-01-08 05:58:36 +000066 errorHandler().ExitEarly = CanExitEarly;
Rui Ueyama7fed58c2016-12-08 19:10:28 +000067 Config = make<Configuration>();
Rui Ueyamacbf969e2017-08-28 21:51:07 +000068
69 Symtab = make<SymbolTable>();
70
Rui Ueyama7fed58c2016-12-08 19:10:28 +000071 Driver = make<LinkerDriver>();
Rui Ueyama417553d2016-02-28 19:54:51 +000072 Driver->link(Args);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000073
74 // Call exit() if we can to avoid calling destructors.
75 if (CanExitEarly)
Bob Haarmanb8a59c82017-10-25 22:28:38 +000076 exitLld(errorCount() ? 1 : 0);
Rui Ueyama6f4e2552017-10-23 20:03:32 +000077
78 freeArena();
Rui Ueyama279621f2018-07-26 17:11:24 +000079 ObjFile::Instances.clear();
80 ImportFile::Instances.clear();
81 BitcodeFile::Instances.clear();
Bob Haarmanb8a59c82017-10-25 22:28:38 +000082 return !errorCount();
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000083}
Rui Ueyama411c63602015-05-28 19:09:30 +000084
Nico Weber5660de72016-04-20 22:34:15 +000085// Drop directory components and replace extension with ".exe" or ".dll".
Rui Ueyamaad660982015-06-07 00:20:32 +000086static std::string getOutputPath(StringRef Path) {
87 auto P = Path.find_last_of("\\/");
88 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
Nico Weber5660de72016-04-20 22:34:15 +000089 const char* E = Config->DLL ? ".dll" : ".exe";
90 return (S.substr(0, S.rfind('.')) + E).str();
Rui Ueyama411c63602015-05-28 19:09:30 +000091}
92
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +000093// ErrorOr is not default constructible, so it cannot be used as the type
94// parameter of a future.
95// FIXME: We could open the file in createFutureForFile and avoid needing to
96// return an error here, but for the moment that would cost us a file descriptor
97// (a limited resource on Windows) for the duration that the future is pending.
98typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
99
100// Create a std::future that opens and maps a file using the best strategy for
101// the host platform.
102static std::future<MBErrPair> createFutureForFile(std::string Path) {
Nico Weberfb647302018-04-10 13:15:21 +0000103#if _WIN32
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000104 // On Windows, file I/O is relatively slow so it is best to do this
105 // asynchronously.
106 auto Strategy = std::launch::async;
107#else
108 auto Strategy = std::launch::deferred;
109#endif
110 return std::async(Strategy, [=]() {
Bob Haarman8832f882018-04-24 23:16:39 +0000111 auto MBOrErr = MemoryBuffer::getFile(Path,
112 /*FileSize*/ -1,
113 /*RequiresNullTerminator*/ false);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000114 if (!MBOrErr)
115 return MBErrPair{nullptr, MBOrErr.getError()};
116 return MBErrPair{std::move(*MBOrErr), std::error_code()};
117 });
118}
119
Nico Weberd48d5f02018-08-03 12:00:12 +0000120// Symbol names are mangled by prepending "_" on x86.
121static StringRef mangle(StringRef Sym) {
122 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
123 if (Config->Machine == I386)
124 return Saver.save("_" + Sym);
125 return Sym;
126}
127
128static bool findUnderscoreMangle(StringRef Sym) {
129 StringRef Entry = Symtab->findMangle(mangle(Sym));
130 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry));
131}
132
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000133MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
134 MemoryBufferRef MBRef = *MB;
Rui Ueyama01f93332017-05-18 17:03:49 +0000135 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000136
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000137 if (Driver->Tar)
138 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
139 MBRef.getBuffer());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000140 return MBRef;
141}
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000142
Martin Storsjo8278ba52017-09-13 07:28:03 +0000143void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
144 bool WholeArchive) {
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000145 StringRef Filename = MB->getBufferIdentifier();
146
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000147 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000148 FilePaths.push_back(Filename);
Peter Collingbournefeee2102016-07-26 02:00:42 +0000149
Rui Ueyama711cd2d2015-05-31 21:17:10 +0000150 // File type is detected by contents, not by file extension.
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000151 switch (identify_magic(MBRef.getBuffer())) {
152 case file_magic::windows_resource:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000153 Resources.push_back(MBRef);
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000154 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000155 case file_magic::archive:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000156 if (WholeArchive) {
157 std::unique_ptr<Archive> File =
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000158 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
Martin Storsjo8278ba52017-09-13 07:28:03 +0000159
160 for (MemoryBufferRef M : getArchiveMembers(File.get()))
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000161 addArchiveBuffer(M, "<whole-archive>", Filename);
Martin Storsjo8278ba52017-09-13 07:28:03 +0000162 return;
163 }
164 Symtab->addFile(make<ArchiveFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000165 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000166 case file_magic::bitcode:
Martin Storsjo8278ba52017-09-13 07:28:03 +0000167 Symtab->addFile(make<BitcodeFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000168 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000169 case file_magic::coff_object:
170 case file_magic::coff_import_library:
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000171 Symtab->addFile(make<ObjFile>(MBRef));
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000172 break;
Rui Ueyamacdd5fb52018-03-01 23:11:30 +0000173 case file_magic::coff_cl_gl_object:
174 error(Filename + ": is not a native COFF file. Recompile without /GL");
175 break;
176 case file_magic::pecoff_executable:
177 if (Filename.endswith_lower(".dll")) {
178 error(Filename + ": bad file type. Did you specify a DLL instead of an "
179 "import library?");
180 break;
181 }
182 LLVM_FALLTHROUGH;
183 default:
184 error(MBRef.getBufferIdentifier() + ": unknown file type");
185 break;
Peter Collingbourne9362ac62017-10-16 23:15:04 +0000186 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000187}
188
Martin Storsjo8278ba52017-09-13 07:28:03 +0000189void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000190 auto Future =
191 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
192 std::string PathStr = Path;
193 enqueueTask([=]() {
194 auto MBOrErr = Future->get();
195 if (MBOrErr.second)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000196 error("could not open " + PathStr + ": " + MBOrErr.second.message());
197 else
Martin Storsjo8278ba52017-09-13 07:28:03 +0000198 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000199 });
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000200}
201
202void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
203 StringRef ParentName) {
204 file_magic Magic = identify_magic(MB.getBuffer());
205 if (Magic == file_magic::coff_import_library) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000206 Symtab->addFile(make<ImportFile>(MB));
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000207 return;
208 }
209
210 InputFile *Obj;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000211 if (Magic == file_magic::coff_object) {
Rui Ueyamae1b48e02017-07-26 23:05:24 +0000212 Obj = make<ObjFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000213 } else if (Magic == file_magic::bitcode) {
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000214 Obj = make<BitcodeFile>(MB);
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000215 } else {
216 error("unknown file type: " + MB.getBufferIdentifier());
217 return;
218 }
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000219
220 Obj->ParentName = ParentName;
Rui Ueyamacbf969e2017-08-28 21:51:07 +0000221 Symtab->addFile(Obj);
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000222 log("Loaded " + toString(Obj) + " for " + SymName);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000223}
224
225void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
226 StringRef SymName,
227 StringRef ParentName) {
228 if (!C.getParent()->isThin()) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000229 MemoryBufferRef MB = CHECK(
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000230 C.getMemoryBufferRef(),
231 "could not get the buffer for the member defining symbol " + SymName);
232 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
233 return;
234 }
235
236 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
Rui Ueyamabdc51502017-12-06 22:08:17 +0000237 CHECK(C.getFullName(),
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000238 "could not get the filename for the member defining symbol " +
239 SymName)));
240 enqueueTask([=]() {
241 auto MBOrErr = Future->get();
242 if (MBOrErr.second)
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000243 fatal("could not get the buffer for the member defining " + SymName +
244 ": " + MBOrErr.second.message());
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000245 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
246 ParentName);
247 });
Rui Ueyama411c63602015-05-28 19:09:30 +0000248}
249
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000250static bool isDecorated(StringRef Sym) {
Martin Storsjoddb094a2017-10-23 09:08:24 +0000251 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
252 (!Config->MinGW && Sym.contains('@'));
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000253}
254
Rui Ueyama411c63602015-05-28 19:09:30 +0000255// Parses .drectve section contents and returns a list of files
256// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000257void LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000258 ArgParser Parser;
Nico Webera05cbb82017-09-05 23:46:45 +0000259 // .drectve is always tokenized using Windows shell rules.
Rui Ueyama5fa0d6e2018-01-09 20:36:42 +0000260 // /EXPORT: option can appear too many times, processing in fastpath.
261 opt::InputArgList Args;
262 std::vector<StringRef> Exports;
263 std::tie(Args, Exports) = Parser.parseDirectives(S);
264
265 for (StringRef E : Exports) {
266 // If a common header file contains dllexported function
267 // declarations, many object files may end up with having the
268 // same /EXPORT options. In order to save cost of parsing them,
269 // we dedup them first.
270 if (!DirectivesExports.insert(E).second)
271 continue;
272
273 Export Exp = parseExport(E);
274 if (Config->Machine == I386 && Config->MinGW) {
275 if (!isDecorated(Exp.Name))
276 Exp.Name = Saver.save("_" + Exp.Name);
277 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
278 Exp.ExtName = Saver.save("_" + Exp.ExtName);
279 }
280 Exp.Directives = true;
281 Config->Exports.push_back(Exp);
282 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000283
David Blaikie6521ed92015-06-22 22:06:52 +0000284 for (auto *Arg : Args) {
Rui Ueyama38b0f4a2017-07-19 20:30:04 +0000285 switch (Arg->getOption().getUnaliasedOption().getID()) {
Martin Storsjod2752aa2017-08-14 19:07:27 +0000286 case OPT_aligncomm:
287 parseAligncomm(Arg->getValue());
288 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000289 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000290 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000291 break;
292 case OPT_defaultlib:
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000293 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +0000294 enqueuePath(*Path, false);
Rui Ueyama562daa82015-06-18 21:50:38 +0000295 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000296 case OPT_entry:
297 Config->Entry = addUndefined(mangle(Arg->getValue()));
298 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000299 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000300 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000301 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000302 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000303 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000304 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000305 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000306 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000307 break;
308 case OPT_nodefaultlib:
309 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
310 break;
Rui Ueyama440138c2016-06-20 03:39:39 +0000311 case OPT_section:
312 parseSection(Arg->getValue());
313 break;
Rui Ueyama215286f2017-11-29 20:46:13 +0000314 case OPT_subsystem:
315 parseSubsystem(Arg->getValue(), &Config->Subsystem,
316 &Config->MajorOSVersion, &Config->MinorOSVersion);
317 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000318 case OPT_editandcontinue:
Reid Kleckner9cd77ce2016-03-25 18:09:29 +0000319 case OPT_fastfail:
Rui Ueyama31e66e32015-09-03 16:20:47 +0000320 case OPT_guardsym:
Rui Ueyama9d9bdab2017-09-11 22:24:13 +0000321 case OPT_natvis:
Rui Ueyama432383172015-07-29 21:01:15 +0000322 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000323 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000324 default:
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000325 error(Arg->getSpelling() + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000326 }
327 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000328}
329
Rui Ueyama54b71da2015-05-31 19:17:12 +0000330// Find file from search paths. You can omit ".obj", this function takes
331// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000332StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000333 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
334 if (HasPathSep)
Rui Ueyama54b71da2015-05-31 19:17:12 +0000335 return Filename;
Rui Ueyama12234f82017-07-19 21:40:26 +0000336 bool HasExt = Filename.contains('.');
Rui Ueyama54b71da2015-05-31 19:17:12 +0000337 for (StringRef Dir : SearchPaths) {
338 SmallString<128> Path = Dir;
Rui Ueyama8fe17672016-12-08 20:50:47 +0000339 sys::path::append(Path, Filename);
340 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000341 return Saver.save(Path.str());
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000342 if (!HasExt) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000343 Path.append(".obj");
Rui Ueyama8fe17672016-12-08 20:50:47 +0000344 if (sys::fs::exists(Path.str()))
Rui Ueyama8d433d72016-12-08 21:27:09 +0000345 return Saver.save(Path.str());
Rui Ueyama54b71da2015-05-31 19:17:12 +0000346 }
347 }
348 return Filename;
349}
350
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000351static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
352 sys::fs::UniqueID Ret;
353 if (sys::fs::getUniqueID(Path, Ret))
354 return None;
355 return Ret;
356}
357
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000358// Resolves a file path. This never returns the same path
359// (in that case, it returns None).
360Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
361 StringRef Path = doFindFile(Filename);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000362
363 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
364 bool Seen = !VisitedFiles.insert(*ID).second;
365 if (Seen)
366 return None;
367 }
368
Rui Ueyamab59ceb12017-12-11 23:09:18 +0000369 if (Path.endswith_lower(".lib"))
370 VisitedLibs.insert(sys::path::filename(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000371 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000372}
373
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000374// Find library file from search path.
375StringRef LinkerDriver::doFindLib(StringRef Filename) {
376 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama12234f82017-07-19 21:40:26 +0000377 bool HasExt = Filename.contains('.');
Rui Ueyamabf4ddeb2016-11-29 04:22:57 +0000378 if (!HasExt)
Rui Ueyama8d433d72016-12-08 21:27:09 +0000379 Filename = Saver.save(Filename + ".lib");
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000380 return doFindFile(Filename);
381}
382
383// Resolves a library path. /nodefaultlib options are taken into
384// consideration. This never returns the same path (in that case,
385// it returns None).
386Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
387 if (Config->NoDefaultLibAll)
388 return None;
Peter Collingbournec1ded7d2016-12-16 03:45:59 +0000389 if (!VisitedLibs.insert(Filename.lower()).second)
390 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000391
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000392 StringRef Path = doFindLib(Filename);
393 if (Config->NoDefaultLibs.count(Path))
394 return None;
Rui Ueyama4eed6cc2018-06-12 21:47:31 +0000395
396 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
397 if (!VisitedFiles.insert(*ID).second)
398 return None;
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000399 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000400}
401
402// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000403void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000404 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
405 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000406 return;
Rui Ueyama8d433d72016-12-08 21:27:09 +0000407 StringRef Env = Saver.save(*EnvOpt);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000408 while (!Env.empty()) {
409 StringRef Path;
410 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000411 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000412 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000413}
414
Rui Ueyamaf52496e2017-11-03 21:21:47 +0000415Symbol *LinkerDriver::addUndefined(StringRef Name) {
416 Symbol *B = Symtab->addUndefined(Name);
Reid Kleckner58839892017-11-13 18:38:53 +0000417 if (!B->IsGCRoot) {
418 B->IsGCRoot = true;
419 Config->GCRoot.push_back(B);
420 }
Peter Collingbourne79a5e6b2016-12-09 21:55:24 +0000421 return B;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000422}
423
Rui Ueyama45044f42015-06-29 01:03:53 +0000424// Windows specific -- find default entry point name.
Rui Ueyamac93530d2018-07-18 17:48:14 +0000425//
426// There are four different entry point functions for Windows executables,
427// each of which corresponds to a user-defined "main" function. This function
428// infers an entry point from a user-defined "main" function.
Rui Ueyama45044f42015-06-29 01:03:53 +0000429StringRef LinkerDriver::findDefaultEntry() {
Nico Weberf4f5b7e2018-08-07 19:10:28 +0000430 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
431 "must handle /subsystem before calling this");
432
433 // As a special case, if /nodefaultlib is given, we directly look for an
434 // entry point. This is because, if no default library is linked, users
435 // need to define an entry point instead of a "main".
436 bool FindMain = !Config->NoDefaultLibAll;
437 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
438 if (findUnderscoreMangle(FindMain ? "WinMain" : "WinMainCRTStartup"))
439 return mangle("WinMainCRTStartup");
440 if (findUnderscoreMangle(FindMain ? "wWinMain" : "wWinMainCRTStartup"))
441 return mangle("wWinMainCRTStartup");
Rui Ueyama45044f42015-06-29 01:03:53 +0000442 }
Nico Weberf4f5b7e2018-08-07 19:10:28 +0000443 if (findUnderscoreMangle(FindMain ? "main" : "mainCRTStartup"))
444 return mangle("mainCRTStartup");
445 if (findUnderscoreMangle(FindMain ? "wmain" : "wmainCRTStartup"))
446 return mangle("wmainCRTStartup");
Rui Ueyama45044f42015-06-29 01:03:53 +0000447 return "";
448}
449
450WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000451 if (Config->DLL)
452 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Nico Weberebc27c42018-08-22 16:47:16 +0000453 bool HaveMain = findUnderscoreMangle("main");
454 bool HaveWMain = findUnderscoreMangle("wmain");
455 bool HaveWinMain = findUnderscoreMangle("WinMain");
456 bool HaveWWinMain = findUnderscoreMangle("wWinMain");
457 if (HaveMain || HaveWMain) {
458 if (HaveWinMain || HaveWWinMain) {
459 warn(std::string("found ") + (HaveMain ? "main" : "wmain") + " and " +
460 (HaveWinMain ? "WinMain" : "wWinMain") +
461 "; defaulting to /subsystem:console");
462 }
Rui Ueyama45044f42015-06-29 01:03:53 +0000463 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Nico Weberebc27c42018-08-22 16:47:16 +0000464 }
465 if (HaveWinMain || HaveWWinMain)
Rui Ueyama45044f42015-06-29 01:03:53 +0000466 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
467 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000468}
469
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000470static uint64_t getDefaultImageBase() {
471 if (Config->is64())
472 return Config->DLL ? 0x180000000 : 0x140000000;
473 return Config->DLL ? 0x10000000 : 0x400000;
474}
475
Rui Ueyama8fe17672016-12-08 20:50:47 +0000476static std::string createResponseFile(const opt::InputArgList &Args,
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000477 ArrayRef<StringRef> FilePaths,
Peter Collingbournefeee2102016-07-26 02:00:42 +0000478 ArrayRef<StringRef> SearchPaths) {
479 SmallString<0> Data;
480 raw_svector_ostream OS(Data);
481
482 for (auto *Arg : Args) {
483 switch (Arg->getOption().getID()) {
484 case OPT_linkrepro:
485 case OPT_INPUT:
486 case OPT_defaultlib:
487 case OPT_libpath:
Peter Collingbourneacc3baa2017-10-25 05:00:54 +0000488 case OPT_manifest:
489 case OPT_manifest_colon:
490 case OPT_manifestdependency:
491 case OPT_manifestfile:
492 case OPT_manifestinput:
493 case OPT_manifestuac:
Peter Collingbournefeee2102016-07-26 02:00:42 +0000494 break;
495 default:
Sam Clegg7e756632017-12-05 16:50:46 +0000496 OS << toString(*Arg) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000497 }
498 }
499
500 for (StringRef Path : SearchPaths) {
501 std::string RelPath = relativeToRoot(Path);
502 OS << "/libpath:" << quote(RelPath) << "\n";
503 }
504
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000505 for (StringRef Path : FilePaths)
506 OS << quote(relativeToRoot(Path)) << "\n";
Peter Collingbournefeee2102016-07-26 02:00:42 +0000507
508 return Data.str();
509}
510
Rui Ueyama8fe17672016-12-08 20:50:47 +0000511static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000512 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
513 if (Args.hasArg(OPT_driver))
514 DebugTypes |= static_cast<unsigned>(DebugType::PData);
515 if (Args.hasArg(OPT_profile))
516 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
517 return DebugTypes;
518}
519
520static unsigned parseDebugType(StringRef Arg) {
Rui Ueyama8fe17672016-12-08 20:50:47 +0000521 SmallVector<StringRef, 3> Types;
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000522 Arg.split(Types, ',', /*KeepEmpty=*/false);
523
524 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
525 for (StringRef Type : Types)
526 DebugTypes |= StringSwitch<unsigned>(Type.lower())
527 .Case("cv", static_cast<unsigned>(DebugType::CV))
528 .Case("pdata", static_cast<unsigned>(DebugType::PData))
Saleem Abdulrasoolb6394282017-02-07 04:28:05 +0000529 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
530 .Default(0);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000531 return DebugTypes;
532}
533
Hans Wennborg1818e652016-12-09 20:54:44 +0000534static std::string getMapFile(const opt::InputArgList &Args) {
535 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
536 if (!Arg)
537 return "";
538 if (Arg->getOption().getID() == OPT_lldmap_file)
539 return Arg->getValue();
540
541 assert(Arg->getOption().getID() == OPT_lldmap);
542 StringRef OutFile = Config->OutputFile;
543 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
544}
545
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000546static std::string getImplibPath() {
547 if (!Config->Implib.empty())
548 return Config->Implib;
549 SmallString<128> Out = StringRef(Config->OutputFile);
550 sys::path::replace_extension(Out, ".lib");
551 return Out.str();
552}
553
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000554//
555// The import name is caculated as the following:
556//
557// | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
558// -----+----------------+---------------------+------------------
559// LINK | {value} | {value}.{.dll/.exe} | {output name}
560// LIB | {value} | {value}.dll | {output name}.dll
561//
562static std::string getImportName(bool AsLib) {
563 SmallString<128> Out;
564
565 if (Config->ImportName.empty()) {
566 Out.assign(sys::path::filename(Config->OutputFile));
567 if (AsLib)
568 sys::path::replace_extension(Out, ".dll");
569 } else {
570 Out.assign(Config->ImportName);
571 if (!sys::path::has_extension(Out))
572 sys::path::replace_extension(Out,
573 (Config->DLL || AsLib) ? ".dll" : ".exe");
574 }
575
576 return Out.str();
577}
578
579static void createImportLibrary(bool AsLib) {
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000580 std::vector<COFFShortExport> Exports;
581 for (Export &E1 : Config->Exports) {
582 COFFShortExport E2;
Martin Storsjoa50275cf2017-08-16 05:13:25 +0000583 E2.Name = E1.Name;
584 E2.SymbolName = E1.SymbolName;
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000585 E2.ExtName = E1.ExtName;
586 E2.Ordinal = E1.Ordinal;
587 E2.Noname = E1.Noname;
588 E2.Data = E1.Data;
589 E2.Private = E1.Private;
590 E2.Constant = E1.Constant;
591 Exports.push_back(E2);
592 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000593
Bob Haarman4ce341f2018-01-23 00:36:42 +0000594 auto HandleError = [](Error &&E) {
595 handleAllErrors(std::move(E),
596 [](ErrorInfoBase &EIB) { error(EIB.message()); });
597 };
598 std::string LibName = getImportName(AsLib);
599 std::string Path = getImplibPath();
600
Bob Haarman5ec44852018-01-31 23:44:00 +0000601 if (!Config->Incremental) {
602 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000603 Config->MinGW));
Bob Haarman5ec44852018-01-31 23:44:00 +0000604 return;
605 }
606
Bob Haarman4ce341f2018-01-23 00:36:42 +0000607 // If the import library already exists, replace it only if the contents
608 // have changed.
Bob Haarman8832f882018-04-24 23:16:39 +0000609 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
610 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000611 if (!OldBuf) {
612 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000613 Config->MinGW));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000614 return;
615 }
616
617 SmallString<128> TmpName;
618 if (std::error_code EC =
619 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
620 fatal("cannot create temporary file for import library " + Path + ": " +
621 EC.message());
622
623 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
Martin Storsjo97379ff2018-05-09 09:22:03 +0000624 Config->MinGW)) {
Bob Haarman4ce341f2018-01-23 00:36:42 +0000625 HandleError(std::move(E));
626 return;
627 }
628
Bob Haarman8832f882018-04-24 23:16:39 +0000629 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
630 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
Bob Haarman4ce341f2018-01-23 00:36:42 +0000631 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
632 OldBuf->reset();
633 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
Martin Storsjocf47b042018-01-30 07:26:01 +0000634 } else {
635 sys::fs::remove(TmpName);
Bob Haarman4ce341f2018-01-23 00:36:42 +0000636 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000637}
638
639static void parseModuleDefs(StringRef Path) {
Rui Ueyamabdc51502017-12-06 22:08:17 +0000640 std::unique_ptr<MemoryBuffer> MB = CHECK(
641 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
Martin Storsjoddb094a2017-10-23 09:08:24 +0000642 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
643 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000644
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000645 if (Config->OutputFile.empty())
646 Config->OutputFile = Saver.save(M.OutputFile);
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +0000647 Config->ImportName = Saver.save(M.ImportName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000648 if (M.ImageBase)
649 Config->ImageBase = M.ImageBase;
650 if (M.StackReserve)
651 Config->StackReserve = M.StackReserve;
652 if (M.StackCommit)
653 Config->StackCommit = M.StackCommit;
654 if (M.HeapReserve)
655 Config->HeapReserve = M.HeapReserve;
656 if (M.HeapCommit)
657 Config->HeapCommit = M.HeapCommit;
658 if (M.MajorImageVersion)
659 Config->MajorImageVersion = M.MajorImageVersion;
660 if (M.MinorImageVersion)
661 Config->MinorImageVersion = M.MinorImageVersion;
662 if (M.MajorOSVersion)
663 Config->MajorOSVersion = M.MajorOSVersion;
664 if (M.MinorOSVersion)
665 Config->MinorOSVersion = M.MinorOSVersion;
666
667 for (COFFShortExport E1 : M.Exports) {
668 Export E2;
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000669 // In simple cases, only Name is set. Renamed exports are parsed
670 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
671 // it shouldn't be a normal exported function but a forward to another
672 // DLL instead. This is supported by both MS and GNU linkers.
673 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
Martin Storsjo5c84d442018-05-09 19:07:10 +0000674 E2.Name = Saver.save(E1.ExtName);
675 E2.ForwardTo = Saver.save(E1.Name);
Martin Storsjo0ca06f72018-05-09 18:19:41 +0000676 Config->Exports.push_back(E2);
677 continue;
678 }
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000679 E2.Name = Saver.save(E1.Name);
Martin Storsjo97379ff2018-05-09 09:22:03 +0000680 E2.ExtName = Saver.save(E1.ExtName);
Reid Kleckner146eb7a2017-06-02 17:53:06 +0000681 E2.Ordinal = E1.Ordinal;
682 E2.Noname = E1.Noname;
683 E2.Data = E1.Data;
684 E2.Private = E1.Private;
685 E2.Constant = E1.Constant;
686 Config->Exports.push_back(E2);
687 }
688}
689
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000690void LinkerDriver::enqueueTask(std::function<void()> Task) {
691 TaskQueue.push_back(std::move(Task));
692}
693
694bool LinkerDriver::run() {
Zachary Turner727f1532018-01-17 19:16:26 +0000695 ScopedTimer T(InputFileTimer);
696
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +0000697 bool DidWork = !TaskQueue.empty();
698 while (!TaskQueue.empty()) {
699 TaskQueue.front()();
700 TaskQueue.pop_front();
701 }
702 return DidWork;
703}
704
Rui Ueyama57175aa2018-01-27 00:34:46 +0000705// Parse an /order file. If an option is given, the linker places
706// COMDAT sections in the same order as their names appear in the
707// given file.
708static void parseOrderFile(StringRef Arg) {
709 // For some reason, the MSVC linker requires a filename to be
710 // preceded by "@".
711 if (!Arg.startswith("@")) {
712 error("malformed /order option: '@' missing");
713 return;
714 }
715
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000716 // Get a list of all comdat sections for error checking.
717 DenseSet<StringRef> Set;
718 for (Chunk *C : Symtab->getChunks())
719 if (auto *Sec = dyn_cast<SectionChunk>(C))
720 if (Sec->Sym)
721 Set.insert(Sec->Sym->getName());
722
Rui Ueyama57175aa2018-01-27 00:34:46 +0000723 // Open a file.
724 StringRef Path = Arg.substr(1);
725 std::unique_ptr<MemoryBuffer> MB = CHECK(
726 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
727
728 // Parse a file. An order file contains one symbol per line.
729 // All symbols that were not present in a given order file are
730 // considered to have the lowest priority 0 and are placed at
731 // end of an output section.
732 for (std::string S : args::getLines(MB->getMemBufferRef())) {
733 if (Config->Machine == I386 && !isDecorated(S))
734 S = "_" + S;
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000735
Nico Weber0771c602018-03-09 12:41:04 +0000736 if (Set.count(S) == 0) {
737 if (Config->WarnMissingOrderSymbol)
Nico Weber11a6db32018-03-12 12:04:17 +0000738 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
Nico Weber0771c602018-03-09 12:41:04 +0000739 }
Rui Ueyamab6d3a932018-01-29 21:50:53 +0000740 else
741 Config->Order[S] = INT_MIN + Config->Order.size();
Rui Ueyama57175aa2018-01-27 00:34:46 +0000742 }
743}
744
Peter Collingbourneab038022018-08-23 17:44:42 +0000745static void markAddrsig(Symbol *S) {
746 if (auto *D = dyn_cast_or_null<Defined>(S))
747 if (Chunk *C = D->getChunk())
748 C->KeepUnique = true;
749}
750
751static void findKeepUniqueSections() {
752 // Exported symbols could be address-significant in other executables or DSOs,
753 // so we conservatively mark them as address-significant.
754 for (Export &R : Config->Exports)
755 markAddrsig(R.Sym);
756
757 // Visit the address-significance table in each object file and mark each
758 // referenced symbol as address-significant.
759 for (ObjFile *Obj : ObjFile::Instances) {
760 ArrayRef<Symbol *> Syms = Obj->getSymbols();
761 if (Obj->AddrsigSec) {
762 ArrayRef<uint8_t> Contents;
763 Obj->getCOFFObj()->getSectionContents(Obj->AddrsigSec, Contents);
764 const uint8_t *Cur = Contents.begin();
765 while (Cur != Contents.end()) {
766 unsigned Size;
767 const char *Err;
768 uint64_t SymIndex = decodeULEB128(Cur, &Size, Contents.end(), &Err);
769 if (Err)
770 fatal(toString(Obj) + ": could not decode addrsig section: " + Err);
771 if (SymIndex >= Syms.size())
772 fatal(toString(Obj) + ": invalid symbol index in addrsig section");
773 markAddrsig(Syms[SymIndex]);
774 Cur += Size;
775 }
776 } else {
777 // If an object file does not have an address-significance table,
778 // conservatively mark all of its symbols as address-significant.
779 for (Symbol *S : Syms)
780 markAddrsig(S);
781 }
782 }
783}
784
Rui Ueyama8fe17672016-12-08 20:50:47 +0000785void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000786 // If the first command line argument is "/lib", link.exe acts like lib.exe.
787 // We call our own implementation of lib.exe that understands bitcode files.
788 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
789 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
Rui Ueyama60604792016-07-14 23:37:14 +0000790 fatal("lib failed");
Rui Ueyama27e470a2015-08-09 20:45:17 +0000791 return;
792 }
793
Peter Collingbourne60c16162015-06-01 20:10:10 +0000794 // Needed for LTO.
Rui Ueyama8fe17672016-12-08 20:50:47 +0000795 InitializeAllTargetInfos();
796 InitializeAllTargets();
797 InitializeAllTargetMCs();
798 InitializeAllAsmParsers();
799 InitializeAllAsmPrinters();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000800
Rui Ueyama411c63602015-05-28 19:09:30 +0000801 // Parse command line options.
Rui Ueyamaaffb40e2017-08-28 20:46:30 +0000802 ArgParser Parser;
Reid Kleckner276d7162018-07-20 22:34:20 +0000803 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000804
Rui Ueyama9a3e7332017-03-30 20:10:40 +0000805 // Parse and evaluate -mllvm options.
806 std::vector<const char *> V;
807 V.push_back("lld-link (LLVM option parsing)");
808 for (auto *Arg : Args.filtered(OPT_mllvm))
809 V.push_back(Arg->getValue());
810 cl::ParseCommandLineOptions(V.size(), V.data());
811
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000812 // Handle /errorlimit early, because error() depends on it.
813 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
814 int N = 20;
815 StringRef S = Arg->getValue();
816 if (S.getAsInteger(10, N))
817 error(Arg->getSpelling() + " number expected, but got " + S);
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000818 errorHandler().ErrorLimit = N;
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000819 }
820
Rui Ueyama5c726432015-05-29 16:11:52 +0000821 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000822 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000823 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000824 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000825 }
826
Zachary Turner727f1532018-01-17 19:16:26 +0000827 if (Args.hasArg(OPT_show_timing))
828 Config->ShowTiming = true;
829
830 ScopedTimer T(Timer::root());
Rui Ueyamaa4cf97b2017-10-23 14:57:53 +0000831 // Handle --version, which is an lld extension. This option is a bit odd
832 // because it doesn't start with "/", but we deliberately chose "--" to
833 // avoid conflict with /version and for compatibility with clang-cl.
834 if (Args.hasArg(OPT_dash_dash_version)) {
835 outs() << getLLDVersion() << "\n";
836 return;
837 }
838
Martin Storsjo31fe4cd2017-09-13 19:29:39 +0000839 // Handle /lldmingw early, since it can potentially affect how other
840 // options are handled.
841 Config->MinGW = Args.hasArg(OPT_lldmingw);
842
Peter Collingbournefeee2102016-07-26 02:00:42 +0000843 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
844 SmallString<64> Path = StringRef(Arg->getValue());
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000845 sys::path::append(Path, "repro.tar");
846
847 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
848 TarWriter::create(Path, "repro");
849
850 if (ErrOrWriter) {
851 Tar = std::move(*ErrOrWriter);
852 } else {
Rui Ueyamae6e206d2017-02-21 23:22:56 +0000853 error("/linkrepro: failed to open " + Path + ": " +
854 toString(ErrOrWriter.takeError()));
Rui Ueyama7f1f9122017-01-06 02:33:53 +0000855 }
Peter Collingbournefeee2102016-07-26 02:00:42 +0000856 }
857
Rui Ueyamaa835bab2017-09-13 20:30:59 +0000858 if (!Args.hasArg(OPT_INPUT)) {
859 if (Args.hasArg(OPT_deffile))
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +0000860 Config->NoEntry = true;
861 else
862 fatal("no input files");
863 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000864
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000865 // Construct search path list.
866 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000867 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000868 SearchPaths.push_back(Arg->getValue());
869 addLibSearchPaths();
870
Bob Haarmane90ac012017-12-28 07:02:13 +0000871 // Handle /ignore
872 for (auto *Arg : Args.filtered(OPT_ignore)) {
Nico Weber0771c602018-03-09 12:41:04 +0000873 if (StringRef(Arg->getValue()) == "4037")
874 Config->WarnMissingOrderSymbol = false;
875 else if (StringRef(Arg->getValue()) == "4217")
Bob Haarmane90ac012017-12-28 07:02:13 +0000876 Config->WarnLocallyDefinedImported = false;
877 // Other warning numbers are ignored.
878 }
879
Rui Ueyamaad660982015-06-07 00:20:32 +0000880 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000881 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000882 Config->OutputFile = Arg->getValue();
883
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000884 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000885 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000886 Config->Verbose = true;
Bob Haarmanb8a59c82017-10-25 22:28:38 +0000887 errorHandler().Verbose = Config->Verbose;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000888
Rui Ueyama95925fd2015-06-28 19:35:15 +0000889 // Handle /force or /force:unresolved
Shoaib Meenai111db792017-12-15 23:51:14 +0000890 if (Args.hasArg(OPT_force, OPT_force_unresolved))
Rui Ueyama11ca38f2018-09-13 22:05:10 +0000891 Config->ForceUnresolved = true;
892
893 // Handle /force or /force:multiple
894 if (Args.hasArg(OPT_force, OPT_force_multiple))
895 Config->ForceMultiple = true;
Rui Ueyama95925fd2015-06-28 19:35:15 +0000896
Rui Ueyama6600eb12015-07-04 23:37:32 +0000897 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000898 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000899 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000900 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000901 if (auto *Arg = Args.getLastArg(OPT_debugtype))
902 Config->DebugTypes = parseDebugType(Arg->getValue());
903 else
904 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000905 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000906
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000907 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000908 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000909 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000910 if (auto *Arg = Args.getLastArg(OPT_pdb))
911 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000912 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
913 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000914 if (Args.hasArg(OPT_natvis))
915 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
Takuto Ikutad8559282018-07-19 04:56:22 +0000916
917 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
918 Config->PDBSourcePath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000919 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000920
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000921 // Handle /noentry
922 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000923 if (Args.hasArg(OPT_dll))
924 Config->NoEntry = true;
925 else
926 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000927 }
928
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000929 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000930 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000931 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000932 Config->ManifestID = 2;
933 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000934
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000935 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
936 // because we need to explicitly check whether that option or its inverse was
937 // present in the argument list in order to handle /fixed.
938 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
939 if (DynamicBaseArg &&
940 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
941 Config->DynamicBase = false;
942
Nico Webera7643792018-03-30 17:17:04 +0000943 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
944 // default setting for any other project type.", but link.exe defaults to
945 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000946 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
947 if (Fixed) {
948 if (DynamicBaseArg &&
949 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000950 error("/fixed must not be specified with /dynamicbase");
951 } else {
952 Config->Relocatable = false;
953 Config->DynamicBase = false;
954 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000955 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000956
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000957 // Handle /appcontainer
958 Config->AppContainer =
959 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000960
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000961 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000962 if (auto *Arg = Args.getLastArg(OPT_machine))
963 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000964
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000965 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000966 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000967 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
968
969 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000970 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000971 Config->NoDefaultLibAll = true;
972
Rui Ueyama804a8b62015-05-29 16:18:15 +0000973 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000974 if (auto *Arg = Args.getLastArg(OPT_base))
975 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000976
977 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000978 if (auto *Arg = Args.getLastArg(OPT_stack))
979 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000980
Reid Kleckneraf2f7da2018-02-06 01:58:26 +0000981 // Handle /guard:cf
982 if (auto *Arg = Args.getLastArg(OPT_guard))
983 parseGuard(Arg->getValue());
984
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000985 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000986 if (auto *Arg = Args.getLastArg(OPT_heap))
987 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000988
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000989 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000990 if (auto *Arg = Args.getLastArg(OPT_version))
991 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
992 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000993
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000994 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000995 if (auto *Arg = Args.getLastArg(OPT_subsystem))
996 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
997 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000998
Zachary Turnerc8dd6cc2018-05-17 15:11:01 +0000999 // Handle /timestamp
1000 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1001 if (Arg->getOption().getID() == OPT_repro) {
1002 Config->Timestamp = 0;
1003 Config->Repro = true;
1004 } else {
1005 Config->Repro = false;
1006 StringRef Value(Arg->getValue());
1007 if (Value.getAsInteger(0, Config->Timestamp))
1008 fatal(Twine("invalid timestamp: ") + Value +
1009 ". Expected 32-bit integer");
1010 }
1011 } else {
1012 Config->Repro = false;
1013 Config->Timestamp = time(nullptr);
1014 }
1015
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001016 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001017 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001018 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001019
Rui Ueyama08d5e182015-06-18 23:20:11 +00001020 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001021 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001022 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001023
Rui Ueyamab95188c2015-06-18 20:27:09 +00001024 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001025 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001026 Config->Implib = Arg->getValue();
1027
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001028 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001029 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1030 unsigned ICFLevel =
1031 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001032 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +00001033 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001034 std::string Str = StringRef(Arg->getValue()).lower();
1035 SmallVector<StringRef, 1> Vec;
1036 StringRef(Str).split(Vec, ',');
1037 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001038 if (S == "ref") {
1039 DoGC = true;
1040 } else if (S == "noref") {
1041 DoGC = false;
1042 } else if (S == "icf" || S.startswith("icf=")) {
1043 ICFLevel = 2;
1044 } else if (S == "noicf") {
1045 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001046 } else if (S == "lldtailmerge") {
1047 TailMerge = 2;
1048 } else if (S == "nolldtailmerge") {
1049 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001050 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001051 StringRef OptLevel = S.substr(7);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001052 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001053 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001054 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001055 StringRef Jobs = S.substr(11);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001056 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1057 Config->ThinLTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001058 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001059 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001060 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001061 if (N.getAsInteger(10, Config->LTOPartitions) ||
1062 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001063 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001064 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001065 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001066 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001067 }
1068
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001069 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1070 // explicitly.
1071 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1072 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1073 // comdat readonly data.
1074 if (ICFLevel == 1 && !DoGC)
1075 ICFLevel = 0;
1076 Config->DoGC = DoGC;
1077 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001078 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001079
Bob Haarman69b196d2017-02-08 18:36:41 +00001080 // Handle /lldsavetemps
1081 if (Args.hasArg(OPT_lldsavetemps))
1082 Config->SaveTemps = true;
1083
Martin Storsjo53518912018-03-14 20:17:16 +00001084 // Handle /kill-at
1085 if (Args.hasArg(OPT_kill_at))
1086 Config->KillAt = true;
1087
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001088 // Handle /lldltocache
1089 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1090 Config->LTOCache = Arg->getValue();
1091
1092 // Handle /lldsavecachepolicy
1093 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001094 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001095 parseCachePruningPolicy(Arg->getValue()),
1096 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1097
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001098 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001099 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001100 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001101
Rui Ueyama6600eb12015-07-04 23:37:32 +00001102 // Handle /merge
1103 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001104 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001105
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001106 // Add default section merging rules after user rules. User rules take
1107 // precedence, but we will emit a warning if there is a conflict.
1108 parseMerge(".idata=.rdata");
1109 parseMerge(".didat=.rdata");
1110 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001111 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001112 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001113
Martin Storsjocfbbb702018-08-29 17:24:10 +00001114 if (Config->MinGW) {
1115 parseMerge(".ctors=.rdata");
1116 parseMerge(".dtors=.rdata");
1117 parseMerge(".CRT=.rdata");
1118 }
1119
Rui Ueyama440138c2016-06-20 03:39:39 +00001120 // Handle /section
1121 for (auto *Arg : Args.filtered(OPT_section))
1122 parseSection(Arg->getValue());
1123
Martin Storsjod2752aa2017-08-14 19:07:27 +00001124 // Handle /aligncomm
1125 for (auto *Arg : Args.filtered(OPT_aligncomm))
1126 parseAligncomm(Arg->getValue());
1127
Nico Webera7a2c442017-07-25 18:08:03 +00001128 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1129 // also passed.
1130 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1131 Config->ManifestDependency = Arg->getValue();
1132 Config->Manifest = Configuration::SideBySide;
1133 }
1134
1135 // Handle /manifest and /manifest:
1136 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1137 if (Arg->getOption().getID() == OPT_manifest)
1138 Config->Manifest = Configuration::SideBySide;
1139 else
1140 parseManifest(Arg->getValue());
1141 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001142
1143 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001144 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1145 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001146
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001147 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001148 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001149 Config->ManifestFile = Arg->getValue();
1150
Rui Ueyamaafb19012016-04-19 01:21:58 +00001151 // Handle /manifestinput
1152 for (auto *Arg : Args.filtered(OPT_manifestinput))
1153 Config->ManifestInput.push_back(Arg->getValue());
1154
Nico Webera7a2c442017-07-25 18:08:03 +00001155 if (!Config->ManifestInput.empty() &&
1156 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001157 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001158 }
1159
Rui Ueyama6592ff82015-06-16 23:13:00 +00001160 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001161 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1162 Config->AllowIsolation =
1163 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001164 Config->Incremental =
1165 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001166 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1167 !Args.hasArg(OPT_profile));
Nico Weberd657c252018-05-31 13:43:02 +00001168 Config->IntegrityCheck =
1169 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001170 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001171 Config->TerminalServerAware =
1172 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001173 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001174 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Martin Storsjo3a7905b2018-06-29 06:08:25 +00001175 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001176
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001177 Config->MapFile = getMapFile(Args);
1178
Nico Weber0945ad62018-03-30 17:14:50 +00001179 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1180 warn("ignoring '/incremental' due to '/profile' specification");
1181 Config->Incremental = false;
1182 }
1183
1184 if (Config->Incremental && Args.hasArg(OPT_order)) {
1185 warn("ignoring '/incremental' due to '/order' specification");
1186 Config->Incremental = false;
1187 }
1188
Bob Haarman5ec44852018-01-31 23:44:00 +00001189 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001190 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001191 "disable");
1192 Config->Incremental = false;
1193 }
1194
1195 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001196 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001197 "disable");
1198 Config->Incremental = false;
1199 }
1200
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001201 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001202 return;
1203
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001204 std::set<sys::fs::UniqueID> WholeArchives;
Martin Storsjoa47957a2018-09-04 20:56:56 +00001205 AutoExporter Exporter;
1206 for (auto *Arg : Args.filtered(OPT_wholearchive_file)) {
1207 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
Reid Kleckner34085682018-06-14 19:56:03 +00001208 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1209 WholeArchives.insert(*ID);
Martin Storsjoa47957a2018-09-04 20:56:56 +00001210 Exporter.addWholeArchive(*Path);
1211 }
1212 }
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001213
1214 // A predicate returning true if a given path is an argument for
1215 // /wholearchive:, or /wholearchive is enabled globally.
1216 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1217 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1218 auto IsWholeArchive = [&](StringRef Path) -> bool {
1219 if (Args.hasArg(OPT_wholearchive_flag))
1220 return true;
1221 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1222 return WholeArchives.count(*ID);
1223 return false;
1224 };
1225
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001226 // Create a list of input files. Files can be given as arguments
1227 // for /defaultlib option.
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001228 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1229 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Reid Kleckner34085682018-06-14 19:56:03 +00001230 enqueuePath(*Path, IsWholeArchive(*Path));
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001231
David Blaikie6521ed92015-06-22 22:06:52 +00001232 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001233 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001234 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001235
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001236 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001237 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001238 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001239
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001240 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001241 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001242
Nico Weberf1828e32018-09-13 18:13:21 +00001243 if (errorCount())
1244 return;
1245
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001246 // We should have inferred a machine type by now from the input files, but if
1247 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001248 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001249 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001250 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001251 }
1252
Eric Beckmann9e19d792017-06-17 02:26:27 +00001253 // Input files can be Windows resource files (.res files). We use
1254 // WindowsResource to convert resource files to a regular COFF file,
1255 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001256 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001257 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001258
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001259 if (Tar)
1260 Tar->append("response.txt",
1261 createResponseFile(Args, FilePaths,
1262 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001263
Rui Ueyama4d545342015-07-28 03:12:00 +00001264 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001265 Config->LargeAddressAware = Args.hasFlag(
1266 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001267
Rui Ueyamad68e2112015-07-28 03:15:57 +00001268 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001269 Config->HighEntropyVA =
1270 Config->is64() &&
1271 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001272
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001273 if (!Config->DynamicBase &&
1274 (Config->Machine == ARMNT || Config->Machine == ARM64))
1275 error("/dynamicbase:no is not compatible with " +
1276 machineToStr(Config->Machine));
1277
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001278 // Handle /export
1279 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001280 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001281 if (Config->Machine == I386) {
1282 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001283 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001284 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001285 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001286 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001287 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001288 }
1289
1290 // Handle /def
1291 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001292 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001293 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001294 }
1295
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001296 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001297 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001298 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001299 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001300 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001301 }
1302
Nico Weberf4f5b7e2018-08-07 19:10:28 +00001303 // Windows specific -- if no /subsystem is given, we need to infer
1304 // that from entry point name. Must happen before /entry handling,
1305 // and after the early return when just writing an import library.
1306 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1307 Config->Subsystem = inferSubsystem();
1308 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1309 fatal("subsystem must be defined");
1310 }
1311
1312 // Handle /entry and /dll
1313 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1314 Config->Entry = addUndefined(mangle(Arg->getValue()));
1315 } else if (!Config->Entry && !Config->NoEntry) {
1316 if (Args.hasArg(OPT_dll)) {
1317 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1318 : "_DllMainCRTStartup";
1319 Config->Entry = addUndefined(S);
1320 } else {
1321 // Windows specific -- If entry point name is not given, we need to
1322 // infer that from user-defined entry name.
1323 StringRef S = findDefaultEntry();
1324 if (S.empty())
1325 fatal("entry point must be defined");
1326 Config->Entry = addUndefined(S);
1327 log("Entry name inferred: " + S);
1328 }
1329 }
1330
Rui Ueyama6d249082015-07-13 22:31:45 +00001331 // Handle /delayload
1332 for (auto *Arg : Args.filtered(OPT_delayload)) {
1333 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001334 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001335 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001336 } else {
1337 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001338 }
1339 }
1340
Reid Kleckner7668182e2017-03-21 00:12:51 +00001341 // Set default image name if neither /out or /def set it.
1342 if (Config->OutputFile.empty()) {
1343 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001344 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001345 }
1346
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001347 if (ShouldCreatePDB) {
1348 // Put the PDB next to the image if no /pdb flag was passed.
1349 if (Config->PDBPath.empty()) {
1350 Config->PDBPath = Config->OutputFile;
1351 sys::path::replace_extension(Config->PDBPath, ".pdb");
1352 }
1353
1354 // The embedded PDB path should be the absolute path to the PDB if no
1355 // /pdbaltpath flag was passed.
1356 if (Config->PDBAltPath.empty()) {
1357 Config->PDBAltPath = Config->PDBPath;
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001358
1359 // It's important to make the path absolute and remove dots. This path
1360 // will eventually be written into the PE header, and certain Microsoft
1361 // tools won't work correctly if these assumptions are not held.
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001362 sys::fs::make_absolute(Config->PDBAltPath);
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001363 sys::path::remove_dots(Config->PDBAltPath);
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001364 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001365 }
1366
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001367 // Set default image base if /base is not given.
1368 if (Config->ImageBase == uint64_t(-1))
1369 Config->ImageBase = getDefaultImageBase();
1370
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001371 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001372 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001373 Symtab->addAbsolute("___safe_se_handler_table", 0);
1374 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001375 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001376
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001377 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1378 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001379 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001380 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1381 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1382 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1383 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001384 // Needed for MSVC 2017 15.5 CRT.
1385 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001386
Martin Storsjoeac1b052018-08-27 08:43:31 +00001387 if (Config->MinGW) {
1388 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1389 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
Martin Storsjo7a416932018-09-14 22:26:59 +00001390 Symtab->addAbsolute(mangle("__CTOR_LIST__"), 0);
1391 Symtab->addAbsolute(mangle("__DTOR_LIST__"), 0);
Martin Storsjoeac1b052018-08-27 08:43:31 +00001392 }
1393
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001394 // This code may add new undefined symbols to the link, which may enqueue more
1395 // symbol resolution tasks, so we need to continue executing tasks until we
1396 // converge.
1397 do {
1398 // Windows specific -- if entry point is not found,
1399 // search for its mangled names.
1400 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001401 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001402
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001403 // Windows specific -- Make sure we resolve all dllexported symbols.
1404 for (Export &E : Config->Exports) {
1405 if (!E.ForwardTo.empty())
1406 continue;
1407 E.Sym = addUndefined(E.Name);
1408 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001409 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001410 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001411
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001412 // Add weak aliases. Weak aliases is a mechanism to give remaining
1413 // undefined symbols final chance to be resolved successfully.
1414 for (auto Pair : Config->AlternateNames) {
1415 StringRef From = Pair.first;
1416 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001417 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001418 if (!Sym)
1419 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001420 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001421 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001422 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001423 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001424
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001425 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001426 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001427 addUndefined(mangle("_load_config_used"));
1428 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001429
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001430 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001431 return;
1432
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001433 // Do LTO by compiling bitcode input files to a set of native COFF files then
1434 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001435 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001436 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001437
Martin Storsjoeac1b052018-08-27 08:43:31 +00001438 if (Config->MinGW) {
1439 // Load any further object files that might be needed for doing automatic
1440 // imports.
1441 //
1442 // For cases with no automatically imported symbols, this iterates once
1443 // over the symbol table and doesn't do anything.
1444 //
1445 // For the normal case with a few automatically imported symbols, this
1446 // should only need to be run once, since each new object file imported
1447 // is an import library and wouldn't add any new undefined references,
1448 // but there's nothing stopping the __imp_ symbols from coming from a
1449 // normal object file as well (although that won't be used for the
1450 // actual autoimport later on). If this pass adds new undefined references,
1451 // we won't iterate further to resolve them.
1452 Symtab->loadMinGWAutomaticImports();
1453 run();
1454 }
1455
Peter Collingbourne2612a322015-07-04 05:28:41 +00001456 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001457 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001458 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001459 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001460
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001461 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001462 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001463 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001464 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001465 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001466 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001467 return;
1468 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001469
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001470 // In MinGW, all symbols are automatically exported if no symbols
1471 // are chosen to be exported.
1472 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1473 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjoa47957a2018-09-04 20:56:56 +00001474 Exporter.initSymbolExcludes();
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001475
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001476 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001477 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001478 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001479 return;
1480 Export E;
1481 E.Name = Def->getName();
1482 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001483 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001484 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001485 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001486 Config->Exports.push_back(E);
1487 });
1488 }
1489
Rui Ueyama151d8622015-06-17 20:40:43 +00001490 // Windows specific -- when we are creating a .dll file, we also
1491 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001492 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001493 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001494 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001495 assignExportOrdinals();
1496 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001497
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001498 // Handle /output-def (MinGW specific).
1499 if (auto *Arg = Args.getLastArg(OPT_output_def))
1500 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001501
Martin Storsjod2752aa2017-08-14 19:07:27 +00001502 // Set extra alignment for .comm symbols
1503 for (auto Pair : Config->AlignComm) {
1504 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001505 uint32_t Alignment = Pair.second;
1506
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001507 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001508 if (!Sym) {
1509 warn("/aligncomm symbol " + Name + " not found");
1510 continue;
1511 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001512
Martin Storsjo214d6992018-08-06 19:49:18 +00001513 // If the symbol isn't common, it must have been replaced with a regular
1514 // symbol, which will carry its own alignment.
Rui Ueyama616cd992017-10-31 16:10:24 +00001515 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjo214d6992018-08-06 19:49:18 +00001516 if (!DC)
Martin Storsjod2752aa2017-08-14 19:07:27 +00001517 continue;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001518
1519 CommonChunk *C = DC->getChunk();
1520 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001521 }
1522
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001523 // Windows specific -- Create a side-by-side manifest file.
1524 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001525 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001526
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001527 // Handle /order. We want to do this at this moment because we
1528 // need a complete list of comdat sections to warn on nonexistent
1529 // functions.
1530 if (auto *Arg = Args.getLastArg(OPT_order))
1531 parseOrderFile(Arg->getValue());
1532
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001533 // Identify unreferenced COMDAT sections.
1534 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001535 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001536
1537 // Identify identical COMDAT sections to merge them.
Peter Collingbourneab038022018-08-23 17:44:42 +00001538 if (Config->DoICF) {
1539 findKeepUniqueSections();
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001540 doICF(Symtab->getChunks());
Peter Collingbourneab038022018-08-23 17:44:42 +00001541 }
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001542
Rui Ueyama411c63602015-05-28 19:09:30 +00001543 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001544 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001545
1546 // Stop early so we can print the results.
1547 Timer::root().stop();
1548 if (Config->ShowTiming)
1549 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001550}
1551
Rui Ueyama411c63602015-05-28 19:09:30 +00001552} // namespace coff
1553} // namespace lld