xref: /llvm-project-15.0.7/lld/MachO/Driver.cpp (revision 2a7ed8fc)
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 // An order file has one entry per line, in the following format:
464 //
465 //   <cpu>:<object file>:<symbol name>
466 //
467 // <cpu> and <object file> are optional. If not specified, then that entry
468 // matches any symbol of that name. Parsing this format is not quite
469 // straightforward because the symbol name itself can contain colons, so when
470 // encountering a colon, we consider the preceding characters to decide if it
471 // can be a valid CPU type or file path.
472 //
473 // If a symbol is matched by multiple entries, then it takes the lowest-ordered
474 // entry (the one nearest to the front of the list.)
475 //
476 // The file can also have line comments that start with '#'.
477 // We expect sub-library names of the form "libfoo", which will match a dylib
478 // with a path of .*/libfoo.{dylib, tbd}.
479 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
480 // I'm not sure what the use case for that is.
481 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
482   for (InputFile *file : inputFiles) {
483     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
484       StringRef filename = path::filename(dylibFile->getName());
485       if (filename.consume_front(searchName) &&
486           (filename.empty() ||
487            find(extensions, filename) != extensions.end())) {
488         dylibFile->reexport = true;
489         return true;
490       }
491     }
492   }
493   return false;
494 }
495 
496 // This function is called on startup. We need this for LTO since
497 // LTO calls LLVM functions to compile bitcode files to native code.
498 // Technically this can be delayed until we read bitcode files, but
499 // we don't bother to do lazily because the initialization is fast.
500 static void initLLVM() {
501   InitializeAllTargets();
502   InitializeAllTargetMCs();
503   InitializeAllAsmPrinters();
504   InitializeAllAsmParsers();
505 }
506 
507 static void compileBitcodeFiles() {
508   TimeTraceScope timeScope("LTO");
509   auto *lto = make<BitcodeCompiler>();
510   for (InputFile *file : inputFiles)
511     if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
512       if (!file->lazy)
513         lto->add(*bitcodeFile);
514 
515   for (ObjFile *file : lto->compile())
516     inputFiles.insert(file);
517 }
518 
519 // Replaces common symbols with defined symbols residing in __common sections.
520 // This function must be called after all symbol names are resolved (i.e. after
521 // all InputFiles have been loaded.) As a result, later operations won't see
522 // any CommonSymbols.
523 static void replaceCommonSymbols() {
524   TimeTraceScope timeScope("Replace common symbols");
525   ConcatOutputSection *osec = nullptr;
526   for (Symbol *sym : symtab->getSymbols()) {
527     auto *common = dyn_cast<CommonSymbol>(sym);
528     if (common == nullptr)
529       continue;
530 
531     // Casting to size_t will truncate large values on 32-bit architectures,
532     // but it's not really worth supporting the linking of 64-bit programs on
533     // 32-bit archs.
534     ArrayRef<uint8_t> data = {nullptr, static_cast<size_t>(common->size)};
535     // FIXME avoid creating one Section per symbol?
536     auto *section =
537         make<Section>(common->getFile(), segment_names::data,
538                       section_names::common, S_ZEROFILL, /*addr=*/0);
539     auto *isec = make<ConcatInputSection>(*section, data, common->align);
540     if (!osec)
541       osec = ConcatOutputSection::getOrCreateForInput(isec);
542     isec->parent = osec;
543     inputSections.push_back(isec);
544 
545     // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
546     // and pass them on here.
547     replaceSymbol<Defined>(sym, sym->getName(), common->getFile(), isec,
548                            /*value=*/0,
549                            /*size=*/0,
550                            /*isWeakDef=*/false,
551                            /*isExternal=*/true, common->privateExtern,
552                            /*isThumb=*/false,
553                            /*isReferencedDynamically=*/false,
554                            /*noDeadStrip=*/false);
555   }
556 }
557 
558 static void initializeSectionRenameMap() {
559   if (config->dataConst) {
560     SmallVector<StringRef> v{section_names::got,
561                              section_names::authGot,
562                              section_names::authPtr,
563                              section_names::nonLazySymbolPtr,
564                              section_names::const_,
565                              section_names::cfString,
566                              section_names::moduleInitFunc,
567                              section_names::moduleTermFunc,
568                              section_names::objcClassList,
569                              section_names::objcNonLazyClassList,
570                              section_names::objcCatList,
571                              section_names::objcNonLazyCatList,
572                              section_names::objcProtoList,
573                              section_names::objcImageInfo};
574     for (StringRef s : v)
575       config->sectionRenameMap[{segment_names::data, s}] = {
576           segment_names::dataConst, s};
577   }
578   config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
579       segment_names::text, section_names::text};
580   config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
581       config->dataConst ? segment_names::dataConst : segment_names::data,
582       section_names::nonLazySymbolPtr};
583 }
584 
585 static inline char toLowerDash(char x) {
586   if (x >= 'A' && x <= 'Z')
587     return x - 'A' + 'a';
588   else if (x == ' ')
589     return '-';
590   return x;
591 }
592 
593 static std::string lowerDash(StringRef s) {
594   return std::string(map_iterator(s.begin(), toLowerDash),
595                      map_iterator(s.end(), toLowerDash));
596 }
597 
598 // Has the side-effect of setting Config::platformInfo.
599 static PlatformType parsePlatformVersion(const ArgList &args) {
600   const Arg *arg = args.getLastArg(OPT_platform_version);
601   if (!arg) {
602     error("must specify -platform_version");
603     return PLATFORM_UNKNOWN;
604   }
605 
606   StringRef platformStr = arg->getValue(0);
607   StringRef minVersionStr = arg->getValue(1);
608   StringRef sdkVersionStr = arg->getValue(2);
609 
610   // TODO(compnerd) see if we can generate this case list via XMACROS
611   PlatformType platform =
612       StringSwitch<PlatformType>(lowerDash(platformStr))
613           .Cases("macos", "1", PLATFORM_MACOS)
614           .Cases("ios", "2", PLATFORM_IOS)
615           .Cases("tvos", "3", PLATFORM_TVOS)
616           .Cases("watchos", "4", PLATFORM_WATCHOS)
617           .Cases("bridgeos", "5", PLATFORM_BRIDGEOS)
618           .Cases("mac-catalyst", "6", PLATFORM_MACCATALYST)
619           .Cases("ios-simulator", "7", PLATFORM_IOSSIMULATOR)
620           .Cases("tvos-simulator", "8", PLATFORM_TVOSSIMULATOR)
621           .Cases("watchos-simulator", "9", PLATFORM_WATCHOSSIMULATOR)
622           .Cases("driverkit", "10", PLATFORM_DRIVERKIT)
623           .Default(PLATFORM_UNKNOWN);
624   if (platform == PLATFORM_UNKNOWN)
625     error(Twine("malformed platform: ") + platformStr);
626   // TODO: check validity of version strings, which varies by platform
627   // NOTE: ld64 accepts version strings with 5 components
628   // llvm::VersionTuple accepts no more than 4 components
629   // Has Apple ever published version strings with 5 components?
630   if (config->platformInfo.minimum.tryParse(minVersionStr))
631     error(Twine("malformed minimum version: ") + minVersionStr);
632   if (config->platformInfo.sdk.tryParse(sdkVersionStr))
633     error(Twine("malformed sdk version: ") + sdkVersionStr);
634   return platform;
635 }
636 
637 // Has the side-effect of setting Config::target.
638 static TargetInfo *createTargetInfo(InputArgList &args) {
639   StringRef archName = args.getLastArgValue(OPT_arch);
640   if (archName.empty()) {
641     error("must specify -arch");
642     return nullptr;
643   }
644 
645   PlatformType platform = parsePlatformVersion(args);
646   config->platformInfo.target =
647       MachO::Target(getArchitectureFromName(archName), platform);
648 
649   uint32_t cpuType;
650   uint32_t cpuSubtype;
651   std::tie(cpuType, cpuSubtype) = getCPUTypeFromArchitecture(config->arch());
652 
653   switch (cpuType) {
654   case CPU_TYPE_X86_64:
655     return createX86_64TargetInfo();
656   case CPU_TYPE_ARM64:
657     return createARM64TargetInfo();
658   case CPU_TYPE_ARM64_32:
659     return createARM64_32TargetInfo();
660   case CPU_TYPE_ARM:
661     return createARMTargetInfo(cpuSubtype);
662   default:
663     error("missing or unsupported -arch " + archName);
664     return nullptr;
665   }
666 }
667 
668 static UndefinedSymbolTreatment
669 getUndefinedSymbolTreatment(const ArgList &args) {
670   StringRef treatmentStr = args.getLastArgValue(OPT_undefined);
671   auto treatment =
672       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
673           .Cases("error", "", UndefinedSymbolTreatment::error)
674           .Case("warning", UndefinedSymbolTreatment::warning)
675           .Case("suppress", UndefinedSymbolTreatment::suppress)
676           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
677           .Default(UndefinedSymbolTreatment::unknown);
678   if (treatment == UndefinedSymbolTreatment::unknown) {
679     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
680          "', defaulting to 'error'");
681     treatment = UndefinedSymbolTreatment::error;
682   } else if (config->namespaceKind == NamespaceKind::twolevel &&
683              (treatment == UndefinedSymbolTreatment::warning ||
684               treatment == UndefinedSymbolTreatment::suppress)) {
685     if (treatment == UndefinedSymbolTreatment::warning)
686       error("'-undefined warning' only valid with '-flat_namespace'");
687     else
688       error("'-undefined suppress' only valid with '-flat_namespace'");
689     treatment = UndefinedSymbolTreatment::error;
690   }
691   return treatment;
692 }
693 
694 static ICFLevel getICFLevel(const ArgList &args) {
695   StringRef icfLevelStr = args.getLastArgValue(OPT_icf_eq);
696   auto icfLevel = StringSwitch<ICFLevel>(icfLevelStr)
697                       .Cases("none", "", ICFLevel::none)
698                       .Case("safe", ICFLevel::safe)
699                       .Case("all", ICFLevel::all)
700                       .Default(ICFLevel::unknown);
701   if (icfLevel == ICFLevel::unknown) {
702     warn(Twine("unknown --icf=OPTION `") + icfLevelStr +
703          "', defaulting to `none'");
704     icfLevel = ICFLevel::none;
705   } else if (icfLevel == ICFLevel::safe) {
706     warn(Twine("`--icf=safe' is not yet implemented, reverting to `none'"));
707     icfLevel = ICFLevel::none;
708   }
709   return icfLevel;
710 }
711 
712 static void warnIfDeprecatedOption(const Option &opt) {
713   if (!opt.getGroup().isValid())
714     return;
715   if (opt.getGroup().getID() == OPT_grp_deprecated) {
716     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
717     warn(opt.getHelpText());
718   }
719 }
720 
721 static void warnIfUnimplementedOption(const Option &opt) {
722   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
723     return;
724   switch (opt.getGroup().getID()) {
725   case OPT_grp_deprecated:
726     // warn about deprecated options elsewhere
727     break;
728   case OPT_grp_undocumented:
729     warn("Option `" + opt.getPrefixedName() +
730          "' is undocumented. Should lld implement it?");
731     break;
732   case OPT_grp_obsolete:
733     warn("Option `" + opt.getPrefixedName() +
734          "' is obsolete. Please modernize your usage.");
735     break;
736   case OPT_grp_ignored:
737     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
738     break;
739   case OPT_grp_ignored_silently:
740     break;
741   default:
742     warn("Option `" + opt.getPrefixedName() +
743          "' is not yet implemented. Stay tuned...");
744     break;
745   }
746 }
747 
748 static const char *getReproduceOption(InputArgList &args) {
749   if (const Arg *arg = args.getLastArg(OPT_reproduce))
750     return arg->getValue();
751   return getenv("LLD_REPRODUCE");
752 }
753 
754 static void parseClangOption(StringRef opt, const Twine &msg) {
755   std::string err;
756   raw_string_ostream os(err);
757 
758   const char *argv[] = {"lld", opt.data()};
759   if (cl::ParseCommandLineOptions(2, argv, "", &os))
760     return;
761   os.flush();
762   error(msg + ": " + StringRef(err).trim());
763 }
764 
765 static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
766   const Arg *arg = args.getLastArg(id);
767   if (!arg)
768     return 0;
769 
770   if (config->outputType != MH_DYLIB) {
771     error(arg->getAsString(args) + ": only valid with -dylib");
772     return 0;
773   }
774 
775   PackedVersion version;
776   if (!version.parse32(arg->getValue())) {
777     error(arg->getAsString(args) + ": malformed version");
778     return 0;
779   }
780 
781   return version.rawValue();
782 }
783 
784 static uint32_t parseProtection(StringRef protStr) {
785   uint32_t prot = 0;
786   for (char c : protStr) {
787     switch (c) {
788     case 'r':
789       prot |= VM_PROT_READ;
790       break;
791     case 'w':
792       prot |= VM_PROT_WRITE;
793       break;
794     case 'x':
795       prot |= VM_PROT_EXECUTE;
796       break;
797     case '-':
798       break;
799     default:
800       error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);
801       return 0;
802     }
803   }
804   return prot;
805 }
806 
807 static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
808   std::vector<SectionAlign> sectAligns;
809   for (const Arg *arg : args.filtered(OPT_sectalign)) {
810     StringRef segName = arg->getValue(0);
811     StringRef sectName = arg->getValue(1);
812     StringRef alignStr = arg->getValue(2);
813     if (alignStr.startswith("0x") || alignStr.startswith("0X"))
814       alignStr = alignStr.drop_front(2);
815     uint32_t align;
816     if (alignStr.getAsInteger(16, align)) {
817       error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +
818             "' as number");
819       continue;
820     }
821     if (!isPowerOf2_32(align)) {
822       error("-sectalign: '" + StringRef(arg->getValue(2)) +
823             "' (in base 16) not a power of two");
824       continue;
825     }
826     sectAligns.push_back({segName, sectName, align});
827   }
828   return sectAligns;
829 }
830 
831 PlatformType macho::removeSimulator(PlatformType platform) {
832   switch (platform) {
833   case PLATFORM_IOSSIMULATOR:
834     return PLATFORM_IOS;
835   case PLATFORM_TVOSSIMULATOR:
836     return PLATFORM_TVOS;
837   case PLATFORM_WATCHOSSIMULATOR:
838     return PLATFORM_WATCHOS;
839   default:
840     return platform;
841   }
842 }
843 
844 static bool dataConstDefault(const InputArgList &args) {
845   static const std::vector<std::pair<PlatformType, VersionTuple>> minVersion = {
846       {PLATFORM_MACOS, VersionTuple(10, 15)},
847       {PLATFORM_IOS, VersionTuple(13, 0)},
848       {PLATFORM_TVOS, VersionTuple(13, 0)},
849       {PLATFORM_WATCHOS, VersionTuple(6, 0)},
850       {PLATFORM_BRIDGEOS, VersionTuple(4, 0)}};
851   PlatformType platform = removeSimulator(config->platformInfo.target.Platform);
852   auto it = llvm::find_if(minVersion,
853                           [&](const auto &p) { return p.first == platform; });
854   if (it != minVersion.end())
855     if (config->platformInfo.minimum < it->second)
856       return false;
857 
858   switch (config->outputType) {
859   case MH_EXECUTE:
860     return !args.hasArg(OPT_no_pie);
861   case MH_BUNDLE:
862     // FIXME: return false when -final_name ...
863     // has prefix "/System/Library/UserEventPlugins/"
864     // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
865     return true;
866   case MH_DYLIB:
867     return true;
868   case MH_OBJECT:
869     return false;
870   default:
871     llvm_unreachable(
872         "unsupported output type for determining data-const default");
873   }
874   return false;
875 }
876 
877 void SymbolPatterns::clear() {
878   literals.clear();
879   globs.clear();
880 }
881 
882 void SymbolPatterns::insert(StringRef symbolName) {
883   if (symbolName.find_first_of("*?[]") == StringRef::npos)
884     literals.insert(CachedHashStringRef(symbolName));
885   else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))
886     globs.emplace_back(*pattern);
887   else
888     error("invalid symbol-name pattern: " + symbolName);
889 }
890 
891 bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
892   return literals.contains(CachedHashStringRef(symbolName));
893 }
894 
895 bool SymbolPatterns::matchGlob(StringRef symbolName) const {
896   for (const GlobPattern &glob : globs)
897     if (glob.match(symbolName))
898       return true;
899   return false;
900 }
901 
902 bool SymbolPatterns::match(StringRef symbolName) const {
903   return matchLiteral(symbolName) || matchGlob(symbolName);
904 }
905 
906 static void handleSymbolPatterns(InputArgList &args,
907                                  SymbolPatterns &symbolPatterns,
908                                  unsigned singleOptionCode,
909                                  unsigned listFileOptionCode) {
910   for (const Arg *arg : args.filtered(singleOptionCode))
911     symbolPatterns.insert(arg->getValue());
912   for (const Arg *arg : args.filtered(listFileOptionCode)) {
913     StringRef path = arg->getValue();
914     Optional<MemoryBufferRef> buffer = readFile(path);
915     if (!buffer) {
916       error("Could not read symbol file: " + path);
917       continue;
918     }
919     MemoryBufferRef mbref = *buffer;
920     for (StringRef line : args::getLines(mbref)) {
921       line = line.take_until([](char c) { return c == '#'; }).trim();
922       if (!line.empty())
923         symbolPatterns.insert(line);
924     }
925   }
926 }
927 
928 static void createFiles(const InputArgList &args) {
929   TimeTraceScope timeScope("Load input files");
930   // This loop should be reserved for options whose exact ordering matters.
931   // Other options should be handled via filtered() and/or getLastArg().
932   bool isLazy = false;
933   for (const Arg *arg : args) {
934     const Option &opt = arg->getOption();
935     warnIfDeprecatedOption(opt);
936     warnIfUnimplementedOption(opt);
937 
938     switch (opt.getID()) {
939     case OPT_INPUT:
940       addFile(rerootPath(arg->getValue()), ForceLoad::Default, isLazy);
941       break;
942     case OPT_needed_library:
943       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
944               addFile(rerootPath(arg->getValue()), ForceLoad::Default)))
945         dylibFile->forceNeeded = true;
946       break;
947     case OPT_reexport_library:
948       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
949               addFile(rerootPath(arg->getValue()), ForceLoad::Default))) {
950         config->hasReexports = true;
951         dylibFile->reexport = true;
952       }
953       break;
954     case OPT_weak_library:
955       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
956               addFile(rerootPath(arg->getValue()), ForceLoad::Default)))
957         dylibFile->forceWeakImport = true;
958       break;
959     case OPT_filelist:
960       addFileList(arg->getValue(), isLazy);
961       break;
962     case OPT_force_load:
963       addFile(rerootPath(arg->getValue()), ForceLoad::Yes);
964       break;
965     case OPT_l:
966     case OPT_needed_l:
967     case OPT_reexport_l:
968     case OPT_weak_l:
969       addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,
970                  opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,
971                  /*isExplicit=*/true, ForceLoad::Default);
972       break;
973     case OPT_framework:
974     case OPT_needed_framework:
975     case OPT_reexport_framework:
976     case OPT_weak_framework:
977       addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,
978                    opt.getID() == OPT_weak_framework,
979                    opt.getID() == OPT_reexport_framework, /*isExplicit=*/true,
980                    ForceLoad::Default);
981       break;
982     case OPT_start_lib:
983       if (isLazy)
984         error("nested --start-lib");
985       isLazy = true;
986       break;
987     case OPT_end_lib:
988       if (!isLazy)
989         error("stray --end-lib");
990       isLazy = false;
991       break;
992     default:
993       break;
994     }
995   }
996 }
997 
998 static void gatherInputSections() {
999   TimeTraceScope timeScope("Gathering input sections");
1000   int inputOrder = 0;
1001   for (const InputFile *file : inputFiles) {
1002     for (const Section *section : file->sections) {
1003       const Subsections &subsections = section->subsections;
1004       if (subsections.empty())
1005         continue;
1006       if (subsections[0].isec->getName() == section_names::compactUnwind)
1007         // Compact unwind entries require special handling elsewhere.
1008         continue;
1009       ConcatOutputSection *osec = nullptr;
1010       for (const Subsection &subsection : subsections) {
1011         if (auto *isec = dyn_cast<ConcatInputSection>(subsection.isec)) {
1012           if (isec->isCoalescedWeak())
1013             continue;
1014           isec->outSecOff = inputOrder++;
1015           if (!osec)
1016             osec = ConcatOutputSection::getOrCreateForInput(isec);
1017           isec->parent = osec;
1018           inputSections.push_back(isec);
1019         } else if (auto *isec =
1020                        dyn_cast<CStringInputSection>(subsection.isec)) {
1021           if (in.cStringSection->inputOrder == UnspecifiedInputOrder)
1022             in.cStringSection->inputOrder = inputOrder++;
1023           in.cStringSection->addInput(isec);
1024         } else if (auto *isec =
1025                        dyn_cast<WordLiteralInputSection>(subsection.isec)) {
1026           if (in.wordLiteralSection->inputOrder == UnspecifiedInputOrder)
1027             in.wordLiteralSection->inputOrder = inputOrder++;
1028           in.wordLiteralSection->addInput(isec);
1029         } else {
1030           llvm_unreachable("unexpected input section kind");
1031         }
1032       }
1033     }
1034   }
1035   assert(inputOrder <= UnspecifiedInputOrder);
1036 }
1037 
1038 static void foldIdenticalLiterals() {
1039   // We always create a cStringSection, regardless of whether dedupLiterals is
1040   // true. If it isn't, we simply create a non-deduplicating CStringSection.
1041   // Either way, we must unconditionally finalize it here.
1042   in.cStringSection->finalizeContents();
1043   if (in.wordLiteralSection)
1044     in.wordLiteralSection->finalizeContents();
1045 }
1046 
1047 static void referenceStubBinder() {
1048   bool needsStubHelper = config->outputType == MH_DYLIB ||
1049                          config->outputType == MH_EXECUTE ||
1050                          config->outputType == MH_BUNDLE;
1051   if (!needsStubHelper || !symtab->find("dyld_stub_binder"))
1052     return;
1053 
1054   // dyld_stub_binder is used by dyld to resolve lazy bindings. This code here
1055   // adds a opportunistic reference to dyld_stub_binder if it happens to exist.
1056   // dyld_stub_binder is in libSystem.dylib, which is usually linked in. This
1057   // isn't needed for correctness, but the presence of that symbol suppresses
1058   // "no symbols" diagnostics from `nm`.
1059   // StubHelperSection::setup() adds a reference and errors out if
1060   // dyld_stub_binder doesn't exist in case it is actually needed.
1061   symtab->addUndefined("dyld_stub_binder", /*file=*/nullptr, /*isWeak=*/false);
1062 }
1063 
1064 bool macho::link(ArrayRef<const char *> argsArr, llvm::raw_ostream &stdoutOS,
1065                  llvm::raw_ostream &stderrOS, bool exitEarly,
1066                  bool disableOutput) {
1067   // This driver-specific context will be freed later by lldMain().
1068   auto *ctx = new CommonLinkerContext;
1069 
1070   ctx->e.initialize(stdoutOS, stderrOS, exitEarly, disableOutput);
1071   ctx->e.cleanupCallback = []() {
1072     resolvedFrameworks.clear();
1073     resolvedLibraries.clear();
1074     cachedReads.clear();
1075     concatOutputSections.clear();
1076     inputFiles.clear();
1077     inputSections.clear();
1078     loadedArchives.clear();
1079     loadedObjectFrameworks.clear();
1080     syntheticSections.clear();
1081     thunkMap.clear();
1082 
1083     firstTLVDataSection = nullptr;
1084     tar = nullptr;
1085     memset(&in, 0, sizeof(in));
1086 
1087     resetLoadedDylibs();
1088     resetOutputSegments();
1089     resetWriter();
1090     InputFile::resetIdCount();
1091   };
1092 
1093   ctx->e.logName = args::getFilenameWithoutExe(argsArr[0]);
1094 
1095   MachOOptTable parser;
1096   InputArgList args = parser.parse(argsArr.slice(1));
1097 
1098   ctx->e.errorLimitExceededMsg = "too many errors emitted, stopping now "
1099                                  "(use --error-limit=0 to see all errors)";
1100   ctx->e.errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);
1101   ctx->e.verbose = args.hasArg(OPT_verbose);
1102 
1103   if (args.hasArg(OPT_help_hidden)) {
1104     parser.printHelp(argsArr[0], /*showHidden=*/true);
1105     return true;
1106   }
1107   if (args.hasArg(OPT_help)) {
1108     parser.printHelp(argsArr[0], /*showHidden=*/false);
1109     return true;
1110   }
1111   if (args.hasArg(OPT_version)) {
1112     message(getLLDVersion());
1113     return true;
1114   }
1115 
1116   config = std::make_unique<Configuration>();
1117   symtab = std::make_unique<SymbolTable>();
1118   target = createTargetInfo(args);
1119   depTracker = std::make_unique<DependencyTracker>(
1120       args.getLastArgValue(OPT_dependency_info));
1121   if (errorCount())
1122     return false;
1123 
1124   if (args.hasArg(OPT_pagezero_size)) {
1125     uint64_t pagezeroSize = args::getHex(args, OPT_pagezero_size, 0);
1126 
1127     // ld64 does something really weird. It attempts to realign the value to the
1128     // page size, but assumes the the page size is 4K. This doesn't work with
1129     // most of Apple's ARM64 devices, which use a page size of 16K. This means
1130     // that it will first 4K align it by rounding down, then round up to 16K.
1131     // This probably only happened because no one using this arg with anything
1132     // other then 0, so no one checked if it did what is what it says it does.
1133 
1134     // So we are not copying this weird behavior and doing the it in a logical
1135     // way, by always rounding down to page size.
1136     if (!isAligned(Align(target->getPageSize()), pagezeroSize)) {
1137       pagezeroSize -= pagezeroSize % target->getPageSize();
1138       warn("__PAGEZERO size is not page aligned, rounding down to 0x" +
1139            Twine::utohexstr(pagezeroSize));
1140     }
1141 
1142     target->pageZeroSize = pagezeroSize;
1143   }
1144 
1145   config->osoPrefix = args.getLastArgValue(OPT_oso_prefix);
1146   if (!config->osoPrefix.empty()) {
1147     // Expand special characters, such as ".", "..", or  "~", if present.
1148     // Note: LD64 only expands "." and not other special characters.
1149     // That seems silly to imitate so we will not try to follow it, but rather
1150     // just use real_path() to do it.
1151 
1152     // The max path length is 4096, in theory. However that seems quite long
1153     // and seems unlikely that any one would want to strip everything from the
1154     // path. Hence we've picked a reasonably large number here.
1155     SmallString<1024> expanded;
1156     if (!fs::real_path(config->osoPrefix, expanded,
1157                        /*expand_tilde=*/true)) {
1158       // Note: LD64 expands "." to be `<current_dir>/`
1159       // (ie., it has a slash suffix) whereas real_path() doesn't.
1160       // So we have to append '/' to be consistent.
1161       StringRef sep = sys::path::get_separator();
1162       // real_path removes trailing slashes as part of the normalization, but
1163       // these are meaningful for our text based stripping
1164       if (config->osoPrefix.equals(".") || config->osoPrefix.endswith(sep))
1165         expanded += sep;
1166       config->osoPrefix = saver().save(expanded.str());
1167     }
1168   }
1169 
1170   // Must be set before any InputSections and Symbols are created.
1171   config->deadStrip = args.hasArg(OPT_dead_strip);
1172 
1173   config->systemLibraryRoots = getSystemLibraryRoots(args);
1174   if (const char *path = getReproduceOption(args)) {
1175     // Note that --reproduce is a debug option so you can ignore it
1176     // if you are trying to understand the whole picture of the code.
1177     Expected<std::unique_ptr<TarWriter>> errOrWriter =
1178         TarWriter::create(path, path::stem(path));
1179     if (errOrWriter) {
1180       tar = std::move(*errOrWriter);
1181       tar->append("response.txt", createResponseFile(args));
1182       tar->append("version.txt", getLLDVersion() + "\n");
1183     } else {
1184       error("--reproduce: " + toString(errOrWriter.takeError()));
1185     }
1186   }
1187 
1188   if (auto *arg = args.getLastArg(OPT_threads_eq)) {
1189     StringRef v(arg->getValue());
1190     unsigned threads = 0;
1191     if (!llvm::to_integer(v, threads, 0) || threads == 0)
1192       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1193             arg->getValue() + "'");
1194     parallel::strategy = hardware_concurrency(threads);
1195     config->thinLTOJobs = v;
1196   }
1197   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1198     config->thinLTOJobs = arg->getValue();
1199   if (!get_threadpool_strategy(config->thinLTOJobs))
1200     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1201 
1202   for (const Arg *arg : args.filtered(OPT_u)) {
1203     config->explicitUndefineds.push_back(symtab->addUndefined(
1204         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1205   }
1206 
1207   for (const Arg *arg : args.filtered(OPT_U))
1208     config->explicitDynamicLookups.insert(arg->getValue());
1209 
1210   config->mapFile = args.getLastArgValue(OPT_map);
1211   config->optimize = args::getInteger(args, OPT_O, 1);
1212   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
1213   config->finalOutput =
1214       args.getLastArgValue(OPT_final_output, config->outputFile);
1215   config->astPaths = args.getAllArgValues(OPT_add_ast_path);
1216   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
1217   config->headerPadMaxInstallNames =
1218       args.hasArg(OPT_headerpad_max_install_names);
1219   config->printDylibSearch =
1220       args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");
1221   config->printEachFile = args.hasArg(OPT_t);
1222   config->printWhyLoad = args.hasArg(OPT_why_load);
1223   config->omitDebugInfo = args.hasArg(OPT_S);
1224   config->outputType = getOutputType(args);
1225   config->errorForArchMismatch = args.hasArg(OPT_arch_errors_fatal);
1226   if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {
1227     if (config->outputType != MH_BUNDLE)
1228       error("-bundle_loader can only be used with MachO bundle output");
1229     addFile(arg->getValue(), ForceLoad::Default, /*isLazy=*/false,
1230             /*isExplicit=*/false,
1231             /*isBundleLoader=*/true);
1232   }
1233   if (const Arg *arg = args.getLastArg(OPT_umbrella)) {
1234     if (config->outputType != MH_DYLIB)
1235       warn("-umbrella used, but not creating dylib");
1236     config->umbrella = arg->getValue();
1237   }
1238   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
1239   config->ltoNewPassManager =
1240       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
1241                    LLVM_ENABLE_NEW_PASS_MANAGER);
1242   config->ltoo = args::getInteger(args, OPT_lto_O, 2);
1243   if (config->ltoo > 3)
1244     error("--lto-O: invalid optimization level: " + Twine(config->ltoo));
1245   config->thinLTOCacheDir = args.getLastArgValue(OPT_cache_path_lto);
1246   config->thinLTOCachePolicy = getLTOCachePolicy(args);
1247   config->runtimePaths = args::getStrings(args, OPT_rpath);
1248   config->allLoad = args.hasFlag(OPT_all_load, OPT_noall_load, false);
1249   config->archMultiple = args.hasArg(OPT_arch_multiple);
1250   config->applicationExtension = args.hasFlag(
1251       OPT_application_extension, OPT_no_application_extension, false);
1252   config->exportDynamic = args.hasArg(OPT_export_dynamic);
1253   config->forceLoadObjC = args.hasArg(OPT_ObjC);
1254   config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);
1255   config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);
1256   config->demangle = args.hasArg(OPT_demangle);
1257   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
1258   config->emitFunctionStarts =
1259       args.hasFlag(OPT_function_starts, OPT_no_function_starts, true);
1260   config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle);
1261   config->emitDataInCodeInfo =
1262       args.hasFlag(OPT_data_in_code_info, OPT_no_data_in_code_info, true);
1263   config->icfLevel = getICFLevel(args);
1264   config->dedupLiterals =
1265       args.hasFlag(OPT_deduplicate_literals, OPT_icf_eq, false) ||
1266       config->icfLevel != ICFLevel::none;
1267   config->warnDylibInstallName = args.hasFlag(
1268       OPT_warn_dylib_install_name, OPT_no_warn_dylib_install_name, false);
1269   config->callGraphProfileSort = args.hasFlag(
1270       OPT_call_graph_profile_sort, OPT_no_call_graph_profile_sort, true);
1271   config->printSymbolOrder = args.getLastArgValue(OPT_print_symbol_order);
1272 
1273   // FIXME: Add a commandline flag for this too.
1274   config->zeroModTime = getenv("ZERO_AR_DATE");
1275 
1276   std::array<PlatformType, 3> encryptablePlatforms{
1277       PLATFORM_IOS, PLATFORM_WATCHOS, PLATFORM_TVOS};
1278   config->emitEncryptionInfo =
1279       args.hasFlag(OPT_encryptable, OPT_no_encryption,
1280                    is_contained(encryptablePlatforms, config->platform()));
1281 
1282 #ifndef LLVM_HAVE_LIBXAR
1283   if (config->emitBitcodeBundle)
1284     error("-bitcode_bundle unsupported because LLD wasn't built with libxar");
1285 #endif
1286 
1287   if (const Arg *arg = args.getLastArg(OPT_install_name)) {
1288     if (config->warnDylibInstallName && config->outputType != MH_DYLIB)
1289       warn(
1290           arg->getAsString(args) +
1291           ": ignored, only has effect with -dylib [--warn-dylib-install-name]");
1292     else
1293       config->installName = arg->getValue();
1294   } else if (config->outputType == MH_DYLIB) {
1295     config->installName = config->finalOutput;
1296   }
1297 
1298   if (args.hasArg(OPT_mark_dead_strippable_dylib)) {
1299     if (config->outputType != MH_DYLIB)
1300       warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
1301     else
1302       config->markDeadStrippableDylib = true;
1303   }
1304 
1305   if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
1306     config->staticLink = (arg->getOption().getID() == OPT_static);
1307 
1308   if (const Arg *arg =
1309           args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
1310     config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
1311                                 ? NamespaceKind::twolevel
1312                                 : NamespaceKind::flat;
1313 
1314   config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
1315 
1316   if (config->outputType == MH_EXECUTE)
1317     config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
1318                                          /*file=*/nullptr,
1319                                          /*isWeakRef=*/false);
1320 
1321   config->librarySearchPaths =
1322       getLibrarySearchPaths(args, config->systemLibraryRoots);
1323   config->frameworkSearchPaths =
1324       getFrameworkSearchPaths(args, config->systemLibraryRoots);
1325   if (const Arg *arg =
1326           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
1327     config->searchDylibsFirst =
1328         arg->getOption().getID() == OPT_search_dylibs_first;
1329 
1330   config->dylibCompatibilityVersion =
1331       parseDylibVersion(args, OPT_compatibility_version);
1332   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
1333 
1334   config->dataConst =
1335       args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));
1336   // Populate config->sectionRenameMap with builtin default renames.
1337   // Options -rename_section and -rename_segment are able to override.
1338   initializeSectionRenameMap();
1339   // Reject every special character except '.' and '$'
1340   // TODO(gkm): verify that this is the proper set of invalid chars
1341   StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
1342   auto validName = [invalidNameChars](StringRef s) {
1343     if (s.find_first_of(invalidNameChars) != StringRef::npos)
1344       error("invalid name for segment or section: " + s);
1345     return s;
1346   };
1347   for (const Arg *arg : args.filtered(OPT_rename_section)) {
1348     config->sectionRenameMap[{validName(arg->getValue(0)),
1349                               validName(arg->getValue(1))}] = {
1350         validName(arg->getValue(2)), validName(arg->getValue(3))};
1351   }
1352   for (const Arg *arg : args.filtered(OPT_rename_segment)) {
1353     config->segmentRenameMap[validName(arg->getValue(0))] =
1354         validName(arg->getValue(1));
1355   }
1356 
1357   config->sectionAlignments = parseSectAlign(args);
1358 
1359   for (const Arg *arg : args.filtered(OPT_segprot)) {
1360     StringRef segName = arg->getValue(0);
1361     uint32_t maxProt = parseProtection(arg->getValue(1));
1362     uint32_t initProt = parseProtection(arg->getValue(2));
1363     if (maxProt != initProt && config->arch() != AK_i386)
1364       error("invalid argument '" + arg->getAsString(args) +
1365             "': max and init must be the same for non-i386 archs");
1366     if (segName == segment_names::linkEdit)
1367       error("-segprot cannot be used to change __LINKEDIT's protections");
1368     config->segmentProtections.push_back({segName, maxProt, initProt});
1369   }
1370 
1371   handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,
1372                        OPT_exported_symbols_list);
1373   handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,
1374                        OPT_unexported_symbols_list);
1375   if (!config->exportedSymbols.empty() && !config->unexportedSymbols.empty()) {
1376     error("cannot use both -exported_symbol* and -unexported_symbol* options\n"
1377           ">>> ignoring unexports");
1378     config->unexportedSymbols.clear();
1379   }
1380   // Explicitly-exported literal symbols must be defined, but might
1381   // languish in an archive if unreferenced elsewhere. Light a fire
1382   // under those lazy symbols!
1383   for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
1384     symtab->addUndefined(cachedName.val(), /*file=*/nullptr,
1385                          /*isWeakRef=*/false);
1386 
1387   config->saveTemps = args.hasArg(OPT_save_temps);
1388 
1389   config->adhocCodesign = args.hasFlag(
1390       OPT_adhoc_codesign, OPT_no_adhoc_codesign,
1391       (config->arch() == AK_arm64 || config->arch() == AK_arm64e) &&
1392           config->platform() == PLATFORM_MACOS);
1393 
1394   if (args.hasArg(OPT_v)) {
1395     message(getLLDVersion(), lld::errs());
1396     message(StringRef("Library search paths:") +
1397                 (config->librarySearchPaths.empty()
1398                      ? ""
1399                      : "\n\t" + join(config->librarySearchPaths, "\n\t")),
1400             lld::errs());
1401     message(StringRef("Framework search paths:") +
1402                 (config->frameworkSearchPaths.empty()
1403                      ? ""
1404                      : "\n\t" + join(config->frameworkSearchPaths, "\n\t")),
1405             lld::errs());
1406   }
1407 
1408   config->progName = argsArr[0];
1409 
1410   config->timeTraceEnabled = args.hasArg(
1411       OPT_time_trace, OPT_time_trace_granularity_eq, OPT_time_trace_file_eq);
1412   config->timeTraceGranularity =
1413       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
1414 
1415   // Initialize time trace profiler.
1416   if (config->timeTraceEnabled)
1417     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
1418 
1419   {
1420     TimeTraceScope timeScope("ExecuteLinker");
1421 
1422     initLLVM(); // must be run before any call to addFile()
1423     createFiles(args);
1424 
1425     config->isPic = config->outputType == MH_DYLIB ||
1426                     config->outputType == MH_BUNDLE ||
1427                     (config->outputType == MH_EXECUTE &&
1428                      args.hasFlag(OPT_pie, OPT_no_pie, true));
1429 
1430     // Now that all dylibs have been loaded, search for those that should be
1431     // re-exported.
1432     {
1433       auto reexportHandler = [](const Arg *arg,
1434                                 const std::vector<StringRef> &extensions) {
1435         config->hasReexports = true;
1436         StringRef searchName = arg->getValue();
1437         if (!markReexport(searchName, extensions))
1438           error(arg->getSpelling() + " " + searchName +
1439                 " does not match a supplied dylib");
1440       };
1441       std::vector<StringRef> extensions = {".tbd"};
1442       for (const Arg *arg : args.filtered(OPT_sub_umbrella))
1443         reexportHandler(arg, extensions);
1444 
1445       extensions.push_back(".dylib");
1446       for (const Arg *arg : args.filtered(OPT_sub_library))
1447         reexportHandler(arg, extensions);
1448     }
1449 
1450     cl::ResetAllOptionOccurrences();
1451 
1452     // Parse LTO options.
1453     if (const Arg *arg = args.getLastArg(OPT_mcpu))
1454       parseClangOption(saver().save("-mcpu=" + StringRef(arg->getValue())),
1455                        arg->getSpelling());
1456 
1457     for (const Arg *arg : args.filtered(OPT_mllvm))
1458       parseClangOption(arg->getValue(), arg->getSpelling());
1459 
1460     compileBitcodeFiles();
1461     replaceCommonSymbols();
1462 
1463     StringRef orderFile = args.getLastArgValue(OPT_order_file);
1464     if (!orderFile.empty()) {
1465       parseOrderFile(orderFile);
1466       config->callGraphProfileSort = false;
1467     }
1468 
1469     referenceStubBinder();
1470 
1471     // FIXME: should terminate the link early based on errors encountered so
1472     // far?
1473 
1474     createSyntheticSections();
1475     createSyntheticSymbols();
1476 
1477     if (!config->exportedSymbols.empty()) {
1478       parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1479         if (auto *defined = dyn_cast<Defined>(sym)) {
1480           StringRef symbolName = defined->getName();
1481           if (config->exportedSymbols.match(symbolName)) {
1482             if (defined->privateExtern) {
1483               if (defined->weakDefCanBeHidden) {
1484                 // weak_def_can_be_hidden symbols behave similarly to
1485                 // private_extern symbols in most cases, except for when
1486                 // it is explicitly exported.
1487                 // The former can be exported but the latter cannot.
1488                 defined->privateExtern = false;
1489               } else {
1490                 warn("cannot export hidden symbol " + symbolName +
1491                      "\n>>> defined in " + toString(defined->getFile()));
1492               }
1493             }
1494           } else {
1495             defined->privateExtern = true;
1496           }
1497         }
1498       });
1499     } else if (!config->unexportedSymbols.empty()) {
1500       parallelForEach(symtab->getSymbols(), [](Symbol *sym) {
1501         if (auto *defined = dyn_cast<Defined>(sym))
1502           if (config->unexportedSymbols.match(defined->getName()))
1503             defined->privateExtern = true;
1504       });
1505     }
1506 
1507     for (const Arg *arg : args.filtered(OPT_sectcreate)) {
1508       StringRef segName = arg->getValue(0);
1509       StringRef sectName = arg->getValue(1);
1510       StringRef fileName = arg->getValue(2);
1511       Optional<MemoryBufferRef> buffer = readFile(fileName);
1512       if (buffer)
1513         inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
1514     }
1515 
1516     for (const Arg *arg : args.filtered(OPT_add_empty_section)) {
1517       StringRef segName = arg->getValue(0);
1518       StringRef sectName = arg->getValue(1);
1519       inputFiles.insert(make<OpaqueFile>(MemoryBufferRef(), segName, sectName));
1520     }
1521 
1522     gatherInputSections();
1523     if (config->callGraphProfileSort)
1524       extractCallGraphProfile();
1525 
1526     if (config->deadStrip)
1527       markLive();
1528 
1529     // ICF assumes that all literals have been folded already, so we must run
1530     // foldIdenticalLiterals before foldIdenticalSections.
1531     foldIdenticalLiterals();
1532     if (config->icfLevel != ICFLevel::none)
1533       foldIdenticalSections();
1534 
1535     // Write to an output file.
1536     if (target->wordSize == 8)
1537       writeResult<LP64>();
1538     else
1539       writeResult<ILP32>();
1540 
1541     depTracker->write(getLLDVersion(), inputFiles, config->outputFile);
1542   }
1543 
1544   if (config->timeTraceEnabled) {
1545     checkError(timeTraceProfilerWrite(
1546         args.getLastArgValue(OPT_time_trace_file_eq).str(),
1547         config->outputFile));
1548 
1549     timeTraceProfilerCleanup();
1550   }
1551   return errorCount() == 0;
1552 }
1553