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