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