xref: /llvm-project-15.0.7/lld/MachO/Driver.cpp (revision f84dbd2f)
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 = make<ConcatInputSection>();
537     isec->file = common->getFile();
538     isec->name = section_names::common;
539     isec->segname = segment_names::data;
540     isec->align = common->align;
541     // Casting to size_t will truncate large values on 32-bit architectures,
542     // but it's not really worth supporting the linking of 64-bit programs on
543     // 32-bit archs.
544     isec->data = {nullptr, static_cast<size_t>(common->size)};
545     isec->flags = S_ZEROFILL;
546     inputSections.push_back(isec);
547 
548     // FIXME: CommonSymbol should store isReferencedDynamically, noDeadStrip
549     // and pass them on here.
550     replaceSymbol<Defined>(sym, sym->getName(), isec->file, isec, /*value=*/0,
551                            /*size=*/0,
552                            /*isWeakDef=*/false,
553                            /*isExternal=*/true, common->privateExtern,
554                            /*isThumb=*/false,
555                            /*isReferencedDynamically=*/false,
556                            /*noDeadStrip=*/false);
557   }
558 }
559 
560 static void initializeSectionRenameMap() {
561   if (config->dataConst) {
562     SmallVector<StringRef> v{section_names::got,
563                              section_names::authGot,
564                              section_names::authPtr,
565                              section_names::nonLazySymbolPtr,
566                              section_names::const_,
567                              section_names::cfString,
568                              section_names::moduleInitFunc,
569                              section_names::moduleTermFunc,
570                              section_names::objcClassList,
571                              section_names::objcNonLazyClassList,
572                              section_names::objcCatList,
573                              section_names::objcNonLazyCatList,
574                              section_names::objcProtoList,
575                              section_names::objcImageInfo};
576     for (StringRef s : v)
577       config->sectionRenameMap[{segment_names::data, s}] = {
578           segment_names::dataConst, s};
579   }
580   config->sectionRenameMap[{segment_names::text, section_names::staticInit}] = {
581       segment_names::text, section_names::text};
582   config->sectionRenameMap[{segment_names::import, section_names::pointers}] = {
583       config->dataConst ? segment_names::dataConst : segment_names::data,
584       section_names::nonLazySymbolPtr};
585 }
586 
587 static inline char toLowerDash(char x) {
588   if (x >= 'A' && x <= 'Z')
589     return x - 'A' + 'a';
590   else if (x == ' ')
591     return '-';
592   return x;
593 }
594 
595 static std::string lowerDash(StringRef s) {
596   return std::string(map_iterator(s.begin(), toLowerDash),
597                      map_iterator(s.end(), toLowerDash));
598 }
599 
600 // Has the side-effect of setting Config::platformInfo.
601 static PlatformKind parsePlatformVersion(const ArgList &args) {
602   const Arg *arg = args.getLastArg(OPT_platform_version);
603   if (!arg) {
604     error("must specify -platform_version");
605     return PlatformKind::unknown;
606   }
607 
608   StringRef platformStr = arg->getValue(0);
609   StringRef minVersionStr = arg->getValue(1);
610   StringRef sdkVersionStr = arg->getValue(2);
611 
612   // TODO(compnerd) see if we can generate this case list via XMACROS
613   PlatformKind platform =
614       StringSwitch<PlatformKind>(lowerDash(platformStr))
615           .Cases("macos", "1", PlatformKind::macOS)
616           .Cases("ios", "2", PlatformKind::iOS)
617           .Cases("tvos", "3", PlatformKind::tvOS)
618           .Cases("watchos", "4", PlatformKind::watchOS)
619           .Cases("bridgeos", "5", PlatformKind::bridgeOS)
620           .Cases("mac-catalyst", "6", PlatformKind::macCatalyst)
621           .Cases("ios-simulator", "7", PlatformKind::iOSSimulator)
622           .Cases("tvos-simulator", "8", PlatformKind::tvOSSimulator)
623           .Cases("watchos-simulator", "9", PlatformKind::watchOSSimulator)
624           .Cases("driverkit", "10", PlatformKind::driverKit)
625           .Default(PlatformKind::unknown);
626   if (platform == PlatformKind::unknown)
627     error(Twine("malformed platform: ") + platformStr);
628   // TODO: check validity of version strings, which varies by platform
629   // NOTE: ld64 accepts version strings with 5 components
630   // llvm::VersionTuple accepts no more than 4 components
631   // Has Apple ever published version strings with 5 components?
632   if (config->platformInfo.minimum.tryParse(minVersionStr))
633     error(Twine("malformed minimum version: ") + minVersionStr);
634   if (config->platformInfo.sdk.tryParse(sdkVersionStr))
635     error(Twine("malformed sdk version: ") + sdkVersionStr);
636   return platform;
637 }
638 
639 // Has the side-effect of setting Config::target.
640 static TargetInfo *createTargetInfo(InputArgList &args) {
641   StringRef archName = args.getLastArgValue(OPT_arch);
642   if (archName.empty())
643     fatal("must specify -arch");
644   PlatformKind platform = parsePlatformVersion(args);
645 
646   config->platformInfo.target =
647       MachO::Target(getArchitectureFromName(archName), platform);
648 
649   uint32_t cpuType;
650   uint32_t cpuSubtype;
651   std::tie(cpuType, cpuSubtype) = getCPUTypeFromArchitecture(config->arch());
652 
653   switch (cpuType) {
654   case CPU_TYPE_X86_64:
655     return createX86_64TargetInfo();
656   case CPU_TYPE_ARM64:
657     return createARM64TargetInfo();
658   case CPU_TYPE_ARM64_32:
659     return createARM64_32TargetInfo();
660   case CPU_TYPE_ARM:
661     return createARMTargetInfo(cpuSubtype);
662   default:
663     fatal("missing or unsupported -arch " + archName);
664   }
665 }
666 
667 static UndefinedSymbolTreatment
668 getUndefinedSymbolTreatment(const ArgList &args) {
669   StringRef treatmentStr = args.getLastArgValue(OPT_undefined);
670   auto treatment =
671       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
672           .Cases("error", "", UndefinedSymbolTreatment::error)
673           .Case("warning", UndefinedSymbolTreatment::warning)
674           .Case("suppress", UndefinedSymbolTreatment::suppress)
675           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
676           .Default(UndefinedSymbolTreatment::unknown);
677   if (treatment == UndefinedSymbolTreatment::unknown) {
678     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
679          "', defaulting to 'error'");
680     treatment = UndefinedSymbolTreatment::error;
681   } else if (config->namespaceKind == NamespaceKind::twolevel &&
682              (treatment == UndefinedSymbolTreatment::warning ||
683               treatment == UndefinedSymbolTreatment::suppress)) {
684     if (treatment == UndefinedSymbolTreatment::warning)
685       error("'-undefined warning' only valid with '-flat_namespace'");
686     else
687       error("'-undefined suppress' only valid with '-flat_namespace'");
688     treatment = UndefinedSymbolTreatment::error;
689   }
690   return treatment;
691 }
692 
693 static void warnIfDeprecatedOption(const Option &opt) {
694   if (!opt.getGroup().isValid())
695     return;
696   if (opt.getGroup().getID() == OPT_grp_deprecated) {
697     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
698     warn(opt.getHelpText());
699   }
700 }
701 
702 static void warnIfUnimplementedOption(const Option &opt) {
703   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
704     return;
705   switch (opt.getGroup().getID()) {
706   case OPT_grp_deprecated:
707     // warn about deprecated options elsewhere
708     break;
709   case OPT_grp_undocumented:
710     warn("Option `" + opt.getPrefixedName() +
711          "' is undocumented. Should lld implement it?");
712     break;
713   case OPT_grp_obsolete:
714     warn("Option `" + opt.getPrefixedName() +
715          "' is obsolete. Please modernize your usage.");
716     break;
717   case OPT_grp_ignored:
718     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
719     break;
720   default:
721     warn("Option `" + opt.getPrefixedName() +
722          "' is not yet implemented. Stay tuned...");
723     break;
724   }
725 }
726 
727 static const char *getReproduceOption(InputArgList &args) {
728   if (const Arg *arg = args.getLastArg(OPT_reproduce))
729     return arg->getValue();
730   return getenv("LLD_REPRODUCE");
731 }
732 
733 static void parseClangOption(StringRef opt, const Twine &msg) {
734   std::string err;
735   raw_string_ostream os(err);
736 
737   const char *argv[] = {"lld", opt.data()};
738   if (cl::ParseCommandLineOptions(2, argv, "", &os))
739     return;
740   os.flush();
741   error(msg + ": " + StringRef(err).trim());
742 }
743 
744 static uint32_t parseDylibVersion(const ArgList &args, unsigned id) {
745   const Arg *arg = args.getLastArg(id);
746   if (!arg)
747     return 0;
748 
749   if (config->outputType != MH_DYLIB) {
750     error(arg->getAsString(args) + ": only valid with -dylib");
751     return 0;
752   }
753 
754   PackedVersion version;
755   if (!version.parse32(arg->getValue())) {
756     error(arg->getAsString(args) + ": malformed version");
757     return 0;
758   }
759 
760   return version.rawValue();
761 }
762 
763 static uint32_t parseProtection(StringRef protStr) {
764   uint32_t prot = 0;
765   for (char c : protStr) {
766     switch (c) {
767     case 'r':
768       prot |= VM_PROT_READ;
769       break;
770     case 'w':
771       prot |= VM_PROT_WRITE;
772       break;
773     case 'x':
774       prot |= VM_PROT_EXECUTE;
775       break;
776     case '-':
777       break;
778     default:
779       error("unknown -segprot letter '" + Twine(c) + "' in " + protStr);
780       return 0;
781     }
782   }
783   return prot;
784 }
785 
786 static std::vector<SectionAlign> parseSectAlign(const opt::InputArgList &args) {
787   std::vector<SectionAlign> sectAligns;
788   for (const Arg *arg : args.filtered(OPT_sectalign)) {
789     StringRef segName = arg->getValue(0);
790     StringRef sectName = arg->getValue(1);
791     StringRef alignStr = arg->getValue(2);
792     if (alignStr.startswith("0x") || alignStr.startswith("0X"))
793       alignStr = alignStr.drop_front(2);
794     uint32_t align;
795     if (alignStr.getAsInteger(16, align)) {
796       error("-sectalign: failed to parse '" + StringRef(arg->getValue(2)) +
797             "' as number");
798       continue;
799     }
800     if (!isPowerOf2_32(align)) {
801       error("-sectalign: '" + StringRef(arg->getValue(2)) +
802             "' (in base 16) not a power of two");
803       continue;
804     }
805     sectAligns.push_back({segName, sectName, align});
806   }
807   return sectAligns;
808 }
809 
810 static bool dataConstDefault(const InputArgList &args) {
811   switch (config->outputType) {
812   case MH_EXECUTE:
813     return !args.hasArg(OPT_no_pie);
814   case MH_BUNDLE:
815     // FIXME: return false when -final_name ...
816     // has prefix "/System/Library/UserEventPlugins/"
817     // or matches "/usr/libexec/locationd" "/usr/libexec/terminusd"
818     return true;
819   case MH_DYLIB:
820     return true;
821   case MH_OBJECT:
822     return false;
823   default:
824     llvm_unreachable(
825         "unsupported output type for determining data-const default");
826   }
827   return false;
828 }
829 
830 void SymbolPatterns::clear() {
831   literals.clear();
832   globs.clear();
833 }
834 
835 void SymbolPatterns::insert(StringRef symbolName) {
836   if (symbolName.find_first_of("*?[]") == StringRef::npos)
837     literals.insert(CachedHashStringRef(symbolName));
838   else if (Expected<GlobPattern> pattern = GlobPattern::create(symbolName))
839     globs.emplace_back(*pattern);
840   else
841     error("invalid symbol-name pattern: " + symbolName);
842 }
843 
844 bool SymbolPatterns::matchLiteral(StringRef symbolName) const {
845   return literals.contains(CachedHashStringRef(symbolName));
846 }
847 
848 bool SymbolPatterns::matchGlob(StringRef symbolName) const {
849   for (const llvm::GlobPattern &glob : globs)
850     if (glob.match(symbolName))
851       return true;
852   return false;
853 }
854 
855 bool SymbolPatterns::match(StringRef symbolName) const {
856   return matchLiteral(symbolName) || matchGlob(symbolName);
857 }
858 
859 static void handleSymbolPatterns(InputArgList &args,
860                                  SymbolPatterns &symbolPatterns,
861                                  unsigned singleOptionCode,
862                                  unsigned listFileOptionCode) {
863   for (const Arg *arg : args.filtered(singleOptionCode))
864     symbolPatterns.insert(arg->getValue());
865   for (const Arg *arg : args.filtered(listFileOptionCode)) {
866     StringRef path = arg->getValue();
867     Optional<MemoryBufferRef> buffer = readFile(path);
868     if (!buffer) {
869       error("Could not read symbol file: " + path);
870       continue;
871     }
872     MemoryBufferRef mbref = *buffer;
873     for (StringRef line : args::getLines(mbref)) {
874       line = line.take_until([](char c) { return c == '#'; }).trim();
875       if (!line.empty())
876         symbolPatterns.insert(line);
877     }
878   }
879 }
880 
881 void createFiles(const InputArgList &args) {
882   TimeTraceScope timeScope("Load input files");
883   // This loop should be reserved for options whose exact ordering matters.
884   // Other options should be handled via filtered() and/or getLastArg().
885   for (const Arg *arg : args) {
886     const Option &opt = arg->getOption();
887     warnIfDeprecatedOption(opt);
888     warnIfUnimplementedOption(opt);
889 
890     switch (opt.getID()) {
891     case OPT_INPUT:
892       addFile(rerootPath(arg->getValue()), /*forceLoadArchive=*/false);
893       break;
894     case OPT_needed_library:
895       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
896               addFile(rerootPath(arg->getValue()), false)))
897         dylibFile->forceNeeded = true;
898       break;
899     case OPT_reexport_library:
900       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(
901               rerootPath(arg->getValue()), /*forceLoadArchive=*/false))) {
902         config->hasReexports = true;
903         dylibFile->reexport = true;
904       }
905       break;
906     case OPT_weak_library:
907       if (auto *dylibFile = dyn_cast_or_null<DylibFile>(
908               addFile(rerootPath(arg->getValue()), /*forceLoadArchive=*/false)))
909         dylibFile->forceWeakImport = true;
910       break;
911     case OPT_filelist:
912       addFileList(arg->getValue());
913       break;
914     case OPT_force_load:
915       addFile(rerootPath(arg->getValue()), /*forceLoadArchive=*/true);
916       break;
917     case OPT_l:
918     case OPT_needed_l:
919     case OPT_reexport_l:
920     case OPT_weak_l:
921       addLibrary(arg->getValue(), opt.getID() == OPT_needed_l,
922                  opt.getID() == OPT_weak_l, opt.getID() == OPT_reexport_l,
923                  /*isExplicit=*/true, /*forceLoad=*/false);
924       break;
925     case OPT_framework:
926     case OPT_needed_framework:
927     case OPT_reexport_framework:
928     case OPT_weak_framework:
929       addFramework(arg->getValue(), opt.getID() == OPT_needed_framework,
930                    opt.getID() == OPT_weak_framework,
931                    opt.getID() == OPT_reexport_framework, /*isExplicit=*/true);
932       break;
933     default:
934       break;
935     }
936   }
937 }
938 
939 bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
940                  raw_ostream &stdoutOS, raw_ostream &stderrOS) {
941   lld::stdoutOS = &stdoutOS;
942   lld::stderrOS = &stderrOS;
943 
944   errorHandler().cleanupCallback = []() { freeArena(); };
945 
946   errorHandler().logName = args::getFilenameWithoutExe(argsArr[0]);
947   stderrOS.enable_colors(stderrOS.has_colors());
948 
949   MachOOptTable parser;
950   InputArgList args = parser.parse(argsArr.slice(1));
951 
952   errorHandler().errorLimitExceededMsg =
953       "too many errors emitted, stopping now "
954       "(use --error-limit=0 to see all errors)";
955   errorHandler().errorLimit = args::getInteger(args, OPT_error_limit_eq, 20);
956   errorHandler().verbose = args.hasArg(OPT_verbose);
957 
958   if (args.hasArg(OPT_help_hidden)) {
959     parser.printHelp(argsArr[0], /*showHidden=*/true);
960     return true;
961   }
962   if (args.hasArg(OPT_help)) {
963     parser.printHelp(argsArr[0], /*showHidden=*/false);
964     return true;
965   }
966   if (args.hasArg(OPT_version)) {
967     message(getLLDVersion());
968     return true;
969   }
970 
971   config = make<Configuration>();
972   symtab = make<SymbolTable>();
973   target = createTargetInfo(args);
974   depTracker =
975       make<DependencyTracker>(args.getLastArgValue(OPT_dependency_info));
976 
977   // Must be set before any InputSections and Symbols are created.
978   config->deadStrip = args.hasArg(OPT_dead_strip);
979 
980   config->systemLibraryRoots = getSystemLibraryRoots(args);
981   if (const char *path = getReproduceOption(args)) {
982     // Note that --reproduce is a debug option so you can ignore it
983     // if you are trying to understand the whole picture of the code.
984     Expected<std::unique_ptr<TarWriter>> errOrWriter =
985         TarWriter::create(path, path::stem(path));
986     if (errOrWriter) {
987       tar = std::move(*errOrWriter);
988       tar->append("response.txt", createResponseFile(args));
989       tar->append("version.txt", getLLDVersion() + "\n");
990     } else {
991       error("--reproduce: " + toString(errOrWriter.takeError()));
992     }
993   }
994 
995   if (auto *arg = args.getLastArg(OPT_threads_eq)) {
996     StringRef v(arg->getValue());
997     unsigned threads = 0;
998     if (!llvm::to_integer(v, threads, 0) || threads == 0)
999       error(arg->getSpelling() + ": expected a positive integer, but got '" +
1000             arg->getValue() + "'");
1001     parallel::strategy = hardware_concurrency(threads);
1002     config->thinLTOJobs = v;
1003   }
1004   if (auto *arg = args.getLastArg(OPT_thinlto_jobs_eq))
1005     config->thinLTOJobs = arg->getValue();
1006   if (!get_threadpool_strategy(config->thinLTOJobs))
1007     error("--thinlto-jobs: invalid job count: " + config->thinLTOJobs);
1008 
1009   for (const Arg *arg : args.filtered(OPT_u)) {
1010     config->explicitUndefineds.push_back(symtab->addUndefined(
1011         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
1012   }
1013 
1014   for (const Arg *arg : args.filtered(OPT_U))
1015     symtab->addDynamicLookup(arg->getValue());
1016 
1017   config->mapFile = args.getLastArgValue(OPT_map);
1018   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
1019   config->astPaths = args.getAllArgValues(OPT_add_ast_path);
1020   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
1021   config->headerPadMaxInstallNames =
1022       args.hasArg(OPT_headerpad_max_install_names);
1023   config->printDylibSearch =
1024       args.hasArg(OPT_print_dylib_search) || getenv("RC_TRACE_DYLIB_SEARCHING");
1025   config->printEachFile = args.hasArg(OPT_t);
1026   config->printWhyLoad = args.hasArg(OPT_why_load);
1027   config->outputType = getOutputType(args);
1028   if (const Arg *arg = args.getLastArg(OPT_bundle_loader)) {
1029     if (config->outputType != MH_BUNDLE)
1030       error("-bundle_loader can only be used with MachO bundle output");
1031     addFile(arg->getValue(), /*forceLoadArchive=*/false, /*isExplicit=*/false,
1032             /*isBundleLoader=*/true);
1033   }
1034   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
1035   config->ltoNewPassManager =
1036       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
1037                    LLVM_ENABLE_NEW_PASS_MANAGER);
1038   config->runtimePaths = args::getStrings(args, OPT_rpath);
1039   config->allLoad = args.hasArg(OPT_all_load);
1040   config->forceLoadObjC = args.hasArg(OPT_ObjC);
1041   config->forceLoadSwift = args.hasArg(OPT_force_load_swift_libs);
1042   config->deadStripDylibs = args.hasArg(OPT_dead_strip_dylibs);
1043   config->demangle = args.hasArg(OPT_demangle);
1044   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
1045   config->emitFunctionStarts = !args.hasArg(OPT_no_function_starts);
1046   config->emitBitcodeBundle = args.hasArg(OPT_bitcode_bundle);
1047   config->dedupLiterals = args.hasArg(OPT_deduplicate_literals);
1048 
1049   // FIXME: Add a commandline flag for this too.
1050   config->zeroModTime = getenv("ZERO_AR_DATE");
1051 
1052   std::array<PlatformKind, 3> encryptablePlatforms{
1053       PlatformKind::iOS, PlatformKind::watchOS, PlatformKind::tvOS};
1054   config->emitEncryptionInfo =
1055       args.hasFlag(OPT_encryptable, OPT_no_encryption,
1056                    is_contained(encryptablePlatforms, config->platform()));
1057 
1058 #ifndef LLVM_HAVE_LIBXAR
1059   if (config->emitBitcodeBundle)
1060     error("-bitcode_bundle unsupported because LLD wasn't built with libxar");
1061 #endif
1062 
1063   if (const Arg *arg = args.getLastArg(OPT_install_name)) {
1064     if (config->outputType != MH_DYLIB)
1065       warn(arg->getAsString(args) + ": ignored, only has effect with -dylib");
1066     else
1067       config->installName = arg->getValue();
1068   } else if (config->outputType == MH_DYLIB) {
1069     config->installName = config->outputFile;
1070   }
1071 
1072   if (args.hasArg(OPT_mark_dead_strippable_dylib)) {
1073     if (config->outputType != MH_DYLIB)
1074       warn("-mark_dead_strippable_dylib: ignored, only has effect with -dylib");
1075     else
1076       config->markDeadStrippableDylib = true;
1077   }
1078 
1079   if (const Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
1080     config->staticLink = (arg->getOption().getID() == OPT_static);
1081 
1082   if (const Arg *arg =
1083           args.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace))
1084     config->namespaceKind = arg->getOption().getID() == OPT_twolevel_namespace
1085                                 ? NamespaceKind::twolevel
1086                                 : NamespaceKind::flat;
1087 
1088   config->undefinedSymbolTreatment = getUndefinedSymbolTreatment(args);
1089 
1090   if (config->outputType == MH_EXECUTE)
1091     config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
1092                                          /*file=*/nullptr,
1093                                          /*isWeakRef=*/false);
1094 
1095   config->librarySearchPaths =
1096       getLibrarySearchPaths(args, config->systemLibraryRoots);
1097   config->frameworkSearchPaths =
1098       getFrameworkSearchPaths(args, config->systemLibraryRoots);
1099   if (const Arg *arg =
1100           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
1101     config->searchDylibsFirst =
1102         arg->getOption().getID() == OPT_search_dylibs_first;
1103 
1104   config->dylibCompatibilityVersion =
1105       parseDylibVersion(args, OPT_compatibility_version);
1106   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
1107 
1108   config->dataConst =
1109       args.hasFlag(OPT_data_const, OPT_no_data_const, dataConstDefault(args));
1110   // Populate config->sectionRenameMap with builtin default renames.
1111   // Options -rename_section and -rename_segment are able to override.
1112   initializeSectionRenameMap();
1113   // Reject every special character except '.' and '$'
1114   // TODO(gkm): verify that this is the proper set of invalid chars
1115   StringRef invalidNameChars("!\"#%&'()*+,-/:;<=>?@[\\]^`{|}~");
1116   auto validName = [invalidNameChars](StringRef s) {
1117     if (s.find_first_of(invalidNameChars) != StringRef::npos)
1118       error("invalid name for segment or section: " + s);
1119     return s;
1120   };
1121   for (const Arg *arg : args.filtered(OPT_rename_section)) {
1122     config->sectionRenameMap[{validName(arg->getValue(0)),
1123                               validName(arg->getValue(1))}] = {
1124         validName(arg->getValue(2)), validName(arg->getValue(3))};
1125   }
1126   for (const Arg *arg : args.filtered(OPT_rename_segment)) {
1127     config->segmentRenameMap[validName(arg->getValue(0))] =
1128         validName(arg->getValue(1));
1129   }
1130 
1131   config->sectionAlignments = parseSectAlign(args);
1132 
1133   for (const Arg *arg : args.filtered(OPT_segprot)) {
1134     StringRef segName = arg->getValue(0);
1135     uint32_t maxProt = parseProtection(arg->getValue(1));
1136     uint32_t initProt = parseProtection(arg->getValue(2));
1137     if (maxProt != initProt && config->arch() != AK_i386)
1138       error("invalid argument '" + arg->getAsString(args) +
1139             "': max and init must be the same for non-i386 archs");
1140     if (segName == segment_names::linkEdit)
1141       error("-segprot cannot be used to change __LINKEDIT's protections");
1142     config->segmentProtections.push_back({segName, maxProt, initProt});
1143   }
1144 
1145   handleSymbolPatterns(args, config->exportedSymbols, OPT_exported_symbol,
1146                        OPT_exported_symbols_list);
1147   handleSymbolPatterns(args, config->unexportedSymbols, OPT_unexported_symbol,
1148                        OPT_unexported_symbols_list);
1149   if (!config->exportedSymbols.empty() && !config->unexportedSymbols.empty()) {
1150     error("cannot use both -exported_symbol* and -unexported_symbol* options\n"
1151           ">>> ignoring unexports");
1152     config->unexportedSymbols.clear();
1153   }
1154   // Explicitly-exported literal symbols must be defined, but might
1155   // languish in an archive if unreferenced elsewhere. Light a fire
1156   // under those lazy symbols!
1157   for (const CachedHashStringRef &cachedName : config->exportedSymbols.literals)
1158     symtab->addUndefined(cachedName.val(), /*file=*/nullptr,
1159                          /*isWeakRef=*/false);
1160 
1161   config->saveTemps = args.hasArg(OPT_save_temps);
1162 
1163   config->adhocCodesign = args.hasFlag(
1164       OPT_adhoc_codesign, OPT_no_adhoc_codesign,
1165       (config->arch() == AK_arm64 || config->arch() == AK_arm64e) &&
1166           config->platform() == PlatformKind::macOS);
1167 
1168   if (args.hasArg(OPT_v)) {
1169     message(getLLDVersion());
1170     message(StringRef("Library search paths:") +
1171             (config->librarySearchPaths.empty()
1172                  ? ""
1173                  : "\n\t" + join(config->librarySearchPaths, "\n\t")));
1174     message(StringRef("Framework search paths:") +
1175             (config->frameworkSearchPaths.empty()
1176                  ? ""
1177                  : "\n\t" + join(config->frameworkSearchPaths, "\n\t")));
1178   }
1179 
1180   config->progName = argsArr[0];
1181 
1182   config->timeTraceEnabled = args.hasArg(
1183       OPT_time_trace, OPT_time_trace_granularity_eq, OPT_time_trace_file_eq);
1184   config->timeTraceGranularity =
1185       args::getInteger(args, OPT_time_trace_granularity_eq, 500);
1186 
1187   // Initialize time trace profiler.
1188   if (config->timeTraceEnabled)
1189     timeTraceProfilerInitialize(config->timeTraceGranularity, config->progName);
1190 
1191   {
1192     TimeTraceScope timeScope("ExecuteLinker");
1193 
1194     initLLVM(); // must be run before any call to addFile()
1195     createFiles(args);
1196 
1197     config->isPic = config->outputType == MH_DYLIB ||
1198                     config->outputType == MH_BUNDLE ||
1199                     (config->outputType == MH_EXECUTE &&
1200                      args.hasFlag(OPT_pie, OPT_no_pie, true));
1201 
1202     // Now that all dylibs have been loaded, search for those that should be
1203     // re-exported.
1204     {
1205       auto reexportHandler = [](const Arg *arg,
1206                                 const std::vector<StringRef> &extensions) {
1207         config->hasReexports = true;
1208         StringRef searchName = arg->getValue();
1209         if (!markReexport(searchName, extensions))
1210           error(arg->getSpelling() + " " + searchName +
1211                 " does not match a supplied dylib");
1212       };
1213       std::vector<StringRef> extensions = {".tbd"};
1214       for (const Arg *arg : args.filtered(OPT_sub_umbrella))
1215         reexportHandler(arg, extensions);
1216 
1217       extensions.push_back(".dylib");
1218       for (const Arg *arg : args.filtered(OPT_sub_library))
1219         reexportHandler(arg, extensions);
1220     }
1221 
1222     // Parse LTO options.
1223     if (const Arg *arg = args.getLastArg(OPT_mcpu))
1224       parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
1225                        arg->getSpelling());
1226 
1227     for (const Arg *arg : args.filtered(OPT_mllvm))
1228       parseClangOption(arg->getValue(), arg->getSpelling());
1229 
1230     compileBitcodeFiles();
1231     replaceCommonSymbols();
1232 
1233     StringRef orderFile = args.getLastArgValue(OPT_order_file);
1234     if (!orderFile.empty())
1235       parseOrderFile(orderFile);
1236 
1237     if (config->entry)
1238       if (auto *undefined = dyn_cast<Undefined>(config->entry))
1239         treatUndefinedSymbol(*undefined, "the entry point");
1240 
1241     // FIXME: This prints symbols that are undefined both in input files and
1242     // via -u flag twice.
1243     for (const Symbol *sym : config->explicitUndefineds) {
1244       if (const auto *undefined = dyn_cast<Undefined>(sym))
1245         treatUndefinedSymbol(*undefined, "-u");
1246     }
1247     // Literal exported-symbol names must be defined, but glob
1248     // patterns need not match.
1249     for (const CachedHashStringRef &cachedName :
1250          config->exportedSymbols.literals) {
1251       if (const Symbol *sym = symtab->find(cachedName))
1252         if (const auto *undefined = dyn_cast<Undefined>(sym))
1253           treatUndefinedSymbol(*undefined, "-exported_symbol(s_list)");
1254     }
1255 
1256     // FIXME: should terminate the link early based on errors encountered so
1257     // far?
1258 
1259     createSyntheticSections();
1260     createSyntheticSymbols();
1261 
1262     if (!config->exportedSymbols.empty()) {
1263       for (Symbol *sym : symtab->getSymbols()) {
1264         if (auto *defined = dyn_cast<Defined>(sym)) {
1265           StringRef symbolName = defined->getName();
1266           if (config->exportedSymbols.match(symbolName)) {
1267             if (defined->privateExtern) {
1268               error("cannot export hidden symbol " + symbolName +
1269                     "\n>>> defined in " + toString(defined->getFile()));
1270             }
1271           } else {
1272             defined->privateExtern = true;
1273           }
1274         }
1275       }
1276     } else if (!config->unexportedSymbols.empty()) {
1277       for (Symbol *sym : symtab->getSymbols())
1278         if (auto *defined = dyn_cast<Defined>(sym))
1279           if (config->unexportedSymbols.match(defined->getName()))
1280             defined->privateExtern = true;
1281     }
1282 
1283     for (const Arg *arg : args.filtered(OPT_sectcreate)) {
1284       StringRef segName = arg->getValue(0);
1285       StringRef sectName = arg->getValue(1);
1286       StringRef fileName = arg->getValue(2);
1287       Optional<MemoryBufferRef> buffer = readFile(fileName);
1288       if (buffer)
1289         inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
1290     }
1291 
1292     {
1293       TimeTraceScope timeScope("Gathering input sections");
1294       // Gather all InputSections into one vector.
1295       for (const InputFile *file : inputFiles) {
1296         for (const SubsectionMap &map : file->subsections)
1297           for (const SubsectionEntry &subsectionEntry : map)
1298             inputSections.push_back(subsectionEntry.isec);
1299       }
1300     }
1301 
1302     if (config->deadStrip)
1303       markLive();
1304 
1305     // Write to an output file.
1306     if (target->wordSize == 8)
1307       writeResult<LP64>();
1308     else
1309       writeResult<ILP32>();
1310 
1311     depTracker->write(getLLDVersion(), inputFiles, config->outputFile);
1312   }
1313 
1314   if (config->timeTraceEnabled) {
1315     if (auto E = timeTraceProfilerWrite(
1316             args.getLastArgValue(OPT_time_trace_file_eq).str(),
1317             config->outputFile)) {
1318       handleAllErrors(std::move(E),
1319                       [&](const StringError &SE) { error(SE.getMessage()); });
1320     }
1321 
1322     timeTraceProfilerCleanup();
1323   }
1324 
1325   if (canExitEarly)
1326     exitLld(errorCount() ? 1 : 0);
1327 
1328   return !errorCount();
1329 }
1330