blob: 66009a203b31db2b332eaaf7f2b2c630b6c22648 [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;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000037using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000038using llvm::sys::fs::file_magic;
39using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000040
Rui Ueyama3500f662015-05-28 20:30:06 +000041namespace lld {
42namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000043
Rui Ueyama3500f662015-05-28 20:30:06 +000044Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000045LinkerDriver *Driver;
46
David Blaikie00818192015-06-22 22:06:48 +000047bool link(llvm::ArrayRef<const char *> Args) {
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000048 auto C = make_unique<Configuration>();
49 Config = C.get();
50 auto D = make_unique<LinkerDriver>();
51 Driver = D.get();
David Blaikieb2b1c7c2015-06-21 06:32:10 +000052 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000053}
Rui Ueyama411c63602015-05-28 19:09:30 +000054
Rui Ueyamaad660982015-06-07 00:20:32 +000055// Drop directory components and replace extension with ".exe".
56static std::string getOutputPath(StringRef Path) {
57 auto P = Path.find_last_of("\\/");
58 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
59 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000060}
61
Rui Ueyamad7c2f582015-05-31 21:04:56 +000062// Opens a file. Path has to be resolved already.
63// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000064ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000065 auto MBOrErr = MemoryBuffer::getFile(Path);
66 if (auto EC = MBOrErr.getError())
67 return EC;
68 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
69 MemoryBufferRef MBRef = MB->getMemBufferRef();
70 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000071 return MBRef;
72}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000073
Rui Ueyama2bf6a122015-06-14 21:50:50 +000074static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000075 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000076 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000077 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000078 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000079 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000080 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000081 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000082 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
83 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000084}
85
Rui Ueyama411c63602015-05-28 19:09:30 +000086// Parses .drectve section contents and returns a list of files
87// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000088std::error_code
Rui Ueyama0d2e9992015-06-23 23:56:39 +000089LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000090 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000091 if (auto EC = ArgsOrErr.getError())
92 return EC;
David Blaikie6521ed92015-06-22 22:06:52 +000093 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +000094
David Blaikie6521ed92015-06-22 22:06:52 +000095 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +000096 switch (Arg->getOption().getID()) {
97 case OPT_alternatename:
98 if (auto EC = parseAlternateName(Arg->getValue()))
Rui Ueyamad7c2f582015-05-31 21:04:56 +000099 return EC;
Rui Ueyama562daa82015-06-18 21:50:38 +0000100 break;
101 case OPT_defaultlib:
102 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
103 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
104 if (auto EC = MBOrErr.getError())
105 return EC;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000106 Symtab.addFile(createFile(MBOrErr.get()));
Rui Ueyama562daa82015-06-18 21:50:38 +0000107 }
108 break;
109 case OPT_export: {
110 ErrorOr<Export> E = parseExport(Arg->getValue());
111 if (auto EC = E.getError())
112 return EC;
113 Config->Exports.push_back(E.get());
114 break;
115 }
116 case OPT_failifmismatch:
117 if (auto EC = checkFailIfMismatch(Arg->getValue()))
118 return EC;
119 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000120 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000121 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000122 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000123 case OPT_merge:
124 // Ignore /merge for now.
125 break;
126 case OPT_nodefaultlib:
127 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
128 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000129 default:
130 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
131 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000132 }
133 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000134 return std::error_code();
135}
136
Rui Ueyama54b71da2015-05-31 19:17:12 +0000137// Find file from search paths. You can omit ".obj", this function takes
138// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000139StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000140 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
141 if (hasPathSep)
142 return Filename;
143 bool hasExt = (Filename.find('.') != StringRef::npos);
144 for (StringRef Dir : SearchPaths) {
145 SmallString<128> Path = Dir;
146 llvm::sys::path::append(Path, Filename);
147 if (llvm::sys::fs::exists(Path.str()))
148 return Alloc.save(Path.str());
149 if (!hasExt) {
150 Path.append(".obj");
151 if (llvm::sys::fs::exists(Path.str()))
152 return Alloc.save(Path.str());
153 }
154 }
155 return Filename;
156}
157
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000158// Resolves a file path. This never returns the same path
159// (in that case, it returns None).
160Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
161 StringRef Path = doFindFile(Filename);
162 bool Seen = !VisitedFiles.insert(Path.lower()).second;
163 if (Seen)
164 return None;
165 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000166}
167
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000168// Find library file from search path.
169StringRef LinkerDriver::doFindLib(StringRef Filename) {
170 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000171 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000172 if (!hasExt)
173 Filename = Alloc.save(Filename + ".lib");
174 return doFindFile(Filename);
175}
176
177// Resolves a library path. /nodefaultlib options are taken into
178// consideration. This never returns the same path (in that case,
179// it returns None).
180Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
181 if (Config->NoDefaultLibAll)
182 return None;
183 StringRef Path = doFindLib(Filename);
184 if (Config->NoDefaultLibs.count(Path))
185 return None;
186 bool Seen = !VisitedFiles.insert(Path.lower()).second;
187 if (Seen)
188 return None;
189 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000190}
191
192// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000193void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000194 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
195 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000196 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000197 StringRef Env = Alloc.save(*EnvOpt);
198 while (!Env.empty()) {
199 StringRef Path;
200 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000201 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000202 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000203}
204
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000205void LinkerDriver::addUndefined(StringRef Sym) {
206 Symtab.addUndefined(Sym);
207 Config->GCRoots.insert(Sym);
208}
209
Rui Ueyama45044f42015-06-29 01:03:53 +0000210// Windows specific -- find default entry point name.
211StringRef LinkerDriver::findDefaultEntry() {
212 // User-defined main functions and their corresponding entry points.
213 static const char *Entries[][2] = {
214 {"main", "mainCRTStartup"},
215 {"wmain", "wmainCRTStartup"},
216 {"WinMain", "WinMainCRTStartup"},
217 {"wWinMain", "wWinMainCRTStartup"},
218 };
219 for (auto E : Entries) {
Rui Ueyama4b669892015-06-30 23:46:52 +0000220 Symbol *Sym = Symtab.findSymbol(E[0]);
221 if (Sym && !isa<Undefined>(Sym->Body))
Rui Ueyama45044f42015-06-29 01:03:53 +0000222 return E[1];
223 }
224 return "";
225}
226
227WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000228 if (Config->DLL)
229 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama45044f42015-06-29 01:03:53 +0000230 if (Symtab.find("main") || Symtab.find("wmain"))
231 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
232 if (Symtab.find("WinMain") || Symtab.find("wWinMain"))
233 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
234 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000235}
236
David Blaikie00818192015-06-22 22:06:48 +0000237bool LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000238 // Needed for LTO.
239 llvm::InitializeAllTargetInfos();
240 llvm::InitializeAllTargets();
241 llvm::InitializeAllTargetMCs();
242 llvm::InitializeAllAsmParsers();
243 llvm::InitializeAllAsmPrinters();
244 llvm::InitializeAllDisassemblers();
245
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000246 // If the first command line argument is "/lib", link.exe acts like lib.exe.
247 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000248 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
249 return llvm::libDriverMain(ArgsArr.slice(1)) == 0;
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000250
Rui Ueyama411c63602015-05-28 19:09:30 +0000251 // Parse command line options.
Rui Ueyama9d72f092015-06-28 03:05:38 +0000252 auto ArgsOrErr = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000253 if (auto EC = ArgsOrErr.getError()) {
254 llvm::errs() << EC.message() << "\n";
255 return false;
256 }
David Blaikie6521ed92015-06-22 22:06:52 +0000257 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000258
Rui Ueyama5c726432015-05-29 16:11:52 +0000259 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000260 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000261 printHelp(ArgsArr[0]);
Rui Ueyama5c726432015-05-29 16:11:52 +0000262 return true;
263 }
264
David Blaikie6521ed92015-06-22 22:06:52 +0000265 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000266 llvm::errs() << "no input files.\n";
267 return false;
268 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000269
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000270 // Construct search path list.
271 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000272 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000273 SearchPaths.push_back(Arg->getValue());
274 addLibSearchPaths();
275
Rui Ueyamaad660982015-06-07 00:20:32 +0000276 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000277 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000278 Config->OutputFile = Arg->getValue();
279
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000280 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000281 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000282 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000283
Rui Ueyama95925fd2015-06-28 19:35:15 +0000284 // Handle /force or /force:unresolved
285 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
286 Config->Force = true;
287
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000288 // Handle /entry
289 if (auto *Arg = Args.getLastArg(OPT_entry)) {
290 Config->EntryName = Arg->getValue();
291 addUndefined(Config->EntryName);
292 }
293
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000294 // Handle /noentry
295 if (Args.hasArg(OPT_noentry)) {
296 if (!Args.hasArg(OPT_dll)) {
297 llvm::errs() << "/noentry must be specified with /dll\n";
298 return false;
299 }
300 Config->NoEntry = true;
301 }
302
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000303 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000304 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000305 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000306 Config->ManifestID = 2;
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000307 if (Config->EntryName.empty() && !Config->NoEntry) {
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000308 Config->EntryName = "_DllMainCRTStartup";
309 addUndefined("_DllMainCRTStartup");
310 }
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000311 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000312
Rui Ueyama588e8322015-06-15 01:23:58 +0000313 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000314 if (Args.hasArg(OPT_fixed)) {
315 if (Args.hasArg(OPT_dynamicbase)) {
Rui Ueyama6592ff82015-06-16 23:13:00 +0000316 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
317 return false;
318 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000319 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000320 Config->DynamicBase = false;
321 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000322
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000323 // Handle /machine
David Blaikie6521ed92015-06-22 22:06:52 +0000324 auto MTOrErr = getMachineType(&Args);
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000325 if (auto EC = MTOrErr.getError()) {
326 llvm::errs() << EC.message() << "\n";
327 return false;
328 }
329 Config->MachineType = MTOrErr.get();
330
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000331 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000332 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000333 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
334
335 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000336 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000337 Config->NoDefaultLibAll = true;
338
Rui Ueyama804a8b62015-05-29 16:18:15 +0000339 // Handle /base
David Blaikie6521ed92015-06-22 22:06:52 +0000340 if (auto *Arg = Args.getLastArg(OPT_base)) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000341 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000342 llvm::errs() << "/base: " << EC.message() << "\n";
343 return false;
344 }
345 }
346
347 // Handle /stack
David Blaikie6521ed92015-06-22 22:06:52 +0000348 if (auto *Arg = Args.getLastArg(OPT_stack)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000349 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
350 &Config->StackCommit)) {
351 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000352 return false;
353 }
354 }
355
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000356 // Handle /heap
David Blaikie6521ed92015-06-22 22:06:52 +0000357 if (auto *Arg = Args.getLastArg(OPT_heap)) {
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000358 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
359 &Config->HeapCommit)) {
360 llvm::errs() << "/heap: " << EC.message() << "\n";
361 return false;
362 }
363 }
364
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000365 // Handle /version
David Blaikie6521ed92015-06-22 22:06:52 +0000366 if (auto *Arg = Args.getLastArg(OPT_version)) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000367 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
368 &Config->MinorImageVersion)) {
369 llvm::errs() << "/version: " << EC.message() << "\n";
370 return false;
371 }
372 }
373
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000374 // Handle /subsystem
David Blaikie6521ed92015-06-22 22:06:52 +0000375 if (auto *Arg = Args.getLastArg(OPT_subsystem)) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000376 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
377 &Config->MajorOSVersion,
378 &Config->MinorOSVersion)) {
379 llvm::errs() << "/subsystem: " << EC.message() << "\n";
380 return false;
381 }
382 }
383
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000384 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000385 for (auto *Arg : Args.filtered(OPT_alternatename))
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000386 if (parseAlternateName(Arg->getValue()))
387 return false;
388
Rui Ueyama08d5e182015-06-18 23:20:11 +0000389 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000390 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000391 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000392
Rui Ueyamab95188c2015-06-18 20:27:09 +0000393 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000394 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000395 Config->Implib = Arg->getValue();
396
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000397 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000398 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000399 std::string S = StringRef(Arg->getValue()).lower();
400 if (S == "noref") {
401 Config->DoGC = false;
402 continue;
403 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000404 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000405 Config->ICF = true;
406 continue;
407 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000408 if (S != "ref" && S != "icf" && S != "noicf" &&
409 S != "lbr" && S != "nolbr" &&
410 !StringRef(S).startswith("icf=")) {
411 llvm::errs() << "/opt: unknown option: " << S << "\n";
412 return false;
413 }
414 }
415
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000416 // Handle /export
David Blaikie6521ed92015-06-22 22:06:52 +0000417 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000418 ErrorOr<Export> E = parseExport(Arg->getValue());
419 if (E.getError())
420 return false;
421 Config->Exports.push_back(E.get());
422 }
423
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000424 // Handle /delayload
David Blaikie6521ed92015-06-22 22:06:52 +0000425 for (auto *Arg : Args.filtered(OPT_delayload)) {
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000426 Config->DelayLoads.insert(Arg->getValue());
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000427 addUndefined("__delayLoadHelper2");
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000428 }
429
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000430 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000431 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rui Ueyama75b098b2015-06-18 21:23:34 +0000432 if (checkFailIfMismatch(Arg->getValue()))
433 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000434
Rui Ueyama1f373702015-06-17 19:19:25 +0000435 // Handle /def
David Blaikie6521ed92015-06-22 22:06:52 +0000436 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyama1f373702015-06-17 19:19:25 +0000437 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
438 if (auto EC = MBOrErr.getError()) {
439 llvm::errs() << "/def: " << EC.message() << "\n";
440 return false;
441 }
442 // parseModuleDefs mutates Config object.
443 if (parseModuleDefs(MBOrErr.get()))
444 return false;
445 }
446
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000447 // Handle /manifest
David Blaikie6521ed92015-06-22 22:06:52 +0000448 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000449 if (auto EC = parseManifest(Arg->getValue())) {
450 llvm::errs() << "/manifest: " << EC.message() << "\n";
451 return false;
452 }
453 }
454
455 // Handle /manifestuac
David Blaikie6521ed92015-06-22 22:06:52 +0000456 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000457 if (auto EC = parseManifestUAC(Arg->getValue())) {
458 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
459 return false;
460 }
461 }
462
463 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000464 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000465 Config->ManifestDependency = Arg->getValue();
466
467 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000468 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000469 Config->ManifestFile = Arg->getValue();
470
Rui Ueyama6592ff82015-06-16 23:13:00 +0000471 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000472 if (Args.hasArg(OPT_allowbind_no))
473 Config->AllowBind = false;
474 if (Args.hasArg(OPT_allowisolation_no))
475 Config->AllowIsolation = false;
476 if (Args.hasArg(OPT_dynamicbase_no))
477 Config->DynamicBase = false;
478 if (Args.hasArg(OPT_highentropyva_no))
479 Config->HighEntropyVA = false;
480 if (Args.hasArg(OPT_nxcompat_no))
481 Config->NxCompat = false;
482 if (Args.hasArg(OPT_tsaware_no))
483 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000484
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000485 // Create a list of input files. Files can be given as arguments
486 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000487 std::vector<StringRef> InputPaths;
488 std::vector<MemoryBufferRef> Inputs;
David Blaikie6521ed92015-06-22 22:06:52 +0000489 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000490 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000491 InputPaths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000492 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000493 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000494 InputPaths.push_back(*Path);
495 for (StringRef Path : InputPaths) {
496 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
497 if (auto EC = MBOrErr.getError()) {
498 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
499 return false;
500 }
501 Inputs.push_back(MBOrErr.get());
502 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000503
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000504 // Windows specific -- Create a resource file containing a manifest file.
505 if (Config->Manifest == Configuration::Embed) {
506 auto MBOrErr = createManifestRes();
507 if (MBOrErr.getError())
508 return false;
509 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
510 Inputs.push_back(MB->getMemBufferRef());
511 OwningMBs.push_back(std::move(MB)); // take ownership
512 }
513
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000514 // Windows specific -- Input files can be Windows resource files (.res files).
515 // We invoke cvtres.exe to convert resource files to a regular COFF file
516 // then link the result file normally.
Rui Ueyama77731b42015-06-26 23:59:13 +0000517 auto NotResource = [](MemoryBufferRef MB) {
518 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000519 };
Rui Ueyama77731b42015-06-26 23:59:13 +0000520 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), NotResource);
521 if (It != Inputs.end()) {
522 std::vector<MemoryBufferRef> Files(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000523 auto MBOrErr = convertResToCOFF(Files);
524 if (MBOrErr.getError())
525 return false;
526 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
Rui Ueyama77731b42015-06-26 23:59:13 +0000527 Inputs.erase(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000528 Inputs.push_back(MB->getMemBufferRef());
529 OwningMBs.push_back(std::move(MB)); // take ownership
530 }
531
Rui Ueyama411c63602015-05-28 19:09:30 +0000532 // Parse all input files and put all symbols to the symbol table.
533 // The symbol table will take care of name resolution.
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000534 for (MemoryBufferRef MB : Inputs)
535 Symtab.addFile(createFile(MB));
Rui Ueyama8d3010a2015-06-30 19:35:21 +0000536 if (auto EC = Symtab.readObjects()) {
537 llvm::errs() << EC.message() << "\n";
538 return false;
539 }
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000540 if (auto EC = Symtab.run()) {
541 llvm::errs() << EC.message() << "\n";
542 return false;
Rui Ueyama411c63602015-05-28 19:09:30 +0000543 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000544
Rui Ueyama45044f42015-06-29 01:03:53 +0000545 // Windows specific -- If entry point name is not given, we need to
546 // infer that from user-defined entry name.
547 if (Config->EntryName.empty() && !Config->NoEntry) {
548 StringRef S = findDefaultEntry();
549 if (S.empty()) {
550 llvm::errs() << "entry point must be defined\n";
551 return false;
552 }
553 Config->EntryName = S;
554 addUndefined(S);
555 }
556
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000557 // Resolve auxiliary symbols until converge.
558 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
559 // A new file may contain a directive section to add new command line options.
560 // That's why we have to repeat until converge.)
561 for (;;) {
562 size_t Ver = Symtab.getVersion();
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000563
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000564 // Windows specific -- Make sure we resolve all dllexported symbols.
565 for (Export &E : Config->Exports)
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000566 addUndefined(E.Name);
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000567
568 // Add weak aliases. Weak aliases is a mechanism to give remaining
569 // undefined symbols final chance to be resolved successfully.
570 // This is symbol renaming.
571 for (auto &P : Config->AlternateNames) {
572 StringRef From = P.first;
573 StringRef To = P.second;
574 if (auto EC = Symtab.rename(From, To)) {
575 llvm::errs() << EC.message() << "\n";
576 return false;
577 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000578 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000579
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000580 if (auto EC = Symtab.run()) {
581 llvm::errs() << EC.message() << "\n";
582 return false;
583 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000584 if (Ver == Symtab.getVersion())
585 break;
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000586 }
587
Rui Ueyama2d5e9172015-06-29 14:43:07 +0000588 // Windows specific -- if entry point is not found,
589 // search for its mangled names.
590 if (!Config->EntryName.empty() && !Symtab.find(Config->EntryName)) {
591 StringRef Name;
592 Symbol *Sym;
593 std::tie(Name, Sym) = Symtab.findMangled(Config->EntryName);
594 if (Sym)
595 Symtab.rename(Config->EntryName, Name);
596 }
597
Rui Ueyamaf5313b32015-06-28 22:16:41 +0000598 // Windows specific -- resolve dllexported symbols.
599 for (Export &E : Config->Exports) {
600 StringRef Name;
601 Symbol *Sym;
602 std::tie(Name, Sym) = Symtab.findMangled(E.Name);
603 if (!Sym) {
604 llvm::errs() << "exported symbol is not defined: " << E.Name << "\n";
605 return false;
606 }
607 if (E.Name != Name)
608 Symtab.rename(E.Name, Name);
609 E.Sym = Sym;
610 }
611
Rui Ueyama5cff6852015-05-31 03:34:08 +0000612 // Make sure we have resolved all symbols.
Rui Ueyama411c63602015-05-28 19:09:30 +0000613 if (Symtab.reportRemainingUndefines())
614 return false;
615
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000616 // Do LTO by compiling bitcode input files to a native COFF file
617 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000618 if (auto EC = Symtab.addCombinedLTOObject()) {
619 llvm::errs() << EC.message() << "\n";
620 return false;
621 }
622
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000623 // Windows specific -- if no /subsystem is given, we need to infer
624 // that from entry point name.
625 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000626 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000627 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
628 llvm::errs() << "subsystem must be defined\n";
629 return false;
630 }
631 }
632
Rui Ueyama151d8622015-06-17 20:40:43 +0000633 // Windows specific -- when we are creating a .dll file, we also
634 // need to create a .lib file.
635 if (!Config->Exports.empty())
636 writeImportLibrary();
637
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000638 // Windows specific -- fix up dllexported symbols.
Rui Ueyamaf5313b32015-06-28 22:16:41 +0000639 if (!Config->Exports.empty())
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000640 if (fixupExports())
641 return false;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000642
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000643 // Windows specific -- Create a side-by-side manifest file.
644 if (Config->Manifest == Configuration::SideBySide)
645 if (createSideBySideManifest())
646 return false;
647
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000648 // Create a dummy PDB file to satisfy build sytem rules.
649 if (auto *Arg = Args.getLastArg(OPT_pdb))
650 touchFile(Arg->getValue());
651
Rui Ueyama411c63602015-05-28 19:09:30 +0000652 // Write the result.
653 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000654 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000655 llvm::errs() << EC.message() << "\n";
656 return false;
657 }
Peter Collingbournebe549552015-06-26 18:58:24 +0000658
Rui Ueyama016414f2015-06-28 20:07:08 +0000659 // Create a symbol map file containing symbol VAs and their names
660 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000661 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
662 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000663 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Peter Collingbournebe549552015-06-26 18:58:24 +0000664 if (EC) {
665 llvm::errs() << EC.message() << "\n";
666 return false;
667 }
668 Symtab.printMap(Out);
669 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000670 return true;
671}
672
Rui Ueyama411c63602015-05-28 19:09:30 +0000673} // namespace coff
674} // namespace lld