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 "InputFiles.h" 13 #include "Memory.h" 14 #include "MinGW.h" 15 #include "SymbolTable.h" 16 #include "Symbols.h" 17 #include "Writer.h" 18 #include "lld/Common/Driver.h" 19 #include "lld/Common/ErrorHandler.h" 20 #include "lld/Common/Version.h" 21 #include "llvm/ADT/Optional.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/BinaryFormat/Magic.h" 24 #include "llvm/Object/ArchiveWriter.h" 25 #include "llvm/Object/COFFImportFile.h" 26 #include "llvm/Object/COFFModuleDefinition.h" 27 #include "llvm/Option/Arg.h" 28 #include "llvm/Option/ArgList.h" 29 #include "llvm/Option/Option.h" 30 #include "llvm/Support/Debug.h" 31 #include "llvm/Support/Path.h" 32 #include "llvm/Support/Process.h" 33 #include "llvm/Support/TarWriter.h" 34 #include "llvm/Support/TargetSelect.h" 35 #include "llvm/Support/raw_ostream.h" 36 #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 37 #include <algorithm> 38 #include <memory> 39 40 #include <future> 41 42 using namespace llvm; 43 using namespace llvm::object; 44 using namespace llvm::COFF; 45 using llvm::sys::Process; 46 47 namespace lld { 48 namespace coff { 49 50 Configuration *Config; 51 LinkerDriver *Driver; 52 53 BumpPtrAllocator BAlloc; 54 StringSaver Saver{BAlloc}; 55 std::vector<SpecificAllocBase *> SpecificAllocBase::Instances; 56 57 bool link(ArrayRef<const char *> Args, bool CanExitEarly, raw_ostream &Diag) { 58 errorHandler().LogName = Args[0]; 59 errorHandler().ErrorOS = &Diag; 60 errorHandler().ColorDiagnostics = Diag.has_colors(); 61 errorHandler().ErrorLimitExceededMsg = 62 "too many errors emitted, stopping now" 63 " (use /ERRORLIMIT:0 to see all errors)"; 64 Config = make<Configuration>(); 65 Config->Argv = {Args.begin(), Args.end()}; 66 Config->CanExitEarly = CanExitEarly; 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 return !errorCount(); 79 } 80 81 // Drop directory components and replace extension with ".exe" or ".dll". 82 static std::string getOutputPath(StringRef Path) { 83 auto P = Path.find_last_of("\\/"); 84 StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); 85 const char* E = Config->DLL ? ".dll" : ".exe"; 86 return (S.substr(0, S.rfind('.')) + E).str(); 87 } 88 89 // ErrorOr is not default constructible, so it cannot be used as the type 90 // parameter of a future. 91 // FIXME: We could open the file in createFutureForFile and avoid needing to 92 // return an error here, but for the moment that would cost us a file descriptor 93 // (a limited resource on Windows) for the duration that the future is pending. 94 typedef std::pair<std::unique_ptr<MemoryBuffer>, std::error_code> MBErrPair; 95 96 // Create a std::future that opens and maps a file using the best strategy for 97 // the host platform. 98 static std::future<MBErrPair> createFutureForFile(std::string Path) { 99 #if LLVM_ON_WIN32 100 // On Windows, file I/O is relatively slow so it is best to do this 101 // asynchronously. 102 auto Strategy = std::launch::async; 103 #else 104 auto Strategy = std::launch::deferred; 105 #endif 106 return std::async(Strategy, [=]() { 107 auto MBOrErr = MemoryBuffer::getFile(Path); 108 if (!MBOrErr) 109 return MBErrPair{nullptr, MBOrErr.getError()}; 110 return MBErrPair{std::move(*MBOrErr), std::error_code()}; 111 }); 112 } 113 114 MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> MB) { 115 MemoryBufferRef MBRef = *MB; 116 make<std::unique_ptr<MemoryBuffer>>(std::move(MB)); // take ownership 117 118 if (Driver->Tar) 119 Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), 120 MBRef.getBuffer()); 121 return MBRef; 122 } 123 124 void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> MB, 125 bool WholeArchive) { 126 MemoryBufferRef MBRef = takeBuffer(std::move(MB)); 127 FilePaths.push_back(MBRef.getBufferIdentifier()); 128 129 // File type is detected by contents, not by file extension. 130 switch (identify_magic(MBRef.getBuffer())) { 131 case file_magic::windows_resource: 132 Resources.push_back(MBRef); 133 break; 134 135 case file_magic::archive: 136 if (WholeArchive) { 137 std::unique_ptr<Archive> File = 138 check(Archive::create(MBRef), 139 MBRef.getBufferIdentifier() + ": failed to parse archive"); 140 141 for (MemoryBufferRef M : getArchiveMembers(File.get())) 142 addArchiveBuffer(M, "<whole-archive>", MBRef.getBufferIdentifier()); 143 return; 144 } 145 Symtab->addFile(make<ArchiveFile>(MBRef)); 146 break; 147 148 case file_magic::bitcode: 149 Symtab->addFile(make<BitcodeFile>(MBRef)); 150 break; 151 152 case file_magic::coff_cl_gl_object: 153 error(MBRef.getBufferIdentifier() + ": is not a native COFF file. " 154 "Recompile without /GL"); 155 break; 156 157 default: 158 Symtab->addFile(make<ObjFile>(MBRef)); 159 break; 160 } 161 } 162 163 void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { 164 auto Future = 165 std::make_shared<std::future<MBErrPair>>(createFutureForFile(Path)); 166 std::string PathStr = Path; 167 enqueueTask([=]() { 168 auto MBOrErr = Future->get(); 169 if (MBOrErr.second) 170 error("could not open " + PathStr + ": " + MBOrErr.second.message()); 171 else 172 Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); 173 }); 174 } 175 176 void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, 177 StringRef ParentName) { 178 file_magic Magic = identify_magic(MB.getBuffer()); 179 if (Magic == file_magic::coff_import_library) { 180 Symtab->addFile(make<ImportFile>(MB)); 181 return; 182 } 183 184 InputFile *Obj; 185 if (Magic == file_magic::coff_object) { 186 Obj = make<ObjFile>(MB); 187 } else if (Magic == file_magic::bitcode) { 188 Obj = make<BitcodeFile>(MB); 189 } else { 190 error("unknown file type: " + MB.getBufferIdentifier()); 191 return; 192 } 193 194 Obj->ParentName = ParentName; 195 Symtab->addFile(Obj); 196 log("Loaded " + toString(Obj) + " for " + SymName); 197 } 198 199 void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, 200 StringRef SymName, 201 StringRef ParentName) { 202 if (!C.getParent()->isThin()) { 203 MemoryBufferRef MB = check( 204 C.getMemoryBufferRef(), 205 "could not get the buffer for the member defining symbol " + SymName); 206 enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); }); 207 return; 208 } 209 210 auto Future = std::make_shared<std::future<MBErrPair>>(createFutureForFile( 211 check(C.getFullName(), 212 "could not get the filename for the member defining symbol " + 213 SymName))); 214 enqueueTask([=]() { 215 auto MBOrErr = Future->get(); 216 if (MBOrErr.second) 217 fatal("could not get the buffer for the member defining " + SymName + 218 ": " + MBOrErr.second.message()); 219 Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, 220 ParentName); 221 }); 222 } 223 224 static bool isDecorated(StringRef Sym) { 225 return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || 226 (!Config->MinGW && Sym.contains('@')); 227 } 228 229 // Parses .drectve section contents and returns a list of files 230 // specified by /defaultlib. 231 void LinkerDriver::parseDirectives(StringRef S) { 232 ArgParser Parser; 233 // .drectve is always tokenized using Windows shell rules. 234 opt::InputArgList Args = Parser.parse(S); 235 236 for (auto *Arg : Args) { 237 switch (Arg->getOption().getUnaliasedOption().getID()) { 238 case OPT_aligncomm: 239 parseAligncomm(Arg->getValue()); 240 break; 241 case OPT_alternatename: 242 parseAlternateName(Arg->getValue()); 243 break; 244 case OPT_defaultlib: 245 if (Optional<StringRef> Path = findLib(Arg->getValue())) 246 enqueuePath(*Path, false); 247 break; 248 case OPT_export: { 249 Export E = parseExport(Arg->getValue()); 250 if (Config->Machine == I386 && Config->MinGW) { 251 if (!isDecorated(E.Name)) 252 E.Name = Saver.save("_" + E.Name); 253 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 254 E.ExtName = Saver.save("_" + E.ExtName); 255 } 256 E.Directives = true; 257 Config->Exports.push_back(E); 258 break; 259 } 260 case OPT_failifmismatch: 261 checkFailIfMismatch(Arg->getValue()); 262 break; 263 case OPT_incl: 264 addUndefined(Arg->getValue()); 265 break; 266 case OPT_merge: 267 parseMerge(Arg->getValue()); 268 break; 269 case OPT_nodefaultlib: 270 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 271 break; 272 case OPT_section: 273 parseSection(Arg->getValue()); 274 break; 275 case OPT_editandcontinue: 276 case OPT_fastfail: 277 case OPT_guardsym: 278 case OPT_natvis: 279 case OPT_throwingnew: 280 break; 281 default: 282 error(Arg->getSpelling() + " is not allowed in .drectve"); 283 } 284 } 285 } 286 287 // Find file from search paths. You can omit ".obj", this function takes 288 // care of that. Note that the returned path is not guaranteed to exist. 289 StringRef LinkerDriver::doFindFile(StringRef Filename) { 290 bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); 291 if (HasPathSep) 292 return Filename; 293 bool HasExt = Filename.contains('.'); 294 for (StringRef Dir : SearchPaths) { 295 SmallString<128> Path = Dir; 296 sys::path::append(Path, Filename); 297 if (sys::fs::exists(Path.str())) 298 return Saver.save(Path.str()); 299 if (!HasExt) { 300 Path.append(".obj"); 301 if (sys::fs::exists(Path.str())) 302 return Saver.save(Path.str()); 303 } 304 } 305 return Filename; 306 } 307 308 // Resolves a file path. This never returns the same path 309 // (in that case, it returns None). 310 Optional<StringRef> LinkerDriver::findFile(StringRef Filename) { 311 StringRef Path = doFindFile(Filename); 312 bool Seen = !VisitedFiles.insert(Path.lower()).second; 313 if (Seen) 314 return None; 315 return Path; 316 } 317 318 // Find library file from search path. 319 StringRef LinkerDriver::doFindLib(StringRef Filename) { 320 // Add ".lib" to Filename if that has no file extension. 321 bool HasExt = Filename.contains('.'); 322 if (!HasExt) 323 Filename = Saver.save(Filename + ".lib"); 324 return doFindFile(Filename); 325 } 326 327 // Resolves a library path. /nodefaultlib options are taken into 328 // consideration. This never returns the same path (in that case, 329 // it returns None). 330 Optional<StringRef> LinkerDriver::findLib(StringRef Filename) { 331 if (Config->NoDefaultLibAll) 332 return None; 333 if (!VisitedLibs.insert(Filename.lower()).second) 334 return None; 335 StringRef Path = doFindLib(Filename); 336 if (Config->NoDefaultLibs.count(Path)) 337 return None; 338 if (!VisitedFiles.insert(Path.lower()).second) 339 return None; 340 return Path; 341 } 342 343 // Parses LIB environment which contains a list of search paths. 344 void LinkerDriver::addLibSearchPaths() { 345 Optional<std::string> EnvOpt = Process::GetEnv("LIB"); 346 if (!EnvOpt.hasValue()) 347 return; 348 StringRef Env = Saver.save(*EnvOpt); 349 while (!Env.empty()) { 350 StringRef Path; 351 std::tie(Path, Env) = Env.split(';'); 352 SearchPaths.push_back(Path); 353 } 354 } 355 356 Symbol *LinkerDriver::addUndefined(StringRef Name) { 357 Symbol *B = Symtab->addUndefined(Name); 358 Config->GCRoot.insert(B); 359 return B; 360 } 361 362 // Symbol names are mangled by appending "_" prefix on x86. 363 StringRef LinkerDriver::mangle(StringRef Sym) { 364 assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); 365 if (Config->Machine == I386) 366 return Saver.save("_" + Sym); 367 return Sym; 368 } 369 370 // Windows specific -- find default entry point name. 371 StringRef LinkerDriver::findDefaultEntry() { 372 // User-defined main functions and their corresponding entry points. 373 static const char *Entries[][2] = { 374 {"main", "mainCRTStartup"}, 375 {"wmain", "wmainCRTStartup"}, 376 {"WinMain", "WinMainCRTStartup"}, 377 {"wWinMain", "wWinMainCRTStartup"}, 378 }; 379 for (auto E : Entries) { 380 StringRef Entry = Symtab->findMangle(mangle(E[0])); 381 if (!Entry.empty() && !isa<Undefined>(Symtab->find(Entry))) 382 return mangle(E[1]); 383 } 384 return ""; 385 } 386 387 WindowsSubsystem LinkerDriver::inferSubsystem() { 388 if (Config->DLL) 389 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 390 if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain")) 391 return IMAGE_SUBSYSTEM_WINDOWS_CUI; 392 if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain")) 393 return IMAGE_SUBSYSTEM_WINDOWS_GUI; 394 return IMAGE_SUBSYSTEM_UNKNOWN; 395 } 396 397 static uint64_t getDefaultImageBase() { 398 if (Config->is64()) 399 return Config->DLL ? 0x180000000 : 0x140000000; 400 return Config->DLL ? 0x10000000 : 0x400000; 401 } 402 403 static std::string createResponseFile(const opt::InputArgList &Args, 404 ArrayRef<StringRef> FilePaths, 405 ArrayRef<StringRef> SearchPaths) { 406 SmallString<0> Data; 407 raw_svector_ostream OS(Data); 408 409 for (auto *Arg : Args) { 410 switch (Arg->getOption().getID()) { 411 case OPT_linkrepro: 412 case OPT_INPUT: 413 case OPT_defaultlib: 414 case OPT_libpath: 415 case OPT_manifest: 416 case OPT_manifest_colon: 417 case OPT_manifestdependency: 418 case OPT_manifestfile: 419 case OPT_manifestinput: 420 case OPT_manifestuac: 421 break; 422 default: 423 OS << toString(Arg) << "\n"; 424 } 425 } 426 427 for (StringRef Path : SearchPaths) { 428 std::string RelPath = relativeToRoot(Path); 429 OS << "/libpath:" << quote(RelPath) << "\n"; 430 } 431 432 for (StringRef Path : FilePaths) 433 OS << quote(relativeToRoot(Path)) << "\n"; 434 435 return Data.str(); 436 } 437 438 static unsigned getDefaultDebugType(const opt::InputArgList &Args) { 439 unsigned DebugTypes = static_cast<unsigned>(DebugType::CV); 440 if (Args.hasArg(OPT_driver)) 441 DebugTypes |= static_cast<unsigned>(DebugType::PData); 442 if (Args.hasArg(OPT_profile)) 443 DebugTypes |= static_cast<unsigned>(DebugType::Fixup); 444 return DebugTypes; 445 } 446 447 static unsigned parseDebugType(StringRef Arg) { 448 SmallVector<StringRef, 3> Types; 449 Arg.split(Types, ',', /*KeepEmpty=*/false); 450 451 unsigned DebugTypes = static_cast<unsigned>(DebugType::None); 452 for (StringRef Type : Types) 453 DebugTypes |= StringSwitch<unsigned>(Type.lower()) 454 .Case("cv", static_cast<unsigned>(DebugType::CV)) 455 .Case("pdata", static_cast<unsigned>(DebugType::PData)) 456 .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 457 .Default(0); 458 return DebugTypes; 459 } 460 461 static std::string getMapFile(const opt::InputArgList &Args) { 462 auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); 463 if (!Arg) 464 return ""; 465 if (Arg->getOption().getID() == OPT_lldmap_file) 466 return Arg->getValue(); 467 468 assert(Arg->getOption().getID() == OPT_lldmap); 469 StringRef OutFile = Config->OutputFile; 470 return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); 471 } 472 473 static std::string getImplibPath() { 474 if (!Config->Implib.empty()) 475 return Config->Implib; 476 SmallString<128> Out = StringRef(Config->OutputFile); 477 sys::path::replace_extension(Out, ".lib"); 478 return Out.str(); 479 } 480 481 // 482 // The import name is caculated as the following: 483 // 484 // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 485 // -----+----------------+---------------------+------------------ 486 // LINK | {value} | {value}.{.dll/.exe} | {output name} 487 // LIB | {value} | {value}.dll | {output name}.dll 488 // 489 static std::string getImportName(bool AsLib) { 490 SmallString<128> Out; 491 492 if (Config->ImportName.empty()) { 493 Out.assign(sys::path::filename(Config->OutputFile)); 494 if (AsLib) 495 sys::path::replace_extension(Out, ".dll"); 496 } else { 497 Out.assign(Config->ImportName); 498 if (!sys::path::has_extension(Out)) 499 sys::path::replace_extension(Out, 500 (Config->DLL || AsLib) ? ".dll" : ".exe"); 501 } 502 503 return Out.str(); 504 } 505 506 static void createImportLibrary(bool AsLib) { 507 std::vector<COFFShortExport> Exports; 508 for (Export &E1 : Config->Exports) { 509 COFFShortExport E2; 510 E2.Name = E1.Name; 511 E2.SymbolName = E1.SymbolName; 512 E2.ExtName = E1.ExtName; 513 E2.Ordinal = E1.Ordinal; 514 E2.Noname = E1.Noname; 515 E2.Data = E1.Data; 516 E2.Private = E1.Private; 517 E2.Constant = E1.Constant; 518 Exports.push_back(E2); 519 } 520 521 auto E = writeImportLibrary(getImportName(AsLib), getImplibPath(), Exports, 522 Config->Machine, false); 523 handleAllErrors(std::move(E), 524 [&](ErrorInfoBase &EIB) { error(EIB.message()); }); 525 } 526 527 static void parseModuleDefs(StringRef Path) { 528 std::unique_ptr<MemoryBuffer> MB = check( 529 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 530 COFFModuleDefinition M = check(parseCOFFModuleDefinition( 531 MB->getMemBufferRef(), Config->Machine, Config->MinGW)); 532 533 if (Config->OutputFile.empty()) 534 Config->OutputFile = Saver.save(M.OutputFile); 535 Config->ImportName = Saver.save(M.ImportName); 536 if (M.ImageBase) 537 Config->ImageBase = M.ImageBase; 538 if (M.StackReserve) 539 Config->StackReserve = M.StackReserve; 540 if (M.StackCommit) 541 Config->StackCommit = M.StackCommit; 542 if (M.HeapReserve) 543 Config->HeapReserve = M.HeapReserve; 544 if (M.HeapCommit) 545 Config->HeapCommit = M.HeapCommit; 546 if (M.MajorImageVersion) 547 Config->MajorImageVersion = M.MajorImageVersion; 548 if (M.MinorImageVersion) 549 Config->MinorImageVersion = M.MinorImageVersion; 550 if (M.MajorOSVersion) 551 Config->MajorOSVersion = M.MajorOSVersion; 552 if (M.MinorOSVersion) 553 Config->MinorOSVersion = M.MinorOSVersion; 554 555 for (COFFShortExport E1 : M.Exports) { 556 Export E2; 557 E2.Name = Saver.save(E1.Name); 558 if (E1.isWeak()) 559 E2.ExtName = Saver.save(E1.ExtName); 560 E2.Ordinal = E1.Ordinal; 561 E2.Noname = E1.Noname; 562 E2.Data = E1.Data; 563 E2.Private = E1.Private; 564 E2.Constant = E1.Constant; 565 Config->Exports.push_back(E2); 566 } 567 } 568 569 // A helper function for filterBitcodeFiles. 570 static bool needsRebuilding(MemoryBufferRef MB) { 571 // The MSVC linker doesn't support thin archives, so if it's a thin 572 // archive, we always need to rebuild it. 573 std::unique_ptr<Archive> File = 574 check(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier()); 575 if (File->isThin()) 576 return true; 577 578 // Returns true if the archive contains at least one bitcode file. 579 for (MemoryBufferRef Member : getArchiveMembers(File.get())) 580 if (identify_magic(Member.getBuffer()) == file_magic::bitcode) 581 return true; 582 return false; 583 } 584 585 // Opens a given path as an archive file and removes bitcode files 586 // from them if exists. This function is to appease the MSVC linker as 587 // their linker doesn't like archive files containing non-native 588 // object files. 589 // 590 // If a given archive doesn't contain bitcode files, the archive path 591 // is returned as-is. Otherwise, a new temporary file is created and 592 // its path is returned. 593 static Optional<std::string> 594 filterBitcodeFiles(StringRef Path, std::vector<std::string> &TemporaryFiles) { 595 std::unique_ptr<MemoryBuffer> MB = check( 596 MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); 597 MemoryBufferRef MBRef = MB->getMemBufferRef(); 598 file_magic Magic = identify_magic(MBRef.getBuffer()); 599 600 if (Magic == file_magic::bitcode) 601 return None; 602 if (Magic != file_magic::archive) 603 return Path.str(); 604 if (!needsRebuilding(MBRef)) 605 return Path.str(); 606 607 std::unique_ptr<Archive> File = 608 check(Archive::create(MBRef), 609 MBRef.getBufferIdentifier() + ": failed to parse archive"); 610 611 std::vector<NewArchiveMember> New; 612 for (MemoryBufferRef Member : getArchiveMembers(File.get())) 613 if (identify_magic(Member.getBuffer()) != file_magic::bitcode) 614 New.emplace_back(Member); 615 616 if (New.empty()) 617 return None; 618 619 log("Creating a temporary archive for " + Path + " to remove bitcode files"); 620 621 SmallString<128> S; 622 if (auto EC = sys::fs::createTemporaryFile("lld-" + sys::path::stem(Path), 623 ".lib", S)) 624 fatal("cannot create a temporary file: " + EC.message()); 625 std::string Temp = S.str(); 626 TemporaryFiles.push_back(Temp); 627 628 Error E = 629 llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU, 630 /*Deterministics=*/true, 631 /*Thin=*/false); 632 handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { 633 error("failed to create a new archive " + S.str() + ": " + EI.message()); 634 }); 635 return Temp; 636 } 637 638 // Create response file contents and invoke the MSVC linker. 639 void LinkerDriver::invokeMSVC(opt::InputArgList &Args) { 640 std::string Rsp = "/nologo\n"; 641 std::vector<std::string> Temps; 642 643 // Write out archive members that we used in symbol resolution and pass these 644 // to MSVC before any archives, so that MSVC uses the same objects to satisfy 645 // references. 646 for (ObjFile *Obj : ObjFile::Instances) { 647 if (Obj->ParentName.empty()) 648 continue; 649 SmallString<128> S; 650 int Fd; 651 if (auto EC = sys::fs::createTemporaryFile( 652 "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S)) 653 fatal("cannot create a temporary file: " + EC.message()); 654 raw_fd_ostream OS(Fd, /*shouldClose*/ true); 655 OS << Obj->MB.getBuffer(); 656 Temps.push_back(S.str()); 657 Rsp += quote(S) + "\n"; 658 } 659 660 for (auto *Arg : Args) { 661 switch (Arg->getOption().getID()) { 662 case OPT_linkrepro: 663 case OPT_lldmap: 664 case OPT_lldmap_file: 665 case OPT_lldsavetemps: 666 case OPT_msvclto: 667 // LLD-specific options are stripped. 668 break; 669 case OPT_opt: 670 if (!StringRef(Arg->getValue()).startswith("lld")) 671 Rsp += toString(Arg) + " "; 672 break; 673 case OPT_INPUT: { 674 if (Optional<StringRef> Path = doFindFile(Arg->getValue())) { 675 if (Optional<std::string> S = filterBitcodeFiles(*Path, Temps)) 676 Rsp += quote(*S) + "\n"; 677 continue; 678 } 679 Rsp += quote(Arg->getValue()) + "\n"; 680 break; 681 } 682 default: 683 Rsp += toString(Arg) + "\n"; 684 } 685 } 686 687 std::vector<StringRef> ObjFiles = Symtab->compileBitcodeFiles(); 688 runMSVCLinker(Rsp, ObjFiles); 689 690 for (StringRef Path : Temps) 691 sys::fs::remove(Path); 692 } 693 694 void LinkerDriver::enqueueTask(std::function<void()> Task) { 695 TaskQueue.push_back(std::move(Task)); 696 } 697 698 bool LinkerDriver::run() { 699 bool DidWork = !TaskQueue.empty(); 700 while (!TaskQueue.empty()) { 701 TaskQueue.front()(); 702 TaskQueue.pop_front(); 703 } 704 return DidWork; 705 } 706 707 void LinkerDriver::link(ArrayRef<const char *> ArgsArr) { 708 // If the first command line argument is "/lib", link.exe acts like lib.exe. 709 // We call our own implementation of lib.exe that understands bitcode files. 710 if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { 711 if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) 712 fatal("lib failed"); 713 return; 714 } 715 716 // Needed for LTO. 717 InitializeAllTargetInfos(); 718 InitializeAllTargets(); 719 InitializeAllTargetMCs(); 720 InitializeAllAsmParsers(); 721 InitializeAllAsmPrinters(); 722 InitializeAllDisassemblers(); 723 724 // Parse command line options. 725 ArgParser Parser; 726 opt::InputArgList Args = Parser.parseLINK(ArgsArr.slice(1)); 727 728 // Parse and evaluate -mllvm options. 729 std::vector<const char *> V; 730 V.push_back("lld-link (LLVM option parsing)"); 731 for (auto *Arg : Args.filtered(OPT_mllvm)) 732 V.push_back(Arg->getValue()); 733 cl::ParseCommandLineOptions(V.size(), V.data()); 734 735 // Handle /errorlimit early, because error() depends on it. 736 if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { 737 int N = 20; 738 StringRef S = Arg->getValue(); 739 if (S.getAsInteger(10, N)) 740 error(Arg->getSpelling() + " number expected, but got " + S); 741 errorHandler().ErrorLimit = N; 742 } 743 744 // Handle /help 745 if (Args.hasArg(OPT_help)) { 746 printHelp(ArgsArr[0]); 747 return; 748 } 749 750 // Handle --version, which is an lld extension. This option is a bit odd 751 // because it doesn't start with "/", but we deliberately chose "--" to 752 // avoid conflict with /version and for compatibility with clang-cl. 753 if (Args.hasArg(OPT_dash_dash_version)) { 754 outs() << getLLDVersion() << "\n"; 755 return; 756 } 757 758 // Handle /lldmingw early, since it can potentially affect how other 759 // options are handled. 760 Config->MinGW = Args.hasArg(OPT_lldmingw); 761 762 if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { 763 SmallString<64> Path = StringRef(Arg->getValue()); 764 sys::path::append(Path, "repro.tar"); 765 766 Expected<std::unique_ptr<TarWriter>> ErrOrWriter = 767 TarWriter::create(Path, "repro"); 768 769 if (ErrOrWriter) { 770 Tar = std::move(*ErrOrWriter); 771 } else { 772 error("/linkrepro: failed to open " + Path + ": " + 773 toString(ErrOrWriter.takeError())); 774 } 775 } 776 777 if (!Args.hasArg(OPT_INPUT)) { 778 if (Args.hasArg(OPT_deffile)) 779 Config->NoEntry = true; 780 else 781 fatal("no input files"); 782 } 783 784 // Construct search path list. 785 SearchPaths.push_back(""); 786 for (auto *Arg : Args.filtered(OPT_libpath)) 787 SearchPaths.push_back(Arg->getValue()); 788 addLibSearchPaths(); 789 790 // Handle /out 791 if (auto *Arg = Args.getLastArg(OPT_out)) 792 Config->OutputFile = Arg->getValue(); 793 794 // Handle /verbose 795 if (Args.hasArg(OPT_verbose)) 796 Config->Verbose = true; 797 errorHandler().Verbose = Config->Verbose; 798 799 // Handle /force or /force:unresolved 800 if (Args.hasArg(OPT_force) || Args.hasArg(OPT_force_unresolved)) 801 Config->Force = true; 802 803 // Handle /debug 804 if (Args.hasArg(OPT_debug) || Args.hasArg(OPT_debug_dwarf)) { 805 Config->Debug = true; 806 if (auto *Arg = Args.getLastArg(OPT_debugtype)) 807 Config->DebugTypes = parseDebugType(Arg->getValue()); 808 else 809 Config->DebugTypes = getDefaultDebugType(Args); 810 } 811 812 // Create a dummy PDB file to satisfy build sytem rules. 813 if (auto *Arg = Args.getLastArg(OPT_pdb)) 814 Config->PDBPath = Arg->getValue(); 815 816 // Handle /noentry 817 if (Args.hasArg(OPT_noentry)) { 818 if (Args.hasArg(OPT_dll)) 819 Config->NoEntry = true; 820 else 821 error("/noentry must be specified with /dll"); 822 } 823 824 // Handle /dll 825 if (Args.hasArg(OPT_dll)) { 826 Config->DLL = true; 827 Config->ManifestID = 2; 828 } 829 830 // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 831 // because we need to explicitly check whether that option or its inverse was 832 // present in the argument list in order to handle /fixed. 833 auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 834 if (DynamicBaseArg && 835 DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 836 Config->DynamicBase = false; 837 838 bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); 839 if (Fixed) { 840 if (DynamicBaseArg && 841 DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 842 error("/fixed must not be specified with /dynamicbase"); 843 } else { 844 Config->Relocatable = false; 845 Config->DynamicBase = false; 846 } 847 } 848 849 // Handle /appcontainer 850 Config->AppContainer = 851 Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 852 853 // Handle /machine 854 if (auto *Arg = Args.getLastArg(OPT_machine)) 855 Config->Machine = getMachineType(Arg->getValue()); 856 857 // Handle /nodefaultlib:<filename> 858 for (auto *Arg : Args.filtered(OPT_nodefaultlib)) 859 Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); 860 861 // Handle /nodefaultlib 862 if (Args.hasArg(OPT_nodefaultlib_all)) 863 Config->NoDefaultLibAll = true; 864 865 // Handle /base 866 if (auto *Arg = Args.getLastArg(OPT_base)) 867 parseNumbers(Arg->getValue(), &Config->ImageBase); 868 869 // Handle /stack 870 if (auto *Arg = Args.getLastArg(OPT_stack)) 871 parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); 872 873 // Handle /heap 874 if (auto *Arg = Args.getLastArg(OPT_heap)) 875 parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); 876 877 // Handle /version 878 if (auto *Arg = Args.getLastArg(OPT_version)) 879 parseVersion(Arg->getValue(), &Config->MajorImageVersion, 880 &Config->MinorImageVersion); 881 882 // Handle /subsystem 883 if (auto *Arg = Args.getLastArg(OPT_subsystem)) 884 parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, 885 &Config->MinorOSVersion); 886 887 // Handle /alternatename 888 for (auto *Arg : Args.filtered(OPT_alternatename)) 889 parseAlternateName(Arg->getValue()); 890 891 // Handle /include 892 for (auto *Arg : Args.filtered(OPT_incl)) 893 addUndefined(Arg->getValue()); 894 895 // Handle /implib 896 if (auto *Arg = Args.getLastArg(OPT_implib)) 897 Config->Implib = Arg->getValue(); 898 899 // Handle /opt 900 for (auto *Arg : Args.filtered(OPT_opt)) { 901 std::string Str = StringRef(Arg->getValue()).lower(); 902 SmallVector<StringRef, 1> Vec; 903 StringRef(Str).split(Vec, ','); 904 for (StringRef S : Vec) { 905 if (S == "noref") { 906 Config->DoGC = false; 907 Config->DoICF = false; 908 continue; 909 } 910 if (S == "icf" || S.startswith("icf=")) { 911 Config->DoICF = true; 912 continue; 913 } 914 if (S == "noicf") { 915 Config->DoICF = false; 916 continue; 917 } 918 if (S.startswith("lldlto=")) { 919 StringRef OptLevel = S.substr(7); 920 if (OptLevel.getAsInteger(10, Config->LTOOptLevel) || 921 Config->LTOOptLevel > 3) 922 error("/opt:lldlto: invalid optimization level: " + OptLevel); 923 continue; 924 } 925 if (S.startswith("lldltojobs=")) { 926 StringRef Jobs = S.substr(11); 927 if (Jobs.getAsInteger(10, Config->LTOJobs) || Config->LTOJobs == 0) 928 error("/opt:lldltojobs: invalid job count: " + Jobs); 929 continue; 930 } 931 if (S.startswith("lldltopartitions=")) { 932 StringRef N = S.substr(17); 933 if (N.getAsInteger(10, Config->LTOPartitions) || 934 Config->LTOPartitions == 0) 935 error("/opt:lldltopartitions: invalid partition count: " + N); 936 continue; 937 } 938 if (S != "ref" && S != "lbr" && S != "nolbr") 939 error("/opt: unknown option: " + S); 940 } 941 } 942 943 // Handle /lldsavetemps 944 if (Args.hasArg(OPT_lldsavetemps)) 945 Config->SaveTemps = true; 946 947 // Handle /lldltocache 948 if (auto *Arg = Args.getLastArg(OPT_lldltocache)) 949 Config->LTOCache = Arg->getValue(); 950 951 // Handle /lldsavecachepolicy 952 if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) 953 Config->LTOCachePolicy = check( 954 parseCachePruningPolicy(Arg->getValue()), 955 Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue()); 956 957 // Handle /failifmismatch 958 for (auto *Arg : Args.filtered(OPT_failifmismatch)) 959 checkFailIfMismatch(Arg->getValue()); 960 961 // Handle /merge 962 for (auto *Arg : Args.filtered(OPT_merge)) 963 parseMerge(Arg->getValue()); 964 965 // Handle /section 966 for (auto *Arg : Args.filtered(OPT_section)) 967 parseSection(Arg->getValue()); 968 969 // Handle /aligncomm 970 for (auto *Arg : Args.filtered(OPT_aligncomm)) 971 parseAligncomm(Arg->getValue()); 972 973 // Handle /manifestdependency. This enables /manifest unless /manifest:no is 974 // also passed. 975 if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { 976 Config->ManifestDependency = Arg->getValue(); 977 Config->Manifest = Configuration::SideBySide; 978 } 979 980 // Handle /manifest and /manifest: 981 if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 982 if (Arg->getOption().getID() == OPT_manifest) 983 Config->Manifest = Configuration::SideBySide; 984 else 985 parseManifest(Arg->getValue()); 986 } 987 988 // Handle /manifestuac 989 if (auto *Arg = Args.getLastArg(OPT_manifestuac)) 990 parseManifestUAC(Arg->getValue()); 991 992 // Handle /manifestfile 993 if (auto *Arg = Args.getLastArg(OPT_manifestfile)) 994 Config->ManifestFile = Arg->getValue(); 995 996 // Handle /manifestinput 997 for (auto *Arg : Args.filtered(OPT_manifestinput)) 998 Config->ManifestInput.push_back(Arg->getValue()); 999 1000 if (!Config->ManifestInput.empty() && 1001 Config->Manifest != Configuration::Embed) { 1002 fatal("/MANIFESTINPUT: requires /MANIFEST:EMBED"); 1003 } 1004 1005 // Handle miscellaneous boolean flags. 1006 Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 1007 Config->AllowIsolation = 1008 Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 1009 Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 1010 Config->TerminalServerAware = Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 1011 if (Args.hasArg(OPT_nosymtab)) 1012 Config->WriteSymtab = false; 1013 1014 Config->MapFile = getMapFile(Args); 1015 1016 if (errorCount()) 1017 return; 1018 1019 bool WholeArchiveFlag = Args.hasArg(OPT_wholearchive_flag); 1020 // Create a list of input files. Files can be given as arguments 1021 // for /defaultlib option. 1022 std::vector<MemoryBufferRef> MBs; 1023 for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) { 1024 switch (Arg->getOption().getID()) { 1025 case OPT_INPUT: 1026 if (Optional<StringRef> Path = findFile(Arg->getValue())) 1027 enqueuePath(*Path, WholeArchiveFlag); 1028 break; 1029 case OPT_wholearchive_file: 1030 if (Optional<StringRef> Path = findFile(Arg->getValue())) 1031 enqueuePath(*Path, true); 1032 break; 1033 } 1034 } 1035 for (auto *Arg : Args.filtered(OPT_defaultlib)) 1036 if (Optional<StringRef> Path = findLib(Arg->getValue())) 1037 enqueuePath(*Path, false); 1038 1039 // Windows specific -- Create a resource file containing a manifest file. 1040 if (Config->Manifest == Configuration::Embed) 1041 addBuffer(createManifestRes(), false); 1042 1043 // Read all input files given via the command line. 1044 run(); 1045 1046 // We should have inferred a machine type by now from the input files, but if 1047 // not we assume x64. 1048 if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { 1049 warn("/machine is not specified. x64 is assumed"); 1050 Config->Machine = AMD64; 1051 } 1052 1053 // Input files can be Windows resource files (.res files). We use 1054 // WindowsResource to convert resource files to a regular COFF file, 1055 // then link the resulting file normally. 1056 if (!Resources.empty()) 1057 Symtab->addFile(make<ObjFile>(convertResToCOFF(Resources))); 1058 1059 if (Tar) 1060 Tar->append("response.txt", 1061 createResponseFile(Args, FilePaths, 1062 ArrayRef<StringRef>(SearchPaths).slice(1))); 1063 1064 // Handle /largeaddressaware 1065 Config->LargeAddressAware = Args.hasFlag( 1066 OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); 1067 1068 // Handle /highentropyva 1069 Config->HighEntropyVA = 1070 Config->is64() && 1071 Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 1072 1073 // Handle /entry and /dll 1074 if (auto *Arg = Args.getLastArg(OPT_entry)) { 1075 Config->Entry = addUndefined(mangle(Arg->getValue())); 1076 } else if (Args.hasArg(OPT_dll) && !Config->NoEntry) { 1077 StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" 1078 : "_DllMainCRTStartup"; 1079 Config->Entry = addUndefined(S); 1080 } else if (!Config->NoEntry) { 1081 // Windows specific -- If entry point name is not given, we need to 1082 // infer that from user-defined entry name. 1083 StringRef S = findDefaultEntry(); 1084 if (S.empty()) 1085 fatal("entry point must be defined"); 1086 Config->Entry = addUndefined(S); 1087 log("Entry name inferred: " + S); 1088 } 1089 1090 // Handle /export 1091 for (auto *Arg : Args.filtered(OPT_export)) { 1092 Export E = parseExport(Arg->getValue()); 1093 if (Config->Machine == I386) { 1094 if (!isDecorated(E.Name)) 1095 E.Name = Saver.save("_" + E.Name); 1096 if (!E.ExtName.empty() && !isDecorated(E.ExtName)) 1097 E.ExtName = Saver.save("_" + E.ExtName); 1098 } 1099 Config->Exports.push_back(E); 1100 } 1101 1102 // Handle /def 1103 if (auto *Arg = Args.getLastArg(OPT_deffile)) { 1104 // parseModuleDefs mutates Config object. 1105 parseModuleDefs(Arg->getValue()); 1106 } 1107 1108 // Handle generation of import library from a def file. 1109 if (!Args.hasArg(OPT_INPUT)) { 1110 fixupExports(); 1111 createImportLibrary(/*AsLib=*/true); 1112 return; 1113 } 1114 1115 // Handle /delayload 1116 for (auto *Arg : Args.filtered(OPT_delayload)) { 1117 Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); 1118 if (Config->Machine == I386) { 1119 Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); 1120 } else { 1121 Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); 1122 } 1123 } 1124 1125 // Set default image name if neither /out or /def set it. 1126 if (Config->OutputFile.empty()) { 1127 Config->OutputFile = 1128 getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); 1129 } 1130 1131 // Put the PDB next to the image if no /pdb flag was passed. 1132 if (Config->Debug && Config->PDBPath.empty()) { 1133 Config->PDBPath = Config->OutputFile; 1134 sys::path::replace_extension(Config->PDBPath, ".pdb"); 1135 } 1136 1137 // Disable PDB generation if the user requested it. 1138 if (Args.hasArg(OPT_nopdb) || Args.hasArg(OPT_debug_dwarf)) 1139 Config->PDBPath = ""; 1140 1141 // Set default image base if /base is not given. 1142 if (Config->ImageBase == uint64_t(-1)) 1143 Config->ImageBase = getDefaultImageBase(); 1144 1145 Symtab->addSynthetic(mangle("__ImageBase"), nullptr); 1146 if (Config->Machine == I386) { 1147 Symtab->addAbsolute("___safe_se_handler_table", 0); 1148 Symtab->addAbsolute("___safe_se_handler_count", 0); 1149 } 1150 1151 // We do not support /guard:cf (control flow protection) yet. 1152 // Define CFG symbols anyway so that we can link MSVC 2015 CRT. 1153 Symtab->addAbsolute(mangle("__guard_fids_count"), 0); 1154 Symtab->addAbsolute(mangle("__guard_fids_table"), 0); 1155 Symtab->addAbsolute(mangle("__guard_flags"), 0x100); 1156 Symtab->addAbsolute(mangle("__guard_iat_count"), 0); 1157 Symtab->addAbsolute(mangle("__guard_iat_table"), 0); 1158 Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 1159 Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 1160 1161 // This code may add new undefined symbols to the link, which may enqueue more 1162 // symbol resolution tasks, so we need to continue executing tasks until we 1163 // converge. 1164 do { 1165 // Windows specific -- if entry point is not found, 1166 // search for its mangled names. 1167 if (Config->Entry) 1168 Symtab->mangleMaybe(Config->Entry); 1169 1170 // Windows specific -- Make sure we resolve all dllexported symbols. 1171 for (Export &E : Config->Exports) { 1172 if (!E.ForwardTo.empty()) 1173 continue; 1174 E.Sym = addUndefined(E.Name); 1175 if (!E.Directives) 1176 Symtab->mangleMaybe(E.Sym); 1177 } 1178 1179 // Add weak aliases. Weak aliases is a mechanism to give remaining 1180 // undefined symbols final chance to be resolved successfully. 1181 for (auto Pair : Config->AlternateNames) { 1182 StringRef From = Pair.first; 1183 StringRef To = Pair.second; 1184 Symbol *Sym = Symtab->find(From); 1185 if (!Sym) 1186 continue; 1187 if (auto *U = dyn_cast<Undefined>(Sym)) 1188 if (!U->WeakAlias) 1189 U->WeakAlias = Symtab->addUndefined(To); 1190 } 1191 1192 // Windows specific -- if __load_config_used can be resolved, resolve it. 1193 if (Symtab->findUnderscore("_load_config_used")) 1194 addUndefined(mangle("_load_config_used")); 1195 } while (run()); 1196 1197 if (errorCount()) 1198 return; 1199 1200 // If /msvclto is given, we use the MSVC linker to link LTO output files. 1201 // This is useful because MSVC link.exe can generate complete PDBs. 1202 if (Args.hasArg(OPT_msvclto)) { 1203 invokeMSVC(Args); 1204 return; 1205 } 1206 1207 // Do LTO by compiling bitcode input files to a set of native COFF files then 1208 // link those files. 1209 Symtab->addCombinedLTOObjects(); 1210 run(); 1211 1212 // Make sure we have resolved all symbols. 1213 Symtab->reportRemainingUndefines(); 1214 if (errorCount()) 1215 return; 1216 1217 // Windows specific -- if no /subsystem is given, we need to infer 1218 // that from entry point name. 1219 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 1220 Config->Subsystem = inferSubsystem(); 1221 if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 1222 fatal("subsystem must be defined"); 1223 } 1224 1225 // Handle /safeseh. 1226 if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { 1227 for (ObjFile *File : ObjFile::Instances) 1228 if (!File->SEHCompat) 1229 error("/safeseh: " + File->getName() + " is not compatible with SEH"); 1230 if (errorCount()) 1231 return; 1232 } 1233 1234 // In MinGW, all symbols are automatically exported if no symbols 1235 // are chosen to be exported. 1236 if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) || 1237 Args.hasArg(OPT_export_all_symbols))) { 1238 AutoExporter Exporter; 1239 1240 Symtab->forEachSymbol([=](Symbol *S) { 1241 auto *Def = dyn_cast<Defined>(S); 1242 if (!Exporter.shouldExport(Def)) 1243 return; 1244 Export E; 1245 E.Name = Def->getName(); 1246 E.Sym = Def; 1247 if (Def->getChunk() && 1248 !(Def->getChunk()->getPermissions() & IMAGE_SCN_MEM_EXECUTE)) 1249 E.Data = true; 1250 Config->Exports.push_back(E); 1251 }); 1252 } 1253 1254 // Windows specific -- when we are creating a .dll file, we also 1255 // need to create a .lib file. 1256 if (!Config->Exports.empty() || Config->DLL) { 1257 fixupExports(); 1258 createImportLibrary(/*AsLib=*/false); 1259 assignExportOrdinals(); 1260 } 1261 1262 // Handle /output-def (MinGW specific). 1263 if (auto *Arg = Args.getLastArg(OPT_output_def)) 1264 writeDefFile(Arg->getValue()); 1265 1266 // Set extra alignment for .comm symbols 1267 for (auto Pair : Config->AlignComm) { 1268 StringRef Name = Pair.first; 1269 uint32_t Alignment = Pair.second; 1270 1271 Symbol *Sym = Symtab->find(Name); 1272 if (!Sym) { 1273 warn("/aligncomm symbol " + Name + " not found"); 1274 continue; 1275 } 1276 1277 auto *DC = dyn_cast<DefinedCommon>(Sym); 1278 if (!DC) { 1279 warn("/aligncomm symbol " + Name + " of wrong kind"); 1280 continue; 1281 } 1282 1283 CommonChunk *C = DC->getChunk(); 1284 C->Alignment = std::max(C->Alignment, Alignment); 1285 } 1286 1287 // Windows specific -- Create a side-by-side manifest file. 1288 if (Config->Manifest == Configuration::SideBySide) 1289 createSideBySideManifest(); 1290 1291 // Identify unreferenced COMDAT sections. 1292 if (Config->DoGC) 1293 markLive(Symtab->getChunks()); 1294 1295 // Identify identical COMDAT sections to merge them. 1296 if (Config->DoICF) 1297 doICF(Symtab->getChunks()); 1298 1299 // Write the result. 1300 writeResult(); 1301 } 1302 1303 } // namespace coff 1304 } // namespace lld 1305