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/Core/ArchiveLibraryFile.h"
17 #include "lld/Core/Error.h"
18 #include "lld/Core/File.h"
19 #include "lld/Core/Instrumentation.h"
20 #include "lld/Core/LLVM.h"
21 #include "lld/Core/Node.h"
22 #include "lld/Core/PassManager.h"
23 #include "lld/Core/Resolver.h"
24 #include "lld/Core/SharedLibraryFile.h"
25 #include "lld/Core/Simple.h"
26 #include "lld/Core/LinkingContext.h"
27 #include "lld/ReaderWriter/MachOLinkingContext.h"
28 #include "llvm/ADT/ArrayRef.h"
29 #include "llvm/ADT/Optional.h"
30 #include "llvm/ADT/SmallString.h"
31 #include "llvm/ADT/STLExtras.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringRef.h"
34 #include "llvm/ADT/Twine.h"
35 #include "llvm/Option/Arg.h"
36 #include "llvm/Option/ArgList.h"
37 #include "llvm/Option/Option.h"
38 #include "llvm/Option/OptTable.h"
39 #include "llvm/Support/Casting.h"
40 #include "llvm/Support/CommandLine.h"
41 #include "llvm/Support/Error.h"
42 #include "llvm/Support/ErrorOr.h"
43 #include "llvm/Support/Format.h"
44 #include "llvm/Support/MachO.h"
45 #include "llvm/Support/MathExtras.h"
46 #include "llvm/Support/MemoryBuffer.h"
47 #include "llvm/Support/Path.h"
48 #include "llvm/Support/raw_ostream.h"
53 #include <system_error>
61 // Create enum with OPT_xxx values for each option in DarwinLdOptions.td
64 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
67 #include "DarwinLdOptions.inc"
71 // Create prefix string literals used in DarwinLdOptions.td
72 #define PREFIX(NAME, VALUE) const char *const NAME[] = VALUE;
73 #include "DarwinLdOptions.inc"
76 // Create table mapping all options defined in DarwinLdOptions.td
77 static const llvm::opt::OptTable::Info infoTable[] = {
78 #define OPTION(PREFIX, NAME, ID, KIND, GROUP, ALIAS, ALIASARGS, FLAGS, PARAM, \
80 { PREFIX, NAME, HELPTEXT, METAVAR, OPT_##ID, llvm::opt::Option::KIND##Class, \
81 PARAM, FLAGS, OPT_##GROUP, OPT_##ALIAS, ALIASARGS },
82 #include "DarwinLdOptions.inc"
86 // Create OptTable class for parsing actual command line arguments
87 class DarwinLdOptTable : public llvm::opt::OptTable {
89 DarwinLdOptTable() : OptTable(infoTable) {}
92 static std::vector<std::unique_ptr<File>>
93 makeErrorFile(StringRef path, std::error_code ec) {
94 std::vector<std::unique_ptr<File>> result;
95 result.push_back(llvm::make_unique<ErrorFile>(path, ec));
99 static std::vector<std::unique_ptr<File>>
100 parseMemberFiles(std::unique_ptr<File> file) {
101 std::vector<std::unique_ptr<File>> members;
102 if (auto *archive = dyn_cast<ArchiveLibraryFile>(file.get())) {
103 if (std::error_code ec = archive->parseAllMembers(members))
104 return makeErrorFile(file->path(), ec);
106 members.push_back(std::move(file));
111 std::vector<std::unique_ptr<File>>
112 loadFile(MachOLinkingContext &ctx, StringRef path,
113 raw_ostream &diag, bool wholeArchive, bool upwardDylib) {
114 if (ctx.logInputFiles())
115 diag << path << "\n";
117 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = ctx.getMemoryBuffer(path);
118 if (std::error_code ec = mbOrErr.getError())
119 return makeErrorFile(path, ec);
120 ErrorOr<std::unique_ptr<File>> fileOrErr =
121 ctx.registry().loadFile(std::move(mbOrErr.get()));
122 if (std::error_code ec = fileOrErr.getError())
123 return makeErrorFile(path, ec);
124 std::unique_ptr<File> &file = fileOrErr.get();
126 // If file is a dylib, inform LinkingContext about it.
127 if (SharedLibraryFile *shl = dyn_cast<SharedLibraryFile>(file.get())) {
128 if (std::error_code ec = shl->parse())
129 return makeErrorFile(path, ec);
130 ctx.registerDylib(reinterpret_cast<mach_o::MachODylibFile *>(shl),
134 return parseMemberFiles(std::move(file));
135 std::vector<std::unique_ptr<File>> files;
136 files.push_back(std::move(file));
140 } // end anonymous namespace
142 // Test may be running on Windows. Canonicalize the path
143 // separator to '/' to get consistent outputs for tests.
144 static std::string canonicalizePath(StringRef path) {
145 char sep = llvm::sys::path::get_separator().front();
147 std::string fixedPath = path;
148 std::replace(fixedPath.begin(), fixedPath.end(), sep, '/');
155 static void addFile(StringRef path, MachOLinkingContext &ctx,
156 bool loadWholeArchive,
157 bool upwardDylib, raw_ostream &diag) {
158 std::vector<std::unique_ptr<File>> files =
159 loadFile(ctx, path, diag, loadWholeArchive, upwardDylib);
160 for (std::unique_ptr<File> &file : files)
161 ctx.getNodes().push_back(llvm::make_unique<FileNode>(std::move(file)));
164 // Export lists are one symbol per line. Blank lines are ignored.
165 // Trailing comments start with #.
166 static std::error_code parseExportsList(StringRef exportFilePath,
167 MachOLinkingContext &ctx,
168 raw_ostream &diagnostics) {
169 // Map in export list file.
170 ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
171 MemoryBuffer::getFileOrSTDIN(exportFilePath);
172 if (std::error_code ec = mb.getError())
174 ctx.addInputFileDependency(exportFilePath);
175 StringRef buffer = mb->get()->getBuffer();
176 while (!buffer.empty()) {
177 // Split off each line in the file.
178 std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
179 StringRef line = lineAndRest.first;
180 // Ignore trailing # comments.
181 std::pair<StringRef, StringRef> symAndComment = line.split('#');
182 StringRef sym = symAndComment.first.trim();
184 ctx.addExportSymbol(sym);
185 buffer = lineAndRest.second;
187 return std::error_code();
190 /// Order files are one symbol per line. Blank lines are ignored.
191 /// Trailing comments start with #. Symbol names can be prefixed with an
192 /// architecture name and/or .o leaf name. Examples:
195 /// libfrob.a(bar.o):_bar
197 static std::error_code parseOrderFile(StringRef orderFilePath,
198 MachOLinkingContext &ctx,
199 raw_ostream &diagnostics) {
200 // Map in order file.
201 ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
202 MemoryBuffer::getFileOrSTDIN(orderFilePath);
203 if (std::error_code ec = mb.getError())
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 raw_ostream &diagnostics) {
255 // If there is a comma, split off <dir>.
256 std::pair<StringRef, StringRef> opt = fileListPath.split(',');
257 StringRef filePath = opt.first;
258 StringRef dirName = opt.second;
259 ctx.addInputFileDependency(filePath);
260 // Map in file list file.
261 ErrorOr<std::unique_ptr<MemoryBuffer>> mb =
262 MemoryBuffer::getFileOrSTDIN(filePath);
263 if (std::error_code ec = mb.getError())
264 return llvm::errorCodeToError(ec);
265 StringRef buffer = mb->get()->getBuffer();
266 while (!buffer.empty()) {
267 // Split off each line in the file.
268 std::pair<StringRef, StringRef> lineAndRest = buffer.split('\n');
269 StringRef line = lineAndRest.first;
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 diagnostics << "Found filelist entry " << canonicalizePath(path) << '\n';
289 addFile(path, ctx, forceLoad, false, diagnostics);
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 raw_ostream &diagnostics) {
320 // Parse command line options using DarwinLdOptions.td
321 DarwinLdOptTable table;
322 unsigned missingIndex;
323 unsigned missingCount;
324 llvm::opt::InputArgList parsedArgs =
325 table.ParseArgs(args.slice(1), missingIndex, missingCount);
327 diagnostics << "error: missing arg value for '"
328 << parsedArgs.getArgString(missingIndex) << "' expected "
329 << missingCount << " argument(s).\n";
333 for (auto unknownArg : parsedArgs.filtered(OPT_UNKNOWN)) {
334 diagnostics << "warning: ignoring unknown argument: "
335 << unknownArg->getAsString(parsedArgs) << "\n";
338 // Figure out output kind ( -dylib, -r, -bundle, -preload, or -static )
339 llvm::MachO::HeaderFileType fileType = llvm::MachO::MH_EXECUTE;
340 bool isStaticExecutable = false;
341 if (llvm::opt::Arg *kind = parsedArgs.getLastArg(
342 OPT_dylib, OPT_relocatable, OPT_bundle, OPT_static, OPT_preload)) {
343 switch (kind->getOption().getID()) {
345 fileType = llvm::MachO::MH_DYLIB;
347 case OPT_relocatable:
348 fileType = llvm::MachO::MH_OBJECT;
351 fileType = llvm::MachO::MH_BUNDLE;
354 fileType = llvm::MachO::MH_EXECUTE;
355 isStaticExecutable = true;
358 fileType = llvm::MachO::MH_PRELOAD;
364 MachOLinkingContext::Arch arch = MachOLinkingContext::arch_unknown;
365 if (llvm::opt::Arg *archStr = parsedArgs.getLastArg(OPT_arch)) {
366 arch = MachOLinkingContext::archFromName(archStr->getValue());
367 if (arch == MachOLinkingContext::arch_unknown) {
368 diagnostics << "error: unknown arch named '" << archStr->getValue()
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(), args[0], "LLVM Linker", false);
387 diagnostics << "error: -arch not specified and could not be inferred\n";
392 // Handle -macosx_version_min or -ios_version_min
393 MachOLinkingContext::OS os = MachOLinkingContext::OS::unknown;
394 uint32_t minOSVersion = 0;
395 if (llvm::opt::Arg *minOS =
396 parsedArgs.getLastArg(OPT_macosx_version_min, OPT_ios_version_min,
397 OPT_ios_simulator_version_min)) {
398 switch (minOS->getOption().getID()) {
399 case OPT_macosx_version_min:
400 os = MachOLinkingContext::OS::macOSX;
401 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
403 diagnostics << "error: malformed macosx_version_min value\n";
407 case OPT_ios_version_min:
408 os = MachOLinkingContext::OS::iOS;
409 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
411 diagnostics << "error: malformed ios_version_min value\n";
415 case OPT_ios_simulator_version_min:
416 os = MachOLinkingContext::OS::iOS_simulator;
417 if (MachOLinkingContext::parsePackedVersion(minOS->getValue(),
419 diagnostics << "error: malformed ios_simulator_version_min value\n";
425 // No min-os version on command line, check environment variables
428 // Handle export_dynamic
429 // FIXME: Should we warn when this applies to something other than a static
430 // executable or dylib? Those are the only cases where this has an effect.
431 // Note, this has to come before ctx.configure() so that we get the correct
432 // value for _globalsAreDeadStripRoots.
433 bool exportDynamicSymbols = parsedArgs.hasArg(OPT_export_dynamic);
435 // Now that there's enough information parsed in, let the linking context
436 // set up default values.
437 ctx.configure(fileType, arch, os, minOSVersion, exportDynamicSymbols);
440 if (llvm::opt::Arg *entry = parsedArgs.getLastArg(OPT_entry))
441 ctx.setEntrySymbolName(entry->getValue());
444 if (llvm::opt::Arg *outpath = parsedArgs.getLastArg(OPT_output))
445 ctx.setOutputPath(outpath->getValue());
447 ctx.setOutputPath("a.out");
449 // Handle -image_base XXX and -seg1addr XXXX
450 if (llvm::opt::Arg *imageBase = parsedArgs.getLastArg(OPT_image_base)) {
451 uint64_t baseAddress;
452 if (parseNumberBase16(imageBase->getValue(), baseAddress)) {
453 diagnostics << "error: image_base expects a hex number\n";
455 } else if (baseAddress < ctx.pageZeroSize()) {
456 diagnostics << "error: image_base overlaps with __PAGEZERO\n";
458 } else if (baseAddress % ctx.pageSize()) {
459 diagnostics << "error: image_base must be a multiple of page size ("
460 << "0x" << llvm::utohexstr(ctx.pageSize()) << ")\n";
464 ctx.setBaseAddress(baseAddress);
467 // Handle -dead_strip
468 if (parsedArgs.getLastArg(OPT_dead_strip))
469 ctx.setDeadStripping(true);
471 bool globalWholeArchive = false;
473 if (parsedArgs.getLastArg(OPT_all_load))
474 globalWholeArchive = true;
476 // Handle -install_name
477 if (llvm::opt::Arg *installName = parsedArgs.getLastArg(OPT_install_name))
478 ctx.setInstallName(installName->getValue());
480 ctx.setInstallName(ctx.outputPath());
482 // Handle -mark_dead_strippable_dylib
483 if (parsedArgs.getLastArg(OPT_mark_dead_strippable_dylib))
484 ctx.setDeadStrippableDylib(true);
486 // Handle -compatibility_version and -current_version
487 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_compatibility_version)) {
488 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
490 << "error: -compatibility_version can only be used with -dylib\n";
494 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
495 diagnostics << "error: -compatibility_version value is malformed\n";
498 ctx.setCompatibilityVersion(parsedVers);
501 if (llvm::opt::Arg *vers = parsedArgs.getLastArg(OPT_current_version)) {
502 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
503 diagnostics << "-current_version can only be used with -dylib\n";
507 if (MachOLinkingContext::parsePackedVersion(vers->getValue(), parsedVers)) {
508 diagnostics << "error: -current_version value is malformed\n";
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 diagnostics << "error: -sectalign alignment value '"
528 << alignStr << "' not a valid number\n";
531 uint16_t align = 1 << llvm::countTrailingZeros(alignValue);
532 if (!llvm::isPowerOf2_64(alignValue)) {
533 diagnostics << "warning: alignment for '-sectalign "
534 << segName << " " << sectName
535 << llvm::format(" 0x%llX", alignValue)
536 << "' is not a power of two, using "
537 << llvm::format("0x%08X", align) << "\n";
539 ctx.addSectionAlignment(segName, sectName, align);
543 for (auto &llvmArg : parsedArgs.filtered(OPT_mllvm)) {
544 ctx.appendLLVMOption(llvmArg->getValue());
547 // Handle -print_atoms
548 if (parsedArgs.getLastArg(OPT_print_atoms))
551 // Handle -t (trace) option.
552 if (parsedArgs.getLastArg(OPT_t))
553 ctx.setLogInputFiles(true);
555 // Handle -demangle option.
556 if (parsedArgs.getLastArg(OPT_demangle))
557 ctx.setDemangleSymbols(true);
559 // Handle -keep_private_externs
560 if (parsedArgs.getLastArg(OPT_keep_private_externs)) {
561 ctx.setKeepPrivateExterns(true);
562 if (ctx.outputMachOType() != llvm::MachO::MH_OBJECT)
563 diagnostics << "warning: -keep_private_externs only used in -r mode\n";
566 // Handle -dependency_info <path> used by Xcode.
567 if (llvm::opt::Arg *depInfo = parsedArgs.getLastArg(OPT_dependency_info)) {
568 if (std::error_code ec = ctx.createDependencyFile(depInfo->getValue())) {
569 diagnostics << "warning: " << ec.message()
570 << ", processing '-dependency_info "
571 << depInfo->getValue()
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 (parsedArgs.getLastArg(OPT_v)) {
641 diagnostics << "Library search paths:\n";
642 for (auto path : ctx.searchDirs()) {
643 diagnostics << " " << path << '\n';
645 diagnostics << "Framework search paths:\n";
646 for (auto path : ctx.frameworkDirs()) {
647 diagnostics << " " << path << '\n';
651 // Handle -exported_symbols_list <file>
652 for (auto expFile : parsedArgs.filtered(OPT_exported_symbols_list)) {
653 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
654 diagnostics << "error: -exported_symbols_list cannot be combined "
655 << "with -unexported_symbol[s_list]\n";
658 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
659 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx,
661 diagnostics << "error: " << ec.message()
662 << ", processing '-exported_symbols_list "
663 << expFile->getValue()
669 // Handle -exported_symbol <symbol>
670 for (auto symbol : parsedArgs.filtered(OPT_exported_symbol)) {
671 if (ctx.exportMode() == MachOLinkingContext::ExportMode::blackList) {
672 diagnostics << "error: -exported_symbol cannot be combined "
673 << "with -unexported_symbol[s_list]\n";
676 ctx.setExportMode(MachOLinkingContext::ExportMode::whiteList);
677 ctx.addExportSymbol(symbol->getValue());
680 // Handle -unexported_symbols_list <file>
681 for (auto expFile : parsedArgs.filtered(OPT_unexported_symbols_list)) {
682 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
683 diagnostics << "error: -unexported_symbols_list cannot be combined "
684 << "with -exported_symbol[s_list]\n";
687 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
688 if (std::error_code ec = parseExportsList(expFile->getValue(), ctx,
690 diagnostics << "error: " << ec.message()
691 << ", processing '-unexported_symbols_list "
692 << expFile->getValue()
698 // Handle -unexported_symbol <symbol>
699 for (auto symbol : parsedArgs.filtered(OPT_unexported_symbol)) {
700 if (ctx.exportMode() == MachOLinkingContext::ExportMode::whiteList) {
701 diagnostics << "error: -unexported_symbol cannot be combined "
702 << "with -exported_symbol[s_list]\n";
705 ctx.setExportMode(MachOLinkingContext::ExportMode::blackList);
706 ctx.addExportSymbol(symbol->getValue());
709 // Handle obosolete -multi_module and -single_module
710 if (llvm::opt::Arg *mod =
711 parsedArgs.getLastArg(OPT_multi_module, OPT_single_module)) {
712 if (mod->getOption().getID() == OPT_multi_module) {
713 diagnostics << "warning: -multi_module is obsolete and being ignored\n";
716 if (ctx.outputMachOType() != llvm::MachO::MH_DYLIB) {
717 diagnostics << "warning: -single_module being ignored. "
718 "It is only for use when producing a dylib\n";
723 // Handle obsolete ObjC options: -objc_gc_compaction, -objc_gc, -objc_gc_only
724 if (parsedArgs.getLastArg(OPT_objc_gc_compaction)) {
725 diagnostics << "error: -objc_gc_compaction is not supported\n";
729 if (parsedArgs.getLastArg(OPT_objc_gc)) {
730 diagnostics << "error: -objc_gc is not supported\n";
734 if (parsedArgs.getLastArg(OPT_objc_gc_only)) {
735 diagnostics << "error: -objc_gc_only is not supported\n";
739 // Handle -pie or -no_pie
740 if (llvm::opt::Arg *pie = parsedArgs.getLastArg(OPT_pie, OPT_no_pie)) {
741 switch (ctx.outputMachOType()) {
742 case llvm::MachO::MH_EXECUTE:
744 case MachOLinkingContext::OS::macOSX:
745 if ((minOSVersion < 0x000A0500) &&
746 (pie->getOption().getID() == OPT_pie)) {
747 diagnostics << "-pie can only be used when targeting "
748 "Mac OS X 10.5 or later\n";
752 case MachOLinkingContext::OS::iOS:
753 if ((minOSVersion < 0x00040200) &&
754 (pie->getOption().getID() == OPT_pie)) {
755 diagnostics << "-pie can only be used when targeting "
756 "iOS 4.2 or later\n";
760 case MachOLinkingContext::OS::iOS_simulator:
761 if (pie->getOption().getID() == OPT_no_pie) {
762 diagnostics << "iOS simulator programs must be built PIE\n";
766 case MachOLinkingContext::OS::unknown:
769 ctx.setPIE(pie->getOption().getID() == OPT_pie);
771 case llvm::MachO::MH_PRELOAD:
773 case llvm::MachO::MH_DYLIB:
774 case llvm::MachO::MH_BUNDLE:
775 diagnostics << "warning: " << pie->getSpelling() << " being ignored. "
776 << "It is only used when linking main executables\n";
779 diagnostics << pie->getSpelling()
780 << " can only used when linking main executables\n";
785 // Handle -version_load_command or -no_version_load_command
788 bool flagOff = false;
789 if (auto *arg = parsedArgs.getLastArg(OPT_version_load_command,
790 OPT_no_version_load_command)) {
791 flagOn = arg->getOption().getID() == OPT_version_load_command;
792 flagOff = arg->getOption().getID() == OPT_no_version_load_command;
795 // default to adding version load command for dynamic code,
796 // static code must opt-in
797 switch (ctx.outputMachOType()) {
798 case llvm::MachO::MH_OBJECT:
799 ctx.setGenerateVersionLoadCommand(false);
801 case llvm::MachO::MH_EXECUTE:
802 // dynamic executables default to generating a version load command,
803 // while static exectuables only generate it if required.
804 if (isStaticExecutable) {
806 ctx.setGenerateVersionLoadCommand(true);
809 ctx.setGenerateVersionLoadCommand(true);
812 case llvm::MachO::MH_PRELOAD:
813 case llvm::MachO::MH_KEXT_BUNDLE:
815 ctx.setGenerateVersionLoadCommand(true);
817 case llvm::MachO::MH_DYLINKER:
818 case llvm::MachO::MH_DYLIB:
819 case llvm::MachO::MH_BUNDLE:
821 ctx.setGenerateVersionLoadCommand(true);
823 case llvm::MachO::MH_FVMLIB:
824 case llvm::MachO::MH_DYLDLINK:
825 case llvm::MachO::MH_DYLIB_STUB:
826 case llvm::MachO::MH_DSYM:
827 // We don't generate load commands for these file types, even if
833 // Handle -function_starts or -no_function_starts
836 bool flagOff = false;
837 if (auto *arg = parsedArgs.getLastArg(OPT_function_starts,
838 OPT_no_function_starts)) {
839 flagOn = arg->getOption().getID() == OPT_function_starts;
840 flagOff = arg->getOption().getID() == OPT_no_function_starts;
843 // default to adding functions start for dynamic code, static code must
845 switch (ctx.outputMachOType()) {
846 case llvm::MachO::MH_OBJECT:
847 ctx.setGenerateFunctionStartsLoadCommand(false);
849 case llvm::MachO::MH_EXECUTE:
850 // dynamic executables default to generating a version load command,
851 // while static exectuables only generate it if required.
852 if (isStaticExecutable) {
854 ctx.setGenerateFunctionStartsLoadCommand(true);
857 ctx.setGenerateFunctionStartsLoadCommand(true);
860 case llvm::MachO::MH_PRELOAD:
861 case llvm::MachO::MH_KEXT_BUNDLE:
863 ctx.setGenerateFunctionStartsLoadCommand(true);
865 case llvm::MachO::MH_DYLINKER:
866 case llvm::MachO::MH_DYLIB:
867 case llvm::MachO::MH_BUNDLE:
869 ctx.setGenerateFunctionStartsLoadCommand(true);
871 case llvm::MachO::MH_FVMLIB:
872 case llvm::MachO::MH_DYLDLINK:
873 case llvm::MachO::MH_DYLIB_STUB:
874 case llvm::MachO::MH_DSYM:
875 // We don't generate load commands for these file types, even if
881 // Handle -data_in_code_info or -no_data_in_code_info
884 bool flagOff = false;
885 if (auto *arg = parsedArgs.getLastArg(OPT_data_in_code_info,
886 OPT_no_data_in_code_info)) {
887 flagOn = arg->getOption().getID() == OPT_data_in_code_info;
888 flagOff = arg->getOption().getID() == OPT_no_data_in_code_info;
891 // default to adding data in code for dynamic code, static code must
893 switch (ctx.outputMachOType()) {
894 case llvm::MachO::MH_OBJECT:
896 ctx.setGenerateDataInCodeLoadCommand(true);
898 case llvm::MachO::MH_EXECUTE:
899 // dynamic executables default to generating a version load command,
900 // while static exectuables only generate it if required.
901 if (isStaticExecutable) {
903 ctx.setGenerateDataInCodeLoadCommand(true);
906 ctx.setGenerateDataInCodeLoadCommand(true);
909 case llvm::MachO::MH_PRELOAD:
910 case llvm::MachO::MH_KEXT_BUNDLE:
912 ctx.setGenerateDataInCodeLoadCommand(true);
914 case llvm::MachO::MH_DYLINKER:
915 case llvm::MachO::MH_DYLIB:
916 case llvm::MachO::MH_BUNDLE:
918 ctx.setGenerateDataInCodeLoadCommand(true);
920 case llvm::MachO::MH_FVMLIB:
921 case llvm::MachO::MH_DYLDLINK:
922 case llvm::MachO::MH_DYLIB_STUB:
923 case llvm::MachO::MH_DSYM:
924 // We don't generate load commands for these file types, even if
930 // Handle sdk_version
931 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_sdk_version)) {
932 uint32_t sdkVersion = 0;
933 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
935 diagnostics << "error: malformed sdkVersion value\n";
938 ctx.setSdkVersion(sdkVersion);
939 } else if (ctx.generateVersionLoadCommand()) {
940 // If we don't have an sdk version, but were going to emit a load command
941 // with min_version, then we need to give an warning as we have no sdk
942 // version to put in that command.
943 // FIXME: We need to decide whether to make this an error.
944 diagnostics << "warning: -sdk_version is required when emitting "
945 "min version load command. "
946 "Setting sdk version to match provided min version\n";
947 ctx.setSdkVersion(ctx.osMinVersion());
950 // Handle source_version
951 if (llvm::opt::Arg *arg = parsedArgs.getLastArg(OPT_source_version)) {
952 uint64_t version = 0;
953 if (MachOLinkingContext::parsePackedVersion(arg->getValue(),
955 diagnostics << "error: malformed source_version value\n";
958 ctx.setSourceVersion(version);
962 if (llvm::opt::Arg *stackSize = parsedArgs.getLastArg(OPT_stack_size)) {
963 uint64_t stackSizeVal;
964 if (parseNumberBase16(stackSize->getValue(), stackSizeVal)) {
965 diagnostics << "error: stack_size expects a hex number\n";
968 if ((stackSizeVal % ctx.pageSize()) != 0) {
969 diagnostics << "error: stack_size must be a multiple of page size ("
970 << "0x" << llvm::utohexstr(ctx.pageSize()) << ")\n";
974 ctx.setStackSize(stackSizeVal);
977 // Handle debug info handling options: -S
978 if (parsedArgs.hasArg(OPT_S))
979 ctx.setDebugInfoMode(MachOLinkingContext::DebugInfoMode::noDebugMap);
981 // Handle -order_file <file>
982 for (auto orderFile : parsedArgs.filtered(OPT_order_file)) {
983 if (std::error_code ec = parseOrderFile(orderFile->getValue(), ctx,
985 diagnostics << "error: " << ec.message()
986 << ", processing '-order_file "
987 << orderFile->getValue()
993 // Handle -flat_namespace.
994 if (llvm::opt::Arg *ns =
995 parsedArgs.getLastArg(OPT_flat_namespace, OPT_twolevel_namespace)) {
996 if (ns->getOption().getID() == OPT_flat_namespace)
997 ctx.setUseFlatNamespace(true);
1000 // Handle -undefined
1001 if (llvm::opt::Arg *undef = parsedArgs.getLastArg(OPT_undefined)) {
1002 MachOLinkingContext::UndefinedMode UndefMode;
1003 if (StringRef(undef->getValue()).equals("error"))
1004 UndefMode = MachOLinkingContext::UndefinedMode::error;
1005 else if (StringRef(undef->getValue()).equals("warning"))
1006 UndefMode = MachOLinkingContext::UndefinedMode::warning;
1007 else if (StringRef(undef->getValue()).equals("suppress"))
1008 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1009 else if (StringRef(undef->getValue()).equals("dynamic_lookup"))
1010 UndefMode = MachOLinkingContext::UndefinedMode::dynamicLookup;
1012 diagnostics << "error: invalid option to -undefined "
1013 "[ warning | error | suppress | dynamic_lookup ]\n";
1017 if (ctx.useFlatNamespace()) {
1018 // If we're using -flat_namespace then 'warning', 'suppress' and
1019 // 'dynamic_lookup' are all equivalent, so map them to 'suppress'.
1020 if (UndefMode != MachOLinkingContext::UndefinedMode::error)
1021 UndefMode = MachOLinkingContext::UndefinedMode::suppress;
1023 // If we're using -twolevel_namespace then 'warning' and 'suppress' are
1024 // illegal. Emit a diagnostic if they've been (mis)used.
1025 if (UndefMode == MachOLinkingContext::UndefinedMode::warning ||
1026 UndefMode == MachOLinkingContext::UndefinedMode::suppress) {
1027 diagnostics << "error: can't use -undefined warning or suppress with "
1028 "-twolevel_namespace\n";
1033 ctx.setUndefinedMode(UndefMode);
1036 // Handle -no_objc_category_merging.
1037 if (parsedArgs.getLastArg(OPT_no_objc_category_merging))
1038 ctx.setMergeObjCCategories(false);
1040 // Handle -rpath <path>
1041 if (parsedArgs.hasArg(OPT_rpath)) {
1042 switch (ctx.outputMachOType()) {
1043 case llvm::MachO::MH_EXECUTE:
1044 case llvm::MachO::MH_DYLIB:
1045 case llvm::MachO::MH_BUNDLE:
1046 if (!ctx.minOS("10.5", "2.0")) {
1047 if (ctx.os() == MachOLinkingContext::OS::macOSX) {
1048 diagnostics << "error: -rpath can only be used when targeting "
1049 "OS X 10.5 or later\n";
1051 diagnostics << "error: -rpath can only be used when targeting "
1052 "iOS 2.0 or later\n";
1058 diagnostics << "error: -rpath can only be used when creating "
1059 "a dynamic final linked image\n";
1063 for (auto rPath : parsedArgs.filtered(OPT_rpath)) {
1064 ctx.addRpath(rPath->getValue());
1068 // Parse the LLVM options before we process files in case the file handling
1069 // makes use of things like DEBUG().
1070 parseLLVMOptions(ctx);
1072 // Handle input files and sectcreate.
1073 for (auto &arg : parsedArgs) {
1075 llvm::Optional<StringRef> resolvedPath;
1076 switch (arg->getOption().getID()) {
1080 addFile(arg->getValue(), ctx, globalWholeArchive, false, diagnostics);
1082 case OPT_upward_library:
1083 addFile(arg->getValue(), ctx, false, true, diagnostics);
1085 case OPT_force_load:
1086 addFile(arg->getValue(), ctx, true, false, diagnostics);
1090 upward = (arg->getOption().getID() == OPT_upward_l);
1091 resolvedPath = ctx.searchLibrary(arg->getValue());
1092 if (!resolvedPath) {
1093 diagnostics << "Unable to find library for " << arg->getSpelling()
1094 << arg->getValue() << "\n";
1096 } else if (ctx.testingFileUsage()) {
1097 diagnostics << "Found " << (upward ? "upward " : " ") << "library "
1098 << canonicalizePath(resolvedPath.getValue()) << '\n';
1100 addFile(resolvedPath.getValue(), ctx, globalWholeArchive,
1101 upward, diagnostics);
1104 case OPT_upward_framework:
1105 upward = (arg->getOption().getID() == OPT_upward_framework);
1106 resolvedPath = ctx.findPathForFramework(arg->getValue());
1107 if (!resolvedPath) {
1108 diagnostics << "Unable to find framework for "
1109 << arg->getSpelling() << " " << arg->getValue() << "\n";
1111 } else if (ctx.testingFileUsage()) {
1112 diagnostics << "Found " << (upward ? "upward " : " ") << "framework "
1113 << canonicalizePath(resolvedPath.getValue()) << '\n';
1115 addFile(resolvedPath.getValue(), ctx, globalWholeArchive,
1116 upward, diagnostics);
1119 if (auto ec = loadFileList(arg->getValue(),
1120 ctx, globalWholeArchive,
1122 handleAllErrors(std::move(ec), [&](const llvm::ErrorInfoBase &EI) {
1123 diagnostics << "error: ";
1124 EI.log(diagnostics);
1125 diagnostics << ", processing '-filelist " << arg->getValue() << "'\n";
1130 case OPT_sectcreate: {
1131 const char* seg = arg->getValue(0);
1132 const char* sect = arg->getValue(1);
1133 const char* fileName = arg->getValue(2);
1135 ErrorOr<std::unique_ptr<MemoryBuffer>> contentOrErr =
1136 MemoryBuffer::getFile(fileName);
1138 if (!contentOrErr) {
1139 diagnostics << "error: can't open -sectcreate file " << fileName << "\n";
1143 ctx.addSectCreateSection(seg, sect, std::move(*contentOrErr));
1149 if (ctx.getNodes().empty()) {
1150 diagnostics << "No input files\n";
1154 // Validate the combination of options used.
1155 return ctx.validate(diagnostics);
1158 static void createFiles(MachOLinkingContext &ctx, bool Implicit) {
1159 std::vector<std::unique_ptr<File>> Files;
1161 ctx.createImplicitFiles(Files);
1163 ctx.createInternalFiles(Files);
1164 for (auto i = Files.rbegin(), e = Files.rend(); i != e; ++i) {
1165 auto &members = ctx.getNodes();
1166 members.insert(members.begin(), llvm::make_unique<FileNode>(std::move(*i)));
1170 /// This is where the link is actually performed.
1171 bool link(llvm::ArrayRef<const char *> args, raw_ostream &diagnostics) {
1172 MachOLinkingContext ctx;
1173 if (!parse(args, ctx, diagnostics))
1175 if (ctx.doNothing())
1177 if (ctx.getNodes().empty())
1180 for (std::unique_ptr<Node> &ie : ctx.getNodes())
1181 if (FileNode *node = dyn_cast<FileNode>(ie.get()))
1182 node->getFile()->parse();
1184 createFiles(ctx, false /* Implicit */);
1186 // Give target a chance to add files
1187 createFiles(ctx, true /* Implicit */);
1189 // Give target a chance to postprocess input files.
1190 // Mach-O uses this chance to move all object files before library files.
1191 ctx.finalizeInputFiles();
1194 ScopedTask resolveTask(getDefaultDomain(), "Resolve");
1195 Resolver resolver(ctx);
1196 if (!resolver.resolve())
1198 SimpleFile *merged = nullptr;
1200 std::unique_ptr<SimpleFile> mergedFile = resolver.resultFile();
1201 merged = mergedFile.get();
1202 auto &members = ctx.getNodes();
1203 members.insert(members.begin(),
1204 llvm::make_unique<FileNode>(std::move(mergedFile)));
1208 // Run passes on linked atoms.
1209 ScopedTask passTask(getDefaultDomain(), "Passes");
1212 if (auto ec = pm.runOnFile(*merged)) {
1213 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1214 // to be passed a Twine instead of a string.
1215 diagnostics << "Failed to run passes on file '" << ctx.outputPath()
1217 logAllUnhandledErrors(std::move(ec), diagnostics, std::string());
1223 // Give linked atoms to Writer to generate output file.
1224 ScopedTask writeTask(getDefaultDomain(), "Write");
1225 if (auto ec = ctx.writeFile(*merged)) {
1226 // FIXME: This should be passed to logAllUnhandledErrors but it needs
1227 // to be passed a Twine instead of a string.
1228 diagnostics << "Failed to write file '" << ctx.outputPath() << "': ";
1229 logAllUnhandledErrors(std::move(ec), diagnostics, std::string());
1236 } // end namespace mach_o
1237 } // end namespace lld