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(), args[0], "LLVM Linker", false);
388 error("-arch not specified and could not be inferred");
393 // Handle -macosx_version_min or -ios_version_min
394 MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
395 uint32_t minOSVersion = 0;
396 if (llvm::opt::Arg *minOS =
397 parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
398 OPT_ios_simulator_version_min)) {
399 switch (minOS->getOption().getID()) {
400 case OPT_macosx_version_min:
401 os = MachOLinkingContext::OS::macOSX;
402 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
404 error("malformed macosx_version_min value");
408 case OPT_ios_version_min:
409 os = MachOLinkingContext::OS::iOS;
410 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
412 error("malformed ios_version_min value");
416 case OPT_ios_simulator_version_min:
417 os = MachOLinkingContext::OS::iOS_simulator;
418 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
420 error("malformed ios_simulator_version_min value");
426 // No min-os version on command line, check environment variables
429 // Handle export_dynamic
430 // FIXME: Should we warn when this applies to something other than a static
431 // executable or dylib? Those are the only cases where this has an effect.
432 // Note, this has to come before ctx.configure() so that we get the correct
433 // value for _globalsAreDeadStripRoots.
434 bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
436 // Now that there's enough information parsed in, let the linking context
437 // set up default values.
438 ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
441 if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
442 ctx.setEntrySymbolName(entry->getValue());
445 if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
446 ctx.setOutputPath(outpath->getValue());
448 ctx.setOutputPath("a.out");
450 // Handle -image_base XXX and -seg1addr XXXX
451 if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
452 uint64_t baseAddress;
453 if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
454 error("image_base expects a hex number");
456 } else if (baseAddress < ctx.pageZeroSize()) {
457 error("image_base overlaps with __PAGEZERO");
459 } else if (baseAddress % ctx.pageSize()) {
460 error("image_base must be a multiple of page size (0x" +
461 llvm::utohexstr(ctx.pageSize()) + ")");
465 ctx.setBaseAddress(baseAddress);
468 // Handle -dead_strip
469 if (parsedArgs.getLastArg(OPT_dead_strip))
470 ctx.setDeadStripping(true);
472 bool globalWholeArchive = false;
474 if (parsedArgs.getLastArg(OPT_all_load))
475 globalWholeArchive = true;
477 // Handle -install_name
478 if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
479 ctx.setInstallName(installName->getValue());
481 ctx.setInstallName(ctx.outputPath());
483 // Handle -mark_dead_strippable_dylib
484 if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
485 ctx.setDeadStrippableDylib(true);
487 // Handle -compatibility_version and -current_version
488 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
489 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
490 error("-compatibility_version can only be used with -dylib");
494 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
495 error("-compatibility_version value is malformed");
498 ctx.setCompatibilityVersion(parsedVers);
501 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
502 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
503 error("-current_version can only be used with -dylib");
507 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
508 error("-current_version value is malformed");
511 ctx.setCurrentVersion(parsedVers);
514 // Handle -bundle_loader
515 if (llvm::opt::Arg *loader = parsedArgs.getLastArg(OPT_bundle_loader))
516 ctx.setBundleLoader(loader->getValue());
518 // Handle -sectalign segname sectname align
519 for (auto &alignArg : parsedArgs.filtered(OPT_sectalign)) {
520 const char* segName = alignArg->getValue(0);
521 const char* sectName = alignArg->getValue(1);
522 const char* alignStr = alignArg->getValue(2);
523 if ((alignStr[0] == '0') && (alignStr[1] == 'x'))
525 unsigned long long alignValue;
526 if (llvm::getAsUnsignedInteger(alignStr, 16, alignValue)) {
527 error("-sectalign alignment value '" + Twine(alignStr) +
528 "' not a valid number");
531 uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
532 if (!llvm::isPowerOf2_64(alignValue)) {
534 llvm::raw_string_ostream OS(Msg);
535 OS << "alignment for '-sectalign " << segName << " " << sectName
536 << llvm::format(" 0x%llX", alignValue)
537 << "' is not a power of two, using " << llvm::format("0x%08X", align);
541 ctx.addSectionAlignment(segName, sectName, align);
545 for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
546 ctx.appendLLVMOption(llvmArg->getValue());
549 // Handle -print_atoms
550 if (parsedArgs.getLastArg(OPT_print_atoms))
553 // Handle -t (trace) option.
554 if (parsedArgs.getLastArg(OPT_t))
555 ctx.setLogInputFiles(true);
557 // Handle -demangle option.
558 if (parsedArgs.getLastArg(OPT_demangle))
559 ctx.setDemangleSymbols(true);
561 // Handle -keep_private_externs
562 if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
563 ctx.setKeepPrivateExterns(true);
564 if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
565 warn("-keep_private_externs only used in -r mode");
568 // Handle -dependency_info <path> used by Xcode.
569 if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info))
570 if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue()))
571 warn(ec.message() + ", processing '-dependency_info " +
572 depInfo->getValue());
574 // In -test_file_usage mode, we'll be given an explicit list of paths that
575 // exist. We'll also be expected to print out information about how we located
576 // libraries and so on that the user specified, but not to actually do any
578 if (parsedArgs.getLastArg(OPT_test_file_usage)) {
579 ctx.setTestingFileUsage();
581 // With paths existing by fiat, linking is not going to end well.
582 ctx.setDoNothing(true);
584 // Only bother looking for an existence override if we're going to use it.
585 for (auto existingPath : parsedArgs.filtered(OPT_path_exists)) {
586 ctx.addExistingPathForDebug(existingPath->getValue());
590 // Register possible input file parsers.
591 if (!ctx.doNothing()) {
592 ctx.registry().addSupportMachOObjects(ctx);
593 ctx.registry().addSupportArchives(ctx.logInputFiles());
594 ctx.registry().addSupportYamlFiles();
597 // Now construct the set of library search directories, following ld64's
598 // baroque set of accumulated hacks. Mostly, the algorithm constructs
599 // { syslibroots } x { libpaths }
601 // Unfortunately, there are numerous exceptions:
602 // 1. Only absolute paths get modified by syslibroot options.
603 // 2. If there is just 1 -syslibroot, system paths not found in it are
605 // 3. If the last -syslibroot is "/", all of them are ignored entirely.
606 // 4. If { syslibroots } x path == {}, the original path is kept.
607 std::vector<StringRef> sysLibRoots;
608 for (auto syslibRoot : parsedArgs.filtered(OPT_syslibroot)) {
609 sysLibRoots.push_back(syslibRoot->getValue());
611 if (!sysLibRoots.empty()) {
612 // Ignore all if last -syslibroot is "/".
613 if (sysLibRoots.back() != "/")
614 ctx.setSysLibRoots(sysLibRoots);
617 // Paths specified with -L come first, and are not considered system paths for
618 // the case where there is precisely 1 -syslibroot.
619 for (auto libPath : parsedArgs.filtered(OPT_L)) {
620 ctx.addModifiedSearchDir(libPath->getValue());
623 // Process -F directories (where to look for frameworks).
624 for (auto fwPath : parsedArgs.filtered(OPT_F)) {
625 ctx.addFrameworkSearchDir(fwPath->getValue());
628 // -Z suppresses the standard search paths.
629 if (!parsedArgs.hasArg(OPT_Z)) {
630 ctx.addModifiedSearchDir("/usr/lib", true);
631 ctx.addModifiedSearchDir("/usr/local/lib", true);
632 ctx.addFrameworkSearchDir("/Library/Frameworks", true);
633 ctx.addFrameworkSearchDir("/System/Library/Frameworks", true);
636 // Now that we've constructed the final set of search paths, print out those
637 // search paths in verbose mode.
638 if (errorHandler().Verbose) {
639 message("Library search paths:");
640 for (auto path : ctx.searchDirs()) {
643 message("Framework search paths:");
644 for (auto path : ctx.frameworkDirs()) {
649 // Handle -exported_symbols_list <file>
650 for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
651 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
652 error("-exported_symbols_list cannot be combined with "
653 "-unexported_symbol[s_list]");
656 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
657 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
658 error(ec.message() + ", processing '-exported_symbols_list " +
659 expFile->getValue());
664 // Handle -exported_symbol <symbol>
665 for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
666 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
667 error("-exported_symbol cannot be combined with "
668 "-unexported_symbol[s_list]");
671 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
672 ctx.addExportSymbol(symbol->getValue());
675 // Handle -unexported_symbols_list <file>
676 for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
677 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
678 error("-unexported_symbols_list cannot be combined with "
679 "-exported_symbol[s_list]");
682 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
683 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx)) {
684 error(ec.message() + ", processing '-unexported_symbols_list " +
685 expFile->getValue());
690 // Handle -unexported_symbol <symbol>
691 for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
692 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
693 error("-unexported_symbol cannot be combined with "
694 "-exported_symbol[s_list]");
697 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
698 ctx.addExportSymbol(symbol->getValue());
701 // Handle obosolete -multi_module and -single_module
702 if (llvm::opt::Arg *mod =
703 parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
704 if (mod->getOption().getID() == OPT_multi_module)
705 warn("-multi_module is obsolete and being ignored");
706 else if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB)
707 warn("-single_module being ignored. It is only for use when producing a "
711 // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
712 if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
713 error("-objc_gc_compaction is not supported");
717 if (parsedArgs.getLastArg(OPT_objc_gc)) {
718 error("-objc_gc is not supported");
722 if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
723 error("-objc_gc_only is not supported");
727 // Handle -pie or -no_pie
728 if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
729 switch (ctx.outputMachOType()) {
730 case llvm::MachO::MH_EXECUTE:
732 case MachOLinkingContext::OS::macOSX:
733 if ((minOSVersion < 0x000A0500) &&
734 (pie->getOption().getID() == OPT_pie)) {
735 error("-pie can only be used when targeting Mac OS X 10.5 or later");
739 case MachOLinkingContext::OS::iOS:
740 if ((minOSVersion < 0x00040200) &&
741 (pie->getOption().getID() == OPT_pie)) {
742 error("-pie can only be used when targeting iOS 4.2 or later");
746 case MachOLinkingContext::OS::iOS_simulator:
747 if (pie->getOption().getID() == OPT_no_pie) {
748 error("iOS simulator programs must be built PIE");
752 case MachOLinkingContext::OS::unknown:
755 ctx.setPIE(pie->getOption().getID() == OPT_pie);
757 case llvm::MachO::MH_PRELOAD:
759 case llvm::MachO::MH_DYLIB:
760 case llvm::MachO::MH_BUNDLE:
761 warn(pie->getSpelling() +
762 " being ignored. It is only used when linking main executables");
765 error(pie->getSpelling() +
766 " can only used when linking main executables");
771 // Handle -version_load_command or -no_version_load_command
774 bool flagOff = false;
775 if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
776 OPT_no_version_load_command)) {
777 flagOn = arg->getOption().getID() == OPT_version_load_command;
778 flagOff = arg->getOption().getID() == OPT_no_version_load_command;
781 // default to adding version load command for dynamic code,
782 // static code must opt-in
783 switch (ctx.outputMachOType()) {
784 case llvm::MachO::MH_OBJECT:
785 ctx.setGenerateVersionLoadCommand(false);
787 case llvm::MachO::MH_EXECUTE:
788 // dynamic executables default to generating a version load command,
789 // while static exectuables only generate it if required.
790 if (isStaticExecutable) {
792 ctx.setGenerateVersionLoadCommand(true);
795 ctx.setGenerateVersionLoadCommand(true);
798 case llvm::MachO::MH_PRELOAD:
799 case llvm::MachO::MH_KEXT_BUNDLE:
801 ctx.setGenerateVersionLoadCommand(true);
803 case llvm::MachO::MH_DYLINKER:
804 case llvm::MachO::MH_DYLIB:
805 case llvm::MachO::MH_BUNDLE:
807 ctx.setGenerateVersionLoadCommand(true);
809 case llvm::MachO::MH_FVMLIB:
810 case llvm::MachO::MH_DYLDLINK:
811 case llvm::MachO::MH_DYLIB_STUB:
812 case llvm::MachO::MH_DSYM:
813 // We don't generate load commands for these file types, even if
819 // Handle -function_starts or -no_function_starts
822 bool flagOff = false;
823 if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
824 OPT_no_function_starts)) {
825 flagOn = arg->getOption().getID() == OPT_function_starts;
826 flagOff = arg->getOption().getID() == OPT_no_function_starts;
829 // default to adding functions start for dynamic code, static code must
831 switch (ctx.outputMachOType()) {
832 case llvm::MachO::MH_OBJECT:
833 ctx.setGenerateFunctionStartsLoadCommand(false);
835 case llvm::MachO::MH_EXECUTE:
836 // dynamic executables default to generating a version load command,
837 // while static exectuables only generate it if required.
838 if (isStaticExecutable) {
840 ctx.setGenerateFunctionStartsLoadCommand(true);
843 ctx.setGenerateFunctionStartsLoadCommand(true);
846 case llvm::MachO::MH_PRELOAD:
847 case llvm::MachO::MH_KEXT_BUNDLE:
849 ctx.setGenerateFunctionStartsLoadCommand(true);
851 case llvm::MachO::MH_DYLINKER:
852 case llvm::MachO::MH_DYLIB:
853 case llvm::MachO::MH_BUNDLE:
855 ctx.setGenerateFunctionStartsLoadCommand(true);
857 case llvm::MachO::MH_FVMLIB:
858 case llvm::MachO::MH_DYLDLINK:
859 case llvm::MachO::MH_DYLIB_STUB:
860 case llvm::MachO::MH_DSYM:
861 // We don't generate load commands for these file types, even if
867 // Handle -data_in_code_info or -no_data_in_code_info
870 bool flagOff = false;
871 if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
872 OPT_no_data_in_code_info)) {
873 flagOn = arg->getOption().getID() == OPT_data_in_code_info;
874 flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
877 // default to adding data in code for dynamic code, static code must
879 switch (ctx.outputMachOType()) {
880 case llvm::MachO::MH_OBJECT:
882 ctx.setGenerateDataInCodeLoadCommand(true);
884 case llvm::MachO::MH_EXECUTE:
885 // dynamic executables default to generating a version load command,
886 // while static exectuables only generate it if required.
887 if (isStaticExecutable) {
889 ctx.setGenerateDataInCodeLoadCommand(true);
892 ctx.setGenerateDataInCodeLoadCommand(true);
895 case llvm::MachO::MH_PRELOAD:
896 case llvm::MachO::MH_KEXT_BUNDLE:
898 ctx.setGenerateDataInCodeLoadCommand(true);
900 case llvm::MachO::MH_DYLINKER:
901 case llvm::MachO::MH_DYLIB:
902 case llvm::MachO::MH_BUNDLE:
904 ctx.setGenerateDataInCodeLoadCommand(true);
906 case llvm::MachO::MH_FVMLIB:
907 case llvm::MachO::MH_DYLDLINK:
908 case llvm::MachO::MH_DYLIB_STUB:
909 case llvm::MachO::MH_DSYM:
910 // We don't generate load commands for these file types, even if
916 // Handle sdk_version
917 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
918 uint32_t sdkVersion = 0;
919 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
921 error("malformed sdkVersion value");
924 ctx.setSdkVersion(sdkVersion);
925 } else if (ctx.generateVersionLoadCommand()) {
926 // If we don't have an sdk version, but were going to emit a load command
927 // with min_version, then we need to give an warning as we have no sdk
928 // version to put in that command.
929 // FIXME: We need to decide whether to make this an error.
930 warn("-sdk_version is required when emitting min version load command. "
931 "Setting sdk version to match provided min version");
932 ctx.setSdkVersion(ctx.osMinVersion());
935 // Handle source_version
936 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
937 uint64_t version = 0;
938 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
940 error("malformed source_version value");
943 ctx.setSourceVersion(version);
947 if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
948 uint64_t stackSizeVal;
949 if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
950 error("stack_size expects a hex number");
953 if ((stackSizeVal % ctx.pageSize()) != 0) {
954 error("stack_size must be a multiple of page size (0x" +
955 llvm::utohexstr(ctx.pageSize()) + ")");
959 ctx.setStackSize(stackSizeVal);
962 // Handle debug info handling options: -S
963 if (parsedArgs.hasArg(OPT_S))
964 ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
966 // Handle -order_file <file>
967 for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
968 if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx)) {
969 error(ec.message() + ", processing '-order_file " + orderFile->getValue()
975 // Handle -flat_namespace.
976 if (llvm::opt::Arg *ns =
977 parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
978 if (ns->getOption().getID() == OPT_flat_namespace)
979 ctx.setUseFlatNamespace(true);
983 if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
984 MachOLinkingContext::UndefinedMode UndefMode;
985 if (StringRef(undef->getValue()).equals("error"))
986 UndefMode = MachOLinkingContext::UndefinedMode::error;
987 else if (StringRef(undef->getValue()).equals("warning"))
988 UndefMode = MachOLinkingContext::UndefinedMode::warning;
989 else if (StringRef(undef->getValue()).equals("suppress"))
990 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
991 else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
992 UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
994 error("invalid option to -undefined [ warning | error | suppress | "
999 if (ctx.useFlatNamespace()) {
1000 // If we're using -flat_namespace then 'warning', 'suppress' and
1001 // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1002 if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1003 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1005 // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1006 // illegal. Emit a diagnostic if they've been (mis)used.
1007 if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1008 UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1009 error("can't use -undefined warning or suppress with "
1010 "-twolevel_namespace");
1015 ctx.setUndefinedMode(UndefMode);
1018 // Handle -no_objc_category_merging.
1019 if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1020 ctx.setMergeObjCCategories(false);
1022 // Handle -rpath <path>
1023 if (parsedArgs.hasArg(OPT_rpath)) {
1024 switch (ctx.outputMachOType()) {
1025 case llvm::MachO::MH_EXECUTE:
1026 case llvm::MachO::MH_DYLIB:
1027 case llvm::MachO::MH_BUNDLE:
1028 if (!ctx.minOS("10.5", "2.0")) {
1029 if (ctx.os() == MachOLinkingContext::OS::macOSX)
1030 error("-rpath can only be used when targeting OS X 10.5 or later");
1032 error("-rpath can only be used when targeting iOS 2.0 or later");
1037 error("-rpath can only be used when creating a dynamic final linked "
1042 for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1043 ctx.addRpath(rPath->getValue());
1047 // Parse the LLVM options before we process files in case the file handling
1048 // makes use of things like LLVM_DEBUG().
1049 parseLLVMOptions(ctx);
1051 // Handle input files and sectcreate.
1052 for (auto &arg : parsedArgs) {
1054 llvm::Optional<StringRef> resolvedPath;
1055 switch (arg->getOption().getID()) {
1059 addFile(arg->getValue(), ctx, globalWholeArchive, false);
1061 case OPT_upward_library:
1062 addFile(arg->getValue(), ctx, false, true);
1064 case OPT_force_load:
1065 addFile(arg->getValue(), ctx, true, false);
1069 upward = (arg->getOption().getID() == OPT_upward_l);
1070 resolvedPath = ctx.searchLibrary(arg->getValue());
1071 if (!resolvedPath) {
1072 error("Unable to find library for " + arg->getSpelling() +
1075 } else if (ctx.testingFileUsage()) {
1076 message(Twine("Found ") + (upward ? "upward " : " ") + "library " +
1077 canonicalizePath(resolvedPath.getValue()));
1079 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1082 case OPT_upward_framework:
1083 upward = (arg->getOption().getID() == OPT_upward_framework);
1084 resolvedPath = ctx.findPathForFramework(arg->getValue());
1085 if (!resolvedPath) {
1086 error("Unable to find framework for " + arg->getSpelling() + " " +
1089 } else if (ctx.testingFileUsage()) {
1090 message(Twine("Found ") + (upward ? "upward " : " ") + "framework " +
1091 canonicalizePath(resolvedPath.getValue()));
1093 addFile(resolvedPath.getValue(), ctx, globalWholeArchive, upward);
1096 if (auto ec = loadFileList(arg->getValue(), ctx, globalWholeArchive)) {
1097 handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1098 error(EI.message() + ", processing '-filelist " + arg->getValue());
1103 case OPT_sectcreate: {
1104 const char* seg = arg->getValue(0);
1105 const char* sect = arg->getValue(1);
1106 const char* fileName = arg->getValue(2);
1108 ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1109 MemoryBuffer::getFile(fileName);
1111 if (!contentOrErr) {
1112 error("can't open -sectcreate file " + Twine(fileName));
1116 ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1122 if (ctx.getNodes().empty()) {
1123 error("No input files");
1127 // Validate the combination of options used.
1128 return ctx.validate();
1131 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1132 std::vector<std::unique_ptr<File>> Files;
1134 ctx.createImplicitFiles(Files);
1136 ctx.createInternalFiles(Files);
1137 for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1138 auto &members = ctx.getNodes();
1139 members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1143 /// This is where the link is actually performed.
1144 bool link(llvm::ArrayRef<const char *> args, bool CanExitEarly,
1145 raw_ostream &Error) {
1146 errorHandler().LogName = llvm::sys::path::filename(args[0]);
1147 errorHandler().ErrorLimitExceededMsg =
1148 "too many errors emitted, stopping now (use "
1149 "'-error-limit 0' to see all errors)";
1150 errorHandler().ErrorOS = &Error;
1151 errorHandler().ExitEarly = CanExitEarly;
1152 errorHandler().ColorDiagnostics = Error.has_colors();
1154 MachOLinkingContext ctx;
1155 if (!parse(args, ctx))
1157 if (ctx.doNothing())
1159 if (ctx.getNodes().empty())
1162 for (std::unique_ptr<Node> &ie : ctx.getNodes())
1163 if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1164 node->getFile()->parse();
1166 createFiles(ctx, false /* Implicit */);
1168 // Give target a chance to add files
1169 createFiles(ctx, true /* Implicit */);
1171 // Give target a chance to postprocess input files.
1172 // Mach-O uses this chance to move all object files before library files.
1173 ctx.finalizeInputFiles();
1176 ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1177 Resolver resolver(ctx);
1178 if (!resolver.resolve())
1180 SimpleFile *merged = nullptr;
1182 std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1183 merged = mergedFile.get();
1184 auto &members = ctx.getNodes();
1185 members.insert(members.begin(),
1186 llvm::make_unique<FileNode>(std::move(mergedFile)));
1190 // Run passes on linked atoms.
1191 ScopedTask passTask(getDefaultDomain(), "Passes");
1194 if (auto ec = pm.runOnFile(*merged)) {
1195 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1196 // to be passed a Twine instead of a string.
1197 *errorHandler().ErrorOS << "Failed to run passes on file '"
1198 << ctx.outputPath() << "': ";
1199 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1206 // Give linked atoms to Writer to generate output file.
1207 ScopedTask writeTask(getDefaultDomain(), "Write");
1208 if (auto ec = ctx.writeFile(*merged)) {
1209 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1210 // to be passed a Twine instead of a string.
1211 *errorHandler().ErrorOS << "Failed to write file '" << ctx.outputPath()
1213 logAllUnhandledErrors(std::move(ec), *errorHandler().ErrorOS,
1218 // Call exit() if we can to avoid calling destructors.
1220 exitLld(errorCount() ? 1 : 0);
1226 } // end namespace mach_o
1227 } // end namespace lld