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