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