10b57cec5SDimitry Andric //===- Driver.cpp ---------------------------------------------------------===// 20b57cec5SDimitry Andric // 30b57cec5SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 40b57cec5SDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 50b57cec5SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 60b57cec5SDimitry Andric // 70b57cec5SDimitry Andric //===----------------------------------------------------------------------===// 80b57cec5SDimitry Andric 90b57cec5SDimitry Andric #include "Driver.h" 100b57cec5SDimitry Andric #include "Config.h" 110b57cec5SDimitry Andric #include "DebugTypes.h" 120b57cec5SDimitry Andric #include "ICF.h" 130b57cec5SDimitry Andric #include "InputFiles.h" 140b57cec5SDimitry Andric #include "MarkLive.h" 150b57cec5SDimitry Andric #include "MinGW.h" 160b57cec5SDimitry Andric #include "SymbolTable.h" 170b57cec5SDimitry Andric #include "Symbols.h" 180b57cec5SDimitry Andric #include "Writer.h" 190b57cec5SDimitry Andric #include "lld/Common/Args.h" 200b57cec5SDimitry Andric #include "lld/Common/Driver.h" 210b57cec5SDimitry Andric #include "lld/Common/ErrorHandler.h" 220b57cec5SDimitry Andric #include "lld/Common/Filesystem.h" 230b57cec5SDimitry Andric #include "lld/Common/Memory.h" 240b57cec5SDimitry Andric #include "lld/Common/Timer.h" 250b57cec5SDimitry Andric #include "lld/Common/Version.h" 260b57cec5SDimitry Andric #include "llvm/ADT/Optional.h" 270b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 280b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h" 29*e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 3085868e8aSDimitry Andric #include "llvm/LTO/LTO.h" 310b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h" 320b57cec5SDimitry Andric #include "llvm/Object/COFFImportFile.h" 330b57cec5SDimitry Andric #include "llvm/Object/COFFModuleDefinition.h" 340b57cec5SDimitry Andric #include "llvm/Object/WindowsMachineFlag.h" 350b57cec5SDimitry Andric #include "llvm/Option/Arg.h" 360b57cec5SDimitry Andric #include "llvm/Option/ArgList.h" 370b57cec5SDimitry Andric #include "llvm/Option/Option.h" 38*e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h" 39480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 400b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 410b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 420b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 435ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 440b57cec5SDimitry Andric #include "llvm/Support/Path.h" 450b57cec5SDimitry Andric #include "llvm/Support/Process.h" 460b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 470b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 480b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 490b57cec5SDimitry Andric #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 500b57cec5SDimitry Andric #include <algorithm> 510b57cec5SDimitry Andric #include <future> 520b57cec5SDimitry Andric #include <memory> 530b57cec5SDimitry Andric 540b57cec5SDimitry Andric using namespace llvm; 550b57cec5SDimitry Andric using namespace llvm::object; 560b57cec5SDimitry Andric using namespace llvm::COFF; 570b57cec5SDimitry Andric using llvm::sys::Process; 580b57cec5SDimitry Andric 590b57cec5SDimitry Andric namespace lld { 600b57cec5SDimitry Andric namespace coff { 610b57cec5SDimitry Andric 620b57cec5SDimitry Andric static Timer inputFileTimer("Input File Reading", Timer::root()); 630b57cec5SDimitry Andric 640b57cec5SDimitry Andric Configuration *config; 650b57cec5SDimitry Andric LinkerDriver *driver; 660b57cec5SDimitry Andric 67480093f4SDimitry Andric bool link(ArrayRef<const char *> args, bool canExitEarly, raw_ostream &stdoutOS, 68480093f4SDimitry Andric raw_ostream &stderrOS) { 69480093f4SDimitry Andric lld::stdoutOS = &stdoutOS; 70480093f4SDimitry Andric lld::stderrOS = &stderrOS; 71480093f4SDimitry Andric 72*e8d8bef9SDimitry Andric errorHandler().cleanupCallback = []() { 73*e8d8bef9SDimitry Andric TpiSource::clear(); 74*e8d8bef9SDimitry Andric freeArena(); 75*e8d8bef9SDimitry Andric ObjFile::instances.clear(); 76*e8d8bef9SDimitry Andric PDBInputFile::instances.clear(); 77*e8d8bef9SDimitry Andric ImportFile::instances.clear(); 78*e8d8bef9SDimitry Andric BitcodeFile::instances.clear(); 79*e8d8bef9SDimitry Andric memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances)); 80*e8d8bef9SDimitry Andric OutputSection::clear(); 81*e8d8bef9SDimitry Andric }; 82*e8d8bef9SDimitry Andric 830b57cec5SDimitry Andric errorHandler().logName = args::getFilenameWithoutExe(args[0]); 840b57cec5SDimitry Andric errorHandler().errorLimitExceededMsg = 850b57cec5SDimitry Andric "too many errors emitted, stopping now" 860b57cec5SDimitry Andric " (use /errorlimit:0 to see all errors)"; 870b57cec5SDimitry Andric errorHandler().exitEarly = canExitEarly; 88480093f4SDimitry Andric stderrOS.enable_colors(stderrOS.has_colors()); 8985868e8aSDimitry Andric 900b57cec5SDimitry Andric config = make<Configuration>(); 910b57cec5SDimitry Andric symtab = make<SymbolTable>(); 920b57cec5SDimitry Andric driver = make<LinkerDriver>(); 9385868e8aSDimitry Andric 94*e8d8bef9SDimitry Andric driver->linkerMain(args); 950b57cec5SDimitry Andric 960b57cec5SDimitry Andric // Call exit() if we can to avoid calling destructors. 970b57cec5SDimitry Andric if (canExitEarly) 980b57cec5SDimitry Andric exitLld(errorCount() ? 1 : 0); 990b57cec5SDimitry Andric 100*e8d8bef9SDimitry Andric bool ret = errorCount() == 0; 101*e8d8bef9SDimitry Andric if (!canExitEarly) 102*e8d8bef9SDimitry Andric errorHandler().reset(); 103*e8d8bef9SDimitry Andric return ret; 1040b57cec5SDimitry Andric } 1050b57cec5SDimitry Andric 1060b57cec5SDimitry Andric // Parse options of the form "old;new". 1070b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 1080b57cec5SDimitry Andric unsigned id) { 1090b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 1100b57cec5SDimitry Andric if (!arg) 1110b57cec5SDimitry Andric return {"", ""}; 1120b57cec5SDimitry Andric 1130b57cec5SDimitry Andric StringRef s = arg->getValue(); 1140b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 1150b57cec5SDimitry Andric if (ret.second.empty()) 1160b57cec5SDimitry Andric error(arg->getSpelling() + " expects 'old;new' format, but got " + s); 1170b57cec5SDimitry Andric return ret; 1180b57cec5SDimitry Andric } 1190b57cec5SDimitry Andric 120480093f4SDimitry Andric // Drop directory components and replace extension with 121480093f4SDimitry Andric // ".exe", ".dll" or ".sys". 1220b57cec5SDimitry Andric static std::string getOutputPath(StringRef path) { 123480093f4SDimitry Andric StringRef ext = ".exe"; 124480093f4SDimitry Andric if (config->dll) 125480093f4SDimitry Andric ext = ".dll"; 126480093f4SDimitry Andric else if (config->driver) 127480093f4SDimitry Andric ext = ".sys"; 128480093f4SDimitry Andric 129480093f4SDimitry Andric return (sys::path::stem(path) + ext).str(); 1300b57cec5SDimitry Andric } 1310b57cec5SDimitry Andric 1320b57cec5SDimitry Andric // Returns true if S matches /crtend.?\.o$/. 1330b57cec5SDimitry Andric static bool isCrtend(StringRef s) { 1340b57cec5SDimitry Andric if (!s.endswith(".o")) 1350b57cec5SDimitry Andric return false; 1360b57cec5SDimitry Andric s = s.drop_back(2); 1370b57cec5SDimitry Andric if (s.endswith("crtend")) 1380b57cec5SDimitry Andric return true; 1390b57cec5SDimitry Andric return !s.empty() && s.drop_back().endswith("crtend"); 1400b57cec5SDimitry Andric } 1410b57cec5SDimitry Andric 1420b57cec5SDimitry Andric // ErrorOr is not default constructible, so it cannot be used as the type 1430b57cec5SDimitry Andric // parameter of a future. 1440b57cec5SDimitry Andric // FIXME: We could open the file in createFutureForFile and avoid needing to 1450b57cec5SDimitry Andric // return an error here, but for the moment that would cost us a file descriptor 1460b57cec5SDimitry Andric // (a limited resource on Windows) for the duration that the future is pending. 1470b57cec5SDimitry Andric using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 1480b57cec5SDimitry Andric 1490b57cec5SDimitry Andric // Create a std::future that opens and maps a file using the best strategy for 1500b57cec5SDimitry Andric // the host platform. 1510b57cec5SDimitry Andric static std::future<MBErrPair> createFutureForFile(std::string path) { 1520b57cec5SDimitry Andric #if _WIN32 1530b57cec5SDimitry Andric // On Windows, file I/O is relatively slow so it is best to do this 1540b57cec5SDimitry Andric // asynchronously. 1550b57cec5SDimitry Andric auto strategy = std::launch::async; 1560b57cec5SDimitry Andric #else 1570b57cec5SDimitry Andric auto strategy = std::launch::deferred; 1580b57cec5SDimitry Andric #endif 1590b57cec5SDimitry Andric return std::async(strategy, [=]() { 1600b57cec5SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, 1610b57cec5SDimitry Andric /*FileSize*/ -1, 1620b57cec5SDimitry Andric /*RequiresNullTerminator*/ false); 1630b57cec5SDimitry Andric if (!mbOrErr) 1640b57cec5SDimitry Andric return MBErrPair{nullptr, mbOrErr.getError()}; 1650b57cec5SDimitry Andric return MBErrPair{std::move(*mbOrErr), std::error_code()}; 1660b57cec5SDimitry Andric }); 1670b57cec5SDimitry Andric } 1680b57cec5SDimitry Andric 1690b57cec5SDimitry Andric // Symbol names are mangled by prepending "_" on x86. 1700b57cec5SDimitry Andric static StringRef mangle(StringRef sym) { 1710b57cec5SDimitry Andric assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN); 1720b57cec5SDimitry Andric if (config->machine == I386) 1730b57cec5SDimitry Andric return saver.save("_" + sym); 1740b57cec5SDimitry Andric return sym; 1750b57cec5SDimitry Andric } 1760b57cec5SDimitry Andric 1770b57cec5SDimitry Andric static bool findUnderscoreMangle(StringRef sym) { 1780b57cec5SDimitry Andric Symbol *s = symtab->findMangle(mangle(sym)); 1790b57cec5SDimitry Andric return s && !isa<Undefined>(s); 1800b57cec5SDimitry Andric } 1810b57cec5SDimitry Andric 1820b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { 1830b57cec5SDimitry Andric MemoryBufferRef mbref = *mb; 1840b57cec5SDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership 1850b57cec5SDimitry Andric 1860b57cec5SDimitry Andric if (driver->tar) 1870b57cec5SDimitry Andric driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()), 1880b57cec5SDimitry Andric mbref.getBuffer()); 1890b57cec5SDimitry Andric return mbref; 1900b57cec5SDimitry Andric } 1910b57cec5SDimitry Andric 1920b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, 19385868e8aSDimitry Andric bool wholeArchive, bool lazy) { 1940b57cec5SDimitry Andric StringRef filename = mb->getBufferIdentifier(); 1950b57cec5SDimitry Andric 1960b57cec5SDimitry Andric MemoryBufferRef mbref = takeBuffer(std::move(mb)); 1970b57cec5SDimitry Andric filePaths.push_back(filename); 1980b57cec5SDimitry Andric 1990b57cec5SDimitry Andric // File type is detected by contents, not by file extension. 2000b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 2010b57cec5SDimitry Andric case file_magic::windows_resource: 2020b57cec5SDimitry Andric resources.push_back(mbref); 2030b57cec5SDimitry Andric break; 2040b57cec5SDimitry Andric case file_magic::archive: 2050b57cec5SDimitry Andric if (wholeArchive) { 2060b57cec5SDimitry Andric std::unique_ptr<Archive> file = 2070b57cec5SDimitry Andric CHECK(Archive::create(mbref), filename + ": failed to parse archive"); 2080b57cec5SDimitry Andric Archive *archive = file.get(); 2090b57cec5SDimitry Andric make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 2100b57cec5SDimitry Andric 21185868e8aSDimitry Andric int memberIndex = 0; 2120b57cec5SDimitry Andric for (MemoryBufferRef m : getArchiveMembers(archive)) 21385868e8aSDimitry Andric addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++); 2140b57cec5SDimitry Andric return; 2150b57cec5SDimitry Andric } 2160b57cec5SDimitry Andric symtab->addFile(make<ArchiveFile>(mbref)); 2170b57cec5SDimitry Andric break; 2180b57cec5SDimitry Andric case file_magic::bitcode: 21985868e8aSDimitry Andric if (lazy) 22085868e8aSDimitry Andric symtab->addFile(make<LazyObjFile>(mbref)); 22185868e8aSDimitry Andric else 2220b57cec5SDimitry Andric symtab->addFile(make<BitcodeFile>(mbref, "", 0)); 2230b57cec5SDimitry Andric break; 2240b57cec5SDimitry Andric case file_magic::coff_object: 2250b57cec5SDimitry Andric case file_magic::coff_import_library: 22685868e8aSDimitry Andric if (lazy) 22785868e8aSDimitry Andric symtab->addFile(make<LazyObjFile>(mbref)); 22885868e8aSDimitry Andric else 2290b57cec5SDimitry Andric symtab->addFile(make<ObjFile>(mbref)); 2300b57cec5SDimitry Andric break; 2310b57cec5SDimitry Andric case file_magic::pdb: 2325ffd83dbSDimitry Andric symtab->addFile(make<PDBInputFile>(mbref)); 2330b57cec5SDimitry Andric break; 2340b57cec5SDimitry Andric case file_magic::coff_cl_gl_object: 2350b57cec5SDimitry Andric error(filename + ": is not a native COFF file. Recompile without /GL"); 2360b57cec5SDimitry Andric break; 2370b57cec5SDimitry Andric case file_magic::pecoff_executable: 2380b57cec5SDimitry Andric if (filename.endswith_lower(".dll")) { 2390b57cec5SDimitry Andric error(filename + ": bad file type. Did you specify a DLL instead of an " 2400b57cec5SDimitry Andric "import library?"); 2410b57cec5SDimitry Andric break; 2420b57cec5SDimitry Andric } 2430b57cec5SDimitry Andric LLVM_FALLTHROUGH; 2440b57cec5SDimitry Andric default: 2450b57cec5SDimitry Andric error(mbref.getBufferIdentifier() + ": unknown file type"); 2460b57cec5SDimitry Andric break; 2470b57cec5SDimitry Andric } 2480b57cec5SDimitry Andric } 2490b57cec5SDimitry Andric 25085868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 2515ffd83dbSDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 2525ffd83dbSDimitry Andric createFutureForFile(std::string(path))); 2535ffd83dbSDimitry Andric std::string pathStr = std::string(path); 2540b57cec5SDimitry Andric enqueueTask([=]() { 2550b57cec5SDimitry Andric auto mbOrErr = future->get(); 2560b57cec5SDimitry Andric if (mbOrErr.second) { 2570b57cec5SDimitry Andric std::string msg = 2580b57cec5SDimitry Andric "could not open '" + pathStr + "': " + mbOrErr.second.message(); 2590b57cec5SDimitry Andric // Check if the filename is a typo for an option flag. OptTable thinks 2600b57cec5SDimitry Andric // that all args that are not known options and that start with / are 2610b57cec5SDimitry Andric // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 2620b57cec5SDimitry Andric // the option `/nodefaultlib` than a reference to a file in the root 2630b57cec5SDimitry Andric // directory. 2640b57cec5SDimitry Andric std::string nearest; 2655ffd83dbSDimitry Andric if (optTable.findNearest(pathStr, nearest) > 1) 2660b57cec5SDimitry Andric error(msg); 2670b57cec5SDimitry Andric else 2680b57cec5SDimitry Andric error(msg + "; did you mean '" + nearest + "'"); 2690b57cec5SDimitry Andric } else 27085868e8aSDimitry Andric driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 2710b57cec5SDimitry Andric }); 2720b57cec5SDimitry Andric } 2730b57cec5SDimitry Andric 2740b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 2750b57cec5SDimitry Andric StringRef parentName, 2760b57cec5SDimitry Andric uint64_t offsetInArchive) { 2770b57cec5SDimitry Andric file_magic magic = identify_magic(mb.getBuffer()); 2780b57cec5SDimitry Andric if (magic == file_magic::coff_import_library) { 2790b57cec5SDimitry Andric InputFile *imp = make<ImportFile>(mb); 2800b57cec5SDimitry Andric imp->parentName = parentName; 2810b57cec5SDimitry Andric symtab->addFile(imp); 2820b57cec5SDimitry Andric return; 2830b57cec5SDimitry Andric } 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric InputFile *obj; 2860b57cec5SDimitry Andric if (magic == file_magic::coff_object) { 2870b57cec5SDimitry Andric obj = make<ObjFile>(mb); 2880b57cec5SDimitry Andric } else if (magic == file_magic::bitcode) { 2890b57cec5SDimitry Andric obj = make<BitcodeFile>(mb, parentName, offsetInArchive); 2900b57cec5SDimitry Andric } else { 2910b57cec5SDimitry Andric error("unknown file type: " + mb.getBufferIdentifier()); 2920b57cec5SDimitry Andric return; 2930b57cec5SDimitry Andric } 2940b57cec5SDimitry Andric 2950b57cec5SDimitry Andric obj->parentName = parentName; 2960b57cec5SDimitry Andric symtab->addFile(obj); 2970b57cec5SDimitry Andric log("Loaded " + toString(obj) + " for " + symName); 2980b57cec5SDimitry Andric } 2990b57cec5SDimitry Andric 3000b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 3010b57cec5SDimitry Andric const Archive::Symbol &sym, 3020b57cec5SDimitry Andric StringRef parentName) { 3030b57cec5SDimitry Andric 3040b57cec5SDimitry Andric auto reportBufferError = [=](Error &&e, StringRef childName) { 3050b57cec5SDimitry Andric fatal("could not get the buffer for the member defining symbol " + 3060b57cec5SDimitry Andric toCOFFString(sym) + ": " + parentName + "(" + childName + "): " + 3070b57cec5SDimitry Andric toString(std::move(e))); 3080b57cec5SDimitry Andric }; 3090b57cec5SDimitry Andric 3100b57cec5SDimitry Andric if (!c.getParent()->isThin()) { 3110b57cec5SDimitry Andric uint64_t offsetInArchive = c.getChildOffset(); 3120b57cec5SDimitry Andric Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 3130b57cec5SDimitry Andric if (!mbOrErr) 3140b57cec5SDimitry Andric reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 3150b57cec5SDimitry Andric MemoryBufferRef mb = mbOrErr.get(); 3160b57cec5SDimitry Andric enqueueTask([=]() { 3170b57cec5SDimitry Andric driver->addArchiveBuffer(mb, toCOFFString(sym), parentName, 3180b57cec5SDimitry Andric offsetInArchive); 3190b57cec5SDimitry Andric }); 3200b57cec5SDimitry Andric return; 3210b57cec5SDimitry Andric } 3220b57cec5SDimitry Andric 3230b57cec5SDimitry Andric std::string childName = CHECK( 3240b57cec5SDimitry Andric c.getFullName(), 3250b57cec5SDimitry Andric "could not get the filename for the member defining symbol " + 3260b57cec5SDimitry Andric toCOFFString(sym)); 3270b57cec5SDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 3280b57cec5SDimitry Andric createFutureForFile(childName)); 3290b57cec5SDimitry Andric enqueueTask([=]() { 3300b57cec5SDimitry Andric auto mbOrErr = future->get(); 3310b57cec5SDimitry Andric if (mbOrErr.second) 3320b57cec5SDimitry Andric reportBufferError(errorCodeToError(mbOrErr.second), childName); 33385868e8aSDimitry Andric // Pass empty string as archive name so that the original filename is 33485868e8aSDimitry Andric // used as the buffer identifier. 3350b57cec5SDimitry Andric driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 33685868e8aSDimitry Andric toCOFFString(sym), "", /*OffsetInArchive=*/0); 3370b57cec5SDimitry Andric }); 3380b57cec5SDimitry Andric } 3390b57cec5SDimitry Andric 3400b57cec5SDimitry Andric static bool isDecorated(StringRef sym) { 3410b57cec5SDimitry Andric return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 3420b57cec5SDimitry Andric (!config->mingw && sym.contains('@')); 3430b57cec5SDimitry Andric } 3440b57cec5SDimitry Andric 3450b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files 3460b57cec5SDimitry Andric // specified by /defaultlib. 3470b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) { 3480b57cec5SDimitry Andric StringRef s = file->getDirectives(); 3490b57cec5SDimitry Andric if (s.empty()) 3500b57cec5SDimitry Andric return; 3510b57cec5SDimitry Andric 3520b57cec5SDimitry Andric log("Directives: " + toString(file) + ": " + s); 3530b57cec5SDimitry Andric 3540b57cec5SDimitry Andric ArgParser parser; 3550b57cec5SDimitry Andric // .drectve is always tokenized using Windows shell rules. 3560b57cec5SDimitry Andric // /EXPORT: option can appear too many times, processing in fastpath. 3575ffd83dbSDimitry Andric ParsedDirectives directives = parser.parseDirectives(s); 3580b57cec5SDimitry Andric 3595ffd83dbSDimitry Andric for (StringRef e : directives.exports) { 3600b57cec5SDimitry Andric // If a common header file contains dllexported function 3610b57cec5SDimitry Andric // declarations, many object files may end up with having the 3620b57cec5SDimitry Andric // same /EXPORT options. In order to save cost of parsing them, 3630b57cec5SDimitry Andric // we dedup them first. 3640b57cec5SDimitry Andric if (!directivesExports.insert(e).second) 3650b57cec5SDimitry Andric continue; 3660b57cec5SDimitry Andric 3670b57cec5SDimitry Andric Export exp = parseExport(e); 3680b57cec5SDimitry Andric if (config->machine == I386 && config->mingw) { 3690b57cec5SDimitry Andric if (!isDecorated(exp.name)) 3700b57cec5SDimitry Andric exp.name = saver.save("_" + exp.name); 3710b57cec5SDimitry Andric if (!exp.extName.empty() && !isDecorated(exp.extName)) 3720b57cec5SDimitry Andric exp.extName = saver.save("_" + exp.extName); 3730b57cec5SDimitry Andric } 3740b57cec5SDimitry Andric exp.directives = true; 3750b57cec5SDimitry Andric config->exports.push_back(exp); 3760b57cec5SDimitry Andric } 3770b57cec5SDimitry Andric 3785ffd83dbSDimitry Andric // Handle /include: in bulk. 3795ffd83dbSDimitry Andric for (StringRef inc : directives.includes) 3805ffd83dbSDimitry Andric addUndefined(inc); 3815ffd83dbSDimitry Andric 3825ffd83dbSDimitry Andric for (auto *arg : directives.args) { 3830b57cec5SDimitry Andric switch (arg->getOption().getID()) { 3840b57cec5SDimitry Andric case OPT_aligncomm: 3850b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 3860b57cec5SDimitry Andric break; 3870b57cec5SDimitry Andric case OPT_alternatename: 3880b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 3890b57cec5SDimitry Andric break; 3900b57cec5SDimitry Andric case OPT_defaultlib: 3910b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 39285868e8aSDimitry Andric enqueuePath(*path, false, false); 3930b57cec5SDimitry Andric break; 3940b57cec5SDimitry Andric case OPT_entry: 3950b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 3960b57cec5SDimitry Andric break; 3970b57cec5SDimitry Andric case OPT_failifmismatch: 3980b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), file); 3990b57cec5SDimitry Andric break; 4000b57cec5SDimitry Andric case OPT_incl: 4010b57cec5SDimitry Andric addUndefined(arg->getValue()); 4020b57cec5SDimitry Andric break; 4030b57cec5SDimitry Andric case OPT_merge: 4040b57cec5SDimitry Andric parseMerge(arg->getValue()); 4050b57cec5SDimitry Andric break; 4060b57cec5SDimitry Andric case OPT_nodefaultlib: 4070b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 4080b57cec5SDimitry Andric break; 4090b57cec5SDimitry Andric case OPT_section: 4100b57cec5SDimitry Andric parseSection(arg->getValue()); 4110b57cec5SDimitry Andric break; 412*e8d8bef9SDimitry Andric case OPT_subsystem: { 413*e8d8bef9SDimitry Andric bool gotVersion = false; 4140b57cec5SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 415*e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 416*e8d8bef9SDimitry Andric &config->minorSubsystemVersion, &gotVersion); 417*e8d8bef9SDimitry Andric if (gotVersion) { 418*e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 419*e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 420*e8d8bef9SDimitry Andric } 4210b57cec5SDimitry Andric break; 422*e8d8bef9SDimitry Andric } 4230b57cec5SDimitry Andric // Only add flags here that link.exe accepts in 4240b57cec5SDimitry Andric // `#pragma comment(linker, "/flag")`-generated sections. 4250b57cec5SDimitry Andric case OPT_editandcontinue: 4260b57cec5SDimitry Andric case OPT_guardsym: 4270b57cec5SDimitry Andric case OPT_throwingnew: 4280b57cec5SDimitry Andric break; 4290b57cec5SDimitry Andric default: 4300b57cec5SDimitry Andric error(arg->getSpelling() + " is not allowed in .drectve"); 4310b57cec5SDimitry Andric } 4320b57cec5SDimitry Andric } 4330b57cec5SDimitry Andric } 4340b57cec5SDimitry Andric 4350b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes 4360b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist. 4370b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) { 4380b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4390b57cec5SDimitry Andric if (hasPathSep) 4400b57cec5SDimitry Andric return filename; 4410b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4420b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4430b57cec5SDimitry Andric SmallString<128> path = dir; 4440b57cec5SDimitry Andric sys::path::append(path, filename); 4450b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 4460b57cec5SDimitry Andric return saver.save(path.str()); 4470b57cec5SDimitry Andric if (!hasExt) { 4480b57cec5SDimitry Andric path.append(".obj"); 4490b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 4500b57cec5SDimitry Andric return saver.save(path.str()); 4510b57cec5SDimitry Andric } 4520b57cec5SDimitry Andric } 4530b57cec5SDimitry Andric return filename; 4540b57cec5SDimitry Andric } 4550b57cec5SDimitry Andric 4560b57cec5SDimitry Andric static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4570b57cec5SDimitry Andric sys::fs::UniqueID ret; 4580b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 4590b57cec5SDimitry Andric return None; 4600b57cec5SDimitry Andric return ret; 4610b57cec5SDimitry Andric } 4620b57cec5SDimitry Andric 4630b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 4640b57cec5SDimitry Andric // (in that case, it returns None). 4650b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4660b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4670b57cec5SDimitry Andric 4680b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4690b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4700b57cec5SDimitry Andric if (seen) 4710b57cec5SDimitry Andric return None; 4720b57cec5SDimitry Andric } 4730b57cec5SDimitry Andric 4740b57cec5SDimitry Andric if (path.endswith_lower(".lib")) 4755ffd83dbSDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path))); 4760b57cec5SDimitry Andric return path; 4770b57cec5SDimitry Andric } 4780b57cec5SDimitry Andric 4790b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 4800b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 4810b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 4820b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 4830b57cec5SDimitry Andric return filename; 4840b57cec5SDimitry Andric 4850b57cec5SDimitry Andric SmallString<128> s = filename; 4860b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 4870b57cec5SDimitry Andric StringRef libName = saver.save("lib" + s.str()); 4880b57cec5SDimitry Andric return doFindFile(libName); 4890b57cec5SDimitry Andric } 4900b57cec5SDimitry Andric 4910b57cec5SDimitry Andric // Find library file from search path. 4920b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 4930b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 4940b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4950b57cec5SDimitry Andric if (!hasExt) 4960b57cec5SDimitry Andric filename = saver.save(filename + ".lib"); 4970b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 4980b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 4990b57cec5SDimitry Andric // looking for a MinGW formatted library name. 5000b57cec5SDimitry Andric if (config->mingw && ret == filename) 5010b57cec5SDimitry Andric return doFindLibMinGW(filename); 5020b57cec5SDimitry Andric return ret; 5030b57cec5SDimitry Andric } 5040b57cec5SDimitry Andric 5050b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 5060b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 5070b57cec5SDimitry Andric // it returns None). 5080b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 5090b57cec5SDimitry Andric if (config->noDefaultLibAll) 5100b57cec5SDimitry Andric return None; 5110b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 5120b57cec5SDimitry Andric return None; 5130b57cec5SDimitry Andric 5140b57cec5SDimitry Andric StringRef path = doFindLib(filename); 5150b57cec5SDimitry Andric if (config->noDefaultLibs.count(path.lower())) 5160b57cec5SDimitry Andric return None; 5170b57cec5SDimitry Andric 5180b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 5190b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 5200b57cec5SDimitry Andric return None; 5210b57cec5SDimitry Andric return path; 5220b57cec5SDimitry Andric } 5230b57cec5SDimitry Andric 5240b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 5250b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 5260b57cec5SDimitry Andric Optional<std::string> envOpt = Process::GetEnv("LIB"); 5270b57cec5SDimitry Andric if (!envOpt.hasValue()) 5280b57cec5SDimitry Andric return; 5290b57cec5SDimitry Andric StringRef env = saver.save(*envOpt); 5300b57cec5SDimitry Andric while (!env.empty()) { 5310b57cec5SDimitry Andric StringRef path; 5320b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 5330b57cec5SDimitry Andric searchPaths.push_back(path); 5340b57cec5SDimitry Andric } 5350b57cec5SDimitry Andric } 5360b57cec5SDimitry Andric 5370b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 5380b57cec5SDimitry Andric Symbol *b = symtab->addUndefined(name); 5390b57cec5SDimitry Andric if (!b->isGCRoot) { 5400b57cec5SDimitry Andric b->isGCRoot = true; 5410b57cec5SDimitry Andric config->gcroot.push_back(b); 5420b57cec5SDimitry Andric } 5430b57cec5SDimitry Andric return b; 5440b57cec5SDimitry Andric } 5450b57cec5SDimitry Andric 5460b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 5470b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 5480b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 5490b57cec5SDimitry Andric if (!unmangled) 5500b57cec5SDimitry Andric return ""; 5510b57cec5SDimitry Andric 5520b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 5530b57cec5SDimitry Andric Symbol *mangled = symtab->findMangle(unmangled->getName()); 5540b57cec5SDimitry Andric if (!mangled) 5550b57cec5SDimitry Andric return ""; 5560b57cec5SDimitry Andric 5570b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 5580b57cec5SDimitry Andric // its name. 5590b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 5600b57cec5SDimitry Andric unmangled->weakAlias = symtab->addUndefined(mangled->getName()); 5610b57cec5SDimitry Andric return mangled->getName(); 5620b57cec5SDimitry Andric } 5630b57cec5SDimitry Andric 5640b57cec5SDimitry Andric // Windows specific -- find default entry point name. 5650b57cec5SDimitry Andric // 5660b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 5670b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 5680b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 5690b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 5700b57cec5SDimitry Andric assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 5710b57cec5SDimitry Andric "must handle /subsystem before calling this"); 5720b57cec5SDimitry Andric 5730b57cec5SDimitry Andric if (config->mingw) 5740b57cec5SDimitry Andric return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 5750b57cec5SDimitry Andric ? "WinMainCRTStartup" 5760b57cec5SDimitry Andric : "mainCRTStartup"); 5770b57cec5SDimitry Andric 5780b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 5790b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 5800b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 5810b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 5820b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 5830b57cec5SDimitry Andric } 5840b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 5850b57cec5SDimitry Andric } 5860b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 5870b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 5880b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 5890b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 5900b57cec5SDimitry Andric } 5910b57cec5SDimitry Andric return mangle("mainCRTStartup"); 5920b57cec5SDimitry Andric } 5930b57cec5SDimitry Andric 5940b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 5950b57cec5SDimitry Andric if (config->dll) 5960b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 5970b57cec5SDimitry Andric if (config->mingw) 5980b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 5990b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 6000b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 6010b57cec5SDimitry Andric // to not be called. 6020b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 6030b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 6040b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 6050b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 6060b57cec5SDimitry Andric if (haveMain || haveWMain) { 6070b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 6080b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 6090b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 6100b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 6110b57cec5SDimitry Andric } 6120b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 6130b57cec5SDimitry Andric } 6140b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 6150b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 6160b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 6170b57cec5SDimitry Andric } 6180b57cec5SDimitry Andric 6190b57cec5SDimitry Andric static uint64_t getDefaultImageBase() { 6200b57cec5SDimitry Andric if (config->is64()) 6210b57cec5SDimitry Andric return config->dll ? 0x180000000 : 0x140000000; 6220b57cec5SDimitry Andric return config->dll ? 0x10000000 : 0x400000; 6230b57cec5SDimitry Andric } 6240b57cec5SDimitry Andric 6250b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 6260b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 6270b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 6280b57cec5SDimitry Andric SmallString<0> data; 6290b57cec5SDimitry Andric raw_svector_ostream os(data); 6300b57cec5SDimitry Andric 6310b57cec5SDimitry Andric for (auto *arg : args) { 6320b57cec5SDimitry Andric switch (arg->getOption().getID()) { 6330b57cec5SDimitry Andric case OPT_linkrepro: 63485868e8aSDimitry Andric case OPT_reproduce: 6350b57cec5SDimitry Andric case OPT_INPUT: 6360b57cec5SDimitry Andric case OPT_defaultlib: 6370b57cec5SDimitry Andric case OPT_libpath: 6380b57cec5SDimitry Andric case OPT_manifest: 6390b57cec5SDimitry Andric case OPT_manifest_colon: 6400b57cec5SDimitry Andric case OPT_manifestdependency: 6410b57cec5SDimitry Andric case OPT_manifestfile: 6420b57cec5SDimitry Andric case OPT_manifestinput: 6430b57cec5SDimitry Andric case OPT_manifestuac: 6440b57cec5SDimitry Andric break; 6450b57cec5SDimitry Andric case OPT_implib: 6460b57cec5SDimitry Andric case OPT_pdb: 6475ffd83dbSDimitry Andric case OPT_pdbstripped: 6480b57cec5SDimitry Andric case OPT_out: 6490b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 6500b57cec5SDimitry Andric break; 6510b57cec5SDimitry Andric default: 6520b57cec5SDimitry Andric os << toString(*arg) << "\n"; 6530b57cec5SDimitry Andric } 6540b57cec5SDimitry Andric } 6550b57cec5SDimitry Andric 6560b57cec5SDimitry Andric for (StringRef path : searchPaths) { 6570b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 6580b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 6590b57cec5SDimitry Andric } 6600b57cec5SDimitry Andric 6610b57cec5SDimitry Andric for (StringRef path : filePaths) 6620b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 6630b57cec5SDimitry Andric 6645ffd83dbSDimitry Andric return std::string(data.str()); 6650b57cec5SDimitry Andric } 6660b57cec5SDimitry Andric 6670b57cec5SDimitry Andric enum class DebugKind { Unknown, None, Full, FastLink, GHash, Dwarf, Symtab }; 6680b57cec5SDimitry Andric 6690b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 6700b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 6710b57cec5SDimitry Andric if (!a) 6720b57cec5SDimitry Andric return DebugKind::None; 6730b57cec5SDimitry Andric if (a->getNumValues() == 0) 6740b57cec5SDimitry Andric return DebugKind::Full; 6750b57cec5SDimitry Andric 6760b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 6770b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 6780b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 6790b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 6800b57cec5SDimitry Andric // LLD extensions 6810b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 6820b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 6830b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 6840b57cec5SDimitry Andric .Default(DebugKind::Unknown); 6850b57cec5SDimitry Andric 6860b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 6870b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 6880b57cec5SDimitry Andric return DebugKind::Full; 6890b57cec5SDimitry Andric } 6900b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 6910b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 6920b57cec5SDimitry Andric return DebugKind::None; 6930b57cec5SDimitry Andric } 6940b57cec5SDimitry Andric return debug; 6950b57cec5SDimitry Andric } 6960b57cec5SDimitry Andric 6970b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 6980b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 6990b57cec5SDimitry Andric 7000b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 7010b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 7020b57cec5SDimitry Andric StringRef(a->getValue()) 7030b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 7040b57cec5SDimitry Andric 7050b57cec5SDimitry Andric for (StringRef type : types) { 7060b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 7070b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 7080b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 7090b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 7100b57cec5SDimitry Andric .Default(0); 7110b57cec5SDimitry Andric if (v == 0) { 7120b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 7130b57cec5SDimitry Andric continue; 7140b57cec5SDimitry Andric } 7150b57cec5SDimitry Andric debugTypes |= v; 7160b57cec5SDimitry Andric } 7170b57cec5SDimitry Andric return debugTypes; 7180b57cec5SDimitry Andric } 7190b57cec5SDimitry Andric 7200b57cec5SDimitry Andric // Default debug types 7210b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 7220b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 7230b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 7240b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 7250b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 7260b57cec5SDimitry Andric 7270b57cec5SDimitry Andric return debugTypes; 7280b57cec5SDimitry Andric } 7290b57cec5SDimitry Andric 7305ffd83dbSDimitry Andric static std::string getMapFile(const opt::InputArgList &args, 7315ffd83dbSDimitry Andric opt::OptSpecifier os, opt::OptSpecifier osFile) { 7325ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 7330b57cec5SDimitry Andric if (!arg) 7340b57cec5SDimitry Andric return ""; 7355ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 7360b57cec5SDimitry Andric return arg->getValue(); 7370b57cec5SDimitry Andric 7385ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 7390b57cec5SDimitry Andric StringRef outFile = config->outputFile; 7400b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 7410b57cec5SDimitry Andric } 7420b57cec5SDimitry Andric 7430b57cec5SDimitry Andric static std::string getImplibPath() { 7440b57cec5SDimitry Andric if (!config->implib.empty()) 7455ffd83dbSDimitry Andric return std::string(config->implib); 7460b57cec5SDimitry Andric SmallString<128> out = StringRef(config->outputFile); 7470b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 7485ffd83dbSDimitry Andric return std::string(out.str()); 7490b57cec5SDimitry Andric } 7500b57cec5SDimitry Andric 75185868e8aSDimitry Andric // The import name is calculated as follows: 7520b57cec5SDimitry Andric // 7530b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 7540b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 7550b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 7560b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 7570b57cec5SDimitry Andric // 7580b57cec5SDimitry Andric static std::string getImportName(bool asLib) { 7590b57cec5SDimitry Andric SmallString<128> out; 7600b57cec5SDimitry Andric 7610b57cec5SDimitry Andric if (config->importName.empty()) { 7620b57cec5SDimitry Andric out.assign(sys::path::filename(config->outputFile)); 7630b57cec5SDimitry Andric if (asLib) 7640b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 7650b57cec5SDimitry Andric } else { 7660b57cec5SDimitry Andric out.assign(config->importName); 7670b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 7680b57cec5SDimitry Andric sys::path::replace_extension(out, 7690b57cec5SDimitry Andric (config->dll || asLib) ? ".dll" : ".exe"); 7700b57cec5SDimitry Andric } 7710b57cec5SDimitry Andric 7725ffd83dbSDimitry Andric return std::string(out.str()); 7730b57cec5SDimitry Andric } 7740b57cec5SDimitry Andric 7750b57cec5SDimitry Andric static void createImportLibrary(bool asLib) { 7760b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 7770b57cec5SDimitry Andric for (Export &e1 : config->exports) { 7780b57cec5SDimitry Andric COFFShortExport e2; 7795ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 7805ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 7815ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 7820b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 7830b57cec5SDimitry Andric e2.Noname = e1.noname; 7840b57cec5SDimitry Andric e2.Data = e1.data; 7850b57cec5SDimitry Andric e2.Private = e1.isPrivate; 7860b57cec5SDimitry Andric e2.Constant = e1.constant; 7870b57cec5SDimitry Andric exports.push_back(e2); 7880b57cec5SDimitry Andric } 7890b57cec5SDimitry Andric 7900b57cec5SDimitry Andric auto handleError = [](Error &&e) { 7910b57cec5SDimitry Andric handleAllErrors(std::move(e), 7920b57cec5SDimitry Andric [](ErrorInfoBase &eib) { error(eib.message()); }); 7930b57cec5SDimitry Andric }; 7940b57cec5SDimitry Andric std::string libName = getImportName(asLib); 7950b57cec5SDimitry Andric std::string path = getImplibPath(); 7960b57cec5SDimitry Andric 7970b57cec5SDimitry Andric if (!config->incremental) { 7980b57cec5SDimitry Andric handleError(writeImportLibrary(libName, path, exports, config->machine, 7990b57cec5SDimitry Andric config->mingw)); 8000b57cec5SDimitry Andric return; 8010b57cec5SDimitry Andric } 8020b57cec5SDimitry Andric 8030b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 8040b57cec5SDimitry Andric // have changed. 8050b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 8060b57cec5SDimitry Andric path, /*FileSize*/ -1, /*RequiresNullTerminator*/ false); 8070b57cec5SDimitry Andric if (!oldBuf) { 8080b57cec5SDimitry Andric handleError(writeImportLibrary(libName, path, exports, config->machine, 8090b57cec5SDimitry Andric config->mingw)); 8100b57cec5SDimitry Andric return; 8110b57cec5SDimitry Andric } 8120b57cec5SDimitry Andric 8130b57cec5SDimitry Andric SmallString<128> tmpName; 8140b57cec5SDimitry Andric if (std::error_code ec = 8150b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 8160b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 8170b57cec5SDimitry Andric ec.message()); 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 8200b57cec5SDimitry Andric config->mingw)) { 8210b57cec5SDimitry Andric handleError(std::move(e)); 8220b57cec5SDimitry Andric return; 8230b57cec5SDimitry Andric } 8240b57cec5SDimitry Andric 8250b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 8260b57cec5SDimitry Andric tmpName, /*FileSize*/ -1, /*RequiresNullTerminator*/ false)); 8270b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 8280b57cec5SDimitry Andric oldBuf->reset(); 8290b57cec5SDimitry Andric handleError(errorCodeToError(sys::fs::rename(tmpName, path))); 8300b57cec5SDimitry Andric } else { 8310b57cec5SDimitry Andric sys::fs::remove(tmpName); 8320b57cec5SDimitry Andric } 8330b57cec5SDimitry Andric } 8340b57cec5SDimitry Andric 8350b57cec5SDimitry Andric static void parseModuleDefs(StringRef path) { 8360b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> mb = CHECK( 8370b57cec5SDimitry Andric MemoryBuffer::getFile(path, -1, false, true), "could not open " + path); 8380b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 8390b57cec5SDimitry Andric mb->getMemBufferRef(), config->machine, config->mingw)); 8400b57cec5SDimitry Andric 8410b57cec5SDimitry Andric if (config->outputFile.empty()) 8425ffd83dbSDimitry Andric config->outputFile = std::string(saver.save(m.OutputFile)); 8435ffd83dbSDimitry Andric config->importName = std::string(saver.save(m.ImportName)); 8440b57cec5SDimitry Andric if (m.ImageBase) 8450b57cec5SDimitry Andric config->imageBase = m.ImageBase; 8460b57cec5SDimitry Andric if (m.StackReserve) 8470b57cec5SDimitry Andric config->stackReserve = m.StackReserve; 8480b57cec5SDimitry Andric if (m.StackCommit) 8490b57cec5SDimitry Andric config->stackCommit = m.StackCommit; 8500b57cec5SDimitry Andric if (m.HeapReserve) 8510b57cec5SDimitry Andric config->heapReserve = m.HeapReserve; 8520b57cec5SDimitry Andric if (m.HeapCommit) 8530b57cec5SDimitry Andric config->heapCommit = m.HeapCommit; 8540b57cec5SDimitry Andric if (m.MajorImageVersion) 8550b57cec5SDimitry Andric config->majorImageVersion = m.MajorImageVersion; 8560b57cec5SDimitry Andric if (m.MinorImageVersion) 8570b57cec5SDimitry Andric config->minorImageVersion = m.MinorImageVersion; 8580b57cec5SDimitry Andric if (m.MajorOSVersion) 8590b57cec5SDimitry Andric config->majorOSVersion = m.MajorOSVersion; 8600b57cec5SDimitry Andric if (m.MinorOSVersion) 8610b57cec5SDimitry Andric config->minorOSVersion = m.MinorOSVersion; 8620b57cec5SDimitry Andric 8630b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 8640b57cec5SDimitry Andric Export e2; 8650b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 8660b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 8670b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 8680b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 8695ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 8705ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 8710b57cec5SDimitry Andric e2.name = saver.save(e1.ExtName); 8720b57cec5SDimitry Andric e2.forwardTo = saver.save(e1.Name); 8730b57cec5SDimitry Andric config->exports.push_back(e2); 8740b57cec5SDimitry Andric continue; 8750b57cec5SDimitry Andric } 8760b57cec5SDimitry Andric e2.name = saver.save(e1.Name); 8770b57cec5SDimitry Andric e2.extName = saver.save(e1.ExtName); 8780b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 8790b57cec5SDimitry Andric e2.noname = e1.Noname; 8800b57cec5SDimitry Andric e2.data = e1.Data; 8810b57cec5SDimitry Andric e2.isPrivate = e1.Private; 8820b57cec5SDimitry Andric e2.constant = e1.Constant; 8830b57cec5SDimitry Andric config->exports.push_back(e2); 8840b57cec5SDimitry Andric } 8850b57cec5SDimitry Andric } 8860b57cec5SDimitry Andric 8870b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 8880b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 8890b57cec5SDimitry Andric } 8900b57cec5SDimitry Andric 8910b57cec5SDimitry Andric bool LinkerDriver::run() { 8920b57cec5SDimitry Andric ScopedTimer t(inputFileTimer); 8930b57cec5SDimitry Andric 8940b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 8950b57cec5SDimitry Andric while (!taskQueue.empty()) { 8960b57cec5SDimitry Andric taskQueue.front()(); 8970b57cec5SDimitry Andric taskQueue.pop_front(); 8980b57cec5SDimitry Andric } 8990b57cec5SDimitry Andric return didWork; 9000b57cec5SDimitry Andric } 9010b57cec5SDimitry Andric 9020b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 9030b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 9040b57cec5SDimitry Andric // given file. 9050b57cec5SDimitry Andric static void parseOrderFile(StringRef arg) { 9060b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 9070b57cec5SDimitry Andric // preceded by "@". 9080b57cec5SDimitry Andric if (!arg.startswith("@")) { 9090b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 9100b57cec5SDimitry Andric return; 9110b57cec5SDimitry Andric } 9120b57cec5SDimitry Andric 9130b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 9140b57cec5SDimitry Andric DenseSet<StringRef> set; 9150b57cec5SDimitry Andric for (Chunk *c : symtab->getChunks()) 9160b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 9170b57cec5SDimitry Andric if (sec->sym) 9180b57cec5SDimitry Andric set.insert(sec->sym->getName()); 9190b57cec5SDimitry Andric 9200b57cec5SDimitry Andric // Open a file. 9210b57cec5SDimitry Andric StringRef path = arg.substr(1); 9220b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> mb = CHECK( 9230b57cec5SDimitry Andric MemoryBuffer::getFile(path, -1, false, true), "could not open " + path); 9240b57cec5SDimitry Andric 9250b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 9260b57cec5SDimitry Andric // All symbols that were not present in a given order file are 9270b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 9280b57cec5SDimitry Andric // end of an output section. 9295ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 9305ffd83dbSDimitry Andric std::string s(arg); 9310b57cec5SDimitry Andric if (config->machine == I386 && !isDecorated(s)) 9320b57cec5SDimitry Andric s = "_" + s; 9330b57cec5SDimitry Andric 9340b57cec5SDimitry Andric if (set.count(s) == 0) { 9350b57cec5SDimitry Andric if (config->warnMissingOrderSymbol) 9360b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 9370b57cec5SDimitry Andric } 9380b57cec5SDimitry Andric else 9390b57cec5SDimitry Andric config->order[s] = INT_MIN + config->order.size(); 9400b57cec5SDimitry Andric } 9410b57cec5SDimitry Andric } 9420b57cec5SDimitry Andric 943*e8d8bef9SDimitry Andric static void parseCallGraphFile(StringRef path) { 944*e8d8bef9SDimitry Andric std::unique_ptr<MemoryBuffer> mb = CHECK( 945*e8d8bef9SDimitry Andric MemoryBuffer::getFile(path, -1, false, true), "could not open " + path); 946*e8d8bef9SDimitry Andric 947*e8d8bef9SDimitry Andric // Build a map from symbol name to section. 948*e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 949*e8d8bef9SDimitry Andric for (ObjFile *file : ObjFile::instances) 950*e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 951*e8d8bef9SDimitry Andric if (sym) 952*e8d8bef9SDimitry Andric map[sym->getName()] = sym; 953*e8d8bef9SDimitry Andric 954*e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 955*e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 956*e8d8bef9SDimitry Andric if (!sym) { 957*e8d8bef9SDimitry Andric if (config->warnMissingOrderSymbol) 958*e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 959*e8d8bef9SDimitry Andric return nullptr; 960*e8d8bef9SDimitry Andric } 961*e8d8bef9SDimitry Andric 962*e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 963*e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 964*e8d8bef9SDimitry Andric return nullptr; 965*e8d8bef9SDimitry Andric }; 966*e8d8bef9SDimitry Andric 967*e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 968*e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 969*e8d8bef9SDimitry Andric line.split(fields, ' '); 970*e8d8bef9SDimitry Andric uint64_t count; 971*e8d8bef9SDimitry Andric 972*e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 973*e8d8bef9SDimitry Andric error(path + ": parse error"); 974*e8d8bef9SDimitry Andric return; 975*e8d8bef9SDimitry Andric } 976*e8d8bef9SDimitry Andric 977*e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 978*e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 979*e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 980*e8d8bef9SDimitry Andric } 981*e8d8bef9SDimitry Andric } 982*e8d8bef9SDimitry Andric 983*e8d8bef9SDimitry Andric static void readCallGraphsFromObjectFiles() { 984*e8d8bef9SDimitry Andric for (ObjFile *obj : ObjFile::instances) { 985*e8d8bef9SDimitry Andric if (obj->callgraphSec) { 986*e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 987*e8d8bef9SDimitry Andric cantFail( 988*e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 989*e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 990*e8d8bef9SDimitry Andric while (!reader.empty()) { 991*e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 992*e8d8bef9SDimitry Andric uint64_t count; 993*e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 994*e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 995*e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 996*e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 997*e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 998*e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 999*e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1000*e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1001*e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1002*e8d8bef9SDimitry Andric continue; 1003*e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1004*e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1005*e8d8bef9SDimitry Andric if (from && to) 1006*e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1007*e8d8bef9SDimitry Andric } 1008*e8d8bef9SDimitry Andric } 1009*e8d8bef9SDimitry Andric } 1010*e8d8bef9SDimitry Andric } 1011*e8d8bef9SDimitry Andric 10120b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 10130b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 10140b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 10150b57cec5SDimitry Andric c->keepUnique = true; 10160b57cec5SDimitry Andric } 10170b57cec5SDimitry Andric 10180b57cec5SDimitry Andric static void findKeepUniqueSections() { 10190b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 10200b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 10210b57cec5SDimitry Andric for (Export &r : config->exports) 10220b57cec5SDimitry Andric markAddrsig(r.sym); 10230b57cec5SDimitry Andric 10240b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 10250b57cec5SDimitry Andric // referenced symbol as address-significant. 10260b57cec5SDimitry Andric for (ObjFile *obj : ObjFile::instances) { 10270b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 10280b57cec5SDimitry Andric if (obj->addrsigSec) { 10290b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 10300b57cec5SDimitry Andric cantFail( 10310b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 10320b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 10330b57cec5SDimitry Andric while (cur != contents.end()) { 10340b57cec5SDimitry Andric unsigned size; 10350b57cec5SDimitry Andric const char *err; 10360b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 10370b57cec5SDimitry Andric if (err) 10380b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 10390b57cec5SDimitry Andric if (symIndex >= syms.size()) 10400b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 10410b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 10420b57cec5SDimitry Andric cur += size; 10430b57cec5SDimitry Andric } 10440b57cec5SDimitry Andric } else { 10450b57cec5SDimitry Andric // If an object file does not have an address-significance table, 10460b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 10470b57cec5SDimitry Andric for (Symbol *s : syms) 10480b57cec5SDimitry Andric markAddrsig(s); 10490b57cec5SDimitry Andric } 10500b57cec5SDimitry Andric } 10510b57cec5SDimitry Andric } 10520b57cec5SDimitry Andric 10530b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 10540b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 10550b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 10560b57cec5SDimitry Andric // binary). 10570b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 10580b57cec5SDimitry Andric // vars. 10590b57cec5SDimitry Andric static void parsePDBAltPath(StringRef altPath) { 10600b57cec5SDimitry Andric SmallString<128> buf; 10610b57cec5SDimitry Andric StringRef pdbBasename = 10620b57cec5SDimitry Andric sys::path::filename(config->pdbPath, sys::path::Style::windows); 10630b57cec5SDimitry Andric StringRef binaryExtension = 10640b57cec5SDimitry Andric sys::path::extension(config->outputFile, sys::path::Style::windows); 10650b57cec5SDimitry Andric if (!binaryExtension.empty()) 10660b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 10670b57cec5SDimitry Andric 10680b57cec5SDimitry Andric // Invariant: 10690b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 10700b57cec5SDimitry Andric // | +----- firstMark 10710b57cec5SDimitry Andric // | | +- secondMark 10720b57cec5SDimitry Andric // v v v 10730b57cec5SDimitry Andric // a...%...%... 10740b57cec5SDimitry Andric size_t cursor = 0; 10750b57cec5SDimitry Andric while (cursor < altPath.size()) { 10760b57cec5SDimitry Andric size_t firstMark, secondMark; 10770b57cec5SDimitry Andric if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 10780b57cec5SDimitry Andric (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 10790b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 10800b57cec5SDimitry Andric buf.append(altPath.substr(cursor)); 10810b57cec5SDimitry Andric break; 10820b57cec5SDimitry Andric } 10830b57cec5SDimitry Andric 10840b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 10850b57cec5SDimitry Andric // text between first and second % as variable name. 10860b57cec5SDimitry Andric buf.append(altPath.substr(cursor, firstMark - cursor)); 10870b57cec5SDimitry Andric StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 10880b57cec5SDimitry Andric if (var.equals_lower("%_pdb%")) 10890b57cec5SDimitry Andric buf.append(pdbBasename); 10900b57cec5SDimitry Andric else if (var.equals_lower("%_ext%")) 10910b57cec5SDimitry Andric buf.append(binaryExtension); 10920b57cec5SDimitry Andric else { 10930b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 10940b57cec5SDimitry Andric var + " as literal"); 10950b57cec5SDimitry Andric buf.append(var); 10960b57cec5SDimitry Andric } 10970b57cec5SDimitry Andric 10980b57cec5SDimitry Andric cursor = secondMark + 1; 10990b57cec5SDimitry Andric } 11000b57cec5SDimitry Andric 11010b57cec5SDimitry Andric config->pdbAltPath = buf; 11020b57cec5SDimitry Andric } 11030b57cec5SDimitry Andric 110485868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 110585868e8aSDimitry Andric /// trees into one resource tree. 11060b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 110785868e8aSDimitry Andric void LinkerDriver::convertResources() { 110885868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 110985868e8aSDimitry Andric 11100b57cec5SDimitry Andric for (ObjFile *f : ObjFile::instances) { 111185868e8aSDimitry Andric if (f->isResourceObjFile()) 111285868e8aSDimitry Andric resourceObjFiles.push_back(f); 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric 111585868e8aSDimitry Andric if (!config->mingw && 111685868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 111785868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 111885868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 111985868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 11200b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 112185868e8aSDimitry Andric toString(resourceObjFiles.front())); 112285868e8aSDimitry Andric return; 11230b57cec5SDimitry Andric } 112485868e8aSDimitry Andric 112585868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 112685868e8aSDimitry Andric // No resources to convert, and max one resource object file in 112785868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 112885868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 112985868e8aSDimitry Andric f->includeResourceChunks(); 113085868e8aSDimitry Andric return; 113185868e8aSDimitry Andric } 113285868e8aSDimitry Andric ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles)); 113385868e8aSDimitry Andric symtab->addFile(f); 113485868e8aSDimitry Andric f->includeResourceChunks(); 11350b57cec5SDimitry Andric } 11360b57cec5SDimitry Andric 11370b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 11380b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 11390b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 11400b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 11410b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 11420b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 11430b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 11440b57cec5SDimitry Andric if (!config->dll) 11450b57cec5SDimitry Andric return; 11460b57cec5SDimitry Andric 11470b57cec5SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 11480b57cec5SDimitry Andric if (!config->exports.empty()) 11490b57cec5SDimitry Andric return; 11500b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 11510b57cec5SDimitry Andric return; 11520b57cec5SDimitry Andric } 11530b57cec5SDimitry Andric 11540b57cec5SDimitry Andric AutoExporter exporter; 11550b57cec5SDimitry Andric 11560b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 11570b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 11580b57cec5SDimitry Andric exporter.addWholeArchive(*path); 11590b57cec5SDimitry Andric 11600b57cec5SDimitry Andric symtab->forEachSymbol([&](Symbol *s) { 11610b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 11620b57cec5SDimitry Andric if (!exporter.shouldExport(def)) 11630b57cec5SDimitry Andric return; 11640b57cec5SDimitry Andric 11650b57cec5SDimitry Andric Export e; 11660b57cec5SDimitry Andric e.name = def->getName(); 11670b57cec5SDimitry Andric e.sym = def; 11680b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 11690b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 11700b57cec5SDimitry Andric e.data = true; 11710b57cec5SDimitry Andric config->exports.push_back(e); 11720b57cec5SDimitry Andric }); 11730b57cec5SDimitry Andric } 11740b57cec5SDimitry Andric 117585868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 117685868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 117785868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 117885868e8aSDimitry Andric // 117985868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 118085868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 118185868e8aSDimitry Andric // with Microsoft link.exe. 118285868e8aSDimitry Andric Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 118385868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 118485868e8aSDimitry Andric return std::string(arg->getValue()); 118585868e8aSDimitry Andric 118685868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 118785868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 118885868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 11895ffd83dbSDimitry Andric return std::string(path); 119085868e8aSDimitry Andric } 119185868e8aSDimitry Andric 1192*e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1193*e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1194*e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1195*e8d8bef9SDimitry Andric return std::string(path); 1196*e8d8bef9SDimitry Andric 119785868e8aSDimitry Andric return None; 119885868e8aSDimitry Andric } 11990b57cec5SDimitry Andric 1200*e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 12015ffd83dbSDimitry Andric ScopedTimer rootTimer(Timer::root()); 12025ffd83dbSDimitry Andric 12030b57cec5SDimitry Andric // Needed for LTO. 12040b57cec5SDimitry Andric InitializeAllTargetInfos(); 12050b57cec5SDimitry Andric InitializeAllTargets(); 12060b57cec5SDimitry Andric InitializeAllTargetMCs(); 12070b57cec5SDimitry Andric InitializeAllAsmParsers(); 12080b57cec5SDimitry Andric InitializeAllAsmPrinters(); 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 12110b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 12120b57cec5SDimitry Andric if (argsArr.size() > 1 && StringRef(argsArr[1]).equals_lower("/lib")) { 12130b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 12140b57cec5SDimitry Andric fatal("lib failed"); 12150b57cec5SDimitry Andric return; 12160b57cec5SDimitry Andric } 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric // Parse command line options. 12190b57cec5SDimitry Andric ArgParser parser; 122085868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 12230b57cec5SDimitry Andric std::vector<const char *> v; 12240b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 12250b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 12260b57cec5SDimitry Andric v.push_back(arg->getValue()); 1227*e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 12280b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 12290b57cec5SDimitry Andric 12300b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 12310b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 12320b57cec5SDimitry Andric int n = 20; 12330b57cec5SDimitry Andric StringRef s = arg->getValue(); 12340b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 12350b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 12360b57cec5SDimitry Andric errorHandler().errorLimit = n; 12370b57cec5SDimitry Andric } 12380b57cec5SDimitry Andric 12390b57cec5SDimitry Andric // Handle /help 12400b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 12410b57cec5SDimitry Andric printHelp(argsArr[0]); 12420b57cec5SDimitry Andric return; 12430b57cec5SDimitry Andric } 12440b57cec5SDimitry Andric 12455ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 12465ffd83dbSDimitry Andric // /opt:lldltojobs=. 12475ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 12485ffd83dbSDimitry Andric StringRef v(arg->getValue()); 12495ffd83dbSDimitry Andric unsigned threads = 0; 12505ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 12515ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 12525ffd83dbSDimitry Andric arg->getValue() + "'"); 12535ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 12545ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 12555ffd83dbSDimitry Andric } 12560b57cec5SDimitry Andric 12570b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 12580b57cec5SDimitry Andric config->showTiming = true; 12590b57cec5SDimitry Andric 12600b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 12610b57cec5SDimitry Andric 12620b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 12630b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 12640b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 12650b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1266*e8d8bef9SDimitry Andric message(getLLDVersion()); 12670b57cec5SDimitry Andric return; 12680b57cec5SDimitry Andric } 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 12710b57cec5SDimitry Andric // options are handled. 12720b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 12730b57cec5SDimitry Andric 127485868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 127585868e8aSDimitry Andric if (Optional<std::string> path = getReproduceFile(args)) { 12760b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 127785868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 12780b57cec5SDimitry Andric 12790b57cec5SDimitry Andric if (errOrWriter) { 12800b57cec5SDimitry Andric tar = std::move(*errOrWriter); 12810b57cec5SDimitry Andric } else { 128285868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 12830b57cec5SDimitry Andric toString(errOrWriter.takeError())); 12840b57cec5SDimitry Andric } 12850b57cec5SDimitry Andric } 12860b57cec5SDimitry Andric 1287480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 12880b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 12890b57cec5SDimitry Andric config->noEntry = true; 12900b57cec5SDimitry Andric else 12910b57cec5SDimitry Andric fatal("no input files"); 12920b57cec5SDimitry Andric } 12930b57cec5SDimitry Andric 12940b57cec5SDimitry Andric // Construct search path list. 12950b57cec5SDimitry Andric searchPaths.push_back(""); 12960b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 12970b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 129885868e8aSDimitry Andric if (!args.hasArg(OPT_lldignoreenv)) 12990b57cec5SDimitry Andric addLibSearchPaths(); 13000b57cec5SDimitry Andric 13010b57cec5SDimitry Andric // Handle /ignore 13020b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 13030b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 13040b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 13050b57cec5SDimitry Andric for (StringRef s : vec) { 13060b57cec5SDimitry Andric if (s == "4037") 13070b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 13080b57cec5SDimitry Andric else if (s == "4099") 13090b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 13100b57cec5SDimitry Andric else if (s == "4217") 13110b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1312480093f4SDimitry Andric else if (s == "longsections") 1313480093f4SDimitry Andric config->warnLongSectionNames = false; 13140b57cec5SDimitry Andric // Other warning numbers are ignored. 13150b57cec5SDimitry Andric } 13160b57cec5SDimitry Andric } 13170b57cec5SDimitry Andric 13180b57cec5SDimitry Andric // Handle /out 13190b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 13200b57cec5SDimitry Andric config->outputFile = arg->getValue(); 13210b57cec5SDimitry Andric 13220b57cec5SDimitry Andric // Handle /verbose 13230b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 13240b57cec5SDimitry Andric config->verbose = true; 13250b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 13260b57cec5SDimitry Andric 13270b57cec5SDimitry Andric // Handle /force or /force:unresolved 13280b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 13290b57cec5SDimitry Andric config->forceUnresolved = true; 13300b57cec5SDimitry Andric 13310b57cec5SDimitry Andric // Handle /force or /force:multiple 13320b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 13330b57cec5SDimitry Andric config->forceMultiple = true; 13340b57cec5SDimitry Andric 13350b57cec5SDimitry Andric // Handle /force or /force:multipleres 13360b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 13370b57cec5SDimitry Andric config->forceMultipleRes = true; 13380b57cec5SDimitry Andric 13390b57cec5SDimitry Andric // Handle /debug 13400b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 13410b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 13420b57cec5SDimitry Andric debug == DebugKind::GHash) { 13430b57cec5SDimitry Andric config->debug = true; 13440b57cec5SDimitry Andric config->incremental = true; 13450b57cec5SDimitry Andric } 13460b57cec5SDimitry Andric 13470b57cec5SDimitry Andric // Handle /demangle 13480b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 13490b57cec5SDimitry Andric 13500b57cec5SDimitry Andric // Handle /debugtype 13510b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 13520b57cec5SDimitry Andric 1353480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1354480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1355480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1356480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1357480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1358480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1359480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1360480093f4SDimitry Andric config->driver = 1361480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1362480093f4SDimitry Andric 13630b57cec5SDimitry Andric // Handle /pdb 13640b57cec5SDimitry Andric bool shouldCreatePDB = 13650b57cec5SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash); 13660b57cec5SDimitry Andric if (shouldCreatePDB) { 13670b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 13680b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 13690b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 13700b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 13710b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 13720b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 13735ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 13745ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 13755ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 13765ffd83dbSDimitry Andric const StringRef name = nameFile.first; 13775ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 13785ffd83dbSDimitry Andric config->namedStreams[name] = file; 13795ffd83dbSDimitry Andric } 13805ffd83dbSDimitry Andric } 13810b57cec5SDimitry Andric 13820b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 13830b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 13840b57cec5SDimitry Andric } 13850b57cec5SDimitry Andric 13865ffd83dbSDimitry Andric // Handle /pdbstripped 13875ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 13885ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 13895ffd83dbSDimitry Andric 13900b57cec5SDimitry Andric // Handle /noentry 13910b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 13920b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 13930b57cec5SDimitry Andric config->noEntry = true; 13940b57cec5SDimitry Andric else 13950b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 13960b57cec5SDimitry Andric } 13970b57cec5SDimitry Andric 13980b57cec5SDimitry Andric // Handle /dll 13990b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 14000b57cec5SDimitry Andric config->dll = true; 14010b57cec5SDimitry Andric config->manifestID = 2; 14020b57cec5SDimitry Andric } 14030b57cec5SDimitry Andric 14040b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 14050b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 14060b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 14070b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 14080b57cec5SDimitry Andric if (dynamicBaseArg && 14090b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 14100b57cec5SDimitry Andric config->dynamicBase = false; 14110b57cec5SDimitry Andric 14120b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 14130b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 14140b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 14150b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 14160b57cec5SDimitry Andric if (fixed) { 14170b57cec5SDimitry Andric if (dynamicBaseArg && 14180b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 14190b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 14200b57cec5SDimitry Andric } else { 14210b57cec5SDimitry Andric config->relocatable = false; 14220b57cec5SDimitry Andric config->dynamicBase = false; 14230b57cec5SDimitry Andric } 14240b57cec5SDimitry Andric } 14250b57cec5SDimitry Andric 14260b57cec5SDimitry Andric // Handle /appcontainer 14270b57cec5SDimitry Andric config->appContainer = 14280b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 14290b57cec5SDimitry Andric 14300b57cec5SDimitry Andric // Handle /machine 14310b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 14320b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 14330b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 14340b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 14350b57cec5SDimitry Andric } 14360b57cec5SDimitry Andric 14370b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 14380b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 14390b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 14400b57cec5SDimitry Andric 14410b57cec5SDimitry Andric // Handle /nodefaultlib 14420b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 14430b57cec5SDimitry Andric config->noDefaultLibAll = true; 14440b57cec5SDimitry Andric 14450b57cec5SDimitry Andric // Handle /base 14460b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 14470b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 14480b57cec5SDimitry Andric 14490b57cec5SDimitry Andric // Handle /filealign 14500b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 14510b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 14520b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 14530b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 14540b57cec5SDimitry Andric } 14550b57cec5SDimitry Andric 14560b57cec5SDimitry Andric // Handle /stack 14570b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 14580b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 14590b57cec5SDimitry Andric 14600b57cec5SDimitry Andric // Handle /guard:cf 14610b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 14620b57cec5SDimitry Andric parseGuard(arg->getValue()); 14630b57cec5SDimitry Andric 14640b57cec5SDimitry Andric // Handle /heap 14650b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 14660b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 14670b57cec5SDimitry Andric 14680b57cec5SDimitry Andric // Handle /version 14690b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 14700b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 14710b57cec5SDimitry Andric &config->minorImageVersion); 14720b57cec5SDimitry Andric 14730b57cec5SDimitry Andric // Handle /subsystem 14740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1475*e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1476*e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1477*e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1478*e8d8bef9SDimitry Andric 1479*e8d8bef9SDimitry Andric // Handle /osversion 1480*e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1481*e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 14820b57cec5SDimitry Andric &config->minorOSVersion); 1483*e8d8bef9SDimitry Andric } else { 1484*e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1485*e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1486*e8d8bef9SDimitry Andric } 14870b57cec5SDimitry Andric 14880b57cec5SDimitry Andric // Handle /timestamp 14890b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 14900b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 14910b57cec5SDimitry Andric config->timestamp = 0; 14920b57cec5SDimitry Andric config->repro = true; 14930b57cec5SDimitry Andric } else { 14940b57cec5SDimitry Andric config->repro = false; 14950b57cec5SDimitry Andric StringRef value(arg->getValue()); 14960b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 14970b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 14980b57cec5SDimitry Andric ". Expected 32-bit integer"); 14990b57cec5SDimitry Andric } 15000b57cec5SDimitry Andric } else { 15010b57cec5SDimitry Andric config->repro = false; 15020b57cec5SDimitry Andric config->timestamp = time(nullptr); 15030b57cec5SDimitry Andric } 15040b57cec5SDimitry Andric 15050b57cec5SDimitry Andric // Handle /alternatename 15060b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 15070b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 15080b57cec5SDimitry Andric 15090b57cec5SDimitry Andric // Handle /include 15100b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 15110b57cec5SDimitry Andric addUndefined(arg->getValue()); 15120b57cec5SDimitry Andric 15130b57cec5SDimitry Andric // Handle /implib 15140b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 15150b57cec5SDimitry Andric config->implib = arg->getValue(); 15160b57cec5SDimitry Andric 15170b57cec5SDimitry Andric // Handle /opt. 15180b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 15190b57cec5SDimitry Andric unsigned icfLevel = 15200b57cec5SDimitry Andric args.hasArg(OPT_profile) ? 0 : 1; // 0: off, 1: limited, 2: on 15210b57cec5SDimitry Andric unsigned tailMerge = 1; 1522*e8d8bef9SDimitry Andric bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1523*e8d8bef9SDimitry Andric bool ltoDebugPM = false; 15240b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 15250b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 15260b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 15270b57cec5SDimitry Andric StringRef(str).split(vec, ','); 15280b57cec5SDimitry Andric for (StringRef s : vec) { 15290b57cec5SDimitry Andric if (s == "ref") { 15300b57cec5SDimitry Andric doGC = true; 15310b57cec5SDimitry Andric } else if (s == "noref") { 15320b57cec5SDimitry Andric doGC = false; 15330b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 15340b57cec5SDimitry Andric icfLevel = 2; 15350b57cec5SDimitry Andric } else if (s == "noicf") { 15360b57cec5SDimitry Andric icfLevel = 0; 15370b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 15380b57cec5SDimitry Andric tailMerge = 2; 15390b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 15400b57cec5SDimitry Andric tailMerge = 0; 1541*e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 1542*e8d8bef9SDimitry Andric ltoNewPM = true; 1543*e8d8bef9SDimitry Andric } else if (s == "noltonewpassmanager") { 1544*e8d8bef9SDimitry Andric ltoNewPM = false; 1545*e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1546*e8d8bef9SDimitry Andric ltoDebugPM = true; 1547*e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1548*e8d8bef9SDimitry Andric ltoDebugPM = false; 15490b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 15500b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 15510b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 15520b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 15530b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 15540b57cec5SDimitry Andric StringRef jobs = s.substr(11); 15555ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 15560b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 15575ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 15580b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 15590b57cec5SDimitry Andric StringRef n = s.substr(17); 15600b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 15610b57cec5SDimitry Andric config->ltoPartitions == 0) 15620b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 15630b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 15640b57cec5SDimitry Andric error("/opt: unknown option: " + s); 15650b57cec5SDimitry Andric } 15660b57cec5SDimitry Andric } 15670b57cec5SDimitry Andric 15680b57cec5SDimitry Andric // Limited ICF is enabled if GC is enabled and ICF was never mentioned 15690b57cec5SDimitry Andric // explicitly. 15700b57cec5SDimitry Andric // FIXME: LLD only implements "limited" ICF, i.e. it only merges identical 15710b57cec5SDimitry Andric // code. If the user passes /OPT:ICF explicitly, LLD should merge identical 15720b57cec5SDimitry Andric // comdat readonly data. 15730b57cec5SDimitry Andric if (icfLevel == 1 && !doGC) 15740b57cec5SDimitry Andric icfLevel = 0; 15750b57cec5SDimitry Andric config->doGC = doGC; 15760b57cec5SDimitry Andric config->doICF = icfLevel > 0; 15770b57cec5SDimitry Andric config->tailMerge = (tailMerge == 1 && config->doICF) || tailMerge == 2; 1578*e8d8bef9SDimitry Andric config->ltoNewPassManager = ltoNewPM; 1579*e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 15800b57cec5SDimitry Andric 15810b57cec5SDimitry Andric // Handle /lldsavetemps 15820b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 15830b57cec5SDimitry Andric config->saveTemps = true; 15840b57cec5SDimitry Andric 15850b57cec5SDimitry Andric // Handle /kill-at 15860b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 15870b57cec5SDimitry Andric config->killAt = true; 15880b57cec5SDimitry Andric 15890b57cec5SDimitry Andric // Handle /lldltocache 15900b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 15910b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 15920b57cec5SDimitry Andric 15930b57cec5SDimitry Andric // Handle /lldsavecachepolicy 15940b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 15950b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 15960b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 15970b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 15980b57cec5SDimitry Andric 15990b57cec5SDimitry Andric // Handle /failifmismatch 16000b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 16010b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 16020b57cec5SDimitry Andric 16030b57cec5SDimitry Andric // Handle /merge 16040b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 16050b57cec5SDimitry Andric parseMerge(arg->getValue()); 16060b57cec5SDimitry Andric 16070b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 16080b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 16090b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 16100b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 16110b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 16120b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 16130b57cec5SDimitry Andric parseMerge(".bss=.data"); 16140b57cec5SDimitry Andric 16150b57cec5SDimitry Andric if (config->mingw) { 16160b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 16170b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 16180b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 16190b57cec5SDimitry Andric } 16200b57cec5SDimitry Andric 16210b57cec5SDimitry Andric // Handle /section 16220b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 16230b57cec5SDimitry Andric parseSection(arg->getValue()); 16240b57cec5SDimitry Andric 16250b57cec5SDimitry Andric // Handle /align 16260b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 16270b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 16280b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 16290b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1630480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1631480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 16320b57cec5SDimitry Andric } 16330b57cec5SDimitry Andric 16340b57cec5SDimitry Andric // Handle /aligncomm 16350b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 16360b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 16370b57cec5SDimitry Andric 16380b57cec5SDimitry Andric // Handle /manifestdependency. This enables /manifest unless /manifest:no is 16390b57cec5SDimitry Andric // also passed. 16400b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestdependency)) { 16410b57cec5SDimitry Andric config->manifestDependency = arg->getValue(); 16420b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 16430b57cec5SDimitry Andric } 16440b57cec5SDimitry Andric 16450b57cec5SDimitry Andric // Handle /manifest and /manifest: 16460b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 16470b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 16480b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 16490b57cec5SDimitry Andric else 16500b57cec5SDimitry Andric parseManifest(arg->getValue()); 16510b57cec5SDimitry Andric } 16520b57cec5SDimitry Andric 16530b57cec5SDimitry Andric // Handle /manifestuac 16540b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 16550b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 16560b57cec5SDimitry Andric 16570b57cec5SDimitry Andric // Handle /manifestfile 16580b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 16590b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 16600b57cec5SDimitry Andric 16610b57cec5SDimitry Andric // Handle /manifestinput 16620b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 16630b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 16640b57cec5SDimitry Andric 16650b57cec5SDimitry Andric if (!config->manifestInput.empty() && 16660b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 16670b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 16680b57cec5SDimitry Andric } 16690b57cec5SDimitry Andric 16700b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 16710b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 16720b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 16730b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 16740b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 16750b57cec5SDimitry Andric config->thinLTOPrefixReplace = 16760b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 16770b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 16780b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 167985868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 16800b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 16810b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 16820b57cec5SDimitry Andric config->allowIsolation = 16830b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 16840b57cec5SDimitry Andric config->incremental = 16850b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 16860b57cec5SDimitry Andric !config->doGC && !config->doICF && !args.hasArg(OPT_order) && 16870b57cec5SDimitry Andric !args.hasArg(OPT_profile)); 16880b57cec5SDimitry Andric config->integrityCheck = 16890b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 16905ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 16910b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 16920b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 16930b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 16940b57cec5SDimitry Andric config->terminalServerAware = 16950b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 16960b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 16970b57cec5SDimitry Andric config->debugGHashes = debug == DebugKind::GHash; 16980b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 16995ffd83dbSDimitry Andric config->autoImport = 17005ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 17015ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 17025ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1703*e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1704*e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 17050b57cec5SDimitry Andric 1706*e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1707*e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1708480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1709480093f4SDimitry Andric config->warnLongSectionNames = false; 1710480093f4SDimitry Andric 17115ffd83dbSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 17125ffd83dbSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 17135ffd83dbSDimitry Andric 17145ffd83dbSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 17155ffd83dbSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 17165ffd83dbSDimitry Andric "'.\n>>> ignoring /lldmap"); 17175ffd83dbSDimitry Andric config->lldmapFile.clear(); 17185ffd83dbSDimitry Andric } 17190b57cec5SDimitry Andric 17200b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 17210b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 17220b57cec5SDimitry Andric config->incremental = false; 17230b57cec5SDimitry Andric } 17240b57cec5SDimitry Andric 17250b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 17260b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 17270b57cec5SDimitry Andric config->incremental = false; 17280b57cec5SDimitry Andric } 17290b57cec5SDimitry Andric 17300b57cec5SDimitry Andric if (config->incremental && config->doGC) { 17310b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 17320b57cec5SDimitry Andric "disable"); 17330b57cec5SDimitry Andric config->incremental = false; 17340b57cec5SDimitry Andric } 17350b57cec5SDimitry Andric 17360b57cec5SDimitry Andric if (config->incremental && config->doICF) { 17370b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 17380b57cec5SDimitry Andric "disable"); 17390b57cec5SDimitry Andric config->incremental = false; 17400b57cec5SDimitry Andric } 17410b57cec5SDimitry Andric 17420b57cec5SDimitry Andric if (errorCount()) 17430b57cec5SDimitry Andric return; 17440b57cec5SDimitry Andric 17450b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 17460b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 17470b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 17480b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 17490b57cec5SDimitry Andric wholeArchives.insert(*id); 17500b57cec5SDimitry Andric 17510b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 17520b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 17530b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 17540b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 17550b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 17560b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 17570b57cec5SDimitry Andric return true; 17580b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 17590b57cec5SDimitry Andric return wholeArchives.count(*id); 17600b57cec5SDimitry Andric return false; 17610b57cec5SDimitry Andric }; 17620b57cec5SDimitry Andric 176385868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 176485868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 176585868e8aSDimitry Andric // and OPT_end_lib. 176685868e8aSDimitry Andric bool inLib = false; 176785868e8aSDimitry Andric for (auto *arg : args) { 176885868e8aSDimitry Andric switch (arg->getOption().getID()) { 176985868e8aSDimitry Andric case OPT_end_lib: 177085868e8aSDimitry Andric if (!inLib) 177185868e8aSDimitry Andric error("stray " + arg->getSpelling()); 177285868e8aSDimitry Andric inLib = false; 177385868e8aSDimitry Andric break; 177485868e8aSDimitry Andric case OPT_start_lib: 177585868e8aSDimitry Andric if (inLib) 177685868e8aSDimitry Andric error("nested " + arg->getSpelling()); 177785868e8aSDimitry Andric inLib = true; 177885868e8aSDimitry Andric break; 177985868e8aSDimitry Andric case OPT_wholearchive_file: 17800b57cec5SDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 178185868e8aSDimitry Andric enqueuePath(*path, true, inLib); 178285868e8aSDimitry Andric break; 178385868e8aSDimitry Andric case OPT_INPUT: 178485868e8aSDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 178585868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 178685868e8aSDimitry Andric break; 178785868e8aSDimitry Andric default: 178885868e8aSDimitry Andric // Ignore other options. 178985868e8aSDimitry Andric break; 179085868e8aSDimitry Andric } 179185868e8aSDimitry Andric } 17920b57cec5SDimitry Andric 179385868e8aSDimitry Andric // Process files specified as /defaultlib. These should be enequeued after 179485868e8aSDimitry Andric // other files, which is why they are in a separate loop. 17950b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 17960b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 179785868e8aSDimitry Andric enqueuePath(*path, false, false); 17980b57cec5SDimitry Andric 17990b57cec5SDimitry Andric // Windows specific -- Create a resource file containing a manifest file. 18000b57cec5SDimitry Andric if (config->manifest == Configuration::Embed) 180185868e8aSDimitry Andric addBuffer(createManifestRes(), false, false); 18020b57cec5SDimitry Andric 18030b57cec5SDimitry Andric // Read all input files given via the command line. 18040b57cec5SDimitry Andric run(); 18050b57cec5SDimitry Andric 18060b57cec5SDimitry Andric if (errorCount()) 18070b57cec5SDimitry Andric return; 18080b57cec5SDimitry Andric 18090b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 18100b57cec5SDimitry Andric // not we assume x64. 18110b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 18120b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 18130b57cec5SDimitry Andric config->machine = AMD64; 18140b57cec5SDimitry Andric } 18150b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 18160b57cec5SDimitry Andric 18170b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 1818979e22ffSDimitry Andric if (config->machine == I386) { 1819979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1820979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 1821979e22ffSDimitry Andric } 18220b57cec5SDimitry Andric 18230b57cec5SDimitry Andric // Handle /functionpadmin 18240b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 18250b57cec5SDimitry Andric parseFunctionPadMin(arg, config->machine); 18260b57cec5SDimitry Andric 18270b57cec5SDimitry Andric if (tar) 18280b57cec5SDimitry Andric tar->append("response.txt", 18290b57cec5SDimitry Andric createResponseFile(args, filePaths, 18300b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 18310b57cec5SDimitry Andric 18320b57cec5SDimitry Andric // Handle /largeaddressaware 18330b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 18340b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 18350b57cec5SDimitry Andric 18360b57cec5SDimitry Andric // Handle /highentropyva 18370b57cec5SDimitry Andric config->highEntropyVA = 18380b57cec5SDimitry Andric config->is64() && 18390b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 18400b57cec5SDimitry Andric 18410b57cec5SDimitry Andric if (!config->dynamicBase && 18420b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 18430b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 18440b57cec5SDimitry Andric machineToStr(config->machine)); 18450b57cec5SDimitry Andric 18460b57cec5SDimitry Andric // Handle /export 18470b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 18480b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 18490b57cec5SDimitry Andric if (config->machine == I386) { 18500b57cec5SDimitry Andric if (!isDecorated(e.name)) 18510b57cec5SDimitry Andric e.name = saver.save("_" + e.name); 18520b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 18530b57cec5SDimitry Andric e.extName = saver.save("_" + e.extName); 18540b57cec5SDimitry Andric } 18550b57cec5SDimitry Andric config->exports.push_back(e); 18560b57cec5SDimitry Andric } 18570b57cec5SDimitry Andric 18580b57cec5SDimitry Andric // Handle /def 18590b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 18600b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 18610b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 18620b57cec5SDimitry Andric } 18630b57cec5SDimitry Andric 18640b57cec5SDimitry Andric // Handle generation of import library from a def file. 1865480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 18660b57cec5SDimitry Andric fixupExports(); 18670b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 18680b57cec5SDimitry Andric return; 18690b57cec5SDimitry Andric } 18700b57cec5SDimitry Andric 18710b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 18720b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 18730b57cec5SDimitry Andric // and after the early return when just writing an import library. 18740b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 18750b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 18760b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 18770b57cec5SDimitry Andric fatal("subsystem must be defined"); 18780b57cec5SDimitry Andric } 18790b57cec5SDimitry Andric 18800b57cec5SDimitry Andric // Handle /entry and /dll 18810b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 18820b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 18830b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 18840b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 18850b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 18860b57cec5SDimitry Andric : "_DllMainCRTStartup"; 18870b57cec5SDimitry Andric config->entry = addUndefined(s); 1888480093f4SDimitry Andric } else if (config->driverWdm) { 1889480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 1890480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 18910b57cec5SDimitry Andric } else { 18920b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 18930b57cec5SDimitry Andric // infer that from user-defined entry name. 18940b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 18950b57cec5SDimitry Andric if (s.empty()) 18960b57cec5SDimitry Andric fatal("entry point must be defined"); 18970b57cec5SDimitry Andric config->entry = addUndefined(s); 18980b57cec5SDimitry Andric log("Entry name inferred: " + s); 18990b57cec5SDimitry Andric } 19000b57cec5SDimitry Andric } 19010b57cec5SDimitry Andric 19020b57cec5SDimitry Andric // Handle /delayload 19030b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 19040b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 19050b57cec5SDimitry Andric if (config->machine == I386) { 19060b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 19070b57cec5SDimitry Andric } else { 19080b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 19090b57cec5SDimitry Andric } 19100b57cec5SDimitry Andric } 19110b57cec5SDimitry Andric 19120b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 19130b57cec5SDimitry Andric if (config->outputFile.empty()) { 1914480093f4SDimitry Andric config->outputFile = getOutputPath( 1915480093f4SDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 19160b57cec5SDimitry Andric } 19170b57cec5SDimitry Andric 19180b57cec5SDimitry Andric // Fail early if an output file is not writable. 19190b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 19200b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 19210b57cec5SDimitry Andric return; 19220b57cec5SDimitry Andric } 19230b57cec5SDimitry Andric 19240b57cec5SDimitry Andric if (shouldCreatePDB) { 19250b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 19260b57cec5SDimitry Andric if (config->pdbPath.empty()) { 19270b57cec5SDimitry Andric config->pdbPath = config->outputFile; 19280b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 19290b57cec5SDimitry Andric } 19300b57cec5SDimitry Andric 19310b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 19320b57cec5SDimitry Andric // /pdbaltpath flag was passed. 19330b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 19340b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 19350b57cec5SDimitry Andric 19360b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 19370b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 19380b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 19390b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 19400b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 19410b57cec5SDimitry Andric } else { 19420b57cec5SDimitry Andric // Don't do this earlier, so that Config->OutputFile is ready. 19430b57cec5SDimitry Andric parsePDBAltPath(config->pdbAltPath); 19440b57cec5SDimitry Andric } 19450b57cec5SDimitry Andric } 19460b57cec5SDimitry Andric 19470b57cec5SDimitry Andric // Set default image base if /base is not given. 19480b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 19490b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 19500b57cec5SDimitry Andric 19510b57cec5SDimitry Andric symtab->addSynthetic(mangle("__ImageBase"), nullptr); 19520b57cec5SDimitry Andric if (config->machine == I386) { 19530b57cec5SDimitry Andric symtab->addAbsolute("___safe_se_handler_table", 0); 19540b57cec5SDimitry Andric symtab->addAbsolute("___safe_se_handler_count", 0); 19550b57cec5SDimitry Andric } 19560b57cec5SDimitry Andric 19570b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_fids_count"), 0); 19580b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_fids_table"), 0); 19590b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_flags"), 0); 19600b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_iat_count"), 0); 19610b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_iat_table"), 0); 19620b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 19630b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 19640b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 19650b57cec5SDimitry Andric symtab->addAbsolute(mangle("__enclave_config"), 0); 19660b57cec5SDimitry Andric 19675ffd83dbSDimitry Andric if (config->pseudoRelocs) { 19680b57cec5SDimitry Andric symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 19690b57cec5SDimitry Andric symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 19705ffd83dbSDimitry Andric } 19715ffd83dbSDimitry Andric if (config->mingw) { 19720b57cec5SDimitry Andric symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); 19730b57cec5SDimitry Andric symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); 19740b57cec5SDimitry Andric } 19750b57cec5SDimitry Andric 19760b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 19770b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 19780b57cec5SDimitry Andric // converge. 19790b57cec5SDimitry Andric do { 19800b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 19810b57cec5SDimitry Andric // search for its mangled names. 19820b57cec5SDimitry Andric if (config->entry) 19830b57cec5SDimitry Andric mangleMaybe(config->entry); 19840b57cec5SDimitry Andric 19850b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 19860b57cec5SDimitry Andric for (Export &e : config->exports) { 19870b57cec5SDimitry Andric if (!e.forwardTo.empty()) 19880b57cec5SDimitry Andric continue; 19890b57cec5SDimitry Andric e.sym = addUndefined(e.name); 19900b57cec5SDimitry Andric if (!e.directives) 19910b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 19920b57cec5SDimitry Andric } 19930b57cec5SDimitry Andric 19940b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 19950b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 19960b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 19970b57cec5SDimitry Andric StringRef from = pair.first; 19980b57cec5SDimitry Andric StringRef to = pair.second; 19990b57cec5SDimitry Andric Symbol *sym = symtab->find(from); 20000b57cec5SDimitry Andric if (!sym) 20010b57cec5SDimitry Andric continue; 20020b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 20030b57cec5SDimitry Andric if (!u->weakAlias) 20040b57cec5SDimitry Andric u->weakAlias = symtab->addUndefined(to); 20050b57cec5SDimitry Andric } 20060b57cec5SDimitry Andric 20070b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 20080b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 20090b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 20100b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 20110b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 20120b57cec5SDimitry Andric if (!BitcodeFile::instances.empty()) 201385868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 20140b57cec5SDimitry Andric symtab->addLibcall(s); 20150b57cec5SDimitry Andric 20160b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 20170b57cec5SDimitry Andric if (symtab->findUnderscore("_load_config_used")) 20180b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 20190b57cec5SDimitry Andric } while (run()); 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 20220b57cec5SDimitry Andric // Handle /includeoptional 20230b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 202485868e8aSDimitry Andric if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue()))) 20250b57cec5SDimitry Andric addUndefined(arg->getValue()); 20260b57cec5SDimitry Andric while (run()); 20270b57cec5SDimitry Andric } 20280b57cec5SDimitry Andric 2029*e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2030*e8d8bef9SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2031*e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2032*e8d8bef9SDimitry Andric if (!wrapped.empty()) 2033*e8d8bef9SDimitry Andric while (run()); 2034*e8d8bef9SDimitry Andric 20355ffd83dbSDimitry Andric if (config->autoImport) { 20365ffd83dbSDimitry Andric // MinGW specific. 20370b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 20380b57cec5SDimitry Andric // imports. 20390b57cec5SDimitry Andric // 20400b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 20410b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 20420b57cec5SDimitry Andric // 20430b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 20440b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 20450b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 20460b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 20470b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 20480b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 20490b57cec5SDimitry Andric // we won't iterate further to resolve them. 20500b57cec5SDimitry Andric symtab->loadMinGWAutomaticImports(); 20510b57cec5SDimitry Andric run(); 20520b57cec5SDimitry Andric } 20530b57cec5SDimitry Andric 205485868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 205585868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 205685868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 205785868e8aSDimitry Andric // will fail to link anyway. 205885868e8aSDimitry Andric if (!BitcodeFile::instances.empty() && !config->forceUnresolved) 205985868e8aSDimitry Andric symtab->reportUnresolvable(); 20600b57cec5SDimitry Andric if (errorCount()) 20610b57cec5SDimitry Andric return; 20620b57cec5SDimitry Andric 206385868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 206485868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 206585868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 206685868e8aSDimitry Andric symtab->addCombinedLTOObjects(); 206785868e8aSDimitry Andric 206885868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 206985868e8aSDimitry Andric // files" and not object files. Index file creation is already done 207085868e8aSDimitry Andric // in addCombinedLTOObject, so we are done if that's the case. 207185868e8aSDimitry Andric if (config->thinLTOIndexOnly) 207285868e8aSDimitry Andric return; 207385868e8aSDimitry Andric 207485868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 207585868e8aSDimitry Andric // references to the symbols we use from them. 207685868e8aSDimitry Andric run(); 207785868e8aSDimitry Andric 2078*e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2079*e8d8bef9SDimitry Andric if (!wrapped.empty()) 2080*e8d8bef9SDimitry Andric wrapSymbols(wrapped); 2081*e8d8bef9SDimitry Andric 208285868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 208385868e8aSDimitry Andric symtab->resolveRemainingUndefines(); 208485868e8aSDimitry Andric if (errorCount()) 208585868e8aSDimitry Andric return; 208685868e8aSDimitry Andric 208785868e8aSDimitry Andric config->hadExplicitExports = !config->exports.empty(); 20880b57cec5SDimitry Andric if (config->mingw) { 20890b57cec5SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 20900b57cec5SDimitry Andric // are chosen to be exported. 20910b57cec5SDimitry Andric maybeExportMinGWSymbols(args); 20920b57cec5SDimitry Andric 20930b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 20940b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 20950b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 20960b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 20970b57cec5SDimitry Andric // files from static libraries only after the last object file on the 20980b57cec5SDimitry Andric // command line. 20990b57cec5SDimitry Andric for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end(); 21000b57cec5SDimitry Andric i != e; i++) { 21010b57cec5SDimitry Andric ObjFile *file = *i; 21020b57cec5SDimitry Andric if (isCrtend(file->getName())) { 21030b57cec5SDimitry Andric ObjFile::instances.erase(i); 21040b57cec5SDimitry Andric ObjFile::instances.push_back(file); 21050b57cec5SDimitry Andric break; 21060b57cec5SDimitry Andric } 21070b57cec5SDimitry Andric } 21080b57cec5SDimitry Andric } 21090b57cec5SDimitry Andric 21100b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 211185868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 211285868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 21130b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 21140b57cec5SDimitry Andric fixupExports(); 211585868e8aSDimitry Andric if (!config->mingw || !config->implib.empty()) 21160b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 21170b57cec5SDimitry Andric assignExportOrdinals(); 21180b57cec5SDimitry Andric } 21190b57cec5SDimitry Andric 21200b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 21210b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 21220b57cec5SDimitry Andric writeDefFile(arg->getValue()); 21230b57cec5SDimitry Andric 21240b57cec5SDimitry Andric // Set extra alignment for .comm symbols 21250b57cec5SDimitry Andric for (auto pair : config->alignComm) { 21260b57cec5SDimitry Andric StringRef name = pair.first; 21270b57cec5SDimitry Andric uint32_t alignment = pair.second; 21280b57cec5SDimitry Andric 21290b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 21300b57cec5SDimitry Andric if (!sym) { 21310b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 21320b57cec5SDimitry Andric continue; 21330b57cec5SDimitry Andric } 21340b57cec5SDimitry Andric 21350b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 21360b57cec5SDimitry Andric // symbol, which will carry its own alignment. 21370b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 21380b57cec5SDimitry Andric if (!dc) 21390b57cec5SDimitry Andric continue; 21400b57cec5SDimitry Andric 21410b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 21420b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 21430b57cec5SDimitry Andric } 21440b57cec5SDimitry Andric 21450b57cec5SDimitry Andric // Windows specific -- Create a side-by-side manifest file. 21460b57cec5SDimitry Andric if (config->manifest == Configuration::SideBySide) 21470b57cec5SDimitry Andric createSideBySideManifest(); 21480b57cec5SDimitry Andric 21490b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 21500b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 21510b57cec5SDimitry Andric // functions. 2152*e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2153*e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2154*e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 21550b57cec5SDimitry Andric parseOrderFile(arg->getValue()); 2156*e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2157*e8d8bef9SDimitry Andric } 2158*e8d8bef9SDimitry Andric 2159*e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2160*e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2161*e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2162*e8d8bef9SDimitry Andric parseCallGraphFile(arg->getValue()); 2163*e8d8bef9SDimitry Andric } 2164*e8d8bef9SDimitry Andric readCallGraphsFromObjectFiles(); 2165*e8d8bef9SDimitry Andric } 2166*e8d8bef9SDimitry Andric 2167*e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2168*e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2169*e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 21700b57cec5SDimitry Andric 21710b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 21720b57cec5SDimitry Andric if (config->doGC) 21730b57cec5SDimitry Andric markLive(symtab->getChunks()); 21740b57cec5SDimitry Andric 21750b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 217685868e8aSDimitry Andric convertResources(); 21770b57cec5SDimitry Andric 21780b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 21790b57cec5SDimitry Andric if (config->doICF) { 21800b57cec5SDimitry Andric findKeepUniqueSections(); 21810b57cec5SDimitry Andric doICF(symtab->getChunks()); 21820b57cec5SDimitry Andric } 21830b57cec5SDimitry Andric 21840b57cec5SDimitry Andric // Write the result. 21850b57cec5SDimitry Andric writeResult(); 21860b57cec5SDimitry Andric 21870b57cec5SDimitry Andric // Stop early so we can print the results. 21885ffd83dbSDimitry Andric rootTimer.stop(); 21890b57cec5SDimitry Andric if (config->showTiming) 21900b57cec5SDimitry Andric Timer::root().print(); 21910b57cec5SDimitry Andric } 21920b57cec5SDimitry Andric 21930b57cec5SDimitry Andric } // namespace coff 21940b57cec5SDimitry Andric } // namespace lld 2195