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