1 //===- lib/ReaderWriter/MachO/MachOLinkingContext.cpp ---------------------===//
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "lld/ReaderWriter/MachOLinkingContext.h"
11 #include "ArchHandler.h"
13 #include "FlatNamespaceFile.h"
14 #include "MachONormalizedFile.h"
15 #include "MachOPasses.h"
16 #include "SectCreateFile.h"
17 #include "lld/Common/Driver.h"
18 #include "lld/Core/ArchiveLibraryFile.h"
19 #include "lld/Core/PassManager.h"
20 #include "lld/Core/Reader.h"
21 #include "lld/Core/Writer.h"
22 #include "llvm/ADT/STLExtras.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/Triple.h"
25 #include "llvm/BinaryFormat/MachO.h"
26 #include "llvm/Demangle/Demangle.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/Errc.h"
29 #include "llvm/Support/Host.h"
30 #include "llvm/Support/Path.h"
33 using lld::mach_o::ArchHandler;
34 using lld::mach_o::MachOFile;
35 using lld::mach_o::MachODylibFile;
36 using namespace llvm::MachO;
40 bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
46 SmallVector<StringRef, 3> parts;
47 llvm::SplitString(str, parts, ".");
49 unsigned long long num;
50 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
56 if (parts.size() > 1) {
57 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
64 if (parts.size() > 2) {
65 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
75 bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
81 SmallVector<StringRef, 5> parts;
82 llvm::SplitString(str, parts, ".");
84 unsigned long long num;
85 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
92 for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
93 if (llvm::getAsUnsignedInteger(str, 10, num))
97 result |= (num << Shift);
104 MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
105 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
106 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
107 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
108 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
109 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
110 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
111 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
112 { "", arch_unknown,false, 0, 0 }
115 MachOLinkingContext::Arch
116 MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
117 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
118 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
124 MachOLinkingContext::Arch
125 MachOLinkingContext::archFromName(StringRef archName) {
126 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
127 if (info->archName.equals(archName))
133 StringRef MachOLinkingContext::nameFromArch(Arch arch) {
134 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
135 if (info->arch == arch)
136 return info->archName;
141 uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
142 assert(arch != arch_unknown);
143 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
144 if (info->arch == arch)
145 return info->cputype;
147 llvm_unreachable("Unknown arch type");
150 uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
151 assert(arch != arch_unknown);
152 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
153 if (info->arch == arch)
154 return info->cpusubtype;
156 llvm_unreachable("Unknown arch type");
159 bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
160 return mach_o::normalized::isThinObjectFile(path, arch);
163 bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
165 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
168 MachOLinkingContext::MachOLinkingContext() {}
170 MachOLinkingContext::~MachOLinkingContext() {
171 // Atoms are allocated on BumpPtrAllocator's on File's.
172 // As we transfer atoms from one file to another, we need to clear all of the
173 // atoms before we remove any of the BumpPtrAllocator's.
174 auto &nodes = getNodes();
175 for (unsigned i = 0, e = nodes.size(); i != e; ++i) {
176 FileNode *node = dyn_cast<FileNode>(nodes[i].get());
179 File *file = node->getFile();
184 void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
185 uint32_t minOSVersion,
186 bool exportDynamicSymbols) {
187 _outputMachOType = type;
190 _osMinVersion = minOSVersion;
192 // If min OS not specified on command line, use reasonable defaults.
193 // Note that we only do sensible defaults when emitting something other than
194 // object and preload.
195 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
196 _outputMachOType != llvm::MachO::MH_PRELOAD) {
197 if (minOSVersion == 0) {
201 parsePackedVersion("10.8", _osMinVersion);
202 _os = MachOLinkingContext::OS::macOSX;
208 parsePackedVersion("7.0", _osMinVersion);
209 _os = MachOLinkingContext::OS::iOS;
217 switch (_outputMachOType) {
218 case llvm::MachO::MH_EXECUTE:
219 // If targeting newer OS, use _main
220 if (minOS("10.8", "6.0")) {
221 _entrySymbolName = "_main";
223 // If targeting older OS, use start (in crt1.o)
224 _entrySymbolName = "start";
227 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
228 // support) and 4KB on 32-bit.
229 if (is64Bit(_arch)) {
230 _pageZeroSize = 0x100000000;
232 _pageZeroSize = 0x1000;
235 // Initial base address is __PAGEZERO size.
236 _baseAddress = _pageZeroSize;
238 // Make PIE by default when targetting newer OSs.
241 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
245 if (minOSVersion >= 0x00040300) // iOS 4.3
248 case OS::iOS_simulator:
254 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
256 case llvm::MachO::MH_DYLIB:
257 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
259 case llvm::MachO::MH_BUNDLE:
261 case llvm::MachO::MH_OBJECT:
262 _printRemainingUndefines = false;
263 _allowRemainingUndefines = true;
268 // Set default segment page sizes based on arch.
269 if (arch == arch_arm64)
273 uint32_t MachOLinkingContext::getCPUType() const {
274 return cpuTypeFromArch(_arch);
277 uint32_t MachOLinkingContext::getCPUSubType() const {
278 return cpuSubtypeFromArch(_arch);
281 bool MachOLinkingContext::is64Bit(Arch arch) {
282 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
283 if (info->arch == arch) {
284 return (info->cputype & CPU_ARCH_ABI64);
287 // unknown archs are not 64-bit.
291 bool MachOLinkingContext::isHostEndian(Arch arch) {
292 assert(arch != arch_unknown);
293 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
294 if (info->arch == arch) {
295 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
298 llvm_unreachable("Unknown arch type");
301 bool MachOLinkingContext::isBigEndian(Arch arch) {
302 assert(arch != arch_unknown);
303 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
304 if (info->arch == arch) {
305 return ! info->littleEndian;
308 llvm_unreachable("Unknown arch type");
311 bool MachOLinkingContext::is64Bit() const {
312 return is64Bit(_arch);
315 bool MachOLinkingContext::outputTypeHasEntry() const {
316 switch (_outputMachOType) {
326 bool MachOLinkingContext::needsStubsPass() const {
327 switch (_outputMachOType) {
329 return !_outputMachOTypeStatic;
338 bool MachOLinkingContext::needsGOTPass() const {
339 // GOT pass not used in -r mode.
340 if (_outputMachOType == MH_OBJECT)
342 // Only some arches use GOT pass.
352 bool MachOLinkingContext::needsCompactUnwindPass() const {
353 switch (_outputMachOType) {
357 return archHandler().needsCompactUnwind();
363 bool MachOLinkingContext::needsObjCPass() const {
364 // ObjC pass is only needed if any of the inputs were ObjC.
365 return _objcConstraint != objc_unknown;
368 bool MachOLinkingContext::needsShimPass() const {
369 // Shim pass only used in final executables.
370 if (_outputMachOType == MH_OBJECT)
372 // Only 32-bit arm arches use Shim pass.
383 bool MachOLinkingContext::needsTLVPass() const {
384 switch (_outputMachOType) {
394 StringRef MachOLinkingContext::binderSymbolName() const {
395 return archHandler().stubInfo().binderSymbolName;
398 bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
399 uint32_t parsedVersion;
402 if (parsePackedVersion(mac, parsedVersion))
404 return _osMinVersion >= parsedVersion;
406 case OS::iOS_simulator:
407 if (parsePackedVersion(iOS, parsedVersion))
409 return _osMinVersion >= parsedVersion;
411 // If we don't know the target, then assume that we don't meet the min OS.
412 // This matches the ld64 behaviour
415 llvm_unreachable("invalid OS enum");
418 bool MachOLinkingContext::addEntryPointLoadCommand() const {
419 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
420 return minOS("10.8", "6.0");
425 bool MachOLinkingContext::addUnixThreadLoadCommand() const {
426 switch (_outputMachOType) {
428 if (_outputMachOTypeStatic)
431 return !minOS("10.8", "6.0");
441 bool MachOLinkingContext::pathExists(StringRef path) const {
442 if (!_testingFileUsage)
443 return llvm::sys::fs::exists(path.str());
445 // Otherwise, we're in test mode: only files explicitly provided on the
446 // command-line exist.
447 std::string key = path.str();
448 std::replace(key.begin(), key.end(), '\\', '/');
449 return _existingPaths.find(key) != _existingPaths.end();
452 bool MachOLinkingContext::fileExists(StringRef path) const {
453 bool found = pathExists(path);
454 // Log search misses.
456 addInputFileNotFound(path);
458 // When testing, file is never opened, so logging is done here.
459 if (_testingFileUsage && found)
460 addInputFileDependency(path);
465 void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
466 _syslibRoots = paths;
469 void MachOLinkingContext::addRpath(StringRef rpath) {
470 _rpaths.push_back(rpath);
473 void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
475 bool addedModifiedPath = false;
477 // -syslibroot only applies to absolute paths.
478 if (libPath.startswith("/")) {
479 for (auto syslibRoot : _syslibRoots) {
480 SmallString<256> path(syslibRoot);
481 llvm::sys::path::append(path, libPath);
482 if (pathExists(path)) {
483 _searchDirs.push_back(path.str().copy(_allocator));
484 addedModifiedPath = true;
489 if (addedModifiedPath)
492 // Finally, if only one -syslibroot is given, system paths which aren't in it
494 if (_syslibRoots.size() != 1 || !isSystemPath) {
495 if (pathExists(libPath)) {
496 _searchDirs.push_back(libPath);
501 void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
503 bool pathAdded = false;
505 // -syslibroot only used with to absolute framework search paths.
506 if (fwPath.startswith("/")) {
507 for (auto syslibRoot : _syslibRoots) {
508 SmallString<256> path(syslibRoot);
509 llvm::sys::path::append(path, fwPath);
510 if (pathExists(path)) {
511 _frameworkDirs.push_back(path.str().copy(_allocator));
516 // If fwPath found in any -syslibroot, then done.
520 // If only one -syslibroot, system paths not in that SDK are suppressed.
521 if (isSystemPath && (_syslibRoots.size() == 1))
524 // Only use raw fwPath if that directory exists.
525 if (pathExists(fwPath))
526 _frameworkDirs.push_back(fwPath);
529 llvm::Optional<StringRef>
530 MachOLinkingContext::searchDirForLibrary(StringRef path,
531 StringRef libName) const {
532 SmallString<256> fullPath;
533 if (libName.endswith(".o")) {
534 // A request ending in .o is special: just search for the file directly.
535 fullPath.assign(path);
536 llvm::sys::path::append(fullPath, libName);
537 if (fileExists(fullPath))
538 return fullPath.str().copy(_allocator);
542 // Search for dynamic library
543 fullPath.assign(path);
544 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
545 if (fileExists(fullPath))
546 return fullPath.str().copy(_allocator);
548 // If not, try for a static library
549 fullPath.assign(path);
550 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
551 if (fileExists(fullPath))
552 return fullPath.str().copy(_allocator);
557 llvm::Optional<StringRef>
558 MachOLinkingContext::searchLibrary(StringRef libName) const {
559 SmallString<256> path;
560 for (StringRef dir : searchDirs()) {
561 llvm::Optional<StringRef> searchDir = searchDirForLibrary(dir, libName);
569 llvm::Optional<StringRef>
570 MachOLinkingContext::findPathForFramework(StringRef fwName) const{
571 SmallString<256> fullPath;
572 for (StringRef dir : frameworkDirs()) {
573 fullPath.assign(dir);
574 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
575 if (fileExists(fullPath))
576 return fullPath.str().copy(_allocator);
582 bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
583 // TODO: if -arch not specified, look at arch of first .o file.
585 if (_currentVersion && _outputMachOType != MH_DYLIB) {
586 diagnostics << "error: -current_version can only be used with dylibs\n";
590 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
592 << "error: -compatibility_version can only be used with dylibs\n";
596 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
598 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
602 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
604 << "error: -bundle_loader can only be used with Mach-O bundles\n";
608 // If -exported_symbols_list used, all exported symbols must be defined.
609 if (_exportMode == ExportMode::whiteList) {
610 for (const auto &symbol : _exportedSymbols)
611 addInitialUndefinedSymbol(symbol.getKey());
614 // If -dead_strip, set up initial live symbols.
616 // Entry point is live.
617 if (outputTypeHasEntry())
618 addDeadStripRoot(entrySymbolName());
619 // Lazy binding helper is live.
620 if (needsStubsPass())
621 addDeadStripRoot(binderSymbolName());
622 // If using -exported_symbols_list, make all exported symbols live.
623 if (_exportMode == ExportMode::whiteList) {
624 setGlobalsAreDeadStripRoots(false);
625 for (const auto &symbol : _exportedSymbols)
626 addDeadStripRoot(symbol.getKey());
630 addOutputFileDependency(outputPath());
635 void MachOLinkingContext::addPasses(PassManager &pm) {
636 // objc pass should be before layout pass. Otherwise test cases may contain
637 // no atoms which confuses the layout pass.
639 mach_o::addObjCPass(pm, *this);
640 mach_o::addLayoutPass(pm, *this);
641 if (needsStubsPass())
642 mach_o::addStubsPass(pm, *this);
643 if (needsCompactUnwindPass())
644 mach_o::addCompactUnwindPass(pm, *this);
646 mach_o::addGOTPass(pm, *this);
648 mach_o::addTLVPass(pm, *this);
650 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
653 Writer &MachOLinkingContext::writer() const {
655 _writer = createWriterMachO(*this);
659 ErrorOr<std::unique_ptr<MemoryBuffer>>
660 MachOLinkingContext::getMemoryBuffer(StringRef path) {
661 addInputFileDependency(path);
663 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
664 MemoryBuffer::getFileOrSTDIN(path);
665 if (std::error_code ec = mbOrErr.getError())
667 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
669 // If buffer contains a fat file, find required arch in fat buffer
670 // and switch buffer to point to just that required slice.
673 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
674 return MemoryBuffer::getFileSlice(path, size, offset);
675 return std::move(mb);
678 MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
679 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
680 if (mbOrErr.getError())
683 ErrorOr<std::unique_ptr<File>> fileOrErr =
684 registry().loadFile(std::move(mbOrErr.get()));
687 std::unique_ptr<File> &file = fileOrErr.get();
689 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
690 // Node object now owned by _indirectDylibs vector.
691 _indirectDylibs.push_back(std::move(file));
695 MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
696 // See if already loaded.
697 auto pos = _pathToDylibMap.find(path);
698 if (pos != _pathToDylibMap.end())
701 // Search -L paths if of the form "libXXX.dylib"
702 std::pair<StringRef, StringRef> split = path.rsplit('/');
703 StringRef leafName = split.second;
704 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
705 // FIXME: Need to enhance searchLibrary() to only look for .dylib
706 auto libPath = searchLibrary(leafName);
708 return loadIndirectDylib(libPath.getValue());
711 // Try full path with sysroot.
712 for (StringRef sysPath : _syslibRoots) {
713 SmallString<256> fullPath;
714 fullPath.assign(sysPath);
715 llvm::sys::path::append(fullPath, path);
716 if (pathExists(fullPath))
717 return loadIndirectDylib(fullPath);
721 if (pathExists(path)) {
722 return loadIndirectDylib(path);
728 uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
729 auto pos = _pathToDylibMap.find(installName);
730 if (pos != _pathToDylibMap.end())
731 return pos->second->currentVersion();
733 return 0x10000; // 1.0
736 uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
737 auto pos = _pathToDylibMap.find(installName);
738 if (pos != _pathToDylibMap.end())
739 return pos->second->compatVersion();
741 return 0x10000; // 1.0
744 void MachOLinkingContext::createImplicitFiles(
745 std::vector<std::unique_ptr<File> > &result) {
746 // Add indirect dylibs by asking each linked dylib to add its indirects.
747 // Iterate until no more dylibs get loaded.
748 size_t dylibCount = 0;
749 while (dylibCount != _allDylibs.size()) {
750 dylibCount = _allDylibs.size();
751 for (MachODylibFile *dylib : _allDylibs) {
752 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
753 return findIndirectDylib(path); });
757 // Let writer add output type specific extras.
758 writer().createImplicitFiles(result);
760 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
761 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
762 if (undefinedMode() != UndefinedMode::error) {
763 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
764 _flatNamespaceFile = result.back().get();
768 void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
770 std::lock_guard<std::mutex> lock(_dylibsMutex);
772 if (std::find(_allDylibs.begin(),
773 _allDylibs.end(), dylib) == _allDylibs.end())
774 _allDylibs.push_back(dylib);
775 _pathToDylibMap[dylib->installName()] = dylib;
776 // If path is different than install name, register path too.
777 if (!dylib->path().equals(dylib->installName()))
778 _pathToDylibMap[dylib->path()] = dylib;
780 _upwardDylibs.insert(dylib);
783 bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
784 for (MachODylibFile *dylib : _upwardDylibs) {
785 if (dylib->installName().equals(installName))
791 ArchHandler &MachOLinkingContext::archHandler() const {
793 _archHandler = ArchHandler::create(_arch);
794 return *_archHandler;
797 void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
799 SectionAlign entry = { seg, sect, align };
800 _sectAligns.push_back(entry);
803 void MachOLinkingContext::addSectCreateSection(
804 StringRef seg, StringRef sect,
805 std::unique_ptr<MemoryBuffer> content) {
807 if (!_sectCreateFile) {
808 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
809 _sectCreateFile = sectCreateFile.get();
810 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
813 assert(_sectCreateFile && "sectcreate file does not exist.");
814 _sectCreateFile->addSection(seg, sect, std::move(content));
817 bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
818 uint16_t &align) const {
819 for (const SectionAlign &entry : _sectAligns) {
820 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
828 void MachOLinkingContext::addExportSymbol(StringRef sym) {
829 // Support old crufty export lists with bogus entries.
830 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
831 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
834 // Only i386 MacOSX uses old ABI, so don't change those.
835 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
836 // ObjC has two differnent ABIs. Be nice and allow one export list work for
837 // both ABIs by renaming symbols.
838 if (sym.startswith(".objc_class_name_")) {
839 std::string abi2className("_OBJC_CLASS_$_");
840 abi2className += sym.substr(17);
841 _exportedSymbols.insert(copy(abi2className));
842 std::string abi2metaclassName("_OBJC_METACLASS_$_");
843 abi2metaclassName += sym.substr(17);
844 _exportedSymbols.insert(copy(abi2metaclassName));
849 // FIXME: Support wildcards.
850 _exportedSymbols.insert(sym);
853 bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
854 switch (_exportMode) {
855 case ExportMode::globals:
856 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
858 case ExportMode::whiteList:
859 return _exportedSymbols.count(sym);
860 case ExportMode::blackList:
861 return !_exportedSymbols.count(sym);
863 llvm_unreachable("_exportMode unknown enum value");
866 std::string MachOLinkingContext::demangle(StringRef symbolName) const {
867 // Only try to demangle symbols if -demangle on command line
868 if (!demangleSymbols())
871 // Only try to demangle symbols that look like C++ symbols
872 if (!symbolName.startswith("__Z"))
875 SmallString<256> symBuff;
876 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
877 // Mach-O has extra leading underscore that needs to be removed.
878 const char *cstr = nullTermSym.data() + 1;
880 char *demangled = llvm::itaniumDemangle(cstr, nullptr, nullptr, &status);
882 std::string result(demangled);
883 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
891 static void addDependencyInfoHelper(llvm::raw_fd_ostream *DepInfo,
892 char Opcode, StringRef Path) {
901 std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
903 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
904 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
906 _dependencyInfo.reset();
910 addDependencyInfoHelper(_dependencyInfo.get(), 0x00, "lld" /*FIXME*/);
911 return std::error_code();
914 void MachOLinkingContext::addInputFileDependency(StringRef path) const {
915 addDependencyInfoHelper(_dependencyInfo.get(), 0x10, path);
918 void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
919 addDependencyInfoHelper(_dependencyInfo.get(), 0x11, path);
922 void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
923 addDependencyInfoHelper(_dependencyInfo.get(), 0x40, path);
926 void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
927 StringRef filename) {
928 // To support sorting static functions which may have the same name in
929 // multiple .o files, _orderFiles maps the symbol name to a vector
930 // of OrderFileNode each of which can specify a file prefix.
932 if (!filename.empty())
933 info.fileFilter = copy(filename);
934 info.order = _orderFileEntries++;
935 _orderFiles[symbol].push_back(info);
939 MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
940 const DefinedAtom *atom,
942 const File *objFile = &atom->file();
944 StringRef objName = objFile->path();
945 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
946 if (!dirAndLeaf.second.empty())
947 objName = dirAndLeaf.second;
948 for (const OrderFileNode &info : nodes) {
949 if (info.fileFilter.empty()) {
950 // Have unprefixed symbol name in order file that matches this atom.
951 ordinal = info.order;
954 if (info.fileFilter.equals(objName)) {
955 // Have prefixed symbol name in order file that matches atom's path.
956 ordinal = info.order;
963 bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
964 const DefinedAtom *right,
965 bool &leftBeforeRight) const {
966 // No custom sorting if no order file entries.
967 if (!_orderFileEntries)
970 // Order files can only order named atoms.
971 StringRef leftName = left->name();
972 StringRef rightName = right->name();
973 if (leftName.empty() || rightName.empty())
976 // If neither is in order file list, no custom sorter.
977 auto leftPos = _orderFiles.find(leftName);
978 auto rightPos = _orderFiles.find(rightName);
979 bool leftIsOrdered = (leftPos != _orderFiles.end());
980 bool rightIsOrdered = (rightPos != _orderFiles.end());
981 if (!leftIsOrdered && !rightIsOrdered)
984 // There could be multiple symbols with same name but different file prefixes.
988 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
989 bool foundRight = rightIsOrdered &&
990 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
991 if (!foundLeft && !foundRight)
994 // If only one is in order file list, ordered one goes first.
995 if (foundLeft != foundRight)
996 leftBeforeRight = foundLeft;
998 leftBeforeRight = (leftOrder < rightOrder);
1003 static bool isLibrary(const std::unique_ptr<Node> &elem) {
1004 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1005 File *file = node->getFile();
1006 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1011 // The darwin linker processes input files in two phases. The first phase
1012 // links in all object (.o) files in command line order. The second phase
1013 // links in libraries in command line order.
1014 // In this function we reorder the input files so that all the object files
1015 // comes before any library file. We also make a group for the library files
1016 // so that the Resolver will reiterate over the libraries as long as we find
1017 // new undefines from libraries.
1018 void MachOLinkingContext::finalizeInputFiles() {
1019 std::vector<std::unique_ptr<Node>> &elements = getNodes();
1020 std::stable_sort(elements.begin(), elements.end(),
1021 [](const std::unique_ptr<Node> &a,
1022 const std::unique_ptr<Node> &b) {
1023 return !isLibrary(a) && isLibrary(b);
1025 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1026 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1029 llvm::Error MachOLinkingContext::handleLoadedFile(File &file) {
1030 auto *machoFile = dyn_cast<MachOFile>(&file);
1032 return llvm::Error::success();
1034 // Check that the arch of the context matches that of the file.
1035 // Also set the arch of the context if it didn't have one.
1036 if (_arch == arch_unknown) {
1037 _arch = machoFile->arch();
1038 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1039 // Archs are different.
1040 return llvm::make_error<GenericError>(file.path() +
1041 Twine(" cannot be linked due to incompatible architecture"));
1044 // Check that the OS of the context matches that of the file.
1045 // Also set the OS of the context if it didn't have one.
1046 if (_os == OS::unknown) {
1047 _os = machoFile->OS();
1048 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1049 // OSes are different.
1050 return llvm::make_error<GenericError>(file.path() +
1051 Twine(" cannot be linked due to incompatible operating systems"));
1054 // Check that if the objc info exists, that it is compatible with the target
1056 switch (machoFile->objcConstraint()) {
1058 // The file is not compiled with objc, so skip the checks.
1061 case objc_supports_gc:
1062 llvm_unreachable("GC support should already have thrown an error");
1063 case objc_retainReleaseForSimulator:
1064 // The file is built with simulator objc, so make sure that the context
1065 // is also building with simulator support.
1066 if (_os != OS::iOS_simulator)
1067 return llvm::make_error<GenericError>(file.path() +
1068 Twine(" cannot be linked. It contains ObjC built for the simulator"
1069 " while we are linking a non-simulator target"));
1070 assert((_objcConstraint == objc_unknown ||
1071 _objcConstraint == objc_retainReleaseForSimulator) &&
1072 "Must be linking with retain/release for the simulator");
1073 _objcConstraint = objc_retainReleaseForSimulator;
1075 case objc_retainRelease:
1076 // The file is built without simulator objc, so make sure that the
1077 // context is also building without simulator support.
1078 if (_os == OS::iOS_simulator)
1079 return llvm::make_error<GenericError>(file.path() +
1080 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1081 " target while we are linking a simulator target"));
1082 assert((_objcConstraint == objc_unknown ||
1083 _objcConstraint == objc_retainRelease) &&
1084 "Must be linking with retain/release for a non-simulator target");
1085 _objcConstraint = objc_retainRelease;
1089 // Check that the swift version of the context matches that of the file.
1090 // Also set the swift version of the context if it didn't have one.
1091 if (!_swiftVersion) {
1092 _swiftVersion = machoFile->swiftVersion();
1093 } else if (machoFile->swiftVersion() &&
1094 machoFile->swiftVersion() != _swiftVersion) {
1095 // Swift versions are different.
1096 return llvm::make_error<GenericError>("different swift versions");
1099 return llvm::Error::success();
1102 } // end namespace lld