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