blob: 000ef59f7faa38c024a5a1c12653660557f7dc13 [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 Ueyama95925fd2015-06-28 19:35:15 +0000891 Config->Force = true;
892
Rui Ueyama6600eb12015-07-04 23:37:32 +0000893 // Handle /debug
Shoaib Meenai111db792017-12-15 23:51:14 +0000894 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
Rui Ueyama6600eb12015-07-04 23:37:32 +0000895 Config->Debug = true;
Bob Haarman5ec44852018-01-31 23:44:00 +0000896 Config->Incremental = true;
Rui Ueyama9f7032a2017-08-24 20:26:54 +0000897 if (auto *Arg = Args.getLastArg(OPT_debugtype))
898 Config->DebugTypes = parseDebugType(Arg->getValue());
899 else
900 Config->DebugTypes = getDefaultDebugType(Args);
Saleem Abdulrasoola2cca7e2016-08-08 22:02:44 +0000901 }
Rui Ueyama6600eb12015-07-04 23:37:32 +0000902
Shoaib Meenaic4fdbca2017-12-15 23:52:46 +0000903 // Handle /pdb
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000904 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
Zachary Turnerf2282762018-03-23 19:57:25 +0000905 if (ShouldCreatePDB) {
Shoaib Meenaia1f6fba2017-12-16 00:23:24 +0000906 if (auto *Arg = Args.getLastArg(OPT_pdb))
907 Config->PDBPath = Arg->getValue();
Peter Collingbourne94aa62e2018-04-17 23:28:38 +0000908 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
909 Config->PDBAltPath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000910 if (Args.hasArg(OPT_natvis))
911 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
Takuto Ikutad8559282018-07-19 04:56:22 +0000912
913 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
914 Config->PDBSourcePath = Arg->getValue();
Zachary Turnerf2282762018-03-23 19:57:25 +0000915 }
Saleem Abdulrasool8fcff932016-08-29 21:20:46 +0000916
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000917 // Handle /noentry
918 if (Args.hasArg(OPT_noentry)) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000919 if (Args.hasArg(OPT_dll))
920 Config->NoEntry = true;
921 else
922 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000923 }
924
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000925 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000926 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000927 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000928 Config->ManifestID = 2;
929 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000930
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000931 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
932 // because we need to explicitly check whether that option or its inverse was
933 // present in the argument list in order to handle /fixed.
934 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
935 if (DynamicBaseArg &&
936 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
937 Config->DynamicBase = false;
938
Nico Webera7643792018-03-30 17:17:04 +0000939 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
940 // default setting for any other project type.", but link.exe defaults to
941 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000942 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
943 if (Fixed) {
944 if (DynamicBaseArg &&
945 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
Bob Haarmanac8f7fc2017-04-05 00:43:54 +0000946 error("/fixed must not be specified with /dynamicbase");
947 } else {
948 Config->Relocatable = false;
949 Config->DynamicBase = false;
950 }
Rui Ueyama6592ff82015-06-16 23:13:00 +0000951 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000952
Shoaib Meenai59bf3622017-10-24 21:17:16 +0000953 // Handle /appcontainer
954 Config->AppContainer =
955 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
Saleem Abdulrasool671029d2017-04-06 23:07:53 +0000956
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000957 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000958 if (auto *Arg = Args.getLastArg(OPT_machine))
959 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000960
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000961 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000962 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000963 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
964
965 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000966 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000967 Config->NoDefaultLibAll = true;
968
Rui Ueyama804a8b62015-05-29 16:18:15 +0000969 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000970 if (auto *Arg = Args.getLastArg(OPT_base))
971 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000972
973 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000974 if (auto *Arg = Args.getLastArg(OPT_stack))
975 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000976
Reid Kleckneraf2f7da2018-02-06 01:58:26 +0000977 // Handle /guard:cf
978 if (auto *Arg = Args.getLastArg(OPT_guard))
979 parseGuard(Arg->getValue());
980
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000981 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000982 if (auto *Arg = Args.getLastArg(OPT_heap))
983 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000984
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000985 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000986 if (auto *Arg = Args.getLastArg(OPT_version))
987 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
988 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000989
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000990 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000991 if (auto *Arg = Args.getLastArg(OPT_subsystem))
992 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
993 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000994
Zachary Turnerc8dd6cc2018-05-17 15:11:01 +0000995 // Handle /timestamp
996 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
997 if (Arg->getOption().getID() == OPT_repro) {
998 Config->Timestamp = 0;
999 Config->Repro = true;
1000 } else {
1001 Config->Repro = false;
1002 StringRef Value(Arg->getValue());
1003 if (Value.getAsInteger(0, Config->Timestamp))
1004 fatal(Twine("invalid timestamp: ") + Value +
1005 ". Expected 32-bit integer");
1006 }
1007 } else {
1008 Config->Repro = false;
1009 Config->Timestamp = time(nullptr);
1010 }
1011
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001012 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +00001013 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001014 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001015
Rui Ueyama08d5e182015-06-18 23:20:11 +00001016 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +00001017 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +00001018 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +00001019
Rui Ueyamab95188c2015-06-18 20:27:09 +00001020 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +00001021 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +00001022 Config->Implib = Arg->getValue();
1023
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001024 // Handle /opt.
Nico Weber0945ad62018-03-30 17:14:50 +00001025 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1026 unsigned ICFLevel =
1027 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001028 unsigned TailMerge = 1;
David Blaikie6521ed92015-06-22 22:06:52 +00001029 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyama75656ee2015-10-19 19:40:43 +00001030 std::string Str = StringRef(Arg->getValue()).lower();
1031 SmallVector<StringRef, 1> Vec;
1032 StringRef(Str).split(Vec, ',');
1033 for (StringRef S : Vec) {
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001034 if (S == "ref") {
1035 DoGC = true;
1036 } else if (S == "noref") {
1037 DoGC = false;
1038 } else if (S == "icf" || S.startswith("icf=")) {
1039 ICFLevel = 2;
1040 } else if (S == "noicf") {
1041 ICFLevel = 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001042 } else if (S == "lldtailmerge") {
1043 TailMerge = 2;
1044 } else if (S == "nolldtailmerge") {
1045 TailMerge = 0;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001046 } else if (S.startswith("lldlto=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001047 StringRef OptLevel = S.substr(7);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001048 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001049 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001050 } else if (S.startswith("lldltojobs=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001051 StringRef Jobs = S.substr(11);
Sam Clegg3ad27e92018-05-22 20:20:25 +00001052 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1053 Config->ThinLTOJobs == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001054 error("/opt:lldltojobs: invalid job count: " + Jobs);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001055 } else if (S.startswith("lldltopartitions=")) {
Peter Collingbournecef80992017-09-07 23:49:09 +00001056 StringRef N = S.substr(17);
Bob Haarmancde5e5b2017-02-02 23:58:14 +00001057 if (N.getAsInteger(10, Config->LTOPartitions) ||
1058 Config->LTOPartitions == 0)
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001059 error("/opt:lldltopartitions: invalid partition count: " + N);
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001060 } else if (S != "lbr" && S != "nolbr")
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001061 error("/opt: unknown option: " + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001062 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +00001063 }
1064
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001065 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1066 // explicitly.
1067 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1068 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1069 // comdat readonly data.
1070 if (ICFLevel == 1 && !DoGC)
1071 ICFLevel = 0;
1072 Config->DoGC = DoGC;
1073 Config->DoICF = ICFLevel > 0;
Peter Collingbourned25dfe92018-05-11 22:21:36 +00001074 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
Reid Klecknerc2dcdd82017-11-13 18:38:25 +00001075
Bob Haarman69b196d2017-02-08 18:36:41 +00001076 // Handle /lldsavetemps
1077 if (Args.hasArg(OPT_lldsavetemps))
1078 Config->SaveTemps = true;
1079
Martin Storsjo53518912018-03-14 20:17:16 +00001080 // Handle /kill-at
1081 if (Args.hasArg(OPT_kill_at))
1082 Config->KillAt = true;
1083
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001084 // Handle /lldltocache
1085 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1086 Config->LTOCache = Arg->getValue();
1087
1088 // Handle /lldsavecachepolicy
1089 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
Rui Ueyamabdc51502017-12-06 22:08:17 +00001090 Config->LTOCachePolicy = CHECK(
Peter Collingbourne052e855e2017-09-08 00:50:50 +00001091 parseCachePruningPolicy(Arg->getValue()),
1092 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1093
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001094 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +00001095 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001096 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +00001097
Rui Ueyama6600eb12015-07-04 23:37:32 +00001098 // Handle /merge
1099 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +00001100 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +00001101
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001102 // Add default section merging rules after user rules. User rules take
1103 // precedence, but we will emit a warning if there is a conflict.
1104 parseMerge(".idata=.rdata");
1105 parseMerge(".didat=.rdata");
1106 parseMerge(".edata=.rdata");
Peter Collingbourne3d636ed2018-04-20 21:32:37 +00001107 parseMerge(".xdata=.rdata");
Peter Collingbourne326f4192018-04-20 21:30:36 +00001108 parseMerge(".bss=.data");
Peter Collingbourne66f1c9a2018-04-17 23:28:52 +00001109
Rui Ueyama440138c2016-06-20 03:39:39 +00001110 // Handle /section
1111 for (auto *Arg : Args.filtered(OPT_section))
1112 parseSection(Arg->getValue());
1113
Martin Storsjod2752aa2017-08-14 19:07:27 +00001114 // Handle /aligncomm
1115 for (auto *Arg : Args.filtered(OPT_aligncomm))
1116 parseAligncomm(Arg->getValue());
1117
Nico Webera7a2c442017-07-25 18:08:03 +00001118 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1119 // also passed.
1120 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1121 Config->ManifestDependency = Arg->getValue();
1122 Config->Manifest = Configuration::SideBySide;
1123 }
1124
1125 // Handle /manifest and /manifest:
1126 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1127 if (Arg->getOption().getID() == OPT_manifest)
1128 Config->Manifest = Configuration::SideBySide;
1129 else
1130 parseManifest(Arg->getValue());
1131 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001132
1133 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +00001134 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1135 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001136
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001137 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +00001138 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001139 Config->ManifestFile = Arg->getValue();
1140
Rui Ueyamaafb19012016-04-19 01:21:58 +00001141 // Handle /manifestinput
1142 for (auto *Arg : Args.filtered(OPT_manifestinput))
1143 Config->ManifestInput.push_back(Arg->getValue());
1144
Nico Webera7a2c442017-07-25 18:08:03 +00001145 if (!Config->ManifestInput.empty() &&
1146 Config->Manifest != Configuration::Embed) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001147 fatal("/manifestinput: requires /manifest:embed");
Nico Webera7a2c442017-07-25 18:08:03 +00001148 }
1149
Rui Ueyama6592ff82015-06-16 23:13:00 +00001150 // Handle miscellaneous boolean flags.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001151 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1152 Config->AllowIsolation =
1153 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
Bob Haarman5ec44852018-01-31 23:44:00 +00001154 Config->Incremental =
1155 Args.hasFlag(OPT_incremental, OPT_incremental_no,
Nico Weber0945ad62018-03-30 17:14:50 +00001156 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1157 !Args.hasArg(OPT_profile));
Nico Weberd657c252018-05-31 13:43:02 +00001158 Config->IntegrityCheck =
1159 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001160 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
Hans Wennborg03ca8f42018-04-25 20:32:00 +00001161 Config->TerminalServerAware =
1162 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
Peter Collingbournef874bd62017-11-21 01:14:14 +00001163 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
Zachary Turner0d07a8e2017-12-14 18:07:04 +00001164 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
Martin Storsjo3a7905b2018-06-29 06:08:25 +00001165 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
Rui Ueyama6592ff82015-06-16 23:13:00 +00001166
Peter Collingbourne6f24fdb2017-01-14 03:14:46 +00001167 Config->MapFile = getMapFile(Args);
1168
Nico Weber0945ad62018-03-30 17:14:50 +00001169 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1170 warn("ignoring '/incremental' due to '/profile' specification");
1171 Config->Incremental = false;
1172 }
1173
1174 if (Config->Incremental && Args.hasArg(OPT_order)) {
1175 warn("ignoring '/incremental' due to '/order' specification");
1176 Config->Incremental = false;
1177 }
1178
Bob Haarman5ec44852018-01-31 23:44:00 +00001179 if (Config->Incremental && Config->DoGC) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001180 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001181 "disable");
1182 Config->Incremental = false;
1183 }
1184
1185 if (Config->Incremental && Config->DoICF) {
Nico Weberf06ae4f2018-03-12 12:45:40 +00001186 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
Bob Haarman5ec44852018-01-31 23:44:00 +00001187 "disable");
1188 Config->Incremental = false;
1189 }
1190
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001191 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001192 return;
1193
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001194 std::set<sys::fs::UniqueID> WholeArchives;
1195 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
Reid Kleckner34085682018-06-14 19:56:03 +00001196 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1197 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1198 WholeArchives.insert(*ID);
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001199
1200 // A predicate returning true if a given path is an argument for
1201 // /wholearchive:, or /wholearchive is enabled globally.
1202 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1203 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1204 auto IsWholeArchive = [&](StringRef Path) -> bool {
1205 if (Args.hasArg(OPT_wholearchive_flag))
1206 return true;
1207 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1208 return WholeArchives.count(*ID);
1209 return false;
1210 };
1211
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001212 // Create a list of input files. Files can be given as arguments
1213 // for /defaultlib option.
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001214 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1215 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Reid Kleckner34085682018-06-14 19:56:03 +00001216 enqueuePath(*Path, IsWholeArchive(*Path));
Rui Ueyama4eed6cc2018-06-12 21:47:31 +00001217
David Blaikie6521ed92015-06-22 22:06:52 +00001218 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001219 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Martin Storsjo8278ba52017-09-13 07:28:03 +00001220 enqueuePath(*Path, false);
Rui Ueyamad21b00b2015-05-31 19:17:14 +00001221
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001222 // Windows specific -- Create a resource file containing a manifest file.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001223 if (Config->Manifest == Configuration::Embed)
Martin Storsjo8278ba52017-09-13 07:28:03 +00001224 addBuffer(createManifestRes(), false);
Rui Ueyama2bf6a122015-06-14 21:50:50 +00001225
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001226 // Read all input files given via the command line.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001227 run();
Rui Ueyama5cff6852015-05-31 03:34:08 +00001228
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001229 // We should have inferred a machine type by now from the input files, but if
1230 // not we assume x64.
Rui Ueyama5e706b32015-07-25 21:54:50 +00001231 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamae6e206d2017-02-21 23:22:56 +00001232 warn("/machine is not specified. x64 is assumed");
Rui Ueyama5e706b32015-07-25 21:54:50 +00001233 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001234 }
1235
Eric Beckmann9e19d792017-06-17 02:26:27 +00001236 // Input files can be Windows resource files (.res files). We use
1237 // WindowsResource to convert resource files to a regular COFF file,
1238 // then link the resulting file normally.
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001239 if (!Resources.empty())
Peter Collingbourne9362ac62017-10-16 23:15:04 +00001240 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
Rui Ueyamaea533cd2015-07-09 19:54:13 +00001241
Rui Ueyama7f1f9122017-01-06 02:33:53 +00001242 if (Tar)
1243 Tar->append("response.txt",
1244 createResponseFile(Args, FilePaths,
1245 ArrayRef<StringRef>(SearchPaths).slice(1)));
Peter Collingbournefeee2102016-07-26 02:00:42 +00001246
Rui Ueyama4d545342015-07-28 03:12:00 +00001247 // Handle /largeaddressaware
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001248 Config->LargeAddressAware = Args.hasFlag(
1249 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
Rui Ueyama4d545342015-07-28 03:12:00 +00001250
Rui Ueyamad68e2112015-07-28 03:15:57 +00001251 // Handle /highentropyva
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001252 Config->HighEntropyVA =
1253 Config->is64() &&
1254 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
Rui Ueyamad68e2112015-07-28 03:15:57 +00001255
Martin Storsjo6ea167c2017-12-12 19:39:13 +00001256 if (!Config->DynamicBase &&
1257 (Config->Machine == ARMNT || Config->Machine == ARM64))
1258 error("/dynamicbase:no is not compatible with " +
1259 machineToStr(Config->Machine));
1260
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001261 // Handle /export
1262 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001263 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001264 if (Config->Machine == I386) {
1265 if (!isDecorated(E.Name))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001266 E.Name = Saver.save("_" + E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001267 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
Rui Ueyama8d433d72016-12-08 21:27:09 +00001268 E.ExtName = Saver.save("_" + E.ExtName);
Rui Ueyamaf10a3202015-08-31 08:43:21 +00001269 }
Rafael Espindolab835ae82015-08-06 14:58:50 +00001270 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001271 }
1272
1273 // Handle /def
1274 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001275 // parseModuleDefs mutates Config object.
Reid Kleckner146eb7a2017-06-02 17:53:06 +00001276 parseModuleDefs(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001277 }
1278
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001279 // Handle generation of import library from a def file.
Rui Ueyamaa835bab2017-09-13 20:30:59 +00001280 if (!Args.hasArg(OPT_INPUT)) {
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001281 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001282 createImportLibrary(/*AsLib=*/true);
Rui Ueyama6f4e2552017-10-23 20:03:32 +00001283 return;
Saleem Abdulrasoolbc7ff702017-06-15 20:39:58 +00001284 }
1285
Nico Weberf4f5b7e2018-08-07 19:10:28 +00001286 // Windows specific -- if no /subsystem is given, we need to infer
1287 // that from entry point name. Must happen before /entry handling,
1288 // and after the early return when just writing an import library.
1289 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1290 Config->Subsystem = inferSubsystem();
1291 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1292 fatal("subsystem must be defined");
1293 }
1294
1295 // Handle /entry and /dll
1296 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1297 Config->Entry = addUndefined(mangle(Arg->getValue()));
1298 } else if (!Config->Entry && !Config->NoEntry) {
1299 if (Args.hasArg(OPT_dll)) {
1300 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1301 : "_DllMainCRTStartup";
1302 Config->Entry = addUndefined(S);
1303 } else {
1304 // Windows specific -- If entry point name is not given, we need to
1305 // infer that from user-defined entry name.
1306 StringRef S = findDefaultEntry();
1307 if (S.empty())
1308 fatal("entry point must be defined");
1309 Config->Entry = addUndefined(S);
1310 log("Entry name inferred: " + S);
1311 }
1312 }
1313
Rui Ueyama6d249082015-07-13 22:31:45 +00001314 // Handle /delayload
1315 for (auto *Arg : Args.filtered(OPT_delayload)) {
1316 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +00001317 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +00001318 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +00001319 } else {
1320 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +00001321 }
1322 }
1323
Reid Kleckner7668182e2017-03-21 00:12:51 +00001324 // Set default image name if neither /out or /def set it.
1325 if (Config->OutputFile.empty()) {
1326 Config->OutputFile =
Richard Smitha13714e2017-04-12 23:51:20 +00001327 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
Reid Kleckner7668182e2017-03-21 00:12:51 +00001328 }
1329
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001330 if (ShouldCreatePDB) {
1331 // Put the PDB next to the image if no /pdb flag was passed.
1332 if (Config->PDBPath.empty()) {
1333 Config->PDBPath = Config->OutputFile;
1334 sys::path::replace_extension(Config->PDBPath, ".pdb");
1335 }
1336
1337 // The embedded PDB path should be the absolute path to the PDB if no
1338 // /pdbaltpath flag was passed.
1339 if (Config->PDBAltPath.empty()) {
1340 Config->PDBAltPath = Config->PDBPath;
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001341
1342 // It's important to make the path absolute and remove dots. This path
1343 // will eventually be written into the PE header, and certain Microsoft
1344 // tools won't work correctly if these assumptions are not held.
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001345 sys::fs::make_absolute(Config->PDBAltPath);
Zachary Turnere2ce2a52018-07-12 03:22:39 +00001346 sys::path::remove_dots(Config->PDBAltPath);
Peter Collingbourne94aa62e2018-04-17 23:28:38 +00001347 }
Reid Kleckner13bdbfb2017-03-22 00:57:14 +00001348 }
1349
Rui Ueyama5c437cd2015-07-25 21:42:33 +00001350 // Set default image base if /base is not given.
1351 if (Config->ImageBase == uint64_t(-1))
1352 Config->ImageBase = getDefaultImageBase();
1353
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001354 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
Rui Ueyama5e706b32015-07-25 21:54:50 +00001355 if (Config->Machine == I386) {
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001356 Symtab->addAbsolute("___safe_se_handler_table", 0);
1357 Symtab->addAbsolute("___safe_se_handler_count", 0);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +00001358 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +00001359
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001360 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1361 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001362 Symtab->addAbsolute(mangle("__guard_flags"), 0);
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001363 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1364 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1365 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1366 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
Martin Storsjo2b964102017-12-12 08:22:29 +00001367 // Needed for MSVC 2017 15.5 CRT.
1368 Symtab->addAbsolute(mangle("__enclave_config"), 0);
Rui Ueyama107db552015-08-09 21:01:06 +00001369
Martin Storsjoeac1b052018-08-27 08:43:31 +00001370 if (Config->MinGW) {
1371 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0);
1372 Symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0);
1373 }
1374
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001375 // This code may add new undefined symbols to the link, which may enqueue more
1376 // symbol resolution tasks, so we need to continue executing tasks until we
1377 // converge.
1378 do {
1379 // Windows specific -- if entry point is not found,
1380 // search for its mangled names.
1381 if (Config->Entry)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001382 Symtab->mangleMaybe(Config->Entry);
Rui Ueyama85225b02015-07-02 03:15:15 +00001383
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001384 // Windows specific -- Make sure we resolve all dllexported symbols.
1385 for (Export &E : Config->Exports) {
1386 if (!E.ForwardTo.empty())
1387 continue;
1388 E.Sym = addUndefined(E.Name);
1389 if (!E.Directives)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001390 Symtab->mangleMaybe(E.Sym);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001391 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +00001392
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001393 // Add weak aliases. Weak aliases is a mechanism to give remaining
1394 // undefined symbols final chance to be resolved successfully.
1395 for (auto Pair : Config->AlternateNames) {
1396 StringRef From = Pair.first;
1397 StringRef To = Pair.second;
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001398 Symbol *Sym = Symtab->find(From);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001399 if (!Sym)
1400 continue;
Rui Ueyama616cd992017-10-31 16:10:24 +00001401 if (auto *U = dyn_cast<Undefined>(Sym))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001402 if (!U->WeakAlias)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001403 U->WeakAlias = Symtab->addUndefined(To);
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001404 }
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001405
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001406 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001407 if (Symtab->findUnderscore("_load_config_used"))
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001408 addUndefined(mangle("_load_config_used"));
1409 } while (run());
Peter Collingbourne8b65e512016-12-11 22:15:25 +00001410
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001411 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001412 return;
1413
Peter Collingbournedf5783b2015-08-28 22:16:09 +00001414 // Do LTO by compiling bitcode input files to a set of native COFF files then
1415 // link those files.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001416 Symtab->addCombinedLTOObjects();
Peter Collingbourne6ee0b4e2016-12-15 04:02:23 +00001417 run();
Peter Collingbourne60c16162015-06-01 20:10:10 +00001418
Martin Storsjoeac1b052018-08-27 08:43:31 +00001419 if (Config->MinGW) {
1420 // Load any further object files that might be needed for doing automatic
1421 // imports.
1422 //
1423 // For cases with no automatically imported symbols, this iterates once
1424 // over the symbol table and doesn't do anything.
1425 //
1426 // For the normal case with a few automatically imported symbols, this
1427 // should only need to be run once, since each new object file imported
1428 // is an import library and wouldn't add any new undefined references,
1429 // but there's nothing stopping the __imp_ symbols from coming from a
1430 // normal object file as well (although that won't be used for the
1431 // actual autoimport later on). If this pass adds new undefined references,
1432 // we won't iterate further to resolve them.
1433 Symtab->loadMinGWAutomaticImports();
1434 run();
1435 }
1436
Peter Collingbourne2612a322015-07-04 05:28:41 +00001437 // Make sure we have resolved all symbols.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001438 Symtab->reportRemainingUndefines();
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001439 if (errorCount())
Rui Ueyamacc6738a2017-10-06 23:43:54 +00001440 return;
Peter Collingbourne2612a322015-07-04 05:28:41 +00001441
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001442 // Handle /safeseh.
Shoaib Meenai59bf3622017-10-24 21:17:16 +00001443 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
Rui Ueyamaacd632d2017-07-27 00:45:26 +00001444 for (ObjFile *File : ObjFile::Instances)
Reid Kleckneraf2f7da2018-02-06 01:58:26 +00001445 if (!File->hasSafeSEH())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001446 error("/safeseh: " + File->getName() + " is not compatible with SEH");
Bob Haarmanb8a59c82017-10-25 22:28:38 +00001447 if (errorCount())
Bob Haarmanac8f7fc2017-04-05 00:43:54 +00001448 return;
1449 }
Rui Ueyamaff88d5a2015-07-29 20:25:40 +00001450
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001451 // In MinGW, all symbols are automatically exported if no symbols
1452 // are chosen to be exported.
1453 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1454 Args.hasArg(OPT_export_all_symbols))) {
Martin Storsjob40ccc12017-10-19 06:56:04 +00001455 AutoExporter Exporter;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001456
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001457 Symtab->forEachSymbol([=](Symbol *S) {
Rui Ueyama616cd992017-10-31 16:10:24 +00001458 auto *Def = dyn_cast<Defined>(S);
Martin Storsjob40ccc12017-10-19 06:56:04 +00001459 if (!Exporter.shouldExport(Def))
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001460 return;
1461 Export E;
1462 E.Name = Def->getName();
1463 E.Sym = Def;
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001464 if (Def->getChunk() &&
Peter Collingbournefa322ab2018-04-19 20:03:24 +00001465 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
Martin Storsjodc95dbf2017-11-03 20:58:20 +00001466 E.Data = true;
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001467 Config->Exports.push_back(E);
1468 });
1469 }
1470
Rui Ueyama151d8622015-06-17 20:40:43 +00001471 // Windows specific -- when we are creating a .dll file, we also
1472 // need to create a .lib file.
Rui Ueyama100ffac2015-09-01 09:15:58 +00001473 if (!Config->Exports.empty() || Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +00001474 fixupExports();
Saleem Abdulrasoolace2fa72017-07-19 02:01:27 +00001475 createImportLibrary(/*AsLib=*/false);
Rui Ueyama8765fba2015-07-15 22:21:08 +00001476 assignExportOrdinals();
1477 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +00001478
Martin Storsjo7f71acd2017-10-12 05:37:13 +00001479 // Handle /output-def (MinGW specific).
1480 if (auto *Arg = Args.getLastArg(OPT_output_def))
1481 writeDefFile(Arg->getValue());
Rui Ueyamad73479b2018-01-29 19:55:55 +00001482
Martin Storsjod2752aa2017-08-14 19:07:27 +00001483 // Set extra alignment for .comm symbols
1484 for (auto Pair : Config->AlignComm) {
1485 StringRef Name = Pair.first;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001486 uint32_t Alignment = Pair.second;
1487
Rui Ueyamaf52496e2017-11-03 21:21:47 +00001488 Symbol *Sym = Symtab->find(Name);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001489 if (!Sym) {
1490 warn("/aligncomm symbol " + Name + " not found");
1491 continue;
1492 }
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001493
Martin Storsjo214d6992018-08-06 19:49:18 +00001494 // If the symbol isn't common, it must have been replaced with a regular
1495 // symbol, which will carry its own alignment.
Rui Ueyama616cd992017-10-31 16:10:24 +00001496 auto *DC = dyn_cast<DefinedCommon>(Sym);
Martin Storsjo214d6992018-08-06 19:49:18 +00001497 if (!DC)
Martin Storsjod2752aa2017-08-14 19:07:27 +00001498 continue;
Rui Ueyamacfc2f802017-09-13 21:54:55 +00001499
1500 CommonChunk *C = DC->getChunk();
1501 C->Alignment = std::max(C->Alignment, Alignment);
Martin Storsjod2752aa2017-08-14 19:07:27 +00001502 }
1503
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001504 // Windows specific -- Create a side-by-side manifest file.
1505 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +00001506 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +00001507
Rui Ueyamab6d3a932018-01-29 21:50:53 +00001508 // Handle /order. We want to do this at this moment because we
1509 // need a complete list of comdat sections to warn on nonexistent
1510 // functions.
1511 if (auto *Arg = Args.getLastArg(OPT_order))
1512 parseOrderFile(Arg->getValue());
1513
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001514 // Identify unreferenced COMDAT sections.
1515 if (Config->DoGC)
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001516 markLive(Symtab->getChunks());
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001517
1518 // Identify identical COMDAT sections to merge them.
Peter Collingbourneab038022018-08-23 17:44:42 +00001519 if (Config->DoICF) {
1520 findKeepUniqueSections();
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001521 doICF(Symtab->getChunks());
Peter Collingbourneab038022018-08-23 17:44:42 +00001522 }
Rui Ueyamaa5f0f752015-09-19 21:36:28 +00001523
Rui Ueyama411c63602015-05-28 19:09:30 +00001524 // Write the result.
Rui Ueyamacbf969e2017-08-28 21:51:07 +00001525 writeResult();
Zachary Turner727f1532018-01-17 19:16:26 +00001526
1527 // Stop early so we can print the results.
1528 Timer::root().stop();
1529 if (Config->ShowTiming)
1530 Timer::root().print();
Rui Ueyama411c63602015-05-28 19:09:30 +00001531}
1532
Rui Ueyama411c63602015-05-28 19:09:30 +00001533} // namespace coff
1534} // namespace lld