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" 29e8d8bef9SDimitry 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" 38e8d8bef9SDimitry 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; 57*fe6060f1SDimitry Andric using namespace llvm::sys; 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 72e8d8bef9SDimitry Andric errorHandler().cleanupCallback = []() { 73e8d8bef9SDimitry Andric TpiSource::clear(); 74e8d8bef9SDimitry Andric freeArena(); 75e8d8bef9SDimitry Andric ObjFile::instances.clear(); 76e8d8bef9SDimitry Andric PDBInputFile::instances.clear(); 77e8d8bef9SDimitry Andric ImportFile::instances.clear(); 78e8d8bef9SDimitry Andric BitcodeFile::instances.clear(); 79e8d8bef9SDimitry Andric memset(MergeChunk::instances, 0, sizeof(MergeChunk::instances)); 80e8d8bef9SDimitry Andric OutputSection::clear(); 81e8d8bef9SDimitry Andric }; 82e8d8bef9SDimitry 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 94e8d8bef9SDimitry 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 100e8d8bef9SDimitry Andric bool ret = errorCount() == 0; 101e8d8bef9SDimitry Andric if (!canExitEarly) 102e8d8bef9SDimitry Andric errorHandler().reset(); 103e8d8bef9SDimitry 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) { 152*fe6060f1SDimitry Andric #if _WIN64 1530b57cec5SDimitry Andric // On Windows, file I/O is relatively slow so it is best to do this 154*fe6060f1SDimitry Andric // asynchronously. But 32-bit has issues with potentially launching tons 155*fe6060f1SDimitry Andric // of threads 1560b57cec5SDimitry Andric auto strategy = std::launch::async; 1570b57cec5SDimitry Andric #else 1580b57cec5SDimitry Andric auto strategy = std::launch::deferred; 1590b57cec5SDimitry Andric #endif 1600b57cec5SDimitry Andric return std::async(strategy, [=]() { 161*fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 162*fe6060f1SDimitry 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: 238*fe6060f1SDimitry Andric if (config->mingw) { 239*fe6060f1SDimitry Andric symtab->addFile(make<DLLFile>(mbref)); 240*fe6060f1SDimitry Andric break; 241*fe6060f1SDimitry Andric } 242*fe6060f1SDimitry Andric if (filename.endswith_insensitive(".dll")) { 2430b57cec5SDimitry Andric error(filename + ": bad file type. Did you specify a DLL instead of an " 2440b57cec5SDimitry Andric "import library?"); 2450b57cec5SDimitry Andric break; 2460b57cec5SDimitry Andric } 2470b57cec5SDimitry Andric LLVM_FALLTHROUGH; 2480b57cec5SDimitry Andric default: 2490b57cec5SDimitry Andric error(mbref.getBufferIdentifier() + ": unknown file type"); 2500b57cec5SDimitry Andric break; 2510b57cec5SDimitry Andric } 2520b57cec5SDimitry Andric } 2530b57cec5SDimitry Andric 25485868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 2555ffd83dbSDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 2565ffd83dbSDimitry Andric createFutureForFile(std::string(path))); 2575ffd83dbSDimitry Andric std::string pathStr = std::string(path); 2580b57cec5SDimitry Andric enqueueTask([=]() { 2590b57cec5SDimitry Andric auto mbOrErr = future->get(); 2600b57cec5SDimitry Andric if (mbOrErr.second) { 2610b57cec5SDimitry Andric std::string msg = 2620b57cec5SDimitry Andric "could not open '" + pathStr + "': " + mbOrErr.second.message(); 2630b57cec5SDimitry Andric // Check if the filename is a typo for an option flag. OptTable thinks 2640b57cec5SDimitry Andric // that all args that are not known options and that start with / are 2650b57cec5SDimitry Andric // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 2660b57cec5SDimitry Andric // the option `/nodefaultlib` than a reference to a file in the root 2670b57cec5SDimitry Andric // directory. 2680b57cec5SDimitry Andric std::string nearest; 2695ffd83dbSDimitry Andric if (optTable.findNearest(pathStr, nearest) > 1) 2700b57cec5SDimitry Andric error(msg); 2710b57cec5SDimitry Andric else 2720b57cec5SDimitry Andric error(msg + "; did you mean '" + nearest + "'"); 2730b57cec5SDimitry Andric } else 27485868e8aSDimitry Andric driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 2750b57cec5SDimitry Andric }); 2760b57cec5SDimitry Andric } 2770b57cec5SDimitry Andric 2780b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 2790b57cec5SDimitry Andric StringRef parentName, 2800b57cec5SDimitry Andric uint64_t offsetInArchive) { 2810b57cec5SDimitry Andric file_magic magic = identify_magic(mb.getBuffer()); 2820b57cec5SDimitry Andric if (magic == file_magic::coff_import_library) { 2830b57cec5SDimitry Andric InputFile *imp = make<ImportFile>(mb); 2840b57cec5SDimitry Andric imp->parentName = parentName; 2850b57cec5SDimitry Andric symtab->addFile(imp); 2860b57cec5SDimitry Andric return; 2870b57cec5SDimitry Andric } 2880b57cec5SDimitry Andric 2890b57cec5SDimitry Andric InputFile *obj; 2900b57cec5SDimitry Andric if (magic == file_magic::coff_object) { 2910b57cec5SDimitry Andric obj = make<ObjFile>(mb); 2920b57cec5SDimitry Andric } else if (magic == file_magic::bitcode) { 2930b57cec5SDimitry Andric obj = make<BitcodeFile>(mb, parentName, offsetInArchive); 2940b57cec5SDimitry Andric } else { 2950b57cec5SDimitry Andric error("unknown file type: " + mb.getBufferIdentifier()); 2960b57cec5SDimitry Andric return; 2970b57cec5SDimitry Andric } 2980b57cec5SDimitry Andric 2990b57cec5SDimitry Andric obj->parentName = parentName; 3000b57cec5SDimitry Andric symtab->addFile(obj); 3010b57cec5SDimitry Andric log("Loaded " + toString(obj) + " for " + symName); 3020b57cec5SDimitry Andric } 3030b57cec5SDimitry Andric 3040b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 3050b57cec5SDimitry Andric const Archive::Symbol &sym, 3060b57cec5SDimitry Andric StringRef parentName) { 3070b57cec5SDimitry Andric 3080b57cec5SDimitry Andric auto reportBufferError = [=](Error &&e, StringRef childName) { 3090b57cec5SDimitry Andric fatal("could not get the buffer for the member defining symbol " + 3100b57cec5SDimitry Andric toCOFFString(sym) + ": " + parentName + "(" + childName + "): " + 3110b57cec5SDimitry Andric toString(std::move(e))); 3120b57cec5SDimitry Andric }; 3130b57cec5SDimitry Andric 3140b57cec5SDimitry Andric if (!c.getParent()->isThin()) { 3150b57cec5SDimitry Andric uint64_t offsetInArchive = c.getChildOffset(); 3160b57cec5SDimitry Andric Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 3170b57cec5SDimitry Andric if (!mbOrErr) 3180b57cec5SDimitry Andric reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 3190b57cec5SDimitry Andric MemoryBufferRef mb = mbOrErr.get(); 3200b57cec5SDimitry Andric enqueueTask([=]() { 3210b57cec5SDimitry Andric driver->addArchiveBuffer(mb, toCOFFString(sym), parentName, 3220b57cec5SDimitry Andric offsetInArchive); 3230b57cec5SDimitry Andric }); 3240b57cec5SDimitry Andric return; 3250b57cec5SDimitry Andric } 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric std::string childName = CHECK( 3280b57cec5SDimitry Andric c.getFullName(), 3290b57cec5SDimitry Andric "could not get the filename for the member defining symbol " + 3300b57cec5SDimitry Andric toCOFFString(sym)); 3310b57cec5SDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 3320b57cec5SDimitry Andric createFutureForFile(childName)); 3330b57cec5SDimitry Andric enqueueTask([=]() { 3340b57cec5SDimitry Andric auto mbOrErr = future->get(); 3350b57cec5SDimitry Andric if (mbOrErr.second) 3360b57cec5SDimitry Andric reportBufferError(errorCodeToError(mbOrErr.second), childName); 33785868e8aSDimitry Andric // Pass empty string as archive name so that the original filename is 33885868e8aSDimitry Andric // used as the buffer identifier. 3390b57cec5SDimitry Andric driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 34085868e8aSDimitry Andric toCOFFString(sym), "", /*OffsetInArchive=*/0); 3410b57cec5SDimitry Andric }); 3420b57cec5SDimitry Andric } 3430b57cec5SDimitry Andric 3440b57cec5SDimitry Andric static bool isDecorated(StringRef sym) { 3450b57cec5SDimitry Andric return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 3460b57cec5SDimitry Andric (!config->mingw && sym.contains('@')); 3470b57cec5SDimitry Andric } 3480b57cec5SDimitry Andric 3490b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files 3500b57cec5SDimitry Andric // specified by /defaultlib. 3510b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) { 3520b57cec5SDimitry Andric StringRef s = file->getDirectives(); 3530b57cec5SDimitry Andric if (s.empty()) 3540b57cec5SDimitry Andric return; 3550b57cec5SDimitry Andric 3560b57cec5SDimitry Andric log("Directives: " + toString(file) + ": " + s); 3570b57cec5SDimitry Andric 3580b57cec5SDimitry Andric ArgParser parser; 3590b57cec5SDimitry Andric // .drectve is always tokenized using Windows shell rules. 3600b57cec5SDimitry Andric // /EXPORT: option can appear too many times, processing in fastpath. 3615ffd83dbSDimitry Andric ParsedDirectives directives = parser.parseDirectives(s); 3620b57cec5SDimitry Andric 3635ffd83dbSDimitry Andric for (StringRef e : directives.exports) { 3640b57cec5SDimitry Andric // If a common header file contains dllexported function 3650b57cec5SDimitry Andric // declarations, many object files may end up with having the 3660b57cec5SDimitry Andric // same /EXPORT options. In order to save cost of parsing them, 3670b57cec5SDimitry Andric // we dedup them first. 3680b57cec5SDimitry Andric if (!directivesExports.insert(e).second) 3690b57cec5SDimitry Andric continue; 3700b57cec5SDimitry Andric 3710b57cec5SDimitry Andric Export exp = parseExport(e); 3720b57cec5SDimitry Andric if (config->machine == I386 && config->mingw) { 3730b57cec5SDimitry Andric if (!isDecorated(exp.name)) 3740b57cec5SDimitry Andric exp.name = saver.save("_" + exp.name); 3750b57cec5SDimitry Andric if (!exp.extName.empty() && !isDecorated(exp.extName)) 3760b57cec5SDimitry Andric exp.extName = saver.save("_" + exp.extName); 3770b57cec5SDimitry Andric } 3780b57cec5SDimitry Andric exp.directives = true; 3790b57cec5SDimitry Andric config->exports.push_back(exp); 3800b57cec5SDimitry Andric } 3810b57cec5SDimitry Andric 3825ffd83dbSDimitry Andric // Handle /include: in bulk. 3835ffd83dbSDimitry Andric for (StringRef inc : directives.includes) 3845ffd83dbSDimitry Andric addUndefined(inc); 3855ffd83dbSDimitry Andric 3865ffd83dbSDimitry Andric for (auto *arg : directives.args) { 3870b57cec5SDimitry Andric switch (arg->getOption().getID()) { 3880b57cec5SDimitry Andric case OPT_aligncomm: 3890b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 3900b57cec5SDimitry Andric break; 3910b57cec5SDimitry Andric case OPT_alternatename: 3920b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 3930b57cec5SDimitry Andric break; 3940b57cec5SDimitry Andric case OPT_defaultlib: 3950b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 39685868e8aSDimitry Andric enqueuePath(*path, false, false); 3970b57cec5SDimitry Andric break; 3980b57cec5SDimitry Andric case OPT_entry: 3990b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 4000b57cec5SDimitry Andric break; 4010b57cec5SDimitry Andric case OPT_failifmismatch: 4020b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), file); 4030b57cec5SDimitry Andric break; 4040b57cec5SDimitry Andric case OPT_incl: 4050b57cec5SDimitry Andric addUndefined(arg->getValue()); 4060b57cec5SDimitry Andric break; 4070b57cec5SDimitry Andric case OPT_merge: 4080b57cec5SDimitry Andric parseMerge(arg->getValue()); 4090b57cec5SDimitry Andric break; 4100b57cec5SDimitry Andric case OPT_nodefaultlib: 4110b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 4120b57cec5SDimitry Andric break; 4130b57cec5SDimitry Andric case OPT_section: 4140b57cec5SDimitry Andric parseSection(arg->getValue()); 4150b57cec5SDimitry Andric break; 416*fe6060f1SDimitry Andric case OPT_stack: 417*fe6060f1SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, 418*fe6060f1SDimitry Andric &config->stackCommit); 419*fe6060f1SDimitry Andric break; 420e8d8bef9SDimitry Andric case OPT_subsystem: { 421e8d8bef9SDimitry Andric bool gotVersion = false; 4220b57cec5SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 423e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 424e8d8bef9SDimitry Andric &config->minorSubsystemVersion, &gotVersion); 425e8d8bef9SDimitry Andric if (gotVersion) { 426e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 427e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 428e8d8bef9SDimitry Andric } 4290b57cec5SDimitry Andric break; 430e8d8bef9SDimitry Andric } 4310b57cec5SDimitry Andric // Only add flags here that link.exe accepts in 4320b57cec5SDimitry Andric // `#pragma comment(linker, "/flag")`-generated sections. 4330b57cec5SDimitry Andric case OPT_editandcontinue: 4340b57cec5SDimitry Andric case OPT_guardsym: 4350b57cec5SDimitry Andric case OPT_throwingnew: 4360b57cec5SDimitry Andric break; 4370b57cec5SDimitry Andric default: 4380b57cec5SDimitry Andric error(arg->getSpelling() + " is not allowed in .drectve"); 4390b57cec5SDimitry Andric } 4400b57cec5SDimitry Andric } 4410b57cec5SDimitry Andric } 4420b57cec5SDimitry Andric 4430b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes 4440b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist. 4450b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) { 4460b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4470b57cec5SDimitry Andric if (hasPathSep) 4480b57cec5SDimitry Andric return filename; 4490b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4500b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4510b57cec5SDimitry Andric SmallString<128> path = dir; 4520b57cec5SDimitry Andric sys::path::append(path, filename); 4530b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 4540b57cec5SDimitry Andric return saver.save(path.str()); 4550b57cec5SDimitry Andric if (!hasExt) { 4560b57cec5SDimitry Andric path.append(".obj"); 4570b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 4580b57cec5SDimitry Andric return saver.save(path.str()); 4590b57cec5SDimitry Andric } 4600b57cec5SDimitry Andric } 4610b57cec5SDimitry Andric return filename; 4620b57cec5SDimitry Andric } 4630b57cec5SDimitry Andric 4640b57cec5SDimitry Andric static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4650b57cec5SDimitry Andric sys::fs::UniqueID ret; 4660b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 4670b57cec5SDimitry Andric return None; 4680b57cec5SDimitry Andric return ret; 4690b57cec5SDimitry Andric } 4700b57cec5SDimitry Andric 4710b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 4720b57cec5SDimitry Andric // (in that case, it returns None). 4730b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4740b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4750b57cec5SDimitry Andric 4760b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4770b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4780b57cec5SDimitry Andric if (seen) 4790b57cec5SDimitry Andric return None; 4800b57cec5SDimitry Andric } 4810b57cec5SDimitry Andric 482*fe6060f1SDimitry Andric if (path.endswith_insensitive(".lib")) 4835ffd83dbSDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path))); 4840b57cec5SDimitry Andric return path; 4850b57cec5SDimitry Andric } 4860b57cec5SDimitry Andric 4870b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 4880b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 4890b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 4900b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 4910b57cec5SDimitry Andric return filename; 4920b57cec5SDimitry Andric 4930b57cec5SDimitry Andric SmallString<128> s = filename; 4940b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 4950b57cec5SDimitry Andric StringRef libName = saver.save("lib" + s.str()); 4960b57cec5SDimitry Andric return doFindFile(libName); 4970b57cec5SDimitry Andric } 4980b57cec5SDimitry Andric 4990b57cec5SDimitry Andric // Find library file from search path. 5000b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 5010b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 5020b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 5030b57cec5SDimitry Andric if (!hasExt) 5040b57cec5SDimitry Andric filename = saver.save(filename + ".lib"); 5050b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 5060b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 5070b57cec5SDimitry Andric // looking for a MinGW formatted library name. 5080b57cec5SDimitry Andric if (config->mingw && ret == filename) 5090b57cec5SDimitry Andric return doFindLibMinGW(filename); 5100b57cec5SDimitry Andric return ret; 5110b57cec5SDimitry Andric } 5120b57cec5SDimitry Andric 5130b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 5140b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 5150b57cec5SDimitry Andric // it returns None). 5160b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 5170b57cec5SDimitry Andric if (config->noDefaultLibAll) 5180b57cec5SDimitry Andric return None; 5190b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 5200b57cec5SDimitry Andric return None; 5210b57cec5SDimitry Andric 5220b57cec5SDimitry Andric StringRef path = doFindLib(filename); 5230b57cec5SDimitry Andric if (config->noDefaultLibs.count(path.lower())) 5240b57cec5SDimitry Andric return None; 5250b57cec5SDimitry Andric 5260b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 5270b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 5280b57cec5SDimitry Andric return None; 5290b57cec5SDimitry Andric return path; 5300b57cec5SDimitry Andric } 5310b57cec5SDimitry Andric 5320b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 5330b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 5340b57cec5SDimitry Andric Optional<std::string> envOpt = Process::GetEnv("LIB"); 5350b57cec5SDimitry Andric if (!envOpt.hasValue()) 5360b57cec5SDimitry Andric return; 5370b57cec5SDimitry Andric StringRef env = saver.save(*envOpt); 5380b57cec5SDimitry Andric while (!env.empty()) { 5390b57cec5SDimitry Andric StringRef path; 5400b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 5410b57cec5SDimitry Andric searchPaths.push_back(path); 5420b57cec5SDimitry Andric } 5430b57cec5SDimitry Andric } 5440b57cec5SDimitry Andric 5450b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 5460b57cec5SDimitry Andric Symbol *b = symtab->addUndefined(name); 5470b57cec5SDimitry Andric if (!b->isGCRoot) { 5480b57cec5SDimitry Andric b->isGCRoot = true; 5490b57cec5SDimitry Andric config->gcroot.push_back(b); 5500b57cec5SDimitry Andric } 5510b57cec5SDimitry Andric return b; 5520b57cec5SDimitry Andric } 5530b57cec5SDimitry Andric 5540b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 5550b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 5560b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 5570b57cec5SDimitry Andric if (!unmangled) 5580b57cec5SDimitry Andric return ""; 5590b57cec5SDimitry Andric 5600b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 5610b57cec5SDimitry Andric Symbol *mangled = symtab->findMangle(unmangled->getName()); 5620b57cec5SDimitry Andric if (!mangled) 5630b57cec5SDimitry Andric return ""; 5640b57cec5SDimitry Andric 5650b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 5660b57cec5SDimitry Andric // its name. 5670b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 5680b57cec5SDimitry Andric unmangled->weakAlias = symtab->addUndefined(mangled->getName()); 5690b57cec5SDimitry Andric return mangled->getName(); 5700b57cec5SDimitry Andric } 5710b57cec5SDimitry Andric 5720b57cec5SDimitry Andric // Windows specific -- find default entry point name. 5730b57cec5SDimitry Andric // 5740b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 5750b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 5760b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 5770b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 5780b57cec5SDimitry Andric assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 5790b57cec5SDimitry Andric "must handle /subsystem before calling this"); 5800b57cec5SDimitry Andric 5810b57cec5SDimitry Andric if (config->mingw) 5820b57cec5SDimitry Andric return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 5830b57cec5SDimitry Andric ? "WinMainCRTStartup" 5840b57cec5SDimitry Andric : "mainCRTStartup"); 5850b57cec5SDimitry Andric 5860b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 5870b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 5880b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 5890b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 5900b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 5910b57cec5SDimitry Andric } 5920b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 5930b57cec5SDimitry Andric } 5940b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 5950b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 5960b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 5970b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 5980b57cec5SDimitry Andric } 5990b57cec5SDimitry Andric return mangle("mainCRTStartup"); 6000b57cec5SDimitry Andric } 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 6030b57cec5SDimitry Andric if (config->dll) 6040b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 6050b57cec5SDimitry Andric if (config->mingw) 6060b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 6070b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 6080b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 6090b57cec5SDimitry Andric // to not be called. 6100b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 6110b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 6120b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 6130b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 6140b57cec5SDimitry Andric if (haveMain || haveWMain) { 6150b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 6160b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 6170b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 6180b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 6190b57cec5SDimitry Andric } 6200b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 6210b57cec5SDimitry Andric } 6220b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 6230b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 6240b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 6250b57cec5SDimitry Andric } 6260b57cec5SDimitry Andric 6270b57cec5SDimitry Andric static uint64_t getDefaultImageBase() { 6280b57cec5SDimitry Andric if (config->is64()) 6290b57cec5SDimitry Andric return config->dll ? 0x180000000 : 0x140000000; 6300b57cec5SDimitry Andric return config->dll ? 0x10000000 : 0x400000; 6310b57cec5SDimitry Andric } 6320b57cec5SDimitry Andric 633*fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) { 634*fe6060f1SDimitry Andric if (fs::exists(s)) 635*fe6060f1SDimitry Andric return relativeToRoot(s); 636*fe6060f1SDimitry Andric return std::string(s); 637*fe6060f1SDimitry Andric } 638*fe6060f1SDimitry Andric 639*fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run 640*fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce. 6410b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 6420b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 6430b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 6440b57cec5SDimitry Andric SmallString<0> data; 6450b57cec5SDimitry Andric raw_svector_ostream os(data); 6460b57cec5SDimitry Andric 6470b57cec5SDimitry Andric for (auto *arg : args) { 6480b57cec5SDimitry Andric switch (arg->getOption().getID()) { 6490b57cec5SDimitry Andric case OPT_linkrepro: 65085868e8aSDimitry Andric case OPT_reproduce: 6510b57cec5SDimitry Andric case OPT_INPUT: 6520b57cec5SDimitry Andric case OPT_defaultlib: 6530b57cec5SDimitry Andric case OPT_libpath: 6540b57cec5SDimitry Andric case OPT_manifest: 6550b57cec5SDimitry Andric case OPT_manifest_colon: 6560b57cec5SDimitry Andric case OPT_manifestdependency: 6570b57cec5SDimitry Andric case OPT_manifestfile: 6580b57cec5SDimitry Andric case OPT_manifestinput: 6590b57cec5SDimitry Andric case OPT_manifestuac: 6600b57cec5SDimitry Andric break; 661*fe6060f1SDimitry Andric case OPT_call_graph_ordering_file: 662*fe6060f1SDimitry Andric case OPT_deffile: 663*fe6060f1SDimitry Andric case OPT_natvis: 664*fe6060f1SDimitry Andric os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 665*fe6060f1SDimitry Andric break; 666*fe6060f1SDimitry Andric case OPT_order: { 667*fe6060f1SDimitry Andric StringRef orderFile = arg->getValue(); 668*fe6060f1SDimitry Andric orderFile.consume_front("@"); 669*fe6060f1SDimitry Andric os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 670*fe6060f1SDimitry Andric break; 671*fe6060f1SDimitry Andric } 672*fe6060f1SDimitry Andric case OPT_pdbstream: { 673*fe6060f1SDimitry Andric const std::pair<StringRef, StringRef> nameFile = 674*fe6060f1SDimitry Andric StringRef(arg->getValue()).split("="); 675*fe6060f1SDimitry Andric os << arg->getSpelling() << nameFile.first << '=' 676*fe6060f1SDimitry Andric << quote(rewritePath(nameFile.second)) << '\n'; 677*fe6060f1SDimitry Andric break; 678*fe6060f1SDimitry Andric } 6790b57cec5SDimitry Andric case OPT_implib: 6800b57cec5SDimitry Andric case OPT_pdb: 6815ffd83dbSDimitry Andric case OPT_pdbstripped: 6820b57cec5SDimitry Andric case OPT_out: 6830b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 6840b57cec5SDimitry Andric break; 6850b57cec5SDimitry Andric default: 6860b57cec5SDimitry Andric os << toString(*arg) << "\n"; 6870b57cec5SDimitry Andric } 6880b57cec5SDimitry Andric } 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric for (StringRef path : searchPaths) { 6910b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 6920b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 6930b57cec5SDimitry Andric } 6940b57cec5SDimitry Andric 6950b57cec5SDimitry Andric for (StringRef path : filePaths) 6960b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 6970b57cec5SDimitry Andric 6985ffd83dbSDimitry Andric return std::string(data.str()); 6990b57cec5SDimitry Andric } 7000b57cec5SDimitry Andric 701*fe6060f1SDimitry Andric enum class DebugKind { 702*fe6060f1SDimitry Andric Unknown, 703*fe6060f1SDimitry Andric None, 704*fe6060f1SDimitry Andric Full, 705*fe6060f1SDimitry Andric FastLink, 706*fe6060f1SDimitry Andric GHash, 707*fe6060f1SDimitry Andric NoGHash, 708*fe6060f1SDimitry Andric Dwarf, 709*fe6060f1SDimitry Andric Symtab 710*fe6060f1SDimitry Andric }; 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 7130b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 7140b57cec5SDimitry Andric if (!a) 7150b57cec5SDimitry Andric return DebugKind::None; 7160b57cec5SDimitry Andric if (a->getNumValues() == 0) 7170b57cec5SDimitry Andric return DebugKind::Full; 7180b57cec5SDimitry Andric 7190b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 7200b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 7210b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 7220b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 7230b57cec5SDimitry Andric // LLD extensions 7240b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 725*fe6060f1SDimitry Andric .CaseLower("noghash", DebugKind::NoGHash) 7260b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 7270b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 7280b57cec5SDimitry Andric .Default(DebugKind::Unknown); 7290b57cec5SDimitry Andric 7300b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 7310b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 7320b57cec5SDimitry Andric return DebugKind::Full; 7330b57cec5SDimitry Andric } 7340b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 7350b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 7360b57cec5SDimitry Andric return DebugKind::None; 7370b57cec5SDimitry Andric } 7380b57cec5SDimitry Andric return debug; 7390b57cec5SDimitry Andric } 7400b57cec5SDimitry Andric 7410b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 7420b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 7430b57cec5SDimitry Andric 7440b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 7450b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 7460b57cec5SDimitry Andric StringRef(a->getValue()) 7470b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 7480b57cec5SDimitry Andric 7490b57cec5SDimitry Andric for (StringRef type : types) { 7500b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 7510b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 7520b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 7530b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 7540b57cec5SDimitry Andric .Default(0); 7550b57cec5SDimitry Andric if (v == 0) { 7560b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 7570b57cec5SDimitry Andric continue; 7580b57cec5SDimitry Andric } 7590b57cec5SDimitry Andric debugTypes |= v; 7600b57cec5SDimitry Andric } 7610b57cec5SDimitry Andric return debugTypes; 7620b57cec5SDimitry Andric } 7630b57cec5SDimitry Andric 7640b57cec5SDimitry Andric // Default debug types 7650b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 7660b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 7670b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 7680b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 7690b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 7700b57cec5SDimitry Andric 7710b57cec5SDimitry Andric return debugTypes; 7720b57cec5SDimitry Andric } 7730b57cec5SDimitry Andric 7745ffd83dbSDimitry Andric static std::string getMapFile(const opt::InputArgList &args, 7755ffd83dbSDimitry Andric opt::OptSpecifier os, opt::OptSpecifier osFile) { 7765ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 7770b57cec5SDimitry Andric if (!arg) 7780b57cec5SDimitry Andric return ""; 7795ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 7800b57cec5SDimitry Andric return arg->getValue(); 7810b57cec5SDimitry Andric 7825ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 7830b57cec5SDimitry Andric StringRef outFile = config->outputFile; 7840b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 7850b57cec5SDimitry Andric } 7860b57cec5SDimitry Andric 7870b57cec5SDimitry Andric static std::string getImplibPath() { 7880b57cec5SDimitry Andric if (!config->implib.empty()) 7895ffd83dbSDimitry Andric return std::string(config->implib); 7900b57cec5SDimitry Andric SmallString<128> out = StringRef(config->outputFile); 7910b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 7925ffd83dbSDimitry Andric return std::string(out.str()); 7930b57cec5SDimitry Andric } 7940b57cec5SDimitry Andric 79585868e8aSDimitry Andric // The import name is calculated as follows: 7960b57cec5SDimitry Andric // 7970b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 7980b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 7990b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 8000b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 8010b57cec5SDimitry Andric // 8020b57cec5SDimitry Andric static std::string getImportName(bool asLib) { 8030b57cec5SDimitry Andric SmallString<128> out; 8040b57cec5SDimitry Andric 8050b57cec5SDimitry Andric if (config->importName.empty()) { 8060b57cec5SDimitry Andric out.assign(sys::path::filename(config->outputFile)); 8070b57cec5SDimitry Andric if (asLib) 8080b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 8090b57cec5SDimitry Andric } else { 8100b57cec5SDimitry Andric out.assign(config->importName); 8110b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 8120b57cec5SDimitry Andric sys::path::replace_extension(out, 8130b57cec5SDimitry Andric (config->dll || asLib) ? ".dll" : ".exe"); 8140b57cec5SDimitry Andric } 8150b57cec5SDimitry Andric 8165ffd83dbSDimitry Andric return std::string(out.str()); 8170b57cec5SDimitry Andric } 8180b57cec5SDimitry Andric 8190b57cec5SDimitry Andric static void createImportLibrary(bool asLib) { 8200b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 8210b57cec5SDimitry Andric for (Export &e1 : config->exports) { 8220b57cec5SDimitry Andric COFFShortExport e2; 8235ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 8245ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 8255ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 8260b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 8270b57cec5SDimitry Andric e2.Noname = e1.noname; 8280b57cec5SDimitry Andric e2.Data = e1.data; 8290b57cec5SDimitry Andric e2.Private = e1.isPrivate; 8300b57cec5SDimitry Andric e2.Constant = e1.constant; 8310b57cec5SDimitry Andric exports.push_back(e2); 8320b57cec5SDimitry Andric } 8330b57cec5SDimitry Andric 8340b57cec5SDimitry Andric auto handleError = [](Error &&e) { 8350b57cec5SDimitry Andric handleAllErrors(std::move(e), 8360b57cec5SDimitry Andric [](ErrorInfoBase &eib) { error(eib.message()); }); 8370b57cec5SDimitry Andric }; 8380b57cec5SDimitry Andric std::string libName = getImportName(asLib); 8390b57cec5SDimitry Andric std::string path = getImplibPath(); 8400b57cec5SDimitry Andric 8410b57cec5SDimitry Andric if (!config->incremental) { 8420b57cec5SDimitry Andric handleError(writeImportLibrary(libName, path, exports, config->machine, 8430b57cec5SDimitry Andric config->mingw)); 8440b57cec5SDimitry Andric return; 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric 8470b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 8480b57cec5SDimitry Andric // have changed. 8490b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 850*fe6060f1SDimitry Andric path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 8510b57cec5SDimitry Andric if (!oldBuf) { 8520b57cec5SDimitry Andric handleError(writeImportLibrary(libName, path, exports, config->machine, 8530b57cec5SDimitry Andric config->mingw)); 8540b57cec5SDimitry Andric return; 8550b57cec5SDimitry Andric } 8560b57cec5SDimitry Andric 8570b57cec5SDimitry Andric SmallString<128> tmpName; 8580b57cec5SDimitry Andric if (std::error_code ec = 8590b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 8600b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 8610b57cec5SDimitry Andric ec.message()); 8620b57cec5SDimitry Andric 8630b57cec5SDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 8640b57cec5SDimitry Andric config->mingw)) { 8650b57cec5SDimitry Andric handleError(std::move(e)); 8660b57cec5SDimitry Andric return; 8670b57cec5SDimitry Andric } 8680b57cec5SDimitry Andric 8690b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 870*fe6060f1SDimitry Andric tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 8710b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 8720b57cec5SDimitry Andric oldBuf->reset(); 8730b57cec5SDimitry Andric handleError(errorCodeToError(sys::fs::rename(tmpName, path))); 8740b57cec5SDimitry Andric } else { 8750b57cec5SDimitry Andric sys::fs::remove(tmpName); 8760b57cec5SDimitry Andric } 8770b57cec5SDimitry Andric } 8780b57cec5SDimitry Andric 8790b57cec5SDimitry Andric static void parseModuleDefs(StringRef path) { 880*fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 881*fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 882*fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 883*fe6060f1SDimitry Andric /*IsVolatile=*/true), 884*fe6060f1SDimitry Andric "could not open " + path); 8850b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 8860b57cec5SDimitry Andric mb->getMemBufferRef(), config->machine, config->mingw)); 8870b57cec5SDimitry Andric 888*fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 889*fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 890*fe6060f1SDimitry Andric 8910b57cec5SDimitry Andric if (config->outputFile.empty()) 8925ffd83dbSDimitry Andric config->outputFile = std::string(saver.save(m.OutputFile)); 8935ffd83dbSDimitry Andric config->importName = std::string(saver.save(m.ImportName)); 8940b57cec5SDimitry Andric if (m.ImageBase) 8950b57cec5SDimitry Andric config->imageBase = m.ImageBase; 8960b57cec5SDimitry Andric if (m.StackReserve) 8970b57cec5SDimitry Andric config->stackReserve = m.StackReserve; 8980b57cec5SDimitry Andric if (m.StackCommit) 8990b57cec5SDimitry Andric config->stackCommit = m.StackCommit; 9000b57cec5SDimitry Andric if (m.HeapReserve) 9010b57cec5SDimitry Andric config->heapReserve = m.HeapReserve; 9020b57cec5SDimitry Andric if (m.HeapCommit) 9030b57cec5SDimitry Andric config->heapCommit = m.HeapCommit; 9040b57cec5SDimitry Andric if (m.MajorImageVersion) 9050b57cec5SDimitry Andric config->majorImageVersion = m.MajorImageVersion; 9060b57cec5SDimitry Andric if (m.MinorImageVersion) 9070b57cec5SDimitry Andric config->minorImageVersion = m.MinorImageVersion; 9080b57cec5SDimitry Andric if (m.MajorOSVersion) 9090b57cec5SDimitry Andric config->majorOSVersion = m.MajorOSVersion; 9100b57cec5SDimitry Andric if (m.MinorOSVersion) 9110b57cec5SDimitry Andric config->minorOSVersion = m.MinorOSVersion; 9120b57cec5SDimitry Andric 9130b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 9140b57cec5SDimitry Andric Export e2; 9150b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 9160b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 9170b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 9180b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 9195ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 9205ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 9210b57cec5SDimitry Andric e2.name = saver.save(e1.ExtName); 9220b57cec5SDimitry Andric e2.forwardTo = saver.save(e1.Name); 9230b57cec5SDimitry Andric config->exports.push_back(e2); 9240b57cec5SDimitry Andric continue; 9250b57cec5SDimitry Andric } 9260b57cec5SDimitry Andric e2.name = saver.save(e1.Name); 9270b57cec5SDimitry Andric e2.extName = saver.save(e1.ExtName); 9280b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 9290b57cec5SDimitry Andric e2.noname = e1.Noname; 9300b57cec5SDimitry Andric e2.data = e1.Data; 9310b57cec5SDimitry Andric e2.isPrivate = e1.Private; 9320b57cec5SDimitry Andric e2.constant = e1.Constant; 9330b57cec5SDimitry Andric config->exports.push_back(e2); 9340b57cec5SDimitry Andric } 9350b57cec5SDimitry Andric } 9360b57cec5SDimitry Andric 9370b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 9380b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 9390b57cec5SDimitry Andric } 9400b57cec5SDimitry Andric 9410b57cec5SDimitry Andric bool LinkerDriver::run() { 9420b57cec5SDimitry Andric ScopedTimer t(inputFileTimer); 9430b57cec5SDimitry Andric 9440b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 9450b57cec5SDimitry Andric while (!taskQueue.empty()) { 9460b57cec5SDimitry Andric taskQueue.front()(); 9470b57cec5SDimitry Andric taskQueue.pop_front(); 9480b57cec5SDimitry Andric } 9490b57cec5SDimitry Andric return didWork; 9500b57cec5SDimitry Andric } 9510b57cec5SDimitry Andric 9520b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 9530b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 9540b57cec5SDimitry Andric // given file. 9550b57cec5SDimitry Andric static void parseOrderFile(StringRef arg) { 9560b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 9570b57cec5SDimitry Andric // preceded by "@". 9580b57cec5SDimitry Andric if (!arg.startswith("@")) { 9590b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 9600b57cec5SDimitry Andric return; 9610b57cec5SDimitry Andric } 9620b57cec5SDimitry Andric 9630b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 9640b57cec5SDimitry Andric DenseSet<StringRef> set; 9650b57cec5SDimitry Andric for (Chunk *c : symtab->getChunks()) 9660b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 9670b57cec5SDimitry Andric if (sec->sym) 9680b57cec5SDimitry Andric set.insert(sec->sym->getName()); 9690b57cec5SDimitry Andric 9700b57cec5SDimitry Andric // Open a file. 9710b57cec5SDimitry Andric StringRef path = arg.substr(1); 972*fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 973*fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 974*fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 975*fe6060f1SDimitry Andric /*IsVolatile=*/true), 976*fe6060f1SDimitry Andric "could not open " + path); 9770b57cec5SDimitry Andric 9780b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 9790b57cec5SDimitry Andric // All symbols that were not present in a given order file are 9800b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 9810b57cec5SDimitry Andric // end of an output section. 9825ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 9835ffd83dbSDimitry Andric std::string s(arg); 9840b57cec5SDimitry Andric if (config->machine == I386 && !isDecorated(s)) 9850b57cec5SDimitry Andric s = "_" + s; 9860b57cec5SDimitry Andric 9870b57cec5SDimitry Andric if (set.count(s) == 0) { 9880b57cec5SDimitry Andric if (config->warnMissingOrderSymbol) 9890b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 9900b57cec5SDimitry Andric } 9910b57cec5SDimitry Andric else 9920b57cec5SDimitry Andric config->order[s] = INT_MIN + config->order.size(); 9930b57cec5SDimitry Andric } 994*fe6060f1SDimitry Andric 995*fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 996*fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 9970b57cec5SDimitry Andric } 9980b57cec5SDimitry Andric 999e8d8bef9SDimitry Andric static void parseCallGraphFile(StringRef path) { 1000*fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 1001*fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 1002*fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 1003*fe6060f1SDimitry Andric /*IsVolatile=*/true), 1004*fe6060f1SDimitry Andric "could not open " + path); 1005e8d8bef9SDimitry Andric 1006e8d8bef9SDimitry Andric // Build a map from symbol name to section. 1007e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 1008e8d8bef9SDimitry Andric for (ObjFile *file : ObjFile::instances) 1009e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 1010e8d8bef9SDimitry Andric if (sym) 1011e8d8bef9SDimitry Andric map[sym->getName()] = sym; 1012e8d8bef9SDimitry Andric 1013e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 1014e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 1015e8d8bef9SDimitry Andric if (!sym) { 1016e8d8bef9SDimitry Andric if (config->warnMissingOrderSymbol) 1017e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 1018e8d8bef9SDimitry Andric return nullptr; 1019e8d8bef9SDimitry Andric } 1020e8d8bef9SDimitry Andric 1021e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 1022e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 1023e8d8bef9SDimitry Andric return nullptr; 1024e8d8bef9SDimitry Andric }; 1025e8d8bef9SDimitry Andric 1026e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 1027e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 1028e8d8bef9SDimitry Andric line.split(fields, ' '); 1029e8d8bef9SDimitry Andric uint64_t count; 1030e8d8bef9SDimitry Andric 1031e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 1032e8d8bef9SDimitry Andric error(path + ": parse error"); 1033e8d8bef9SDimitry Andric return; 1034e8d8bef9SDimitry Andric } 1035e8d8bef9SDimitry Andric 1036e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 1037e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 1038e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1039e8d8bef9SDimitry Andric } 1040*fe6060f1SDimitry Andric 1041*fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1042*fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 1043e8d8bef9SDimitry Andric } 1044e8d8bef9SDimitry Andric 1045e8d8bef9SDimitry Andric static void readCallGraphsFromObjectFiles() { 1046e8d8bef9SDimitry Andric for (ObjFile *obj : ObjFile::instances) { 1047e8d8bef9SDimitry Andric if (obj->callgraphSec) { 1048e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 1049e8d8bef9SDimitry Andric cantFail( 1050e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1051e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 1052e8d8bef9SDimitry Andric while (!reader.empty()) { 1053e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 1054e8d8bef9SDimitry Andric uint64_t count; 1055e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 1056e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1057e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 1058e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1059e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 1060e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 1061e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1062e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1063e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1064e8d8bef9SDimitry Andric continue; 1065e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1066e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1067e8d8bef9SDimitry Andric if (from && to) 1068e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1069e8d8bef9SDimitry Andric } 1070e8d8bef9SDimitry Andric } 1071e8d8bef9SDimitry Andric } 1072e8d8bef9SDimitry Andric } 1073e8d8bef9SDimitry Andric 10740b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 10750b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 10760b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 10770b57cec5SDimitry Andric c->keepUnique = true; 10780b57cec5SDimitry Andric } 10790b57cec5SDimitry Andric 10800b57cec5SDimitry Andric static void findKeepUniqueSections() { 10810b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 10820b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 10830b57cec5SDimitry Andric for (Export &r : config->exports) 10840b57cec5SDimitry Andric markAddrsig(r.sym); 10850b57cec5SDimitry Andric 10860b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 10870b57cec5SDimitry Andric // referenced symbol as address-significant. 10880b57cec5SDimitry Andric for (ObjFile *obj : ObjFile::instances) { 10890b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 10900b57cec5SDimitry Andric if (obj->addrsigSec) { 10910b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 10920b57cec5SDimitry Andric cantFail( 10930b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 10940b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 10950b57cec5SDimitry Andric while (cur != contents.end()) { 10960b57cec5SDimitry Andric unsigned size; 10970b57cec5SDimitry Andric const char *err; 10980b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 10990b57cec5SDimitry Andric if (err) 11000b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 11010b57cec5SDimitry Andric if (symIndex >= syms.size()) 11020b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 11030b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 11040b57cec5SDimitry Andric cur += size; 11050b57cec5SDimitry Andric } 11060b57cec5SDimitry Andric } else { 11070b57cec5SDimitry Andric // If an object file does not have an address-significance table, 11080b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 11090b57cec5SDimitry Andric for (Symbol *s : syms) 11100b57cec5SDimitry Andric markAddrsig(s); 11110b57cec5SDimitry Andric } 11120b57cec5SDimitry Andric } 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 11160b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 11170b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 11180b57cec5SDimitry Andric // binary). 11190b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 11200b57cec5SDimitry Andric // vars. 11210b57cec5SDimitry Andric static void parsePDBAltPath(StringRef altPath) { 11220b57cec5SDimitry Andric SmallString<128> buf; 11230b57cec5SDimitry Andric StringRef pdbBasename = 11240b57cec5SDimitry Andric sys::path::filename(config->pdbPath, sys::path::Style::windows); 11250b57cec5SDimitry Andric StringRef binaryExtension = 11260b57cec5SDimitry Andric sys::path::extension(config->outputFile, sys::path::Style::windows); 11270b57cec5SDimitry Andric if (!binaryExtension.empty()) 11280b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 11290b57cec5SDimitry Andric 11300b57cec5SDimitry Andric // Invariant: 11310b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 11320b57cec5SDimitry Andric // | +----- firstMark 11330b57cec5SDimitry Andric // | | +- secondMark 11340b57cec5SDimitry Andric // v v v 11350b57cec5SDimitry Andric // a...%...%... 11360b57cec5SDimitry Andric size_t cursor = 0; 11370b57cec5SDimitry Andric while (cursor < altPath.size()) { 11380b57cec5SDimitry Andric size_t firstMark, secondMark; 11390b57cec5SDimitry Andric if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 11400b57cec5SDimitry Andric (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 11410b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 11420b57cec5SDimitry Andric buf.append(altPath.substr(cursor)); 11430b57cec5SDimitry Andric break; 11440b57cec5SDimitry Andric } 11450b57cec5SDimitry Andric 11460b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 11470b57cec5SDimitry Andric // text between first and second % as variable name. 11480b57cec5SDimitry Andric buf.append(altPath.substr(cursor, firstMark - cursor)); 11490b57cec5SDimitry Andric StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1150*fe6060f1SDimitry Andric if (var.equals_insensitive("%_pdb%")) 11510b57cec5SDimitry Andric buf.append(pdbBasename); 1152*fe6060f1SDimitry Andric else if (var.equals_insensitive("%_ext%")) 11530b57cec5SDimitry Andric buf.append(binaryExtension); 11540b57cec5SDimitry Andric else { 11550b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 11560b57cec5SDimitry Andric var + " as literal"); 11570b57cec5SDimitry Andric buf.append(var); 11580b57cec5SDimitry Andric } 11590b57cec5SDimitry Andric 11600b57cec5SDimitry Andric cursor = secondMark + 1; 11610b57cec5SDimitry Andric } 11620b57cec5SDimitry Andric 11630b57cec5SDimitry Andric config->pdbAltPath = buf; 11640b57cec5SDimitry Andric } 11650b57cec5SDimitry Andric 116685868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 116785868e8aSDimitry Andric /// trees into one resource tree. 11680b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 116985868e8aSDimitry Andric void LinkerDriver::convertResources() { 117085868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 117185868e8aSDimitry Andric 11720b57cec5SDimitry Andric for (ObjFile *f : ObjFile::instances) { 117385868e8aSDimitry Andric if (f->isResourceObjFile()) 117485868e8aSDimitry Andric resourceObjFiles.push_back(f); 11750b57cec5SDimitry Andric } 11760b57cec5SDimitry Andric 117785868e8aSDimitry Andric if (!config->mingw && 117885868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 117985868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 118085868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 118185868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 11820b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 118385868e8aSDimitry Andric toString(resourceObjFiles.front())); 118485868e8aSDimitry Andric return; 11850b57cec5SDimitry Andric } 118685868e8aSDimitry Andric 118785868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 118885868e8aSDimitry Andric // No resources to convert, and max one resource object file in 118985868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 119085868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 119185868e8aSDimitry Andric f->includeResourceChunks(); 119285868e8aSDimitry Andric return; 119385868e8aSDimitry Andric } 119485868e8aSDimitry Andric ObjFile *f = make<ObjFile>(convertResToCOFF(resources, resourceObjFiles)); 119585868e8aSDimitry Andric symtab->addFile(f); 119685868e8aSDimitry Andric f->includeResourceChunks(); 11970b57cec5SDimitry Andric } 11980b57cec5SDimitry Andric 11990b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 12000b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 12010b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 12020b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 12030b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 12040b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 12050b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1206*fe6060f1SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 12070b57cec5SDimitry Andric if (!config->dll) 12080b57cec5SDimitry Andric return; 12090b57cec5SDimitry Andric 12100b57cec5SDimitry Andric if (!config->exports.empty()) 12110b57cec5SDimitry Andric return; 12120b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 12130b57cec5SDimitry Andric return; 12140b57cec5SDimitry Andric } 12150b57cec5SDimitry Andric 12160b57cec5SDimitry Andric AutoExporter exporter; 12170b57cec5SDimitry Andric 12180b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 12190b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 12200b57cec5SDimitry Andric exporter.addWholeArchive(*path); 12210b57cec5SDimitry Andric 12220b57cec5SDimitry Andric symtab->forEachSymbol([&](Symbol *s) { 12230b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 12240b57cec5SDimitry Andric if (!exporter.shouldExport(def)) 12250b57cec5SDimitry Andric return; 12260b57cec5SDimitry Andric 1227*fe6060f1SDimitry Andric if (!def->isGCRoot) { 1228*fe6060f1SDimitry Andric def->isGCRoot = true; 1229*fe6060f1SDimitry Andric config->gcroot.push_back(def); 1230*fe6060f1SDimitry Andric } 1231*fe6060f1SDimitry Andric 12320b57cec5SDimitry Andric Export e; 12330b57cec5SDimitry Andric e.name = def->getName(); 12340b57cec5SDimitry Andric e.sym = def; 12350b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 12360b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 12370b57cec5SDimitry Andric e.data = true; 1238*fe6060f1SDimitry Andric s->isUsedInRegularObj = true; 12390b57cec5SDimitry Andric config->exports.push_back(e); 12400b57cec5SDimitry Andric }); 12410b57cec5SDimitry Andric } 12420b57cec5SDimitry Andric 124385868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 124485868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 124585868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 124685868e8aSDimitry Andric // 124785868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 124885868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 124985868e8aSDimitry Andric // with Microsoft link.exe. 125085868e8aSDimitry Andric Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 125185868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 125285868e8aSDimitry Andric return std::string(arg->getValue()); 125385868e8aSDimitry Andric 125485868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 125585868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 125685868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 12575ffd83dbSDimitry Andric return std::string(path); 125885868e8aSDimitry Andric } 125985868e8aSDimitry Andric 1260e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1261e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1262e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1263e8d8bef9SDimitry Andric return std::string(path); 1264e8d8bef9SDimitry Andric 126585868e8aSDimitry Andric return None; 126685868e8aSDimitry Andric } 12670b57cec5SDimitry Andric 1268e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 12695ffd83dbSDimitry Andric ScopedTimer rootTimer(Timer::root()); 12705ffd83dbSDimitry Andric 12710b57cec5SDimitry Andric // Needed for LTO. 12720b57cec5SDimitry Andric InitializeAllTargetInfos(); 12730b57cec5SDimitry Andric InitializeAllTargets(); 12740b57cec5SDimitry Andric InitializeAllTargetMCs(); 12750b57cec5SDimitry Andric InitializeAllAsmParsers(); 12760b57cec5SDimitry Andric InitializeAllAsmPrinters(); 12770b57cec5SDimitry Andric 12780b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 12790b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 1280*fe6060f1SDimitry Andric if (argsArr.size() > 1 && 1281*fe6060f1SDimitry Andric (StringRef(argsArr[1]).equals_insensitive("/lib") || 1282*fe6060f1SDimitry Andric StringRef(argsArr[1]).equals_insensitive("-lib"))) { 12830b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 12840b57cec5SDimitry Andric fatal("lib failed"); 12850b57cec5SDimitry Andric return; 12860b57cec5SDimitry Andric } 12870b57cec5SDimitry Andric 12880b57cec5SDimitry Andric // Parse command line options. 12890b57cec5SDimitry Andric ArgParser parser; 129085868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 12910b57cec5SDimitry Andric 12920b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 12930b57cec5SDimitry Andric std::vector<const char *> v; 12940b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 12950b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 12960b57cec5SDimitry Andric v.push_back(arg->getValue()); 1297e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 12980b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 12990b57cec5SDimitry Andric 13000b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 13010b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 13020b57cec5SDimitry Andric int n = 20; 13030b57cec5SDimitry Andric StringRef s = arg->getValue(); 13040b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 13050b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 13060b57cec5SDimitry Andric errorHandler().errorLimit = n; 13070b57cec5SDimitry Andric } 13080b57cec5SDimitry Andric 13090b57cec5SDimitry Andric // Handle /help 13100b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 13110b57cec5SDimitry Andric printHelp(argsArr[0]); 13120b57cec5SDimitry Andric return; 13130b57cec5SDimitry Andric } 13140b57cec5SDimitry Andric 13155ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 13165ffd83dbSDimitry Andric // /opt:lldltojobs=. 13175ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 13185ffd83dbSDimitry Andric StringRef v(arg->getValue()); 13195ffd83dbSDimitry Andric unsigned threads = 0; 13205ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 13215ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 13225ffd83dbSDimitry Andric arg->getValue() + "'"); 13235ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 13245ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 13255ffd83dbSDimitry Andric } 13260b57cec5SDimitry Andric 13270b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 13280b57cec5SDimitry Andric config->showTiming = true; 13290b57cec5SDimitry Andric 13300b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 13310b57cec5SDimitry Andric 13320b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 13330b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 13340b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 13350b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1336e8d8bef9SDimitry Andric message(getLLDVersion()); 13370b57cec5SDimitry Andric return; 13380b57cec5SDimitry Andric } 13390b57cec5SDimitry Andric 13400b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 13410b57cec5SDimitry Andric // options are handled. 13420b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 13430b57cec5SDimitry Andric 134485868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 134585868e8aSDimitry Andric if (Optional<std::string> path = getReproduceFile(args)) { 13460b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 134785868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 13480b57cec5SDimitry Andric 13490b57cec5SDimitry Andric if (errOrWriter) { 13500b57cec5SDimitry Andric tar = std::move(*errOrWriter); 13510b57cec5SDimitry Andric } else { 135285868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 13530b57cec5SDimitry Andric toString(errOrWriter.takeError())); 13540b57cec5SDimitry Andric } 13550b57cec5SDimitry Andric } 13560b57cec5SDimitry Andric 1357480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 13580b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 13590b57cec5SDimitry Andric config->noEntry = true; 13600b57cec5SDimitry Andric else 13610b57cec5SDimitry Andric fatal("no input files"); 13620b57cec5SDimitry Andric } 13630b57cec5SDimitry Andric 13640b57cec5SDimitry Andric // Construct search path list. 13650b57cec5SDimitry Andric searchPaths.push_back(""); 13660b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 13670b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 136885868e8aSDimitry Andric if (!args.hasArg(OPT_lldignoreenv)) 13690b57cec5SDimitry Andric addLibSearchPaths(); 13700b57cec5SDimitry Andric 13710b57cec5SDimitry Andric // Handle /ignore 13720b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 13730b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 13740b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 13750b57cec5SDimitry Andric for (StringRef s : vec) { 13760b57cec5SDimitry Andric if (s == "4037") 13770b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 13780b57cec5SDimitry Andric else if (s == "4099") 13790b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 13800b57cec5SDimitry Andric else if (s == "4217") 13810b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1382480093f4SDimitry Andric else if (s == "longsections") 1383480093f4SDimitry Andric config->warnLongSectionNames = false; 13840b57cec5SDimitry Andric // Other warning numbers are ignored. 13850b57cec5SDimitry Andric } 13860b57cec5SDimitry Andric } 13870b57cec5SDimitry Andric 13880b57cec5SDimitry Andric // Handle /out 13890b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 13900b57cec5SDimitry Andric config->outputFile = arg->getValue(); 13910b57cec5SDimitry Andric 13920b57cec5SDimitry Andric // Handle /verbose 13930b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 13940b57cec5SDimitry Andric config->verbose = true; 13950b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 13960b57cec5SDimitry Andric 13970b57cec5SDimitry Andric // Handle /force or /force:unresolved 13980b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 13990b57cec5SDimitry Andric config->forceUnresolved = true; 14000b57cec5SDimitry Andric 14010b57cec5SDimitry Andric // Handle /force or /force:multiple 14020b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 14030b57cec5SDimitry Andric config->forceMultiple = true; 14040b57cec5SDimitry Andric 14050b57cec5SDimitry Andric // Handle /force or /force:multipleres 14060b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 14070b57cec5SDimitry Andric config->forceMultipleRes = true; 14080b57cec5SDimitry Andric 14090b57cec5SDimitry Andric // Handle /debug 14100b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 14110b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1412*fe6060f1SDimitry Andric debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 14130b57cec5SDimitry Andric config->debug = true; 14140b57cec5SDimitry Andric config->incremental = true; 14150b57cec5SDimitry Andric } 14160b57cec5SDimitry Andric 14170b57cec5SDimitry Andric // Handle /demangle 14180b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 14190b57cec5SDimitry Andric 14200b57cec5SDimitry Andric // Handle /debugtype 14210b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 14220b57cec5SDimitry Andric 1423480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1424480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1425480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1426480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1427480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1428480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1429480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1430480093f4SDimitry Andric config->driver = 1431480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1432480093f4SDimitry Andric 14330b57cec5SDimitry Andric // Handle /pdb 14340b57cec5SDimitry Andric bool shouldCreatePDB = 1435*fe6060f1SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash || 1436*fe6060f1SDimitry Andric debug == DebugKind::NoGHash); 14370b57cec5SDimitry Andric if (shouldCreatePDB) { 14380b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 14390b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 14400b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 14410b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 14420b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 14430b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 14445ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 14455ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 14465ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 14475ffd83dbSDimitry Andric const StringRef name = nameFile.first; 14485ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 14495ffd83dbSDimitry Andric config->namedStreams[name] = file; 14505ffd83dbSDimitry Andric } 14515ffd83dbSDimitry Andric } 14520b57cec5SDimitry Andric 14530b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 14540b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 14550b57cec5SDimitry Andric } 14560b57cec5SDimitry Andric 14575ffd83dbSDimitry Andric // Handle /pdbstripped 14585ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 14595ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 14605ffd83dbSDimitry Andric 14610b57cec5SDimitry Andric // Handle /noentry 14620b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 14630b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 14640b57cec5SDimitry Andric config->noEntry = true; 14650b57cec5SDimitry Andric else 14660b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 14670b57cec5SDimitry Andric } 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric // Handle /dll 14700b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 14710b57cec5SDimitry Andric config->dll = true; 14720b57cec5SDimitry Andric config->manifestID = 2; 14730b57cec5SDimitry Andric } 14740b57cec5SDimitry Andric 14750b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 14760b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 14770b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 14780b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 14790b57cec5SDimitry Andric if (dynamicBaseArg && 14800b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 14810b57cec5SDimitry Andric config->dynamicBase = false; 14820b57cec5SDimitry Andric 14830b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 14840b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 14850b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 14860b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 14870b57cec5SDimitry Andric if (fixed) { 14880b57cec5SDimitry Andric if (dynamicBaseArg && 14890b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 14900b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 14910b57cec5SDimitry Andric } else { 14920b57cec5SDimitry Andric config->relocatable = false; 14930b57cec5SDimitry Andric config->dynamicBase = false; 14940b57cec5SDimitry Andric } 14950b57cec5SDimitry Andric } 14960b57cec5SDimitry Andric 14970b57cec5SDimitry Andric // Handle /appcontainer 14980b57cec5SDimitry Andric config->appContainer = 14990b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 15000b57cec5SDimitry Andric 15010b57cec5SDimitry Andric // Handle /machine 15020b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 15030b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 15040b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 15050b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 15060b57cec5SDimitry Andric } 15070b57cec5SDimitry Andric 15080b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 15090b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 15100b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 15110b57cec5SDimitry Andric 15120b57cec5SDimitry Andric // Handle /nodefaultlib 15130b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 15140b57cec5SDimitry Andric config->noDefaultLibAll = true; 15150b57cec5SDimitry Andric 15160b57cec5SDimitry Andric // Handle /base 15170b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 15180b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 15190b57cec5SDimitry Andric 15200b57cec5SDimitry Andric // Handle /filealign 15210b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 15220b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 15230b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 15240b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 15250b57cec5SDimitry Andric } 15260b57cec5SDimitry Andric 15270b57cec5SDimitry Andric // Handle /stack 15280b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 15290b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 15300b57cec5SDimitry Andric 15310b57cec5SDimitry Andric // Handle /guard:cf 15320b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 15330b57cec5SDimitry Andric parseGuard(arg->getValue()); 15340b57cec5SDimitry Andric 15350b57cec5SDimitry Andric // Handle /heap 15360b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 15370b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 15380b57cec5SDimitry Andric 15390b57cec5SDimitry Andric // Handle /version 15400b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 15410b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 15420b57cec5SDimitry Andric &config->minorImageVersion); 15430b57cec5SDimitry Andric 15440b57cec5SDimitry Andric // Handle /subsystem 15450b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1546e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1547e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1548e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1549e8d8bef9SDimitry Andric 1550e8d8bef9SDimitry Andric // Handle /osversion 1551e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1552e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 15530b57cec5SDimitry Andric &config->minorOSVersion); 1554e8d8bef9SDimitry Andric } else { 1555e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1556e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1557e8d8bef9SDimitry Andric } 15580b57cec5SDimitry Andric 15590b57cec5SDimitry Andric // Handle /timestamp 15600b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 15610b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 15620b57cec5SDimitry Andric config->timestamp = 0; 15630b57cec5SDimitry Andric config->repro = true; 15640b57cec5SDimitry Andric } else { 15650b57cec5SDimitry Andric config->repro = false; 15660b57cec5SDimitry Andric StringRef value(arg->getValue()); 15670b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 15680b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 15690b57cec5SDimitry Andric ". Expected 32-bit integer"); 15700b57cec5SDimitry Andric } 15710b57cec5SDimitry Andric } else { 15720b57cec5SDimitry Andric config->repro = false; 15730b57cec5SDimitry Andric config->timestamp = time(nullptr); 15740b57cec5SDimitry Andric } 15750b57cec5SDimitry Andric 15760b57cec5SDimitry Andric // Handle /alternatename 15770b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 15780b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 15790b57cec5SDimitry Andric 15800b57cec5SDimitry Andric // Handle /include 15810b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 15820b57cec5SDimitry Andric addUndefined(arg->getValue()); 15830b57cec5SDimitry Andric 15840b57cec5SDimitry Andric // Handle /implib 15850b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 15860b57cec5SDimitry Andric config->implib = arg->getValue(); 15870b57cec5SDimitry Andric 15880b57cec5SDimitry Andric // Handle /opt. 15890b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1590*fe6060f1SDimitry Andric Optional<ICFLevel> icfLevel = None; 1591*fe6060f1SDimitry Andric if (args.hasArg(OPT_profile)) 1592*fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 15930b57cec5SDimitry Andric unsigned tailMerge = 1; 1594e8d8bef9SDimitry Andric bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1595e8d8bef9SDimitry Andric bool ltoDebugPM = false; 15960b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 15970b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 15980b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 15990b57cec5SDimitry Andric StringRef(str).split(vec, ','); 16000b57cec5SDimitry Andric for (StringRef s : vec) { 16010b57cec5SDimitry Andric if (s == "ref") { 16020b57cec5SDimitry Andric doGC = true; 16030b57cec5SDimitry Andric } else if (s == "noref") { 16040b57cec5SDimitry Andric doGC = false; 16050b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 1606*fe6060f1SDimitry Andric icfLevel = ICFLevel::All; 1607*fe6060f1SDimitry Andric } else if (s == "safeicf") { 1608*fe6060f1SDimitry Andric icfLevel = ICFLevel::Safe; 16090b57cec5SDimitry Andric } else if (s == "noicf") { 1610*fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 16110b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 16120b57cec5SDimitry Andric tailMerge = 2; 16130b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 16140b57cec5SDimitry Andric tailMerge = 0; 1615e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 1616e8d8bef9SDimitry Andric ltoNewPM = true; 1617e8d8bef9SDimitry Andric } else if (s == "noltonewpassmanager") { 1618e8d8bef9SDimitry Andric ltoNewPM = false; 1619e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1620e8d8bef9SDimitry Andric ltoDebugPM = true; 1621e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1622e8d8bef9SDimitry Andric ltoDebugPM = false; 16230b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 16240b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 16250b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 16260b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 16270b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 16280b57cec5SDimitry Andric StringRef jobs = s.substr(11); 16295ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 16300b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 16315ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 16320b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 16330b57cec5SDimitry Andric StringRef n = s.substr(17); 16340b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 16350b57cec5SDimitry Andric config->ltoPartitions == 0) 16360b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 16370b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 16380b57cec5SDimitry Andric error("/opt: unknown option: " + s); 16390b57cec5SDimitry Andric } 16400b57cec5SDimitry Andric } 16410b57cec5SDimitry Andric 1642*fe6060f1SDimitry Andric if (!icfLevel) 1643*fe6060f1SDimitry Andric icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 16440b57cec5SDimitry Andric config->doGC = doGC; 1645*fe6060f1SDimitry Andric config->doICF = icfLevel.getValue(); 1646*fe6060f1SDimitry Andric config->tailMerge = 1647*fe6060f1SDimitry Andric (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1648e8d8bef9SDimitry Andric config->ltoNewPassManager = ltoNewPM; 1649e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 16500b57cec5SDimitry Andric 16510b57cec5SDimitry Andric // Handle /lldsavetemps 16520b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 16530b57cec5SDimitry Andric config->saveTemps = true; 16540b57cec5SDimitry Andric 16550b57cec5SDimitry Andric // Handle /kill-at 16560b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 16570b57cec5SDimitry Andric config->killAt = true; 16580b57cec5SDimitry Andric 16590b57cec5SDimitry Andric // Handle /lldltocache 16600b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 16610b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric // Handle /lldsavecachepolicy 16640b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 16650b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 16660b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 16670b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 16680b57cec5SDimitry Andric 16690b57cec5SDimitry Andric // Handle /failifmismatch 16700b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 16710b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 16720b57cec5SDimitry Andric 16730b57cec5SDimitry Andric // Handle /merge 16740b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 16750b57cec5SDimitry Andric parseMerge(arg->getValue()); 16760b57cec5SDimitry Andric 16770b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 16780b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 16790b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 16800b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 16810b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 16820b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 16830b57cec5SDimitry Andric parseMerge(".bss=.data"); 16840b57cec5SDimitry Andric 16850b57cec5SDimitry Andric if (config->mingw) { 16860b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 16870b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 16880b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 16890b57cec5SDimitry Andric } 16900b57cec5SDimitry Andric 16910b57cec5SDimitry Andric // Handle /section 16920b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 16930b57cec5SDimitry Andric parseSection(arg->getValue()); 16940b57cec5SDimitry Andric 16950b57cec5SDimitry Andric // Handle /align 16960b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 16970b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 16980b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 16990b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1700480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1701480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 17020b57cec5SDimitry Andric } 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric // Handle /aligncomm 17050b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 17060b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 17070b57cec5SDimitry Andric 17080b57cec5SDimitry Andric // Handle /manifestdependency. This enables /manifest unless /manifest:no is 17090b57cec5SDimitry Andric // also passed. 17100b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestdependency)) { 17110b57cec5SDimitry Andric config->manifestDependency = arg->getValue(); 17120b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 17130b57cec5SDimitry Andric } 17140b57cec5SDimitry Andric 17150b57cec5SDimitry Andric // Handle /manifest and /manifest: 17160b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 17170b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 17180b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 17190b57cec5SDimitry Andric else 17200b57cec5SDimitry Andric parseManifest(arg->getValue()); 17210b57cec5SDimitry Andric } 17220b57cec5SDimitry Andric 17230b57cec5SDimitry Andric // Handle /manifestuac 17240b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 17250b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 17260b57cec5SDimitry Andric 17270b57cec5SDimitry Andric // Handle /manifestfile 17280b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 17290b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 17300b57cec5SDimitry Andric 17310b57cec5SDimitry Andric // Handle /manifestinput 17320b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 17330b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 17340b57cec5SDimitry Andric 17350b57cec5SDimitry Andric if (!config->manifestInput.empty() && 17360b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 17370b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 17380b57cec5SDimitry Andric } 17390b57cec5SDimitry Andric 17400b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 17410b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 17420b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 17430b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 17440b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 17450b57cec5SDimitry Andric config->thinLTOPrefixReplace = 17460b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 17470b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 17480b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 174985868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1750*fe6060f1SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1751*fe6060f1SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 17520b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 17530b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 17540b57cec5SDimitry Andric config->allowIsolation = 17550b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 17560b57cec5SDimitry Andric config->incremental = 17570b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 1758*fe6060f1SDimitry Andric !config->doGC && config->doICF == ICFLevel::None && 1759*fe6060f1SDimitry Andric !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 17600b57cec5SDimitry Andric config->integrityCheck = 17610b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 17625ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 17630b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 17640b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 17650b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 17660b57cec5SDimitry Andric config->terminalServerAware = 17670b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 17680b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 1769*fe6060f1SDimitry Andric config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 17700b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 17715ffd83dbSDimitry Andric config->autoImport = 17725ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 17735ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 17745ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1775e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1776e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1777*fe6060f1SDimitry Andric config->stdcallFixup = 1778*fe6060f1SDimitry Andric args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1779*fe6060f1SDimitry Andric config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 17800b57cec5SDimitry Andric 1781e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1782e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1783480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1784480093f4SDimitry Andric config->warnLongSectionNames = false; 1785480093f4SDimitry Andric 17865ffd83dbSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 17875ffd83dbSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 17885ffd83dbSDimitry Andric 17895ffd83dbSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 17905ffd83dbSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 17915ffd83dbSDimitry Andric "'.\n>>> ignoring /lldmap"); 17925ffd83dbSDimitry Andric config->lldmapFile.clear(); 17935ffd83dbSDimitry Andric } 17940b57cec5SDimitry Andric 17950b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 17960b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 17970b57cec5SDimitry Andric config->incremental = false; 17980b57cec5SDimitry Andric } 17990b57cec5SDimitry Andric 18000b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 18010b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 18020b57cec5SDimitry Andric config->incremental = false; 18030b57cec5SDimitry Andric } 18040b57cec5SDimitry Andric 18050b57cec5SDimitry Andric if (config->incremental && config->doGC) { 18060b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 18070b57cec5SDimitry Andric "disable"); 18080b57cec5SDimitry Andric config->incremental = false; 18090b57cec5SDimitry Andric } 18100b57cec5SDimitry Andric 1811*fe6060f1SDimitry Andric if (config->incremental && config->doICF != ICFLevel::None) { 18120b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 18130b57cec5SDimitry Andric "disable"); 18140b57cec5SDimitry Andric config->incremental = false; 18150b57cec5SDimitry Andric } 18160b57cec5SDimitry Andric 18170b57cec5SDimitry Andric if (errorCount()) 18180b57cec5SDimitry Andric return; 18190b57cec5SDimitry Andric 18200b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 18210b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 18220b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 18230b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 18240b57cec5SDimitry Andric wholeArchives.insert(*id); 18250b57cec5SDimitry Andric 18260b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 18270b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 18280b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 18290b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 18300b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 18310b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 18320b57cec5SDimitry Andric return true; 18330b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 18340b57cec5SDimitry Andric return wholeArchives.count(*id); 18350b57cec5SDimitry Andric return false; 18360b57cec5SDimitry Andric }; 18370b57cec5SDimitry Andric 183885868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 183985868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 184085868e8aSDimitry Andric // and OPT_end_lib. 184185868e8aSDimitry Andric bool inLib = false; 184285868e8aSDimitry Andric for (auto *arg : args) { 184385868e8aSDimitry Andric switch (arg->getOption().getID()) { 184485868e8aSDimitry Andric case OPT_end_lib: 184585868e8aSDimitry Andric if (!inLib) 184685868e8aSDimitry Andric error("stray " + arg->getSpelling()); 184785868e8aSDimitry Andric inLib = false; 184885868e8aSDimitry Andric break; 184985868e8aSDimitry Andric case OPT_start_lib: 185085868e8aSDimitry Andric if (inLib) 185185868e8aSDimitry Andric error("nested " + arg->getSpelling()); 185285868e8aSDimitry Andric inLib = true; 185385868e8aSDimitry Andric break; 185485868e8aSDimitry Andric case OPT_wholearchive_file: 18550b57cec5SDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 185685868e8aSDimitry Andric enqueuePath(*path, true, inLib); 185785868e8aSDimitry Andric break; 185885868e8aSDimitry Andric case OPT_INPUT: 185985868e8aSDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 186085868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 186185868e8aSDimitry Andric break; 186285868e8aSDimitry Andric default: 186385868e8aSDimitry Andric // Ignore other options. 186485868e8aSDimitry Andric break; 186585868e8aSDimitry Andric } 186685868e8aSDimitry Andric } 18670b57cec5SDimitry Andric 186885868e8aSDimitry Andric // Process files specified as /defaultlib. These should be enequeued after 186985868e8aSDimitry Andric // other files, which is why they are in a separate loop. 18700b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 18710b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 187285868e8aSDimitry Andric enqueuePath(*path, false, false); 18730b57cec5SDimitry Andric 18740b57cec5SDimitry Andric // Windows specific -- Create a resource file containing a manifest file. 18750b57cec5SDimitry Andric if (config->manifest == Configuration::Embed) 187685868e8aSDimitry Andric addBuffer(createManifestRes(), false, false); 18770b57cec5SDimitry Andric 18780b57cec5SDimitry Andric // Read all input files given via the command line. 18790b57cec5SDimitry Andric run(); 18800b57cec5SDimitry Andric 18810b57cec5SDimitry Andric if (errorCount()) 18820b57cec5SDimitry Andric return; 18830b57cec5SDimitry Andric 18840b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 18850b57cec5SDimitry Andric // not we assume x64. 18860b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 18870b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 18880b57cec5SDimitry Andric config->machine = AMD64; 18890b57cec5SDimitry Andric } 18900b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 18910b57cec5SDimitry Andric 18920b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 1893979e22ffSDimitry Andric if (config->machine == I386) { 1894979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1895979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 1896979e22ffSDimitry Andric } 18970b57cec5SDimitry Andric 18980b57cec5SDimitry Andric // Handle /functionpadmin 18990b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 19000b57cec5SDimitry Andric parseFunctionPadMin(arg, config->machine); 19010b57cec5SDimitry Andric 19020b57cec5SDimitry Andric if (tar) 19030b57cec5SDimitry Andric tar->append("response.txt", 19040b57cec5SDimitry Andric createResponseFile(args, filePaths, 19050b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 19060b57cec5SDimitry Andric 19070b57cec5SDimitry Andric // Handle /largeaddressaware 19080b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 19090b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 19100b57cec5SDimitry Andric 19110b57cec5SDimitry Andric // Handle /highentropyva 19120b57cec5SDimitry Andric config->highEntropyVA = 19130b57cec5SDimitry Andric config->is64() && 19140b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 19150b57cec5SDimitry Andric 19160b57cec5SDimitry Andric if (!config->dynamicBase && 19170b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 19180b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 19190b57cec5SDimitry Andric machineToStr(config->machine)); 19200b57cec5SDimitry Andric 19210b57cec5SDimitry Andric // Handle /export 19220b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 19230b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 19240b57cec5SDimitry Andric if (config->machine == I386) { 19250b57cec5SDimitry Andric if (!isDecorated(e.name)) 19260b57cec5SDimitry Andric e.name = saver.save("_" + e.name); 19270b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 19280b57cec5SDimitry Andric e.extName = saver.save("_" + e.extName); 19290b57cec5SDimitry Andric } 19300b57cec5SDimitry Andric config->exports.push_back(e); 19310b57cec5SDimitry Andric } 19320b57cec5SDimitry Andric 19330b57cec5SDimitry Andric // Handle /def 19340b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 19350b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 19360b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 19370b57cec5SDimitry Andric } 19380b57cec5SDimitry Andric 19390b57cec5SDimitry Andric // Handle generation of import library from a def file. 1940480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 19410b57cec5SDimitry Andric fixupExports(); 19420b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 19430b57cec5SDimitry Andric return; 19440b57cec5SDimitry Andric } 19450b57cec5SDimitry Andric 19460b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 19470b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 19480b57cec5SDimitry Andric // and after the early return when just writing an import library. 19490b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 19500b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 19510b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 19520b57cec5SDimitry Andric fatal("subsystem must be defined"); 19530b57cec5SDimitry Andric } 19540b57cec5SDimitry Andric 19550b57cec5SDimitry Andric // Handle /entry and /dll 19560b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 19570b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 19580b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 19590b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 19600b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 19610b57cec5SDimitry Andric : "_DllMainCRTStartup"; 19620b57cec5SDimitry Andric config->entry = addUndefined(s); 1963480093f4SDimitry Andric } else if (config->driverWdm) { 1964480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 1965480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 19660b57cec5SDimitry Andric } else { 19670b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 19680b57cec5SDimitry Andric // infer that from user-defined entry name. 19690b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 19700b57cec5SDimitry Andric if (s.empty()) 19710b57cec5SDimitry Andric fatal("entry point must be defined"); 19720b57cec5SDimitry Andric config->entry = addUndefined(s); 19730b57cec5SDimitry Andric log("Entry name inferred: " + s); 19740b57cec5SDimitry Andric } 19750b57cec5SDimitry Andric } 19760b57cec5SDimitry Andric 19770b57cec5SDimitry Andric // Handle /delayload 19780b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 19790b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 19800b57cec5SDimitry Andric if (config->machine == I386) { 19810b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 19820b57cec5SDimitry Andric } else { 19830b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 19840b57cec5SDimitry Andric } 19850b57cec5SDimitry Andric } 19860b57cec5SDimitry Andric 19870b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 19880b57cec5SDimitry Andric if (config->outputFile.empty()) { 1989480093f4SDimitry Andric config->outputFile = getOutputPath( 1990480093f4SDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 19910b57cec5SDimitry Andric } 19920b57cec5SDimitry Andric 19930b57cec5SDimitry Andric // Fail early if an output file is not writable. 19940b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 19950b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 19960b57cec5SDimitry Andric return; 19970b57cec5SDimitry Andric } 19980b57cec5SDimitry Andric 19990b57cec5SDimitry Andric if (shouldCreatePDB) { 20000b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 20010b57cec5SDimitry Andric if (config->pdbPath.empty()) { 20020b57cec5SDimitry Andric config->pdbPath = config->outputFile; 20030b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 20040b57cec5SDimitry Andric } 20050b57cec5SDimitry Andric 20060b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 20070b57cec5SDimitry Andric // /pdbaltpath flag was passed. 20080b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 20090b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 20100b57cec5SDimitry Andric 20110b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 20120b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 20130b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 20140b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 20150b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 20160b57cec5SDimitry Andric } else { 20170b57cec5SDimitry Andric // Don't do this earlier, so that Config->OutputFile is ready. 20180b57cec5SDimitry Andric parsePDBAltPath(config->pdbAltPath); 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric } 20210b57cec5SDimitry Andric 20220b57cec5SDimitry Andric // Set default image base if /base is not given. 20230b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 20240b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 20250b57cec5SDimitry Andric 20260b57cec5SDimitry Andric symtab->addSynthetic(mangle("__ImageBase"), nullptr); 20270b57cec5SDimitry Andric if (config->machine == I386) { 20280b57cec5SDimitry Andric symtab->addAbsolute("___safe_se_handler_table", 0); 20290b57cec5SDimitry Andric symtab->addAbsolute("___safe_se_handler_count", 0); 20300b57cec5SDimitry Andric } 20310b57cec5SDimitry Andric 20320b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_fids_count"), 0); 20330b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_fids_table"), 0); 20340b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_flags"), 0); 20350b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_iat_count"), 0); 20360b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_iat_table"), 0); 20370b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_longjmp_count"), 0); 20380b57cec5SDimitry Andric symtab->addAbsolute(mangle("__guard_longjmp_table"), 0); 20390b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 20400b57cec5SDimitry Andric symtab->addAbsolute(mangle("__enclave_config"), 0); 2041*fe6060f1SDimitry Andric // Needed for MSVC 2019 16.8 CRT. 2042*fe6060f1SDimitry Andric symtab->addAbsolute(mangle("__guard_eh_cont_count"), 0); 2043*fe6060f1SDimitry Andric symtab->addAbsolute(mangle("__guard_eh_cont_table"), 0); 20440b57cec5SDimitry Andric 20455ffd83dbSDimitry Andric if (config->pseudoRelocs) { 20460b57cec5SDimitry Andric symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 20470b57cec5SDimitry Andric symtab->addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 20485ffd83dbSDimitry Andric } 20495ffd83dbSDimitry Andric if (config->mingw) { 20500b57cec5SDimitry Andric symtab->addAbsolute(mangle("__CTOR_LIST__"), 0); 20510b57cec5SDimitry Andric symtab->addAbsolute(mangle("__DTOR_LIST__"), 0); 20520b57cec5SDimitry Andric } 20530b57cec5SDimitry Andric 20540b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 20550b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 20560b57cec5SDimitry Andric // converge. 20570b57cec5SDimitry Andric do { 20580b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 20590b57cec5SDimitry Andric // search for its mangled names. 20600b57cec5SDimitry Andric if (config->entry) 20610b57cec5SDimitry Andric mangleMaybe(config->entry); 20620b57cec5SDimitry Andric 20630b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 20640b57cec5SDimitry Andric for (Export &e : config->exports) { 20650b57cec5SDimitry Andric if (!e.forwardTo.empty()) 20660b57cec5SDimitry Andric continue; 20670b57cec5SDimitry Andric e.sym = addUndefined(e.name); 20680b57cec5SDimitry Andric if (!e.directives) 20690b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 20700b57cec5SDimitry Andric } 20710b57cec5SDimitry Andric 20720b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 20730b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 20740b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 20750b57cec5SDimitry Andric StringRef from = pair.first; 20760b57cec5SDimitry Andric StringRef to = pair.second; 20770b57cec5SDimitry Andric Symbol *sym = symtab->find(from); 20780b57cec5SDimitry Andric if (!sym) 20790b57cec5SDimitry Andric continue; 20800b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 20810b57cec5SDimitry Andric if (!u->weakAlias) 20820b57cec5SDimitry Andric u->weakAlias = symtab->addUndefined(to); 20830b57cec5SDimitry Andric } 20840b57cec5SDimitry Andric 20850b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 20860b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 20870b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 20880b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 20890b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 20900b57cec5SDimitry Andric if (!BitcodeFile::instances.empty()) 209185868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 20920b57cec5SDimitry Andric symtab->addLibcall(s); 20930b57cec5SDimitry Andric 20940b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 20950b57cec5SDimitry Andric if (symtab->findUnderscore("_load_config_used")) 20960b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 20970b57cec5SDimitry Andric } while (run()); 20980b57cec5SDimitry Andric 20990b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 21000b57cec5SDimitry Andric // Handle /includeoptional 21010b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 210285868e8aSDimitry Andric if (dyn_cast_or_null<LazyArchive>(symtab->find(arg->getValue()))) 21030b57cec5SDimitry Andric addUndefined(arg->getValue()); 21040b57cec5SDimitry Andric while (run()); 21050b57cec5SDimitry Andric } 21060b57cec5SDimitry Andric 2107e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2108e8d8bef9SDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(args); 2109e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2110e8d8bef9SDimitry Andric if (!wrapped.empty()) 2111e8d8bef9SDimitry Andric while (run()); 2112e8d8bef9SDimitry Andric 2113*fe6060f1SDimitry Andric if (config->autoImport || config->stdcallFixup) { 21145ffd83dbSDimitry Andric // MinGW specific. 21150b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 2116*fe6060f1SDimitry Andric // imports, and do stdcall fixups. 21170b57cec5SDimitry Andric // 21180b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 21190b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 21200b57cec5SDimitry Andric // 21210b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 21220b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 21230b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 21240b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 21250b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 21260b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 21270b57cec5SDimitry Andric // we won't iterate further to resolve them. 2128*fe6060f1SDimitry Andric // 2129*fe6060f1SDimitry Andric // If stdcall fixups only are needed for loading import entries from 2130*fe6060f1SDimitry Andric // a DLL without import library, this also just needs running once. 2131*fe6060f1SDimitry Andric // If it ends up pulling in more object files from static libraries, 2132*fe6060f1SDimitry Andric // (and maybe doing more stdcall fixups along the way), this would need 2133*fe6060f1SDimitry Andric // to loop these two calls. 2134*fe6060f1SDimitry Andric symtab->loadMinGWSymbols(); 21350b57cec5SDimitry Andric run(); 21360b57cec5SDimitry Andric } 21370b57cec5SDimitry Andric 213885868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 213985868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 214085868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 214185868e8aSDimitry Andric // will fail to link anyway. 214285868e8aSDimitry Andric if (!BitcodeFile::instances.empty() && !config->forceUnresolved) 214385868e8aSDimitry Andric symtab->reportUnresolvable(); 21440b57cec5SDimitry Andric if (errorCount()) 21450b57cec5SDimitry Andric return; 21460b57cec5SDimitry Andric 2147*fe6060f1SDimitry Andric config->hadExplicitExports = !config->exports.empty(); 2148*fe6060f1SDimitry Andric if (config->mingw) { 2149*fe6060f1SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 2150*fe6060f1SDimitry Andric // are chosen to be exported. 2151*fe6060f1SDimitry Andric maybeExportMinGWSymbols(args); 2152*fe6060f1SDimitry Andric } 2153*fe6060f1SDimitry Andric 215485868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 215585868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 215685868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 215785868e8aSDimitry Andric symtab->addCombinedLTOObjects(); 215885868e8aSDimitry Andric 215985868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 216085868e8aSDimitry Andric // files" and not object files. Index file creation is already done 216185868e8aSDimitry Andric // in addCombinedLTOObject, so we are done if that's the case. 216285868e8aSDimitry Andric if (config->thinLTOIndexOnly) 216385868e8aSDimitry Andric return; 216485868e8aSDimitry Andric 216585868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 216685868e8aSDimitry Andric // references to the symbols we use from them. 216785868e8aSDimitry Andric run(); 216885868e8aSDimitry Andric 2169e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2170e8d8bef9SDimitry Andric if (!wrapped.empty()) 2171e8d8bef9SDimitry Andric wrapSymbols(wrapped); 2172e8d8bef9SDimitry Andric 217385868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 217485868e8aSDimitry Andric symtab->resolveRemainingUndefines(); 217585868e8aSDimitry Andric if (errorCount()) 217685868e8aSDimitry Andric return; 217785868e8aSDimitry Andric 21780b57cec5SDimitry Andric if (config->mingw) { 21790b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 21800b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 21810b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 21820b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 21830b57cec5SDimitry Andric // files from static libraries only after the last object file on the 21840b57cec5SDimitry Andric // command line. 21850b57cec5SDimitry Andric for (auto i = ObjFile::instances.begin(), e = ObjFile::instances.end(); 21860b57cec5SDimitry Andric i != e; i++) { 21870b57cec5SDimitry Andric ObjFile *file = *i; 21880b57cec5SDimitry Andric if (isCrtend(file->getName())) { 21890b57cec5SDimitry Andric ObjFile::instances.erase(i); 21900b57cec5SDimitry Andric ObjFile::instances.push_back(file); 21910b57cec5SDimitry Andric break; 21920b57cec5SDimitry Andric } 21930b57cec5SDimitry Andric } 21940b57cec5SDimitry Andric } 21950b57cec5SDimitry Andric 21960b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 219785868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 219885868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 21990b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 22000b57cec5SDimitry Andric fixupExports(); 220185868e8aSDimitry Andric if (!config->mingw || !config->implib.empty()) 22020b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 22030b57cec5SDimitry Andric assignExportOrdinals(); 22040b57cec5SDimitry Andric } 22050b57cec5SDimitry Andric 22060b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 22070b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 22080b57cec5SDimitry Andric writeDefFile(arg->getValue()); 22090b57cec5SDimitry Andric 22100b57cec5SDimitry Andric // Set extra alignment for .comm symbols 22110b57cec5SDimitry Andric for (auto pair : config->alignComm) { 22120b57cec5SDimitry Andric StringRef name = pair.first; 22130b57cec5SDimitry Andric uint32_t alignment = pair.second; 22140b57cec5SDimitry Andric 22150b57cec5SDimitry Andric Symbol *sym = symtab->find(name); 22160b57cec5SDimitry Andric if (!sym) { 22170b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 22180b57cec5SDimitry Andric continue; 22190b57cec5SDimitry Andric } 22200b57cec5SDimitry Andric 22210b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 22220b57cec5SDimitry Andric // symbol, which will carry its own alignment. 22230b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 22240b57cec5SDimitry Andric if (!dc) 22250b57cec5SDimitry Andric continue; 22260b57cec5SDimitry Andric 22270b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 22280b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 22290b57cec5SDimitry Andric } 22300b57cec5SDimitry Andric 22310b57cec5SDimitry Andric // Windows specific -- Create a side-by-side manifest file. 22320b57cec5SDimitry Andric if (config->manifest == Configuration::SideBySide) 22330b57cec5SDimitry Andric createSideBySideManifest(); 22340b57cec5SDimitry Andric 22350b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 22360b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 22370b57cec5SDimitry Andric // functions. 2238e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2239e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2240e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 22410b57cec5SDimitry Andric parseOrderFile(arg->getValue()); 2242e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2243e8d8bef9SDimitry Andric } 2244e8d8bef9SDimitry Andric 2245e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2246e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2247e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2248e8d8bef9SDimitry Andric parseCallGraphFile(arg->getValue()); 2249e8d8bef9SDimitry Andric } 2250e8d8bef9SDimitry Andric readCallGraphsFromObjectFiles(); 2251e8d8bef9SDimitry Andric } 2252e8d8bef9SDimitry Andric 2253e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2254e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2255e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 22560b57cec5SDimitry Andric 22570b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 2258*fe6060f1SDimitry Andric if (config->doGC) { 2259*fe6060f1SDimitry Andric if (config->mingw) { 2260*fe6060f1SDimitry Andric // markLive doesn't traverse .eh_frame, but the personality function is 2261*fe6060f1SDimitry Andric // only reached that way. The proper solution would be to parse and 2262*fe6060f1SDimitry Andric // traverse the .eh_frame section, like the ELF linker does. 2263*fe6060f1SDimitry Andric // For now, just manually try to retain the known possible personality 2264*fe6060f1SDimitry Andric // functions. This doesn't bring in more object files, but only marks 2265*fe6060f1SDimitry Andric // functions that already have been included to be retained. 2266*fe6060f1SDimitry Andric for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2267*fe6060f1SDimitry Andric Defined *d = dyn_cast_or_null<Defined>(symtab->findUnderscore(n)); 2268*fe6060f1SDimitry Andric if (d && !d->isGCRoot) { 2269*fe6060f1SDimitry Andric d->isGCRoot = true; 2270*fe6060f1SDimitry Andric config->gcroot.push_back(d); 2271*fe6060f1SDimitry Andric } 2272*fe6060f1SDimitry Andric } 2273*fe6060f1SDimitry Andric } 2274*fe6060f1SDimitry Andric 22750b57cec5SDimitry Andric markLive(symtab->getChunks()); 2276*fe6060f1SDimitry Andric } 22770b57cec5SDimitry Andric 22780b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 227985868e8aSDimitry Andric convertResources(); 22800b57cec5SDimitry Andric 22810b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 2282*fe6060f1SDimitry Andric if (config->doICF != ICFLevel::None) { 22830b57cec5SDimitry Andric findKeepUniqueSections(); 2284*fe6060f1SDimitry Andric doICF(symtab->getChunks(), config->doICF); 22850b57cec5SDimitry Andric } 22860b57cec5SDimitry Andric 22870b57cec5SDimitry Andric // Write the result. 22880b57cec5SDimitry Andric writeResult(); 22890b57cec5SDimitry Andric 22900b57cec5SDimitry Andric // Stop early so we can print the results. 22915ffd83dbSDimitry Andric rootTimer.stop(); 22920b57cec5SDimitry Andric if (config->showTiming) 22930b57cec5SDimitry Andric Timer::root().print(); 22940b57cec5SDimitry Andric } 22950b57cec5SDimitry Andric 22960b57cec5SDimitry Andric } // namespace coff 22970b57cec5SDimitry Andric } // namespace lld 2298