blob: fa29d14678bf8ca82f6e1c09667abe4b006b6488 [file] [log] [blame]
Rui Ueyama411c63602015-05-28 19:09:30 +00001//===- Driver.cpp ---------------------------------------------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "Config.h"
11#include "Driver.h"
Rui Ueyama562daa82015-06-18 21:50:38 +000012#include "Error.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000013#include "InputFiles.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000014#include "SymbolTable.h"
15#include "Writer.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000016#include "llvm/ADT/Optional.h"
17#include "llvm/ADT/STLExtras.h"
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000018#include "llvm/ADT/StringSwitch.h"
Peter Collingbournebd1cb792015-06-09 21:52:48 +000019#include "llvm/LibDriver/LibDriver.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000020#include "llvm/Option/Arg.h"
21#include "llvm/Option/ArgList.h"
22#include "llvm/Option/Option.h"
23#include "llvm/Support/CommandLine.h"
24#include "llvm/Support/Debug.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000025#include "llvm/Support/Path.h"
Rui Ueyama54b71da2015-05-31 19:17:12 +000026#include "llvm/Support/Process.h"
Peter Collingbourne60c16162015-06-01 20:10:10 +000027#include "llvm/Support/TargetSelect.h"
Rui Ueyama411c63602015-05-28 19:09:30 +000028#include "llvm/Support/raw_ostream.h"
Rui Ueyama2bf6a122015-06-14 21:50:50 +000029#include <algorithm>
Rui Ueyama411c63602015-05-28 19:09:30 +000030#include <memory>
31
32using namespace llvm;
Rui Ueyama3ee0fe42015-05-31 03:55:46 +000033using llvm::COFF::IMAGE_SUBSYSTEM_UNKNOWN;
34using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_CUI;
35using llvm::COFF::IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama54b71da2015-05-31 19:17:12 +000036using llvm::sys::Process;
Peter Collingbournebaf5f872015-06-26 19:20:09 +000037using llvm::sys::fs::OpenFlags;
Rui Ueyama711cd2d2015-05-31 21:17:10 +000038using llvm::sys::fs::file_magic;
39using llvm::sys::fs::identify_magic;
Rui Ueyama411c63602015-05-28 19:09:30 +000040
Rui Ueyama3500f662015-05-28 20:30:06 +000041namespace lld {
42namespace coff {
Rui Ueyama411c63602015-05-28 19:09:30 +000043
Rui Ueyama3500f662015-05-28 20:30:06 +000044Configuration *Config;
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000045LinkerDriver *Driver;
46
David Blaikie00818192015-06-22 22:06:48 +000047bool link(llvm::ArrayRef<const char *> Args) {
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000048 auto C = make_unique<Configuration>();
49 Config = C.get();
50 auto D = make_unique<LinkerDriver>();
51 Driver = D.get();
David Blaikieb2b1c7c2015-06-21 06:32:10 +000052 return Driver->link(Args);
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000053}
Rui Ueyama411c63602015-05-28 19:09:30 +000054
Rui Ueyamaad660982015-06-07 00:20:32 +000055// Drop directory components and replace extension with ".exe".
56static std::string getOutputPath(StringRef Path) {
57 auto P = Path.find_last_of("\\/");
58 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
59 return (S.substr(0, S.rfind('.')) + ".exe").str();
Rui Ueyama411c63602015-05-28 19:09:30 +000060}
61
Rui Ueyamad7c2f582015-05-31 21:04:56 +000062// Opens a file. Path has to be resolved already.
63// Newly created memory buffers are owned by this driver.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000064ErrorOr<MemoryBufferRef> LinkerDriver::openFile(StringRef Path) {
Rui Ueyamad7c2f582015-05-31 21:04:56 +000065 auto MBOrErr = MemoryBuffer::getFile(Path);
66 if (auto EC = MBOrErr.getError())
67 return EC;
68 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
69 MemoryBufferRef MBRef = MB->getMemBufferRef();
70 OwningMBs.push_back(std::move(MB)); // take ownership
Rui Ueyama2bf6a122015-06-14 21:50:50 +000071 return MBRef;
72}
Rui Ueyama711cd2d2015-05-31 21:17:10 +000073
Rui Ueyama2bf6a122015-06-14 21:50:50 +000074static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
Rui Ueyama711cd2d2015-05-31 21:17:10 +000075 // File type is detected by contents, not by file extension.
Rui Ueyama2bf6a122015-06-14 21:50:50 +000076 file_magic Magic = identify_magic(MB.getBuffer());
Rui Ueyama711cd2d2015-05-31 21:17:10 +000077 if (Magic == file_magic::archive)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000078 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
Peter Collingbourne60c16162015-06-01 20:10:10 +000079 if (Magic == file_magic::bitcode)
Rui Ueyama2bf6a122015-06-14 21:50:50 +000080 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
Rui Ueyamaad660982015-06-07 00:20:32 +000081 if (Config->OutputFile == "")
Rui Ueyama2bf6a122015-06-14 21:50:50 +000082 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
83 return std::unique_ptr<InputFile>(new ObjectFile(MB));
Rui Ueyama411c63602015-05-28 19:09:30 +000084}
85
Rui Ueyama411c63602015-05-28 19:09:30 +000086// Parses .drectve section contents and returns a list of files
87// specified by /defaultlib.
Rui Ueyamaa9cbbf82015-05-31 19:17:09 +000088std::error_code
Rui Ueyama0d2e9992015-06-23 23:56:39 +000089LinkerDriver::parseDirectives(StringRef S) {
Rui Ueyama115d7c12015-06-07 02:55:19 +000090 auto ArgsOrErr = Parser.parse(S);
Rui Ueyama411c63602015-05-28 19:09:30 +000091 if (auto EC = ArgsOrErr.getError())
92 return EC;
David Blaikie6521ed92015-06-22 22:06:52 +000093 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +000094
David Blaikie6521ed92015-06-22 22:06:52 +000095 for (auto *Arg : Args) {
Rui Ueyama562daa82015-06-18 21:50:38 +000096 switch (Arg->getOption().getID()) {
97 case OPT_alternatename:
98 if (auto EC = parseAlternateName(Arg->getValue()))
Rui Ueyamad7c2f582015-05-31 21:04:56 +000099 return EC;
Rui Ueyama562daa82015-06-18 21:50:38 +0000100 break;
101 case OPT_defaultlib:
102 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
103 ErrorOr<MemoryBufferRef> MBOrErr = openFile(*Path);
104 if (auto EC = MBOrErr.getError())
105 return EC;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000106 Symtab.addFile(createFile(MBOrErr.get()));
Rui Ueyama562daa82015-06-18 21:50:38 +0000107 }
108 break;
109 case OPT_export: {
110 ErrorOr<Export> E = parseExport(Arg->getValue());
111 if (auto EC = E.getError())
112 return EC;
113 Config->Exports.push_back(E.get());
114 break;
115 }
116 case OPT_failifmismatch:
117 if (auto EC = checkFailIfMismatch(Arg->getValue()))
118 return EC;
119 break;
Rui Ueyama08d5e182015-06-18 23:20:11 +0000120 case OPT_incl:
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000121 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000122 break;
Rui Ueyamace86c992015-06-18 23:22:39 +0000123 case OPT_merge:
Rui Ueyama6600eb12015-07-04 23:37:32 +0000124 if (auto EC = parseMerge(Arg->getValue()))
125 return EC;
Rui Ueyamace86c992015-06-18 23:22:39 +0000126 break;
127 case OPT_nodefaultlib:
128 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
129 break;
Rui Ueyama562daa82015-06-18 21:50:38 +0000130 default:
131 llvm::errs() << Arg->getSpelling() << " is not allowed in .drectve\n";
132 return make_error_code(LLDError::InvalidOption);
Rui Ueyamad7c2f582015-05-31 21:04:56 +0000133 }
134 }
Rui Ueyama411c63602015-05-28 19:09:30 +0000135 return std::error_code();
136}
137
Rui Ueyama54b71da2015-05-31 19:17:12 +0000138// Find file from search paths. You can omit ".obj", this function takes
139// care of that. Note that the returned path is not guaranteed to exist.
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000140StringRef LinkerDriver::doFindFile(StringRef Filename) {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000141 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
142 if (hasPathSep)
143 return Filename;
144 bool hasExt = (Filename.find('.') != StringRef::npos);
145 for (StringRef Dir : SearchPaths) {
146 SmallString<128> Path = Dir;
147 llvm::sys::path::append(Path, Filename);
148 if (llvm::sys::fs::exists(Path.str()))
149 return Alloc.save(Path.str());
150 if (!hasExt) {
151 Path.append(".obj");
152 if (llvm::sys::fs::exists(Path.str()))
153 return Alloc.save(Path.str());
154 }
155 }
156 return Filename;
157}
158
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000159// Resolves a file path. This never returns the same path
160// (in that case, it returns None).
161Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
162 StringRef Path = doFindFile(Filename);
163 bool Seen = !VisitedFiles.insert(Path.lower()).second;
164 if (Seen)
165 return None;
166 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000167}
168
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000169// Find library file from search path.
170StringRef LinkerDriver::doFindLib(StringRef Filename) {
171 // Add ".lib" to Filename if that has no file extension.
Rui Ueyama54b71da2015-05-31 19:17:12 +0000172 bool hasExt = (Filename.find('.') != StringRef::npos);
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000173 if (!hasExt)
174 Filename = Alloc.save(Filename + ".lib");
175 return doFindFile(Filename);
176}
177
178// Resolves a library path. /nodefaultlib options are taken into
179// consideration. This never returns the same path (in that case,
180// it returns None).
181Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
182 if (Config->NoDefaultLibAll)
183 return None;
184 StringRef Path = doFindLib(Filename);
185 if (Config->NoDefaultLibs.count(Path))
186 return None;
187 bool Seen = !VisitedFiles.insert(Path.lower()).second;
188 if (Seen)
189 return None;
190 return Path;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000191}
192
193// Parses LIB environment which contains a list of search paths.
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000194void LinkerDriver::addLibSearchPaths() {
Rui Ueyama54b71da2015-05-31 19:17:12 +0000195 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
196 if (!EnvOpt.hasValue())
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000197 return;
Rui Ueyama54b71da2015-05-31 19:17:12 +0000198 StringRef Env = Alloc.save(*EnvOpt);
199 while (!Env.empty()) {
200 StringRef Path;
201 std::tie(Path, Env) = Env.split(';');
Rui Ueyamaf00df0a2015-06-19 22:39:48 +0000202 SearchPaths.push_back(Path);
Rui Ueyama54b71da2015-05-31 19:17:12 +0000203 }
Rui Ueyama54b71da2015-05-31 19:17:12 +0000204}
205
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000206Undefined *LinkerDriver::addUndefined(StringRef Name) {
207 Undefined *U = Symtab.addUndefined(Name);
Rui Ueyama18f8d2c2015-07-02 00:21:08 +0000208 Config->GCRoot.insert(U);
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000209 return U;
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000210}
211
Rui Ueyama45044f42015-06-29 01:03:53 +0000212// Windows specific -- find default entry point name.
213StringRef LinkerDriver::findDefaultEntry() {
214 // User-defined main functions and their corresponding entry points.
215 static const char *Entries[][2] = {
216 {"main", "mainCRTStartup"},
217 {"wmain", "wmainCRTStartup"},
218 {"WinMain", "WinMainCRTStartup"},
219 {"wWinMain", "wWinMainCRTStartup"},
220 };
221 for (auto E : Entries) {
Rui Ueyama458d7442015-07-02 03:59:04 +0000222 Symbol *Sym = Symtab.find(E[0]);
Rui Ueyama4b669892015-06-30 23:46:52 +0000223 if (Sym && !isa<Undefined>(Sym->Body))
Rui Ueyama45044f42015-06-29 01:03:53 +0000224 return E[1];
225 }
226 return "";
227}
228
229WindowsSubsystem LinkerDriver::inferSubsystem() {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000230 if (Config->DLL)
231 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
Rui Ueyama45044f42015-06-29 01:03:53 +0000232 if (Symtab.find("main") || Symtab.find("wmain"))
233 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
234 if (Symtab.find("WinMain") || Symtab.find("wWinMain"))
235 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
236 return IMAGE_SUBSYSTEM_UNKNOWN;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000237}
238
David Blaikie00818192015-06-22 22:06:48 +0000239bool LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
Peter Collingbourne60c16162015-06-01 20:10:10 +0000240 // Needed for LTO.
241 llvm::InitializeAllTargetInfos();
242 llvm::InitializeAllTargets();
243 llvm::InitializeAllTargetMCs();
244 llvm::InitializeAllAsmParsers();
245 llvm::InitializeAllAsmPrinters();
246 llvm::InitializeAllDisassemblers();
247
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000248 // If the first command line argument is "/lib", link.exe acts like lib.exe.
249 // We call our own implementation of lib.exe that understands bitcode files.
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000250 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib"))
251 return llvm::libDriverMain(ArgsArr.slice(1)) == 0;
Peter Collingbournebd1cb792015-06-09 21:52:48 +0000252
Rui Ueyama411c63602015-05-28 19:09:30 +0000253 // Parse command line options.
Rui Ueyama9d72f092015-06-28 03:05:38 +0000254 auto ArgsOrErr = Parser.parseLINK(ArgsArr.slice(1));
Rui Ueyama411c63602015-05-28 19:09:30 +0000255 if (auto EC = ArgsOrErr.getError()) {
256 llvm::errs() << EC.message() << "\n";
257 return false;
258 }
David Blaikie6521ed92015-06-22 22:06:52 +0000259 llvm::opt::InputArgList Args = std::move(ArgsOrErr.get());
Rui Ueyama411c63602015-05-28 19:09:30 +0000260
Rui Ueyama5c726432015-05-29 16:11:52 +0000261 // Handle /help
David Blaikie6521ed92015-06-22 22:06:52 +0000262 if (Args.hasArg(OPT_help)) {
David Blaikieb2b1c7c2015-06-21 06:32:10 +0000263 printHelp(ArgsArr[0]);
Rui Ueyama5c726432015-05-29 16:11:52 +0000264 return true;
265 }
266
David Blaikie6521ed92015-06-22 22:06:52 +0000267 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end()) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000268 llvm::errs() << "no input files.\n";
269 return false;
270 }
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 Ueyama32f8e1c2015-06-26 03:44:00 +0000290 // Handle /entry
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000291 if (auto *Arg = Args.getLastArg(OPT_entry))
292 Config->Entry = addUndefined(Arg->getValue());
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000293
Rui Ueyama6600eb12015-07-04 23:37:32 +0000294 // Handle /debug
295 if (Args.hasArg(OPT_debug))
296 Config->Debug = true;
297
Rui Ueyamaa8b60452015-06-28 19:56:30 +0000298 // Handle /noentry
299 if (Args.hasArg(OPT_noentry)) {
300 if (!Args.hasArg(OPT_dll)) {
301 llvm::errs() << "/noentry must be specified with /dll\n";
302 return false;
303 }
304 Config->NoEntry = true;
305 }
306
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000307 // Handle /dll
David Blaikie6521ed92015-06-22 22:06:52 +0000308 if (Args.hasArg(OPT_dll)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000309 Config->DLL = true;
Rui Ueyama49d6cd32015-07-03 00:02:19 +0000310 Config->ImageBase = 0x180000000U;
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000311 Config->ManifestID = 2;
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000312 if (Config->Entry == nullptr && !Config->NoEntry)
313 Config->Entry = addUndefined("_DllMainCRTStartup");
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000314 }
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000315
Rui Ueyama588e8322015-06-15 01:23:58 +0000316 // Handle /fixed
David Blaikie6521ed92015-06-22 22:06:52 +0000317 if (Args.hasArg(OPT_fixed)) {
318 if (Args.hasArg(OPT_dynamicbase)) {
Rui Ueyama6592ff82015-06-16 23:13:00 +0000319 llvm::errs() << "/fixed must not be specified with /dynamicbase\n";
320 return false;
321 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000322 Config->Relocatable = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000323 Config->DynamicBase = false;
324 }
Rui Ueyama588e8322015-06-15 01:23:58 +0000325
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000326 // Handle /machine
David Blaikie6521ed92015-06-22 22:06:52 +0000327 auto MTOrErr = getMachineType(&Args);
Rui Ueyama3d3e6fb2015-05-29 16:06:00 +0000328 if (auto EC = MTOrErr.getError()) {
329 llvm::errs() << EC.message() << "\n";
330 return false;
331 }
332 Config->MachineType = MTOrErr.get();
333
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000334 // Handle /nodefaultlib:<filename>
David Blaikie6521ed92015-06-22 22:06:52 +0000335 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000336 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
337
338 // Handle /nodefaultlib
David Blaikie6521ed92015-06-22 22:06:52 +0000339 if (Args.hasArg(OPT_nodefaultlib_all))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000340 Config->NoDefaultLibAll = true;
341
Rui Ueyama804a8b62015-05-29 16:18:15 +0000342 // Handle /base
David Blaikie6521ed92015-06-22 22:06:52 +0000343 if (auto *Arg = Args.getLastArg(OPT_base)) {
Rui Ueyama804a8b62015-05-29 16:18:15 +0000344 if (auto EC = parseNumbers(Arg->getValue(), &Config->ImageBase)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000345 llvm::errs() << "/base: " << EC.message() << "\n";
346 return false;
347 }
348 }
349
350 // Handle /stack
David Blaikie6521ed92015-06-22 22:06:52 +0000351 if (auto *Arg = Args.getLastArg(OPT_stack)) {
Rui Ueyamab41b7e52015-05-29 16:21:11 +0000352 if (auto EC = parseNumbers(Arg->getValue(), &Config->StackReserve,
353 &Config->StackCommit)) {
354 llvm::errs() << "/stack: " << EC.message() << "\n";
Rui Ueyama804a8b62015-05-29 16:18:15 +0000355 return false;
356 }
357 }
358
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000359 // Handle /heap
David Blaikie6521ed92015-06-22 22:06:52 +0000360 if (auto *Arg = Args.getLastArg(OPT_heap)) {
Rui Ueyamac377e9a2015-05-29 16:23:40 +0000361 if (auto EC = parseNumbers(Arg->getValue(), &Config->HeapReserve,
362 &Config->HeapCommit)) {
363 llvm::errs() << "/heap: " << EC.message() << "\n";
364 return false;
365 }
366 }
367
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000368 // Handle /version
David Blaikie6521ed92015-06-22 22:06:52 +0000369 if (auto *Arg = Args.getLastArg(OPT_version)) {
Rui Ueyamab9dcdb52015-05-29 16:28:29 +0000370 if (auto EC = parseVersion(Arg->getValue(), &Config->MajorImageVersion,
371 &Config->MinorImageVersion)) {
372 llvm::errs() << "/version: " << EC.message() << "\n";
373 return false;
374 }
375 }
376
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000377 // Handle /subsystem
David Blaikie6521ed92015-06-22 22:06:52 +0000378 if (auto *Arg = Args.getLastArg(OPT_subsystem)) {
Rui Ueyama15cc47e2015-05-29 16:34:31 +0000379 if (auto EC = parseSubsystem(Arg->getValue(), &Config->Subsystem,
380 &Config->MajorOSVersion,
381 &Config->MinorOSVersion)) {
382 llvm::errs() << "/subsystem: " << EC.message() << "\n";
383 return false;
384 }
385 }
386
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000387 // Handle /alternatename
David Blaikie6521ed92015-06-22 22:06:52 +0000388 for (auto *Arg : Args.filtered(OPT_alternatename))
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000389 if (parseAlternateName(Arg->getValue()))
390 return false;
391
Rui Ueyama08d5e182015-06-18 23:20:11 +0000392 // Handle /include
David Blaikie6521ed92015-06-22 22:06:52 +0000393 for (auto *Arg : Args.filtered(OPT_incl))
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000394 addUndefined(Arg->getValue());
Rui Ueyama08d5e182015-06-18 23:20:11 +0000395
Rui Ueyamab95188c2015-06-18 20:27:09 +0000396 // Handle /implib
David Blaikie6521ed92015-06-22 22:06:52 +0000397 if (auto *Arg = Args.getLastArg(OPT_implib))
Rui Ueyamab95188c2015-06-18 20:27:09 +0000398 Config->Implib = Arg->getValue();
399
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000400 // Handle /opt
David Blaikie6521ed92015-06-22 22:06:52 +0000401 for (auto *Arg : Args.filtered(OPT_opt)) {
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000402 std::string S = StringRef(Arg->getValue()).lower();
403 if (S == "noref") {
404 Config->DoGC = false;
405 continue;
406 }
Rui Ueyamaf799ede2015-06-25 23:26:58 +0000407 if (S == "lldicf") {
Rui Ueyamaddf71fc2015-06-24 04:36:52 +0000408 Config->ICF = true;
409 continue;
410 }
Rui Ueyamae2cbfea2015-06-07 03:17:42 +0000411 if (S != "ref" && S != "icf" && S != "noicf" &&
412 S != "lbr" && S != "nolbr" &&
413 !StringRef(S).startswith("icf=")) {
414 llvm::errs() << "/opt: unknown option: " << S << "\n";
415 return false;
416 }
417 }
418
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000419 // Handle /export
David Blaikie6521ed92015-06-22 22:06:52 +0000420 for (auto *Arg : Args.filtered(OPT_export)) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000421 ErrorOr<Export> E = parseExport(Arg->getValue());
422 if (E.getError())
423 return false;
424 Config->Exports.push_back(E.get());
425 }
426
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000427 // Handle /delayload
David Blaikie6521ed92015-06-22 22:06:52 +0000428 for (auto *Arg : Args.filtered(OPT_delayload)) {
Rui Ueyama7a247ee2015-07-03 01:40:14 +0000429 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
Rui Ueyama32f8e1c2015-06-26 03:44:00 +0000430 addUndefined("__delayLoadHelper2");
Rui Ueyamaa77336b2015-06-21 22:31:52 +0000431 }
432
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000433 // Handle /failifmismatch
David Blaikie6521ed92015-06-22 22:06:52 +0000434 for (auto *Arg : Args.filtered(OPT_failifmismatch))
Rui Ueyama75b098b2015-06-18 21:23:34 +0000435 if (checkFailIfMismatch(Arg->getValue()))
436 return false;
Rui Ueyama8854d8a2015-06-04 19:21:24 +0000437
Rui Ueyama1f373702015-06-17 19:19:25 +0000438 // Handle /def
David Blaikie6521ed92015-06-22 22:06:52 +0000439 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
Rui Ueyama1f373702015-06-17 19:19:25 +0000440 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Arg->getValue());
441 if (auto EC = MBOrErr.getError()) {
442 llvm::errs() << "/def: " << EC.message() << "\n";
443 return false;
444 }
445 // parseModuleDefs mutates Config object.
446 if (parseModuleDefs(MBOrErr.get()))
447 return false;
448 }
449
Rui Ueyama6600eb12015-07-04 23:37:32 +0000450 // Handle /merge
451 for (auto *Arg : Args.filtered(OPT_merge))
452 if (parseMerge(Arg->getValue()))
453 return false;
454
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000455 // Handle /manifest
David Blaikie6521ed92015-06-22 22:06:52 +0000456 if (auto *Arg = Args.getLastArg(OPT_manifest_colon)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000457 if (auto EC = parseManifest(Arg->getValue())) {
458 llvm::errs() << "/manifest: " << EC.message() << "\n";
459 return false;
460 }
461 }
462
463 // Handle /manifestuac
David Blaikie6521ed92015-06-22 22:06:52 +0000464 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) {
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000465 if (auto EC = parseManifestUAC(Arg->getValue())) {
466 llvm::errs() << "/manifestuac: " << EC.message() << "\n";
467 return false;
468 }
469 }
470
471 // Handle /manifestdependency
David Blaikie6521ed92015-06-22 22:06:52 +0000472 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000473 Config->ManifestDependency = Arg->getValue();
474
475 // Handle /manifestfile
David Blaikie6521ed92015-06-22 22:06:52 +0000476 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000477 Config->ManifestFile = Arg->getValue();
478
Rui Ueyama6592ff82015-06-16 23:13:00 +0000479 // Handle miscellaneous boolean flags.
David Blaikie6521ed92015-06-22 22:06:52 +0000480 if (Args.hasArg(OPT_allowbind_no))
481 Config->AllowBind = false;
482 if (Args.hasArg(OPT_allowisolation_no))
483 Config->AllowIsolation = false;
484 if (Args.hasArg(OPT_dynamicbase_no))
485 Config->DynamicBase = false;
486 if (Args.hasArg(OPT_highentropyva_no))
487 Config->HighEntropyVA = false;
488 if (Args.hasArg(OPT_nxcompat_no))
489 Config->NxCompat = false;
490 if (Args.hasArg(OPT_tsaware_no))
491 Config->TerminalServerAware = false;
Rui Ueyama6592ff82015-06-16 23:13:00 +0000492
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000493 // Create a list of input files. Files can be given as arguments
494 // for /defaultlib option.
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000495 std::vector<StringRef> InputPaths;
496 std::vector<MemoryBufferRef> Inputs;
David Blaikie6521ed92015-06-22 22:06:52 +0000497 for (auto *Arg : Args.filtered(OPT_INPUT))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000498 if (Optional<StringRef> Path = findFile(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000499 InputPaths.push_back(*Path);
David Blaikie6521ed92015-06-22 22:06:52 +0000500 for (auto *Arg : Args.filtered(OPT_defaultlib))
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000501 if (Optional<StringRef> Path = findLib(Arg->getValue()))
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000502 InputPaths.push_back(*Path);
503 for (StringRef Path : InputPaths) {
504 ErrorOr<MemoryBufferRef> MBOrErr = openFile(Path);
505 if (auto EC = MBOrErr.getError()) {
506 llvm::errs() << "cannot open " << Path << ": " << EC.message() << "\n";
507 return false;
508 }
509 Inputs.push_back(MBOrErr.get());
510 }
Rui Ueyamad21b00b2015-05-31 19:17:14 +0000511
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000512 // Windows specific -- Create a resource file containing a manifest file.
513 if (Config->Manifest == Configuration::Embed) {
514 auto MBOrErr = createManifestRes();
515 if (MBOrErr.getError())
516 return false;
517 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
518 Inputs.push_back(MB->getMemBufferRef());
519 OwningMBs.push_back(std::move(MB)); // take ownership
520 }
521
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000522 // Windows specific -- Input files can be Windows resource files (.res files).
523 // We invoke cvtres.exe to convert resource files to a regular COFF file
524 // then link the result file normally.
Rui Ueyama77731b42015-06-26 23:59:13 +0000525 auto NotResource = [](MemoryBufferRef MB) {
526 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000527 };
Rui Ueyama77731b42015-06-26 23:59:13 +0000528 auto It = std::stable_partition(Inputs.begin(), Inputs.end(), NotResource);
529 if (It != Inputs.end()) {
530 std::vector<MemoryBufferRef> Files(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000531 auto MBOrErr = convertResToCOFF(Files);
532 if (MBOrErr.getError())
533 return false;
534 std::unique_ptr<MemoryBuffer> MB = std::move(MBOrErr.get());
Rui Ueyama77731b42015-06-26 23:59:13 +0000535 Inputs.erase(It, Inputs.end());
Rui Ueyama2bf6a122015-06-14 21:50:50 +0000536 Inputs.push_back(MB->getMemBufferRef());
537 OwningMBs.push_back(std::move(MB)); // take ownership
538 }
539
Rui Ueyama49d6cd32015-07-03 00:02:19 +0000540 Symtab.addAbsolute("__ImageBase", Config->ImageBase);
541
Rui Ueyama85225b02015-07-02 03:15:15 +0000542 // Read all input files given via the command line. Note that step()
543 // doesn't read files that are specified by directive sections.
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000544 for (MemoryBufferRef MB : Inputs)
545 Symtab.addFile(createFile(MB));
Rui Ueyama85225b02015-07-02 03:15:15 +0000546 if (auto EC = Symtab.step()) {
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000547 llvm::errs() << EC.message() << "\n";
548 return false;
Rui Ueyama411c63602015-05-28 19:09:30 +0000549 }
Rui Ueyama5cff6852015-05-31 03:34:08 +0000550
Rui Ueyama45044f42015-06-29 01:03:53 +0000551 // Windows specific -- If entry point name is not given, we need to
552 // infer that from user-defined entry name.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000553 if (Config->Entry == nullptr && !Config->NoEntry) {
Rui Ueyama45044f42015-06-29 01:03:53 +0000554 StringRef S = findDefaultEntry();
555 if (S.empty()) {
556 llvm::errs() << "entry point must be defined\n";
557 return false;
558 }
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000559 Config->Entry = addUndefined(S);
Rui Ueyama85225b02015-07-02 03:15:15 +0000560 if (Config->Verbose)
561 llvm::outs() << "Entry name inferred: " << S << "\n";
Rui Ueyama45044f42015-06-29 01:03:53 +0000562 }
563
Rui Ueyama85225b02015-07-02 03:15:15 +0000564 // Read as much files as we can.
565 if (auto EC = Symtab.run()) {
566 llvm::errs() << EC.message() << "\n";
567 return false;
568 }
569
570 // Resolve auxiliary symbols until we get a convergence.
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000571 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
572 // A new file may contain a directive section to add new command line options.
573 // That's why we have to repeat until converge.)
574 for (;;) {
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000575 // Windows specific -- if entry point is not found,
576 // search for its mangled names.
577 if (Config->Entry)
578 Symtab.mangleMaybe(Config->Entry);
579
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000580 // Windows specific -- Make sure we resolve all dllexported symbols.
Rui Ueyama6bf638e2015-07-02 00:04:14 +0000581 for (Export &E : Config->Exports) {
582 E.Sym = addUndefined(E.Name);
583 Symtab.mangleMaybe(E.Sym);
584 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000585
586 // Add weak aliases. Weak aliases is a mechanism to give remaining
587 // undefined symbols final chance to be resolved successfully.
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000588 for (auto Pair : Config->AlternateNames) {
589 StringRef From = Pair.first;
590 StringRef To = Pair.second;
Rui Ueyama458d7442015-07-02 03:59:04 +0000591 Symbol *Sym = Symtab.find(From);
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000592 if (!Sym)
593 continue;
594 if (auto *U = dyn_cast<Undefined>(Sym->Body))
595 if (!U->WeakAlias)
596 U->WeakAlias = Symtab.addUndefined(To);
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000597 }
Rui Ueyama573bf7d2015-06-19 21:12:48 +0000598
Rui Ueyama3d4c69c2015-07-02 02:38:59 +0000599 if (Symtab.queueEmpty())
600 break;
Rui Ueyama0d2e9992015-06-23 23:56:39 +0000601 if (auto EC = Symtab.run()) {
602 llvm::errs() << EC.message() << "\n";
603 return false;
604 }
Rui Ueyama2edb35a2015-06-18 19:09:30 +0000605 }
606
Rui Ueyamaeb262ce2015-06-04 02:12:16 +0000607 // Do LTO by compiling bitcode input files to a native COFF file
608 // then link that file.
Peter Collingbourne60c16162015-06-01 20:10:10 +0000609 if (auto EC = Symtab.addCombinedLTOObject()) {
610 llvm::errs() << EC.message() << "\n";
611 return false;
612 }
613
Peter Collingbourne2612a322015-07-04 05:28:41 +0000614 // Make sure we have resolved all symbols.
615 if (Symtab.reportRemainingUndefines(/*Resolve=*/true))
616 return false;
617
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000618 // Windows specific -- if no /subsystem is given, we need to infer
619 // that from entry point name.
620 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000621 Config->Subsystem = inferSubsystem();
Rui Ueyama3ee0fe42015-05-31 03:55:46 +0000622 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
623 llvm::errs() << "subsystem must be defined\n";
624 return false;
625 }
626 }
627
Rui Ueyama151d8622015-06-17 20:40:43 +0000628 // Windows specific -- when we are creating a .dll file, we also
629 // need to create a .lib file.
630 if (!Config->Exports.empty())
631 writeImportLibrary();
632
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000633 // Windows specific -- fix up dllexported symbols.
Rui Ueyamaf5313b32015-06-28 22:16:41 +0000634 if (!Config->Exports.empty())
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000635 if (fixupExports())
636 return false;
Rui Ueyama97dff9e2015-06-17 00:16:33 +0000637
Rui Ueyama24c5fd02015-06-18 00:12:42 +0000638 // Windows specific -- Create a side-by-side manifest file.
639 if (Config->Manifest == Configuration::SideBySide)
640 if (createSideBySideManifest())
641 return false;
642
Rui Ueyama0fc26d22015-06-29 14:27:12 +0000643 // Create a dummy PDB file to satisfy build sytem rules.
644 if (auto *Arg = Args.getLastArg(OPT_pdb))
645 touchFile(Arg->getValue());
646
Rui Ueyama411c63602015-05-28 19:09:30 +0000647 // Write the result.
648 Writer Out(&Symtab);
Rui Ueyamaad660982015-06-07 00:20:32 +0000649 if (auto EC = Out.write(Config->OutputFile)) {
Rui Ueyama411c63602015-05-28 19:09:30 +0000650 llvm::errs() << EC.message() << "\n";
651 return false;
652 }
Peter Collingbournebe549552015-06-26 18:58:24 +0000653
Rui Ueyama016414f2015-06-28 20:07:08 +0000654 // Create a symbol map file containing symbol VAs and their names
655 // to help debugging.
Peter Collingbournebe549552015-06-26 18:58:24 +0000656 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
657 std::error_code EC;
Peter Collingbournebaf5f872015-06-26 19:20:09 +0000658 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
Peter Collingbournebe549552015-06-26 18:58:24 +0000659 if (EC) {
660 llvm::errs() << EC.message() << "\n";
661 return false;
662 }
663 Symtab.printMap(Out);
664 }
Rui Ueyamaa51ce712015-07-03 05:31:35 +0000665 // Call exit to avoid calling destructors.
666 exit(0);
Rui Ueyama411c63602015-05-28 19:09:30 +0000667}
668
Rui Ueyama411c63602015-05-28 19:09:30 +0000669} // namespace coff
670} // namespace lld