1 //===- Driver.cpp ---------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 #include "Driver.h"
10 #include "Config.h"
11 #include "ICF.h"
12 #include "InputFiles.h"
13 #include "LTO.h"
14 #include "MarkLive.h"
15 #include "ObjC.h"
16 #include "OutputSection.h"
17 #include "OutputSegment.h"
18 #include "SectionPriorities.h"
19 #include "SymbolTable.h"
20 #include "Symbols.h"
21 #include "SyntheticSections.h"
22 #include "Target.h"
23 #include "UnwindInfoSection.h"
24 #include "Writer.h"
25 
26 #include "lld/Common/Args.h"
27 #include "lld/Common/CommonLinkerContext.h"
28 #include "lld/Common/Driver.h"
29 #include "lld/Common/ErrorHandler.h"
30 #include "lld/Common/LLVM.h"
31 #include "lld/Common/Memory.h"
32 #include "lld/Common/Reproduce.h"
33 #include "lld/Common/Version.h"
34 #include "llvm/ADT/DenseSet.h"
35 #include "llvm/ADT/StringExtras.h"
36 #include "llvm/ADT/StringRef.h"
37 #include "llvm/BinaryFormat/MachO.h"
38 #include "llvm/BinaryFormat/Magic.h"
39 #include "llvm/Config/llvm-config.h"
40 #include "llvm/LTO/LTO.h"
41 #include "llvm/Object/Archive.h"
42 #include "llvm/Option/ArgList.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/FileSystem.h"
45 #include "llvm/Support/MemoryBuffer.h"
46 #include "llvm/Support/Parallel.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/TarWriter.h"
49 #include "llvm/Support/TargetSelect.h"
50 #include "llvm/Support/TimeProfiler.h"
51 #include "llvm/TargetParser/Host.h"
52 #include "llvm/TextAPI/PackedVersion.h"
53 
54 #include <algorithm>
55 
56 using namespace llvm;
57 using namespace llvm::MachO;
58 using namespace llvm::object;
59 using namespace llvm::opt;
60 using namespace llvm::sys;
61 using namespace lld;
62 using namespace lld::macho;
63 
64 std::unique_ptr<Configuration> macho::config;
65 std::unique_ptr<DependencyTracker> macho::depTracker;
66 
67 static HeaderFileType getOutputType(const InputArgList &args) {
68   // TODO: -r, -dylinker, -preload...
69   Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute);
70   if (outputArg == nullptr)
71     return MH_EXECUTE;
72 
73   switch (outputArg->getOption().getID()) {
74   case OPT_bundle:
75     return MH_BUNDLE;
76   case OPT_dylib:
77     return MH_DYLIB;
78   case OPT_execute:
79     return MH_EXECUTE;
80   default:
81     llvm_unreachable("internal error");
82   }
83 }
84 
85 static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;
86 static std::optional<StringRef> findLibrary(StringRef name) {
87   CachedHashStringRef key(name);
88   auto entry = resolvedLibraries.find(key);
89   if (entry != resolvedLibraries.end())
90     return entry->second;
91 
92   auto doFind = [&] {
93     if (config->searchDylibsFirst) {
94       if (std::optional<StringRef> path =
95               findPathCombination("lib" + name, config->librarySearchPaths,
96                                   {".tbd", ".dylib", ".so"}))
97         return path;
98       return findPathCombination("lib" + name, config->librarySearchPaths,
99                                  {".a"});
100     }
101     return findPathCombination("lib" + name, config->librarySearchPaths,
102                                {".tbd", ".dylib", ".so", ".a"});
103   };
104 
105   std::optional<StringRef> path = doFind();
106   if (path)
107     resolvedLibraries[key] = *path;
108 
109   return path;
110 }
111 
112 static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;
113 static std::optional<StringRef> findFramework(StringRef name) {
114   CachedHashStringRef key(name);
115   auto entry = resolvedFrameworks.find(key);
116   if (entry != resolvedFrameworks.end())
117     return entry->second;
118 
119   SmallString<260> symlink;
120   StringRef suffix;
121   std::tie(name, suffix) = name.split(",");
122   for (StringRef dir : config->frameworkSearchPaths) {
123     symlink = dir;
124     path::append(symlink, name + ".framework", name);
125 
126     if (!suffix.empty()) {
127       // NOTE: we must resolve the symlink before trying the suffixes, because
128       // there are no symlinks for the suffixed paths.
129       SmallString<260> location;
130       if (!fs::real_path(symlink, location)) {
131         // only append suffix if realpath() succeeds
132         Twine suffixed = location + suffix;
133         if (fs::exists(suffixed))
134           return resolvedFrameworks[key] = saver().save(suffixed.str());
135       }
136       // Suffix lookup failed, fall through to the no-suffix case.
137     }
138 
139     if (std::optional<StringRef> path = resolveDylibPath(symlink.str()))
140       return resolvedFrameworks[key] = *path;
141   }
142   return {};
143 }
144 
145 static bool warnIfNotDirectory(StringRef option, StringRef path) {
146   if (!fs::exists(path)) {
147     warn("directory not found for option -" + option + path);
148     return false;
149   } else if (!fs::is_directory(path)) {
150     warn("option -" + option + path + " references a non-directory path");
151     return false;
152   }
153   return true;
154 }
155 
156 static std::vector<StringRef>
157 getSearchPaths(unsigned optionCode, InputArgList &args,
158                const std::vector<StringRef> &roots,
159                const SmallVector<StringRef, 2> &systemPaths) {
160   std::vector<StringRef> paths;
161   StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
162   for (StringRef path : args::getStrings(args, optionCode)) {
163     // NOTE: only absolute paths are re-rooted to syslibroot(s)
164     bool found = false;
165     if (path::is_absolute(path, path::Style::posix)) {
166       for (StringRef root : roots) {
167         SmallString<261> buffer(root);
168         path::append(buffer, path);
169         // Do not warn about paths that are computed via the syslib roots
170         if (fs::is_directory(buffer)) {
171           paths.push_back(saver().save(buffer.str()));
172           found = true;
173         }
174       }
175     }
176     if (!found && warnIfNotDirectory(optionLetter, path))
177       paths.push_back(path);
178   }
179 
180   // `-Z` suppresses the standard "system" search paths.
181   if (args.hasArg(OPT_Z))
182     return paths;
183 
184   for (const StringRef &path : systemPaths) {
185     for (const StringRef &root : roots) {
186       SmallString<261> buffer(root);
187       path::append(buffer, path);
188       if (fs::is_directory(buffer))
189         paths.push_back(saver().save(buffer.str()));
190     }
191   }
192   return paths;
193 }
194 
195 static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) {
196   std::vector<StringRef> roots;
197   for (const Arg *arg : args.filtered(OPT_syslibroot))
198     roots.push_back(arg->getValue());
199   // NOTE: the final `-syslibroot` being `/` will ignore all roots
200   if (!roots.empty() && roots.back() == "/")
201     roots.clear();
202   // NOTE: roots can never be empty - add an empty root to simplify the library
203   // and framework search path computation.
204   if (roots.empty())
205     roots.emplace_back("");
206   return roots;
207 }
208 
209 static std::vector<StringRef>
210 getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) {
211   return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});
212 }
213 
214 static std::vector<StringRef>
215 getFrameworkSearchPaths(InputArgList &args,
216                         const std::vector<StringRef> &roots) {
217   return getSearchPaths(OPT_F, args, roots,
218                         {"/Library/Frameworks", "/System/Library/Frameworks"});
219 }
220 
221 static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) {
222   SmallString<128> ltoPolicy;
223   auto add = [&ltoPolicy](Twine val) {
224     if (!ltoPolicy.empty())
225       ltoPolicy += ":";
226     val.toVector(ltoPolicy);
227   };
228   for (const Arg *arg :
229        args.filtered(OPT_thinlto_cache_policy_eq, OPT_prune_interval_lto,
230                      OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) {
231     switch (arg->getOption().getID()) {
232     case OPT_thinlto_cache_policy_eq:
233       add(arg->getValue());
234       break;
235     case OPT_prune_interval_lto:
236       if (!strcmp("-1", arg->getValue()))
237         add("prune_interval=87600h"); // 10 years
238       else
239         add(Twine("prune_interval=") + arg->getValue() + "s");
240       break;
241     case OPT_prune_after_lto:
242       add(Twine("prune_after=") + arg->getValue() + "s");
243       break;
244     case OPT_max_relative_cache_size_lto:
245       add(Twine("cache_size=") + arg->getValue() + "%");
246       break;
247     }
248   }
249   return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy");
250 }
251 
252 // What caused a given library to be loaded. Only relevant for archives.
253 // Note that this does not tell us *how* we should load the library, i.e.
254 // whether we should do it lazily or eagerly (AKA force loading). The "how" is
255 // decided within addFile().
256 enum class LoadType {
257   CommandLine,      // Library was passed as a regular CLI argument
258   CommandLineForce, // Library was passed via `-force_load`
259   LCLinkerOption,   // Library was passed via LC_LINKER_OPTIONS
260 };
261 
262 struct ArchiveFileInfo {
263   ArchiveFile *file;
264   bool isCommandLineLoad;
265 };
266 
267 static DenseMap<StringRef, ArchiveFileInfo> loadedArchives;
268 
269 static InputFile *addFile(StringRef path, LoadType loadType,
270                           bool isLazy = false, bool isExplicit = true,
271                           bool isBundleLoader = false,
272                           bool isForceHidden = false) {
273   std::optional<MemoryBufferRef> buffer = readFile(path);
274   if (!buffer)
275     return nullptr;
276   MemoryBufferRef mbref = *buffer;
277   InputFile *newFile = nullptr;
278 
279   file_magic magic = identify_magic(mbref.getBuffer());
280   switch (magic) {
281   case file_magic::archive: {
282     bool isCommandLineLoad = loadType != LoadType::LCLinkerOption;
283     // Avoid loading archives twice. If the archives are being force-loaded,
284     // loading them twice would create duplicate symbol errors. In the
285     // non-force-loading case, this is just a minor performance optimization.
286     // We don't take a reference to cachedFile here because the
287     // loadArchiveMember() call below may recursively call addFile() and
288     // invalidate this reference.
289     auto entry = loadedArchives.find(path);
290 
291     ArchiveFile *file;
292     if (entry == loadedArchives.end()) {
293       // No cached archive, we need to create a new one
294       std::unique_ptr<object::Archive> archive = CHECK(
295           object::Archive::create(mbref), path + ": failed to parse archive");
296 
297       if (!archive->isEmpty() && !archive->hasSymbolTable())
298         error(path + ": archive has no index; run ranlib to add one");
299       file = make<ArchiveFile>(std::move(archive), isForceHidden);
300     } else {
301       file = entry->second.file;
302       // Command-line loads take precedence. If file is previously loaded via
303       // command line, or is loaded via LC_LINKER_OPTION and being loaded via
304       // LC_LINKER_OPTION again, using the cached archive is enough.
305       if (entry->second.isCommandLineLoad || !isCommandLineLoad)
306         return file;
307     }
308 
309     bool isLCLinkerForceLoad = loadType == LoadType::LCLinkerOption &&
310                                config->forceLoadSwift &&
311                                path::filename(path).starts_with("libswift");
312     if ((isCommandLineLoad && config->allLoad) ||
313         loadType == LoadType::CommandLineForce || isLCLinkerForceLoad) {
314       if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
315         Error e = Error::success();
316         for (const object::Archive::Child &c : file->getArchive().children(e)) {
317           StringRef reason;
318           switch (loadType) {
319             case LoadType::LCLinkerOption:
320               reason = "LC_LINKER_OPTION";
321               break;
322             case LoadType::CommandLineForce:
323               reason = "-force_load";
324               break;
325             case LoadType::CommandLine:
326               reason = "-all_load";
327               break;
328           }
329           if (Error e = file->fetch(c, reason))
330             error(toString(file) + ": " + reason +
331                   " failed to load archive member: " + toString(std::move(e)));
332         }
333         if (e)
334           error(toString(file) +
335                 ": Archive::children failed: " + toString(std::move(e)));
336       }
337     } else if (isCommandLineLoad && config->forceLoadObjC) {
338       for (const object::Archive::Symbol &sym : file->getArchive().symbols())
339         if (sym.getName().starts_with(objc::klass))
340           file->fetch(sym);
341 
342       // TODO: no need to look for ObjC sections for a given archive member if
343       // we already found that it contains an ObjC symbol.
344       if (std::optional<MemoryBufferRef> buffer = readFile(path)) {
345         Error e = Error::success();
346         for (const object::Archive::Child &c : file->getArchive().children(e)) {
347           Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
348           if (!mb || !hasObjCSection(*mb))
349             continue;
350           if (Error e = file->fetch(c, "-ObjC"))
351             error(toString(file) + ": -ObjC failed to load archive member: " +
352                   toString(std::move(e)));
353         }
354         if (e)
355           error(toString(file) +
356                 ": Archive::children failed: " + toString(std::move(e)));
357       }
358     }
359 
360     file->addLazySymbols();
361     loadedArchives[path] = ArchiveFileInfo{file, isCommandLineLoad};
362     newFile = file;
363     break;
364   }
365   case file_magic::macho_object:
366     newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy);
367     break;
368   case file_magic::macho_dynamically_linked_shared_lib:
369   case file_magic::macho_dynamically_linked_shared_lib_stub:
370   case file_magic::tapi_file:
371     if (DylibFile *dylibFile =
372             loadDylib(mbref, nullptr, /*isBundleLoader=*/false, isExplicit))
373       newFile = dylibFile;
374     break;
375   case file_magic::bitcode:
376     newFile = make<BitcodeFile>(mbref, "", 0, isLazy);
377     break;
378   case file_magic::macho_executable:
379   case file_magic::macho_bundle:
380     // We only allow executable and bundle type here if it is used
381     // as a bundle loader.
382     if (!isBundleLoader)
383       error(path + ": unhandled file type");
384     if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader))
385       newFile = dylibFile;
386     break;
387   default:
388     error(path + ": unhandled file type");
389   }
390   if (newFile && !isa<DylibFile>(newFile)) {
391     if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy &&
392         config->forceLoadObjC) {
393       for (Symbol *sym : newFile->symbols)
394         if (sym && sym->getName().starts_with(objc::klass)) {
395           extract(*newFile, "-ObjC");
396           break;
397         }
398       if (newFile->lazy && hasObjCSection(mbref))
399         extract(*newFile, "-ObjC");
400     }
401 
402     // printArchiveMemberLoad() prints both .a and .o names, so no need to
403     // print the .a name here. Similarly skip lazy files.
404     if (config->printEachFile && magic != file_magic::archive && !isLazy)
405       message(toString(newFile));
406     inputFiles.insert(newFile);
407   }
408   return newFile;
409 }
410 
411 static std::vector<StringRef> missingAutolinkWarnings;
412 static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
413                        bool isReexport, bool isHidden, bool isExplicit,
414                        LoadType loadType, InputFile *originFile = nullptr) {
415   if (std::optional<StringRef> path = findLibrary(name)) {
416     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
417             addFile(*path, loadType, /*isLazy=*/false, isExplicit,
418                     /*isBundleLoader=*/false, isHidden))) {
419       if (isNeeded)
420         dylibFile->forceNeeded = true;
421       if (isWeak)
422         dylibFile->forceWeakImport = true;
423       if (isReexport) {
424         config->hasReexports = true;
425         dylibFile->reexport = true;
426       }
427     }
428     return;
429   }
430   if (loadType == LoadType::LCLinkerOption) {
431     assert(originFile);
432     missingAutolinkWarnings.push_back(
433         saver().save(toString(originFile) +
434                      ": auto-linked library not found for -l" + name));
435     return;
436   }
437   error("library not found for -l" + name);
438 }
439 
440 static DenseSet<StringRef> loadedObjectFrameworks;
441 static void addFramework(StringRef name, bool isNeeded, bool isWeak,
442                          bool isReexport, bool isExplicit, LoadType loadType,
443                          InputFile *originFile = nullptr) {
444   if (std::optional<StringRef> path = findFramework(name)) {
445     if (loadedObjectFrameworks.contains(*path))
446       return;
447 
448     InputFile *file =
449         addFile(*path, loadType, /*isLazy=*/false, isExplicit, false);
450     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) {
451       if (isNeeded)
452         dylibFile->forceNeeded = true;
453       if (isWeak)
454         dylibFile->forceWeakImport = true;
455       if (isReexport) {
456         config->hasReexports = true;
457         dylibFile->reexport = true;
458       }
459     } else if (isa_and_nonnull<ObjFile>(file) ||
460                isa_and_nonnull<BitcodeFile>(file)) {
461       // Cache frameworks containing object or bitcode files to avoid duplicate
462       // symbols. Frameworks containing static archives are cached separately
463       // in addFile() to share caching with libraries, and frameworks
464       // containing dylibs should allow overwriting of attributes such as
465       // forceNeeded by subsequent loads
466       loadedObjectFrameworks.insert(*path);
467     }
468     return;
469   }
470   if (loadType == LoadType::LCLinkerOption) {
471     assert(originFile);
472     missingAutolinkWarnings.push_back(saver().save(
473         toString(originFile) +
474         ": auto-linked framework not found for -framework " + name));
475     return;
476   }
477   error("framework not found for -framework " + name);
478 }
479 
480 // Parses LC_LINKER_OPTION contents, which can add additional command line
481 // flags. This directly parses the flags instead of using the standard argument
482 // parser to improve performance.
483 void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) {
484   if (config->ignoreAutoLink)
485     return;
486 
487   SmallVector<StringRef, 4> argv;
488   size_t offset = 0;
489   for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
490     argv.push_back(data.data() + offset);
491     offset += strlen(data.data() + offset) + 1;
492   }
493   if (argv.size() != argc || offset > data.size())
494     fatal(toString(f) + ": invalid LC_LINKER_OPTION");
495 
496   unsigned i = 0;
497   StringRef arg = argv[i];
498   if (arg.consume_front("-l")) {
499     if (config->ignoreAutoLinkOptions.contains(arg))
500       return;
501     addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false,
502                /*isReexport=*/false, /*isHidden=*/false, /*isExplicit=*/false,
503                LoadType::LCLinkerOption, f);
504   } else if (arg == "-framework") {
505     StringRef name = argv[++i];
506     if (config->ignoreAutoLinkOptions.contains(name))
507       return;
508     addFramework(name, /*isNeeded=*/false, /*isWeak=*/false,
509                  /*isReexport=*/false, /*isExplicit=*/false,
510                  LoadType::LCLinkerOption, f);
511   } else {
512     error(arg + " is not allowed in LC_LINKER_OPTION");
513   }
514 }
515 
516 static void addFileList(StringRef path, bool isLazy) {
517   std::optional<MemoryBufferRef> buffer = readFile(path);
518   if (!buffer)
519     return;
520   MemoryBufferRef mbref = *buffer;
521   for (StringRef path : args::getLines(mbref))
522     addFile(rerootPath(path), LoadType::CommandLine, isLazy);
523 }
524 
525 // We expect sub-library names of the form "libfoo", which will match a dylib
526 // with a path of .*/libfoo.{dylib, tbd}.
527 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
528 // I'm not sure what the use case for that is.
529 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
530   for (InputFile *file : inputFiles) {
531     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
532       StringRef filename = path::filename(dylibFile->getName());
533       if (filename.consume_front(searchName) &&
534           (filename.empty() || llvm::is_contained(extensions, filename))) {
535         dylibFile->reexport = true;
536         return true;
537       }
538     }
539   }
540   return false;
541 }
542 
543 // This function is called on startup. We need this for LTO since
544 // LTO calls LLVM functions to compile bitcode files to native code.
545 // Technically this can be delayed until we read bitcode files, but
546 // we don't bother to do lazily because the initialization is fast.
547 static void initLLVM() {
548   InitializeAllTargets();
549   InitializeAllTargetMCs();
550   InitializeAllAsmPrinters();
551   InitializeAllAsmParsers();
552 }
553 
554 static bool compileBitcodeFiles() {
555   TimeTraceScope timeScope("LTO");
556   auto *lto = make<BitcodeCompiler>();
557   for (InputFile *file : inputFiles)
558     if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
559       if (!file->lazy)
560         lto->add(*bitcodeFile);
561 
562   std::vector<ObjFile *> compiled = lto->compile();
563   for (ObjFile *file : compiled)
564     inputFiles.insert(file);
565 
566   return !compiled.empty();
567 }
568 
569 // Replaces common symbols with defined symbols residing in __common sections.
570 // This function must be called after all symbol names are resolved (i.e. after
571 // all InputFiles have been loaded.) As a result, later operations won't see
572 // any CommonSymbols.
573 static void replaceCommonSymbols() {
574   TimeTraceScope timeScope("Replace common symbols");
575   ConcatOutputSection *osec = nullptr;
576   for (Symbol *sym : symtab->getSymbols()) {
577     auto *common = dyn_cast<CommonSymbol>(sym);
578     if (common == nullptr)
579       continue;
580 
581     // Casting to size_t will truncate large values on 32-bit architectures,
582     // but it's not really worth supporting the linking of 64-bit programs on
583     // 32-bit archs.
584     ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};
585     // FIXME avoid creating one Section per symbol?
586     auto *section =
587         make<Section>(common->getFile(), segment_names::data,
588                       section_names::common, S_ZEROFILL, /*addr=*/0);
589     auto *isec = make<ConcatInputSection>(*section, data, common->align);
590     if (!osec)
591       osec = ConcatOutputSection::getOrCreateForInput(isec);
592     isec->parent = osec;
593     inputSections.push_back(isec);
594 
595     // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
596     // and pass them on here.
597     replaceSymbol<Defined>(
598         sym, sym->getName(), common->getFile(), isec, /*value=*/0, common->size,
599         /*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern,
600         /*includeInSymtab=*/true, /*isReferencedDynamically=*/false,
601         /*noDeadStrip=*/false);
602   }
603 }
604 
605 static void initializeSectionRenameMap() {
606   if (config->dataConst) {
607     SmallVector<StringRef> v{section_names::got,
608                              section_names::authGot,
609                              section_names::authPtr,
610                              section_names::nonLazySymbolPtr,
611                              section_names::const_,
612                              section_names::cfString,
613                              section_names::moduleInitFunc,
614                              section_names::moduleTermFunc,
615                              section_names::objcClassList,
616                              section_names::objcNonLazyClassList,
617                              section_names::objcCatList,
618                              section_names::objcNonLazyCatList,
619                              section_names::objcProtoList,
620                              section_names::objCImageInfo};
621     for (StringRef s : v)
622       config->sectionRenameMap[{segment_names::data, s}] = {
623           segment_names::dataConst, s};
624   }
625   config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
626       segment_names::text, section_names::text};
627   config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
628       config->dataConst ? segment_names::dataConst : segment_names::data,
629       section_names::nonLazySymbolPtr};
630 }
631 
632 static inline char toLowerDash(char x) {
633   if (x >= 'A' && x <= 'Z')
634     return x - 'A' + 'a';
635   else if (x == ' ')
636     return '-';
637   return x;
638 }
639 
640 static std::string lowerDash(StringRef s) {
641   return std::string(map_iterator(s.begin(), toLowerDash),
642                      map_iterator(s.end(), toLowerDash));
643 }
644 
645 struct PlatformVersion {
646   PlatformType platform = PLATFORM_UNKNOWN;
647   llvm::VersionTuple minimum;
648   llvm::VersionTuple sdk;
649 };
650 
651 static PlatformVersion parsePlatformVersion(const Arg *arg) {
652   assert(arg->getOption().getID() == OPT_platform_version);
653   StringRef platformStr = arg->getValue(0);
654   StringRef minVersionStr = arg->getValue(1);
655   StringRef sdkVersionStr = arg->getValue(2);
656 
657   PlatformVersion platformVersion;
658 
659   // TODO(compnerd) see if we can generate this case list via XMACROS
660   platformVersion.platform =
661       StringSwitch<PlatformType>(lowerDash(platformStr))
662           .Cases("macos", "1", PLATFORM_MACOS)
663           .Cases("ios", "2", PLATFORM_IOS)
664           .Cases("tvos", "3", PLATFORM_TVOS)
665           .Cases("watchos", "4", PLATFORM_WATCHOS)
666           .Cases("bridgeos", "5", PLATFORM_BRIDGEOS)
667           .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST)
668           .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR)
669           .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR)
670           .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR)
671           .Cases("driverkit", "10", PLATFORM_DRIVERKIT)
672           .Default(PLATFORM_UNKNOWN);
673   if (platformVersion.platform == PLATFORM_UNKNOWN)
674     error(Twine("malformed platform: ") + platformStr);
675   // TODO: check validity of version strings, which varies by platform
676   // NOTE: ld64 accepts version strings with 5 components
677   // llvm::VersionTuple accepts no more than 4 components
678   // Has Apple ever published version strings with 5 components?
679   if (platformVersion.minimum.tryParse(minVersionStr))
680     error(Twine("malformed minimum version: ") + minVersionStr);
681   if (platformVersion.sdk.tryParse(sdkVersionStr))
682     error(Twine("malformed sdk version: ") + sdkVersionStr);
683   return platformVersion;
684 }
685 
686 // Has the side-effect of setting Config::platformInfo and
687 // potentially Config::secondaryPlatformInfo.
688 static void setPlatformVersions(StringRef archName, const ArgList &args) {
689   std::map<PlatformType, PlatformVersion> platformVersions;
690   const PlatformVersion *lastVersionInfo = nullptr;
691   for (const Arg *arg : args.filtered(OPT_platform_version)) {
692     PlatformVersion version = parsePlatformVersion(arg);
693 
694     // For each platform, the last flag wins:
695     // `-platform_version macos 2 3 -platform_version macos 4 5` has the same
696     // effect as just passing `-platform_version macos 4 5`.
697     // FIXME: ld64 warns on multiple flags for one platform. Should we?
698     platformVersions[version.platform] = version;
699     lastVersionInfo = &platformVersions[version.platform];
700   }
701 
702   if (platformVersions.empty()) {
703     error("must specify -platform_version");
704     return;
705   }
706   if (platformVersions.size() > 2) {
707     error("must specify -platform_version at most twice");
708     return;
709   }
710   if (platformVersions.size() == 2) {
711     bool isZipperedCatalyst = platformVersions.count(PLATFORM_MACOS) &&
712                               platformVersions.count(PLATFORM_MACCATALYST);
713 
714     if (!isZipperedCatalyst) {
715       error("lld supports writing zippered outputs only for "
716             "macos and mac-catalyst");
717     } else if (config->outputType != MH_DYLIB &&
718                config->outputType != MH_BUNDLE) {
719       error("writing zippered outputs only valid for -dylib and -bundle");
720     }
721 
722     config->platformInfo = {
723         MachO::Target(getArchitectureFromName(archName), PLATFORM_MACOS,
724                       platformVersions[PLATFORM_MACOS].minimum),
725         platformVersions[PLATFORM_MACOS].sdk};
726     config->secondaryPlatformInfo = {
727         MachO::Target(getArchitectureFromName(archName), PLATFORM_MACCATALYST,
728                       platformVersions[PLATFORM_MACCATALYST].minimum),
729         platformVersions[PLATFORM_MACCATALYST].sdk};
730     return;
731   }
732 
733   config->platformInfo = {MachO::Target(getArchitectureFromName(archName),
734                                         lastVersionInfo->platform,
735                                         lastVersionInfo->minimum),
736                           lastVersionInfo->sdk};
737 }
738 
739 // Has the side-effect of setting Config::target.
740 static TargetInfo *createTargetInfo(InputArgList &args) {
741   StringRef archName = args.getLastArgValue(OPT_arch);
742   if (archName.empty()) {
743     error("must specify -arch");
744     return nullptr;
745   }
746 
747   setPlatformVersions(archName, args);
748   auto [cpuType, cpuSubtype] = getCPUTypeFromArchitecture(config->arch());
749   switch (cpuType) {
750   case CPU_TYPE_X86_64:
751     return createX86_64TargetInfo();
752   case CPU_TYPE_ARM64:
753     return createARM64TargetInfo();
754   case CPU_TYPE_ARM64_32:
755     return createARM64_32TargetInfo();
756   default:
757     error("missing or unsupported -arch " + archName);
758     return nullptr;
759   }
760 }
761 
762 static UndefinedSymbolTreatment
763 getUndefinedSymbolTreatment(const ArgList &args) {
764   StringRef treatmentStr = args.getLastArgValue(OPT_undefined);
765   auto treatment =
766       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
767           .Cases("error", "", UndefinedSymbolTreatment::error)
768           .Case("warning", UndefinedSymbolTreatment::warning)
769           .Case("suppress", UndefinedSymbolTreatment::suppress)
770           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
771           .Default(UndefinedSymbolTreatment::unknown);
772   if (treatment == UndefinedSymbolTreatment::unknown) {
773     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
774          "', defaulting to 'error'");
775     treatment = UndefinedSymbolTreatment::error;
776   } else if (config->namespaceKind == NamespaceKind::twolevel &&
777              (treatment == UndefinedSymbolTreatment::warning ||
778               treatment == UndefinedSymbolTreatment::suppress)) {
779     if (treatment == UndefinedSymbolTreatment::warning)
780       fatal("'-undefined warning' only valid with '-flat_namespace'");
781     else
782       fatal("'-undefined suppress' only valid with '-flat_namespace'");
783     treatment = UndefinedSymbolTreatment::error;
784   }
785   return treatment;
786 }
787 
788 static ICFLevel getICFLevel(const ArgList &args) {
789   StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq);
790   auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
791                       .Cases("none", "", ICFLevel::none)
792                       .Case("safe", ICFLevel::safe)
793                       .Case("all", ICFLevel::all)
794                       .Default(ICFLevel::unknown);
795   if (icfLevel == ICFLevel::unknown) {
796     warn(Twine("unknown --icf=OPTION `") + icfLevelStr +
797          "', defaulting to `none'");
798     icfLevel = ICFLevel::none;
799   }
800   return icfLevel;
801 }
802 
803 static ObjCStubsMode getObjCStubsMode(const ArgList &args) {
804   const Arg *arg = args.getLastArg(OPT_objc_stubs_fast, OPT_objc_stubs_small);
805   if (!arg)
806     return ObjCStubsMode::fast;
807 
808   if (arg->getOption().getID() == OPT_objc_stubs_small)
809     warn("-objc_stubs_small is not yet implemented, defaulting to "
810          "-objc_stubs_fast");
811   return ObjCStubsMode::fast;
812 }
813 
814 static void warnIfDeprecatedOption(const Option &opt) {
815   if (!opt.getGroup().isValid())
816     return;
817   if (opt.getGroup().getID() == OPT_grp_deprecated) {
818     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
819     warn(opt.getHelpText());
820   }
821 }
822 
823 static void warnIfUnimplementedOption(const Option &opt) {
824   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
825     return;
826   switch (opt.getGroup().getID()) {
827   case OPT_grp_deprecated:
828     // warn about deprecated options elsewhere
829     break;
830   case OPT_grp_undocumented:
831     warn("Option `" + opt.getPrefixedName() +
832          "' is undocumented. Should lld implement it?");
833     break;
834   case OPT_grp_obsolete:
835     warn("Option `" + opt.getPrefixedName() +
836          "' is obsolete. Please modernize your usage.");
837     break;
838   case OPT_grp_ignored:
839     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
840     break;
841   case OPT_grp_ignored_silently:
842     break;
843   default:
844     warn("Option `" + opt.getPrefixedName() +
845          "' is not yet implemented. Stay tuned...");
846     break;
847   }
848 }
849 
850 static const char *getReproduceOption(InputArgList &args) {
851   if (const Arg *arg = args.getLastArg(OPT_reproduce))
852     return arg->getValue();
853   return getenv("LLD_REPRODUCE");
854 }
855 
856 // Parse options of the form "old;new".
857 static std::pair<StringRef, StringRef> getOldNewOptions(opt::InputArgList &args,
858                                                         unsigned id) {
859   auto *arg = args.getLastArg(id);
860   if (!arg)
861     return {"", ""};
862 
863   StringRef s = arg->getValue();
864   std::pair<StringRef, StringRef> ret = s.split(';');
865   if (ret.second.empty())
866     error(arg->getSpelling() + " expects 'old;new' format, but got " + s);
867   return ret;
868 }
869 
870 // Parse options of the form "old;new[;extra]".
871 static std::tuple<StringRef, StringRef, StringRef>
872 getOldNewOptionsExtra(opt::InputArgList &args, unsigned id) {
873   auto [oldDir, second] = getOldNewOptions(args, id);
874   auto [newDir, extraDir] = second.split(';');
875   return {oldDir, newDir, extraDir};
876 }
877 
878 static void parseClangOption(StringRef opt, const Twine &msg) {
879   std::string err;
880   raw_string_ostream os(err);
881 
882   const char *argv[] = {"lld", opt.data()};
883   if (cl::ParseCommandLineOptions(2, argv, "", &os))
884     return;
885   os.flush();
886   error(msg + ": " + StringRef(err).trim());
887 }
888 
889 static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
890   const Arg *arg = args.getLastArg(id);
891   if (!arg)
892     return 0;
893 
894   if (config->outputType != MH_DYLIB) {
895     error(arg->getAsString(args) + ": only valid with -dylib");
896     return 0;
897   }
898 
899   PackedVersion version;
900   if (!version.parse32(arg->getValue())) {
901     error(arg->getAsString(args) + ": malformed version");
902     return 0;
903   }
904 
905   return version.rawValue();
906 }
907 
908 static uint32_t parseProtection(StringRef protStr) {
909   uint32_t prot = 0;
910   for (char c : protStr) {
911     switch (c) {
912     case 'r':
913       prot |= VM_PROT_READ;
914       break;
915     case 'w':
916       prot |= VM_PROT_WRITE;
917       break;
918     case 'x':
919       prot |= VM_PROT_EXECUTE;
920       break;
921     case '-':
922       break;
923     default:
924       error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);
925       return 0;
926     }
927   }
928   return prot;
929 }
930 
931 static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
932   std::vector<SectionAlign> sectAligns;
933   for (const Arg *arg : args.filtered(OPT_sectalign)) {
934     StringRef segName = arg->getValue(0);
935     StringRef sectName = arg->getValue(1);
936     StringRef alignStr = arg->getValue(2);
937     if (alignStr.starts_with("0x") || alignStr.starts_with("0X"))
938       alignStr = alignStr.drop_front(2);
939     uint32_t align;
940     if (alignStr.getAsInteger(16, align)) {
941       error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +
942             "' as number");
943       continue;
944     }
945     if (!isPowerOf2_32(align)) {
946       error("-sectalign: '" + StringRef(arg->getValue(2)) +
947             "' (in base 16) not a power of two");
948       continue;
949     }
950     sectAligns.push_back({segName, sectName, align});
951   }
952   return sectAligns;
953 }
954 
955 PlatformType macho::removeSimulator(PlatformType platform) {
956   switch (platform) {
957   case PLATFORM_IOSSIMULATOR:
958     return PLATFORM_IOS;
959   case PLATFORM_TVOSSIMULATOR:
960     return PLATFORM_TVOS;
961   case PLATFORM_WATCHOSSIMULATOR:
962     return PLATFORM_WATCHOS;
963   default:
964     return platform;
965   }
966 }
967 
968 static bool supportsNoPie() {
969   return !(config->arch() == AK_arm64 || config->arch() == AK_arm64e ||
970            config->arch() == AK_arm64_32);
971 }
972 
973 static bool shouldAdhocSignByDefault(Architecture arch, PlatformType platform) {
974   if (arch != AK_arm64 && arch != AK_arm64e)
975     return false;
976 
977   return platform == PLATFORM_MACOS || platform == PLATFORM_IOSSIMULATOR ||
978          platform == PLATFORM_TVOSSIMULATOR ||
979          platform == PLATFORM_WATCHOSSIMULATOR;
980 }
981 
982 static bool dataConstDefault(const InputArgList &args) {
983   static const std::array<std::pair<PlatformType, VersionTuple>, 5> minVersion =
984       {{{PLATFORM_MACOS, VersionTuple(10, 15)},
985         {PLATFORM_IOS, VersionTuple(13, 0)},
986         {PLATFORM_TVOS, VersionTuple(13, 0)},
987         {PLATFORM_WATCHOS, VersionTuple(6, 0)},
988         {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}}};
989   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
990   auto it = llvm::find_if(minVersion,
991                           [&](const auto &p) { return p.first == platform; });
992   if (it != minVersion.end())
993     if (config->platformInfo.target.MinDeployment < it->second)
994       return false;
995 
996   switch (config->outputType) {
997   case MH_EXECUTE:
998     return !(args.hasArg(OPT_no_pie) && supportsNoPie());
999   case MH_BUNDLE:
1000     // FIXME: return false when -final_name ...
1001     // has prefix "/System/Library/UserEventPlugins/"
1002     // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
1003     return true;
1004   case MH_DYLIB:
1005     return true;
1006   case MH_OBJECT:
1007     return false;
1008   default:
1009     llvm_unreachable(
1010         "unsupported output type for determining data-const default");
1011   }
1012   return false;
1013 }
1014 
1015 static bool shouldEmitChainedFixups(const InputArgList &args) {
1016   const Arg *arg = args.getLastArg(OPT_fixup_chains, OPT_no_fixup_chains);
1017   if (arg && arg->getOption().matches(OPT_no_fixup_chains))
1018     return false;
1019 
1020   bool isRequested = arg != nullptr;
1021 
1022   // Version numbers taken from the Xcode 13.3 release notes.
1023   static const std::array<std::pair<PlatformType, VersionTuple>, 4> minVersion =
1024       {{{PLATFORM_MACOS, VersionTuple(11, 0)},
1025         {PLATFORM_IOS, VersionTuple(13, 4)},
1026         {PLATFORM_TVOS, VersionTuple(14, 0)},
1027         {PLATFORM_WATCHOS, VersionTuple(7, 0)}}};
1028   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
1029   auto it = llvm::find_if(minVersion,
1030                           [&](const auto &p) { return p.first == platform; });
1031   if (it != minVersion.end() &&
1032       it->second > config->platformInfo.target.MinDeployment) {
1033     if (!isRequested)
1034       return false;
1035 
1036     warn("-fixup_chains requires " + getPlatformName(config->platform()) + " " +
1037          it->second.getAsString() + ", which is newer than target minimum of " +
1038          config->platformInfo.target.MinDeployment.getAsString());
1039   }
1040 
1041   if (!is_contained({AK_x86_64, AK_x86_64h, AK_arm64}, config->arch())) {
1042     if (isRequested)
1043       error("-fixup_chains is only supported on x86_64 and arm64 targets");
1044     return false;
1045   }
1046 
1047   if (!config->isPic) {
1048     if (isRequested)
1049       error("-fixup_chains is incompatible with -no_pie");
1050     return false;
1051   }
1052 
1053   // TODO: Enable by default once stable.
1054   return isRequested;
1055 }
1056 
1057 void SymbolPatterns::clear() {
1058   literals.clear();
1059   globs.clear();
1060 }
1061 
1062 void SymbolPatterns::insert(StringRef symbolName) {
1063   if (symbolName.find_first_of("*?[]") == StringRef::npos)
1064     literals.insert(CachedHashStringRef(symbolName));
1065   else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))
1066     globs.emplace_back(*pattern);
1067   else
1068     error("invalid symbol-name pattern: " + symbolName);
1069 }
1070 
1071 bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
1072   return literals.contains(CachedHashStringRef(symbolName));
1073 }
1074 
1075 bool SymbolPatterns::matchGlob(StringRef symbolName) const {
1076   for (const GlobPattern &glob : globs)
1077     if (glob.match(symbolName))
1078       return true;
1079   return false;
1080 }
1081 
1082 bool SymbolPatterns::match(StringRef symbolName) const {
1083   return matchLiteral(symbolName) || matchGlob(symbolName);
1084 }
1085 
1086 static void parseSymbolPatternsFile(const Arg *arg,
1087                                     SymbolPatterns &symbolPatterns) {
1088   StringRef path = arg->getValue();
1089   std::optional<MemoryBufferRef> buffer = readFile(path);
1090   if (!buffer) {
1091     error("Could not read symbol file: " + path);
1092     return;
1093   }
1094   MemoryBufferRef mbref = *buffer;
1095   for (StringRef line : args::getLines(mbref)) {
1096     line = line.take_until([](char c) { return c == '#'; }).trim();
1097     if (!line.empty())
1098       symbolPatterns.insert(line);
1099   }
1100 }
1101 
1102 static void handleSymbolPatterns(InputArgList &args,
1103                                  SymbolPatterns &symbolPatterns,
1104                                  unsigned singleOptionCode,
1105                                  unsigned listFileOptionCode) {
1106   for (const Arg *arg : args.filtered(singleOptionCode))
1107     symbolPatterns.insert(arg->getValue());
1108   for (const Arg *arg : args.filtered(listFileOptionCode))
1109     parseSymbolPatternsFile(arg, symbolPatterns);
1110 }
1111 
1112 static void createFiles(const InputArgList &args) {
1113   TimeTraceScope timeScope("Load input files");
1114   // This loop should be reserved for options whose exact ordering matters.
1115   // Other options should be handled via filtered() and/or getLastArg().
1116   bool isLazy = false;
1117   for (const Arg *arg : args) {
1118     const Option &opt = arg->getOption();
1119     warnIfDeprecatedOption(opt);
1120     warnIfUnimplementedOption(opt);
1121 
1122     switch (opt.getID()) {
1123     case OPT_INPUT:
1124       addFile(rerootPath(arg->getValue()), LoadType::CommandLine, isLazy);
1125       break;
1126     case OPT_needed_library:
1127       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1128               addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))
1129         dylibFile->forceNeeded = true;
1130       break;
1131     case OPT_reexport_library:
1132       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1133               addFile(rerootPath(arg->getValue()), LoadType::CommandLine))) {
1134         config->hasReexports = true;
1135         dylibFile->reexport = true;
1136       }
1137       break;
1138     case OPT_weak_library:
1139       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
1140               addFile(rerootPath(arg->getValue()), LoadType::CommandLine)))
1141         dylibFile->forceWeakImport = true;
1142       break;
1143     case OPT_filelist:
1144       addFileList(arg->getValue(), isLazy);
1145       break;
1146     case OPT_force_load:
1147       addFile(rerootPath(arg->getValue()), LoadType::CommandLineForce);
1148       break;
1149     case OPT_load_hidden:
1150       addFile(rerootPath(arg->getValue()), LoadType::CommandLine,
1151               /*isLazy=*/false, /*isExplicit=*/true, /*isBundleLoader=*/false,
1152               /*isForceHidden=*/true);
1153       break;
1154     case OPT_l:
1155     case OPT_needed_l:
1156     case OPT_reexport_l:
1157     case OPT_weak_l:
1158     case OPT_hidden_l:
1159       addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,
1160                  opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,
1161                  opt.getID() == OPT_hidden_l,
1162                  /*isExplicit=*/true, LoadType::CommandLine);
1163       break;
1164     case OPT_framework:
1165     case OPT_needed_framework:
1166     case OPT_reexport_framework:
1167     case OPT_weak_framework:
1168       addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,
1169                    opt.getID() == OPT_weak_framework,
1170                    opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
1171                    LoadType::CommandLine);
1172       break;
1173     case OPT_start_lib:
1174       if (isLazy)
1175         error("nested --start-lib");
1176       isLazy = true;
1177       break;
1178     case OPT_end_lib:
1179       if (!isLazy)
1180         error("stray --end-lib");
1181       isLazy = false;
1182       break;
1183     default:
1184       break;
1185     }
1186   }
1187 }
1188 
1189 static void gatherInputSections() {
1190   TimeTraceScope timeScope("Gathering input sections");
1191   int inputOrder = 0;
1192   for (const InputFile *file : inputFiles) {
1193     for (const Section *section : file->sections) {
1194       // Compact unwind entries require special handling elsewhere. (In
1195       // contrast, EH frames are handled like regular ConcatInputSections.)
1196       if (section->name == section_names::compactUnwind)
1197         continue;
1198       ConcatOutputSection *osec = nullptr;
1199       for (const Subsection &subsection : section->subsections) {
1200         if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) {
1201           if (isec->isCoalescedWeak())
1202             continue;
1203           if (config->emitInitOffsets &&
1204               sectionType(isec->getFlags()) == S_MOD_INIT_FUNC_POINTERS) {
1205             in.initOffsets->addInput(isec);
1206             continue;
1207           }
1208           isec->outSecOff = inputOrder++;
1209           if (!osec)
1210             osec = ConcatOutputSection::getOrCreateForInput(isec);
1211           isec->parent = osec;
1212           inputSections.push_back(isec);
1213         } else if (auto *isec =
1214                        dyn_cast<CStringInputSection>(subsection.isec)) {
1215           if (isec->getName() == section_names::objcMethname) {
1216             if (in.objcMethnameSection->inputOrder == UnspecifiedInputOrder)
1217               in.objcMethnameSection->inputOrder = inputOrder++;
1218             in.objcMethnameSection->addInput(isec);
1219           } else {
1220             if (in.cStringSection->inputOrder == UnspecifiedInputOrder)
1221               in.cStringSection->inputOrder = inputOrder++;
1222             in.cStringSection->addInput(isec);
1223           }
1224         } else if (auto *isec =
1225                        dyn_cast<WordLiteralInputSection>(subsection.isec)) {
1226           if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder)
1227             in.wordLiteralSection->inputOrder = inputOrder++;
1228           in.wordLiteralSection->addInput(isec);
1229         } else {
1230           llvm_unreachable("unexpected input section kind");
1231         }
1232       }
1233     }
1234     if (!file->objCImageInfo.empty())
1235       in.objCImageInfo->addFile(file);
1236   }
1237   assert(inputOrder <= UnspecifiedInputOrder);
1238 }
1239 
1240 static void foldIdenticalLiterals() {
1241   TimeTraceScope timeScope("Fold identical literals");
1242   // We always create a cStringSection, regardless of whether dedupLiterals is
1243   // true. If it isn't, we simply create a non-deduplicating CStringSection.
1244   // Either way, we must unconditionally finalize it here.
1245   in.cStringSection->finalizeContents();
1246   in.objcMethnameSection->finalizeContents();
1247   in.wordLiteralSection->finalizeContents();
1248 }
1249 
1250 static void addSynthenticMethnames() {
1251   std::string &data = *make<std::string>();
1252   llvm::raw_string_ostream os(data);
1253   const int prefixLength = ObjCStubsSection::symbolPrefix.size();
1254   for (Symbol *sym : symtab->getSymbols())
1255     if (isa<Undefined>(sym))
1256       if (sym->getName().starts_with(ObjCStubsSection::symbolPrefix))
1257         os << sym->getName().drop_front(prefixLength) << '\0';
1258 
1259   if (data.empty())
1260     return;
1261 
1262   const auto *buf = reinterpret_cast<const uint8_t *>(data.c_str());
1263   Section &section = *make<Section>(/*file=*/nullptr, segment_names::text,
1264                                     section_names::objcMethname,
1265                                     S_CSTRING_LITERALS, /*addr=*/0);
1266 
1267   auto *isec =
1268       make<CStringInputSection>(section, ArrayRef<uint8_t>{buf, data.size()},
1269                                 /*align=*/1, /*dedupLiterals=*/true);
1270   isec->splitIntoPieces();
1271   for (auto &piece : isec->pieces)
1272     piece.live = true;
1273   section.subsections.push_back({0, isec});
1274   in.objcMethnameSection->addInput(isec);
1275   in.objcMethnameSection->isec->markLive(0);
1276 }
1277 
1278 static void referenceStubBinder() {
1279   bool needsStubHelper = config->outputType == MH_DYLIB ||
1280                          config->outputType == MH_EXECUTE ||
1281                          config->outputType == MH_BUNDLE;
1282   if (!needsStubHelper || !symtab->find("dyld_stub_binder"))
1283     return;
1284 
1285   // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
1286   // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
1287   // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
1288   // isn't needed for correctness, but the presence of that symbol suppresses
1289   // "no symbols" diagnostics from `nm`.
1290   // StubHelperSection::setUp() adds a reference and errors out if
1291   // dyld_stub_binder doesn't exist in case it is actually needed.
1292   symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false);
1293 }
1294 
1295 static void createAliases() {
1296   for (const auto &pair : config->aliasedSymbols) {
1297     if (const auto &sym = symtab->find(pair.first)) {
1298       if (const auto &defined = dyn_cast<Defined>(sym)) {
1299         symtab->aliasDefined(defined, pair.second, defined->getFile())
1300             ->noDeadStrip = true;
1301       } else {
1302         error("TODO: support aliasing to symbols of kind " +
1303               Twine(sym->kind()));
1304       }
1305     } else {
1306       warn("undefined base symbol '" + pair.first + "' for alias '" +
1307            pair.second + "'\n");
1308     }
1309   }
1310 
1311   for (const InputFile *file : inputFiles) {
1312     if (auto *objFile = dyn_cast<ObjFile>(file)) {
1313       for (const AliasSymbol *alias : objFile->aliases) {
1314         if (const auto &aliased = symtab->find(alias->getAliasedName())) {
1315           if (const auto &defined = dyn_cast<Defined>(aliased)) {
1316             symtab->aliasDefined(defined, alias->getName(), alias->getFile(),
1317                                  alias->privateExtern);
1318           } else {
1319             // Common, dylib, and undefined symbols are all valid alias
1320             // referents (undefineds can become valid Defined symbols later on
1321             // in the link.)
1322             error("TODO: support aliasing to symbols of kind " +
1323                   Twine(aliased->kind()));
1324           }
1325         } else {
1326           // This shouldn't happen since MC generates undefined symbols to
1327           // represent the alias referents. Thus we fatal() instead of just
1328           // warning here.
1329           fatal("unable to find alias referent " + alias->getAliasedName() +
1330                 " for " + alias->getName());
1331         }
1332       }
1333     }
1334   }
1335 }
1336 
1337 static void handleExplicitExports() {
1338   if (config->hasExplicitExports) {
1339     parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1340       if (auto *defined = dyn_cast<Defined>(sym)) {
1341         if (config->exportedSymbols.match(sym->getName())) {
1342           if (defined->privateExtern) {
1343             if (defined->weakDefCanBeHidden) {
1344               // weak_def_can_be_hidden symbols behave similarly to
1345               // private_extern symbols in most cases, except for when
1346               // it is explicitly exported.
1347               // The former can be exported but the latter cannot.
1348               defined->privateExtern = false;
1349             } else {
1350               warn("cannot export hidden symbol " + toString(*defined) +
1351                    "\n>>> defined in " + toString(defined->getFile()));
1352             }
1353           }
1354         } else {
1355           defined->privateExtern = true;
1356         }
1357       } else if (auto *dysym = dyn_cast<DylibSymbol>(sym)) {
1358         dysym->shouldReexport = config->exportedSymbols.match(sym->getName());
1359       }
1360     });
1361   } else if (!config->unexportedSymbols.empty()) {
1362     parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1363       if (auto *defined = dyn_cast<Defined>(sym))
1364         if (config->unexportedSymbols.match(defined->getName()))
1365           defined->privateExtern = true;
1366     });
1367   }
1368 }
1369 
1370 namespace lld {
1371 namespace macho {
1372 bool link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1373           llvm::raw_ostream &stderrOS, bool exitEarly, bool disableOutput) {
1374   // This driver-specific context will be freed later by lldMain().
1375   auto *ctx = new CommonLinkerContext;
1376 
1377   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1378   ctx->e.cleanupCallback = []() {
1379     resolvedFrameworks.clear();
1380     resolvedLibraries.clear();
1381     cachedReads.clear();
1382     concatOutputSections.clear();
1383     inputFiles.clear();
1384     inputSections.clear();
1385     loadedArchives.clear();
1386     loadedObjectFrameworks.clear();
1387     missingAutolinkWarnings.clear();
1388     syntheticSections.clear();
1389     thunkMap.clear();
1390 
1391     firstTLVDataSection = nullptr;
1392     tar = nullptr;
1393     memset(&in, 0, sizeof(in));
1394 
1395     resetLoadedDylibs();
1396     resetOutputSegments();
1397     resetWriter();
1398     InputFile::resetIdCount();
1399   };
1400 
1401   ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]);
1402 
1403   MachOOptTable parser;
1404   InputArgList args = parser.parse(argsArr.slice(1));
1405 
1406   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
1407                                  "(use --error-limit=0 to see all errors)";
1408   ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);
1409   ctx->e.verbose = args.hasArg(OPT_verbose);
1410 
1411   if (args.hasArg(OPT_help_hidden)) {
1412     parser.printHelp(argsArr[0], /*showHidden=*/true);
1413     return true;
1414   }
1415   if (args.hasArg(OPT_help)) {
1416     parser.printHelp(argsArr[0], /*showHidden=*/false);
1417     return true;
1418   }
1419   if (args.hasArg(OPT_version)) {
1420     message(getLLDVersion());
1421     return true;
1422   }
1423 
1424   config = std::make_unique<Configuration>();
1425   symtab = std::make_unique<SymbolTable>();
1426   config->outputType = getOutputType(args);
1427   target = createTargetInfo(args);
1428   depTracker = std::make_unique<DependencyTracker>(
1429       args.getLastArgValue(OPT_dependency_info));
1430 
1431   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1432   if (config->ltoo > 3)
1433     error("--lto-O: invalid optimization level: " + Twine(config->ltoo));
1434   unsigned ltoCgo =
1435       args::getInteger(args, OPT_lto_CGO, args::getCGOptLevel(config->ltoo));
1436   if (auto level = CodeGenOpt::getLevel(ltoCgo))
1437     config->ltoCgo = *level;
1438   else
1439     error("--lto-CGO: invalid codegen optimization level: " + Twine(ltoCgo));
1440 
1441   if (errorCount())
1442     return false;
1443 
1444   if (args.hasArg(OPT_pagezero_size)) {
1445     uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0);
1446 
1447     // ld64 does something really weird. It attempts to realign the value to the
1448     // page size, but assumes the page size is 4K. This doesn't work with most
1449     // of Apple's ARM64 devices, which use a page size of 16K. This means that
1450     // it will first 4K align it by rounding down, then round up to 16K.  This
1451     // probably only happened because no one using this arg with anything other
1452     // then 0, so no one checked if it did what is what it says it does.
1453 
1454     // So we are not copying this weird behavior and doing the it in a logical
1455     // way, by always rounding down to page size.
1456     if (!isAligned(Align(target->getPageSize()), pagezeroSize)) {
1457       pagezeroSize -= pagezeroSize % target->getPageSize();
1458       warn("__PAGEZERO size is not page aligned, rounding down to 0x" +
1459            Twine::utohexstr(pagezeroSize));
1460     }
1461 
1462     target->pageZeroSize = pagezeroSize;
1463   }
1464 
1465   config->osoPrefix = args.getLastArgValue(OPT_oso_prefix);
1466   if (!config->osoPrefix.empty()) {
1467     // Expand special characters, such as ".", "..", or  "~", if present.
1468     // Note: LD64 only expands "." and not other special characters.
1469     // That seems silly to imitate so we will not try to follow it, but rather
1470     // just use real_path() to do it.
1471 
1472     // The max path length is 4096, in theory. However that seems quite long
1473     // and seems unlikely that any one would want to strip everything from the
1474     // path. Hence we've picked a reasonably large number here.
1475     SmallString<1024> expanded;
1476     if (!fs::real_path(config->osoPrefix, expanded,
1477                        /*expand_tilde=*/true)) {
1478       // Note: LD64 expands "." to be `<current_dir>/`
1479       // (ie., it has a slash suffix) whereas real_path() doesn't.
1480       // So we have to append '/' to be consistent.
1481       StringRef sep = sys::path::get_separator();
1482       // real_path removes trailing slashes as part of the normalization, but
1483       // these are meaningful for our text based stripping
1484       if (config->osoPrefix.equals(".") || config->osoPrefix.ends_with(sep))
1485         expanded += sep;
1486       config->osoPrefix = saver().save(expanded.str());
1487     }
1488   }
1489 
1490   bool pie = args.hasFlag(OPT_pie, OPT_no_pie, true);
1491   if (!supportsNoPie() && !pie) {
1492     warn("-no_pie ignored for arm64");
1493     pie = true;
1494   }
1495 
1496   config->isPic = config->outputType == MH_DYLIB ||
1497                   config->outputType == MH_BUNDLE ||
1498                   (config->outputType == MH_EXECUTE && pie);
1499 
1500   // Must be set before any InputSections and Symbols are created.
1501   config->deadStrip = args.hasArg(OPT_dead_strip);
1502 
1503   config->systemLibraryRoots = getSystemLibraryRoots(args);
1504   if (const char *path = getReproduceOption(args)) {
1505     // Note that --reproduce is a debug option so you can ignore it
1506     // if you are trying to understand the whole picture of the code.
1507     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1508         TarWriter::create(path, path::stem(path));
1509     if (errOrWriter) {
1510       tar = std::move(*errOrWriter);
1511       tar->append("response.txt", createResponseFile(args));
1512       tar->append("version.txt", getLLDVersion() + "\n");
1513     } else {
1514       error("--reproduce: " + toString(errOrWriter.takeError()));
1515     }
1516   }
1517 
1518   if (auto *arg = args.getLastArg(OPT_threads_eq)) {
1519     StringRef v(arg->getValue());
1520     unsigned threads = 0;
1521     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1522       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1523             arg->getValue() + "'");
1524     parallel::strategy = hardware_concurrency(threads);
1525     config->thinLTOJobs = v;
1526   }
1527   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1528     config->thinLTOJobs = arg->getValue();
1529   if (!get_threadpool_strategy(config->thinLTOJobs))
1530     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1531 
1532   for (const Arg *arg : args.filtered(OPT_u)) {
1533     config->explicitUndefineds.push_back(symtab->addUndefined(
1534         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1535   }
1536 
1537   for (const Arg *arg : args.filtered(OPT_U))
1538     config->explicitDynamicLookups.insert(arg->getValue());
1539 
1540   config->mapFile = args.getLastArgValue(OPT_map);
1541   config->optimize = args::getInteger(args, OPT_O, 1);
1542   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
1543   config->finalOutput =
1544       args.getLastArgValue(OPT_final_output, config->outputFile);
1545   config->astPaths = args.getAllArgValues(OPT_add_ast_path);
1546   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
1547   config->headerPadMaxInstallNames =
1548       args.hasArg(OPT_headerpad_max_install_names);
1549   config->printDylibSearch =
1550       args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");
1551   config->printEachFile = args.hasArg(OPT_t);
1552   config->printWhyLoad = args.hasArg(OPT_why_load);
1553   config->omitDebugInfo = args.hasArg(OPT_S);
1554   config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal);
1555   if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {
1556     if (config->outputType != MH_BUNDLE)
1557       error("-bundle_loader can only be used with MachO bundle output");
1558     addFile(arg->getValue(), LoadType::CommandLine, /*isLazy=*/false,
1559             /*isExplicit=*/false, /*isBundleLoader=*/true);
1560   }
1561   for (auto *arg : args.filtered(OPT_dyld_env)) {
1562     StringRef envPair(arg->getValue());
1563     if (!envPair.contains('='))
1564       error("-dyld_env's argument is  malformed. Expected "
1565             "-dyld_env <ENV_VAR>=<VALUE>, got `" +
1566             envPair + "`");
1567     config->dyldEnvs.push_back(envPair);
1568   }
1569   if (!config->dyldEnvs.empty() && config->outputType != MH_EXECUTE)
1570     error("-dyld_env can only be used when creating executable output");
1571 
1572   if (const Arg *arg = args.getLastArg(OPT_umbrella)) {
1573     if (config->outputType != MH_DYLIB)
1574       warn("-umbrella used, but not creating dylib");
1575     config->umbrella = arg->getValue();
1576   }
1577   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
1578   config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto);
1579   config->thinLTOCachePolicy = getLTOCachePolicy(args);
1580   config->thinLTOEmitImportsFiles = args.hasArg(OPT_thinlto_emit_imports_files);
1581   config->thinLTOEmitIndexFiles = args.hasArg(OPT_thinlto_emit_index_files) ||
1582                                   args.hasArg(OPT_thinlto_index_only) ||
1583                                   args.hasArg(OPT_thinlto_index_only_eq);
1584   config->thinLTOIndexOnly = args.hasArg(OPT_thinlto_index_only) ||
1585                              args.hasArg(OPT_thinlto_index_only_eq);
1586   config->thinLTOIndexOnlyArg = args.getLastArgValue(OPT_thinlto_index_only_eq);
1587   config->thinLTOObjectSuffixReplace =
1588       getOldNewOptions(args, OPT_thinlto_object_suffix_replace_eq);
1589   std::tie(config->thinLTOPrefixReplaceOld, config->thinLTOPrefixReplaceNew,
1590            config->thinLTOPrefixReplaceNativeObject) =
1591       getOldNewOptionsExtra(args, OPT_thinlto_prefix_replace_eq);
1592   if (config->thinLTOEmitIndexFiles && !config->thinLTOIndexOnly) {
1593     if (args.hasArg(OPT_thinlto_object_suffix_replace_eq))
1594       error("--thinlto-object-suffix-replace is not supported with "
1595             "--thinlto-emit-index-files");
1596     else if (args.hasArg(OPT_thinlto_prefix_replace_eq))
1597       error("--thinlto-prefix-replace is not supported with "
1598             "--thinlto-emit-index-files");
1599   }
1600   if (!config->thinLTOPrefixReplaceNativeObject.empty() &&
1601       config->thinLTOIndexOnlyArg.empty()) {
1602     error("--thinlto-prefix-replace=old_dir;new_dir;obj_dir must be used with "
1603           "--thinlto-index-only=");
1604   }
1605   config->runtimePaths = args::getStrings(args, OPT_rpath);
1606   config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false);
1607   config->archMultiple = args.hasArg(OPT_arch_multiple);
1608   config->applicationExtension = args.hasFlag(
1609       OPT_application_extension, OPT_no_application_extension, false);
1610   config->exportDynamic = args.hasArg(OPT_export_dynamic);
1611   config->forceLoadObjC = args.hasArg(OPT_ObjC);
1612   config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);
1613   config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);
1614   config->demangle = args.hasArg(OPT_demangle);
1615   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
1616   config->emitFunctionStarts =
1617       args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);
1618   config->emitDataInCodeInfo =
1619       args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);
1620   config->emitChainedFixups = shouldEmitChainedFixups(args);
1621   config->emitInitOffsets =
1622       config->emitChainedFixups || args.hasArg(OPT_init_offsets);
1623   config->icfLevel = getICFLevel(args);
1624   config->dedupStrings =
1625       args.hasFlag(OPT_deduplicate_strings, OPT_no_deduplicate_strings, true);
1626   config->deadStripDuplicates = args.hasArg(OPT_dead_strip_duplicates);
1627   config->warnDylibInstallName = args.hasFlag(
1628       OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false);
1629   config->ignoreOptimizationHints = args.hasArg(OPT_ignore_optimization_hints);
1630   config->callGraphProfileSort = args.hasFlag(
1631       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1632   config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order_eq);
1633   config->forceExactCpuSubtypeMatch =
1634       getenv("LD_DYLIB_CPU_SUBTYPES_MUST_MATCH");
1635   config->objcStubsMode = getObjCStubsMode(args);
1636   config->ignoreAutoLink = args.hasArg(OPT_ignore_auto_link);
1637   for (const Arg *arg : args.filtered(OPT_ignore_auto_link_option))
1638     config->ignoreAutoLinkOptions.insert(arg->getValue());
1639   config->strictAutoLink = args.hasArg(OPT_strict_auto_link);
1640   config->ltoDebugPassManager = args.hasArg(OPT_lto_debug_pass_manager);
1641   config->csProfileGenerate = args.hasArg(OPT_cs_profile_generate);
1642   config->csProfilePath = args.getLastArgValue(OPT_cs_profile_path);
1643   config->generateUuid = !args.hasArg(OPT_no_uuid);
1644 
1645   for (const Arg *arg : args.filtered(OPT_alias)) {
1646     config->aliasedSymbols.push_back(
1647         std::make_pair(arg->getValue(0), arg->getValue(1)));
1648   }
1649 
1650   if (const char *zero = getenv("ZERO_AR_DATE"))
1651     config->zeroModTime = strcmp(zero, "0") != 0;
1652   if (args.getLastArg(OPT_reproducible))
1653     config->zeroModTime = true;
1654 
1655   std::array<PlatformType, 3> encryptablePlatforms{
1656       PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS};
1657   config->emitEncryptionInfo =
1658       args.hasFlag(OPT_encryptable, OPT_no_encryption,
1659                    is_contained(encryptablePlatforms, config->platform()));
1660 
1661   if (const Arg *arg = args.getLastArg(OPT_install_name)) {
1662     if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
1663       warn(
1664           arg->getAsString(args) +
1665           ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
1666     else
1667       config->installName = arg->getValue();
1668   } else if (config->outputType == MH_DYLIB) {
1669     config->installName = config->finalOutput;
1670   }
1671 
1672   if (args.hasArg(OPT_mark_dead_strippable_dylib)) {
1673     if (config->outputType != MH_DYLIB)
1674       warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
1675     else
1676       config->markDeadStrippableDylib = true;
1677   }
1678 
1679   if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
1680     config->staticLink = (arg->getOption().getID() == OPT_static);
1681 
1682   if (const Arg *arg =
1683           args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
1684     config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
1685                                 ? NamespaceKind::twolevel
1686                                 : NamespaceKind::flat;
1687 
1688   config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
1689 
1690   if (config->outputType == MH_EXECUTE)
1691     config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
1692                                          /*file=*/nullptr,
1693                                          /*isWeakRef=*/false);
1694 
1695   config->librarySearchPaths =
1696       getLibrarySearchPaths(args, config->systemLibraryRoots);
1697   config->frameworkSearchPaths =
1698       getFrameworkSearchPaths(args, config->systemLibraryRoots);
1699   if (const Arg *arg =
1700           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
1701     config->searchDylibsFirst =
1702         arg->getOption().getID() == OPT_search_dylibs_first;
1703 
1704   config->dylibCompatibilityVersion =
1705       parseDylibVersion(args, OPT_compatibility_version);
1706   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
1707 
1708   config->dataConst =
1709       args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));
1710   // Populate config->sectionRenameMap with builtin default renames.
1711   // Options -rename_section and -rename_segment are able to override.
1712   initializeSectionRenameMap();
1713   // Reject every special character except '.' and '$'
1714   // TODO(gkm): verify that this is the proper set of invalid chars
1715   StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
1716   auto validName = [invalidNameChars](StringRef s) {
1717     if (s.find_first_of(invalidNameChars) != StringRef::npos)
1718       error("invalid name for segment or section: " + s);
1719     return s;
1720   };
1721   for (const Arg *arg : args.filtered(OPT_rename_section)) {
1722     config->sectionRenameMap[{validName(arg->getValue(0)),
1723                               validName(arg->getValue(1))}] = {
1724         validName(arg->getValue(2)), validName(arg->getValue(3))};
1725   }
1726   for (const Arg *arg : args.filtered(OPT_rename_segment)) {
1727     config->segmentRenameMap[validName(arg->getValue(0))] =
1728         validName(arg->getValue(1));
1729   }
1730 
1731   config->sectionAlignments = parseSectAlign(args);
1732 
1733   for (const Arg *arg : args.filtered(OPT_segprot)) {
1734     StringRef segName = arg->getValue(0);
1735     uint32_t maxProt = parseProtection(arg->getValue(1));
1736     uint32_t initProt = parseProtection(arg->getValue(2));
1737     if (maxProt != initProt && config->arch() != AK_i386)
1738       error("invalid argument '" + arg->getAsString(args) +
1739             "': max and init must be the same for non-i386 archs");
1740     if (segName == segment_names::linkEdit)
1741       error("-segprot cannot be used to change __LINKEDIT's protections");
1742     config->segmentProtections.push_back({segName, maxProt, initProt});
1743   }
1744 
1745   config->hasExplicitExports =
1746       args.hasArg(OPT_no_exported_symbols) ||
1747       args.hasArgNoClaim(OPT_exported_symbol, OPT_exported_symbols_list);
1748   handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,
1749                        OPT_exported_symbols_list);
1750   handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,
1751                        OPT_unexported_symbols_list);
1752   if (config->hasExplicitExports && !config->unexportedSymbols.empty())
1753     error("cannot use both -exported_symbol* and -unexported_symbol* options");
1754 
1755   if (args.hasArg(OPT_no_exported_symbols) && !config->exportedSymbols.empty())
1756     error("cannot use both -exported_symbol* and -no_exported_symbols options");
1757 
1758   // Imitating LD64's:
1759   // -non_global_symbols_no_strip_list and -non_global_symbols_strip_list can't
1760   // both be present.
1761   // But -x can be used with either of these two, in which case, the last arg
1762   // takes effect.
1763   // (TODO: This is kind of confusing - considering disallowing using them
1764   // together for a more straightforward behaviour)
1765   {
1766     bool includeLocal = false;
1767     bool excludeLocal = false;
1768     for (const Arg *arg :
1769          args.filtered(OPT_x, OPT_non_global_symbols_no_strip_list,
1770                        OPT_non_global_symbols_strip_list)) {
1771       switch (arg->getOption().getID()) {
1772       case OPT_x:
1773         config->localSymbolsPresence = SymtabPresence::None;
1774         break;
1775       case OPT_non_global_symbols_no_strip_list:
1776         if (excludeLocal) {
1777           error("cannot use both -non_global_symbols_no_strip_list and "
1778                 "-non_global_symbols_strip_list");
1779         } else {
1780           includeLocal = true;
1781           config->localSymbolsPresence = SymtabPresence::SelectivelyIncluded;
1782           parseSymbolPatternsFile(arg, config->localSymbolPatterns);
1783         }
1784         break;
1785       case OPT_non_global_symbols_strip_list:
1786         if (includeLocal) {
1787           error("cannot use both -non_global_symbols_no_strip_list and "
1788                 "-non_global_symbols_strip_list");
1789         } else {
1790           excludeLocal = true;
1791           config->localSymbolsPresence = SymtabPresence::SelectivelyExcluded;
1792           parseSymbolPatternsFile(arg, config->localSymbolPatterns);
1793         }
1794         break;
1795       default:
1796         llvm_unreachable("unexpected option");
1797       }
1798     }
1799   }
1800   // Explicitly-exported literal symbols must be defined, but might
1801   // languish in an archive if unreferenced elsewhere or if they are in the
1802   // non-global strip list. Light a fire under those lazy symbols!
1803   for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
1804     symtab->addUndefined(cachedName.val(), /*file=*/nullptr,
1805                          /*isWeakRef=*/false);
1806 
1807   for (const Arg *arg : args.filtered(OPT_why_live))
1808     config->whyLive.insert(arg->getValue());
1809   if (!config->whyLive.empty() && !config->deadStrip)
1810     warn("-why_live has no effect without -dead_strip, ignoring");
1811 
1812   config->saveTemps = args.hasArg(OPT_save_temps);
1813 
1814   config->adhocCodesign = args.hasFlag(
1815       OPT_adhoc_codesign, OPT_no_adhoc_codesign,
1816       shouldAdhocSignByDefault(config->arch(), config->platform()));
1817 
1818   if (args.hasArg(OPT_v)) {
1819     message(getLLDVersion(), lld::errs());
1820     message(StringRef("Library search paths:") +
1821                 (config->librarySearchPaths.empty()
1822                      ? ""
1823                      : "\n\t" + join(config->librarySearchPaths, "\n\t")),
1824             lld::errs());
1825     message(StringRef("Framework search paths:") +
1826                 (config->frameworkSearchPaths.empty()
1827                      ? ""
1828                      : "\n\t" + join(config->frameworkSearchPaths, "\n\t")),
1829             lld::errs());
1830   }
1831 
1832   config->progName = argsArr[0];
1833 
1834   config->timeTraceEnabled = args.hasArg(OPT_time_trace_eq);
1835   config->timeTraceGranularity =
1836       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
1837 
1838   // Initialize time trace profiler.
1839   if (config->timeTraceEnabled)
1840     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
1841 
1842   {
1843     TimeTraceScope timeScope("ExecuteLinker");
1844 
1845     initLLVM(); // must be run before any call to addFile()
1846     createFiles(args);
1847 
1848     // Now that all dylibs have been loaded, search for those that should be
1849     // re-exported.
1850     {
1851       auto reexportHandler = [](const Arg *arg,
1852                                 const std::vector<StringRef> &extensions) {
1853         config->hasReexports = true;
1854         StringRef searchName = arg->getValue();
1855         if (!markReexport(searchName, extensions))
1856           error(arg->getSpelling() + " " + searchName +
1857                 " does not match a supplied dylib");
1858       };
1859       std::vector<StringRef> extensions = {".tbd"};
1860       for (const Arg *arg : args.filtered(OPT_sub_umbrella))
1861         reexportHandler(arg, extensions);
1862 
1863       extensions.push_back(".dylib");
1864       for (const Arg *arg : args.filtered(OPT_sub_library))
1865         reexportHandler(arg, extensions);
1866     }
1867 
1868     cl::ResetAllOptionOccurrences();
1869 
1870     // Parse LTO options.
1871     if (const Arg *arg = args.getLastArg(OPT_mcpu))
1872       parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1873                        arg->getSpelling());
1874 
1875     for (const Arg *arg : args.filtered(OPT_mllvm)) {
1876       parseClangOption(arg->getValue(), arg->getSpelling());
1877       config->mllvmOpts.emplace_back(arg->getValue());
1878     }
1879 
1880     createSyntheticSections();
1881     createSyntheticSymbols();
1882     addSynthenticMethnames();
1883 
1884     createAliases();
1885     // If we are in "explicit exports" mode, hide everything that isn't
1886     // explicitly exported. Do this before running LTO so that LTO can better
1887     // optimize.
1888     handleExplicitExports();
1889 
1890     bool didCompileBitcodeFiles = compileBitcodeFiles();
1891 
1892     // If --thinlto-index-only is given, we should create only "index
1893     // files" and not object files. Index file creation is already done
1894     // in compileBitcodeFiles, so we are done if that's the case.
1895     if (config->thinLTOIndexOnly)
1896       return errorCount() == 0;
1897 
1898     // LTO may emit a non-hidden (extern) object file symbol even if the
1899     // corresponding bitcode symbol is hidden. In particular, this happens for
1900     // cross-module references to hidden symbols under ThinLTO. Thus, if we
1901     // compiled any bitcode files, we must redo the symbol hiding.
1902     if (didCompileBitcodeFiles)
1903       handleExplicitExports();
1904     replaceCommonSymbols();
1905 
1906     StringRef orderFile = args.getLastArgValue(OPT_order_file);
1907     if (!orderFile.empty())
1908       priorityBuilder.parseOrderFile(orderFile);
1909 
1910     referenceStubBinder();
1911 
1912     // FIXME: should terminate the link early based on errors encountered so
1913     // far?
1914 
1915     for (const Arg *arg : args.filtered(OPT_sectcreate)) {
1916       StringRef segName = arg->getValue(0);
1917       StringRef sectName = arg->getValue(1);
1918       StringRef fileName = arg->getValue(2);
1919       std::optional<MemoryBufferRef> buffer = readFile(fileName);
1920       if (buffer)
1921         inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
1922     }
1923 
1924     for (const Arg *arg : args.filtered(OPT_add_empty_section)) {
1925       StringRef segName = arg->getValue(0);
1926       StringRef sectName = arg->getValue(1);
1927       inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName));
1928     }
1929 
1930     gatherInputSections();
1931     if (config->callGraphProfileSort)
1932       priorityBuilder.extractCallGraphProfile();
1933 
1934     if (config->deadStrip)
1935       markLive();
1936 
1937     if (args.hasArg(OPT_check_category_conflicts))
1938       objc::checkCategories();
1939 
1940     // ICF assumes that all literals have been folded already, so we must run
1941     // foldIdenticalLiterals before foldIdenticalSections.
1942     foldIdenticalLiterals();
1943     if (config->icfLevel != ICFLevel::none) {
1944       if (config->icfLevel == ICFLevel::safe)
1945         markAddrSigSymbols();
1946       foldIdenticalSections(/*onlyCfStrings=*/false);
1947     } else if (config->dedupStrings) {
1948       foldIdenticalSections(/*onlyCfStrings=*/true);
1949     }
1950 
1951     // Write to an output file.
1952     if (target->wordSize == 8)
1953       writeResult<LP64>();
1954     else
1955       writeResult<ILP32>();
1956 
1957     depTracker->write(getLLDVersion(), inputFiles, config->outputFile);
1958   }
1959 
1960   if (config->timeTraceEnabled) {
1961     checkError(timeTraceProfilerWrite(
1962         args.getLastArgValue(OPT_time_trace_eq).str(), config->outputFile));
1963 
1964     timeTraceProfilerCleanup();
1965   }
1966 
1967   if (errorCount() != 0 || config->strictAutoLink)
1968     for (const auto &warning : missingAutolinkWarnings)
1969       warn(warning);
1970 
1971   return errorCount() == 0;
1972 }
1973 } // namespace macho
1974 } // namespace lld
1975