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