blob: d363230f1ec053e64d2e35f4c675360c174796d1 [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 Ueyamaa9cbbf82015-05-31 19:17:09 +000047 auto C = make_unique<Configuration>();
48 Config = C.get();
49 auto D = make_unique<LinkerDriver>();
50 Driver = D.get();
David Blaikieb2b1c7c2015-06-21 06:32:10 +000051 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000052}
Rui Ueyama411c63602015-05-28 19:09:30 +000053
Rui Ueyamaad660982015-06-07 00:20:32 +000054// Drop directory components and replace extension with ".exe".
55static std::string getOutputPath(StringRef Path) {
56 auto P = Path.find_last_of("\\/");
57 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
58 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000059}
60
Rui Ueyamad7c2f582015-05-31 21:04:56 +000061// Opens a file. Path has to be resolved already.
62// Newly created memory buffers are owned by this driver.
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 Ueyama411c63602015-05-28 19:09:30 +000084// Parses .drectve section contents and returns a list of files
85// specified by /defaultlib.
Rafael Espindolab835ae82015-08-06 14:58:50 +000086void LinkerDriver::parseDirectives(StringRef S) {
87 llvm::opt::InputArgList Args = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000088
David Blaikie6521ed92015-06-22 22:06:52 +000089 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +000090 switch (Arg->getOption().getID()) {
91 case OPT_alternatename:
Rafael Espindolab835ae82015-08-06 14:58:50 +000092 parseAlternateName(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +000093 break;
94 case OPT_defaultlib:
95 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
Rafael Espindolab835ae82015-08-06 14:58:50 +000096 MemoryBufferRef MB = openFile(*Path);
97 Symtab.addFile(createFile(MB));
Rui Ueyama562daa82015-06-18 21:50:38 +000098 }
99 break;
100 case OPT_export: {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000101 Export E = parseExport(Arg->getValue());
102 if (Config->Machine == I386 && E.ExtName.startswith("_"))
103 E.ExtName = E.ExtName.substr(1);
104 Config->Exports.push_back(E);
Rui Ueyama562daa82015-06-18 21:50:38 +0000105 break;
106 }
107 case OPT_failifmismatch:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000108 checkFailIfMismatch(Arg->getValue());
Rui Ueyama562daa82015-06-18 21:50:38 +0000109 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000110 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000111 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000112 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000113 case OPT_merge:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000114 parseMerge(Arg->getValue());
Rui Ueyamace86c992015-06-18 23:22:39 +0000115 break;
116 case OPT_nodefaultlib:
117 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
118 break;
Rui Ueyama432383172015-07-29 21:01:15 +0000119 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000120 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000121 default:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000122 error(Twine(Arg->getSpelling()) + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000123 }
124 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000125}
126
Rui Ueyama54b71da2015-05-31 19:17:12 +0000127// Find file from search paths. You can omit ".obj", this function takes
128// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000129StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000130 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
131 if (hasPathSep)
132 return Filename;
133 bool hasExt = (Filename.find('.') != StringRef::npos);
134 for (StringRef Dir : SearchPaths) {
135 SmallString<128> Path = Dir;
136 llvm::sys::path::append(Path, Filename);
137 if (llvm::sys::fs::exists(Path.str()))
138 return Alloc.save(Path.str());
139 if (!hasExt) {
140 Path.append(".obj");
141 if (llvm::sys::fs::exists(Path.str()))
142 return Alloc.save(Path.str());
143 }
144 }
145 return Filename;
146}
147
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000148// Resolves a file path. This never returns the same path
149// (in that case, it returns None).
150Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
151 StringRef Path = doFindFile(Filename);
152 bool Seen = !VisitedFiles.insert(Path.lower()).second;
153 if (Seen)
154 return None;
155 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000156}
157
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000158// Find library file from search path.
159StringRef LinkerDriver::doFindLib(StringRef Filename) {
160 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000161 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000162 if (!hasExt)
163 Filename = Alloc.save(Filename + ".lib");
164 return doFindFile(Filename);
165}
166
167// Resolves a library path. /nodefaultlib options are taken into
168// consideration. This never returns the same path (in that case,
169// it returns None).
170Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
171 if (Config->NoDefaultLibAll)
172 return None;
173 StringRef Path = doFindLib(Filename);
174 if (Config->NoDefaultLibs.count(Path))
175 return None;
176 bool Seen = !VisitedFiles.insert(Path.lower()).second;
177 if (Seen)
178 return None;
179 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000180}
181
182// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000183void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000184 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
185 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000186 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000187 StringRef Env = Alloc.save(*EnvOpt);
188 while (!Env.empty()) {
189 StringRef Path;
190 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000191 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000192 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000193}
194
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000195Undefined *LinkerDriver::addUndefined(StringRef Name) {
196 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000197 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000198 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000199}
200
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000201// Symbol names are mangled by appending "_" prefix on x86.
202StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000203 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
204 if (Config->Machine == I386)
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000205 return Alloc.save("_" + Sym);
206 return Sym;
207}
208
Rui Ueyama45044f42015-06-29 01:03:53 +0000209// Windows specific -- find default entry point name.
210StringRef LinkerDriver::findDefaultEntry() {
211 // User-defined main functions and their corresponding entry points.
212 static const char *Entries[][2] = {
213 {"main", "mainCRTStartup"},
214 {"wmain", "wmainCRTStartup"},
215 {"WinMain", "WinMainCRTStartup"},
216 {"wWinMain", "wWinMainCRTStartup"},
217 };
218 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000219 StringRef Entry = Symtab.findMangle(mangle(E[0]));
220 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000221 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000222 }
223 return "";
224}
225
226WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000227 if (Config->DLL)
228 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000229 if (Symtab.find(mangle("main")) || Symtab.find(mangle("wmain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000230 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000231 if (Symtab.find(mangle("WinMain")) || Symtab.find(mangle("wWinMain")))
Rui Ueyama45044f42015-06-29 01:03:53 +0000232 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
233 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000234}
235
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000236static uint64_t getDefaultImageBase() {
237 if (Config->is64())
238 return Config->DLL ? 0x180000000 : 0x140000000;
239 return Config->DLL ? 0x10000000 : 0x400000;
240}
241
Rafael Espindolab835ae82015-08-06 14:58:50 +0000242void LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000243 // Needed for LTO.
244 llvm::InitializeAllTargetInfos();
245 llvm::InitializeAllTargets();
246 llvm::InitializeAllTargetMCs();
247 llvm::InitializeAllAsmParsers();
248 llvm::InitializeAllAsmPrinters();
249 llvm::InitializeAllDisassemblers();
250
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000251 // If the first command line argument is "/lib", link.exe acts like lib.exe.
252 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000253 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000254 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
255 error("lib failed");
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000256
Rui Ueyama411c63602015-05-28 19:09:30 +0000257 // Parse command line options.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000258 llvm::opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000259
Rui Ueyama5c726432015-05-29 16:11:52 +0000260 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000261 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000262 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000263 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000264 }
265
Rafael Espindolab835ae82015-08-06 14:58:50 +0000266 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
267 error("no input files.");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000268
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000269 // Construct search path list.
270 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000271 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000272 SearchPaths.push_back(Arg->getValue());
273 addLibSearchPaths();
274
Rui Ueyamaad660982015-06-07 00:20:32 +0000275 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000276 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000277 Config->OutputFile = Arg->getValue();
278
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000279 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000280 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000281 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000282
Rui Ueyama95925fd2015-06-28 19:35:15 +0000283 // Handle /force or /force:unresolved
284 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
285 Config->Force = true;
286
Rui Ueyama6600eb12015-07-04 23:37:32 +0000287 // Handle /debug
288 if (Args.hasArg(OPT_debug))
289 Config->Debug = true;
290
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000291 // Handle /noentry
292 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000293 if (!Args.hasArg(OPT_dll))
294 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000295 Config->NoEntry = true;
296 }
297
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000298 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000299 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000300 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000301 Config->ManifestID = 2;
302 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000303
Rui Ueyama588e8322015-06-15 01:23:58 +0000304 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000305 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000306 if (Args.hasArg(OPT_dynamicbase))
307 error("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000308 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000309 Config->DynamicBase = false;
310 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000311
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000312 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000313 if (auto *Arg = Args.getLastArg(OPT_machine))
314 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000315
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000316 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000317 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000318 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
319
320 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000321 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000322 Config->NoDefaultLibAll = true;
323
Rui Ueyama804a8b62015-05-29 16:18:15 +0000324 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000325 if (auto *Arg = Args.getLastArg(OPT_base))
326 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000327
328 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000329 if (auto *Arg = Args.getLastArg(OPT_stack))
330 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000331
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000332 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000333 if (auto *Arg = Args.getLastArg(OPT_heap))
334 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000335
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000336 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000337 if (auto *Arg = Args.getLastArg(OPT_version))
338 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
339 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000340
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000341 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000342 if (auto *Arg = Args.getLastArg(OPT_subsystem))
343 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
344 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000345
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000346 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000347 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000348 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000349
Rui Ueyama08d5e182015-06-18 23:20:11 +0000350 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000351 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000352 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000353
Rui Ueyamab95188c2015-06-18 20:27:09 +0000354 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000355 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000356 Config->Implib = Arg->getValue();
357
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000358 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000359 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000360 std::string S = StringRef(Arg->getValue()).lower();
361 if (S == "noref") {
362 Config->DoGC = false;
363 continue;
364 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000365 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000366 Config->ICF = true;
367 continue;
368 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000369 if (S != "ref" && S != "icf" && S != "noicf" &&
370 S != "lbr" && S != "nolbr" &&
371 !StringRef(S).startswith("icf=")) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000372 error(Twine("/opt: unknown option: ") + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000373 }
374 }
375
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000376 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000377 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000378 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000379
Rui Ueyama6600eb12015-07-04 23:37:32 +0000380 // Handle /merge
381 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000382 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000383
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000384 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000385 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
386 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000387
388 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000389 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
390 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000391
392 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000393 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000394 Config->ManifestDependency = Arg->getValue();
395
396 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000397 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000398 Config->ManifestFile = Arg->getValue();
399
Rui Ueyama6592ff82015-06-16 23:13:00 +0000400 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000401 if (Args.hasArg(OPT_allowbind_no))
402 Config->AllowBind = false;
403 if (Args.hasArg(OPT_allowisolation_no))
404 Config->AllowIsolation = false;
405 if (Args.hasArg(OPT_dynamicbase_no))
406 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000407 if (Args.hasArg(OPT_nxcompat_no))
408 Config->NxCompat = false;
409 if (Args.hasArg(OPT_tsaware_no))
410 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000411
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000412 // Create a list of input files. Files can be given as arguments
413 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000414 std::vector<StringRef> Paths;
415 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000416 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000417 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000418 Paths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000419 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000420 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000421 Paths.push_back(*Path);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000422 for (StringRef Path : Paths)
423 MBs.push_back(openFile(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000424
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000425 // Windows specific -- Create a resource file containing a manifest file.
426 if (Config->Manifest == Configuration::Embed) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000427 std::unique_ptr<MemoryBuffer> MB = createManifestRes();
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000428 MBs.push_back(MB->getMemBufferRef());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000429 OwningMBs.push_back(std::move(MB)); // take ownership
430 }
431
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000432 // Windows specific -- Input files can be Windows resource files (.res files).
433 // We invoke cvtres.exe to convert resource files to a regular COFF file
434 // then link the result file normally.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000435 std::vector<MemoryBufferRef> Resources;
Rui Ueyama77731b42015-06-26 23:59:13 +0000436 auto NotResource = [](MemoryBufferRef MB) {
437 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000438 };
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000439 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
440 if (It != MBs.end()) {
441 Resources.insert(Resources.end(), It, MBs.end());
442 MBs.erase(It, MBs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000443 }
444
Rui Ueyama85225b02015-07-02 03:15:15 +0000445 // Read all input files given via the command line. Note that step()
446 // doesn't read files that are specified by directive sections.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000447 for (MemoryBufferRef MB : MBs)
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000448 Symtab.addFile(createFile(MB));
Rafael Espindolab835ae82015-08-06 14:58:50 +0000449 Symtab.step();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000450
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000451 // Determine machine type and check if all object files are
452 // for the same CPU type. Note that this needs to be done before
453 // any call to mangle().
454 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
455 MachineTypes MT = File->getMachineType();
456 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
457 continue;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000458 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
459 Config->Machine = MT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000460 continue;
461 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000462 if (Config->Machine != MT)
463 error(Twine(File->getShortName()) + ": machine type " + machineToStr(MT) +
464 " conflicts with " + machineToStr(Config->Machine));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000465 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000466 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000467 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000468 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000469 }
470
471 // Windows specific -- Convert Windows resource files to a COFF file.
472 if (!Resources.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000473 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources);
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000474 Symtab.addFile(createFile(MB->getMemBufferRef()));
475 OwningMBs.push_back(std::move(MB)); // take ownership
476 }
477
Rui Ueyama4d545342015-07-28 03:12:00 +0000478 // Handle /largeaddressaware
479 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
480 Config->LargeAddressAware = true;
481
Rui Ueyamad68e2112015-07-28 03:15:57 +0000482 // Handle /highentropyva
483 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
484 Config->HighEntropyVA = true;
485
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000486 // Handle /entry and /dll
487 if (auto *Arg = Args.getLastArg(OPT_entry)) {
488 Config->Entry = addUndefined(mangle(Arg->getValue()));
489 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000490 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
491 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000492 Config->Entry = addUndefined(S);
493 } else if (!Config->NoEntry) {
494 // Windows specific -- If entry point name is not given, we need to
495 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000496 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000497 if (S.empty())
498 error("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000499 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000500 if (Config->Verbose)
501 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000502 }
503
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000504 // Handle /export
505 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000506 Export E = parseExport(Arg->getValue());
507 if (Config->Machine == I386 && !E.Name.startswith("_@?"))
508 E.Name = mangle(E.Name);
509 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000510 }
511
512 // Handle /def
513 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000514 MemoryBufferRef MB = openFile(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000515 // parseModuleDefs mutates Config object.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000516 parseModuleDefs(MB, &Alloc);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000517 }
518
Rui Ueyama6d249082015-07-13 22:31:45 +0000519 // Handle /delayload
520 for (auto *Arg : Args.filtered(OPT_delayload)) {
521 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000522 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000523 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000524 } else {
525 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000526 }
527 }
528
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000529 // Set default image base if /base is not given.
530 if (Config->ImageBase == uint64_t(-1))
531 Config->ImageBase = getDefaultImageBase();
532
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000533 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000534 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000535 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
536 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
537 }
Rui Ueyama29f74c32015-07-29 16:30:31 +0000538 Config->LoadConfigUsed = mangle("_load_config_used");
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000539
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000540 // Read as much files as we can from directives sections.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000541 Symtab.run();
Rui Ueyama85225b02015-07-02 03:15:15 +0000542
543 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000544 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
545 // A new file may contain a directive section to add new command line options.
546 // That's why we have to repeat until converge.)
547 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000548 // Windows specific -- if entry point is not found,
549 // search for its mangled names.
550 if (Config->Entry)
551 Symtab.mangleMaybe(Config->Entry);
552
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000553 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000554 for (Export &E : Config->Exports) {
555 E.Sym = addUndefined(E.Name);
556 Symtab.mangleMaybe(E.Sym);
557 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000558
559 // Add weak aliases. Weak aliases is a mechanism to give remaining
560 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000561 for (auto Pair : Config->AlternateNames) {
562 StringRef From = Pair.first;
563 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000564 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000565 if (!Sym)
566 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000567 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000568 if (!U->WeakAlias)
569 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000570 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000571
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000572 // Windows specific -- if __load_config_used can be resolved, resolve it.
Peter Collingbournee7107ec2015-07-31 05:33:34 +0000573 if (Symtab.find(Config->LoadConfigUsed))
574 addUndefined(Config->LoadConfigUsed);
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000575
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000576 if (Symtab.queueEmpty())
577 break;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000578 Symtab.run();
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000579 }
580
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000581 // Do LTO by compiling bitcode input files to a native COFF file
582 // then link that file.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000583 Symtab.addCombinedLTOObject();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000584
Peter Collingbourne2612a322015-07-04 05:28:41 +0000585 // Make sure we have resolved all symbols.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000586 Symtab.reportRemainingUndefines(/*Resolve=*/true);
Peter Collingbourne2612a322015-07-04 05:28:41 +0000587
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000588 // Windows specific -- if no /subsystem is given, we need to infer
589 // that from entry point name.
590 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000591 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000592 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
593 error("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000594 }
595
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000596 // Handle /safeseh.
597 if (Args.hasArg(OPT_safeseh)) {
598 for (ObjectFile *File : Symtab.ObjectFiles) {
599 if (File->SEHCompat)
600 continue;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000601 error(Twine("/safeseh: ") + File->getName() +
602 " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000603 }
604 }
605
Rui Ueyama151d8622015-06-17 20:40:43 +0000606 // Windows specific -- when we are creating a .dll file, we also
607 // need to create a .lib file.
Rui Ueyama8765fba2015-07-15 22:21:08 +0000608 if (!Config->Exports.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000609 fixupExports();
610 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000611 assignExportOrdinals();
612 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000613
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000614 // Windows specific -- Create a side-by-side manifest file.
615 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000616 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000617
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000618 // Create a dummy PDB file to satisfy build sytem rules.
619 if (auto *Arg = Args.getLastArg(OPT_pdb))
620 touchFile(Arg->getValue());
621
Rui Ueyama411c63602015-05-28 19:09:30 +0000622 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000623 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000624
Rui Ueyama016414f2015-06-28 20:07:08 +0000625 // Create a symbol map file containing symbol VAs and their names
626 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000627 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
628 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000629 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000630 error(EC, "Could not create the symbol map");
Peter Collingbournebe549552015-06-26 18:58:24 +0000631 Symtab.printMap(Out);
632 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000633 // Call exit to avoid calling destructors.
634 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000635}
636
Rui Ueyama411c63602015-05-28 19:09:30 +0000637} // namespace coff
638} // namespace lld