blob: b7e7f4cbeaf8a38b0833965e82672cb6f09373be [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;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000111 if (Config->Machine == I386 && E->ExtName.startswith("_"))
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000112 E->ExtName = E->ExtName.substr(1);
Rui Ueyama562daa82015-06-18 21:50:38 +0000113 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:
Rui Ueyama6600eb12015-07-04 23:37:32 +0000124 if (auto EC = parseMerge(Arg->getValue()))
125 return EC;
Rui Ueyamace86c992015-06-18 23:22:39 +0000126 break;
127 case OPT_nodefaultlib:
128 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
129 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000130 default:
131 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
132 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000133 }
134 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000135 return std::error_code();
136}
137
Rui Ueyama54b71da2015-05-31 19:17:12 +0000138// Find file from search paths. You can omit ".obj", this function takes
139// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000140StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000141 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
142 if (hasPathSep)
143 return Filename;
144 bool hasExt = (Filename.find('.') != StringRef::npos);
145 for (StringRef Dir : SearchPaths) {
146 SmallString<128> Path = Dir;
147 llvm::sys::path::append(Path, Filename);
148 if (llvm::sys::fs::exists(Path.str()))
149 return Alloc.save(Path.str());
150 if (!hasExt) {
151 Path.append(".obj");
152 if (llvm::sys::fs::exists(Path.str()))
153 return Alloc.save(Path.str());
154 }
155 }
156 return Filename;
157}
158
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000159// Resolves a file path. This never returns the same path
160// (in that case, it returns None).
161Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
162 StringRef Path = doFindFile(Filename);
163 bool Seen = !VisitedFiles.insert(Path.lower()).second;
164 if (Seen)
165 return None;
166 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000167}
168
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000169// Find library file from search path.
170StringRef LinkerDriver::doFindLib(StringRef Filename) {
171 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000172 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000173 if (!hasExt)
174 Filename = Alloc.save(Filename + ".lib");
175 return doFindFile(Filename);
176}
177
178// Resolves a library path. /nodefaultlib options are taken into
179// consideration. This never returns the same path (in that case,
180// it returns None).
181Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
182 if (Config->NoDefaultLibAll)
183 return None;
184 StringRef Path = doFindLib(Filename);
185 if (Config->NoDefaultLibs.count(Path))
186 return None;
187 bool Seen = !VisitedFiles.insert(Path.lower()).second;
188 if (Seen)
189 return None;
190 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000191}
192
193// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000194void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000195 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
196 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000197 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000198 StringRef Env = Alloc.save(*EnvOpt);
199 while (!Env.empty()) {
200 StringRef Path;
201 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000202 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000203 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000204}
205
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000206Undefined *LinkerDriver::addUndefined(StringRef Name) {
207 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000208 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000209 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000210}
211
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000212// Symbol names are mangled by appending "_" prefix on x86.
213StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000214 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
215 if (Config->Machine == I386)
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000216 return Alloc.save("_" + Sym);
217 return Sym;
218}
219
Rui Ueyama45044f42015-06-29 01:03:53 +0000220// Windows specific -- find default entry point name.
221StringRef LinkerDriver::findDefaultEntry() {
222 // User-defined main functions and their corresponding entry points.
223 static const char *Entries[][2] = {
224 {"main", "mainCRTStartup"},
225 {"wmain", "wmainCRTStartup"},
226 {"WinMain", "WinMainCRTStartup"},
227 {"wWinMain", "wWinMainCRTStartup"},
228 };
229 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000230 StringRef Entry = Symtab.findMangle(mangle(E[0]));
231 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000232 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000233 }
234 return "";
235}
236
237WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000238 if (Config->DLL)
239 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000240 if (Symtab.find(mangle("main")) || Symtab.find(mangle("wmain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000241 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000242 if (Symtab.find(mangle("WinMain")) || Symtab.find(mangle("wWinMain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000243 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
244 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000245}
246
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000247static uint64_t getDefaultImageBase() {
248 if (Config->is64())
249 return Config->DLL ? 0x180000000 : 0x140000000;
250 return Config->DLL ? 0x10000000 : 0x400000;
251}
252
David Blaikie00818192015-06-22 22:06:48 +0000253bool LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000254 // Needed for LTO.
255 llvm::InitializeAllTargetInfos();
256 llvm::InitializeAllTargets();
257 llvm::InitializeAllTargetMCs();
258 llvm::InitializeAllAsmParsers();
259 llvm::InitializeAllAsmPrinters();
260 llvm::InitializeAllDisassemblers();
261
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000262 // If the first command line argument is "/lib", link.exe acts like lib.exe.
263 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000264 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
265 return llvm::libDriverMain(ArgsArr.slice(1)) == 0;
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000266
Rui Ueyama411c63602015-05-28 19:09:30 +0000267 // Parse command line options.
Rui Ueyama9d72f092015-06-28 03:05:38 +0000268 auto ArgsOrErr = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000269 if (auto EC = ArgsOrErr.getError()) {
270 llvm::errs() << EC.message() << "\n";
271 return false;
272 }
David Blaikie6521ed92015-06-22 22:06:52 +0000273 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000274
Rui Ueyama5c726432015-05-29 16:11:52 +0000275 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000276 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000277 printHelp(ArgsArr[0]);
Rui Ueyama5c726432015-05-29 16:11:52 +0000278 return true;
279 }
280
David Blaikie6521ed92015-06-22 22:06:52 +0000281 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000282 llvm::errs() << "no input files.\n";
283 return false;
284 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000285
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000286 // Construct search path list.
287 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000288 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000289 SearchPaths.push_back(Arg->getValue());
290 addLibSearchPaths();
291
Rui Ueyamaad660982015-06-07 00:20:32 +0000292 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000293 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000294 Config->OutputFile = Arg->getValue();
295
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000296 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000297 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000298 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000299
Rui Ueyama95925fd2015-06-28 19:35:15 +0000300 // Handle /force or /force:unresolved
301 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
302 Config->Force = true;
303
Rui Ueyama6600eb12015-07-04 23:37:32 +0000304 // Handle /debug
305 if (Args.hasArg(OPT_debug))
306 Config->Debug = true;
307
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000308 // Handle /noentry
309 if (Args.hasArg(OPT_noentry)) {
310 if (!Args.hasArg(OPT_dll)) {
311 llvm::errs() << "/noentry must be specified with /dll\n";
312 return false;
313 }
314 Config->NoEntry = true;
315 }
316
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000317 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000318 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000319 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000320 Config->ManifestID = 2;
321 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000322
Rui Ueyama588e8322015-06-15 01:23:58 +0000323 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000324 if (Args.hasArg(OPT_fixed)) {
325 if (Args.hasArg(OPT_dynamicbase)) {
Rui Ueyama6592ff82015-06-16 23:13:00 +0000326 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
327 return false;
328 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000329 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000330 Config->DynamicBase = false;
331 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000332
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000333 // Handle /machine
Rui Ueyamae16a75d52015-07-08 18:14:51 +0000334 if (auto *Arg = Args.getLastArg(OPT_machine)) {
335 ErrorOr<MachineTypes> MTOrErr = getMachineType(Arg->getValue());
336 if (MTOrErr.getError())
337 return false;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000338 Config->Machine = MTOrErr.get();
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000339 }
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000340
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000341 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000342 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000343 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
344
345 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000346 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000347 Config->NoDefaultLibAll = true;
348
Rui Ueyama804a8b62015-05-29 16:18:15 +0000349 // Handle /base
David Blaikie6521ed92015-06-22 22:06:52 +0000350 if (auto *Arg = Args.getLastArg(OPT_base)) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000351 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000352 llvm::errs() << "/base: " << EC.message() << "\n";
353 return false;
354 }
355 }
356
357 // Handle /stack
David Blaikie6521ed92015-06-22 22:06:52 +0000358 if (auto *Arg = Args.getLastArg(OPT_stack)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000359 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
360 &Config->StackCommit)) {
361 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000362 return false;
363 }
364 }
365
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000366 // Handle /heap
David Blaikie6521ed92015-06-22 22:06:52 +0000367 if (auto *Arg = Args.getLastArg(OPT_heap)) {
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000368 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
369 &Config->HeapCommit)) {
370 llvm::errs() << "/heap: " << EC.message() << "\n";
371 return false;
372 }
373 }
374
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000375 // Handle /version
David Blaikie6521ed92015-06-22 22:06:52 +0000376 if (auto *Arg = Args.getLastArg(OPT_version)) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000377 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
378 &Config->MinorImageVersion)) {
379 llvm::errs() << "/version: " << EC.message() << "\n";
380 return false;
381 }
382 }
383
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000384 // Handle /subsystem
David Blaikie6521ed92015-06-22 22:06:52 +0000385 if (auto *Arg = Args.getLastArg(OPT_subsystem)) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000386 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
387 &Config->MajorOSVersion,
388 &Config->MinorOSVersion)) {
389 llvm::errs() << "/subsystem: " << EC.message() << "\n";
390 return false;
391 }
392 }
393
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000394 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000395 for (auto *Arg : Args.filtered(OPT_alternatename))
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000396 if (parseAlternateName(Arg->getValue()))
397 return false;
398
Rui Ueyama08d5e182015-06-18 23:20:11 +0000399 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000400 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000401 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000402
Rui Ueyamab95188c2015-06-18 20:27:09 +0000403 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000404 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000405 Config->Implib = Arg->getValue();
406
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000407 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000408 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000409 std::string S = StringRef(Arg->getValue()).lower();
410 if (S == "noref") {
411 Config->DoGC = false;
412 continue;
413 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000414 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000415 Config->ICF = true;
416 continue;
417 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000418 if (S != "ref" && S != "icf" && S != "noicf" &&
419 S != "lbr" && S != "nolbr" &&
420 !StringRef(S).startswith("icf=")) {
421 llvm::errs() << "/opt: unknown option: " << S << "\n";
422 return false;
423 }
424 }
425
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000426 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000427 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rui Ueyama75b098b2015-06-18 21:23:34 +0000428 if (checkFailIfMismatch(Arg->getValue()))
429 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000430
Rui Ueyama6600eb12015-07-04 23:37:32 +0000431 // Handle /merge
432 for (auto *Arg : Args.filtered(OPT_merge))
433 if (parseMerge(Arg->getValue()))
434 return false;
435
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000436 // Handle /manifest
David Blaikie6521ed92015-06-22 22:06:52 +0000437 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000438 if (auto EC = parseManifest(Arg->getValue())) {
439 llvm::errs() << "/manifest: " << EC.message() << "\n";
440 return false;
441 }
442 }
443
444 // Handle /manifestuac
David Blaikie6521ed92015-06-22 22:06:52 +0000445 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000446 if (auto EC = parseManifestUAC(Arg->getValue())) {
447 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
448 return false;
449 }
450 }
451
452 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000453 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000454 Config->ManifestDependency = Arg->getValue();
455
456 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000457 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000458 Config->ManifestFile = Arg->getValue();
459
Rui Ueyama6592ff82015-06-16 23:13:00 +0000460 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000461 if (Args.hasArg(OPT_allowbind_no))
462 Config->AllowBind = false;
463 if (Args.hasArg(OPT_allowisolation_no))
464 Config->AllowIsolation = false;
465 if (Args.hasArg(OPT_dynamicbase_no))
466 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000467 if (Args.hasArg(OPT_nxcompat_no))
468 Config->NxCompat = false;
469 if (Args.hasArg(OPT_tsaware_no))
470 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000471
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000472 // Create a list of input files. Files can be given as arguments
473 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000474 std::vector<StringRef> Paths;
475 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000476 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000477 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000478 Paths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000479 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000480 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000481 Paths.push_back(*Path);
482 for (StringRef Path : Paths) {
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000483 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
484 if (auto EC = MBOrErr.getError()) {
485 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
486 return false;
487 }
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000488 MBs.push_back(MBOrErr.get());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000489 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000490
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000491 // Windows specific -- Create a resource file containing a manifest file.
492 if (Config->Manifest == Configuration::Embed) {
493 auto MBOrErr = createManifestRes();
494 if (MBOrErr.getError())
495 return false;
496 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000497 MBs.push_back(MB->getMemBufferRef());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000498 OwningMBs.push_back(std::move(MB)); // take ownership
499 }
500
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000501 // Windows specific -- Input files can be Windows resource files (.res files).
502 // We invoke cvtres.exe to convert resource files to a regular COFF file
503 // then link the result file normally.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000504 std::vector<MemoryBufferRef> Resources;
Rui Ueyama77731b42015-06-26 23:59:13 +0000505 auto NotResource = [](MemoryBufferRef MB) {
506 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000507 };
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000508 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
509 if (It != MBs.end()) {
510 Resources.insert(Resources.end(), It, MBs.end());
511 MBs.erase(It, MBs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000512 }
513
Rui Ueyama85225b02015-07-02 03:15:15 +0000514 // Read all input files given via the command line. Note that step()
515 // doesn't read files that are specified by directive sections.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000516 for (MemoryBufferRef MB : MBs)
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000517 Symtab.addFile(createFile(MB));
Rui Ueyama85225b02015-07-02 03:15:15 +0000518 if (auto EC = Symtab.step()) {
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000519 llvm::errs() << EC.message() << "\n";
520 return false;
Rui Ueyama411c63602015-05-28 19:09:30 +0000521 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000522
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000523 // Determine machine type and check if all object files are
524 // for the same CPU type. Note that this needs to be done before
525 // any call to mangle().
526 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
527 MachineTypes MT = File->getMachineType();
528 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
529 continue;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000530 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
531 Config->Machine = MT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000532 continue;
533 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000534 if (Config->Machine != MT) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000535 llvm::errs() << File->getShortName() << ": machine type "
Rui Ueyama5e706b32015-07-25 21:54:50 +0000536 << machineToStr(MT) << " conflicts with "
537 << machineToStr(Config->Machine) << "\n";
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000538 return false;
539 }
540 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000541 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000542 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000543 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000544 }
545
546 // Windows specific -- Convert Windows resource files to a COFF file.
547 if (!Resources.empty()) {
548 auto MBOrErr = convertResToCOFF(Resources);
549 if (MBOrErr.getError())
550 return false;
551 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
552 Symtab.addFile(createFile(MB->getMemBufferRef()));
553 OwningMBs.push_back(std::move(MB)); // take ownership
554 }
555
Rui Ueyama4d545342015-07-28 03:12:00 +0000556 // Handle /largeaddressaware
557 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
558 Config->LargeAddressAware = true;
559
Rui Ueyamad68e2112015-07-28 03:15:57 +0000560 // Handle /highentropyva
561 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
562 Config->HighEntropyVA = true;
563
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000564 // Handle /entry and /dll
565 if (auto *Arg = Args.getLastArg(OPT_entry)) {
566 Config->Entry = addUndefined(mangle(Arg->getValue()));
567 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000568 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
569 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000570 Config->Entry = addUndefined(S);
571 } else if (!Config->NoEntry) {
572 // Windows specific -- If entry point name is not given, we need to
573 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000574 StringRef S = findDefaultEntry();
575 if (S.empty()) {
576 llvm::errs() << "entry point must be defined\n";
577 return false;
578 }
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000579 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000580 if (Config->Verbose)
581 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000582 }
583
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000584 // Handle /export
585 for (auto *Arg : Args.filtered(OPT_export)) {
586 ErrorOr<Export> E = parseExport(Arg->getValue());
587 if (E.getError())
588 return false;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000589 if (Config->Machine == I386 && !E->Name.startswith("_@?"))
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000590 E->Name = mangle(E->Name);
591 Config->Exports.push_back(E.get());
592 }
593
594 // Handle /def
595 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
596 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
597 if (auto EC = MBOrErr.getError()) {
598 llvm::errs() << "/def: " << EC.message() << "\n";
599 return false;
600 }
601 // parseModuleDefs mutates Config object.
602 if (parseModuleDefs(MBOrErr.get(), &Alloc))
603 return false;
604 }
605
Rui Ueyama6d249082015-07-13 22:31:45 +0000606 // Handle /delayload
607 for (auto *Arg : Args.filtered(OPT_delayload)) {
608 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000609 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000610 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000611 } else {
612 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000613 }
614 }
615
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000616 // Set default image base if /base is not given.
617 if (Config->ImageBase == uint64_t(-1))
618 Config->ImageBase = getDefaultImageBase();
619
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000620 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000621 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000622 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
623 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
624 }
Rui Ueyama29f74c32015-07-29 16:30:31 +0000625 Config->LoadConfigUsed = mangle("_load_config_used");
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000626
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000627 // Read as much files as we can from directives sections.
Rui Ueyama85225b02015-07-02 03:15:15 +0000628 if (auto EC = Symtab.run()) {
629 llvm::errs() << EC.message() << "\n";
630 return false;
631 }
632
633 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000634 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
635 // A new file may contain a directive section to add new command line options.
636 // That's why we have to repeat until converge.)
637 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000638 // Windows specific -- if entry point is not found,
639 // search for its mangled names.
640 if (Config->Entry)
641 Symtab.mangleMaybe(Config->Entry);
642
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000643 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000644 for (Export &E : Config->Exports) {
645 E.Sym = addUndefined(E.Name);
646 Symtab.mangleMaybe(E.Sym);
647 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000648
649 // Add weak aliases. Weak aliases is a mechanism to give remaining
650 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000651 for (auto Pair : Config->AlternateNames) {
652 StringRef From = Pair.first;
653 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000654 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000655 if (!Sym)
656 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000657 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000658 if (!U->WeakAlias)
659 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000660 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000661
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000662 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyama29f74c32015-07-29 16:30:31 +0000663 if (Symbol *Sym = Symtab.find(Config->LoadConfigUsed))
664 if (isa<Lazy>(Sym->Body))
665 Symtab.addUndefined(Config->LoadConfigUsed);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000666
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000667 if (Symtab.queueEmpty())
668 break;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000669 if (auto EC = Symtab.run()) {
670 llvm::errs() << EC.message() << "\n";
671 return false;
672 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000673 }
674
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000675 // Do LTO by compiling bitcode input files to a native COFF file
676 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000677 if (auto EC = Symtab.addCombinedLTOObject()) {
678 llvm::errs() << EC.message() << "\n";
679 return false;
680 }
681
Peter Collingbourne2612a322015-07-04 05:28:41 +0000682 // Make sure we have resolved all symbols.
683 if (Symtab.reportRemainingUndefines(/*Resolve=*/true))
684 return false;
685
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000686 // Windows specific -- if no /subsystem is given, we need to infer
687 // that from entry point name.
688 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000689 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000690 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
691 llvm::errs() << "subsystem must be defined\n";
692 return false;
693 }
694 }
695
Rui Ueyama151d8622015-06-17 20:40:43 +0000696 // Windows specific -- when we are creating a .dll file, we also
697 // need to create a .lib file.
Rui Ueyama8765fba2015-07-15 22:21:08 +0000698 if (!Config->Exports.empty()) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000699 if (fixupExports())
700 return false;
Rui Ueyama8765fba2015-07-15 22:21:08 +0000701 writeImportLibrary();
702 assignExportOrdinals();
703 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000704
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000705 // Windows specific -- Create a side-by-side manifest file.
706 if (Config->Manifest == Configuration::SideBySide)
707 if (createSideBySideManifest())
708 return false;
709
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000710 // Create a dummy PDB file to satisfy build sytem rules.
711 if (auto *Arg = Args.getLastArg(OPT_pdb))
712 touchFile(Arg->getValue());
713
Rui Ueyama411c63602015-05-28 19:09:30 +0000714 // Write the result.
715 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000716 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000717 llvm::errs() << EC.message() << "\n";
718 return false;
719 }
Peter Collingbournebe549552015-06-26 18:58:24 +0000720
Rui Ueyama016414f2015-06-28 20:07:08 +0000721 // Create a symbol map file containing symbol VAs and their names
722 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000723 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
724 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000725 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Peter Collingbournebe549552015-06-26 18:58:24 +0000726 if (EC) {
727 llvm::errs() << EC.message() << "\n";
728 return false;
729 }
730 Symtab.printMap(Out);
731 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000732 // Call exit to avoid calling destructors.
733 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000734}
735
Rui Ueyama411c63602015-05-28 19:09:30 +0000736} // namespace coff
737} // namespace lld