xref: /openbsd-src/gnu/llvm/lld/MachO/Driver.cpp (revision dfe94b169149f14cc1aee2cf6dad58a8d9a1860c)
1bb684c34Spatrick //===- Driver.cpp ---------------------------------------------------------===//
2bb684c34Spatrick //
3bb684c34Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4bb684c34Spatrick // See https://llvm.org/LICENSE.txt for license information.
5bb684c34Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6bb684c34Spatrick //
7bb684c34Spatrick //===----------------------------------------------------------------------===//
8bb684c34Spatrick 
9bb684c34Spatrick #include "Driver.h"
10bb684c34Spatrick #include "Config.h"
111cf9926bSpatrick #include "ICF.h"
12bb684c34Spatrick #include "InputFiles.h"
131cf9926bSpatrick #include "LTO.h"
141cf9926bSpatrick #include "MarkLive.h"
151cf9926bSpatrick #include "ObjC.h"
16bb684c34Spatrick #include "OutputSection.h"
17bb684c34Spatrick #include "OutputSegment.h"
18*dfe94b16Srobert #include "SectionPriorities.h"
19bb684c34Spatrick #include "SymbolTable.h"
20bb684c34Spatrick #include "Symbols.h"
211cf9926bSpatrick #include "SyntheticSections.h"
22bb684c34Spatrick #include "Target.h"
231cf9926bSpatrick #include "UnwindInfoSection.h"
24bb684c34Spatrick #include "Writer.h"
25bb684c34Spatrick 
26bb684c34Spatrick #include "lld/Common/Args.h"
27*dfe94b16Srobert #include "lld/Common/CommonLinkerContext.h"
28bb684c34Spatrick #include "lld/Common/Driver.h"
29bb684c34Spatrick #include "lld/Common/ErrorHandler.h"
30bb684c34Spatrick #include "lld/Common/LLVM.h"
31bb684c34Spatrick #include "lld/Common/Memory.h"
321cf9926bSpatrick #include "lld/Common/Reproduce.h"
33bb684c34Spatrick #include "lld/Common/Version.h"
34bb684c34Spatrick #include "llvm/ADT/DenseSet.h"
35bb684c34Spatrick #include "llvm/ADT/StringExtras.h"
36bb684c34Spatrick #include "llvm/ADT/StringRef.h"
37bb684c34Spatrick #include "llvm/BinaryFormat/MachO.h"
38bb684c34Spatrick #include "llvm/BinaryFormat/Magic.h"
391cf9926bSpatrick #include "llvm/Config/llvm-config.h"
401cf9926bSpatrick #include "llvm/LTO/LTO.h"
41bb684c34Spatrick #include "llvm/Object/Archive.h"
42bb684c34Spatrick #include "llvm/Option/ArgList.h"
431cf9926bSpatrick #include "llvm/Support/CommandLine.h"
441cf9926bSpatrick #include "llvm/Support/FileSystem.h"
45bb684c34Spatrick #include "llvm/Support/Host.h"
46bb684c34Spatrick #include "llvm/Support/MemoryBuffer.h"
471cf9926bSpatrick #include "llvm/Support/Parallel.h"
48bb684c34Spatrick #include "llvm/Support/Path.h"
491cf9926bSpatrick #include "llvm/Support/TarWriter.h"
501cf9926bSpatrick #include "llvm/Support/TargetSelect.h"
511cf9926bSpatrick #include "llvm/Support/TimeProfiler.h"
521cf9926bSpatrick #include "llvm/TextAPI/PackedVersion.h"
531cf9926bSpatrick 
541cf9926bSpatrick #include <algorithm>
55bb684c34Spatrick 
56bb684c34Spatrick using namespace llvm;
57bb684c34Spatrick using namespace llvm::MachO;
581cf9926bSpatrick using namespace llvm::object;
59bb684c34Spatrick using namespace llvm::opt;
601cf9926bSpatrick using namespace llvm::sys;
61bb684c34Spatrick using namespace lld;
62bb684c34Spatrick using namespace lld::macho;
63bb684c34Spatrick 
64*dfe94b16Srobert std::unique_ptr<Configuration> macho::config;
65*dfe94b16Srobert std::unique_ptr<DependencyTracker> macho::depTracker;
66bb684c34Spatrick 
getOutputType(const InputArgList & args)671cf9926bSpatrick static HeaderFileType getOutputType(const InputArgList &args) {
681cf9926bSpatrick   // TODO: -r, -dylinker, -preload...
691cf9926bSpatrick   Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute);
701cf9926bSpatrick   if (outputArg == nullptr)
711cf9926bSpatrick     return MH_EXECUTE;
72bb684c34Spatrick 
731cf9926bSpatrick   switch (outputArg->getOption().getID()) {
741cf9926bSpatrick   case OPT_bundle:
751cf9926bSpatrick     return MH_BUNDLE;
761cf9926bSpatrick   case OPT_dylib:
771cf9926bSpatrick     return MH_DYLIB;
781cf9926bSpatrick   case OPT_execute:
791cf9926bSpatrick     return MH_EXECUTE;
801cf9926bSpatrick   default:
811cf9926bSpatrick     llvm_unreachable("internal error");
821cf9926bSpatrick   }
83bb684c34Spatrick }
84bb684c34Spatrick 
85*dfe94b16Srobert static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;
findLibrary(StringRef name)86*dfe94b16Srobert static std::optional<StringRef> findLibrary(StringRef name) {
87*dfe94b16Srobert   CachedHashStringRef key(name);
88*dfe94b16Srobert   auto entry = resolvedLibraries.find(key);
89*dfe94b16Srobert   if (entry != resolvedLibraries.end())
90*dfe94b16Srobert     return entry->second;
91*dfe94b16Srobert 
92*dfe94b16Srobert   auto doFind = [&] {
931cf9926bSpatrick     if (config->searchDylibsFirst) {
94*dfe94b16Srobert       if (std::optional<StringRef> path = findPathCombination(
951cf9926bSpatrick               "lib" + name, config->librarySearchPaths, {".tbd", ".dylib"}))
961cf9926bSpatrick         return path;
971cf9926bSpatrick       return findPathCombination("lib" + name, config->librarySearchPaths,
981cf9926bSpatrick                                  {".a"});
991cf9926bSpatrick     }
1001cf9926bSpatrick     return findPathCombination("lib" + name, config->librarySearchPaths,
1011cf9926bSpatrick                                {".tbd", ".dylib", ".a"});
102*dfe94b16Srobert   };
103*dfe94b16Srobert 
104*dfe94b16Srobert   std::optional<StringRef> path = doFind();
105*dfe94b16Srobert   if (path)
106*dfe94b16Srobert     resolvedLibraries[key] = *path;
107*dfe94b16Srobert 
108*dfe94b16Srobert   return path;
109bb684c34Spatrick }
110bb684c34Spatrick 
111*dfe94b16Srobert static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;
findFramework(StringRef name)112*dfe94b16Srobert static std::optional<StringRef> findFramework(StringRef name) {
113*dfe94b16Srobert   CachedHashStringRef key(name);
114*dfe94b16Srobert   auto entry = resolvedFrameworks.find(key);
115*dfe94b16Srobert   if (entry != resolvedFrameworks.end())
116*dfe94b16Srobert     return entry->second;
117*dfe94b16Srobert 
1181cf9926bSpatrick   SmallString<260> symlink;
1191cf9926bSpatrick   StringRef suffix;
1201cf9926bSpatrick   std::tie(name, suffix) = name.split(",");
1211cf9926bSpatrick   for (StringRef dir : config->frameworkSearchPaths) {
1221cf9926bSpatrick     symlink = dir;
1231cf9926bSpatrick     path::append(symlink, name + ".framework", name);
124bb684c34Spatrick 
1251cf9926bSpatrick     if (!suffix.empty()) {
1261cf9926bSpatrick       // NOTE: we must resolve the symlink before trying the suffixes, because
1271cf9926bSpatrick       // there are no symlinks for the suffixed paths.
1281cf9926bSpatrick       SmallString<260> location;
1291cf9926bSpatrick       if (!fs::real_path(symlink, location)) {
1301cf9926bSpatrick         // only append suffix if realpath() succeeds
1311cf9926bSpatrick         Twine suffixed = location + suffix;
1321cf9926bSpatrick         if (fs::exists(suffixed))
133*dfe94b16Srobert           return resolvedFrameworks[key] = saver().save(suffixed.str());
134bb684c34Spatrick       }
1351cf9926bSpatrick       // Suffix lookup failed, fall through to the no-suffix case.
1361cf9926bSpatrick     }
1371cf9926bSpatrick 
138*dfe94b16Srobert     if (std::optional<StringRef> path = resolveDylibPath(symlink.str()))
139*dfe94b16Srobert       return resolvedFrameworks[key] = *path;
140bb684c34Spatrick   }
141bb684c34Spatrick   return {};
142bb684c34Spatrick }
143bb684c34Spatrick 
warnIfNotDirectory(StringRef option,StringRef path)1441cf9926bSpatrick static bool warnIfNotDirectory(StringRef option, StringRef path) {
145bb684c34Spatrick   if (!fs::exists(path)) {
146bb684c34Spatrick     warn("directory not found for option -" + option + path);
147bb684c34Spatrick     return false;
148bb684c34Spatrick   } else if (!fs::is_directory(path)) {
149bb684c34Spatrick     warn("option -" + option + path + " references a non-directory path");
150bb684c34Spatrick     return false;
151bb684c34Spatrick   }
152bb684c34Spatrick   return true;
153bb684c34Spatrick }
154bb684c34Spatrick 
1551cf9926bSpatrick static std::vector<StringRef>
getSearchPaths(unsigned optionCode,InputArgList & args,const std::vector<StringRef> & roots,const SmallVector<StringRef,2> & systemPaths)1561cf9926bSpatrick getSearchPaths(unsigned optionCode, InputArgList &args,
1571cf9926bSpatrick                const std::vector<StringRef> &roots,
158bb684c34Spatrick                const SmallVector<StringRef, 2> &systemPaths) {
1591cf9926bSpatrick   std::vector<StringRef> paths;
1601cf9926bSpatrick   StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
1611cf9926bSpatrick   for (StringRef path : args::getStrings(args, optionCode)) {
1621cf9926bSpatrick     // NOTE: only absolute paths are re-rooted to syslibroot(s)
1631cf9926bSpatrick     bool found = false;
1641cf9926bSpatrick     if (path::is_absolute(path, path::Style::posix)) {
1651cf9926bSpatrick       for (StringRef root : roots) {
1661cf9926bSpatrick         SmallString<261> buffer(root);
1671cf9926bSpatrick         path::append(buffer, path);
1681cf9926bSpatrick         // Do not warn about paths that are computed via the syslib roots
1691cf9926bSpatrick         if (fs::is_directory(buffer)) {
170*dfe94b16Srobert           paths.push_back(saver().save(buffer.str()));
1711cf9926bSpatrick           found = true;
1721cf9926bSpatrick         }
1731cf9926bSpatrick       }
1741cf9926bSpatrick     }
1751cf9926bSpatrick     if (!found && warnIfNotDirectory(optionLetter, path))
176bb684c34Spatrick       paths.push_back(path);
177bb684c34Spatrick   }
1781cf9926bSpatrick 
1791cf9926bSpatrick   // `-Z` suppresses the standard "system" search paths.
1801cf9926bSpatrick   if (args.hasArg(OPT_Z))
1811cf9926bSpatrick     return paths;
1821cf9926bSpatrick 
1831cf9926bSpatrick   for (const StringRef &path : systemPaths) {
1841cf9926bSpatrick     for (const StringRef &root : roots) {
1851cf9926bSpatrick       SmallString<261> buffer(root);
1861cf9926bSpatrick       path::append(buffer, path);
1871cf9926bSpatrick       if (fs::is_directory(buffer))
188*dfe94b16Srobert         paths.push_back(saver().save(buffer.str()));
189bb684c34Spatrick     }
190bb684c34Spatrick   }
1911cf9926bSpatrick   return paths;
192bb684c34Spatrick }
193bb684c34Spatrick 
getSystemLibraryRoots(InputArgList & args)1941cf9926bSpatrick static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) {
1951cf9926bSpatrick   std::vector<StringRef> roots;
1961cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_syslibroot))
1971cf9926bSpatrick     roots.push_back(arg->getValue());
1981cf9926bSpatrick   // NOTE: the final `-syslibroot` being `/` will ignore all roots
199*dfe94b16Srobert   if (!roots.empty() && roots.back() == "/")
2001cf9926bSpatrick     roots.clear();
2011cf9926bSpatrick   // NOTE: roots can never be empty - add an empty root to simplify the library
2021cf9926bSpatrick   // and framework search path computation.
2031cf9926bSpatrick   if (roots.empty())
2041cf9926bSpatrick     roots.emplace_back("");
2051cf9926bSpatrick   return roots;
206bb684c34Spatrick }
207bb684c34Spatrick 
2081cf9926bSpatrick static std::vector<StringRef>
getLibrarySearchPaths(InputArgList & args,const std::vector<StringRef> & roots)2091cf9926bSpatrick getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) {
2101cf9926bSpatrick   return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});
2111cf9926bSpatrick }
2121cf9926bSpatrick 
2131cf9926bSpatrick static std::vector<StringRef>
getFrameworkSearchPaths(InputArgList & args,const std::vector<StringRef> & roots)2141cf9926bSpatrick getFrameworkSearchPaths(InputArgList &args,
2151cf9926bSpatrick                         const std::vector<StringRef> &roots) {
2161cf9926bSpatrick   return getSearchPaths(OPT_F, args, roots,
217bb684c34Spatrick                         {"/Library/Frameworks", "/System/Library/Frameworks"});
218bb684c34Spatrick }
219bb684c34Spatrick 
getLTOCachePolicy(InputArgList & args)2201cf9926bSpatrick static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) {
2211cf9926bSpatrick   SmallString<128> ltoPolicy;
2221cf9926bSpatrick   auto add = [&ltoPolicy](Twine val) {
2231cf9926bSpatrick     if (!ltoPolicy.empty())
2241cf9926bSpatrick       ltoPolicy += ":";
2251cf9926bSpatrick     val.toVector(ltoPolicy);
2261cf9926bSpatrick   };
2271cf9926bSpatrick   for (const Arg *arg :
228*dfe94b16Srobert        args.filtered(OPT_thinlto_cache_policy_eq, OPT_prune_interval_lto,
2291cf9926bSpatrick                      OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) {
2301cf9926bSpatrick     switch (arg->getOption().getID()) {
231*dfe94b16Srobert     case OPT_thinlto_cache_policy_eq:
232*dfe94b16Srobert       add(arg->getValue());
233*dfe94b16Srobert       break;
2341cf9926bSpatrick     case OPT_prune_interval_lto:
2351cf9926bSpatrick       if (!strcmp("-1", arg->getValue()))
2361cf9926bSpatrick         add("prune_interval=87600h"); // 10 years
2371cf9926bSpatrick       else
2381cf9926bSpatrick         add(Twine("prune_interval=") + arg->getValue() + "s");
2391cf9926bSpatrick       break;
2401cf9926bSpatrick     case OPT_prune_after_lto:
2411cf9926bSpatrick       add(Twine("prune_after=") + arg->getValue() + "s");
2421cf9926bSpatrick       break;
2431cf9926bSpatrick     case OPT_max_relative_cache_size_lto:
2441cf9926bSpatrick       add(Twine("cache_size=") + arg->getValue() + "%");
2451cf9926bSpatrick       break;
2461cf9926bSpatrick     }
2471cf9926bSpatrick   }
2481cf9926bSpatrick   return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy");
2491cf9926bSpatrick }
2501cf9926bSpatrick 
251*dfe94b16Srobert // What caused a given library to be loaded. Only relevant for archives.
252*dfe94b16Srobert // Note that this does not tell us *how* we should load the library, i.e.
253*dfe94b16Srobert // whether we should do it lazily or eagerly (AKA force loading). The "how" is
254*dfe94b16Srobert // decided within addFile().
255*dfe94b16Srobert enum class LoadType {
256*dfe94b16Srobert   CommandLine,      // Library was passed as a regular CLI argument
257*dfe94b16Srobert   CommandLineForce, // Library was passed via `-force_load`
258*dfe94b16Srobert   LCLinkerOption,   // Library was passed via LC_LINKER_OPTIONS
2591cf9926bSpatrick };
2601cf9926bSpatrick 
261*dfe94b16Srobert struct ArchiveFileInfo {
262*dfe94b16Srobert   ArchiveFile *file;
263*dfe94b16Srobert   bool isCommandLineLoad;
264*dfe94b16Srobert };
2651cf9926bSpatrick 
266*dfe94b16Srobert static DenseMap<StringRef, ArchiveFileInfo> loadedArchives;
2671cf9926bSpatrick 
addFile(StringRef path,LoadType loadType,bool isLazy=false,bool isExplicit=true,bool isBundleLoader=false,bool isForceHidden=false)268*dfe94b16Srobert static InputFile *addFile(StringRef path, LoadType loadType,
269*dfe94b16Srobert                           bool isLazy = false, bool isExplicit = true,
270*dfe94b16Srobert                           bool isBundleLoader = false,
271*dfe94b16Srobert                           bool isForceHidden = false) {
272*dfe94b16Srobert   std::optional<MemoryBufferRef> buffer = readFile(path);
273bb684c34Spatrick   if (!buffer)
2741cf9926bSpatrick     return nullptr;
275bb684c34Spatrick   MemoryBufferRef mbref = *buffer;
2761cf9926bSpatrick   InputFile *newFile = nullptr;
277bb684c34Spatrick 
2781cf9926bSpatrick   file_magic magic = identify_magic(mbref.getBuffer());
2791cf9926bSpatrick   switch (magic) {
280bb684c34Spatrick   case file_magic::archive: {
281*dfe94b16Srobert     bool isCommandLineLoad = loadType != LoadType::LCLinkerOption;
2821cf9926bSpatrick     // Avoid loading archives twice. If the archives are being force-loaded,
2831cf9926bSpatrick     // loading them twice would create duplicate symbol errors. In the
2841cf9926bSpatrick     // non-force-loading case, this is just a minor performance optimization.
2851cf9926bSpatrick     // We don't take a reference to cachedFile here because the
2861cf9926bSpatrick     // loadArchiveMember() call below may recursively call addFile() and
2871cf9926bSpatrick     // invalidate this reference.
288*dfe94b16Srobert     auto entry = loadedArchives.find(path);
2891cf9926bSpatrick 
290*dfe94b16Srobert     ArchiveFile *file;
291*dfe94b16Srobert     if (entry == loadedArchives.end()) {
292*dfe94b16Srobert       // No cached archive, we need to create a new one
293*dfe94b16Srobert       std::unique_ptr<object::Archive> archive = CHECK(
294bb684c34Spatrick           object::Archive::create(mbref), path + ": failed to parse archive");
295bb684c34Spatrick 
296*dfe94b16Srobert       if (!archive->isEmpty() && !archive->hasSymbolTable())
297bb684c34Spatrick         error(path + ": archive has no index; run ranlib to add one");
298*dfe94b16Srobert       file = make<ArchiveFile>(std::move(archive), isForceHidden);
299*dfe94b16Srobert     } else {
300*dfe94b16Srobert       file = entry->second.file;
301*dfe94b16Srobert       // Command-line loads take precedence. If file is previously loaded via
302*dfe94b16Srobert       // command line, or is loaded via LC_LINKER_OPTION and being loaded via
303*dfe94b16Srobert       // LC_LINKER_OPTION again, using the cached archive is enough.
304*dfe94b16Srobert       if (entry->second.isCommandLineLoad || !isCommandLineLoad)
305*dfe94b16Srobert         return file;
306*dfe94b16Srobert     }
307bb684c34Spatrick 
308*dfe94b16Srobert     bool isLCLinkerForceLoad = loadType == LoadType::LCLinkerOption &&
309*dfe94b16Srobert                                config->forceLoadSwift &&
310*dfe94b16Srobert                                path::filename(path).startswith("libswift");
311*dfe94b16Srobert     if ((isCommandLineLoad && config->allLoad) ||
312*dfe94b16Srobert         loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) {
313*dfe94b16Srobert       if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
314*dfe94b16Srobert         Error e = Error::success();
315*dfe94b16Srobert         for (const object::Archive::Child &c : file->getArchive().children(e)) {
316*dfe94b16Srobert           StringRef reason;
317*dfe94b16Srobert           switch (loadType) {
318*dfe94b16Srobert             case LoadType::LCLinkerOption:
319*dfe94b16Srobert               reason = "LC_LINKER_OPTION";
320*dfe94b16Srobert               break;
321*dfe94b16Srobert             case LoadType::CommandLineForce:
322*dfe94b16Srobert               reason = "-force_load";
323*dfe94b16Srobert               break;
324*dfe94b16Srobert             case LoadType::CommandLine:
325*dfe94b16Srobert               reason = "-all_load";
326*dfe94b16Srobert               break;
3271cf9926bSpatrick           }
328*dfe94b16Srobert           if (Error e = file->fetch(c, reason))
329*dfe94b16Srobert             error(toString(file) + ": " + reason +
330*dfe94b16Srobert                   " failed to load archive member: " + toString(std::move(e)));
3311cf9926bSpatrick         }
332*dfe94b16Srobert         if (e)
333*dfe94b16Srobert           error(toString(file) +
334*dfe94b16Srobert                 ": Archive::children failed: " + toString(std::move(e)));
3351cf9926bSpatrick       }
336*dfe94b16Srobert     } else if (isCommandLineLoad && config->forceLoadObjC) {
337*dfe94b16Srobert       for (const object::Archive::Symbol &sym : file->getArchive().symbols())
3381cf9926bSpatrick         if (sym.getName().startswith(objc::klass))
339*dfe94b16Srobert           file->fetch(sym);
3401cf9926bSpatrick 
3411cf9926bSpatrick       // TODO: no need to look for ObjC sections for a given archive member if
342*dfe94b16Srobert       // we already found that it contains an ObjC symbol.
343*dfe94b16Srobert       if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
344*dfe94b16Srobert         Error e = Error::success();
345*dfe94b16Srobert         for (const object::Archive::Child &c : file->getArchive().children(e)) {
346*dfe94b16Srobert           Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
347*dfe94b16Srobert           if (!mb || !hasObjCSection(*mb))
348*dfe94b16Srobert             continue;
349*dfe94b16Srobert           if (Error e = file->fetch(c, "-ObjC"))
350*dfe94b16Srobert             error(toString(file) + ": -ObjC failed to load archive member: " +
351*dfe94b16Srobert                   toString(std::move(e)));
3521cf9926bSpatrick         }
353*dfe94b16Srobert         if (e)
354*dfe94b16Srobert           error(toString(file) +
355*dfe94b16Srobert                 ": Archive::children failed: " + toString(std::move(e)));
3561cf9926bSpatrick       }
3571cf9926bSpatrick     }
3581cf9926bSpatrick 
359*dfe94b16Srobert     file->addLazySymbols();
360*dfe94b16Srobert     loadedArchives[path] = ArchiveFileInfo{file, isCommandLineLoad};
361*dfe94b16Srobert     newFile = file;
362bb684c34Spatrick     break;
363bb684c34Spatrick   }
364bb684c34Spatrick   case file_magic::macho_object:
365*dfe94b16Srobert     newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy);
366bb684c34Spatrick     break;
367bb684c34Spatrick   case file_magic::macho_dynamically_linked_shared_lib:
3681cf9926bSpatrick   case file_magic::macho_dynamically_linked_shared_lib_stub:
3691cf9926bSpatrick   case file_magic::tapi_file:
370*dfe94b16Srobert     if (DylibFile *dylibFile =
371*dfe94b16Srobert             loadDylib(mbref, nullptr, /*isBundleLoader=*/false, isExplicit))
3721cf9926bSpatrick       newFile = dylibFile;
3731cf9926bSpatrick     break;
3741cf9926bSpatrick   case file_magic::bitcode:
375*dfe94b16Srobert     newFile = make<BitcodeFile>(mbref, "", 0, isLazy);
3761cf9926bSpatrick     break;
3771cf9926bSpatrick   case file_magic::macho_executable:
3781cf9926bSpatrick   case file_magic::macho_bundle:
3791cf9926bSpatrick     // We only allow executable and bundle type here if it is used
3801cf9926bSpatrick     // as a bundle loader.
3811cf9926bSpatrick     if (!isBundleLoader)
3821cf9926bSpatrick       error(path + ": unhandled file type");
3831cf9926bSpatrick     if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader))
3841cf9926bSpatrick       newFile = dylibFile;
3851cf9926bSpatrick     break;
386bb684c34Spatrick   default:
387bb684c34Spatrick     error(path + ": unhandled file type");
388bb684c34Spatrick   }
3891cf9926bSpatrick   if (newFile && !isa<DylibFile>(newFile)) {
390*dfe94b16Srobert     if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy &&
391*dfe94b16Srobert         config->forceLoadObjC) {
392*dfe94b16Srobert       for (Symbol *sym : newFile->symbols)
393*dfe94b16Srobert         if (sym && sym->getName().startswith(objc::klass)) {
394*dfe94b16Srobert           extract(*newFile, "-ObjC");
395*dfe94b16Srobert           break;
396*dfe94b16Srobert         }
397*dfe94b16Srobert       if (newFile->lazy && hasObjCSection(mbref))
398*dfe94b16Srobert         extract(*newFile, "-ObjC");
399*dfe94b16Srobert     }
400*dfe94b16Srobert 
4011cf9926bSpatrick     // printArchiveMemberLoad() prints both .a and .o names, so no need to
402*dfe94b16Srobert     // print the .a name here. Similarly skip lazy files.
403*dfe94b16Srobert     if (config->printEachFile && magic != file_magic::archive && !isLazy)
4041cf9926bSpatrick       message(toString(newFile));
4051cf9926bSpatrick     inputFiles.insert(newFile);
4061cf9926bSpatrick   }
4071cf9926bSpatrick   return newFile;
408bb684c34Spatrick }
409bb684c34Spatrick 
410*dfe94b16Srobert static std::vector<StringRef> missingAutolinkWarnings;
addLibrary(StringRef name,bool isNeeded,bool isWeak,bool isReexport,bool isHidden,bool isExplicit,LoadType loadType,InputFile * originFile=nullptr)4111cf9926bSpatrick static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
412*dfe94b16Srobert                        bool isReexport, bool isHidden, bool isExplicit,
413*dfe94b16Srobert                        LoadType loadType, InputFile *originFile = nullptr) {
414*dfe94b16Srobert   if (std::optional<StringRef> path = findLibrary(name)) {
4151cf9926bSpatrick     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
416*dfe94b16Srobert             addFile(*path, loadType, /*isLazy=*/false, isExplicit,
417*dfe94b16Srobert                     /*isBundleLoader=*/false, isHidden))) {
4181cf9926bSpatrick       if (isNeeded)
4191cf9926bSpatrick         dylibFile->forceNeeded = true;
4201cf9926bSpatrick       if (isWeak)
4211cf9926bSpatrick         dylibFile->forceWeakImport = true;
4221cf9926bSpatrick       if (isReexport) {
4231cf9926bSpatrick         config->hasReexports = true;
4241cf9926bSpatrick         dylibFile->reexport = true;
4251cf9926bSpatrick       }
4261cf9926bSpatrick     }
4271cf9926bSpatrick     return;
4281cf9926bSpatrick   }
429*dfe94b16Srobert   if (loadType == LoadType::LCLinkerOption) {
430*dfe94b16Srobert     assert(originFile);
431*dfe94b16Srobert     missingAutolinkWarnings.push_back(
432*dfe94b16Srobert         saver().save(toString(originFile) +
433*dfe94b16Srobert                      ": auto-linked library not found for -l" + name));
434*dfe94b16Srobert     return;
435*dfe94b16Srobert   }
4361cf9926bSpatrick   error("library not found for -l" + name);
4371cf9926bSpatrick }
4381cf9926bSpatrick 
439*dfe94b16Srobert static DenseSet<StringRef> loadedObjectFrameworks;
addFramework(StringRef name,bool isNeeded,bool isWeak,bool isReexport,bool isExplicit,LoadType loadType,InputFile * originFile=nullptr)4401cf9926bSpatrick static void addFramework(StringRef name, bool isNeeded, bool isWeak,
441*dfe94b16Srobert                          bool isReexport, bool isExplicit, LoadType loadType,
442*dfe94b16Srobert                          InputFile *originFile = nullptr) {
443*dfe94b16Srobert   if (std::optional<StringRef> path = findFramework(name)) {
444*dfe94b16Srobert     if (loadedObjectFrameworks.contains(*path))
445*dfe94b16Srobert       return;
446*dfe94b16Srobert 
447*dfe94b16Srobert     InputFile *file =
448*dfe94b16Srobert         addFile(*path, loadType, /*isLazy=*/false, isExplicit, false);
449*dfe94b16Srobert     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) {
4501cf9926bSpatrick       if (isNeeded)
4511cf9926bSpatrick         dylibFile->forceNeeded = true;
4521cf9926bSpatrick       if (isWeak)
4531cf9926bSpatrick         dylibFile->forceWeakImport = true;
4541cf9926bSpatrick       if (isReexport) {
4551cf9926bSpatrick         config->hasReexports = true;
4561cf9926bSpatrick         dylibFile->reexport = true;
4571cf9926bSpatrick       }
458*dfe94b16Srobert     } else if (isa_and_nonnull<ObjFile>(file) ||
459*dfe94b16Srobert                isa_and_nonnull<BitcodeFile>(file)) {
460*dfe94b16Srobert       // Cache frameworks containing object or bitcode files to avoid duplicate
461*dfe94b16Srobert       // symbols. Frameworks containing static archives are cached separately
462*dfe94b16Srobert       // in addFile() to share caching with libraries, and frameworks
463*dfe94b16Srobert       // containing dylibs should allow overwriting of attributes such as
464*dfe94b16Srobert       // forceNeeded by subsequent loads
465*dfe94b16Srobert       loadedObjectFrameworks.insert(*path);
4661cf9926bSpatrick     }
4671cf9926bSpatrick     return;
4681cf9926bSpatrick   }
469*dfe94b16Srobert   if (loadType == LoadType::LCLinkerOption) {
470*dfe94b16Srobert     assert(originFile);
471*dfe94b16Srobert     missingAutolinkWarnings.push_back(saver().save(
472*dfe94b16Srobert         toString(originFile) +
473*dfe94b16Srobert         ": auto-linked framework not found for -framework " + name));
474*dfe94b16Srobert     return;
475*dfe94b16Srobert   }
4761cf9926bSpatrick   error("framework not found for -framework " + name);
4771cf9926bSpatrick }
4781cf9926bSpatrick 
4791cf9926bSpatrick // Parses LC_LINKER_OPTION contents, which can add additional command line
480*dfe94b16Srobert // flags. This directly parses the flags instead of using the standard argument
481*dfe94b16Srobert // parser to improve performance.
parseLCLinkerOption(InputFile * f,unsigned argc,StringRef data)4821cf9926bSpatrick void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) {
483*dfe94b16Srobert   if (config->ignoreAutoLink)
484*dfe94b16Srobert     return;
485*dfe94b16Srobert 
486*dfe94b16Srobert   SmallVector<StringRef, 4> argv;
4871cf9926bSpatrick   size_t offset = 0;
4881cf9926bSpatrick   for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
4891cf9926bSpatrick     argv.push_back(data.data() + offset);
4901cf9926bSpatrick     offset += strlen(data.data() + offset) + 1;
4911cf9926bSpatrick   }
4921cf9926bSpatrick   if (argv.size() != argc || offset > data.size())
4931cf9926bSpatrick     fatal(toString(f) + ": invalid LC_LINKER_OPTION");
4941cf9926bSpatrick 
495*dfe94b16Srobert   unsigned i = 0;
496*dfe94b16Srobert   StringRef arg = argv[i];
497*dfe94b16Srobert   if (arg.consume_front("-l")) {
498*dfe94b16Srobert     if (config->ignoreAutoLinkOptions.contains(arg))
499*dfe94b16Srobert       return;
500*dfe94b16Srobert     addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false,
501*dfe94b16Srobert                /*isReexport=*/false, /*isHidden=*/false, /*isExplicit=*/false,
502*dfe94b16Srobert                LoadType::LCLinkerOption, f);
503*dfe94b16Srobert   } else if (arg == "-framework") {
504*dfe94b16Srobert     StringRef name = argv[++i];
505*dfe94b16Srobert     if (config->ignoreAutoLinkOptions.contains(name))
506*dfe94b16Srobert       return;
507*dfe94b16Srobert     addFramework(name, /*isNeeded=*/false, /*isWeak=*/false,
508*dfe94b16Srobert                  /*isReexport=*/false, /*isExplicit=*/false,
509*dfe94b16Srobert                  LoadType::LCLinkerOption, f);
510*dfe94b16Srobert   } else {
511*dfe94b16Srobert     error(arg + " is not allowed in LC_LINKER_OPTION");
5121cf9926bSpatrick   }
5131cf9926bSpatrick }
5141cf9926bSpatrick 
addFileList(StringRef path,bool isLazy)515*dfe94b16Srobert static void addFileList(StringRef path, bool isLazy) {
516*dfe94b16Srobert   std::optional<MemoryBufferRef> buffer = readFile(path);
5171cf9926bSpatrick   if (!buffer)
5181cf9926bSpatrick     return;
5191cf9926bSpatrick   MemoryBufferRef mbref = *buffer;
5201cf9926bSpatrick   for (StringRef path : args::getLines(mbref))
521*dfe94b16Srobert     addFile(rerootPath(path), LoadType::CommandLine, isLazy);
522bb684c34Spatrick }
523bb684c34Spatrick 
524bb684c34Spatrick // We expect sub-library names of the form "libfoo", which will match a dylib
5251cf9926bSpatrick // with a path of .*/libfoo.{dylib, tbd}.
5261cf9926bSpatrick // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
5271cf9926bSpatrick // I'm not sure what the use case for that is.
markReexport(StringRef searchName,ArrayRef<StringRef> extensions)5281cf9926bSpatrick static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
529bb684c34Spatrick   for (InputFile *file : inputFiles) {
530bb684c34Spatrick     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
531bb684c34Spatrick       StringRef filename = path::filename(dylibFile->getName());
5321cf9926bSpatrick       if (filename.consume_front(searchName) &&
533*dfe94b16Srobert           (filename.empty() || llvm::is_contained(extensions, filename))) {
534bb684c34Spatrick         dylibFile->reexport = true;
535bb684c34Spatrick         return true;
536bb684c34Spatrick       }
537bb684c34Spatrick     }
538bb684c34Spatrick   }
539bb684c34Spatrick   return false;
540bb684c34Spatrick }
541bb684c34Spatrick 
5421cf9926bSpatrick // This function is called on startup. We need this for LTO since
5431cf9926bSpatrick // LTO calls LLVM functions to compile bitcode files to native code.
5441cf9926bSpatrick // Technically this can be delayed until we read bitcode files, but
5451cf9926bSpatrick // we don't bother to do lazily because the initialization is fast.
initLLVM()5461cf9926bSpatrick static void initLLVM() {
5471cf9926bSpatrick   InitializeAllTargets();
5481cf9926bSpatrick   InitializeAllTargetMCs();
5491cf9926bSpatrick   InitializeAllAsmPrinters();
5501cf9926bSpatrick   InitializeAllAsmParsers();
551bb684c34Spatrick }
552bb684c34Spatrick 
compileBitcodeFiles()553*dfe94b16Srobert static bool compileBitcodeFiles() {
5541cf9926bSpatrick   TimeTraceScope timeScope("LTO");
5551cf9926bSpatrick   auto *lto = make<BitcodeCompiler>();
5561cf9926bSpatrick   for (InputFile *file : inputFiles)
5571cf9926bSpatrick     if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
558*dfe94b16Srobert       if (!file->lazy)
5591cf9926bSpatrick         lto->add(*bitcodeFile);
5601cf9926bSpatrick 
561*dfe94b16Srobert   std::vector<ObjFile *> compiled = lto->compile();
562*dfe94b16Srobert   for (ObjFile *file : compiled)
5631cf9926bSpatrick     inputFiles.insert(file);
564*dfe94b16Srobert 
565*dfe94b16Srobert   return !compiled.empty();
5661cf9926bSpatrick }
5671cf9926bSpatrick 
5681cf9926bSpatrick // Replaces common symbols with defined symbols residing in __common sections.
5691cf9926bSpatrick // This function must be called after all symbol names are resolved (i.e. after
5701cf9926bSpatrick // all InputFiles have been loaded.) As a result, later operations won't see
5711cf9926bSpatrick // any CommonSymbols.
replaceCommonSymbols()5721cf9926bSpatrick static void replaceCommonSymbols() {
5731cf9926bSpatrick   TimeTraceScope timeScope("Replace common symbols");
5741cf9926bSpatrick   ConcatOutputSection *osec = nullptr;
5751cf9926bSpatrick   for (Symbol *sym : symtab->getSymbols()) {
5761cf9926bSpatrick     auto *common = dyn_cast<CommonSymbol>(sym);
5771cf9926bSpatrick     if (common == nullptr)
5781cf9926bSpatrick       continue;
5791cf9926bSpatrick 
5801cf9926bSpatrick     // Casting to size_t will truncate large values on 32-bit architectures,
5811cf9926bSpatrick     // but it's not really worth supporting the linking of 64-bit programs on
5821cf9926bSpatrick     // 32-bit archs.
5831cf9926bSpatrick     ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};
584*dfe94b16Srobert     // FIXME avoid creating one Section per symbol?
585*dfe94b16Srobert     auto *section =
586*dfe94b16Srobert         make<Section>(common->getFile(), segment_names::data,
587*dfe94b16Srobert                       section_names::common, S_ZEROFILL, /*addr=*/0);
588*dfe94b16Srobert     auto *isec = make<ConcatInputSection>(*section, data, common->align);
5891cf9926bSpatrick     if (!osec)
5901cf9926bSpatrick       osec = ConcatOutputSection::getOrCreateForInput(isec);
5911cf9926bSpatrick     isec->parent = osec;
5921cf9926bSpatrick     inputSections.push_back(isec);
5931cf9926bSpatrick 
5941cf9926bSpatrick     // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
5951cf9926bSpatrick     // and pass them on here.
596*dfe94b16Srobert     replaceSymbol<Defined>(
597*dfe94b16Srobert         sym, sym->getName(), common->getFile(), isec, /*value=*/0, common->size,
598*dfe94b16Srobert         /*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern,
599*dfe94b16Srobert         /*includeInSymtab=*/true, /*isThumb=*/false,
600*dfe94b16Srobert         /*isReferencedDynamically=*/false, /*noDeadStrip=*/false);
6011cf9926bSpatrick   }
6021cf9926bSpatrick }
6031cf9926bSpatrick 
initializeSectionRenameMap()6041cf9926bSpatrick static void initializeSectionRenameMap() {
6051cf9926bSpatrick   if (config->dataConst) {
6061cf9926bSpatrick     SmallVector<StringRef> v{section_names::got,
6071cf9926bSpatrick                              section_names::authGot,
6081cf9926bSpatrick                              section_names::authPtr,
6091cf9926bSpatrick                              section_names::nonLazySymbolPtr,
6101cf9926bSpatrick                              section_names::const_,
6111cf9926bSpatrick                              section_names::cfString,
6121cf9926bSpatrick                              section_names::moduleInitFunc,
6131cf9926bSpatrick                              section_names::moduleTermFunc,
6141cf9926bSpatrick                              section_names::objcClassList,
6151cf9926bSpatrick                              section_names::objcNonLazyClassList,
6161cf9926bSpatrick                              section_names::objcCatList,
6171cf9926bSpatrick                              section_names::objcNonLazyCatList,
6181cf9926bSpatrick                              section_names::objcProtoList,
619*dfe94b16Srobert                              section_names::objCImageInfo};
6201cf9926bSpatrick     for (StringRef s : v)
6211cf9926bSpatrick       config->sectionRenameMap[{segment_names::data, s}] = {
6221cf9926bSpatrick           segment_names::dataConst, s};
6231cf9926bSpatrick   }
6241cf9926bSpatrick   config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
6251cf9926bSpatrick       segment_names::text, section_names::text};
6261cf9926bSpatrick   config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
6271cf9926bSpatrick       config->dataConst ? segment_names::dataConst : segment_names::data,
6281cf9926bSpatrick       section_names::nonLazySymbolPtr};
6291cf9926bSpatrick }
6301cf9926bSpatrick 
toLowerDash(char x)6311cf9926bSpatrick static inline char toLowerDash(char x) {
6321cf9926bSpatrick   if (x >= 'A' && x <= 'Z')
6331cf9926bSpatrick     return x - 'A' + 'a';
6341cf9926bSpatrick   else if (x == ' ')
6351cf9926bSpatrick     return '-';
6361cf9926bSpatrick   return x;
6371cf9926bSpatrick }
6381cf9926bSpatrick 
lowerDash(StringRef s)6391cf9926bSpatrick static std::string lowerDash(StringRef s) {
6401cf9926bSpatrick   return std::string(map_iterator(s.begin(), toLowerDash),
6411cf9926bSpatrick                      map_iterator(s.end(), toLowerDash));
6421cf9926bSpatrick }
6431cf9926bSpatrick 
644*dfe94b16Srobert struct PlatformVersion {
645*dfe94b16Srobert   PlatformType platform = PLATFORM_UNKNOWN;
646*dfe94b16Srobert   llvm::VersionTuple minimum;
647*dfe94b16Srobert   llvm::VersionTuple sdk;
648*dfe94b16Srobert };
6491cf9926bSpatrick 
parsePlatformVersion(const Arg * arg)650*dfe94b16Srobert static PlatformVersion parsePlatformVersion(const Arg *arg) {
651*dfe94b16Srobert   assert(arg->getOption().getID() == OPT_platform_version);
6521cf9926bSpatrick   StringRef platformStr = arg->getValue(0);
6531cf9926bSpatrick   StringRef minVersionStr = arg->getValue(1);
6541cf9926bSpatrick   StringRef sdkVersionStr = arg->getValue(2);
6551cf9926bSpatrick 
656*dfe94b16Srobert   PlatformVersion platformVersion;
657*dfe94b16Srobert 
6581cf9926bSpatrick   // TODO(compnerd) see if we can generate this case list via XMACROS
659*dfe94b16Srobert   platformVersion.platform =
660*dfe94b16Srobert       StringSwitch<PlatformType>(lowerDash(platformStr))
661*dfe94b16Srobert           .Cases("macos", "1", PLATFORM_MACOS)
662*dfe94b16Srobert           .Cases("ios", "2", PLATFORM_IOS)
663*dfe94b16Srobert           .Cases("tvos", "3", PLATFORM_TVOS)
664*dfe94b16Srobert           .Cases("watchos", "4", PLATFORM_WATCHOS)
665*dfe94b16Srobert           .Cases("bridgeos", "5", PLATFORM_BRIDGEOS)
666*dfe94b16Srobert           .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST)
667*dfe94b16Srobert           .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR)
668*dfe94b16Srobert           .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR)
669*dfe94b16Srobert           .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR)
670*dfe94b16Srobert           .Cases("driverkit", "10", PLATFORM_DRIVERKIT)
671*dfe94b16Srobert           .Default(PLATFORM_UNKNOWN);
672*dfe94b16Srobert   if (platformVersion.platform == PLATFORM_UNKNOWN)
6731cf9926bSpatrick     error(Twine("malformed platform: ") + platformStr);
6741cf9926bSpatrick   // TODO: check validity of version strings, which varies by platform
6751cf9926bSpatrick   // NOTE: ld64 accepts version strings with 5 components
6761cf9926bSpatrick   // llvm::VersionTuple accepts no more than 4 components
6771cf9926bSpatrick   // Has Apple ever published version strings with 5 components?
678*dfe94b16Srobert   if (platformVersion.minimum.tryParse(minVersionStr))
6791cf9926bSpatrick     error(Twine("malformed minimum version: ") + minVersionStr);
680*dfe94b16Srobert   if (platformVersion.sdk.tryParse(sdkVersionStr))
6811cf9926bSpatrick     error(Twine("malformed sdk version: ") + sdkVersionStr);
682*dfe94b16Srobert   return platformVersion;
683*dfe94b16Srobert }
684*dfe94b16Srobert 
685*dfe94b16Srobert // Has the side-effect of setting Config::platformInfo.
parsePlatformVersions(const ArgList & args)686*dfe94b16Srobert static PlatformType parsePlatformVersions(const ArgList &args) {
687*dfe94b16Srobert   std::map<PlatformType, PlatformVersion> platformVersions;
688*dfe94b16Srobert   const PlatformVersion *lastVersionInfo = nullptr;
689*dfe94b16Srobert   for (const Arg *arg : args.filtered(OPT_platform_version)) {
690*dfe94b16Srobert     PlatformVersion version = parsePlatformVersion(arg);
691*dfe94b16Srobert 
692*dfe94b16Srobert     // For each platform, the last flag wins:
693*dfe94b16Srobert     // `-platform_version macos 2 3 -platform_version macos 4 5` has the same
694*dfe94b16Srobert     // effect as just passing `-platform_version macos 4 5`.
695*dfe94b16Srobert     // FIXME: ld64 warns on multiple flags for one platform. Should we?
696*dfe94b16Srobert     platformVersions[version.platform] = version;
697*dfe94b16Srobert     lastVersionInfo = &platformVersions[version.platform];
698*dfe94b16Srobert   }
699*dfe94b16Srobert 
700*dfe94b16Srobert   if (platformVersions.empty()) {
701*dfe94b16Srobert     error("must specify -platform_version");
702*dfe94b16Srobert     return PLATFORM_UNKNOWN;
703*dfe94b16Srobert   }
704*dfe94b16Srobert   if (platformVersions.size() > 2) {
705*dfe94b16Srobert     error("must specify -platform_version at most twice");
706*dfe94b16Srobert     return PLATFORM_UNKNOWN;
707*dfe94b16Srobert   }
708*dfe94b16Srobert   if (platformVersions.size() == 2) {
709*dfe94b16Srobert     bool isZipperedCatalyst = platformVersions.count(PLATFORM_MACOS) &&
710*dfe94b16Srobert                               platformVersions.count(PLATFORM_MACCATALYST);
711*dfe94b16Srobert 
712*dfe94b16Srobert     if (!isZipperedCatalyst) {
713*dfe94b16Srobert       error("lld supports writing zippered outputs only for "
714*dfe94b16Srobert             "macos and mac-catalyst");
715*dfe94b16Srobert     } else if (config->outputType != MH_DYLIB &&
716*dfe94b16Srobert                config->outputType != MH_BUNDLE) {
717*dfe94b16Srobert       error("writing zippered outputs only valid for -dylib and -bundle");
718*dfe94b16Srobert     } else {
719*dfe94b16Srobert       config->platformInfo.minimum = platformVersions[PLATFORM_MACOS].minimum;
720*dfe94b16Srobert       config->platformInfo.sdk = platformVersions[PLATFORM_MACOS].sdk;
721*dfe94b16Srobert       config->secondaryPlatformInfo = PlatformInfo{};
722*dfe94b16Srobert       config->secondaryPlatformInfo->minimum =
723*dfe94b16Srobert           platformVersions[PLATFORM_MACCATALYST].minimum;
724*dfe94b16Srobert       config->secondaryPlatformInfo->sdk =
725*dfe94b16Srobert           platformVersions[PLATFORM_MACCATALYST].sdk;
726*dfe94b16Srobert     }
727*dfe94b16Srobert     return PLATFORM_MACOS;
728*dfe94b16Srobert   }
729*dfe94b16Srobert 
730*dfe94b16Srobert   config->platformInfo.minimum = lastVersionInfo->minimum;
731*dfe94b16Srobert   config->platformInfo.sdk = lastVersionInfo->sdk;
732*dfe94b16Srobert   return lastVersionInfo->platform;
7331cf9926bSpatrick }
7341cf9926bSpatrick 
7351cf9926bSpatrick // Has the side-effect of setting Config::target.
createTargetInfo(InputArgList & args)7361cf9926bSpatrick static TargetInfo *createTargetInfo(InputArgList &args) {
7371cf9926bSpatrick   StringRef archName = args.getLastArgValue(OPT_arch);
738*dfe94b16Srobert   if (archName.empty()) {
739*dfe94b16Srobert     error("must specify -arch");
740*dfe94b16Srobert     return nullptr;
741*dfe94b16Srobert   }
7421cf9926bSpatrick 
743*dfe94b16Srobert   PlatformType platform = parsePlatformVersions(args);
7441cf9926bSpatrick   config->platformInfo.target =
7451cf9926bSpatrick       MachO::Target(getArchitectureFromName(archName), platform);
746*dfe94b16Srobert   if (config->secondaryPlatformInfo) {
747*dfe94b16Srobert     config->secondaryPlatformInfo->target =
748*dfe94b16Srobert         MachO::Target(getArchitectureFromName(archName), PLATFORM_MACCATALYST);
749*dfe94b16Srobert   }
7501cf9926bSpatrick 
751*dfe94b16Srobert   auto [cpuType, cpuSubtype] = getCPUTypeFromArchitecture(config->arch());
7521cf9926bSpatrick   switch (cpuType) {
7531cf9926bSpatrick   case CPU_TYPE_X86_64:
7541cf9926bSpatrick     return createX86_64TargetInfo();
7551cf9926bSpatrick   case CPU_TYPE_ARM64:
7561cf9926bSpatrick     return createARM64TargetInfo();
7571cf9926bSpatrick   case CPU_TYPE_ARM64_32:
7581cf9926bSpatrick     return createARM64_32TargetInfo();
7591cf9926bSpatrick   case CPU_TYPE_ARM:
7601cf9926bSpatrick     return createARMTargetInfo(cpuSubtype);
7611cf9926bSpatrick   default:
762*dfe94b16Srobert     error("missing or unsupported -arch " + archName);
763*dfe94b16Srobert     return nullptr;
7641cf9926bSpatrick   }
7651cf9926bSpatrick }
7661cf9926bSpatrick 
7671cf9926bSpatrick static UndefinedSymbolTreatment
getUndefinedSymbolTreatment(const ArgList & args)7681cf9926bSpatrick getUndefinedSymbolTreatment(const ArgList &args) {
7691cf9926bSpatrick   StringRef treatmentStr = args.getLastArgValue(OPT_undefined);
7701cf9926bSpatrick   auto treatment =
7711cf9926bSpatrick       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
7721cf9926bSpatrick           .Cases("error", "", UndefinedSymbolTreatment::error)
7731cf9926bSpatrick           .Case("warning", UndefinedSymbolTreatment::warning)
7741cf9926bSpatrick           .Case("suppress", UndefinedSymbolTreatment::suppress)
7751cf9926bSpatrick           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
7761cf9926bSpatrick           .Default(UndefinedSymbolTreatment::unknown);
7771cf9926bSpatrick   if (treatment == UndefinedSymbolTreatment::unknown) {
7781cf9926bSpatrick     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
7791cf9926bSpatrick          "', defaulting to 'error'");
7801cf9926bSpatrick     treatment = UndefinedSymbolTreatment::error;
7811cf9926bSpatrick   } else if (config->namespaceKind == NamespaceKind::twolevel &&
7821cf9926bSpatrick              (treatment == UndefinedSymbolTreatment::warning ||
7831cf9926bSpatrick               treatment == UndefinedSymbolTreatment::suppress)) {
7841cf9926bSpatrick     if (treatment == UndefinedSymbolTreatment::warning)
785*dfe94b16Srobert       fatal("'-undefined warning' only valid with '-flat_namespace'");
7861cf9926bSpatrick     else
787*dfe94b16Srobert       fatal("'-undefined suppress' only valid with '-flat_namespace'");
7881cf9926bSpatrick     treatment = UndefinedSymbolTreatment::error;
7891cf9926bSpatrick   }
7901cf9926bSpatrick   return treatment;
7911cf9926bSpatrick }
7921cf9926bSpatrick 
getICFLevel(const ArgList & args)7931cf9926bSpatrick static ICFLevel getICFLevel(const ArgList &args) {
7941cf9926bSpatrick   StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq);
7951cf9926bSpatrick   auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
7961cf9926bSpatrick                       .Cases("none", "", ICFLevel::none)
7971cf9926bSpatrick                       .Case("safe", ICFLevel::safe)
7981cf9926bSpatrick                       .Case("all", ICFLevel::all)
7991cf9926bSpatrick                       .Default(ICFLevel::unknown);
8001cf9926bSpatrick   if (icfLevel == ICFLevel::unknown) {
8011cf9926bSpatrick     warn(Twine("unknown --icf=OPTION `") + icfLevelStr +
8021cf9926bSpatrick          "', defaulting to `none'");
8031cf9926bSpatrick     icfLevel = ICFLevel::none;
8041cf9926bSpatrick   }
8051cf9926bSpatrick   return icfLevel;
8061cf9926bSpatrick }
8071cf9926bSpatrick 
getObjCStubsMode(const ArgList & args)808*dfe94b16Srobert static ObjCStubsMode getObjCStubsMode(const ArgList &args) {
809*dfe94b16Srobert   const Arg *arg = args.getLastArg(OPT_objc_stubs_fast, OPT_objc_stubs_small);
810*dfe94b16Srobert   if (!arg)
811*dfe94b16Srobert     return ObjCStubsMode::fast;
812*dfe94b16Srobert 
813*dfe94b16Srobert   if (arg->getOption().getID() == OPT_objc_stubs_small)
814*dfe94b16Srobert     warn("-objc_stubs_small is not yet implemented, defaulting to "
815*dfe94b16Srobert          "-objc_stubs_fast");
816*dfe94b16Srobert   return ObjCStubsMode::fast;
817*dfe94b16Srobert }
818*dfe94b16Srobert 
warnIfDeprecatedOption(const Option & opt)8191cf9926bSpatrick static void warnIfDeprecatedOption(const Option &opt) {
820bb684c34Spatrick   if (!opt.getGroup().isValid())
821bb684c34Spatrick     return;
822bb684c34Spatrick   if (opt.getGroup().getID() == OPT_grp_deprecated) {
823bb684c34Spatrick     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
824bb684c34Spatrick     warn(opt.getHelpText());
825bb684c34Spatrick   }
826bb684c34Spatrick }
827bb684c34Spatrick 
warnIfUnimplementedOption(const Option & opt)8281cf9926bSpatrick static void warnIfUnimplementedOption(const Option &opt) {
8291cf9926bSpatrick   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
830bb684c34Spatrick     return;
831bb684c34Spatrick   switch (opt.getGroup().getID()) {
832bb684c34Spatrick   case OPT_grp_deprecated:
833bb684c34Spatrick     // warn about deprecated options elsewhere
834bb684c34Spatrick     break;
835bb684c34Spatrick   case OPT_grp_undocumented:
836bb684c34Spatrick     warn("Option `" + opt.getPrefixedName() +
837bb684c34Spatrick          "' is undocumented. Should lld implement it?");
838bb684c34Spatrick     break;
839bb684c34Spatrick   case OPT_grp_obsolete:
840bb684c34Spatrick     warn("Option `" + opt.getPrefixedName() +
841bb684c34Spatrick          "' is obsolete. Please modernize your usage.");
842bb684c34Spatrick     break;
843bb684c34Spatrick   case OPT_grp_ignored:
844bb684c34Spatrick     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
845bb684c34Spatrick     break;
846*dfe94b16Srobert   case OPT_grp_ignored_silently:
847*dfe94b16Srobert     break;
848bb684c34Spatrick   default:
849bb684c34Spatrick     warn("Option `" + opt.getPrefixedName() +
850bb684c34Spatrick          "' is not yet implemented. Stay tuned...");
851bb684c34Spatrick     break;
852bb684c34Spatrick   }
853bb684c34Spatrick }
854bb684c34Spatrick 
getReproduceOption(InputArgList & args)8551cf9926bSpatrick static const char *getReproduceOption(InputArgList &args) {
8561cf9926bSpatrick   if (const Arg *arg = args.getLastArg(OPT_reproduce))
8571cf9926bSpatrick     return arg->getValue();
8581cf9926bSpatrick   return getenv("LLD_REPRODUCE");
8591cf9926bSpatrick }
8601cf9926bSpatrick 
861*dfe94b16Srobert // Parse options of the form "old;new".
getOldNewOptions(opt::InputArgList & args,unsigned id)862*dfe94b16Srobert static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
863*dfe94b16Srobert                                                         unsigned id) {
864*dfe94b16Srobert   auto *arg = args.getLastArg(id);
865*dfe94b16Srobert   if (!arg)
866*dfe94b16Srobert     return {"", ""};
867*dfe94b16Srobert 
868*dfe94b16Srobert   StringRef s = arg->getValue();
869*dfe94b16Srobert   std::pair<StringRef, StringRef> ret = s.split(';');
870*dfe94b16Srobert   if (ret.second.empty())
871*dfe94b16Srobert     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
872*dfe94b16Srobert   return ret;
873*dfe94b16Srobert }
874*dfe94b16Srobert 
parseClangOption(StringRef opt,const Twine & msg)8751cf9926bSpatrick static void parseClangOption(StringRef opt, const Twine &msg) {
8761cf9926bSpatrick   std::string err;
8771cf9926bSpatrick   raw_string_ostream os(err);
8781cf9926bSpatrick 
8791cf9926bSpatrick   const char *argv[] = {"lld", opt.data()};
8801cf9926bSpatrick   if (cl::ParseCommandLineOptions(2, argv, "", &os))
8811cf9926bSpatrick     return;
8821cf9926bSpatrick   os.flush();
8831cf9926bSpatrick   error(msg + ": " + StringRef(err).trim());
8841cf9926bSpatrick }
8851cf9926bSpatrick 
parseDylibVersion(const ArgList & args,unsigned id)8861cf9926bSpatrick static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
8871cf9926bSpatrick   const Arg *arg = args.getLastArg(id);
8881cf9926bSpatrick   if (!arg)
8891cf9926bSpatrick     return 0;
8901cf9926bSpatrick 
8911cf9926bSpatrick   if (config->outputType != MH_DYLIB) {
8921cf9926bSpatrick     error(arg->getAsString(args) + ": only valid with -dylib");
8931cf9926bSpatrick     return 0;
8941cf9926bSpatrick   }
8951cf9926bSpatrick 
8961cf9926bSpatrick   PackedVersion version;
8971cf9926bSpatrick   if (!version.parse32(arg->getValue())) {
8981cf9926bSpatrick     error(arg->getAsString(args) + ": malformed version");
8991cf9926bSpatrick     return 0;
9001cf9926bSpatrick   }
9011cf9926bSpatrick 
9021cf9926bSpatrick   return version.rawValue();
9031cf9926bSpatrick }
9041cf9926bSpatrick 
parseProtection(StringRef protStr)9051cf9926bSpatrick static uint32_t parseProtection(StringRef protStr) {
9061cf9926bSpatrick   uint32_t prot = 0;
9071cf9926bSpatrick   for (char c : protStr) {
9081cf9926bSpatrick     switch (c) {
9091cf9926bSpatrick     case 'r':
9101cf9926bSpatrick       prot |= VM_PROT_READ;
9111cf9926bSpatrick       break;
9121cf9926bSpatrick     case 'w':
9131cf9926bSpatrick       prot |= VM_PROT_WRITE;
9141cf9926bSpatrick       break;
9151cf9926bSpatrick     case 'x':
9161cf9926bSpatrick       prot |= VM_PROT_EXECUTE;
9171cf9926bSpatrick       break;
9181cf9926bSpatrick     case '-':
9191cf9926bSpatrick       break;
9201cf9926bSpatrick     default:
9211cf9926bSpatrick       error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);
9221cf9926bSpatrick       return 0;
9231cf9926bSpatrick     }
9241cf9926bSpatrick   }
9251cf9926bSpatrick   return prot;
9261cf9926bSpatrick }
9271cf9926bSpatrick 
parseSectAlign(const opt::InputArgList & args)9281cf9926bSpatrick static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
9291cf9926bSpatrick   std::vector<SectionAlign> sectAligns;
9301cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_sectalign)) {
9311cf9926bSpatrick     StringRef segName = arg->getValue(0);
9321cf9926bSpatrick     StringRef sectName = arg->getValue(1);
9331cf9926bSpatrick     StringRef alignStr = arg->getValue(2);
9341cf9926bSpatrick     if (alignStr.startswith("0x") || alignStr.startswith("0X"))
9351cf9926bSpatrick       alignStr = alignStr.drop_front(2);
9361cf9926bSpatrick     uint32_t align;
9371cf9926bSpatrick     if (alignStr.getAsInteger(16, align)) {
9381cf9926bSpatrick       error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +
9391cf9926bSpatrick             "' as number");
9401cf9926bSpatrick       continue;
9411cf9926bSpatrick     }
9421cf9926bSpatrick     if (!isPowerOf2_32(align)) {
9431cf9926bSpatrick       error("-sectalign: '" + StringRef(arg->getValue(2)) +
9441cf9926bSpatrick             "' (in base 16) not a power of two");
9451cf9926bSpatrick       continue;
9461cf9926bSpatrick     }
9471cf9926bSpatrick     sectAligns.push_back({segName, sectName, align});
9481cf9926bSpatrick   }
9491cf9926bSpatrick   return sectAligns;
9501cf9926bSpatrick }
9511cf9926bSpatrick 
removeSimulator(PlatformType platform)952*dfe94b16Srobert PlatformType macho::removeSimulator(PlatformType platform) {
9531cf9926bSpatrick   switch (platform) {
954*dfe94b16Srobert   case PLATFORM_IOSSIMULATOR:
955*dfe94b16Srobert     return PLATFORM_IOS;
956*dfe94b16Srobert   case PLATFORM_TVOSSIMULATOR:
957*dfe94b16Srobert     return PLATFORM_TVOS;
958*dfe94b16Srobert   case PLATFORM_WATCHOSSIMULATOR:
959*dfe94b16Srobert     return PLATFORM_WATCHOS;
9601cf9926bSpatrick   default:
9611cf9926bSpatrick     return platform;
9621cf9926bSpatrick   }
9631cf9926bSpatrick }
9641cf9926bSpatrick 
supportsNoPie()965*dfe94b16Srobert static bool supportsNoPie() {
966*dfe94b16Srobert   return !(config->arch() == AK_arm64 || config->arch() == AK_arm64e ||
967*dfe94b16Srobert            config->arch() == AK_arm64_32);
968*dfe94b16Srobert }
969*dfe94b16Srobert 
shouldAdhocSignByDefault(Architecture arch,PlatformType platform)970*dfe94b16Srobert static bool shouldAdhocSignByDefault(Architecture arch, PlatformType platform) {
971*dfe94b16Srobert   if (arch != AK_arm64 && arch != AK_arm64e)
972*dfe94b16Srobert     return false;
973*dfe94b16Srobert 
974*dfe94b16Srobert   return platform == PLATFORM_MACOS || platform == PLATFORM_IOSSIMULATOR ||
975*dfe94b16Srobert          platform == PLATFORM_TVOSSIMULATOR ||
976*dfe94b16Srobert          platform == PLATFORM_WATCHOSSIMULATOR;
977*dfe94b16Srobert }
978*dfe94b16Srobert 
dataConstDefault(const InputArgList & args)9791cf9926bSpatrick static bool dataConstDefault(const InputArgList &args) {
980*dfe94b16Srobert   static const std::array<std::pair<PlatformType, VersionTuple>, 5> minVersion =
981*dfe94b16Srobert       {{{PLATFORM_MACOS, VersionTuple(10, 15)},
982*dfe94b16Srobert         {PLATFORM_IOS, VersionTuple(13, 0)},
983*dfe94b16Srobert         {PLATFORM_TVOS, VersionTuple(13, 0)},
984*dfe94b16Srobert         {PLATFORM_WATCHOS, VersionTuple(6, 0)},
985*dfe94b16Srobert         {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}}};
986*dfe94b16Srobert   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
9871cf9926bSpatrick   auto it = llvm::find_if(minVersion,
9881cf9926bSpatrick                           [&](const auto &p) { return p.first == platform; });
9891cf9926bSpatrick   if (it != minVersion.end())
9901cf9926bSpatrick     if (config->platformInfo.minimum < it->second)
9911cf9926bSpatrick       return false;
9921cf9926bSpatrick 
9931cf9926bSpatrick   switch (config->outputType) {
9941cf9926bSpatrick   case MH_EXECUTE:
995*dfe94b16Srobert     return !(args.hasArg(OPT_no_pie) && supportsNoPie());
9961cf9926bSpatrick   case MH_BUNDLE:
9971cf9926bSpatrick     // FIXME: return false when -final_name ...
9981cf9926bSpatrick     // has prefix "/System/Library/UserEventPlugins/"
9991cf9926bSpatrick     // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
10001cf9926bSpatrick     return true;
10011cf9926bSpatrick   case MH_DYLIB:
10021cf9926bSpatrick     return true;
10031cf9926bSpatrick   case MH_OBJECT:
10041cf9926bSpatrick     return false;
10051cf9926bSpatrick   default:
10061cf9926bSpatrick     llvm_unreachable(
10071cf9926bSpatrick         "unsupported output type for determining data-const default");
10081cf9926bSpatrick   }
10091cf9926bSpatrick   return false;
10101cf9926bSpatrick }
10111cf9926bSpatrick 
shouldEmitChainedFixups(const InputArgList & args)1012*dfe94b16Srobert static bool shouldEmitChainedFixups(const InputArgList &args) {
1013*dfe94b16Srobert   const Arg *arg = args.getLastArg(OPT_fixup_chains, OPT_no_fixup_chains);
1014*dfe94b16Srobert   if (arg && arg->getOption().matches(OPT_no_fixup_chains))
1015*dfe94b16Srobert     return false;
1016*dfe94b16Srobert 
1017*dfe94b16Srobert   bool isRequested = arg != nullptr;
1018*dfe94b16Srobert 
1019*dfe94b16Srobert   // Version numbers taken from the Xcode 13.3 release notes.
1020*dfe94b16Srobert   static const std::array<std::pair<PlatformType, VersionTuple>, 4> minVersion =
1021*dfe94b16Srobert       {{{PLATFORM_MACOS, VersionTuple(11, 0)},
1022*dfe94b16Srobert         {PLATFORM_IOS, VersionTuple(13, 4)},
1023*dfe94b16Srobert         {PLATFORM_TVOS, VersionTuple(14, 0)},
1024*dfe94b16Srobert         {PLATFORM_WATCHOS, VersionTuple(7, 0)}}};
1025*dfe94b16Srobert   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
1026*dfe94b16Srobert   auto it = llvm::find_if(minVersion,
1027*dfe94b16Srobert                           [&](const auto &p) { return p.first == platform; });
1028*dfe94b16Srobert   if (it != minVersion.end() && it->second > config->platformInfo.minimum) {
1029*dfe94b16Srobert     if (!isRequested)
1030*dfe94b16Srobert       return false;
1031*dfe94b16Srobert 
1032*dfe94b16Srobert     warn("-fixup_chains requires " + getPlatformName(config->platform()) + " " +
1033*dfe94b16Srobert          it->second.getAsString() + ", which is newer than target minimum of " +
1034*dfe94b16Srobert          config->platformInfo.minimum.getAsString());
1035*dfe94b16Srobert   }
1036*dfe94b16Srobert 
1037*dfe94b16Srobert   if (!is_contained({AK_x86_64, AK_x86_64h, AK_arm64}, config->arch())) {
1038*dfe94b16Srobert     if (isRequested)
1039*dfe94b16Srobert       error("-fixup_chains is only supported on x86_64 and arm64 targets");
1040*dfe94b16Srobert     return false;
1041*dfe94b16Srobert   }
1042*dfe94b16Srobert 
1043*dfe94b16Srobert   if (!config->isPic) {
1044*dfe94b16Srobert     if (isRequested)
1045*dfe94b16Srobert       error("-fixup_chains is incompatible with -no_pie");
1046*dfe94b16Srobert     return false;
1047*dfe94b16Srobert   }
1048*dfe94b16Srobert 
1049*dfe94b16Srobert   // TODO: Enable by default once stable.
1050*dfe94b16Srobert   return isRequested;
1051*dfe94b16Srobert }
1052*dfe94b16Srobert 
clear()10531cf9926bSpatrick void SymbolPatterns::clear() {
10541cf9926bSpatrick   literals.clear();
10551cf9926bSpatrick   globs.clear();
10561cf9926bSpatrick }
10571cf9926bSpatrick 
insert(StringRef symbolName)10581cf9926bSpatrick void SymbolPatterns::insert(StringRef symbolName) {
10591cf9926bSpatrick   if (symbolName.find_first_of("*?[]") == StringRef::npos)
10601cf9926bSpatrick     literals.insert(CachedHashStringRef(symbolName));
10611cf9926bSpatrick   else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))
10621cf9926bSpatrick     globs.emplace_back(*pattern);
10631cf9926bSpatrick   else
10641cf9926bSpatrick     error("invalid symbol-name pattern: " + symbolName);
10651cf9926bSpatrick }
10661cf9926bSpatrick 
matchLiteral(StringRef symbolName) const10671cf9926bSpatrick bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
10681cf9926bSpatrick   return literals.contains(CachedHashStringRef(symbolName));
10691cf9926bSpatrick }
10701cf9926bSpatrick 
matchGlob(StringRef symbolName) const10711cf9926bSpatrick bool SymbolPatterns::matchGlob(StringRef symbolName) const {
10721cf9926bSpatrick   for (const GlobPattern &glob : globs)
10731cf9926bSpatrick     if (glob.match(symbolName))
10741cf9926bSpatrick       return true;
10751cf9926bSpatrick   return false;
10761cf9926bSpatrick }
10771cf9926bSpatrick 
match(StringRef symbolName) const10781cf9926bSpatrick bool SymbolPatterns::match(StringRef symbolName) const {
10791cf9926bSpatrick   return matchLiteral(symbolName) || matchGlob(symbolName);
10801cf9926bSpatrick }
10811cf9926bSpatrick 
parseSymbolPatternsFile(const Arg * arg,SymbolPatterns & symbolPatterns)1082*dfe94b16Srobert static void parseSymbolPatternsFile(const Arg *arg,
1083*dfe94b16Srobert                                     SymbolPatterns &symbolPatterns) {
10841cf9926bSpatrick   StringRef path = arg->getValue();
1085*dfe94b16Srobert   std::optional<MemoryBufferRef> buffer = readFile(path);
10861cf9926bSpatrick   if (!buffer) {
10871cf9926bSpatrick     error("Could not read symbol file: " + path);
1088*dfe94b16Srobert     return;
10891cf9926bSpatrick   }
10901cf9926bSpatrick   MemoryBufferRef mbref = *buffer;
10911cf9926bSpatrick   for (StringRef line : args::getLines(mbref)) {
10921cf9926bSpatrick     line = line.take_until([](char c) { return c == '#'; }).trim();
10931cf9926bSpatrick     if (!line.empty())
10941cf9926bSpatrick       symbolPatterns.insert(line);
10951cf9926bSpatrick   }
10961cf9926bSpatrick }
1097*dfe94b16Srobert 
handleSymbolPatterns(InputArgList & args,SymbolPatterns & symbolPatterns,unsigned singleOptionCode,unsigned listFileOptionCode)1098*dfe94b16Srobert static void handleSymbolPatterns(InputArgList &args,
1099*dfe94b16Srobert                                  SymbolPatterns &symbolPatterns,
1100*dfe94b16Srobert                                  unsigned singleOptionCode,
1101*dfe94b16Srobert                                  unsigned listFileOptionCode) {
1102*dfe94b16Srobert   for (const Arg *arg : args.filtered(singleOptionCode))
1103*dfe94b16Srobert     symbolPatterns.insert(arg->getValue());
1104*dfe94b16Srobert   for (const Arg *arg : args.filtered(listFileOptionCode))
1105*dfe94b16Srobert     parseSymbolPatternsFile(arg, symbolPatterns);
11061cf9926bSpatrick }
11071cf9926bSpatrick 
createFiles(const InputArgList & args)1108*dfe94b16Srobert static void createFiles(const InputArgList &args) {
11091cf9926bSpatrick   TimeTraceScope timeScope("Load input files");
11101cf9926bSpatrick   // This loop should be reserved for options whose exact ordering matters.
11111cf9926bSpatrick   // Other options should be handled via filtered() and/or getLastArg().
1112*dfe94b16Srobert   bool isLazy = false;
11131cf9926bSpatrick   for (const Arg *arg : args) {
11141cf9926bSpatrick     const Option &opt = arg->getOption();
11151cf9926bSpatrick     warnIfDeprecatedOption(opt);
11161cf9926bSpatrick     warnIfUnimplementedOption(opt);
11171cf9926bSpatrick 
11181cf9926bSpatrick     switch (opt.getID()) {
11191cf9926bSpatrick     case OPT_INPUT:
1120*dfe94b16Srobert       addFile(rerootPath(arg->getValue()), LoadType::CommandLine, isLazy);
11211cf9926bSpatrick       break;
11221cf9926bSpatrick     case OPT_needed_library:
11231cf9926bSpatrick       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1124*dfe94b16Srobert               addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))
11251cf9926bSpatrick         dylibFile->forceNeeded = true;
11261cf9926bSpatrick       break;
11271cf9926bSpatrick     case OPT_reexport_library:
1128*dfe94b16Srobert       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1129*dfe94b16Srobert               addFile(rerootPath(arg->getValue()), LoadType::CommandLine))) {
11301cf9926bSpatrick         config->hasReexports = true;
11311cf9926bSpatrick         dylibFile->reexport = true;
11321cf9926bSpatrick       }
11331cf9926bSpatrick       break;
11341cf9926bSpatrick     case OPT_weak_library:
11351cf9926bSpatrick       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1136*dfe94b16Srobert               addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))
11371cf9926bSpatrick         dylibFile->forceWeakImport = true;
11381cf9926bSpatrick       break;
11391cf9926bSpatrick     case OPT_filelist:
1140*dfe94b16Srobert       addFileList(arg->getValue(), isLazy);
11411cf9926bSpatrick       break;
11421cf9926bSpatrick     case OPT_force_load:
1143*dfe94b16Srobert       addFile(rerootPath(arg->getValue()), LoadType::CommandLineForce);
1144*dfe94b16Srobert       break;
1145*dfe94b16Srobert     case OPT_load_hidden:
1146*dfe94b16Srobert       addFile(rerootPath(arg->getValue()), LoadType::CommandLine,
1147*dfe94b16Srobert               /*isLazy=*/false, /*isExplicit=*/true, /*isBundleLoader=*/false,
1148*dfe94b16Srobert               /*isForceHidden=*/true);
11491cf9926bSpatrick       break;
11501cf9926bSpatrick     case OPT_l:
11511cf9926bSpatrick     case OPT_needed_l:
11521cf9926bSpatrick     case OPT_reexport_l:
11531cf9926bSpatrick     case OPT_weak_l:
1154*dfe94b16Srobert     case OPT_hidden_l:
11551cf9926bSpatrick       addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,
11561cf9926bSpatrick                  opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,
1157*dfe94b16Srobert                  opt.getID() == OPT_hidden_l,
1158*dfe94b16Srobert                  /*isExplicit=*/true, LoadType::CommandLine);
11591cf9926bSpatrick       break;
11601cf9926bSpatrick     case OPT_framework:
11611cf9926bSpatrick     case OPT_needed_framework:
11621cf9926bSpatrick     case OPT_reexport_framework:
11631cf9926bSpatrick     case OPT_weak_framework:
11641cf9926bSpatrick       addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,
11651cf9926bSpatrick                    opt.getID() == OPT_weak_framework,
1166*dfe94b16Srobert                    opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
1167*dfe94b16Srobert                    LoadType::CommandLine);
1168*dfe94b16Srobert       break;
1169*dfe94b16Srobert     case OPT_start_lib:
1170*dfe94b16Srobert       if (isLazy)
1171*dfe94b16Srobert         error("nested --start-lib");
1172*dfe94b16Srobert       isLazy = true;
1173*dfe94b16Srobert       break;
1174*dfe94b16Srobert     case OPT_end_lib:
1175*dfe94b16Srobert       if (!isLazy)
1176*dfe94b16Srobert         error("stray --end-lib");
1177*dfe94b16Srobert       isLazy = false;
11781cf9926bSpatrick       break;
11791cf9926bSpatrick     default:
11801cf9926bSpatrick       break;
11811cf9926bSpatrick     }
11821cf9926bSpatrick   }
11831cf9926bSpatrick }
11841cf9926bSpatrick 
gatherInputSections()11851cf9926bSpatrick static void gatherInputSections() {
11861cf9926bSpatrick   TimeTraceScope timeScope("Gathering input sections");
11871cf9926bSpatrick   int inputOrder = 0;
11881cf9926bSpatrick   for (const InputFile *file : inputFiles) {
1189*dfe94b16Srobert     for (const Section *section : file->sections) {
1190*dfe94b16Srobert       // Compact unwind entries require special handling elsewhere. (In
1191*dfe94b16Srobert       // contrast, EH frames are handled like regular ConcatInputSections.)
1192*dfe94b16Srobert       if (section->name == section_names::compactUnwind)
1193*dfe94b16Srobert         continue;
11941cf9926bSpatrick       ConcatOutputSection *osec = nullptr;
1195*dfe94b16Srobert       for (const Subsection &subsection : section->subsections) {
1196*dfe94b16Srobert         if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) {
11971cf9926bSpatrick           if (isec->isCoalescedWeak())
11981cf9926bSpatrick             continue;
1199*dfe94b16Srobert           if (config->emitInitOffsets &&
1200*dfe94b16Srobert               sectionType(isec->getFlags()) == S_MOD_INIT_FUNC_POINTERS) {
1201*dfe94b16Srobert             in.initOffsets->addInput(isec);
12021cf9926bSpatrick             continue;
12031cf9926bSpatrick           }
12041cf9926bSpatrick           isec->outSecOff = inputOrder++;
12051cf9926bSpatrick           if (!osec)
12061cf9926bSpatrick             osec = ConcatOutputSection::getOrCreateForInput(isec);
12071cf9926bSpatrick           isec->parent = osec;
12081cf9926bSpatrick           inputSections.push_back(isec);
1209*dfe94b16Srobert         } else if (auto *isec =
1210*dfe94b16Srobert                        dyn_cast<CStringInputSection>(subsection.isec)) {
1211*dfe94b16Srobert           if (isec->getName() == section_names::objcMethname) {
1212*dfe94b16Srobert             if (in.objcMethnameSection->inputOrder == UnspecifiedInputOrder)
1213*dfe94b16Srobert               in.objcMethnameSection->inputOrder = inputOrder++;
1214*dfe94b16Srobert             in.objcMethnameSection->addInput(isec);
1215*dfe94b16Srobert           } else {
12161cf9926bSpatrick             if (in.cStringSection->inputOrder == UnspecifiedInputOrder)
12171cf9926bSpatrick               in.cStringSection->inputOrder = inputOrder++;
12181cf9926bSpatrick             in.cStringSection->addInput(isec);
1219*dfe94b16Srobert           }
1220*dfe94b16Srobert         } else if (auto *isec =
1221*dfe94b16Srobert                        dyn_cast<WordLiteralInputSection>(subsection.isec)) {
12221cf9926bSpatrick           if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder)
12231cf9926bSpatrick             in.wordLiteralSection->inputOrder = inputOrder++;
12241cf9926bSpatrick           in.wordLiteralSection->addInput(isec);
12251cf9926bSpatrick         } else {
12261cf9926bSpatrick           llvm_unreachable("unexpected input section kind");
12271cf9926bSpatrick         }
12281cf9926bSpatrick       }
12291cf9926bSpatrick     }
1230*dfe94b16Srobert     if (!file->objCImageInfo.empty())
1231*dfe94b16Srobert       in.objCImageInfo->addFile(file);
12321cf9926bSpatrick   }
12331cf9926bSpatrick   assert(inputOrder <= UnspecifiedInputOrder);
12341cf9926bSpatrick }
12351cf9926bSpatrick 
foldIdenticalLiterals()12361cf9926bSpatrick static void foldIdenticalLiterals() {
1237*dfe94b16Srobert   TimeTraceScope timeScope("Fold identical literals");
12381cf9926bSpatrick   // We always create a cStringSection, regardless of whether dedupLiterals is
12391cf9926bSpatrick   // true. If it isn't, we simply create a non-deduplicating CStringSection.
12401cf9926bSpatrick   // Either way, we must unconditionally finalize it here.
12411cf9926bSpatrick   in.cStringSection->finalizeContents();
1242*dfe94b16Srobert   in.objcMethnameSection->finalizeContents();
12431cf9926bSpatrick   in.wordLiteralSection->finalizeContents();
12441cf9926bSpatrick }
12451cf9926bSpatrick 
addSynthenticMethnames()1246*dfe94b16Srobert static void addSynthenticMethnames() {
1247*dfe94b16Srobert   std::string &data = *make<std::string>();
1248*dfe94b16Srobert   llvm::raw_string_ostream os(data);
1249*dfe94b16Srobert   const int prefixLength = ObjCStubsSection::symbolPrefix.size();
1250*dfe94b16Srobert   for (Symbol *sym : symtab->getSymbols())
1251*dfe94b16Srobert     if (isa<Undefined>(sym))
1252*dfe94b16Srobert       if (sym->getName().startswith(ObjCStubsSection::symbolPrefix))
1253*dfe94b16Srobert         os << sym->getName().drop_front(prefixLength) << '\0';
1254*dfe94b16Srobert 
1255*dfe94b16Srobert   if (data.empty())
1256*dfe94b16Srobert     return;
1257*dfe94b16Srobert 
1258*dfe94b16Srobert   const auto *buf = reinterpret_cast<const uint8_t *>(data.c_str());
1259*dfe94b16Srobert   Section &section = *make<Section>(/*file=*/nullptr, segment_names::text,
1260*dfe94b16Srobert                                     section_names::objcMethname,
1261*dfe94b16Srobert                                     S_CSTRING_LITERALS, /*addr=*/0);
1262*dfe94b16Srobert 
1263*dfe94b16Srobert   auto *isec =
1264*dfe94b16Srobert       make<CStringInputSection>(section, ArrayRef<uint8_t>{buf, data.size()},
1265*dfe94b16Srobert                                 /*align=*/1, /*dedupLiterals=*/true);
1266*dfe94b16Srobert   isec->splitIntoPieces();
1267*dfe94b16Srobert   for (auto &piece : isec->pieces)
1268*dfe94b16Srobert     piece.live = true;
1269*dfe94b16Srobert   section.subsections.push_back({0, isec});
1270*dfe94b16Srobert   in.objcMethnameSection->addInput(isec);
1271*dfe94b16Srobert   in.objcMethnameSection->isec->markLive(0);
1272*dfe94b16Srobert }
1273*dfe94b16Srobert 
referenceStubBinder()12741cf9926bSpatrick static void referenceStubBinder() {
12751cf9926bSpatrick   bool needsStubHelper = config->outputType == MH_DYLIB ||
12761cf9926bSpatrick                          config->outputType == MH_EXECUTE ||
12771cf9926bSpatrick                          config->outputType == MH_BUNDLE;
12781cf9926bSpatrick   if (!needsStubHelper || !symtab->find("dyld_stub_binder"))
12791cf9926bSpatrick     return;
12801cf9926bSpatrick 
12811cf9926bSpatrick   // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
12821cf9926bSpatrick   // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
12831cf9926bSpatrick   // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
12841cf9926bSpatrick   // isn't needed for correctness, but the presence of that symbol suppresses
12851cf9926bSpatrick   // "no symbols" diagnostics from `nm`.
1286*dfe94b16Srobert   // StubHelperSection::setUp() adds a reference and errors out if
12871cf9926bSpatrick   // dyld_stub_binder doesn't exist in case it is actually needed.
12881cf9926bSpatrick   symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false);
12891cf9926bSpatrick }
12901cf9926bSpatrick 
createAliases()1291*dfe94b16Srobert static void createAliases() {
1292*dfe94b16Srobert   for (const auto &pair : config->aliasedSymbols) {
1293*dfe94b16Srobert     if (const auto &sym = symtab->find(pair.first)) {
1294*dfe94b16Srobert       if (const auto &defined = dyn_cast<Defined>(sym)) {
1295*dfe94b16Srobert         symtab->aliasDefined(defined, pair.second, defined->getFile())
1296*dfe94b16Srobert             ->noDeadStrip = true;
1297*dfe94b16Srobert       } else {
1298*dfe94b16Srobert         error("TODO: support aliasing to symbols of kind " +
1299*dfe94b16Srobert               Twine(sym->kind()));
1300*dfe94b16Srobert       }
1301*dfe94b16Srobert     } else {
1302*dfe94b16Srobert       warn("undefined base symbol '" + pair.first + "' for alias '" +
1303*dfe94b16Srobert            pair.second + "'\n");
1304*dfe94b16Srobert     }
1305*dfe94b16Srobert   }
1306bb684c34Spatrick 
1307*dfe94b16Srobert   for (const InputFile *file : inputFiles) {
1308*dfe94b16Srobert     if (auto *objFile = dyn_cast<ObjFile>(file)) {
1309*dfe94b16Srobert       for (const AliasSymbol *alias : objFile->aliases) {
1310*dfe94b16Srobert         if (const auto &aliased = symtab->find(alias->getAliasedName())) {
1311*dfe94b16Srobert           if (const auto &defined = dyn_cast<Defined>(aliased)) {
1312*dfe94b16Srobert             symtab->aliasDefined(defined, alias->getName(), alias->getFile(),
1313*dfe94b16Srobert                                  alias->privateExtern);
1314*dfe94b16Srobert           } else {
1315*dfe94b16Srobert             // Common, dylib, and undefined symbols are all valid alias
1316*dfe94b16Srobert             // referents (undefineds can become valid Defined symbols later on
1317*dfe94b16Srobert             // in the link.)
1318*dfe94b16Srobert             error("TODO: support aliasing to symbols of kind " +
1319*dfe94b16Srobert                   Twine(aliased->kind()));
1320*dfe94b16Srobert           }
1321*dfe94b16Srobert         } else {
1322*dfe94b16Srobert           // This shouldn't happen since MC generates undefined symbols to
1323*dfe94b16Srobert           // represent the alias referents. Thus we fatal() instead of just
1324*dfe94b16Srobert           // warning here.
1325*dfe94b16Srobert           fatal("unable to find alias referent " + alias->getAliasedName() +
1326*dfe94b16Srobert                 " for " + alias->getName());
1327*dfe94b16Srobert         }
1328*dfe94b16Srobert       }
1329*dfe94b16Srobert     }
1330*dfe94b16Srobert   }
1331*dfe94b16Srobert }
13321cf9926bSpatrick 
handleExplicitExports()1333*dfe94b16Srobert static void handleExplicitExports() {
1334*dfe94b16Srobert   if (config->hasExplicitExports) {
1335*dfe94b16Srobert     parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1336*dfe94b16Srobert       if (auto *defined = dyn_cast<Defined>(sym)) {
1337*dfe94b16Srobert         StringRef symbolName = defined->getName();
1338*dfe94b16Srobert         if (config->exportedSymbols.match(symbolName)) {
1339*dfe94b16Srobert           if (defined->privateExtern) {
1340*dfe94b16Srobert             if (defined->weakDefCanBeHidden) {
1341*dfe94b16Srobert               // weak_def_can_be_hidden symbols behave similarly to
1342*dfe94b16Srobert               // private_extern symbols in most cases, except for when
1343*dfe94b16Srobert               // it is explicitly exported.
1344*dfe94b16Srobert               // The former can be exported but the latter cannot.
1345*dfe94b16Srobert               defined->privateExtern = false;
1346*dfe94b16Srobert             } else {
1347*dfe94b16Srobert               warn("cannot export hidden symbol " + toString(*defined) +
1348*dfe94b16Srobert                    "\n>>> defined in " + toString(defined->getFile()));
1349*dfe94b16Srobert             }
1350*dfe94b16Srobert           }
1351*dfe94b16Srobert         } else {
1352*dfe94b16Srobert           defined->privateExtern = true;
1353*dfe94b16Srobert         }
1354*dfe94b16Srobert       }
1355*dfe94b16Srobert     });
1356*dfe94b16Srobert   } else if (!config->unexportedSymbols.empty()) {
1357*dfe94b16Srobert     parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1358*dfe94b16Srobert       if (auto *defined = dyn_cast<Defined>(sym))
1359*dfe94b16Srobert         if (config->unexportedSymbols.match(defined->getName()))
1360*dfe94b16Srobert           defined->privateExtern = true;
1361*dfe94b16Srobert     });
1362*dfe94b16Srobert   }
1363*dfe94b16Srobert }
1364*dfe94b16Srobert 
link(ArrayRef<const char * > argsArr,llvm::raw_ostream & stdoutOS,llvm::raw_ostream & stderrOS,bool exitEarly,bool disableOutput)1365*dfe94b16Srobert bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1366*dfe94b16Srobert                  llvm::raw_ostream &stderrOS, bool exitEarly,
1367*dfe94b16Srobert                  bool disableOutput) {
1368*dfe94b16Srobert   // This driver-specific context will be freed later by lldMain().
1369*dfe94b16Srobert   auto *ctx = new CommonLinkerContext;
1370*dfe94b16Srobert 
1371*dfe94b16Srobert   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1372*dfe94b16Srobert   ctx->e.cleanupCallback = []() {
1373*dfe94b16Srobert     resolvedFrameworks.clear();
1374*dfe94b16Srobert     resolvedLibraries.clear();
1375*dfe94b16Srobert     cachedReads.clear();
1376*dfe94b16Srobert     concatOutputSections.clear();
1377*dfe94b16Srobert     inputFiles.clear();
1378*dfe94b16Srobert     inputSections.clear();
1379*dfe94b16Srobert     loadedArchives.clear();
1380*dfe94b16Srobert     loadedObjectFrameworks.clear();
1381*dfe94b16Srobert     missingAutolinkWarnings.clear();
1382*dfe94b16Srobert     syntheticSections.clear();
1383*dfe94b16Srobert     thunkMap.clear();
1384*dfe94b16Srobert 
1385*dfe94b16Srobert     firstTLVDataSection = nullptr;
1386*dfe94b16Srobert     tar = nullptr;
1387*dfe94b16Srobert     memset(&in, 0, sizeof(in));
1388*dfe94b16Srobert 
1389*dfe94b16Srobert     resetLoadedDylibs();
1390*dfe94b16Srobert     resetOutputSegments();
1391*dfe94b16Srobert     resetWriter();
1392*dfe94b16Srobert     InputFile::resetIdCount();
1393*dfe94b16Srobert   };
1394*dfe94b16Srobert 
1395*dfe94b16Srobert   ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]);
1396bb684c34Spatrick 
1397bb684c34Spatrick   MachOOptTable parser;
13981cf9926bSpatrick   InputArgList args = parser.parse(argsArr.slice(1));
13991cf9926bSpatrick 
1400*dfe94b16Srobert   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
14011cf9926bSpatrick                                  "(use --error-limit=0 to see all errors)";
1402*dfe94b16Srobert   ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);
1403*dfe94b16Srobert   ctx->e.verbose = args.hasArg(OPT_verbose);
1404bb684c34Spatrick 
1405bb684c34Spatrick   if (args.hasArg(OPT_help_hidden)) {
1406bb684c34Spatrick     parser.printHelp(argsArr[0], /*showHidden=*/true);
1407bb684c34Spatrick     return true;
14081cf9926bSpatrick   }
14091cf9926bSpatrick   if (args.hasArg(OPT_help)) {
1410bb684c34Spatrick     parser.printHelp(argsArr[0], /*showHidden=*/false);
1411bb684c34Spatrick     return true;
1412bb684c34Spatrick   }
14131cf9926bSpatrick   if (args.hasArg(OPT_version)) {
14141cf9926bSpatrick     message(getLLDVersion());
14151cf9926bSpatrick     return true;
14161cf9926bSpatrick   }
1417bb684c34Spatrick 
1418*dfe94b16Srobert   config = std::make_unique<Configuration>();
1419*dfe94b16Srobert   symtab = std::make_unique<SymbolTable>();
1420*dfe94b16Srobert   config->outputType = getOutputType(args);
1421bb684c34Spatrick   target = createTargetInfo(args);
1422*dfe94b16Srobert   depTracker = std::make_unique<DependencyTracker>(
1423*dfe94b16Srobert       args.getLastArgValue(OPT_dependency_info));
1424*dfe94b16Srobert   if (errorCount())
1425*dfe94b16Srobert     return false;
1426*dfe94b16Srobert 
1427*dfe94b16Srobert   if (args.hasArg(OPT_pagezero_size)) {
1428*dfe94b16Srobert     uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0);
1429*dfe94b16Srobert 
1430*dfe94b16Srobert     // ld64 does something really weird. It attempts to realign the value to the
1431*dfe94b16Srobert     // page size, but assumes the page size is 4K. This doesn't work with most
1432*dfe94b16Srobert     // of Apple's ARM64 devices, which use a page size of 16K. This means that
1433*dfe94b16Srobert     // it will first 4K align it by rounding down, then round up to 16K.  This
1434*dfe94b16Srobert     // probably only happened because no one using this arg with anything other
1435*dfe94b16Srobert     // then 0, so no one checked if it did what is what it says it does.
1436*dfe94b16Srobert 
1437*dfe94b16Srobert     // So we are not copying this weird behavior and doing the it in a logical
1438*dfe94b16Srobert     // way, by always rounding down to page size.
1439*dfe94b16Srobert     if (!isAligned(Align(target->getPageSize()), pagezeroSize)) {
1440*dfe94b16Srobert       pagezeroSize -= pagezeroSize % target->getPageSize();
1441*dfe94b16Srobert       warn("__PAGEZERO size is not page aligned, rounding down to 0x" +
1442*dfe94b16Srobert            Twine::utohexstr(pagezeroSize));
1443*dfe94b16Srobert     }
1444*dfe94b16Srobert 
1445*dfe94b16Srobert     target->pageZeroSize = pagezeroSize;
1446*dfe94b16Srobert   }
1447*dfe94b16Srobert 
1448*dfe94b16Srobert   config->osoPrefix = args.getLastArgValue(OPT_oso_prefix);
1449*dfe94b16Srobert   if (!config->osoPrefix.empty()) {
1450*dfe94b16Srobert     // Expand special characters, such as ".", "..", or  "~", if present.
1451*dfe94b16Srobert     // Note: LD64 only expands "." and not other special characters.
1452*dfe94b16Srobert     // That seems silly to imitate so we will not try to follow it, but rather
1453*dfe94b16Srobert     // just use real_path() to do it.
1454*dfe94b16Srobert 
1455*dfe94b16Srobert     // The max path length is 4096, in theory. However that seems quite long
1456*dfe94b16Srobert     // and seems unlikely that any one would want to strip everything from the
1457*dfe94b16Srobert     // path. Hence we've picked a reasonably large number here.
1458*dfe94b16Srobert     SmallString<1024> expanded;
1459*dfe94b16Srobert     if (!fs::real_path(config->osoPrefix, expanded,
1460*dfe94b16Srobert                        /*expand_tilde=*/true)) {
1461*dfe94b16Srobert       // Note: LD64 expands "." to be `<current_dir>/`
1462*dfe94b16Srobert       // (ie., it has a slash suffix) whereas real_path() doesn't.
1463*dfe94b16Srobert       // So we have to append '/' to be consistent.
1464*dfe94b16Srobert       StringRef sep = sys::path::get_separator();
1465*dfe94b16Srobert       // real_path removes trailing slashes as part of the normalization, but
1466*dfe94b16Srobert       // these are meaningful for our text based stripping
1467*dfe94b16Srobert       if (config->osoPrefix.equals(".") || config->osoPrefix.endswith(sep))
1468*dfe94b16Srobert         expanded += sep;
1469*dfe94b16Srobert       config->osoPrefix = saver().save(expanded.str());
1470*dfe94b16Srobert     }
1471*dfe94b16Srobert   }
1472*dfe94b16Srobert 
1473*dfe94b16Srobert   bool pie = args.hasFlag(OPT_pie, OPT_no_pie, true);
1474*dfe94b16Srobert   if (!supportsNoPie() && !pie) {
1475*dfe94b16Srobert     warn("-no_pie ignored for arm64");
1476*dfe94b16Srobert     pie = true;
1477*dfe94b16Srobert   }
1478*dfe94b16Srobert 
1479*dfe94b16Srobert   config->isPic = config->outputType == MH_DYLIB ||
1480*dfe94b16Srobert                   config->outputType == MH_BUNDLE ||
1481*dfe94b16Srobert                   (config->outputType == MH_EXECUTE && pie);
1482bb684c34Spatrick 
14831cf9926bSpatrick   // Must be set before any InputSections and Symbols are created.
14841cf9926bSpatrick   config->deadStrip = args.hasArg(OPT_dead_strip);
14851cf9926bSpatrick 
14861cf9926bSpatrick   config->systemLibraryRoots = getSystemLibraryRoots(args);
14871cf9926bSpatrick   if (const char *path = getReproduceOption(args)) {
14881cf9926bSpatrick     // Note that --reproduce is a debug option so you can ignore it
14891cf9926bSpatrick     // if you are trying to understand the whole picture of the code.
14901cf9926bSpatrick     Expected<std::unique_ptr<TarWriter>> errOrWriter =
14911cf9926bSpatrick         TarWriter::create(path, path::stem(path));
14921cf9926bSpatrick     if (errOrWriter) {
14931cf9926bSpatrick       tar = std::move(*errOrWriter);
14941cf9926bSpatrick       tar->append("response.txt", createResponseFile(args));
14951cf9926bSpatrick       tar->append("version.txt", getLLDVersion() + "\n");
14961cf9926bSpatrick     } else {
14971cf9926bSpatrick       error("--reproduce: " + toString(errOrWriter.takeError()));
14981cf9926bSpatrick     }
14991cf9926bSpatrick   }
15001cf9926bSpatrick 
15011cf9926bSpatrick   if (auto *arg = args.getLastArg(OPT_threads_eq)) {
15021cf9926bSpatrick     StringRef v(arg->getValue());
15031cf9926bSpatrick     unsigned threads = 0;
15041cf9926bSpatrick     if (!llvm::to_integer(v, threads, 0) || threads == 0)
15051cf9926bSpatrick       error(arg->getSpelling() + ": expected a positive integer, but got '" +
15061cf9926bSpatrick             arg->getValue() + "'");
15071cf9926bSpatrick     parallel::strategy = hardware_concurrency(threads);
15081cf9926bSpatrick     config->thinLTOJobs = v;
15091cf9926bSpatrick   }
15101cf9926bSpatrick   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
15111cf9926bSpatrick     config->thinLTOJobs = arg->getValue();
15121cf9926bSpatrick   if (!get_threadpool_strategy(config->thinLTOJobs))
15131cf9926bSpatrick     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
15141cf9926bSpatrick 
15151cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_u)) {
15161cf9926bSpatrick     config->explicitUndefineds.push_back(symtab->addUndefined(
15171cf9926bSpatrick         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
15181cf9926bSpatrick   }
15191cf9926bSpatrick 
15201cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_U))
15211cf9926bSpatrick     config->explicitDynamicLookups.insert(arg->getValue());
15221cf9926bSpatrick 
15231cf9926bSpatrick   config->mapFile = args.getLastArgValue(OPT_map);
15241cf9926bSpatrick   config->optimize = args::getInteger(args, OPT_O, 1);
1525bb684c34Spatrick   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
15261cf9926bSpatrick   config->finalOutput =
15271cf9926bSpatrick       args.getLastArgValue(OPT_final_output, config->outputFile);
15281cf9926bSpatrick   config->astPaths = args.getAllArgValues(OPT_add_ast_path);
15291cf9926bSpatrick   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
15301cf9926bSpatrick   config->headerPadMaxInstallNames =
15311cf9926bSpatrick       args.hasArg(OPT_headerpad_max_install_names);
15321cf9926bSpatrick   config->printDylibSearch =
15331cf9926bSpatrick       args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");
15341cf9926bSpatrick   config->printEachFile = args.hasArg(OPT_t);
15351cf9926bSpatrick   config->printWhyLoad = args.hasArg(OPT_why_load);
1536*dfe94b16Srobert   config->omitDebugInfo = args.hasArg(OPT_S);
1537*dfe94b16Srobert   config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal);
15381cf9926bSpatrick   if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {
15391cf9926bSpatrick     if (config->outputType != MH_BUNDLE)
15401cf9926bSpatrick       error("-bundle_loader can only be used with MachO bundle output");
1541*dfe94b16Srobert     addFile(arg->getValue(), LoadType::CommandLine, /*isLazy=*/false,
1542*dfe94b16Srobert             /*isExplicit=*/false, /*isBundleLoader=*/true);
15431cf9926bSpatrick   }
1544*dfe94b16Srobert   for (auto *arg : args.filtered(OPT_dyld_env)) {
1545*dfe94b16Srobert     StringRef envPair(arg->getValue());
1546*dfe94b16Srobert     if (!envPair.contains('='))
1547*dfe94b16Srobert       error("-dyld_env's argument is  malformed. Expected "
1548*dfe94b16Srobert             "-dyld_env <ENV_VAR>=<VALUE>, got `" +
1549*dfe94b16Srobert             envPair + "`");
1550*dfe94b16Srobert     config->dyldEnvs.push_back(envPair);
1551*dfe94b16Srobert   }
1552*dfe94b16Srobert   if (!config->dyldEnvs.empty() && config->outputType != MH_EXECUTE)
1553*dfe94b16Srobert     error("-dyld_env can only be used when creating executable output");
1554*dfe94b16Srobert 
15551cf9926bSpatrick   if (const Arg *arg = args.getLastArg(OPT_umbrella)) {
15561cf9926bSpatrick     if (config->outputType != MH_DYLIB)
15571cf9926bSpatrick       warn("-umbrella used, but not creating dylib");
15581cf9926bSpatrick     config->umbrella = arg->getValue();
15591cf9926bSpatrick   }
15601cf9926bSpatrick   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
15611cf9926bSpatrick   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
15621cf9926bSpatrick   if (config->ltoo > 3)
15631cf9926bSpatrick     error("--lto-O: invalid optimization level: " + Twine(config->ltoo));
15641cf9926bSpatrick   config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto);
15651cf9926bSpatrick   config->thinLTOCachePolicy = getLTOCachePolicy(args);
1566*dfe94b16Srobert   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1567*dfe94b16Srobert   config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1568*dfe94b16Srobert                                   args.hasArg(OPT_thinlto_index_only) ||
1569*dfe94b16Srobert                                   args.hasArg(OPT_thinlto_index_only_eq);
1570*dfe94b16Srobert   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1571*dfe94b16Srobert                              args.hasArg(OPT_thinlto_index_only_eq);
1572*dfe94b16Srobert   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1573*dfe94b16Srobert   config->thinLTOObjectSuffixReplace =
1574*dfe94b16Srobert       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1575*dfe94b16Srobert   config->thinLTOPrefixReplace =
1576*dfe94b16Srobert       getOldNewOptions(args, OPT_thinlto_prefix_replace_eq);
1577*dfe94b16Srobert   if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1578*dfe94b16Srobert     if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
1579*dfe94b16Srobert       error("--thinlto-object-suffix-replace is not supported with "
1580*dfe94b16Srobert             "--thinlto-emit-index-files");
1581*dfe94b16Srobert     else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
1582*dfe94b16Srobert       error("--thinlto-prefix-replace is not supported with "
1583*dfe94b16Srobert             "--thinlto-emit-index-files");
1584*dfe94b16Srobert   }
15851cf9926bSpatrick   config->runtimePaths = args::getStrings(args, OPT_rpath);
1586*dfe94b16Srobert   config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false);
15871cf9926bSpatrick   config->archMultiple = args.hasArg(OPT_arch_multiple);
15881cf9926bSpatrick   config->applicationExtension = args.hasFlag(
15891cf9926bSpatrick       OPT_application_extension, OPT_no_application_extension, false);
15901cf9926bSpatrick   config->exportDynamic = args.hasArg(OPT_export_dynamic);
15911cf9926bSpatrick   config->forceLoadObjC = args.hasArg(OPT_ObjC);
15921cf9926bSpatrick   config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);
15931cf9926bSpatrick   config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);
15941cf9926bSpatrick   config->demangle = args.hasArg(OPT_demangle);
15951cf9926bSpatrick   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
15961cf9926bSpatrick   config->emitFunctionStarts =
15971cf9926bSpatrick       args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);
15981cf9926bSpatrick   config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle);
15991cf9926bSpatrick   config->emitDataInCodeInfo =
16001cf9926bSpatrick       args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);
1601*dfe94b16Srobert   config->emitChainedFixups = shouldEmitChainedFixups(args);
1602*dfe94b16Srobert   config->emitInitOffsets =
1603*dfe94b16Srobert       config->emitChainedFixups || args.hasArg(OPT_init_offsets);
16041cf9926bSpatrick   config->icfLevel = getICFLevel(args);
1605*dfe94b16Srobert   config->dedupStrings =
1606*dfe94b16Srobert       args.hasFlag(OPT_deduplicate_strings, OPT_no_deduplicate_strings, true);
1607*dfe94b16Srobert   config->deadStripDuplicates = args.hasArg(OPT_dead_strip_duplicates);
1608*dfe94b16Srobert   config->warnDylibInstallName = args.hasFlag(
1609*dfe94b16Srobert       OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false);
1610*dfe94b16Srobert   config->ignoreOptimizationHints = args.hasArg(OPT_ignore_optimization_hints);
1611*dfe94b16Srobert   config->callGraphProfileSort = args.hasFlag(
1612*dfe94b16Srobert       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1613*dfe94b16Srobert   config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order_eq);
1614*dfe94b16Srobert   config->forceExactCpuSubtypeMatch =
1615*dfe94b16Srobert       getenv("LD_DYLIB_CPU_SUBTYPES_MUST_MATCH");
1616*dfe94b16Srobert   config->objcStubsMode = getObjCStubsMode(args);
1617*dfe94b16Srobert   config->ignoreAutoLink = args.hasArg(OPT_ignore_auto_link);
1618*dfe94b16Srobert   for (const Arg *arg : args.filtered(OPT_ignore_auto_link_option))
1619*dfe94b16Srobert     config->ignoreAutoLinkOptions.insert(arg->getValue());
1620*dfe94b16Srobert   config->strictAutoLink = args.hasArg(OPT_strict_auto_link);
1621*dfe94b16Srobert 
1622*dfe94b16Srobert   for (const Arg *arg : args.filtered(OPT_alias)) {
1623*dfe94b16Srobert     config->aliasedSymbols.push_back(
1624*dfe94b16Srobert         std::make_pair(arg->getValue(0), arg->getValue(1)));
1625*dfe94b16Srobert   }
16261cf9926bSpatrick 
16271cf9926bSpatrick   // FIXME: Add a commandline flag for this too.
1628*dfe94b16Srobert   if (const char *zero = getenv("ZERO_AR_DATE"))
1629*dfe94b16Srobert     config->zeroModTime = strcmp(zero, "0") != 0;
16301cf9926bSpatrick 
1631*dfe94b16Srobert   std::array<PlatformType, 3> encryptablePlatforms{
1632*dfe94b16Srobert       PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS};
16331cf9926bSpatrick   config->emitEncryptionInfo =
16341cf9926bSpatrick       args.hasFlag(OPT_encryptable, OPT_no_encryption,
16351cf9926bSpatrick                    is_contained(encryptablePlatforms, config->platform()));
16361cf9926bSpatrick 
16371cf9926bSpatrick #ifndef LLVM_HAVE_LIBXAR
16381cf9926bSpatrick   if (config->emitBitcodeBundle)
16391cf9926bSpatrick     error("-bitcode_bundle unsupported because LLD wasn't built with libxar");
16401cf9926bSpatrick #endif
16411cf9926bSpatrick 
16421cf9926bSpatrick   if (const Arg *arg = args.getLastArg(OPT_install_name)) {
1643*dfe94b16Srobert     if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
1644*dfe94b16Srobert       warn(
1645*dfe94b16Srobert           arg->getAsString(args) +
1646*dfe94b16Srobert           ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
16471cf9926bSpatrick     else
16481cf9926bSpatrick       config->installName = arg->getValue();
16491cf9926bSpatrick   } else if (config->outputType == MH_DYLIB) {
16501cf9926bSpatrick     config->installName = config->finalOutput;
16511cf9926bSpatrick   }
16521cf9926bSpatrick 
16531cf9926bSpatrick   if (args.hasArg(OPT_mark_dead_strippable_dylib)) {
16541cf9926bSpatrick     if (config->outputType != MH_DYLIB)
16551cf9926bSpatrick       warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
16561cf9926bSpatrick     else
16571cf9926bSpatrick       config->markDeadStrippableDylib = true;
16581cf9926bSpatrick   }
16591cf9926bSpatrick 
16601cf9926bSpatrick   if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
16611cf9926bSpatrick     config->staticLink = (arg->getOption().getID() == OPT_static);
16621cf9926bSpatrick 
16631cf9926bSpatrick   if (const Arg *arg =
16641cf9926bSpatrick           args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
16651cf9926bSpatrick     config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
16661cf9926bSpatrick                                 ? NamespaceKind::twolevel
16671cf9926bSpatrick                                 : NamespaceKind::flat;
16681cf9926bSpatrick 
16691cf9926bSpatrick   config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
16701cf9926bSpatrick 
16711cf9926bSpatrick   if (config->outputType == MH_EXECUTE)
16721cf9926bSpatrick     config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
16731cf9926bSpatrick                                          /*file=*/nullptr,
16741cf9926bSpatrick                                          /*isWeakRef=*/false);
16751cf9926bSpatrick 
16761cf9926bSpatrick   config->librarySearchPaths =
16771cf9926bSpatrick       getLibrarySearchPaths(args, config->systemLibraryRoots);
16781cf9926bSpatrick   config->frameworkSearchPaths =
16791cf9926bSpatrick       getFrameworkSearchPaths(args, config->systemLibraryRoots);
16801cf9926bSpatrick   if (const Arg *arg =
16811cf9926bSpatrick           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
16821cf9926bSpatrick     config->searchDylibsFirst =
16831cf9926bSpatrick         arg->getOption().getID() == OPT_search_dylibs_first;
16841cf9926bSpatrick 
16851cf9926bSpatrick   config->dylibCompatibilityVersion =
16861cf9926bSpatrick       parseDylibVersion(args, OPT_compatibility_version);
16871cf9926bSpatrick   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
16881cf9926bSpatrick 
16891cf9926bSpatrick   config->dataConst =
16901cf9926bSpatrick       args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));
16911cf9926bSpatrick   // Populate config->sectionRenameMap with builtin default renames.
16921cf9926bSpatrick   // Options -rename_section and -rename_segment are able to override.
16931cf9926bSpatrick   initializeSectionRenameMap();
16941cf9926bSpatrick   // Reject every special character except '.' and '$'
16951cf9926bSpatrick   // TODO(gkm): verify that this is the proper set of invalid chars
16961cf9926bSpatrick   StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
16971cf9926bSpatrick   auto validName = [invalidNameChars](StringRef s) {
16981cf9926bSpatrick     if (s.find_first_of(invalidNameChars) != StringRef::npos)
16991cf9926bSpatrick       error("invalid name for segment or section: " + s);
17001cf9926bSpatrick     return s;
17011cf9926bSpatrick   };
17021cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_rename_section)) {
17031cf9926bSpatrick     config->sectionRenameMap[{validName(arg->getValue(0)),
17041cf9926bSpatrick                               validName(arg->getValue(1))}] = {
17051cf9926bSpatrick         validName(arg->getValue(2)), validName(arg->getValue(3))};
17061cf9926bSpatrick   }
17071cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_rename_segment)) {
17081cf9926bSpatrick     config->segmentRenameMap[validName(arg->getValue(0))] =
17091cf9926bSpatrick         validName(arg->getValue(1));
17101cf9926bSpatrick   }
17111cf9926bSpatrick 
17121cf9926bSpatrick   config->sectionAlignments = parseSectAlign(args);
17131cf9926bSpatrick 
17141cf9926bSpatrick   for (const Arg *arg : args.filtered(OPT_segprot)) {
17151cf9926bSpatrick     StringRef segName = arg->getValue(0);
17161cf9926bSpatrick     uint32_t maxProt = parseProtection(arg->getValue(1));
17171cf9926bSpatrick     uint32_t initProt = parseProtection(arg->getValue(2));
17181cf9926bSpatrick     if (maxProt != initProt && config->arch() != AK_i386)
17191cf9926bSpatrick       error("invalid argument '" + arg->getAsString(args) +
17201cf9926bSpatrick             "': max and init must be the same for non-i386 archs");
17211cf9926bSpatrick     if (segName == segment_names::linkEdit)
17221cf9926bSpatrick       error("-segprot cannot be used to change __LINKEDIT's protections");
17231cf9926bSpatrick     config->segmentProtections.push_back({segName, maxProt, initProt});
17241cf9926bSpatrick   }
17251cf9926bSpatrick 
1726*dfe94b16Srobert   config->hasExplicitExports =
1727*dfe94b16Srobert       args.hasArg(OPT_no_exported_symbols) ||
1728*dfe94b16Srobert       args.hasArgNoClaim(OPT_exported_symbol, OPT_exported_symbols_list);
17291cf9926bSpatrick   handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,
17301cf9926bSpatrick                        OPT_exported_symbols_list);
17311cf9926bSpatrick   handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,
17321cf9926bSpatrick                        OPT_unexported_symbols_list);
1733*dfe94b16Srobert   if (config->hasExplicitExports && !config->unexportedSymbols.empty())
1734*dfe94b16Srobert     error("cannot use both -exported_symbol* and -unexported_symbol* options");
1735*dfe94b16Srobert 
1736*dfe94b16Srobert   if (args.hasArg(OPT_no_exported_symbols) && !config->exportedSymbols.empty())
1737*dfe94b16Srobert     error("cannot use both -exported_symbol* and -no_exported_symbols options");
1738*dfe94b16Srobert 
1739*dfe94b16Srobert   // Imitating LD64's:
1740*dfe94b16Srobert   // -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't
1741*dfe94b16Srobert   // both be present.
1742*dfe94b16Srobert   // But -x can be used with either of these two, in which case, the last arg
1743*dfe94b16Srobert   // takes effect.
1744*dfe94b16Srobert   // (TODO: This is kind of confusing - considering disallowing using them
1745*dfe94b16Srobert   // together for a more straightforward behaviour)
1746*dfe94b16Srobert   {
1747*dfe94b16Srobert     bool includeLocal = false;
1748*dfe94b16Srobert     bool excludeLocal = false;
1749*dfe94b16Srobert     for (const Arg *arg :
1750*dfe94b16Srobert          args.filtered(OPT_x, OPT_non_global_symbols_no_strip_list,
1751*dfe94b16Srobert                        OPT_non_global_symbols_strip_list)) {
1752*dfe94b16Srobert       switch (arg->getOption().getID()) {
1753*dfe94b16Srobert       case OPT_x:
1754*dfe94b16Srobert         config->localSymbolsPresence = SymtabPresence::None;
1755*dfe94b16Srobert         break;
1756*dfe94b16Srobert       case OPT_non_global_symbols_no_strip_list:
1757*dfe94b16Srobert         if (excludeLocal) {
1758*dfe94b16Srobert           error("cannot use both -non_global_symbols_no_strip_list and "
1759*dfe94b16Srobert                 "-non_global_symbols_strip_list");
1760*dfe94b16Srobert         } else {
1761*dfe94b16Srobert           includeLocal = true;
1762*dfe94b16Srobert           config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded;
1763*dfe94b16Srobert           parseSymbolPatternsFile(arg, config->localSymbolPatterns);
1764*dfe94b16Srobert         }
1765*dfe94b16Srobert         break;
1766*dfe94b16Srobert       case OPT_non_global_symbols_strip_list:
1767*dfe94b16Srobert         if (includeLocal) {
1768*dfe94b16Srobert           error("cannot use both -non_global_symbols_no_strip_list and "
1769*dfe94b16Srobert                 "-non_global_symbols_strip_list");
1770*dfe94b16Srobert         } else {
1771*dfe94b16Srobert           excludeLocal = true;
1772*dfe94b16Srobert           config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded;
1773*dfe94b16Srobert           parseSymbolPatternsFile(arg, config->localSymbolPatterns);
1774*dfe94b16Srobert         }
1775*dfe94b16Srobert         break;
1776*dfe94b16Srobert       default:
1777*dfe94b16Srobert         llvm_unreachable("unexpected option");
1778*dfe94b16Srobert       }
1779*dfe94b16Srobert     }
17801cf9926bSpatrick   }
17811cf9926bSpatrick   // Explicitly-exported literal symbols must be defined, but might
1782*dfe94b16Srobert   // languish in an archive if unreferenced elsewhere or if they are in the
1783*dfe94b16Srobert   // non-global strip list. Light a fire under those lazy symbols!
17841cf9926bSpatrick   for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
17851cf9926bSpatrick     symtab->addUndefined(cachedName.val(), /*file=*/nullptr,
17861cf9926bSpatrick                          /*isWeakRef=*/false);
17871cf9926bSpatrick 
1788*dfe94b16Srobert   for (const Arg *arg : args.filtered(OPT_why_live))
1789*dfe94b16Srobert     config->whyLive.insert(arg->getValue());
1790*dfe94b16Srobert   if (!config->whyLive.empty() && !config->deadStrip)
1791*dfe94b16Srobert     warn("-why_live has no effect without -dead_strip, ignoring");
1792*dfe94b16Srobert 
17931cf9926bSpatrick   config->saveTemps = args.hasArg(OPT_save_temps);
17941cf9926bSpatrick 
17951cf9926bSpatrick   config->adhocCodesign = args.hasFlag(
17961cf9926bSpatrick       OPT_adhoc_codesign, OPT_no_adhoc_codesign,
1797*dfe94b16Srobert       shouldAdhocSignByDefault(config->arch(), config->platform()));
1798bb684c34Spatrick 
1799bb684c34Spatrick   if (args.hasArg(OPT_v)) {
1800*dfe94b16Srobert     message(getLLDVersion(), lld::errs());
1801bb684c34Spatrick     message(StringRef("Library search paths:") +
18021cf9926bSpatrick                 (config->librarySearchPaths.empty()
18031cf9926bSpatrick                      ? ""
1804*dfe94b16Srobert                      : "\n\t" + join(config->librarySearchPaths, "\n\t")),
1805*dfe94b16Srobert             lld::errs());
1806bb684c34Spatrick     message(StringRef("Framework search paths:") +
18071cf9926bSpatrick                 (config->frameworkSearchPaths.empty()
18081cf9926bSpatrick                      ? ""
1809*dfe94b16Srobert                      : "\n\t" + join(config->frameworkSearchPaths, "\n\t")),
1810*dfe94b16Srobert             lld::errs());
1811bb684c34Spatrick   }
1812bb684c34Spatrick 
18131cf9926bSpatrick   config->progName = argsArr[0];
18141cf9926bSpatrick 
1815*dfe94b16Srobert   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
18161cf9926bSpatrick   config->timeTraceGranularity =
18171cf9926bSpatrick       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
18181cf9926bSpatrick 
18191cf9926bSpatrick   // Initialize time trace profiler.
18201cf9926bSpatrick   if (config->timeTraceEnabled)
18211cf9926bSpatrick     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
18221cf9926bSpatrick 
18231cf9926bSpatrick   {
18241cf9926bSpatrick     TimeTraceScope timeScope("ExecuteLinker");
18251cf9926bSpatrick 
18261cf9926bSpatrick     initLLVM(); // must be run before any call to addFile()
18271cf9926bSpatrick     createFiles(args);
18281cf9926bSpatrick 
1829bb684c34Spatrick     // Now that all dylibs have been loaded, search for those that should be
1830bb684c34Spatrick     // re-exported.
18311cf9926bSpatrick     {
18321cf9926bSpatrick       auto reexportHandler = [](const Arg *arg,
18331cf9926bSpatrick                                 const std::vector<StringRef> &extensions) {
1834bb684c34Spatrick         config->hasReexports = true;
1835bb684c34Spatrick         StringRef searchName = arg->getValue();
18361cf9926bSpatrick         if (!markReexport(searchName, extensions))
18371cf9926bSpatrick           error(arg->getSpelling() + " " + searchName +
18381cf9926bSpatrick                 " does not match a supplied dylib");
18391cf9926bSpatrick       };
18401cf9926bSpatrick       std::vector<StringRef> extensions = {".tbd"};
18411cf9926bSpatrick       for (const Arg *arg : args.filtered(OPT_sub_umbrella))
18421cf9926bSpatrick         reexportHandler(arg, extensions);
18431cf9926bSpatrick 
18441cf9926bSpatrick       extensions.push_back(".dylib");
18451cf9926bSpatrick       for (const Arg *arg : args.filtered(OPT_sub_library))
18461cf9926bSpatrick         reexportHandler(arg, extensions);
1847bb684c34Spatrick     }
1848bb684c34Spatrick 
1849*dfe94b16Srobert     cl::ResetAllOptionOccurrences();
1850*dfe94b16Srobert 
18511cf9926bSpatrick     // Parse LTO options.
18521cf9926bSpatrick     if (const Arg *arg = args.getLastArg(OPT_mcpu))
1853*dfe94b16Srobert       parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
18541cf9926bSpatrick                        arg->getSpelling());
18551cf9926bSpatrick 
1856*dfe94b16Srobert     for (const Arg *arg : args.filtered(OPT_mllvm)) {
18571cf9926bSpatrick       parseClangOption(arg->getValue(), arg->getSpelling());
1858*dfe94b16Srobert       config->mllvmOpts.emplace_back(arg->getValue());
1859*dfe94b16Srobert     }
18601cf9926bSpatrick 
1861*dfe94b16Srobert     createSyntheticSections();
1862*dfe94b16Srobert     createSyntheticSymbols();
1863*dfe94b16Srobert     addSynthenticMethnames();
1864*dfe94b16Srobert 
1865*dfe94b16Srobert     createAliases();
1866*dfe94b16Srobert     // If we are in "explicit exports" mode, hide everything that isn't
1867*dfe94b16Srobert     // explicitly exported. Do this before running LTO so that LTO can better
1868*dfe94b16Srobert     // optimize.
1869*dfe94b16Srobert     handleExplicitExports();
1870*dfe94b16Srobert 
1871*dfe94b16Srobert     bool didCompileBitcodeFiles = compileBitcodeFiles();
1872*dfe94b16Srobert 
1873*dfe94b16Srobert     // If --thinlto-index-only is given, we should create only "index
1874*dfe94b16Srobert     // files" and not object files. Index file creation is already done
1875*dfe94b16Srobert     // in compileBitcodeFiles, so we are done if that's the case.
1876*dfe94b16Srobert     if (config->thinLTOIndexOnly)
1877*dfe94b16Srobert       return errorCount() == 0;
1878*dfe94b16Srobert 
1879*dfe94b16Srobert     // LTO may emit a non-hidden (extern) object file symbol even if the
1880*dfe94b16Srobert     // corresponding bitcode symbol is hidden. In particular, this happens for
1881*dfe94b16Srobert     // cross-module references to hidden symbols under ThinLTO. Thus, if we
1882*dfe94b16Srobert     // compiled any bitcode files, we must redo the symbol hiding.
1883*dfe94b16Srobert     if (didCompileBitcodeFiles)
1884*dfe94b16Srobert       handleExplicitExports();
18851cf9926bSpatrick     replaceCommonSymbols();
18861cf9926bSpatrick 
1887bb684c34Spatrick     StringRef orderFile = args.getLastArgValue(OPT_order_file);
1888bb684c34Spatrick     if (!orderFile.empty())
1889*dfe94b16Srobert       priorityBuilder.parseOrderFile(orderFile);
1890bb684c34Spatrick 
18911cf9926bSpatrick     referenceStubBinder();
18921cf9926bSpatrick 
18931cf9926bSpatrick     // FIXME: should terminate the link early based on errors encountered so
18941cf9926bSpatrick     // far?
1895bb684c34Spatrick 
18961cf9926bSpatrick     for (const Arg *arg : args.filtered(OPT_sectcreate)) {
18971cf9926bSpatrick       StringRef segName = arg->getValue(0);
18981cf9926bSpatrick       StringRef sectName = arg->getValue(1);
18991cf9926bSpatrick       StringRef fileName = arg->getValue(2);
1900*dfe94b16Srobert       std::optional<MemoryBufferRef> buffer = readFile(fileName);
19011cf9926bSpatrick       if (buffer)
19021cf9926bSpatrick         inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
19031cf9926bSpatrick     }
19041cf9926bSpatrick 
1905*dfe94b16Srobert     for (const Arg *arg : args.filtered(OPT_add_empty_section)) {
1906*dfe94b16Srobert       StringRef segName = arg->getValue(0);
1907*dfe94b16Srobert       StringRef sectName = arg->getValue(1);
1908*dfe94b16Srobert       inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName));
1909*dfe94b16Srobert     }
1910*dfe94b16Srobert 
19111cf9926bSpatrick     gatherInputSections();
1912*dfe94b16Srobert     if (config->callGraphProfileSort)
1913*dfe94b16Srobert       priorityBuilder.extractCallGraphProfile();
19141cf9926bSpatrick 
19151cf9926bSpatrick     if (config->deadStrip)
19161cf9926bSpatrick       markLive();
19171cf9926bSpatrick 
19181cf9926bSpatrick     // ICF assumes that all literals have been folded already, so we must run
19191cf9926bSpatrick     // foldIdenticalLiterals before foldIdenticalSections.
19201cf9926bSpatrick     foldIdenticalLiterals();
1921*dfe94b16Srobert     if (config->icfLevel != ICFLevel::none) {
1922*dfe94b16Srobert       if (config->icfLevel == ICFLevel::safe)
1923*dfe94b16Srobert         markAddrSigSymbols();
1924*dfe94b16Srobert       foldIdenticalSections(/*onlyCfStrings=*/false);
1925*dfe94b16Srobert     } else if (config->dedupStrings) {
1926*dfe94b16Srobert       foldIdenticalSections(/*onlyCfStrings=*/true);
1927*dfe94b16Srobert     }
1928bb684c34Spatrick 
1929bb684c34Spatrick     // Write to an output file.
19301cf9926bSpatrick     if (target->wordSize == 8)
19311cf9926bSpatrick       writeResult<LP64>();
19321cf9926bSpatrick     else
19331cf9926bSpatrick       writeResult<ILP32>();
19341cf9926bSpatrick 
19351cf9926bSpatrick     depTracker->write(getLLDVersion(), inputFiles, config->outputFile);
19361cf9926bSpatrick   }
19371cf9926bSpatrick 
19381cf9926bSpatrick   if (config->timeTraceEnabled) {
1939*dfe94b16Srobert     checkError(timeTraceProfilerWrite(
1940*dfe94b16Srobert         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
19411cf9926bSpatrick 
19421cf9926bSpatrick     timeTraceProfilerCleanup();
19431cf9926bSpatrick   }
1944bb684c34Spatrick 
1945*dfe94b16Srobert   if (errorCount() != 0 || config->strictAutoLink)
1946*dfe94b16Srobert     for (const auto &warning : missingAutolinkWarnings)
1947*dfe94b16Srobert       warn(warning);
1948bb684c34Spatrick 
1949*dfe94b16Srobert   return errorCount() == 0;
1950bb684c34Spatrick }
1951