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