15ffd83dbSDimitry Andric //===- Driver.cpp ---------------------------------------------------------===// 25ffd83dbSDimitry Andric // 35ffd83dbSDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 45ffd83dbSDimitry Andric // See https://llvm.org/LICENSE.txt for license information. 55ffd83dbSDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 65ffd83dbSDimitry Andric // 75ffd83dbSDimitry Andric //===----------------------------------------------------------------------===// 85ffd83dbSDimitry Andric 95ffd83dbSDimitry Andric #include "Driver.h" 105ffd83dbSDimitry Andric #include "Config.h" 11fe6060f1SDimitry Andric #include "ICF.h" 125ffd83dbSDimitry Andric #include "InputFiles.h" 13e8d8bef9SDimitry Andric #include "LTO.h" 14fe6060f1SDimitry Andric #include "MarkLive.h" 15e8d8bef9SDimitry Andric #include "ObjC.h" 165ffd83dbSDimitry Andric #include "OutputSection.h" 175ffd83dbSDimitry Andric #include "OutputSegment.h" 1804eeddc0SDimitry Andric #include "SectionPriorities.h" 195ffd83dbSDimitry Andric #include "SymbolTable.h" 205ffd83dbSDimitry Andric #include "Symbols.h" 21e8d8bef9SDimitry Andric #include "SyntheticSections.h" 225ffd83dbSDimitry Andric #include "Target.h" 23fe6060f1SDimitry Andric #include "UnwindInfoSection.h" 245ffd83dbSDimitry Andric #include "Writer.h" 255ffd83dbSDimitry Andric 265ffd83dbSDimitry Andric #include "lld/Common/Args.h" 275ffd83dbSDimitry Andric #include "lld/Common/Driver.h" 285ffd83dbSDimitry Andric #include "lld/Common/ErrorHandler.h" 295ffd83dbSDimitry Andric #include "lld/Common/LLVM.h" 305ffd83dbSDimitry Andric #include "lld/Common/Memory.h" 31e8d8bef9SDimitry Andric #include "lld/Common/Reproduce.h" 325ffd83dbSDimitry Andric #include "lld/Common/Version.h" 335ffd83dbSDimitry Andric #include "llvm/ADT/DenseSet.h" 345ffd83dbSDimitry Andric #include "llvm/ADT/StringExtras.h" 355ffd83dbSDimitry Andric #include "llvm/ADT/StringRef.h" 365ffd83dbSDimitry Andric #include "llvm/BinaryFormat/MachO.h" 375ffd83dbSDimitry Andric #include "llvm/BinaryFormat/Magic.h" 38fe6060f1SDimitry Andric #include "llvm/Config/llvm-config.h" 39e8d8bef9SDimitry Andric #include "llvm/LTO/LTO.h" 405ffd83dbSDimitry Andric #include "llvm/Object/Archive.h" 415ffd83dbSDimitry Andric #include "llvm/Option/ArgList.h" 42e8d8bef9SDimitry Andric #include "llvm/Support/CommandLine.h" 43e8d8bef9SDimitry Andric #include "llvm/Support/FileSystem.h" 445ffd83dbSDimitry Andric #include "llvm/Support/Host.h" 455ffd83dbSDimitry Andric #include "llvm/Support/MemoryBuffer.h" 46fe6060f1SDimitry Andric #include "llvm/Support/Parallel.h" 475ffd83dbSDimitry Andric #include "llvm/Support/Path.h" 48e8d8bef9SDimitry Andric #include "llvm/Support/TarWriter.h" 49e8d8bef9SDimitry Andric #include "llvm/Support/TargetSelect.h" 50fe6060f1SDimitry Andric #include "llvm/Support/TimeProfiler.h" 51fe6060f1SDimitry Andric #include "llvm/TextAPI/PackedVersion.h" 52e8d8bef9SDimitry Andric 53e8d8bef9SDimitry Andric #include <algorithm> 545ffd83dbSDimitry Andric 555ffd83dbSDimitry Andric using namespace llvm; 565ffd83dbSDimitry Andric using namespace llvm::MachO; 57e8d8bef9SDimitry Andric using namespace llvm::object; 585ffd83dbSDimitry Andric using namespace llvm::opt; 59e8d8bef9SDimitry Andric using namespace llvm::sys; 605ffd83dbSDimitry Andric using namespace lld; 615ffd83dbSDimitry Andric using namespace lld::macho; 625ffd83dbSDimitry Andric 6304eeddc0SDimitry Andric std::unique_ptr<Configuration> macho::config; 6404eeddc0SDimitry Andric std::unique_ptr<DependencyTracker> macho::depTracker; 655ffd83dbSDimitry Andric 66fe6060f1SDimitry Andric static HeaderFileType getOutputType(const InputArgList &args) { 67e8d8bef9SDimitry Andric // TODO: -r, -dylinker, -preload... 68fe6060f1SDimitry Andric Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute); 69e8d8bef9SDimitry Andric if (outputArg == nullptr) 70e8d8bef9SDimitry Andric return MH_EXECUTE; 715ffd83dbSDimitry Andric 72e8d8bef9SDimitry Andric switch (outputArg->getOption().getID()) { 73e8d8bef9SDimitry Andric case OPT_bundle: 74e8d8bef9SDimitry Andric return MH_BUNDLE; 75e8d8bef9SDimitry Andric case OPT_dylib: 76e8d8bef9SDimitry Andric return MH_DYLIB; 77e8d8bef9SDimitry Andric case OPT_execute: 78e8d8bef9SDimitry Andric return MH_EXECUTE; 79e8d8bef9SDimitry Andric default: 80e8d8bef9SDimitry Andric llvm_unreachable("internal error"); 81e8d8bef9SDimitry Andric } 825ffd83dbSDimitry Andric } 835ffd83dbSDimitry Andric 84349cc55cSDimitry Andric static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries; 85fe6060f1SDimitry Andric static Optional<StringRef> findLibrary(StringRef name) { 86349cc55cSDimitry Andric CachedHashStringRef key(name); 87349cc55cSDimitry Andric auto entry = resolvedLibraries.find(key); 88349cc55cSDimitry Andric if (entry != resolvedLibraries.end()) 89349cc55cSDimitry Andric return entry->second; 90349cc55cSDimitry Andric 91349cc55cSDimitry Andric auto doFind = [&] { 92e8d8bef9SDimitry Andric if (config->searchDylibsFirst) { 93fe6060f1SDimitry Andric if (Optional<StringRef> path = findPathCombination( 94fe6060f1SDimitry Andric "lib" + name, config->librarySearchPaths, {".tbd", ".dylib"})) 95e8d8bef9SDimitry Andric return path; 96fe6060f1SDimitry Andric return findPathCombination("lib" + name, config->librarySearchPaths, 97fe6060f1SDimitry Andric {".a"}); 985ffd83dbSDimitry Andric } 99fe6060f1SDimitry Andric return findPathCombination("lib" + name, config->librarySearchPaths, 100fe6060f1SDimitry Andric {".tbd", ".dylib", ".a"}); 101349cc55cSDimitry Andric }; 102349cc55cSDimitry Andric 103349cc55cSDimitry Andric Optional<StringRef> path = doFind(); 104349cc55cSDimitry Andric if (path) 105349cc55cSDimitry Andric resolvedLibraries[key] = *path; 106349cc55cSDimitry Andric 107349cc55cSDimitry Andric return path; 108e8d8bef9SDimitry Andric } 109e8d8bef9SDimitry Andric 110349cc55cSDimitry Andric static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks; 111349cc55cSDimitry Andric static Optional<StringRef> findFramework(StringRef name) { 112349cc55cSDimitry Andric CachedHashStringRef key(name); 113349cc55cSDimitry Andric auto entry = resolvedFrameworks.find(key); 114349cc55cSDimitry Andric if (entry != resolvedFrameworks.end()) 115349cc55cSDimitry Andric return entry->second; 116349cc55cSDimitry Andric 117e8d8bef9SDimitry Andric SmallString<260> symlink; 118e8d8bef9SDimitry Andric StringRef suffix; 119e8d8bef9SDimitry Andric std::tie(name, suffix) = name.split(","); 120e8d8bef9SDimitry Andric for (StringRef dir : config->frameworkSearchPaths) { 121e8d8bef9SDimitry Andric symlink = dir; 122e8d8bef9SDimitry Andric path::append(symlink, name + ".framework", name); 123e8d8bef9SDimitry Andric 124e8d8bef9SDimitry Andric if (!suffix.empty()) { 125e8d8bef9SDimitry Andric // NOTE: we must resolve the symlink before trying the suffixes, because 126e8d8bef9SDimitry Andric // there are no symlinks for the suffixed paths. 127e8d8bef9SDimitry Andric SmallString<260> location; 128e8d8bef9SDimitry Andric if (!fs::real_path(symlink, location)) { 129e8d8bef9SDimitry Andric // only append suffix if realpath() succeeds 130e8d8bef9SDimitry Andric Twine suffixed = location + suffix; 131e8d8bef9SDimitry Andric if (fs::exists(suffixed)) 13204eeddc0SDimitry Andric return resolvedFrameworks[key] = saver().save(suffixed.str()); 133e8d8bef9SDimitry Andric } 134e8d8bef9SDimitry Andric // Suffix lookup failed, fall through to the no-suffix case. 135e8d8bef9SDimitry Andric } 136e8d8bef9SDimitry Andric 137349cc55cSDimitry Andric if (Optional<StringRef> path = resolveDylibPath(symlink.str())) 138349cc55cSDimitry Andric return resolvedFrameworks[key] = *path; 1395ffd83dbSDimitry Andric } 1405ffd83dbSDimitry Andric return {}; 1415ffd83dbSDimitry Andric } 1425ffd83dbSDimitry Andric 143e8d8bef9SDimitry Andric static bool warnIfNotDirectory(StringRef option, StringRef path) { 1445ffd83dbSDimitry Andric if (!fs::exists(path)) { 1455ffd83dbSDimitry Andric warn("directory not found for option -" + option + path); 1465ffd83dbSDimitry Andric return false; 1475ffd83dbSDimitry Andric } else if (!fs::is_directory(path)) { 1485ffd83dbSDimitry Andric warn("option -" + option + path + " references a non-directory path"); 1495ffd83dbSDimitry Andric return false; 1505ffd83dbSDimitry Andric } 1515ffd83dbSDimitry Andric return true; 1525ffd83dbSDimitry Andric } 1535ffd83dbSDimitry Andric 154e8d8bef9SDimitry Andric static std::vector<StringRef> 155fe6060f1SDimitry Andric getSearchPaths(unsigned optionCode, InputArgList &args, 156e8d8bef9SDimitry Andric const std::vector<StringRef> &roots, 1575ffd83dbSDimitry Andric const SmallVector<StringRef, 2> &systemPaths) { 158e8d8bef9SDimitry Andric std::vector<StringRef> paths; 159e8d8bef9SDimitry Andric StringRef optionLetter{optionCode == OPT_F ? "F" : "L"}; 160e8d8bef9SDimitry Andric for (StringRef path : args::getStrings(args, optionCode)) { 161e8d8bef9SDimitry Andric // NOTE: only absolute paths are re-rooted to syslibroot(s) 162e8d8bef9SDimitry Andric bool found = false; 163e8d8bef9SDimitry Andric if (path::is_absolute(path, path::Style::posix)) { 164e8d8bef9SDimitry Andric for (StringRef root : roots) { 165e8d8bef9SDimitry Andric SmallString<261> buffer(root); 166e8d8bef9SDimitry Andric path::append(buffer, path); 167e8d8bef9SDimitry Andric // Do not warn about paths that are computed via the syslib roots 168e8d8bef9SDimitry Andric if (fs::is_directory(buffer)) { 16904eeddc0SDimitry Andric paths.push_back(saver().save(buffer.str())); 170e8d8bef9SDimitry Andric found = true; 171e8d8bef9SDimitry Andric } 172e8d8bef9SDimitry Andric } 173e8d8bef9SDimitry Andric } 174e8d8bef9SDimitry Andric if (!found && warnIfNotDirectory(optionLetter, path)) 1755ffd83dbSDimitry Andric paths.push_back(path); 1765ffd83dbSDimitry Andric } 177e8d8bef9SDimitry Andric 178e8d8bef9SDimitry Andric // `-Z` suppresses the standard "system" search paths. 179e8d8bef9SDimitry Andric if (args.hasArg(OPT_Z)) 180e8d8bef9SDimitry Andric return paths; 181e8d8bef9SDimitry Andric 182fe6060f1SDimitry Andric for (const StringRef &path : systemPaths) { 183fe6060f1SDimitry Andric for (const StringRef &root : roots) { 184e8d8bef9SDimitry Andric SmallString<261> buffer(root); 185e8d8bef9SDimitry Andric path::append(buffer, path); 186e8d8bef9SDimitry Andric if (fs::is_directory(buffer)) 18704eeddc0SDimitry Andric paths.push_back(saver().save(buffer.str())); 1885ffd83dbSDimitry Andric } 1895ffd83dbSDimitry Andric } 190e8d8bef9SDimitry Andric return paths; 1915ffd83dbSDimitry Andric } 1925ffd83dbSDimitry Andric 193fe6060f1SDimitry Andric static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) { 194e8d8bef9SDimitry Andric std::vector<StringRef> roots; 195e8d8bef9SDimitry Andric for (const Arg *arg : args.filtered(OPT_syslibroot)) 196e8d8bef9SDimitry Andric roots.push_back(arg->getValue()); 197e8d8bef9SDimitry Andric // NOTE: the final `-syslibroot` being `/` will ignore all roots 198349cc55cSDimitry Andric if (!roots.empty() && roots.back() == "/") 199e8d8bef9SDimitry Andric roots.clear(); 200e8d8bef9SDimitry Andric // NOTE: roots can never be empty - add an empty root to simplify the library 201e8d8bef9SDimitry Andric // and framework search path computation. 202e8d8bef9SDimitry Andric if (roots.empty()) 203e8d8bef9SDimitry Andric roots.emplace_back(""); 204e8d8bef9SDimitry Andric return roots; 2055ffd83dbSDimitry Andric } 2065ffd83dbSDimitry Andric 207e8d8bef9SDimitry Andric static std::vector<StringRef> 208fe6060f1SDimitry Andric getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) { 209e8d8bef9SDimitry Andric return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"}); 210e8d8bef9SDimitry Andric } 211e8d8bef9SDimitry Andric 212e8d8bef9SDimitry Andric static std::vector<StringRef> 213fe6060f1SDimitry Andric getFrameworkSearchPaths(InputArgList &args, 214e8d8bef9SDimitry Andric const std::vector<StringRef> &roots) { 215e8d8bef9SDimitry Andric return getSearchPaths(OPT_F, args, roots, 2165ffd83dbSDimitry Andric {"/Library/Frameworks", "/System/Library/Frameworks"}); 2175ffd83dbSDimitry Andric } 2185ffd83dbSDimitry Andric 219fe6060f1SDimitry Andric static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) { 220fe6060f1SDimitry Andric SmallString<128> ltoPolicy; 221fe6060f1SDimitry Andric auto add = [<oPolicy](Twine val) { 222fe6060f1SDimitry Andric if (!ltoPolicy.empty()) 223fe6060f1SDimitry Andric ltoPolicy += ":"; 224fe6060f1SDimitry Andric val.toVector(ltoPolicy); 225fe6060f1SDimitry Andric }; 226fe6060f1SDimitry Andric for (const Arg *arg : 227fe6060f1SDimitry Andric args.filtered(OPT_thinlto_cache_policy, OPT_prune_interval_lto, 228fe6060f1SDimitry Andric OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) { 229fe6060f1SDimitry Andric switch (arg->getOption().getID()) { 230349cc55cSDimitry Andric case OPT_thinlto_cache_policy: 231349cc55cSDimitry Andric add(arg->getValue()); 232349cc55cSDimitry Andric break; 233fe6060f1SDimitry Andric case OPT_prune_interval_lto: 234fe6060f1SDimitry Andric if (!strcmp("-1", arg->getValue())) 235fe6060f1SDimitry Andric add("prune_interval=87600h"); // 10 years 236fe6060f1SDimitry Andric else 237fe6060f1SDimitry Andric add(Twine("prune_interval=") + arg->getValue() + "s"); 238fe6060f1SDimitry Andric break; 239fe6060f1SDimitry Andric case OPT_prune_after_lto: 240fe6060f1SDimitry Andric add(Twine("prune_after=") + arg->getValue() + "s"); 241fe6060f1SDimitry Andric break; 242fe6060f1SDimitry Andric case OPT_max_relative_cache_size_lto: 243fe6060f1SDimitry Andric add(Twine("cache_size=") + arg->getValue() + "%"); 244fe6060f1SDimitry Andric break; 245fe6060f1SDimitry Andric } 246fe6060f1SDimitry Andric } 247fe6060f1SDimitry Andric return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy"); 248fe6060f1SDimitry Andric } 249fe6060f1SDimitry Andric 250fe6060f1SDimitry Andric static DenseMap<StringRef, ArchiveFile *> loadedArchives; 251fe6060f1SDimitry Andric 252349cc55cSDimitry Andric static InputFile *addFile(StringRef path, ForceLoad forceLoadArchive, 25304eeddc0SDimitry Andric bool isLazy = false, bool isExplicit = true, 25404eeddc0SDimitry Andric bool isBundleLoader = false) { 2555ffd83dbSDimitry Andric Optional<MemoryBufferRef> buffer = readFile(path); 2565ffd83dbSDimitry Andric if (!buffer) 257e8d8bef9SDimitry Andric return nullptr; 2585ffd83dbSDimitry Andric MemoryBufferRef mbref = *buffer; 259e8d8bef9SDimitry Andric InputFile *newFile = nullptr; 2605ffd83dbSDimitry Andric 261fe6060f1SDimitry Andric file_magic magic = identify_magic(mbref.getBuffer()); 262e8d8bef9SDimitry Andric switch (magic) { 2635ffd83dbSDimitry Andric case file_magic::archive: { 264fe6060f1SDimitry Andric // Avoid loading archives twice. If the archives are being force-loaded, 265fe6060f1SDimitry Andric // loading them twice would create duplicate symbol errors. In the 266fe6060f1SDimitry Andric // non-force-loading case, this is just a minor performance optimization. 267fe6060f1SDimitry Andric // We don't take a reference to cachedFile here because the 268fe6060f1SDimitry Andric // loadArchiveMember() call below may recursively call addFile() and 269fe6060f1SDimitry Andric // invalidate this reference. 270*81ad6265SDimitry Andric auto entry = loadedArchives.find(path); 271*81ad6265SDimitry Andric if (entry != loadedArchives.end()) 272*81ad6265SDimitry Andric return entry->second; 273fe6060f1SDimitry Andric 274349cc55cSDimitry Andric std::unique_ptr<object::Archive> archive = CHECK( 2755ffd83dbSDimitry Andric object::Archive::create(mbref), path + ": failed to parse archive"); 2765ffd83dbSDimitry Andric 277349cc55cSDimitry Andric if (!archive->isEmpty() && !archive->hasSymbolTable()) 2785ffd83dbSDimitry Andric error(path + ": archive has no index; run ranlib to add one"); 2795ffd83dbSDimitry Andric 280349cc55cSDimitry Andric auto *file = make<ArchiveFile>(std::move(archive)); 281349cc55cSDimitry Andric if ((forceLoadArchive == ForceLoad::Default && config->allLoad) || 282349cc55cSDimitry Andric forceLoadArchive == ForceLoad::Yes) { 283e8d8bef9SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(path)) { 284349cc55cSDimitry Andric Error e = Error::success(); 285349cc55cSDimitry Andric for (const object::Archive::Child &c : file->getArchive().children(e)) { 286349cc55cSDimitry Andric StringRef reason = 287349cc55cSDimitry Andric forceLoadArchive == ForceLoad::Yes ? "-force_load" : "-all_load"; 288349cc55cSDimitry Andric if (Error e = file->fetch(c, reason)) 289349cc55cSDimitry Andric error(toString(file) + ": " + reason + 290349cc55cSDimitry Andric " failed to load archive member: " + toString(std::move(e))); 291e8d8bef9SDimitry Andric } 292349cc55cSDimitry Andric if (e) 293349cc55cSDimitry Andric error(toString(file) + 294349cc55cSDimitry Andric ": Archive::children failed: " + toString(std::move(e))); 295e8d8bef9SDimitry Andric } 296349cc55cSDimitry Andric } else if (forceLoadArchive == ForceLoad::Default && 297349cc55cSDimitry Andric config->forceLoadObjC) { 298349cc55cSDimitry Andric for (const object::Archive::Symbol &sym : file->getArchive().symbols()) 299e8d8bef9SDimitry Andric if (sym.getName().startswith(objc::klass)) 300349cc55cSDimitry Andric file->fetch(sym); 301e8d8bef9SDimitry Andric 302e8d8bef9SDimitry Andric // TODO: no need to look for ObjC sections for a given archive member if 303349cc55cSDimitry Andric // we already found that it contains an ObjC symbol. 304e8d8bef9SDimitry Andric if (Optional<MemoryBufferRef> buffer = readFile(path)) { 305349cc55cSDimitry Andric Error e = Error::success(); 306349cc55cSDimitry Andric for (const object::Archive::Child &c : file->getArchive().children(e)) { 307349cc55cSDimitry Andric Expected<MemoryBufferRef> mb = c.getMemoryBufferRef(); 308349cc55cSDimitry Andric if (!mb || !hasObjCSection(*mb)) 309349cc55cSDimitry Andric continue; 310349cc55cSDimitry Andric if (Error e = file->fetch(c, "-ObjC")) 311349cc55cSDimitry Andric error(toString(file) + ": -ObjC failed to load archive member: " + 312349cc55cSDimitry Andric toString(std::move(e))); 313e8d8bef9SDimitry Andric } 314349cc55cSDimitry Andric if (e) 315349cc55cSDimitry Andric error(toString(file) + 316349cc55cSDimitry Andric ": Archive::children failed: " + toString(std::move(e))); 317e8d8bef9SDimitry Andric } 318e8d8bef9SDimitry Andric } 319e8d8bef9SDimitry Andric 320349cc55cSDimitry Andric file->addLazySymbols(); 321349cc55cSDimitry Andric newFile = loadedArchives[path] = file; 3225ffd83dbSDimitry Andric break; 3235ffd83dbSDimitry Andric } 3245ffd83dbSDimitry Andric case file_magic::macho_object: 32504eeddc0SDimitry Andric newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy); 3265ffd83dbSDimitry Andric break; 3275ffd83dbSDimitry Andric case file_magic::macho_dynamically_linked_shared_lib: 328e8d8bef9SDimitry Andric case file_magic::macho_dynamically_linked_shared_lib_stub: 329fe6060f1SDimitry Andric case file_magic::tapi_file: 330*81ad6265SDimitry Andric if (DylibFile *dylibFile = 331*81ad6265SDimitry Andric loadDylib(mbref, nullptr, /*isBundleLoader=*/false, isExplicit)) 332fe6060f1SDimitry Andric newFile = dylibFile; 333fe6060f1SDimitry Andric break; 334e8d8bef9SDimitry Andric case file_magic::bitcode: 33504eeddc0SDimitry Andric newFile = make<BitcodeFile>(mbref, "", 0, isLazy); 336fe6060f1SDimitry Andric break; 337fe6060f1SDimitry Andric case file_magic::macho_executable: 338fe6060f1SDimitry Andric case file_magic::macho_bundle: 339fe6060f1SDimitry Andric // We only allow executable and bundle type here if it is used 340fe6060f1SDimitry Andric // as a bundle loader. 341fe6060f1SDimitry Andric if (!isBundleLoader) 342fe6060f1SDimitry Andric error(path + ": unhandled file type"); 343fe6060f1SDimitry Andric if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader)) 344fe6060f1SDimitry Andric newFile = dylibFile; 345e8d8bef9SDimitry Andric break; 3465ffd83dbSDimitry Andric default: 3475ffd83dbSDimitry Andric error(path + ": unhandled file type"); 3485ffd83dbSDimitry Andric } 349fe6060f1SDimitry Andric if (newFile && !isa<DylibFile>(newFile)) { 35004eeddc0SDimitry Andric if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy && 35104eeddc0SDimitry Andric config->forceLoadObjC) { 35204eeddc0SDimitry Andric for (Symbol *sym : newFile->symbols) 35304eeddc0SDimitry Andric if (sym && sym->getName().startswith(objc::klass)) { 35404eeddc0SDimitry Andric extract(*newFile, "-ObjC"); 35504eeddc0SDimitry Andric break; 35604eeddc0SDimitry Andric } 35704eeddc0SDimitry Andric if (newFile->lazy && hasObjCSection(mbref)) 35804eeddc0SDimitry Andric extract(*newFile, "-ObjC"); 35904eeddc0SDimitry Andric } 36004eeddc0SDimitry Andric 361e8d8bef9SDimitry Andric // printArchiveMemberLoad() prints both .a and .o names, so no need to 36204eeddc0SDimitry Andric // print the .a name here. Similarly skip lazy files. 36304eeddc0SDimitry Andric if (config->printEachFile && magic != file_magic::archive && !isLazy) 364e8d8bef9SDimitry Andric message(toString(newFile)); 365e8d8bef9SDimitry Andric inputFiles.insert(newFile); 366e8d8bef9SDimitry Andric } 367e8d8bef9SDimitry Andric return newFile; 3685ffd83dbSDimitry Andric } 3695ffd83dbSDimitry Andric 370fe6060f1SDimitry Andric static void addLibrary(StringRef name, bool isNeeded, bool isWeak, 371349cc55cSDimitry Andric bool isReexport, bool isExplicit, 372349cc55cSDimitry Andric ForceLoad forceLoadArchive) { 373fe6060f1SDimitry Andric if (Optional<StringRef> path = findLibrary(name)) { 374fe6060f1SDimitry Andric if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 37504eeddc0SDimitry Andric addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit))) { 376fe6060f1SDimitry Andric if (isNeeded) 377fe6060f1SDimitry Andric dylibFile->forceNeeded = true; 378fe6060f1SDimitry Andric if (isWeak) 379e8d8bef9SDimitry Andric dylibFile->forceWeakImport = true; 380fe6060f1SDimitry Andric if (isReexport) { 381fe6060f1SDimitry Andric config->hasReexports = true; 382fe6060f1SDimitry Andric dylibFile->reexport = true; 383fe6060f1SDimitry Andric } 384fe6060f1SDimitry Andric } 385e8d8bef9SDimitry Andric return; 386e8d8bef9SDimitry Andric } 387e8d8bef9SDimitry Andric error("library not found for -l" + name); 388e8d8bef9SDimitry Andric } 389e8d8bef9SDimitry Andric 390*81ad6265SDimitry Andric static DenseSet<StringRef> loadedObjectFrameworks; 391fe6060f1SDimitry Andric static void addFramework(StringRef name, bool isNeeded, bool isWeak, 392349cc55cSDimitry Andric bool isReexport, bool isExplicit, 393349cc55cSDimitry Andric ForceLoad forceLoadArchive) { 394349cc55cSDimitry Andric if (Optional<StringRef> path = findFramework(name)) { 395*81ad6265SDimitry Andric if (loadedObjectFrameworks.contains(*path)) 396*81ad6265SDimitry Andric return; 397*81ad6265SDimitry Andric 398*81ad6265SDimitry Andric InputFile *file = 399*81ad6265SDimitry Andric addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit); 400*81ad6265SDimitry Andric if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) { 401fe6060f1SDimitry Andric if (isNeeded) 402fe6060f1SDimitry Andric dylibFile->forceNeeded = true; 403fe6060f1SDimitry Andric if (isWeak) 404e8d8bef9SDimitry Andric dylibFile->forceWeakImport = true; 405fe6060f1SDimitry Andric if (isReexport) { 406fe6060f1SDimitry Andric config->hasReexports = true; 407fe6060f1SDimitry Andric dylibFile->reexport = true; 408fe6060f1SDimitry Andric } 409*81ad6265SDimitry Andric } else if (isa_and_nonnull<ObjFile>(file) || 410*81ad6265SDimitry Andric isa_and_nonnull<BitcodeFile>(file)) { 411*81ad6265SDimitry Andric // Cache frameworks containing object or bitcode files to avoid duplicate 412*81ad6265SDimitry Andric // symbols. Frameworks containing static archives are cached separately 413*81ad6265SDimitry Andric // in addFile() to share caching with libraries, and frameworks 414*81ad6265SDimitry Andric // containing dylibs should allow overwriting of attributes such as 415*81ad6265SDimitry Andric // forceNeeded by subsequent loads 416*81ad6265SDimitry Andric loadedObjectFrameworks.insert(*path); 417fe6060f1SDimitry Andric } 418e8d8bef9SDimitry Andric return; 419e8d8bef9SDimitry Andric } 420e8d8bef9SDimitry Andric error("framework not found for -framework " + name); 421e8d8bef9SDimitry Andric } 422e8d8bef9SDimitry Andric 423fe6060f1SDimitry Andric // Parses LC_LINKER_OPTION contents, which can add additional command line 424349cc55cSDimitry Andric // flags. This directly parses the flags instead of using the standard argument 425349cc55cSDimitry Andric // parser to improve performance. 426e8d8bef9SDimitry Andric void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) { 427349cc55cSDimitry Andric SmallVector<StringRef, 4> argv; 428e8d8bef9SDimitry Andric size_t offset = 0; 429e8d8bef9SDimitry Andric for (unsigned i = 0; i < argc && offset < data.size(); ++i) { 430e8d8bef9SDimitry Andric argv.push_back(data.data() + offset); 431e8d8bef9SDimitry Andric offset += strlen(data.data() + offset) + 1; 432e8d8bef9SDimitry Andric } 433e8d8bef9SDimitry Andric if (argv.size() != argc || offset > data.size()) 434e8d8bef9SDimitry Andric fatal(toString(f) + ": invalid LC_LINKER_OPTION"); 435e8d8bef9SDimitry Andric 436349cc55cSDimitry Andric unsigned i = 0; 437349cc55cSDimitry Andric StringRef arg = argv[i]; 438349cc55cSDimitry Andric if (arg.consume_front("-l")) { 439349cc55cSDimitry Andric ForceLoad forceLoadArchive = 440349cc55cSDimitry Andric config->forceLoadSwift && arg.startswith("swift") ? ForceLoad::Yes 441349cc55cSDimitry Andric : ForceLoad::No; 442349cc55cSDimitry Andric addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false, 443349cc55cSDimitry Andric /*isReexport=*/false, /*isExplicit=*/false, forceLoadArchive); 444349cc55cSDimitry Andric } else if (arg == "-framework") { 445349cc55cSDimitry Andric StringRef name = argv[++i]; 446349cc55cSDimitry Andric addFramework(name, /*isNeeded=*/false, /*isWeak=*/false, 447349cc55cSDimitry Andric /*isReexport=*/false, /*isExplicit=*/false, ForceLoad::No); 448349cc55cSDimitry Andric } else { 449349cc55cSDimitry Andric error(arg + " is not allowed in LC_LINKER_OPTION"); 450e8d8bef9SDimitry Andric } 451e8d8bef9SDimitry Andric } 452e8d8bef9SDimitry Andric 45304eeddc0SDimitry Andric static void addFileList(StringRef path, bool isLazy) { 454e8d8bef9SDimitry Andric Optional<MemoryBufferRef> buffer = readFile(path); 455e8d8bef9SDimitry Andric if (!buffer) 456e8d8bef9SDimitry Andric return; 457e8d8bef9SDimitry Andric MemoryBufferRef mbref = *buffer; 458e8d8bef9SDimitry Andric for (StringRef path : args::getLines(mbref)) 45904eeddc0SDimitry Andric addFile(rerootPath(path), ForceLoad::Default, isLazy); 4605ffd83dbSDimitry Andric } 4615ffd83dbSDimitry Andric 4625ffd83dbSDimitry Andric // We expect sub-library names of the form "libfoo", which will match a dylib 463e8d8bef9SDimitry Andric // with a path of .*/libfoo.{dylib, tbd}. 464e8d8bef9SDimitry Andric // XXX ld64 seems to ignore the extension entirely when matching sub-libraries; 465e8d8bef9SDimitry Andric // I'm not sure what the use case for that is. 466e8d8bef9SDimitry Andric static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) { 4675ffd83dbSDimitry Andric for (InputFile *file : inputFiles) { 4685ffd83dbSDimitry Andric if (auto *dylibFile = dyn_cast<DylibFile>(file)) { 4695ffd83dbSDimitry Andric StringRef filename = path::filename(dylibFile->getName()); 470e8d8bef9SDimitry Andric if (filename.consume_front(searchName) && 471e8d8bef9SDimitry Andric (filename.empty() || 472e8d8bef9SDimitry Andric find(extensions, filename) != extensions.end())) { 4735ffd83dbSDimitry Andric dylibFile->reexport = true; 4745ffd83dbSDimitry Andric return true; 4755ffd83dbSDimitry Andric } 4765ffd83dbSDimitry Andric } 4775ffd83dbSDimitry Andric } 4785ffd83dbSDimitry Andric return false; 4795ffd83dbSDimitry Andric } 4805ffd83dbSDimitry Andric 481e8d8bef9SDimitry Andric // This function is called on startup. We need this for LTO since 482e8d8bef9SDimitry Andric // LTO calls LLVM functions to compile bitcode files to native code. 483e8d8bef9SDimitry Andric // Technically this can be delayed until we read bitcode files, but 484e8d8bef9SDimitry Andric // we don't bother to do lazily because the initialization is fast. 485e8d8bef9SDimitry Andric static void initLLVM() { 486e8d8bef9SDimitry Andric InitializeAllTargets(); 487e8d8bef9SDimitry Andric InitializeAllTargetMCs(); 488e8d8bef9SDimitry Andric InitializeAllAsmPrinters(); 489e8d8bef9SDimitry Andric InitializeAllAsmParsers(); 490e8d8bef9SDimitry Andric } 491e8d8bef9SDimitry Andric 492e8d8bef9SDimitry Andric static void compileBitcodeFiles() { 493fe6060f1SDimitry Andric TimeTraceScope timeScope("LTO"); 494fe6060f1SDimitry Andric auto *lto = make<BitcodeCompiler>(); 495e8d8bef9SDimitry Andric for (InputFile *file : inputFiles) 496e8d8bef9SDimitry Andric if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file)) 49704eeddc0SDimitry Andric if (!file->lazy) 498e8d8bef9SDimitry Andric lto->add(*bitcodeFile); 499e8d8bef9SDimitry Andric 500e8d8bef9SDimitry Andric for (ObjFile *file : lto->compile()) 501e8d8bef9SDimitry Andric inputFiles.insert(file); 502e8d8bef9SDimitry Andric } 503e8d8bef9SDimitry Andric 504e8d8bef9SDimitry Andric // Replaces common symbols with defined symbols residing in __common sections. 505e8d8bef9SDimitry Andric // This function must be called after all symbol names are resolved (i.e. after 506e8d8bef9SDimitry Andric // all InputFiles have been loaded.) As a result, later operations won't see 507e8d8bef9SDimitry Andric // any CommonSymbols. 508e8d8bef9SDimitry Andric static void replaceCommonSymbols() { 509fe6060f1SDimitry Andric TimeTraceScope timeScope("Replace common symbols"); 510fe6060f1SDimitry Andric ConcatOutputSection *osec = nullptr; 511fe6060f1SDimitry Andric for (Symbol *sym : symtab->getSymbols()) { 512e8d8bef9SDimitry Andric auto *common = dyn_cast<CommonSymbol>(sym); 513e8d8bef9SDimitry Andric if (common == nullptr) 514e8d8bef9SDimitry Andric continue; 515e8d8bef9SDimitry Andric 516e8d8bef9SDimitry Andric // Casting to size_t will truncate large values on 32-bit architectures, 517e8d8bef9SDimitry Andric // but it's not really worth supporting the linking of 64-bit programs on 518e8d8bef9SDimitry Andric // 32-bit archs. 519fe6060f1SDimitry Andric ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)}; 520*81ad6265SDimitry Andric // FIXME avoid creating one Section per symbol? 521*81ad6265SDimitry Andric auto *section = 522*81ad6265SDimitry Andric make<Section>(common->getFile(), segment_names::data, 523*81ad6265SDimitry Andric section_names::common, S_ZEROFILL, /*addr=*/0); 524*81ad6265SDimitry Andric auto *isec = make<ConcatInputSection>(*section, data, common->align); 525fe6060f1SDimitry Andric if (!osec) 526fe6060f1SDimitry Andric osec = ConcatOutputSection::getOrCreateForInput(isec); 527fe6060f1SDimitry Andric isec->parent = osec; 528e8d8bef9SDimitry Andric inputSections.push_back(isec); 529e8d8bef9SDimitry Andric 530fe6060f1SDimitry Andric // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip 531fe6060f1SDimitry Andric // and pass them on here. 532*81ad6265SDimitry Andric replaceSymbol<Defined>( 533*81ad6265SDimitry Andric sym, sym->getName(), common->getFile(), isec, /*value=*/0, /*size=*/0, 534*81ad6265SDimitry Andric /*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern, 535*81ad6265SDimitry Andric /*includeInSymtab=*/true, /*isThumb=*/false, 536*81ad6265SDimitry Andric /*isReferencedDynamically=*/false, /*noDeadStrip=*/false); 537e8d8bef9SDimitry Andric } 538e8d8bef9SDimitry Andric } 539e8d8bef9SDimitry Andric 540fe6060f1SDimitry Andric static void initializeSectionRenameMap() { 541fe6060f1SDimitry Andric if (config->dataConst) { 542fe6060f1SDimitry Andric SmallVector<StringRef> v{section_names::got, 543fe6060f1SDimitry Andric section_names::authGot, 544fe6060f1SDimitry Andric section_names::authPtr, 545fe6060f1SDimitry Andric section_names::nonLazySymbolPtr, 546fe6060f1SDimitry Andric section_names::const_, 547fe6060f1SDimitry Andric section_names::cfString, 548fe6060f1SDimitry Andric section_names::moduleInitFunc, 549fe6060f1SDimitry Andric section_names::moduleTermFunc, 550fe6060f1SDimitry Andric section_names::objcClassList, 551fe6060f1SDimitry Andric section_names::objcNonLazyClassList, 552fe6060f1SDimitry Andric section_names::objcCatList, 553fe6060f1SDimitry Andric section_names::objcNonLazyCatList, 554fe6060f1SDimitry Andric section_names::objcProtoList, 555fe6060f1SDimitry Andric section_names::objcImageInfo}; 556fe6060f1SDimitry Andric for (StringRef s : v) 557fe6060f1SDimitry Andric config->sectionRenameMap[{segment_names::data, s}] = { 558fe6060f1SDimitry Andric segment_names::dataConst, s}; 559fe6060f1SDimitry Andric } 560fe6060f1SDimitry Andric config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = { 561fe6060f1SDimitry Andric segment_names::text, section_names::text}; 562fe6060f1SDimitry Andric config->sectionRenameMap[{segment_names::import, section_names::pointers}] = { 563fe6060f1SDimitry Andric config->dataConst ? segment_names::dataConst : segment_names::data, 564fe6060f1SDimitry Andric section_names::nonLazySymbolPtr}; 565fe6060f1SDimitry Andric } 566fe6060f1SDimitry Andric 567e8d8bef9SDimitry Andric static inline char toLowerDash(char x) { 568e8d8bef9SDimitry Andric if (x >= 'A' && x <= 'Z') 569e8d8bef9SDimitry Andric return x - 'A' + 'a'; 570e8d8bef9SDimitry Andric else if (x == ' ') 571e8d8bef9SDimitry Andric return '-'; 572e8d8bef9SDimitry Andric return x; 573e8d8bef9SDimitry Andric } 574e8d8bef9SDimitry Andric 575e8d8bef9SDimitry Andric static std::string lowerDash(StringRef s) { 576e8d8bef9SDimitry Andric return std::string(map_iterator(s.begin(), toLowerDash), 577e8d8bef9SDimitry Andric map_iterator(s.end(), toLowerDash)); 578e8d8bef9SDimitry Andric } 579e8d8bef9SDimitry Andric 580*81ad6265SDimitry Andric struct PlatformVersion { 581*81ad6265SDimitry Andric PlatformType platform = PLATFORM_UNKNOWN; 582*81ad6265SDimitry Andric llvm::VersionTuple minimum; 583*81ad6265SDimitry Andric llvm::VersionTuple sdk; 584*81ad6265SDimitry Andric }; 585fe6060f1SDimitry Andric 586*81ad6265SDimitry Andric static PlatformVersion parsePlatformVersion(const Arg *arg) { 587*81ad6265SDimitry Andric assert(arg->getOption().getID() == OPT_platform_version); 588e8d8bef9SDimitry Andric StringRef platformStr = arg->getValue(0); 589e8d8bef9SDimitry Andric StringRef minVersionStr = arg->getValue(1); 590e8d8bef9SDimitry Andric StringRef sdkVersionStr = arg->getValue(2); 591e8d8bef9SDimitry Andric 592*81ad6265SDimitry Andric PlatformVersion platformVersion; 593*81ad6265SDimitry Andric 594e8d8bef9SDimitry Andric // TODO(compnerd) see if we can generate this case list via XMACROS 595*81ad6265SDimitry Andric platformVersion.platform = 59604eeddc0SDimitry Andric StringSwitch<PlatformType>(lowerDash(platformStr)) 59704eeddc0SDimitry Andric .Cases("macos", "1", PLATFORM_MACOS) 59804eeddc0SDimitry Andric .Cases("ios", "2", PLATFORM_IOS) 59904eeddc0SDimitry Andric .Cases("tvos", "3", PLATFORM_TVOS) 60004eeddc0SDimitry Andric .Cases("watchos", "4", PLATFORM_WATCHOS) 60104eeddc0SDimitry Andric .Cases("bridgeos", "5", PLATFORM_BRIDGEOS) 60204eeddc0SDimitry Andric .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST) 60304eeddc0SDimitry Andric .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR) 60404eeddc0SDimitry Andric .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR) 60504eeddc0SDimitry Andric .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR) 60604eeddc0SDimitry Andric .Cases("driverkit", "10", PLATFORM_DRIVERKIT) 60704eeddc0SDimitry Andric .Default(PLATFORM_UNKNOWN); 608*81ad6265SDimitry Andric if (platformVersion.platform == PLATFORM_UNKNOWN) 609e8d8bef9SDimitry Andric error(Twine("malformed platform: ") + platformStr); 610e8d8bef9SDimitry Andric // TODO: check validity of version strings, which varies by platform 611e8d8bef9SDimitry Andric // NOTE: ld64 accepts version strings with 5 components 612e8d8bef9SDimitry Andric // llvm::VersionTuple accepts no more than 4 components 613e8d8bef9SDimitry Andric // Has Apple ever published version strings with 5 components? 614*81ad6265SDimitry Andric if (platformVersion.minimum.tryParse(minVersionStr)) 615e8d8bef9SDimitry Andric error(Twine("malformed minimum version: ") + minVersionStr); 616*81ad6265SDimitry Andric if (platformVersion.sdk.tryParse(sdkVersionStr)) 617e8d8bef9SDimitry Andric error(Twine("malformed sdk version: ") + sdkVersionStr); 618*81ad6265SDimitry Andric return platformVersion; 619*81ad6265SDimitry Andric } 620*81ad6265SDimitry Andric 621*81ad6265SDimitry Andric // Has the side-effect of setting Config::platformInfo. 622*81ad6265SDimitry Andric static PlatformType parsePlatformVersions(const ArgList &args) { 623*81ad6265SDimitry Andric std::map<PlatformType, PlatformVersion> platformVersions; 624*81ad6265SDimitry Andric const PlatformVersion *lastVersionInfo = nullptr; 625*81ad6265SDimitry Andric for (const Arg *arg : args.filtered(OPT_platform_version)) { 626*81ad6265SDimitry Andric PlatformVersion version = parsePlatformVersion(arg); 627*81ad6265SDimitry Andric 628*81ad6265SDimitry Andric // For each platform, the last flag wins: 629*81ad6265SDimitry Andric // `-platform_version macos 2 3 -platform_version macos 4 5` has the same 630*81ad6265SDimitry Andric // effect as just passing `-platform_version macos 4 5`. 631*81ad6265SDimitry Andric // FIXME: ld64 warns on multiple flags for one platform. Should we? 632*81ad6265SDimitry Andric platformVersions[version.platform] = version; 633*81ad6265SDimitry Andric lastVersionInfo = &platformVersions[version.platform]; 634*81ad6265SDimitry Andric } 635*81ad6265SDimitry Andric 636*81ad6265SDimitry Andric if (platformVersions.empty()) { 637*81ad6265SDimitry Andric error("must specify -platform_version"); 638*81ad6265SDimitry Andric return PLATFORM_UNKNOWN; 639*81ad6265SDimitry Andric } 640*81ad6265SDimitry Andric if (platformVersions.size() > 2) { 641*81ad6265SDimitry Andric error("must specify -platform_version at most twice"); 642*81ad6265SDimitry Andric return PLATFORM_UNKNOWN; 643*81ad6265SDimitry Andric } 644*81ad6265SDimitry Andric if (platformVersions.size() == 2) { 645*81ad6265SDimitry Andric bool isZipperedCatalyst = platformVersions.count(PLATFORM_MACOS) && 646*81ad6265SDimitry Andric platformVersions.count(PLATFORM_MACCATALYST); 647*81ad6265SDimitry Andric 648*81ad6265SDimitry Andric if (!isZipperedCatalyst) { 649*81ad6265SDimitry Andric error("lld supports writing zippered outputs only for " 650*81ad6265SDimitry Andric "macos and mac-catalyst"); 651*81ad6265SDimitry Andric } else if (config->outputType != MH_DYLIB && 652*81ad6265SDimitry Andric config->outputType != MH_BUNDLE) { 653*81ad6265SDimitry Andric error("writing zippered outputs only valid for -dylib and -bundle"); 654*81ad6265SDimitry Andric } else { 655*81ad6265SDimitry Andric config->platformInfo.minimum = platformVersions[PLATFORM_MACOS].minimum; 656*81ad6265SDimitry Andric config->platformInfo.sdk = platformVersions[PLATFORM_MACOS].sdk; 657*81ad6265SDimitry Andric config->secondaryPlatformInfo = PlatformInfo{}; 658*81ad6265SDimitry Andric config->secondaryPlatformInfo->minimum = 659*81ad6265SDimitry Andric platformVersions[PLATFORM_MACCATALYST].minimum; 660*81ad6265SDimitry Andric config->secondaryPlatformInfo->sdk = 661*81ad6265SDimitry Andric platformVersions[PLATFORM_MACCATALYST].sdk; 662*81ad6265SDimitry Andric } 663*81ad6265SDimitry Andric return PLATFORM_MACOS; 664*81ad6265SDimitry Andric } 665*81ad6265SDimitry Andric 666*81ad6265SDimitry Andric config->platformInfo.minimum = lastVersionInfo->minimum; 667*81ad6265SDimitry Andric config->platformInfo.sdk = lastVersionInfo->sdk; 668*81ad6265SDimitry Andric return lastVersionInfo->platform; 669e8d8bef9SDimitry Andric } 670e8d8bef9SDimitry Andric 671fe6060f1SDimitry Andric // Has the side-effect of setting Config::target. 672fe6060f1SDimitry Andric static TargetInfo *createTargetInfo(InputArgList &args) { 673fe6060f1SDimitry Andric StringRef archName = args.getLastArgValue(OPT_arch); 674349cc55cSDimitry Andric if (archName.empty()) { 675349cc55cSDimitry Andric error("must specify -arch"); 676349cc55cSDimitry Andric return nullptr; 677349cc55cSDimitry Andric } 678fe6060f1SDimitry Andric 679*81ad6265SDimitry Andric PlatformType platform = parsePlatformVersions(args); 680fe6060f1SDimitry Andric config->platformInfo.target = 681fe6060f1SDimitry Andric MachO::Target(getArchitectureFromName(archName), platform); 682*81ad6265SDimitry Andric if (config->secondaryPlatformInfo) { 683*81ad6265SDimitry Andric config->secondaryPlatformInfo->target = 684*81ad6265SDimitry Andric MachO::Target(getArchitectureFromName(archName), PLATFORM_MACCATALYST); 685*81ad6265SDimitry Andric } 686fe6060f1SDimitry Andric 687fe6060f1SDimitry Andric uint32_t cpuType; 688fe6060f1SDimitry Andric uint32_t cpuSubtype; 689fe6060f1SDimitry Andric std::tie(cpuType, cpuSubtype) = getCPUTypeFromArchitecture(config->arch()); 690fe6060f1SDimitry Andric 691fe6060f1SDimitry Andric switch (cpuType) { 692fe6060f1SDimitry Andric case CPU_TYPE_X86_64: 693fe6060f1SDimitry Andric return createX86_64TargetInfo(); 694fe6060f1SDimitry Andric case CPU_TYPE_ARM64: 695fe6060f1SDimitry Andric return createARM64TargetInfo(); 696fe6060f1SDimitry Andric case CPU_TYPE_ARM64_32: 697fe6060f1SDimitry Andric return createARM64_32TargetInfo(); 698fe6060f1SDimitry Andric case CPU_TYPE_ARM: 699fe6060f1SDimitry Andric return createARMTargetInfo(cpuSubtype); 700fe6060f1SDimitry Andric default: 701349cc55cSDimitry Andric error("missing or unsupported -arch " + archName); 702349cc55cSDimitry Andric return nullptr; 703fe6060f1SDimitry Andric } 704fe6060f1SDimitry Andric } 705fe6060f1SDimitry Andric 706fe6060f1SDimitry Andric static UndefinedSymbolTreatment 707fe6060f1SDimitry Andric getUndefinedSymbolTreatment(const ArgList &args) { 708fe6060f1SDimitry Andric StringRef treatmentStr = args.getLastArgValue(OPT_undefined); 709fe6060f1SDimitry Andric auto treatment = 710e8d8bef9SDimitry Andric StringSwitch<UndefinedSymbolTreatment>(treatmentStr) 711fe6060f1SDimitry Andric .Cases("error", "", UndefinedSymbolTreatment::error) 712e8d8bef9SDimitry Andric .Case("warning", UndefinedSymbolTreatment::warning) 713e8d8bef9SDimitry Andric .Case("suppress", UndefinedSymbolTreatment::suppress) 714e8d8bef9SDimitry Andric .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup) 715e8d8bef9SDimitry Andric .Default(UndefinedSymbolTreatment::unknown); 716fe6060f1SDimitry Andric if (treatment == UndefinedSymbolTreatment::unknown) { 717e8d8bef9SDimitry Andric warn(Twine("unknown -undefined TREATMENT '") + treatmentStr + 718e8d8bef9SDimitry Andric "', defaulting to 'error'"); 719fe6060f1SDimitry Andric treatment = UndefinedSymbolTreatment::error; 720fe6060f1SDimitry Andric } else if (config->namespaceKind == NamespaceKind::twolevel && 721fe6060f1SDimitry Andric (treatment == UndefinedSymbolTreatment::warning || 722fe6060f1SDimitry Andric treatment == UndefinedSymbolTreatment::suppress)) { 723fe6060f1SDimitry Andric if (treatment == UndefinedSymbolTreatment::warning) 724fe6060f1SDimitry Andric error("'-undefined warning' only valid with '-flat_namespace'"); 725fe6060f1SDimitry Andric else 726fe6060f1SDimitry Andric error("'-undefined suppress' only valid with '-flat_namespace'"); 727fe6060f1SDimitry Andric treatment = UndefinedSymbolTreatment::error; 728e8d8bef9SDimitry Andric } 729fe6060f1SDimitry Andric return treatment; 7305ffd83dbSDimitry Andric } 7315ffd83dbSDimitry Andric 732fe6060f1SDimitry Andric static ICFLevel getICFLevel(const ArgList &args) { 733fe6060f1SDimitry Andric StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq); 734fe6060f1SDimitry Andric auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr) 735fe6060f1SDimitry Andric .Cases("none", "", ICFLevel::none) 736fe6060f1SDimitry Andric .Case("safe", ICFLevel::safe) 737fe6060f1SDimitry Andric .Case("all", ICFLevel::all) 738fe6060f1SDimitry Andric .Default(ICFLevel::unknown); 739fe6060f1SDimitry Andric if (icfLevel == ICFLevel::unknown) { 740fe6060f1SDimitry Andric warn(Twine("unknown --icf=OPTION `") + icfLevelStr + 741fe6060f1SDimitry Andric "', defaulting to `none'"); 742fe6060f1SDimitry Andric icfLevel = ICFLevel::none; 743fe6060f1SDimitry Andric } 744fe6060f1SDimitry Andric return icfLevel; 745fe6060f1SDimitry Andric } 746fe6060f1SDimitry Andric 747fe6060f1SDimitry Andric static void warnIfDeprecatedOption(const Option &opt) { 7485ffd83dbSDimitry Andric if (!opt.getGroup().isValid()) 7495ffd83dbSDimitry Andric return; 7505ffd83dbSDimitry Andric if (opt.getGroup().getID() == OPT_grp_deprecated) { 7515ffd83dbSDimitry Andric warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:"); 7525ffd83dbSDimitry Andric warn(opt.getHelpText()); 7535ffd83dbSDimitry Andric } 7545ffd83dbSDimitry Andric } 7555ffd83dbSDimitry Andric 756fe6060f1SDimitry Andric static void warnIfUnimplementedOption(const Option &opt) { 757e8d8bef9SDimitry Andric if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden)) 7585ffd83dbSDimitry Andric return; 7595ffd83dbSDimitry Andric switch (opt.getGroup().getID()) { 7605ffd83dbSDimitry Andric case OPT_grp_deprecated: 7615ffd83dbSDimitry Andric // warn about deprecated options elsewhere 7625ffd83dbSDimitry Andric break; 7635ffd83dbSDimitry Andric case OPT_grp_undocumented: 7645ffd83dbSDimitry Andric warn("Option `" + opt.getPrefixedName() + 7655ffd83dbSDimitry Andric "' is undocumented. Should lld implement it?"); 7665ffd83dbSDimitry Andric break; 7675ffd83dbSDimitry Andric case OPT_grp_obsolete: 7685ffd83dbSDimitry Andric warn("Option `" + opt.getPrefixedName() + 7695ffd83dbSDimitry Andric "' is obsolete. Please modernize your usage."); 7705ffd83dbSDimitry Andric break; 7715ffd83dbSDimitry Andric case OPT_grp_ignored: 7725ffd83dbSDimitry Andric warn("Option `" + opt.getPrefixedName() + "' is ignored."); 7735ffd83dbSDimitry Andric break; 774349cc55cSDimitry Andric case OPT_grp_ignored_silently: 775349cc55cSDimitry Andric break; 7765ffd83dbSDimitry Andric default: 7775ffd83dbSDimitry Andric warn("Option `" + opt.getPrefixedName() + 7785ffd83dbSDimitry Andric "' is not yet implemented. Stay tuned..."); 7795ffd83dbSDimitry Andric break; 7805ffd83dbSDimitry Andric } 7815ffd83dbSDimitry Andric } 7825ffd83dbSDimitry Andric 783fe6060f1SDimitry Andric static const char *getReproduceOption(InputArgList &args) { 784fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_reproduce)) 785e8d8bef9SDimitry Andric return arg->getValue(); 786e8d8bef9SDimitry Andric return getenv("LLD_REPRODUCE"); 787e8d8bef9SDimitry Andric } 788e8d8bef9SDimitry Andric 789e8d8bef9SDimitry Andric static void parseClangOption(StringRef opt, const Twine &msg) { 790e8d8bef9SDimitry Andric std::string err; 791e8d8bef9SDimitry Andric raw_string_ostream os(err); 792e8d8bef9SDimitry Andric 793e8d8bef9SDimitry Andric const char *argv[] = {"lld", opt.data()}; 794e8d8bef9SDimitry Andric if (cl::ParseCommandLineOptions(2, argv, "", &os)) 795e8d8bef9SDimitry Andric return; 796e8d8bef9SDimitry Andric os.flush(); 797e8d8bef9SDimitry Andric error(msg + ": " + StringRef(err).trim()); 798e8d8bef9SDimitry Andric } 799e8d8bef9SDimitry Andric 800fe6060f1SDimitry Andric static uint32_t parseDylibVersion(const ArgList &args, unsigned id) { 801fe6060f1SDimitry Andric const Arg *arg = args.getLastArg(id); 802e8d8bef9SDimitry Andric if (!arg) 803e8d8bef9SDimitry Andric return 0; 804e8d8bef9SDimitry Andric 805e8d8bef9SDimitry Andric if (config->outputType != MH_DYLIB) { 806e8d8bef9SDimitry Andric error(arg->getAsString(args) + ": only valid with -dylib"); 807e8d8bef9SDimitry Andric return 0; 808e8d8bef9SDimitry Andric } 809e8d8bef9SDimitry Andric 810e8d8bef9SDimitry Andric PackedVersion version; 811e8d8bef9SDimitry Andric if (!version.parse32(arg->getValue())) { 812e8d8bef9SDimitry Andric error(arg->getAsString(args) + ": malformed version"); 813e8d8bef9SDimitry Andric return 0; 814e8d8bef9SDimitry Andric } 815e8d8bef9SDimitry Andric 816e8d8bef9SDimitry Andric return version.rawValue(); 817e8d8bef9SDimitry Andric } 818e8d8bef9SDimitry Andric 819fe6060f1SDimitry Andric static uint32_t parseProtection(StringRef protStr) { 820fe6060f1SDimitry Andric uint32_t prot = 0; 821fe6060f1SDimitry Andric for (char c : protStr) { 822fe6060f1SDimitry Andric switch (c) { 823fe6060f1SDimitry Andric case 'r': 824fe6060f1SDimitry Andric prot |= VM_PROT_READ; 825fe6060f1SDimitry Andric break; 826fe6060f1SDimitry Andric case 'w': 827fe6060f1SDimitry Andric prot |= VM_PROT_WRITE; 828fe6060f1SDimitry Andric break; 829fe6060f1SDimitry Andric case 'x': 830fe6060f1SDimitry Andric prot |= VM_PROT_EXECUTE; 831fe6060f1SDimitry Andric break; 832fe6060f1SDimitry Andric case '-': 833fe6060f1SDimitry Andric break; 834fe6060f1SDimitry Andric default: 835fe6060f1SDimitry Andric error("unknown -segprot letter '" + Twine(c) + "' in " + protStr); 836fe6060f1SDimitry Andric return 0; 837fe6060f1SDimitry Andric } 838fe6060f1SDimitry Andric } 839fe6060f1SDimitry Andric return prot; 840fe6060f1SDimitry Andric } 841fe6060f1SDimitry Andric 842fe6060f1SDimitry Andric static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) { 843fe6060f1SDimitry Andric std::vector<SectionAlign> sectAligns; 844fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_sectalign)) { 845fe6060f1SDimitry Andric StringRef segName = arg->getValue(0); 846fe6060f1SDimitry Andric StringRef sectName = arg->getValue(1); 847fe6060f1SDimitry Andric StringRef alignStr = arg->getValue(2); 848fe6060f1SDimitry Andric if (alignStr.startswith("0x") || alignStr.startswith("0X")) 849fe6060f1SDimitry Andric alignStr = alignStr.drop_front(2); 850fe6060f1SDimitry Andric uint32_t align; 851fe6060f1SDimitry Andric if (alignStr.getAsInteger(16, align)) { 852fe6060f1SDimitry Andric error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) + 853fe6060f1SDimitry Andric "' as number"); 854fe6060f1SDimitry Andric continue; 855fe6060f1SDimitry Andric } 856fe6060f1SDimitry Andric if (!isPowerOf2_32(align)) { 857fe6060f1SDimitry Andric error("-sectalign: '" + StringRef(arg->getValue(2)) + 858fe6060f1SDimitry Andric "' (in base 16) not a power of two"); 859fe6060f1SDimitry Andric continue; 860fe6060f1SDimitry Andric } 861fe6060f1SDimitry Andric sectAligns.push_back({segName, sectName, align}); 862fe6060f1SDimitry Andric } 863fe6060f1SDimitry Andric return sectAligns; 864fe6060f1SDimitry Andric } 865fe6060f1SDimitry Andric 86604eeddc0SDimitry Andric PlatformType macho::removeSimulator(PlatformType platform) { 867fe6060f1SDimitry Andric switch (platform) { 86804eeddc0SDimitry Andric case PLATFORM_IOSSIMULATOR: 86904eeddc0SDimitry Andric return PLATFORM_IOS; 87004eeddc0SDimitry Andric case PLATFORM_TVOSSIMULATOR: 87104eeddc0SDimitry Andric return PLATFORM_TVOS; 87204eeddc0SDimitry Andric case PLATFORM_WATCHOSSIMULATOR: 87304eeddc0SDimitry Andric return PLATFORM_WATCHOS; 874fe6060f1SDimitry Andric default: 875fe6060f1SDimitry Andric return platform; 876fe6060f1SDimitry Andric } 877fe6060f1SDimitry Andric } 878fe6060f1SDimitry Andric 879fe6060f1SDimitry Andric static bool dataConstDefault(const InputArgList &args) { 88004eeddc0SDimitry Andric static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = { 88104eeddc0SDimitry Andric {PLATFORM_MACOS, VersionTuple(10, 15)}, 88204eeddc0SDimitry Andric {PLATFORM_IOS, VersionTuple(13, 0)}, 88304eeddc0SDimitry Andric {PLATFORM_TVOS, VersionTuple(13, 0)}, 88404eeddc0SDimitry Andric {PLATFORM_WATCHOS, VersionTuple(6, 0)}, 88504eeddc0SDimitry Andric {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}}; 88604eeddc0SDimitry Andric PlatformType platform = removeSimulator(config->platformInfo.target.Platform); 887fe6060f1SDimitry Andric auto it = llvm::find_if(minVersion, 888fe6060f1SDimitry Andric [&](const auto &p) { return p.first == platform; }); 889fe6060f1SDimitry Andric if (it != minVersion.end()) 890fe6060f1SDimitry Andric if (config->platformInfo.minimum < it->second) 891fe6060f1SDimitry Andric return false; 892fe6060f1SDimitry Andric 893fe6060f1SDimitry Andric switch (config->outputType) { 894fe6060f1SDimitry Andric case MH_EXECUTE: 895fe6060f1SDimitry Andric return !args.hasArg(OPT_no_pie); 896fe6060f1SDimitry Andric case MH_BUNDLE: 897fe6060f1SDimitry Andric // FIXME: return false when -final_name ... 898fe6060f1SDimitry Andric // has prefix "/System/Library/UserEventPlugins/" 899fe6060f1SDimitry Andric // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd" 900fe6060f1SDimitry Andric return true; 901fe6060f1SDimitry Andric case MH_DYLIB: 902fe6060f1SDimitry Andric return true; 903fe6060f1SDimitry Andric case MH_OBJECT: 904fe6060f1SDimitry Andric return false; 905fe6060f1SDimitry Andric default: 906fe6060f1SDimitry Andric llvm_unreachable( 907fe6060f1SDimitry Andric "unsupported output type for determining data-const default"); 908fe6060f1SDimitry Andric } 909fe6060f1SDimitry Andric return false; 910fe6060f1SDimitry Andric } 911fe6060f1SDimitry Andric 912fe6060f1SDimitry Andric void SymbolPatterns::clear() { 913fe6060f1SDimitry Andric literals.clear(); 914fe6060f1SDimitry Andric globs.clear(); 915fe6060f1SDimitry Andric } 916fe6060f1SDimitry Andric 917fe6060f1SDimitry Andric void SymbolPatterns::insert(StringRef symbolName) { 918fe6060f1SDimitry Andric if (symbolName.find_first_of("*?[]") == StringRef::npos) 919fe6060f1SDimitry Andric literals.insert(CachedHashStringRef(symbolName)); 920fe6060f1SDimitry Andric else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName)) 921fe6060f1SDimitry Andric globs.emplace_back(*pattern); 922fe6060f1SDimitry Andric else 923fe6060f1SDimitry Andric error("invalid symbol-name pattern: " + symbolName); 924fe6060f1SDimitry Andric } 925fe6060f1SDimitry Andric 926fe6060f1SDimitry Andric bool SymbolPatterns::matchLiteral(StringRef symbolName) const { 927fe6060f1SDimitry Andric return literals.contains(CachedHashStringRef(symbolName)); 928fe6060f1SDimitry Andric } 929fe6060f1SDimitry Andric 930fe6060f1SDimitry Andric bool SymbolPatterns::matchGlob(StringRef symbolName) const { 931fe6060f1SDimitry Andric for (const GlobPattern &glob : globs) 932fe6060f1SDimitry Andric if (glob.match(symbolName)) 933fe6060f1SDimitry Andric return true; 934fe6060f1SDimitry Andric return false; 935fe6060f1SDimitry Andric } 936fe6060f1SDimitry Andric 937fe6060f1SDimitry Andric bool SymbolPatterns::match(StringRef symbolName) const { 938fe6060f1SDimitry Andric return matchLiteral(symbolName) || matchGlob(symbolName); 939fe6060f1SDimitry Andric } 940fe6060f1SDimitry Andric 941*81ad6265SDimitry Andric static void parseSymbolPatternsFile(const Arg *arg, 942*81ad6265SDimitry Andric SymbolPatterns &symbolPatterns) { 943fe6060f1SDimitry Andric StringRef path = arg->getValue(); 944fe6060f1SDimitry Andric Optional<MemoryBufferRef> buffer = readFile(path); 945fe6060f1SDimitry Andric if (!buffer) { 946fe6060f1SDimitry Andric error("Could not read symbol file: " + path); 947*81ad6265SDimitry Andric return; 948fe6060f1SDimitry Andric } 949fe6060f1SDimitry Andric MemoryBufferRef mbref = *buffer; 950fe6060f1SDimitry Andric for (StringRef line : args::getLines(mbref)) { 951fe6060f1SDimitry Andric line = line.take_until([](char c) { return c == '#'; }).trim(); 952fe6060f1SDimitry Andric if (!line.empty()) 953fe6060f1SDimitry Andric symbolPatterns.insert(line); 954fe6060f1SDimitry Andric } 955fe6060f1SDimitry Andric } 956*81ad6265SDimitry Andric 957*81ad6265SDimitry Andric static void handleSymbolPatterns(InputArgList &args, 958*81ad6265SDimitry Andric SymbolPatterns &symbolPatterns, 959*81ad6265SDimitry Andric unsigned singleOptionCode, 960*81ad6265SDimitry Andric unsigned listFileOptionCode) { 961*81ad6265SDimitry Andric for (const Arg *arg : args.filtered(singleOptionCode)) 962*81ad6265SDimitry Andric symbolPatterns.insert(arg->getValue()); 963*81ad6265SDimitry Andric for (const Arg *arg : args.filtered(listFileOptionCode)) 964*81ad6265SDimitry Andric parseSymbolPatternsFile(arg, symbolPatterns); 965fe6060f1SDimitry Andric } 966fe6060f1SDimitry Andric 967349cc55cSDimitry Andric static void createFiles(const InputArgList &args) { 968fe6060f1SDimitry Andric TimeTraceScope timeScope("Load input files"); 969fe6060f1SDimitry Andric // This loop should be reserved for options whose exact ordering matters. 970fe6060f1SDimitry Andric // Other options should be handled via filtered() and/or getLastArg(). 97104eeddc0SDimitry Andric bool isLazy = false; 972fe6060f1SDimitry Andric for (const Arg *arg : args) { 973fe6060f1SDimitry Andric const Option &opt = arg->getOption(); 974fe6060f1SDimitry Andric warnIfDeprecatedOption(opt); 975fe6060f1SDimitry Andric warnIfUnimplementedOption(opt); 976fe6060f1SDimitry Andric 977fe6060f1SDimitry Andric switch (opt.getID()) { 978fe6060f1SDimitry Andric case OPT_INPUT: 97904eeddc0SDimitry Andric addFile(rerootPath(arg->getValue()), ForceLoad::Default, isLazy); 980fe6060f1SDimitry Andric break; 981fe6060f1SDimitry Andric case OPT_needed_library: 982fe6060f1SDimitry Andric if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 983349cc55cSDimitry Andric addFile(rerootPath(arg->getValue()), ForceLoad::Default))) 984fe6060f1SDimitry Andric dylibFile->forceNeeded = true; 985fe6060f1SDimitry Andric break; 986fe6060f1SDimitry Andric case OPT_reexport_library: 987349cc55cSDimitry Andric if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 988349cc55cSDimitry Andric addFile(rerootPath(arg->getValue()), ForceLoad::Default))) { 989fe6060f1SDimitry Andric config->hasReexports = true; 990fe6060f1SDimitry Andric dylibFile->reexport = true; 991fe6060f1SDimitry Andric } 992fe6060f1SDimitry Andric break; 993fe6060f1SDimitry Andric case OPT_weak_library: 994fe6060f1SDimitry Andric if (auto *dylibFile = dyn_cast_or_null<DylibFile>( 995349cc55cSDimitry Andric addFile(rerootPath(arg->getValue()), ForceLoad::Default))) 996fe6060f1SDimitry Andric dylibFile->forceWeakImport = true; 997fe6060f1SDimitry Andric break; 998fe6060f1SDimitry Andric case OPT_filelist: 99904eeddc0SDimitry Andric addFileList(arg->getValue(), isLazy); 1000fe6060f1SDimitry Andric break; 1001fe6060f1SDimitry Andric case OPT_force_load: 1002349cc55cSDimitry Andric addFile(rerootPath(arg->getValue()), ForceLoad::Yes); 1003fe6060f1SDimitry Andric break; 1004fe6060f1SDimitry Andric case OPT_l: 1005fe6060f1SDimitry Andric case OPT_needed_l: 1006fe6060f1SDimitry Andric case OPT_reexport_l: 1007fe6060f1SDimitry Andric case OPT_weak_l: 1008fe6060f1SDimitry Andric addLibrary(arg->getValue(), opt.getID() == OPT_needed_l, 1009fe6060f1SDimitry Andric opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l, 1010349cc55cSDimitry Andric /*isExplicit=*/true, ForceLoad::Default); 1011fe6060f1SDimitry Andric break; 1012fe6060f1SDimitry Andric case OPT_framework: 1013fe6060f1SDimitry Andric case OPT_needed_framework: 1014fe6060f1SDimitry Andric case OPT_reexport_framework: 1015fe6060f1SDimitry Andric case OPT_weak_framework: 1016fe6060f1SDimitry Andric addFramework(arg->getValue(), opt.getID() == OPT_needed_framework, 1017fe6060f1SDimitry Andric opt.getID() == OPT_weak_framework, 1018349cc55cSDimitry Andric opt.getID() == OPT_reexport_framework, /*isExplicit=*/true, 1019349cc55cSDimitry Andric ForceLoad::Default); 1020fe6060f1SDimitry Andric break; 102104eeddc0SDimitry Andric case OPT_start_lib: 102204eeddc0SDimitry Andric if (isLazy) 102304eeddc0SDimitry Andric error("nested --start-lib"); 102404eeddc0SDimitry Andric isLazy = true; 102504eeddc0SDimitry Andric break; 102604eeddc0SDimitry Andric case OPT_end_lib: 102704eeddc0SDimitry Andric if (!isLazy) 102804eeddc0SDimitry Andric error("stray --end-lib"); 102904eeddc0SDimitry Andric isLazy = false; 103004eeddc0SDimitry Andric break; 1031fe6060f1SDimitry Andric default: 1032fe6060f1SDimitry Andric break; 1033fe6060f1SDimitry Andric } 1034fe6060f1SDimitry Andric } 1035fe6060f1SDimitry Andric } 1036fe6060f1SDimitry Andric 1037fe6060f1SDimitry Andric static void gatherInputSections() { 1038fe6060f1SDimitry Andric TimeTraceScope timeScope("Gathering input sections"); 1039fe6060f1SDimitry Andric int inputOrder = 0; 1040fe6060f1SDimitry Andric for (const InputFile *file : inputFiles) { 1041*81ad6265SDimitry Andric for (const Section *section : file->sections) { 1042*81ad6265SDimitry Andric // Compact unwind entries require special handling elsewhere. (In 1043*81ad6265SDimitry Andric // contrast, EH frames are handled like regular ConcatInputSections.) 1044*81ad6265SDimitry Andric if (section->name == section_names::compactUnwind) 1045349cc55cSDimitry Andric continue; 1046fe6060f1SDimitry Andric ConcatOutputSection *osec = nullptr; 1047*81ad6265SDimitry Andric for (const Subsection &subsection : section->subsections) { 1048349cc55cSDimitry Andric if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) { 1049fe6060f1SDimitry Andric if (isec->isCoalescedWeak()) 1050fe6060f1SDimitry Andric continue; 1051fe6060f1SDimitry Andric isec->outSecOff = inputOrder++; 1052fe6060f1SDimitry Andric if (!osec) 1053fe6060f1SDimitry Andric osec = ConcatOutputSection::getOrCreateForInput(isec); 1054fe6060f1SDimitry Andric isec->parent = osec; 1055fe6060f1SDimitry Andric inputSections.push_back(isec); 1056349cc55cSDimitry Andric } else if (auto *isec = 1057349cc55cSDimitry Andric dyn_cast<CStringInputSection>(subsection.isec)) { 1058fe6060f1SDimitry Andric if (in.cStringSection->inputOrder == UnspecifiedInputOrder) 1059fe6060f1SDimitry Andric in.cStringSection->inputOrder = inputOrder++; 1060fe6060f1SDimitry Andric in.cStringSection->addInput(isec); 1061349cc55cSDimitry Andric } else if (auto *isec = 1062349cc55cSDimitry Andric dyn_cast<WordLiteralInputSection>(subsection.isec)) { 1063fe6060f1SDimitry Andric if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder) 1064fe6060f1SDimitry Andric in.wordLiteralSection->inputOrder = inputOrder++; 1065fe6060f1SDimitry Andric in.wordLiteralSection->addInput(isec); 1066fe6060f1SDimitry Andric } else { 1067fe6060f1SDimitry Andric llvm_unreachable("unexpected input section kind"); 1068fe6060f1SDimitry Andric } 1069fe6060f1SDimitry Andric } 1070fe6060f1SDimitry Andric } 1071fe6060f1SDimitry Andric } 1072fe6060f1SDimitry Andric assert(inputOrder <= UnspecifiedInputOrder); 1073fe6060f1SDimitry Andric } 1074fe6060f1SDimitry Andric 1075fe6060f1SDimitry Andric static void foldIdenticalLiterals() { 1076*81ad6265SDimitry Andric TimeTraceScope timeScope("Fold identical literals"); 1077fe6060f1SDimitry Andric // We always create a cStringSection, regardless of whether dedupLiterals is 1078fe6060f1SDimitry Andric // true. If it isn't, we simply create a non-deduplicating CStringSection. 1079fe6060f1SDimitry Andric // Either way, we must unconditionally finalize it here. 1080fe6060f1SDimitry Andric in.cStringSection->finalizeContents(); 1081fe6060f1SDimitry Andric if (in.wordLiteralSection) 1082fe6060f1SDimitry Andric in.wordLiteralSection->finalizeContents(); 1083fe6060f1SDimitry Andric } 1084fe6060f1SDimitry Andric 1085fe6060f1SDimitry Andric static void referenceStubBinder() { 1086fe6060f1SDimitry Andric bool needsStubHelper = config->outputType == MH_DYLIB || 1087fe6060f1SDimitry Andric config->outputType == MH_EXECUTE || 1088fe6060f1SDimitry Andric config->outputType == MH_BUNDLE; 1089fe6060f1SDimitry Andric if (!needsStubHelper || !symtab->find("dyld_stub_binder")) 1090fe6060f1SDimitry Andric return; 1091fe6060f1SDimitry Andric 1092fe6060f1SDimitry Andric // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here 1093fe6060f1SDimitry Andric // adds a opportunistic reference to dyld_stub_binder if it happens to exist. 1094fe6060f1SDimitry Andric // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This 1095fe6060f1SDimitry Andric // isn't needed for correctness, but the presence of that symbol suppresses 1096fe6060f1SDimitry Andric // "no symbols" diagnostics from `nm`. 1097fe6060f1SDimitry Andric // StubHelperSection::setup() adds a reference and errors out if 1098fe6060f1SDimitry Andric // dyld_stub_binder doesn't exist in case it is actually needed. 1099fe6060f1SDimitry Andric symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false); 1100fe6060f1SDimitry Andric } 1101fe6060f1SDimitry Andric 110204eeddc0SDimitry Andric bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS, 110304eeddc0SDimitry Andric llvm::raw_ostream &stderrOS, bool exitEarly, 110404eeddc0SDimitry Andric bool disableOutput) { 110504eeddc0SDimitry Andric // This driver-specific context will be freed later by lldMain(). 110604eeddc0SDimitry Andric auto *ctx = new CommonLinkerContext; 11075ffd83dbSDimitry Andric 110804eeddc0SDimitry Andric ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput); 110904eeddc0SDimitry Andric ctx->e.cleanupCallback = []() { 1110349cc55cSDimitry Andric resolvedFrameworks.clear(); 1111349cc55cSDimitry Andric resolvedLibraries.clear(); 1112349cc55cSDimitry Andric cachedReads.clear(); 1113349cc55cSDimitry Andric concatOutputSections.clear(); 1114349cc55cSDimitry Andric inputFiles.clear(); 1115349cc55cSDimitry Andric inputSections.clear(); 1116349cc55cSDimitry Andric loadedArchives.clear(); 1117*81ad6265SDimitry Andric loadedObjectFrameworks.clear(); 1118349cc55cSDimitry Andric syntheticSections.clear(); 1119349cc55cSDimitry Andric thunkMap.clear(); 1120349cc55cSDimitry Andric 1121349cc55cSDimitry Andric firstTLVDataSection = nullptr; 1122349cc55cSDimitry Andric tar = nullptr; 1123349cc55cSDimitry Andric memset(&in, 0, sizeof(in)); 1124349cc55cSDimitry Andric 1125349cc55cSDimitry Andric resetLoadedDylibs(); 1126349cc55cSDimitry Andric resetOutputSegments(); 1127349cc55cSDimitry Andric resetWriter(); 1128349cc55cSDimitry Andric InputFile::resetIdCount(); 1129349cc55cSDimitry Andric }; 1130e8d8bef9SDimitry Andric 113104eeddc0SDimitry Andric ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]); 1132fe6060f1SDimitry Andric 11335ffd83dbSDimitry Andric MachOOptTable parser; 1134fe6060f1SDimitry Andric InputArgList args = parser.parse(argsArr.slice(1)); 1135fe6060f1SDimitry Andric 113604eeddc0SDimitry Andric ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now " 1137fe6060f1SDimitry Andric "(use --error-limit=0 to see all errors)"; 113804eeddc0SDimitry Andric ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20); 113904eeddc0SDimitry Andric ctx->e.verbose = args.hasArg(OPT_verbose); 11405ffd83dbSDimitry Andric 11415ffd83dbSDimitry Andric if (args.hasArg(OPT_help_hidden)) { 11425ffd83dbSDimitry Andric parser.printHelp(argsArr[0], /*showHidden=*/true); 11435ffd83dbSDimitry Andric return true; 1144e8d8bef9SDimitry Andric } 1145e8d8bef9SDimitry Andric if (args.hasArg(OPT_help)) { 11465ffd83dbSDimitry Andric parser.printHelp(argsArr[0], /*showHidden=*/false); 11475ffd83dbSDimitry Andric return true; 11485ffd83dbSDimitry Andric } 1149e8d8bef9SDimitry Andric if (args.hasArg(OPT_version)) { 1150e8d8bef9SDimitry Andric message(getLLDVersion()); 1151e8d8bef9SDimitry Andric return true; 1152e8d8bef9SDimitry Andric } 1153e8d8bef9SDimitry Andric 115404eeddc0SDimitry Andric config = std::make_unique<Configuration>(); 115504eeddc0SDimitry Andric symtab = std::make_unique<SymbolTable>(); 1156*81ad6265SDimitry Andric config->outputType = getOutputType(args); 1157fe6060f1SDimitry Andric target = createTargetInfo(args); 115804eeddc0SDimitry Andric depTracker = std::make_unique<DependencyTracker>( 115904eeddc0SDimitry Andric args.getLastArgValue(OPT_dependency_info)); 1160349cc55cSDimitry Andric if (errorCount()) 1161349cc55cSDimitry Andric return false; 1162349cc55cSDimitry Andric 1163*81ad6265SDimitry Andric if (args.hasArg(OPT_pagezero_size)) { 1164*81ad6265SDimitry Andric uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0); 1165*81ad6265SDimitry Andric 1166*81ad6265SDimitry Andric // ld64 does something really weird. It attempts to realign the value to the 1167*81ad6265SDimitry Andric // page size, but assumes the the page size is 4K. This doesn't work with 1168*81ad6265SDimitry Andric // most of Apple's ARM64 devices, which use a page size of 16K. This means 1169*81ad6265SDimitry Andric // that it will first 4K align it by rounding down, then round up to 16K. 1170*81ad6265SDimitry Andric // This probably only happened because no one using this arg with anything 1171*81ad6265SDimitry Andric // other then 0, so no one checked if it did what is what it says it does. 1172*81ad6265SDimitry Andric 1173*81ad6265SDimitry Andric // So we are not copying this weird behavior and doing the it in a logical 1174*81ad6265SDimitry Andric // way, by always rounding down to page size. 1175*81ad6265SDimitry Andric if (!isAligned(Align(target->getPageSize()), pagezeroSize)) { 1176*81ad6265SDimitry Andric pagezeroSize -= pagezeroSize % target->getPageSize(); 1177*81ad6265SDimitry Andric warn("__PAGEZERO size is not page aligned, rounding down to 0x" + 1178*81ad6265SDimitry Andric Twine::utohexstr(pagezeroSize)); 1179*81ad6265SDimitry Andric } 1180*81ad6265SDimitry Andric 1181*81ad6265SDimitry Andric target->pageZeroSize = pagezeroSize; 1182*81ad6265SDimitry Andric } 1183*81ad6265SDimitry Andric 1184349cc55cSDimitry Andric config->osoPrefix = args.getLastArgValue(OPT_oso_prefix); 1185349cc55cSDimitry Andric if (!config->osoPrefix.empty()) { 1186349cc55cSDimitry Andric // Expand special characters, such as ".", "..", or "~", if present. 1187349cc55cSDimitry Andric // Note: LD64 only expands "." and not other special characters. 1188349cc55cSDimitry Andric // That seems silly to imitate so we will not try to follow it, but rather 1189349cc55cSDimitry Andric // just use real_path() to do it. 1190349cc55cSDimitry Andric 1191349cc55cSDimitry Andric // The max path length is 4096, in theory. However that seems quite long 1192349cc55cSDimitry Andric // and seems unlikely that any one would want to strip everything from the 1193349cc55cSDimitry Andric // path. Hence we've picked a reasonably large number here. 1194349cc55cSDimitry Andric SmallString<1024> expanded; 1195349cc55cSDimitry Andric if (!fs::real_path(config->osoPrefix, expanded, 1196349cc55cSDimitry Andric /*expand_tilde=*/true)) { 1197349cc55cSDimitry Andric // Note: LD64 expands "." to be `<current_dir>/` 1198349cc55cSDimitry Andric // (ie., it has a slash suffix) whereas real_path() doesn't. 1199349cc55cSDimitry Andric // So we have to append '/' to be consistent. 1200349cc55cSDimitry Andric StringRef sep = sys::path::get_separator(); 1201349cc55cSDimitry Andric // real_path removes trailing slashes as part of the normalization, but 1202349cc55cSDimitry Andric // these are meaningful for our text based stripping 1203349cc55cSDimitry Andric if (config->osoPrefix.equals(".") || config->osoPrefix.endswith(sep)) 1204349cc55cSDimitry Andric expanded += sep; 120504eeddc0SDimitry Andric config->osoPrefix = saver().save(expanded.str()); 1206349cc55cSDimitry Andric } 1207349cc55cSDimitry Andric } 1208fe6060f1SDimitry Andric 1209fe6060f1SDimitry Andric // Must be set before any InputSections and Symbols are created. 1210fe6060f1SDimitry Andric config->deadStrip = args.hasArg(OPT_dead_strip); 1211fe6060f1SDimitry Andric 1212fe6060f1SDimitry Andric config->systemLibraryRoots = getSystemLibraryRoots(args); 1213e8d8bef9SDimitry Andric if (const char *path = getReproduceOption(args)) { 1214e8d8bef9SDimitry Andric // Note that --reproduce is a debug option so you can ignore it 1215e8d8bef9SDimitry Andric // if you are trying to understand the whole picture of the code. 1216e8d8bef9SDimitry Andric Expected<std::unique_ptr<TarWriter>> errOrWriter = 1217e8d8bef9SDimitry Andric TarWriter::create(path, path::stem(path)); 1218e8d8bef9SDimitry Andric if (errOrWriter) { 1219e8d8bef9SDimitry Andric tar = std::move(*errOrWriter); 1220e8d8bef9SDimitry Andric tar->append("response.txt", createResponseFile(args)); 1221e8d8bef9SDimitry Andric tar->append("version.txt", getLLDVersion() + "\n"); 1222e8d8bef9SDimitry Andric } else { 1223e8d8bef9SDimitry Andric error("--reproduce: " + toString(errOrWriter.takeError())); 1224e8d8bef9SDimitry Andric } 1225e8d8bef9SDimitry Andric } 12265ffd83dbSDimitry Andric 1227fe6060f1SDimitry Andric if (auto *arg = args.getLastArg(OPT_threads_eq)) { 1228fe6060f1SDimitry Andric StringRef v(arg->getValue()); 1229fe6060f1SDimitry Andric unsigned threads = 0; 1230fe6060f1SDimitry Andric if (!llvm::to_integer(v, threads, 0) || threads == 0) 1231fe6060f1SDimitry Andric error(arg->getSpelling() + ": expected a positive integer, but got '" + 1232fe6060f1SDimitry Andric arg->getValue() + "'"); 1233fe6060f1SDimitry Andric parallel::strategy = hardware_concurrency(threads); 1234fe6060f1SDimitry Andric config->thinLTOJobs = v; 1235fe6060f1SDimitry Andric } 1236fe6060f1SDimitry Andric if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq)) 1237fe6060f1SDimitry Andric config->thinLTOJobs = arg->getValue(); 1238fe6060f1SDimitry Andric if (!get_threadpool_strategy(config->thinLTOJobs)) 1239fe6060f1SDimitry Andric error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs); 12405ffd83dbSDimitry Andric 1241fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_u)) { 1242fe6060f1SDimitry Andric config->explicitUndefineds.push_back(symtab->addUndefined( 1243fe6060f1SDimitry Andric arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false)); 1244fe6060f1SDimitry Andric } 1245fe6060f1SDimitry Andric 1246fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_U)) 1247fe6060f1SDimitry Andric config->explicitDynamicLookups.insert(arg->getValue()); 1248fe6060f1SDimitry Andric 1249fe6060f1SDimitry Andric config->mapFile = args.getLastArgValue(OPT_map); 1250fe6060f1SDimitry Andric config->optimize = args::getInteger(args, OPT_O, 1); 12515ffd83dbSDimitry Andric config->outputFile = args.getLastArgValue(OPT_o, "a.out"); 1252fe6060f1SDimitry Andric config->finalOutput = 1253fe6060f1SDimitry Andric args.getLastArgValue(OPT_final_output, config->outputFile); 1254fe6060f1SDimitry Andric config->astPaths = args.getAllArgValues(OPT_add_ast_path); 1255e8d8bef9SDimitry Andric config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32); 1256e8d8bef9SDimitry Andric config->headerPadMaxInstallNames = 1257e8d8bef9SDimitry Andric args.hasArg(OPT_headerpad_max_install_names); 1258fe6060f1SDimitry Andric config->printDylibSearch = 1259fe6060f1SDimitry Andric args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING"); 1260e8d8bef9SDimitry Andric config->printEachFile = args.hasArg(OPT_t); 1261e8d8bef9SDimitry Andric config->printWhyLoad = args.hasArg(OPT_why_load); 1262349cc55cSDimitry Andric config->omitDebugInfo = args.hasArg(OPT_S); 1263349cc55cSDimitry Andric config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal); 1264fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) { 1265fe6060f1SDimitry Andric if (config->outputType != MH_BUNDLE) 1266fe6060f1SDimitry Andric error("-bundle_loader can only be used with MachO bundle output"); 126704eeddc0SDimitry Andric addFile(arg->getValue(), ForceLoad::Default, /*isLazy=*/false, 126804eeddc0SDimitry Andric /*isExplicit=*/false, 1269fe6060f1SDimitry Andric /*isBundleLoader=*/true); 1270fe6060f1SDimitry Andric } 1271fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_umbrella)) { 1272fe6060f1SDimitry Andric if (config->outputType != MH_DYLIB) 1273fe6060f1SDimitry Andric warn("-umbrella used, but not creating dylib"); 1274fe6060f1SDimitry Andric config->umbrella = arg->getValue(); 1275fe6060f1SDimitry Andric } 1276e8d8bef9SDimitry Andric config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto); 1277fe6060f1SDimitry Andric config->ltoo = args::getInteger(args, OPT_lto_O, 2); 1278fe6060f1SDimitry Andric if (config->ltoo > 3) 1279fe6060f1SDimitry Andric error("--lto-O: invalid optimization level: " + Twine(config->ltoo)); 1280fe6060f1SDimitry Andric config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto); 1281fe6060f1SDimitry Andric config->thinLTOCachePolicy = getLTOCachePolicy(args); 1282e8d8bef9SDimitry Andric config->runtimePaths = args::getStrings(args, OPT_rpath); 128304eeddc0SDimitry Andric config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false); 1284fe6060f1SDimitry Andric config->archMultiple = args.hasArg(OPT_arch_multiple); 1285fe6060f1SDimitry Andric config->applicationExtension = args.hasFlag( 1286fe6060f1SDimitry Andric OPT_application_extension, OPT_no_application_extension, false); 1287fe6060f1SDimitry Andric config->exportDynamic = args.hasArg(OPT_export_dynamic); 1288e8d8bef9SDimitry Andric config->forceLoadObjC = args.hasArg(OPT_ObjC); 1289fe6060f1SDimitry Andric config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs); 1290fe6060f1SDimitry Andric config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs); 1291e8d8bef9SDimitry Andric config->demangle = args.hasArg(OPT_demangle); 1292e8d8bef9SDimitry Andric config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs); 1293fe6060f1SDimitry Andric config->emitFunctionStarts = 1294fe6060f1SDimitry Andric args.hasFlag(OPT_function_starts, OPT_no_function_starts, true); 1295fe6060f1SDimitry Andric config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle); 1296fe6060f1SDimitry Andric config->emitDataInCodeInfo = 1297fe6060f1SDimitry Andric args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true); 1298fe6060f1SDimitry Andric config->icfLevel = getICFLevel(args); 129904eeddc0SDimitry Andric config->dedupLiterals = 130004eeddc0SDimitry Andric args.hasFlag(OPT_deduplicate_literals, OPT_icf_eq, false) || 1301fe6060f1SDimitry Andric config->icfLevel != ICFLevel::none; 1302349cc55cSDimitry Andric config->warnDylibInstallName = args.hasFlag( 1303349cc55cSDimitry Andric OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false); 1304*81ad6265SDimitry Andric config->ignoreOptimizationHints = args.hasArg(OPT_ignore_optimization_hints); 130504eeddc0SDimitry Andric config->callGraphProfileSort = args.hasFlag( 130604eeddc0SDimitry Andric OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true); 130704eeddc0SDimitry Andric config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order); 1308*81ad6265SDimitry Andric config->parseEhFrames = static_cast<bool>(getenv("LLD_IN_TEST")); 1309e8d8bef9SDimitry Andric 1310fe6060f1SDimitry Andric // FIXME: Add a commandline flag for this too. 1311fe6060f1SDimitry Andric config->zeroModTime = getenv("ZERO_AR_DATE"); 1312fe6060f1SDimitry Andric 131304eeddc0SDimitry Andric std::array<PlatformType, 3> encryptablePlatforms{ 131404eeddc0SDimitry Andric PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS}; 1315fe6060f1SDimitry Andric config->emitEncryptionInfo = 1316fe6060f1SDimitry Andric args.hasFlag(OPT_encryptable, OPT_no_encryption, 1317fe6060f1SDimitry Andric is_contained(encryptablePlatforms, config->platform())); 1318fe6060f1SDimitry Andric 1319fe6060f1SDimitry Andric #ifndef LLVM_HAVE_LIBXAR 1320fe6060f1SDimitry Andric if (config->emitBitcodeBundle) 1321fe6060f1SDimitry Andric error("-bitcode_bundle unsupported because LLD wasn't built with libxar"); 1322fe6060f1SDimitry Andric #endif 1323fe6060f1SDimitry Andric 1324fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_install_name)) { 1325349cc55cSDimitry Andric if (config->warnDylibInstallName && config->outputType != MH_DYLIB) 1326349cc55cSDimitry Andric warn( 1327349cc55cSDimitry Andric arg->getAsString(args) + 1328349cc55cSDimitry Andric ": ignored, only has effect with -dylib [--warn-dylib-install-name]"); 1329fe6060f1SDimitry Andric else 1330fe6060f1SDimitry Andric config->installName = arg->getValue(); 1331fe6060f1SDimitry Andric } else if (config->outputType == MH_DYLIB) { 1332fe6060f1SDimitry Andric config->installName = config->finalOutput; 1333fe6060f1SDimitry Andric } 1334fe6060f1SDimitry Andric 1335fe6060f1SDimitry Andric if (args.hasArg(OPT_mark_dead_strippable_dylib)) { 1336fe6060f1SDimitry Andric if (config->outputType != MH_DYLIB) 1337fe6060f1SDimitry Andric warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib"); 1338fe6060f1SDimitry Andric else 1339fe6060f1SDimitry Andric config->markDeadStrippableDylib = true; 1340fe6060f1SDimitry Andric } 1341fe6060f1SDimitry Andric 1342fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic)) 1343e8d8bef9SDimitry Andric config->staticLink = (arg->getOption().getID() == OPT_static); 1344e8d8bef9SDimitry Andric 1345fe6060f1SDimitry Andric if (const Arg *arg = 1346fe6060f1SDimitry Andric args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) 1347fe6060f1SDimitry Andric config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace 1348fe6060f1SDimitry Andric ? NamespaceKind::twolevel 1349fe6060f1SDimitry Andric : NamespaceKind::flat; 1350fe6060f1SDimitry Andric 1351fe6060f1SDimitry Andric config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args); 1352fe6060f1SDimitry Andric 1353fe6060f1SDimitry Andric if (config->outputType == MH_EXECUTE) 1354fe6060f1SDimitry Andric config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"), 1355fe6060f1SDimitry Andric /*file=*/nullptr, 1356fe6060f1SDimitry Andric /*isWeakRef=*/false); 1357fe6060f1SDimitry Andric 1358e8d8bef9SDimitry Andric config->librarySearchPaths = 1359e8d8bef9SDimitry Andric getLibrarySearchPaths(args, config->systemLibraryRoots); 1360e8d8bef9SDimitry Andric config->frameworkSearchPaths = 1361e8d8bef9SDimitry Andric getFrameworkSearchPaths(args, config->systemLibraryRoots); 1362fe6060f1SDimitry Andric if (const Arg *arg = 1363e8d8bef9SDimitry Andric args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first)) 1364e8d8bef9SDimitry Andric config->searchDylibsFirst = 1365e8d8bef9SDimitry Andric arg->getOption().getID() == OPT_search_dylibs_first; 1366e8d8bef9SDimitry Andric 1367e8d8bef9SDimitry Andric config->dylibCompatibilityVersion = 1368e8d8bef9SDimitry Andric parseDylibVersion(args, OPT_compatibility_version); 1369e8d8bef9SDimitry Andric config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version); 1370e8d8bef9SDimitry Andric 1371fe6060f1SDimitry Andric config->dataConst = 1372fe6060f1SDimitry Andric args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args)); 1373fe6060f1SDimitry Andric // Populate config->sectionRenameMap with builtin default renames. 1374fe6060f1SDimitry Andric // Options -rename_section and -rename_segment are able to override. 1375fe6060f1SDimitry Andric initializeSectionRenameMap(); 1376fe6060f1SDimitry Andric // Reject every special character except '.' and '$' 1377fe6060f1SDimitry Andric // TODO(gkm): verify that this is the proper set of invalid chars 1378fe6060f1SDimitry Andric StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~"); 1379fe6060f1SDimitry Andric auto validName = [invalidNameChars](StringRef s) { 1380fe6060f1SDimitry Andric if (s.find_first_of(invalidNameChars) != StringRef::npos) 1381fe6060f1SDimitry Andric error("invalid name for segment or section: " + s); 1382fe6060f1SDimitry Andric return s; 1383fe6060f1SDimitry Andric }; 1384fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_rename_section)) { 1385fe6060f1SDimitry Andric config->sectionRenameMap[{validName(arg->getValue(0)), 1386fe6060f1SDimitry Andric validName(arg->getValue(1))}] = { 1387fe6060f1SDimitry Andric validName(arg->getValue(2)), validName(arg->getValue(3))}; 1388fe6060f1SDimitry Andric } 1389fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_rename_segment)) { 1390fe6060f1SDimitry Andric config->segmentRenameMap[validName(arg->getValue(0))] = 1391fe6060f1SDimitry Andric validName(arg->getValue(1)); 1392fe6060f1SDimitry Andric } 1393fe6060f1SDimitry Andric 1394fe6060f1SDimitry Andric config->sectionAlignments = parseSectAlign(args); 1395fe6060f1SDimitry Andric 1396fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_segprot)) { 1397fe6060f1SDimitry Andric StringRef segName = arg->getValue(0); 1398fe6060f1SDimitry Andric uint32_t maxProt = parseProtection(arg->getValue(1)); 1399fe6060f1SDimitry Andric uint32_t initProt = parseProtection(arg->getValue(2)); 1400fe6060f1SDimitry Andric if (maxProt != initProt && config->arch() != AK_i386) 1401fe6060f1SDimitry Andric error("invalid argument '" + arg->getAsString(args) + 1402fe6060f1SDimitry Andric "': max and init must be the same for non-i386 archs"); 1403fe6060f1SDimitry Andric if (segName == segment_names::linkEdit) 1404fe6060f1SDimitry Andric error("-segprot cannot be used to change __LINKEDIT's protections"); 1405fe6060f1SDimitry Andric config->segmentProtections.push_back({segName, maxProt, initProt}); 1406fe6060f1SDimitry Andric } 1407fe6060f1SDimitry Andric 1408*81ad6265SDimitry Andric config->hasExplicitExports = 1409*81ad6265SDimitry Andric args.hasArg(OPT_no_exported_symbols) || 1410*81ad6265SDimitry Andric args.hasArgNoClaim(OPT_exported_symbol, OPT_exported_symbols_list); 1411fe6060f1SDimitry Andric handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol, 1412fe6060f1SDimitry Andric OPT_exported_symbols_list); 1413fe6060f1SDimitry Andric handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol, 1414fe6060f1SDimitry Andric OPT_unexported_symbols_list); 1415*81ad6265SDimitry Andric if (config->hasExplicitExports && !config->unexportedSymbols.empty()) 1416*81ad6265SDimitry Andric error("cannot use both -exported_symbol* and -unexported_symbol* options"); 1417*81ad6265SDimitry Andric 1418*81ad6265SDimitry Andric if (args.hasArg(OPT_no_exported_symbols) && !config->exportedSymbols.empty()) 1419*81ad6265SDimitry Andric error("cannot use both -exported_symbol* and -no_exported_symbols options"); 1420*81ad6265SDimitry Andric 1421*81ad6265SDimitry Andric // Imitating LD64's: 1422*81ad6265SDimitry Andric // -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't 1423*81ad6265SDimitry Andric // both be present. 1424*81ad6265SDimitry Andric // But -x can be used with either of these two, in which case, the last arg 1425*81ad6265SDimitry Andric // takes effect. 1426*81ad6265SDimitry Andric // (TODO: This is kind of confusing - considering disallowing using them 1427*81ad6265SDimitry Andric // together for a more straightforward behaviour) 1428*81ad6265SDimitry Andric { 1429*81ad6265SDimitry Andric bool includeLocal = false; 1430*81ad6265SDimitry Andric bool excludeLocal = false; 1431*81ad6265SDimitry Andric for (const Arg *arg : 1432*81ad6265SDimitry Andric args.filtered(OPT_x, OPT_non_global_symbols_no_strip_list, 1433*81ad6265SDimitry Andric OPT_non_global_symbols_strip_list)) { 1434*81ad6265SDimitry Andric switch (arg->getOption().getID()) { 1435*81ad6265SDimitry Andric case OPT_x: 1436*81ad6265SDimitry Andric config->localSymbolsPresence = SymtabPresence::None; 1437*81ad6265SDimitry Andric break; 1438*81ad6265SDimitry Andric case OPT_non_global_symbols_no_strip_list: 1439*81ad6265SDimitry Andric if (excludeLocal) { 1440*81ad6265SDimitry Andric error("cannot use both -non_global_symbols_no_strip_list and " 1441*81ad6265SDimitry Andric "-non_global_symbols_strip_list"); 1442*81ad6265SDimitry Andric } else { 1443*81ad6265SDimitry Andric includeLocal = true; 1444*81ad6265SDimitry Andric config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded; 1445*81ad6265SDimitry Andric parseSymbolPatternsFile(arg, config->localSymbolPatterns); 1446*81ad6265SDimitry Andric } 1447*81ad6265SDimitry Andric break; 1448*81ad6265SDimitry Andric case OPT_non_global_symbols_strip_list: 1449*81ad6265SDimitry Andric if (includeLocal) { 1450*81ad6265SDimitry Andric error("cannot use both -non_global_symbols_no_strip_list and " 1451*81ad6265SDimitry Andric "-non_global_symbols_strip_list"); 1452*81ad6265SDimitry Andric } else { 1453*81ad6265SDimitry Andric excludeLocal = true; 1454*81ad6265SDimitry Andric config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded; 1455*81ad6265SDimitry Andric parseSymbolPatternsFile(arg, config->localSymbolPatterns); 1456*81ad6265SDimitry Andric } 1457*81ad6265SDimitry Andric break; 1458*81ad6265SDimitry Andric default: 1459*81ad6265SDimitry Andric llvm_unreachable("unexpected option"); 1460*81ad6265SDimitry Andric } 1461*81ad6265SDimitry Andric } 1462fe6060f1SDimitry Andric } 1463fe6060f1SDimitry Andric // Explicitly-exported literal symbols must be defined, but might 1464*81ad6265SDimitry Andric // languish in an archive if unreferenced elsewhere or if they are in the 1465*81ad6265SDimitry Andric // non-global strip list. Light a fire under those lazy symbols! 1466fe6060f1SDimitry Andric for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals) 1467fe6060f1SDimitry Andric symtab->addUndefined(cachedName.val(), /*file=*/nullptr, 1468fe6060f1SDimitry Andric /*isWeakRef=*/false); 1469fe6060f1SDimitry Andric 1470*81ad6265SDimitry Andric for (const Arg *arg : args.filtered(OPT_why_live)) 1471*81ad6265SDimitry Andric config->whyLive.insert(arg->getValue()); 1472*81ad6265SDimitry Andric if (!config->whyLive.empty() && !config->deadStrip) 1473*81ad6265SDimitry Andric warn("-why_live has no effect without -dead_strip, ignoring"); 1474*81ad6265SDimitry Andric 1475e8d8bef9SDimitry Andric config->saveTemps = args.hasArg(OPT_save_temps); 14765ffd83dbSDimitry Andric 1477fe6060f1SDimitry Andric config->adhocCodesign = args.hasFlag( 1478fe6060f1SDimitry Andric OPT_adhoc_codesign, OPT_no_adhoc_codesign, 1479fe6060f1SDimitry Andric (config->arch() == AK_arm64 || config->arch() == AK_arm64e) && 148004eeddc0SDimitry Andric config->platform() == PLATFORM_MACOS); 1481fe6060f1SDimitry Andric 14825ffd83dbSDimitry Andric if (args.hasArg(OPT_v)) { 1483349cc55cSDimitry Andric message(getLLDVersion(), lld::errs()); 14845ffd83dbSDimitry Andric message(StringRef("Library search paths:") + 1485fe6060f1SDimitry Andric (config->librarySearchPaths.empty() 1486fe6060f1SDimitry Andric ? "" 1487349cc55cSDimitry Andric : "\n\t" + join(config->librarySearchPaths, "\n\t")), 1488349cc55cSDimitry Andric lld::errs()); 14895ffd83dbSDimitry Andric message(StringRef("Framework search paths:") + 1490fe6060f1SDimitry Andric (config->frameworkSearchPaths.empty() 1491fe6060f1SDimitry Andric ? "" 1492349cc55cSDimitry Andric : "\n\t" + join(config->frameworkSearchPaths, "\n\t")), 1493349cc55cSDimitry Andric lld::errs()); 14945ffd83dbSDimitry Andric } 14955ffd83dbSDimitry Andric 1496fe6060f1SDimitry Andric config->progName = argsArr[0]; 1497fe6060f1SDimitry Andric 1498*81ad6265SDimitry Andric config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq); 1499fe6060f1SDimitry Andric config->timeTraceGranularity = 1500fe6060f1SDimitry Andric args::getInteger(args, OPT_time_trace_granularity_eq, 500); 1501fe6060f1SDimitry Andric 1502fe6060f1SDimitry Andric // Initialize time trace profiler. 1503fe6060f1SDimitry Andric if (config->timeTraceEnabled) 1504fe6060f1SDimitry Andric timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName); 1505fe6060f1SDimitry Andric 1506fe6060f1SDimitry Andric { 1507fe6060f1SDimitry Andric TimeTraceScope timeScope("ExecuteLinker"); 1508fe6060f1SDimitry Andric 1509e8d8bef9SDimitry Andric initLLVM(); // must be run before any call to addFile() 1510fe6060f1SDimitry Andric createFiles(args); 15115ffd83dbSDimitry Andric 1512e8d8bef9SDimitry Andric config->isPic = config->outputType == MH_DYLIB || 1513fe6060f1SDimitry Andric config->outputType == MH_BUNDLE || 1514fe6060f1SDimitry Andric (config->outputType == MH_EXECUTE && 1515fe6060f1SDimitry Andric args.hasFlag(OPT_pie, OPT_no_pie, true)); 1516e8d8bef9SDimitry Andric 15175ffd83dbSDimitry Andric // Now that all dylibs have been loaded, search for those that should be 15185ffd83dbSDimitry Andric // re-exported. 1519fe6060f1SDimitry Andric { 1520fe6060f1SDimitry Andric auto reexportHandler = [](const Arg *arg, 1521fe6060f1SDimitry Andric const std::vector<StringRef> &extensions) { 15225ffd83dbSDimitry Andric config->hasReexports = true; 15235ffd83dbSDimitry Andric StringRef searchName = arg->getValue(); 1524e8d8bef9SDimitry Andric if (!markReexport(searchName, extensions)) 1525e8d8bef9SDimitry Andric error(arg->getSpelling() + " " + searchName + 1526e8d8bef9SDimitry Andric " does not match a supplied dylib"); 1527fe6060f1SDimitry Andric }; 1528fe6060f1SDimitry Andric std::vector<StringRef> extensions = {".tbd"}; 1529fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_sub_umbrella)) 1530fe6060f1SDimitry Andric reexportHandler(arg, extensions); 1531fe6060f1SDimitry Andric 1532fe6060f1SDimitry Andric extensions.push_back(".dylib"); 1533fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_sub_library)) 1534fe6060f1SDimitry Andric reexportHandler(arg, extensions); 15355ffd83dbSDimitry Andric } 15365ffd83dbSDimitry Andric 1537349cc55cSDimitry Andric cl::ResetAllOptionOccurrences(); 1538349cc55cSDimitry Andric 1539e8d8bef9SDimitry Andric // Parse LTO options. 1540fe6060f1SDimitry Andric if (const Arg *arg = args.getLastArg(OPT_mcpu)) 154104eeddc0SDimitry Andric parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())), 1542e8d8bef9SDimitry Andric arg->getSpelling()); 1543e8d8bef9SDimitry Andric 1544fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_mllvm)) 1545e8d8bef9SDimitry Andric parseClangOption(arg->getValue(), arg->getSpelling()); 1546e8d8bef9SDimitry Andric 1547e8d8bef9SDimitry Andric compileBitcodeFiles(); 1548e8d8bef9SDimitry Andric replaceCommonSymbols(); 1549e8d8bef9SDimitry Andric 15505ffd83dbSDimitry Andric StringRef orderFile = args.getLastArgValue(OPT_order_file); 1551*81ad6265SDimitry Andric if (!orderFile.empty()) 1552*81ad6265SDimitry Andric priorityBuilder.parseOrderFile(orderFile); 15535ffd83dbSDimitry Andric 1554fe6060f1SDimitry Andric referenceStubBinder(); 1555fe6060f1SDimitry Andric 1556fe6060f1SDimitry Andric // FIXME: should terminate the link early based on errors encountered so 1557fe6060f1SDimitry Andric // far? 15585ffd83dbSDimitry Andric 15595ffd83dbSDimitry Andric createSyntheticSections(); 1560fe6060f1SDimitry Andric createSyntheticSymbols(); 1561e8d8bef9SDimitry Andric 1562*81ad6265SDimitry Andric if (config->hasExplicitExports) { 1563349cc55cSDimitry Andric parallelForEach(symtab->getSymbols(), [](Symbol *sym) { 1564fe6060f1SDimitry Andric if (auto *defined = dyn_cast<Defined>(sym)) { 1565fe6060f1SDimitry Andric StringRef symbolName = defined->getName(); 1566fe6060f1SDimitry Andric if (config->exportedSymbols.match(symbolName)) { 1567fe6060f1SDimitry Andric if (defined->privateExtern) { 1568349cc55cSDimitry Andric if (defined->weakDefCanBeHidden) { 1569349cc55cSDimitry Andric // weak_def_can_be_hidden symbols behave similarly to 1570349cc55cSDimitry Andric // private_extern symbols in most cases, except for when 1571349cc55cSDimitry Andric // it is explicitly exported. 1572349cc55cSDimitry Andric // The former can be exported but the latter cannot. 1573349cc55cSDimitry Andric defined->privateExtern = false; 1574349cc55cSDimitry Andric } else { 1575*81ad6265SDimitry Andric warn("cannot export hidden symbol " + toString(*defined) + 1576fe6060f1SDimitry Andric "\n>>> defined in " + toString(defined->getFile())); 1577fe6060f1SDimitry Andric } 1578349cc55cSDimitry Andric } 1579fe6060f1SDimitry Andric } else { 1580fe6060f1SDimitry Andric defined->privateExtern = true; 1581fe6060f1SDimitry Andric } 1582fe6060f1SDimitry Andric } 1583349cc55cSDimitry Andric }); 1584fe6060f1SDimitry Andric } else if (!config->unexportedSymbols.empty()) { 1585349cc55cSDimitry Andric parallelForEach(symtab->getSymbols(), [](Symbol *sym) { 1586fe6060f1SDimitry Andric if (auto *defined = dyn_cast<Defined>(sym)) 1587fe6060f1SDimitry Andric if (config->unexportedSymbols.match(defined->getName())) 1588fe6060f1SDimitry Andric defined->privateExtern = true; 1589349cc55cSDimitry Andric }); 1590fe6060f1SDimitry Andric } 1591fe6060f1SDimitry Andric 1592fe6060f1SDimitry Andric for (const Arg *arg : args.filtered(OPT_sectcreate)) { 1593e8d8bef9SDimitry Andric StringRef segName = arg->getValue(0); 1594e8d8bef9SDimitry Andric StringRef sectName = arg->getValue(1); 1595e8d8bef9SDimitry Andric StringRef fileName = arg->getValue(2); 1596e8d8bef9SDimitry Andric Optional<MemoryBufferRef> buffer = readFile(fileName); 1597e8d8bef9SDimitry Andric if (buffer) 1598e8d8bef9SDimitry Andric inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName)); 1599e8d8bef9SDimitry Andric } 16005ffd83dbSDimitry Andric 16011fd87a68SDimitry Andric for (const Arg *arg : args.filtered(OPT_add_empty_section)) { 16021fd87a68SDimitry Andric StringRef segName = arg->getValue(0); 16031fd87a68SDimitry Andric StringRef sectName = arg->getValue(1); 16041fd87a68SDimitry Andric inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName)); 16051fd87a68SDimitry Andric } 16061fd87a68SDimitry Andric 1607fe6060f1SDimitry Andric gatherInputSections(); 160804eeddc0SDimitry Andric if (config->callGraphProfileSort) 1609*81ad6265SDimitry Andric priorityBuilder.extractCallGraphProfile(); 1610fe6060f1SDimitry Andric 1611fe6060f1SDimitry Andric if (config->deadStrip) 1612fe6060f1SDimitry Andric markLive(); 1613fe6060f1SDimitry Andric 1614fe6060f1SDimitry Andric // ICF assumes that all literals have been folded already, so we must run 1615fe6060f1SDimitry Andric // foldIdenticalLiterals before foldIdenticalSections. 1616fe6060f1SDimitry Andric foldIdenticalLiterals(); 1617*81ad6265SDimitry Andric if (config->icfLevel != ICFLevel::none) { 1618*81ad6265SDimitry Andric if (config->icfLevel == ICFLevel::safe) 1619*81ad6265SDimitry Andric markAddrSigSymbols(); 1620fe6060f1SDimitry Andric foldIdenticalSections(); 1621*81ad6265SDimitry Andric } 16225ffd83dbSDimitry Andric 16235ffd83dbSDimitry Andric // Write to an output file. 1624fe6060f1SDimitry Andric if (target->wordSize == 8) 1625fe6060f1SDimitry Andric writeResult<LP64>(); 1626fe6060f1SDimitry Andric else 1627fe6060f1SDimitry Andric writeResult<ILP32>(); 1628fe6060f1SDimitry Andric 1629fe6060f1SDimitry Andric depTracker->write(getLLDVersion(), inputFiles, config->outputFile); 1630fe6060f1SDimitry Andric } 1631fe6060f1SDimitry Andric 1632fe6060f1SDimitry Andric if (config->timeTraceEnabled) { 1633349cc55cSDimitry Andric checkError(timeTraceProfilerWrite( 1634*81ad6265SDimitry Andric args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile)); 1635fe6060f1SDimitry Andric 1636fe6060f1SDimitry Andric timeTraceProfilerCleanup(); 1637fe6060f1SDimitry Andric } 163804eeddc0SDimitry Andric return errorCount() == 0; 16395ffd83dbSDimitry Andric } 1640