• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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/FileSystem.h"
38 #include "llvm/Support/Host.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/Path.h"
41 #include "llvm/Support/TarWriter.h"
42 #include "llvm/Support/TargetSelect.h"
43 
44 #include <algorithm>
45 
46 using namespace llvm;
47 using namespace llvm::MachO;
48 using namespace llvm::object;
49 using namespace llvm::opt;
50 using namespace llvm::sys;
51 using namespace lld;
52 using namespace lld::macho;
53 
54 Configuration *lld::macho::config;
55 
getOutputType(const opt::InputArgList & args)56 static HeaderFileType getOutputType(const opt::InputArgList &args) {
57   // TODO: -r, -dylinker, -preload...
58   opt::Arg *outputArg = args.getLastArg(OPT_bundle, OPT_dylib, OPT_execute);
59   if (outputArg == nullptr)
60     return MH_EXECUTE;
61 
62   switch (outputArg->getOption().getID()) {
63   case OPT_bundle:
64     return MH_BUNDLE;
65   case OPT_dylib:
66     return MH_DYLIB;
67   case OPT_execute:
68     return MH_EXECUTE;
69   default:
70     llvm_unreachable("internal error");
71   }
72 }
73 
74 static Optional<std::string>
findAlongPathsWithExtensions(StringRef name,ArrayRef<StringRef> extensions)75 findAlongPathsWithExtensions(StringRef name, ArrayRef<StringRef> extensions) {
76   llvm::SmallString<261> base;
77   for (StringRef dir : config->librarySearchPaths) {
78     base = dir;
79     path::append(base, Twine("lib") + name);
80     for (StringRef ext : extensions) {
81       Twine location = base + ext;
82       if (fs::exists(location))
83         return location.str();
84     }
85   }
86   return {};
87 }
88 
findLibrary(StringRef name)89 static Optional<std::string> findLibrary(StringRef name) {
90   if (config->searchDylibsFirst) {
91     if (Optional<std::string> path =
92             findAlongPathsWithExtensions(name, {".tbd", ".dylib"}))
93       return path;
94     return findAlongPathsWithExtensions(name, {".a"});
95   }
96   return findAlongPathsWithExtensions(name, {".tbd", ".dylib", ".a"});
97 }
98 
findFramework(StringRef name)99 static Optional<std::string> findFramework(StringRef name) {
100   llvm::SmallString<260> symlink;
101   StringRef suffix;
102   std::tie(name, suffix) = name.split(",");
103   for (StringRef dir : config->frameworkSearchPaths) {
104     symlink = dir;
105     path::append(symlink, name + ".framework", name);
106 
107     if (!suffix.empty()) {
108       // NOTE: we must resolve the symlink before trying the suffixes, because
109       // there are no symlinks for the suffixed paths.
110       llvm::SmallString<260> location;
111       if (!fs::real_path(symlink, location)) {
112         // only append suffix if realpath() succeeds
113         Twine suffixed = location + suffix;
114         if (fs::exists(suffixed))
115           return suffixed.str();
116       }
117       // Suffix lookup failed, fall through to the no-suffix case.
118     }
119 
120     if (Optional<std::string> path = resolveDylibPath(symlink))
121       return path;
122   }
123   return {};
124 }
125 
createTargetInfo(opt::InputArgList & args)126 static TargetInfo *createTargetInfo(opt::InputArgList &args) {
127   StringRef arch = args.getLastArgValue(OPT_arch, "x86_64");
128   config->arch = llvm::MachO::getArchitectureFromName(
129       args.getLastArgValue(OPT_arch, arch));
130   switch (config->arch) {
131   case llvm::MachO::AK_x86_64:
132   case llvm::MachO::AK_x86_64h:
133     return createX86_64TargetInfo();
134   default:
135     fatal("missing or unsupported -arch " + arch);
136   }
137 }
138 
warnIfNotDirectory(StringRef option,StringRef path)139 static bool warnIfNotDirectory(StringRef option, StringRef path) {
140   if (!fs::exists(path)) {
141     warn("directory not found for option -" + option + path);
142     return false;
143   } else if (!fs::is_directory(path)) {
144     warn("option -" + option + path + " references a non-directory path");
145     return false;
146   }
147   return true;
148 }
149 
150 static std::vector<StringRef>
getSearchPaths(unsigned optionCode,opt::InputArgList & args,const std::vector<StringRef> & roots,const SmallVector<StringRef,2> & systemPaths)151 getSearchPaths(unsigned optionCode, opt::InputArgList &args,
152                const std::vector<StringRef> &roots,
153                const SmallVector<StringRef, 2> &systemPaths) {
154   std::vector<StringRef> paths;
155   StringRef optionLetter{optionCode == OPT_F ? "F" : "L"};
156   for (StringRef path : args::getStrings(args, optionCode)) {
157     // NOTE: only absolute paths are re-rooted to syslibroot(s)
158     bool found = false;
159     if (path::is_absolute(path, path::Style::posix)) {
160       for (StringRef root : roots) {
161         SmallString<261> buffer(root);
162         path::append(buffer, path);
163         // Do not warn about paths that are computed via the syslib roots
164         if (fs::is_directory(buffer)) {
165           paths.push_back(saver.save(buffer.str()));
166           found = true;
167         }
168       }
169     }
170     if (!found && warnIfNotDirectory(optionLetter, path))
171       paths.push_back(path);
172   }
173 
174   // `-Z` suppresses the standard "system" search paths.
175   if (args.hasArg(OPT_Z))
176     return paths;
177 
178   for (auto const &path : systemPaths) {
179     for (auto root : roots) {
180       SmallString<261> buffer(root);
181       path::append(buffer, path);
182       if (fs::is_directory(buffer))
183         paths.push_back(saver.save(buffer.str()));
184     }
185   }
186   return paths;
187 }
188 
getSystemLibraryRoots(opt::InputArgList & args)189 static std::vector<StringRef> getSystemLibraryRoots(opt::InputArgList &args) {
190   std::vector<StringRef> roots;
191   for (const Arg *arg : args.filtered(OPT_syslibroot))
192     roots.push_back(arg->getValue());
193   // NOTE: the final `-syslibroot` being `/` will ignore all roots
194   if (roots.size() && roots.back() == "/")
195     roots.clear();
196   // NOTE: roots can never be empty - add an empty root to simplify the library
197   // and framework search path computation.
198   if (roots.empty())
199     roots.emplace_back("");
200   return roots;
201 }
202 
203 static std::vector<StringRef>
getLibrarySearchPaths(opt::InputArgList & args,const std::vector<StringRef> & roots)204 getLibrarySearchPaths(opt::InputArgList &args,
205                       const std::vector<StringRef> &roots) {
206   return getSearchPaths(OPT_L, args, roots, {"/usr/lib", "/usr/local/lib"});
207 }
208 
209 static std::vector<StringRef>
getFrameworkSearchPaths(opt::InputArgList & args,const std::vector<StringRef> & roots)210 getFrameworkSearchPaths(opt::InputArgList &args,
211                         const std::vector<StringRef> &roots) {
212   return getSearchPaths(OPT_F, args, roots,
213                         {"/Library/Frameworks", "/System/Library/Frameworks"});
214 }
215 
216 namespace {
217 struct ArchiveMember {
218   MemoryBufferRef mbref;
219   uint32_t modTime;
220 };
221 } // namespace
222 
223 // Returns slices of MB by parsing MB as an archive file.
224 // Each slice consists of a member file in the archive.
getArchiveMembers(MemoryBufferRef mb)225 static std::vector<ArchiveMember> getArchiveMembers(MemoryBufferRef mb) {
226   std::unique_ptr<Archive> file =
227       CHECK(Archive::create(mb),
228             mb.getBufferIdentifier() + ": failed to parse archive");
229   Archive *archive = file.get();
230   make<std::unique_ptr<Archive>>(std::move(file)); // take ownership
231 
232   std::vector<ArchiveMember> v;
233   Error err = Error::success();
234 
235   // Thin archives refer to .o files, so --reproduces needs the .o files too.
236   bool addToTar = archive->isThin() && tar;
237 
238   for (const Archive::Child &c : archive->children(err)) {
239     MemoryBufferRef mbref =
240         CHECK(c.getMemoryBufferRef(),
241               mb.getBufferIdentifier() +
242                   ": could not get the buffer for a child of the archive");
243     if (addToTar)
244       tar->append(relativeToRoot(check(c.getFullName())), mbref.getBuffer());
245     uint32_t modTime = toTimeT(
246         CHECK(c.getLastModified(), mb.getBufferIdentifier() +
247                                        ": could not get the modification "
248                                        "time for a child of the archive"));
249     v.push_back({mbref, modTime});
250   }
251   if (err)
252     fatal(mb.getBufferIdentifier() +
253           ": Archive::children failed: " + toString(std::move(err)));
254 
255   return v;
256 }
257 
addFile(StringRef path,bool forceLoadArchive)258 static InputFile *addFile(StringRef path, bool forceLoadArchive) {
259   Optional<MemoryBufferRef> buffer = readFile(path);
260   if (!buffer)
261     return nullptr;
262   MemoryBufferRef mbref = *buffer;
263   InputFile *newFile = nullptr;
264 
265   auto magic = identify_magic(mbref.getBuffer());
266   switch (magic) {
267   case file_magic::archive: {
268     std::unique_ptr<object::Archive> file = CHECK(
269         object::Archive::create(mbref), path + ": failed to parse archive");
270 
271     if (!file->isEmpty() && !file->hasSymbolTable())
272       error(path + ": archive has no index; run ranlib to add one");
273 
274     if (config->allLoad || forceLoadArchive) {
275       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
276         for (const ArchiveMember &member : getArchiveMembers(*buffer)) {
277           inputFiles.push_back(
278               make<ObjFile>(member.mbref, member.modTime, path));
279           printArchiveMemberLoad(
280               (forceLoadArchive ? "-force_load" : "-all_load"),
281               inputFiles.back());
282         }
283       }
284     } else if (config->forceLoadObjC) {
285       for (const object::Archive::Symbol &sym : file->symbols())
286         if (sym.getName().startswith(objc::klass))
287           symtab->addUndefined(sym.getName());
288 
289       // TODO: no need to look for ObjC sections for a given archive member if
290       // we already found that it contains an ObjC symbol. We should also
291       // consider creating a LazyObjFile class in order to avoid double-loading
292       // these files here and below (as part of the ArchiveFile).
293       if (Optional<MemoryBufferRef> buffer = readFile(path)) {
294         for (const ArchiveMember &member : getArchiveMembers(*buffer)) {
295           if (hasObjCSection(member.mbref)) {
296             inputFiles.push_back(
297                 make<ObjFile>(member.mbref, member.modTime, path));
298             printArchiveMemberLoad("-ObjC", inputFiles.back());
299           }
300         }
301       }
302     }
303 
304     newFile = make<ArchiveFile>(std::move(file));
305     break;
306   }
307   case file_magic::macho_object:
308     newFile = make<ObjFile>(mbref, getModTime(path), "");
309     break;
310   case file_magic::macho_dynamically_linked_shared_lib:
311   case file_magic::macho_dynamically_linked_shared_lib_stub:
312     newFile = make<DylibFile>(mbref);
313     break;
314   case file_magic::tapi_file: {
315     if (Optional<DylibFile *> dylibFile = makeDylibFromTAPI(mbref))
316       newFile = *dylibFile;
317     break;
318   }
319   case file_magic::bitcode:
320     newFile = make<BitcodeFile>(mbref);
321     break;
322   default:
323     error(path + ": unhandled file type");
324   }
325   if (newFile) {
326     // printArchiveMemberLoad() prints both .a and .o names, so no need to
327     // print the .a name here.
328     if (config->printEachFile && magic != file_magic::archive)
329       lld::outs() << toString(newFile) << '\n';
330     inputFiles.push_back(newFile);
331   }
332   return newFile;
333 }
334 
addLibrary(StringRef name,bool isWeak)335 static void addLibrary(StringRef name, bool isWeak) {
336   if (Optional<std::string> path = findLibrary(name)) {
337     auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false));
338     if (isWeak && dylibFile)
339       dylibFile->forceWeakImport = true;
340     return;
341   }
342   error("library not found for -l" + name);
343 }
344 
addFramework(StringRef name,bool isWeak)345 static void addFramework(StringRef name, bool isWeak) {
346   if (Optional<std::string> path = findFramework(name)) {
347     auto *dylibFile = dyn_cast_or_null<DylibFile>(addFile(*path, false));
348     if (isWeak && dylibFile)
349       dylibFile->forceWeakImport = true;
350     return;
351   }
352   error("framework not found for -framework " + name);
353 }
354 
355 // Parses LC_LINKER_OPTION contents, which can add additional command line flags.
parseLCLinkerOption(InputFile * f,unsigned argc,StringRef data)356 void macho::parseLCLinkerOption(InputFile* f, unsigned argc, StringRef data) {
357   SmallVector<const char *, 4> argv;
358   size_t offset = 0;
359   for (unsigned i = 0; i < argc && offset < data.size(); ++i) {
360     argv.push_back(data.data() + offset);
361     offset += strlen(data.data() + offset) + 1;
362   }
363   if (argv.size() != argc || offset > data.size())
364     fatal(toString(f) + ": invalid LC_LINKER_OPTION");
365 
366   MachOOptTable table;
367   unsigned missingIndex, missingCount;
368   opt::InputArgList args = table.ParseArgs(argv, missingIndex, missingCount);
369   if (missingCount)
370     fatal(Twine(args.getArgString(missingIndex)) + ": missing argument");
371   for (auto *arg : args.filtered(OPT_UNKNOWN))
372     error("unknown argument: " + arg->getAsString(args));
373 
374   for (auto *arg : args) {
375     switch (arg->getOption().getID()) {
376     case OPT_l:
377       addLibrary(arg->getValue(), false);
378       break;
379     case OPT_framework:
380       addFramework(arg->getValue(), false);
381       break;
382     default:
383       error(arg->getSpelling() + " is not allowed in LC_LINKER_OPTION");
384     }
385   }
386 }
387 
addFileList(StringRef path)388 static void addFileList(StringRef path) {
389   Optional<MemoryBufferRef> buffer = readFile(path);
390   if (!buffer)
391     return;
392   MemoryBufferRef mbref = *buffer;
393   for (StringRef path : args::getLines(mbref))
394     addFile(path, false);
395 }
396 
397 static std::array<StringRef, 6> archNames{"arm",    "arm64", "i386",
398                                           "x86_64", "ppc",   "ppc64"};
isArchString(StringRef s)399 static bool isArchString(StringRef s) {
400   static DenseSet<StringRef> archNamesSet(archNames.begin(), archNames.end());
401   return archNamesSet.find(s) != archNamesSet.end();
402 }
403 
404 // An order file has one entry per line, in the following format:
405 //
406 //   <arch>:<object file>:<symbol name>
407 //
408 // <arch> and <object file> are optional. If not specified, then that entry
409 // matches any symbol of that name.
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 '#'.
parseOrderFile(StringRef path)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 rest : args::getLines(mbref)) {
425     StringRef arch, objectFile, symbol;
426 
427     std::array<StringRef, 3> fields;
428     uint8_t fieldCount = 0;
429     while (rest != "" && fieldCount < 3) {
430       std::pair<StringRef, StringRef> p = getToken(rest, ": \t\n\v\f\r");
431       StringRef tok = p.first;
432       rest = p.second;
433 
434       // Check if we have a comment
435       if (tok == "" || tok[0] == '#')
436         break;
437 
438       fields[fieldCount++] = tok;
439     }
440 
441     switch (fieldCount) {
442     case 3:
443       arch = fields[0];
444       objectFile = fields[1];
445       symbol = fields[2];
446       break;
447     case 2:
448       (isArchString(fields[0]) ? arch : objectFile) = fields[0];
449       symbol = fields[1];
450       break;
451     case 1:
452       symbol = fields[0];
453       break;
454     case 0:
455       break;
456     default:
457       llvm_unreachable("too many fields in order file");
458     }
459 
460     if (!arch.empty()) {
461       if (!isArchString(arch)) {
462         error("invalid arch \"" + arch + "\" in order file: expected one of " +
463               llvm::join(archNames, ", "));
464         continue;
465       }
466 
467       // TODO: Update when we extend support for other archs
468       if (arch != "x86_64")
469         continue;
470     }
471 
472     if (!objectFile.empty() && !objectFile.endswith(".o")) {
473       error("invalid object file name \"" + objectFile +
474             "\" in order file: should end with .o");
475       continue;
476     }
477 
478     if (!symbol.empty()) {
479       SymbolPriorityEntry &entry = config->priorities[symbol];
480       if (!objectFile.empty())
481         entry.objectFiles.insert(std::make_pair(objectFile, priority));
482       else
483         entry.anyObjectFile = std::max(entry.anyObjectFile, priority);
484     }
485 
486     --priority;
487   }
488 }
489 
490 // We expect sub-library names of the form "libfoo", which will match a dylib
491 // with a path of .*/libfoo.{dylib, tbd}.
492 // XXX ld64 seems to ignore the extension entirely when matching sub-libraries;
493 // I'm not sure what the use case for that is.
markSubLibrary(StringRef searchName)494 static bool markSubLibrary(StringRef searchName) {
495   for (InputFile *file : inputFiles) {
496     if (auto *dylibFile = dyn_cast<DylibFile>(file)) {
497       StringRef filename = path::filename(dylibFile->getName());
498       if (filename.consume_front(searchName) &&
499           (filename == ".dylib" || filename == ".tbd")) {
500         dylibFile->reexport = true;
501         return true;
502       }
503     }
504   }
505   return false;
506 }
507 
508 // This function is called on startup. We need this for LTO since
509 // LTO calls LLVM functions to compile bitcode files to native code.
510 // Technically this can be delayed until we read bitcode files, but
511 // we don't bother to do lazily because the initialization is fast.
initLLVM()512 static void initLLVM() {
513   InitializeAllTargets();
514   InitializeAllTargetMCs();
515   InitializeAllAsmPrinters();
516   InitializeAllAsmParsers();
517 }
518 
compileBitcodeFiles()519 static void compileBitcodeFiles() {
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.push_back(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.
replaceCommonSymbols()533 static void replaceCommonSymbols() {
534   for (macho::Symbol *sym : symtab->getSymbols()) {
535     auto *common = dyn_cast<CommonSymbol>(sym);
536     if (common == nullptr)
537       continue;
538 
539     auto *isec = make<InputSection>();
540     isec->file = common->file;
541     isec->name = section_names::common;
542     isec->segname = segment_names::data;
543     isec->align = common->align;
544     // Casting to size_t will truncate large values on 32-bit architectures,
545     // but it's not really worth supporting the linking of 64-bit programs on
546     // 32-bit archs.
547     isec->data = {nullptr, static_cast<size_t>(common->size)};
548     isec->flags = S_ZEROFILL;
549     inputSections.push_back(isec);
550 
551     replaceSymbol<Defined>(sym, sym->getName(), isec, /*value=*/0,
552                            /*isWeakDef=*/false,
553                            /*isExternal=*/true);
554   }
555 }
556 
toLowerDash(char x)557 static inline char toLowerDash(char x) {
558   if (x >= 'A' && x <= 'Z')
559     return x - 'A' + 'a';
560   else if (x == ' ')
561     return '-';
562   return x;
563 }
564 
lowerDash(StringRef s)565 static std::string lowerDash(StringRef s) {
566   return std::string(map_iterator(s.begin(), toLowerDash),
567                      map_iterator(s.end(), toLowerDash));
568 }
569 
handlePlatformVersion(const opt::Arg * arg)570 static void handlePlatformVersion(const opt::Arg *arg) {
571   StringRef platformStr = arg->getValue(0);
572   StringRef minVersionStr = arg->getValue(1);
573   StringRef sdkVersionStr = arg->getValue(2);
574 
575   // TODO(compnerd) see if we can generate this case list via XMACROS
576   config->platform.kind =
577       llvm::StringSwitch<llvm::MachO::PlatformKind>(lowerDash(platformStr))
578           .Cases("macos", "1", llvm::MachO::PlatformKind::macOS)
579           .Cases("ios", "2", llvm::MachO::PlatformKind::iOS)
580           .Cases("tvos", "3", llvm::MachO::PlatformKind::tvOS)
581           .Cases("watchos", "4", llvm::MachO::PlatformKind::watchOS)
582           .Cases("bridgeos", "5", llvm::MachO::PlatformKind::bridgeOS)
583           .Cases("mac-catalyst", "6", llvm::MachO::PlatformKind::macCatalyst)
584           .Cases("ios-simulator", "7", llvm::MachO::PlatformKind::iOSSimulator)
585           .Cases("tvos-simulator", "8",
586                  llvm::MachO::PlatformKind::tvOSSimulator)
587           .Cases("watchos-simulator", "9",
588                  llvm::MachO::PlatformKind::watchOSSimulator)
589           .Default(llvm::MachO::PlatformKind::unknown);
590   if (config->platform.kind == llvm::MachO::PlatformKind::unknown)
591     error(Twine("malformed platform: ") + platformStr);
592   // TODO: check validity of version strings, which varies by platform
593   // NOTE: ld64 accepts version strings with 5 components
594   // llvm::VersionTuple accepts no more than 4 components
595   // Has Apple ever published version strings with 5 components?
596   if (config->platform.minimum.tryParse(minVersionStr))
597     error(Twine("malformed minimum version: ") + minVersionStr);
598   if (config->platform.sdk.tryParse(sdkVersionStr))
599     error(Twine("malformed sdk version: ") + sdkVersionStr);
600 }
601 
warnIfDeprecatedOption(const opt::Option & opt)602 static void warnIfDeprecatedOption(const opt::Option &opt) {
603   if (!opt.getGroup().isValid())
604     return;
605   if (opt.getGroup().getID() == OPT_grp_deprecated) {
606     warn("Option `" + opt.getPrefixedName() + "' is deprecated in ld64:");
607     warn(opt.getHelpText());
608   }
609 }
610 
warnIfUnimplementedOption(const opt::Option & opt)611 static void warnIfUnimplementedOption(const opt::Option &opt) {
612   if (!opt.getGroup().isValid() || !opt.hasFlag(DriverFlag::HelpHidden))
613     return;
614   switch (opt.getGroup().getID()) {
615   case OPT_grp_deprecated:
616     // warn about deprecated options elsewhere
617     break;
618   case OPT_grp_undocumented:
619     warn("Option `" + opt.getPrefixedName() +
620          "' is undocumented. Should lld implement it?");
621     break;
622   case OPT_grp_obsolete:
623     warn("Option `" + opt.getPrefixedName() +
624          "' is obsolete. Please modernize your usage.");
625     break;
626   case OPT_grp_ignored:
627     warn("Option `" + opt.getPrefixedName() + "' is ignored.");
628     break;
629   default:
630     warn("Option `" + opt.getPrefixedName() +
631          "' is not yet implemented. Stay tuned...");
632     break;
633   }
634 }
635 
getReproduceOption(opt::InputArgList & args)636 static const char *getReproduceOption(opt::InputArgList &args) {
637   if (auto *arg = args.getLastArg(OPT_reproduce))
638     return arg->getValue();
639   return getenv("LLD_REPRODUCE");
640 }
641 
isPie(opt::InputArgList & args)642 static bool isPie(opt::InputArgList &args) {
643   if (config->outputType != MH_EXECUTE || args.hasArg(OPT_no_pie))
644     return false;
645 
646   // TODO: add logic here as we support more archs. E.g. i386 should default
647   // to PIE from 10.7, arm64 should always be PIE, etc
648   assert(config->arch == AK_x86_64 || config->arch == AK_x86_64h);
649 
650   if (config->platform.kind == MachO::PlatformKind::macOS &&
651       config->platform.minimum >= VersionTuple(10, 6))
652     return true;
653 
654   return args.hasArg(OPT_pie);
655 }
656 
link(llvm::ArrayRef<const char * > argsArr,bool canExitEarly,raw_ostream & stdoutOS,raw_ostream & stderrOS)657 bool macho::link(llvm::ArrayRef<const char *> argsArr, bool canExitEarly,
658                  raw_ostream &stdoutOS, raw_ostream &stderrOS) {
659   lld::stdoutOS = &stdoutOS;
660   lld::stderrOS = &stderrOS;
661 
662   stderrOS.enable_colors(stderrOS.has_colors());
663   // TODO: Set up error handler properly, e.g. the errorLimitExceededMsg
664 
665   errorHandler().cleanupCallback = []() { freeArena(); };
666 
667   MachOOptTable parser;
668   opt::InputArgList args = parser.parse(argsArr.slice(1));
669 
670   if (args.hasArg(OPT_help_hidden)) {
671     parser.printHelp(argsArr[0], /*showHidden=*/true);
672     return true;
673   } else if (args.hasArg(OPT_help)) {
674     parser.printHelp(argsArr[0], /*showHidden=*/false);
675     return true;
676   }
677 
678   if (const char *path = getReproduceOption(args)) {
679     // Note that --reproduce is a debug option so you can ignore it
680     // if you are trying to understand the whole picture of the code.
681     Expected<std::unique_ptr<TarWriter>> errOrWriter =
682         TarWriter::create(path, path::stem(path));
683     if (errOrWriter) {
684       tar = std::move(*errOrWriter);
685       tar->append("response.txt", createResponseFile(args));
686       tar->append("version.txt", getLLDVersion() + "\n");
687     } else {
688       error("--reproduce: " + toString(errOrWriter.takeError()));
689     }
690   }
691 
692   config = make<Configuration>();
693   symtab = make<SymbolTable>();
694   target = createTargetInfo(args);
695 
696   config->entry = symtab->addUndefined(args.getLastArgValue(OPT_e, "_main"));
697   config->outputFile = args.getLastArgValue(OPT_o, "a.out");
698   config->installName =
699       args.getLastArgValue(OPT_install_name, config->outputFile);
700   config->headerPad = args::getHex(args, OPT_headerpad, /*Default=*/32);
701   config->headerPadMaxInstallNames =
702       args.hasArg(OPT_headerpad_max_install_names);
703   config->printEachFile = args.hasArg(OPT_t);
704   config->printWhyLoad = args.hasArg(OPT_why_load);
705   config->outputType = getOutputType(args);
706   config->runtimePaths = args::getStrings(args, OPT_rpath);
707   config->allLoad = args.hasArg(OPT_all_load);
708   config->forceLoadObjC = args.hasArg(OPT_ObjC);
709   config->demangle = args.hasArg(OPT_demangle);
710 
711   if (const opt::Arg *arg = args.getLastArg(OPT_static, OPT_dynamic))
712     config->staticLink = (arg->getOption().getID() == OPT_static);
713 
714   config->systemLibraryRoots = getSystemLibraryRoots(args);
715   config->librarySearchPaths =
716       getLibrarySearchPaths(args, config->systemLibraryRoots);
717   config->frameworkSearchPaths =
718       getFrameworkSearchPaths(args, config->systemLibraryRoots);
719   if (const opt::Arg *arg =
720           args.getLastArg(OPT_search_paths_first, OPT_search_dylibs_first))
721     config->searchDylibsFirst =
722         (arg && arg->getOption().getID() == OPT_search_dylibs_first);
723 
724   config->saveTemps = args.hasArg(OPT_save_temps);
725 
726   if (args.hasArg(OPT_v)) {
727     message(getLLDVersion());
728     message(StringRef("Library search paths:") +
729             (config->librarySearchPaths.size()
730                  ? "\n\t" + llvm::join(config->librarySearchPaths, "\n\t")
731                  : ""));
732     message(StringRef("Framework search paths:") +
733             (config->frameworkSearchPaths.size()
734                  ? "\n\t" + llvm::join(config->frameworkSearchPaths, "\n\t")
735                  : ""));
736     freeArena();
737     return !errorCount();
738   }
739 
740   for (const auto &arg : args) {
741     const auto &opt = arg->getOption();
742     warnIfDeprecatedOption(opt);
743     warnIfUnimplementedOption(opt);
744     // TODO: are any of these better handled via filtered() or getLastArg()?
745     switch (opt.getID()) {
746     case OPT_INPUT:
747       addFile(arg->getValue(), false);
748       break;
749     case OPT_weak_library: {
750       auto *dylibFile =
751           dyn_cast_or_null<DylibFile>(addFile(arg->getValue(), false));
752       if (dylibFile)
753         dylibFile->forceWeakImport = true;
754       break;
755     }
756     case OPT_filelist:
757       addFileList(arg->getValue());
758       break;
759     case OPT_force_load:
760       addFile(arg->getValue(), true);
761       break;
762     case OPT_l:
763     case OPT_weak_l:
764       addLibrary(arg->getValue(), opt.getID() == OPT_weak_l);
765       break;
766     case OPT_framework:
767     case OPT_weak_framework:
768       addFramework(arg->getValue(), opt.getID() == OPT_weak_framework);
769       break;
770     case OPT_platform_version:
771       handlePlatformVersion(arg);
772       break;
773     default:
774       break;
775     }
776   }
777 
778   config->isPic = config->outputType == MH_DYLIB ||
779                   config->outputType == MH_BUNDLE || isPie(args);
780 
781   // Now that all dylibs have been loaded, search for those that should be
782   // re-exported.
783   for (opt::Arg *arg : args.filtered(OPT_sub_library)) {
784     config->hasReexports = true;
785     StringRef searchName = arg->getValue();
786     if (!markSubLibrary(searchName))
787       error("-sub_library " + searchName + " does not match a supplied dylib");
788   }
789 
790   initLLVM();
791   compileBitcodeFiles();
792   replaceCommonSymbols();
793 
794   StringRef orderFile = args.getLastArgValue(OPT_order_file);
795   if (!orderFile.empty())
796     parseOrderFile(orderFile);
797 
798   if (config->outputType == MH_EXECUTE && isa<Undefined>(config->entry)) {
799     error("undefined symbol: " + toString(*config->entry));
800     return false;
801   }
802 
803   createSyntheticSections();
804   symtab->addDSOHandle(in.header);
805 
806   for (opt::Arg *arg : args.filtered(OPT_sectcreate)) {
807     StringRef segName = arg->getValue(0);
808     StringRef sectName = arg->getValue(1);
809     StringRef fileName = arg->getValue(2);
810     Optional<MemoryBufferRef> buffer = readFile(fileName);
811     if (buffer)
812       inputFiles.push_back(make<OpaqueFile>(*buffer, segName, sectName));
813   }
814 
815   // Initialize InputSections.
816   for (InputFile *file : inputFiles) {
817     for (SubsectionMap &map : file->subsections) {
818       for (auto &p : map) {
819         InputSection *isec = p.second;
820         inputSections.push_back(isec);
821       }
822     }
823   }
824 
825   // Write to an output file.
826   writeResult();
827 
828   if (canExitEarly)
829     exitLld(errorCount() ? 1 : 0);
830 
831   return !errorCount();
832 }
833