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