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