blob: 96139aa03a8bc4f7c42bd1129bf638de2e0abc6e [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"
Rui Ueyama685c41c2015-08-05 23:43:53 +000015#include "Symbols.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000017#include "llvm/ADT/Optional.h"
18#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000019#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000020#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000021#include "llvm/Option/Arg.h"
22#include "llvm/Option/ArgList.h"
23#include "llvm/Option/Option.h"
24#include "llvm/Support/CommandLine.h"
25#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000026#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000027#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000028#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000029#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000030#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000031#include <memory>
32
33using namespace llvm;
Rui Ueyama84936e02015-07-07 23:39:18 +000034using namespace llvm::COFF;
Rui Ueyama54b71da2015-05-31 19:17:12 +000035using llvm::sys::Process;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000036using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000037using llvm::sys::fs::file_magic;
38using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000039
Rui Ueyama3500f662015-05-28 20:30:06 +000040namespace lld {
41namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000042
Rui Ueyama3500f662015-05-28 20:30:06 +000043Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000044LinkerDriver *Driver;
45
Rafael Espindolab835ae82015-08-06 14:58:50 +000046void link(llvm::ArrayRef<const char *> Args) {
Rui Ueyama570752c2015-08-18 09:13:25 +000047 Configuration C;
48 LinkerDriver D;
49 Config = &C;
50 Driver = &D;
David Blaikieb2b1c7c2015-06-21 06:32:10 +000051 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000052}
Rui Ueyama411c63602015-05-28 19:09:30 +000053
Rui Ueyamaad660982015-06-07 00:20:32 +000054// Drop directory components and replace extension with ".exe".
55static std::string getOutputPath(StringRef Path) {
56 auto P = Path.find_last_of("\\/");
57 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
58 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000059}
60
Rui Ueyamad7c2f582015-05-31 21:04:56 +000061// Opens a file. Path has to be resolved already.
62// Newly created memory buffers are owned by this driver.
Rafael Espindolab835ae82015-08-06 14:58:50 +000063MemoryBufferRef LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000064 auto MBOrErr = MemoryBuffer::getFile(Path);
Rafael Espindolab835ae82015-08-06 14:58:50 +000065 error(MBOrErr, Twine("Could not open ") + Path);
66 std::unique_ptr<MemoryBuffer> &MB = *MBOrErr;
Rui Ueyamad7c2f582015-05-31 21:04:56 +000067 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 Ueyamaf10a3202015-08-31 08:43:21 +000084static bool isDecorated(StringRef Sym) {
85 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
86}
87
Rui Ueyama411c63602015-05-28 19:09:30 +000088// Parses .drectve section contents and returns a list of files
89// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +000090void LinkerDriver::parseDirectives(StringRef S) {
91 llvm::opt::InputArgList Args = Parser.parse(S);
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:
Rafael Espindolab835ae82015-08-06 14:58:50 +000096 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +000097 break;
98 case OPT_defaultlib:
99 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000100 MemoryBufferRef MB = openFile(*Path);
101 Symtab.addFile(createFile(MB));
Rui Ueyama562daa82015-06-18 21:50:38 +0000102 }
103 break;
104 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000105 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000106 E.Directives = true;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000107 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000108 break;
109 }
110 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000111 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000112 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000113 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000114 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000115 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000116 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000117 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000118 break;
119 case OPT_nodefaultlib:
120 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
121 break;
Rui Ueyama3c4737d2015-08-11 16:46:08 +0000122 case OPT_editandcontinue:
Rui Ueyama432383172015-07-29 21:01:15 +0000123 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000124 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000125 default:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000126 error(Twine(Arg->getSpelling()) + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000127 }
128 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000129}
130
Rui Ueyama54b71da2015-05-31 19:17:12 +0000131// Find file from search paths. You can omit ".obj", this function takes
132// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000133StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000134 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
135 if (hasPathSep)
136 return Filename;
137 bool hasExt = (Filename.find('.') != StringRef::npos);
138 for (StringRef Dir : SearchPaths) {
139 SmallString<128> Path = Dir;
140 llvm::sys::path::append(Path, Filename);
141 if (llvm::sys::fs::exists(Path.str()))
142 return Alloc.save(Path.str());
143 if (!hasExt) {
144 Path.append(".obj");
145 if (llvm::sys::fs::exists(Path.str()))
146 return Alloc.save(Path.str());
147 }
148 }
149 return Filename;
150}
151
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000152// Resolves a file path. This never returns the same path
153// (in that case, it returns None).
154Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
155 StringRef Path = doFindFile(Filename);
156 bool Seen = !VisitedFiles.insert(Path.lower()).second;
157 if (Seen)
158 return None;
159 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000160}
161
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000162// Find library file from search path.
163StringRef LinkerDriver::doFindLib(StringRef Filename) {
164 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000165 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000166 if (!hasExt)
167 Filename = Alloc.save(Filename + ".lib");
168 return doFindFile(Filename);
169}
170
171// Resolves a library path. /nodefaultlib options are taken into
172// consideration. This never returns the same path (in that case,
173// it returns None).
174Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
175 if (Config->NoDefaultLibAll)
176 return None;
177 StringRef Path = doFindLib(Filename);
178 if (Config->NoDefaultLibs.count(Path))
179 return None;
180 bool Seen = !VisitedFiles.insert(Path.lower()).second;
181 if (Seen)
182 return None;
183 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000184}
185
186// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000187void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000188 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
189 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000190 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000191 StringRef Env = Alloc.save(*EnvOpt);
192 while (!Env.empty()) {
193 StringRef Path;
194 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000195 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000196 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000197}
198
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000199Undefined *LinkerDriver::addUndefined(StringRef Name) {
200 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000201 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000202 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000203}
204
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000205// Symbol names are mangled by appending "_" prefix on x86.
206StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000207 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
208 if (Config->Machine == I386)
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000209 return Alloc.save("_" + Sym);
210 return Sym;
211}
212
Rui Ueyama45044f42015-06-29 01:03:53 +0000213// Windows specific -- find default entry point name.
214StringRef LinkerDriver::findDefaultEntry() {
215 // User-defined main functions and their corresponding entry points.
216 static const char *Entries[][2] = {
217 {"main", "mainCRTStartup"},
218 {"wmain", "wmainCRTStartup"},
219 {"WinMain", "WinMainCRTStartup"},
220 {"wWinMain", "wWinMainCRTStartup"},
221 };
222 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000223 StringRef Entry = Symtab.findMangle(mangle(E[0]));
224 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000225 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000226 }
227 return "";
228}
229
230WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000231 if (Config->DLL)
232 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000233 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000234 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000235 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000236 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
237 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000238}
239
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000240static uint64_t getDefaultImageBase() {
241 if (Config->is64())
242 return Config->DLL ? 0x180000000 : 0x140000000;
243 return Config->DLL ? 0x10000000 : 0x400000;
244}
245
Rafael Espindolab835ae82015-08-06 14:58:50 +0000246void LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000247 // If the first command line argument is "/lib", link.exe acts like lib.exe.
248 // We call our own implementation of lib.exe that understands bitcode files.
249 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
250 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
251 error("lib failed");
252 return;
253 }
254
Peter Collingbourne60c16162015-06-01 20:10:10 +0000255 // Needed for LTO.
256 llvm::InitializeAllTargetInfos();
257 llvm::InitializeAllTargets();
258 llvm::InitializeAllTargetMCs();
259 llvm::InitializeAllAsmParsers();
260 llvm::InitializeAllAsmPrinters();
261 llvm::InitializeAllDisassemblers();
262
Rui Ueyama411c63602015-05-28 19:09:30 +0000263 // Parse command line options.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000264 llvm::opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
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]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000269 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000270 }
271
Rafael Espindolab835ae82015-08-06 14:58:50 +0000272 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
273 error("no input files.");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000274
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000275 // Construct search path list.
276 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000277 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000278 SearchPaths.push_back(Arg->getValue());
279 addLibSearchPaths();
280
Rui Ueyamaad660982015-06-07 00:20:32 +0000281 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000282 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000283 Config->OutputFile = Arg->getValue();
284
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000285 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000286 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000287 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000288
Rui Ueyama95925fd2015-06-28 19:35:15 +0000289 // Handle /force or /force:unresolved
290 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
291 Config->Force = true;
292
Rui Ueyama6600eb12015-07-04 23:37:32 +0000293 // Handle /debug
294 if (Args.hasArg(OPT_debug))
295 Config->Debug = true;
296
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000297 // Handle /noentry
298 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000299 if (!Args.hasArg(OPT_dll))
300 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000301 Config->NoEntry = true;
302 }
303
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000304 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000305 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000306 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000307 Config->ManifestID = 2;
308 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000309
Rui Ueyama588e8322015-06-15 01:23:58 +0000310 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000311 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000312 if (Args.hasArg(OPT_dynamicbase))
313 error("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000314 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000315 Config->DynamicBase = false;
316 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000317
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000318 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000319 if (auto *Arg = Args.getLastArg(OPT_machine))
320 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000321
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000322 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000323 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000324 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
325
326 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000327 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000328 Config->NoDefaultLibAll = true;
329
Rui Ueyama804a8b62015-05-29 16:18:15 +0000330 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000331 if (auto *Arg = Args.getLastArg(OPT_base))
332 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000333
334 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000335 if (auto *Arg = Args.getLastArg(OPT_stack))
336 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000337
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000338 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000339 if (auto *Arg = Args.getLastArg(OPT_heap))
340 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000341
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000342 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000343 if (auto *Arg = Args.getLastArg(OPT_version))
344 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
345 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000346
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000347 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000348 if (auto *Arg = Args.getLastArg(OPT_subsystem))
349 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
350 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000351
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000352 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000353 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000354 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000355
Rui Ueyama08d5e182015-06-18 23:20:11 +0000356 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000357 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000358 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000359
Rui Ueyamab95188c2015-06-18 20:27:09 +0000360 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000361 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000362 Config->Implib = Arg->getValue();
363
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000364 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000365 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000366 std::string S = StringRef(Arg->getValue()).lower();
367 if (S == "noref") {
368 Config->DoGC = false;
369 continue;
370 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000371 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000372 Config->ICF = true;
373 continue;
374 }
Peter Collingbourne526ff152015-08-14 04:47:07 +0000375 if (StringRef(S).startswith("lldlto=")) {
376 StringRef OptLevel = StringRef(S).substr(7);
377 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000378 Config->LTOOptLevel > 3)
Peter Collingbourne526ff152015-08-14 04:47:07 +0000379 error("/opt:lldlto: invalid optimization level: " + OptLevel);
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000380 continue;
381 }
382 if (StringRef(S).startswith("lldltojobs=")) {
383 StringRef Jobs = StringRef(S).substr(11);
384 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
385 error("/opt:lldltojobs: invalid job count: " + Jobs);
Peter Collingbourne526ff152015-08-14 04:47:07 +0000386 continue;
387 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000388 if (S != "ref" && S != "icf" && S != "noicf" &&
389 S != "lbr" && S != "nolbr" &&
390 !StringRef(S).startswith("icf=")) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000391 error(Twine("/opt: unknown option: ") + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000392 }
393 }
394
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000395 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000396 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000397 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000398
Rui Ueyama6600eb12015-07-04 23:37:32 +0000399 // Handle /merge
400 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000401 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000402
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000403 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000404 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
405 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000406
407 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000408 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
409 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000410
411 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000412 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000413 Config->ManifestDependency = Arg->getValue();
414
415 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000416 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000417 Config->ManifestFile = Arg->getValue();
418
Rui Ueyama6592ff82015-06-16 23:13:00 +0000419 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000420 if (Args.hasArg(OPT_allowbind_no))
421 Config->AllowBind = false;
422 if (Args.hasArg(OPT_allowisolation_no))
423 Config->AllowIsolation = false;
424 if (Args.hasArg(OPT_dynamicbase_no))
425 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000426 if (Args.hasArg(OPT_nxcompat_no))
427 Config->NxCompat = false;
428 if (Args.hasArg(OPT_tsaware_no))
429 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000430
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000431 // Create a list of input files. Files can be given as arguments
432 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000433 std::vector<StringRef> Paths;
434 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000435 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000436 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000437 Paths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000438 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000439 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000440 Paths.push_back(*Path);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000441 for (StringRef Path : Paths)
442 MBs.push_back(openFile(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000443
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000444 // Windows specific -- Create a resource file containing a manifest file.
445 if (Config->Manifest == Configuration::Embed) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000446 std::unique_ptr<MemoryBuffer> MB = createManifestRes();
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000447 MBs.push_back(MB->getMemBufferRef());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000448 OwningMBs.push_back(std::move(MB)); // take ownership
449 }
450
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000451 // Windows specific -- Input files can be Windows resource files (.res files).
452 // We invoke cvtres.exe to convert resource files to a regular COFF file
453 // then link the result file normally.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000454 std::vector<MemoryBufferRef> Resources;
Rui Ueyama77731b42015-06-26 23:59:13 +0000455 auto NotResource = [](MemoryBufferRef MB) {
456 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000457 };
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000458 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
459 if (It != MBs.end()) {
460 Resources.insert(Resources.end(), It, MBs.end());
461 MBs.erase(It, MBs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000462 }
463
Rui Ueyama85225b02015-07-02 03:15:15 +0000464 // Read all input files given via the command line. Note that step()
465 // doesn't read files that are specified by directive sections.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000466 for (MemoryBufferRef MB : MBs)
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000467 Symtab.addFile(createFile(MB));
Rafael Espindolab835ae82015-08-06 14:58:50 +0000468 Symtab.step();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000469
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000470 // Determine machine type and check if all object files are
471 // for the same CPU type. Note that this needs to be done before
472 // any call to mangle().
473 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
474 MachineTypes MT = File->getMachineType();
475 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
476 continue;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000477 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
478 Config->Machine = MT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000479 continue;
480 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000481 if (Config->Machine != MT)
482 error(Twine(File->getShortName()) + ": machine type " + machineToStr(MT) +
483 " conflicts with " + machineToStr(Config->Machine));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000484 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000485 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000486 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000487 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000488 }
489
490 // Windows specific -- Convert Windows resource files to a COFF file.
491 if (!Resources.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000492 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources);
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000493 Symtab.addFile(createFile(MB->getMemBufferRef()));
494 OwningMBs.push_back(std::move(MB)); // take ownership
495 }
496
Rui Ueyama4d545342015-07-28 03:12:00 +0000497 // Handle /largeaddressaware
498 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
499 Config->LargeAddressAware = true;
500
Rui Ueyamad68e2112015-07-28 03:15:57 +0000501 // Handle /highentropyva
502 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
503 Config->HighEntropyVA = true;
504
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000505 // Handle /entry and /dll
506 if (auto *Arg = Args.getLastArg(OPT_entry)) {
507 Config->Entry = addUndefined(mangle(Arg->getValue()));
508 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000509 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
510 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000511 Config->Entry = addUndefined(S);
512 } else if (!Config->NoEntry) {
513 // Windows specific -- If entry point name is not given, we need to
514 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000515 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000516 if (S.empty())
517 error("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000518 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000519 if (Config->Verbose)
520 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000521 }
522
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000523 // Handle /export
524 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000525 Export E = parseExport(Arg->getValue());
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000526 if (Config->Machine == I386) {
527 if (!isDecorated(E.Name))
528 E.Name = Alloc.save("_" + E.Name);
529 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
530 E.ExtName = Alloc.save("_" + E.ExtName);
531 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000532 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000533 }
534
535 // Handle /def
536 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000537 MemoryBufferRef MB = openFile(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000538 // parseModuleDefs mutates Config object.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000539 parseModuleDefs(MB, &Alloc);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000540 }
541
Rui Ueyama6d249082015-07-13 22:31:45 +0000542 // Handle /delayload
543 for (auto *Arg : Args.filtered(OPT_delayload)) {
544 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000545 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000546 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000547 } else {
548 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000549 }
550 }
551
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000552 // Set default image base if /base is not given.
553 if (Config->ImageBase == uint64_t(-1))
554 Config->ImageBase = getDefaultImageBase();
555
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000556 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000557 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000558 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
559 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
560 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000561
Rui Ueyama107db552015-08-09 21:01:06 +0000562 // We do not support /guard:cf (control flow protection) yet.
563 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
564 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
565 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
566 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
567
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000568 // Read as much files as we can from directives sections.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000569 Symtab.run();
Rui Ueyama85225b02015-07-02 03:15:15 +0000570
571 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000572 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
573 // A new file may contain a directive section to add new command line options.
574 // That's why we have to repeat until converge.)
575 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000576 // Windows specific -- if entry point is not found,
577 // search for its mangled names.
578 if (Config->Entry)
579 Symtab.mangleMaybe(Config->Entry);
580
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000581 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000582 for (Export &E : Config->Exports) {
583 E.Sym = addUndefined(E.Name);
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000584 if (!E.Directives)
585 Symtab.mangleMaybe(E.Sym);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000586 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000587
588 // Add weak aliases. Weak aliases is a mechanism to give remaining
589 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000590 for (auto Pair : Config->AlternateNames) {
591 StringRef From = Pair.first;
592 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000593 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000594 if (!Sym)
595 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000596 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000597 if (!U->WeakAlias)
598 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000599 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000600
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000601 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyama8ebdc8c2015-08-07 22:43:53 +0000602 if (Symtab.findUnderscore("_load_config_used"))
603 addUndefined(mangle("_load_config_used"));
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000604
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000605 if (Symtab.queueEmpty())
606 break;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000607 Symtab.run();
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000608 }
609
Peter Collingbournedf5783b2015-08-28 22:16:09 +0000610 // Do LTO by compiling bitcode input files to a set of native COFF files then
611 // link those files.
612 Symtab.addCombinedLTOObjects();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000613
Peter Collingbourne2612a322015-07-04 05:28:41 +0000614 // Make sure we have resolved all symbols.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000615 Symtab.reportRemainingUndefines(/*Resolve=*/true);
Peter Collingbourne2612a322015-07-04 05:28:41 +0000616
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000617 // Windows specific -- if no /subsystem is given, we need to infer
618 // that from entry point name.
619 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000620 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000621 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
622 error("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000623 }
624
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000625 // Handle /safeseh.
626 if (Args.hasArg(OPT_safeseh)) {
627 for (ObjectFile *File : Symtab.ObjectFiles) {
628 if (File->SEHCompat)
629 continue;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000630 error(Twine("/safeseh: ") + File->getName() +
631 " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000632 }
633 }
634
Rui Ueyama151d8622015-06-17 20:40:43 +0000635 // Windows specific -- when we are creating a .dll file, we also
636 // need to create a .lib file.
Rui Ueyamaf10a3202015-08-31 08:43:21 +0000637 if (Config->DLL) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000638 fixupExports();
639 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000640 assignExportOrdinals();
641 }
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)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000645 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000646
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000647 // Create a dummy PDB file to satisfy build sytem rules.
648 if (auto *Arg = Args.getLastArg(OPT_pdb))
649 touchFile(Arg->getValue());
650
Rui Ueyama411c63602015-05-28 19:09:30 +0000651 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000652 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000653
Rui Ueyama016414f2015-06-28 20:07:08 +0000654 // Create a symbol map file containing symbol VAs and their names
655 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000656 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
657 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000658 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000659 error(EC, "Could not create the symbol map");
Peter Collingbournebe549552015-06-26 18:58:24 +0000660 Symtab.printMap(Out);
661 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000662 // Call exit to avoid calling destructors.
663 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000664}
665
Rui Ueyama411c63602015-05-28 19:09:30 +0000666} // namespace coff
667} // namespace lld