1 //===- 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 "Driver.h"
11 #include "Config.h"
12 #include "ICF.h"
13 #include "InputFiles.h"
14 #include "MarkLive.h"
15 #include "MinGW.h"
16 #include "SymbolTable.h"
17 #include "Symbols.h"
18 #include "Writer.h"
19 #include "lld/Common/Args.h"
20 #include "lld/Common/Driver.h"
21 #include "lld/Common/ErrorHandler.h"
22 #include "lld/Common/Memory.h"
23 #include "lld/Common/Timer.h"
24 #include "lld/Common/Version.h"
25 #include "llvm/ADT/Optional.h"
26 #include "llvm/ADT/StringSwitch.h"
27 #include "llvm/BinaryFormat/Magic.h"
28 #include "llvm/Object/ArchiveWriter.h"
29 #include "llvm/Object/COFFImportFile.h"
30 #include "llvm/Object/COFFModuleDefinition.h"
31 #include "llvm/Option/Arg.h"
32 #include "llvm/Option/ArgList.h"
33 #include "llvm/Option/Option.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/Path.h"
36 #include "llvm/Support/Process.h"
37 #include "llvm/Support/TarWriter.h"
38 #include "llvm/Support/TargetSelect.h"
39 #include "llvm/Support/raw_ostream.h"
40 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h"
41 #include <algorithm>
42 #include <future>
43 #include <memory>
44
45 using namespace llvm;
46 using namespace llvm::object;
47 using namespace llvm::COFF;
48 using llvm::sys::Process;
49
50 namespace lld {
51 namespace coff {
52
53 static Timer InputFileTimer("Input File Reading", Timer::root());
54
55 Configuration *Config;
56 LinkerDriver *Driver;
57
link(ArrayRef<const char * > Args,bool CanExitEarly,raw_ostream & Diag)58 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) {
59 errorHandler().LogName = sys::path::filename(Args[0]);
60 errorHandler().ErrorOS = &Diag;
61 errorHandler().ColorDiagnostics = Diag.has_colors();
62 errorHandler().ErrorLimitExceededMsg =
63 "too many errors emitted, stopping now"
64 " (use /errorlimit:0 to see all errors)";
65 errorHandler().ExitEarly = CanExitEarly;
66 Config = make<Configuration>();
67
68 Symtab = make<SymbolTable>();
69
70 Driver = make<LinkerDriver>();
71 Driver->link(Args);
72
73 // Call exit() if we can to avoid calling destructors.
74 if (CanExitEarly)
75 exitLld(errorCount() ? 1 : 0);
76
77 freeArena();
78 ObjFile::Instances.clear();
79 ImportFile::Instances.clear();
80 BitcodeFile::Instances.clear();
81 return !errorCount();
82 }
83
84 // Drop directory components and replace extension with ".exe" or ".dll".
getOutputPath(StringRef Path)85 static std::string getOutputPath(StringRef Path) {
86 auto P = Path.find_last_of("\\/");
87 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1);
88 const char* E = Config->DLL ? ".dll" : ".exe";
89 return (S.substr(0, S.rfind('.')) + E).str();
90 }
91
92 // ErrorOr is not default constructible, so it cannot be used as the type
93 // parameter of a future.
94 // FIXME: We could open the file in createFutureForFile and avoid needing to
95 // return an error here, but for the moment that would cost us a file descriptor
96 // (a limited resource on Windows) for the duration that the future is pending.
97 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair;
98
99 // Create a std::future that opens and maps a file using the best strategy for
100 // the host platform.
createFutureForFile(std::string Path)101 static std::future<MBErrPair> createFutureForFile(std::string Path) {
102 #if _WIN32
103 // On Windows, file I/O is relatively slow so it is best to do this
104 // asynchronously.
105 auto Strategy = std::launch::async;
106 #else
107 auto Strategy = std::launch::deferred;
108 #endif
109 return std::async(Strategy, [=]() {
110 auto MBOrErr = MemoryBuffer::getFile(Path,
111 /*FileSize*/ -1,
112 /*RequiresNullTerminator*/ false);
113 if (!MBOrErr)
114 return MBErrPair{nullptr, MBOrErr.getError()};
115 return MBErrPair{std::move(*MBOrErr), std::error_code()};
116 });
117 }
118
119 // Symbol names are mangled by prepending "_" on x86.
mangle(StringRef Sym)120 static StringRef mangle(StringRef Sym) {
121 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN);
122 if (Config->Machine == I386)
123 return Saver.save("_" + Sym);
124 return Sym;
125 }
126
findUnderscoreMangle(StringRef Sym)127 static bool findUnderscoreMangle(StringRef Sym) {
128 StringRef Entry = Symtab->findMangle(mangle(Sym));
129 return !Entry.empty() && !isa<Undefined>(Symtab->find(Entry));
130 }
131
takeBuffer(std::unique_ptr<MemoryBuffer> MB)132 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) {
133 MemoryBufferRef MBRef = *MB;
134 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership
135
136 if (Driver->Tar)
137 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()),
138 MBRef.getBuffer());
139 return MBRef;
140 }
141
addBuffer(std::unique_ptr<MemoryBuffer> MB,bool WholeArchive)142 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB,
143 bool WholeArchive) {
144 StringRef Filename = MB->getBufferIdentifier();
145
146 MemoryBufferRef MBRef = takeBuffer(std::move(MB));
147 FilePaths.push_back(Filename);
148
149 // File type is detected by contents, not by file extension.
150 switch (identify_magic(MBRef.getBuffer())) {
151 case file_magic::windows_resource:
152 Resources.push_back(MBRef);
153 break;
154 case file_magic::archive:
155 if (WholeArchive) {
156 std::unique_ptr<Archive> File =
157 CHECK(Archive::create(MBRef), Filename + ": failed to parse archive");
158
159 for (MemoryBufferRef M : getArchiveMembers(File.get()))
160 addArchiveBuffer(M, "<whole-archive>", Filename);
161 return;
162 }
163 Symtab->addFile(make<ArchiveFile>(MBRef));
164 break;
165 case file_magic::bitcode:
166 Symtab->addFile(make<BitcodeFile>(MBRef));
167 break;
168 case file_magic::coff_object:
169 case file_magic::coff_import_library:
170 Symtab->addFile(make<ObjFile>(MBRef));
171 break;
172 case file_magic::coff_cl_gl_object:
173 error(Filename + ": is not a native COFF file. Recompile without /GL");
174 break;
175 case file_magic::pecoff_executable:
176 if (Filename.endswith_lower(".dll")) {
177 error(Filename + ": bad file type. Did you specify a DLL instead of an "
178 "import library?");
179 break;
180 }
181 LLVM_FALLTHROUGH;
182 default:
183 error(MBRef.getBufferIdentifier() + ": unknown file type");
184 break;
185 }
186 }
187
enqueuePath(StringRef Path,bool WholeArchive)188 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) {
189 auto Future =
190 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path));
191 std::string PathStr = Path;
192 enqueueTask([=]() {
193 auto MBOrErr = Future->get();
194 if (MBOrErr.second)
195 error("could not open " + PathStr + ": " + MBOrErr.second.message());
196 else
197 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive);
198 });
199 }
200
addArchiveBuffer(MemoryBufferRef MB,StringRef SymName,StringRef ParentName)201 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName,
202 StringRef ParentName) {
203 file_magic Magic = identify_magic(MB.getBuffer());
204 if (Magic == file_magic::coff_import_library) {
205 Symtab->addFile(make<ImportFile>(MB));
206 return;
207 }
208
209 InputFile *Obj;
210 if (Magic == file_magic::coff_object) {
211 Obj = make<ObjFile>(MB);
212 } else if (Magic == file_magic::bitcode) {
213 Obj = make<BitcodeFile>(MB);
214 } else {
215 error("unknown file type: " + MB.getBufferIdentifier());
216 return;
217 }
218
219 Obj->ParentName = ParentName;
220 Symtab->addFile(Obj);
221 log("Loaded " + toString(Obj) + " for " + SymName);
222 }
223
enqueueArchiveMember(const Archive::Child & C,StringRef SymName,StringRef ParentName)224 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C,
225 StringRef SymName,
226 StringRef ParentName) {
227 if (!C.getParent()->isThin()) {
228 MemoryBufferRef MB = CHECK(
229 C.getMemoryBufferRef(),
230 "could not get the buffer for the member defining symbol " + SymName);
231 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); });
232 return;
233 }
234
235 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile(
236 CHECK(C.getFullName(),
237 "could not get the filename for the member defining symbol " +
238 SymName)));
239 enqueueTask([=]() {
240 auto MBOrErr = Future->get();
241 if (MBOrErr.second)
242 fatal("could not get the buffer for the member defining " + SymName +
243 ": " + MBOrErr.second.message());
244 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName,
245 ParentName);
246 });
247 }
248
isDecorated(StringRef Sym)249 static bool isDecorated(StringRef Sym) {
250 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") ||
251 (!Config->MinGW && Sym.contains('@'));
252 }
253
254 // Parses .drectve section contents and returns a list of files
255 // specified by /defaultlib.
parseDirectives(StringRef S)256 void LinkerDriver::parseDirectives(StringRef S) {
257 ArgParser Parser;
258 // .drectve is always tokenized using Windows shell rules.
259 // /EXPORT: option can appear too many times, processing in fastpath.
260 opt::InputArgList Args;
261 std::vector<StringRef> Exports;
262 std::tie(Args, Exports) = Parser.parseDirectives(S);
263
264 for (StringRef E : Exports) {
265 // If a common header file contains dllexported function
266 // declarations, many object files may end up with having the
267 // same /EXPORT options. In order to save cost of parsing them,
268 // we dedup them first.
269 if (!DirectivesExports.insert(E).second)
270 continue;
271
272 Export Exp = parseExport(E);
273 if (Config->Machine == I386 && Config->MinGW) {
274 if (!isDecorated(Exp.Name))
275 Exp.Name = Saver.save("_" + Exp.Name);
276 if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName))
277 Exp.ExtName = Saver.save("_" + Exp.ExtName);
278 }
279 Exp.Directives = true;
280 Config->Exports.push_back(Exp);
281 }
282
283 for (auto *Arg : Args) {
284 switch (Arg->getOption().getUnaliasedOption().getID()) {
285 case OPT_aligncomm:
286 parseAligncomm(Arg->getValue());
287 break;
288 case OPT_alternatename:
289 parseAlternateName(Arg->getValue());
290 break;
291 case OPT_defaultlib:
292 if (Optional<StringRef> Path = findLib(Arg->getValue()))
293 enqueuePath(*Path, false);
294 break;
295 case OPT_entry:
296 Config->Entry = addUndefined(mangle(Arg->getValue()));
297 break;
298 case OPT_failifmismatch:
299 checkFailIfMismatch(Arg->getValue());
300 break;
301 case OPT_incl:
302 addUndefined(Arg->getValue());
303 break;
304 case OPT_merge:
305 parseMerge(Arg->getValue());
306 break;
307 case OPT_nodefaultlib:
308 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
309 break;
310 case OPT_section:
311 parseSection(Arg->getValue());
312 break;
313 case OPT_subsystem:
314 parseSubsystem(Arg->getValue(), &Config->Subsystem,
315 &Config->MajorOSVersion, &Config->MinorOSVersion);
316 break;
317 case OPT_editandcontinue:
318 case OPT_fastfail:
319 case OPT_guardsym:
320 case OPT_natvis:
321 case OPT_throwingnew:
322 break;
323 default:
324 error(Arg->getSpelling() + " is not allowed in .drectve");
325 }
326 }
327 }
328
329 // Find file from search paths. You can omit ".obj", this function takes
330 // care of that. Note that the returned path is not guaranteed to exist.
doFindFile(StringRef Filename)331 StringRef LinkerDriver::doFindFile(StringRef Filename) {
332 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos);
333 if (HasPathSep)
334 return Filename;
335 bool HasExt = Filename.contains('.');
336 for (StringRef Dir : SearchPaths) {
337 SmallString<128> Path = Dir;
338 sys::path::append(Path, Filename);
339 if (sys::fs::exists(Path.str()))
340 return Saver.save(Path.str());
341 if (!HasExt) {
342 Path.append(".obj");
343 if (sys::fs::exists(Path.str()))
344 return Saver.save(Path.str());
345 }
346 }
347 return Filename;
348 }
349
getUniqueID(StringRef Path)350 static Optional<sys::fs::UniqueID> getUniqueID(StringRef Path) {
351 sys::fs::UniqueID Ret;
352 if (sys::fs::getUniqueID(Path, Ret))
353 return None;
354 return Ret;
355 }
356
357 // Resolves a file path. This never returns the same path
358 // (in that case, it returns None).
findFile(StringRef Filename)359 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) {
360 StringRef Path = doFindFile(Filename);
361
362 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path)) {
363 bool Seen = !VisitedFiles.insert(*ID).second;
364 if (Seen)
365 return None;
366 }
367
368 if (Path.endswith_lower(".lib"))
369 VisitedLibs.insert(sys::path::filename(Path));
370 return Path;
371 }
372
373 // Find library file from search path.
doFindLib(StringRef Filename)374 StringRef LinkerDriver::doFindLib(StringRef Filename) {
375 // Add ".lib" to Filename if that has no file extension.
376 bool HasExt = Filename.contains('.');
377 if (!HasExt)
378 Filename = Saver.save(Filename + ".lib");
379 return doFindFile(Filename);
380 }
381
382 // Resolves a library path. /nodefaultlib options are taken into
383 // consideration. This never returns the same path (in that case,
384 // it returns None).
findLib(StringRef Filename)385 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) {
386 if (Config->NoDefaultLibAll)
387 return None;
388 if (!VisitedLibs.insert(Filename.lower()).second)
389 return None;
390
391 StringRef Path = doFindLib(Filename);
392 if (Config->NoDefaultLibs.count(Path))
393 return None;
394
395 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
396 if (!VisitedFiles.insert(*ID).second)
397 return None;
398 return Path;
399 }
400
401 // Parses LIB environment which contains a list of search paths.
addLibSearchPaths()402 void LinkerDriver::addLibSearchPaths() {
403 Optional<std::string> EnvOpt = Process::GetEnv("LIB");
404 if (!EnvOpt.hasValue())
405 return;
406 StringRef Env = Saver.save(*EnvOpt);
407 while (!Env.empty()) {
408 StringRef Path;
409 std::tie(Path, Env) = Env.split(';');
410 SearchPaths.push_back(Path);
411 }
412 }
413
addUndefined(StringRef Name)414 Symbol *LinkerDriver::addUndefined(StringRef Name) {
415 Symbol *B = Symtab->addUndefined(Name);
416 if (!B->IsGCRoot) {
417 B->IsGCRoot = true;
418 Config->GCRoot.push_back(B);
419 }
420 return B;
421 }
422
423 // Windows specific -- find default entry point name.
424 //
425 // There are four different entry point functions for Windows executables,
426 // each of which corresponds to a user-defined "main" function. This function
427 // infers an entry point from a user-defined "main" function.
findDefaultEntry()428 StringRef LinkerDriver::findDefaultEntry() {
429 assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN &&
430 "must handle /subsystem before calling this");
431
432 // As a special case, if /nodefaultlib is given, we directly look for an
433 // entry point. This is because, if no default library is linked, users
434 // need to define an entry point instead of a "main".
435 bool FindMain = !Config->NoDefaultLibAll;
436 if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) {
437 if (findUnderscoreMangle(FindMain ? "WinMain" : "WinMainCRTStartup"))
438 return mangle("WinMainCRTStartup");
439 if (findUnderscoreMangle(FindMain ? "wWinMain" : "wWinMainCRTStartup"))
440 return mangle("wWinMainCRTStartup");
441 }
442 if (findUnderscoreMangle(FindMain ? "main" : "mainCRTStartup"))
443 return mangle("mainCRTStartup");
444 if (findUnderscoreMangle(FindMain ? "wmain" : "wmainCRTStartup"))
445 return mangle("wmainCRTStartup");
446 return "";
447 }
448
inferSubsystem()449 WindowsSubsystem LinkerDriver::inferSubsystem() {
450 if (Config->DLL)
451 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
452 if (findUnderscoreMangle("main") || findUnderscoreMangle("wmain"))
453 return IMAGE_SUBSYSTEM_WINDOWS_CUI;
454 if (findUnderscoreMangle("WinMain") || findUnderscoreMangle("wWinMain"))
455 return IMAGE_SUBSYSTEM_WINDOWS_GUI;
456 return IMAGE_SUBSYSTEM_UNKNOWN;
457 }
458
getDefaultImageBase()459 static uint64_t getDefaultImageBase() {
460 if (Config->is64())
461 return Config->DLL ? 0x180000000 : 0x140000000;
462 return Config->DLL ? 0x10000000 : 0x400000;
463 }
464
createResponseFile(const opt::InputArgList & Args,ArrayRef<StringRef> FilePaths,ArrayRef<StringRef> SearchPaths)465 static std::string createResponseFile(const opt::InputArgList &Args,
466 ArrayRef<StringRef> FilePaths,
467 ArrayRef<StringRef> SearchPaths) {
468 SmallString<0> Data;
469 raw_svector_ostream OS(Data);
470
471 for (auto *Arg : Args) {
472 switch (Arg->getOption().getID()) {
473 case OPT_linkrepro:
474 case OPT_INPUT:
475 case OPT_defaultlib:
476 case OPT_libpath:
477 case OPT_manifest:
478 case OPT_manifest_colon:
479 case OPT_manifestdependency:
480 case OPT_manifestfile:
481 case OPT_manifestinput:
482 case OPT_manifestuac:
483 break;
484 default:
485 OS << toString(*Arg) << "\n";
486 }
487 }
488
489 for (StringRef Path : SearchPaths) {
490 std::string RelPath = relativeToRoot(Path);
491 OS << "/libpath:" << quote(RelPath) << "\n";
492 }
493
494 for (StringRef Path : FilePaths)
495 OS << quote(relativeToRoot(Path)) << "\n";
496
497 return Data.str();
498 }
499
getDefaultDebugType(const opt::InputArgList & Args)500 static unsigned getDefaultDebugType(const opt::InputArgList &Args) {
501 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV);
502 if (Args.hasArg(OPT_driver))
503 DebugTypes |= static_cast<unsigned>(DebugType::PData);
504 if (Args.hasArg(OPT_profile))
505 DebugTypes |= static_cast<unsigned>(DebugType::Fixup);
506 return DebugTypes;
507 }
508
parseDebugType(StringRef Arg)509 static unsigned parseDebugType(StringRef Arg) {
510 SmallVector<StringRef, 3> Types;
511 Arg.split(Types, ',', /*KeepEmpty=*/false);
512
513 unsigned DebugTypes = static_cast<unsigned>(DebugType::None);
514 for (StringRef Type : Types)
515 DebugTypes |= StringSwitch<unsigned>(Type.lower())
516 .Case("cv", static_cast<unsigned>(DebugType::CV))
517 .Case("pdata", static_cast<unsigned>(DebugType::PData))
518 .Case("fixup", static_cast<unsigned>(DebugType::Fixup))
519 .Default(0);
520 return DebugTypes;
521 }
522
getMapFile(const opt::InputArgList & Args)523 static std::string getMapFile(const opt::InputArgList &Args) {
524 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file);
525 if (!Arg)
526 return "";
527 if (Arg->getOption().getID() == OPT_lldmap_file)
528 return Arg->getValue();
529
530 assert(Arg->getOption().getID() == OPT_lldmap);
531 StringRef OutFile = Config->OutputFile;
532 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str();
533 }
534
getImplibPath()535 static std::string getImplibPath() {
536 if (!Config->Implib.empty())
537 return Config->Implib;
538 SmallString<128> Out = StringRef(Config->OutputFile);
539 sys::path::replace_extension(Out, ".lib");
540 return Out.str();
541 }
542
543 //
544 // The import name is caculated as the following:
545 //
546 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY
547 // -----+----------------+---------------------+------------------
548 // LINK | {value} | {value}.{.dll/.exe} | {output name}
549 // LIB | {value} | {value}.dll | {output name}.dll
550 //
getImportName(bool AsLib)551 static std::string getImportName(bool AsLib) {
552 SmallString<128> Out;
553
554 if (Config->ImportName.empty()) {
555 Out.assign(sys::path::filename(Config->OutputFile));
556 if (AsLib)
557 sys::path::replace_extension(Out, ".dll");
558 } else {
559 Out.assign(Config->ImportName);
560 if (!sys::path::has_extension(Out))
561 sys::path::replace_extension(Out,
562 (Config->DLL || AsLib) ? ".dll" : ".exe");
563 }
564
565 return Out.str();
566 }
567
createImportLibrary(bool AsLib)568 static void createImportLibrary(bool AsLib) {
569 std::vector<COFFShortExport> Exports;
570 for (Export &E1 : Config->Exports) {
571 COFFShortExport E2;
572 E2.Name = E1.Name;
573 E2.SymbolName = E1.SymbolName;
574 E2.ExtName = E1.ExtName;
575 E2.Ordinal = E1.Ordinal;
576 E2.Noname = E1.Noname;
577 E2.Data = E1.Data;
578 E2.Private = E1.Private;
579 E2.Constant = E1.Constant;
580 Exports.push_back(E2);
581 }
582
583 auto HandleError = [](Error &&E) {
584 handleAllErrors(std::move(E),
585 [](ErrorInfoBase &EIB) { error(EIB.message()); });
586 };
587 std::string LibName = getImportName(AsLib);
588 std::string Path = getImplibPath();
589
590 if (!Config->Incremental) {
591 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
592 Config->MinGW));
593 return;
594 }
595
596 // If the import library already exists, replace it only if the contents
597 // have changed.
598 ErrorOr<std::unique_ptr<MemoryBuffer>> OldBuf = MemoryBuffer::getFile(
599 Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false);
600 if (!OldBuf) {
601 HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine,
602 Config->MinGW));
603 return;
604 }
605
606 SmallString<128> TmpName;
607 if (std::error_code EC =
608 sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName))
609 fatal("cannot create temporary file for import library " + Path + ": " +
610 EC.message());
611
612 if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine,
613 Config->MinGW)) {
614 HandleError(std::move(E));
615 return;
616 }
617
618 std::unique_ptr<MemoryBuffer> NewBuf = check(MemoryBuffer::getFile(
619 TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false));
620 if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) {
621 OldBuf->reset();
622 HandleError(errorCodeToError(sys::fs::rename(TmpName, Path)));
623 } else {
624 sys::fs::remove(TmpName);
625 }
626 }
627
parseModuleDefs(StringRef Path)628 static void parseModuleDefs(StringRef Path) {
629 std::unique_ptr<MemoryBuffer> MB = CHECK(
630 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
631 COFFModuleDefinition M = check(parseCOFFModuleDefinition(
632 MB->getMemBufferRef(), Config->Machine, Config->MinGW));
633
634 if (Config->OutputFile.empty())
635 Config->OutputFile = Saver.save(M.OutputFile);
636 Config->ImportName = Saver.save(M.ImportName);
637 if (M.ImageBase)
638 Config->ImageBase = M.ImageBase;
639 if (M.StackReserve)
640 Config->StackReserve = M.StackReserve;
641 if (M.StackCommit)
642 Config->StackCommit = M.StackCommit;
643 if (M.HeapReserve)
644 Config->HeapReserve = M.HeapReserve;
645 if (M.HeapCommit)
646 Config->HeapCommit = M.HeapCommit;
647 if (M.MajorImageVersion)
648 Config->MajorImageVersion = M.MajorImageVersion;
649 if (M.MinorImageVersion)
650 Config->MinorImageVersion = M.MinorImageVersion;
651 if (M.MajorOSVersion)
652 Config->MajorOSVersion = M.MajorOSVersion;
653 if (M.MinorOSVersion)
654 Config->MinorOSVersion = M.MinorOSVersion;
655
656 for (COFFShortExport E1 : M.Exports) {
657 Export E2;
658 // In simple cases, only Name is set. Renamed exports are parsed
659 // and set as "ExtName = Name". If Name has the form "OtherDll.Func",
660 // it shouldn't be a normal exported function but a forward to another
661 // DLL instead. This is supported by both MS and GNU linkers.
662 if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) {
663 E2.Name = Saver.save(E1.ExtName);
664 E2.ForwardTo = Saver.save(E1.Name);
665 Config->Exports.push_back(E2);
666 continue;
667 }
668 E2.Name = Saver.save(E1.Name);
669 E2.ExtName = Saver.save(E1.ExtName);
670 E2.Ordinal = E1.Ordinal;
671 E2.Noname = E1.Noname;
672 E2.Data = E1.Data;
673 E2.Private = E1.Private;
674 E2.Constant = E1.Constant;
675 Config->Exports.push_back(E2);
676 }
677 }
678
679 // A helper function for filterBitcodeFiles.
needsRebuilding(MemoryBufferRef MB)680 static bool needsRebuilding(MemoryBufferRef MB) {
681 // The MSVC linker doesn't support thin archives, so if it's a thin
682 // archive, we always need to rebuild it.
683 std::unique_ptr<Archive> File =
684 CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier());
685 if (File->isThin())
686 return true;
687
688 // Returns true if the archive contains at least one bitcode file.
689 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
690 if (identify_magic(Member.getBuffer()) == file_magic::bitcode)
691 return true;
692 return false;
693 }
694
695 // Opens a given path as an archive file and removes bitcode files
696 // from them if exists. This function is to appease the MSVC linker as
697 // their linker doesn't like archive files containing non-native
698 // object files.
699 //
700 // If a given archive doesn't contain bitcode files, the archive path
701 // is returned as-is. Otherwise, a new temporary file is created and
702 // its path is returned.
703 static Optional<std::string>
filterBitcodeFiles(StringRef Path,std::vector<std::string> & TemporaryFiles)704 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) {
705 std::unique_ptr<MemoryBuffer> MB = CHECK(
706 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
707 MemoryBufferRef MBRef = MB->getMemBufferRef();
708 file_magic Magic = identify_magic(MBRef.getBuffer());
709
710 if (Magic == file_magic::bitcode)
711 return None;
712 if (Magic != file_magic::archive)
713 return Path.str();
714 if (!needsRebuilding(MBRef))
715 return Path.str();
716
717 std::unique_ptr<Archive> File =
718 CHECK(Archive::create(MBRef),
719 MBRef.getBufferIdentifier() + ": failed to parse archive");
720
721 std::vector<NewArchiveMember> New;
722 for (MemoryBufferRef Member : getArchiveMembers(File.get()))
723 if (identify_magic(Member.getBuffer()) != file_magic::bitcode)
724 New.emplace_back(Member);
725
726 if (New.empty())
727 return None;
728
729 log("Creating a temporary archive for " + Path + " to remove bitcode files");
730
731 SmallString<128> S;
732 if (std::error_code EC = sys::fs::createTemporaryFile(
733 "lld-" + sys::path::stem(Path), ".lib", S))
734 fatal("cannot create a temporary file: " + EC.message());
735 std::string Temp = S.str();
736 TemporaryFiles.push_back(Temp);
737
738 Error E =
739 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU,
740 /*Deterministics=*/true,
741 /*Thin=*/false);
742 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) {
743 error("failed to create a new archive " + S.str() + ": " + EI.message());
744 });
745 return Temp;
746 }
747
748 // Create response file contents and invoke the MSVC linker.
invokeMSVC(opt::InputArgList & Args)749 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) {
750 std::string Rsp = "/nologo\n";
751 std::vector<std::string> Temps;
752
753 // Write out archive members that we used in symbol resolution and pass these
754 // to MSVC before any archives, so that MSVC uses the same objects to satisfy
755 // references.
756 for (ObjFile *Obj : ObjFile::Instances) {
757 if (Obj->ParentName.empty())
758 continue;
759 SmallString<128> S;
760 int Fd;
761 if (auto EC = sys::fs::createTemporaryFile(
762 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S))
763 fatal("cannot create a temporary file: " + EC.message());
764 raw_fd_ostream OS(Fd, /*shouldClose*/ true);
765 OS << Obj->MB.getBuffer();
766 Temps.push_back(S.str());
767 Rsp += quote(S) + "\n";
768 }
769
770 for (auto *Arg : Args) {
771 switch (Arg->getOption().getID()) {
772 case OPT_linkrepro:
773 case OPT_lldmap:
774 case OPT_lldmap_file:
775 case OPT_lldsavetemps:
776 case OPT_msvclto:
777 // LLD-specific options are stripped.
778 break;
779 case OPT_opt:
780 if (!StringRef(Arg->getValue()).startswith("lld"))
781 Rsp += toString(*Arg) + " ";
782 break;
783 case OPT_INPUT: {
784 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) {
785 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps))
786 Rsp += quote(*S) + "\n";
787 continue;
788 }
789 Rsp += quote(Arg->getValue()) + "\n";
790 break;
791 }
792 default:
793 Rsp += toString(*Arg) + "\n";
794 }
795 }
796
797 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles();
798 runMSVCLinker(Rsp, ObjFiles);
799
800 for (StringRef Path : Temps)
801 sys::fs::remove(Path);
802 }
803
enqueueTask(std::function<void ()> Task)804 void LinkerDriver::enqueueTask(std::function<void()> Task) {
805 TaskQueue.push_back(std::move(Task));
806 }
807
run()808 bool LinkerDriver::run() {
809 ScopedTimer T(InputFileTimer);
810
811 bool DidWork = !TaskQueue.empty();
812 while (!TaskQueue.empty()) {
813 TaskQueue.front()();
814 TaskQueue.pop_front();
815 }
816 return DidWork;
817 }
818
819 // Parse an /order file. If an option is given, the linker places
820 // COMDAT sections in the same order as their names appear in the
821 // given file.
parseOrderFile(StringRef Arg)822 static void parseOrderFile(StringRef Arg) {
823 // For some reason, the MSVC linker requires a filename to be
824 // preceded by "@".
825 if (!Arg.startswith("@")) {
826 error("malformed /order option: '@' missing");
827 return;
828 }
829
830 // Get a list of all comdat sections for error checking.
831 DenseSet<StringRef> Set;
832 for (Chunk *C : Symtab->getChunks())
833 if (auto *Sec = dyn_cast<SectionChunk>(C))
834 if (Sec->Sym)
835 Set.insert(Sec->Sym->getName());
836
837 // Open a file.
838 StringRef Path = Arg.substr(1);
839 std::unique_ptr<MemoryBuffer> MB = CHECK(
840 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path);
841
842 // Parse a file. An order file contains one symbol per line.
843 // All symbols that were not present in a given order file are
844 // considered to have the lowest priority 0 and are placed at
845 // end of an output section.
846 for (std::string S : args::getLines(MB->getMemBufferRef())) {
847 if (Config->Machine == I386 && !isDecorated(S))
848 S = "_" + S;
849
850 if (Set.count(S) == 0) {
851 if (Config->WarnMissingOrderSymbol)
852 warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]");
853 }
854 else
855 Config->Order[S] = INT_MIN + Config->Order.size();
856 }
857 }
858
link(ArrayRef<const char * > ArgsArr)859 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) {
860 // If the first command line argument is "/lib", link.exe acts like lib.exe.
861 // We call our own implementation of lib.exe that understands bitcode files.
862 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) {
863 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0)
864 fatal("lib failed");
865 return;
866 }
867
868 // Needed for LTO.
869 InitializeAllTargetInfos();
870 InitializeAllTargets();
871 InitializeAllTargetMCs();
872 InitializeAllAsmParsers();
873 InitializeAllAsmPrinters();
874
875 // Parse command line options.
876 ArgParser Parser;
877 opt::InputArgList Args = Parser.parseLINK(ArgsArr);
878
879 // Parse and evaluate -mllvm options.
880 std::vector<const char *> V;
881 V.push_back("lld-link (LLVM option parsing)");
882 for (auto *Arg : Args.filtered(OPT_mllvm))
883 V.push_back(Arg->getValue());
884 cl::ParseCommandLineOptions(V.size(), V.data());
885
886 // Handle /errorlimit early, because error() depends on it.
887 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) {
888 int N = 20;
889 StringRef S = Arg->getValue();
890 if (S.getAsInteger(10, N))
891 error(Arg->getSpelling() + " number expected, but got " + S);
892 errorHandler().ErrorLimit = N;
893 }
894
895 // Handle /help
896 if (Args.hasArg(OPT_help)) {
897 printHelp(ArgsArr[0]);
898 return;
899 }
900
901 if (Args.hasArg(OPT_show_timing))
902 Config->ShowTiming = true;
903
904 ScopedTimer T(Timer::root());
905 // Handle --version, which is an lld extension. This option is a bit odd
906 // because it doesn't start with "/", but we deliberately chose "--" to
907 // avoid conflict with /version and for compatibility with clang-cl.
908 if (Args.hasArg(OPT_dash_dash_version)) {
909 outs() << getLLDVersion() << "\n";
910 return;
911 }
912
913 // Handle /lldmingw early, since it can potentially affect how other
914 // options are handled.
915 Config->MinGW = Args.hasArg(OPT_lldmingw);
916
917 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) {
918 SmallString<64> Path = StringRef(Arg->getValue());
919 sys::path::append(Path, "repro.tar");
920
921 Expected<std::unique_ptr<TarWriter>> ErrOrWriter =
922 TarWriter::create(Path, "repro");
923
924 if (ErrOrWriter) {
925 Tar = std::move(*ErrOrWriter);
926 } else {
927 error("/linkrepro: failed to open " + Path + ": " +
928 toString(ErrOrWriter.takeError()));
929 }
930 }
931
932 if (!Args.hasArg(OPT_INPUT)) {
933 if (Args.hasArg(OPT_deffile))
934 Config->NoEntry = true;
935 else
936 fatal("no input files");
937 }
938
939 // Construct search path list.
940 SearchPaths.push_back("");
941 for (auto *Arg : Args.filtered(OPT_libpath))
942 SearchPaths.push_back(Arg->getValue());
943 addLibSearchPaths();
944
945 // Handle /ignore
946 for (auto *Arg : Args.filtered(OPT_ignore)) {
947 if (StringRef(Arg->getValue()) == "4037")
948 Config->WarnMissingOrderSymbol = false;
949 else if (StringRef(Arg->getValue()) == "4217")
950 Config->WarnLocallyDefinedImported = false;
951 // Other warning numbers are ignored.
952 }
953
954 // Handle /out
955 if (auto *Arg = Args.getLastArg(OPT_out))
956 Config->OutputFile = Arg->getValue();
957
958 // Handle /verbose
959 if (Args.hasArg(OPT_verbose))
960 Config->Verbose = true;
961 errorHandler().Verbose = Config->Verbose;
962
963 // Handle /force or /force:unresolved
964 if (Args.hasArg(OPT_force, OPT_force_unresolved))
965 Config->Force = true;
966
967 // Handle /debug
968 if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) {
969 Config->Debug = true;
970 Config->Incremental = true;
971 if (auto *Arg = Args.getLastArg(OPT_debugtype))
972 Config->DebugTypes = parseDebugType(Arg->getValue());
973 else
974 Config->DebugTypes = getDefaultDebugType(Args);
975 }
976
977 // Handle /pdb
978 bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash);
979 if (ShouldCreatePDB) {
980 if (auto *Arg = Args.getLastArg(OPT_pdb))
981 Config->PDBPath = Arg->getValue();
982 if (auto *Arg = Args.getLastArg(OPT_pdbaltpath))
983 Config->PDBAltPath = Arg->getValue();
984 if (Args.hasArg(OPT_natvis))
985 Config->NatvisFiles = Args.getAllArgValues(OPT_natvis);
986
987 if (auto *Arg = Args.getLastArg(OPT_pdb_source_path))
988 Config->PDBSourcePath = Arg->getValue();
989 }
990
991 // Handle /noentry
992 if (Args.hasArg(OPT_noentry)) {
993 if (Args.hasArg(OPT_dll))
994 Config->NoEntry = true;
995 else
996 error("/noentry must be specified with /dll");
997 }
998
999 // Handle /dll
1000 if (Args.hasArg(OPT_dll)) {
1001 Config->DLL = true;
1002 Config->ManifestID = 2;
1003 }
1004
1005 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase
1006 // because we need to explicitly check whether that option or its inverse was
1007 // present in the argument list in order to handle /fixed.
1008 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no);
1009 if (DynamicBaseArg &&
1010 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no)
1011 Config->DynamicBase = false;
1012
1013 // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the
1014 // default setting for any other project type.", but link.exe defaults to
1015 // /FIXED:NO for exe outputs as well. Match behavior, not docs.
1016 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false);
1017 if (Fixed) {
1018 if (DynamicBaseArg &&
1019 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) {
1020 error("/fixed must not be specified with /dynamicbase");
1021 } else {
1022 Config->Relocatable = false;
1023 Config->DynamicBase = false;
1024 }
1025 }
1026
1027 // Handle /appcontainer
1028 Config->AppContainer =
1029 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false);
1030
1031 // Handle /machine
1032 if (auto *Arg = Args.getLastArg(OPT_machine))
1033 Config->Machine = getMachineType(Arg->getValue());
1034
1035 // Handle /nodefaultlib:<filename>
1036 for (auto *Arg : Args.filtered(OPT_nodefaultlib))
1037 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue()));
1038
1039 // Handle /nodefaultlib
1040 if (Args.hasArg(OPT_nodefaultlib_all))
1041 Config->NoDefaultLibAll = true;
1042
1043 // Handle /base
1044 if (auto *Arg = Args.getLastArg(OPT_base))
1045 parseNumbers(Arg->getValue(), &Config->ImageBase);
1046
1047 // Handle /stack
1048 if (auto *Arg = Args.getLastArg(OPT_stack))
1049 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit);
1050
1051 // Handle /guard:cf
1052 if (auto *Arg = Args.getLastArg(OPT_guard))
1053 parseGuard(Arg->getValue());
1054
1055 // Handle /heap
1056 if (auto *Arg = Args.getLastArg(OPT_heap))
1057 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit);
1058
1059 // Handle /version
1060 if (auto *Arg = Args.getLastArg(OPT_version))
1061 parseVersion(Arg->getValue(), &Config->MajorImageVersion,
1062 &Config->MinorImageVersion);
1063
1064 // Handle /subsystem
1065 if (auto *Arg = Args.getLastArg(OPT_subsystem))
1066 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion,
1067 &Config->MinorOSVersion);
1068
1069 // Handle /timestamp
1070 if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) {
1071 if (Arg->getOption().getID() == OPT_repro) {
1072 Config->Timestamp = 0;
1073 Config->Repro = true;
1074 } else {
1075 Config->Repro = false;
1076 StringRef Value(Arg->getValue());
1077 if (Value.getAsInteger(0, Config->Timestamp))
1078 fatal(Twine("invalid timestamp: ") + Value +
1079 ". Expected 32-bit integer");
1080 }
1081 } else {
1082 Config->Repro = false;
1083 Config->Timestamp = time(nullptr);
1084 }
1085
1086 // Handle /alternatename
1087 for (auto *Arg : Args.filtered(OPT_alternatename))
1088 parseAlternateName(Arg->getValue());
1089
1090 // Handle /include
1091 for (auto *Arg : Args.filtered(OPT_incl))
1092 addUndefined(Arg->getValue());
1093
1094 // Handle /implib
1095 if (auto *Arg = Args.getLastArg(OPT_implib))
1096 Config->Implib = Arg->getValue();
1097
1098 // Handle /opt.
1099 bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile);
1100 unsigned ICFLevel =
1101 Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on
1102 unsigned TailMerge = 1;
1103 for (auto *Arg : Args.filtered(OPT_opt)) {
1104 std::string Str = StringRef(Arg->getValue()).lower();
1105 SmallVector<StringRef, 1> Vec;
1106 StringRef(Str).split(Vec, ',');
1107 for (StringRef S : Vec) {
1108 if (S == "ref") {
1109 DoGC = true;
1110 } else if (S == "noref") {
1111 DoGC = false;
1112 } else if (S == "icf" || S.startswith("icf=")) {
1113 ICFLevel = 2;
1114 } else if (S == "noicf") {
1115 ICFLevel = 0;
1116 } else if (S == "lldtailmerge") {
1117 TailMerge = 2;
1118 } else if (S == "nolldtailmerge") {
1119 TailMerge = 0;
1120 } else if (S.startswith("lldlto=")) {
1121 StringRef OptLevel = S.substr(7);
1122 if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3)
1123 error("/opt:lldlto: invalid optimization level: " + OptLevel);
1124 } else if (S.startswith("lldltojobs=")) {
1125 StringRef Jobs = S.substr(11);
1126 if (Jobs.getAsInteger(10, Config->ThinLTOJobs) ||
1127 Config->ThinLTOJobs == 0)
1128 error("/opt:lldltojobs: invalid job count: " + Jobs);
1129 } else if (S.startswith("lldltopartitions=")) {
1130 StringRef N = S.substr(17);
1131 if (N.getAsInteger(10, Config->LTOPartitions) ||
1132 Config->LTOPartitions == 0)
1133 error("/opt:lldltopartitions: invalid partition count: " + N);
1134 } else if (S != "lbr" && S != "nolbr")
1135 error("/opt: unknown option: " + S);
1136 }
1137 }
1138
1139 // Limited ICF is enabled if GC is enabled and ICF was never mentioned
1140 // explicitly.
1141 // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical
1142 // code. If the user passes /OPT:ICF explicitly, LLD should merge identical
1143 // comdat readonly data.
1144 if (ICFLevel == 1 && !DoGC)
1145 ICFLevel = 0;
1146 Config->DoGC = DoGC;
1147 Config->DoICF = ICFLevel > 0;
1148 Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2;
1149
1150 // Handle /lldsavetemps
1151 if (Args.hasArg(OPT_lldsavetemps))
1152 Config->SaveTemps = true;
1153
1154 // Handle /kill-at
1155 if (Args.hasArg(OPT_kill_at))
1156 Config->KillAt = true;
1157
1158 // Handle /lldltocache
1159 if (auto *Arg = Args.getLastArg(OPT_lldltocache))
1160 Config->LTOCache = Arg->getValue();
1161
1162 // Handle /lldsavecachepolicy
1163 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy))
1164 Config->LTOCachePolicy = CHECK(
1165 parseCachePruningPolicy(Arg->getValue()),
1166 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue());
1167
1168 // Handle /failifmismatch
1169 for (auto *Arg : Args.filtered(OPT_failifmismatch))
1170 checkFailIfMismatch(Arg->getValue());
1171
1172 // Handle /merge
1173 for (auto *Arg : Args.filtered(OPT_merge))
1174 parseMerge(Arg->getValue());
1175
1176 // Add default section merging rules after user rules. User rules take
1177 // precedence, but we will emit a warning if there is a conflict.
1178 parseMerge(".idata=.rdata");
1179 parseMerge(".didat=.rdata");
1180 parseMerge(".edata=.rdata");
1181 parseMerge(".xdata=.rdata");
1182 parseMerge(".bss=.data");
1183
1184 // Handle /section
1185 for (auto *Arg : Args.filtered(OPT_section))
1186 parseSection(Arg->getValue());
1187
1188 // Handle /aligncomm
1189 for (auto *Arg : Args.filtered(OPT_aligncomm))
1190 parseAligncomm(Arg->getValue());
1191
1192 // Handle /manifestdependency. This enables /manifest unless /manifest:no is
1193 // also passed.
1194 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) {
1195 Config->ManifestDependency = Arg->getValue();
1196 Config->Manifest = Configuration::SideBySide;
1197 }
1198
1199 // Handle /manifest and /manifest:
1200 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) {
1201 if (Arg->getOption().getID() == OPT_manifest)
1202 Config->Manifest = Configuration::SideBySide;
1203 else
1204 parseManifest(Arg->getValue());
1205 }
1206
1207 // Handle /manifestuac
1208 if (auto *Arg = Args.getLastArg(OPT_manifestuac))
1209 parseManifestUAC(Arg->getValue());
1210
1211 // Handle /manifestfile
1212 if (auto *Arg = Args.getLastArg(OPT_manifestfile))
1213 Config->ManifestFile = Arg->getValue();
1214
1215 // Handle /manifestinput
1216 for (auto *Arg : Args.filtered(OPT_manifestinput))
1217 Config->ManifestInput.push_back(Arg->getValue());
1218
1219 if (!Config->ManifestInput.empty() &&
1220 Config->Manifest != Configuration::Embed) {
1221 fatal("/manifestinput: requires /manifest:embed");
1222 }
1223
1224 // Handle miscellaneous boolean flags.
1225 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true);
1226 Config->AllowIsolation =
1227 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true);
1228 Config->Incremental =
1229 Args.hasFlag(OPT_incremental, OPT_incremental_no,
1230 !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) &&
1231 !Args.hasArg(OPT_profile));
1232 Config->IntegrityCheck =
1233 Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false);
1234 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true);
1235 Config->TerminalServerAware =
1236 !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true);
1237 Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf);
1238 Config->DebugGHashes = Args.hasArg(OPT_debug_ghash);
1239 Config->DebugSymtab = Args.hasArg(OPT_debug_symtab);
1240
1241 Config->MapFile = getMapFile(Args);
1242
1243 if (Config->Incremental && Args.hasArg(OPT_profile)) {
1244 warn("ignoring '/incremental' due to '/profile' specification");
1245 Config->Incremental = false;
1246 }
1247
1248 if (Config->Incremental && Args.hasArg(OPT_order)) {
1249 warn("ignoring '/incremental' due to '/order' specification");
1250 Config->Incremental = false;
1251 }
1252
1253 if (Config->Incremental && Config->DoGC) {
1254 warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to "
1255 "disable");
1256 Config->Incremental = false;
1257 }
1258
1259 if (Config->Incremental && Config->DoICF) {
1260 warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to "
1261 "disable");
1262 Config->Incremental = false;
1263 }
1264
1265 if (errorCount())
1266 return;
1267
1268 std::set<sys::fs::UniqueID> WholeArchives;
1269 for (auto *Arg : Args.filtered(OPT_wholearchive_file))
1270 if (Optional<StringRef> Path = doFindFile(Arg->getValue()))
1271 if (Optional<sys::fs::UniqueID> ID = getUniqueID(*Path))
1272 WholeArchives.insert(*ID);
1273
1274 // A predicate returning true if a given path is an argument for
1275 // /wholearchive:, or /wholearchive is enabled globally.
1276 // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj"
1277 // needs to be handled as "/wholearchive:foo.obj foo.obj".
1278 auto IsWholeArchive = [&](StringRef Path) -> bool {
1279 if (Args.hasArg(OPT_wholearchive_flag))
1280 return true;
1281 if (Optional<sys::fs::UniqueID> ID = getUniqueID(Path))
1282 return WholeArchives.count(*ID);
1283 return false;
1284 };
1285
1286 // Create a list of input files. Files can be given as arguments
1287 // for /defaultlib option.
1288 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file))
1289 if (Optional<StringRef> Path = findFile(Arg->getValue()))
1290 enqueuePath(*Path, IsWholeArchive(*Path));
1291
1292 for (auto *Arg : Args.filtered(OPT_defaultlib))
1293 if (Optional<StringRef> Path = findLib(Arg->getValue()))
1294 enqueuePath(*Path, false);
1295
1296 // Windows specific -- Create a resource file containing a manifest file.
1297 if (Config->Manifest == Configuration::Embed)
1298 addBuffer(createManifestRes(), false);
1299
1300 // Read all input files given via the command line.
1301 run();
1302
1303 // We should have inferred a machine type by now from the input files, but if
1304 // not we assume x64.
1305 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) {
1306 warn("/machine is not specified. x64 is assumed");
1307 Config->Machine = AMD64;
1308 }
1309
1310 // Input files can be Windows resource files (.res files). We use
1311 // WindowsResource to convert resource files to a regular COFF file,
1312 // then link the resulting file normally.
1313 if (!Resources.empty())
1314 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources)));
1315
1316 if (Tar)
1317 Tar->append("response.txt",
1318 createResponseFile(Args, FilePaths,
1319 ArrayRef<StringRef>(SearchPaths).slice(1)));
1320
1321 // Handle /largeaddressaware
1322 Config->LargeAddressAware = Args.hasFlag(
1323 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64());
1324
1325 // Handle /highentropyva
1326 Config->HighEntropyVA =
1327 Config->is64() &&
1328 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true);
1329
1330 if (!Config->DynamicBase &&
1331 (Config->Machine == ARMNT || Config->Machine == ARM64))
1332 error("/dynamicbase:no is not compatible with " +
1333 machineToStr(Config->Machine));
1334
1335 // Handle /export
1336 for (auto *Arg : Args.filtered(OPT_export)) {
1337 Export E = parseExport(Arg->getValue());
1338 if (Config->Machine == I386) {
1339 if (!isDecorated(E.Name))
1340 E.Name = Saver.save("_" + E.Name);
1341 if (!E.ExtName.empty() && !isDecorated(E.ExtName))
1342 E.ExtName = Saver.save("_" + E.ExtName);
1343 }
1344 Config->Exports.push_back(E);
1345 }
1346
1347 // Handle /def
1348 if (auto *Arg = Args.getLastArg(OPT_deffile)) {
1349 // parseModuleDefs mutates Config object.
1350 parseModuleDefs(Arg->getValue());
1351 }
1352
1353 // Handle generation of import library from a def file.
1354 if (!Args.hasArg(OPT_INPUT)) {
1355 fixupExports();
1356 createImportLibrary(/*AsLib=*/true);
1357 return;
1358 }
1359
1360 // Windows specific -- if no /subsystem is given, we need to infer
1361 // that from entry point name. Must happen before /entry handling,
1362 // and after the early return when just writing an import library.
1363 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) {
1364 Config->Subsystem = inferSubsystem();
1365 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN)
1366 fatal("subsystem must be defined");
1367 }
1368
1369 // Handle /entry and /dll
1370 if (auto *Arg = Args.getLastArg(OPT_entry)) {
1371 Config->Entry = addUndefined(mangle(Arg->getValue()));
1372 } else if (!Config->Entry && !Config->NoEntry) {
1373 if (Args.hasArg(OPT_dll)) {
1374 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12"
1375 : "_DllMainCRTStartup";
1376 Config->Entry = addUndefined(S);
1377 } else {
1378 // Windows specific -- If entry point name is not given, we need to
1379 // infer that from user-defined entry name.
1380 StringRef S = findDefaultEntry();
1381 if (S.empty())
1382 fatal("entry point must be defined");
1383 Config->Entry = addUndefined(S);
1384 log("Entry name inferred: " + S);
1385 }
1386 }
1387
1388 // Handle /delayload
1389 for (auto *Arg : Args.filtered(OPT_delayload)) {
1390 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower());
1391 if (Config->Machine == I386) {
1392 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8");
1393 } else {
1394 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2");
1395 }
1396 }
1397
1398 // Set default image name if neither /out or /def set it.
1399 if (Config->OutputFile.empty()) {
1400 Config->OutputFile =
1401 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue());
1402 }
1403
1404 if (ShouldCreatePDB) {
1405 // Put the PDB next to the image if no /pdb flag was passed.
1406 if (Config->PDBPath.empty()) {
1407 Config->PDBPath = Config->OutputFile;
1408 sys::path::replace_extension(Config->PDBPath, ".pdb");
1409 }
1410
1411 // The embedded PDB path should be the absolute path to the PDB if no
1412 // /pdbaltpath flag was passed.
1413 if (Config->PDBAltPath.empty()) {
1414 Config->PDBAltPath = Config->PDBPath;
1415
1416 // It's important to make the path absolute and remove dots. This path
1417 // will eventually be written into the PE header, and certain Microsoft
1418 // tools won't work correctly if these assumptions are not held.
1419 sys::fs::make_absolute(Config->PDBAltPath);
1420 sys::path::remove_dots(Config->PDBAltPath);
1421 }
1422 }
1423
1424 // Set default image base if /base is not given.
1425 if (Config->ImageBase == uint64_t(-1))
1426 Config->ImageBase = getDefaultImageBase();
1427
1428 Symtab->addSynthetic(mangle("__ImageBase"), nullptr);
1429 if (Config->Machine == I386) {
1430 Symtab->addAbsolute("___safe_se_handler_table", 0);
1431 Symtab->addAbsolute("___safe_se_handler_count", 0);
1432 }
1433
1434 Symtab->addAbsolute(mangle("__guard_fids_count"), 0);
1435 Symtab->addAbsolute(mangle("__guard_fids_table"), 0);
1436 Symtab->addAbsolute(mangle("__guard_flags"), 0);
1437 Symtab->addAbsolute(mangle("__guard_iat_count"), 0);
1438 Symtab->addAbsolute(mangle("__guard_iat_table"), 0);
1439 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0);
1440 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0);
1441 // Needed for MSVC 2017 15.5 CRT.
1442 Symtab->addAbsolute(mangle("__enclave_config"), 0);
1443
1444 // This code may add new undefined symbols to the link, which may enqueue more
1445 // symbol resolution tasks, so we need to continue executing tasks until we
1446 // converge.
1447 do {
1448 // Windows specific -- if entry point is not found,
1449 // search for its mangled names.
1450 if (Config->Entry)
1451 Symtab->mangleMaybe(Config->Entry);
1452
1453 // Windows specific -- Make sure we resolve all dllexported symbols.
1454 for (Export &E : Config->Exports) {
1455 if (!E.ForwardTo.empty())
1456 continue;
1457 E.Sym = addUndefined(E.Name);
1458 if (!E.Directives)
1459 Symtab->mangleMaybe(E.Sym);
1460 }
1461
1462 // Add weak aliases. Weak aliases is a mechanism to give remaining
1463 // undefined symbols final chance to be resolved successfully.
1464 for (auto Pair : Config->AlternateNames) {
1465 StringRef From = Pair.first;
1466 StringRef To = Pair.second;
1467 Symbol *Sym = Symtab->find(From);
1468 if (!Sym)
1469 continue;
1470 if (auto *U = dyn_cast<Undefined>(Sym))
1471 if (!U->WeakAlias)
1472 U->WeakAlias = Symtab->addUndefined(To);
1473 }
1474
1475 // Windows specific -- if __load_config_used can be resolved, resolve it.
1476 if (Symtab->findUnderscore("_load_config_used"))
1477 addUndefined(mangle("_load_config_used"));
1478 } while (run());
1479
1480 if (errorCount())
1481 return;
1482
1483 // If /msvclto is given, we use the MSVC linker to link LTO output files.
1484 // This is useful because MSVC link.exe can generate complete PDBs.
1485 if (Args.hasArg(OPT_msvclto)) {
1486 invokeMSVC(Args);
1487 return;
1488 }
1489
1490 // Do LTO by compiling bitcode input files to a set of native COFF files then
1491 // link those files.
1492 Symtab->addCombinedLTOObjects();
1493 run();
1494
1495 // Make sure we have resolved all symbols.
1496 Symtab->reportRemainingUndefines();
1497 if (errorCount())
1498 return;
1499
1500 // Handle /safeseh.
1501 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) {
1502 for (ObjFile *File : ObjFile::Instances)
1503 if (!File->hasSafeSEH())
1504 error("/safeseh: " + File->getName() + " is not compatible with SEH");
1505 if (errorCount())
1506 return;
1507 }
1508
1509 // In MinGW, all symbols are automatically exported if no symbols
1510 // are chosen to be exported.
1511 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) ||
1512 Args.hasArg(OPT_export_all_symbols))) {
1513 AutoExporter Exporter;
1514
1515 Symtab->forEachSymbol([=](Symbol *S) {
1516 auto *Def = dyn_cast<Defined>(S);
1517 if (!Exporter.shouldExport(Def))
1518 return;
1519 Export E;
1520 E.Name = Def->getName();
1521 E.Sym = Def;
1522 if (Def->getChunk() &&
1523 !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE))
1524 E.Data = true;
1525 Config->Exports.push_back(E);
1526 });
1527 }
1528
1529 // Windows specific -- when we are creating a .dll file, we also
1530 // need to create a .lib file.
1531 if (!Config->Exports.empty() || Config->DLL) {
1532 fixupExports();
1533 createImportLibrary(/*AsLib=*/false);
1534 assignExportOrdinals();
1535 }
1536
1537 // Handle /output-def (MinGW specific).
1538 if (auto *Arg = Args.getLastArg(OPT_output_def))
1539 writeDefFile(Arg->getValue());
1540
1541 // Set extra alignment for .comm symbols
1542 for (auto Pair : Config->AlignComm) {
1543 StringRef Name = Pair.first;
1544 uint32_t Alignment = Pair.second;
1545
1546 Symbol *Sym = Symtab->find(Name);
1547 if (!Sym) {
1548 warn("/aligncomm symbol " + Name + " not found");
1549 continue;
1550 }
1551
1552 // If the symbol isn't common, it must have been replaced with a regular
1553 // symbol, which will carry its own alignment.
1554 auto *DC = dyn_cast<DefinedCommon>(Sym);
1555 if (!DC)
1556 continue;
1557
1558 CommonChunk *C = DC->getChunk();
1559 C->Alignment = std::max(C->Alignment, Alignment);
1560 }
1561
1562 // Windows specific -- Create a side-by-side manifest file.
1563 if (Config->Manifest == Configuration::SideBySide)
1564 createSideBySideManifest();
1565
1566 // Handle /order. We want to do this at this moment because we
1567 // need a complete list of comdat sections to warn on nonexistent
1568 // functions.
1569 if (auto *Arg = Args.getLastArg(OPT_order))
1570 parseOrderFile(Arg->getValue());
1571
1572 // Identify unreferenced COMDAT sections.
1573 if (Config->DoGC)
1574 markLive(Symtab->getChunks());
1575
1576 // Identify identical COMDAT sections to merge them.
1577 if (Config->DoICF)
1578 doICF(Symtab->getChunks());
1579
1580 // Write the result.
1581 writeResult();
1582
1583 // Stop early so we can print the results.
1584 Timer::root().stop();
1585 if (Config->ShowTiming)
1586 Timer::root().print();
1587 }
1588
1589 } // namespace coff
1590 } // namespace lld
1591