Index: vendor/lld/dist-release_70/COFF/Driver.cpp =================================================================== --- vendor/lld/dist-release_70/COFF/Driver.cpp (revision 338582) +++ vendor/lld/dist-release_70/COFF/Driver.cpp (revision 338583) @@ -1,1592 +1,1590 @@ //===- Driver.cpp ---------------------------------------------------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "Driver.h" #include "Config.h" #include "ICF.h" #include "InputFiles.h" #include "MarkLive.h" #include "MinGW.h" #include "SymbolTable.h" #include "Symbols.h" #include "Writer.h" #include "lld/Common/Args.h" #include "lld/Common/Driver.h" #include "lld/Common/ErrorHandler.h" #include "lld/Common/Memory.h" #include "lld/Common/Timer.h" #include "lld/Common/Version.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringSwitch.h" #include "llvm/BinaryFormat/Magic.h" #include "llvm/Object/ArchiveWriter.h" #include "llvm/Object/COFFImportFile.h" #include "llvm/Object/COFFModuleDefinition.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Option/Option.h" #include "llvm/Support/Debug.h" #include "llvm/Support/Path.h" #include "llvm/Support/Process.h" #include "llvm/Support/TarWriter.h" #include "llvm/Support/TargetSelect.h" #include "llvm/Support/raw_ostream.h" #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" #include #include #include using namespace llvm; using namespace llvm::object; using namespace llvm::COFF; using llvm::sys::Process; namespace lld { namespace coff { static Timer InputFileTimer("Input File Reading", Timer::root()); Configuration *Config; LinkerDriver *Driver; bool link(ArrayRef Args, bool CanExitEarly, raw_ostream &Diag) { errorHandler().LogName = sys::path::filename(Args[0]); errorHandler().ErrorOS = &Diag; errorHandler().ColorDiagnostics = Diag.has_colors(); errorHandler().ErrorLimitExceededMsg = "too many errors emitted, stopping now" " (use /errorlimit:0 to see all errors)"; errorHandler().ExitEarly = CanExitEarly; Config = make(); Symtab = make(); Driver = make(); Driver->link(Args); // Call exit() if we can to avoid calling destructors. if (CanExitEarly) exitLld(errorCount() ? 1 : 0); freeArena(); ObjFile::Instances.clear(); ImportFile::Instances.clear(); BitcodeFile::Instances.clear(); return !errorCount(); } // Drop directory components and replace extension with ".exe" or ".dll". static std::string getOutputPath(StringRef Path) { auto P = Path.find_last_of("\\/"); StringRef S = (P == StringRef::npos) ? Path : Path.substr(P + 1); const char* E = Config->DLL ? ".dll" : ".exe"; return (S.substr(0, S.rfind('.')) + E).str(); } // ErrorOr is not default constructible, so it cannot be used as the type // parameter of a future. // FIXME: We could open the file in createFutureForFile and avoid needing to // return an error here, but for the moment that would cost us a file descriptor // (a limited resource on Windows) for the duration that the future is pending. typedef std::pair, std::error_code> MBErrPair; // Create a std::future that opens and maps a file using the best strategy for // the host platform. static std::future createFutureForFile(std::string Path) { #if _WIN32 // On Windows, file I/O is relatively slow so it is best to do this // asynchronously. auto Strategy = std::launch::async; #else auto Strategy = std::launch::deferred; #endif return std::async(Strategy, [=]() { auto MBOrErr = MemoryBuffer::getFile(Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false); if (!MBOrErr) return MBErrPair{nullptr, MBOrErr.getError()}; return MBErrPair{std::move(*MBOrErr), std::error_code()}; }); } +// Symbol names are mangled by prepending "_" on x86. +static StringRef mangle(StringRef Sym) { + assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); + if (Config->Machine == I386) + return Saver.save("_" + Sym); + return Sym; +} + +static bool findUnderscoreMangle(StringRef Sym) { + StringRef Entry = Symtab->findMangle(mangle(Sym)); + return !Entry.empty() && !isa(Symtab->find(Entry)); +} + MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr MB) { MemoryBufferRef MBRef = *MB; make>(std::move(MB)); // take ownership if (Driver->Tar) Driver->Tar->append(relativeToRoot(MBRef.getBufferIdentifier()), MBRef.getBuffer()); return MBRef; } void LinkerDriver::addBuffer(std::unique_ptr MB, bool WholeArchive) { StringRef Filename = MB->getBufferIdentifier(); MemoryBufferRef MBRef = takeBuffer(std::move(MB)); FilePaths.push_back(Filename); // File type is detected by contents, not by file extension. switch (identify_magic(MBRef.getBuffer())) { case file_magic::windows_resource: Resources.push_back(MBRef); break; case file_magic::archive: if (WholeArchive) { std::unique_ptr File = CHECK(Archive::create(MBRef), Filename + ": failed to parse archive"); for (MemoryBufferRef M : getArchiveMembers(File.get())) addArchiveBuffer(M, "", Filename); return; } Symtab->addFile(make(MBRef)); break; case file_magic::bitcode: Symtab->addFile(make(MBRef)); break; case file_magic::coff_object: case file_magic::coff_import_library: Symtab->addFile(make(MBRef)); break; case file_magic::coff_cl_gl_object: error(Filename + ": is not a native COFF file. Recompile without /GL"); break; case file_magic::pecoff_executable: if (Filename.endswith_lower(".dll")) { error(Filename + ": bad file type. Did you specify a DLL instead of an " "import library?"); break; } LLVM_FALLTHROUGH; default: error(MBRef.getBufferIdentifier() + ": unknown file type"); break; } } void LinkerDriver::enqueuePath(StringRef Path, bool WholeArchive) { auto Future = std::make_shared>(createFutureForFile(Path)); std::string PathStr = Path; enqueueTask([=]() { auto MBOrErr = Future->get(); if (MBOrErr.second) error("could not open " + PathStr + ": " + MBOrErr.second.message()); else Driver->addBuffer(std::move(MBOrErr.first), WholeArchive); }); } void LinkerDriver::addArchiveBuffer(MemoryBufferRef MB, StringRef SymName, StringRef ParentName) { file_magic Magic = identify_magic(MB.getBuffer()); if (Magic == file_magic::coff_import_library) { Symtab->addFile(make(MB)); return; } InputFile *Obj; if (Magic == file_magic::coff_object) { Obj = make(MB); } else if (Magic == file_magic::bitcode) { Obj = make(MB); } else { error("unknown file type: " + MB.getBufferIdentifier()); return; } Obj->ParentName = ParentName; Symtab->addFile(Obj); log("Loaded " + toString(Obj) + " for " + SymName); } void LinkerDriver::enqueueArchiveMember(const Archive::Child &C, StringRef SymName, StringRef ParentName) { if (!C.getParent()->isThin()) { MemoryBufferRef MB = CHECK( C.getMemoryBufferRef(), "could not get the buffer for the member defining symbol " + SymName); enqueueTask([=]() { Driver->addArchiveBuffer(MB, SymName, ParentName); }); return; } auto Future = std::make_shared>(createFutureForFile( CHECK(C.getFullName(), "could not get the filename for the member defining symbol " + SymName))); enqueueTask([=]() { auto MBOrErr = Future->get(); if (MBOrErr.second) fatal("could not get the buffer for the member defining " + SymName + ": " + MBOrErr.second.message()); Driver->addArchiveBuffer(takeBuffer(std::move(MBOrErr.first)), SymName, ParentName); }); } static bool isDecorated(StringRef Sym) { return Sym.startswith("@") || Sym.contains("@@") || Sym.startswith("?") || (!Config->MinGW && Sym.contains('@')); } // Parses .drectve section contents and returns a list of files // specified by /defaultlib. void LinkerDriver::parseDirectives(StringRef S) { ArgParser Parser; // .drectve is always tokenized using Windows shell rules. // /EXPORT: option can appear too many times, processing in fastpath. opt::InputArgList Args; std::vector Exports; std::tie(Args, Exports) = Parser.parseDirectives(S); for (StringRef E : Exports) { // If a common header file contains dllexported function // declarations, many object files may end up with having the // same /EXPORT options. In order to save cost of parsing them, // we dedup them first. if (!DirectivesExports.insert(E).second) continue; Export Exp = parseExport(E); if (Config->Machine == I386 && Config->MinGW) { if (!isDecorated(Exp.Name)) Exp.Name = Saver.save("_" + Exp.Name); if (!Exp.ExtName.empty() && !isDecorated(Exp.ExtName)) Exp.ExtName = Saver.save("_" + Exp.ExtName); } Exp.Directives = true; Config->Exports.push_back(Exp); } for (auto *Arg : Args) { switch (Arg->getOption().getUnaliasedOption().getID()) { case OPT_aligncomm: parseAligncomm(Arg->getValue()); break; case OPT_alternatename: parseAlternateName(Arg->getValue()); break; case OPT_defaultlib: if (Optional Path = findLib(Arg->getValue())) enqueuePath(*Path, false); break; case OPT_entry: Config->Entry = addUndefined(mangle(Arg->getValue())); break; case OPT_failifmismatch: checkFailIfMismatch(Arg->getValue()); break; case OPT_incl: addUndefined(Arg->getValue()); break; case OPT_merge: parseMerge(Arg->getValue()); break; case OPT_nodefaultlib: Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); break; case OPT_section: parseSection(Arg->getValue()); break; case OPT_subsystem: parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, &Config->MinorOSVersion); break; case OPT_editandcontinue: case OPT_fastfail: case OPT_guardsym: case OPT_natvis: case OPT_throwingnew: break; default: error(Arg->getSpelling() + " is not allowed in .drectve"); } } } // Find file from search paths. You can omit ".obj", this function takes // care of that. Note that the returned path is not guaranteed to exist. StringRef LinkerDriver::doFindFile(StringRef Filename) { bool HasPathSep = (Filename.find_first_of("/\\") != StringRef::npos); if (HasPathSep) return Filename; bool HasExt = Filename.contains('.'); for (StringRef Dir : SearchPaths) { SmallString<128> Path = Dir; sys::path::append(Path, Filename); if (sys::fs::exists(Path.str())) return Saver.save(Path.str()); if (!HasExt) { Path.append(".obj"); if (sys::fs::exists(Path.str())) return Saver.save(Path.str()); } } return Filename; } static Optional getUniqueID(StringRef Path) { sys::fs::UniqueID Ret; if (sys::fs::getUniqueID(Path, Ret)) return None; return Ret; } // Resolves a file path. This never returns the same path // (in that case, it returns None). Optional LinkerDriver::findFile(StringRef Filename) { StringRef Path = doFindFile(Filename); if (Optional ID = getUniqueID(Path)) { bool Seen = !VisitedFiles.insert(*ID).second; if (Seen) return None; } if (Path.endswith_lower(".lib")) VisitedLibs.insert(sys::path::filename(Path)); return Path; } // Find library file from search path. StringRef LinkerDriver::doFindLib(StringRef Filename) { // Add ".lib" to Filename if that has no file extension. bool HasExt = Filename.contains('.'); if (!HasExt) Filename = Saver.save(Filename + ".lib"); return doFindFile(Filename); } // Resolves a library path. /nodefaultlib options are taken into // consideration. This never returns the same path (in that case, // it returns None). Optional LinkerDriver::findLib(StringRef Filename) { if (Config->NoDefaultLibAll) return None; if (!VisitedLibs.insert(Filename.lower()).second) return None; StringRef Path = doFindLib(Filename); if (Config->NoDefaultLibs.count(Path)) return None; if (Optional ID = getUniqueID(Path)) if (!VisitedFiles.insert(*ID).second) return None; return Path; } // Parses LIB environment which contains a list of search paths. void LinkerDriver::addLibSearchPaths() { Optional EnvOpt = Process::GetEnv("LIB"); if (!EnvOpt.hasValue()) return; StringRef Env = Saver.save(*EnvOpt); while (!Env.empty()) { StringRef Path; std::tie(Path, Env) = Env.split(';'); SearchPaths.push_back(Path); } } Symbol *LinkerDriver::addUndefined(StringRef Name) { Symbol *B = Symtab->addUndefined(Name); if (!B->IsGCRoot) { B->IsGCRoot = true; Config->GCRoot.push_back(B); } return B; } -// Symbol names are mangled by appending "_" prefix on x86. -StringRef LinkerDriver::mangle(StringRef Sym) { - assert(Config->Machine != IMAGE_FILE_MACHINE_UNKNOWN); - if (Config->Machine == I386) - return Saver.save("_" + Sym); - return Sym; -} - // Windows specific -- find default entry point name. // // There are four different entry point functions for Windows executables, // each of which corresponds to a user-defined "main" function. This function // infers an entry point from a user-defined "main" function. StringRef LinkerDriver::findDefaultEntry() { + assert(Config->Subsystem != IMAGE_SUBSYSTEM_UNKNOWN && + "must handle /subsystem before calling this"); + // As a special case, if /nodefaultlib is given, we directly look for an // entry point. This is because, if no default library is linked, users // need to define an entry point instead of a "main". - if (Config->NoDefaultLibAll) { - for (StringRef S : {"mainCRTStartup", "wmainCRTStartup", - "WinMainCRTStartup", "wWinMainCRTStartup"}) { - StringRef Entry = Symtab->findMangle(S); - if (!Entry.empty() && !isa(Symtab->find(Entry))) - return mangle(S); - } - return ""; + bool FindMain = !Config->NoDefaultLibAll; + if (Config->Subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { + if (findUnderscoreMangle(FindMain ? "WinMain" : "WinMainCRTStartup")) + return mangle("WinMainCRTStartup"); + if (findUnderscoreMangle(FindMain ? "wWinMain" : "wWinMainCRTStartup")) + return mangle("wWinMainCRTStartup"); } - - // User-defined main functions and their corresponding entry points. - static const char *Entries[][2] = { - {"main", "mainCRTStartup"}, - {"wmain", "wmainCRTStartup"}, - {"WinMain", "WinMainCRTStartup"}, - {"wWinMain", "wWinMainCRTStartup"}, - }; - for (auto E : Entries) { - StringRef Entry = Symtab->findMangle(mangle(E[0])); - if (!Entry.empty() && !isa(Symtab->find(Entry))) - return mangle(E[1]); - } + if (findUnderscoreMangle(FindMain ? "main" : "mainCRTStartup")) + return mangle("mainCRTStartup"); + if (findUnderscoreMangle(FindMain ? "wmain" : "wmainCRTStartup")) + return mangle("wmainCRTStartup"); return ""; } WindowsSubsystem LinkerDriver::inferSubsystem() { if (Config->DLL) return IMAGE_SUBSYSTEM_WINDOWS_GUI; - if (Symtab->findUnderscore("main") || Symtab->findUnderscore("wmain")) + if (findUnderscoreMangle("main") || findUnderscoreMangle("wmain")) return IMAGE_SUBSYSTEM_WINDOWS_CUI; - if (Symtab->findUnderscore("WinMain") || Symtab->findUnderscore("wWinMain")) + if (findUnderscoreMangle("WinMain") || findUnderscoreMangle("wWinMain")) return IMAGE_SUBSYSTEM_WINDOWS_GUI; return IMAGE_SUBSYSTEM_UNKNOWN; } static uint64_t getDefaultImageBase() { if (Config->is64()) return Config->DLL ? 0x180000000 : 0x140000000; return Config->DLL ? 0x10000000 : 0x400000; } static std::string createResponseFile(const opt::InputArgList &Args, ArrayRef FilePaths, ArrayRef SearchPaths) { SmallString<0> Data; raw_svector_ostream OS(Data); for (auto *Arg : Args) { switch (Arg->getOption().getID()) { case OPT_linkrepro: case OPT_INPUT: case OPT_defaultlib: case OPT_libpath: case OPT_manifest: case OPT_manifest_colon: case OPT_manifestdependency: case OPT_manifestfile: case OPT_manifestinput: case OPT_manifestuac: break; default: OS << toString(*Arg) << "\n"; } } for (StringRef Path : SearchPaths) { std::string RelPath = relativeToRoot(Path); OS << "/libpath:" << quote(RelPath) << "\n"; } for (StringRef Path : FilePaths) OS << quote(relativeToRoot(Path)) << "\n"; return Data.str(); } static unsigned getDefaultDebugType(const opt::InputArgList &Args) { unsigned DebugTypes = static_cast(DebugType::CV); if (Args.hasArg(OPT_driver)) DebugTypes |= static_cast(DebugType::PData); if (Args.hasArg(OPT_profile)) DebugTypes |= static_cast(DebugType::Fixup); return DebugTypes; } static unsigned parseDebugType(StringRef Arg) { SmallVector Types; Arg.split(Types, ',', /*KeepEmpty=*/false); unsigned DebugTypes = static_cast(DebugType::None); for (StringRef Type : Types) DebugTypes |= StringSwitch(Type.lower()) .Case("cv", static_cast(DebugType::CV)) .Case("pdata", static_cast(DebugType::PData)) .Case("fixup", static_cast(DebugType::Fixup)) .Default(0); return DebugTypes; } static std::string getMapFile(const opt::InputArgList &Args) { auto *Arg = Args.getLastArg(OPT_lldmap, OPT_lldmap_file); if (!Arg) return ""; if (Arg->getOption().getID() == OPT_lldmap_file) return Arg->getValue(); assert(Arg->getOption().getID() == OPT_lldmap); StringRef OutFile = Config->OutputFile; return (OutFile.substr(0, OutFile.rfind('.')) + ".map").str(); } static std::string getImplibPath() { if (!Config->Implib.empty()) return Config->Implib; SmallString<128> Out = StringRef(Config->OutputFile); sys::path::replace_extension(Out, ".lib"); return Out.str(); } // // The import name is caculated as the following: // // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY // -----+----------------+---------------------+------------------ // LINK | {value} | {value}.{.dll/.exe} | {output name} // LIB | {value} | {value}.dll | {output name}.dll // static std::string getImportName(bool AsLib) { SmallString<128> Out; if (Config->ImportName.empty()) { Out.assign(sys::path::filename(Config->OutputFile)); if (AsLib) sys::path::replace_extension(Out, ".dll"); } else { Out.assign(Config->ImportName); if (!sys::path::has_extension(Out)) sys::path::replace_extension(Out, (Config->DLL || AsLib) ? ".dll" : ".exe"); } return Out.str(); } static void createImportLibrary(bool AsLib) { std::vector Exports; for (Export &E1 : Config->Exports) { COFFShortExport E2; E2.Name = E1.Name; E2.SymbolName = E1.SymbolName; E2.ExtName = E1.ExtName; E2.Ordinal = E1.Ordinal; E2.Noname = E1.Noname; E2.Data = E1.Data; E2.Private = E1.Private; E2.Constant = E1.Constant; Exports.push_back(E2); } auto HandleError = [](Error &&E) { handleAllErrors(std::move(E), [](ErrorInfoBase &EIB) { error(EIB.message()); }); }; std::string LibName = getImportName(AsLib); std::string Path = getImplibPath(); if (!Config->Incremental) { HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, Config->MinGW)); return; } // If the import library already exists, replace it only if the contents // have changed. ErrorOr> OldBuf = MemoryBuffer::getFile( Path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false); if (!OldBuf) { HandleError(writeImportLibrary(LibName, Path, Exports, Config->Machine, Config->MinGW)); return; } SmallString<128> TmpName; if (std::error_code EC = sys::fs::createUniqueFile(Path + ".tmp-%%%%%%%%.lib", TmpName)) fatal("cannot create temporary file for import library " + Path + ": " + EC.message()); if (Error E = writeImportLibrary(LibName, TmpName, Exports, Config->Machine, Config->MinGW)) { HandleError(std::move(E)); return; } std::unique_ptr NewBuf = check(MemoryBuffer::getFile( TmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false)); if ((*OldBuf)->getBuffer() != NewBuf->getBuffer()) { OldBuf->reset(); HandleError(errorCodeToError(sys::fs::rename(TmpName, Path))); } else { sys::fs::remove(TmpName); } } static void parseModuleDefs(StringRef Path) { std::unique_ptr MB = CHECK( MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); COFFModuleDefinition M = check(parseCOFFModuleDefinition( MB->getMemBufferRef(), Config->Machine, Config->MinGW)); if (Config->OutputFile.empty()) Config->OutputFile = Saver.save(M.OutputFile); Config->ImportName = Saver.save(M.ImportName); if (M.ImageBase) Config->ImageBase = M.ImageBase; if (M.StackReserve) Config->StackReserve = M.StackReserve; if (M.StackCommit) Config->StackCommit = M.StackCommit; if (M.HeapReserve) Config->HeapReserve = M.HeapReserve; if (M.HeapCommit) Config->HeapCommit = M.HeapCommit; if (M.MajorImageVersion) Config->MajorImageVersion = M.MajorImageVersion; if (M.MinorImageVersion) Config->MinorImageVersion = M.MinorImageVersion; if (M.MajorOSVersion) Config->MajorOSVersion = M.MajorOSVersion; if (M.MinorOSVersion) Config->MinorOSVersion = M.MinorOSVersion; for (COFFShortExport E1 : M.Exports) { Export E2; // In simple cases, only Name is set. Renamed exports are parsed // and set as "ExtName = Name". If Name has the form "OtherDll.Func", // it shouldn't be a normal exported function but a forward to another // DLL instead. This is supported by both MS and GNU linkers. if (E1.ExtName != E1.Name && StringRef(E1.Name).contains('.')) { E2.Name = Saver.save(E1.ExtName); E2.ForwardTo = Saver.save(E1.Name); Config->Exports.push_back(E2); continue; } E2.Name = Saver.save(E1.Name); E2.ExtName = Saver.save(E1.ExtName); E2.Ordinal = E1.Ordinal; E2.Noname = E1.Noname; E2.Data = E1.Data; E2.Private = E1.Private; E2.Constant = E1.Constant; Config->Exports.push_back(E2); } } // A helper function for filterBitcodeFiles. static bool needsRebuilding(MemoryBufferRef MB) { // The MSVC linker doesn't support thin archives, so if it's a thin // archive, we always need to rebuild it. std::unique_ptr File = CHECK(Archive::create(MB), "Failed to read " + MB.getBufferIdentifier()); if (File->isThin()) return true; // Returns true if the archive contains at least one bitcode file. for (MemoryBufferRef Member : getArchiveMembers(File.get())) if (identify_magic(Member.getBuffer()) == file_magic::bitcode) return true; return false; } // Opens a given path as an archive file and removes bitcode files // from them if exists. This function is to appease the MSVC linker as // their linker doesn't like archive files containing non-native // object files. // // If a given archive doesn't contain bitcode files, the archive path // is returned as-is. Otherwise, a new temporary file is created and // its path is returned. static Optional filterBitcodeFiles(StringRef Path, std::vector &TemporaryFiles) { std::unique_ptr MB = CHECK( MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); MemoryBufferRef MBRef = MB->getMemBufferRef(); file_magic Magic = identify_magic(MBRef.getBuffer()); if (Magic == file_magic::bitcode) return None; if (Magic != file_magic::archive) return Path.str(); if (!needsRebuilding(MBRef)) return Path.str(); std::unique_ptr File = CHECK(Archive::create(MBRef), MBRef.getBufferIdentifier() + ": failed to parse archive"); std::vector New; for (MemoryBufferRef Member : getArchiveMembers(File.get())) if (identify_magic(Member.getBuffer()) != file_magic::bitcode) New.emplace_back(Member); if (New.empty()) return None; log("Creating a temporary archive for " + Path + " to remove bitcode files"); SmallString<128> S; if (std::error_code EC = sys::fs::createTemporaryFile( "lld-" + sys::path::stem(Path), ".lib", S)) fatal("cannot create a temporary file: " + EC.message()); std::string Temp = S.str(); TemporaryFiles.push_back(Temp); Error E = llvm::writeArchive(Temp, New, /*WriteSymtab=*/true, Archive::Kind::K_GNU, /*Deterministics=*/true, /*Thin=*/false); handleAllErrors(std::move(E), [&](const ErrorInfoBase &EI) { error("failed to create a new archive " + S.str() + ": " + EI.message()); }); return Temp; } // Create response file contents and invoke the MSVC linker. void LinkerDriver::invokeMSVC(opt::InputArgList &Args) { std::string Rsp = "/nologo\n"; std::vector Temps; // Write out archive members that we used in symbol resolution and pass these // to MSVC before any archives, so that MSVC uses the same objects to satisfy // references. for (ObjFile *Obj : ObjFile::Instances) { if (Obj->ParentName.empty()) continue; SmallString<128> S; int Fd; if (auto EC = sys::fs::createTemporaryFile( "lld-" + sys::path::filename(Obj->ParentName), ".obj", Fd, S)) fatal("cannot create a temporary file: " + EC.message()); raw_fd_ostream OS(Fd, /*shouldClose*/ true); OS << Obj->MB.getBuffer(); Temps.push_back(S.str()); Rsp += quote(S) + "\n"; } for (auto *Arg : Args) { switch (Arg->getOption().getID()) { case OPT_linkrepro: case OPT_lldmap: case OPT_lldmap_file: case OPT_lldsavetemps: case OPT_msvclto: // LLD-specific options are stripped. break; case OPT_opt: if (!StringRef(Arg->getValue()).startswith("lld")) Rsp += toString(*Arg) + " "; break; case OPT_INPUT: { if (Optional Path = doFindFile(Arg->getValue())) { if (Optional S = filterBitcodeFiles(*Path, Temps)) Rsp += quote(*S) + "\n"; continue; } Rsp += quote(Arg->getValue()) + "\n"; break; } default: Rsp += toString(*Arg) + "\n"; } } std::vector ObjFiles = Symtab->compileBitcodeFiles(); runMSVCLinker(Rsp, ObjFiles); for (StringRef Path : Temps) sys::fs::remove(Path); } void LinkerDriver::enqueueTask(std::function Task) { TaskQueue.push_back(std::move(Task)); } bool LinkerDriver::run() { ScopedTimer T(InputFileTimer); bool DidWork = !TaskQueue.empty(); while (!TaskQueue.empty()) { TaskQueue.front()(); TaskQueue.pop_front(); } return DidWork; } // Parse an /order file. If an option is given, the linker places // COMDAT sections in the same order as their names appear in the // given file. static void parseOrderFile(StringRef Arg) { // For some reason, the MSVC linker requires a filename to be // preceded by "@". if (!Arg.startswith("@")) { error("malformed /order option: '@' missing"); return; } // Get a list of all comdat sections for error checking. DenseSet Set; for (Chunk *C : Symtab->getChunks()) if (auto *Sec = dyn_cast(C)) if (Sec->Sym) Set.insert(Sec->Sym->getName()); // Open a file. StringRef Path = Arg.substr(1); std::unique_ptr MB = CHECK( MemoryBuffer::getFile(Path, -1, false, true), "could not open " + Path); // Parse a file. An order file contains one symbol per line. // All symbols that were not present in a given order file are // considered to have the lowest priority 0 and are placed at // end of an output section. for (std::string S : args::getLines(MB->getMemBufferRef())) { if (Config->Machine == I386 && !isDecorated(S)) S = "_" + S; if (Set.count(S) == 0) { if (Config->WarnMissingOrderSymbol) warn("/order:" + Arg + ": missing symbol: " + S + " [LNK4037]"); } else Config->Order[S] = INT_MIN + Config->Order.size(); } } void LinkerDriver::link(ArrayRef ArgsArr) { // If the first command line argument is "/lib", link.exe acts like lib.exe. // We call our own implementation of lib.exe that understands bitcode files. if (ArgsArr.size() > 1 && StringRef(ArgsArr[1]).equals_lower("/lib")) { if (llvm::libDriverMain(ArgsArr.slice(1)) != 0) fatal("lib failed"); return; } // Needed for LTO. InitializeAllTargetInfos(); InitializeAllTargets(); InitializeAllTargetMCs(); InitializeAllAsmParsers(); InitializeAllAsmPrinters(); // Parse command line options. ArgParser Parser; opt::InputArgList Args = Parser.parseLINK(ArgsArr); // Parse and evaluate -mllvm options. std::vector V; V.push_back("lld-link (LLVM option parsing)"); for (auto *Arg : Args.filtered(OPT_mllvm)) V.push_back(Arg->getValue()); cl::ParseCommandLineOptions(V.size(), V.data()); // Handle /errorlimit early, because error() depends on it. if (auto *Arg = Args.getLastArg(OPT_errorlimit)) { int N = 20; StringRef S = Arg->getValue(); if (S.getAsInteger(10, N)) error(Arg->getSpelling() + " number expected, but got " + S); errorHandler().ErrorLimit = N; } // Handle /help if (Args.hasArg(OPT_help)) { printHelp(ArgsArr[0]); return; } if (Args.hasArg(OPT_show_timing)) Config->ShowTiming = true; ScopedTimer T(Timer::root()); // Handle --version, which is an lld extension. This option is a bit odd // because it doesn't start with "/", but we deliberately chose "--" to // avoid conflict with /version and for compatibility with clang-cl. if (Args.hasArg(OPT_dash_dash_version)) { outs() << getLLDVersion() << "\n"; return; } // Handle /lldmingw early, since it can potentially affect how other // options are handled. Config->MinGW = Args.hasArg(OPT_lldmingw); if (auto *Arg = Args.getLastArg(OPT_linkrepro)) { SmallString<64> Path = StringRef(Arg->getValue()); sys::path::append(Path, "repro.tar"); Expected> ErrOrWriter = TarWriter::create(Path, "repro"); if (ErrOrWriter) { Tar = std::move(*ErrOrWriter); } else { error("/linkrepro: failed to open " + Path + ": " + toString(ErrOrWriter.takeError())); } } if (!Args.hasArg(OPT_INPUT)) { if (Args.hasArg(OPT_deffile)) Config->NoEntry = true; else fatal("no input files"); } // Construct search path list. SearchPaths.push_back(""); for (auto *Arg : Args.filtered(OPT_libpath)) SearchPaths.push_back(Arg->getValue()); addLibSearchPaths(); // Handle /ignore for (auto *Arg : Args.filtered(OPT_ignore)) { if (StringRef(Arg->getValue()) == "4037") Config->WarnMissingOrderSymbol = false; else if (StringRef(Arg->getValue()) == "4217") Config->WarnLocallyDefinedImported = false; // Other warning numbers are ignored. } // Handle /out if (auto *Arg = Args.getLastArg(OPT_out)) Config->OutputFile = Arg->getValue(); // Handle /verbose if (Args.hasArg(OPT_verbose)) Config->Verbose = true; errorHandler().Verbose = Config->Verbose; // Handle /force or /force:unresolved if (Args.hasArg(OPT_force, OPT_force_unresolved)) Config->Force = true; // Handle /debug if (Args.hasArg(OPT_debug, OPT_debug_dwarf, OPT_debug_ghash)) { Config->Debug = true; Config->Incremental = true; if (auto *Arg = Args.getLastArg(OPT_debugtype)) Config->DebugTypes = parseDebugType(Arg->getValue()); else Config->DebugTypes = getDefaultDebugType(Args); } // Handle /pdb bool ShouldCreatePDB = Args.hasArg(OPT_debug, OPT_debug_ghash); if (ShouldCreatePDB) { if (auto *Arg = Args.getLastArg(OPT_pdb)) Config->PDBPath = Arg->getValue(); if (auto *Arg = Args.getLastArg(OPT_pdbaltpath)) Config->PDBAltPath = Arg->getValue(); if (Args.hasArg(OPT_natvis)) Config->NatvisFiles = Args.getAllArgValues(OPT_natvis); if (auto *Arg = Args.getLastArg(OPT_pdb_source_path)) Config->PDBSourcePath = Arg->getValue(); } // Handle /noentry if (Args.hasArg(OPT_noentry)) { if (Args.hasArg(OPT_dll)) Config->NoEntry = true; else error("/noentry must be specified with /dll"); } // Handle /dll if (Args.hasArg(OPT_dll)) { Config->DLL = true; Config->ManifestID = 2; } // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase // because we need to explicitly check whether that option or its inverse was // present in the argument list in order to handle /fixed. auto *DynamicBaseArg = Args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); if (DynamicBaseArg && DynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) Config->DynamicBase = false; // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the // default setting for any other project type.", but link.exe defaults to // /FIXED:NO for exe outputs as well. Match behavior, not docs. bool Fixed = Args.hasFlag(OPT_fixed, OPT_fixed_no, false); if (Fixed) { if (DynamicBaseArg && DynamicBaseArg->getOption().getID() == OPT_dynamicbase) { error("/fixed must not be specified with /dynamicbase"); } else { Config->Relocatable = false; Config->DynamicBase = false; } } // Handle /appcontainer Config->AppContainer = Args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); // Handle /machine if (auto *Arg = Args.getLastArg(OPT_machine)) Config->Machine = getMachineType(Arg->getValue()); // Handle /nodefaultlib: for (auto *Arg : Args.filtered(OPT_nodefaultlib)) Config->NoDefaultLibs.insert(doFindLib(Arg->getValue())); // Handle /nodefaultlib if (Args.hasArg(OPT_nodefaultlib_all)) Config->NoDefaultLibAll = true; // Handle /base if (auto *Arg = Args.getLastArg(OPT_base)) parseNumbers(Arg->getValue(), &Config->ImageBase); // Handle /stack if (auto *Arg = Args.getLastArg(OPT_stack)) parseNumbers(Arg->getValue(), &Config->StackReserve, &Config->StackCommit); // Handle /guard:cf if (auto *Arg = Args.getLastArg(OPT_guard)) parseGuard(Arg->getValue()); // Handle /heap if (auto *Arg = Args.getLastArg(OPT_heap)) parseNumbers(Arg->getValue(), &Config->HeapReserve, &Config->HeapCommit); // Handle /version if (auto *Arg = Args.getLastArg(OPT_version)) parseVersion(Arg->getValue(), &Config->MajorImageVersion, &Config->MinorImageVersion); // Handle /subsystem if (auto *Arg = Args.getLastArg(OPT_subsystem)) parseSubsystem(Arg->getValue(), &Config->Subsystem, &Config->MajorOSVersion, &Config->MinorOSVersion); // Handle /timestamp if (llvm::opt::Arg *Arg = Args.getLastArg(OPT_timestamp, OPT_repro)) { if (Arg->getOption().getID() == OPT_repro) { Config->Timestamp = 0; Config->Repro = true; } else { Config->Repro = false; StringRef Value(Arg->getValue()); if (Value.getAsInteger(0, Config->Timestamp)) fatal(Twine("invalid timestamp: ") + Value + ". Expected 32-bit integer"); } } else { Config->Repro = false; Config->Timestamp = time(nullptr); } // Handle /alternatename for (auto *Arg : Args.filtered(OPT_alternatename)) parseAlternateName(Arg->getValue()); // Handle /include for (auto *Arg : Args.filtered(OPT_incl)) addUndefined(Arg->getValue()); // Handle /implib if (auto *Arg = Args.getLastArg(OPT_implib)) Config->Implib = Arg->getValue(); // Handle /opt. bool DoGC = !Args.hasArg(OPT_debug) || Args.hasArg(OPT_profile); unsigned ICFLevel = Args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on unsigned TailMerge = 1; for (auto *Arg : Args.filtered(OPT_opt)) { std::string Str = StringRef(Arg->getValue()).lower(); SmallVector Vec; StringRef(Str).split(Vec, ','); for (StringRef S : Vec) { if (S == "ref") { DoGC = true; } else if (S == "noref") { DoGC = false; } else if (S == "icf" || S.startswith("icf=")) { ICFLevel = 2; } else if (S == "noicf") { ICFLevel = 0; } else if (S == "lldtailmerge") { TailMerge = 2; } else if (S == "nolldtailmerge") { TailMerge = 0; } else if (S.startswith("lldlto=")) { StringRef OptLevel = S.substr(7); if (OptLevel.getAsInteger(10, Config->LTOO) || Config->LTOO > 3) error("/opt:lldlto: invalid optimization level: " + OptLevel); } else if (S.startswith("lldltojobs=")) { StringRef Jobs = S.substr(11); if (Jobs.getAsInteger(10, Config->ThinLTOJobs) || Config->ThinLTOJobs == 0) error("/opt:lldltojobs: invalid job count: " + Jobs); } else if (S.startswith("lldltopartitions=")) { StringRef N = S.substr(17); if (N.getAsInteger(10, Config->LTOPartitions) || Config->LTOPartitions == 0) error("/opt:lldltopartitions: invalid partition count: " + N); } else if (S != "lbr" && S != "nolbr") error("/opt: unknown option: " + S); } } // Limited ICF is enabled if GC is enabled and ICF was never mentioned // explicitly. // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical // code. If the user passes /OPT:ICF explicitly, LLD should merge identical // comdat readonly data. if (ICFLevel == 1 && !DoGC) ICFLevel = 0; Config->DoGC = DoGC; Config->DoICF = ICFLevel > 0; Config->TailMerge = (TailMerge == 1 && Config->DoICF) || TailMerge == 2; // Handle /lldsavetemps if (Args.hasArg(OPT_lldsavetemps)) Config->SaveTemps = true; // Handle /kill-at if (Args.hasArg(OPT_kill_at)) Config->KillAt = true; // Handle /lldltocache if (auto *Arg = Args.getLastArg(OPT_lldltocache)) Config->LTOCache = Arg->getValue(); // Handle /lldsavecachepolicy if (auto *Arg = Args.getLastArg(OPT_lldltocachepolicy)) Config->LTOCachePolicy = CHECK( parseCachePruningPolicy(Arg->getValue()), Twine("/lldltocachepolicy: invalid cache policy: ") + Arg->getValue()); // Handle /failifmismatch for (auto *Arg : Args.filtered(OPT_failifmismatch)) checkFailIfMismatch(Arg->getValue()); // Handle /merge for (auto *Arg : Args.filtered(OPT_merge)) parseMerge(Arg->getValue()); // Add default section merging rules after user rules. User rules take // precedence, but we will emit a warning if there is a conflict. parseMerge(".idata=.rdata"); parseMerge(".didat=.rdata"); parseMerge(".edata=.rdata"); parseMerge(".xdata=.rdata"); parseMerge(".bss=.data"); // Handle /section for (auto *Arg : Args.filtered(OPT_section)) parseSection(Arg->getValue()); // Handle /aligncomm for (auto *Arg : Args.filtered(OPT_aligncomm)) parseAligncomm(Arg->getValue()); // Handle /manifestdependency. This enables /manifest unless /manifest:no is // also passed. if (auto *Arg = Args.getLastArg(OPT_manifestdependency)) { Config->ManifestDependency = Arg->getValue(); Config->Manifest = Configuration::SideBySide; } // Handle /manifest and /manifest: if (auto *Arg = Args.getLastArg(OPT_manifest, OPT_manifest_colon)) { if (Arg->getOption().getID() == OPT_manifest) Config->Manifest = Configuration::SideBySide; else parseManifest(Arg->getValue()); } // Handle /manifestuac if (auto *Arg = Args.getLastArg(OPT_manifestuac)) parseManifestUAC(Arg->getValue()); // Handle /manifestfile if (auto *Arg = Args.getLastArg(OPT_manifestfile)) Config->ManifestFile = Arg->getValue(); // Handle /manifestinput for (auto *Arg : Args.filtered(OPT_manifestinput)) Config->ManifestInput.push_back(Arg->getValue()); if (!Config->ManifestInput.empty() && Config->Manifest != Configuration::Embed) { fatal("/manifestinput: requires /manifest:embed"); } // Handle miscellaneous boolean flags. Config->AllowBind = Args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); Config->AllowIsolation = Args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); Config->Incremental = Args.hasFlag(OPT_incremental, OPT_incremental_no, !Config->DoGC && !Config->DoICF && !Args.hasArg(OPT_order) && !Args.hasArg(OPT_profile)); Config->IntegrityCheck = Args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); Config->NxCompat = Args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); Config->TerminalServerAware = !Config->DLL && Args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); Config->DebugDwarf = Args.hasArg(OPT_debug_dwarf); Config->DebugGHashes = Args.hasArg(OPT_debug_ghash); Config->DebugSymtab = Args.hasArg(OPT_debug_symtab); Config->MapFile = getMapFile(Args); if (Config->Incremental && Args.hasArg(OPT_profile)) { warn("ignoring '/incremental' due to '/profile' specification"); Config->Incremental = false; } if (Config->Incremental && Args.hasArg(OPT_order)) { warn("ignoring '/incremental' due to '/order' specification"); Config->Incremental = false; } if (Config->Incremental && Config->DoGC) { warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " "disable"); Config->Incremental = false; } if (Config->Incremental && Config->DoICF) { warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " "disable"); Config->Incremental = false; } if (errorCount()) return; std::set WholeArchives; for (auto *Arg : Args.filtered(OPT_wholearchive_file)) if (Optional Path = doFindFile(Arg->getValue())) if (Optional ID = getUniqueID(*Path)) WholeArchives.insert(*ID); // A predicate returning true if a given path is an argument for // /wholearchive:, or /wholearchive is enabled globally. // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" // needs to be handled as "/wholearchive:foo.obj foo.obj". auto IsWholeArchive = [&](StringRef Path) -> bool { if (Args.hasArg(OPT_wholearchive_flag)) return true; if (Optional ID = getUniqueID(Path)) return WholeArchives.count(*ID); return false; }; // Create a list of input files. Files can be given as arguments // for /defaultlib option. for (auto *Arg : Args.filtered(OPT_INPUT, OPT_wholearchive_file)) if (Optional Path = findFile(Arg->getValue())) enqueuePath(*Path, IsWholeArchive(*Path)); for (auto *Arg : Args.filtered(OPT_defaultlib)) if (Optional Path = findLib(Arg->getValue())) enqueuePath(*Path, false); // Windows specific -- Create a resource file containing a manifest file. if (Config->Manifest == Configuration::Embed) addBuffer(createManifestRes(), false); // Read all input files given via the command line. run(); // We should have inferred a machine type by now from the input files, but if // not we assume x64. if (Config->Machine == IMAGE_FILE_MACHINE_UNKNOWN) { warn("/machine is not specified. x64 is assumed"); Config->Machine = AMD64; } // Input files can be Windows resource files (.res files). We use // WindowsResource to convert resource files to a regular COFF file, // then link the resulting file normally. if (!Resources.empty()) Symtab->addFile(make(convertResToCOFF(Resources))); if (Tar) Tar->append("response.txt", createResponseFile(Args, FilePaths, ArrayRef(SearchPaths).slice(1))); // Handle /largeaddressaware Config->LargeAddressAware = Args.hasFlag( OPT_largeaddressaware, OPT_largeaddressaware_no, Config->is64()); // Handle /highentropyva Config->HighEntropyVA = Config->is64() && Args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); if (!Config->DynamicBase && (Config->Machine == ARMNT || Config->Machine == ARM64)) error("/dynamicbase:no is not compatible with " + machineToStr(Config->Machine)); - // Handle /entry and /dll - if (auto *Arg = Args.getLastArg(OPT_entry)) { - Config->Entry = addUndefined(mangle(Arg->getValue())); - } else if (!Config->Entry && !Config->NoEntry) { - if (Args.hasArg(OPT_dll)) { - StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" - : "_DllMainCRTStartup"; - Config->Entry = addUndefined(S); - } else { - // Windows specific -- If entry point name is not given, we need to - // infer that from user-defined entry name. - StringRef S = findDefaultEntry(); - if (S.empty()) - fatal("entry point must be defined"); - Config->Entry = addUndefined(S); - log("Entry name inferred: " + S); - } - } - // Handle /export for (auto *Arg : Args.filtered(OPT_export)) { Export E = parseExport(Arg->getValue()); if (Config->Machine == I386) { if (!isDecorated(E.Name)) E.Name = Saver.save("_" + E.Name); if (!E.ExtName.empty() && !isDecorated(E.ExtName)) E.ExtName = Saver.save("_" + E.ExtName); } Config->Exports.push_back(E); } // Handle /def if (auto *Arg = Args.getLastArg(OPT_deffile)) { // parseModuleDefs mutates Config object. parseModuleDefs(Arg->getValue()); } // Handle generation of import library from a def file. if (!Args.hasArg(OPT_INPUT)) { fixupExports(); createImportLibrary(/*AsLib=*/true); return; } + // Windows specific -- if no /subsystem is given, we need to infer + // that from entry point name. Must happen before /entry handling, + // and after the early return when just writing an import library. + if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { + Config->Subsystem = inferSubsystem(); + if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) + fatal("subsystem must be defined"); + } + + // Handle /entry and /dll + if (auto *Arg = Args.getLastArg(OPT_entry)) { + Config->Entry = addUndefined(mangle(Arg->getValue())); + } else if (!Config->Entry && !Config->NoEntry) { + if (Args.hasArg(OPT_dll)) { + StringRef S = (Config->Machine == I386) ? "__DllMainCRTStartup@12" + : "_DllMainCRTStartup"; + Config->Entry = addUndefined(S); + } else { + // Windows specific -- If entry point name is not given, we need to + // infer that from user-defined entry name. + StringRef S = findDefaultEntry(); + if (S.empty()) + fatal("entry point must be defined"); + Config->Entry = addUndefined(S); + log("Entry name inferred: " + S); + } + } + // Handle /delayload for (auto *Arg : Args.filtered(OPT_delayload)) { Config->DelayLoads.insert(StringRef(Arg->getValue()).lower()); if (Config->Machine == I386) { Config->DelayLoadHelper = addUndefined("___delayLoadHelper2@8"); } else { Config->DelayLoadHelper = addUndefined("__delayLoadHelper2"); } } // Set default image name if neither /out or /def set it. if (Config->OutputFile.empty()) { Config->OutputFile = getOutputPath((*Args.filtered(OPT_INPUT).begin())->getValue()); } if (ShouldCreatePDB) { // Put the PDB next to the image if no /pdb flag was passed. if (Config->PDBPath.empty()) { Config->PDBPath = Config->OutputFile; sys::path::replace_extension(Config->PDBPath, ".pdb"); } // The embedded PDB path should be the absolute path to the PDB if no // /pdbaltpath flag was passed. if (Config->PDBAltPath.empty()) { Config->PDBAltPath = Config->PDBPath; // It's important to make the path absolute and remove dots. This path // will eventually be written into the PE header, and certain Microsoft // tools won't work correctly if these assumptions are not held. sys::fs::make_absolute(Config->PDBAltPath); sys::path::remove_dots(Config->PDBAltPath); } } // Set default image base if /base is not given. if (Config->ImageBase == uint64_t(-1)) Config->ImageBase = getDefaultImageBase(); Symtab->addSynthetic(mangle("__ImageBase"), nullptr); if (Config->Machine == I386) { Symtab->addAbsolute("___safe_se_handler_table", 0); Symtab->addAbsolute("___safe_se_handler_count", 0); } Symtab->addAbsolute(mangle("__guard_fids_count"), 0); Symtab->addAbsolute(mangle("__guard_fids_table"), 0); Symtab->addAbsolute(mangle("__guard_flags"), 0); Symtab->addAbsolute(mangle("__guard_iat_count"), 0); Symtab->addAbsolute(mangle("__guard_iat_table"), 0); Symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); Symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); // Needed for MSVC 2017 15.5 CRT. Symtab->addAbsolute(mangle("__enclave_config"), 0); // This code may add new undefined symbols to the link, which may enqueue more // symbol resolution tasks, so we need to continue executing tasks until we // converge. do { // Windows specific -- if entry point is not found, // search for its mangled names. if (Config->Entry) Symtab->mangleMaybe(Config->Entry); // Windows specific -- Make sure we resolve all dllexported symbols. for (Export &E : Config->Exports) { if (!E.ForwardTo.empty()) continue; E.Sym = addUndefined(E.Name); if (!E.Directives) Symtab->mangleMaybe(E.Sym); } // Add weak aliases. Weak aliases is a mechanism to give remaining // undefined symbols final chance to be resolved successfully. for (auto Pair : Config->AlternateNames) { StringRef From = Pair.first; StringRef To = Pair.second; Symbol *Sym = Symtab->find(From); if (!Sym) continue; if (auto *U = dyn_cast(Sym)) if (!U->WeakAlias) U->WeakAlias = Symtab->addUndefined(To); } // Windows specific -- if __load_config_used can be resolved, resolve it. if (Symtab->findUnderscore("_load_config_used")) addUndefined(mangle("_load_config_used")); } while (run()); if (errorCount()) return; // If /msvclto is given, we use the MSVC linker to link LTO output files. // This is useful because MSVC link.exe can generate complete PDBs. if (Args.hasArg(OPT_msvclto)) { invokeMSVC(Args); return; } // Do LTO by compiling bitcode input files to a set of native COFF files then // link those files. Symtab->addCombinedLTOObjects(); run(); // Make sure we have resolved all symbols. Symtab->reportRemainingUndefines(); if (errorCount()) return; - - // Windows specific -- if no /subsystem is given, we need to infer - // that from entry point name. - if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { - Config->Subsystem = inferSubsystem(); - if (Config->Subsystem == IMAGE_SUBSYSTEM_UNKNOWN) - fatal("subsystem must be defined"); - } // Handle /safeseh. if (Args.hasFlag(OPT_safeseh, OPT_safeseh_no, false)) { for (ObjFile *File : ObjFile::Instances) if (!File->hasSafeSEH()) error("/safeseh: " + File->getName() + " is not compatible with SEH"); if (errorCount()) return; } // In MinGW, all symbols are automatically exported if no symbols // are chosen to be exported. if (Config->DLL && ((Config->MinGW && Config->Exports.empty()) || Args.hasArg(OPT_export_all_symbols))) { AutoExporter Exporter; Symtab->forEachSymbol([=](Symbol *S) { auto *Def = dyn_cast(S); if (!Exporter.shouldExport(Def)) return; Export E; E.Name = Def->getName(); E.Sym = Def; if (Def->getChunk() && !(Def->getChunk()->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) E.Data = true; Config->Exports.push_back(E); }); } // Windows specific -- when we are creating a .dll file, we also // need to create a .lib file. if (!Config->Exports.empty() || Config->DLL) { fixupExports(); createImportLibrary(/*AsLib=*/false); assignExportOrdinals(); } // Handle /output-def (MinGW specific). if (auto *Arg = Args.getLastArg(OPT_output_def)) writeDefFile(Arg->getValue()); // Set extra alignment for .comm symbols for (auto Pair : Config->AlignComm) { StringRef Name = Pair.first; uint32_t Alignment = Pair.second; Symbol *Sym = Symtab->find(Name); if (!Sym) { warn("/aligncomm symbol " + Name + " not found"); continue; } // If the symbol isn't common, it must have been replaced with a regular // symbol, which will carry its own alignment. auto *DC = dyn_cast(Sym); if (!DC) continue; CommonChunk *C = DC->getChunk(); C->Alignment = std::max(C->Alignment, Alignment); } // Windows specific -- Create a side-by-side manifest file. if (Config->Manifest == Configuration::SideBySide) createSideBySideManifest(); // Handle /order. We want to do this at this moment because we // need a complete list of comdat sections to warn on nonexistent // functions. if (auto *Arg = Args.getLastArg(OPT_order)) parseOrderFile(Arg->getValue()); // Identify unreferenced COMDAT sections. if (Config->DoGC) markLive(Symtab->getChunks()); // Identify identical COMDAT sections to merge them. if (Config->DoICF) doICF(Symtab->getChunks()); // Write the result. writeResult(); // Stop early so we can print the results. Timer::root().stop(); if (Config->ShowTiming) Timer::root().print(); } } // namespace coff } // namespace lld Index: vendor/lld/dist-release_70/COFF/Driver.h =================================================================== --- vendor/lld/dist-release_70/COFF/Driver.h (revision 338582) +++ vendor/lld/dist-release_70/COFF/Driver.h (revision 338583) @@ -1,199 +1,198 @@ //===- Driver.h -------------------------------------------------*- C++ -*-===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_COFF_DRIVER_H #define LLD_COFF_DRIVER_H #include "Config.h" #include "SymbolTable.h" #include "lld/Common/LLVM.h" #include "lld/Common/Reproduce.h" #include "llvm/ADT/Optional.h" #include "llvm/ADT/StringRef.h" #include "llvm/ADT/StringSet.h" #include "llvm/Object/Archive.h" #include "llvm/Object/COFF.h" #include "llvm/Option/Arg.h" #include "llvm/Option/ArgList.h" #include "llvm/Support/FileSystem.h" #include "llvm/Support/TarWriter.h" #include #include #include namespace lld { namespace coff { class LinkerDriver; extern LinkerDriver *Driver; using llvm::COFF::MachineTypes; using llvm::COFF::WindowsSubsystem; using llvm::Optional; class COFFOptTable : public llvm::opt::OptTable { public: COFFOptTable(); }; class ArgParser { public: // Concatenate LINK environment variable and given arguments and parse them. llvm::opt::InputArgList parseLINK(std::vector Args); // Tokenizes a given string and then parses as command line options. llvm::opt::InputArgList parse(StringRef S) { return parse(tokenize(S)); } // Tokenizes a given string and then parses as command line options in // .drectve section. /EXPORT options are returned in second element // to be processed in fastpath. std::pair> parseDirectives(StringRef S); private: // Parses command line options. llvm::opt::InputArgList parse(llvm::ArrayRef Args); std::vector tokenize(StringRef S); COFFOptTable Table; }; class LinkerDriver { public: void link(llvm::ArrayRef Args); // Used by the resolver to parse .drectve section contents. void parseDirectives(StringRef S); // Used by ArchiveFile to enqueue members. void enqueueArchiveMember(const Archive::Child &C, StringRef SymName, StringRef ParentName); MemoryBufferRef takeBuffer(std::unique_ptr MB); private: std::unique_ptr Tar; // for /linkrepro // Opens a file. Path has to be resolved already. MemoryBufferRef openFile(StringRef Path); // Searches a file from search paths. Optional findFile(StringRef Filename); Optional findLib(StringRef Filename); StringRef doFindFile(StringRef Filename); StringRef doFindLib(StringRef Filename); // Parses LIB environment which contains a list of search paths. void addLibSearchPaths(); // Library search path. The first element is always "" (current directory). std::vector SearchPaths; // We don't want to add the same file more than once. // Files are uniquified by their filesystem and file number. std::set VisitedFiles; std::set VisitedLibs; Symbol *addUndefined(StringRef Sym); - StringRef mangle(StringRef Sym); // Windows specific -- "main" is not the only main function in Windows. // You can choose one from these four -- {w,}{WinMain,main}. // There are four different entry point functions for them, // {w,}{WinMain,main}CRTStartup, respectively. The linker needs to // choose the right one depending on which "main" function is defined. // This function looks up the symbol table and resolve corresponding // entry point name. StringRef findDefaultEntry(); WindowsSubsystem inferSubsystem(); void invokeMSVC(llvm::opt::InputArgList &Args); void addBuffer(std::unique_ptr MB, bool WholeArchive); void addArchiveBuffer(MemoryBufferRef MBRef, StringRef SymName, StringRef ParentName); void enqueuePath(StringRef Path, bool WholeArchive); void enqueueTask(std::function Task); bool run(); std::list> TaskQueue; std::vector FilePaths; std::vector Resources; llvm::StringSet<> DirectivesExports; }; // Functions below this line are defined in DriverUtils.cpp. void printHelp(const char *Argv0); // For /machine option. MachineTypes getMachineType(StringRef Arg); StringRef machineToStr(MachineTypes MT); // Parses a string in the form of "[,]". void parseNumbers(StringRef Arg, uint64_t *Addr, uint64_t *Size = nullptr); void parseGuard(StringRef Arg); // Parses a string in the form of "[.]". // Minor's default value is 0. void parseVersion(StringRef Arg, uint32_t *Major, uint32_t *Minor); // Parses a string in the form of "[,[.]]". void parseSubsystem(StringRef Arg, WindowsSubsystem *Sys, uint32_t *Major, uint32_t *Minor); void parseAlternateName(StringRef); void parseMerge(StringRef); void parseSection(StringRef); void parseAligncomm(StringRef); // Parses a string in the form of "EMBED[,=]|NO". void parseManifest(StringRef Arg); // Parses a string in the form of "level=|uiAccess=" void parseManifestUAC(StringRef Arg); // Create a resource file containing a manifest XML. std::unique_ptr createManifestRes(); void createSideBySideManifest(); // Used for dllexported symbols. Export parseExport(StringRef Arg); void fixupExports(); void assignExportOrdinals(); // Parses a string in the form of "key=value" and check // if value matches previous values for the key. // This feature used in the directive section to reject // incompatible objects. void checkFailIfMismatch(StringRef Arg); // Convert Windows resource files (.res files) to a .obj file. MemoryBufferRef convertResToCOFF(ArrayRef MBs); void runMSVCLinker(std::string Rsp, ArrayRef Objects); // Create enum with OPT_xxx values for each option in Options.td enum { OPT_INVALID = 0, #define OPTION(_1, _2, ID, _4, _5, _6, _7, _8, _9, _10, _11, _12) OPT_##ID, #include "Options.inc" #undef OPTION }; } // namespace coff } // namespace lld #endif Index: vendor/lld/dist-release_70/docs/ReleaseNotes.rst =================================================================== --- vendor/lld/dist-release_70/docs/ReleaseNotes.rst (revision 338582) +++ vendor/lld/dist-release_70/docs/ReleaseNotes.rst (revision 338583) @@ -1,51 +1,102 @@ ======================= LLD 7.0.0 Release Notes ======================= .. contents:: :local: -.. warning:: - These are in-progress notes for the upcoming LLVM 7.0.0 release. - Release notes for previous releases can be found on - `the Download Page `_. - Introduction ============ -This document contains the release notes for the lld linker, release 7.0.0. -Here we describe the status of lld, including major improvements -from the previous release. All lld releases may be downloaded -from the `LLVM releases web site `_. +lld is a high-performance linker that supports ELF (Unix), COFF (Windows), +Mach-O (macOS), MinGW and WebAssembly. lld is command-line-compatible with GNU +linkers and Microsoft link.exe, and is significantly faster than these system +default linkers. +lld 7 for ELF and COFF are production-ready. lld/ELF can build the entire +FreeBSD/AMD64 and will be the default linker of the next version of the +operating system. lld/COFF is being used to build popular large programs such as +the Chrome web browser. Mach-O, MinGW and WebAssembly supports are still +experimental. + Non-comprehensive list of changes in this release ================================================= ELF Improvements ---------------- -* lld is now able to overcome MIPS GOT entries number limitation - and generate multi-GOT if necessary. +* Fixed a lot of long-tail compatibility issues with GNU linkers. -* lld is now able to produce MIPS position-independent executable (PIE). +* Added ``-z retpolineplt`` to emit a PLT entry that doesn't contain an indirect + jump instruction to mitigate Spectre v2 vulnerability. +* Added experimental support for `SHT_RELR sections + `_ to create a + compact dynamic relocation table. + +* Added support for `split stacks `_. + +* Added support for address significance table (section with type + SHT_LLVM_ADDRSIG) to improve Identical Code Folding (ICF). Combined with the + ``-faddrsig`` compiler option added to Clang 7, lld's ``--icf=all`` can now + safely merge functions and data to generate smaller outputs than before. + +* Improved ``--gdb-index`` so that it is faster (`r336790 + `_) and uses less memory (`r336672 + `_). + +* Reduced memory usage of ``--compress-debug-sections`` (`r338913 + `_). + +* Added linker script OVERLAY support (`r335714 `_). + +* Added ``--warn-backref`` to make it easy to identify command line option order + that doesn't work with GNU linkers (`r329636 `_) + +* Added ld.lld.1 man page (`r324512 `_). + +* Added support for multi-GOT. + +* Added support for MIPS position-independent executable (PIE). + * Fixed MIPS TLS GOT entries for local symbols in shared libraries. -* Fixed calculation of MIPS GP relative relocations - in case of relocatable output. +* Fixed calculation of MIPS GP relative relocations in case of relocatable + output. +* Added support for PPCv2 ABI. + +* Removed an incomplete support of PPCv1 ABI. + +* Added support for Qualcomm Hexagon ISA. + +* Added the following flags: ``--apply-dynamic-relocs``, ``--check-sections``, + ``--cref``, ``--just-symbols``, ``--keep-unique``, + ``--no-allow-multiple-definition``, ``--no-apply-dynamic-relocs``, + ``--no-check-sections``, ``--no-gnu-unique, ``--no-pic-executable``, + ``--no-undefined-version``, ``--no-warn-common``, ``--pack-dyn-relocs=relr``, + ``--pop-state``, ``--print-icf-sections``, ``--push-state``, + ``--thinlto-index-only``, ``--thinlto-object-suffix-replace``, + ``--thinlto-prefix-replace``, ``--warn-backref``, ``-z combreloc``, ``-z + copyreloc``, ``-z initfirst``, ``-z keep-text-section-prefix``, ``-z lazy``, + ``-z noexecstack``, ``-z relro``, ``-z retpolineplt``, ``-z text`` + COFF Improvements ----------------- * Improved correctness of exporting mangled stdcall symbols. * Completed support for ARM64 relocations. * Added support for outputting PDB debug info for MinGW targets. * Improved compatibility of output binaries with GNU binutils objcopy/strip. -MachO Improvements ------------------- +* Sped up PDB file creation. -* Item 1. +* Changed section layout to improve compatibility with link.exe. + +* Added the following flags: ``--color-diagnostics={always,never,auto}``, + ``--no-color-diagnostics``, ``/brepro``, ``/debug:full``, ``/debug:ghash``, + ``/guard:cf``, ``/guard:longjmp``, ``/guard:nolongjmp``, ``/integritycheck``, + ``/order``, ``/pdbsourcepath``, ``/timestamp`` Index: vendor/lld/dist-release_70/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h =================================================================== --- vendor/lld/dist-release_70/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h (revision 338582) +++ vendor/lld/dist-release_70/lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h (revision 338583) @@ -1,215 +1,214 @@ //===- lib/ReaderWriter/MachO/MachONormalizedFileBinaryUtils.h ------------===// // // The LLVM Linker // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #ifndef LLD_READER_WRITER_MACHO_NORMALIZED_FILE_BINARY_UTILS_H #define LLD_READER_WRITER_MACHO_NORMALIZED_FILE_BINARY_UTILS_H #include "MachONormalizedFile.h" #include "lld/Common/LLVM.h" #include "lld/Core/Error.h" #include "llvm/ADT/StringRef.h" #include "llvm/BinaryFormat/MachO.h" #include "llvm/Support/Casting.h" #include "llvm/Support/Endian.h" #include "llvm/Support/ErrorHandling.h" #include "llvm/Support/Host.h" #include "llvm/Support/LEB128.h" #include namespace lld { namespace mach_o { namespace normalized { class ByteBuffer { public: ByteBuffer() : _ostream(_bytes) { } void append_byte(uint8_t b) { _ostream << b; } void append_uleb128(uint64_t value) { llvm::encodeULEB128(value, _ostream); } void append_uleb128Fixed(uint64_t value, unsigned byteCount) { unsigned min = llvm::getULEB128Size(value); assert(min <= byteCount); unsigned pad = byteCount - min; llvm::encodeULEB128(value, _ostream, pad); } void append_sleb128(int64_t value) { llvm::encodeSLEB128(value, _ostream); } void append_string(StringRef str) { _ostream << str; append_byte(0); } void align(unsigned alignment) { while ( (_ostream.tell() % alignment) != 0 ) append_byte(0); } size_t size() { return _ostream.tell(); } const uint8_t *bytes() { return reinterpret_cast(_ostream.str().data()); } private: SmallVector _bytes; // Stream ivar must be after SmallVector ivar to construct properly. llvm::raw_svector_ostream _ostream; }; using namespace llvm::support::endian; using llvm::sys::getSwappedBytes; template static inline uint16_t read16(const T *loc, bool isBig) { assert((uint64_t)loc % alignof(T) == 0 && "invalid pointer alignment"); return isBig ? read16be(loc) : read16le(loc); } template static inline uint32_t read32(const T *loc, bool isBig) { assert((uint64_t)loc % alignof(T) == 0 && "invalid pointer alignment"); return isBig ? read32be(loc) : read32le(loc); } template static inline uint64_t read64(const T *loc, bool isBig) { assert((uint64_t)loc % alignof(T) == 0 && "invalid pointer alignment"); return isBig ? read64be(loc) : read64le(loc); } inline void write16(uint8_t *loc, uint16_t value, bool isBig) { if (isBig) write16be(loc, value); else write16le(loc, value); } inline void write32(uint8_t *loc, uint32_t value, bool isBig) { if (isBig) write32be(loc, value); else write32le(loc, value); } inline void write64(uint8_t *loc, uint64_t value, bool isBig) { if (isBig) write64be(loc, value); else write64le(loc, value); } inline uint32_t bitFieldExtract(uint32_t value, bool isBigEndianBigField, uint8_t firstBit, uint8_t bitCount) { const uint32_t mask = ((1<> shift) & mask; } inline void bitFieldSet(uint32_t &bits, bool isBigEndianBigField, uint32_t newBits, uint8_t firstBit, uint8_t bitCount) { const uint32_t mask = ((1< 16 ) - return x.substr(0, 16); - else - return x; + // The StringRef(const char *) constructor passes the const char * to + // strlen(), so we can't use this constructor here, because if there is no + // null terminator in s, then strlen() will read past the end of the array. + return StringRef(s, strnlen(s, 16)); } inline void setString16(StringRef str, char s[16]) { memset(s, 0, 16); memcpy(s, str.begin(), (str.size() > 16) ? 16: str.size()); } // Implemented in normalizedToAtoms() and used by normalizedFromAtoms() so // that the same table can be used to map mach-o sections to and from // DefinedAtom::ContentType. void relocatableSectionInfoForContentType(DefinedAtom::ContentType atomType, StringRef &segmentName, StringRef §ionName, SectionType §ionType, SectionAttr §ionAttrs, bool &relocsToDefinedCanBeImplicit); } // namespace normalized } // namespace mach_o } // namespace lld #endif // LLD_READER_WRITER_MACHO_NORMALIZED_FILE_BINARY_UTILS_H Index: vendor/lld/dist-release_70/test/COFF/entry-inference3.test =================================================================== --- vendor/lld/dist-release_70/test/COFF/entry-inference3.test (revision 338582) +++ vendor/lld/dist-release_70/test/COFF/entry-inference3.test (revision 338583) @@ -1,35 +1,39 @@ -# RUN: yaml2obj < %s > %t.obj -# RUN: not lld-link /out:%t.exe %t.obj /verbose /nodefaultlib > %t.log 2>&1 +# RUN: sed -e s/ENTRYNAME/mainCRTStartup/ %s | yaml2obj > %t.obj +# RUN: lld-link /subsystem:console /out:%t.exe %t.obj /verbose /nodefaultlib > %t.log 2>&1 # RUN: FileCheck %s < %t.log +# RUN: sed -e s/ENTRYNAME/?mainCRTStartup@@YAHXZ/ %s | yaml2obj > %t.obj +# RUN: lld-link /subsystem:console /out:%t.exe %t.obj /verbose /nodefaultlib > %t.log 2>&1 +# RUN: FileCheck %s < %t.log + # CHECK: Entry name inferred: mainCRTStartup --- !COFF header: Machine: IMAGE_FILE_MACHINE_AMD64 Characteristics: [] sections: - Name: .text Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] Alignment: 4 SectionData: B82A000000C3 symbols: - Name: .text Value: 0 SectionNumber: 1 SimpleType: IMAGE_SYM_TYPE_NULL ComplexType: IMAGE_SYM_DTYPE_NULL StorageClass: IMAGE_SYM_CLASS_STATIC SectionDefinition: Length: 6 NumberOfRelocations: 0 NumberOfLinenumbers: 0 CheckSum: 0 Number: 0 - - Name: mainCRTStartup + - Name: "ENTRYNAME" Value: 0 SectionNumber: 1 SimpleType: IMAGE_SYM_TYPE_NULL ComplexType: IMAGE_SYM_DTYPE_NULL StorageClass: IMAGE_SYM_CLASS_EXTERNAL ... Index: vendor/lld/dist-release_70/test/COFF/entry-inference332.test =================================================================== --- vendor/lld/dist-release_70/test/COFF/entry-inference332.test (nonexistent) +++ vendor/lld/dist-release_70/test/COFF/entry-inference332.test (revision 338583) @@ -0,0 +1,39 @@ +# RUN: sed -e s/ENTRYNAME/_mainCRTStartup/ %s | yaml2obj > %t.obj +# RUN: lld-link /subsystem:console /out:%t.exe %t.obj /verbose /nodefaultlib > %t.log 2>&1 +# RUN: FileCheck %s < %t.log + +# RUN: sed -e s/ENTRYNAME/?mainCRTStartup@@YAHXZ/ %s | yaml2obj > %t.obj +# RUN: lld-link /subsystem:console /out:%t.exe %t.obj /verbose /nodefaultlib > %t.log 2>&1 +# RUN: FileCheck %s < %t.log + +# CHECK: Entry name inferred: _mainCRTStartup + +--- !COFF +header: + Machine: IMAGE_FILE_MACHINE_I386 + Characteristics: [] +sections: + - Name: .text + Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] + Alignment: 4 + SectionData: B82A000000C3 +symbols: + - Name: .text + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_STATIC + SectionDefinition: + Length: 6 + NumberOfRelocations: 0 + NumberOfLinenumbers: 0 + CheckSum: 0 + Number: 0 + - Name: "ENTRYNAME" + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL +... Index: vendor/lld/dist-release_70/test/COFF/entry-inference4.test =================================================================== --- vendor/lld/dist-release_70/test/COFF/entry-inference4.test (nonexistent) +++ vendor/lld/dist-release_70/test/COFF/entry-inference4.test (revision 338583) @@ -0,0 +1,56 @@ +# RUN: sed 's/ENTRY1/WinMain/;s/ENTRY2/main/' %s | yaml2obj > %t.obj +# RUN: not lld-link /subsystem:windows /out:%t.exe %t.obj > %t.log 2>&1 +# RUN: FileCheck -check-prefix=WINMAIN %s < %t.log + +# RUN: sed 's/ENTRY1/wWinMain/;s/ENTRY2/main/' %s | yaml2obj > %t.obj +# RUN: not lld-link /subsystem:windows /out:%t.exe %t.obj > %t.log 2>&1 +# RUN: FileCheck -check-prefix=WWINMAIN %s < %t.log + +# RUN: sed 's/ENTRY1/WinMain/;s/ENTRY2/main/' %s | yaml2obj > %t.obj +# RUN: not lld-link /subsystem:console /out:%t.exe %t.obj > %t.log 2>&1 +# RUN: FileCheck -check-prefix=MAIN %s < %t.log + +# RUN: sed 's/ENTRY1/WinMain/;s/ENTRY2/wmain/' %s | yaml2obj > %t.obj +# RUN: not lld-link /subsystem:console /out:%t.exe %t.obj > %t.log 2>&1 +# RUN: FileCheck -check-prefix=WMAIN %s < %t.log + +# MAIN: error: : undefined symbol: mainCRTStartup +# WMAIN: error: : undefined symbol: wmainCRTStartup +# WINMAIN: error: : undefined symbol: WinMainCRTStartup +# WWINMAIN: error: : undefined symbol: wWinMainCRTStartup + +--- !COFF +header: + Machine: IMAGE_FILE_MACHINE_AMD64 + Characteristics: [] +sections: + - Name: .text + Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] + Alignment: 4 + SectionData: B82A000000C3 +symbols: + - Name: .text + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_STATIC + SectionDefinition: + Length: 6 + NumberOfRelocations: 0 + NumberOfLinenumbers: 0 + CheckSum: 0 + Number: 0 + - Name: ENTRY1 + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL + - Name: ENTRY2 + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL +... Index: vendor/lld/dist-release_70/test/COFF/guardcf-align.s =================================================================== --- vendor/lld/dist-release_70/test/COFF/guardcf-align.s (revision 338582) +++ vendor/lld/dist-release_70/test/COFF/guardcf-align.s (revision 338583) @@ -1,45 +1,46 @@ +# REQUIRES: x86 # RUN: llvm-mc -triple x86_64-windows-msvc -filetype=obj -o %t.obj %s # RUN: yaml2obj < %p/Inputs/guardcf-align-foobar.yaml \ # RUN: > %T/guardcf-align-foobar.obj # RUN: lld-link -out:%T/guardcf-align.exe -entry:main -guard:cf \ # RUN: %t.obj %T/guardcf-align-foobar.obj # RUN: llvm-readobj -coff-load-config %T/guardcf-align.exe | FileCheck %s # Check that the gfids table contains at least one entry that ends in 0 # and no entries that end in something other than 0. # CHECK: GuardFidTable [ # CHECK-NOT: 0x{{[0-9A-Fa-f]+[^0]$}} # CHECK: 0x{{[0-9A-Fa-f]+0$}} # CHECK-NOT: 0x{{[0-9A-Fa-f]+[^0]$}} # CHECK: ] # @feat.00 and _load_config_used to indicate we have gfids. .def @feat.00; .scl 3; .type 0; .endef .globl @feat.00 @feat.00 = 0x801 .section .rdata,"dr" .globl _load_config_used _load_config_used: .long 256 .fill 124, 1, 0 .quad __guard_fids_table .quad __guard_fids_count .long __guard_flags .fill 128, 1, 0 # Functions that are called indirectly. .section .gfids$y,"dr" .symidx foo .section .text,"rx" .global main main: movq foo, %rcx xorq %rax, %rax callq bar retq Index: vendor/lld/dist-release_70/test/COFF/subsystem-inference32.test =================================================================== --- vendor/lld/dist-release_70/test/COFF/subsystem-inference32.test (nonexistent) +++ vendor/lld/dist-release_70/test/COFF/subsystem-inference32.test (revision 338583) @@ -0,0 +1,74 @@ +# RUN: sed -e s/ENTRYNAME/_main/ %s | yaml2obj > %t.obj +# RUN: lld-link /out:%t.exe %t.obj +# RUN: llvm-readobj -file-headers %t.exe | FileCheck -check-prefix=MAIN %s + +# RUN: sed s/ENTRYNAME/_wmain/ %s | yaml2obj > %t.obj +# RUN: lld-link /out:%t.exe %t.obj +# RUN: llvm-readobj -file-headers %t.exe | FileCheck -check-prefix=WMAIN %s + +# RUN: sed s/ENTRYNAME/_WinMain@16/ %s | yaml2obj > %t.obj +# RUN: lld-link /out:%t.exe %t.obj +# RUN: llvm-readobj -file-headers %t.exe | FileCheck -check-prefix=WINMAIN %s + +# RUN: sed s/ENTRYNAME/_wWinMain@16/ %s | yaml2obj > %t.obj +# RUN: lld-link /out:%t.exe %t.obj +# RUN: llvm-readobj -file-headers %t.exe | FileCheck -check-prefix=WWINMAIN %s + +# MAIN: Subsystem: IMAGE_SUBSYSTEM_WINDOWS_CUI +# WMAIN: Subsystem: IMAGE_SUBSYSTEM_WINDOWS_CUI +# WINMAIN: Subsystem: IMAGE_SUBSYSTEM_WINDOWS_GUI +# WWINMAIN: Subsystem: IMAGE_SUBSYSTEM_WINDOWS_GUI + +--- !COFF +header: + Machine: IMAGE_FILE_MACHINE_I386 + Characteristics: [] +sections: + - Name: .text + Characteristics: [ IMAGE_SCN_CNT_CODE, IMAGE_SCN_MEM_EXECUTE, IMAGE_SCN_MEM_READ ] + Alignment: 4 + SectionData: B82A000000C3 +symbols: + - Name: .text + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_STATIC + SectionDefinition: + Length: 6 + NumberOfRelocations: 0 + NumberOfLinenumbers: 0 + CheckSum: 0 + Number: 0 + - Name: ENTRYNAME + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL + - Name: _mainCRTStartup + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL + - Name: _wmainCRTStartup + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL + - Name: _WinMainCRTStartup + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL + - Name: _wWinMainCRTStartup + Value: 0 + SectionNumber: 1 + SimpleType: IMAGE_SYM_TYPE_NULL + ComplexType: IMAGE_SYM_DTYPE_NULL + StorageClass: IMAGE_SYM_CLASS_EXTERNAL +... Index: vendor/lld/dist-release_70/test/ELF/icf13.s =================================================================== --- vendor/lld/dist-release_70/test/ELF/icf13.s (revision 338582) +++ vendor/lld/dist-release_70/test/ELF/icf13.s (revision 338583) @@ -1,20 +1,21 @@ +# REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t1 # RUN: ld.lld -shared -z notext %t1 -o /dev/null --icf=all --print-icf-sections 2>&1 | FileCheck -allow-empty %s ## Check that ICF does not merge sections which relocations point to symbols ## that are not of the regular defined kind. # CHECK-NOT: selected .globl und .section .text .globl _start _start: ret .section .text.foo, "ax" .quad _start .section .text.bar, "ax" .quad und Index: vendor/lld/dist-release_70/test/ELF/icf15.s =================================================================== --- vendor/lld/dist-release_70/test/ELF/icf15.s (revision 338582) +++ vendor/lld/dist-release_70/test/ELF/icf15.s (revision 338583) @@ -1,23 +1,24 @@ +# REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t1 # RUN: ld.lld %t1 -o /dev/null --icf=all --print-icf-sections 2>&1 | FileCheck -allow-empty %s ## Check that ICF does not merge sections which relocations have equal addends, ## but different target values. # CHECK-NOT: selected .globl und .section .text .globl foo foo: .byte 0 .globl bar bar: .byte 0 .section .text.foo, "ax" .quad foo .section .text.bar, "ax" .quad bar Index: vendor/lld/dist-release_70/test/ELF/icf16.s =================================================================== --- vendor/lld/dist-release_70/test/ELF/icf16.s (revision 338582) +++ vendor/lld/dist-release_70/test/ELF/icf16.s (revision 338583) @@ -1,23 +1,24 @@ +# REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t1 # RUN: ld.lld -shared -z notext %t1 -o /dev/null --icf=all --print-icf-sections 2>&1 | FileCheck -allow-empty %s ## ICF is able to merge sections which relocations referring regular input sections ## or mergeable sections. .eh_frame is represented with a different kind of section, ## here we check that ICF code is able to handle and will not merge sections which ## relocations referring .eh_frame. # CHECK-NOT: selected .section ".eh_frame", "a", @progbits .globl foo foo: .quad 0 .globl bar bar: .quad 0 .section .text.foo, "ax" .quad foo .section .text.bar, "ax" .quad bar Index: vendor/lld/dist-release_70/test/ELF/icf17.s =================================================================== --- vendor/lld/dist-release_70/test/ELF/icf17.s (revision 338582) +++ vendor/lld/dist-release_70/test/ELF/icf17.s (revision 338583) @@ -1,15 +1,16 @@ +# REQUIRES: x86 # RUN: llvm-mc -filetype=obj -triple=x86_64-unknown-linux %s -o %t1 # RUN: ld.lld %t1 -o /dev/null --icf=all --print-icf-sections 2>&1 | FileCheck -allow-empty %s # CHECK-NOT: selected .section .text .globl _start _start: ret .section .aaa, "ax",%progbits,unique,1 .quad _start .section .aaa, "axS",%progbits,unique,2 .quad _start Index: vendor/lld/dist-release_70/test/ELF/lto/libcall-archive.ll =================================================================== --- vendor/lld/dist-release_70/test/ELF/lto/libcall-archive.ll (revision 338582) +++ vendor/lld/dist-release_70/test/ELF/lto/libcall-archive.ll (revision 338583) @@ -1,20 +1,21 @@ +; REQUIRES: x86 ; RUN: rm -f %t.a ; RUN: llvm-as -o %t.o %s ; RUN: llvm-as -o %t2.o %S/Inputs/libcall-archive.ll ; RUN: llvm-ar rcs %t.a %t2.o ; RUN: ld.lld -o %t %t.o %t.a ; RUN: llvm-nm %t | FileCheck %s ; CHECK: T _start ; CHECK: T memcpy target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128" target triple = "x86_64-unknown-linux-gnu" define void @_start(i8* %a, i8* %b) { entry: call void @llvm.memcpy.p0i8.p0i8.i64(i8* %a, i8* %b, i64 1024, i1 false) ret void } declare void @llvm.memcpy.p0i8.p0i8.i64(i8* nocapture, i8* nocapture, i64, i1)