blob: fcc4dd820afeb8604b74dfc25344a596e4d6016f [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 }
Peter Collingbourne526ff152015-08-14 04:47:07 +0000372 if (StringRef(S).startswith("lldlto=")) {
373 StringRef OptLevel = StringRef(S).substr(7);
374 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
375 Config->LTOOptLevel > 3) {
376 error("/opt:lldlto: invalid optimization level: " + OptLevel);
377 }
378 continue;
379 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000380 if (S != "ref" && S != "icf" && S != "noicf" &&
381 S != "lbr" && S != "nolbr" &&
382 !StringRef(S).startswith("icf=")) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000383 error(Twine("/opt: unknown option: ") + S);
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000384 }
385 }
386
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000387 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000388 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000389 checkFailIfMismatch(Arg->getValue());
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000390
Rui Ueyama6600eb12015-07-04 23:37:32 +0000391 // Handle /merge
392 for (auto *Arg : Args.filtered(OPT_merge))
Rafael Espindolab835ae82015-08-06 14:58:50 +0000393 parseMerge(Arg->getValue());
Rui Ueyama6600eb12015-07-04 23:37:32 +0000394
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000395 // Handle /manifest
Rafael Espindolab835ae82015-08-06 14:58:50 +0000396 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
397 parseManifest(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000398
399 // Handle /manifestuac
Rafael Espindolab835ae82015-08-06 14:58:50 +0000400 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
401 parseManifestUAC(Arg->getValue());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000402
403 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000404 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000405 Config->ManifestDependency = Arg->getValue();
406
407 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000408 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000409 Config->ManifestFile = Arg->getValue();
410
Rui Ueyama6592ff82015-06-16 23:13:00 +0000411 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000412 if (Args.hasArg(OPT_allowbind_no))
413 Config->AllowBind = false;
414 if (Args.hasArg(OPT_allowisolation_no))
415 Config->AllowIsolation = false;
416 if (Args.hasArg(OPT_dynamicbase_no))
417 Config->DynamicBase = false;
David Blaikie6521ed92015-06-22 22:06:52 +0000418 if (Args.hasArg(OPT_nxcompat_no))
419 Config->NxCompat = false;
420 if (Args.hasArg(OPT_tsaware_no))
421 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000422
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000423 // Create a list of input files. Files can be given as arguments
424 // for /defaultlib option.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000425 std::vector<StringRef> Paths;
426 std::vector<MemoryBufferRef> MBs;
David Blaikie6521ed92015-06-22 22:06:52 +0000427 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000428 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000429 Paths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000430 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000431 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000432 Paths.push_back(*Path);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000433 for (StringRef Path : Paths)
434 MBs.push_back(openFile(Path));
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000435
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000436 // Windows specific -- Create a resource file containing a manifest file.
437 if (Config->Manifest == Configuration::Embed) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000438 std::unique_ptr<MemoryBuffer> MB = createManifestRes();
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000439 MBs.push_back(MB->getMemBufferRef());
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000440 OwningMBs.push_back(std::move(MB)); // take ownership
441 }
442
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000443 // Windows specific -- Input files can be Windows resource files (.res files).
444 // We invoke cvtres.exe to convert resource files to a regular COFF file
445 // then link the result file normally.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000446 std::vector<MemoryBufferRef> Resources;
Rui Ueyama77731b42015-06-26 23:59:13 +0000447 auto NotResource = [](MemoryBufferRef MB) {
448 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000449 };
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000450 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
451 if (It != MBs.end()) {
452 Resources.insert(Resources.end(), It, MBs.end());
453 MBs.erase(It, MBs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000454 }
455
Rui Ueyama85225b02015-07-02 03:15:15 +0000456 // Read all input files given via the command line. Note that step()
457 // doesn't read files that are specified by directive sections.
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000458 for (MemoryBufferRef MB : MBs)
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000459 Symtab.addFile(createFile(MB));
Rafael Espindolab835ae82015-08-06 14:58:50 +0000460 Symtab.step();
Rui Ueyama5cff6852015-05-31 03:34:08 +0000461
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000462 // Determine machine type and check if all object files are
463 // for the same CPU type. Note that this needs to be done before
464 // any call to mangle().
465 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
466 MachineTypes MT = File->getMachineType();
467 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
468 continue;
Rui Ueyama5e706b32015-07-25 21:54:50 +0000469 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
470 Config->Machine = MT;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000471 continue;
472 }
Rafael Espindolab835ae82015-08-06 14:58:50 +0000473 if (Config->Machine != MT)
474 error(Twine(File->getShortName()) + ": machine type " + machineToStr(MT) +
475 " conflicts with " + machineToStr(Config->Machine));
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000476 }
Rui Ueyama5e706b32015-07-25 21:54:50 +0000477 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000478 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
Rui Ueyama5e706b32015-07-25 21:54:50 +0000479 Config->Machine = AMD64;
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000480 }
481
482 // Windows specific -- Convert Windows resource files to a COFF file.
483 if (!Resources.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000484 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources);
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000485 Symtab.addFile(createFile(MB->getMemBufferRef()));
486 OwningMBs.push_back(std::move(MB)); // take ownership
487 }
488
Rui Ueyama4d545342015-07-28 03:12:00 +0000489 // Handle /largeaddressaware
490 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
491 Config->LargeAddressAware = true;
492
Rui Ueyamad68e2112015-07-28 03:15:57 +0000493 // Handle /highentropyva
494 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
495 Config->HighEntropyVA = true;
496
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000497 // Handle /entry and /dll
498 if (auto *Arg = Args.getLastArg(OPT_entry)) {
499 Config->Entry = addUndefined(mangle(Arg->getValue()));
500 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
Rui Ueyama5e706b32015-07-25 21:54:50 +0000501 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
502 : "_DllMainCRTStartup";
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000503 Config->Entry = addUndefined(S);
504 } else if (!Config->NoEntry) {
505 // Windows specific -- If entry point name is not given, we need to
506 // infer that from user-defined entry name.
Rui Ueyama45044f42015-06-29 01:03:53 +0000507 StringRef S = findDefaultEntry();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000508 if (S.empty())
509 error("entry point must be defined");
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000510 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000511 if (Config->Verbose)
512 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000513 }
514
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000515 // Handle /export
516 for (auto *Arg : Args.filtered(OPT_export)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000517 Export E = parseExport(Arg->getValue());
518 if (Config->Machine == I386 && !E.Name.startswith("_@?"))
519 E.Name = mangle(E.Name);
520 Config->Exports.push_back(E);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000521 }
522
523 // Handle /def
524 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000525 MemoryBufferRef MB = openFile(Arg->getValue());
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000526 // parseModuleDefs mutates Config object.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000527 parseModuleDefs(MB, &Alloc);
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000528 }
529
Rui Ueyama6d249082015-07-13 22:31:45 +0000530 // Handle /delayload
531 for (auto *Arg : Args.filtered(OPT_delayload)) {
532 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama5e706b32015-07-25 21:54:50 +0000533 if (Config->Machine == I386) {
Rui Ueyama6d249082015-07-13 22:31:45 +0000534 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
Rui Ueyama35ccb0f2015-07-25 00:20:06 +0000535 } else {
536 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
Rui Ueyama6d249082015-07-13 22:31:45 +0000537 }
538 }
539
Rui Ueyama5c437cd2015-07-25 21:42:33 +0000540 // Set default image base if /base is not given.
541 if (Config->ImageBase == uint64_t(-1))
542 Config->ImageBase = getDefaultImageBase();
543
Rui Ueyama3cb895c2015-07-24 22:58:44 +0000544 Symtab.addRelative(mangle("__ImageBase"), 0);
Rui Ueyama5e706b32015-07-25 21:54:50 +0000545 if (Config->Machine == I386) {
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000546 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
547 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
548 }
Rui Ueyamabbdec4f2015-07-09 22:51:41 +0000549
Rui Ueyama107db552015-08-09 21:01:06 +0000550 // We do not support /guard:cf (control flow protection) yet.
551 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
552 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
553 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
554 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
555
Rui Ueyamaea533cd2015-07-09 19:54:13 +0000556 // Read as much files as we can from directives sections.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000557 Symtab.run();
Rui Ueyama85225b02015-07-02 03:15:15 +0000558
559 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000560 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
561 // A new file may contain a directive section to add new command line options.
562 // That's why we have to repeat until converge.)
563 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000564 // Windows specific -- if entry point is not found,
565 // search for its mangled names.
566 if (Config->Entry)
567 Symtab.mangleMaybe(Config->Entry);
568
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000569 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000570 for (Export &E : Config->Exports) {
571 E.Sym = addUndefined(E.Name);
572 Symtab.mangleMaybe(E.Sym);
573 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000574
575 // Add weak aliases. Weak aliases is a mechanism to give remaining
576 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000577 for (auto Pair : Config->AlternateNames) {
578 StringRef From = Pair.first;
579 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000580 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000581 if (!Sym)
582 continue;
Rui Ueyama183f53f2015-07-06 17:45:22 +0000583 if (auto *U = dyn_cast<Undefined>(Sym->Body))
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000584 if (!U->WeakAlias)
585 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000586 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000587
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000588 // Windows specific -- if __load_config_used can be resolved, resolve it.
Rui Ueyama8ebdc8c2015-08-07 22:43:53 +0000589 if (Symtab.findUnderscore("_load_config_used"))
590 addUndefined(mangle("_load_config_used"));
Rui Ueyamacd3f99b2015-07-24 23:51:14 +0000591
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000592 if (Symtab.queueEmpty())
593 break;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000594 Symtab.run();
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000595 }
596
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000597 // Do LTO by compiling bitcode input files to a native COFF file
598 // then link that file.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000599 Symtab.addCombinedLTOObject();
Peter Collingbourne60c16162015-06-01 20:10:10 +0000600
Peter Collingbourne2612a322015-07-04 05:28:41 +0000601 // Make sure we have resolved all symbols.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000602 Symtab.reportRemainingUndefines(/*Resolve=*/true);
Peter Collingbourne2612a322015-07-04 05:28:41 +0000603
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000604 // Windows specific -- if no /subsystem is given, we need to infer
605 // that from entry point name.
606 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000607 Config->Subsystem = inferSubsystem();
Rafael Espindolab835ae82015-08-06 14:58:50 +0000608 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
609 error("subsystem must be defined");
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000610 }
611
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000612 // Handle /safeseh.
613 if (Args.hasArg(OPT_safeseh)) {
614 for (ObjectFile *File : Symtab.ObjectFiles) {
615 if (File->SEHCompat)
616 continue;
Rafael Espindolab835ae82015-08-06 14:58:50 +0000617 error(Twine("/safeseh: ") + File->getName() +
618 " is not compatible with SEH");
Rui Ueyamaff88d5a2015-07-29 20:25:40 +0000619 }
620 }
621
Rui Ueyama151d8622015-06-17 20:40:43 +0000622 // Windows specific -- when we are creating a .dll file, we also
623 // need to create a .lib file.
Rui Ueyama8765fba2015-07-15 22:21:08 +0000624 if (!Config->Exports.empty()) {
Rafael Espindolab835ae82015-08-06 14:58:50 +0000625 fixupExports();
626 writeImportLibrary();
Rui Ueyama8765fba2015-07-15 22:21:08 +0000627 assignExportOrdinals();
628 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000629
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000630 // Windows specific -- Create a side-by-side manifest file.
631 if (Config->Manifest == Configuration::SideBySide)
Rafael Espindolab835ae82015-08-06 14:58:50 +0000632 createSideBySideManifest();
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000633
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000634 // Create a dummy PDB file to satisfy build sytem rules.
635 if (auto *Arg = Args.getLastArg(OPT_pdb))
636 touchFile(Arg->getValue());
637
Rui Ueyama411c63602015-05-28 19:09:30 +0000638 // Write the result.
Rafael Espindolab835ae82015-08-06 14:58:50 +0000639 writeResult(&Symtab);
Peter Collingbournebe549552015-06-26 18:58:24 +0000640
Rui Ueyama016414f2015-06-28 20:07:08 +0000641 // Create a symbol map file containing symbol VAs and their names
642 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000643 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
644 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000645 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Rafael Espindolab835ae82015-08-06 14:58:50 +0000646 error(EC, "Could not create the symbol map");
Peter Collingbournebe549552015-06-26 18:58:24 +0000647 Symtab.printMap(Out);
648 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000649 // Call exit to avoid calling destructors.
650 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000651}
652
Rui Ueyama411c63602015-05-28 19:09:30 +0000653} // namespace coff
654} // namespace lld