Path: blob/main/contrib/llvm-project/lld/MachO/Driver.cpp
34878 views
//===- Driver.cpp ---------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "Driver.h"9#include "Config.h"10#include "ICF.h"11#include "InputFiles.h"12#include "LTO.h"13#include "MarkLive.h"14#include "ObjC.h"15#include "OutputSection.h"16#include "OutputSegment.h"17#include "SectionPriorities.h"18#include "SymbolTable.h"19#include "Symbols.h"20#include "SyntheticSections.h"21#include "Target.h"22#include "UnwindInfoSection.h"23#include "Writer.h"2425#include "lld/Common/Args.h"26#include "lld/Common/CommonLinkerContext.h"27#include "lld/Common/Driver.h"28#include "lld/Common/ErrorHandler.h"29#include "lld/Common/LLVM.h"30#include "lld/Common/Memory.h"31#include "lld/Common/Reproduce.h"32#include "lld/Common/Version.h"33#include "llvm/ADT/DenseSet.h"34#include "llvm/ADT/StringExtras.h"35#include "llvm/ADT/StringRef.h"36#include "llvm/BinaryFormat/MachO.h"37#include "llvm/BinaryFormat/Magic.h"38#include "llvm/Config/llvm-config.h"39#include "llvm/LTO/LTO.h"40#include "llvm/Object/Archive.h"41#include "llvm/Option/ArgList.h"42#include "llvm/Support/CommandLine.h"43#include "llvm/Support/FileSystem.h"44#include "llvm/Support/MemoryBuffer.h"45#include "llvm/Support/Parallel.h"46#include "llvm/Support/Path.h"47#include "llvm/Support/TarWriter.h"48#include "llvm/Support/TargetSelect.h"49#include "llvm/Support/TimeProfiler.h"50#include "llvm/TargetParser/Host.h"51#include "llvm/TextAPI/Architecture.h"52#include "llvm/TextAPI/PackedVersion.h"5354#include <algorithm>5556using namespace llvm;57using namespace llvm::MachO;58using namespace llvm::object;59using namespace llvm::opt;60using namespace llvm::sys;61using namespace lld;62using namespace lld::macho;6364std::unique_ptr<Configuration> macho::config;65std::unique_ptr<DependencyTracker> macho::depTracker;6667static HeaderFileType getOutputType(const InputArgList &args) {68// TODO: -r, -dylinker, -preload...69Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute);70if (outputArg == nullptr)71return MH_EXECUTE;7273switch (outputArg->getOption().getID()) {74case OPT_bundle:75return MH_BUNDLE;76case OPT_dylib:77return MH_DYLIB;78case OPT_execute:79return MH_EXECUTE;80default:81llvm_unreachable("internal error");82}83}8485static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;86static std::optional<StringRef> findLibrary(StringRef name) {87CachedHashStringRef key(name);88auto entry = resolvedLibraries.find(key);89if (entry != resolvedLibraries.end())90return entry->second;9192auto doFind = [&] {93// Special case for Csu support files required for Mac OS X 10.7 and older94// (crt1.o)95if (name.ends_with(".o"))96return findPathCombination(name, config->librarySearchPaths, {""});97if (config->searchDylibsFirst) {98if (std::optional<StringRef> path =99findPathCombination("lib" + name, config->librarySearchPaths,100{".tbd", ".dylib", ".so"}))101return path;102return findPathCombination("lib" + name, config->librarySearchPaths,103{".a"});104}105return findPathCombination("lib" + name, config->librarySearchPaths,106{".tbd", ".dylib", ".so", ".a"});107};108109std::optional<StringRef> path = doFind();110if (path)111resolvedLibraries[key] = *path;112113return path;114}115116static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;117static std::optional<StringRef> findFramework(StringRef name) {118CachedHashStringRef key(name);119auto entry = resolvedFrameworks.find(key);120if (entry != resolvedFrameworks.end())121return entry->second;122123SmallString<260> symlink;124StringRef suffix;125std::tie(name, suffix) = name.split(",");126for (StringRef dir : config->frameworkSearchPaths) {127symlink = dir;128path::append(symlink, name + ".framework", name);129130if (!suffix.empty()) {131// NOTE: we must resolve the symlink before trying the suffixes, because132// there are no symlinks for the suffixed paths.133SmallString<260> location;134if (!fs::real_path(symlink, location)) {135// only append suffix if realpath() succeeds136Twine suffixed = location + suffix;137if (fs::exists(suffixed))138return resolvedFrameworks[key] = saver().save(suffixed.str());139}140// Suffix lookup failed, fall through to the no-suffix case.141}142143if (std::optional<StringRef> path = resolveDylibPath(symlink.str()))144return resolvedFrameworks[key] = *path;145}146return {};147}148149static bool warnIfNotDirectory(StringRef option, StringRef path) {150if (!fs::exists(path)) {151warn("directory not found for option -" + option + path);152return false;153} else if (!fs::is_directory(path)) {154warn("option -" + option + path + " references a non-directory path");155return false;156}157return true;158}159160static std::vector<StringRef>161getSearchPaths(unsigned optionCode, InputArgList &args,162const std::vector<StringRef> &roots,163const SmallVector<StringRef, 2> &systemPaths) {164std::vector<StringRef> paths;165StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};166for (StringRef path : args::getStrings(args, optionCode)) {167// NOTE: only absolute paths are re-rooted to syslibroot(s)168bool found = false;169if (path::is_absolute(path, path::Style::posix)) {170for (StringRef root : roots) {171SmallString<261> buffer(root);172path::append(buffer, path);173// Do not warn about paths that are computed via the syslib roots174if (fs::is_directory(buffer)) {175paths.push_back(saver().save(buffer.str()));176found = true;177}178}179}180if (!found && warnIfNotDirectory(optionLetter, path))181paths.push_back(path);182}183184// `-Z` suppresses the standard "system" search paths.185if (args.hasArg(OPT_Z))186return paths;187188for (const StringRef &path : systemPaths) {189for (const StringRef &root : roots) {190SmallString<261> buffer(root);191path::append(buffer, path);192if (fs::is_directory(buffer))193paths.push_back(saver().save(buffer.str()));194}195}196return paths;197}198199static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) {200std::vector<StringRef> roots;201for (const Arg *arg : args.filtered(OPT_syslibroot))202roots.push_back(arg->getValue());203// NOTE: the final `-syslibroot` being `/` will ignore all roots204if (!roots.empty() && roots.back() == "/")205roots.clear();206// NOTE: roots can never be empty - add an empty root to simplify the library207// and framework search path computation.208if (roots.empty())209roots.emplace_back("");210return roots;211}212213static std::vector<StringRef>214getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) {215return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});216}217218static std::vector<StringRef>219getFrameworkSearchPaths(InputArgList &args,220const std::vector<StringRef> &roots) {221return getSearchPaths(OPT_F, args, roots,222{"/Library/Frameworks", "/System/Library/Frameworks"});223}224225static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) {226SmallString<128> ltoPolicy;227auto add = [<oPolicy](Twine val) {228if (!ltoPolicy.empty())229ltoPolicy += ":";230val.toVector(ltoPolicy);231};232for (const Arg *arg :233args.filtered(OPT_thinlto_cache_policy_eq, OPT_prune_interval_lto,234OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) {235switch (arg->getOption().getID()) {236case OPT_thinlto_cache_policy_eq:237add(arg->getValue());238break;239case OPT_prune_interval_lto:240if (!strcmp("-1", arg->getValue()))241add("prune_interval=87600h"); // 10 years242else243add(Twine("prune_interval=") + arg->getValue() + "s");244break;245case OPT_prune_after_lto:246add(Twine("prune_after=") + arg->getValue() + "s");247break;248case OPT_max_relative_cache_size_lto:249add(Twine("cache_size=") + arg->getValue() + "%");250break;251}252}253return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy");254}255256// What caused a given library to be loaded. Only relevant for archives.257// Note that this does not tell us *how* we should load the library, i.e.258// whether we should do it lazily or eagerly (AKA force loading). The "how" is259// decided within addFile().260enum class LoadType {261CommandLine, // Library was passed as a regular CLI argument262CommandLineForce, // Library was passed via `-force_load`263LCLinkerOption, // Library was passed via LC_LINKER_OPTIONS264};265266struct ArchiveFileInfo {267ArchiveFile *file;268bool isCommandLineLoad;269};270271static DenseMap<StringRef, ArchiveFileInfo> loadedArchives;272273static void saveThinArchiveToRepro(ArchiveFile const *file) {274assert(tar && file->getArchive().isThin());275276Error e = Error::success();277for (const object::Archive::Child &c : file->getArchive().children(e)) {278MemoryBufferRef mb = CHECK(c.getMemoryBufferRef(),279toString(file) + ": failed to get buffer");280tar->append(relativeToRoot(CHECK(c.getFullName(), file)), mb.getBuffer());281}282if (e)283error(toString(file) +284": Archive::children failed: " + toString(std::move(e)));285}286287static InputFile *addFile(StringRef path, LoadType loadType,288bool isLazy = false, bool isExplicit = true,289bool isBundleLoader = false,290bool isForceHidden = false) {291std::optional<MemoryBufferRef> buffer = readFile(path);292if (!buffer)293return nullptr;294MemoryBufferRef mbref = *buffer;295InputFile *newFile = nullptr;296297file_magic magic = identify_magic(mbref.getBuffer());298switch (magic) {299case file_magic::archive: {300bool isCommandLineLoad = loadType != LoadType::LCLinkerOption;301// Avoid loading archives twice. If the archives are being force-loaded,302// loading them twice would create duplicate symbol errors. In the303// non-force-loading case, this is just a minor performance optimization.304// We don't take a reference to cachedFile here because the305// loadArchiveMember() call below may recursively call addFile() and306// invalidate this reference.307auto entry = loadedArchives.find(path);308309ArchiveFile *file;310if (entry == loadedArchives.end()) {311// No cached archive, we need to create a new one312std::unique_ptr<object::Archive> archive = CHECK(313object::Archive::create(mbref), path + ": failed to parse archive");314315if (!archive->isEmpty() && !archive->hasSymbolTable())316error(path + ": archive has no index; run ranlib to add one");317file = make<ArchiveFile>(std::move(archive), isForceHidden);318319if (tar && file->getArchive().isThin())320saveThinArchiveToRepro(file);321} else {322file = entry->second.file;323// Command-line loads take precedence. If file is previously loaded via324// command line, or is loaded via LC_LINKER_OPTION and being loaded via325// LC_LINKER_OPTION again, using the cached archive is enough.326if (entry->second.isCommandLineLoad || !isCommandLineLoad)327return file;328}329330bool isLCLinkerForceLoad = loadType == LoadType::LCLinkerOption &&331config->forceLoadSwift &&332path::filename(path).starts_with("libswift");333if ((isCommandLineLoad && config->allLoad) ||334loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) {335if (readFile(path)) {336Error e = Error::success();337for (const object::Archive::Child &c : file->getArchive().children(e)) {338StringRef reason;339switch (loadType) {340case LoadType::LCLinkerOption:341reason = "LC_LINKER_OPTION";342break;343case LoadType::CommandLineForce:344reason = "-force_load";345break;346case LoadType::CommandLine:347reason = "-all_load";348break;349}350if (Error e = file->fetch(c, reason)) {351if (config->warnThinArchiveMissingMembers)352warn(toString(file) + ": " + reason +353" failed to load archive member: " + toString(std::move(e)));354else355llvm::consumeError(std::move(e));356}357}358if (e)359error(toString(file) +360": Archive::children failed: " + toString(std::move(e)));361}362} else if (isCommandLineLoad && config->forceLoadObjC) {363for (const object::Archive::Symbol &sym : file->getArchive().symbols())364if (sym.getName().starts_with(objc::symbol_names::klass))365file->fetch(sym);366367// TODO: no need to look for ObjC sections for a given archive member if368// we already found that it contains an ObjC symbol.369if (readFile(path)) {370Error e = Error::success();371for (const object::Archive::Child &c : file->getArchive().children(e)) {372Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();373if (!mb) {374// We used to create broken repro tarballs that only included those375// object files from thin archives that ended up being used.376if (config->warnThinArchiveMissingMembers)377warn(toString(file) + ": -ObjC failed to open archive member: " +378toString(mb.takeError()));379else380llvm::consumeError(mb.takeError());381continue;382}383384if (!hasObjCSection(*mb))385continue;386if (Error e = file->fetch(c, "-ObjC"))387error(toString(file) + ": -ObjC failed to load archive member: " +388toString(std::move(e)));389}390if (e)391error(toString(file) +392": Archive::children failed: " + toString(std::move(e)));393}394}395396file->addLazySymbols();397loadedArchives[path] = ArchiveFileInfo{file, isCommandLineLoad};398newFile = file;399break;400}401case file_magic::macho_object:402newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy);403break;404case file_magic::macho_dynamically_linked_shared_lib:405case file_magic::macho_dynamically_linked_shared_lib_stub:406case file_magic::tapi_file:407if (DylibFile *dylibFile =408loadDylib(mbref, nullptr, /*isBundleLoader=*/false, isExplicit))409newFile = dylibFile;410break;411case file_magic::bitcode:412newFile = make<BitcodeFile>(mbref, "", 0, isLazy);413break;414case file_magic::macho_executable:415case file_magic::macho_bundle:416// We only allow executable and bundle type here if it is used417// as a bundle loader.418if (!isBundleLoader)419error(path + ": unhandled file type");420if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader))421newFile = dylibFile;422break;423default:424error(path + ": unhandled file type");425}426if (newFile && !isa<DylibFile>(newFile)) {427if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy &&428config->forceLoadObjC) {429for (Symbol *sym : newFile->symbols)430if (sym && sym->getName().starts_with(objc::symbol_names::klass)) {431extract(*newFile, "-ObjC");432break;433}434if (newFile->lazy && hasObjCSection(mbref))435extract(*newFile, "-ObjC");436}437438// printArchiveMemberLoad() prints both .a and .o names, so no need to439// print the .a name here. Similarly skip lazy files.440if (config->printEachFile && magic != file_magic::archive && !isLazy)441message(toString(newFile));442inputFiles.insert(newFile);443}444return newFile;445}446447static std::vector<StringRef> missingAutolinkWarnings;448static void addLibrary(StringRef name, bool isNeeded, bool isWeak,449bool isReexport, bool isHidden, bool isExplicit,450LoadType loadType) {451if (std::optional<StringRef> path = findLibrary(name)) {452if (auto *dylibFile = dyn_cast_or_null<DylibFile>(453addFile(*path, loadType, /*isLazy=*/false, isExplicit,454/*isBundleLoader=*/false, isHidden))) {455if (isNeeded)456dylibFile->forceNeeded = true;457if (isWeak)458dylibFile->forceWeakImport = true;459if (isReexport) {460config->hasReexports = true;461dylibFile->reexport = true;462}463}464return;465}466if (loadType == LoadType::LCLinkerOption) {467missingAutolinkWarnings.push_back(468saver().save("auto-linked library not found for -l" + name));469return;470}471error("library not found for -l" + name);472}473474static DenseSet<StringRef> loadedObjectFrameworks;475static void addFramework(StringRef name, bool isNeeded, bool isWeak,476bool isReexport, bool isExplicit, LoadType loadType) {477if (std::optional<StringRef> path = findFramework(name)) {478if (loadedObjectFrameworks.contains(*path))479return;480481InputFile *file =482addFile(*path, loadType, /*isLazy=*/false, isExplicit, false);483if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) {484if (isNeeded)485dylibFile->forceNeeded = true;486if (isWeak)487dylibFile->forceWeakImport = true;488if (isReexport) {489config->hasReexports = true;490dylibFile->reexport = true;491}492} else if (isa_and_nonnull<ObjFile>(file) ||493isa_and_nonnull<BitcodeFile>(file)) {494// Cache frameworks containing object or bitcode files to avoid duplicate495// symbols. Frameworks containing static archives are cached separately496// in addFile() to share caching with libraries, and frameworks497// containing dylibs should allow overwriting of attributes such as498// forceNeeded by subsequent loads499loadedObjectFrameworks.insert(*path);500}501return;502}503if (loadType == LoadType::LCLinkerOption) {504missingAutolinkWarnings.push_back(505saver().save("auto-linked framework not found for -framework " + name));506return;507}508error("framework not found for -framework " + name);509}510511// Parses LC_LINKER_OPTION contents, which can add additional command line512// flags. This directly parses the flags instead of using the standard argument513// parser to improve performance.514void macho::parseLCLinkerOption(515llvm::SmallVectorImpl<StringRef> &LCLinkerOptions, InputFile *f,516unsigned argc, StringRef data) {517if (config->ignoreAutoLink)518return;519520SmallVector<StringRef, 4> argv;521size_t offset = 0;522for (unsigned i = 0; i < argc && offset < data.size(); ++i) {523argv.push_back(data.data() + offset);524offset += strlen(data.data() + offset) + 1;525}526if (argv.size() != argc || offset > data.size())527fatal(toString(f) + ": invalid LC_LINKER_OPTION");528529unsigned i = 0;530StringRef arg = argv[i];531if (arg.consume_front("-l")) {532if (config->ignoreAutoLinkOptions.contains(arg))533return;534} else if (arg == "-framework") {535StringRef name = argv[++i];536if (config->ignoreAutoLinkOptions.contains(name))537return;538} else {539error(arg + " is not allowed in LC_LINKER_OPTION");540}541542LCLinkerOptions.append(argv);543}544545void macho::resolveLCLinkerOptions() {546while (!unprocessedLCLinkerOptions.empty()) {547SmallVector<StringRef> LCLinkerOptions(unprocessedLCLinkerOptions);548unprocessedLCLinkerOptions.clear();549550for (unsigned i = 0; i < LCLinkerOptions.size(); ++i) {551StringRef arg = LCLinkerOptions[i];552if (arg.consume_front("-l")) {553assert(!config->ignoreAutoLinkOptions.contains(arg));554addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false,555/*isReexport=*/false, /*isHidden=*/false,556/*isExplicit=*/false, LoadType::LCLinkerOption);557} else if (arg == "-framework") {558StringRef name = LCLinkerOptions[++i];559assert(!config->ignoreAutoLinkOptions.contains(name));560addFramework(name, /*isNeeded=*/false, /*isWeak=*/false,561/*isReexport=*/false, /*isExplicit=*/false,562LoadType::LCLinkerOption);563} else {564error(arg + " is not allowed in LC_LINKER_OPTION");565}566}567}568}569570static void addFileList(StringRef path, bool isLazy) {571std::optional<MemoryBufferRef> buffer = readFile(path);572if (!buffer)573return;574MemoryBufferRef mbref = *buffer;575for (StringRef path : args::getLines(mbref))576addFile(rerootPath(path), LoadType::CommandLine, isLazy);577}578579// We expect sub-library names of the form "libfoo", which will match a dylib580// with a path of .*/libfoo.{dylib, tbd}.581// XXX ld64 seems to ignore the extension entirely when matching sub-libraries;582// I'm not sure what the use case for that is.583static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {584for (InputFile *file : inputFiles) {585if (auto *dylibFile = dyn_cast<DylibFile>(file)) {586StringRef filename = path::filename(dylibFile->getName());587if (filename.consume_front(searchName) &&588(filename.empty() || llvm::is_contained(extensions, filename))) {589dylibFile->reexport = true;590return true;591}592}593}594return false;595}596597// This function is called on startup. We need this for LTO since598// LTO calls LLVM functions to compile bitcode files to native code.599// Technically this can be delayed until we read bitcode files, but600// we don't bother to do lazily because the initialization is fast.601static void initLLVM() {602InitializeAllTargets();603InitializeAllTargetMCs();604InitializeAllAsmPrinters();605InitializeAllAsmParsers();606}607608static bool compileBitcodeFiles() {609TimeTraceScope timeScope("LTO");610auto *lto = make<BitcodeCompiler>();611for (InputFile *file : inputFiles)612if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))613if (!file->lazy)614lto->add(*bitcodeFile);615616std::vector<ObjFile *> compiled = lto->compile();617for (ObjFile *file : compiled)618inputFiles.insert(file);619620return !compiled.empty();621}622623// Replaces common symbols with defined symbols residing in __common sections.624// This function must be called after all symbol names are resolved (i.e. after625// all InputFiles have been loaded.) As a result, later operations won't see626// any CommonSymbols.627static void replaceCommonSymbols() {628TimeTraceScope timeScope("Replace common symbols");629ConcatOutputSection *osec = nullptr;630for (Symbol *sym : symtab->getSymbols()) {631auto *common = dyn_cast<CommonSymbol>(sym);632if (common == nullptr)633continue;634635// Casting to size_t will truncate large values on 32-bit architectures,636// but it's not really worth supporting the linking of 64-bit programs on637// 32-bit archs.638ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};639// FIXME avoid creating one Section per symbol?640auto *section =641make<Section>(common->getFile(), segment_names::data,642section_names::common, S_ZEROFILL, /*addr=*/0);643auto *isec = make<ConcatInputSection>(*section, data, common->align);644if (!osec)645osec = ConcatOutputSection::getOrCreateForInput(isec);646isec->parent = osec;647addInputSection(isec);648649// FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip650// and pass them on here.651replaceSymbol<Defined>(652sym, sym->getName(), common->getFile(), isec, /*value=*/0, common->size,653/*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern,654/*includeInSymtab=*/true, /*isReferencedDynamically=*/false,655/*noDeadStrip=*/false);656}657}658659static void initializeSectionRenameMap() {660if (config->dataConst) {661SmallVector<StringRef> v{section_names::got,662section_names::authGot,663section_names::authPtr,664section_names::nonLazySymbolPtr,665section_names::const_,666section_names::cfString,667section_names::moduleInitFunc,668section_names::moduleTermFunc,669section_names::objcClassList,670section_names::objcNonLazyClassList,671section_names::objcCatList,672section_names::objcNonLazyCatList,673section_names::objcProtoList,674section_names::objCImageInfo};675for (StringRef s : v)676config->sectionRenameMap[{segment_names::data, s}] = {677segment_names::dataConst, s};678}679config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {680segment_names::text, section_names::text};681config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {682config->dataConst ? segment_names::dataConst : segment_names::data,683section_names::nonLazySymbolPtr};684}685686static inline char toLowerDash(char x) {687if (x >= 'A' && x <= 'Z')688return x - 'A' + 'a';689else if (x == ' ')690return '-';691return x;692}693694static std::string lowerDash(StringRef s) {695return std::string(map_iterator(s.begin(), toLowerDash),696map_iterator(s.end(), toLowerDash));697}698699struct PlatformVersion {700PlatformType platform = PLATFORM_UNKNOWN;701llvm::VersionTuple minimum;702llvm::VersionTuple sdk;703};704705static PlatformVersion parsePlatformVersion(const Arg *arg) {706assert(arg->getOption().getID() == OPT_platform_version);707StringRef platformStr = arg->getValue(0);708StringRef minVersionStr = arg->getValue(1);709StringRef sdkVersionStr = arg->getValue(2);710711PlatformVersion platformVersion;712713// TODO(compnerd) see if we can generate this case list via XMACROS714platformVersion.platform =715StringSwitch<PlatformType>(lowerDash(platformStr))716.Cases("macos", "1", PLATFORM_MACOS)717.Cases("ios", "2", PLATFORM_IOS)718.Cases("tvos", "3", PLATFORM_TVOS)719.Cases("watchos", "4", PLATFORM_WATCHOS)720.Cases("bridgeos", "5", PLATFORM_BRIDGEOS)721.Cases("mac-catalyst", "6", PLATFORM_MACCATALYST)722.Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR)723.Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR)724.Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR)725.Cases("driverkit", "10", PLATFORM_DRIVERKIT)726.Cases("xros", "11", PLATFORM_XROS)727.Cases("xros-simulator", "12", PLATFORM_XROS_SIMULATOR)728.Default(PLATFORM_UNKNOWN);729if (platformVersion.platform == PLATFORM_UNKNOWN)730error(Twine("malformed platform: ") + platformStr);731// TODO: check validity of version strings, which varies by platform732// NOTE: ld64 accepts version strings with 5 components733// llvm::VersionTuple accepts no more than 4 components734// Has Apple ever published version strings with 5 components?735if (platformVersion.minimum.tryParse(minVersionStr))736error(Twine("malformed minimum version: ") + minVersionStr);737if (platformVersion.sdk.tryParse(sdkVersionStr))738error(Twine("malformed sdk version: ") + sdkVersionStr);739return platformVersion;740}741742// Has the side-effect of setting Config::platformInfo and743// potentially Config::secondaryPlatformInfo.744static void setPlatformVersions(StringRef archName, const ArgList &args) {745std::map<PlatformType, PlatformVersion> platformVersions;746const PlatformVersion *lastVersionInfo = nullptr;747for (const Arg *arg : args.filtered(OPT_platform_version)) {748PlatformVersion version = parsePlatformVersion(arg);749750// For each platform, the last flag wins:751// `-platform_version macos 2 3 -platform_version macos 4 5` has the same752// effect as just passing `-platform_version macos 4 5`.753// FIXME: ld64 warns on multiple flags for one platform. Should we?754platformVersions[version.platform] = version;755lastVersionInfo = &platformVersions[version.platform];756}757758if (platformVersions.empty()) {759error("must specify -platform_version");760return;761}762if (platformVersions.size() > 2) {763error("must specify -platform_version at most twice");764return;765}766if (platformVersions.size() == 2) {767bool isZipperedCatalyst = platformVersions.count(PLATFORM_MACOS) &&768platformVersions.count(PLATFORM_MACCATALYST);769770if (!isZipperedCatalyst) {771error("lld supports writing zippered outputs only for "772"macos and mac-catalyst");773} else if (config->outputType != MH_DYLIB &&774config->outputType != MH_BUNDLE) {775error("writing zippered outputs only valid for -dylib and -bundle");776}777778config->platformInfo = {779MachO::Target(getArchitectureFromName(archName), PLATFORM_MACOS,780platformVersions[PLATFORM_MACOS].minimum),781platformVersions[PLATFORM_MACOS].sdk};782config->secondaryPlatformInfo = {783MachO::Target(getArchitectureFromName(archName), PLATFORM_MACCATALYST,784platformVersions[PLATFORM_MACCATALYST].minimum),785platformVersions[PLATFORM_MACCATALYST].sdk};786return;787}788789config->platformInfo = {MachO::Target(getArchitectureFromName(archName),790lastVersionInfo->platform,791lastVersionInfo->minimum),792lastVersionInfo->sdk};793}794795// Has the side-effect of setting Config::target.796static TargetInfo *createTargetInfo(InputArgList &args) {797StringRef archName = args.getLastArgValue(OPT_arch);798if (archName.empty()) {799error("must specify -arch");800return nullptr;801}802803setPlatformVersions(archName, args);804auto [cpuType, cpuSubtype] = getCPUTypeFromArchitecture(config->arch());805switch (cpuType) {806case CPU_TYPE_X86_64:807return createX86_64TargetInfo();808case CPU_TYPE_ARM64:809return createARM64TargetInfo();810case CPU_TYPE_ARM64_32:811return createARM64_32TargetInfo();812default:813error("missing or unsupported -arch " + archName);814return nullptr;815}816}817818static UndefinedSymbolTreatment819getUndefinedSymbolTreatment(const ArgList &args) {820StringRef treatmentStr = args.getLastArgValue(OPT_undefined);821auto treatment =822StringSwitch<UndefinedSymbolTreatment>(treatmentStr)823.Cases("error", "", UndefinedSymbolTreatment::error)824.Case("warning", UndefinedSymbolTreatment::warning)825.Case("suppress", UndefinedSymbolTreatment::suppress)826.Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)827.Default(UndefinedSymbolTreatment::unknown);828if (treatment == UndefinedSymbolTreatment::unknown) {829warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +830"', defaulting to 'error'");831treatment = UndefinedSymbolTreatment::error;832} else if (config->namespaceKind == NamespaceKind::twolevel &&833(treatment == UndefinedSymbolTreatment::warning ||834treatment == UndefinedSymbolTreatment::suppress)) {835if (treatment == UndefinedSymbolTreatment::warning)836fatal("'-undefined warning' only valid with '-flat_namespace'");837else838fatal("'-undefined suppress' only valid with '-flat_namespace'");839treatment = UndefinedSymbolTreatment::error;840}841return treatment;842}843844static ICFLevel getICFLevel(const ArgList &args) {845StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq);846auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)847.Cases("none", "", ICFLevel::none)848.Case("safe", ICFLevel::safe)849.Case("all", ICFLevel::all)850.Default(ICFLevel::unknown);851if (icfLevel == ICFLevel::unknown) {852warn(Twine("unknown --icf=OPTION `") + icfLevelStr +853"', defaulting to `none'");854icfLevel = ICFLevel::none;855}856return icfLevel;857}858859static ObjCStubsMode getObjCStubsMode(const ArgList &args) {860const Arg *arg = args.getLastArg(OPT_objc_stubs_fast, OPT_objc_stubs_small);861if (!arg)862return ObjCStubsMode::fast;863864if (arg->getOption().getID() == OPT_objc_stubs_small) {865if (is_contained({AK_arm64e, AK_arm64}, config->arch()))866return ObjCStubsMode::small;867else868warn("-objc_stubs_small is not yet implemented, defaulting to "869"-objc_stubs_fast");870}871return ObjCStubsMode::fast;872}873874static void warnIfDeprecatedOption(const Option &opt) {875if (!opt.getGroup().isValid())876return;877if (opt.getGroup().getID() == OPT_grp_deprecated) {878warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");879warn(opt.getHelpText());880}881}882883static void warnIfUnimplementedOption(const Option &opt) {884if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))885return;886switch (opt.getGroup().getID()) {887case OPT_grp_deprecated:888// warn about deprecated options elsewhere889break;890case OPT_grp_undocumented:891warn("Option `" + opt.getPrefixedName() +892"' is undocumented. Should lld implement it?");893break;894case OPT_grp_obsolete:895warn("Option `" + opt.getPrefixedName() +896"' is obsolete. Please modernize your usage.");897break;898case OPT_grp_ignored:899warn("Option `" + opt.getPrefixedName() + "' is ignored.");900break;901case OPT_grp_ignored_silently:902break;903default:904warn("Option `" + opt.getPrefixedName() +905"' is not yet implemented. Stay tuned...");906break;907}908}909910static const char *getReproduceOption(InputArgList &args) {911if (const Arg *arg = args.getLastArg(OPT_reproduce))912return arg->getValue();913return getenv("LLD_REPRODUCE");914}915916// Parse options of the form "old;new".917static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,918unsigned id) {919auto *arg = args.getLastArg(id);920if (!arg)921return {"", ""};922923StringRef s = arg->getValue();924std::pair<StringRef, StringRef> ret = s.split(';');925if (ret.second.empty())926error(arg->getSpelling() + " expects 'old;new' format, but got " + s);927return ret;928}929930// Parse options of the form "old;new[;extra]".931static std::tuple<StringRef, StringRef, StringRef>932getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {933auto [oldDir, second] = getOldNewOptions(args, id);934auto [newDir, extraDir] = second.split(';');935return {oldDir, newDir, extraDir};936}937938static void parseClangOption(StringRef opt, const Twine &msg) {939std::string err;940raw_string_ostream os(err);941942const char *argv[] = {"lld", opt.data()};943if (cl::ParseCommandLineOptions(2, argv, "", &os))944return;945os.flush();946error(msg + ": " + StringRef(err).trim());947}948949static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {950const Arg *arg = args.getLastArg(id);951if (!arg)952return 0;953954if (config->outputType != MH_DYLIB) {955error(arg->getAsString(args) + ": only valid with -dylib");956return 0;957}958959PackedVersion version;960if (!version.parse32(arg->getValue())) {961error(arg->getAsString(args) + ": malformed version");962return 0;963}964965return version.rawValue();966}967968static uint32_t parseProtection(StringRef protStr) {969uint32_t prot = 0;970for (char c : protStr) {971switch (c) {972case 'r':973prot |= VM_PROT_READ;974break;975case 'w':976prot |= VM_PROT_WRITE;977break;978case 'x':979prot |= VM_PROT_EXECUTE;980break;981case '-':982break;983default:984error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);985return 0;986}987}988return prot;989}990991static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {992std::vector<SectionAlign> sectAligns;993for (const Arg *arg : args.filtered(OPT_sectalign)) {994StringRef segName = arg->getValue(0);995StringRef sectName = arg->getValue(1);996StringRef alignStr = arg->getValue(2);997alignStr.consume_front_insensitive("0x");998uint32_t align;999if (alignStr.getAsInteger(16, align)) {1000error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +1001"' as number");1002continue;1003}1004if (!isPowerOf2_32(align)) {1005error("-sectalign: '" + StringRef(arg->getValue(2)) +1006"' (in base 16) not a power of two");1007continue;1008}1009sectAligns.push_back({segName, sectName, align});1010}1011return sectAligns;1012}10131014PlatformType macho::removeSimulator(PlatformType platform) {1015switch (platform) {1016case PLATFORM_IOSSIMULATOR:1017return PLATFORM_IOS;1018case PLATFORM_TVOSSIMULATOR:1019return PLATFORM_TVOS;1020case PLATFORM_WATCHOSSIMULATOR:1021return PLATFORM_WATCHOS;1022case PLATFORM_XROS_SIMULATOR:1023return PLATFORM_XROS;1024default:1025return platform;1026}1027}10281029static bool supportsNoPie() {1030return !(config->arch() == AK_arm64 || config->arch() == AK_arm64e ||1031config->arch() == AK_arm64_32);1032}10331034static bool shouldAdhocSignByDefault(Architecture arch, PlatformType platform) {1035if (arch != AK_arm64 && arch != AK_arm64e)1036return false;10371038return platform == PLATFORM_MACOS || platform == PLATFORM_IOSSIMULATOR ||1039platform == PLATFORM_TVOSSIMULATOR ||1040platform == PLATFORM_WATCHOSSIMULATOR ||1041platform == PLATFORM_XROS_SIMULATOR;1042}10431044static bool dataConstDefault(const InputArgList &args) {1045static const std::array<std::pair<PlatformType, VersionTuple>, 6> minVersion =1046{{{PLATFORM_MACOS, VersionTuple(10, 15)},1047{PLATFORM_IOS, VersionTuple(13, 0)},1048{PLATFORM_TVOS, VersionTuple(13, 0)},1049{PLATFORM_WATCHOS, VersionTuple(6, 0)},1050{PLATFORM_XROS, VersionTuple(1, 0)},1051{PLATFORM_BRIDGEOS, VersionTuple(4, 0)}}};1052PlatformType platform = removeSimulator(config->platformInfo.target.Platform);1053auto it = llvm::find_if(minVersion,1054[&](const auto &p) { return p.first == platform; });1055if (it != minVersion.end())1056if (config->platformInfo.target.MinDeployment < it->second)1057return false;10581059switch (config->outputType) {1060case MH_EXECUTE:1061return !(args.hasArg(OPT_no_pie) && supportsNoPie());1062case MH_BUNDLE:1063// FIXME: return false when -final_name ...1064// has prefix "/System/Library/UserEventPlugins/"1065// or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"1066return true;1067case MH_DYLIB:1068return true;1069case MH_OBJECT:1070return false;1071default:1072llvm_unreachable(1073"unsupported output type for determining data-const default");1074}1075return false;1076}10771078static bool shouldEmitChainedFixups(const InputArgList &args) {1079const Arg *arg = args.getLastArg(OPT_fixup_chains, OPT_no_fixup_chains);1080if (arg && arg->getOption().matches(OPT_no_fixup_chains))1081return false;10821083bool requested = arg && arg->getOption().matches(OPT_fixup_chains);1084if (!config->isPic) {1085if (requested)1086error("-fixup_chains is incompatible with -no_pie");10871088return false;1089}10901091if (!is_contained({AK_x86_64, AK_x86_64h, AK_arm64}, config->arch())) {1092if (requested)1093error("-fixup_chains is only supported on x86_64 and arm64 targets");10941095return false;1096}10971098if (args.hasArg(OPT_preload)) {1099if (requested)1100error("-fixup_chains is incompatible with -preload");11011102return false;1103}11041105if (requested)1106return true;11071108static const std::array<std::pair<PlatformType, VersionTuple>, 9> minVersion =1109{{1110{PLATFORM_IOS, VersionTuple(13, 4)},1111{PLATFORM_IOSSIMULATOR, VersionTuple(16, 0)},1112{PLATFORM_MACOS, VersionTuple(13, 0)},1113{PLATFORM_TVOS, VersionTuple(14, 0)},1114{PLATFORM_TVOSSIMULATOR, VersionTuple(15, 0)},1115{PLATFORM_WATCHOS, VersionTuple(7, 0)},1116{PLATFORM_WATCHOSSIMULATOR, VersionTuple(8, 0)},1117{PLATFORM_XROS, VersionTuple(1, 0)},1118{PLATFORM_XROS_SIMULATOR, VersionTuple(1, 0)},1119}};1120PlatformType platform = config->platformInfo.target.Platform;1121auto it = llvm::find_if(minVersion,1122[&](const auto &p) { return p.first == platform; });11231124// We don't know the versions for other platforms, so default to disabled.1125if (it == minVersion.end())1126return false;11271128if (it->second > config->platformInfo.target.MinDeployment)1129return false;11301131return true;1132}11331134static bool shouldEmitRelativeMethodLists(const InputArgList &args) {1135const Arg *arg = args.getLastArg(OPT_objc_relative_method_lists,1136OPT_no_objc_relative_method_lists);1137if (arg && arg->getOption().getID() == OPT_objc_relative_method_lists)1138return true;1139if (arg && arg->getOption().getID() == OPT_no_objc_relative_method_lists)1140return false;11411142// TODO: If no flag is specified, don't default to false, but instead:1143// - default false on < ios141144// - default true on >= ios141145// For now, until this feature is confirmed stable, default to false if no1146// flag is explicitly specified1147return false;1148}11491150void SymbolPatterns::clear() {1151literals.clear();1152globs.clear();1153}11541155void SymbolPatterns::insert(StringRef symbolName) {1156if (symbolName.find_first_of("*?[]") == StringRef::npos)1157literals.insert(CachedHashStringRef(symbolName));1158else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))1159globs.emplace_back(*pattern);1160else1161error("invalid symbol-name pattern: " + symbolName);1162}11631164bool SymbolPatterns::matchLiteral(StringRef symbolName) const {1165return literals.contains(CachedHashStringRef(symbolName));1166}11671168bool SymbolPatterns::matchGlob(StringRef symbolName) const {1169for (const GlobPattern &glob : globs)1170if (glob.match(symbolName))1171return true;1172return false;1173}11741175bool SymbolPatterns::match(StringRef symbolName) const {1176return matchLiteral(symbolName) || matchGlob(symbolName);1177}11781179static void parseSymbolPatternsFile(const Arg *arg,1180SymbolPatterns &symbolPatterns) {1181StringRef path = arg->getValue();1182std::optional<MemoryBufferRef> buffer = readFile(path);1183if (!buffer) {1184error("Could not read symbol file: " + path);1185return;1186}1187MemoryBufferRef mbref = *buffer;1188for (StringRef line : args::getLines(mbref)) {1189line = line.take_until([](char c) { return c == '#'; }).trim();1190if (!line.empty())1191symbolPatterns.insert(line);1192}1193}11941195static void handleSymbolPatterns(InputArgList &args,1196SymbolPatterns &symbolPatterns,1197unsigned singleOptionCode,1198unsigned listFileOptionCode) {1199for (const Arg *arg : args.filtered(singleOptionCode))1200symbolPatterns.insert(arg->getValue());1201for (const Arg *arg : args.filtered(listFileOptionCode))1202parseSymbolPatternsFile(arg, symbolPatterns);1203}12041205static void createFiles(const InputArgList &args) {1206TimeTraceScope timeScope("Load input files");1207// This loop should be reserved for options whose exact ordering matters.1208// Other options should be handled via filtered() and/or getLastArg().1209bool isLazy = false;1210// If we've processed an opening --start-lib, without a matching --end-lib1211bool inLib = false;1212for (const Arg *arg : args) {1213const Option &opt = arg->getOption();1214warnIfDeprecatedOption(opt);1215warnIfUnimplementedOption(opt);12161217switch (opt.getID()) {1218case OPT_INPUT:1219addFile(rerootPath(arg->getValue()), LoadType::CommandLine, isLazy);1220break;1221case OPT_needed_library:1222if (auto *dylibFile = dyn_cast_or_null<DylibFile>(1223addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))1224dylibFile->forceNeeded = true;1225break;1226case OPT_reexport_library:1227if (auto *dylibFile = dyn_cast_or_null<DylibFile>(1228addFile(rerootPath(arg->getValue()), LoadType::CommandLine))) {1229config->hasReexports = true;1230dylibFile->reexport = true;1231}1232break;1233case OPT_weak_library:1234if (auto *dylibFile = dyn_cast_or_null<DylibFile>(1235addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))1236dylibFile->forceWeakImport = true;1237break;1238case OPT_filelist:1239addFileList(arg->getValue(), isLazy);1240break;1241case OPT_force_load:1242addFile(rerootPath(arg->getValue()), LoadType::CommandLineForce);1243break;1244case OPT_load_hidden:1245addFile(rerootPath(arg->getValue()), LoadType::CommandLine,1246/*isLazy=*/false, /*isExplicit=*/true, /*isBundleLoader=*/false,1247/*isForceHidden=*/true);1248break;1249case OPT_l:1250case OPT_needed_l:1251case OPT_reexport_l:1252case OPT_weak_l:1253case OPT_hidden_l:1254addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,1255opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,1256opt.getID() == OPT_hidden_l,1257/*isExplicit=*/true, LoadType::CommandLine);1258break;1259case OPT_framework:1260case OPT_needed_framework:1261case OPT_reexport_framework:1262case OPT_weak_framework:1263addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,1264opt.getID() == OPT_weak_framework,1265opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,1266LoadType::CommandLine);1267break;1268case OPT_start_lib:1269if (inLib)1270error("nested --start-lib");1271inLib = true;1272if (!config->allLoad)1273isLazy = true;1274break;1275case OPT_end_lib:1276if (!inLib)1277error("stray --end-lib");1278inLib = false;1279isLazy = false;1280break;1281default:1282break;1283}1284}1285}12861287static void gatherInputSections() {1288TimeTraceScope timeScope("Gathering input sections");1289for (const InputFile *file : inputFiles) {1290for (const Section *section : file->sections) {1291// Compact unwind entries require special handling elsewhere. (In1292// contrast, EH frames are handled like regular ConcatInputSections.)1293if (section->name == section_names::compactUnwind)1294continue;1295// Addrsig sections contain metadata only needed at link time.1296if (section->name == section_names::addrSig)1297continue;1298for (const Subsection &subsection : section->subsections)1299addInputSection(subsection.isec);1300}1301if (!file->objCImageInfo.empty())1302in.objCImageInfo->addFile(file);1303}1304}13051306static void foldIdenticalLiterals() {1307TimeTraceScope timeScope("Fold identical literals");1308// We always create a cStringSection, regardless of whether dedupLiterals is1309// true. If it isn't, we simply create a non-deduplicating CStringSection.1310// Either way, we must unconditionally finalize it here.1311in.cStringSection->finalizeContents();1312in.objcMethnameSection->finalizeContents();1313in.wordLiteralSection->finalizeContents();1314}13151316static void addSynthenticMethnames() {1317std::string &data = *make<std::string>();1318llvm::raw_string_ostream os(data);1319for (Symbol *sym : symtab->getSymbols())1320if (isa<Undefined>(sym))1321if (ObjCStubsSection::isObjCStubSymbol(sym))1322os << ObjCStubsSection::getMethname(sym) << '\0';13231324if (data.empty())1325return;13261327const auto *buf = reinterpret_cast<const uint8_t *>(data.c_str());1328Section §ion = *make<Section>(/*file=*/nullptr, segment_names::text,1329section_names::objcMethname,1330S_CSTRING_LITERALS, /*addr=*/0);13311332auto *isec =1333make<CStringInputSection>(section, ArrayRef<uint8_t>{buf, data.size()},1334/*align=*/1, /*dedupLiterals=*/true);1335isec->splitIntoPieces();1336for (auto &piece : isec->pieces)1337piece.live = true;1338section.subsections.push_back({0, isec});1339in.objcMethnameSection->addInput(isec);1340in.objcMethnameSection->isec->markLive(0);1341}13421343static void referenceStubBinder() {1344bool needsStubHelper = config->outputType == MH_DYLIB ||1345config->outputType == MH_EXECUTE ||1346config->outputType == MH_BUNDLE;1347if (!needsStubHelper || !symtab->find("dyld_stub_binder"))1348return;13491350// dyld_stub_binder is used by dyld to resolve lazy bindings. This code here1351// adds a opportunistic reference to dyld_stub_binder if it happens to exist.1352// dyld_stub_binder is in libSystem.dylib, which is usually linked in. This1353// isn't needed for correctness, but the presence of that symbol suppresses1354// "no symbols" diagnostics from `nm`.1355// StubHelperSection::setUp() adds a reference and errors out if1356// dyld_stub_binder doesn't exist in case it is actually needed.1357symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false);1358}13591360static void createAliases() {1361for (const auto &pair : config->aliasedSymbols) {1362if (const auto &sym = symtab->find(pair.first)) {1363if (const auto &defined = dyn_cast<Defined>(sym)) {1364symtab->aliasDefined(defined, pair.second, defined->getFile())1365->noDeadStrip = true;1366} else {1367error("TODO: support aliasing to symbols of kind " +1368Twine(sym->kind()));1369}1370} else {1371warn("undefined base symbol '" + pair.first + "' for alias '" +1372pair.second + "'\n");1373}1374}13751376for (const InputFile *file : inputFiles) {1377if (auto *objFile = dyn_cast<ObjFile>(file)) {1378for (const AliasSymbol *alias : objFile->aliases) {1379if (const auto &aliased = symtab->find(alias->getAliasedName())) {1380if (const auto &defined = dyn_cast<Defined>(aliased)) {1381symtab->aliasDefined(defined, alias->getName(), alias->getFile(),1382alias->privateExtern);1383} else {1384// Common, dylib, and undefined symbols are all valid alias1385// referents (undefineds can become valid Defined symbols later on1386// in the link.)1387error("TODO: support aliasing to symbols of kind " +1388Twine(aliased->kind()));1389}1390} else {1391// This shouldn't happen since MC generates undefined symbols to1392// represent the alias referents. Thus we fatal() instead of just1393// warning here.1394fatal("unable to find alias referent " + alias->getAliasedName() +1395" for " + alias->getName());1396}1397}1398}1399}1400}14011402static void handleExplicitExports() {1403static constexpr int kMaxWarnings = 3;1404if (config->hasExplicitExports) {1405std::atomic<uint64_t> warningsCount{0};1406parallelForEach(symtab->getSymbols(), [&warningsCount](Symbol *sym) {1407if (auto *defined = dyn_cast<Defined>(sym)) {1408if (config->exportedSymbols.match(sym->getName())) {1409if (defined->privateExtern) {1410if (defined->weakDefCanBeHidden) {1411// weak_def_can_be_hidden symbols behave similarly to1412// private_extern symbols in most cases, except for when1413// it is explicitly exported.1414// The former can be exported but the latter cannot.1415defined->privateExtern = false;1416} else {1417// Only print the first 3 warnings verbosely, and1418// shorten the rest to avoid crowding logs.1419if (warningsCount.fetch_add(1, std::memory_order_relaxed) <1420kMaxWarnings)1421warn("cannot export hidden symbol " + toString(*defined) +1422"\n>>> defined in " + toString(defined->getFile()));1423}1424}1425} else {1426defined->privateExtern = true;1427}1428} else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {1429dysym->shouldReexport = config->exportedSymbols.match(sym->getName());1430}1431});1432if (warningsCount > kMaxWarnings)1433warn("<... " + Twine(warningsCount - kMaxWarnings) +1434" more similar warnings...>");1435} else if (!config->unexportedSymbols.empty()) {1436parallelForEach(symtab->getSymbols(), [](Symbol *sym) {1437if (auto *defined = dyn_cast<Defined>(sym))1438if (config->unexportedSymbols.match(defined->getName()))1439defined->privateExtern = true;1440});1441}1442}14431444static void eraseInitializerSymbols() {1445for (ConcatInputSection *isec : in.initOffsets->inputs())1446for (Defined *sym : isec->symbols)1447sym->used = false;1448}14491450static SmallVector<StringRef, 0> getRuntimePaths(opt::InputArgList &args) {1451SmallVector<StringRef, 0> vals;1452DenseSet<StringRef> seen;1453for (const Arg *arg : args.filtered(OPT_rpath)) {1454StringRef val = arg->getValue();1455if (seen.insert(val).second)1456vals.push_back(val);1457else if (config->warnDuplicateRpath)1458warn("duplicate -rpath '" + val + "' ignored [--warn-duplicate-rpath]");1459}1460return vals;1461}14621463namespace lld {1464namespace macho {1465bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,1466llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {1467// This driver-specific context will be freed later by lldMain().1468auto *ctx = new CommonLinkerContext;14691470ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);1471ctx->e.cleanupCallback = []() {1472resolvedFrameworks.clear();1473resolvedLibraries.clear();1474cachedReads.clear();1475concatOutputSections.clear();1476inputFiles.clear();1477inputSections.clear();1478inputSectionsOrder = 0;1479loadedArchives.clear();1480loadedObjectFrameworks.clear();1481missingAutolinkWarnings.clear();1482syntheticSections.clear();1483thunkMap.clear();1484unprocessedLCLinkerOptions.clear();1485ObjCSelRefsHelper::cleanup();14861487firstTLVDataSection = nullptr;1488tar = nullptr;1489memset(&in, 0, sizeof(in));14901491resetLoadedDylibs();1492resetOutputSegments();1493resetWriter();1494InputFile::resetIdCount();14951496objc::doCleanup();1497};14981499ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]);15001501MachOOptTable parser;1502InputArgList args = parser.parse(argsArr.slice(1));15031504ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "1505"(use --error-limit=0 to see all errors)";1506ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);1507ctx->e.verbose = args.hasArg(OPT_verbose);15081509if (args.hasArg(OPT_help_hidden)) {1510parser.printHelp(argsArr[0], /*showHidden=*/true);1511return true;1512}1513if (args.hasArg(OPT_help)) {1514parser.printHelp(argsArr[0], /*showHidden=*/false);1515return true;1516}1517if (args.hasArg(OPT_version)) {1518message(getLLDVersion());1519return true;1520}15211522config = std::make_unique<Configuration>();1523symtab = std::make_unique<SymbolTable>();1524config->outputType = getOutputType(args);1525target = createTargetInfo(args);1526depTracker = std::make_unique<DependencyTracker>(1527args.getLastArgValue(OPT_dependency_info));15281529config->ltoo = args::getInteger(args, OPT_lto_O, 2);1530if (config->ltoo > 3)1531error("--lto-O: invalid optimization level: " + Twine(config->ltoo));1532unsigned ltoCgo =1533args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));1534if (auto level = CodeGenOpt::getLevel(ltoCgo))1535config->ltoCgo = *level;1536else1537error("--lto-CGO: invalid codegen optimization level: " + Twine(ltoCgo));15381539if (errorCount())1540return false;15411542if (args.hasArg(OPT_pagezero_size)) {1543uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0);15441545// ld64 does something really weird. It attempts to realign the value to the1546// page size, but assumes the page size is 4K. This doesn't work with most1547// of Apple's ARM64 devices, which use a page size of 16K. This means that1548// it will first 4K align it by rounding down, then round up to 16K. This1549// probably only happened because no one using this arg with anything other1550// then 0, so no one checked if it did what is what it says it does.15511552// So we are not copying this weird behavior and doing the it in a logical1553// way, by always rounding down to page size.1554if (!isAligned(Align(target->getPageSize()), pagezeroSize)) {1555pagezeroSize -= pagezeroSize % target->getPageSize();1556warn("__PAGEZERO size is not page aligned, rounding down to 0x" +1557Twine::utohexstr(pagezeroSize));1558}15591560target->pageZeroSize = pagezeroSize;1561}15621563config->osoPrefix = args.getLastArgValue(OPT_oso_prefix);1564if (!config->osoPrefix.empty()) {1565// Expand special characters, such as ".", "..", or "~", if present.1566// Note: LD64 only expands "." and not other special characters.1567// That seems silly to imitate so we will not try to follow it, but rather1568// just use real_path() to do it.15691570// The max path length is 4096, in theory. However that seems quite long1571// and seems unlikely that any one would want to strip everything from the1572// path. Hence we've picked a reasonably large number here.1573SmallString<1024> expanded;1574if (!fs::real_path(config->osoPrefix, expanded,1575/*expand_tilde=*/true)) {1576// Note: LD64 expands "." to be `<current_dir>/`1577// (ie., it has a slash suffix) whereas real_path() doesn't.1578// So we have to append '/' to be consistent.1579StringRef sep = sys::path::get_separator();1580// real_path removes trailing slashes as part of the normalization, but1581// these are meaningful for our text based stripping1582if (config->osoPrefix == "." || config->osoPrefix.ends_with(sep))1583expanded += sep;1584config->osoPrefix = saver().save(expanded.str());1585}1586}15871588bool pie = args.hasFlag(OPT_pie, OPT_no_pie, true);1589if (!supportsNoPie() && !pie) {1590warn("-no_pie ignored for arm64");1591pie = true;1592}15931594config->isPic = config->outputType == MH_DYLIB ||1595config->outputType == MH_BUNDLE ||1596(config->outputType == MH_EXECUTE && pie);15971598// Must be set before any InputSections and Symbols are created.1599config->deadStrip = args.hasArg(OPT_dead_strip);16001601config->systemLibraryRoots = getSystemLibraryRoots(args);1602if (const char *path = getReproduceOption(args)) {1603// Note that --reproduce is a debug option so you can ignore it1604// if you are trying to understand the whole picture of the code.1605Expected<std::unique_ptr<TarWriter>> errOrWriter =1606TarWriter::create(path, path::stem(path));1607if (errOrWriter) {1608tar = std::move(*errOrWriter);1609tar->append("response.txt", createResponseFile(args));1610tar->append("version.txt", getLLDVersion() + "\n");1611} else {1612error("--reproduce: " + toString(errOrWriter.takeError()));1613}1614}16151616if (auto *arg = args.getLastArg(OPT_threads_eq)) {1617StringRef v(arg->getValue());1618unsigned threads = 0;1619if (!llvm::to_integer(v, threads, 0) || threads == 0)1620error(arg->getSpelling() + ": expected a positive integer, but got '" +1621arg->getValue() + "'");1622parallel::strategy = hardware_concurrency(threads);1623config->thinLTOJobs = v;1624}1625if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))1626config->thinLTOJobs = arg->getValue();1627if (!get_threadpool_strategy(config->thinLTOJobs))1628error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);16291630for (const Arg *arg : args.filtered(OPT_u)) {1631config->explicitUndefineds.push_back(symtab->addUndefined(1632arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));1633}16341635for (const Arg *arg : args.filtered(OPT_U))1636config->explicitDynamicLookups.insert(arg->getValue());16371638config->mapFile = args.getLastArgValue(OPT_map);1639config->optimize = args::getInteger(args, OPT_O, 1);1640config->outputFile = args.getLastArgValue(OPT_o, "a.out");1641config->finalOutput =1642args.getLastArgValue(OPT_final_output, config->outputFile);1643config->astPaths = args.getAllArgValues(OPT_add_ast_path);1644config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);1645config->headerPadMaxInstallNames =1646args.hasArg(OPT_headerpad_max_install_names);1647config->printDylibSearch =1648args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");1649config->printEachFile = args.hasArg(OPT_t);1650config->printWhyLoad = args.hasArg(OPT_why_load);1651config->omitDebugInfo = args.hasArg(OPT_S);1652config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal);1653if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {1654if (config->outputType != MH_BUNDLE)1655error("-bundle_loader can only be used with MachO bundle output");1656addFile(arg->getValue(), LoadType::CommandLine, /*isLazy=*/false,1657/*isExplicit=*/false, /*isBundleLoader=*/true);1658}1659for (auto *arg : args.filtered(OPT_dyld_env)) {1660StringRef envPair(arg->getValue());1661if (!envPair.contains('='))1662error("-dyld_env's argument is malformed. Expected "1663"-dyld_env <ENV_VAR>=<VALUE>, got `" +1664envPair + "`");1665config->dyldEnvs.push_back(envPair);1666}1667if (!config->dyldEnvs.empty() && config->outputType != MH_EXECUTE)1668error("-dyld_env can only be used when creating executable output");16691670if (const Arg *arg = args.getLastArg(OPT_umbrella)) {1671if (config->outputType != MH_DYLIB)1672warn("-umbrella used, but not creating dylib");1673config->umbrella = arg->getValue();1674}1675config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);1676config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto);1677config->thinLTOCachePolicy = getLTOCachePolicy(args);1678config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);1679config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||1680args.hasArg(OPT_thinlto_index_only) ||1681args.hasArg(OPT_thinlto_index_only_eq);1682config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||1683args.hasArg(OPT_thinlto_index_only_eq);1684config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);1685config->thinLTOObjectSuffixReplace =1686getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);1687std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,1688config->thinLTOPrefixReplaceNativeObject) =1689getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);1690if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {1691if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))1692error("--thinlto-object-suffix-replace is not supported with "1693"--thinlto-emit-index-files");1694else if (args.hasArg(OPT_thinlto_prefix_replace_eq))1695error("--thinlto-prefix-replace is not supported with "1696"--thinlto-emit-index-files");1697}1698if (!config->thinLTOPrefixReplaceNativeObject.empty() &&1699config->thinLTOIndexOnlyArg.empty()) {1700error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "1701"--thinlto-index-only=");1702}1703config->warnDuplicateRpath =1704args.hasFlag(OPT_warn_duplicate_rpath, OPT_no_warn_duplicate_rpath, true);1705config->runtimePaths = getRuntimePaths(args);1706config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false);1707config->archMultiple = args.hasArg(OPT_arch_multiple);1708config->applicationExtension = args.hasFlag(1709OPT_application_extension, OPT_no_application_extension, false);1710config->exportDynamic = args.hasArg(OPT_export_dynamic);1711config->forceLoadObjC = args.hasArg(OPT_ObjC);1712config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);1713config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);1714config->demangle = args.hasArg(OPT_demangle);1715config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);1716config->emitFunctionStarts =1717args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);1718config->emitDataInCodeInfo =1719args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);1720config->emitChainedFixups = shouldEmitChainedFixups(args);1721config->emitInitOffsets =1722config->emitChainedFixups || args.hasArg(OPT_init_offsets);1723config->emitRelativeMethodLists = shouldEmitRelativeMethodLists(args);1724config->icfLevel = getICFLevel(args);1725config->keepICFStabs = args.hasArg(OPT_keep_icf_stabs);1726config->dedupStrings =1727args.hasFlag(OPT_deduplicate_strings, OPT_no_deduplicate_strings, true);1728config->deadStripDuplicates = args.hasArg(OPT_dead_strip_duplicates);1729config->warnDylibInstallName = args.hasFlag(1730OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false);1731config->ignoreOptimizationHints = args.hasArg(OPT_ignore_optimization_hints);1732config->callGraphProfileSort = args.hasFlag(1733OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);1734config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order_eq);1735config->forceExactCpuSubtypeMatch =1736getenv("LD_DYLIB_CPU_SUBTYPES_MUST_MATCH");1737config->objcStubsMode = getObjCStubsMode(args);1738config->ignoreAutoLink = args.hasArg(OPT_ignore_auto_link);1739for (const Arg *arg : args.filtered(OPT_ignore_auto_link_option))1740config->ignoreAutoLinkOptions.insert(arg->getValue());1741config->strictAutoLink = args.hasArg(OPT_strict_auto_link);1742config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);1743config->csProfileGenerate = args.hasArg(OPT_cs_profile_generate);1744config->csProfilePath = args.getLastArgValue(OPT_cs_profile_path);1745config->pgoWarnMismatch =1746args.hasFlag(OPT_pgo_warn_mismatch, OPT_no_pgo_warn_mismatch, true);1747config->warnThinArchiveMissingMembers =1748args.hasFlag(OPT_warn_thin_archive_missing_members,1749OPT_no_warn_thin_archive_missing_members, true);1750config->generateUuid = !args.hasArg(OPT_no_uuid);17511752for (const Arg *arg : args.filtered(OPT_alias)) {1753config->aliasedSymbols.push_back(1754std::make_pair(arg->getValue(0), arg->getValue(1)));1755}17561757if (const char *zero = getenv("ZERO_AR_DATE"))1758config->zeroModTime = strcmp(zero, "0") != 0;1759if (args.getLastArg(OPT_reproducible))1760config->zeroModTime = true;17611762std::array<PlatformType, 4> encryptablePlatforms{1763PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS, PLATFORM_XROS};1764config->emitEncryptionInfo =1765args.hasFlag(OPT_encryptable, OPT_no_encryption,1766is_contained(encryptablePlatforms, config->platform()));17671768if (const Arg *arg = args.getLastArg(OPT_install_name)) {1769if (config->warnDylibInstallName && config->outputType != MH_DYLIB)1770warn(1771arg->getAsString(args) +1772": ignored, only has effect with -dylib [--warn-dylib-install-name]");1773else1774config->installName = arg->getValue();1775} else if (config->outputType == MH_DYLIB) {1776config->installName = config->finalOutput;1777}17781779if (args.hasArg(OPT_mark_dead_strippable_dylib)) {1780if (config->outputType != MH_DYLIB)1781warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");1782else1783config->markDeadStrippableDylib = true;1784}17851786if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))1787config->staticLink = (arg->getOption().getID() == OPT_static);17881789if (const Arg *arg =1790args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))1791config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace1792? NamespaceKind::twolevel1793: NamespaceKind::flat;17941795config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);17961797if (config->outputType == MH_EXECUTE)1798config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),1799/*file=*/nullptr,1800/*isWeakRef=*/false);18011802config->librarySearchPaths =1803getLibrarySearchPaths(args, config->systemLibraryRoots);1804config->frameworkSearchPaths =1805getFrameworkSearchPaths(args, config->systemLibraryRoots);1806if (const Arg *arg =1807args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))1808config->searchDylibsFirst =1809arg->getOption().getID() == OPT_search_dylibs_first;18101811config->dylibCompatibilityVersion =1812parseDylibVersion(args, OPT_compatibility_version);1813config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);18141815config->dataConst =1816args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));1817// Populate config->sectionRenameMap with builtin default renames.1818// Options -rename_section and -rename_segment are able to override.1819initializeSectionRenameMap();1820// Reject every special character except '.' and '$'1821// TODO(gkm): verify that this is the proper set of invalid chars1822StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");1823auto validName = [invalidNameChars](StringRef s) {1824if (s.find_first_of(invalidNameChars) != StringRef::npos)1825error("invalid name for segment or section: " + s);1826return s;1827};1828for (const Arg *arg : args.filtered(OPT_rename_section)) {1829config->sectionRenameMap[{validName(arg->getValue(0)),1830validName(arg->getValue(1))}] = {1831validName(arg->getValue(2)), validName(arg->getValue(3))};1832}1833for (const Arg *arg : args.filtered(OPT_rename_segment)) {1834config->segmentRenameMap[validName(arg->getValue(0))] =1835validName(arg->getValue(1));1836}18371838config->sectionAlignments = parseSectAlign(args);18391840for (const Arg *arg : args.filtered(OPT_segprot)) {1841StringRef segName = arg->getValue(0);1842uint32_t maxProt = parseProtection(arg->getValue(1));1843uint32_t initProt = parseProtection(arg->getValue(2));1844if (maxProt != initProt && config->arch() != AK_i386)1845error("invalid argument '" + arg->getAsString(args) +1846"': max and init must be the same for non-i386 archs");1847if (segName == segment_names::linkEdit)1848error("-segprot cannot be used to change __LINKEDIT's protections");1849config->segmentProtections.push_back({segName, maxProt, initProt});1850}18511852config->hasExplicitExports =1853args.hasArg(OPT_no_exported_symbols) ||1854args.hasArgNoClaim(OPT_exported_symbol, OPT_exported_symbols_list);1855handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,1856OPT_exported_symbols_list);1857handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,1858OPT_unexported_symbols_list);1859if (config->hasExplicitExports && !config->unexportedSymbols.empty())1860error("cannot use both -exported_symbol* and -unexported_symbol* options");18611862if (args.hasArg(OPT_no_exported_symbols) && !config->exportedSymbols.empty())1863error("cannot use both -exported_symbol* and -no_exported_symbols options");18641865// Imitating LD64's:1866// -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't1867// both be present.1868// But -x can be used with either of these two, in which case, the last arg1869// takes effect.1870// (TODO: This is kind of confusing - considering disallowing using them1871// together for a more straightforward behaviour)1872{1873bool includeLocal = false;1874bool excludeLocal = false;1875for (const Arg *arg :1876args.filtered(OPT_x, OPT_non_global_symbols_no_strip_list,1877OPT_non_global_symbols_strip_list)) {1878switch (arg->getOption().getID()) {1879case OPT_x:1880config->localSymbolsPresence = SymtabPresence::None;1881break;1882case OPT_non_global_symbols_no_strip_list:1883if (excludeLocal) {1884error("cannot use both -non_global_symbols_no_strip_list and "1885"-non_global_symbols_strip_list");1886} else {1887includeLocal = true;1888config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded;1889parseSymbolPatternsFile(arg, config->localSymbolPatterns);1890}1891break;1892case OPT_non_global_symbols_strip_list:1893if (includeLocal) {1894error("cannot use both -non_global_symbols_no_strip_list and "1895"-non_global_symbols_strip_list");1896} else {1897excludeLocal = true;1898config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded;1899parseSymbolPatternsFile(arg, config->localSymbolPatterns);1900}1901break;1902default:1903llvm_unreachable("unexpected option");1904}1905}1906}1907// Explicitly-exported literal symbols must be defined, but might1908// languish in an archive if unreferenced elsewhere or if they are in the1909// non-global strip list. Light a fire under those lazy symbols!1910for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)1911symtab->addUndefined(cachedName.val(), /*file=*/nullptr,1912/*isWeakRef=*/false);19131914for (const Arg *arg : args.filtered(OPT_why_live))1915config->whyLive.insert(arg->getValue());1916if (!config->whyLive.empty() && !config->deadStrip)1917warn("-why_live has no effect without -dead_strip, ignoring");19181919config->saveTemps = args.hasArg(OPT_save_temps);19201921config->adhocCodesign = args.hasFlag(1922OPT_adhoc_codesign, OPT_no_adhoc_codesign,1923shouldAdhocSignByDefault(config->arch(), config->platform()));19241925if (args.hasArg(OPT_v)) {1926message(getLLDVersion(), lld::errs());1927message(StringRef("Library search paths:") +1928(config->librarySearchPaths.empty()1929? ""1930: "\n\t" + join(config->librarySearchPaths, "\n\t")),1931lld::errs());1932message(StringRef("Framework search paths:") +1933(config->frameworkSearchPaths.empty()1934? ""1935: "\n\t" + join(config->frameworkSearchPaths, "\n\t")),1936lld::errs());1937}19381939config->progName = argsArr[0];19401941config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);1942config->timeTraceGranularity =1943args::getInteger(args, OPT_time_trace_granularity_eq, 500);19441945// Initialize time trace profiler.1946if (config->timeTraceEnabled)1947timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);19481949{1950TimeTraceScope timeScope("ExecuteLinker");19511952initLLVM(); // must be run before any call to addFile()1953createFiles(args);19541955// Now that all dylibs have been loaded, search for those that should be1956// re-exported.1957{1958auto reexportHandler = [](const Arg *arg,1959const std::vector<StringRef> &extensions) {1960config->hasReexports = true;1961StringRef searchName = arg->getValue();1962if (!markReexport(searchName, extensions))1963error(arg->getSpelling() + " " + searchName +1964" does not match a supplied dylib");1965};1966std::vector<StringRef> extensions = {".tbd"};1967for (const Arg *arg : args.filtered(OPT_sub_umbrella))1968reexportHandler(arg, extensions);19691970extensions.push_back(".dylib");1971for (const Arg *arg : args.filtered(OPT_sub_library))1972reexportHandler(arg, extensions);1973}19741975cl::ResetAllOptionOccurrences();19761977// Parse LTO options.1978if (const Arg *arg = args.getLastArg(OPT_mcpu))1979parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),1980arg->getSpelling());19811982for (const Arg *arg : args.filtered(OPT_mllvm)) {1983parseClangOption(arg->getValue(), arg->getSpelling());1984config->mllvmOpts.emplace_back(arg->getValue());1985}19861987createSyntheticSections();1988createSyntheticSymbols();1989addSynthenticMethnames();19901991createAliases();1992// If we are in "explicit exports" mode, hide everything that isn't1993// explicitly exported. Do this before running LTO so that LTO can better1994// optimize.1995handleExplicitExports();19961997bool didCompileBitcodeFiles = compileBitcodeFiles();19981999resolveLCLinkerOptions();20002001// If --thinlto-index-only is given, we should create only "index2002// files" and not object files. Index file creation is already done2003// in compileBitcodeFiles, so we are done if that's the case.2004if (config->thinLTOIndexOnly)2005return errorCount() == 0;20062007// LTO may emit a non-hidden (extern) object file symbol even if the2008// corresponding bitcode symbol is hidden. In particular, this happens for2009// cross-module references to hidden symbols under ThinLTO. Thus, if we2010// compiled any bitcode files, we must redo the symbol hiding.2011if (didCompileBitcodeFiles)2012handleExplicitExports();2013replaceCommonSymbols();20142015StringRef orderFile = args.getLastArgValue(OPT_order_file);2016if (!orderFile.empty())2017priorityBuilder.parseOrderFile(orderFile);20182019referenceStubBinder();20202021// FIXME: should terminate the link early based on errors encountered so2022// far?20232024for (const Arg *arg : args.filtered(OPT_sectcreate)) {2025StringRef segName = arg->getValue(0);2026StringRef sectName = arg->getValue(1);2027StringRef fileName = arg->getValue(2);2028std::optional<MemoryBufferRef> buffer = readFile(fileName);2029if (buffer)2030inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));2031}20322033for (const Arg *arg : args.filtered(OPT_add_empty_section)) {2034StringRef segName = arg->getValue(0);2035StringRef sectName = arg->getValue(1);2036inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName));2037}20382039gatherInputSections();2040if (config->callGraphProfileSort)2041priorityBuilder.extractCallGraphProfile();20422043if (config->deadStrip)2044markLive();20452046// Ensure that no symbols point inside __mod_init_func sections if they are2047// removed due to -init_offsets. This must run after dead stripping.2048if (config->emitInitOffsets)2049eraseInitializerSymbols();20502051// Categories are not subject to dead-strip. The __objc_catlist section is2052// marked as NO_DEAD_STRIP and that propagates into all category data.2053if (args.hasArg(OPT_check_category_conflicts))2054objc::checkCategories();20552056// Category merging uses "->live = false" to erase old category data, so2057// it has to run after dead-stripping (markLive).2058if (args.hasFlag(OPT_objc_category_merging, OPT_no_objc_category_merging,2059false))2060objc::mergeCategories();20612062// ICF assumes that all literals have been folded already, so we must run2063// foldIdenticalLiterals before foldIdenticalSections.2064foldIdenticalLiterals();2065if (config->icfLevel != ICFLevel::none) {2066if (config->icfLevel == ICFLevel::safe)2067markAddrSigSymbols();2068foldIdenticalSections(/*onlyCfStrings=*/false);2069} else if (config->dedupStrings) {2070foldIdenticalSections(/*onlyCfStrings=*/true);2071}20722073// Write to an output file.2074if (target->wordSize == 8)2075writeResult<LP64>();2076else2077writeResult<ILP32>();20782079depTracker->write(getLLDVersion(), inputFiles, config->outputFile);2080}20812082if (config->timeTraceEnabled) {2083checkError(timeTraceProfilerWrite(2084args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));20852086timeTraceProfilerCleanup();2087}20882089if (errorCount() != 0 || config->strictAutoLink)2090for (const auto &warning : missingAutolinkWarnings)2091warn(warning);20922093return errorCount() == 0;2094}2095} // namespace macho2096} // namespace lld209720982099