1 //===- lib/Driver/DarwinLdDriver.cpp --------------------------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
12 /// Concrete instance of the Driver for darwin's ld.
14 //===----------------------------------------------------------------------===//
16 #include "lld/Common/Args.h"
17 #include "lld/Common/ErrorHandler.h"
18 #include "lld/Common/LLVM.h"
19 #include "lld/Core/ArchiveLibraryFile.h"
20 #include "lld/Core/Error.h"
21 #include "lld/Core/File.h"
22 #include "lld/Core/Instrumentation.h"
23 #include "lld/Core/LinkingContext.h"
24 #include "lld/Core/Node.h"
25 #include "lld/Core/PassManager.h"
26 #include "lld/Core/Resolver.h"
27 #include "lld/Core/SharedLibraryFile.h"
28 #include "lld/Core/Simple.h"
29 #include "lld/ReaderWriter/MachOLinkingContext.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallString.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/ADT/Twine.h"
37 #include "llvm/BinaryFormat/MachO.h"
38 #include "llvm/Option/Arg.h"
39 #include "llvm/Option/ArgList.h"
40 #include "llvm/Option/OptTable.h"
41 #include "llvm/Option/Option.h"
42 #include "llvm/Support/Casting.h"
43 #include "llvm/Support/CommandLine.h"
44 #include "llvm/Support/Error.h"
45 #include "llvm/Support/ErrorOr.h"
46 #include "llvm/Support/Format.h"
47 #include "llvm/Support/MathExtras.h"
48 #include "llvm/Support/MemoryBuffer.h"
49 #include "llvm/Support/Path.h"
50 #include "llvm/Support/raw_ostream.h"
55 #include <system_error>
63 // Create enum with OPT_xxx values for each option in DarwinLdOptions.td
66 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
69 #include "DarwinLdOptions.inc"
73 // Create prefix string literals used in DarwinLdOptions.td
74 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
75 #include "DarwinLdOptions.inc"
78 // Create table mapping all options defined in DarwinLdOptions.td
79 static const llvm::opt::OptTable::Info InfoTable[] = {
80 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
81 HELPTEXT, METAVAR, VALUES) \
82 {PREFIX, NAME, HELPTEXT, \
83 METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
84 PARAM, FLAGS, OPT_##GROUP, \
85 OPT_##ALIAS, ALIASARGS, VALUES},
86 #include "DarwinLdOptions.inc"
90 // Create OptTable class for parsing actual command line arguments
91 class DarwinLdOptTable : public llvm::opt::OptTable {
93 DarwinLdOptTable() : OptTable(InfoTable) {}
96 static std::vector<std::unique_ptr<File>>
97 makeErrorFile(StringRef path, std::error_code ec) {
98 std::vector<std::unique_ptr<File>> result;
99 result.push_back(llvm::make_unique<ErrorFile>(path, ec));
103 static std::vector<std::unique_ptr<File>>
104 parseMemberFiles(std::unique_ptr<File> file) {
105 std::vector<std::unique_ptr<File>> members;
106 if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
107 if (std::error_code ec = archive->parseAllMembers(members))
108 return makeErrorFile(file->path(), ec);
110 members.push_back(std::move(file));
115 std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
116 StringRef path, bool wholeArchive,
118 if (ctx.logInputFiles())
121 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
122 if (std::error_code ec = mbOrErr.getError())
123 return makeErrorFile(path, ec);
124 ErrorOr<std::unique_ptr<File>> fileOrErr =
125 ctx.registry().loadFile(std::move(mbOrErr.get()));
126 if (std::error_code ec = fileOrErr.getError())
127 return makeErrorFile(path, ec);
128 std::unique_ptr<File> &file = fileOrErr.get();
130 // If file is a dylib, inform LinkingContext about it.
131 if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
132 if (std::error_code ec = shl->parse())
133 return makeErrorFile(path, ec);
134 ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
138 return parseMemberFiles(std::move(file));
139 std::vector<std::unique_ptr<File>> files;
140 files.push_back(std::move(file));
144 } // end anonymous namespace
146 // Test may be running on Windows. Canonicalize the path
147 // separator to '/' to get consistent outputs for tests.
148 static std::string canonicalizePath(StringRef path) {
149 char sep = llvm::sys::path::get_separator().front();
151 std::string fixedPath = path;
152 std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
159 static void addFile(StringRef path, MachOLinkingContext &ctx,
160 bool loadWholeArchive, bool upwardDylib) {
161 std::vector<std::unique_ptr<File>> files =
162 loadFile(ctx, path, loadWholeArchive, upwardDylib);
163 for (std::unique_ptr<File> &file : files)
164 ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
167 // Export lists are one symbol per line. Blank lines are ignored.
168 // Trailing comments start with #.
169 static std::error_code parseExportsList(StringRef exportFilePath,
170 MachOLinkingContext &ctx) {
171 // Map in export list file.
172 ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
173 MemoryBuffer::getFileOrSTDIN(exportFilePath);
174 if (std::error_code ec = mb.getError())
176 ctx.addInputFileDependency(exportFilePath);
177 StringRef buffer = mb->get()->getBuffer();
178 while (!buffer.empty()) {
179 // Split off each line in the file.
180 std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
181 StringRef line = lineAndRest.first;
182 // Ignore trailing # comments.
183 std::pair<StringRef, StringRef> symAndComment = line.split('#');
184 StringRef sym = symAndComment.first.trim();
186 ctx.addExportSymbol(sym);
187 buffer = lineAndRest.second;
189 return std::error_code();
192 /// Order files are one symbol per line. Blank lines are ignored.
193 /// Trailing comments start with #. Symbol names can be prefixed with an
194 /// architecture name and/or .o leaf name. Examples:
197 /// libfrob.a(bar.o):_bar
199 static std::error_code parseOrderFile(StringRef orderFilePath,
200 MachOLinkingContext &ctx) {
201 // Map in order file.
202 ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
203 MemoryBuffer::getFileOrSTDIN(orderFilePath);
204 if (std::error_code ec = mb.getError())
206 ctx.addInputFileDependency(orderFilePath);
207 StringRef buffer = mb->get()->getBuffer();
208 while (!buffer.empty()) {
209 // Split off each line in the file.
210 std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
211 StringRef line = lineAndRest.first;
212 buffer = lineAndRest.second;
213 // Ignore trailing # comments.
214 std::pair<StringRef, StringRef> symAndComment = line.split('#');
215 if (symAndComment.first.empty())
217 StringRef sym = symAndComment.first.trim();
222 std::pair<StringRef, StringRef> prefixAndSym = sym.split(':');
223 if (!prefixAndSym.second.empty()) {
224 sym = prefixAndSym.second;
225 prefix = prefixAndSym.first;
226 if (!prefix.endswith(".o") && !prefix.endswith(".o)")) {
227 // If arch name prefix does not match arch being linked, ignore symbol.
228 if (!ctx.archName().equals(prefix))
233 sym = prefixAndSym.first;
235 ctx.appendOrderedSymbol(sym, prefix);
236 //llvm::errs() << sym << ", prefix=" << prefix << "\n";
239 return std::error_code();
243 // There are two variants of the -filelist option:
246 // In this variant, the path is to a text file which contains one file path
247 // per line. There are no comments or trimming of whitespace.
249 // -fileList <path>,<dir>
250 // In this variant, the path is to a text file which contains a partial path
251 // per line. The <dir> prefix is prepended to each partial path.
253 static llvm::Error loadFileList(StringRef fileListPath,
254 MachOLinkingContext &ctx, bool forceLoad) {
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;
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());
278 // No <dir> use whole line as input file path.
279 path = ctx.copy(line);
281 if (!ctx.pathExists(path)) {
282 return llvm::make_error<GenericError>(Twine("File not found '")
286 if (ctx.testingFileUsage()) {
287 message("Found filelist entry " + canonicalizePath(path));
289 addFile(path, ctx, forceLoad, false);
290 buffer = lineAndRest.second;
292 return llvm::Error::success();
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);
302 static void parseLLVMOptions(const LinkingContext &ctx) {
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);
318 bool parse(llvm::ArrayRef<const char *> args, MachOLinkingContext &ctx) {
319 // Parse command line options using DarwinLdOptions.td
320 DarwinLdOptTable table;
321 unsigned missingIndex;
322 unsigned missingCount;
323 llvm::opt::InputArgList parsedArgs =
324 table.ParseArgs(args.slice(1), missingIndex, missingCount);
326 error("missing arg value for '" +
327 Twine(parsedArgs.getArgString(missingIndex)) + "' expected " +
328 Twine(missingCount) + " argument(s).");
332 for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
333 warn("ignoring unknown argument: " +
334 Twine(unknownArg->getAsString(parsedArgs)));
337 errorHandler().Verbose = parsedArgs.hasArg(OPT_v);
338 errorHandler().ErrorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
340 // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
341 llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
342 bool isStaticExecutable = false;
343 if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
344 OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
345 switch (kind->getOption().getID()) {
347 fileType = llvm::MachO::MH_DYLIB;
349 case OPT_relocatable:
350 fileType = llvm::MachO::MH_OBJECT;
353 fileType = llvm::MachO::MH_BUNDLE;
356 fileType = llvm::MachO::MH_EXECUTE;
357 isStaticExecutable = true;
360 fileType = llvm::MachO::MH_PRELOAD;
366 MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
367 if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
368 arch = MachOLinkingContext::archFromName(archStr->getValue());
369 if (arch == MachOLinkingContext::arch_unknown) {
370 error("unknown arch named '" + Twine(archStr->getValue()) + "'");
374 // If no -arch specified, scan input files to find first non-fat .o file.
375 if (arch == MachOLinkingContext::arch_unknown) {
376 for (auto &inFile : parsedArgs.filtered(OPT_INPUT)) {
377 // This is expensive because it opens and maps the file. But that is
378 // ok because no -arch is rare.
379 if (MachOLinkingContext::isThinObjectFile(inFile->getValue(), arch))
382 if (arch == MachOLinkingContext::arch_unknown &&
383 !parsedArgs.getLastArg(OPT_test_file_usage)) {
384 // If no -arch and no options at all, print usage message.
385 if (parsedArgs.size() == 0) {
386 table.PrintHelp(llvm::outs(),
387 (std::string(args[0]) + " [options] file...").c_str(),
388 "LLVM Linker", false);
390 error("-arch not specified and could not be inferred");
396 // Handle -macosx_version_min or -ios_version_min
397 MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
398 uint32_t minOSVersion = 0;
399 if (llvm::opt::Arg *minOS =
400 parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
401 OPT_ios_simulator_version_min)) {
402 switch (minOS->getOption().getID()) {
403 case OPT_macosx_version_min:
404 os = MachOLinkingContext::OS::macOSX;
405 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
407 error("malformed macosx_version_min value");
411 case OPT_ios_version_min:
412 os = MachOLinkingContext::OS::iOS;
413 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
415 error("malformed ios_version_min value");
419 case OPT_ios_simulator_version_min:
420 os = MachOLinkingContext::OS::iOS_simulator;
421 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
423 error("malformed ios_simulator_version_min value");
429 // No min-os version on command line, check environment variables
432 // Handle export_dynamic
433 // FIXME: Should we warn when this applies to something other than a static
434 // executable or dylib? Those are the only cases where this has an effect.
435 // Note, this has to come before ctx.configure() so that we get the correct
436 // value for _globalsAreDeadStripRoots.
437 bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
439 // Now that there's enough information parsed in, let the linking context
440 // set up default values.
441 ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
444 if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
445 ctx.setEntrySymbolName(entry->getValue());
448 if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
449 ctx.setOutputPath(outpath->getValue());
451 ctx.setOutputPath("a.out");
453 // Handle -image_base XXX and -seg1addr XXXX
454 if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
455 uint64_t baseAddress;
456 if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
457 error("image_base expects a hex number");
459 } else if (baseAddress < ctx.pageZeroSize()) {
460 error("image_base overlaps with __PAGEZERO");
462 } else if (baseAddress % ctx.pageSize()) {
463 error("image_base must be a multiple of page size (0x" +
464 llvm::utohexstr(ctx.pageSize()) + ")");
468 ctx.setBaseAddress(baseAddress);
471 // Handle -dead_strip
472 if (parsedArgs.getLastArg(OPT_dead_strip))
473 ctx.setDeadStripping(true);
475 bool globalWholeArchive = false;
477 if (parsedArgs.getLastArg(OPT_all_load))
478 globalWholeArchive = true;
480 // Handle -install_name
481 if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
482 ctx.setInstallName(installName->getValue());
484 ctx.setInstallName(ctx.outputPath());
486 // Handle -mark_dead_strippable_dylib
487 if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
488 ctx.setDeadStrippableDylib(true);
490 // Handle -compatibility_version and -current_version
491 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
492 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
493 error("-compatibility_version can only be used with -dylib");
497 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
498 error("-compatibility_version value is malformed");
501 ctx.setCompatibilityVersion(parsedVers);
504 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
505 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
506 error("-current_version can only be used with -dylib");
510 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
511 error("-current_version value is malformed");
514 ctx.setCurrentVersion(parsedVers);
517 // Handle -bundle_loader
518 if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
519 ctx.setBundleLoader(loader->getValue());
521 // Handle -sectalign segname sectname align
522 for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
523 const char* segName = alignArg->getValue(0);
524 const char* sectName = alignArg->getValue(1);
525 const char* alignStr = alignArg->getValue(2);
526 if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
528 unsigned long long alignValue;
529 if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
530 error("-sectalign alignment value '" + Twine(alignStr) +
531 "' not a valid number");
534 uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
535 if (!llvm::isPowerOf2_64(alignValue)) {
537 llvm::raw_string_ostream OS(Msg);
538 OS << "alignment for '-sectalign " << segName << " " << sectName
539 << llvm::format(" 0x%llX", alignValue)
540 << "' is not a power of two, using " << llvm::format("0x%08X", align);
544 ctx.addSectionAlignment(segName, sectName, align);
548 for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
549 ctx.appendLLVMOption(llvmArg->getValue());
552 // Handle -print_atoms
553 if (parsedArgs.getLastArg(OPT_print_atoms))
556 // Handle -t (trace) option.
557 if (parsedArgs.getLastArg(OPT_t))
558 ctx.setLogInputFiles(true);
560 // Handle -demangle option.
561 if (parsedArgs.getLastArg(OPT_demangle))
562 ctx.setDemangleSymbols(true);
564 // Handle -keep_private_externs
565 if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
566 ctx.setKeepPrivateExterns(true);
567 if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
568 warn("-keep_private_externs only used in -r mode");
571 // Handle -dependency_info <path> used by Xcode.
572 if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
573 if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
574 warn(ec.message() + ", processing '-dependency_info " +
575 depInfo->getValue());
577 // In -test_file_usage mode, we'll be given an explicit list of paths that
578 // exist. We'll also be expected to print out information about how we located
579 // libraries and so on that the user specified, but not to actually do any
581 if (parsedArgs.getLastArg(OPT_test_file_usage)) {
582 ctx.setTestingFileUsage();
584 // With paths existing by fiat, linking is not going to end well.
585 ctx.setDoNothing(true);
587 // Only bother looking for an existence override if we're going to use it.
588 for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
589 ctx.addExistingPathForDebug(existingPath->getValue());
593 // Register possible input file parsers.
594 if (!ctx.doNothing()) {
595 ctx.registry().addSupportMachOObjects(ctx);
596 ctx.registry().addSupportArchives(ctx.logInputFiles());
597 ctx.registry().addSupportYamlFiles();
600 // Now construct the set of library search directories, following ld64's
601 // baroque set of accumulated hacks. Mostly, the algorithm constructs
602 // { syslibroots } x { libpaths }
604 // Unfortunately, there are numerous exceptions:
605 // 1. Only absolute paths get modified by syslibroot options.
606 // 2. If there is just 1 -syslibroot, system paths not found in it are
608 // 3. If the last -syslibroot is "/", all of them are ignored entirely.
609 // 4. If { syslibroots } x path == {}, the original path is kept.
610 std::vector<StringRef> sysLibRoots;
611 for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
612 sysLibRoots.push_back(syslibRoot->getValue());
614 if (!sysLibRoots.empty()) {
615 // Ignore all if last -syslibroot is "/".
616 if (sysLibRoots.back() != "/")
617 ctx.setSysLibRoots(sysLibRoots);
620 // Paths specified with -L come first, and are not considered system paths for
621 // the case where there is precisely 1 -syslibroot.
622 for (auto libPath : parsedArgs.filtered(OPT_L)) {
623 ctx.addModifiedSearchDir(libPath->getValue());
626 // Process -F directories (where to look for frameworks).
627 for (auto fwPath : parsedArgs.filtered(OPT_F)) {
628 ctx.addFrameworkSearchDir(fwPath->getValue());
631 // -Z suppresses the standard search paths.
632 if (!parsedArgs.hasArg(OPT_Z)) {
633 ctx.addModifiedSearchDir("/usr/lib", true);
634 ctx.addModifiedSearchDir("/usr/local/lib", true);
635 ctx.addFrameworkSearchDir("/Library/Frameworks", true);
636 ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
639 // Now that we've constructed the final set of search paths, print out those
640 // search paths in verbose mode.
641 if (errorHandler().Verbose) {
642 message("Library search paths:");
643 for (auto path : ctx.searchDirs()) {
646 message("Framework search paths:");
647 for (auto path : ctx.frameworkDirs()) {
652 // Handle -exported_symbols_list <file>
653 for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
654 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
655 error("-exported_symbols_list cannot be combined with "
656 "-unexported_symbol[s_list]");
659 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
660 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
661 error(ec.message() + ", processing '-exported_symbols_list " +
662 expFile->getValue());
667 // Handle -exported_symbol <symbol>
668 for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
669 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
670 error("-exported_symbol cannot be combined with "
671 "-unexported_symbol[s_list]");
674 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
675 ctx.addExportSymbol(symbol->getValue());
678 // Handle -unexported_symbols_list <file>
679 for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
680 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
681 error("-unexported_symbols_list cannot be combined with "
682 "-exported_symbol[s_list]");
685 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
686 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
687 error(ec.message() + ", processing '-unexported_symbols_list " +
688 expFile->getValue());
693 // Handle -unexported_symbol <symbol>
694 for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
695 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
696 error("-unexported_symbol cannot be combined with "
697 "-exported_symbol[s_list]");
700 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
701 ctx.addExportSymbol(symbol->getValue());
704 // Handle obosolete -multi_module and -single_module
705 if (llvm::opt::Arg *mod =
706 parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
707 if (mod->getOption().getID() == OPT_multi_module)
708 warn("-multi_module is obsolete and being ignored");
709 else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
710 warn("-single_module being ignored. It is only for use when producing a "
714 // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
715 if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
716 error("-objc_gc_compaction is not supported");
720 if (parsedArgs.getLastArg(OPT_objc_gc)) {
721 error("-objc_gc is not supported");
725 if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
726 error("-objc_gc_only is not supported");
730 // Handle -pie or -no_pie
731 if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
732 switch (ctx.outputMachOType()) {
733 case llvm::MachO::MH_EXECUTE:
735 case MachOLinkingContext::OS::macOSX:
736 if ((minOSVersion < 0x000A0500) &&
737 (pie->getOption().getID() == OPT_pie)) {
738 error("-pie can only be used when targeting Mac OS X 10.5 or later");
742 case MachOLinkingContext::OS::iOS:
743 if ((minOSVersion < 0x00040200) &&
744 (pie->getOption().getID() == OPT_pie)) {
745 error("-pie can only be used when targeting iOS 4.2 or later");
749 case MachOLinkingContext::OS::iOS_simulator:
750 if (pie->getOption().getID() == OPT_no_pie) {
751 error("iOS simulator programs must be built PIE");
755 case MachOLinkingContext::OS::unknown:
758 ctx.setPIE(pie->getOption().getID() == OPT_pie);
760 case llvm::MachO::MH_PRELOAD:
762 case llvm::MachO::MH_DYLIB:
763 case llvm::MachO::MH_BUNDLE:
764 warn(pie->getSpelling() +
765 " being ignored. It is only used when linking main executables");
768 error(pie->getSpelling() +
769 " can only used when linking main executables");
774 // Handle -version_load_command or -no_version_load_command
777 bool flagOff = false;
778 if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
779 OPT_no_version_load_command)) {
780 flagOn = arg->getOption().getID() == OPT_version_load_command;
781 flagOff = arg->getOption().getID() == OPT_no_version_load_command;
784 // default to adding version load command for dynamic code,
785 // static code must opt-in
786 switch (ctx.outputMachOType()) {
787 case llvm::MachO::MH_OBJECT:
788 ctx.setGenerateVersionLoadCommand(false);
790 case llvm::MachO::MH_EXECUTE:
791 // dynamic executables default to generating a version load command,
792 // while static exectuables only generate it if required.
793 if (isStaticExecutable) {
795 ctx.setGenerateVersionLoadCommand(true);
798 ctx.setGenerateVersionLoadCommand(true);
801 case llvm::MachO::MH_PRELOAD:
802 case llvm::MachO::MH_KEXT_BUNDLE:
804 ctx.setGenerateVersionLoadCommand(true);
806 case llvm::MachO::MH_DYLINKER:
807 case llvm::MachO::MH_DYLIB:
808 case llvm::MachO::MH_BUNDLE:
810 ctx.setGenerateVersionLoadCommand(true);
812 case llvm::MachO::MH_FVMLIB:
813 case llvm::MachO::MH_DYLDLINK:
814 case llvm::MachO::MH_DYLIB_STUB:
815 case llvm::MachO::MH_DSYM:
816 // We don't generate load commands for these file types, even if
822 // Handle -function_starts or -no_function_starts
825 bool flagOff = false;
826 if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
827 OPT_no_function_starts)) {
828 flagOn = arg->getOption().getID() == OPT_function_starts;
829 flagOff = arg->getOption().getID() == OPT_no_function_starts;
832 // default to adding functions start for dynamic code, static code must
834 switch (ctx.outputMachOType()) {
835 case llvm::MachO::MH_OBJECT:
836 ctx.setGenerateFunctionStartsLoadCommand(false);
838 case llvm::MachO::MH_EXECUTE:
839 // dynamic executables default to generating a version load command,
840 // while static exectuables only generate it if required.
841 if (isStaticExecutable) {
843 ctx.setGenerateFunctionStartsLoadCommand(true);
846 ctx.setGenerateFunctionStartsLoadCommand(true);
849 case llvm::MachO::MH_PRELOAD:
850 case llvm::MachO::MH_KEXT_BUNDLE:
852 ctx.setGenerateFunctionStartsLoadCommand(true);
854 case llvm::MachO::MH_DYLINKER:
855 case llvm::MachO::MH_DYLIB:
856 case llvm::MachO::MH_BUNDLE:
858 ctx.setGenerateFunctionStartsLoadCommand(true);
860 case llvm::MachO::MH_FVMLIB:
861 case llvm::MachO::MH_DYLDLINK:
862 case llvm::MachO::MH_DYLIB_STUB:
863 case llvm::MachO::MH_DSYM:
864 // We don't generate load commands for these file types, even if
870 // Handle -data_in_code_info or -no_data_in_code_info
873 bool flagOff = false;
874 if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
875 OPT_no_data_in_code_info)) {
876 flagOn = arg->getOption().getID() == OPT_data_in_code_info;
877 flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
880 // default to adding data in code for dynamic code, static code must
882 switch (ctx.outputMachOType()) {
883 case llvm::MachO::MH_OBJECT:
885 ctx.setGenerateDataInCodeLoadCommand(true);
887 case llvm::MachO::MH_EXECUTE:
888 // dynamic executables default to generating a version load command,
889 // while static exectuables only generate it if required.
890 if (isStaticExecutable) {
892 ctx.setGenerateDataInCodeLoadCommand(true);
895 ctx.setGenerateDataInCodeLoadCommand(true);
898 case llvm::MachO::MH_PRELOAD:
899 case llvm::MachO::MH_KEXT_BUNDLE:
901 ctx.setGenerateDataInCodeLoadCommand(true);
903 case llvm::MachO::MH_DYLINKER:
904 case llvm::MachO::MH_DYLIB:
905 case llvm::MachO::MH_BUNDLE:
907 ctx.setGenerateDataInCodeLoadCommand(true);
909 case llvm::MachO::MH_FVMLIB:
910 case llvm::MachO::MH_DYLDLINK:
911 case llvm::MachO::MH_DYLIB_STUB:
912 case llvm::MachO::MH_DSYM:
913 // We don't generate load commands for these file types, even if
919 // Handle sdk_version
920 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
921 uint32_t sdkVersion = 0;
922 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
924 error("malformed sdkVersion value");
927 ctx.setSdkVersion(sdkVersion);
928 } else if (ctx.generateVersionLoadCommand()) {
929 // If we don't have an sdk version, but were going to emit a load command
930 // with min_version, then we need to give an warning as we have no sdk
931 // version to put in that command.
932 // FIXME: We need to decide whether to make this an error.
933 warn("-sdk_version is required when emitting min version load command. "
934 "Setting sdk version to match provided min version");
935 ctx.setSdkVersion(ctx.osMinVersion());
938 // Handle source_version
939 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
940 uint64_t version = 0;
941 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
943 error("malformed source_version value");
946 ctx.setSourceVersion(version);
950 if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
951 uint64_t stackSizeVal;
952 if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
953 error("stack_size expects a hex number");
956 if ((stackSizeVal % ctx.pageSize()) != 0) {
957 error("stack_size must be a multiple of page size (0x" +
958 llvm::utohexstr(ctx.pageSize()) + ")");
962 ctx.setStackSize(stackSizeVal);
965 // Handle debug info handling options: -S
966 if (parsedArgs.hasArg(OPT_S))
967 ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
969 // Handle -order_file <file>
970 for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
971 if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
972 error(ec.message() + ", processing '-order_file " + orderFile->getValue()
978 // Handle -flat_namespace.
979 if (llvm::opt::Arg *ns =
980 parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
981 if (ns->getOption().getID() == OPT_flat_namespace)
982 ctx.setUseFlatNamespace(true);
986 if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
987 MachOLinkingContext::UndefinedMode UndefMode;
988 if (StringRef(undef->getValue()).equals("error"))
989 UndefMode = MachOLinkingContext::UndefinedMode::error;
990 else if (StringRef(undef->getValue()).equals("warning"))
991 UndefMode = MachOLinkingContext::UndefinedMode::warning;
992 else if (StringRef(undef->getValue()).equals("suppress"))
993 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
994 else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
995 UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
997 error("invalid option to -undefined [ warning | error | suppress | "
1002 if (ctx.useFlatNamespace()) {
1003 // If we're using -flat_namespace then 'warning', 'suppress' and
1004 // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1005 if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1006 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1008 // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1009 // illegal. Emit a diagnostic if they've been (mis)used.
1010 if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1011 UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1012 error("can't use -undefined warning or suppress with "
1013 "-twolevel_namespace");
1018 ctx.setUndefinedMode(UndefMode);
1021 // Handle -no_objc_category_merging.
1022 if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1023 ctx.setMergeObjCCategories(false);
1025 // Handle -rpath <path>
1026 if (parsedArgs.hasArg(OPT_rpath)) {
1027 switch (ctx.outputMachOType()) {
1028 case llvm::MachO::MH_EXECUTE:
1029 case llvm::MachO::MH_DYLIB:
1030 case llvm::MachO::MH_BUNDLE:
1031 if (!ctx.minOS("10.5", "2.0")) {
1032 if (ctx.os() == MachOLinkingContext::OS::macOSX)
1033 error("-rpath can only be used when targeting OS X 10.5 or later");
1035 error("-rpath can only be used when targeting iOS 2.0 or later");
1040 error("-rpath can only be used when creating a dynamic final linked "
1045 for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1046 ctx.addRpath(rPath->getValue());
1050 // Parse the LLVM options before we process files in case the file handling
1051 // makes use of things like LLVM_DEBUG().
1052 parseLLVMOptions(ctx);
1054 // Handle input files and sectcreate.
1055 for (auto &arg : parsedArgs) {
1057 llvm::Optional<StringRef> resolvedPath;
1058 switch (arg->getOption().getID()) {
1062 addFile(arg->getValue(), ctx, globalWholeArchive, false);
1064 case OPT_upward_library:
1065 addFile(arg->getValue(), ctx, false, true);
1067 case OPT_force_load:
1068 addFile(arg->getValue(), ctx, true, false);
1072 upward = (arg->getOption().getID() == OPT_upward_l);
1073 resolvedPath = ctx.searchLibrary(arg->getValue());
1074 if (!resolvedPath) {
1075 error("Unable to find library for " + arg->getSpelling() +
1078 } else if (ctx.testingFileUsage()) {
1079 message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1080 canonicalizePath(resolvedPath.getValue()));
1082 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1085 case OPT_upward_framework:
1086 upward = (arg->getOption().getID() == OPT_upward_framework);
1087 resolvedPath = ctx.findPathForFramework(arg->getValue());
1088 if (!resolvedPath) {
1089 error("Unable to find framework for " + arg->getSpelling() + " " +
1092 } else if (ctx.testingFileUsage()) {
1093 message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1094 canonicalizePath(resolvedPath.getValue()));
1096 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1099 if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1100 handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1101 error(EI.message() + ", processing '-filelist " + arg->getValue());
1106 case OPT_sectcreate: {
1107 const char* seg = arg->getValue(0);
1108 const char* sect = arg->getValue(1);
1109 const char* fileName = arg->getValue(2);
1111 ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1112 MemoryBuffer::getFile(fileName);
1114 if (!contentOrErr) {
1115 error("can't open -sectcreate file " + Twine(fileName));
1119 ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1125 if (ctx.getNodes().empty()) {
1126 error("No input files");
1130 // Validate the combination of options used.
1131 return ctx.validate();
1134 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1135 std::vector<std::unique_ptr<File>> Files;
1137 ctx.createImplicitFiles(Files);
1139 ctx.createInternalFiles(Files);
1140 for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1141 auto &members = ctx.getNodes();
1142 members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1146 /// This is where the link is actually performed.
1147 bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1148 raw_ostream &Error) {
1149 errorHandler().LogName = args::getFilenameWithoutExe(args[0]);
1150 errorHandler().ErrorLimitExceededMsg =
1151 "too many errors emitted, stopping now (use "
1152 "'-error-limit 0' to see all errors)";
1153 errorHandler().ErrorOS = &Error;
1154 errorHandler().ExitEarly = CanExitEarly;
1155 errorHandler().ColorDiagnostics = Error.has_colors();
1157 MachOLinkingContext ctx;
1158 if (!parse(args, ctx))
1160 if (ctx.doNothing())
1162 if (ctx.getNodes().empty())
1165 for (std::unique_ptr<Node> &ie : ctx.getNodes())
1166 if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1167 node->getFile()->parse();
1169 createFiles(ctx, false /* Implicit */);
1171 // Give target a chance to add files
1172 createFiles(ctx, true /* Implicit */);
1174 // Give target a chance to postprocess input files.
1175 // Mach-O uses this chance to move all object files before library files.
1176 ctx.finalizeInputFiles();
1179 ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1180 Resolver resolver(ctx);
1181 if (!resolver.resolve())
1183 SimpleFile *merged = nullptr;
1185 std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1186 merged = mergedFile.get();
1187 auto &members = ctx.getNodes();
1188 members.insert(members.begin(),
1189 llvm::make_unique<FileNode>(std::move(mergedFile)));
1193 // Run passes on linked atoms.
1194 ScopedTask passTask(getDefaultDomain(), "Passes");
1197 if (auto ec = pm.runOnFile(*merged)) {
1198 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1199 // to be passed a Twine instead of a string.
1200 *errorHandler().ErrorOS << "Failed to run passes on file '"
1201 << ctx.outputPath() << "': ";
1202 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1209 // Give linked atoms to Writer to generate output file.
1210 ScopedTask writeTask(getDefaultDomain(), "Write");
1211 if (auto ec = ctx.writeFile(*merged)) {
1212 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1213 // to be passed a Twine instead of a string.
1214 *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath()
1216 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1221 // Call exit() if we can to avoid calling destructors.
1223 exitLld(errorCount() ? 1 : 0);
1229 } // end namespace mach_o
1230 } // end namespace lld