1 //===- lib/Driver/DarwinLdDriver.cpp --------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
11 /// Concrete instance of the Driver for darwin's ld.
13 //===----------------------------------------------------------------------===//
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"
54 #include <system_error>
62 // Create enum with OPT_xxx values for each option in DarwinLdOptions.td
65 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
68 #include "DarwinLdOptions.inc"
72 // Create prefix string literals used in DarwinLdOptions.td
73 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
74 #include "DarwinLdOptions.inc"
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"
89 // Create OptTable class for parsing actual command line arguments
90 class DarwinLdOptTable : public llvm::opt::OptTable {
92 DarwinLdOptTable() : OptTable(InfoTable) {}
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));
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);
109 members.push_back(std::move(file));
114 std::vector<std::unique_ptr<File>> loadFile(MachOLinkingContext &ctx,
115 StringRef path, bool wholeArchive,
117 if (ctx.logInputFiles())
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();
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),
137 return parseMemberFiles(std::move(file));
138 std::vector<std::unique_ptr<File>> files;
139 files.push_back(std::move(file));
143 } // end anonymous namespace
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();
150 std::string fixedPath = path;
151 std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
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)));
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())
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();
185 ctx.addExportSymbol(sym);
186 buffer = lineAndRest.second;
188 return std::error_code();
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:
196 /// libfrob.a(bar.o):_bar
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())
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())
216 StringRef sym = symAndComment.first.trim();
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))
232 sym = prefixAndSym.first;
234 ctx.appendOrderedSymbol(sym, prefix);
235 //llvm::errs() << sym << ", prefix=" << prefix << "\n";
238 return std::error_code();
242 // There are two variants of the -filelist option:
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.
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.
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;
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());
277 // No <dir> use whole line as input file path.
278 path = ctx.copy(line);
280 if (!ctx.pathExists(path)) {
281 return llvm::make_error<GenericError>(Twine("File not found '")
285 if (ctx.testingFileUsage()) {
286 message("Found filelist entry " + canonicalizePath(path));
288 addFile(path, ctx, forceLoad, false);
289 buffer = lineAndRest.second;
291 return llvm::Error::success();
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);
301 static void parseLLVMOptions(const LinkingContext &ctx) {
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);
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);
325 error("missing arg value for '" +
326 Twine(parsedArgs.getArgString(missingIndex)) + "' expected " +
327 Twine(missingCount) + " argument(s).");
331 for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
332 warn("ignoring unknown argument: " +
333 Twine(unknownArg->getAsString(parsedArgs)));
336 errorHandler().verbose = parsedArgs.hasArg(OPT_v);
337 errorHandler().errorLimit = args::getInteger(parsedArgs, OPT_error_limit, 20);
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()) {
346 fileType = llvm::MachO::MH_DYLIB;
348 case OPT_relocatable:
349 fileType = llvm::MachO::MH_OBJECT;
352 fileType = llvm::MachO::MH_BUNDLE;
355 fileType = llvm::MachO::MH_EXECUTE;
356 isStaticExecutable = true;
359 fileType = llvm::MachO::MH_PRELOAD;
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()) + "'");
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))
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);
389 error("-arch not specified and could not be inferred");
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(),
406 error("malformed macosx_version_min value");
410 case OPT_ios_version_min:
411 os = MachOLinkingContext::OS::iOS;
412 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
414 error("malformed ios_version_min value");
418 case OPT_ios_simulator_version_min:
419 os = MachOLinkingContext::OS::iOS_simulator;
420 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
422 error("malformed ios_simulator_version_min value");
428 // No min-os version on command line, check environment variables
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);
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);
443 if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
444 ctx.setEntrySymbolName(entry->getValue());
447 if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
448 ctx.setOutputPath(outpath->getValue());
450 ctx.setOutputPath("a.out");
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");
458 } else if (baseAddress < ctx.pageZeroSize()) {
459 error("image_base overlaps with __PAGEZERO");
461 } else if (baseAddress % ctx.pageSize()) {
462 error("image_base must be a multiple of page size (0x" +
463 llvm::utohexstr(ctx.pageSize()) + ")");
467 ctx.setBaseAddress(baseAddress);
470 // Handle -dead_strip
471 if (parsedArgs.getLastArg(OPT_dead_strip))
472 ctx.setDeadStripping(true);
474 bool globalWholeArchive = false;
476 if (parsedArgs.getLastArg(OPT_all_load))
477 globalWholeArchive = true;
479 // Handle -install_name
480 if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
481 ctx.setInstallName(installName->getValue());
483 ctx.setInstallName(ctx.outputPath());
485 // Handle -mark_dead_strippable_dylib
486 if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
487 ctx.setDeadStrippableDylib(true);
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");
496 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
497 error("-compatibility_version value is malformed");
500 ctx.setCompatibilityVersion(parsedVers);
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");
509 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
510 error("-current_version value is malformed");
513 ctx.setCurrentVersion(parsedVers);
516 // Handle -bundle_loader
517 if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
518 ctx.setBundleLoader(loader->getValue());
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'))
527 unsigned long long alignValue;
528 if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
529 error("-sectalign alignment value '" + Twine(alignStr) +
530 "' not a valid number");
533 uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
534 if (!llvm::isPowerOf2_64(alignValue)) {
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);
543 ctx.addSectionAlignment(segName, sectName, align);
547 for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
548 ctx.appendLLVMOption(llvmArg->getValue());
551 // Handle -print_atoms
552 if (parsedArgs.getLastArg(OPT_print_atoms))
555 // Handle -t (trace) option.
556 if (parsedArgs.getLastArg(OPT_t))
557 ctx.setLogInputFiles(true);
559 // Handle -demangle option.
560 if (parsedArgs.getLastArg(OPT_demangle))
561 ctx.setDemangleSymbols(true);
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");
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());
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
580 if (parsedArgs.getLastArg(OPT_test_file_usage)) {
581 ctx.setTestingFileUsage();
583 // With paths existing by fiat, linking is not going to end well.
584 ctx.setDoNothing(true);
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());
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();
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 }
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
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());
613 if (!sysLibRoots.empty()) {
614 // Ignore all if last -syslibroot is "/".
615 if (sysLibRoots.back() != "/")
616 ctx.setSysLibRoots(sysLibRoots);
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());
625 // Process -F directories (where to look for frameworks).
626 for (auto fwPath : parsedArgs.filtered(OPT_F)) {
627 ctx.addFrameworkSearchDir(fwPath->getValue());
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);
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()) {
645 message("Framework search paths:");
646 for (auto path : ctx.frameworkDirs()) {
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]");
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());
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]");
673 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
674 ctx.addExportSymbol(symbol->getValue());
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]");
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());
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]");
699 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
700 ctx.addExportSymbol(symbol->getValue());
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 "
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");
719 if (parsedArgs.getLastArg(OPT_objc_gc)) {
720 error("-objc_gc is not supported");
724 if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
725 error("-objc_gc_only is not supported");
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:
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");
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");
748 case MachOLinkingContext::OS::iOS_simulator:
749 if (pie->getOption().getID() == OPT_no_pie) {
750 error("iOS simulator programs must be built PIE");
754 case MachOLinkingContext::OS::unknown:
757 ctx.setPIE(pie->getOption().getID() == OPT_pie);
759 case llvm::MachO::MH_PRELOAD:
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");
767 error(pie->getSpelling() +
768 " can only used when linking main executables");
773 // Handle -version_load_command or -no_version_load_command
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;
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);
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) {
794 ctx.setGenerateVersionLoadCommand(true);
797 ctx.setGenerateVersionLoadCommand(true);
800 case llvm::MachO::MH_PRELOAD:
801 case llvm::MachO::MH_KEXT_BUNDLE:
803 ctx.setGenerateVersionLoadCommand(true);
805 case llvm::MachO::MH_DYLINKER:
806 case llvm::MachO::MH_DYLIB:
807 case llvm::MachO::MH_BUNDLE:
809 ctx.setGenerateVersionLoadCommand(true);
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
821 // Handle -function_starts or -no_function_starts
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;
831 // default to adding functions start for dynamic code, static code must
833 switch (ctx.outputMachOType()) {
834 case llvm::MachO::MH_OBJECT:
835 ctx.setGenerateFunctionStartsLoadCommand(false);
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) {
842 ctx.setGenerateFunctionStartsLoadCommand(true);
845 ctx.setGenerateFunctionStartsLoadCommand(true);
848 case llvm::MachO::MH_PRELOAD:
849 case llvm::MachO::MH_KEXT_BUNDLE:
851 ctx.setGenerateFunctionStartsLoadCommand(true);
853 case llvm::MachO::MH_DYLINKER:
854 case llvm::MachO::MH_DYLIB:
855 case llvm::MachO::MH_BUNDLE:
857 ctx.setGenerateFunctionStartsLoadCommand(true);
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
869 // Handle -data_in_code_info or -no_data_in_code_info
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;
879 // default to adding data in code for dynamic code, static code must
881 switch (ctx.outputMachOType()) {
882 case llvm::MachO::MH_OBJECT:
884 ctx.setGenerateDataInCodeLoadCommand(true);
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) {
891 ctx.setGenerateDataInCodeLoadCommand(true);
894 ctx.setGenerateDataInCodeLoadCommand(true);
897 case llvm::MachO::MH_PRELOAD:
898 case llvm::MachO::MH_KEXT_BUNDLE:
900 ctx.setGenerateDataInCodeLoadCommand(true);
902 case llvm::MachO::MH_DYLINKER:
903 case llvm::MachO::MH_DYLIB:
904 case llvm::MachO::MH_BUNDLE:
906 ctx.setGenerateDataInCodeLoadCommand(true);
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
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(),
923 error("malformed sdkVersion value");
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());
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(),
942 error("malformed source_version value");
945 ctx.setSourceVersion(version);
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");
955 if ((stackSizeVal % ctx.pageSize()) != 0) {
956 error("stack_size must be a multiple of page size (0x" +
957 llvm::utohexstr(ctx.pageSize()) + ")");
961 ctx.setStackSize(stackSizeVal);
964 // Handle debug info handling options: -S
965 if (parsedArgs.hasArg(OPT_S))
966 ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
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()
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);
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;
996 error("invalid option to -undefined [ warning | error | suppress | "
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;
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");
1017 ctx.setUndefinedMode(UndefMode);
1020 // Handle -no_objc_category_merging.
1021 if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1022 ctx.setMergeObjCCategories(false);
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");
1034 error("-rpath can only be used when targeting iOS 2.0 or later");
1039 error("-rpath can only be used when creating a dynamic final linked "
1044 for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1045 ctx.addRpath(rPath->getValue());
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);
1053 // Handle input files and sectcreate.
1054 for (auto &arg : parsedArgs) {
1056 llvm::Optional<StringRef> resolvedPath;
1057 switch (arg->getOption().getID()) {
1061 addFile(arg->getValue(), ctx, globalWholeArchive, false);
1063 case OPT_upward_library:
1064 addFile(arg->getValue(), ctx, false, true);
1066 case OPT_force_load:
1067 addFile(arg->getValue(), ctx, true, false);
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() +
1077 } else if (ctx.testingFileUsage()) {
1078 message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1079 canonicalizePath(resolvedPath.getValue()));
1081 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
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() + " " +
1091 } else if (ctx.testingFileUsage()) {
1092 message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1093 canonicalizePath(resolvedPath.getValue()));
1095 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
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());
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);
1110 ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1111 MemoryBuffer::getFile(fileName);
1113 if (!contentOrErr) {
1114 error("can't open -sectcreate file " + Twine(fileName));
1118 ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1124 if (ctx.getNodes().empty()) {
1125 error("No input files");
1129 // Validate the combination of options used.
1130 return ctx.validate();
1133 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1134 std::vector<std::unique_ptr<File>> Files;
1136 ctx.createImplicitFiles(Files);
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)));
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();
1156 MachOLinkingContext ctx;
1157 if (!parse(args, ctx))
1159 if (ctx.doNothing())
1161 if (ctx.getNodes().empty())
1164 for (std::unique_ptr<Node> &ie : ctx.getNodes())
1165 if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1166 node->getFile()->parse();
1168 createFiles(ctx, false /* Implicit */);
1170 // Give target a chance to add files
1171 createFiles(ctx, true /* Implicit */);
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();
1178 ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1179 Resolver resolver(ctx);
1180 if (!resolver.resolve())
1182 SimpleFile *merged = nullptr;
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)));
1192 // Run passes on linked atoms.
1193 ScopedTask passTask(getDefaultDomain(), "Passes");
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,
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()
1215 logAllUnhandledErrors(std::move(ec), *errorHandler().errorOS,
1220 // Call exit() if we can to avoid calling destructors.
1222 exitLld(errorCount() ? 1 : 0);
1228 } // end namespace mach_o
1229 } // end namespace lld