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