xref: /llvm-project-15.0.7/lld/MachO/Driver.cpp (revision a7691dee)
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/Driver.h"
28 #include "lld/Common/ErrorHandler.h"
29 #include "lld/Common/LLVM.h"
30 #include "lld/Common/Memory.h"
31 #include "lld/Common/Reproduce.h"
32 #include "lld/Common/Version.h"
33 #include "llvm/ADT/DenseSet.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/BinaryFormat/MachO.h"
37 #include "llvm/BinaryFormat/Magic.h"
38 #include "llvm/Config/llvm-config.h"
39 #include "llvm/LTO/LTO.h"
40 #include "llvm/Object/Archive.h"
41 #include "llvm/Option/ArgList.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/FileSystem.h"
44 #include "llvm/Support/Host.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/TextAPI/PackedVersion.h"
52 
53 #include <algorithm>
54 
55 using namespace llvm;
56 using namespace llvm::MachO;
57 using namespace llvm::object;
58 using namespace llvm::opt;
59 using namespace llvm::sys;
60 using namespace lld;
61 using namespace lld::macho;
62 
63 std::unique_ptr<Configuration> macho::config;
64 std::unique_ptr<DependencyTracker> macho::depTracker;
65 
66 static HeaderFileType getOutputType(const InputArgList &args) {
67   // TODO: -r, -dylinker, -preload...
68   Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute);
69   if (outputArg == nullptr)
70     return MH_EXECUTE;
71 
72   switch (outputArg->getOption().getID()) {
73   case OPT_bundle:
74     return MH_BUNDLE;
75   case OPT_dylib:
76     return MH_DYLIB;
77   case OPT_execute:
78     return MH_EXECUTE;
79   default:
80     llvm_unreachable("internal error");
81   }
82 }
83 
84 static DenseMap<CachedHashStringRef, StringRef> resolvedLibraries;
85 static Optional<StringRef> findLibrary(StringRef name) {
86   CachedHashStringRef key(name);
87   auto entry = resolvedLibraries.find(key);
88   if (entry != resolvedLibraries.end())
89     return entry->second;
90 
91   auto doFind = [&] {
92     if (config->searchDylibsFirst) {
93       if (Optional<StringRef> path = findPathCombination(
94               "lib" + name, config->librarySearchPaths, {".tbd", ".dylib"}))
95         return path;
96       return findPathCombination("lib" + name, config->librarySearchPaths,
97                                  {".a"});
98     }
99     return findPathCombination("lib" + name, config->librarySearchPaths,
100                                {".tbd", ".dylib", ".a"});
101   };
102 
103   Optional<StringRef> path = doFind();
104   if (path)
105     resolvedLibraries[key] = *path;
106 
107   return path;
108 }
109 
110 static DenseMap<CachedHashStringRef, StringRef> resolvedFrameworks;
111 static Optional<StringRef> findFramework(StringRef name) {
112   CachedHashStringRef key(name);
113   auto entry = resolvedFrameworks.find(key);
114   if (entry != resolvedFrameworks.end())
115     return entry->second;
116 
117   SmallString<260> symlink;
118   StringRef suffix;
119   std::tie(name, suffix) = name.split(",");
120   for (StringRef dir : config->frameworkSearchPaths) {
121     symlink = dir;
122     path::append(symlink, name + ".framework", name);
123 
124     if (!suffix.empty()) {
125       // NOTE: we must resolve the symlink before trying the suffixes, because
126       // there are no symlinks for the suffixed paths.
127       SmallString<260> location;
128       if (!fs::real_path(symlink, location)) {
129         // only append suffix if realpath() succeeds
130         Twine suffixed = location + suffix;
131         if (fs::exists(suffixed))
132           return resolvedFrameworks[key] = saver().save(suffixed.str());
133       }
134       // Suffix lookup failed, fall through to the no-suffix case.
135     }
136 
137     if (Optional<StringRef> path = resolveDylibPath(symlink.str()))
138       return resolvedFrameworks[key] = *path;
139   }
140   return {};
141 }
142 
143 static bool warnIfNotDirectory(StringRef option, StringRef path) {
144   if (!fs::exists(path)) {
145     warn("directory not found for option -" + option + path);
146     return false;
147   } else if (!fs::is_directory(path)) {
148     warn("option -" + option + path + " references a non-directory path");
149     return false;
150   }
151   return true;
152 }
153 
154 static std::vector<StringRef>
155 getSearchPaths(unsigned optionCode, InputArgList &args,
156                const std::vector<StringRef> &roots,
157                const SmallVector<StringRef, 2> &systemPaths) {
158   std::vector<StringRef> paths;
159   StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
160   for (StringRef path : args::getStrings(args, optionCode)) {
161     // NOTE: only absolute paths are re-rooted to syslibroot(s)
162     bool found = false;
163     if (path::is_absolute(path, path::Style::posix)) {
164       for (StringRef root : roots) {
165         SmallString<261> buffer(root);
166         path::append(buffer, path);
167         // Do not warn about paths that are computed via the syslib roots
168         if (fs::is_directory(buffer)) {
169           paths.push_back(saver().save(buffer.str()));
170           found = true;
171         }
172       }
173     }
174     if (!found && warnIfNotDirectory(optionLetter, path))
175       paths.push_back(path);
176   }
177 
178   // `-Z` suppresses the standard "system" search paths.
179   if (args.hasArg(OPT_Z))
180     return paths;
181 
182   for (const StringRef &path : systemPaths) {
183     for (const StringRef &root : roots) {
184       SmallString<261> buffer(root);
185       path::append(buffer, path);
186       if (fs::is_directory(buffer))
187         paths.push_back(saver().save(buffer.str()));
188     }
189   }
190   return paths;
191 }
192 
193 static std::vector<StringRef> getSystemLibraryRoots(InputArgList &args) {
194   std::vector<StringRef> roots;
195   for (const Arg *arg : args.filtered(OPT_syslibroot))
196     roots.push_back(arg->getValue());
197   // NOTE: the final `-syslibroot` being `/` will ignore all roots
198   if (!roots.empty() && roots.back() == "/")
199     roots.clear();
200   // NOTE: roots can never be empty - add an empty root to simplify the library
201   // and framework search path computation.
202   if (roots.empty())
203     roots.emplace_back("");
204   return roots;
205 }
206 
207 static std::vector<StringRef>
208 getLibrarySearchPaths(InputArgList &args, const std::vector<StringRef> &roots) {
209   return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});
210 }
211 
212 static std::vector<StringRef>
213 getFrameworkSearchPaths(InputArgList &args,
214                         const std::vector<StringRef> &roots) {
215   return getSearchPaths(OPT_F, args, roots,
216                         {"/Library/Frameworks", "/System/Library/Frameworks"});
217 }
218 
219 static llvm::CachePruningPolicy getLTOCachePolicy(InputArgList &args) {
220   SmallString<128> ltoPolicy;
221   auto add = [&ltoPolicy](Twine val) {
222     if (!ltoPolicy.empty())
223       ltoPolicy += ":";
224     val.toVector(ltoPolicy);
225   };
226   for (const Arg *arg :
227        args.filtered(OPT_thinlto_cache_policy, OPT_prune_interval_lto,
228                      OPT_prune_after_lto, OPT_max_relative_cache_size_lto)) {
229     switch (arg->getOption().getID()) {
230     case OPT_thinlto_cache_policy:
231       add(arg->getValue());
232       break;
233     case OPT_prune_interval_lto:
234       if (!strcmp("-1", arg->getValue()))
235         add("prune_interval=87600h"); // 10 years
236       else
237         add(Twine("prune_interval=") + arg->getValue() + "s");
238       break;
239     case OPT_prune_after_lto:
240       add(Twine("prune_after=") + arg->getValue() + "s");
241       break;
242     case OPT_max_relative_cache_size_lto:
243       add(Twine("cache_size=") + arg->getValue() + "%");
244       break;
245     }
246   }
247   return CHECK(parseCachePruningPolicy(ltoPolicy), "invalid LTO cache policy");
248 }
249 
250 static DenseMap<StringRef, ArchiveFile *> loadedArchives;
251 
252 static InputFile *addFile(StringRef path, ForceLoad forceLoadArchive,
253                           bool isLazy = false, bool isExplicit = true,
254                           bool isBundleLoader = false) {
255   Optional<MemoryBufferRef> buffer = readFile(path);
256   if (!buffer)
257     return nullptr;
258   MemoryBufferRef mbref = *buffer;
259   InputFile *newFile = nullptr;
260 
261   file_magic magic = identify_magic(mbref.getBuffer());
262   switch (magic) {
263   case file_magic::archive: {
264     // Avoid loading archives twice. If the archives are being force-loaded,
265     // loading them twice would create duplicate symbol errors. In the
266     // non-force-loading case, this is just a minor performance optimization.
267     // We don't take a reference to cachedFile here because the
268     // loadArchiveMember() call below may recursively call addFile() and
269     // invalidate this reference.
270     auto entry = loadedArchives.find(path);
271     if (entry != loadedArchives.end())
272       return entry->second;
273 
274     std::unique_ptr<object::Archive> archive = CHECK(
275         object::Archive::create(mbref), path + ": failed to parse archive");
276 
277     if (!archive->isEmpty() && !archive->hasSymbolTable())
278       error(path + ": archive has no index; run ranlib to add one");
279 
280     auto *file = make<ArchiveFile>(std::move(archive));
281     if ((forceLoadArchive == ForceLoad::Default && config->allLoad) ||
282         forceLoadArchive == ForceLoad::Yes) {
283       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
284         Error e = Error::success();
285         for (const object::Archive::Child &c : file->getArchive().children(e)) {
286           StringRef reason =
287               forceLoadArchive == ForceLoad::Yes ? "-force_load" : "-all_load";
288           if (Error e = file->fetch(c, reason))
289             error(toString(file) + ": " + reason +
290                   " failed to load archive member: " + toString(std::move(e)));
291         }
292         if (e)
293           error(toString(file) +
294                 ": Archive::children failed: " + toString(std::move(e)));
295       }
296     } else if (forceLoadArchive == ForceLoad::Default &&
297                config->forceLoadObjC) {
298       for (const object::Archive::Symbol &sym : file->getArchive().symbols())
299         if (sym.getName().startswith(objc::klass))
300           file->fetch(sym);
301 
302       // TODO: no need to look for ObjC sections for a given archive member if
303       // we already found that it contains an ObjC symbol.
304       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
305         Error e = Error::success();
306         for (const object::Archive::Child &c : file->getArchive().children(e)) {
307           Expected<MemoryBufferRef> mb = c.getMemoryBufferRef();
308           if (!mb || !hasObjCSection(*mb))
309             continue;
310           if (Error e = file->fetch(c, "-ObjC"))
311             error(toString(file) + ": -ObjC failed to load archive member: " +
312                   toString(std::move(e)));
313         }
314         if (e)
315           error(toString(file) +
316                 ": Archive::children failed: " + toString(std::move(e)));
317       }
318     }
319 
320     file->addLazySymbols();
321     newFile = loadedArchives[path] = file;
322     break;
323   }
324   case file_magic::macho_object:
325     newFile = make<ObjFile>(mbref, getModTime(path), "", isLazy);
326     break;
327   case file_magic::macho_dynamically_linked_shared_lib:
328   case file_magic::macho_dynamically_linked_shared_lib_stub:
329   case file_magic::tapi_file:
330     if (DylibFile *dylibFile = loadDylib(mbref)) {
331       if (isExplicit)
332         dylibFile->explicitlyLinked = true;
333       newFile = dylibFile;
334     }
335     break;
336   case file_magic::bitcode:
337     newFile = make<BitcodeFile>(mbref, "", 0, isLazy);
338     break;
339   case file_magic::macho_executable:
340   case file_magic::macho_bundle:
341     // We only allow executable and bundle type here if it is used
342     // as a bundle loader.
343     if (!isBundleLoader)
344       error(path + ": unhandled file type");
345     if (DylibFile *dylibFile = loadDylib(mbref, nullptr, isBundleLoader))
346       newFile = dylibFile;
347     break;
348   default:
349     error(path + ": unhandled file type");
350   }
351   if (newFile && !isa<DylibFile>(newFile)) {
352     if ((isa<ObjFile>(newFile) || isa<BitcodeFile>(newFile)) && newFile->lazy &&
353         config->forceLoadObjC) {
354       for (Symbol *sym : newFile->symbols)
355         if (sym && sym->getName().startswith(objc::klass)) {
356           extract(*newFile, "-ObjC");
357           break;
358         }
359       if (newFile->lazy && hasObjCSection(mbref))
360         extract(*newFile, "-ObjC");
361     }
362 
363     // printArchiveMemberLoad() prints both .a and .o names, so no need to
364     // print the .a name here. Similarly skip lazy files.
365     if (config->printEachFile && magic != file_magic::archive && !isLazy)
366       message(toString(newFile));
367     inputFiles.insert(newFile);
368   }
369   return newFile;
370 }
371 
372 static void addLibrary(StringRef name, bool isNeeded, bool isWeak,
373                        bool isReexport, bool isExplicit,
374                        ForceLoad forceLoadArchive) {
375   if (Optional<StringRef> path = findLibrary(name)) {
376     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
377             addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit))) {
378       if (isNeeded)
379         dylibFile->forceNeeded = true;
380       if (isWeak)
381         dylibFile->forceWeakImport = true;
382       if (isReexport) {
383         config->hasReexports = true;
384         dylibFile->reexport = true;
385       }
386     }
387     return;
388   }
389   error("library not found for -l" + name);
390 }
391 
392 static DenseSet<StringRef> loadedObjectFrameworks;
393 static void addFramework(StringRef name, bool isNeeded, bool isWeak,
394                          bool isReexport, bool isExplicit,
395                          ForceLoad forceLoadArchive) {
396   if (Optional<StringRef> path = findFramework(name)) {
397     if (loadedObjectFrameworks.contains(*path))
398       return;
399 
400     InputFile *file =
401         addFile(*path, forceLoadArchive, /*isLazy=*/false, isExplicit);
402     if (auto *dylibFile = dyn_cast_or_null<DylibFile>(file)) {
403       if (isNeeded)
404         dylibFile->forceNeeded = true;
405       if (isWeak)
406         dylibFile->forceWeakImport = true;
407       if (isReexport) {
408         config->hasReexports = true;
409         dylibFile->reexport = true;
410       }
411     } else if (isa<ObjFile>(file) || isa<BitcodeFile>(file)) {
412       // Cache frameworks containing object or bitcode files to avoid duplicate
413       // symbols. Frameworks containing static archives are cached separately
414       // in addFile() to share caching with libraries, and frameworks
415       // containing dylibs should allow overwriting of attributes such as
416       // forceNeeded by subsequent loads
417       loadedObjectFrameworks.insert(*path);
418     }
419     return;
420   }
421   error("framework not found for -framework " + name);
422 }
423 
424 // Parses LC_LINKER_OPTION contents, which can add additional command line
425 // flags. This directly parses the flags instead of using the standard argument
426 // parser to improve performance.
427 void macho::parseLCLinkerOption(InputFile *f, unsigned argc, StringRef data) {
428   SmallVector<StringRef, 4> argv;
429   size_t offset = 0;
430   for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
431     argv.push_back(data.data() + offset);
432     offset += strlen(data.data() + offset) + 1;
433   }
434   if (argv.size() != argc || offset > data.size())
435     fatal(toString(f) + ": invalid LC_LINKER_OPTION");
436 
437   unsigned i = 0;
438   StringRef arg = argv[i];
439   if (arg.consume_front("-l")) {
440     ForceLoad forceLoadArchive =
441         config->forceLoadSwift && arg.startswith("swift") ? ForceLoad::Yes
442                                                           : ForceLoad::No;
443     addLibrary(arg, /*isNeeded=*/false, /*isWeak=*/false,
444                /*isReexport=*/false, /*isExplicit=*/false, forceLoadArchive);
445   } else if (arg == "-framework") {
446     StringRef name = argv[++i];
447     addFramework(name, /*isNeeded=*/false, /*isWeak=*/false,
448                  /*isReexport=*/false, /*isExplicit=*/false, ForceLoad::No);
449   } else {
450     error(arg + " is not allowed in LC_LINKER_OPTION");
451   }
452 }
453 
454 static void addFileList(StringRef path, bool isLazy) {
455   Optional<MemoryBufferRef> buffer = readFile(path);
456   if (!buffer)
457     return;
458   MemoryBufferRef mbref = *buffer;
459   for (StringRef path : args::getLines(mbref))
460     addFile(rerootPath(path), ForceLoad::Default, isLazy);
461 }
462 
463 // We expect sub-library names of the form "libfoo", which will match a dylib
464 // with a path of .*/libfoo.{dylib, tbd}.
465 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
466 // I'm not sure what the use case for that is.
467 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
468   for (InputFile *file : inputFiles) {
469     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
470       StringRef filename = path::filename(dylibFile->getName());
471       if (filename.consume_front(searchName) &&
472           (filename.empty() ||
473            find(extensions, filename) != extensions.end())) {
474         dylibFile->reexport = true;
475         return true;
476       }
477     }
478   }
479   return false;
480 }
481 
482 // This function is called on startup. We need this for LTO since
483 // LTO calls LLVM functions to compile bitcode files to native code.
484 // Technically this can be delayed until we read bitcode files, but
485 // we don't bother to do lazily because the initialization is fast.
486 static void initLLVM() {
487   InitializeAllTargets();
488   InitializeAllTargetMCs();
489   InitializeAllAsmPrinters();
490   InitializeAllAsmParsers();
491 }
492 
493 static void compileBitcodeFiles() {
494   TimeTraceScope timeScope("LTO");
495   auto *lto = make<BitcodeCompiler>();
496   for (InputFile *file : inputFiles)
497     if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
498       if (!file->lazy)
499         lto->add(*bitcodeFile);
500 
501   for (ObjFile *file : lto->compile())
502     inputFiles.insert(file);
503 }
504 
505 // Replaces common symbols with defined symbols residing in __common sections.
506 // This function must be called after all symbol names are resolved (i.e. after
507 // all InputFiles have been loaded.) As a result, later operations won't see
508 // any CommonSymbols.
509 static void replaceCommonSymbols() {
510   TimeTraceScope timeScope("Replace common symbols");
511   ConcatOutputSection *osec = nullptr;
512   for (Symbol *sym : symtab->getSymbols()) {
513     auto *common = dyn_cast<CommonSymbol>(sym);
514     if (common == nullptr)
515       continue;
516 
517     // Casting to size_t will truncate large values on 32-bit architectures,
518     // but it's not really worth supporting the linking of 64-bit programs on
519     // 32-bit archs.
520     ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};
521     // FIXME avoid creating one Section per symbol?
522     auto *section =
523         make<Section>(common->getFile(), segment_names::data,
524                       section_names::common, S_ZEROFILL, /*addr=*/0);
525     auto *isec = make<ConcatInputSection>(*section, data, common->align);
526     if (!osec)
527       osec = ConcatOutputSection::getOrCreateForInput(isec);
528     isec->parent = osec;
529     inputSections.push_back(isec);
530 
531     // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
532     // and pass them on here.
533     replaceSymbol<Defined>(
534         sym, sym->getName(), common->getFile(), isec, /*value=*/0, /*size=*/0,
535         /*isWeakDef=*/false, /*isExternal=*/true, common->privateExtern,
536         /*includeInSymtab=*/true, /*isThumb=*/false,
537         /*isReferencedDynamically=*/false, /*noDeadStrip=*/false);
538   }
539 }
540 
541 static void initializeSectionRenameMap() {
542   if (config->dataConst) {
543     SmallVector<StringRef> v{section_names::got,
544                              section_names::authGot,
545                              section_names::authPtr,
546                              section_names::nonLazySymbolPtr,
547                              section_names::const_,
548                              section_names::cfString,
549                              section_names::moduleInitFunc,
550                              section_names::moduleTermFunc,
551                              section_names::objcClassList,
552                              section_names::objcNonLazyClassList,
553                              section_names::objcCatList,
554                              section_names::objcNonLazyCatList,
555                              section_names::objcProtoList,
556                              section_names::objcImageInfo};
557     for (StringRef s : v)
558       config->sectionRenameMap[{segment_names::data, s}] = {
559           segment_names::dataConst, s};
560   }
561   config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
562       segment_names::text, section_names::text};
563   config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
564       config->dataConst ? segment_names::dataConst : segment_names::data,
565       section_names::nonLazySymbolPtr};
566 }
567 
568 static inline char toLowerDash(char x) {
569   if (x >= 'A' && x <= 'Z')
570     return x - 'A' + 'a';
571   else if (x == ' ')
572     return '-';
573   return x;
574 }
575 
576 static std::string lowerDash(StringRef s) {
577   return std::string(map_iterator(s.begin(), toLowerDash),
578                      map_iterator(s.end(), toLowerDash));
579 }
580 
581 struct PlatformVersion {
582   PlatformType platform = PLATFORM_UNKNOWN;
583   llvm::VersionTuple minimum;
584   llvm::VersionTuple sdk;
585 };
586 
587 static PlatformVersion parsePlatformVersion(const Arg *arg) {
588   assert(arg->getOption().getID() == OPT_platform_version);
589   StringRef platformStr = arg->getValue(0);
590   StringRef minVersionStr = arg->getValue(1);
591   StringRef sdkVersionStr = arg->getValue(2);
592 
593   PlatformVersion platformVersion;
594 
595   // TODO(compnerd) see if we can generate this case list via XMACROS
596   platformVersion.platform =
597       StringSwitch<PlatformType>(lowerDash(platformStr))
598           .Cases("macos", "1", PLATFORM_MACOS)
599           .Cases("ios", "2", PLATFORM_IOS)
600           .Cases("tvos", "3", PLATFORM_TVOS)
601           .Cases("watchos", "4", PLATFORM_WATCHOS)
602           .Cases("bridgeos", "5", PLATFORM_BRIDGEOS)
603           .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST)
604           .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR)
605           .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR)
606           .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR)
607           .Cases("driverkit", "10", PLATFORM_DRIVERKIT)
608           .Default(PLATFORM_UNKNOWN);
609   if (platformVersion.platform == PLATFORM_UNKNOWN)
610     error(Twine("malformed platform: ") + platformStr);
611   // TODO: check validity of version strings, which varies by platform
612   // NOTE: ld64 accepts version strings with 5 components
613   // llvm::VersionTuple accepts no more than 4 components
614   // Has Apple ever published version strings with 5 components?
615   if (platformVersion.minimum.tryParse(minVersionStr))
616     error(Twine("malformed minimum version: ") + minVersionStr);
617   if (platformVersion.sdk.tryParse(sdkVersionStr))
618     error(Twine("malformed sdk version: ") + sdkVersionStr);
619   return platformVersion;
620 }
621 
622 // Has the side-effect of setting Config::platformInfo.
623 static PlatformType parsePlatformVersions(const ArgList &args) {
624   std::map<PlatformType, PlatformVersion> platformVersions;
625   const PlatformVersion *lastVersionInfo = nullptr;
626   for (const Arg *arg : args.filtered(OPT_platform_version)) {
627     PlatformVersion version = parsePlatformVersion(arg);
628 
629     // For each platform, the last flag wins:
630     // `-platform_version macos 2 3 -platform_version macos 4 5` has the same
631     // effect as just passing `-platform_version macos 4 5`.
632     // FIXME: ld64 warns on multiple flags for one platform. Should we?
633     platformVersions[version.platform] = version;
634     lastVersionInfo = &platformVersions[version.platform];
635   }
636 
637   if (platformVersions.empty()) {
638     error("must specify -platform_version");
639     return PLATFORM_UNKNOWN;
640   }
641   if (platformVersions.size() > 2) {
642     error("must specify -platform_version at most twice");
643     return PLATFORM_UNKNOWN;
644   }
645   if (platformVersions.size() == 2) {
646     // FIXME: If you implement support for this, add a diagnostic if
647     // outputType is not dylib or bundle -- linkers shouldn't be able to
648     // write zippered executables.
649     warn("writing zippered outputs not yet implemented, "
650          "ignoring all but last -platform_version flag");
651   }
652   config->platformInfo.minimum = lastVersionInfo->minimum;
653   config->platformInfo.sdk = lastVersionInfo->sdk;
654   return lastVersionInfo->platform;
655 }
656 
657 // Has the side-effect of setting Config::target.
658 static TargetInfo *createTargetInfo(InputArgList &args) {
659   StringRef archName = args.getLastArgValue(OPT_arch);
660   if (archName.empty()) {
661     error("must specify -arch");
662     return nullptr;
663   }
664 
665   PlatformType platform = parsePlatformVersions(args);
666   config->platformInfo.target =
667       MachO::Target(getArchitectureFromName(archName), platform);
668 
669   uint32_t cpuType;
670   uint32_t cpuSubtype;
671   std::tie(cpuType, cpuSubtype) = getCPUTypeFromArchitecture(config->arch());
672 
673   switch (cpuType) {
674   case CPU_TYPE_X86_64:
675     return createX86_64TargetInfo();
676   case CPU_TYPE_ARM64:
677     return createARM64TargetInfo();
678   case CPU_TYPE_ARM64_32:
679     return createARM64_32TargetInfo();
680   case CPU_TYPE_ARM:
681     return createARMTargetInfo(cpuSubtype);
682   default:
683     error("missing or unsupported -arch " + archName);
684     return nullptr;
685   }
686 }
687 
688 static UndefinedSymbolTreatment
689 getUndefinedSymbolTreatment(const ArgList &args) {
690   StringRef treatmentStr = args.getLastArgValue(OPT_undefined);
691   auto treatment =
692       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
693           .Cases("error", "", UndefinedSymbolTreatment::error)
694           .Case("warning", UndefinedSymbolTreatment::warning)
695           .Case("suppress", UndefinedSymbolTreatment::suppress)
696           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
697           .Default(UndefinedSymbolTreatment::unknown);
698   if (treatment == UndefinedSymbolTreatment::unknown) {
699     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
700          "', defaulting to 'error'");
701     treatment = UndefinedSymbolTreatment::error;
702   } else if (config->namespaceKind == NamespaceKind::twolevel &&
703              (treatment == UndefinedSymbolTreatment::warning ||
704               treatment == UndefinedSymbolTreatment::suppress)) {
705     if (treatment == UndefinedSymbolTreatment::warning)
706       error("'-undefined warning' only valid with '-flat_namespace'");
707     else
708       error("'-undefined suppress' only valid with '-flat_namespace'");
709     treatment = UndefinedSymbolTreatment::error;
710   }
711   return treatment;
712 }
713 
714 static ICFLevel getICFLevel(const ArgList &args) {
715   StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq);
716   auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
717                       .Cases("none", "", ICFLevel::none)
718                       .Case("safe", ICFLevel::safe)
719                       .Case("all", ICFLevel::all)
720                       .Default(ICFLevel::unknown);
721   if (icfLevel == ICFLevel::unknown) {
722     warn(Twine("unknown --icf=OPTION `") + icfLevelStr +
723          "', defaulting to `none'");
724     icfLevel = ICFLevel::none;
725   } else if (icfLevel == ICFLevel::safe) {
726     warn(Twine("`--icf=safe' is not yet implemented, reverting to `none'"));
727     icfLevel = ICFLevel::none;
728   }
729   return icfLevel;
730 }
731 
732 static void warnIfDeprecatedOption(const Option &opt) {
733   if (!opt.getGroup().isValid())
734     return;
735   if (opt.getGroup().getID() == OPT_grp_deprecated) {
736     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
737     warn(opt.getHelpText());
738   }
739 }
740 
741 static void warnIfUnimplementedOption(const Option &opt) {
742   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
743     return;
744   switch (opt.getGroup().getID()) {
745   case OPT_grp_deprecated:
746     // warn about deprecated options elsewhere
747     break;
748   case OPT_grp_undocumented:
749     warn("Option `" + opt.getPrefixedName() +
750          "' is undocumented. Should lld implement it?");
751     break;
752   case OPT_grp_obsolete:
753     warn("Option `" + opt.getPrefixedName() +
754          "' is obsolete. Please modernize your usage.");
755     break;
756   case OPT_grp_ignored:
757     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
758     break;
759   case OPT_grp_ignored_silently:
760     break;
761   default:
762     warn("Option `" + opt.getPrefixedName() +
763          "' is not yet implemented. Stay tuned...");
764     break;
765   }
766 }
767 
768 static const char *getReproduceOption(InputArgList &args) {
769   if (const Arg *arg = args.getLastArg(OPT_reproduce))
770     return arg->getValue();
771   return getenv("LLD_REPRODUCE");
772 }
773 
774 static void parseClangOption(StringRef opt, const Twine &msg) {
775   std::string err;
776   raw_string_ostream os(err);
777 
778   const char *argv[] = {"lld", opt.data()};
779   if (cl::ParseCommandLineOptions(2, argv, "", &os))
780     return;
781   os.flush();
782   error(msg + ": " + StringRef(err).trim());
783 }
784 
785 static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
786   const Arg *arg = args.getLastArg(id);
787   if (!arg)
788     return 0;
789 
790   if (config->outputType != MH_DYLIB) {
791     error(arg->getAsString(args) + ": only valid with -dylib");
792     return 0;
793   }
794 
795   PackedVersion version;
796   if (!version.parse32(arg->getValue())) {
797     error(arg->getAsString(args) + ": malformed version");
798     return 0;
799   }
800 
801   return version.rawValue();
802 }
803 
804 static uint32_t parseProtection(StringRef protStr) {
805   uint32_t prot = 0;
806   for (char c : protStr) {
807     switch (c) {
808     case 'r':
809       prot |= VM_PROT_READ;
810       break;
811     case 'w':
812       prot |= VM_PROT_WRITE;
813       break;
814     case 'x':
815       prot |= VM_PROT_EXECUTE;
816       break;
817     case '-':
818       break;
819     default:
820       error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);
821       return 0;
822     }
823   }
824   return prot;
825 }
826 
827 static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
828   std::vector<SectionAlign> sectAligns;
829   for (const Arg *arg : args.filtered(OPT_sectalign)) {
830     StringRef segName = arg->getValue(0);
831     StringRef sectName = arg->getValue(1);
832     StringRef alignStr = arg->getValue(2);
833     if (alignStr.startswith("0x") || alignStr.startswith("0X"))
834       alignStr = alignStr.drop_front(2);
835     uint32_t align;
836     if (alignStr.getAsInteger(16, align)) {
837       error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +
838             "' as number");
839       continue;
840     }
841     if (!isPowerOf2_32(align)) {
842       error("-sectalign: '" + StringRef(arg->getValue(2)) +
843             "' (in base 16) not a power of two");
844       continue;
845     }
846     sectAligns.push_back({segName, sectName, align});
847   }
848   return sectAligns;
849 }
850 
851 PlatformType macho::removeSimulator(PlatformType platform) {
852   switch (platform) {
853   case PLATFORM_IOSSIMULATOR:
854     return PLATFORM_IOS;
855   case PLATFORM_TVOSSIMULATOR:
856     return PLATFORM_TVOS;
857   case PLATFORM_WATCHOSSIMULATOR:
858     return PLATFORM_WATCHOS;
859   default:
860     return platform;
861   }
862 }
863 
864 static bool dataConstDefault(const InputArgList &args) {
865   static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = {
866       {PLATFORM_MACOS, VersionTuple(10, 15)},
867       {PLATFORM_IOS, VersionTuple(13, 0)},
868       {PLATFORM_TVOS, VersionTuple(13, 0)},
869       {PLATFORM_WATCHOS, VersionTuple(6, 0)},
870       {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}};
871   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
872   auto it = llvm::find_if(minVersion,
873                           [&](const auto &p) { return p.first == platform; });
874   if (it != minVersion.end())
875     if (config->platformInfo.minimum < it->second)
876       return false;
877 
878   switch (config->outputType) {
879   case MH_EXECUTE:
880     return !args.hasArg(OPT_no_pie);
881   case MH_BUNDLE:
882     // FIXME: return false when -final_name ...
883     // has prefix "/System/Library/UserEventPlugins/"
884     // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
885     return true;
886   case MH_DYLIB:
887     return true;
888   case MH_OBJECT:
889     return false;
890   default:
891     llvm_unreachable(
892         "unsupported output type for determining data-const default");
893   }
894   return false;
895 }
896 
897 void SymbolPatterns::clear() {
898   literals.clear();
899   globs.clear();
900 }
901 
902 void SymbolPatterns::insert(StringRef symbolName) {
903   if (symbolName.find_first_of("*?[]") == StringRef::npos)
904     literals.insert(CachedHashStringRef(symbolName));
905   else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))
906     globs.emplace_back(*pattern);
907   else
908     error("invalid symbol-name pattern: " + symbolName);
909 }
910 
911 bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
912   return literals.contains(CachedHashStringRef(symbolName));
913 }
914 
915 bool SymbolPatterns::matchGlob(StringRef symbolName) const {
916   for (const GlobPattern &glob : globs)
917     if (glob.match(symbolName))
918       return true;
919   return false;
920 }
921 
922 bool SymbolPatterns::match(StringRef symbolName) const {
923   return matchLiteral(symbolName) || matchGlob(symbolName);
924 }
925 
926 static void handleSymbolPatterns(InputArgList &args,
927                                  SymbolPatterns &symbolPatterns,
928                                  unsigned singleOptionCode,
929                                  unsigned listFileOptionCode) {
930   for (const Arg *arg : args.filtered(singleOptionCode))
931     symbolPatterns.insert(arg->getValue());
932   for (const Arg *arg : args.filtered(listFileOptionCode)) {
933     StringRef path = arg->getValue();
934     Optional<MemoryBufferRef> buffer = readFile(path);
935     if (!buffer) {
936       error("Could not read symbol file: " + path);
937       continue;
938     }
939     MemoryBufferRef mbref = *buffer;
940     for (StringRef line : args::getLines(mbref)) {
941       line = line.take_until([](char c) { return c == '#'; }).trim();
942       if (!line.empty())
943         symbolPatterns.insert(line);
944     }
945   }
946 }
947 
948 static void createFiles(const InputArgList &args) {
949   TimeTraceScope timeScope("Load input files");
950   // This loop should be reserved for options whose exact ordering matters.
951   // Other options should be handled via filtered() and/or getLastArg().
952   bool isLazy = false;
953   for (const Arg *arg : args) {
954     const Option &opt = arg->getOption();
955     warnIfDeprecatedOption(opt);
956     warnIfUnimplementedOption(opt);
957 
958     switch (opt.getID()) {
959     case OPT_INPUT:
960       addFile(rerootPath(arg->getValue()), ForceLoad::Default, isLazy);
961       break;
962     case OPT_needed_library:
963       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
964               addFile(rerootPath(arg->getValue()), ForceLoad::Default)))
965         dylibFile->forceNeeded = true;
966       break;
967     case OPT_reexport_library:
968       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
969               addFile(rerootPath(arg->getValue()), ForceLoad::Default))) {
970         config->hasReexports = true;
971         dylibFile->reexport = true;
972       }
973       break;
974     case OPT_weak_library:
975       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
976               addFile(rerootPath(arg->getValue()), ForceLoad::Default)))
977         dylibFile->forceWeakImport = true;
978       break;
979     case OPT_filelist:
980       addFileList(arg->getValue(), isLazy);
981       break;
982     case OPT_force_load:
983       addFile(rerootPath(arg->getValue()), ForceLoad::Yes);
984       break;
985     case OPT_l:
986     case OPT_needed_l:
987     case OPT_reexport_l:
988     case OPT_weak_l:
989       addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,
990                  opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,
991                  /*isExplicit=*/true, ForceLoad::Default);
992       break;
993     case OPT_framework:
994     case OPT_needed_framework:
995     case OPT_reexport_framework:
996     case OPT_weak_framework:
997       addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,
998                    opt.getID() == OPT_weak_framework,
999                    opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
1000                    ForceLoad::Default);
1001       break;
1002     case OPT_start_lib:
1003       if (isLazy)
1004         error("nested --start-lib");
1005       isLazy = true;
1006       break;
1007     case OPT_end_lib:
1008       if (!isLazy)
1009         error("stray --end-lib");
1010       isLazy = false;
1011       break;
1012     default:
1013       break;
1014     }
1015   }
1016 }
1017 
1018 static void gatherInputSections() {
1019   TimeTraceScope timeScope("Gathering input sections");
1020   int inputOrder = 0;
1021   for (const InputFile *file : inputFiles) {
1022     for (const Section *section : file->sections) {
1023       if (section->name == section_names::compactUnwind)
1024         // Compact unwind entries require special handling elsewhere.
1025         continue;
1026       ConcatOutputSection *osec = nullptr;
1027       for (const Subsection &subsection : section->subsections) {
1028         if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) {
1029           if (isec->isCoalescedWeak())
1030             continue;
1031           isec->outSecOff = inputOrder++;
1032           if (!osec)
1033             osec = ConcatOutputSection::getOrCreateForInput(isec);
1034           isec->parent = osec;
1035           inputSections.push_back(isec);
1036         } else if (auto *isec =
1037                        dyn_cast<CStringInputSection>(subsection.isec)) {
1038           if (in.cStringSection->inputOrder == UnspecifiedInputOrder)
1039             in.cStringSection->inputOrder = inputOrder++;
1040           in.cStringSection->addInput(isec);
1041         } else if (auto *isec =
1042                        dyn_cast<WordLiteralInputSection>(subsection.isec)) {
1043           if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder)
1044             in.wordLiteralSection->inputOrder = inputOrder++;
1045           in.wordLiteralSection->addInput(isec);
1046         } else {
1047           llvm_unreachable("unexpected input section kind");
1048         }
1049       }
1050     }
1051   }
1052   assert(inputOrder <= UnspecifiedInputOrder);
1053 }
1054 
1055 static void foldIdenticalLiterals() {
1056   // We always create a cStringSection, regardless of whether dedupLiterals is
1057   // true. If it isn't, we simply create a non-deduplicating CStringSection.
1058   // Either way, we must unconditionally finalize it here.
1059   in.cStringSection->finalizeContents();
1060   if (in.wordLiteralSection)
1061     in.wordLiteralSection->finalizeContents();
1062 }
1063 
1064 static void referenceStubBinder() {
1065   bool needsStubHelper = config->outputType == MH_DYLIB ||
1066                          config->outputType == MH_EXECUTE ||
1067                          config->outputType == MH_BUNDLE;
1068   if (!needsStubHelper || !symtab->find("dyld_stub_binder"))
1069     return;
1070 
1071   // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
1072   // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
1073   // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
1074   // isn't needed for correctness, but the presence of that symbol suppresses
1075   // "no symbols" diagnostics from `nm`.
1076   // StubHelperSection::setup() adds a reference and errors out if
1077   // dyld_stub_binder doesn't exist in case it is actually needed.
1078   symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false);
1079 }
1080 
1081 bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1082                  llvm::raw_ostream &stderrOS, bool exitEarly,
1083                  bool disableOutput) {
1084   // This driver-specific context will be freed later by lldMain().
1085   auto *ctx = new CommonLinkerContext;
1086 
1087   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1088   ctx->e.cleanupCallback = []() {
1089     resolvedFrameworks.clear();
1090     resolvedLibraries.clear();
1091     cachedReads.clear();
1092     concatOutputSections.clear();
1093     inputFiles.clear();
1094     inputSections.clear();
1095     loadedArchives.clear();
1096     loadedObjectFrameworks.clear();
1097     syntheticSections.clear();
1098     thunkMap.clear();
1099 
1100     firstTLVDataSection = nullptr;
1101     tar = nullptr;
1102     memset(&in, 0, sizeof(in));
1103 
1104     resetLoadedDylibs();
1105     resetOutputSegments();
1106     resetWriter();
1107     InputFile::resetIdCount();
1108   };
1109 
1110   ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]);
1111 
1112   MachOOptTable parser;
1113   InputArgList args = parser.parse(argsArr.slice(1));
1114 
1115   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
1116                                  "(use --error-limit=0 to see all errors)";
1117   ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);
1118   ctx->e.verbose = args.hasArg(OPT_verbose);
1119 
1120   if (args.hasArg(OPT_help_hidden)) {
1121     parser.printHelp(argsArr[0], /*showHidden=*/true);
1122     return true;
1123   }
1124   if (args.hasArg(OPT_help)) {
1125     parser.printHelp(argsArr[0], /*showHidden=*/false);
1126     return true;
1127   }
1128   if (args.hasArg(OPT_version)) {
1129     message(getLLDVersion());
1130     return true;
1131   }
1132 
1133   config = std::make_unique<Configuration>();
1134   symtab = std::make_unique<SymbolTable>();
1135   target = createTargetInfo(args);
1136   depTracker = std::make_unique<DependencyTracker>(
1137       args.getLastArgValue(OPT_dependency_info));
1138   if (errorCount())
1139     return false;
1140 
1141   if (args.hasArg(OPT_pagezero_size)) {
1142     uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0);
1143 
1144     // ld64 does something really weird. It attempts to realign the value to the
1145     // page size, but assumes the the page size is 4K. This doesn't work with
1146     // most of Apple's ARM64 devices, which use a page size of 16K. This means
1147     // that it will first 4K align it by rounding down, then round up to 16K.
1148     // This probably only happened because no one using this arg with anything
1149     // other then 0, so no one checked if it did what is what it says it does.
1150 
1151     // So we are not copying this weird behavior and doing the it in a logical
1152     // way, by always rounding down to page size.
1153     if (!isAligned(Align(target->getPageSize()), pagezeroSize)) {
1154       pagezeroSize -= pagezeroSize % target->getPageSize();
1155       warn("__PAGEZERO size is not page aligned, rounding down to 0x" +
1156            Twine::utohexstr(pagezeroSize));
1157     }
1158 
1159     target->pageZeroSize = pagezeroSize;
1160   }
1161 
1162   config->osoPrefix = args.getLastArgValue(OPT_oso_prefix);
1163   if (!config->osoPrefix.empty()) {
1164     // Expand special characters, such as ".", "..", or  "~", if present.
1165     // Note: LD64 only expands "." and not other special characters.
1166     // That seems silly to imitate so we will not try to follow it, but rather
1167     // just use real_path() to do it.
1168 
1169     // The max path length is 4096, in theory. However that seems quite long
1170     // and seems unlikely that any one would want to strip everything from the
1171     // path. Hence we've picked a reasonably large number here.
1172     SmallString<1024> expanded;
1173     if (!fs::real_path(config->osoPrefix, expanded,
1174                        /*expand_tilde=*/true)) {
1175       // Note: LD64 expands "." to be `<current_dir>/`
1176       // (ie., it has a slash suffix) whereas real_path() doesn't.
1177       // So we have to append '/' to be consistent.
1178       StringRef sep = sys::path::get_separator();
1179       // real_path removes trailing slashes as part of the normalization, but
1180       // these are meaningful for our text based stripping
1181       if (config->osoPrefix.equals(".") || config->osoPrefix.endswith(sep))
1182         expanded += sep;
1183       config->osoPrefix = saver().save(expanded.str());
1184     }
1185   }
1186 
1187   // Must be set before any InputSections and Symbols are created.
1188   config->deadStrip = args.hasArg(OPT_dead_strip);
1189 
1190   config->systemLibraryRoots = getSystemLibraryRoots(args);
1191   if (const char *path = getReproduceOption(args)) {
1192     // Note that --reproduce is a debug option so you can ignore it
1193     // if you are trying to understand the whole picture of the code.
1194     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1195         TarWriter::create(path, path::stem(path));
1196     if (errOrWriter) {
1197       tar = std::move(*errOrWriter);
1198       tar->append("response.txt", createResponseFile(args));
1199       tar->append("version.txt", getLLDVersion() + "\n");
1200     } else {
1201       error("--reproduce: " + toString(errOrWriter.takeError()));
1202     }
1203   }
1204 
1205   if (auto *arg = args.getLastArg(OPT_threads_eq)) {
1206     StringRef v(arg->getValue());
1207     unsigned threads = 0;
1208     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1209       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1210             arg->getValue() + "'");
1211     parallel::strategy = hardware_concurrency(threads);
1212     config->thinLTOJobs = v;
1213   }
1214   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1215     config->thinLTOJobs = arg->getValue();
1216   if (!get_threadpool_strategy(config->thinLTOJobs))
1217     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1218 
1219   for (const Arg *arg : args.filtered(OPT_u)) {
1220     config->explicitUndefineds.push_back(symtab->addUndefined(
1221         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1222   }
1223 
1224   for (const Arg *arg : args.filtered(OPT_U))
1225     config->explicitDynamicLookups.insert(arg->getValue());
1226 
1227   config->mapFile = args.getLastArgValue(OPT_map);
1228   config->optimize = args::getInteger(args, OPT_O, 1);
1229   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
1230   config->finalOutput =
1231       args.getLastArgValue(OPT_final_output, config->outputFile);
1232   config->astPaths = args.getAllArgValues(OPT_add_ast_path);
1233   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
1234   config->headerPadMaxInstallNames =
1235       args.hasArg(OPT_headerpad_max_install_names);
1236   config->printDylibSearch =
1237       args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");
1238   config->printEachFile = args.hasArg(OPT_t);
1239   config->printWhyLoad = args.hasArg(OPT_why_load);
1240   config->omitDebugInfo = args.hasArg(OPT_S);
1241   config->outputType = getOutputType(args);
1242   config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal);
1243   if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {
1244     if (config->outputType != MH_BUNDLE)
1245       error("-bundle_loader can only be used with MachO bundle output");
1246     addFile(arg->getValue(), ForceLoad::Default, /*isLazy=*/false,
1247             /*isExplicit=*/false,
1248             /*isBundleLoader=*/true);
1249   }
1250   if (const Arg *arg = args.getLastArg(OPT_umbrella)) {
1251     if (config->outputType != MH_DYLIB)
1252       warn("-umbrella used, but not creating dylib");
1253     config->umbrella = arg->getValue();
1254   }
1255   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
1256   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1257   if (config->ltoo > 3)
1258     error("--lto-O: invalid optimization level: " + Twine(config->ltoo));
1259   config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto);
1260   config->thinLTOCachePolicy = getLTOCachePolicy(args);
1261   config->runtimePaths = args::getStrings(args, OPT_rpath);
1262   config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false);
1263   config->archMultiple = args.hasArg(OPT_arch_multiple);
1264   config->applicationExtension = args.hasFlag(
1265       OPT_application_extension, OPT_no_application_extension, false);
1266   config->exportDynamic = args.hasArg(OPT_export_dynamic);
1267   config->forceLoadObjC = args.hasArg(OPT_ObjC);
1268   config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);
1269   config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);
1270   config->demangle = args.hasArg(OPT_demangle);
1271   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
1272   config->emitFunctionStarts =
1273       args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);
1274   config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle);
1275   config->emitDataInCodeInfo =
1276       args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);
1277   config->icfLevel = getICFLevel(args);
1278   config->dedupLiterals =
1279       args.hasFlag(OPT_deduplicate_literals, OPT_icf_eq, false) ||
1280       config->icfLevel != ICFLevel::none;
1281   config->warnDylibInstallName = args.hasFlag(
1282       OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false);
1283   config->callGraphProfileSort = args.hasFlag(
1284       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1285   config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order);
1286 
1287   // FIXME: Add a commandline flag for this too.
1288   config->zeroModTime = getenv("ZERO_AR_DATE");
1289 
1290   std::array<PlatformType, 3> encryptablePlatforms{
1291       PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS};
1292   config->emitEncryptionInfo =
1293       args.hasFlag(OPT_encryptable, OPT_no_encryption,
1294                    is_contained(encryptablePlatforms, config->platform()));
1295 
1296 #ifndef LLVM_HAVE_LIBXAR
1297   if (config->emitBitcodeBundle)
1298     error("-bitcode_bundle unsupported because LLD wasn't built with libxar");
1299 #endif
1300 
1301   if (const Arg *arg = args.getLastArg(OPT_install_name)) {
1302     if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
1303       warn(
1304           arg->getAsString(args) +
1305           ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
1306     else
1307       config->installName = arg->getValue();
1308   } else if (config->outputType == MH_DYLIB) {
1309     config->installName = config->finalOutput;
1310   }
1311 
1312   if (args.hasArg(OPT_mark_dead_strippable_dylib)) {
1313     if (config->outputType != MH_DYLIB)
1314       warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
1315     else
1316       config->markDeadStrippableDylib = true;
1317   }
1318 
1319   if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
1320     config->staticLink = (arg->getOption().getID() == OPT_static);
1321 
1322   if (const Arg *arg =
1323           args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
1324     config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
1325                                 ? NamespaceKind::twolevel
1326                                 : NamespaceKind::flat;
1327 
1328   config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
1329 
1330   if (config->outputType == MH_EXECUTE)
1331     config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
1332                                          /*file=*/nullptr,
1333                                          /*isWeakRef=*/false);
1334 
1335   config->librarySearchPaths =
1336       getLibrarySearchPaths(args, config->systemLibraryRoots);
1337   config->frameworkSearchPaths =
1338       getFrameworkSearchPaths(args, config->systemLibraryRoots);
1339   if (const Arg *arg =
1340           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
1341     config->searchDylibsFirst =
1342         arg->getOption().getID() == OPT_search_dylibs_first;
1343 
1344   config->dylibCompatibilityVersion =
1345       parseDylibVersion(args, OPT_compatibility_version);
1346   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
1347 
1348   config->dataConst =
1349       args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));
1350   // Populate config->sectionRenameMap with builtin default renames.
1351   // Options -rename_section and -rename_segment are able to override.
1352   initializeSectionRenameMap();
1353   // Reject every special character except '.' and '$'
1354   // TODO(gkm): verify that this is the proper set of invalid chars
1355   StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
1356   auto validName = [invalidNameChars](StringRef s) {
1357     if (s.find_first_of(invalidNameChars) != StringRef::npos)
1358       error("invalid name for segment or section: " + s);
1359     return s;
1360   };
1361   for (const Arg *arg : args.filtered(OPT_rename_section)) {
1362     config->sectionRenameMap[{validName(arg->getValue(0)),
1363                               validName(arg->getValue(1))}] = {
1364         validName(arg->getValue(2)), validName(arg->getValue(3))};
1365   }
1366   for (const Arg *arg : args.filtered(OPT_rename_segment)) {
1367     config->segmentRenameMap[validName(arg->getValue(0))] =
1368         validName(arg->getValue(1));
1369   }
1370 
1371   config->sectionAlignments = parseSectAlign(args);
1372 
1373   for (const Arg *arg : args.filtered(OPT_segprot)) {
1374     StringRef segName = arg->getValue(0);
1375     uint32_t maxProt = parseProtection(arg->getValue(1));
1376     uint32_t initProt = parseProtection(arg->getValue(2));
1377     if (maxProt != initProt && config->arch() != AK_i386)
1378       error("invalid argument '" + arg->getAsString(args) +
1379             "': max and init must be the same for non-i386 archs");
1380     if (segName == segment_names::linkEdit)
1381       error("-segprot cannot be used to change __LINKEDIT's protections");
1382     config->segmentProtections.push_back({segName, maxProt, initProt});
1383   }
1384 
1385   handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,
1386                        OPT_exported_symbols_list);
1387   handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,
1388                        OPT_unexported_symbols_list);
1389   if (!config->exportedSymbols.empty() && !config->unexportedSymbols.empty()) {
1390     error("cannot use both -exported_symbol* and -unexported_symbol* options\n"
1391           ">>> ignoring unexports");
1392     config->unexportedSymbols.clear();
1393   }
1394   // Explicitly-exported literal symbols must be defined, but might
1395   // languish in an archive if unreferenced elsewhere. Light a fire
1396   // under those lazy symbols!
1397   for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
1398     symtab->addUndefined(cachedName.val(), /*file=*/nullptr,
1399                          /*isWeakRef=*/false);
1400 
1401   for (const Arg *arg : args.filtered(OPT_why_live))
1402     config->whyLive.insert(arg->getValue());
1403   if (!config->whyLive.empty() && !config->deadStrip)
1404     warn("-why_live has no effect without -dead_strip, ignoring");
1405 
1406   config->saveTemps = args.hasArg(OPT_save_temps);
1407 
1408   config->adhocCodesign = args.hasFlag(
1409       OPT_adhoc_codesign, OPT_no_adhoc_codesign,
1410       (config->arch() == AK_arm64 || config->arch() == AK_arm64e) &&
1411           config->platform() == PLATFORM_MACOS);
1412 
1413   if (args.hasArg(OPT_v)) {
1414     message(getLLDVersion(), lld::errs());
1415     message(StringRef("Library search paths:") +
1416                 (config->librarySearchPaths.empty()
1417                      ? ""
1418                      : "\n\t" + join(config->librarySearchPaths, "\n\t")),
1419             lld::errs());
1420     message(StringRef("Framework search paths:") +
1421                 (config->frameworkSearchPaths.empty()
1422                      ? ""
1423                      : "\n\t" + join(config->frameworkSearchPaths, "\n\t")),
1424             lld::errs());
1425   }
1426 
1427   config->progName = argsArr[0];
1428 
1429   config->timeTraceEnabled = args.hasArg(
1430       OPT_time_trace, OPT_time_trace_granularity_eq, OPT_time_trace_file_eq);
1431   config->timeTraceGranularity =
1432       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
1433 
1434   // Initialize time trace profiler.
1435   if (config->timeTraceEnabled)
1436     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
1437 
1438   {
1439     TimeTraceScope timeScope("ExecuteLinker");
1440 
1441     initLLVM(); // must be run before any call to addFile()
1442     createFiles(args);
1443 
1444     config->isPic = config->outputType == MH_DYLIB ||
1445                     config->outputType == MH_BUNDLE ||
1446                     (config->outputType == MH_EXECUTE &&
1447                      args.hasFlag(OPT_pie, OPT_no_pie, true));
1448 
1449     // Now that all dylibs have been loaded, search for those that should be
1450     // re-exported.
1451     {
1452       auto reexportHandler = [](const Arg *arg,
1453                                 const std::vector<StringRef> &extensions) {
1454         config->hasReexports = true;
1455         StringRef searchName = arg->getValue();
1456         if (!markReexport(searchName, extensions))
1457           error(arg->getSpelling() + " " + searchName +
1458                 " does not match a supplied dylib");
1459       };
1460       std::vector<StringRef> extensions = {".tbd"};
1461       for (const Arg *arg : args.filtered(OPT_sub_umbrella))
1462         reexportHandler(arg, extensions);
1463 
1464       extensions.push_back(".dylib");
1465       for (const Arg *arg : args.filtered(OPT_sub_library))
1466         reexportHandler(arg, extensions);
1467     }
1468 
1469     cl::ResetAllOptionOccurrences();
1470 
1471     // Parse LTO options.
1472     if (const Arg *arg = args.getLastArg(OPT_mcpu))
1473       parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1474                        arg->getSpelling());
1475 
1476     for (const Arg *arg : args.filtered(OPT_mllvm))
1477       parseClangOption(arg->getValue(), arg->getSpelling());
1478 
1479     compileBitcodeFiles();
1480     replaceCommonSymbols();
1481 
1482     StringRef orderFile = args.getLastArgValue(OPT_order_file);
1483     if (!orderFile.empty())
1484       priorityBuilder.parseOrderFile(orderFile);
1485 
1486     referenceStubBinder();
1487 
1488     // FIXME: should terminate the link early based on errors encountered so
1489     // far?
1490 
1491     createSyntheticSections();
1492     createSyntheticSymbols();
1493 
1494     if (!config->exportedSymbols.empty()) {
1495       parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1496         if (auto *defined = dyn_cast<Defined>(sym)) {
1497           StringRef symbolName = defined->getName();
1498           if (config->exportedSymbols.match(symbolName)) {
1499             if (defined->privateExtern) {
1500               if (defined->weakDefCanBeHidden) {
1501                 // weak_def_can_be_hidden symbols behave similarly to
1502                 // private_extern symbols in most cases, except for when
1503                 // it is explicitly exported.
1504                 // The former can be exported but the latter cannot.
1505                 defined->privateExtern = false;
1506               } else {
1507                 warn("cannot export hidden symbol " + symbolName +
1508                      "\n>>> defined in " + toString(defined->getFile()));
1509               }
1510             }
1511           } else {
1512             defined->privateExtern = true;
1513           }
1514         }
1515       });
1516     } else if (!config->unexportedSymbols.empty()) {
1517       parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1518         if (auto *defined = dyn_cast<Defined>(sym))
1519           if (config->unexportedSymbols.match(defined->getName()))
1520             defined->privateExtern = true;
1521       });
1522     }
1523 
1524     for (const Arg *arg : args.filtered(OPT_sectcreate)) {
1525       StringRef segName = arg->getValue(0);
1526       StringRef sectName = arg->getValue(1);
1527       StringRef fileName = arg->getValue(2);
1528       Optional<MemoryBufferRef> buffer = readFile(fileName);
1529       if (buffer)
1530         inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
1531     }
1532 
1533     for (const Arg *arg : args.filtered(OPT_add_empty_section)) {
1534       StringRef segName = arg->getValue(0);
1535       StringRef sectName = arg->getValue(1);
1536       inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName));
1537     }
1538 
1539     gatherInputSections();
1540     if (config->callGraphProfileSort)
1541       priorityBuilder.extractCallGraphProfile();
1542 
1543     if (config->deadStrip)
1544       markLive();
1545 
1546     // ICF assumes that all literals have been folded already, so we must run
1547     // foldIdenticalLiterals before foldIdenticalSections.
1548     foldIdenticalLiterals();
1549     if (config->icfLevel != ICFLevel::none)
1550       foldIdenticalSections();
1551 
1552     // Write to an output file.
1553     if (target->wordSize == 8)
1554       writeResult<LP64>();
1555     else
1556       writeResult<ILP32>();
1557 
1558     depTracker->write(getLLDVersion(), inputFiles, config->outputFile);
1559   }
1560 
1561   if (config->timeTraceEnabled) {
1562     checkError(timeTraceProfilerWrite(
1563         args.getLastArgValue(OPT_time_trace_file_eq).str(),
1564         config->outputFile));
1565 
1566     timeTraceProfilerCleanup();
1567   }
1568   return errorCount() == 0;
1569 }
1570