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