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