1 //===- lib/Driver/DarwinLdDriver.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 /// \file
10 ///
11 /// Concrete instance of the Driver for darwin's ld.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #include "lld/Common/Args.h"
16 #include "lld/Common/ErrorHandler.h"
17 #include "lld/Common/LLVM.h"
18 #include "lld/Core/ArchiveLibraryFile.h"
19 #include "lld/Core/Error.h"
20 #include "lld/Core/File.h"
21 #include "lld/Core/Instrumentation.h"
22 #include "lld/Core/LinkingContext.h"
23 #include "lld/Core/Node.h"
24 #include "lld/Core/PassManager.h"
25 #include "lld/Core/Resolver.h"
26 #include "lld/Core/SharedLibraryFile.h"
27 #include "lld/Core/Simple.h"
28 #include "lld/ReaderWriter/MachOLinkingContext.h"
29 #include "llvm/ADT/ArrayRef.h"
30 #include "llvm/ADT/Optional.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/SmallString.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/ADT/Twine.h"
36 #include "llvm/BinaryFormat/MachO.h"
37 #include "llvm/Option/Arg.h"
38 #include "llvm/Option/ArgList.h"
39 #include "llvm/Option/OptTable.h"
40 #include "llvm/Option/Option.h"
41 #include "llvm/Support/Casting.h"
42 #include "llvm/Support/CommandLine.h"
43 #include "llvm/Support/Error.h"
44 #include "llvm/Support/ErrorOr.h"
45 #include "llvm/Support/Format.h"
46 #include "llvm/Support/MathExtras.h"
47 #include "llvm/Support/MemoryBuffer.h"
48 #include "llvm/Support/Path.h"
49 #include "llvm/Support/raw_ostream.h"
50 #include <algorithm>
51 #include <cstdint>
52 #include <memory>
53 #include <string>
54 #include <system_error>
55 #include <utility>
56 #include <vector>
57 
58 using namespace lld;
59 
60 namespace {
61 
62 // Create enum with OPT_xxx values for each option in DarwinLdOptions.td
63 enum {
64   OPT_INVALID = 0,
65 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
66                HELP, META, VALUES)                                             \
67   OPT_##ID,
68 #include "DarwinLdOptions.inc"
69 #undef OPTION
70 };
71 
72 // Create prefix string literals used in DarwinLdOptions.td
73 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
74 #include "DarwinLdOptions.inc"
75 #undef PREFIX
76 
77 // Create table mapping all options defined in DarwinLdOptions.td
78 static const llvm::opt::OptTable::Info InfoTable[] = {
79 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM,  \
80                HELPTEXT, METAVAR, VALUES)                                      \
81   {PREFIX,      NAME,      HELPTEXT,                                           \
82    METAVAR,     OPT_##ID,  llvm::opt::Option::KIND##Class,                     \
83    PARAM,       FLAGS,     OPT_##GROUP,                                        \
84    OPT_##ALIAS, ALIASARGS, VALUES},
85 #include "DarwinLdOptions.inc"
86 #undef OPTION
87 };
88 
89 // Create OptTable class for parsing actual command line arguments
90 class DarwinLdOptTable : public llvm::opt::OptTable {
91 public:
DarwinLdOptTable()92   DarwinLdOptTable() : OptTable(InfoTable) {}
93 };
94 
95 static std::vector<std::unique_ptr<File>>
makeErrorFile(StringRef path,std::error_code ec)96 makeErrorFile(StringRef path, std::error_code ec) {
97   std::vector<std::unique_ptr<File>> result;
98   result.push_back(std::make_unique<ErrorFile>(path, ec));
99   return result;
100 }
101 
102 static std::vector<std::unique_ptr<File>>
parseMemberFiles(std::unique_ptr<File> file)103 parseMemberFiles(std::unique_ptr<File> file) {
104   std::vector<std::unique_ptr<File>> members;
105   if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
106     if (std::error_code ec = archive->parseAllMembers(members))
107       return makeErrorFile(file->path(), ec);
108   } else {
109     members.push_back(std::move(file));
110   }
111   return members;
112 }
113 
loadFile(MachOLinkingContext & ctx,StringRef path,bool wholeArchive,bool upwardDylib)114 std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
115                                             StringRef path, bool wholeArchive,
116                                             bool upwardDylib) {
117   if (ctx.logInputFiles())
118     message(path);
119 
120   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
121   if (std::error_code ec = mbOrErr.getError())
122     return makeErrorFile(path, ec);
123   ErrorOr<std::unique_ptr<File>> fileOrErr =
124       ctx.registry().loadFile(std::move(mbOrErr.get()));
125   if (std::error_code ec = fileOrErr.getError())
126     return makeErrorFile(path, ec);
127   std::unique_ptr<File> &file = fileOrErr.get();
128 
129   // If file is a dylib, inform LinkingContext about it.
130   if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
131     if (std::error_code ec = shl->parse())
132       return makeErrorFile(path, ec);
133     ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
134                       upwardDylib);
135   }
136   if (wholeArchive)
137     return parseMemberFiles(std::move(file));
138   std::vector<std::unique_ptr<File>> files;
139   files.push_back(std::move(file));
140   return files;
141 }
142 
143 } // end anonymous namespace
144 
145 // Test may be running on Windows. Canonicalize the path
146 // separator to '/' to get consistent outputs for tests.
canonicalizePath(StringRef path)147 static std::string canonicalizePath(StringRef path) {
148   char sep = llvm::sys::path::get_separator().front();
149   if (sep != '/') {
150     std::string fixedPath = std::string(path);
151     std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
152     return fixedPath;
153   } else {
154     return std::string(path);
155   }
156 }
157 
addFile(StringRef path,MachOLinkingContext & ctx,bool loadWholeArchive,bool upwardDylib)158 static void addFile(StringRef path, MachOLinkingContext &ctx,
159                     bool loadWholeArchive, bool upwardDylib) {
160   std::vector<std::unique_ptr<File>> files =
161       loadFile(ctx, path, loadWholeArchive, upwardDylib);
162   for (std::unique_ptr<File> &file : files)
163     ctx.getNodes().push_back(std::make_unique<FileNode>(std::move(file)));
164 }
165 
166 // Export lists are one symbol per line.  Blank lines are ignored.
167 // Trailing comments start with #.
parseExportsList(StringRef exportFilePath,MachOLinkingContext & ctx)168 static std::error_code parseExportsList(StringRef exportFilePath,
169                                         MachOLinkingContext &ctx) {
170   // Map in export list file.
171   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
172                                    MemoryBuffer::getFileOrSTDIN(exportFilePath);
173   if (std::error_code ec = mb.getError())
174     return ec;
175   ctx.addInputFileDependency(exportFilePath);
176   StringRef buffer = mb->get()->getBuffer();
177   while (!buffer.empty()) {
178     // Split off each line in the file.
179     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
180     StringRef line = lineAndRest.first;
181     // Ignore trailing # comments.
182     std::pair<StringRef, StringRef> symAndComment = line.split('#');
183     StringRef sym = symAndComment.first.trim();
184     if (!sym.empty())
185       ctx.addExportSymbol(sym);
186     buffer = lineAndRest.second;
187   }
188   return std::error_code();
189 }
190 
191 /// Order files are one symbol per line. Blank lines are ignored.
192 /// Trailing comments start with #. Symbol names can be prefixed with an
193 /// architecture name and/or .o leaf name.  Examples:
194 ///     _foo
195 ///     bar.o:_bar
196 ///     libfrob.a(bar.o):_bar
197 ///     x86_64:_foo64
parseOrderFile(StringRef orderFilePath,MachOLinkingContext & ctx)198 static std::error_code parseOrderFile(StringRef orderFilePath,
199                                       MachOLinkingContext &ctx) {
200   // Map in order file.
201   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
202                                    MemoryBuffer::getFileOrSTDIN(orderFilePath);
203   if (std::error_code ec = mb.getError())
204     return ec;
205   ctx.addInputFileDependency(orderFilePath);
206   StringRef buffer = mb->get()->getBuffer();
207   while (!buffer.empty()) {
208     // Split off each line in the file.
209     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
210     StringRef line = lineAndRest.first;
211     buffer = lineAndRest.second;
212     // Ignore trailing # comments.
213     std::pair<StringRef, StringRef> symAndComment = line.split('#');
214     if (symAndComment.first.empty())
215       continue;
216     StringRef sym = symAndComment.first.trim();
217     if (sym.empty())
218       continue;
219     // Check for prefix.
220     StringRef prefix;
221     std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
222     if (!prefixAndSym.second.empty()) {
223       sym = prefixAndSym.second;
224       prefix = prefixAndSym.first;
225       if (!prefix.endswith(".o") && !prefix.endswith(".o)")) {
226         // If arch name prefix does not match arch being linked, ignore symbol.
227         if (!ctx.archName().equals(prefix))
228           continue;
229         prefix = "";
230       }
231     } else
232      sym = prefixAndSym.first;
233     if (!sym.empty()) {
234       ctx.appendOrderedSymbol(sym, prefix);
235       // llvm::errs() << sym << ", prefix=" << prefix << "\n";
236     }
237   }
238   return std::error_code();
239 }
240 
241 //
242 // There are two variants of the  -filelist option:
243 //
244 //   -filelist <path>
245 // In this variant, the path is to a text file which contains one file path
246 // per line.  There are no comments or trimming of whitespace.
247 //
248 //   -fileList <path>,<dir>
249 // In this variant, the path is to a text file which contains a partial path
250 // per line. The <dir> prefix is prepended to each partial path.
251 //
loadFileList(StringRef fileListPath,MachOLinkingContext & ctx,bool forceLoad)252 static llvm::Error loadFileList(StringRef fileListPath,
253                                 MachOLinkingContext &ctx, bool forceLoad) {
254   // If there is a comma, split off <dir>.
255   std::pair<StringRef, StringRef> opt = fileListPath.split(',');
256   StringRef filePath = opt.first;
257   StringRef dirName = opt.second;
258   ctx.addInputFileDependency(filePath);
259   // Map in file list file.
260   ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
261                                         MemoryBuffer::getFileOrSTDIN(filePath);
262   if (std::error_code ec = mb.getError())
263     return llvm::errorCodeToError(ec);
264   StringRef buffer = mb->get()->getBuffer();
265   while (!buffer.empty()) {
266     // Split off each line in the file.
267     std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
268     StringRef line = lineAndRest.first;
269     StringRef path;
270     if (!dirName.empty()) {
271       // If there is a <dir> then prepend dir to each line.
272       SmallString<256> fullPath;
273       fullPath.assign(dirName);
274       llvm::sys::path::append(fullPath, Twine(line));
275       path = ctx.copy(fullPath.str());
276     } else {
277       // No <dir> use whole line as input file path.
278       path = ctx.copy(line);
279     }
280     if (!ctx.pathExists(path)) {
281       return llvm::make_error<GenericError>(Twine("File not found '")
282                                             + path
283                                             + "'");
284     }
285     if (ctx.testingFileUsage()) {
286       message("Found filelist entry " + canonicalizePath(path));
287     }
288     addFile(path, ctx, forceLoad, false);
289     buffer = lineAndRest.second;
290   }
291   return llvm::Error::success();
292 }
293 
294 /// Parse number assuming it is base 16, but allow 0x prefix.
parseNumberBase16(StringRef numStr,uint64_t & baseAddress)295 static bool parseNumberBase16(StringRef numStr, uint64_t &baseAddress) {
296   if (numStr.startswith_insensitive("0x"))
297     numStr = numStr.drop_front(2);
298   return numStr.getAsInteger(16, baseAddress);
299 }
300 
parseLLVMOptions(const LinkingContext & ctx)301 static void parseLLVMOptions(const LinkingContext &ctx) {
302   // Honor -mllvm
303   if (!ctx.llvmOptions().empty()) {
304     unsigned numArgs = ctx.llvmOptions().size();
305     auto **args = new const char *[numArgs + 2];
306     args[0] = "lld (LLVM option parsing)";
307     for (unsigned i = 0; i != numArgs; ++i)
308       args[i + 1] = ctx.llvmOptions()[i];
309     args[numArgs + 1] = nullptr;
310     llvm::cl::ResetAllOptionOccurrences();
311     llvm::cl::ParseCommandLineOptions(numArgs + 1, args);
312   }
313 }
314 
315 namespace lld {
316 namespace mach_o {
317 
parse(llvm::ArrayRef<const char * > args,MachOLinkingContext & ctx)318 bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
319   // Parse command line options using DarwinLdOptions.td
320   DarwinLdOptTable table;
321   unsigned missingIndex;
322   unsigned missingCount;
323   llvm::opt::InputArgList parsedArgs =
324       table.ParseArgs(args.slice(1), missingIndex, missingCount);
325   if (missingCount) {
326     error("missing arg value for '" +
327           Twine(parsedArgs.getArgString(missingIndex)) + "' expected " +
328           Twine(missingCount) + " argument(s).");
329     return false;
330   }
331 
332   for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
333     warn("ignoring unknown argument: " +
334          Twine(unknownArg->getAsString(parsedArgs)));
335   }
336 
337   errorHandler().verbose = parsedArgs.hasArg(OPT_v);
338   errorHandler().errorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
339 
340   // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
341   llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
342   bool isStaticExecutable = false;
343   if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
344           OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
345     switch (kind->getOption().getID()) {
346     case OPT_dylib:
347       fileType = llvm::MachO::MH_DYLIB;
348       break;
349     case OPT_relocatable:
350       fileType = llvm::MachO::MH_OBJECT;
351       break;
352     case OPT_bundle:
353       fileType = llvm::MachO::MH_BUNDLE;
354       break;
355     case OPT_static:
356       fileType = llvm::MachO::MH_EXECUTE;
357       isStaticExecutable = true;
358       break;
359     case OPT_preload:
360       fileType = llvm::MachO::MH_PRELOAD;
361       break;
362     }
363   }
364 
365   // Handle -arch xxx
366   MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
367   if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
368     arch = MachOLinkingContext::archFromName(archStr->getValue());
369     if (arch == MachOLinkingContext::arch_unknown) {
370       error("unknown arch named '" + Twine(archStr->getValue()) + "'");
371       return false;
372     }
373   }
374   // If no -arch specified, scan input files to find first non-fat .o file.
375   if (arch == MachOLinkingContext::arch_unknown) {
376     for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) {
377       // This is expensive because it opens and maps the file.  But that is
378       // ok because no -arch is rare.
379       if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch))
380         break;
381     }
382     if (arch == MachOLinkingContext::arch_unknown &&
383         !parsedArgs.getLastArg(OPT_test_file_usage)) {
384       // If no -arch and no options at all, print usage message.
385       if (parsedArgs.size() == 0) {
386         table.printHelp(llvm::outs(),
387                         (std::string(args[0]) + " [options] file...").c_str(),
388                         "LLVM Linker", false);
389       } else {
390         error("-arch not specified and could not be inferred");
391       }
392       return false;
393     }
394   }
395 
396   // Handle -macosx_version_min or -ios_version_min
397   MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
398   uint32_t minOSVersion = 0;
399   if (llvm::opt::Arg *minOS =
400           parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
401                                 OPT_ios_simulator_version_min)) {
402     switch (minOS->getOption().getID()) {
403     case OPT_macosx_version_min:
404       os = MachOLinkingContext::OS::macOSX;
405       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
406                                                   minOSVersion)) {
407         error("malformed macosx_version_min value");
408         return false;
409       }
410       break;
411     case OPT_ios_version_min:
412       os = MachOLinkingContext::OS::iOS;
413       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
414                                                   minOSVersion)) {
415         error("malformed ios_version_min value");
416         return false;
417       }
418       break;
419     case OPT_ios_simulator_version_min:
420       os = MachOLinkingContext::OS::iOS_simulator;
421       if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
422                                                   minOSVersion)) {
423         error("malformed ios_simulator_version_min value");
424         return false;
425       }
426       break;
427     }
428   } else {
429     // No min-os version on command line, check environment variables
430   }
431 
432   // Handle export_dynamic
433   // FIXME: Should we warn when this applies to something other than a static
434   // executable or dylib?  Those are the only cases where this has an effect.
435   // Note, this has to come before ctx.configure() so that we get the correct
436   // value for _globalsAreDeadStripRoots.
437   bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
438 
439   // Now that there's enough information parsed in, let the linking context
440   // set up default values.
441   ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
442 
443   // Handle -e xxx
444   if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
445     ctx.setEntrySymbolName(entry->getValue());
446 
447   // Handle -o xxx
448   if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
449     ctx.setOutputPath(outpath->getValue());
450   else
451     ctx.setOutputPath("a.out");
452 
453   // Handle -image_base XXX and -seg1addr XXXX
454   if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
455     uint64_t baseAddress;
456     if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
457       error("image_base expects a hex number");
458       return false;
459     } else if (baseAddress < ctx.pageZeroSize()) {
460       error("image_base overlaps with __PAGEZERO");
461       return false;
462     } else if (baseAddress % ctx.pageSize()) {
463       error("image_base must be a multiple of page size (0x" +
464             llvm::utohexstr(ctx.pageSize()) + ")");
465       return false;
466     }
467 
468     ctx.setBaseAddress(baseAddress);
469   }
470 
471   // Handle -dead_strip
472   if (parsedArgs.getLastArg(OPT_dead_strip))
473     ctx.setDeadStripping(true);
474 
475   bool globalWholeArchive = false;
476   // Handle -all_load
477   if (parsedArgs.getLastArg(OPT_all_load))
478     globalWholeArchive = true;
479 
480   // Handle -install_name
481   if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
482     ctx.setInstallName(installName->getValue());
483   else
484     ctx.setInstallName(ctx.outputPath());
485 
486   // Handle -mark_dead_strippable_dylib
487   if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
488     ctx.setDeadStrippableDylib(true);
489 
490   // Handle -compatibility_version and -current_version
491   if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
492     if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
493       error("-compatibility_version can only be used with -dylib");
494       return false;
495     }
496     uint32_t parsedVers;
497     if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
498       error("-compatibility_version value is malformed");
499       return false;
500     }
501     ctx.setCompatibilityVersion(parsedVers);
502   }
503 
504   if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
505     if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
506       error("-current_version can only be used with -dylib");
507       return false;
508     }
509     uint32_t parsedVers;
510     if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
511       error("-current_version value is malformed");
512       return false;
513     }
514     ctx.setCurrentVersion(parsedVers);
515   }
516 
517   // Handle -bundle_loader
518   if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
519     ctx.setBundleLoader(loader->getValue());
520 
521   // Handle -sectalign segname sectname align
522   for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
523     const char* segName   = alignArg->getValue(0);
524     const char* sectName  = alignArg->getValue(1);
525     const char* alignStr  = alignArg->getValue(2);
526     if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
527       alignStr += 2;
528     unsigned long long alignValue;
529     if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
530       error("-sectalign alignment value '" + Twine(alignStr) +
531             "' not a valid number");
532       return false;
533     }
534     uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
535     if (!llvm::isPowerOf2_64(alignValue)) {
536       std::string Msg;
537       llvm::raw_string_ostream OS(Msg);
538       OS << "alignment for '-sectalign " << segName << " " << sectName
539          << llvm::format(" 0x%llX", alignValue)
540          << "' is not a power of two, using " << llvm::format("0x%08X", align);
541       OS.flush();
542       warn(Msg);
543     }
544     ctx.addSectionAlignment(segName, sectName, align);
545   }
546 
547   // Handle -mllvm
548   for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
549     ctx.appendLLVMOption(llvmArg->getValue());
550   }
551 
552   // Handle -print_atoms
553   if (parsedArgs.getLastArg(OPT_print_atoms))
554     ctx.setPrintAtoms();
555 
556   // Handle -t (trace) option.
557   if (parsedArgs.getLastArg(OPT_t))
558     ctx.setLogInputFiles(true);
559 
560   // Handle -demangle option.
561   if (parsedArgs.getLastArg(OPT_demangle))
562     ctx.setDemangleSymbols(true);
563 
564   // Handle -keep_private_externs
565   if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
566     ctx.setKeepPrivateExterns(true);
567     if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
568       warn("-keep_private_externs only used in -r mode");
569   }
570 
571   // Handle -dependency_info <path> used by Xcode.
572   if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
573     if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
574       warn(ec.message() + ", processing '-dependency_info " +
575            depInfo->getValue());
576 
577   // In -test_file_usage mode, we'll be given an explicit list of paths that
578   // exist. We'll also be expected to print out information about how we located
579   // libraries and so on that the user specified, but not to actually do any
580   // linking.
581   if (parsedArgs.getLastArg(OPT_test_file_usage)) {
582     ctx.setTestingFileUsage();
583 
584     // With paths existing by fiat, linking is not going to end well.
585     ctx.setDoNothing(true);
586 
587     // Only bother looking for an existence override if we're going to use it.
588     for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
589       ctx.addExistingPathForDebug(existingPath->getValue());
590     }
591   }
592 
593   // Register possible input file parsers.
594   if (!ctx.doNothing()) {
595     ctx.registry().addSupportMachOObjects(ctx);
596     ctx.registry().addSupportArchives(ctx.logInputFiles());
597     ctx.registry().addSupportYamlFiles();
598   }
599 
600   // Now construct the set of library search directories, following ld64's
601   // baroque set of accumulated hacks. Mostly, the algorithm constructs
602   //     { syslibroots } x { libpaths }
603   //
604   // Unfortunately, there are numerous exceptions:
605   //   1. Only absolute paths get modified by syslibroot options.
606   //   2. If there is just 1 -syslibroot, system paths not found in it are
607   //      skipped.
608   //   3. If the last -syslibroot is "/", all of them are ignored entirely.
609   //   4. If { syslibroots } x path ==  {}, the original path is kept.
610   std::vector<StringRef> sysLibRoots;
611   for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
612     sysLibRoots.push_back(syslibRoot->getValue());
613   }
614   if (!sysLibRoots.empty()) {
615     // Ignore all if last -syslibroot is "/".
616     if (sysLibRoots.back() != "/")
617       ctx.setSysLibRoots(sysLibRoots);
618   }
619 
620   // Paths specified with -L come first, and are not considered system paths for
621   // the case where there is precisely 1 -syslibroot.
622   for (auto libPath : parsedArgs.filtered(OPT_L)) {
623     ctx.addModifiedSearchDir(libPath->getValue());
624   }
625 
626   // Process -F directories (where to look for frameworks).
627   for (auto fwPath : parsedArgs.filtered(OPT_F)) {
628     ctx.addFrameworkSearchDir(fwPath->getValue());
629   }
630 
631   // -Z suppresses the standard search paths.
632   if (!parsedArgs.hasArg(OPT_Z)) {
633     ctx.addModifiedSearchDir("/usr/lib", true);
634     ctx.addModifiedSearchDir("/usr/local/lib", true);
635     ctx.addFrameworkSearchDir("/Library/Frameworks", true);
636     ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
637   }
638 
639   // Now that we've constructed the final set of search paths, print out those
640   // search paths in verbose mode.
641   if (errorHandler().verbose) {
642     message("Library search paths:");
643     for (auto path : ctx.searchDirs()) {
644       message("    " + path);
645     }
646     message("Framework search paths:");
647     for (auto path : ctx.frameworkDirs()) {
648       message("    " + path);
649     }
650   }
651 
652   // Handle -exported_symbols_list <file>
653   for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
654     if (ctx.exportMode() == MachOLinkingContext::ExportMode::unexported) {
655       error("-exported_symbols_list cannot be combined with "
656             "-unexported_symbol[s_list]");
657       return false;
658     }
659     ctx.setExportMode(MachOLinkingContext::ExportMode::exported);
660     if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
661       error(ec.message() + ", processing '-exported_symbols_list " +
662             expFile->getValue());
663       return false;
664     }
665   }
666 
667   // Handle -exported_symbol <symbol>
668   for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
669     if (ctx.exportMode() == MachOLinkingContext::ExportMode::unexported) {
670       error("-exported_symbol cannot be combined with "
671             "-unexported_symbol[s_list]");
672       return false;
673     }
674     ctx.setExportMode(MachOLinkingContext::ExportMode::exported);
675     ctx.addExportSymbol(symbol->getValue());
676   }
677 
678   // Handle -unexported_symbols_list <file>
679   for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
680     if (ctx.exportMode() == MachOLinkingContext::ExportMode::exported) {
681       error("-unexported_symbols_list cannot be combined with "
682             "-exported_symbol[s_list]");
683       return false;
684     }
685     ctx.setExportMode(MachOLinkingContext::ExportMode::unexported);
686     if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
687       error(ec.message() + ", processing '-unexported_symbols_list " +
688             expFile->getValue());
689       return false;
690     }
691   }
692 
693   // Handle -unexported_symbol <symbol>
694   for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
695     if (ctx.exportMode() == MachOLinkingContext::ExportMode::exported) {
696       error("-unexported_symbol cannot be combined with "
697             "-exported_symbol[s_list]");
698       return false;
699     }
700     ctx.setExportMode(MachOLinkingContext::ExportMode::unexported);
701     ctx.addExportSymbol(symbol->getValue());
702   }
703 
704   // Handle obosolete -multi_module and -single_module
705   if (llvm::opt::Arg *mod =
706           parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
707     if (mod->getOption().getID() == OPT_multi_module)
708       warn("-multi_module is obsolete and being ignored");
709     else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
710       warn("-single_module being ignored. It is only for use when producing a "
711            "dylib");
712   }
713 
714   // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
715   if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
716     error("-objc_gc_compaction is not supported");
717     return false;
718   }
719 
720   if (parsedArgs.getLastArg(OPT_objc_gc)) {
721     error("-objc_gc is not supported");
722     return false;
723   }
724 
725   if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
726     error("-objc_gc_only is not supported");
727     return false;
728   }
729 
730   // Handle -pie or -no_pie
731   if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
732     switch (ctx.outputMachOType()) {
733     case llvm::MachO::MH_EXECUTE:
734       switch (ctx.os()) {
735       case MachOLinkingContext::OS::macOSX:
736         if ((minOSVersion < 0x000A0500) &&
737             (pie->getOption().getID() == OPT_pie)) {
738           error("-pie can only be used when targeting Mac OS X 10.5 or later");
739           return false;
740         }
741         break;
742       case MachOLinkingContext::OS::iOS:
743         if ((minOSVersion < 0x00040200) &&
744             (pie->getOption().getID() == OPT_pie)) {
745           error("-pie can only be used when targeting iOS 4.2 or later");
746           return false;
747         }
748         break;
749       case MachOLinkingContext::OS::iOS_simulator:
750         if (pie->getOption().getID() == OPT_no_pie) {
751           error("iOS simulator programs must be built PIE");
752           return false;
753         }
754         break;
755       case MachOLinkingContext::OS::unknown:
756         break;
757       }
758       ctx.setPIE(pie->getOption().getID() == OPT_pie);
759       break;
760     case llvm::MachO::MH_PRELOAD:
761       break;
762     case llvm::MachO::MH_DYLIB:
763     case llvm::MachO::MH_BUNDLE:
764       warn(pie->getSpelling() +
765            " being ignored. It is only used when linking main executables");
766       break;
767     default:
768       error(pie->getSpelling() +
769             " can only used when linking main executables");
770       return false;
771     }
772   }
773 
774   // Handle -version_load_command or -no_version_load_command
775   {
776     bool flagOn = false;
777     bool flagOff = false;
778     if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
779                                           OPT_no_version_load_command)) {
780       flagOn = arg->getOption().getID() == OPT_version_load_command;
781       flagOff = arg->getOption().getID() == OPT_no_version_load_command;
782     }
783 
784     // default to adding version load command for dynamic code,
785     // static code must opt-in
786     switch (ctx.outputMachOType()) {
787       case llvm::MachO::MH_OBJECT:
788         ctx.setGenerateVersionLoadCommand(false);
789         break;
790       case llvm::MachO::MH_EXECUTE:
791         // dynamic executables default to generating a version load command,
792         // while static executables only generate it if required.
793         if (isStaticExecutable) {
794           if (flagOn)
795             ctx.setGenerateVersionLoadCommand(true);
796         } else {
797           if (!flagOff)
798             ctx.setGenerateVersionLoadCommand(true);
799         }
800         break;
801       case llvm::MachO::MH_PRELOAD:
802       case llvm::MachO::MH_KEXT_BUNDLE:
803         if (flagOn)
804           ctx.setGenerateVersionLoadCommand(true);
805         break;
806       case llvm::MachO::MH_DYLINKER:
807       case llvm::MachO::MH_DYLIB:
808       case llvm::MachO::MH_BUNDLE:
809         if (!flagOff)
810           ctx.setGenerateVersionLoadCommand(true);
811         break;
812       case llvm::MachO::MH_FVMLIB:
813       case llvm::MachO::MH_DYLDLINK:
814       case llvm::MachO::MH_DYLIB_STUB:
815       case llvm::MachO::MH_DSYM:
816         // We don't generate load commands for these file types, even if
817         // forced on.
818         break;
819     }
820   }
821 
822   // Handle -function_starts or -no_function_starts
823   {
824     bool flagOn = false;
825     bool flagOff = false;
826     if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
827                                           OPT_no_function_starts)) {
828       flagOn = arg->getOption().getID() == OPT_function_starts;
829       flagOff = arg->getOption().getID() == OPT_no_function_starts;
830     }
831 
832     // default to adding functions start for dynamic code, static code must
833     // opt-in
834     switch (ctx.outputMachOType()) {
835       case llvm::MachO::MH_OBJECT:
836         ctx.setGenerateFunctionStartsLoadCommand(false);
837         break;
838       case llvm::MachO::MH_EXECUTE:
839         // dynamic executables default to generating a version load command,
840         // while static executables only generate it if required.
841         if (isStaticExecutable) {
842           if (flagOn)
843             ctx.setGenerateFunctionStartsLoadCommand(true);
844         } else {
845           if (!flagOff)
846             ctx.setGenerateFunctionStartsLoadCommand(true);
847         }
848         break;
849       case llvm::MachO::MH_PRELOAD:
850       case llvm::MachO::MH_KEXT_BUNDLE:
851         if (flagOn)
852           ctx.setGenerateFunctionStartsLoadCommand(true);
853         break;
854       case llvm::MachO::MH_DYLINKER:
855       case llvm::MachO::MH_DYLIB:
856       case llvm::MachO::MH_BUNDLE:
857         if (!flagOff)
858           ctx.setGenerateFunctionStartsLoadCommand(true);
859         break;
860       case llvm::MachO::MH_FVMLIB:
861       case llvm::MachO::MH_DYLDLINK:
862       case llvm::MachO::MH_DYLIB_STUB:
863       case llvm::MachO::MH_DSYM:
864         // We don't generate load commands for these file types, even if
865         // forced on.
866         break;
867     }
868   }
869 
870   // Handle -data_in_code_info or -no_data_in_code_info
871   {
872     bool flagOn = false;
873     bool flagOff = false;
874     if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
875                                           OPT_no_data_in_code_info)) {
876       flagOn = arg->getOption().getID() == OPT_data_in_code_info;
877       flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
878     }
879 
880     // default to adding data in code for dynamic code, static code must
881     // opt-in
882     switch (ctx.outputMachOType()) {
883       case llvm::MachO::MH_OBJECT:
884         if (!flagOff)
885           ctx.setGenerateDataInCodeLoadCommand(true);
886         break;
887       case llvm::MachO::MH_EXECUTE:
888         // dynamic executables default to generating a version load command,
889         // while static executables only generate it if required.
890         if (isStaticExecutable) {
891           if (flagOn)
892             ctx.setGenerateDataInCodeLoadCommand(true);
893         } else {
894           if (!flagOff)
895             ctx.setGenerateDataInCodeLoadCommand(true);
896         }
897         break;
898       case llvm::MachO::MH_PRELOAD:
899       case llvm::MachO::MH_KEXT_BUNDLE:
900         if (flagOn)
901           ctx.setGenerateDataInCodeLoadCommand(true);
902         break;
903       case llvm::MachO::MH_DYLINKER:
904       case llvm::MachO::MH_DYLIB:
905       case llvm::MachO::MH_BUNDLE:
906         if (!flagOff)
907           ctx.setGenerateDataInCodeLoadCommand(true);
908         break;
909       case llvm::MachO::MH_FVMLIB:
910       case llvm::MachO::MH_DYLDLINK:
911       case llvm::MachO::MH_DYLIB_STUB:
912       case llvm::MachO::MH_DSYM:
913         // We don't generate load commands for these file types, even if
914         // forced on.
915         break;
916     }
917   }
918 
919   // Handle sdk_version
920   if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
921     uint32_t sdkVersion = 0;
922     if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
923                                                 sdkVersion)) {
924       error("malformed sdkVersion value");
925       return false;
926     }
927     ctx.setSdkVersion(sdkVersion);
928   } else if (ctx.generateVersionLoadCommand()) {
929     // If we don't have an sdk version, but were going to emit a load command
930     // with min_version, then we need to give a warning as we have no sdk
931     // version to put in that command.
932     // FIXME: We need to decide whether to make this an error.
933     warn("-sdk_version is required when emitting min version load command.  "
934          "Setting sdk version to match provided min version");
935     ctx.setSdkVersion(ctx.osMinVersion());
936   }
937 
938   // Handle source_version
939   if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
940     uint64_t version = 0;
941     if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
942                                                 version)) {
943       error("malformed source_version value");
944       return false;
945     }
946     ctx.setSourceVersion(version);
947   }
948 
949   // Handle stack_size
950   if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
951     uint64_t stackSizeVal;
952     if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
953       error("stack_size expects a hex number");
954       return false;
955     }
956     if ((stackSizeVal % ctx.pageSize()) != 0) {
957       error("stack_size must be a multiple of page size (0x" +
958             llvm::utohexstr(ctx.pageSize()) + ")");
959       return false;
960     }
961 
962     ctx.setStackSize(stackSizeVal);
963   }
964 
965   // Handle debug info handling options: -S
966   if (parsedArgs.hasArg(OPT_S))
967     ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
968 
969   // Handle -order_file <file>
970   for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
971     if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
972       error(ec.message() + ", processing '-order_file " + orderFile->getValue()
973             + "'");
974       return false;
975     }
976   }
977 
978   // Handle -flat_namespace.
979   if (llvm::opt::Arg *ns =
980           parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
981     if (ns->getOption().getID() == OPT_flat_namespace)
982       ctx.setUseFlatNamespace(true);
983   }
984 
985   // Handle -undefined
986   if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
987     MachOLinkingContext::UndefinedMode UndefMode;
988     if (StringRef(undef->getValue()).equals("error"))
989       UndefMode = MachOLinkingContext::UndefinedMode::error;
990     else if (StringRef(undef->getValue()).equals("warning"))
991       UndefMode = MachOLinkingContext::UndefinedMode::warning;
992     else if (StringRef(undef->getValue()).equals("suppress"))
993       UndefMode = MachOLinkingContext::UndefinedMode::suppress;
994     else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
995       UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
996     else {
997       error("invalid option to -undefined [ warning | error | suppress | "
998             "dynamic_lookup ]");
999       return false;
1000     }
1001 
1002     if (ctx.useFlatNamespace()) {
1003       // If we're using -flat_namespace then 'warning', 'suppress' and
1004       // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1005       if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1006         UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1007     } else {
1008       // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1009       // illegal. Emit a diagnostic if they've been (mis)used.
1010       if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1011           UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1012         error("can't use -undefined warning or suppress with "
1013               "-twolevel_namespace");
1014         return false;
1015       }
1016     }
1017 
1018     ctx.setUndefinedMode(UndefMode);
1019   }
1020 
1021   // Handle -no_objc_category_merging.
1022   if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1023     ctx.setMergeObjCCategories(false);
1024 
1025   // Handle -rpath <path>
1026   if (parsedArgs.hasArg(OPT_rpath)) {
1027     switch (ctx.outputMachOType()) {
1028       case llvm::MachO::MH_EXECUTE:
1029       case llvm::MachO::MH_DYLIB:
1030       case llvm::MachO::MH_BUNDLE:
1031         if (!ctx.minOS("10.5", "2.0")) {
1032           if (ctx.os() == MachOLinkingContext::OS::macOSX)
1033             error("-rpath can only be used when targeting OS X 10.5 or later");
1034           else
1035             error("-rpath can only be used when targeting iOS 2.0 or later");
1036           return false;
1037         }
1038         break;
1039       default:
1040         error("-rpath can only be used when creating a dynamic final linked "
1041               "image");
1042         return false;
1043     }
1044 
1045     for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1046       ctx.addRpath(rPath->getValue());
1047     }
1048   }
1049 
1050   // Parse the LLVM options before we process files in case the file handling
1051   // makes use of things like LLVM_DEBUG().
1052   parseLLVMOptions(ctx);
1053 
1054   // Handle input files and sectcreate.
1055   for (auto &arg : parsedArgs) {
1056     bool upward;
1057     llvm::Optional<StringRef> resolvedPath;
1058     switch (arg->getOption().getID()) {
1059     default:
1060       continue;
1061     case OPT_INPUT:
1062       addFile(arg->getValue(), ctx, globalWholeArchive, false);
1063       break;
1064     case OPT_upward_library:
1065       addFile(arg->getValue(), ctx, false, true);
1066       break;
1067     case OPT_force_load:
1068       addFile(arg->getValue(), ctx, true, false);
1069       break;
1070     case OPT_l:
1071     case OPT_upward_l:
1072       upward = (arg->getOption().getID() == OPT_upward_l);
1073       resolvedPath = ctx.searchLibrary(arg->getValue());
1074       if (!resolvedPath) {
1075         error("Unable to find library for " + arg->getSpelling() +
1076               arg->getValue());
1077         return false;
1078       } else if (ctx.testingFileUsage()) {
1079         message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1080                 canonicalizePath(resolvedPath.getValue()));
1081       }
1082       addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1083       break;
1084     case OPT_framework:
1085     case OPT_upward_framework:
1086       upward = (arg->getOption().getID() == OPT_upward_framework);
1087       resolvedPath = ctx.findPathForFramework(arg->getValue());
1088       if (!resolvedPath) {
1089         error("Unable to find framework for " + arg->getSpelling() + " " +
1090               arg->getValue());
1091         return false;
1092       } else if (ctx.testingFileUsage()) {
1093         message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1094                 canonicalizePath(resolvedPath.getValue()));
1095       }
1096       addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1097       break;
1098     case OPT_filelist:
1099       if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1100         handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1101           error(EI.message() + ", processing '-filelist " + arg->getValue());
1102         });
1103         return false;
1104       }
1105       break;
1106     case OPT_sectcreate: {
1107         const char* seg  = arg->getValue(0);
1108         const char* sect = arg->getValue(1);
1109         const char* fileName = arg->getValue(2);
1110 
1111         ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1112           MemoryBuffer::getFile(fileName);
1113 
1114         if (!contentOrErr) {
1115           error("can't open -sectcreate file " + Twine(fileName));
1116           return false;
1117         }
1118 
1119         ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1120       }
1121       break;
1122     }
1123   }
1124 
1125   if (ctx.getNodes().empty()) {
1126     error("No input files");
1127     return false;
1128   }
1129 
1130   // Validate the combination of options used.
1131   return ctx.validate();
1132 }
1133 
createFiles(MachOLinkingContext & ctx,bool Implicit)1134 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1135   std::vector<std::unique_ptr<File>> Files;
1136   if (Implicit)
1137     ctx.createImplicitFiles(Files);
1138   else
1139     ctx.createInternalFiles(Files);
1140   for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1141     auto &members = ctx.getNodes();
1142     members.insert(members.begin(), std::make_unique<FileNode>(std::move(*i)));
1143   }
1144 }
1145 
1146 /// This is where the link is actually performed.
link(llvm::ArrayRef<const char * > args,bool CanExitEarly,raw_ostream & StdoutOS,raw_ostream & StderrOS)1147 bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1148           raw_ostream &StdoutOS, raw_ostream &StderrOS) {
1149   lld::stdoutOS = &StdoutOS;
1150   lld::stderrOS = &StderrOS;
1151 
1152   errorHandler().logName = args::getFilenameWithoutExe(args[0]);
1153   errorHandler().errorLimitExceededMsg =
1154       "too many errors emitted, stopping now (use "
1155       "'-error-limit 0' to see all errors)";
1156   errorHandler().exitEarly = CanExitEarly;
1157   StderrOS.enable_colors(StderrOS.has_colors());
1158 
1159   MachOLinkingContext ctx;
1160   if (!parse(args, ctx))
1161     return false;
1162   if (ctx.doNothing())
1163     return true;
1164   if (ctx.getNodes().empty())
1165     return false;
1166 
1167   for (std::unique_ptr<Node> &ie : ctx.getNodes())
1168     if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1169       node->getFile()->parse();
1170 
1171   createFiles(ctx, false /* Implicit */);
1172 
1173   // Give target a chance to add files
1174   createFiles(ctx, true /* Implicit */);
1175 
1176   // Give target a chance to postprocess input files.
1177   // Mach-O uses this chance to move all object files before library files.
1178   ctx.finalizeInputFiles();
1179 
1180   // Do core linking.
1181   ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1182   Resolver resolver(ctx);
1183   if (!resolver.resolve())
1184     return false;
1185   SimpleFile *merged = nullptr;
1186   {
1187     std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1188     merged = mergedFile.get();
1189     auto &members = ctx.getNodes();
1190     members.insert(members.begin(),
1191                    std::make_unique<FileNode>(std::move(mergedFile)));
1192   }
1193   resolveTask.end();
1194 
1195   // Run passes on linked atoms.
1196   ScopedTask passTask(getDefaultDomain(), "Passes");
1197   PassManager pm;
1198   ctx.addPasses(pm);
1199   if (auto ec = pm.runOnFile(*merged)) {
1200     // FIXME: This should be passed to logAllUnhandledErrors but it needs
1201     // to be passed a Twine instead of a string.
1202     lld::errs() << "Failed to run passes on file '" << ctx.outputPath()
1203                 << "': ";
1204     logAllUnhandledErrors(std::move(ec), lld::errs(), std::string());
1205     return false;
1206   }
1207 
1208   passTask.end();
1209 
1210   // Give linked atoms to Writer to generate output file.
1211   ScopedTask writeTask(getDefaultDomain(), "Write");
1212   if (auto ec = ctx.writeFile(*merged)) {
1213     // FIXME: This should be passed to logAllUnhandledErrors but it needs
1214     // to be passed a Twine instead of a string.
1215     lld::errs() << "Failed to write file '" << ctx.outputPath() << "': ";
1216     logAllUnhandledErrors(std::move(ec), lld::errs(), std::string());
1217     return false;
1218   }
1219 
1220   // Call exit() if we can to avoid calling destructors.
1221   if (CanExitEarly)
1222     exitLld(errorCount() ? 1 : 0);
1223 
1224 
1225   return true;
1226 }
1227 
1228 } // end namespace mach_o
1229 } // end namespace lld
1230