blob: ba2c13d9adb84035c4b8bf51cfd137c72863f878 [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
10#include "Config.h"
11#include "Driver.h"
Rui Ueyama562daa82015-06-18 21:50:38 +000012#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "SymbolTable.h"
15#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000018#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000019#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Option/Option.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000026#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000027#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000028#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000029#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include <memory>
31
32using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000033using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
34using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
35using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000036using llvm::sys::Process;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000037using llvm::sys::fs::file_magic;
38using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000039
Rui Ueyama3500f662015-05-28 20:30:06 +000040namespace lld {
41namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000042
Rui Ueyama3500f662015-05-28 20:30:06 +000043Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000044LinkerDriver *Driver;
45
David Blaikie00818192015-06-22 22:06:48 +000046bool link(llvm::ArrayRef<const char *> Args) {
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000047 auto C = make_unique<Configuration>();
48 Config = C.get();
49 auto D = make_unique<LinkerDriver>();
50 Driver = D.get();
David Blaikieb2b1c7c2015-06-21 06:32:10 +000051 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000052}
Rui Ueyama411c63602015-05-28 19:09:30 +000053
Rui Ueyamaad660982015-06-07 00:20:32 +000054// Drop directory components and replace extension with ".exe".
55static std::string getOutputPath(StringRef Path) {
56 auto P = Path.find_last_of("\\/");
57 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
58 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000059}
60
Rui Ueyamad7c2f582015-05-31 21:04:56 +000061// Opens a file. Path has to be resolved already.
62// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000063ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000064 auto MBOrErr = MemoryBuffer::getFile(Path);
65 if (auto EC = MBOrErr.getError())
66 return EC;
67 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
68 MemoryBufferRef MBRef = MB->getMemBufferRef();
69 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000070 return MBRef;
71}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000072
Rui Ueyama2bf6a122015-06-14 21:50:50 +000073static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000074 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000075 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000076 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000077 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000078 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000079 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000080 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000081 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
82 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000083}
84
Rui Ueyama411c63602015-05-28 19:09:30 +000085// Parses .drectve section contents and returns a list of files
86// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000087std::error_code
Rui Ueyama0d2e9992015-06-23 23:56:39 +000088LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000089 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000090 if (auto EC = ArgsOrErr.getError())
91 return EC;
David Blaikie6521ed92015-06-22 22:06:52 +000092 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +000093
David Blaikie6521ed92015-06-22 22:06:52 +000094 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +000095 switch (Arg->getOption().getID()) {
96 case OPT_alternatename:
97 if (auto EC = parseAlternateName(Arg->getValue()))
Rui Ueyamad7c2f582015-05-31 21:04:56 +000098 return EC;
Rui Ueyama562daa82015-06-18 21:50:38 +000099 break;
100 case OPT_defaultlib:
101 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
102 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
103 if (auto EC = MBOrErr.getError())
104 return EC;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000105 Symtab.addFile(createFile(MBOrErr.get()));
Rui Ueyama562daa82015-06-18 21:50:38 +0000106 }
107 break;
108 case OPT_export: {
109 ErrorOr<Export> E = parseExport(Arg->getValue());
110 if (auto EC = E.getError())
111 return EC;
112 Config->Exports.push_back(E.get());
113 break;
114 }
115 case OPT_failifmismatch:
116 if (auto EC = checkFailIfMismatch(Arg->getValue()))
117 return EC;
118 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000119 case OPT_incl:
120 Config->Includes.insert(Arg->getValue());
121 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000122 case OPT_merge:
123 // Ignore /merge for now.
124 break;
125 case OPT_nodefaultlib:
126 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
127 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000128 default:
129 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
130 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000131 }
132 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000133 return std::error_code();
134}
135
Rui Ueyama54b71da2015-05-31 19:17:12 +0000136// Find file from search paths. You can omit ".obj", this function takes
137// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000138StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000139 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
140 if (hasPathSep)
141 return Filename;
142 bool hasExt = (Filename.find('.') != StringRef::npos);
143 for (StringRef Dir : SearchPaths) {
144 SmallString<128> Path = Dir;
145 llvm::sys::path::append(Path, Filename);
146 if (llvm::sys::fs::exists(Path.str()))
147 return Alloc.save(Path.str());
148 if (!hasExt) {
149 Path.append(".obj");
150 if (llvm::sys::fs::exists(Path.str()))
151 return Alloc.save(Path.str());
152 }
153 }
154 return Filename;
155}
156
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000157// Resolves a file path. This never returns the same path
158// (in that case, it returns None).
159Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
160 StringRef Path = doFindFile(Filename);
161 bool Seen = !VisitedFiles.insert(Path.lower()).second;
162 if (Seen)
163 return None;
164 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000165}
166
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000167// Find library file from search path.
168StringRef LinkerDriver::doFindLib(StringRef Filename) {
169 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000170 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000171 if (!hasExt)
172 Filename = Alloc.save(Filename + ".lib");
173 return doFindFile(Filename);
174}
175
176// Resolves a library path. /nodefaultlib options are taken into
177// consideration. This never returns the same path (in that case,
178// it returns None).
179Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
180 if (Config->NoDefaultLibAll)
181 return None;
182 StringRef Path = doFindLib(Filename);
183 if (Config->NoDefaultLibs.count(Path))
184 return None;
185 bool Seen = !VisitedFiles.insert(Path.lower()).second;
186 if (Seen)
187 return None;
188 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000189}
190
191// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000192void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000193 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
194 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000195 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000196 StringRef Env = Alloc.save(*EnvOpt);
197 while (!Env.empty()) {
198 StringRef Path;
199 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000200 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000201 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000202}
203
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000204static WindowsSubsystem inferSubsystem() {
205 if (Config->DLL)
206 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
207 return StringSwitch<WindowsSubsystem>(Config->EntryName)
208 .Case("mainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
209 .Case("wmainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_CUI)
210 .Case("WinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
211 .Case("wWinMainCRTStartup", IMAGE_SUBSYSTEM_WINDOWS_GUI)
212 .Default(IMAGE_SUBSYSTEM_UNKNOWN);
213}
214
David Blaikie00818192015-06-22 22:06:48 +0000215bool LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000216 // Needed for LTO.
217 llvm::InitializeAllTargetInfos();
218 llvm::InitializeAllTargets();
219 llvm::InitializeAllTargetMCs();
220 llvm::InitializeAllAsmParsers();
221 llvm::InitializeAllAsmPrinters();
222 llvm::InitializeAllDisassemblers();
223
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000224 // If the first command line argument is "/lib", link.exe acts like lib.exe.
225 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000226 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
227 return llvm::libDriverMain(ArgsArr.slice(1)) == 0;
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000228
Rui Ueyama411c63602015-05-28 19:09:30 +0000229 // Parse command line options.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000230 auto ArgsOrErr = Parser.parse(ArgsArr);
Rui Ueyama411c63602015-05-28 19:09:30 +0000231 if (auto EC = ArgsOrErr.getError()) {
232 llvm::errs() << EC.message() << "\n";
233 return false;
234 }
David Blaikie6521ed92015-06-22 22:06:52 +0000235 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000236
Rui Ueyama5c726432015-05-29 16:11:52 +0000237 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000238 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000239 printHelp(ArgsArr[0]);
Rui Ueyama5c726432015-05-29 16:11:52 +0000240 return true;
241 }
242
David Blaikie6521ed92015-06-22 22:06:52 +0000243 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000244 llvm::errs() << "no input files.\n";
245 return false;
246 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000247
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000248 // Construct search path list.
249 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000250 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000251 SearchPaths.push_back(Arg->getValue());
252 addLibSearchPaths();
253
Rui Ueyamaad660982015-06-07 00:20:32 +0000254 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000255 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000256 Config->OutputFile = Arg->getValue();
257
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000258 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000259 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000260 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000261
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000262 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000263 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000264 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000265 Config->ManifestID = 2;
266 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000267
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000268 // Handle /entry
David Blaikie6521ed92015-06-22 22:06:52 +0000269 if (auto *Arg = Args.getLastArg(OPT_entry))
Rui Ueyama411c63602015-05-28 19:09:30 +0000270 Config->EntryName = Arg->getValue();
271
Rui Ueyama588e8322015-06-15 01:23:58 +0000272 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000273 if (Args.hasArg(OPT_fixed)) {
274 if (Args.hasArg(OPT_dynamicbase)) {
Rui Ueyama6592ff82015-06-16 23:13:00 +0000275 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
276 return false;
277 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000278 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000279 Config->DynamicBase = false;
280 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000281
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000282 // Handle /machine
David Blaikie6521ed92015-06-22 22:06:52 +0000283 auto MTOrErr = getMachineType(&Args);
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000284 if (auto EC = MTOrErr.getError()) {
285 llvm::errs() << EC.message() << "\n";
286 return false;
287 }
288 Config->MachineType = MTOrErr.get();
289
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000290 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000291 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000292 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
293
294 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000295 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000296 Config->NoDefaultLibAll = true;
297
Rui Ueyama804a8b62015-05-29 16:18:15 +0000298 // Handle /base
David Blaikie6521ed92015-06-22 22:06:52 +0000299 if (auto *Arg = Args.getLastArg(OPT_base)) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000300 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000301 llvm::errs() << "/base: " << EC.message() << "\n";
302 return false;
303 }
304 }
305
306 // Handle /stack
David Blaikie6521ed92015-06-22 22:06:52 +0000307 if (auto *Arg = Args.getLastArg(OPT_stack)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000308 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
309 &Config->StackCommit)) {
310 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000311 return false;
312 }
313 }
314
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000315 // Handle /heap
David Blaikie6521ed92015-06-22 22:06:52 +0000316 if (auto *Arg = Args.getLastArg(OPT_heap)) {
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000317 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
318 &Config->HeapCommit)) {
319 llvm::errs() << "/heap: " << EC.message() << "\n";
320 return false;
321 }
322 }
323
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000324 // Handle /version
David Blaikie6521ed92015-06-22 22:06:52 +0000325 if (auto *Arg = Args.getLastArg(OPT_version)) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000326 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
327 &Config->MinorImageVersion)) {
328 llvm::errs() << "/version: " << EC.message() << "\n";
329 return false;
330 }
331 }
332
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000333 // Handle /subsystem
David Blaikie6521ed92015-06-22 22:06:52 +0000334 if (auto *Arg = Args.getLastArg(OPT_subsystem)) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000335 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
336 &Config->MajorOSVersion,
337 &Config->MinorOSVersion)) {
338 llvm::errs() << "/subsystem: " << EC.message() << "\n";
339 return false;
340 }
341 }
342
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000343 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000344 for (auto *Arg : Args.filtered(OPT_alternatename))
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000345 if (parseAlternateName(Arg->getValue()))
346 return false;
347
Rui Ueyama08d5e182015-06-18 23:20:11 +0000348 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000349 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama08d5e182015-06-18 23:20:11 +0000350 Config->Includes.insert(Arg->getValue());
351
Rui Ueyamab95188c2015-06-18 20:27:09 +0000352 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000353 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000354 Config->Implib = Arg->getValue();
355
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000356 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000357 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000358 std::string S = StringRef(Arg->getValue()).lower();
359 if (S == "noref") {
360 Config->DoGC = false;
361 continue;
362 }
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000363 if (S == "icf") {
364 Config->ICF = true;
365 continue;
366 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000367 if (S != "ref" && S != "icf" && S != "noicf" &&
368 S != "lbr" && S != "nolbr" &&
369 !StringRef(S).startswith("icf=")) {
370 llvm::errs() << "/opt: unknown option: " << S << "\n";
371 return false;
372 }
373 }
374
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000375 // Handle /export
David Blaikie6521ed92015-06-22 22:06:52 +0000376 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000377 ErrorOr<Export> E = parseExport(Arg->getValue());
378 if (E.getError())
379 return false;
380 Config->Exports.push_back(E.get());
381 }
382
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000383 // Handle /delayload
David Blaikie6521ed92015-06-22 22:06:52 +0000384 for (auto *Arg : Args.filtered(OPT_delayload)) {
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000385 Config->DelayLoads.insert(Arg->getValue());
386 Config->Includes.insert("__delayLoadHelper2");
387 }
388
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000389 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000390 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rui Ueyama75b098b2015-06-18 21:23:34 +0000391 if (checkFailIfMismatch(Arg->getValue()))
392 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000393
Rui Ueyama1f373702015-06-17 19:19:25 +0000394 // Handle /def
David Blaikie6521ed92015-06-22 22:06:52 +0000395 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyama1f373702015-06-17 19:19:25 +0000396 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
397 if (auto EC = MBOrErr.getError()) {
398 llvm::errs() << "/def: " << EC.message() << "\n";
399 return false;
400 }
401 // parseModuleDefs mutates Config object.
402 if (parseModuleDefs(MBOrErr.get()))
403 return false;
404 }
405
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000406 // Handle /manifest
David Blaikie6521ed92015-06-22 22:06:52 +0000407 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000408 if (auto EC = parseManifest(Arg->getValue())) {
409 llvm::errs() << "/manifest: " << EC.message() << "\n";
410 return false;
411 }
412 }
413
414 // Handle /manifestuac
David Blaikie6521ed92015-06-22 22:06:52 +0000415 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000416 if (auto EC = parseManifestUAC(Arg->getValue())) {
417 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
418 return false;
419 }
420 }
421
422 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000423 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000424 Config->ManifestDependency = Arg->getValue();
425
426 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000427 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000428 Config->ManifestFile = Arg->getValue();
429
Rui Ueyama6592ff82015-06-16 23:13:00 +0000430 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000431 if (Args.hasArg(OPT_allowbind_no))
432 Config->AllowBind = false;
433 if (Args.hasArg(OPT_allowisolation_no))
434 Config->AllowIsolation = false;
435 if (Args.hasArg(OPT_dynamicbase_no))
436 Config->DynamicBase = false;
437 if (Args.hasArg(OPT_highentropyva_no))
438 Config->HighEntropyVA = false;
439 if (Args.hasArg(OPT_nxcompat_no))
440 Config->NxCompat = false;
441 if (Args.hasArg(OPT_tsaware_no))
442 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000443
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000444 // Create a list of input files. Files can be given as arguments
445 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000446 std::vector<StringRef> InputPaths;
447 std::vector<MemoryBufferRef> Inputs;
David Blaikie6521ed92015-06-22 22:06:52 +0000448 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000449 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000450 InputPaths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000451 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000452 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000453 InputPaths.push_back(*Path);
454 for (StringRef Path : InputPaths) {
455 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
456 if (auto EC = MBOrErr.getError()) {
457 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
458 return false;
459 }
460 Inputs.push_back(MBOrErr.get());
461 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000462
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000463 // Windows specific -- Create a resource file containing a manifest file.
464 if (Config->Manifest == Configuration::Embed) {
465 auto MBOrErr = createManifestRes();
466 if (MBOrErr.getError())
467 return false;
468 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
469 Inputs.push_back(MB->getMemBufferRef());
470 OwningMBs.push_back(std::move(MB)); // take ownership
471 }
472
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000473 // Windows specific -- Input files can be Windows resource files (.res files).
474 // We invoke cvtres.exe to convert resource files to a regular COFF file
475 // then link the result file normally.
476 auto IsResource = [](MemoryBufferRef MB) {
477 return identify_magic(MB.getBuffer()) == file_magic::windows_resource;
478 };
479 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), IsResource);
480 if (It != Inputs.begin()) {
481 std::vector<MemoryBufferRef> Files(Inputs.begin(), It);
482 auto MBOrErr = convertResToCOFF(Files);
483 if (MBOrErr.getError())
484 return false;
485 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
486 Inputs = std::vector<MemoryBufferRef>(It, Inputs.end());
487 Inputs.push_back(MB->getMemBufferRef());
488 OwningMBs.push_back(std::move(MB)); // take ownership
489 }
490
Rui Ueyama411c63602015-05-28 19:09:30 +0000491 // Parse all input files and put all symbols to the symbol table.
492 // The symbol table will take care of name resolution.
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000493 for (MemoryBufferRef MB : Inputs)
494 Symtab.addFile(createFile(MB));
495 if (auto EC = Symtab.run()) {
496 llvm::errs() << EC.message() << "\n";
497 return false;
Rui Ueyama411c63602015-05-28 19:09:30 +0000498 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000499
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000500 // Resolve auxiliary symbols until converge.
501 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
502 // A new file may contain a directive section to add new command line options.
503 // That's why we have to repeat until converge.)
504 for (;;) {
505 size_t Ver = Symtab.getVersion();
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000506
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000507 // Add undefined symbols specified by /include.
508 for (StringRef Sym : Config->Includes)
509 Symtab.addUndefined(Sym);
Rui Ueyama5cff6852015-05-31 03:34:08 +0000510
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000511 // Windows specific -- Make sure we resolve all dllexported symbols.
512 for (Export &E : Config->Exports)
513 Symtab.addUndefined(E.Name);
514
515 // Add weak aliases. Weak aliases is a mechanism to give remaining
516 // undefined symbols final chance to be resolved successfully.
517 // This is symbol renaming.
518 for (auto &P : Config->AlternateNames) {
519 StringRef From = P.first;
520 StringRef To = P.second;
521 if (auto EC = Symtab.rename(From, To)) {
522 llvm::errs() << EC.message() << "\n";
523 return false;
524 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000525 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000526
527 // Windows specific -- If entry point name is not given, we need to
528 // infer that from user-defined entry name. The symbol table takes
529 // care of details.
530 if (Config->EntryName.empty()) {
531 auto EntryOrErr = Symtab.findDefaultEntry();
532 if (auto EC = EntryOrErr.getError()) {
533 llvm::errs() << EC.message() << "\n";
534 return false;
535 }
536 Config->EntryName = EntryOrErr.get();
537 }
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000538 Symtab.addUndefined(Config->EntryName);
539
540 if (auto EC = Symtab.run()) {
541 llvm::errs() << EC.message() << "\n";
542 return false;
543 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000544 if (Ver == Symtab.getVersion())
545 break;
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000546 }
547
Rui Ueyama5cff6852015-05-31 03:34:08 +0000548 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000549 if (Symtab.reportRemainingUndefines())
550 return false;
551
Rui Ueyama08d5e182015-06-18 23:20:11 +0000552 // Initialize a list of GC root.
553 for (StringRef Sym : Config->Includes)
554 Config->GCRoots.insert(Sym);
555 for (Export &E : Config->Exports)
556 Config->GCRoots.insert(E.Name);
557 Config->GCRoots.insert(Config->EntryName);
558
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000559 // Do LTO by compiling bitcode input files to a native COFF file
560 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000561 if (auto EC = Symtab.addCombinedLTOObject()) {
562 llvm::errs() << EC.message() << "\n";
563 return false;
564 }
565
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000566 // Windows specific -- if no /subsystem is given, we need to infer
567 // that from entry point name.
568 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000569 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000570 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
571 llvm::errs() << "subsystem must be defined\n";
572 return false;
573 }
574 }
575
Rui Ueyama151d8622015-06-17 20:40:43 +0000576 // Windows specific -- when we are creating a .dll file, we also
577 // need to create a .lib file.
578 if (!Config->Exports.empty())
579 writeImportLibrary();
580
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000581 // Windows specific -- fix up dllexported symbols.
582 if (!Config->Exports.empty()) {
583 for (Export &E : Config->Exports)
584 E.Sym = Symtab.find(E.Name);
585 if (fixupExports())
586 return false;
587 }
588
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000589 // Windows specific -- Create a side-by-side manifest file.
590 if (Config->Manifest == Configuration::SideBySide)
591 if (createSideBySideManifest())
592 return false;
593
Rui Ueyama411c63602015-05-28 19:09:30 +0000594 // Write the result.
595 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000596 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000597 llvm::errs() << EC.message() << "\n";
598 return false;
599 }
600 return true;
601}
602
Rui Ueyama411c63602015-05-28 19:09:30 +0000603} // namespace coff
604} // namespace lld