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" 10349cc55cSDimitry Andric #include "COFFLinkerContext.h" 110b57cec5SDimitry Andric #include "Config.h" 120b57cec5SDimitry Andric #include "DebugTypes.h" 130b57cec5SDimitry Andric #include "ICF.h" 140b57cec5SDimitry Andric #include "InputFiles.h" 150b57cec5SDimitry Andric #include "MarkLive.h" 160b57cec5SDimitry Andric #include "MinGW.h" 170b57cec5SDimitry Andric #include "SymbolTable.h" 180b57cec5SDimitry Andric #include "Symbols.h" 190b57cec5SDimitry Andric #include "Writer.h" 200b57cec5SDimitry Andric #include "lld/Common/Args.h" 210b57cec5SDimitry Andric #include "lld/Common/Driver.h" 220b57cec5SDimitry Andric #include "lld/Common/Filesystem.h" 230b57cec5SDimitry Andric #include "lld/Common/Timer.h" 240b57cec5SDimitry Andric #include "lld/Common/Version.h" 250b57cec5SDimitry Andric #include "llvm/ADT/Optional.h" 260b57cec5SDimitry Andric #include "llvm/ADT/StringSwitch.h" 270b57cec5SDimitry Andric #include "llvm/BinaryFormat/Magic.h" 28e8d8bef9SDimitry Andric #include "llvm/Config/llvm-config.h" 2985868e8aSDimitry Andric #include "llvm/LTO/LTO.h" 300b57cec5SDimitry Andric #include "llvm/Object/ArchiveWriter.h" 310b57cec5SDimitry Andric #include "llvm/Object/COFFImportFile.h" 320b57cec5SDimitry Andric #include "llvm/Object/COFFModuleDefinition.h" 330b57cec5SDimitry Andric #include "llvm/Object/WindowsMachineFlag.h" 340b57cec5SDimitry Andric #include "llvm/Option/Arg.h" 350b57cec5SDimitry Andric #include "llvm/Option/ArgList.h" 360b57cec5SDimitry Andric #include "llvm/Option/Option.h" 37e8d8bef9SDimitry Andric #include "llvm/Support/BinaryStreamReader.h" 38480093f4SDimitry Andric #include "llvm/Support/CommandLine.h" 390b57cec5SDimitry Andric #include "llvm/Support/Debug.h" 400b57cec5SDimitry Andric #include "llvm/Support/LEB128.h" 410b57cec5SDimitry Andric #include "llvm/Support/MathExtras.h" 425ffd83dbSDimitry Andric #include "llvm/Support/Parallel.h" 430b57cec5SDimitry Andric #include "llvm/Support/Path.h" 440b57cec5SDimitry Andric #include "llvm/Support/Process.h" 450b57cec5SDimitry Andric #include "llvm/Support/TarWriter.h" 460b57cec5SDimitry Andric #include "llvm/Support/TargetSelect.h" 470b57cec5SDimitry Andric #include "llvm/Support/raw_ostream.h" 480b57cec5SDimitry Andric #include "llvm/ToolDrivers/llvm-lib/LibDriver.h" 490b57cec5SDimitry Andric #include <algorithm> 500b57cec5SDimitry Andric #include <future> 510b57cec5SDimitry Andric #include <memory> 520b57cec5SDimitry Andric 530b57cec5SDimitry Andric using namespace llvm; 540b57cec5SDimitry Andric using namespace llvm::object; 550b57cec5SDimitry Andric using namespace llvm::COFF; 56fe6060f1SDimitry Andric using namespace llvm::sys; 570b57cec5SDimitry Andric 580b57cec5SDimitry Andric namespace lld { 590b57cec5SDimitry Andric namespace coff { 600b57cec5SDimitry Andric 61*04eeddc0SDimitry Andric std::unique_ptr<Configuration> config; 62*04eeddc0SDimitry Andric std::unique_ptr<LinkerDriver> driver; 630b57cec5SDimitry Andric 64*04eeddc0SDimitry Andric bool link(ArrayRef<const char *> args, llvm::raw_ostream &stdoutOS, 65*04eeddc0SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) { 66*04eeddc0SDimitry Andric // This driver-specific context will be freed later by lldMain(). 67*04eeddc0SDimitry Andric auto *ctx = new COFFLinkerContext; 68480093f4SDimitry Andric 69*04eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 70*04eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(args[0]); 71*04eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now" 720b57cec5SDimitry Andric " (use /errorlimit:0 to see all errors)"; 7385868e8aSDimitry Andric 74*04eeddc0SDimitry Andric config = std::make_unique<Configuration>(); 75*04eeddc0SDimitry Andric driver = std::make_unique<LinkerDriver>(*ctx); 7685868e8aSDimitry Andric 77e8d8bef9SDimitry Andric driver->linkerMain(args); 780b57cec5SDimitry Andric 79*04eeddc0SDimitry Andric return errorCount() == 0; 800b57cec5SDimitry Andric } 810b57cec5SDimitry Andric 820b57cec5SDimitry Andric // Parse options of the form "old;new". 830b57cec5SDimitry Andric static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args, 840b57cec5SDimitry Andric unsigned id) { 850b57cec5SDimitry Andric auto *arg = args.getLastArg(id); 860b57cec5SDimitry Andric if (!arg) 870b57cec5SDimitry Andric return {"", ""}; 880b57cec5SDimitry Andric 890b57cec5SDimitry Andric StringRef s = arg->getValue(); 900b57cec5SDimitry Andric std::pair<StringRef, StringRef> ret = s.split(';'); 910b57cec5SDimitry Andric if (ret.second.empty()) 920b57cec5SDimitry Andric error(arg->getSpelling() + " expects 'old;new' format, but got " + s); 930b57cec5SDimitry Andric return ret; 940b57cec5SDimitry Andric } 950b57cec5SDimitry Andric 96480093f4SDimitry Andric // Drop directory components and replace extension with 97480093f4SDimitry Andric // ".exe", ".dll" or ".sys". 980b57cec5SDimitry Andric static std::string getOutputPath(StringRef path) { 99480093f4SDimitry Andric StringRef ext = ".exe"; 100480093f4SDimitry Andric if (config->dll) 101480093f4SDimitry Andric ext = ".dll"; 102480093f4SDimitry Andric else if (config->driver) 103480093f4SDimitry Andric ext = ".sys"; 104480093f4SDimitry Andric 105480093f4SDimitry Andric return (sys::path::stem(path) + ext).str(); 1060b57cec5SDimitry Andric } 1070b57cec5SDimitry Andric 1080b57cec5SDimitry Andric // Returns true if S matches /crtend.?\.o$/. 1090b57cec5SDimitry Andric static bool isCrtend(StringRef s) { 1100b57cec5SDimitry Andric if (!s.endswith(".o")) 1110b57cec5SDimitry Andric return false; 1120b57cec5SDimitry Andric s = s.drop_back(2); 1130b57cec5SDimitry Andric if (s.endswith("crtend")) 1140b57cec5SDimitry Andric return true; 1150b57cec5SDimitry Andric return !s.empty() && s.drop_back().endswith("crtend"); 1160b57cec5SDimitry Andric } 1170b57cec5SDimitry Andric 1180b57cec5SDimitry Andric // ErrorOr is not default constructible, so it cannot be used as the type 1190b57cec5SDimitry Andric // parameter of a future. 1200b57cec5SDimitry Andric // FIXME: We could open the file in createFutureForFile and avoid needing to 1210b57cec5SDimitry Andric // return an error here, but for the moment that would cost us a file descriptor 1220b57cec5SDimitry Andric // (a limited resource on Windows) for the duration that the future is pending. 1230b57cec5SDimitry Andric using MBErrPair = std::pair<std::unique_ptr<MemoryBuffer>, std::error_code>; 1240b57cec5SDimitry Andric 1250b57cec5SDimitry Andric // Create a std::future that opens and maps a file using the best strategy for 1260b57cec5SDimitry Andric // the host platform. 1270b57cec5SDimitry Andric static std::future<MBErrPair> createFutureForFile(std::string path) { 128fe6060f1SDimitry Andric #if _WIN64 1290b57cec5SDimitry Andric // On Windows, file I/O is relatively slow so it is best to do this 130fe6060f1SDimitry Andric // asynchronously. But 32-bit has issues with potentially launching tons 131fe6060f1SDimitry Andric // of threads 1320b57cec5SDimitry Andric auto strategy = std::launch::async; 1330b57cec5SDimitry Andric #else 1340b57cec5SDimitry Andric auto strategy = std::launch::deferred; 1350b57cec5SDimitry Andric #endif 1360b57cec5SDimitry Andric return std::async(strategy, [=]() { 137fe6060f1SDimitry Andric auto mbOrErr = MemoryBuffer::getFile(path, /*IsText=*/false, 138fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false); 1390b57cec5SDimitry Andric if (!mbOrErr) 1400b57cec5SDimitry Andric return MBErrPair{nullptr, mbOrErr.getError()}; 1410b57cec5SDimitry Andric return MBErrPair{std::move(*mbOrErr), std::error_code()}; 1420b57cec5SDimitry Andric }); 1430b57cec5SDimitry Andric } 1440b57cec5SDimitry Andric 1450b57cec5SDimitry Andric // Symbol names are mangled by prepending "_" on x86. 1460b57cec5SDimitry Andric static StringRef mangle(StringRef sym) { 1470b57cec5SDimitry Andric assert(config->machine != IMAGE_FILE_MACHINE_UNKNOWN); 1480b57cec5SDimitry Andric if (config->machine == I386) 149*04eeddc0SDimitry Andric return saver().save("_" + sym); 1500b57cec5SDimitry Andric return sym; 1510b57cec5SDimitry Andric } 1520b57cec5SDimitry Andric 153349cc55cSDimitry Andric bool LinkerDriver::findUnderscoreMangle(StringRef sym) { 154349cc55cSDimitry Andric Symbol *s = ctx.symtab.findMangle(mangle(sym)); 1550b57cec5SDimitry Andric return s && !isa<Undefined>(s); 1560b57cec5SDimitry Andric } 1570b57cec5SDimitry Andric 1580b57cec5SDimitry Andric MemoryBufferRef LinkerDriver::takeBuffer(std::unique_ptr<MemoryBuffer> mb) { 1590b57cec5SDimitry Andric MemoryBufferRef mbref = *mb; 1600b57cec5SDimitry Andric make<std::unique_ptr<MemoryBuffer>>(std::move(mb)); // take ownership 1610b57cec5SDimitry Andric 1620b57cec5SDimitry Andric if (driver->tar) 1630b57cec5SDimitry Andric driver->tar->append(relativeToRoot(mbref.getBufferIdentifier()), 1640b57cec5SDimitry Andric mbref.getBuffer()); 1650b57cec5SDimitry Andric return mbref; 1660b57cec5SDimitry Andric } 1670b57cec5SDimitry Andric 1680b57cec5SDimitry Andric void LinkerDriver::addBuffer(std::unique_ptr<MemoryBuffer> mb, 16985868e8aSDimitry Andric bool wholeArchive, bool lazy) { 1700b57cec5SDimitry Andric StringRef filename = mb->getBufferIdentifier(); 1710b57cec5SDimitry Andric 1720b57cec5SDimitry Andric MemoryBufferRef mbref = takeBuffer(std::move(mb)); 1730b57cec5SDimitry Andric filePaths.push_back(filename); 1740b57cec5SDimitry Andric 1750b57cec5SDimitry Andric // File type is detected by contents, not by file extension. 1760b57cec5SDimitry Andric switch (identify_magic(mbref.getBuffer())) { 1770b57cec5SDimitry Andric case file_magic::windows_resource: 1780b57cec5SDimitry Andric resources.push_back(mbref); 1790b57cec5SDimitry Andric break; 1800b57cec5SDimitry Andric case file_magic::archive: 1810b57cec5SDimitry Andric if (wholeArchive) { 1820b57cec5SDimitry Andric std::unique_ptr<Archive> file = 1830b57cec5SDimitry Andric CHECK(Archive::create(mbref), filename + ": failed to parse archive"); 1840b57cec5SDimitry Andric Archive *archive = file.get(); 1850b57cec5SDimitry Andric make<std::unique_ptr<Archive>>(std::move(file)); // take ownership 1860b57cec5SDimitry Andric 18785868e8aSDimitry Andric int memberIndex = 0; 1880b57cec5SDimitry Andric for (MemoryBufferRef m : getArchiveMembers(archive)) 18985868e8aSDimitry Andric addArchiveBuffer(m, "<whole-archive>", filename, memberIndex++); 1900b57cec5SDimitry Andric return; 1910b57cec5SDimitry Andric } 192349cc55cSDimitry Andric ctx.symtab.addFile(make<ArchiveFile>(ctx, mbref)); 1930b57cec5SDimitry Andric break; 1940b57cec5SDimitry Andric case file_magic::bitcode: 195*04eeddc0SDimitry Andric ctx.symtab.addFile(make<BitcodeFile>(ctx, mbref, "", 0, lazy)); 1960b57cec5SDimitry Andric break; 1970b57cec5SDimitry Andric case file_magic::coff_object: 1980b57cec5SDimitry Andric case file_magic::coff_import_library: 199*04eeddc0SDimitry Andric ctx.symtab.addFile(make<ObjFile>(ctx, mbref, lazy)); 2000b57cec5SDimitry Andric break; 2010b57cec5SDimitry Andric case file_magic::pdb: 202349cc55cSDimitry Andric ctx.symtab.addFile(make<PDBInputFile>(ctx, mbref)); 2030b57cec5SDimitry Andric break; 2040b57cec5SDimitry Andric case file_magic::coff_cl_gl_object: 2050b57cec5SDimitry Andric error(filename + ": is not a native COFF file. Recompile without /GL"); 2060b57cec5SDimitry Andric break; 2070b57cec5SDimitry Andric case file_magic::pecoff_executable: 208fe6060f1SDimitry Andric if (config->mingw) { 209349cc55cSDimitry Andric ctx.symtab.addFile(make<DLLFile>(ctx, mbref)); 210fe6060f1SDimitry Andric break; 211fe6060f1SDimitry Andric } 212fe6060f1SDimitry Andric if (filename.endswith_insensitive(".dll")) { 2130b57cec5SDimitry Andric error(filename + ": bad file type. Did you specify a DLL instead of an " 2140b57cec5SDimitry Andric "import library?"); 2150b57cec5SDimitry Andric break; 2160b57cec5SDimitry Andric } 2170b57cec5SDimitry Andric LLVM_FALLTHROUGH; 2180b57cec5SDimitry Andric default: 2190b57cec5SDimitry Andric error(mbref.getBufferIdentifier() + ": unknown file type"); 2200b57cec5SDimitry Andric break; 2210b57cec5SDimitry Andric } 2220b57cec5SDimitry Andric } 2230b57cec5SDimitry Andric 22485868e8aSDimitry Andric void LinkerDriver::enqueuePath(StringRef path, bool wholeArchive, bool lazy) { 2255ffd83dbSDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 2265ffd83dbSDimitry Andric createFutureForFile(std::string(path))); 2275ffd83dbSDimitry Andric std::string pathStr = std::string(path); 2280b57cec5SDimitry Andric enqueueTask([=]() { 2290b57cec5SDimitry Andric auto mbOrErr = future->get(); 2300b57cec5SDimitry Andric if (mbOrErr.second) { 2310b57cec5SDimitry Andric std::string msg = 2320b57cec5SDimitry Andric "could not open '" + pathStr + "': " + mbOrErr.second.message(); 2330b57cec5SDimitry Andric // Check if the filename is a typo for an option flag. OptTable thinks 2340b57cec5SDimitry Andric // that all args that are not known options and that start with / are 2350b57cec5SDimitry Andric // filenames, but e.g. `/nodefaultlibs` is more likely a typo for 2360b57cec5SDimitry Andric // the option `/nodefaultlib` than a reference to a file in the root 2370b57cec5SDimitry Andric // directory. 2380b57cec5SDimitry Andric std::string nearest; 2395ffd83dbSDimitry Andric if (optTable.findNearest(pathStr, nearest) > 1) 2400b57cec5SDimitry Andric error(msg); 2410b57cec5SDimitry Andric else 2420b57cec5SDimitry Andric error(msg + "; did you mean '" + nearest + "'"); 2430b57cec5SDimitry Andric } else 24485868e8aSDimitry Andric driver->addBuffer(std::move(mbOrErr.first), wholeArchive, lazy); 2450b57cec5SDimitry Andric }); 2460b57cec5SDimitry Andric } 2470b57cec5SDimitry Andric 2480b57cec5SDimitry Andric void LinkerDriver::addArchiveBuffer(MemoryBufferRef mb, StringRef symName, 2490b57cec5SDimitry Andric StringRef parentName, 2500b57cec5SDimitry Andric uint64_t offsetInArchive) { 2510b57cec5SDimitry Andric file_magic magic = identify_magic(mb.getBuffer()); 2520b57cec5SDimitry Andric if (magic == file_magic::coff_import_library) { 253349cc55cSDimitry Andric InputFile *imp = make<ImportFile>(ctx, mb); 2540b57cec5SDimitry Andric imp->parentName = parentName; 255349cc55cSDimitry Andric ctx.symtab.addFile(imp); 2560b57cec5SDimitry Andric return; 2570b57cec5SDimitry Andric } 2580b57cec5SDimitry Andric 2590b57cec5SDimitry Andric InputFile *obj; 2600b57cec5SDimitry Andric if (magic == file_magic::coff_object) { 261349cc55cSDimitry Andric obj = make<ObjFile>(ctx, mb); 2620b57cec5SDimitry Andric } else if (magic == file_magic::bitcode) { 263*04eeddc0SDimitry Andric obj = 264*04eeddc0SDimitry Andric make<BitcodeFile>(ctx, mb, parentName, offsetInArchive, /*lazy=*/false); 2650b57cec5SDimitry Andric } else { 2660b57cec5SDimitry Andric error("unknown file type: " + mb.getBufferIdentifier()); 2670b57cec5SDimitry Andric return; 2680b57cec5SDimitry Andric } 2690b57cec5SDimitry Andric 2700b57cec5SDimitry Andric obj->parentName = parentName; 271349cc55cSDimitry Andric ctx.symtab.addFile(obj); 2720b57cec5SDimitry Andric log("Loaded " + toString(obj) + " for " + symName); 2730b57cec5SDimitry Andric } 2740b57cec5SDimitry Andric 2750b57cec5SDimitry Andric void LinkerDriver::enqueueArchiveMember(const Archive::Child &c, 2760b57cec5SDimitry Andric const Archive::Symbol &sym, 2770b57cec5SDimitry Andric StringRef parentName) { 2780b57cec5SDimitry Andric 2790b57cec5SDimitry Andric auto reportBufferError = [=](Error &&e, StringRef childName) { 2800b57cec5SDimitry Andric fatal("could not get the buffer for the member defining symbol " + 2810b57cec5SDimitry Andric toCOFFString(sym) + ": " + parentName + "(" + childName + "): " + 2820b57cec5SDimitry Andric toString(std::move(e))); 2830b57cec5SDimitry Andric }; 2840b57cec5SDimitry Andric 2850b57cec5SDimitry Andric if (!c.getParent()->isThin()) { 2860b57cec5SDimitry Andric uint64_t offsetInArchive = c.getChildOffset(); 2870b57cec5SDimitry Andric Expected<MemoryBufferRef> mbOrErr = c.getMemoryBufferRef(); 2880b57cec5SDimitry Andric if (!mbOrErr) 2890b57cec5SDimitry Andric reportBufferError(mbOrErr.takeError(), check(c.getFullName())); 2900b57cec5SDimitry Andric MemoryBufferRef mb = mbOrErr.get(); 2910b57cec5SDimitry Andric enqueueTask([=]() { 2920b57cec5SDimitry Andric driver->addArchiveBuffer(mb, toCOFFString(sym), parentName, 2930b57cec5SDimitry Andric offsetInArchive); 2940b57cec5SDimitry Andric }); 2950b57cec5SDimitry Andric return; 2960b57cec5SDimitry Andric } 2970b57cec5SDimitry Andric 2980b57cec5SDimitry Andric std::string childName = CHECK( 2990b57cec5SDimitry Andric c.getFullName(), 3000b57cec5SDimitry Andric "could not get the filename for the member defining symbol " + 3010b57cec5SDimitry Andric toCOFFString(sym)); 3020b57cec5SDimitry Andric auto future = std::make_shared<std::future<MBErrPair>>( 3030b57cec5SDimitry Andric createFutureForFile(childName)); 3040b57cec5SDimitry Andric enqueueTask([=]() { 3050b57cec5SDimitry Andric auto mbOrErr = future->get(); 3060b57cec5SDimitry Andric if (mbOrErr.second) 3070b57cec5SDimitry Andric reportBufferError(errorCodeToError(mbOrErr.second), childName); 30885868e8aSDimitry Andric // Pass empty string as archive name so that the original filename is 30985868e8aSDimitry Andric // used as the buffer identifier. 3100b57cec5SDimitry Andric driver->addArchiveBuffer(takeBuffer(std::move(mbOrErr.first)), 31185868e8aSDimitry Andric toCOFFString(sym), "", /*OffsetInArchive=*/0); 3120b57cec5SDimitry Andric }); 3130b57cec5SDimitry Andric } 3140b57cec5SDimitry Andric 3150b57cec5SDimitry Andric static bool isDecorated(StringRef sym) { 3160b57cec5SDimitry Andric return sym.startswith("@") || sym.contains("@@") || sym.startswith("?") || 3170b57cec5SDimitry Andric (!config->mingw && sym.contains('@')); 3180b57cec5SDimitry Andric } 3190b57cec5SDimitry Andric 3200b57cec5SDimitry Andric // Parses .drectve section contents and returns a list of files 3210b57cec5SDimitry Andric // specified by /defaultlib. 3220b57cec5SDimitry Andric void LinkerDriver::parseDirectives(InputFile *file) { 3230b57cec5SDimitry Andric StringRef s = file->getDirectives(); 3240b57cec5SDimitry Andric if (s.empty()) 3250b57cec5SDimitry Andric return; 3260b57cec5SDimitry Andric 3270b57cec5SDimitry Andric log("Directives: " + toString(file) + ": " + s); 3280b57cec5SDimitry Andric 3290b57cec5SDimitry Andric ArgParser parser; 3300b57cec5SDimitry Andric // .drectve is always tokenized using Windows shell rules. 3310b57cec5SDimitry Andric // /EXPORT: option can appear too many times, processing in fastpath. 3325ffd83dbSDimitry Andric ParsedDirectives directives = parser.parseDirectives(s); 3330b57cec5SDimitry Andric 3345ffd83dbSDimitry Andric for (StringRef e : directives.exports) { 3350b57cec5SDimitry Andric // If a common header file contains dllexported function 3360b57cec5SDimitry Andric // declarations, many object files may end up with having the 3370b57cec5SDimitry Andric // same /EXPORT options. In order to save cost of parsing them, 3380b57cec5SDimitry Andric // we dedup them first. 3390b57cec5SDimitry Andric if (!directivesExports.insert(e).second) 3400b57cec5SDimitry Andric continue; 3410b57cec5SDimitry Andric 3420b57cec5SDimitry Andric Export exp = parseExport(e); 3430b57cec5SDimitry Andric if (config->machine == I386 && config->mingw) { 3440b57cec5SDimitry Andric if (!isDecorated(exp.name)) 345*04eeddc0SDimitry Andric exp.name = saver().save("_" + exp.name); 3460b57cec5SDimitry Andric if (!exp.extName.empty() && !isDecorated(exp.extName)) 347*04eeddc0SDimitry Andric exp.extName = saver().save("_" + exp.extName); 3480b57cec5SDimitry Andric } 3490b57cec5SDimitry Andric exp.directives = true; 3500b57cec5SDimitry Andric config->exports.push_back(exp); 3510b57cec5SDimitry Andric } 3520b57cec5SDimitry Andric 3535ffd83dbSDimitry Andric // Handle /include: in bulk. 3545ffd83dbSDimitry Andric for (StringRef inc : directives.includes) 3555ffd83dbSDimitry Andric addUndefined(inc); 3565ffd83dbSDimitry Andric 357349cc55cSDimitry Andric // https://docs.microsoft.com/en-us/cpp/preprocessor/comment-c-cpp?view=msvc-160 3585ffd83dbSDimitry Andric for (auto *arg : directives.args) { 3590b57cec5SDimitry Andric switch (arg->getOption().getID()) { 3600b57cec5SDimitry Andric case OPT_aligncomm: 3610b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 3620b57cec5SDimitry Andric break; 3630b57cec5SDimitry Andric case OPT_alternatename: 3640b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 3650b57cec5SDimitry Andric break; 3660b57cec5SDimitry Andric case OPT_defaultlib: 3670b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 36885868e8aSDimitry Andric enqueuePath(*path, false, false); 3690b57cec5SDimitry Andric break; 3700b57cec5SDimitry Andric case OPT_entry: 3710b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 3720b57cec5SDimitry Andric break; 3730b57cec5SDimitry Andric case OPT_failifmismatch: 3740b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), file); 3750b57cec5SDimitry Andric break; 3760b57cec5SDimitry Andric case OPT_incl: 3770b57cec5SDimitry Andric addUndefined(arg->getValue()); 3780b57cec5SDimitry Andric break; 379349cc55cSDimitry Andric case OPT_manifestdependency: 380349cc55cSDimitry Andric config->manifestDependencies.insert(arg->getValue()); 381349cc55cSDimitry Andric break; 3820b57cec5SDimitry Andric case OPT_merge: 3830b57cec5SDimitry Andric parseMerge(arg->getValue()); 3840b57cec5SDimitry Andric break; 3850b57cec5SDimitry Andric case OPT_nodefaultlib: 3860b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 3870b57cec5SDimitry Andric break; 3880b57cec5SDimitry Andric case OPT_section: 3890b57cec5SDimitry Andric parseSection(arg->getValue()); 3900b57cec5SDimitry Andric break; 391fe6060f1SDimitry Andric case OPT_stack: 392fe6060f1SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, 393fe6060f1SDimitry Andric &config->stackCommit); 394fe6060f1SDimitry Andric break; 395e8d8bef9SDimitry Andric case OPT_subsystem: { 396e8d8bef9SDimitry Andric bool gotVersion = false; 3970b57cec5SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 398e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 399e8d8bef9SDimitry Andric &config->minorSubsystemVersion, &gotVersion); 400e8d8bef9SDimitry Andric if (gotVersion) { 401e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 402e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 403e8d8bef9SDimitry Andric } 4040b57cec5SDimitry Andric break; 405e8d8bef9SDimitry Andric } 4060b57cec5SDimitry Andric // Only add flags here that link.exe accepts in 4070b57cec5SDimitry Andric // `#pragma comment(linker, "/flag")`-generated sections. 4080b57cec5SDimitry Andric case OPT_editandcontinue: 4090b57cec5SDimitry Andric case OPT_guardsym: 4100b57cec5SDimitry Andric case OPT_throwingnew: 4110b57cec5SDimitry Andric break; 4120b57cec5SDimitry Andric default: 4130b57cec5SDimitry Andric error(arg->getSpelling() + " is not allowed in .drectve"); 4140b57cec5SDimitry Andric } 4150b57cec5SDimitry Andric } 4160b57cec5SDimitry Andric } 4170b57cec5SDimitry Andric 4180b57cec5SDimitry Andric // Find file from search paths. You can omit ".obj", this function takes 4190b57cec5SDimitry Andric // care of that. Note that the returned path is not guaranteed to exist. 4200b57cec5SDimitry Andric StringRef LinkerDriver::doFindFile(StringRef filename) { 4210b57cec5SDimitry Andric bool hasPathSep = (filename.find_first_of("/\\") != StringRef::npos); 4220b57cec5SDimitry Andric if (hasPathSep) 4230b57cec5SDimitry Andric return filename; 4240b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4250b57cec5SDimitry Andric for (StringRef dir : searchPaths) { 4260b57cec5SDimitry Andric SmallString<128> path = dir; 4270b57cec5SDimitry Andric sys::path::append(path, filename); 4280b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 429*04eeddc0SDimitry Andric return saver().save(path.str()); 4300b57cec5SDimitry Andric if (!hasExt) { 4310b57cec5SDimitry Andric path.append(".obj"); 4320b57cec5SDimitry Andric if (sys::fs::exists(path.str())) 433*04eeddc0SDimitry Andric return saver().save(path.str()); 4340b57cec5SDimitry Andric } 4350b57cec5SDimitry Andric } 4360b57cec5SDimitry Andric return filename; 4370b57cec5SDimitry Andric } 4380b57cec5SDimitry Andric 4390b57cec5SDimitry Andric static Optional<sys::fs::UniqueID> getUniqueID(StringRef path) { 4400b57cec5SDimitry Andric sys::fs::UniqueID ret; 4410b57cec5SDimitry Andric if (sys::fs::getUniqueID(path, ret)) 4420b57cec5SDimitry Andric return None; 4430b57cec5SDimitry Andric return ret; 4440b57cec5SDimitry Andric } 4450b57cec5SDimitry Andric 4460b57cec5SDimitry Andric // Resolves a file path. This never returns the same path 4470b57cec5SDimitry Andric // (in that case, it returns None). 4480b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findFile(StringRef filename) { 4490b57cec5SDimitry Andric StringRef path = doFindFile(filename); 4500b57cec5SDimitry Andric 4510b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) { 4520b57cec5SDimitry Andric bool seen = !visitedFiles.insert(*id).second; 4530b57cec5SDimitry Andric if (seen) 4540b57cec5SDimitry Andric return None; 4550b57cec5SDimitry Andric } 4560b57cec5SDimitry Andric 457fe6060f1SDimitry Andric if (path.endswith_insensitive(".lib")) 4585ffd83dbSDimitry Andric visitedLibs.insert(std::string(sys::path::filename(path))); 4590b57cec5SDimitry Andric return path; 4600b57cec5SDimitry Andric } 4610b57cec5SDimitry Andric 4620b57cec5SDimitry Andric // MinGW specific. If an embedded directive specified to link to 4630b57cec5SDimitry Andric // foo.lib, but it isn't found, try libfoo.a instead. 4640b57cec5SDimitry Andric StringRef LinkerDriver::doFindLibMinGW(StringRef filename) { 4650b57cec5SDimitry Andric if (filename.contains('/') || filename.contains('\\')) 4660b57cec5SDimitry Andric return filename; 4670b57cec5SDimitry Andric 4680b57cec5SDimitry Andric SmallString<128> s = filename; 4690b57cec5SDimitry Andric sys::path::replace_extension(s, ".a"); 470*04eeddc0SDimitry Andric StringRef libName = saver().save("lib" + s.str()); 4710b57cec5SDimitry Andric return doFindFile(libName); 4720b57cec5SDimitry Andric } 4730b57cec5SDimitry Andric 4740b57cec5SDimitry Andric // Find library file from search path. 4750b57cec5SDimitry Andric StringRef LinkerDriver::doFindLib(StringRef filename) { 4760b57cec5SDimitry Andric // Add ".lib" to Filename if that has no file extension. 4770b57cec5SDimitry Andric bool hasExt = filename.contains('.'); 4780b57cec5SDimitry Andric if (!hasExt) 479*04eeddc0SDimitry Andric filename = saver().save(filename + ".lib"); 4800b57cec5SDimitry Andric StringRef ret = doFindFile(filename); 4810b57cec5SDimitry Andric // For MinGW, if the find above didn't turn up anything, try 4820b57cec5SDimitry Andric // looking for a MinGW formatted library name. 4830b57cec5SDimitry Andric if (config->mingw && ret == filename) 4840b57cec5SDimitry Andric return doFindLibMinGW(filename); 4850b57cec5SDimitry Andric return ret; 4860b57cec5SDimitry Andric } 4870b57cec5SDimitry Andric 4880b57cec5SDimitry Andric // Resolves a library path. /nodefaultlib options are taken into 4890b57cec5SDimitry Andric // consideration. This never returns the same path (in that case, 4900b57cec5SDimitry Andric // it returns None). 4910b57cec5SDimitry Andric Optional<StringRef> LinkerDriver::findLib(StringRef filename) { 4920b57cec5SDimitry Andric if (config->noDefaultLibAll) 4930b57cec5SDimitry Andric return None; 4940b57cec5SDimitry Andric if (!visitedLibs.insert(filename.lower()).second) 4950b57cec5SDimitry Andric return None; 4960b57cec5SDimitry Andric 4970b57cec5SDimitry Andric StringRef path = doFindLib(filename); 4980b57cec5SDimitry Andric if (config->noDefaultLibs.count(path.lower())) 4990b57cec5SDimitry Andric return None; 5000b57cec5SDimitry Andric 5010b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 5020b57cec5SDimitry Andric if (!visitedFiles.insert(*id).second) 5030b57cec5SDimitry Andric return None; 5040b57cec5SDimitry Andric return path; 5050b57cec5SDimitry Andric } 5060b57cec5SDimitry Andric 5070b57cec5SDimitry Andric // Parses LIB environment which contains a list of search paths. 5080b57cec5SDimitry Andric void LinkerDriver::addLibSearchPaths() { 5090b57cec5SDimitry Andric Optional<std::string> envOpt = Process::GetEnv("LIB"); 5100b57cec5SDimitry Andric if (!envOpt.hasValue()) 5110b57cec5SDimitry Andric return; 512*04eeddc0SDimitry Andric StringRef env = saver().save(*envOpt); 5130b57cec5SDimitry Andric while (!env.empty()) { 5140b57cec5SDimitry Andric StringRef path; 5150b57cec5SDimitry Andric std::tie(path, env) = env.split(';'); 5160b57cec5SDimitry Andric searchPaths.push_back(path); 5170b57cec5SDimitry Andric } 5180b57cec5SDimitry Andric } 5190b57cec5SDimitry Andric 5200b57cec5SDimitry Andric Symbol *LinkerDriver::addUndefined(StringRef name) { 521349cc55cSDimitry Andric Symbol *b = ctx.symtab.addUndefined(name); 5220b57cec5SDimitry Andric if (!b->isGCRoot) { 5230b57cec5SDimitry Andric b->isGCRoot = true; 5240b57cec5SDimitry Andric config->gcroot.push_back(b); 5250b57cec5SDimitry Andric } 5260b57cec5SDimitry Andric return b; 5270b57cec5SDimitry Andric } 5280b57cec5SDimitry Andric 5290b57cec5SDimitry Andric StringRef LinkerDriver::mangleMaybe(Symbol *s) { 5300b57cec5SDimitry Andric // If the plain symbol name has already been resolved, do nothing. 5310b57cec5SDimitry Andric Undefined *unmangled = dyn_cast<Undefined>(s); 5320b57cec5SDimitry Andric if (!unmangled) 5330b57cec5SDimitry Andric return ""; 5340b57cec5SDimitry Andric 5350b57cec5SDimitry Andric // Otherwise, see if a similar, mangled symbol exists in the symbol table. 536349cc55cSDimitry Andric Symbol *mangled = ctx.symtab.findMangle(unmangled->getName()); 5370b57cec5SDimitry Andric if (!mangled) 5380b57cec5SDimitry Andric return ""; 5390b57cec5SDimitry Andric 5400b57cec5SDimitry Andric // If we find a similar mangled symbol, make this an alias to it and return 5410b57cec5SDimitry Andric // its name. 5420b57cec5SDimitry Andric log(unmangled->getName() + " aliased to " + mangled->getName()); 543349cc55cSDimitry Andric unmangled->weakAlias = ctx.symtab.addUndefined(mangled->getName()); 5440b57cec5SDimitry Andric return mangled->getName(); 5450b57cec5SDimitry Andric } 5460b57cec5SDimitry Andric 5470b57cec5SDimitry Andric // Windows specific -- find default entry point name. 5480b57cec5SDimitry Andric // 5490b57cec5SDimitry Andric // There are four different entry point functions for Windows executables, 5500b57cec5SDimitry Andric // each of which corresponds to a user-defined "main" function. This function 5510b57cec5SDimitry Andric // infers an entry point from a user-defined "main" function. 5520b57cec5SDimitry Andric StringRef LinkerDriver::findDefaultEntry() { 5530b57cec5SDimitry Andric assert(config->subsystem != IMAGE_SUBSYSTEM_UNKNOWN && 5540b57cec5SDimitry Andric "must handle /subsystem before calling this"); 5550b57cec5SDimitry Andric 5560b57cec5SDimitry Andric if (config->mingw) 5570b57cec5SDimitry Andric return mangle(config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI 5580b57cec5SDimitry Andric ? "WinMainCRTStartup" 5590b57cec5SDimitry Andric : "mainCRTStartup"); 5600b57cec5SDimitry Andric 5610b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_WINDOWS_GUI) { 5620b57cec5SDimitry Andric if (findUnderscoreMangle("wWinMain")) { 5630b57cec5SDimitry Andric if (!findUnderscoreMangle("WinMain")) 5640b57cec5SDimitry Andric return mangle("wWinMainCRTStartup"); 5650b57cec5SDimitry Andric warn("found both wWinMain and WinMain; using latter"); 5660b57cec5SDimitry Andric } 5670b57cec5SDimitry Andric return mangle("WinMainCRTStartup"); 5680b57cec5SDimitry Andric } 5690b57cec5SDimitry Andric if (findUnderscoreMangle("wmain")) { 5700b57cec5SDimitry Andric if (!findUnderscoreMangle("main")) 5710b57cec5SDimitry Andric return mangle("wmainCRTStartup"); 5720b57cec5SDimitry Andric warn("found both wmain and main; using latter"); 5730b57cec5SDimitry Andric } 5740b57cec5SDimitry Andric return mangle("mainCRTStartup"); 5750b57cec5SDimitry Andric } 5760b57cec5SDimitry Andric 5770b57cec5SDimitry Andric WindowsSubsystem LinkerDriver::inferSubsystem() { 5780b57cec5SDimitry Andric if (config->dll) 5790b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 5800b57cec5SDimitry Andric if (config->mingw) 5810b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 5820b57cec5SDimitry Andric // Note that link.exe infers the subsystem from the presence of these 5830b57cec5SDimitry Andric // functions even if /entry: or /nodefaultlib are passed which causes them 5840b57cec5SDimitry Andric // to not be called. 5850b57cec5SDimitry Andric bool haveMain = findUnderscoreMangle("main"); 5860b57cec5SDimitry Andric bool haveWMain = findUnderscoreMangle("wmain"); 5870b57cec5SDimitry Andric bool haveWinMain = findUnderscoreMangle("WinMain"); 5880b57cec5SDimitry Andric bool haveWWinMain = findUnderscoreMangle("wWinMain"); 5890b57cec5SDimitry Andric if (haveMain || haveWMain) { 5900b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) { 5910b57cec5SDimitry Andric warn(std::string("found ") + (haveMain ? "main" : "wmain") + " and " + 5920b57cec5SDimitry Andric (haveWinMain ? "WinMain" : "wWinMain") + 5930b57cec5SDimitry Andric "; defaulting to /subsystem:console"); 5940b57cec5SDimitry Andric } 5950b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_CUI; 5960b57cec5SDimitry Andric } 5970b57cec5SDimitry Andric if (haveWinMain || haveWWinMain) 5980b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_WINDOWS_GUI; 5990b57cec5SDimitry Andric return IMAGE_SUBSYSTEM_UNKNOWN; 6000b57cec5SDimitry Andric } 6010b57cec5SDimitry Andric 6020b57cec5SDimitry Andric static uint64_t getDefaultImageBase() { 6030b57cec5SDimitry Andric if (config->is64()) 6040b57cec5SDimitry Andric return config->dll ? 0x180000000 : 0x140000000; 6050b57cec5SDimitry Andric return config->dll ? 0x10000000 : 0x400000; 6060b57cec5SDimitry Andric } 6070b57cec5SDimitry Andric 608fe6060f1SDimitry Andric static std::string rewritePath(StringRef s) { 609fe6060f1SDimitry Andric if (fs::exists(s)) 610fe6060f1SDimitry Andric return relativeToRoot(s); 611fe6060f1SDimitry Andric return std::string(s); 612fe6060f1SDimitry Andric } 613fe6060f1SDimitry Andric 614fe6060f1SDimitry Andric // Reconstructs command line arguments so that so that you can re-run 615fe6060f1SDimitry Andric // the same command with the same inputs. This is for --reproduce. 6160b57cec5SDimitry Andric static std::string createResponseFile(const opt::InputArgList &args, 6170b57cec5SDimitry Andric ArrayRef<StringRef> filePaths, 6180b57cec5SDimitry Andric ArrayRef<StringRef> searchPaths) { 6190b57cec5SDimitry Andric SmallString<0> data; 6200b57cec5SDimitry Andric raw_svector_ostream os(data); 6210b57cec5SDimitry Andric 6220b57cec5SDimitry Andric for (auto *arg : args) { 6230b57cec5SDimitry Andric switch (arg->getOption().getID()) { 6240b57cec5SDimitry Andric case OPT_linkrepro: 62585868e8aSDimitry Andric case OPT_reproduce: 6260b57cec5SDimitry Andric case OPT_INPUT: 6270b57cec5SDimitry Andric case OPT_defaultlib: 6280b57cec5SDimitry Andric case OPT_libpath: 6290b57cec5SDimitry Andric break; 630fe6060f1SDimitry Andric case OPT_call_graph_ordering_file: 631fe6060f1SDimitry Andric case OPT_deffile: 632349cc55cSDimitry Andric case OPT_manifestinput: 633fe6060f1SDimitry Andric case OPT_natvis: 634fe6060f1SDimitry Andric os << arg->getSpelling() << quote(rewritePath(arg->getValue())) << '\n'; 635fe6060f1SDimitry Andric break; 636fe6060f1SDimitry Andric case OPT_order: { 637fe6060f1SDimitry Andric StringRef orderFile = arg->getValue(); 638fe6060f1SDimitry Andric orderFile.consume_front("@"); 639fe6060f1SDimitry Andric os << arg->getSpelling() << '@' << quote(rewritePath(orderFile)) << '\n'; 640fe6060f1SDimitry Andric break; 641fe6060f1SDimitry Andric } 642fe6060f1SDimitry Andric case OPT_pdbstream: { 643fe6060f1SDimitry Andric const std::pair<StringRef, StringRef> nameFile = 644fe6060f1SDimitry Andric StringRef(arg->getValue()).split("="); 645fe6060f1SDimitry Andric os << arg->getSpelling() << nameFile.first << '=' 646fe6060f1SDimitry Andric << quote(rewritePath(nameFile.second)) << '\n'; 647fe6060f1SDimitry Andric break; 648fe6060f1SDimitry Andric } 6490b57cec5SDimitry Andric case OPT_implib: 650349cc55cSDimitry Andric case OPT_manifestfile: 6510b57cec5SDimitry Andric case OPT_pdb: 6525ffd83dbSDimitry Andric case OPT_pdbstripped: 6530b57cec5SDimitry Andric case OPT_out: 6540b57cec5SDimitry Andric os << arg->getSpelling() << sys::path::filename(arg->getValue()) << "\n"; 6550b57cec5SDimitry Andric break; 6560b57cec5SDimitry Andric default: 6570b57cec5SDimitry Andric os << toString(*arg) << "\n"; 6580b57cec5SDimitry Andric } 6590b57cec5SDimitry Andric } 6600b57cec5SDimitry Andric 6610b57cec5SDimitry Andric for (StringRef path : searchPaths) { 6620b57cec5SDimitry Andric std::string relPath = relativeToRoot(path); 6630b57cec5SDimitry Andric os << "/libpath:" << quote(relPath) << "\n"; 6640b57cec5SDimitry Andric } 6650b57cec5SDimitry Andric 6660b57cec5SDimitry Andric for (StringRef path : filePaths) 6670b57cec5SDimitry Andric os << quote(relativeToRoot(path)) << "\n"; 6680b57cec5SDimitry Andric 6695ffd83dbSDimitry Andric return std::string(data.str()); 6700b57cec5SDimitry Andric } 6710b57cec5SDimitry Andric 672fe6060f1SDimitry Andric enum class DebugKind { 673fe6060f1SDimitry Andric Unknown, 674fe6060f1SDimitry Andric None, 675fe6060f1SDimitry Andric Full, 676fe6060f1SDimitry Andric FastLink, 677fe6060f1SDimitry Andric GHash, 678fe6060f1SDimitry Andric NoGHash, 679fe6060f1SDimitry Andric Dwarf, 680fe6060f1SDimitry Andric Symtab 681fe6060f1SDimitry Andric }; 6820b57cec5SDimitry Andric 6830b57cec5SDimitry Andric static DebugKind parseDebugKind(const opt::InputArgList &args) { 6840b57cec5SDimitry Andric auto *a = args.getLastArg(OPT_debug, OPT_debug_opt); 6850b57cec5SDimitry Andric if (!a) 6860b57cec5SDimitry Andric return DebugKind::None; 6870b57cec5SDimitry Andric if (a->getNumValues() == 0) 6880b57cec5SDimitry Andric return DebugKind::Full; 6890b57cec5SDimitry Andric 6900b57cec5SDimitry Andric DebugKind debug = StringSwitch<DebugKind>(a->getValue()) 6910b57cec5SDimitry Andric .CaseLower("none", DebugKind::None) 6920b57cec5SDimitry Andric .CaseLower("full", DebugKind::Full) 6930b57cec5SDimitry Andric .CaseLower("fastlink", DebugKind::FastLink) 6940b57cec5SDimitry Andric // LLD extensions 6950b57cec5SDimitry Andric .CaseLower("ghash", DebugKind::GHash) 696fe6060f1SDimitry Andric .CaseLower("noghash", DebugKind::NoGHash) 6970b57cec5SDimitry Andric .CaseLower("dwarf", DebugKind::Dwarf) 6980b57cec5SDimitry Andric .CaseLower("symtab", DebugKind::Symtab) 6990b57cec5SDimitry Andric .Default(DebugKind::Unknown); 7000b57cec5SDimitry Andric 7010b57cec5SDimitry Andric if (debug == DebugKind::FastLink) { 7020b57cec5SDimitry Andric warn("/debug:fastlink unsupported; using /debug:full"); 7030b57cec5SDimitry Andric return DebugKind::Full; 7040b57cec5SDimitry Andric } 7050b57cec5SDimitry Andric if (debug == DebugKind::Unknown) { 7060b57cec5SDimitry Andric error("/debug: unknown option: " + Twine(a->getValue())); 7070b57cec5SDimitry Andric return DebugKind::None; 7080b57cec5SDimitry Andric } 7090b57cec5SDimitry Andric return debug; 7100b57cec5SDimitry Andric } 7110b57cec5SDimitry Andric 7120b57cec5SDimitry Andric static unsigned parseDebugTypes(const opt::InputArgList &args) { 7130b57cec5SDimitry Andric unsigned debugTypes = static_cast<unsigned>(DebugType::None); 7140b57cec5SDimitry Andric 7150b57cec5SDimitry Andric if (auto *a = args.getLastArg(OPT_debugtype)) { 7160b57cec5SDimitry Andric SmallVector<StringRef, 3> types; 7170b57cec5SDimitry Andric StringRef(a->getValue()) 7180b57cec5SDimitry Andric .split(types, ',', /*MaxSplit=*/-1, /*KeepEmpty=*/false); 7190b57cec5SDimitry Andric 7200b57cec5SDimitry Andric for (StringRef type : types) { 7210b57cec5SDimitry Andric unsigned v = StringSwitch<unsigned>(type.lower()) 7220b57cec5SDimitry Andric .Case("cv", static_cast<unsigned>(DebugType::CV)) 7230b57cec5SDimitry Andric .Case("pdata", static_cast<unsigned>(DebugType::PData)) 7240b57cec5SDimitry Andric .Case("fixup", static_cast<unsigned>(DebugType::Fixup)) 7250b57cec5SDimitry Andric .Default(0); 7260b57cec5SDimitry Andric if (v == 0) { 7270b57cec5SDimitry Andric warn("/debugtype: unknown option '" + type + "'"); 7280b57cec5SDimitry Andric continue; 7290b57cec5SDimitry Andric } 7300b57cec5SDimitry Andric debugTypes |= v; 7310b57cec5SDimitry Andric } 7320b57cec5SDimitry Andric return debugTypes; 7330b57cec5SDimitry Andric } 7340b57cec5SDimitry Andric 7350b57cec5SDimitry Andric // Default debug types 7360b57cec5SDimitry Andric debugTypes = static_cast<unsigned>(DebugType::CV); 7370b57cec5SDimitry Andric if (args.hasArg(OPT_driver)) 7380b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::PData); 7390b57cec5SDimitry Andric if (args.hasArg(OPT_profile)) 7400b57cec5SDimitry Andric debugTypes |= static_cast<unsigned>(DebugType::Fixup); 7410b57cec5SDimitry Andric 7420b57cec5SDimitry Andric return debugTypes; 7430b57cec5SDimitry Andric } 7440b57cec5SDimitry Andric 7455ffd83dbSDimitry Andric static std::string getMapFile(const opt::InputArgList &args, 7465ffd83dbSDimitry Andric opt::OptSpecifier os, opt::OptSpecifier osFile) { 7475ffd83dbSDimitry Andric auto *arg = args.getLastArg(os, osFile); 7480b57cec5SDimitry Andric if (!arg) 7490b57cec5SDimitry Andric return ""; 7505ffd83dbSDimitry Andric if (arg->getOption().getID() == osFile.getID()) 7510b57cec5SDimitry Andric return arg->getValue(); 7520b57cec5SDimitry Andric 7535ffd83dbSDimitry Andric assert(arg->getOption().getID() == os.getID()); 7540b57cec5SDimitry Andric StringRef outFile = config->outputFile; 7550b57cec5SDimitry Andric return (outFile.substr(0, outFile.rfind('.')) + ".map").str(); 7560b57cec5SDimitry Andric } 7570b57cec5SDimitry Andric 7580b57cec5SDimitry Andric static std::string getImplibPath() { 7590b57cec5SDimitry Andric if (!config->implib.empty()) 7605ffd83dbSDimitry Andric return std::string(config->implib); 7610b57cec5SDimitry Andric SmallString<128> out = StringRef(config->outputFile); 7620b57cec5SDimitry Andric sys::path::replace_extension(out, ".lib"); 7635ffd83dbSDimitry Andric return std::string(out.str()); 7640b57cec5SDimitry Andric } 7650b57cec5SDimitry Andric 76685868e8aSDimitry Andric // The import name is calculated as follows: 7670b57cec5SDimitry Andric // 7680b57cec5SDimitry Andric // | LIBRARY w/ ext | LIBRARY w/o ext | no LIBRARY 7690b57cec5SDimitry Andric // -----+----------------+---------------------+------------------ 7700b57cec5SDimitry Andric // LINK | {value} | {value}.{.dll/.exe} | {output name} 7710b57cec5SDimitry Andric // LIB | {value} | {value}.dll | {output name}.dll 7720b57cec5SDimitry Andric // 7730b57cec5SDimitry Andric static std::string getImportName(bool asLib) { 7740b57cec5SDimitry Andric SmallString<128> out; 7750b57cec5SDimitry Andric 7760b57cec5SDimitry Andric if (config->importName.empty()) { 7770b57cec5SDimitry Andric out.assign(sys::path::filename(config->outputFile)); 7780b57cec5SDimitry Andric if (asLib) 7790b57cec5SDimitry Andric sys::path::replace_extension(out, ".dll"); 7800b57cec5SDimitry Andric } else { 7810b57cec5SDimitry Andric out.assign(config->importName); 7820b57cec5SDimitry Andric if (!sys::path::has_extension(out)) 7830b57cec5SDimitry Andric sys::path::replace_extension(out, 7840b57cec5SDimitry Andric (config->dll || asLib) ? ".dll" : ".exe"); 7850b57cec5SDimitry Andric } 7860b57cec5SDimitry Andric 7875ffd83dbSDimitry Andric return std::string(out.str()); 7880b57cec5SDimitry Andric } 7890b57cec5SDimitry Andric 7900b57cec5SDimitry Andric static void createImportLibrary(bool asLib) { 7910b57cec5SDimitry Andric std::vector<COFFShortExport> exports; 7920b57cec5SDimitry Andric for (Export &e1 : config->exports) { 7930b57cec5SDimitry Andric COFFShortExport e2; 7945ffd83dbSDimitry Andric e2.Name = std::string(e1.name); 7955ffd83dbSDimitry Andric e2.SymbolName = std::string(e1.symbolName); 7965ffd83dbSDimitry Andric e2.ExtName = std::string(e1.extName); 797*04eeddc0SDimitry Andric e2.AliasTarget = std::string(e1.aliasTarget); 7980b57cec5SDimitry Andric e2.Ordinal = e1.ordinal; 7990b57cec5SDimitry Andric e2.Noname = e1.noname; 8000b57cec5SDimitry Andric e2.Data = e1.data; 8010b57cec5SDimitry Andric e2.Private = e1.isPrivate; 8020b57cec5SDimitry Andric e2.Constant = e1.constant; 8030b57cec5SDimitry Andric exports.push_back(e2); 8040b57cec5SDimitry Andric } 8050b57cec5SDimitry Andric 8060b57cec5SDimitry Andric std::string libName = getImportName(asLib); 8070b57cec5SDimitry Andric std::string path = getImplibPath(); 8080b57cec5SDimitry Andric 8090b57cec5SDimitry Andric if (!config->incremental) { 810349cc55cSDimitry Andric checkError(writeImportLibrary(libName, path, exports, config->machine, 8110b57cec5SDimitry Andric config->mingw)); 8120b57cec5SDimitry Andric return; 8130b57cec5SDimitry Andric } 8140b57cec5SDimitry Andric 8150b57cec5SDimitry Andric // If the import library already exists, replace it only if the contents 8160b57cec5SDimitry Andric // have changed. 8170b57cec5SDimitry Andric ErrorOr<std::unique_ptr<MemoryBuffer>> oldBuf = MemoryBuffer::getFile( 818fe6060f1SDimitry Andric path, /*IsText=*/false, /*RequiresNullTerminator=*/false); 8190b57cec5SDimitry Andric if (!oldBuf) { 820349cc55cSDimitry Andric checkError(writeImportLibrary(libName, path, exports, config->machine, 8210b57cec5SDimitry Andric config->mingw)); 8220b57cec5SDimitry Andric return; 8230b57cec5SDimitry Andric } 8240b57cec5SDimitry Andric 8250b57cec5SDimitry Andric SmallString<128> tmpName; 8260b57cec5SDimitry Andric if (std::error_code ec = 8270b57cec5SDimitry Andric sys::fs::createUniqueFile(path + ".tmp-%%%%%%%%.lib", tmpName)) 8280b57cec5SDimitry Andric fatal("cannot create temporary file for import library " + path + ": " + 8290b57cec5SDimitry Andric ec.message()); 8300b57cec5SDimitry Andric 8310b57cec5SDimitry Andric if (Error e = writeImportLibrary(libName, tmpName, exports, config->machine, 8320b57cec5SDimitry Andric config->mingw)) { 833349cc55cSDimitry Andric checkError(std::move(e)); 8340b57cec5SDimitry Andric return; 8350b57cec5SDimitry Andric } 8360b57cec5SDimitry Andric 8370b57cec5SDimitry Andric std::unique_ptr<MemoryBuffer> newBuf = check(MemoryBuffer::getFile( 838fe6060f1SDimitry Andric tmpName, /*IsText=*/false, /*RequiresNullTerminator=*/false)); 8390b57cec5SDimitry Andric if ((*oldBuf)->getBuffer() != newBuf->getBuffer()) { 8400b57cec5SDimitry Andric oldBuf->reset(); 841349cc55cSDimitry Andric checkError(errorCodeToError(sys::fs::rename(tmpName, path))); 8420b57cec5SDimitry Andric } else { 8430b57cec5SDimitry Andric sys::fs::remove(tmpName); 8440b57cec5SDimitry Andric } 8450b57cec5SDimitry Andric } 8460b57cec5SDimitry Andric 8470b57cec5SDimitry Andric static void parseModuleDefs(StringRef path) { 848fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 849fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 850fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 851fe6060f1SDimitry Andric /*IsVolatile=*/true), 852fe6060f1SDimitry Andric "could not open " + path); 8530b57cec5SDimitry Andric COFFModuleDefinition m = check(parseCOFFModuleDefinition( 8540b57cec5SDimitry Andric mb->getMemBufferRef(), config->machine, config->mingw)); 8550b57cec5SDimitry Andric 856fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 857fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 858fe6060f1SDimitry Andric 8590b57cec5SDimitry Andric if (config->outputFile.empty()) 860*04eeddc0SDimitry Andric config->outputFile = std::string(saver().save(m.OutputFile)); 861*04eeddc0SDimitry Andric config->importName = std::string(saver().save(m.ImportName)); 8620b57cec5SDimitry Andric if (m.ImageBase) 8630b57cec5SDimitry Andric config->imageBase = m.ImageBase; 8640b57cec5SDimitry Andric if (m.StackReserve) 8650b57cec5SDimitry Andric config->stackReserve = m.StackReserve; 8660b57cec5SDimitry Andric if (m.StackCommit) 8670b57cec5SDimitry Andric config->stackCommit = m.StackCommit; 8680b57cec5SDimitry Andric if (m.HeapReserve) 8690b57cec5SDimitry Andric config->heapReserve = m.HeapReserve; 8700b57cec5SDimitry Andric if (m.HeapCommit) 8710b57cec5SDimitry Andric config->heapCommit = m.HeapCommit; 8720b57cec5SDimitry Andric if (m.MajorImageVersion) 8730b57cec5SDimitry Andric config->majorImageVersion = m.MajorImageVersion; 8740b57cec5SDimitry Andric if (m.MinorImageVersion) 8750b57cec5SDimitry Andric config->minorImageVersion = m.MinorImageVersion; 8760b57cec5SDimitry Andric if (m.MajorOSVersion) 8770b57cec5SDimitry Andric config->majorOSVersion = m.MajorOSVersion; 8780b57cec5SDimitry Andric if (m.MinorOSVersion) 8790b57cec5SDimitry Andric config->minorOSVersion = m.MinorOSVersion; 8800b57cec5SDimitry Andric 8810b57cec5SDimitry Andric for (COFFShortExport e1 : m.Exports) { 8820b57cec5SDimitry Andric Export e2; 8830b57cec5SDimitry Andric // In simple cases, only Name is set. Renamed exports are parsed 8840b57cec5SDimitry Andric // and set as "ExtName = Name". If Name has the form "OtherDll.Func", 8850b57cec5SDimitry Andric // it shouldn't be a normal exported function but a forward to another 8860b57cec5SDimitry Andric // DLL instead. This is supported by both MS and GNU linkers. 8875ffd83dbSDimitry Andric if (!e1.ExtName.empty() && e1.ExtName != e1.Name && 8885ffd83dbSDimitry Andric StringRef(e1.Name).contains('.')) { 889*04eeddc0SDimitry Andric e2.name = saver().save(e1.ExtName); 890*04eeddc0SDimitry Andric e2.forwardTo = saver().save(e1.Name); 8910b57cec5SDimitry Andric config->exports.push_back(e2); 8920b57cec5SDimitry Andric continue; 8930b57cec5SDimitry Andric } 894*04eeddc0SDimitry Andric e2.name = saver().save(e1.Name); 895*04eeddc0SDimitry Andric e2.extName = saver().save(e1.ExtName); 896*04eeddc0SDimitry Andric e2.aliasTarget = saver().save(e1.AliasTarget); 8970b57cec5SDimitry Andric e2.ordinal = e1.Ordinal; 8980b57cec5SDimitry Andric e2.noname = e1.Noname; 8990b57cec5SDimitry Andric e2.data = e1.Data; 9000b57cec5SDimitry Andric e2.isPrivate = e1.Private; 9010b57cec5SDimitry Andric e2.constant = e1.Constant; 9020b57cec5SDimitry Andric config->exports.push_back(e2); 9030b57cec5SDimitry Andric } 9040b57cec5SDimitry Andric } 9050b57cec5SDimitry Andric 9060b57cec5SDimitry Andric void LinkerDriver::enqueueTask(std::function<void()> task) { 9070b57cec5SDimitry Andric taskQueue.push_back(std::move(task)); 9080b57cec5SDimitry Andric } 9090b57cec5SDimitry Andric 9100b57cec5SDimitry Andric bool LinkerDriver::run() { 911349cc55cSDimitry Andric ScopedTimer t(ctx.inputFileTimer); 9120b57cec5SDimitry Andric 9130b57cec5SDimitry Andric bool didWork = !taskQueue.empty(); 9140b57cec5SDimitry Andric while (!taskQueue.empty()) { 9150b57cec5SDimitry Andric taskQueue.front()(); 9160b57cec5SDimitry Andric taskQueue.pop_front(); 9170b57cec5SDimitry Andric } 9180b57cec5SDimitry Andric return didWork; 9190b57cec5SDimitry Andric } 9200b57cec5SDimitry Andric 9210b57cec5SDimitry Andric // Parse an /order file. If an option is given, the linker places 9220b57cec5SDimitry Andric // COMDAT sections in the same order as their names appear in the 9230b57cec5SDimitry Andric // given file. 924349cc55cSDimitry Andric static void parseOrderFile(COFFLinkerContext &ctx, StringRef arg) { 9250b57cec5SDimitry Andric // For some reason, the MSVC linker requires a filename to be 9260b57cec5SDimitry Andric // preceded by "@". 9270b57cec5SDimitry Andric if (!arg.startswith("@")) { 9280b57cec5SDimitry Andric error("malformed /order option: '@' missing"); 9290b57cec5SDimitry Andric return; 9300b57cec5SDimitry Andric } 9310b57cec5SDimitry Andric 9320b57cec5SDimitry Andric // Get a list of all comdat sections for error checking. 9330b57cec5SDimitry Andric DenseSet<StringRef> set; 934349cc55cSDimitry Andric for (Chunk *c : ctx.symtab.getChunks()) 9350b57cec5SDimitry Andric if (auto *sec = dyn_cast<SectionChunk>(c)) 9360b57cec5SDimitry Andric if (sec->sym) 9370b57cec5SDimitry Andric set.insert(sec->sym->getName()); 9380b57cec5SDimitry Andric 9390b57cec5SDimitry Andric // Open a file. 9400b57cec5SDimitry Andric StringRef path = arg.substr(1); 941fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 942fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 943fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 944fe6060f1SDimitry Andric /*IsVolatile=*/true), 945fe6060f1SDimitry Andric "could not open " + path); 9460b57cec5SDimitry Andric 9470b57cec5SDimitry Andric // Parse a file. An order file contains one symbol per line. 9480b57cec5SDimitry Andric // All symbols that were not present in a given order file are 9490b57cec5SDimitry Andric // considered to have the lowest priority 0 and are placed at 9500b57cec5SDimitry Andric // end of an output section. 9515ffd83dbSDimitry Andric for (StringRef arg : args::getLines(mb->getMemBufferRef())) { 9525ffd83dbSDimitry Andric std::string s(arg); 9530b57cec5SDimitry Andric if (config->machine == I386 && !isDecorated(s)) 9540b57cec5SDimitry Andric s = "_" + s; 9550b57cec5SDimitry Andric 9560b57cec5SDimitry Andric if (set.count(s) == 0) { 9570b57cec5SDimitry Andric if (config->warnMissingOrderSymbol) 9580b57cec5SDimitry Andric warn("/order:" + arg + ": missing symbol: " + s + " [LNK4037]"); 9590b57cec5SDimitry Andric } 9600b57cec5SDimitry Andric else 9610b57cec5SDimitry Andric config->order[s] = INT_MIN + config->order.size(); 9620b57cec5SDimitry Andric } 963fe6060f1SDimitry Andric 964fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 965fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 9660b57cec5SDimitry Andric } 9670b57cec5SDimitry Andric 968349cc55cSDimitry Andric static void parseCallGraphFile(COFFLinkerContext &ctx, StringRef path) { 969fe6060f1SDimitry Andric std::unique_ptr<MemoryBuffer> mb = 970fe6060f1SDimitry Andric CHECK(MemoryBuffer::getFile(path, /*IsText=*/false, 971fe6060f1SDimitry Andric /*RequiresNullTerminator=*/false, 972fe6060f1SDimitry Andric /*IsVolatile=*/true), 973fe6060f1SDimitry Andric "could not open " + path); 974e8d8bef9SDimitry Andric 975e8d8bef9SDimitry Andric // Build a map from symbol name to section. 976e8d8bef9SDimitry Andric DenseMap<StringRef, Symbol *> map; 977349cc55cSDimitry Andric for (ObjFile *file : ctx.objFileInstances) 978e8d8bef9SDimitry Andric for (Symbol *sym : file->getSymbols()) 979e8d8bef9SDimitry Andric if (sym) 980e8d8bef9SDimitry Andric map[sym->getName()] = sym; 981e8d8bef9SDimitry Andric 982e8d8bef9SDimitry Andric auto findSection = [&](StringRef name) -> SectionChunk * { 983e8d8bef9SDimitry Andric Symbol *sym = map.lookup(name); 984e8d8bef9SDimitry Andric if (!sym) { 985e8d8bef9SDimitry Andric if (config->warnMissingOrderSymbol) 986e8d8bef9SDimitry Andric warn(path + ": no such symbol: " + name); 987e8d8bef9SDimitry Andric return nullptr; 988e8d8bef9SDimitry Andric } 989e8d8bef9SDimitry Andric 990e8d8bef9SDimitry Andric if (DefinedCOFF *dr = dyn_cast_or_null<DefinedCOFF>(sym)) 991e8d8bef9SDimitry Andric return dyn_cast_or_null<SectionChunk>(dr->getChunk()); 992e8d8bef9SDimitry Andric return nullptr; 993e8d8bef9SDimitry Andric }; 994e8d8bef9SDimitry Andric 995e8d8bef9SDimitry Andric for (StringRef line : args::getLines(*mb)) { 996e8d8bef9SDimitry Andric SmallVector<StringRef, 3> fields; 997e8d8bef9SDimitry Andric line.split(fields, ' '); 998e8d8bef9SDimitry Andric uint64_t count; 999e8d8bef9SDimitry Andric 1000e8d8bef9SDimitry Andric if (fields.size() != 3 || !to_integer(fields[2], count)) { 1001e8d8bef9SDimitry Andric error(path + ": parse error"); 1002e8d8bef9SDimitry Andric return; 1003e8d8bef9SDimitry Andric } 1004e8d8bef9SDimitry Andric 1005e8d8bef9SDimitry Andric if (SectionChunk *from = findSection(fields[0])) 1006e8d8bef9SDimitry Andric if (SectionChunk *to = findSection(fields[1])) 1007e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1008e8d8bef9SDimitry Andric } 1009fe6060f1SDimitry Andric 1010fe6060f1SDimitry Andric // Include in /reproduce: output if applicable. 1011fe6060f1SDimitry Andric driver->takeBuffer(std::move(mb)); 1012e8d8bef9SDimitry Andric } 1013e8d8bef9SDimitry Andric 1014349cc55cSDimitry Andric static void readCallGraphsFromObjectFiles(COFFLinkerContext &ctx) { 1015349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 1016e8d8bef9SDimitry Andric if (obj->callgraphSec) { 1017e8d8bef9SDimitry Andric ArrayRef<uint8_t> contents; 1018e8d8bef9SDimitry Andric cantFail( 1019e8d8bef9SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->callgraphSec, contents)); 1020e8d8bef9SDimitry Andric BinaryStreamReader reader(contents, support::little); 1021e8d8bef9SDimitry Andric while (!reader.empty()) { 1022e8d8bef9SDimitry Andric uint32_t fromIndex, toIndex; 1023e8d8bef9SDimitry Andric uint64_t count; 1024e8d8bef9SDimitry Andric if (Error err = reader.readInteger(fromIndex)) 1025e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1026e8d8bef9SDimitry Andric if (Error err = reader.readInteger(toIndex)) 1027e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 32-bit integer"); 1028e8d8bef9SDimitry Andric if (Error err = reader.readInteger(count)) 1029e8d8bef9SDimitry Andric fatal(toString(obj) + ": Expected 64-bit integer"); 1030e8d8bef9SDimitry Andric auto *fromSym = dyn_cast_or_null<Defined>(obj->getSymbol(fromIndex)); 1031e8d8bef9SDimitry Andric auto *toSym = dyn_cast_or_null<Defined>(obj->getSymbol(toIndex)); 1032e8d8bef9SDimitry Andric if (!fromSym || !toSym) 1033e8d8bef9SDimitry Andric continue; 1034e8d8bef9SDimitry Andric auto *from = dyn_cast_or_null<SectionChunk>(fromSym->getChunk()); 1035e8d8bef9SDimitry Andric auto *to = dyn_cast_or_null<SectionChunk>(toSym->getChunk()); 1036e8d8bef9SDimitry Andric if (from && to) 1037e8d8bef9SDimitry Andric config->callGraphProfile[{from, to}] += count; 1038e8d8bef9SDimitry Andric } 1039e8d8bef9SDimitry Andric } 1040e8d8bef9SDimitry Andric } 1041e8d8bef9SDimitry Andric } 1042e8d8bef9SDimitry Andric 10430b57cec5SDimitry Andric static void markAddrsig(Symbol *s) { 10440b57cec5SDimitry Andric if (auto *d = dyn_cast_or_null<Defined>(s)) 10450b57cec5SDimitry Andric if (SectionChunk *c = dyn_cast_or_null<SectionChunk>(d->getChunk())) 10460b57cec5SDimitry Andric c->keepUnique = true; 10470b57cec5SDimitry Andric } 10480b57cec5SDimitry Andric 1049349cc55cSDimitry Andric static void findKeepUniqueSections(COFFLinkerContext &ctx) { 10500b57cec5SDimitry Andric // Exported symbols could be address-significant in other executables or DSOs, 10510b57cec5SDimitry Andric // so we conservatively mark them as address-significant. 10520b57cec5SDimitry Andric for (Export &r : config->exports) 10530b57cec5SDimitry Andric markAddrsig(r.sym); 10540b57cec5SDimitry Andric 10550b57cec5SDimitry Andric // Visit the address-significance table in each object file and mark each 10560b57cec5SDimitry Andric // referenced symbol as address-significant. 1057349cc55cSDimitry Andric for (ObjFile *obj : ctx.objFileInstances) { 10580b57cec5SDimitry Andric ArrayRef<Symbol *> syms = obj->getSymbols(); 10590b57cec5SDimitry Andric if (obj->addrsigSec) { 10600b57cec5SDimitry Andric ArrayRef<uint8_t> contents; 10610b57cec5SDimitry Andric cantFail( 10620b57cec5SDimitry Andric obj->getCOFFObj()->getSectionContents(obj->addrsigSec, contents)); 10630b57cec5SDimitry Andric const uint8_t *cur = contents.begin(); 10640b57cec5SDimitry Andric while (cur != contents.end()) { 10650b57cec5SDimitry Andric unsigned size; 10660b57cec5SDimitry Andric const char *err; 10670b57cec5SDimitry Andric uint64_t symIndex = decodeULEB128(cur, &size, contents.end(), &err); 10680b57cec5SDimitry Andric if (err) 10690b57cec5SDimitry Andric fatal(toString(obj) + ": could not decode addrsig section: " + err); 10700b57cec5SDimitry Andric if (symIndex >= syms.size()) 10710b57cec5SDimitry Andric fatal(toString(obj) + ": invalid symbol index in addrsig section"); 10720b57cec5SDimitry Andric markAddrsig(syms[symIndex]); 10730b57cec5SDimitry Andric cur += size; 10740b57cec5SDimitry Andric } 10750b57cec5SDimitry Andric } else { 10760b57cec5SDimitry Andric // If an object file does not have an address-significance table, 10770b57cec5SDimitry Andric // conservatively mark all of its symbols as address-significant. 10780b57cec5SDimitry Andric for (Symbol *s : syms) 10790b57cec5SDimitry Andric markAddrsig(s); 10800b57cec5SDimitry Andric } 10810b57cec5SDimitry Andric } 10820b57cec5SDimitry Andric } 10830b57cec5SDimitry Andric 10840b57cec5SDimitry Andric // link.exe replaces each %foo% in altPath with the contents of environment 10850b57cec5SDimitry Andric // variable foo, and adds the two magic env vars _PDB (expands to the basename 10860b57cec5SDimitry Andric // of pdb's output path) and _EXT (expands to the extension of the output 10870b57cec5SDimitry Andric // binary). 10880b57cec5SDimitry Andric // lld only supports %_PDB% and %_EXT% and warns on references to all other env 10890b57cec5SDimitry Andric // vars. 10900b57cec5SDimitry Andric static void parsePDBAltPath(StringRef altPath) { 10910b57cec5SDimitry Andric SmallString<128> buf; 10920b57cec5SDimitry Andric StringRef pdbBasename = 10930b57cec5SDimitry Andric sys::path::filename(config->pdbPath, sys::path::Style::windows); 10940b57cec5SDimitry Andric StringRef binaryExtension = 10950b57cec5SDimitry Andric sys::path::extension(config->outputFile, sys::path::Style::windows); 10960b57cec5SDimitry Andric if (!binaryExtension.empty()) 10970b57cec5SDimitry Andric binaryExtension = binaryExtension.substr(1); // %_EXT% does not include '.'. 10980b57cec5SDimitry Andric 10990b57cec5SDimitry Andric // Invariant: 11000b57cec5SDimitry Andric // +--------- cursor ('a...' might be the empty string). 11010b57cec5SDimitry Andric // | +----- firstMark 11020b57cec5SDimitry Andric // | | +- secondMark 11030b57cec5SDimitry Andric // v v v 11040b57cec5SDimitry Andric // a...%...%... 11050b57cec5SDimitry Andric size_t cursor = 0; 11060b57cec5SDimitry Andric while (cursor < altPath.size()) { 11070b57cec5SDimitry Andric size_t firstMark, secondMark; 11080b57cec5SDimitry Andric if ((firstMark = altPath.find('%', cursor)) == StringRef::npos || 11090b57cec5SDimitry Andric (secondMark = altPath.find('%', firstMark + 1)) == StringRef::npos) { 11100b57cec5SDimitry Andric // Didn't find another full fragment, treat rest of string as literal. 11110b57cec5SDimitry Andric buf.append(altPath.substr(cursor)); 11120b57cec5SDimitry Andric break; 11130b57cec5SDimitry Andric } 11140b57cec5SDimitry Andric 11150b57cec5SDimitry Andric // Found a full fragment. Append text in front of first %, and interpret 11160b57cec5SDimitry Andric // text between first and second % as variable name. 11170b57cec5SDimitry Andric buf.append(altPath.substr(cursor, firstMark - cursor)); 11180b57cec5SDimitry Andric StringRef var = altPath.substr(firstMark, secondMark - firstMark + 1); 1119fe6060f1SDimitry Andric if (var.equals_insensitive("%_pdb%")) 11200b57cec5SDimitry Andric buf.append(pdbBasename); 1121fe6060f1SDimitry Andric else if (var.equals_insensitive("%_ext%")) 11220b57cec5SDimitry Andric buf.append(binaryExtension); 11230b57cec5SDimitry Andric else { 11240b57cec5SDimitry Andric warn("only %_PDB% and %_EXT% supported in /pdbaltpath:, keeping " + 11250b57cec5SDimitry Andric var + " as literal"); 11260b57cec5SDimitry Andric buf.append(var); 11270b57cec5SDimitry Andric } 11280b57cec5SDimitry Andric 11290b57cec5SDimitry Andric cursor = secondMark + 1; 11300b57cec5SDimitry Andric } 11310b57cec5SDimitry Andric 11320b57cec5SDimitry Andric config->pdbAltPath = buf; 11330b57cec5SDimitry Andric } 11340b57cec5SDimitry Andric 113585868e8aSDimitry Andric /// Convert resource files and potentially merge input resource object 113685868e8aSDimitry Andric /// trees into one resource tree. 11370b57cec5SDimitry Andric /// Call after ObjFile::Instances is complete. 113885868e8aSDimitry Andric void LinkerDriver::convertResources() { 113985868e8aSDimitry Andric std::vector<ObjFile *> resourceObjFiles; 114085868e8aSDimitry Andric 1141349cc55cSDimitry Andric for (ObjFile *f : ctx.objFileInstances) { 114285868e8aSDimitry Andric if (f->isResourceObjFile()) 114385868e8aSDimitry Andric resourceObjFiles.push_back(f); 11440b57cec5SDimitry Andric } 11450b57cec5SDimitry Andric 114685868e8aSDimitry Andric if (!config->mingw && 114785868e8aSDimitry Andric (resourceObjFiles.size() > 1 || 114885868e8aSDimitry Andric (resourceObjFiles.size() == 1 && !resources.empty()))) { 114985868e8aSDimitry Andric error((!resources.empty() ? "internal .obj file created from .res files" 115085868e8aSDimitry Andric : toString(resourceObjFiles[1])) + 11510b57cec5SDimitry Andric ": more than one resource obj file not allowed, already got " + 115285868e8aSDimitry Andric toString(resourceObjFiles.front())); 115385868e8aSDimitry Andric return; 11540b57cec5SDimitry Andric } 115585868e8aSDimitry Andric 115685868e8aSDimitry Andric if (resources.empty() && resourceObjFiles.size() <= 1) { 115785868e8aSDimitry Andric // No resources to convert, and max one resource object file in 115885868e8aSDimitry Andric // the input. Keep that preconverted resource section as is. 115985868e8aSDimitry Andric for (ObjFile *f : resourceObjFiles) 116085868e8aSDimitry Andric f->includeResourceChunks(); 116185868e8aSDimitry Andric return; 116285868e8aSDimitry Andric } 1163349cc55cSDimitry Andric ObjFile *f = 1164349cc55cSDimitry Andric make<ObjFile>(ctx, convertResToCOFF(resources, resourceObjFiles)); 1165349cc55cSDimitry Andric ctx.symtab.addFile(f); 116685868e8aSDimitry Andric f->includeResourceChunks(); 11670b57cec5SDimitry Andric } 11680b57cec5SDimitry Andric 11690b57cec5SDimitry Andric // In MinGW, if no symbols are chosen to be exported, then all symbols are 11700b57cec5SDimitry Andric // automatically exported by default. This behavior can be forced by the 11710b57cec5SDimitry Andric // -export-all-symbols option, so that it happens even when exports are 11720b57cec5SDimitry Andric // explicitly specified. The automatic behavior can be disabled using the 11730b57cec5SDimitry Andric // -exclude-all-symbols option, so that lld-link behaves like link.exe rather 11740b57cec5SDimitry Andric // than MinGW in the case that nothing is explicitly exported. 11750b57cec5SDimitry Andric void LinkerDriver::maybeExportMinGWSymbols(const opt::InputArgList &args) { 1176fe6060f1SDimitry Andric if (!args.hasArg(OPT_export_all_symbols)) { 11770b57cec5SDimitry Andric if (!config->dll) 11780b57cec5SDimitry Andric return; 11790b57cec5SDimitry Andric 11800b57cec5SDimitry Andric if (!config->exports.empty()) 11810b57cec5SDimitry Andric return; 11820b57cec5SDimitry Andric if (args.hasArg(OPT_exclude_all_symbols)) 11830b57cec5SDimitry Andric return; 11840b57cec5SDimitry Andric } 11850b57cec5SDimitry Andric 11860b57cec5SDimitry Andric AutoExporter exporter; 11870b57cec5SDimitry Andric 11880b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 11890b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 11900b57cec5SDimitry Andric exporter.addWholeArchive(*path); 11910b57cec5SDimitry Andric 1192349cc55cSDimitry Andric ctx.symtab.forEachSymbol([&](Symbol *s) { 11930b57cec5SDimitry Andric auto *def = dyn_cast<Defined>(s); 1194349cc55cSDimitry Andric if (!exporter.shouldExport(ctx, def)) 11950b57cec5SDimitry Andric return; 11960b57cec5SDimitry Andric 1197fe6060f1SDimitry Andric if (!def->isGCRoot) { 1198fe6060f1SDimitry Andric def->isGCRoot = true; 1199fe6060f1SDimitry Andric config->gcroot.push_back(def); 1200fe6060f1SDimitry Andric } 1201fe6060f1SDimitry Andric 12020b57cec5SDimitry Andric Export e; 12030b57cec5SDimitry Andric e.name = def->getName(); 12040b57cec5SDimitry Andric e.sym = def; 12050b57cec5SDimitry Andric if (Chunk *c = def->getChunk()) 12060b57cec5SDimitry Andric if (!(c->getOutputCharacteristics() & IMAGE_SCN_MEM_EXECUTE)) 12070b57cec5SDimitry Andric e.data = true; 1208fe6060f1SDimitry Andric s->isUsedInRegularObj = true; 12090b57cec5SDimitry Andric config->exports.push_back(e); 12100b57cec5SDimitry Andric }); 12110b57cec5SDimitry Andric } 12120b57cec5SDimitry Andric 121385868e8aSDimitry Andric // lld has a feature to create a tar file containing all input files as well as 121485868e8aSDimitry Andric // all command line options, so that other people can run lld again with exactly 121585868e8aSDimitry Andric // the same inputs. This feature is accessible via /linkrepro and /reproduce. 121685868e8aSDimitry Andric // 121785868e8aSDimitry Andric // /linkrepro and /reproduce are very similar, but /linkrepro takes a directory 121885868e8aSDimitry Andric // name while /reproduce takes a full path. We have /linkrepro for compatibility 121985868e8aSDimitry Andric // with Microsoft link.exe. 122085868e8aSDimitry Andric Optional<std::string> getReproduceFile(const opt::InputArgList &args) { 122185868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_reproduce)) 122285868e8aSDimitry Andric return std::string(arg->getValue()); 122385868e8aSDimitry Andric 122485868e8aSDimitry Andric if (auto *arg = args.getLastArg(OPT_linkrepro)) { 122585868e8aSDimitry Andric SmallString<64> path = StringRef(arg->getValue()); 122685868e8aSDimitry Andric sys::path::append(path, "repro.tar"); 12275ffd83dbSDimitry Andric return std::string(path); 122885868e8aSDimitry Andric } 122985868e8aSDimitry Andric 1230e8d8bef9SDimitry Andric // This is intentionally not guarded by OPT_lldignoreenv since writing 1231e8d8bef9SDimitry Andric // a repro tar file doesn't affect the main output. 1232e8d8bef9SDimitry Andric if (auto *path = getenv("LLD_REPRODUCE")) 1233e8d8bef9SDimitry Andric return std::string(path); 1234e8d8bef9SDimitry Andric 123585868e8aSDimitry Andric return None; 123685868e8aSDimitry Andric } 12370b57cec5SDimitry Andric 1238e8d8bef9SDimitry Andric void LinkerDriver::linkerMain(ArrayRef<const char *> argsArr) { 1239349cc55cSDimitry Andric ScopedTimer rootTimer(ctx.rootTimer); 12405ffd83dbSDimitry Andric 12410b57cec5SDimitry Andric // Needed for LTO. 12420b57cec5SDimitry Andric InitializeAllTargetInfos(); 12430b57cec5SDimitry Andric InitializeAllTargets(); 12440b57cec5SDimitry Andric InitializeAllTargetMCs(); 12450b57cec5SDimitry Andric InitializeAllAsmParsers(); 12460b57cec5SDimitry Andric InitializeAllAsmPrinters(); 12470b57cec5SDimitry Andric 12480b57cec5SDimitry Andric // If the first command line argument is "/lib", link.exe acts like lib.exe. 12490b57cec5SDimitry Andric // We call our own implementation of lib.exe that understands bitcode files. 1250fe6060f1SDimitry Andric if (argsArr.size() > 1 && 1251fe6060f1SDimitry Andric (StringRef(argsArr[1]).equals_insensitive("/lib") || 1252fe6060f1SDimitry Andric StringRef(argsArr[1]).equals_insensitive("-lib"))) { 12530b57cec5SDimitry Andric if (llvm::libDriverMain(argsArr.slice(1)) != 0) 12540b57cec5SDimitry Andric fatal("lib failed"); 12550b57cec5SDimitry Andric return; 12560b57cec5SDimitry Andric } 12570b57cec5SDimitry Andric 12580b57cec5SDimitry Andric // Parse command line options. 12590b57cec5SDimitry Andric ArgParser parser; 126085868e8aSDimitry Andric opt::InputArgList args = parser.parse(argsArr); 12610b57cec5SDimitry Andric 12620b57cec5SDimitry Andric // Parse and evaluate -mllvm options. 12630b57cec5SDimitry Andric std::vector<const char *> v; 12640b57cec5SDimitry Andric v.push_back("lld-link (LLVM option parsing)"); 12650b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_mllvm)) 12660b57cec5SDimitry Andric v.push_back(arg->getValue()); 1267e8d8bef9SDimitry Andric cl::ResetAllOptionOccurrences(); 12680b57cec5SDimitry Andric cl::ParseCommandLineOptions(v.size(), v.data()); 12690b57cec5SDimitry Andric 12700b57cec5SDimitry Andric // Handle /errorlimit early, because error() depends on it. 12710b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_errorlimit)) { 12720b57cec5SDimitry Andric int n = 20; 12730b57cec5SDimitry Andric StringRef s = arg->getValue(); 12740b57cec5SDimitry Andric if (s.getAsInteger(10, n)) 12750b57cec5SDimitry Andric error(arg->getSpelling() + " number expected, but got " + s); 12760b57cec5SDimitry Andric errorHandler().errorLimit = n; 12770b57cec5SDimitry Andric } 12780b57cec5SDimitry Andric 12790b57cec5SDimitry Andric // Handle /help 12800b57cec5SDimitry Andric if (args.hasArg(OPT_help)) { 12810b57cec5SDimitry Andric printHelp(argsArr[0]); 12820b57cec5SDimitry Andric return; 12830b57cec5SDimitry Andric } 12840b57cec5SDimitry Andric 12855ffd83dbSDimitry Andric // /threads: takes a positive integer and provides the default value for 12865ffd83dbSDimitry Andric // /opt:lldltojobs=. 12875ffd83dbSDimitry Andric if (auto *arg = args.getLastArg(OPT_threads)) { 12885ffd83dbSDimitry Andric StringRef v(arg->getValue()); 12895ffd83dbSDimitry Andric unsigned threads = 0; 12905ffd83dbSDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 12915ffd83dbSDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 12925ffd83dbSDimitry Andric arg->getValue() + "'"); 12935ffd83dbSDimitry Andric parallel::strategy = hardware_concurrency(threads); 12945ffd83dbSDimitry Andric config->thinLTOJobs = v.str(); 12955ffd83dbSDimitry Andric } 12960b57cec5SDimitry Andric 12970b57cec5SDimitry Andric if (args.hasArg(OPT_show_timing)) 12980b57cec5SDimitry Andric config->showTiming = true; 12990b57cec5SDimitry Andric 13000b57cec5SDimitry Andric config->showSummary = args.hasArg(OPT_summary); 13010b57cec5SDimitry Andric 13020b57cec5SDimitry Andric // Handle --version, which is an lld extension. This option is a bit odd 13030b57cec5SDimitry Andric // because it doesn't start with "/", but we deliberately chose "--" to 13040b57cec5SDimitry Andric // avoid conflict with /version and for compatibility with clang-cl. 13050b57cec5SDimitry Andric if (args.hasArg(OPT_dash_dash_version)) { 1306e8d8bef9SDimitry Andric message(getLLDVersion()); 13070b57cec5SDimitry Andric return; 13080b57cec5SDimitry Andric } 13090b57cec5SDimitry Andric 13100b57cec5SDimitry Andric // Handle /lldmingw early, since it can potentially affect how other 13110b57cec5SDimitry Andric // options are handled. 13120b57cec5SDimitry Andric config->mingw = args.hasArg(OPT_lldmingw); 13130b57cec5SDimitry Andric 131485868e8aSDimitry Andric // Handle /linkrepro and /reproduce. 131585868e8aSDimitry Andric if (Optional<std::string> path = getReproduceFile(args)) { 13160b57cec5SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 131785868e8aSDimitry Andric TarWriter::create(*path, sys::path::stem(*path)); 13180b57cec5SDimitry Andric 13190b57cec5SDimitry Andric if (errOrWriter) { 13200b57cec5SDimitry Andric tar = std::move(*errOrWriter); 13210b57cec5SDimitry Andric } else { 132285868e8aSDimitry Andric error("/linkrepro: failed to open " + *path + ": " + 13230b57cec5SDimitry Andric toString(errOrWriter.takeError())); 13240b57cec5SDimitry Andric } 13250b57cec5SDimitry Andric } 13260b57cec5SDimitry Andric 1327480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 13280b57cec5SDimitry Andric if (args.hasArg(OPT_deffile)) 13290b57cec5SDimitry Andric config->noEntry = true; 13300b57cec5SDimitry Andric else 13310b57cec5SDimitry Andric fatal("no input files"); 13320b57cec5SDimitry Andric } 13330b57cec5SDimitry Andric 13340b57cec5SDimitry Andric // Construct search path list. 13350b57cec5SDimitry Andric searchPaths.push_back(""); 13360b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_libpath)) 13370b57cec5SDimitry Andric searchPaths.push_back(arg->getValue()); 133885868e8aSDimitry Andric if (!args.hasArg(OPT_lldignoreenv)) 13390b57cec5SDimitry Andric addLibSearchPaths(); 13400b57cec5SDimitry Andric 13410b57cec5SDimitry Andric // Handle /ignore 13420b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_ignore)) { 13430b57cec5SDimitry Andric SmallVector<StringRef, 8> vec; 13440b57cec5SDimitry Andric StringRef(arg->getValue()).split(vec, ','); 13450b57cec5SDimitry Andric for (StringRef s : vec) { 13460b57cec5SDimitry Andric if (s == "4037") 13470b57cec5SDimitry Andric config->warnMissingOrderSymbol = false; 13480b57cec5SDimitry Andric else if (s == "4099") 13490b57cec5SDimitry Andric config->warnDebugInfoUnusable = false; 13500b57cec5SDimitry Andric else if (s == "4217") 13510b57cec5SDimitry Andric config->warnLocallyDefinedImported = false; 1352480093f4SDimitry Andric else if (s == "longsections") 1353480093f4SDimitry Andric config->warnLongSectionNames = false; 13540b57cec5SDimitry Andric // Other warning numbers are ignored. 13550b57cec5SDimitry Andric } 13560b57cec5SDimitry Andric } 13570b57cec5SDimitry Andric 13580b57cec5SDimitry Andric // Handle /out 13590b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_out)) 13600b57cec5SDimitry Andric config->outputFile = arg->getValue(); 13610b57cec5SDimitry Andric 13620b57cec5SDimitry Andric // Handle /verbose 13630b57cec5SDimitry Andric if (args.hasArg(OPT_verbose)) 13640b57cec5SDimitry Andric config->verbose = true; 13650b57cec5SDimitry Andric errorHandler().verbose = config->verbose; 13660b57cec5SDimitry Andric 13670b57cec5SDimitry Andric // Handle /force or /force:unresolved 13680b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_unresolved)) 13690b57cec5SDimitry Andric config->forceUnresolved = true; 13700b57cec5SDimitry Andric 13710b57cec5SDimitry Andric // Handle /force or /force:multiple 13720b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multiple)) 13730b57cec5SDimitry Andric config->forceMultiple = true; 13740b57cec5SDimitry Andric 13750b57cec5SDimitry Andric // Handle /force or /force:multipleres 13760b57cec5SDimitry Andric if (args.hasArg(OPT_force, OPT_force_multipleres)) 13770b57cec5SDimitry Andric config->forceMultipleRes = true; 13780b57cec5SDimitry Andric 13790b57cec5SDimitry Andric // Handle /debug 13800b57cec5SDimitry Andric DebugKind debug = parseDebugKind(args); 13810b57cec5SDimitry Andric if (debug == DebugKind::Full || debug == DebugKind::Dwarf || 1382fe6060f1SDimitry Andric debug == DebugKind::GHash || debug == DebugKind::NoGHash) { 13830b57cec5SDimitry Andric config->debug = true; 13840b57cec5SDimitry Andric config->incremental = true; 13850b57cec5SDimitry Andric } 13860b57cec5SDimitry Andric 13870b57cec5SDimitry Andric // Handle /demangle 13880b57cec5SDimitry Andric config->demangle = args.hasFlag(OPT_demangle, OPT_demangle_no); 13890b57cec5SDimitry Andric 13900b57cec5SDimitry Andric // Handle /debugtype 13910b57cec5SDimitry Andric config->debugTypes = parseDebugTypes(args); 13920b57cec5SDimitry Andric 1393480093f4SDimitry Andric // Handle /driver[:uponly|:wdm]. 1394480093f4SDimitry Andric config->driverUponly = args.hasArg(OPT_driver_uponly) || 1395480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1396480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1397480093f4SDimitry Andric config->driverWdm = args.hasArg(OPT_driver_wdm) || 1398480093f4SDimitry Andric args.hasArg(OPT_driver_uponly_wdm) || 1399480093f4SDimitry Andric args.hasArg(OPT_driver_wdm_uponly); 1400480093f4SDimitry Andric config->driver = 1401480093f4SDimitry Andric config->driverUponly || config->driverWdm || args.hasArg(OPT_driver); 1402480093f4SDimitry Andric 14030b57cec5SDimitry Andric // Handle /pdb 14040b57cec5SDimitry Andric bool shouldCreatePDB = 1405fe6060f1SDimitry Andric (debug == DebugKind::Full || debug == DebugKind::GHash || 1406fe6060f1SDimitry Andric debug == DebugKind::NoGHash); 14070b57cec5SDimitry Andric if (shouldCreatePDB) { 14080b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb)) 14090b57cec5SDimitry Andric config->pdbPath = arg->getValue(); 14100b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbaltpath)) 14110b57cec5SDimitry Andric config->pdbAltPath = arg->getValue(); 1412349cc55cSDimitry Andric if (auto *arg = args.getLastArg(OPT_pdbpagesize)) 1413349cc55cSDimitry Andric parsePDBPageSize(arg->getValue()); 14140b57cec5SDimitry Andric if (args.hasArg(OPT_natvis)) 14150b57cec5SDimitry Andric config->natvisFiles = args.getAllArgValues(OPT_natvis); 14165ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstream)) { 14175ffd83dbSDimitry Andric for (const StringRef value : args.getAllArgValues(OPT_pdbstream)) { 14185ffd83dbSDimitry Andric const std::pair<StringRef, StringRef> nameFile = value.split("="); 14195ffd83dbSDimitry Andric const StringRef name = nameFile.first; 14205ffd83dbSDimitry Andric const std::string file = nameFile.second.str(); 14215ffd83dbSDimitry Andric config->namedStreams[name] = file; 14225ffd83dbSDimitry Andric } 14235ffd83dbSDimitry Andric } 14240b57cec5SDimitry Andric 14250b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_pdb_source_path)) 14260b57cec5SDimitry Andric config->pdbSourcePath = arg->getValue(); 14270b57cec5SDimitry Andric } 14280b57cec5SDimitry Andric 14295ffd83dbSDimitry Andric // Handle /pdbstripped 14305ffd83dbSDimitry Andric if (args.hasArg(OPT_pdbstripped)) 14315ffd83dbSDimitry Andric warn("ignoring /pdbstripped flag, it is not yet supported"); 14325ffd83dbSDimitry Andric 14330b57cec5SDimitry Andric // Handle /noentry 14340b57cec5SDimitry Andric if (args.hasArg(OPT_noentry)) { 14350b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) 14360b57cec5SDimitry Andric config->noEntry = true; 14370b57cec5SDimitry Andric else 14380b57cec5SDimitry Andric error("/noentry must be specified with /dll"); 14390b57cec5SDimitry Andric } 14400b57cec5SDimitry Andric 14410b57cec5SDimitry Andric // Handle /dll 14420b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 14430b57cec5SDimitry Andric config->dll = true; 14440b57cec5SDimitry Andric config->manifestID = 2; 14450b57cec5SDimitry Andric } 14460b57cec5SDimitry Andric 14470b57cec5SDimitry Andric // Handle /dynamicbase and /fixed. We can't use hasFlag for /dynamicbase 14480b57cec5SDimitry Andric // because we need to explicitly check whether that option or its inverse was 14490b57cec5SDimitry Andric // present in the argument list in order to handle /fixed. 14500b57cec5SDimitry Andric auto *dynamicBaseArg = args.getLastArg(OPT_dynamicbase, OPT_dynamicbase_no); 14510b57cec5SDimitry Andric if (dynamicBaseArg && 14520b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase_no) 14530b57cec5SDimitry Andric config->dynamicBase = false; 14540b57cec5SDimitry Andric 14550b57cec5SDimitry Andric // MSDN claims "/FIXED:NO is the default setting for a DLL, and /FIXED is the 14560b57cec5SDimitry Andric // default setting for any other project type.", but link.exe defaults to 14570b57cec5SDimitry Andric // /FIXED:NO for exe outputs as well. Match behavior, not docs. 14580b57cec5SDimitry Andric bool fixed = args.hasFlag(OPT_fixed, OPT_fixed_no, false); 14590b57cec5SDimitry Andric if (fixed) { 14600b57cec5SDimitry Andric if (dynamicBaseArg && 14610b57cec5SDimitry Andric dynamicBaseArg->getOption().getID() == OPT_dynamicbase) { 14620b57cec5SDimitry Andric error("/fixed must not be specified with /dynamicbase"); 14630b57cec5SDimitry Andric } else { 14640b57cec5SDimitry Andric config->relocatable = false; 14650b57cec5SDimitry Andric config->dynamicBase = false; 14660b57cec5SDimitry Andric } 14670b57cec5SDimitry Andric } 14680b57cec5SDimitry Andric 14690b57cec5SDimitry Andric // Handle /appcontainer 14700b57cec5SDimitry Andric config->appContainer = 14710b57cec5SDimitry Andric args.hasFlag(OPT_appcontainer, OPT_appcontainer_no, false); 14720b57cec5SDimitry Andric 14730b57cec5SDimitry Andric // Handle /machine 14740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_machine)) { 14750b57cec5SDimitry Andric config->machine = getMachineType(arg->getValue()); 14760b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) 14770b57cec5SDimitry Andric fatal(Twine("unknown /machine argument: ") + arg->getValue()); 14780b57cec5SDimitry Andric } 14790b57cec5SDimitry Andric 14800b57cec5SDimitry Andric // Handle /nodefaultlib:<filename> 14810b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_nodefaultlib)) 14820b57cec5SDimitry Andric config->noDefaultLibs.insert(doFindLib(arg->getValue()).lower()); 14830b57cec5SDimitry Andric 14840b57cec5SDimitry Andric // Handle /nodefaultlib 14850b57cec5SDimitry Andric if (args.hasArg(OPT_nodefaultlib_all)) 14860b57cec5SDimitry Andric config->noDefaultLibAll = true; 14870b57cec5SDimitry Andric 14880b57cec5SDimitry Andric // Handle /base 14890b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_base)) 14900b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->imageBase); 14910b57cec5SDimitry Andric 14920b57cec5SDimitry Andric // Handle /filealign 14930b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_filealign)) { 14940b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->fileAlign); 14950b57cec5SDimitry Andric if (!isPowerOf2_64(config->fileAlign)) 14960b57cec5SDimitry Andric error("/filealign: not a power of two: " + Twine(config->fileAlign)); 14970b57cec5SDimitry Andric } 14980b57cec5SDimitry Andric 14990b57cec5SDimitry Andric // Handle /stack 15000b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_stack)) 15010b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->stackReserve, &config->stackCommit); 15020b57cec5SDimitry Andric 15030b57cec5SDimitry Andric // Handle /guard:cf 15040b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_guard)) 15050b57cec5SDimitry Andric parseGuard(arg->getValue()); 15060b57cec5SDimitry Andric 15070b57cec5SDimitry Andric // Handle /heap 15080b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_heap)) 15090b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->heapReserve, &config->heapCommit); 15100b57cec5SDimitry Andric 15110b57cec5SDimitry Andric // Handle /version 15120b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_version)) 15130b57cec5SDimitry Andric parseVersion(arg->getValue(), &config->majorImageVersion, 15140b57cec5SDimitry Andric &config->minorImageVersion); 15150b57cec5SDimitry Andric 15160b57cec5SDimitry Andric // Handle /subsystem 15170b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_subsystem)) 1518e8d8bef9SDimitry Andric parseSubsystem(arg->getValue(), &config->subsystem, 1519e8d8bef9SDimitry Andric &config->majorSubsystemVersion, 1520e8d8bef9SDimitry Andric &config->minorSubsystemVersion); 1521e8d8bef9SDimitry Andric 1522e8d8bef9SDimitry Andric // Handle /osversion 1523e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_osversion)) { 1524e8d8bef9SDimitry Andric parseVersion(arg->getValue(), &config->majorOSVersion, 15250b57cec5SDimitry Andric &config->minorOSVersion); 1526e8d8bef9SDimitry Andric } else { 1527e8d8bef9SDimitry Andric config->majorOSVersion = config->majorSubsystemVersion; 1528e8d8bef9SDimitry Andric config->minorOSVersion = config->minorSubsystemVersion; 1529e8d8bef9SDimitry Andric } 15300b57cec5SDimitry Andric 15310b57cec5SDimitry Andric // Handle /timestamp 15320b57cec5SDimitry Andric if (llvm::opt::Arg *arg = args.getLastArg(OPT_timestamp, OPT_repro)) { 15330b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_repro) { 15340b57cec5SDimitry Andric config->timestamp = 0; 15350b57cec5SDimitry Andric config->repro = true; 15360b57cec5SDimitry Andric } else { 15370b57cec5SDimitry Andric config->repro = false; 15380b57cec5SDimitry Andric StringRef value(arg->getValue()); 15390b57cec5SDimitry Andric if (value.getAsInteger(0, config->timestamp)) 15400b57cec5SDimitry Andric fatal(Twine("invalid timestamp: ") + value + 15410b57cec5SDimitry Andric ". Expected 32-bit integer"); 15420b57cec5SDimitry Andric } 15430b57cec5SDimitry Andric } else { 15440b57cec5SDimitry Andric config->repro = false; 15450b57cec5SDimitry Andric config->timestamp = time(nullptr); 15460b57cec5SDimitry Andric } 15470b57cec5SDimitry Andric 15480b57cec5SDimitry Andric // Handle /alternatename 15490b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_alternatename)) 15500b57cec5SDimitry Andric parseAlternateName(arg->getValue()); 15510b57cec5SDimitry Andric 15520b57cec5SDimitry Andric // Handle /include 15530b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_incl)) 15540b57cec5SDimitry Andric addUndefined(arg->getValue()); 15550b57cec5SDimitry Andric 15560b57cec5SDimitry Andric // Handle /implib 15570b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_implib)) 15580b57cec5SDimitry Andric config->implib = arg->getValue(); 15590b57cec5SDimitry Andric 15600b57cec5SDimitry Andric // Handle /opt. 15610b57cec5SDimitry Andric bool doGC = debug == DebugKind::None || args.hasArg(OPT_profile); 1562fe6060f1SDimitry Andric Optional<ICFLevel> icfLevel = None; 1563fe6060f1SDimitry Andric if (args.hasArg(OPT_profile)) 1564fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 15650b57cec5SDimitry Andric unsigned tailMerge = 1; 1566e8d8bef9SDimitry Andric bool ltoNewPM = LLVM_ENABLE_NEW_PASS_MANAGER; 1567e8d8bef9SDimitry Andric bool ltoDebugPM = false; 15680b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_opt)) { 15690b57cec5SDimitry Andric std::string str = StringRef(arg->getValue()).lower(); 15700b57cec5SDimitry Andric SmallVector<StringRef, 1> vec; 15710b57cec5SDimitry Andric StringRef(str).split(vec, ','); 15720b57cec5SDimitry Andric for (StringRef s : vec) { 15730b57cec5SDimitry Andric if (s == "ref") { 15740b57cec5SDimitry Andric doGC = true; 15750b57cec5SDimitry Andric } else if (s == "noref") { 15760b57cec5SDimitry Andric doGC = false; 15770b57cec5SDimitry Andric } else if (s == "icf" || s.startswith("icf=")) { 1578fe6060f1SDimitry Andric icfLevel = ICFLevel::All; 1579fe6060f1SDimitry Andric } else if (s == "safeicf") { 1580fe6060f1SDimitry Andric icfLevel = ICFLevel::Safe; 15810b57cec5SDimitry Andric } else if (s == "noicf") { 1582fe6060f1SDimitry Andric icfLevel = ICFLevel::None; 15830b57cec5SDimitry Andric } else if (s == "lldtailmerge") { 15840b57cec5SDimitry Andric tailMerge = 2; 15850b57cec5SDimitry Andric } else if (s == "nolldtailmerge") { 15860b57cec5SDimitry Andric tailMerge = 0; 1587e8d8bef9SDimitry Andric } else if (s == "ltonewpassmanager") { 1588e8d8bef9SDimitry Andric ltoNewPM = true; 1589e8d8bef9SDimitry Andric } else if (s == "noltonewpassmanager") { 1590e8d8bef9SDimitry Andric ltoNewPM = false; 1591e8d8bef9SDimitry Andric } else if (s == "ltodebugpassmanager") { 1592e8d8bef9SDimitry Andric ltoDebugPM = true; 1593e8d8bef9SDimitry Andric } else if (s == "noltodebugpassmanager") { 1594e8d8bef9SDimitry Andric ltoDebugPM = false; 15950b57cec5SDimitry Andric } else if (s.startswith("lldlto=")) { 15960b57cec5SDimitry Andric StringRef optLevel = s.substr(7); 15970b57cec5SDimitry Andric if (optLevel.getAsInteger(10, config->ltoo) || config->ltoo > 3) 15980b57cec5SDimitry Andric error("/opt:lldlto: invalid optimization level: " + optLevel); 15990b57cec5SDimitry Andric } else if (s.startswith("lldltojobs=")) { 16000b57cec5SDimitry Andric StringRef jobs = s.substr(11); 16015ffd83dbSDimitry Andric if (!get_threadpool_strategy(jobs)) 16020b57cec5SDimitry Andric error("/opt:lldltojobs: invalid job count: " + jobs); 16035ffd83dbSDimitry Andric config->thinLTOJobs = jobs.str(); 16040b57cec5SDimitry Andric } else if (s.startswith("lldltopartitions=")) { 16050b57cec5SDimitry Andric StringRef n = s.substr(17); 16060b57cec5SDimitry Andric if (n.getAsInteger(10, config->ltoPartitions) || 16070b57cec5SDimitry Andric config->ltoPartitions == 0) 16080b57cec5SDimitry Andric error("/opt:lldltopartitions: invalid partition count: " + n); 16090b57cec5SDimitry Andric } else if (s != "lbr" && s != "nolbr") 16100b57cec5SDimitry Andric error("/opt: unknown option: " + s); 16110b57cec5SDimitry Andric } 16120b57cec5SDimitry Andric } 16130b57cec5SDimitry Andric 1614fe6060f1SDimitry Andric if (!icfLevel) 1615fe6060f1SDimitry Andric icfLevel = doGC ? ICFLevel::All : ICFLevel::None; 16160b57cec5SDimitry Andric config->doGC = doGC; 1617fe6060f1SDimitry Andric config->doICF = icfLevel.getValue(); 1618fe6060f1SDimitry Andric config->tailMerge = 1619fe6060f1SDimitry Andric (tailMerge == 1 && config->doICF != ICFLevel::None) || tailMerge == 2; 1620e8d8bef9SDimitry Andric config->ltoNewPassManager = ltoNewPM; 1621e8d8bef9SDimitry Andric config->ltoDebugPassManager = ltoDebugPM; 16220b57cec5SDimitry Andric 16230b57cec5SDimitry Andric // Handle /lldsavetemps 16240b57cec5SDimitry Andric if (args.hasArg(OPT_lldsavetemps)) 16250b57cec5SDimitry Andric config->saveTemps = true; 16260b57cec5SDimitry Andric 16270b57cec5SDimitry Andric // Handle /kill-at 16280b57cec5SDimitry Andric if (args.hasArg(OPT_kill_at)) 16290b57cec5SDimitry Andric config->killAt = true; 16300b57cec5SDimitry Andric 16310b57cec5SDimitry Andric // Handle /lldltocache 16320b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocache)) 16330b57cec5SDimitry Andric config->ltoCache = arg->getValue(); 16340b57cec5SDimitry Andric 16350b57cec5SDimitry Andric // Handle /lldsavecachepolicy 16360b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_lldltocachepolicy)) 16370b57cec5SDimitry Andric config->ltoCachePolicy = CHECK( 16380b57cec5SDimitry Andric parseCachePruningPolicy(arg->getValue()), 16390b57cec5SDimitry Andric Twine("/lldltocachepolicy: invalid cache policy: ") + arg->getValue()); 16400b57cec5SDimitry Andric 16410b57cec5SDimitry Andric // Handle /failifmismatch 16420b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_failifmismatch)) 16430b57cec5SDimitry Andric checkFailIfMismatch(arg->getValue(), nullptr); 16440b57cec5SDimitry Andric 16450b57cec5SDimitry Andric // Handle /merge 16460b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_merge)) 16470b57cec5SDimitry Andric parseMerge(arg->getValue()); 16480b57cec5SDimitry Andric 16490b57cec5SDimitry Andric // Add default section merging rules after user rules. User rules take 16500b57cec5SDimitry Andric // precedence, but we will emit a warning if there is a conflict. 16510b57cec5SDimitry Andric parseMerge(".idata=.rdata"); 16520b57cec5SDimitry Andric parseMerge(".didat=.rdata"); 16530b57cec5SDimitry Andric parseMerge(".edata=.rdata"); 16540b57cec5SDimitry Andric parseMerge(".xdata=.rdata"); 16550b57cec5SDimitry Andric parseMerge(".bss=.data"); 16560b57cec5SDimitry Andric 16570b57cec5SDimitry Andric if (config->mingw) { 16580b57cec5SDimitry Andric parseMerge(".ctors=.rdata"); 16590b57cec5SDimitry Andric parseMerge(".dtors=.rdata"); 16600b57cec5SDimitry Andric parseMerge(".CRT=.rdata"); 16610b57cec5SDimitry Andric } 16620b57cec5SDimitry Andric 16630b57cec5SDimitry Andric // Handle /section 16640b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_section)) 16650b57cec5SDimitry Andric parseSection(arg->getValue()); 16660b57cec5SDimitry Andric 16670b57cec5SDimitry Andric // Handle /align 16680b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_align)) { 16690b57cec5SDimitry Andric parseNumbers(arg->getValue(), &config->align); 16700b57cec5SDimitry Andric if (!isPowerOf2_64(config->align)) 16710b57cec5SDimitry Andric error("/align: not a power of two: " + StringRef(arg->getValue())); 1672480093f4SDimitry Andric if (!args.hasArg(OPT_driver)) 1673480093f4SDimitry Andric warn("/align specified without /driver; image may not run"); 16740b57cec5SDimitry Andric } 16750b57cec5SDimitry Andric 16760b57cec5SDimitry Andric // Handle /aligncomm 16770b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_aligncomm)) 16780b57cec5SDimitry Andric parseAligncomm(arg->getValue()); 16790b57cec5SDimitry Andric 1680349cc55cSDimitry Andric // Handle /manifestdependency. 1681349cc55cSDimitry Andric for (auto *arg : args.filtered(OPT_manifestdependency)) 1682349cc55cSDimitry Andric config->manifestDependencies.insert(arg->getValue()); 16830b57cec5SDimitry Andric 16840b57cec5SDimitry Andric // Handle /manifest and /manifest: 16850b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifest, OPT_manifest_colon)) { 16860b57cec5SDimitry Andric if (arg->getOption().getID() == OPT_manifest) 16870b57cec5SDimitry Andric config->manifest = Configuration::SideBySide; 16880b57cec5SDimitry Andric else 16890b57cec5SDimitry Andric parseManifest(arg->getValue()); 16900b57cec5SDimitry Andric } 16910b57cec5SDimitry Andric 16920b57cec5SDimitry Andric // Handle /manifestuac 16930b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestuac)) 16940b57cec5SDimitry Andric parseManifestUAC(arg->getValue()); 16950b57cec5SDimitry Andric 16960b57cec5SDimitry Andric // Handle /manifestfile 16970b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_manifestfile)) 16980b57cec5SDimitry Andric config->manifestFile = arg->getValue(); 16990b57cec5SDimitry Andric 17000b57cec5SDimitry Andric // Handle /manifestinput 17010b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_manifestinput)) 17020b57cec5SDimitry Andric config->manifestInput.push_back(arg->getValue()); 17030b57cec5SDimitry Andric 17040b57cec5SDimitry Andric if (!config->manifestInput.empty() && 17050b57cec5SDimitry Andric config->manifest != Configuration::Embed) { 17060b57cec5SDimitry Andric fatal("/manifestinput: requires /manifest:embed"); 17070b57cec5SDimitry Andric } 17080b57cec5SDimitry Andric 17090b57cec5SDimitry Andric config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files); 17100b57cec5SDimitry Andric config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) || 17110b57cec5SDimitry Andric args.hasArg(OPT_thinlto_index_only_arg); 17120b57cec5SDimitry Andric config->thinLTOIndexOnlyArg = 17130b57cec5SDimitry Andric args.getLastArgValue(OPT_thinlto_index_only_arg); 17140b57cec5SDimitry Andric config->thinLTOPrefixReplace = 17150b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_prefix_replace); 17160b57cec5SDimitry Andric config->thinLTOObjectSuffixReplace = 17170b57cec5SDimitry Andric getOldNewOptions(args, OPT_thinlto_object_suffix_replace); 171885868e8aSDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_lto_obj_path); 1719fe6060f1SDimitry Andric config->ltoCSProfileGenerate = args.hasArg(OPT_lto_cs_profile_generate); 1720fe6060f1SDimitry Andric config->ltoCSProfileFile = args.getLastArgValue(OPT_lto_cs_profile_file); 17210b57cec5SDimitry Andric // Handle miscellaneous boolean flags. 1722349cc55cSDimitry Andric config->ltoPGOWarnMismatch = args.hasFlag(OPT_lto_pgo_warn_mismatch, 1723349cc55cSDimitry Andric OPT_lto_pgo_warn_mismatch_no, true); 17240b57cec5SDimitry Andric config->allowBind = args.hasFlag(OPT_allowbind, OPT_allowbind_no, true); 17250b57cec5SDimitry Andric config->allowIsolation = 17260b57cec5SDimitry Andric args.hasFlag(OPT_allowisolation, OPT_allowisolation_no, true); 17270b57cec5SDimitry Andric config->incremental = 17280b57cec5SDimitry Andric args.hasFlag(OPT_incremental, OPT_incremental_no, 1729fe6060f1SDimitry Andric !config->doGC && config->doICF == ICFLevel::None && 1730fe6060f1SDimitry Andric !args.hasArg(OPT_order) && !args.hasArg(OPT_profile)); 17310b57cec5SDimitry Andric config->integrityCheck = 17320b57cec5SDimitry Andric args.hasFlag(OPT_integritycheck, OPT_integritycheck_no, false); 17335ffd83dbSDimitry Andric config->cetCompat = args.hasFlag(OPT_cetcompat, OPT_cetcompat_no, false); 17340b57cec5SDimitry Andric config->nxCompat = args.hasFlag(OPT_nxcompat, OPT_nxcompat_no, true); 17350b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_swaprun)) 17360b57cec5SDimitry Andric parseSwaprun(arg->getValue()); 17370b57cec5SDimitry Andric config->terminalServerAware = 17380b57cec5SDimitry Andric !config->dll && args.hasFlag(OPT_tsaware, OPT_tsaware_no, true); 17390b57cec5SDimitry Andric config->debugDwarf = debug == DebugKind::Dwarf; 1740fe6060f1SDimitry Andric config->debugGHashes = debug == DebugKind::GHash || debug == DebugKind::Full; 17410b57cec5SDimitry Andric config->debugSymtab = debug == DebugKind::Symtab; 17425ffd83dbSDimitry Andric config->autoImport = 17435ffd83dbSDimitry Andric args.hasFlag(OPT_auto_import, OPT_auto_import_no, config->mingw); 17445ffd83dbSDimitry Andric config->pseudoRelocs = args.hasFlag( 17455ffd83dbSDimitry Andric OPT_runtime_pseudo_reloc, OPT_runtime_pseudo_reloc_no, config->mingw); 1746e8d8bef9SDimitry Andric config->callGraphProfileSort = args.hasFlag( 1747e8d8bef9SDimitry Andric OPT_call_graph_profile_sort, OPT_call_graph_profile_sort_no, true); 1748fe6060f1SDimitry Andric config->stdcallFixup = 1749fe6060f1SDimitry Andric args.hasFlag(OPT_stdcall_fixup, OPT_stdcall_fixup_no, config->mingw); 1750fe6060f1SDimitry Andric config->warnStdcallFixup = !args.hasArg(OPT_stdcall_fixup); 17510b57cec5SDimitry Andric 1752e8d8bef9SDimitry Andric // Don't warn about long section names, such as .debug_info, for mingw or 1753e8d8bef9SDimitry Andric // when -debug:dwarf is requested. 1754480093f4SDimitry Andric if (config->mingw || config->debugDwarf) 1755480093f4SDimitry Andric config->warnLongSectionNames = false; 1756480093f4SDimitry Andric 17575ffd83dbSDimitry Andric config->lldmapFile = getMapFile(args, OPT_lldmap, OPT_lldmap_file); 17585ffd83dbSDimitry Andric config->mapFile = getMapFile(args, OPT_map, OPT_map_file); 17595ffd83dbSDimitry Andric 17605ffd83dbSDimitry Andric if (config->lldmapFile != "" && config->lldmapFile == config->mapFile) { 17615ffd83dbSDimitry Andric warn("/lldmap and /map have the same output file '" + config->mapFile + 17625ffd83dbSDimitry Andric "'.\n>>> ignoring /lldmap"); 17635ffd83dbSDimitry Andric config->lldmapFile.clear(); 17645ffd83dbSDimitry Andric } 17650b57cec5SDimitry Andric 17660b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_profile)) { 17670b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/profile' specification"); 17680b57cec5SDimitry Andric config->incremental = false; 17690b57cec5SDimitry Andric } 17700b57cec5SDimitry Andric 17710b57cec5SDimitry Andric if (config->incremental && args.hasArg(OPT_order)) { 17720b57cec5SDimitry Andric warn("ignoring '/incremental' due to '/order' specification"); 17730b57cec5SDimitry Andric config->incremental = false; 17740b57cec5SDimitry Andric } 17750b57cec5SDimitry Andric 17760b57cec5SDimitry Andric if (config->incremental && config->doGC) { 17770b57cec5SDimitry Andric warn("ignoring '/incremental' because REF is enabled; use '/opt:noref' to " 17780b57cec5SDimitry Andric "disable"); 17790b57cec5SDimitry Andric config->incremental = false; 17800b57cec5SDimitry Andric } 17810b57cec5SDimitry Andric 1782fe6060f1SDimitry Andric if (config->incremental && config->doICF != ICFLevel::None) { 17830b57cec5SDimitry Andric warn("ignoring '/incremental' because ICF is enabled; use '/opt:noicf' to " 17840b57cec5SDimitry Andric "disable"); 17850b57cec5SDimitry Andric config->incremental = false; 17860b57cec5SDimitry Andric } 17870b57cec5SDimitry Andric 17880b57cec5SDimitry Andric if (errorCount()) 17890b57cec5SDimitry Andric return; 17900b57cec5SDimitry Andric 17910b57cec5SDimitry Andric std::set<sys::fs::UniqueID> wholeArchives; 17920b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_wholearchive_file)) 17930b57cec5SDimitry Andric if (Optional<StringRef> path = doFindFile(arg->getValue())) 17940b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(*path)) 17950b57cec5SDimitry Andric wholeArchives.insert(*id); 17960b57cec5SDimitry Andric 17970b57cec5SDimitry Andric // A predicate returning true if a given path is an argument for 17980b57cec5SDimitry Andric // /wholearchive:, or /wholearchive is enabled globally. 17990b57cec5SDimitry Andric // This function is a bit tricky because "foo.obj /wholearchive:././foo.obj" 18000b57cec5SDimitry Andric // needs to be handled as "/wholearchive:foo.obj foo.obj". 18010b57cec5SDimitry Andric auto isWholeArchive = [&](StringRef path) -> bool { 18020b57cec5SDimitry Andric if (args.hasArg(OPT_wholearchive_flag)) 18030b57cec5SDimitry Andric return true; 18040b57cec5SDimitry Andric if (Optional<sys::fs::UniqueID> id = getUniqueID(path)) 18050b57cec5SDimitry Andric return wholeArchives.count(*id); 18060b57cec5SDimitry Andric return false; 18070b57cec5SDimitry Andric }; 18080b57cec5SDimitry Andric 180985868e8aSDimitry Andric // Create a list of input files. These can be given as OPT_INPUT options 181085868e8aSDimitry Andric // and OPT_wholearchive_file options, and we also need to track OPT_start_lib 181185868e8aSDimitry Andric // and OPT_end_lib. 181285868e8aSDimitry Andric bool inLib = false; 181385868e8aSDimitry Andric for (auto *arg : args) { 181485868e8aSDimitry Andric switch (arg->getOption().getID()) { 181585868e8aSDimitry Andric case OPT_end_lib: 181685868e8aSDimitry Andric if (!inLib) 181785868e8aSDimitry Andric error("stray " + arg->getSpelling()); 181885868e8aSDimitry Andric inLib = false; 181985868e8aSDimitry Andric break; 182085868e8aSDimitry Andric case OPT_start_lib: 182185868e8aSDimitry Andric if (inLib) 182285868e8aSDimitry Andric error("nested " + arg->getSpelling()); 182385868e8aSDimitry Andric inLib = true; 182485868e8aSDimitry Andric break; 182585868e8aSDimitry Andric case OPT_wholearchive_file: 18260b57cec5SDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 182785868e8aSDimitry Andric enqueuePath(*path, true, inLib); 182885868e8aSDimitry Andric break; 182985868e8aSDimitry Andric case OPT_INPUT: 183085868e8aSDimitry Andric if (Optional<StringRef> path = findFile(arg->getValue())) 183185868e8aSDimitry Andric enqueuePath(*path, isWholeArchive(*path), inLib); 183285868e8aSDimitry Andric break; 183385868e8aSDimitry Andric default: 183485868e8aSDimitry Andric // Ignore other options. 183585868e8aSDimitry Andric break; 183685868e8aSDimitry Andric } 183785868e8aSDimitry Andric } 18380b57cec5SDimitry Andric 183985868e8aSDimitry Andric // Process files specified as /defaultlib. These should be enequeued after 184085868e8aSDimitry Andric // other files, which is why they are in a separate loop. 18410b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_defaultlib)) 18420b57cec5SDimitry Andric if (Optional<StringRef> path = findLib(arg->getValue())) 184385868e8aSDimitry Andric enqueuePath(*path, false, false); 18440b57cec5SDimitry Andric 18450b57cec5SDimitry Andric // Read all input files given via the command line. 18460b57cec5SDimitry Andric run(); 18470b57cec5SDimitry Andric 18480b57cec5SDimitry Andric if (errorCount()) 18490b57cec5SDimitry Andric return; 18500b57cec5SDimitry Andric 18510b57cec5SDimitry Andric // We should have inferred a machine type by now from the input files, but if 18520b57cec5SDimitry Andric // not we assume x64. 18530b57cec5SDimitry Andric if (config->machine == IMAGE_FILE_MACHINE_UNKNOWN) { 18540b57cec5SDimitry Andric warn("/machine is not specified. x64 is assumed"); 18550b57cec5SDimitry Andric config->machine = AMD64; 18560b57cec5SDimitry Andric } 18570b57cec5SDimitry Andric config->wordsize = config->is64() ? 8 : 4; 18580b57cec5SDimitry Andric 18590b57cec5SDimitry Andric // Handle /safeseh, x86 only, on by default, except for mingw. 1860979e22ffSDimitry Andric if (config->machine == I386) { 1861979e22ffSDimitry Andric config->safeSEH = args.hasFlag(OPT_safeseh, OPT_safeseh_no, !config->mingw); 1862979e22ffSDimitry Andric config->noSEH = args.hasArg(OPT_noseh); 1863979e22ffSDimitry Andric } 18640b57cec5SDimitry Andric 18650b57cec5SDimitry Andric // Handle /functionpadmin 18660b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_functionpadmin, OPT_functionpadmin_opt)) 18670b57cec5SDimitry Andric parseFunctionPadMin(arg, config->machine); 18680b57cec5SDimitry Andric 18690b57cec5SDimitry Andric if (tar) 18700b57cec5SDimitry Andric tar->append("response.txt", 18710b57cec5SDimitry Andric createResponseFile(args, filePaths, 18720b57cec5SDimitry Andric ArrayRef<StringRef>(searchPaths).slice(1))); 18730b57cec5SDimitry Andric 18740b57cec5SDimitry Andric // Handle /largeaddressaware 18750b57cec5SDimitry Andric config->largeAddressAware = args.hasFlag( 18760b57cec5SDimitry Andric OPT_largeaddressaware, OPT_largeaddressaware_no, config->is64()); 18770b57cec5SDimitry Andric 18780b57cec5SDimitry Andric // Handle /highentropyva 18790b57cec5SDimitry Andric config->highEntropyVA = 18800b57cec5SDimitry Andric config->is64() && 18810b57cec5SDimitry Andric args.hasFlag(OPT_highentropyva, OPT_highentropyva_no, true); 18820b57cec5SDimitry Andric 18830b57cec5SDimitry Andric if (!config->dynamicBase && 18840b57cec5SDimitry Andric (config->machine == ARMNT || config->machine == ARM64)) 18850b57cec5SDimitry Andric error("/dynamicbase:no is not compatible with " + 18860b57cec5SDimitry Andric machineToStr(config->machine)); 18870b57cec5SDimitry Andric 18880b57cec5SDimitry Andric // Handle /export 18890b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_export)) { 18900b57cec5SDimitry Andric Export e = parseExport(arg->getValue()); 18910b57cec5SDimitry Andric if (config->machine == I386) { 18920b57cec5SDimitry Andric if (!isDecorated(e.name)) 1893*04eeddc0SDimitry Andric e.name = saver().save("_" + e.name); 18940b57cec5SDimitry Andric if (!e.extName.empty() && !isDecorated(e.extName)) 1895*04eeddc0SDimitry Andric e.extName = saver().save("_" + e.extName); 18960b57cec5SDimitry Andric } 18970b57cec5SDimitry Andric config->exports.push_back(e); 18980b57cec5SDimitry Andric } 18990b57cec5SDimitry Andric 19000b57cec5SDimitry Andric // Handle /def 19010b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_deffile)) { 19020b57cec5SDimitry Andric // parseModuleDefs mutates Config object. 19030b57cec5SDimitry Andric parseModuleDefs(arg->getValue()); 19040b57cec5SDimitry Andric } 19050b57cec5SDimitry Andric 19060b57cec5SDimitry Andric // Handle generation of import library from a def file. 1907480093f4SDimitry Andric if (!args.hasArg(OPT_INPUT, OPT_wholearchive_file)) { 19080b57cec5SDimitry Andric fixupExports(); 19090b57cec5SDimitry Andric createImportLibrary(/*asLib=*/true); 19100b57cec5SDimitry Andric return; 19110b57cec5SDimitry Andric } 19120b57cec5SDimitry Andric 19130b57cec5SDimitry Andric // Windows specific -- if no /subsystem is given, we need to infer 19140b57cec5SDimitry Andric // that from entry point name. Must happen before /entry handling, 19150b57cec5SDimitry Andric // and after the early return when just writing an import library. 19160b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) { 19170b57cec5SDimitry Andric config->subsystem = inferSubsystem(); 19180b57cec5SDimitry Andric if (config->subsystem == IMAGE_SUBSYSTEM_UNKNOWN) 19190b57cec5SDimitry Andric fatal("subsystem must be defined"); 19200b57cec5SDimitry Andric } 19210b57cec5SDimitry Andric 19220b57cec5SDimitry Andric // Handle /entry and /dll 19230b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_entry)) { 19240b57cec5SDimitry Andric config->entry = addUndefined(mangle(arg->getValue())); 19250b57cec5SDimitry Andric } else if (!config->entry && !config->noEntry) { 19260b57cec5SDimitry Andric if (args.hasArg(OPT_dll)) { 19270b57cec5SDimitry Andric StringRef s = (config->machine == I386) ? "__DllMainCRTStartup@12" 19280b57cec5SDimitry Andric : "_DllMainCRTStartup"; 19290b57cec5SDimitry Andric config->entry = addUndefined(s); 1930480093f4SDimitry Andric } else if (config->driverWdm) { 1931480093f4SDimitry Andric // /driver:wdm implies /entry:_NtProcessStartup 1932480093f4SDimitry Andric config->entry = addUndefined(mangle("_NtProcessStartup")); 19330b57cec5SDimitry Andric } else { 19340b57cec5SDimitry Andric // Windows specific -- If entry point name is not given, we need to 19350b57cec5SDimitry Andric // infer that from user-defined entry name. 19360b57cec5SDimitry Andric StringRef s = findDefaultEntry(); 19370b57cec5SDimitry Andric if (s.empty()) 19380b57cec5SDimitry Andric fatal("entry point must be defined"); 19390b57cec5SDimitry Andric config->entry = addUndefined(s); 19400b57cec5SDimitry Andric log("Entry name inferred: " + s); 19410b57cec5SDimitry Andric } 19420b57cec5SDimitry Andric } 19430b57cec5SDimitry Andric 19440b57cec5SDimitry Andric // Handle /delayload 19450b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_delayload)) { 19460b57cec5SDimitry Andric config->delayLoads.insert(StringRef(arg->getValue()).lower()); 19470b57cec5SDimitry Andric if (config->machine == I386) { 19480b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("___delayLoadHelper2@8"); 19490b57cec5SDimitry Andric } else { 19500b57cec5SDimitry Andric config->delayLoadHelper = addUndefined("__delayLoadHelper2"); 19510b57cec5SDimitry Andric } 19520b57cec5SDimitry Andric } 19530b57cec5SDimitry Andric 19540b57cec5SDimitry Andric // Set default image name if neither /out or /def set it. 19550b57cec5SDimitry Andric if (config->outputFile.empty()) { 1956480093f4SDimitry Andric config->outputFile = getOutputPath( 1957480093f4SDimitry Andric (*args.filtered(OPT_INPUT, OPT_wholearchive_file).begin())->getValue()); 19580b57cec5SDimitry Andric } 19590b57cec5SDimitry Andric 19600b57cec5SDimitry Andric // Fail early if an output file is not writable. 19610b57cec5SDimitry Andric if (auto e = tryCreateFile(config->outputFile)) { 19620b57cec5SDimitry Andric error("cannot open output file " + config->outputFile + ": " + e.message()); 19630b57cec5SDimitry Andric return; 19640b57cec5SDimitry Andric } 19650b57cec5SDimitry Andric 19660b57cec5SDimitry Andric if (shouldCreatePDB) { 19670b57cec5SDimitry Andric // Put the PDB next to the image if no /pdb flag was passed. 19680b57cec5SDimitry Andric if (config->pdbPath.empty()) { 19690b57cec5SDimitry Andric config->pdbPath = config->outputFile; 19700b57cec5SDimitry Andric sys::path::replace_extension(config->pdbPath, ".pdb"); 19710b57cec5SDimitry Andric } 19720b57cec5SDimitry Andric 19730b57cec5SDimitry Andric // The embedded PDB path should be the absolute path to the PDB if no 19740b57cec5SDimitry Andric // /pdbaltpath flag was passed. 19750b57cec5SDimitry Andric if (config->pdbAltPath.empty()) { 19760b57cec5SDimitry Andric config->pdbAltPath = config->pdbPath; 19770b57cec5SDimitry Andric 19780b57cec5SDimitry Andric // It's important to make the path absolute and remove dots. This path 19790b57cec5SDimitry Andric // will eventually be written into the PE header, and certain Microsoft 19800b57cec5SDimitry Andric // tools won't work correctly if these assumptions are not held. 19810b57cec5SDimitry Andric sys::fs::make_absolute(config->pdbAltPath); 19820b57cec5SDimitry Andric sys::path::remove_dots(config->pdbAltPath); 19830b57cec5SDimitry Andric } else { 19840b57cec5SDimitry Andric // Don't do this earlier, so that Config->OutputFile is ready. 19850b57cec5SDimitry Andric parsePDBAltPath(config->pdbAltPath); 19860b57cec5SDimitry Andric } 19870b57cec5SDimitry Andric } 19880b57cec5SDimitry Andric 19890b57cec5SDimitry Andric // Set default image base if /base is not given. 19900b57cec5SDimitry Andric if (config->imageBase == uint64_t(-1)) 19910b57cec5SDimitry Andric config->imageBase = getDefaultImageBase(); 19920b57cec5SDimitry Andric 1993349cc55cSDimitry Andric ctx.symtab.addSynthetic(mangle("__ImageBase"), nullptr); 19940b57cec5SDimitry Andric if (config->machine == I386) { 1995349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_table", 0); 1996349cc55cSDimitry Andric ctx.symtab.addAbsolute("___safe_se_handler_count", 0); 19970b57cec5SDimitry Andric } 19980b57cec5SDimitry Andric 1999349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_count"), 0); 2000349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_fids_table"), 0); 2001349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_flags"), 0); 2002349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_count"), 0); 2003349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_iat_table"), 0); 2004349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_count"), 0); 2005349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_longjmp_table"), 0); 20060b57cec5SDimitry Andric // Needed for MSVC 2017 15.5 CRT. 2007349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__enclave_config"), 0); 2008fe6060f1SDimitry Andric // Needed for MSVC 2019 16.8 CRT. 2009349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_count"), 0); 2010349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__guard_eh_cont_table"), 0); 20110b57cec5SDimitry Andric 20125ffd83dbSDimitry Andric if (config->pseudoRelocs) { 2013349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST__"), 0); 2014349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__RUNTIME_PSEUDO_RELOC_LIST_END__"), 0); 20155ffd83dbSDimitry Andric } 20165ffd83dbSDimitry Andric if (config->mingw) { 2017349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__CTOR_LIST__"), 0); 2018349cc55cSDimitry Andric ctx.symtab.addAbsolute(mangle("__DTOR_LIST__"), 0); 20190b57cec5SDimitry Andric } 20200b57cec5SDimitry Andric 20210b57cec5SDimitry Andric // This code may add new undefined symbols to the link, which may enqueue more 20220b57cec5SDimitry Andric // symbol resolution tasks, so we need to continue executing tasks until we 20230b57cec5SDimitry Andric // converge. 20240b57cec5SDimitry Andric do { 20250b57cec5SDimitry Andric // Windows specific -- if entry point is not found, 20260b57cec5SDimitry Andric // search for its mangled names. 20270b57cec5SDimitry Andric if (config->entry) 20280b57cec5SDimitry Andric mangleMaybe(config->entry); 20290b57cec5SDimitry Andric 20300b57cec5SDimitry Andric // Windows specific -- Make sure we resolve all dllexported symbols. 20310b57cec5SDimitry Andric for (Export &e : config->exports) { 20320b57cec5SDimitry Andric if (!e.forwardTo.empty()) 20330b57cec5SDimitry Andric continue; 20340b57cec5SDimitry Andric e.sym = addUndefined(e.name); 20350b57cec5SDimitry Andric if (!e.directives) 20360b57cec5SDimitry Andric e.symbolName = mangleMaybe(e.sym); 20370b57cec5SDimitry Andric } 20380b57cec5SDimitry Andric 20390b57cec5SDimitry Andric // Add weak aliases. Weak aliases is a mechanism to give remaining 20400b57cec5SDimitry Andric // undefined symbols final chance to be resolved successfully. 20410b57cec5SDimitry Andric for (auto pair : config->alternateNames) { 20420b57cec5SDimitry Andric StringRef from = pair.first; 20430b57cec5SDimitry Andric StringRef to = pair.second; 2044349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(from); 20450b57cec5SDimitry Andric if (!sym) 20460b57cec5SDimitry Andric continue; 20470b57cec5SDimitry Andric if (auto *u = dyn_cast<Undefined>(sym)) 20480b57cec5SDimitry Andric if (!u->weakAlias) 2049349cc55cSDimitry Andric u->weakAlias = ctx.symtab.addUndefined(to); 20500b57cec5SDimitry Andric } 20510b57cec5SDimitry Andric 20520b57cec5SDimitry Andric // If any inputs are bitcode files, the LTO code generator may create 20530b57cec5SDimitry Andric // references to library functions that are not explicit in the bitcode 20540b57cec5SDimitry Andric // file's symbol table. If any of those library functions are defined in a 20550b57cec5SDimitry Andric // bitcode file in an archive member, we need to arrange to use LTO to 20560b57cec5SDimitry Andric // compile those archive members by adding them to the link beforehand. 2057349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty()) 205885868e8aSDimitry Andric for (auto *s : lto::LTO::getRuntimeLibcallSymbols()) 2059349cc55cSDimitry Andric ctx.symtab.addLibcall(s); 20600b57cec5SDimitry Andric 20610b57cec5SDimitry Andric // Windows specific -- if __load_config_used can be resolved, resolve it. 2062349cc55cSDimitry Andric if (ctx.symtab.findUnderscore("_load_config_used")) 20630b57cec5SDimitry Andric addUndefined(mangle("_load_config_used")); 20640b57cec5SDimitry Andric } while (run()); 20650b57cec5SDimitry Andric 20660b57cec5SDimitry Andric if (args.hasArg(OPT_include_optional)) { 20670b57cec5SDimitry Andric // Handle /includeoptional 20680b57cec5SDimitry Andric for (auto *arg : args.filtered(OPT_include_optional)) 20690eae32dcSDimitry Andric if (isa_and_nonnull<LazyArchive>(ctx.symtab.find(arg->getValue()))) 20700b57cec5SDimitry Andric addUndefined(arg->getValue()); 20710b57cec5SDimitry Andric while (run()); 20720b57cec5SDimitry Andric } 20730b57cec5SDimitry Andric 2074e8d8bef9SDimitry Andric // Create wrapped symbols for -wrap option. 2075349cc55cSDimitry Andric std::vector<WrappedSymbol> wrapped = addWrappedSymbols(ctx, args); 2076e8d8bef9SDimitry Andric // Load more object files that might be needed for wrapped symbols. 2077e8d8bef9SDimitry Andric if (!wrapped.empty()) 2078e8d8bef9SDimitry Andric while (run()); 2079e8d8bef9SDimitry Andric 2080fe6060f1SDimitry Andric if (config->autoImport || config->stdcallFixup) { 20815ffd83dbSDimitry Andric // MinGW specific. 20820b57cec5SDimitry Andric // Load any further object files that might be needed for doing automatic 2083fe6060f1SDimitry Andric // imports, and do stdcall fixups. 20840b57cec5SDimitry Andric // 20850b57cec5SDimitry Andric // For cases with no automatically imported symbols, this iterates once 20860b57cec5SDimitry Andric // over the symbol table and doesn't do anything. 20870b57cec5SDimitry Andric // 20880b57cec5SDimitry Andric // For the normal case with a few automatically imported symbols, this 20890b57cec5SDimitry Andric // should only need to be run once, since each new object file imported 20900b57cec5SDimitry Andric // is an import library and wouldn't add any new undefined references, 20910b57cec5SDimitry Andric // but there's nothing stopping the __imp_ symbols from coming from a 20920b57cec5SDimitry Andric // normal object file as well (although that won't be used for the 20930b57cec5SDimitry Andric // actual autoimport later on). If this pass adds new undefined references, 20940b57cec5SDimitry Andric // we won't iterate further to resolve them. 2095fe6060f1SDimitry Andric // 2096fe6060f1SDimitry Andric // If stdcall fixups only are needed for loading import entries from 2097fe6060f1SDimitry Andric // a DLL without import library, this also just needs running once. 2098fe6060f1SDimitry Andric // If it ends up pulling in more object files from static libraries, 2099fe6060f1SDimitry Andric // (and maybe doing more stdcall fixups along the way), this would need 2100fe6060f1SDimitry Andric // to loop these two calls. 2101349cc55cSDimitry Andric ctx.symtab.loadMinGWSymbols(); 21020b57cec5SDimitry Andric run(); 21030b57cec5SDimitry Andric } 21040b57cec5SDimitry Andric 210585868e8aSDimitry Andric // At this point, we should not have any symbols that cannot be resolved. 210685868e8aSDimitry Andric // If we are going to do codegen for link-time optimization, check for 210785868e8aSDimitry Andric // unresolvable symbols first, so we don't spend time generating code that 210885868e8aSDimitry Andric // will fail to link anyway. 2109349cc55cSDimitry Andric if (!ctx.bitcodeFileInstances.empty() && !config->forceUnresolved) 2110349cc55cSDimitry Andric ctx.symtab.reportUnresolvable(); 21110b57cec5SDimitry Andric if (errorCount()) 21120b57cec5SDimitry Andric return; 21130b57cec5SDimitry Andric 2114fe6060f1SDimitry Andric config->hadExplicitExports = !config->exports.empty(); 2115fe6060f1SDimitry Andric if (config->mingw) { 2116fe6060f1SDimitry Andric // In MinGW, all symbols are automatically exported if no symbols 2117fe6060f1SDimitry Andric // are chosen to be exported. 2118fe6060f1SDimitry Andric maybeExportMinGWSymbols(args); 2119fe6060f1SDimitry Andric } 2120fe6060f1SDimitry Andric 212185868e8aSDimitry Andric // Do LTO by compiling bitcode input files to a set of native COFF files then 212285868e8aSDimitry Andric // link those files (unless -thinlto-index-only was given, in which case we 212385868e8aSDimitry Andric // resolve symbols and write indices, but don't generate native code or link). 2124349cc55cSDimitry Andric ctx.symtab.compileBitcodeFiles(); 212585868e8aSDimitry Andric 212685868e8aSDimitry Andric // If -thinlto-index-only is given, we should create only "index 212785868e8aSDimitry Andric // files" and not object files. Index file creation is already done 2128349cc55cSDimitry Andric // in compileBitcodeFiles, so we are done if that's the case. 212985868e8aSDimitry Andric if (config->thinLTOIndexOnly) 213085868e8aSDimitry Andric return; 213185868e8aSDimitry Andric 213285868e8aSDimitry Andric // If we generated native object files from bitcode files, this resolves 213385868e8aSDimitry Andric // references to the symbols we use from them. 213485868e8aSDimitry Andric run(); 213585868e8aSDimitry Andric 2136e8d8bef9SDimitry Andric // Apply symbol renames for -wrap. 2137e8d8bef9SDimitry Andric if (!wrapped.empty()) 2138349cc55cSDimitry Andric wrapSymbols(ctx, wrapped); 2139e8d8bef9SDimitry Andric 214085868e8aSDimitry Andric // Resolve remaining undefined symbols and warn about imported locals. 2141349cc55cSDimitry Andric ctx.symtab.resolveRemainingUndefines(); 214285868e8aSDimitry Andric if (errorCount()) 214385868e8aSDimitry Andric return; 214485868e8aSDimitry Andric 21450b57cec5SDimitry Andric if (config->mingw) { 21460b57cec5SDimitry Andric // Make sure the crtend.o object is the last object file. This object 21470b57cec5SDimitry Andric // file can contain terminating section chunks that need to be placed 21480b57cec5SDimitry Andric // last. GNU ld processes files and static libraries explicitly in the 21490b57cec5SDimitry Andric // order provided on the command line, while lld will pull in needed 21500b57cec5SDimitry Andric // files from static libraries only after the last object file on the 21510b57cec5SDimitry Andric // command line. 2152349cc55cSDimitry Andric for (auto i = ctx.objFileInstances.begin(), e = ctx.objFileInstances.end(); 21530b57cec5SDimitry Andric i != e; i++) { 21540b57cec5SDimitry Andric ObjFile *file = *i; 21550b57cec5SDimitry Andric if (isCrtend(file->getName())) { 2156349cc55cSDimitry Andric ctx.objFileInstances.erase(i); 2157349cc55cSDimitry Andric ctx.objFileInstances.push_back(file); 21580b57cec5SDimitry Andric break; 21590b57cec5SDimitry Andric } 21600b57cec5SDimitry Andric } 21610b57cec5SDimitry Andric } 21620b57cec5SDimitry Andric 21630b57cec5SDimitry Andric // Windows specific -- when we are creating a .dll file, we also 216485868e8aSDimitry Andric // need to create a .lib file. In MinGW mode, we only do that when the 216585868e8aSDimitry Andric // -implib option is given explicitly, for compatibility with GNU ld. 21660b57cec5SDimitry Andric if (!config->exports.empty() || config->dll) { 21670b57cec5SDimitry Andric fixupExports(); 216885868e8aSDimitry Andric if (!config->mingw || !config->implib.empty()) 21690b57cec5SDimitry Andric createImportLibrary(/*asLib=*/false); 21700b57cec5SDimitry Andric assignExportOrdinals(); 21710b57cec5SDimitry Andric } 21720b57cec5SDimitry Andric 21730b57cec5SDimitry Andric // Handle /output-def (MinGW specific). 21740b57cec5SDimitry Andric if (auto *arg = args.getLastArg(OPT_output_def)) 21750b57cec5SDimitry Andric writeDefFile(arg->getValue()); 21760b57cec5SDimitry Andric 21770b57cec5SDimitry Andric // Set extra alignment for .comm symbols 21780b57cec5SDimitry Andric for (auto pair : config->alignComm) { 21790b57cec5SDimitry Andric StringRef name = pair.first; 21800b57cec5SDimitry Andric uint32_t alignment = pair.second; 21810b57cec5SDimitry Andric 2182349cc55cSDimitry Andric Symbol *sym = ctx.symtab.find(name); 21830b57cec5SDimitry Andric if (!sym) { 21840b57cec5SDimitry Andric warn("/aligncomm symbol " + name + " not found"); 21850b57cec5SDimitry Andric continue; 21860b57cec5SDimitry Andric } 21870b57cec5SDimitry Andric 21880b57cec5SDimitry Andric // If the symbol isn't common, it must have been replaced with a regular 21890b57cec5SDimitry Andric // symbol, which will carry its own alignment. 21900b57cec5SDimitry Andric auto *dc = dyn_cast<DefinedCommon>(sym); 21910b57cec5SDimitry Andric if (!dc) 21920b57cec5SDimitry Andric continue; 21930b57cec5SDimitry Andric 21940b57cec5SDimitry Andric CommonChunk *c = dc->getChunk(); 21950b57cec5SDimitry Andric c->setAlignment(std::max(c->getAlignment(), alignment)); 21960b57cec5SDimitry Andric } 21970b57cec5SDimitry Andric 2198349cc55cSDimitry Andric // Windows specific -- Create an embedded or side-by-side manifest. 2199349cc55cSDimitry Andric // /manifestdependency: enables /manifest unless an explicit /manifest:no is 2200349cc55cSDimitry Andric // also passed. 2201349cc55cSDimitry Andric if (config->manifest == Configuration::Embed) 2202349cc55cSDimitry Andric addBuffer(createManifestRes(), false, false); 2203349cc55cSDimitry Andric else if (config->manifest == Configuration::SideBySide || 2204349cc55cSDimitry Andric (config->manifest == Configuration::Default && 2205349cc55cSDimitry Andric !config->manifestDependencies.empty())) 22060b57cec5SDimitry Andric createSideBySideManifest(); 22070b57cec5SDimitry Andric 22080b57cec5SDimitry Andric // Handle /order. We want to do this at this moment because we 22090b57cec5SDimitry Andric // need a complete list of comdat sections to warn on nonexistent 22100b57cec5SDimitry Andric // functions. 2211e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_order)) { 2212e8d8bef9SDimitry Andric if (args.hasArg(OPT_call_graph_ordering_file)) 2213e8d8bef9SDimitry Andric error("/order and /call-graph-order-file may not be used together"); 2214349cc55cSDimitry Andric parseOrderFile(ctx, arg->getValue()); 2215e8d8bef9SDimitry Andric config->callGraphProfileSort = false; 2216e8d8bef9SDimitry Andric } 2217e8d8bef9SDimitry Andric 2218e8d8bef9SDimitry Andric // Handle /call-graph-ordering-file and /call-graph-profile-sort (default on). 2219e8d8bef9SDimitry Andric if (config->callGraphProfileSort) { 2220e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_call_graph_ordering_file)) { 2221349cc55cSDimitry Andric parseCallGraphFile(ctx, arg->getValue()); 2222e8d8bef9SDimitry Andric } 2223349cc55cSDimitry Andric readCallGraphsFromObjectFiles(ctx); 2224e8d8bef9SDimitry Andric } 2225e8d8bef9SDimitry Andric 2226e8d8bef9SDimitry Andric // Handle /print-symbol-order. 2227e8d8bef9SDimitry Andric if (auto *arg = args.getLastArg(OPT_print_symbol_order)) 2228e8d8bef9SDimitry Andric config->printSymbolOrder = arg->getValue(); 22290b57cec5SDimitry Andric 22300b57cec5SDimitry Andric // Identify unreferenced COMDAT sections. 2231fe6060f1SDimitry Andric if (config->doGC) { 2232fe6060f1SDimitry Andric if (config->mingw) { 2233fe6060f1SDimitry Andric // markLive doesn't traverse .eh_frame, but the personality function is 2234fe6060f1SDimitry Andric // only reached that way. The proper solution would be to parse and 2235fe6060f1SDimitry Andric // traverse the .eh_frame section, like the ELF linker does. 2236fe6060f1SDimitry Andric // For now, just manually try to retain the known possible personality 2237fe6060f1SDimitry Andric // functions. This doesn't bring in more object files, but only marks 2238fe6060f1SDimitry Andric // functions that already have been included to be retained. 2239fe6060f1SDimitry Andric for (const char *n : {"__gxx_personality_v0", "__gcc_personality_v0"}) { 2240349cc55cSDimitry Andric Defined *d = dyn_cast_or_null<Defined>(ctx.symtab.findUnderscore(n)); 2241fe6060f1SDimitry Andric if (d && !d->isGCRoot) { 2242fe6060f1SDimitry Andric d->isGCRoot = true; 2243fe6060f1SDimitry Andric config->gcroot.push_back(d); 2244fe6060f1SDimitry Andric } 2245fe6060f1SDimitry Andric } 2246fe6060f1SDimitry Andric } 2247fe6060f1SDimitry Andric 2248349cc55cSDimitry Andric markLive(ctx); 2249fe6060f1SDimitry Andric } 22500b57cec5SDimitry Andric 22510b57cec5SDimitry Andric // Needs to happen after the last call to addFile(). 225285868e8aSDimitry Andric convertResources(); 22530b57cec5SDimitry Andric 22540b57cec5SDimitry Andric // Identify identical COMDAT sections to merge them. 2255fe6060f1SDimitry Andric if (config->doICF != ICFLevel::None) { 2256349cc55cSDimitry Andric findKeepUniqueSections(ctx); 2257349cc55cSDimitry Andric doICF(ctx, config->doICF); 22580b57cec5SDimitry Andric } 22590b57cec5SDimitry Andric 22600b57cec5SDimitry Andric // Write the result. 2261349cc55cSDimitry Andric writeResult(ctx); 22620b57cec5SDimitry Andric 22630b57cec5SDimitry Andric // Stop early so we can print the results. 22645ffd83dbSDimitry Andric rootTimer.stop(); 22650b57cec5SDimitry Andric if (config->showTiming) 2266349cc55cSDimitry Andric ctx.rootTimer.print(); 22670b57cec5SDimitry Andric } 22680b57cec5SDimitry Andric 22690b57cec5SDimitry Andric } // namespace coff 22700b57cec5SDimitry Andric } // namespace lld 2271