1 //===- Driver.cpp ---------------------------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
13 #include "InputFiles.h"
14 #include "SymbolTable.h"
17 #include "lld/Driver/Driver.h"
18 #include "llvm/ADT/Optional.h"
19 #include "llvm/LibDriver/LibDriver.h"
20 #include "llvm/Option/Arg.h"
21 #include "llvm/Option/ArgList.h"
22 #include "llvm/Option/Option.h"
23 #include "llvm/Support/Debug.h"
24 #include "llvm/Support/Path.h"
25 #include "llvm/Support/Process.h"
26 #include "llvm/Support/TargetSelect.h"
27 #include "llvm/Support/raw_ostream.h"
32 using namespace llvm::COFF;
33 using llvm::sys::Process;
34 using llvm::sys::fs::OpenFlags;
35 using llvm::sys::fs::file_magic;
36 using llvm::sys::fs::identify_magic;
41 Configuration *Config;
44 bool link(llvm::ArrayRef<const char *> Args) {
53 // Drop directory components and replace extension with ".exe" or ".dll".
54 static std::string getOutputPath(StringRef Path) {
55 auto P = Path.find_last_of("\\/");
56 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
57 const char* E = Config->DLL ? ".dll" : ".exe";
58 return (S.substr(0, S.rfind('.')) + E).str();
61 // Opens a file. Path has to be resolved already.
62 // Newly created memory buffers are owned by this driver.
63 MemoryBufferRef LinkerDriver::openFile(StringRef Path) {
64 std::unique_ptr<MemoryBuffer> MB =
65 check(MemoryBuffer::getFile(Path), "could not open " + Path);
66 MemoryBufferRef MBRef = MB->getMemBufferRef();
67 OwningMBs.push_back(std::move(MB)); // take ownership
71 static std::unique_ptr<InputFile> createFile(MemoryBufferRef MB) {
72 // File type is detected by contents, not by file extension.
73 file_magic Magic = identify_magic(MB.getBuffer());
74 if (Magic == file_magic::archive)
75 return std::unique_ptr<InputFile>(new ArchiveFile(MB));
76 if (Magic == file_magic::bitcode)
77 return std::unique_ptr<InputFile>(new BitcodeFile(MB));
78 if (Config->OutputFile == "")
79 Config->OutputFile = getOutputPath(MB.getBufferIdentifier());
80 return std::unique_ptr<InputFile>(new ObjectFile(MB));
83 static bool isDecorated(StringRef Sym) {
84 return Sym.startswith("_") || Sym.startswith("@") || Sym.startswith("?");
87 // Parses .drectve section contents and returns a list of files
88 // specified by /defaultlib.
89 void LinkerDriver::parseDirectives(StringRef S) {
90 llvm::opt::InputArgList Args = Parser.parse(S);
92 for (auto *Arg : Args) {
93 switch (Arg->getOption().getID()) {
94 case OPT_alternatename:
95 parseAlternateName(Arg->getValue());
98 if (Optional<StringRef> Path = findLib(Arg->getValue())) {
99 MemoryBufferRef MB = openFile(*Path);
100 Symtab.addFile(createFile(MB));
104 Export E = parseExport(Arg->getValue());
106 Config->Exports.push_back(E);
109 case OPT_failifmismatch:
110 checkFailIfMismatch(Arg->getValue());
113 addUndefined(Arg->getValue());
116 parseMerge(Arg->getValue());
118 case OPT_nodefaultlib:
119 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
122 parseSection(Arg->getValue());
124 case OPT_editandcontinue:
127 case OPT_throwingnew:
130 fatal(Arg->getSpelling() + " is not allowed in .drectve");
135 // Find file from search paths. You can omit ".obj", this function takes
136 // care of that. Note that the returned path is not guaranteed to exist.
137 StringRef LinkerDriver::doFindFile(StringRef Filename) {
138 bool hasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
141 bool hasExt = (Filename.find('.') != StringRef::npos);
142 for (StringRef Dir : SearchPaths) {
143 SmallString<128> Path = Dir;
144 llvm::sys::path::append(Path, Filename);
145 if (llvm::sys::fs::exists(Path.str()))
146 return Alloc.save(Path.str());
149 if (llvm::sys::fs::exists(Path.str()))
150 return Alloc.save(Path.str());
156 // Resolves a file path. This never returns the same path
157 // (in that case, it returns None).
158 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
159 StringRef Path = doFindFile(Filename);
160 bool Seen = !VisitedFiles.insert(Path.lower()).second;
166 // Find library file from search path.
167 StringRef LinkerDriver::doFindLib(StringRef Filename) {
168 // Add ".lib" to Filename if that has no file extension.
169 bool hasExt = (Filename.find('.') != StringRef::npos);
171 Filename = Alloc.save(Filename + ".lib");
172 return doFindFile(Filename);
175 // Resolves a library path. /nodefaultlib options are taken into
176 // consideration. This never returns the same path (in that case,
178 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
179 if (Config->NoDefaultLibAll)
181 StringRef Path = doFindLib(Filename);
182 if (Config->NoDefaultLibs.count(Path))
184 bool Seen = !VisitedFiles.insert(Path.lower()).second;
190 // Parses LIB environment which contains a list of search paths.
191 void LinkerDriver::addLibSearchPaths() {
192 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
193 if (!EnvOpt.hasValue())
195 StringRef Env = Alloc.save(*EnvOpt);
196 while (!Env.empty()) {
198 std::tie(Path, Env) = Env.split(';');
199 SearchPaths.push_back(Path);
203 Undefined *LinkerDriver::addUndefined(StringRef Name) {
204 Undefined *U = Symtab.addUndefined(Name);
205 Config->GCRoot.insert(U);
209 // Symbol names are mangled by appending "_" prefix on x86.
210 StringRef LinkerDriver::mangle(StringRef Sym) {
211 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
212 if (Config->Machine == I386)
213 return Alloc.save("_" + Sym);
217 // Windows specific -- find default entry point name.
218 StringRef LinkerDriver::findDefaultEntry() {
219 // User-defined main functions and their corresponding entry points.
220 static const char *Entries[][2] = {
221 {"main", "mainCRTStartup"},
222 {"wmain", "wmainCRTStartup"},
223 {"WinMain", "WinMainCRTStartup"},
224 {"wWinMain", "wWinMainCRTStartup"},
226 for (auto E : Entries) {
227 StringRef Entry = Symtab.findMangle(mangle(E[0]));
228 if (!Entry.empty() && !isa<Undefined>(Symtab.find(Entry)->Body))
234 WindowsSubsystem LinkerDriver::inferSubsystem() {
236 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
237 if (Symtab.findUnderscore("main") || Symtab.findUnderscore("wmain"))
238 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
239 if (Symtab.findUnderscore("WinMain") || Symtab.findUnderscore("wWinMain"))
240 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
241 return IMAGE_SUBSYSTEM_UNKNOWN;
244 static uint64_t getDefaultImageBase() {
246 return Config->DLL ? 0x180000000 : 0x140000000;
247 return Config->DLL ? 0x10000000 : 0x400000;
250 void LinkerDriver::link(llvm::ArrayRef<const char *> ArgsArr) {
251 // If the first command line argument is "/lib", link.exe acts like lib.exe.
252 // We call our own implementation of lib.exe that understands bitcode files.
253 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
254 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
260 llvm::InitializeAllTargetInfos();
261 llvm::InitializeAllTargets();
262 llvm::InitializeAllTargetMCs();
263 llvm::InitializeAllAsmParsers();
264 llvm::InitializeAllAsmPrinters();
265 llvm::InitializeAllDisassemblers();
267 // Parse command line options.
268 llvm::opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1));
271 if (Args.hasArg(OPT_help)) {
272 printHelp(ArgsArr[0]);
276 if (Args.filtered_begin(OPT_INPUT) == Args.filtered_end())
277 fatal("no input files");
279 // Construct search path list.
280 SearchPaths.push_back("");
281 for (auto *Arg : Args.filtered(OPT_libpath))
282 SearchPaths.push_back(Arg->getValue());
286 if (auto *Arg = Args.getLastArg(OPT_out))
287 Config->OutputFile = Arg->getValue();
290 if (Args.hasArg(OPT_verbose))
291 Config->Verbose = true;
293 // Handle /force or /force:unresolved
294 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved))
295 Config->Force = true;
298 if (Args.hasArg(OPT_debug))
299 Config->Debug = true;
302 if (Args.hasArg(OPT_noentry)) {
303 if (!Args.hasArg(OPT_dll))
304 fatal("/noentry must be specified with /dll");
305 Config->NoEntry = true;
309 if (Args.hasArg(OPT_dll)) {
311 Config->ManifestID = 2;
315 if (Args.hasArg(OPT_fixed)) {
316 if (Args.hasArg(OPT_dynamicbase))
317 fatal("/fixed must not be specified with /dynamicbase");
318 Config->Relocatable = false;
319 Config->DynamicBase = false;
323 if (auto *Arg = Args.getLastArg(OPT_machine))
324 Config->Machine = getMachineType(Arg->getValue());
326 // Handle /nodefaultlib:<filename>
327 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
328 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
330 // Handle /nodefaultlib
331 if (Args.hasArg(OPT_nodefaultlib_all))
332 Config->NoDefaultLibAll = true;
335 if (auto *Arg = Args.getLastArg(OPT_base))
336 parseNumbers(Arg->getValue(), &Config->ImageBase);
339 if (auto *Arg = Args.getLastArg(OPT_stack))
340 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
343 if (auto *Arg = Args.getLastArg(OPT_heap))
344 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
347 if (auto *Arg = Args.getLastArg(OPT_version))
348 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
349 &Config->MinorImageVersion);
352 if (auto *Arg = Args.getLastArg(OPT_subsystem))
353 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
354 &Config->MinorOSVersion);
356 // Handle /alternatename
357 for (auto *Arg : Args.filtered(OPT_alternatename))
358 parseAlternateName(Arg->getValue());
361 for (auto *Arg : Args.filtered(OPT_incl))
362 addUndefined(Arg->getValue());
365 if (auto *Arg = Args.getLastArg(OPT_implib))
366 Config->Implib = Arg->getValue();
369 for (auto *Arg : Args.filtered(OPT_opt)) {
370 std::string Str = StringRef(Arg->getValue()).lower();
371 SmallVector<StringRef, 1> Vec;
372 StringRef(Str).split(Vec, ',');
373 for (StringRef S : Vec) {
375 Config->DoGC = false;
376 Config->DoICF = false;
379 if (S == "icf" || StringRef(S).startswith("icf=")) {
380 Config->DoICF = true;
384 Config->DoICF = false;
387 if (StringRef(S).startswith("lldlto=")) {
388 StringRef OptLevel = StringRef(S).substr(7);
389 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) ||
390 Config->LTOOptLevel > 3)
391 fatal("/opt:lldlto: invalid optimization level: " + OptLevel);
394 if (StringRef(S).startswith("lldltojobs=")) {
395 StringRef Jobs = StringRef(S).substr(11);
396 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0)
397 fatal("/opt:lldltojobs: invalid job count: " + Jobs);
400 if (S != "ref" && S != "lbr" && S != "nolbr")
401 fatal("/opt: unknown option: " + S);
405 // Handle /failifmismatch
406 for (auto *Arg : Args.filtered(OPT_failifmismatch))
407 checkFailIfMismatch(Arg->getValue());
410 for (auto *Arg : Args.filtered(OPT_merge))
411 parseMerge(Arg->getValue());
414 for (auto *Arg : Args.filtered(OPT_section))
415 parseSection(Arg->getValue());
418 if (auto *Arg = Args.getLastArg(OPT_manifest_colon))
419 parseManifest(Arg->getValue());
421 // Handle /manifestuac
422 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
423 parseManifestUAC(Arg->getValue());
425 // Handle /manifestdependency
426 if (auto *Arg = Args.getLastArg(OPT_manifestdependency))
427 Config->ManifestDependency = Arg->getValue();
429 // Handle /manifestfile
430 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
431 Config->ManifestFile = Arg->getValue();
433 // Handle /manifestinput
434 for (auto *Arg : Args.filtered(OPT_manifestinput))
435 Config->ManifestInput.push_back(Arg->getValue());
437 // Handle miscellaneous boolean flags.
438 if (Args.hasArg(OPT_allowbind_no))
439 Config->AllowBind = false;
440 if (Args.hasArg(OPT_allowisolation_no))
441 Config->AllowIsolation = false;
442 if (Args.hasArg(OPT_dynamicbase_no))
443 Config->DynamicBase = false;
444 if (Args.hasArg(OPT_nxcompat_no))
445 Config->NxCompat = false;
446 if (Args.hasArg(OPT_tsaware_no))
447 Config->TerminalServerAware = false;
448 if (Args.hasArg(OPT_nosymtab))
449 Config->WriteSymtab = false;
451 // Create a list of input files. Files can be given as arguments
452 // for /defaultlib option.
453 std::vector<StringRef> Paths;
454 std::vector<MemoryBufferRef> MBs;
455 for (auto *Arg : Args.filtered(OPT_INPUT))
456 if (Optional<StringRef> Path = findFile(Arg->getValue()))
457 Paths.push_back(*Path);
458 for (auto *Arg : Args.filtered(OPT_defaultlib))
459 if (Optional<StringRef> Path = findLib(Arg->getValue()))
460 Paths.push_back(*Path);
461 for (StringRef Path : Paths)
462 MBs.push_back(openFile(Path));
464 // Windows specific -- Create a resource file containing a manifest file.
465 if (Config->Manifest == Configuration::Embed) {
466 std::unique_ptr<MemoryBuffer> MB = createManifestRes();
467 MBs.push_back(MB->getMemBufferRef());
468 OwningMBs.push_back(std::move(MB)); // take ownership
471 // Windows specific -- Input files can be Windows resource files (.res files).
472 // We invoke cvtres.exe to convert resource files to a regular COFF file
473 // then link the result file normally.
474 std::vector<MemoryBufferRef> Resources;
475 auto NotResource = [](MemoryBufferRef MB) {
476 return identify_magic(MB.getBuffer()) != file_magic::windows_resource;
478 auto It = std::stable_partition(MBs.begin(), MBs.end(), NotResource);
479 if (It != MBs.end()) {
480 Resources.insert(Resources.end(), It, MBs.end());
481 MBs.erase(It, MBs.end());
484 // Read all input files given via the command line. Note that step()
485 // doesn't read files that are specified by directive sections.
486 for (MemoryBufferRef MB : MBs)
487 Symtab.addFile(createFile(MB));
490 // Determine machine type and check if all object files are
491 // for the same CPU type. Note that this needs to be done before
492 // any call to mangle().
493 for (std::unique_ptr<InputFile> &File : Symtab.getFiles()) {
494 MachineTypes MT = File->getMachineType();
495 if (MT == IMAGE_FILE_MACHINE_UNKNOWN)
497 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
498 Config->Machine = MT;
501 if (Config->Machine != MT)
502 fatal(File->getShortName() + ": machine type " + machineToStr(MT) +
503 " conflicts with " + machineToStr(Config->Machine));
505 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
506 llvm::errs() << "warning: /machine is not specified. x64 is assumed.\n";
507 Config->Machine = AMD64;
510 // Windows specific -- Convert Windows resource files to a COFF file.
511 if (!Resources.empty()) {
512 std::unique_ptr<MemoryBuffer> MB = convertResToCOFF(Resources);
513 Symtab.addFile(createFile(MB->getMemBufferRef()));
514 OwningMBs.push_back(std::move(MB)); // take ownership
517 // Handle /largeaddressaware
518 if (Config->is64() || Args.hasArg(OPT_largeaddressaware))
519 Config->LargeAddressAware = true;
521 // Handle /highentropyva
522 if (Config->is64() && !Args.hasArg(OPT_highentropyva_no))
523 Config->HighEntropyVA = true;
525 // Handle /entry and /dll
526 if (auto *Arg = Args.getLastArg(OPT_entry)) {
527 Config->Entry = addUndefined(mangle(Arg->getValue()));
528 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) {
529 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
530 : "_DllMainCRTStartup";
531 Config->Entry = addUndefined(S);
532 } else if (!Config->NoEntry) {
533 // Windows specific -- If entry point name is not given, we need to
534 // infer that from user-defined entry name.
535 StringRef S = findDefaultEntry();
537 fatal("entry point must be defined");
538 Config->Entry = addUndefined(S);
540 llvm::outs() << "Entry name inferred: " << S << "\n";
544 for (auto *Arg : Args.filtered(OPT_export)) {
545 Export E = parseExport(Arg->getValue());
546 if (Config->Machine == I386) {
547 if (!isDecorated(E.Name))
548 E.Name = Alloc.save("_" + E.Name);
549 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
550 E.ExtName = Alloc.save("_" + E.ExtName);
552 Config->Exports.push_back(E);
556 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
557 MemoryBufferRef MB = openFile(Arg->getValue());
558 // parseModuleDefs mutates Config object.
559 parseModuleDefs(MB, &Alloc);
563 for (auto *Arg : Args.filtered(OPT_delayload)) {
564 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
565 if (Config->Machine == I386) {
566 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
568 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
572 // Set default image base if /base is not given.
573 if (Config->ImageBase == uint64_t(-1))
574 Config->ImageBase = getDefaultImageBase();
576 Symtab.addRelative(mangle("__ImageBase"), 0);
577 if (Config->Machine == I386) {
578 Config->SEHTable = Symtab.addRelative("___safe_se_handler_table", 0);
579 Config->SEHCount = Symtab.addAbsolute("___safe_se_handler_count", 0);
582 // We do not support /guard:cf (control flow protection) yet.
583 // Define CFG symbols anyway so that we can link MSVC 2015 CRT.
584 Symtab.addAbsolute(mangle("__guard_fids_table"), 0);
585 Symtab.addAbsolute(mangle("__guard_fids_count"), 0);
586 Symtab.addAbsolute(mangle("__guard_flags"), 0x100);
588 // Read as much files as we can from directives sections.
591 // Resolve auxiliary symbols until we get a convergence.
592 // (Trying to resolve a symbol may trigger a Lazy symbol to load a new file.
593 // A new file may contain a directive section to add new command line options.
594 // That's why we have to repeat until converge.)
596 // Windows specific -- if entry point is not found,
597 // search for its mangled names.
599 Symtab.mangleMaybe(Config->Entry);
601 // Windows specific -- Make sure we resolve all dllexported symbols.
602 for (Export &E : Config->Exports) {
603 if (!E.ForwardTo.empty())
605 E.Sym = addUndefined(E.Name);
607 Symtab.mangleMaybe(E.Sym);
610 // Add weak aliases. Weak aliases is a mechanism to give remaining
611 // undefined symbols final chance to be resolved successfully.
612 for (auto Pair : Config->AlternateNames) {
613 StringRef From = Pair.first;
614 StringRef To = Pair.second;
615 Symbol *Sym = Symtab.find(From);
618 if (auto *U = dyn_cast<Undefined>(Sym->Body))
620 U->WeakAlias = Symtab.addUndefined(To);
623 // Windows specific -- if __load_config_used can be resolved, resolve it.
624 if (Symtab.findUnderscore("_load_config_used"))
625 addUndefined(mangle("_load_config_used"));
627 if (Symtab.queueEmpty())
632 // Do LTO by compiling bitcode input files to a set of native COFF files then
634 Symtab.addCombinedLTOObjects();
636 // Make sure we have resolved all symbols.
637 Symtab.reportRemainingUndefines(/*Resolve=*/true);
639 // Windows specific -- if no /subsystem is given, we need to infer
640 // that from entry point name.
641 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
642 Config->Subsystem = inferSubsystem();
643 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
644 fatal("subsystem must be defined");
648 if (Args.hasArg(OPT_safeseh))
649 for (ObjectFile *File : Symtab.ObjectFiles)
650 if (!File->SEHCompat)
651 fatal("/safeseh: " + File->getName() + " is not compatible with SEH");
653 // Windows specific -- when we are creating a .dll file, we also
654 // need to create a .lib file.
655 if (!Config->Exports.empty() || Config->DLL) {
657 writeImportLibrary();
658 assignExportOrdinals();
661 // Windows specific -- Create a side-by-side manifest file.
662 if (Config->Manifest == Configuration::SideBySide)
663 createSideBySideManifest();
665 // Create a dummy PDB file to satisfy build sytem rules.
666 if (auto *Arg = Args.getLastArg(OPT_pdb))
667 createPDB(Arg->getValue());
669 // Identify unreferenced COMDAT sections.
671 markLive(Symtab.getChunks());
673 // Identify identical COMDAT sections to merge them.
675 doICF(Symtab.getChunks());
678 writeResult(&Symtab);
680 // Create a symbol map file containing symbol VAs and their names
681 // to help debugging.
682 if (auto *Arg = Args.getLastArg(OPT_lldmap)) {
684 llvm::raw_fd_ostream Out(Arg->getValue(), EC, OpenFlags::F_Text);
686 fatal(EC, "could not create the symbol map");
687 Symtab.printMap(Out);
689 // Call exit to avoid calling destructors.