blob: 522bc9bf0f9f2e27f948fe11e6b11af0c76e68ae [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 Ueyama84936e02015-07-07 23:39:18 +000033using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000034using llvm::sys::Process;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000035using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000036using llvm::sys::fs::file_magic;
37using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000038
Rui Ueyama3500f662015-05-28 20:30:06 +000039namespace lld {
40namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000041
Rui Ueyama3500f662015-05-28 20:30:06 +000042Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000043LinkerDriver *Driver;
44
David Blaikie00818192015-06-22 22:06:48 +000045bool link(llvm::ArrayRef<const char *> Args) {
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000046 auto C = make_unique<Configuration>();
47 Config = C.get();
48 auto D = make_unique<LinkerDriver>();
49 Driver = D.get();
David Blaikieb2b1c7c2015-06-21 06:32:10 +000050 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000051}
Rui Ueyama411c63602015-05-28 19:09:30 +000052
Rui Ueyamaad660982015-06-07 00:20:32 +000053// Drop directory components and replace extension with ".exe".
54static std::string getOutputPath(StringRef Path) {
55 auto P = Path.find_last_of("\\/");
56 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
57 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000058}
59
Rui Ueyamad7c2f582015-05-31 21:04:56 +000060// Opens a file. Path has to be resolved already.
61// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000062ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000063 auto MBOrErr = MemoryBuffer::getFile(Path);
64 if (auto EC = MBOrErr.getError())
65 return EC;
66 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
67 MemoryBufferRef MBRef = MB->getMemBufferRef();
68 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000069 return MBRef;
70}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000071
Rui Ueyama2bf6a122015-06-14 21:50:50 +000072static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000073 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000074 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000075 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000076 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000077 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000078 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000079 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000080 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
81 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000082}
83
Rui Ueyama411c63602015-05-28 19:09:30 +000084// Parses .drectve section contents and returns a list of files
85// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000086std::error_code
Rui Ueyama0d2e9992015-06-23 23:56:39 +000087LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000088 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000089 if (auto EC = ArgsOrErr.getError())
90 return EC;
David Blaikie6521ed92015-06-22 22:06:52 +000091 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +000092
David Blaikie6521ed92015-06-22 22:06:52 +000093 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +000094 switch (Arg->getOption().getID()) {
95 case OPT_alternatename:
96 if (auto EC = parseAlternateName(Arg->getValue()))
Rui Ueyamad7c2f582015-05-31 21:04:56 +000097 return EC;
Rui Ueyama562daa82015-06-18 21:50:38 +000098 break;
99 case OPT_defaultlib:
100 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
101 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
102 if (auto EC = MBOrErr.getError())
103 return EC;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000104 Symtab.addFile(createFile(MBOrErr.get()));
Rui Ueyama562daa82015-06-18 21:50:38 +0000105 }
106 break;
107 case OPT_export: {
108 ErrorOr<Export> E = parseExport(Arg->getValue());
109 if (auto EC = E.getError())
110 return EC;
111 Config->Exports.push_back(E.get());
112 break;
113 }
114 case OPT_failifmismatch:
115 if (auto EC = checkFailIfMismatch(Arg->getValue()))
116 return EC;
117 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000118 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000119 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000120 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000121 case OPT_merge:
Rui Ueyama6600eb12015-07-04 23:37:32 +0000122 if (auto EC = parseMerge(Arg->getValue()))
123 return EC;
Rui Ueyamace86c992015-06-18 23:22:39 +0000124 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 Ueyama6bf638e2015-07-02 00:04:14 +0000204Undefined *LinkerDriver::addUndefined(StringRef Name) {
205 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000206 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000207 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000208}
209
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000210// Symbol names are mangled by appending "_" prefix on x86.
211StringRef LinkerDriver::mangle(StringRef Sym) {
212 if (Config->MachineType == IMAGE_FILE_MACHINE_I386)
213 return Alloc.save("_" + Sym);
214 return Sym;
215}
216
Rui Ueyama45044f42015-06-29 01:03:53 +0000217// Windows specific -- find default entry point name.
218StringRef LinkerDriver::findDefaultEntry() {
219 // User-defined main functions and their corresponding entry points.
220 static const char *Entries[][2] = {
221 {"main", "mainCRTStartup"},
222 {"wmain", "wmainCRTStartup"},
223 {"WinMain", "WinMainCRTStartup"},
224 {"wWinMain", "wWinMainCRTStartup"},
225 };
226 for (auto E : Entries) {
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000227 Symbol *Sym = Symtab.find(mangle(E[0]));
Rui Ueyama183f53f2015-07-06 17:45:22 +0000228 if (Sym && !isa<Undefined>(Sym->Body))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000229 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000230 }
231 return "";
232}
233
234WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000235 if (Config->DLL)
236 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000237 if (Symtab.find(mangle("main")) || Symtab.find(mangle("wmain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000238 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000239 if (Symtab.find(mangle("WinMain")) || Symtab.find(mangle("wWinMain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000240 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
241 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000242}
243
David Blaikie00818192015-06-22 22:06:48 +0000244bool LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000245 // Needed for LTO.
246 llvm::InitializeAllTargetInfos();
247 llvm::InitializeAllTargets();
248 llvm::InitializeAllTargetMCs();
249 llvm::InitializeAllAsmParsers();
250 llvm::InitializeAllAsmPrinters();
251 llvm::InitializeAllDisassemblers();
252
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000253 // If the first command line argument is "/lib", link.exe acts like lib.exe.
254 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000255 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
256 return llvm::libDriverMain(ArgsArr.slice(1)) == 0;
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000257
Rui Ueyama411c63602015-05-28 19:09:30 +0000258 // Parse command line options.
Rui Ueyama9d72f092015-06-28 03:05:38 +0000259 auto ArgsOrErr = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000260 if (auto EC = ArgsOrErr.getError()) {
261 llvm::errs() << EC.message() << "\n";
262 return false;
263 }
David Blaikie6521ed92015-06-22 22:06:52 +0000264 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000265
Rui Ueyama5c726432015-05-29 16:11:52 +0000266 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000267 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000268 printHelp(ArgsArr[0]);
Rui Ueyama5c726432015-05-29 16:11:52 +0000269 return true;
270 }
271
David Blaikie6521ed92015-06-22 22:06:52 +0000272 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000273 llvm::errs() << "no input files.\n";
274 return false;
275 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000276
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000277 // Construct search path list.
278 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000279 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000280 SearchPaths.push_back(Arg->getValue());
281 addLibSearchPaths();
282
Rui Ueyamaad660982015-06-07 00:20:32 +0000283 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000284 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000285 Config->OutputFile = Arg->getValue();
286
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000287 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000288 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000289 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000290
Rui Ueyama95925fd2015-06-28 19:35:15 +0000291 // Handle /force or /force:unresolved
292 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
293 Config->Force = true;
294
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000295 // Handle /entry
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000296 if (auto *Arg = Args.getLastArg(OPT_entry))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000297 Config->Entry = addUndefined(mangle(Arg->getValue()));
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000298
Rui Ueyama6600eb12015-07-04 23:37:32 +0000299 // Handle /debug
300 if (Args.hasArg(OPT_debug))
301 Config->Debug = true;
302
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000303 // Handle /noentry
304 if (Args.hasArg(OPT_noentry)) {
305 if (!Args.hasArg(OPT_dll)) {
306 llvm::errs() << "/noentry must be specified with /dll\n";
307 return false;
308 }
309 Config->NoEntry = true;
310 }
311
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000312 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000313 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000314 Config->DLL = true;
Rui Ueyama49d6cd32015-07-03 00:02:19 +0000315 Config->ImageBase = 0x180000000U;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000316 Config->ManifestID = 2;
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000317 if (Config->Entry == nullptr && !Config->NoEntry)
318 Config->Entry = addUndefined("_DllMainCRTStartup");
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000319 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000320
Rui Ueyama588e8322015-06-15 01:23:58 +0000321 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000322 if (Args.hasArg(OPT_fixed)) {
323 if (Args.hasArg(OPT_dynamicbase)) {
Rui Ueyama6592ff82015-06-16 23:13:00 +0000324 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
325 return false;
326 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000327 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000328 Config->DynamicBase = false;
329 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000330
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000331 // Handle /machine
Rui Ueyamae16a75d52015-07-08 18:14:51 +0000332 if (auto *Arg = Args.getLastArg(OPT_machine)) {
333 ErrorOr<MachineTypes> MTOrErr = getMachineType(Arg->getValue());
334 if (MTOrErr.getError())
335 return false;
336 Config->MachineType = MTOrErr.get();
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000337 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000338
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000339 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000340 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000341 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
342
343 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000344 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000345 Config->NoDefaultLibAll = true;
346
Rui Ueyama804a8b62015-05-29 16:18:15 +0000347 // Handle /base
David Blaikie6521ed92015-06-22 22:06:52 +0000348 if (auto *Arg = Args.getLastArg(OPT_base)) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000349 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000350 llvm::errs() << "/base: " << EC.message() << "\n";
351 return false;
352 }
353 }
354
355 // Handle /stack
David Blaikie6521ed92015-06-22 22:06:52 +0000356 if (auto *Arg = Args.getLastArg(OPT_stack)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000357 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
358 &Config->StackCommit)) {
359 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000360 return false;
361 }
362 }
363
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000364 // Handle /heap
David Blaikie6521ed92015-06-22 22:06:52 +0000365 if (auto *Arg = Args.getLastArg(OPT_heap)) {
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000366 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
367 &Config->HeapCommit)) {
368 llvm::errs() << "/heap: " << EC.message() << "\n";
369 return false;
370 }
371 }
372
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000373 // Handle /version
David Blaikie6521ed92015-06-22 22:06:52 +0000374 if (auto *Arg = Args.getLastArg(OPT_version)) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000375 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
376 &Config->MinorImageVersion)) {
377 llvm::errs() << "/version: " << EC.message() << "\n";
378 return false;
379 }
380 }
381
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000382 // Handle /subsystem
David Blaikie6521ed92015-06-22 22:06:52 +0000383 if (auto *Arg = Args.getLastArg(OPT_subsystem)) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000384 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
385 &Config->MajorOSVersion,
386 &Config->MinorOSVersion)) {
387 llvm::errs() << "/subsystem: " << EC.message() << "\n";
388 return false;
389 }
390 }
391
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000392 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000393 for (auto *Arg : Args.filtered(OPT_alternatename))
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000394 if (parseAlternateName(Arg->getValue()))
395 return false;
396
Rui Ueyama08d5e182015-06-18 23:20:11 +0000397 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000398 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000399 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000400
Rui Ueyamab95188c2015-06-18 20:27:09 +0000401 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000402 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000403 Config->Implib = Arg->getValue();
404
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000405 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000406 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000407 std::string S = StringRef(Arg->getValue()).lower();
408 if (S == "noref") {
409 Config->DoGC = false;
410 continue;
411 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000412 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000413 Config->ICF = true;
414 continue;
415 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000416 if (S != "ref" && S != "icf" && S != "noicf" &&
417 S != "lbr" && S != "nolbr" &&
418 !StringRef(S).startswith("icf=")) {
419 llvm::errs() << "/opt: unknown option: " << S << "\n";
420 return false;
421 }
422 }
423
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000424 // Handle /export
David Blaikie6521ed92015-06-22 22:06:52 +0000425 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000426 ErrorOr<Export> E = parseExport(Arg->getValue());
427 if (E.getError())
428 return false;
429 Config->Exports.push_back(E.get());
430 }
431
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000432 // Handle /delayload
David Blaikie6521ed92015-06-22 22:06:52 +0000433 for (auto *Arg : Args.filtered(OPT_delayload)) {
Rui Ueyama7a247ee2015-07-03 01:40:14 +0000434 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000435 addUndefined("__delayLoadHelper2");
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000436 }
437
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000438 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000439 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rui Ueyama75b098b2015-06-18 21:23:34 +0000440 if (checkFailIfMismatch(Arg->getValue()))
441 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000442
Rui Ueyama1f373702015-06-17 19:19:25 +0000443 // Handle /def
David Blaikie6521ed92015-06-22 22:06:52 +0000444 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyama1f373702015-06-17 19:19:25 +0000445 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
446 if (auto EC = MBOrErr.getError()) {
447 llvm::errs() << "/def: " << EC.message() << "\n";
448 return false;
449 }
450 // parseModuleDefs mutates Config object.
451 if (parseModuleDefs(MBOrErr.get()))
452 return false;
453 }
454
Rui Ueyama6600eb12015-07-04 23:37:32 +0000455 // Handle /merge
456 for (auto *Arg : Args.filtered(OPT_merge))
457 if (parseMerge(Arg->getValue()))
458 return false;
459
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000460 // Handle /manifest
David Blaikie6521ed92015-06-22 22:06:52 +0000461 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000462 if (auto EC = parseManifest(Arg->getValue())) {
463 llvm::errs() << "/manifest: " << EC.message() << "\n";
464 return false;
465 }
466 }
467
468 // Handle /manifestuac
David Blaikie6521ed92015-06-22 22:06:52 +0000469 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000470 if (auto EC = parseManifestUAC(Arg->getValue())) {
471 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
472 return false;
473 }
474 }
475
476 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000477 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000478 Config->ManifestDependency = Arg->getValue();
479
480 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000481 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000482 Config->ManifestFile = Arg->getValue();
483
Rui Ueyama6592ff82015-06-16 23:13:00 +0000484 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000485 if (Args.hasArg(OPT_allowbind_no))
486 Config->AllowBind = false;
487 if (Args.hasArg(OPT_allowisolation_no))
488 Config->AllowIsolation = false;
489 if (Args.hasArg(OPT_dynamicbase_no))
490 Config->DynamicBase = false;
491 if (Args.hasArg(OPT_highentropyva_no))
492 Config->HighEntropyVA = false;
493 if (Args.hasArg(OPT_nxcompat_no))
494 Config->NxCompat = false;
495 if (Args.hasArg(OPT_tsaware_no))
496 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000497
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000498 // Create a list of input files. Files can be given as arguments
499 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000500 std::vector<StringRef> InputPaths;
501 std::vector<MemoryBufferRef> Inputs;
David Blaikie6521ed92015-06-22 22:06:52 +0000502 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000503 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000504 InputPaths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000505 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000506 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000507 InputPaths.push_back(*Path);
508 for (StringRef Path : InputPaths) {
509 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
510 if (auto EC = MBOrErr.getError()) {
511 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
512 return false;
513 }
514 Inputs.push_back(MBOrErr.get());
515 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000516
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000517 // Windows specific -- Create a resource file containing a manifest file.
518 if (Config->Manifest == Configuration::Embed) {
519 auto MBOrErr = createManifestRes();
520 if (MBOrErr.getError())
521 return false;
522 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
523 Inputs.push_back(MB->getMemBufferRef());
524 OwningMBs.push_back(std::move(MB)); // take ownership
525 }
526
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000527 // Windows specific -- Input files can be Windows resource files (.res files).
528 // We invoke cvtres.exe to convert resource files to a regular COFF file
529 // then link the result file normally.
Rui Ueyama77731b42015-06-26 23:59:13 +0000530 auto NotResource = [](MemoryBufferRef MB) {
531 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000532 };
Rui Ueyama77731b42015-06-26 23:59:13 +0000533 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), NotResource);
534 if (It != Inputs.end()) {
535 std::vector<MemoryBufferRef> Files(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000536 auto MBOrErr = convertResToCOFF(Files);
537 if (MBOrErr.getError())
538 return false;
539 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
Rui Ueyama77731b42015-06-26 23:59:13 +0000540 Inputs.erase(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000541 Inputs.push_back(MB->getMemBufferRef());
542 OwningMBs.push_back(std::move(MB)); // take ownership
543 }
544
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000545 Symtab.addAbsolute(mangle("__ImageBase"), Config->ImageBase);
Rui Ueyama49d6cd32015-07-03 00:02:19 +0000546
Rui Ueyama85225b02015-07-02 03:15:15 +0000547 // Read all input files given via the command line. Note that step()
548 // doesn't read files that are specified by directive sections.
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000549 for (MemoryBufferRef MB : Inputs)
550 Symtab.addFile(createFile(MB));
Rui Ueyama85225b02015-07-02 03:15:15 +0000551 if (auto EC = Symtab.step()) {
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000552 llvm::errs() << EC.message() << "\n";
553 return false;
Rui Ueyama411c63602015-05-28 19:09:30 +0000554 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000555
Rui Ueyama45044f42015-06-29 01:03:53 +0000556 // Windows specific -- If entry point name is not given, we need to
557 // infer that from user-defined entry name.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000558 if (Config->Entry == nullptr && !Config->NoEntry) {
Rui Ueyama45044f42015-06-29 01:03:53 +0000559 StringRef S = findDefaultEntry();
560 if (S.empty()) {
561 llvm::errs() << "entry point must be defined\n";
562 return false;
563 }
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000564 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000565 if (Config->Verbose)
566 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000567 }
568
Rui Ueyama85225b02015-07-02 03:15:15 +0000569 // Read as much files as we can.
570 if (auto EC = Symtab.run()) {
571 llvm::errs() << EC.message() << "\n";
572 return false;
573 }
574
575 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000576 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
577 // A new file may contain a directive section to add new command line options.
578 // That's why we have to repeat until converge.)
579 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000580 // Windows specific -- if entry point is not found,
581 // search for its mangled names.
582 if (Config->Entry)
583 Symtab.mangleMaybe(Config->Entry);
584
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000585 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000586 for (Export &E : Config->Exports) {
587 E.Sym = addUndefined(E.Name);
588 Symtab.mangleMaybe(E.Sym);
589 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000590
591 // Add weak aliases. Weak aliases is a mechanism to give remaining
592 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000593 for (auto Pair : Config->AlternateNames) {
594 StringRef From = Pair.first;
595 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000596 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000597 if (!Sym)
598 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000599 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000600 if (!U->WeakAlias)
601 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000602 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000603
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000604 if (Symtab.queueEmpty())
605 break;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000606 if (auto EC = Symtab.run()) {
607 llvm::errs() << EC.message() << "\n";
608 return false;
609 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000610 }
611
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000612 // Do LTO by compiling bitcode input files to a native COFF file
613 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000614 if (auto EC = Symtab.addCombinedLTOObject()) {
615 llvm::errs() << EC.message() << "\n";
616 return false;
617 }
618
Peter Collingbourne2612a322015-07-04 05:28:41 +0000619 // Make sure we have resolved all symbols.
620 if (Symtab.reportRemainingUndefines(/*Resolve=*/true))
621 return false;
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 Ueyama84936e02015-07-07 23:39:18 +0000633 // Check if all object files are for the same CPU type and
634 // compatible with /machine option (if given).
635 for (ObjectFile *File : Symtab.ObjectFiles) {
636 auto MT = static_cast<MachineTypes>(File->getCOFFObj()->getMachine());
637 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
638 continue;
639 if (Config->MachineType == IMAGE_FILE_MACHINE_UNKNOWN) {
640 Config->MachineType = MT;
641 continue;
642 }
643 if (Config->MachineType != MT) {
644 llvm::errs() << File->getShortName() << ": machine type "
645 << machineTypeToStr(MT) << " conflicts with "
646 << machineTypeToStr(Config->MachineType) << "\n";
647 return false;
648 }
649 }
650 if (Config->MachineType == IMAGE_FILE_MACHINE_UNKNOWN) {
651 llvm::errs() << "machine type must be specified\n";
652 return false;
653 }
654
Rui Ueyama151d8622015-06-17 20:40:43 +0000655 // Windows specific -- when we are creating a .dll file, we also
656 // need to create a .lib file.
657 if (!Config->Exports.empty())
658 writeImportLibrary();
659
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000660 // Windows specific -- fix up dllexported symbols.
Rui Ueyamaf5313b32015-06-28 22:16:41 +0000661 if (!Config->Exports.empty())
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000662 if (fixupExports())
663 return false;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000664
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000665 // Windows specific -- Create a side-by-side manifest file.
666 if (Config->Manifest == Configuration::SideBySide)
667 if (createSideBySideManifest())
668 return false;
669
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000670 // Create a dummy PDB file to satisfy build sytem rules.
671 if (auto *Arg = Args.getLastArg(OPT_pdb))
672 touchFile(Arg->getValue());
673
Rui Ueyama411c63602015-05-28 19:09:30 +0000674 // Write the result.
675 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000676 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000677 llvm::errs() << EC.message() << "\n";
678 return false;
679 }
Peter Collingbournebe549552015-06-26 18:58:24 +0000680
Rui Ueyama016414f2015-06-28 20:07:08 +0000681 // Create a symbol map file containing symbol VAs and their names
682 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000683 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
684 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000685 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Peter Collingbournebe549552015-06-26 18:58:24 +0000686 if (EC) {
687 llvm::errs() << EC.message() << "\n";
688 return false;
689 }
690 Symtab.printMap(Out);
691 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000692 // Call exit to avoid calling destructors.
693 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000694}
695
Rui Ueyama411c63602015-05-28 19:09:30 +0000696} // namespace coff
697} // namespace lld