blob: 4cff03995fba94bde22ef3dd3255e32882f89c6e [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 Ueyama3c4737d2015-08-11 16:46:08 +0000119 case OPT_editandcontinue:
Rui Ueyama432383172015-07-29 21:01:15 +0000120 case OPT_throwingnew:
Rui Ueyama46682632015-07-29 20:29:15 +0000121 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000122 default:
Rafael Espindolab835ae82015-08-06 14:58:50 +0000123 error(Twine(Arg->getSpelling()) + " is not allowed in .drectve");
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000124 }
125 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000126}
127
Rui Ueyama54b71da2015-05-31 19:17:12 +0000128// Find file from search paths. You can omit ".obj", this function takes
129// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000130StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000131 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
132 if (hasPathSep)
133 return Filename;
134 bool hasExt = (Filename.find('.') != StringRef::npos);
135 for (StringRef Dir : SearchPaths) {
136 SmallString<128> Path = Dir;
137 llvm::sys::path::append(Path, Filename);
138 if (llvm::sys::fs::exists(Path.str()))
139 return Alloc.save(Path.str());
140 if (!hasExt) {
141 Path.append(".obj");
142 if (llvm::sys::fs::exists(Path.str()))
143 return Alloc.save(Path.str());
144 }
145 }
146 return Filename;
147}
148
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000149// Resolves a file path. This never returns the same path
150// (in that case, it returns None).
151Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
152 StringRef Path = doFindFile(Filename);
153 bool Seen = !VisitedFiles.insert(Path.lower()).second;
154 if (Seen)
155 return None;
156 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000157}
158
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000159// Find library file from search path.
160StringRef LinkerDriver::doFindLib(StringRef Filename) {
161 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000162 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000163 if (!hasExt)
164 Filename = Alloc.save(Filename + ".lib");
165 return doFindFile(Filename);
166}
167
168// Resolves a library path. /nodefaultlib options are taken into
169// consideration. This never returns the same path (in that case,
170// it returns None).
171Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
172 if (Config->NoDefaultLibAll)
173 return None;
174 StringRef Path = doFindLib(Filename);
175 if (Config->NoDefaultLibs.count(Path))
176 return None;
177 bool Seen = !VisitedFiles.insert(Path.lower()).second;
178 if (Seen)
179 return None;
180 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000181}
182
183// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000184void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000185 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
186 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000187 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000188 StringRef Env = Alloc.save(*EnvOpt);
189 while (!Env.empty()) {
190 StringRef Path;
191 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000192 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000193 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000194}
195
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000196Undefined *LinkerDriver::addUndefined(StringRef Name) {
197 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000198 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000199 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000200}
201
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000202// Symbol names are mangled by appending "_" prefix on x86.
203StringRef LinkerDriver::mangle(StringRef Sym) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000204 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
205 if (Config->Machine == I386)
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000206 return Alloc.save("_" + Sym);
207 return Sym;
208}
209
Rui Ueyama45044f42015-06-29 01:03:53 +0000210// Windows specific -- find default entry point name.
211StringRef LinkerDriver::findDefaultEntry() {
212 // User-defined main functions and their corresponding entry points.
213 static const char *Entries[][2] = {
214 {"main", "mainCRTStartup"},
215 {"wmain", "wmainCRTStartup"},
216 {"WinMain", "WinMainCRTStartup"},
217 {"wWinMain", "wWinMainCRTStartup"},
218 };
219 for (auto E : Entries) {
Rui Ueyamaa50387f2015-07-14 02:58:13 +0000220 StringRef Entry = Symtab.findMangle(mangle(E[0]));
221 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body))
Rui Ueyama7c3e23f2015-07-09 01:25:49 +0000222 return mangle(E[1]);
Rui Ueyama45044f42015-06-29 01:03:53 +0000223 }
224 return "";
225}
226
227WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000228 if (Config->DLL)
229 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000230 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000231 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
Rui Ueyama611add22015-08-08 00:23:37 +0000232 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
Rui Ueyama45044f42015-06-29 01:03:53 +0000233 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
234 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000235}
236
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000237static uint64_t getDefaultImageBase() {
238 if (Config->is64())
239 return Config->DLL ? 0x180000000 : 0x140000000;
240 return Config->DLL ? 0x10000000 : 0x400000;
241}
242
Rafael Espindolab835ae82015-08-06 14:58:50 +0000243void LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Rui Ueyama27e470a2015-08-09 20:45:17 +0000244 // If the first command line argument is "/lib", link.exe acts like lib.exe.
245 // We call our own implementation of lib.exe that understands bitcode files.
246 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
247 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
248 error("lib failed");
249 return;
250 }
251
Peter Collingbourne60c16162015-06-01 20:10:10 +0000252 // Needed for LTO.
253 llvm::InitializeAllTargetInfos();
254 llvm::InitializeAllTargets();
255 llvm::InitializeAllTargetMCs();
256 llvm::InitializeAllAsmParsers();
257 llvm::InitializeAllAsmPrinters();
258 llvm::InitializeAllDisassemblers();
259
Rui Ueyama411c63602015-05-28 19:09:30 +0000260 // Parse command line options.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000261 llvm::opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000262
Rui Ueyama5c726432015-05-29 16:11:52 +0000263 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000264 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000265 printHelp(ArgsArr[0]);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000266 return;
Rui Ueyama5c726432015-05-29 16:11:52 +0000267 }
268
Rafael Espindolab835ae82015-08-06 14:58:50 +0000269 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
270 error("no input files.");
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000271
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000272 // Construct search path list.
273 SearchPaths.push_back("");
David Blaikie6521ed92015-06-22 22:06:52 +0000274 for (auto *Arg : Args.filtered(OPT_libpath))
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000275 SearchPaths.push_back(Arg->getValue());
276 addLibSearchPaths();
277
Rui Ueyamaad660982015-06-07 00:20:32 +0000278 // Handle /out
David Blaikie6521ed92015-06-22 22:06:52 +0000279 if (auto *Arg = Args.getLastArg(OPT_out))
Rui Ueyamaad660982015-06-07 00:20:32 +0000280 Config->OutputFile = Arg->getValue();
281
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000282 // Handle /verbose
David Blaikie6521ed92015-06-22 22:06:52 +0000283 if (Args.hasArg(OPT_verbose))
Rui Ueyama411c63602015-05-28 19:09:30 +0000284 Config->Verbose = true;
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000285
Rui Ueyama95925fd2015-06-28 19:35:15 +0000286 // Handle /force or /force:unresolved
287 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
288 Config->Force = true;
289
Rui Ueyama6600eb12015-07-04 23:37:32 +0000290 // Handle /debug
291 if (Args.hasArg(OPT_debug))
292 Config->Debug = true;
293
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000294 // Handle /noentry
295 if (Args.hasArg(OPT_noentry)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000296 if (!Args.hasArg(OPT_dll))
297 error("/noentry must be specified with /dll");
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000298 Config->NoEntry = true;
299 }
300
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000301 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000302 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000303 Config->DLL = true;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000304 Config->ManifestID = 2;
305 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000306
Rui Ueyama588e8322015-06-15 01:23:58 +0000307 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000308 if (Args.hasArg(OPT_fixed)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000309 if (Args.hasArg(OPT_dynamicbase))
310 error("/fixed must not be specified with /dynamicbase");
Rui Ueyama588e8322015-06-15 01:23:58 +0000311 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000312 Config->DynamicBase = false;
313 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000314
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000315 // Handle /machine
Rafael Espindolab835ae82015-08-06 14:58:50 +0000316 if (auto *Arg = Args.getLastArg(OPT_machine))
317 Config->Machine = getMachineType(Arg->getValue());
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000318
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000319 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000320 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000321 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
322
323 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000324 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000325 Config->NoDefaultLibAll = true;
326
Rui Ueyama804a8b62015-05-29 16:18:15 +0000327 // Handle /base
Rafael Espindolab835ae82015-08-06 14:58:50 +0000328 if (auto *Arg = Args.getLastArg(OPT_base))
329 parseNumbers(Arg->getValue(), &Config->ImageBase);
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000330
331 // Handle /stack
Rafael Espindolab835ae82015-08-06 14:58:50 +0000332 if (auto *Arg = Args.getLastArg(OPT_stack))
333 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
Rui Ueyama804a8b62015-05-29 16:18:15 +0000334
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000335 // Handle /heap
Rafael Espindolab835ae82015-08-06 14:58:50 +0000336 if (auto *Arg = Args.getLastArg(OPT_heap))
337 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000338
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000339 // Handle /version
Rafael Espindolab835ae82015-08-06 14:58:50 +0000340 if (auto *Arg = Args.getLastArg(OPT_version))
341 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
342 &Config->MinorImageVersion);
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000343
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000344 // Handle /subsystem
Rafael Espindolab835ae82015-08-06 14:58:50 +0000345 if (auto *Arg = Args.getLastArg(OPT_subsystem))
346 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
347 &Config->MinorOSVersion);
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000348
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000349 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000350 for (auto *Arg : Args.filtered(OPT_alternatename))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000351 parseAlternateName(Arg->getValue());
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000352
Rui Ueyama08d5e182015-06-18 23:20:11 +0000353 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000354 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000355 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000356
Rui Ueyamab95188c2015-06-18 20:27:09 +0000357 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000358 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000359 Config->Implib = Arg->getValue();
360
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000361 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000362 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000363 std::string S = StringRef(Arg->getValue()).lower();
364 if (S == "noref") {
365 Config->DoGC = false;
366 continue;
367 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000368 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000369 Config->ICF = true;
370 continue;
371 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000372 if (S != "ref" && S != "icf" && S != "noicf" &&
373 S != "lbr" && S != "nolbr" &&
374 !StringRef(S).startswith("icf=")) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000375 error(Twine("/opt: unknown option: ") + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000376 }
377 }
378
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000379 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000380 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000381 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000382
Rui Ueyama6600eb12015-07-04 23:37:32 +0000383 // Handle /merge
384 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000385 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000386
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000387 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000388 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
389 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000390
391 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000392 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
393 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000394
395 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000396 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000397 Config->ManifestDependency = Arg->getValue();
398
399 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000400 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000401 Config->ManifestFile = Arg->getValue();
402
Rui Ueyama6592ff82015-06-16 23:13:00 +0000403 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000404 if (Args.hasArg(OPT_allowbind_no))
405 Config->AllowBind = false;
406 if (Args.hasArg(OPT_allowisolation_no))
407 Config->AllowIsolation = false;
408 if (Args.hasArg(OPT_dynamicbase_no))
409 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000410 if (Args.hasArg(OPT_nxcompat_no))
411 Config->NxCompat = false;
412 if (Args.hasArg(OPT_tsaware_no))
413 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000414
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000415 // Create a list of input files. Files can be given as arguments
416 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000417 std::vector<StringRef> Paths;
418 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000419 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000420 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000421 Paths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000422 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000423 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000424 Paths.push_back(*Path);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000425 for (StringRef Path : Paths)
426 MBs.push_back(openFile(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000427
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000428 // Windows specific -- Create a resource file containing a manifest file.
429 if (Config->Manifest == Configuration::Embed) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000430 std::unique_ptr<MemoryBuffer> MB = createManifestRes();
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000431 MBs.push_back(MB->getMemBufferRef());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000432 OwningMBs.push_back(std::move(MB)); // take ownership
433 }
434
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000435 // Windows specific -- Input files can be Windows resource files (.res files).
436 // We invoke cvtres.exe to convert resource files to a regular COFF file
437 // then link the result file normally.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000438 std::vector<MemoryBufferRef> Resources;
Rui Ueyama77731b42015-06-26 23:59:13 +0000439 auto NotResource = [](MemoryBufferRef MB) {
440 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000441 };
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000442 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
443 if (It != MBs.end()) {
444 Resources.insert(Resources.end(), It, MBs.end());
445 MBs.erase(It, MBs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000446 }
447
Rui Ueyama85225b02015-07-02 03:15:15 +0000448 // Read all input files given via the command line. Note that step()
449 // doesn't read files that are specified by directive sections.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000450 for (MemoryBufferRef MB : MBs)
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000451 Symtab.addFile(createFile(MB));
Rafael Espindolab835ae82015-08-06 14:58:50 +0000452 Symtab.step();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000453
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000454 // Determine machine type and check if all object files are
455 // for the same CPU type. Note that this needs to be done before
456 // any call to mangle().
457 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
458 MachineTypes MT = File->getMachineType();
459 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
460 continue;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000461 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
462 Config->Machine = MT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000463 continue;
464 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000465 if (Config->Machine != MT)
466 error(Twine(File->getShortName()) + ": machine type " + machineToStr(MT) +
467 " conflicts with " + machineToStr(Config->Machine));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000468 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000469 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000470 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000471 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000472 }
473
474 // Windows specific -- Convert Windows resource files to a COFF file.
475 if (!Resources.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000476 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources);
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000477 Symtab.addFile(createFile(MB->getMemBufferRef()));
478 OwningMBs.push_back(std::move(MB)); // take ownership
479 }
480
Rui Ueyama4d545342015-07-28 03:12:00 +0000481 // Handle /largeaddressaware
482 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
483 Config->LargeAddressAware = true;
484
Rui Ueyamad68e2112015-07-28 03:15:57 +0000485 // Handle /highentropyva
486 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
487 Config->HighEntropyVA = true;
488
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000489 // Handle /entry and /dll
490 if (auto *Arg = Args.getLastArg(OPT_entry)) {
491 Config->Entry = addUndefined(mangle(Arg->getValue()));
492 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000493 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
494 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000495 Config->Entry = addUndefined(S);
496 } else if (!Config->NoEntry) {
497 // Windows specific -- If entry point name is not given, we need to
498 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000499 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000500 if (S.empty())
501 error("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000502 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000503 if (Config->Verbose)
504 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000505 }
506
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000507 // Handle /export
508 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000509 Export E = parseExport(Arg->getValue());
510 if (Config->Machine == I386 && !E.Name.startswith("_@?"))
511 E.Name = mangle(E.Name);
512 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000513 }
514
515 // Handle /def
516 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000517 MemoryBufferRef MB = openFile(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000518 // parseModuleDefs mutates Config object.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000519 parseModuleDefs(MB, &Alloc);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000520 }
521
Rui Ueyama6d249082015-07-13 22:31:45 +0000522 // Handle /delayload
523 for (auto *Arg : Args.filtered(OPT_delayload)) {
524 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000525 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000526 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000527 } else {
528 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000529 }
530 }
531
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000532 // Set default image base if /base is not given.
533 if (Config->ImageBase == uint64_t(-1))
534 Config->ImageBase = getDefaultImageBase();
535
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000536 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000537 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000538 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
539 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
540 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000541
Rui Ueyama107db552015-08-09 21:01:06 +0000542 // We do not support /guard:cf (control flow protection) yet.
543 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
544 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
545 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
546 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
547
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000548 // Read as much files as we can from directives sections.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000549 Symtab.run();
Rui Ueyama85225b02015-07-02 03:15:15 +0000550
551 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000552 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
553 // A new file may contain a directive section to add new command line options.
554 // That's why we have to repeat until converge.)
555 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000556 // Windows specific -- if entry point is not found,
557 // search for its mangled names.
558 if (Config->Entry)
559 Symtab.mangleMaybe(Config->Entry);
560
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000561 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000562 for (Export &E : Config->Exports) {
563 E.Sym = addUndefined(E.Name);
564 Symtab.mangleMaybe(E.Sym);
565 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000566
567 // Add weak aliases. Weak aliases is a mechanism to give remaining
568 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000569 for (auto Pair : Config->AlternateNames) {
570 StringRef From = Pair.first;
571 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000572 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000573 if (!Sym)
574 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000575 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000576 if (!U->WeakAlias)
577 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000578 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000579
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000580 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyama8ebdc8c2015-08-07 22:43:53 +0000581 if (Symtab.findUnderscore("_load_config_used"))
582 addUndefined(mangle("_load_config_used"));
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000583
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000584 if (Symtab.queueEmpty())
585 break;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000586 Symtab.run();
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000587 }
588
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000589 // Do LTO by compiling bitcode input files to a native COFF file
590 // then link that file.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000591 Symtab.addCombinedLTOObject();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000592
Peter Collingbourne2612a322015-07-04 05:28:41 +0000593 // Make sure we have resolved all symbols.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000594 Symtab.reportRemainingUndefines(/*Resolve=*/true);
Peter Collingbourne2612a322015-07-04 05:28:41 +0000595
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000596 // Windows specific -- if no /subsystem is given, we need to infer
597 // that from entry point name.
598 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000599 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000600 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
601 error("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000602 }
603
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000604 // Handle /safeseh.
605 if (Args.hasArg(OPT_safeseh)) {
606 for (ObjectFile *File : Symtab.ObjectFiles) {
607 if (File->SEHCompat)
608 continue;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000609 error(Twine("/safeseh: ") + File->getName() +
610 " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000611 }
612 }
613
Rui Ueyama151d8622015-06-17 20:40:43 +0000614 // Windows specific -- when we are creating a .dll file, we also
615 // need to create a .lib file.
Rui Ueyama8765fba2015-07-15 22:21:08 +0000616 if (!Config->Exports.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000617 fixupExports();
618 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000619 assignExportOrdinals();
620 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000621
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000622 // Windows specific -- Create a side-by-side manifest file.
623 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000624 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000625
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000626 // Create a dummy PDB file to satisfy build sytem rules.
627 if (auto *Arg = Args.getLastArg(OPT_pdb))
628 touchFile(Arg->getValue());
629
Rui Ueyama411c63602015-05-28 19:09:30 +0000630 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000631 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000632
Rui Ueyama016414f2015-06-28 20:07:08 +0000633 // Create a symbol map file containing symbol VAs and their names
634 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000635 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
636 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000637 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000638 error(EC, "Could not create the symbol map");
Peter Collingbournebe549552015-06-26 18:58:24 +0000639 Symtab.printMap(Out);
640 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000641 // Call exit to avoid calling destructors.
642 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000643}
644
Rui Ueyama411c63602015-05-28 19:09:30 +0000645} // namespace coff
646} // namespace lld