xref: /llvm-project-15.0.7/lld/MachO/Driver.cpp (revision c6a96df3)
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 opt::InputArgList &args) {
59   // TODO: -r, -dylinker, -preload...
60   opt::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 TargetInfo *createTargetInfo(opt::InputArgList &args) {
129   // TODO: should unspecified arch be an error rather than defaulting?
130   // Jez: ld64 seems to make unspecified arch an error when LTO is
131   // being used. I'm not sure why though. Feels like we should be able
132   // to infer the arch from our input files regardless
133   StringRef archName = args.getLastArgValue(OPT_arch, "x86_64");
134   config->arch = MachO::getArchitectureFromName(archName);
135   switch (MachO::getCPUTypeFromArchitecture(config->arch).first) {
136   case MachO::CPU_TYPE_X86_64:
137     return createX86_64TargetInfo();
138   case MachO::CPU_TYPE_ARM64:
139     return createARM64TargetInfo();
140   default:
141     fatal("missing or unsupported -arch " + archName);
142   }
143 }
144 
145 static bool warnIfNotDirectory(StringRef option, StringRef path) {
146   if (!fs::exists(path)) {
147     warn("directory not found for option -" + option + path);
148     return false;
149   } else if (!fs::is_directory(path)) {
150     warn("option -" + option + path + " references a non-directory path");
151     return false;
152   }
153   return true;
154 }
155 
156 static std::vector<StringRef>
157 getSearchPaths(unsigned optionCode, opt::InputArgList &args,
158                const std::vector<StringRef> &roots,
159                const SmallVector<StringRef, 2> &systemPaths) {
160   std::vector<StringRef> paths;
161   StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
162   for (StringRef path : args::getStrings(args, optionCode)) {
163     // NOTE: only absolute paths are re-rooted to syslibroot(s)
164     bool found = false;
165     if (path::is_absolute(path, path::Style::posix)) {
166       for (StringRef root : roots) {
167         SmallString<261> buffer(root);
168         path::append(buffer, path);
169         // Do not warn about paths that are computed via the syslib roots
170         if (fs::is_directory(buffer)) {
171           paths.push_back(saver.save(buffer.str()));
172           found = true;
173         }
174       }
175     }
176     if (!found && warnIfNotDirectory(optionLetter, path))
177       paths.push_back(path);
178   }
179 
180   // `-Z` suppresses the standard "system" search paths.
181   if (args.hasArg(OPT_Z))
182     return paths;
183 
184   for (auto const &path : systemPaths) {
185     for (auto root : roots) {
186       SmallString<261> buffer(root);
187       path::append(buffer, path);
188       if (fs::is_directory(buffer))
189         paths.push_back(saver.save(buffer.str()));
190     }
191   }
192   return paths;
193 }
194 
195 static std::vector<StringRef> getSystemLibraryRoots(opt::InputArgList &args) {
196   std::vector<StringRef> roots;
197   for (const Arg *arg : args.filtered(OPT_syslibroot))
198     roots.push_back(arg->getValue());
199   // NOTE: the final `-syslibroot` being `/` will ignore all roots
200   if (roots.size() && roots.back() == "/")
201     roots.clear();
202   // NOTE: roots can never be empty - add an empty root to simplify the library
203   // and framework search path computation.
204   if (roots.empty())
205     roots.emplace_back("");
206   return roots;
207 }
208 
209 static std::vector<StringRef>
210 getLibrarySearchPaths(opt::InputArgList &args,
211                       const std::vector<StringRef> &roots) {
212   return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});
213 }
214 
215 static std::vector<StringRef>
216 getFrameworkSearchPaths(opt::InputArgList &args,
217                         const std::vector<StringRef> &roots) {
218   return getSearchPaths(OPT_F, args, roots,
219                         {"/Library/Frameworks", "/System/Library/Frameworks"});
220 }
221 
222 namespace {
223 struct ArchiveMember {
224   MemoryBufferRef mbref;
225   uint32_t modTime;
226 };
227 } // namespace
228 
229 // Returns slices of MB by parsing MB as an archive file.
230 // Each slice consists of a member file in the archive.
231 static std::vector<ArchiveMember> getArchiveMembers(MemoryBufferRef mb) {
232   std::unique_ptr<Archive> file =
233       CHECK(Archive::create(mb),
234             mb.getBufferIdentifier() + ": failed to parse archive");
235   Archive *archive = file.get();
236   make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
237 
238   std::vector<ArchiveMember> v;
239   Error err = Error::success();
240 
241   // Thin archives refer to .o files, so --reproduces needs the .o files too.
242   bool addToTar = archive->isThin() && tar;
243 
244   for (const Archive::Child &c : archive->children(err)) {
245     MemoryBufferRef mbref =
246         CHECK(c.getMemoryBufferRef(),
247               mb.getBufferIdentifier() +
248                   ": could not get the buffer for a child of the archive");
249     if (addToTar)
250       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
251     uint32_t modTime = toTimeT(
252         CHECK(c.getLastModified(), mb.getBufferIdentifier() +
253                                        ": could not get the modification "
254                                        "time for a child of the archive"));
255     v.push_back({mbref, modTime});
256   }
257   if (err)
258     fatal(mb.getBufferIdentifier() +
259           ": Archive::children failed: " + toString(std::move(err)));
260 
261   return v;
262 }
263 
264 static InputFile *addFile(StringRef path, bool forceLoadArchive) {
265   Optional<MemoryBufferRef> buffer = readFile(path);
266   if (!buffer)
267     return nullptr;
268   MemoryBufferRef mbref = *buffer;
269   InputFile *newFile = nullptr;
270 
271   auto magic = identify_magic(mbref.getBuffer());
272   switch (magic) {
273   case file_magic::archive: {
274     std::unique_ptr<object::Archive> file = CHECK(
275         object::Archive::create(mbref), path + ": failed to parse archive");
276 
277     if (!file->isEmpty() && !file->hasSymbolTable())
278       error(path + ": archive has no index; run ranlib to add one");
279 
280     if (config->allLoad || forceLoadArchive) {
281       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
282         for (const ArchiveMember &member : getArchiveMembers(*buffer)) {
283           if (Optional<InputFile *> file = loadArchiveMember(
284                   member.mbref, member.modTime, path, /*objCOnly=*/false)) {
285             inputFiles.insert(*file);
286             printArchiveMemberLoad(
287                 (forceLoadArchive ? "-force_load" : "-all_load"),
288                 inputFiles.back());
289           }
290         }
291       }
292     } else if (config->forceLoadObjC) {
293       for (const object::Archive::Symbol &sym : file->symbols())
294         if (sym.getName().startswith(objc::klass))
295           symtab->addUndefined(sym.getName(), /*file=*/nullptr,
296                                /*isWeakRef=*/false);
297 
298       // TODO: no need to look for ObjC sections for a given archive member if
299       // we already found that it contains an ObjC symbol. We should also
300       // consider creating a LazyObjFile class in order to avoid double-loading
301       // these files here and below (as part of the ArchiveFile).
302       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
303         for (const ArchiveMember &member : getArchiveMembers(*buffer)) {
304           if (Optional<InputFile *> file = loadArchiveMember(
305                   member.mbref, member.modTime, path, /*objCOnly=*/true)) {
306             inputFiles.insert(*file);
307             printArchiveMemberLoad("-ObjC", inputFiles.back());
308           }
309         }
310       }
311     }
312 
313     newFile = make<ArchiveFile>(std::move(file));
314     break;
315   }
316   case file_magic::macho_object:
317     newFile = make<ObjFile>(mbref, getModTime(path), "");
318     break;
319   case file_magic::macho_dynamically_linked_shared_lib:
320   case file_magic::macho_dynamically_linked_shared_lib_stub:
321   case file_magic::tapi_file:
322     if (Optional<DylibFile *> dylibFile = loadDylib(mbref))
323       newFile = *dylibFile;
324     break;
325   case file_magic::bitcode:
326     newFile = make<BitcodeFile>(mbref);
327     break;
328   default:
329     error(path + ": unhandled file type");
330   }
331   if (newFile) {
332     // printArchiveMemberLoad() prints both .a and .o names, so no need to
333     // print the .a name here.
334     if (config->printEachFile && magic != file_magic::archive)
335       message(toString(newFile));
336     inputFiles.insert(newFile);
337   }
338   return newFile;
339 }
340 
341 static void addLibrary(StringRef name, bool isWeak) {
342   if (Optional<std::string> path = findLibrary(name)) {
343     auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false));
344     if (isWeak && dylibFile)
345       dylibFile->forceWeakImport = true;
346     return;
347   }
348   error("library not found for -l" + name);
349 }
350 
351 static void addFramework(StringRef name, bool isWeak) {
352   if (Optional<std::string> path = findFramework(name)) {
353     auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false));
354     if (isWeak && dylibFile)
355       dylibFile->forceWeakImport = true;
356     return;
357   }
358   error("framework not found for -framework " + name);
359 }
360 
361 // Parses LC_LINKER_OPTION contents, which can add additional command line flags.
362 void macho::parseLCLinkerOption(InputFile* f, unsigned argc, StringRef data) {
363   SmallVector<const char *, 4> argv;
364   size_t offset = 0;
365   for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
366     argv.push_back(data.data() + offset);
367     offset += strlen(data.data() + offset) + 1;
368   }
369   if (argv.size() != argc || offset > data.size())
370     fatal(toString(f) + ": invalid LC_LINKER_OPTION");
371 
372   MachOOptTable table;
373   unsigned missingIndex, missingCount;
374   opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
375   if (missingCount)
376     fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
377   for (auto *arg : args.filtered(OPT_UNKNOWN))
378     error("unknown argument: " + arg->getAsString(args));
379 
380   for (auto *arg : args) {
381     switch (arg->getOption().getID()) {
382     case OPT_l:
383       addLibrary(arg->getValue(), false);
384       break;
385     case OPT_framework:
386       addFramework(arg->getValue(), false);
387       break;
388     default:
389       error(arg->getSpelling() + " is not allowed in LC_LINKER_OPTION");
390     }
391   }
392 }
393 
394 static void addFileList(StringRef path) {
395   Optional<MemoryBufferRef> buffer = readFile(path);
396   if (!buffer)
397     return;
398   MemoryBufferRef mbref = *buffer;
399   for (StringRef path : args::getLines(mbref))
400     addFile(path, false);
401 }
402 
403 // An order file has one entry per line, in the following format:
404 //
405 //   <cpu>:<object file>:<symbol name>
406 //
407 // <cpu> and <object file> are optional. If not specified, then that entry
408 // matches any symbol of that name. Parsing this format is not quite
409 // straightforward because the symbol name itself can contain colons, so when
410 // encountering a colon, we consider the preceding characters to decide if it
411 // can be a valid CPU type or file path.
412 //
413 // If a symbol is matched by multiple entries, then it takes the lowest-ordered
414 // entry (the one nearest to the front of the list.)
415 //
416 // The file can also have line comments that start with '#'.
417 static void parseOrderFile(StringRef path) {
418   Optional<MemoryBufferRef> buffer = readFile(path);
419   if (!buffer) {
420     error("Could not read order file at " + path);
421     return;
422   }
423 
424   MemoryBufferRef mbref = *buffer;
425   size_t priority = std::numeric_limits<size_t>::max();
426   for (StringRef line : args::getLines(mbref)) {
427     StringRef objectFile, symbol;
428     line = line.take_until([](char c) { return c == '#'; }); // ignore comments
429     line = line.ltrim();
430 
431     CPUType cpuType = StringSwitch<CPUType>(line)
432                           .StartsWith("i386:", CPU_TYPE_I386)
433                           .StartsWith("x86_64:", CPU_TYPE_X86_64)
434                           .StartsWith("arm:", CPU_TYPE_ARM)
435                           .StartsWith("arm64:", CPU_TYPE_ARM64)
436                           .StartsWith("ppc:", CPU_TYPE_POWERPC)
437                           .StartsWith("ppc64:", CPU_TYPE_POWERPC64)
438                           .Default(CPU_TYPE_ANY);
439     // Drop the CPU type as well as the colon
440     if (cpuType != CPU_TYPE_ANY)
441       line = line.drop_until([](char c) { return c == ':'; }).drop_front();
442     // TODO: Update when we extend support for other CPUs
443     if (cpuType != CPU_TYPE_ANY && cpuType != CPU_TYPE_X86_64 &&
444         cpuType != CPU_TYPE_ARM64)
445       continue;
446 
447     constexpr std::array<StringRef, 2> fileEnds = {".o:", ".o):"};
448     for (StringRef fileEnd : fileEnds) {
449       size_t pos = line.find(fileEnd);
450       if (pos != StringRef::npos) {
451         // Split the string around the colon
452         objectFile = line.take_front(pos + fileEnd.size() - 1);
453         line = line.drop_front(pos + fileEnd.size());
454         break;
455       }
456     }
457     symbol = line.trim();
458 
459     if (!symbol.empty()) {
460       SymbolPriorityEntry &entry = config->priorities[symbol];
461       if (!objectFile.empty())
462         entry.objectFiles.insert(std::make_pair(objectFile, priority));
463       else
464         entry.anyObjectFile = std::max(entry.anyObjectFile, priority);
465     }
466 
467     --priority;
468   }
469 }
470 
471 // We expect sub-library names of the form "libfoo", which will match a dylib
472 // with a path of .*/libfoo.{dylib, tbd}.
473 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
474 // I'm not sure what the use case for that is.
475 static bool markReexport(StringRef searchName, ArrayRef<StringRef> extensions) {
476   for (InputFile *file : inputFiles) {
477     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
478       StringRef filename = path::filename(dylibFile->getName());
479       if (filename.consume_front(searchName) &&
480           (filename.empty() ||
481            find(extensions, filename) != extensions.end())) {
482         dylibFile->reexport = true;
483         return true;
484       }
485     }
486   }
487   return false;
488 }
489 
490 // This function is called on startup. We need this for LTO since
491 // LTO calls LLVM functions to compile bitcode files to native code.
492 // Technically this can be delayed until we read bitcode files, but
493 // we don't bother to do lazily because the initialization is fast.
494 static void initLLVM() {
495   InitializeAllTargets();
496   InitializeAllTargetMCs();
497   InitializeAllAsmPrinters();
498   InitializeAllAsmParsers();
499 }
500 
501 static void compileBitcodeFiles() {
502   auto lto = make<BitcodeCompiler>();
503   for (InputFile *file : inputFiles)
504     if (auto *bitcodeFile = dyn_cast<BitcodeFile>(file))
505       lto->add(*bitcodeFile);
506 
507   for (ObjFile *file : lto->compile())
508     inputFiles.insert(file);
509 }
510 
511 // Replaces common symbols with defined symbols residing in __common sections.
512 // This function must be called after all symbol names are resolved (i.e. after
513 // all InputFiles have been loaded.) As a result, later operations won't see
514 // any CommonSymbols.
515 static void replaceCommonSymbols() {
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 static void handlePlatformVersion(const opt::Arg *arg) {
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   config->platform.kind =
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 (config->platform.kind == 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->platform.minimum.tryParse(minVersionStr))
578     error(Twine("malformed minimum version: ") + minVersionStr);
579   if (config->platform.sdk.tryParse(sdkVersionStr))
580     error(Twine("malformed sdk version: ") + sdkVersionStr);
581 }
582 
583 static void handleUndefined(const opt::Arg *arg) {
584   StringRef treatmentStr = arg->getValue(0);
585   config->undefinedSymbolTreatment =
586       StringSwitch<UndefinedSymbolTreatment>(treatmentStr)
587           .Case("error", UndefinedSymbolTreatment::error)
588           .Case("warning", UndefinedSymbolTreatment::warning)
589           .Case("suppress", UndefinedSymbolTreatment::suppress)
590           .Case("dynamic_lookup", UndefinedSymbolTreatment::dynamic_lookup)
591           .Default(UndefinedSymbolTreatment::unknown);
592   if (config->undefinedSymbolTreatment == UndefinedSymbolTreatment::unknown) {
593     warn(Twine("unknown -undefined TREATMENT '") + treatmentStr +
594          "', defaulting to 'error'");
595     config->undefinedSymbolTreatment = UndefinedSymbolTreatment::error;
596   }
597 }
598 
599 static void warnIfDeprecatedOption(const opt::Option &opt) {
600   if (!opt.getGroup().isValid())
601     return;
602   if (opt.getGroup().getID() == OPT_grp_deprecated) {
603     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
604     warn(opt.getHelpText());
605   }
606 }
607 
608 static void warnIfUnimplementedOption(const opt::Option &opt) {
609   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
610     return;
611   switch (opt.getGroup().getID()) {
612   case OPT_grp_deprecated:
613     // warn about deprecated options elsewhere
614     break;
615   case OPT_grp_undocumented:
616     warn("Option `" + opt.getPrefixedName() +
617          "' is undocumented. Should lld implement it?");
618     break;
619   case OPT_grp_obsolete:
620     warn("Option `" + opt.getPrefixedName() +
621          "' is obsolete. Please modernize your usage.");
622     break;
623   case OPT_grp_ignored:
624     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
625     break;
626   default:
627     warn("Option `" + opt.getPrefixedName() +
628          "' is not yet implemented. Stay tuned...");
629     break;
630   }
631 }
632 
633 static const char *getReproduceOption(opt::InputArgList &args) {
634   if (auto *arg = args.getLastArg(OPT_reproduce))
635     return arg->getValue();
636   return getenv("LLD_REPRODUCE");
637 }
638 
639 static bool isPie(opt::InputArgList &args) {
640   if (config->outputType != MH_EXECUTE || args.hasArg(OPT_no_pie))
641     return false;
642   if (config->arch == AK_arm64 || config->arch == AK_arm64e)
643     return true;
644 
645   // TODO: add logic here as we support more archs. E.g. i386 should default
646   // to PIE from 10.7
647   assert(config->arch == AK_x86_64 || config->arch == AK_x86_64h);
648 
649   PlatformKind kind = config->platform.kind;
650   if (kind == PlatformKind::macOS &&
651       config->platform.minimum >= VersionTuple(10, 6))
652     return true;
653 
654   if (kind == PlatformKind::iOSSimulator || kind == PlatformKind::driverKit)
655     return true;
656 
657   return args.hasArg(OPT_pie);
658 }
659 
660 static void parseClangOption(StringRef opt, const Twine &msg) {
661   std::string err;
662   raw_string_ostream os(err);
663 
664   const char *argv[] = {"lld", opt.data()};
665   if (cl::ParseCommandLineOptions(2, argv, "", &os))
666     return;
667   os.flush();
668   error(msg + ": " + StringRef(err).trim());
669 }
670 
671 static uint32_t parseDylibVersion(const opt::ArgList& args, unsigned id) {
672   const opt::Arg *arg = args.getLastArg(id);
673   if (!arg)
674     return 0;
675 
676   if (config->outputType != MH_DYLIB) {
677     error(arg->getAsString(args) + ": only valid with -dylib");
678     return 0;
679   }
680 
681   PackedVersion version;
682   if (!version.parse32(arg->getValue())) {
683     error(arg->getAsString(args) + ": malformed version");
684     return 0;
685   }
686 
687   return version.rawValue();
688 }
689 
690 bool macho::link(ArrayRef<const char *> argsArr, bool canExitEarly,
691                  raw_ostream &stdoutOS, raw_ostream &stderrOS) {
692   lld::stdoutOS = &stdoutOS;
693   lld::stderrOS = &stderrOS;
694 
695   stderrOS.enable_colors(stderrOS.has_colors());
696   // TODO: Set up error handler properly, e.g. the errorLimitExceededMsg
697 
698   errorHandler().cleanupCallback = []() { freeArena(); };
699 
700   MachOOptTable parser;
701   opt::InputArgList args = parser.parse(argsArr.slice(1));
702 
703   if (args.hasArg(OPT_help_hidden)) {
704     parser.printHelp(argsArr[0], /*showHidden=*/true);
705     return true;
706   }
707   if (args.hasArg(OPT_help)) {
708     parser.printHelp(argsArr[0], /*showHidden=*/false);
709     return true;
710   }
711   if (args.hasArg(OPT_version)) {
712     message(getLLDVersion());
713     return true;
714   }
715 
716   if (const char *path = getReproduceOption(args)) {
717     // Note that --reproduce is a debug option so you can ignore it
718     // if you are trying to understand the whole picture of the code.
719     Expected<std::unique_ptr<TarWriter>> errOrWriter =
720         TarWriter::create(path, path::stem(path));
721     if (errOrWriter) {
722       tar = std::move(*errOrWriter);
723       tar->append("response.txt", createResponseFile(args));
724       tar->append("version.txt", getLLDVersion() + "\n");
725     } else {
726       error("--reproduce: " + toString(errOrWriter.takeError()));
727     }
728   }
729 
730   config = make<Configuration>();
731   symtab = make<SymbolTable>();
732   target = createTargetInfo(args);
733 
734   config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"),
735                                        /*file=*/nullptr,
736                                        /*isWeakRef=*/false);
737   for (auto *arg : args.filtered(OPT_u)) {
738     config->explicitUndefineds.push_back(symtab->addUndefined(
739         arg->getValue(), /*file=*/nullptr, /*isWeakRef=*/false));
740   }
741   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
742   config->installName =
743       args.getLastArgValue(OPT_install_name, config->outputFile);
744   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
745   config->headerPadMaxInstallNames =
746       args.hasArg(OPT_headerpad_max_install_names);
747   config->printEachFile = args.hasArg(OPT_t);
748   config->printWhyLoad = args.hasArg(OPT_why_load);
749   config->outputType = getOutputType(args);
750   config->ltoObjPath = args.getLastArgValue(OPT_object_path_lto);
751   config->ltoNewPassManager =
752       args.hasFlag(OPT_no_lto_legacy_pass_manager, OPT_lto_legacy_pass_manager,
753                    LLVM_ENABLE_NEW_PASS_MANAGER);
754   config->runtimePaths = args::getStrings(args, OPT_rpath);
755   config->allLoad = args.hasArg(OPT_all_load);
756   config->forceLoadObjC = args.hasArg(OPT_ObjC);
757   config->demangle = args.hasArg(OPT_demangle);
758   config->implicitDylibs = !args.hasArg(OPT_no_implicit_dylibs);
759 
760   if (const opt::Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
761     config->staticLink = (arg->getOption().getID() == OPT_static);
762 
763   config->systemLibraryRoots = getSystemLibraryRoots(args);
764   config->librarySearchPaths =
765       getLibrarySearchPaths(args, config->systemLibraryRoots);
766   config->frameworkSearchPaths =
767       getFrameworkSearchPaths(args, config->systemLibraryRoots);
768   if (const opt::Arg *arg =
769           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
770     config->searchDylibsFirst =
771         arg->getOption().getID() == OPT_search_dylibs_first;
772 
773   config->dylibCompatibilityVersion =
774       parseDylibVersion(args, OPT_compatibility_version);
775   config->dylibCurrentVersion = parseDylibVersion(args, OPT_current_version);
776 
777   config->saveTemps = args.hasArg(OPT_save_temps);
778 
779   if (args.hasArg(OPT_v)) {
780     message(getLLDVersion());
781     message(StringRef("Library search paths:") +
782             (config->librarySearchPaths.size()
783                  ? "\n\t" + join(config->librarySearchPaths, "\n\t")
784                  : ""));
785     message(StringRef("Framework search paths:") +
786             (config->frameworkSearchPaths.size()
787                  ? "\n\t" + join(config->frameworkSearchPaths, "\n\t")
788                  : ""));
789     freeArena();
790     return !errorCount();
791   }
792 
793   initLLVM(); // must be run before any call to addFile()
794 
795   for (const auto &arg : args) {
796     const auto &opt = arg->getOption();
797     warnIfDeprecatedOption(opt);
798     warnIfUnimplementedOption(opt);
799     // TODO: are any of these better handled via filtered() or getLastArg()?
800     switch (opt.getID()) {
801     case OPT_INPUT:
802       addFile(arg->getValue(), false);
803       break;
804     case OPT_weak_library:
805       if (auto *dylibFile =
806               dyn_cast_or_null<DylibFile>(addFile(arg->getValue(), false)))
807         dylibFile->forceWeakImport = true;
808       break;
809     case OPT_filelist:
810       addFileList(arg->getValue());
811       break;
812     case OPT_force_load:
813       addFile(arg->getValue(), true);
814       break;
815     case OPT_l:
816     case OPT_weak_l:
817       addLibrary(arg->getValue(), opt.getID() == OPT_weak_l);
818       break;
819     case OPT_framework:
820     case OPT_weak_framework:
821       addFramework(arg->getValue(), opt.getID() == OPT_weak_framework);
822       break;
823     case OPT_platform_version:
824       handlePlatformVersion(arg);
825       break;
826     case OPT_undefined:
827       handleUndefined(arg);
828       break;
829     default:
830       break;
831     }
832   }
833 
834   config->isPic = config->outputType == MH_DYLIB ||
835                   config->outputType == MH_BUNDLE || isPie(args);
836 
837   // Now that all dylibs have been loaded, search for those that should be
838   // re-exported.
839   for (opt::Arg *arg : args.filtered(OPT_sub_library, OPT_sub_umbrella)) {
840     config->hasReexports = true;
841     StringRef searchName = arg->getValue();
842     std::vector<StringRef> extensions;
843     if (arg->getOption().getID() == OPT_sub_library)
844       extensions = {".dylib", ".tbd"};
845     else
846       extensions = {".tbd"};
847     if (!markReexport(searchName, extensions))
848       error(arg->getSpelling() + " " + searchName +
849             " does not match a supplied dylib");
850   }
851 
852   // Parse LTO options.
853   if (auto *arg = args.getLastArg(OPT_mcpu))
854     parseClangOption(saver.save("-mcpu=" + StringRef(arg->getValue())),
855                      arg->getSpelling());
856 
857   for (auto *arg : args.filtered(OPT_mllvm))
858     parseClangOption(arg->getValue(), arg->getSpelling());
859 
860   compileBitcodeFiles();
861   replaceCommonSymbols();
862 
863   StringRef orderFile = args.getLastArgValue(OPT_order_file);
864   if (!orderFile.empty())
865     parseOrderFile(orderFile);
866 
867   if (config->outputType == MH_EXECUTE && isa<Undefined>(config->entry)) {
868     error("undefined symbol: " + toString(*config->entry));
869     return false;
870   }
871   // FIXME: This prints symbols that are undefined both in input files and
872   // via -u flag twice.
873   for (const auto *undefined : config->explicitUndefineds) {
874     if (isa<Undefined>(undefined)) {
875       error("undefined symbol: " + toString(*undefined) +
876             "\n>>> referenced by flag -u " + toString(*undefined));
877       return false;
878     }
879   }
880 
881   createSyntheticSections();
882   symtab->addDSOHandle(in.header);
883 
884   for (opt::Arg *arg : args.filtered(OPT_sectcreate)) {
885     StringRef segName = arg->getValue(0);
886     StringRef sectName = arg->getValue(1);
887     StringRef fileName = arg->getValue(2);
888     Optional<MemoryBufferRef> buffer = readFile(fileName);
889     if (buffer)
890       inputFiles.insert(make<OpaqueFile>(*buffer, segName, sectName));
891   }
892 
893   // Initialize InputSections.
894   for (InputFile *file : inputFiles) {
895     for (SubsectionMap &map : file->subsections) {
896       for (auto &p : map) {
897         InputSection *isec = p.second;
898         inputSections.push_back(isec);
899       }
900     }
901   }
902 
903   // Write to an output file.
904   writeResult();
905 
906   if (canExitEarly)
907     exitLld(errorCount() ? 1 : 0);
908 
909   return !errorCount();
910 }
911