]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/lld/lib/ReaderWriter/MachO/MachOLinkingContext.cpp
Merge clang 7.0.1 and several follow-up changes
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / lld / lib / ReaderWriter / MachO / MachOLinkingContext.cpp
1 //===- lib/ReaderWriter/MachO/MachOLinkingContext.cpp ---------------------===//
2 //
3 //                             The LLVM Linker
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9
10 #include "lld/Common/ErrorHandler.h"
11 #include "lld/ReaderWriter/MachOLinkingContext.h"
12 #include "ArchHandler.h"
13 #include "File.h"
14 #include "FlatNamespaceFile.h"
15 #include "MachONormalizedFile.h"
16 #include "MachOPasses.h"
17 #include "SectCreateFile.h"
18 #include "lld/Common/Driver.h"
19 #include "lld/Core/ArchiveLibraryFile.h"
20 #include "lld/Core/PassManager.h"
21 #include "lld/Core/Reader.h"
22 #include "lld/Core/Writer.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/StringExtras.h"
25 #include "llvm/ADT/Triple.h"
26 #include "llvm/BinaryFormat/MachO.h"
27 #include "llvm/Demangle/Demangle.h"
28 #include "llvm/Support/Debug.h"
29 #include "llvm/Support/Errc.h"
30 #include "llvm/Support/Host.h"
31 #include "llvm/Support/Path.h"
32 #include <algorithm>
33
34 using lld::mach_o::ArchHandler;
35 using lld::mach_o::MachOFile;
36 using lld::mach_o::MachODylibFile;
37 using namespace llvm::MachO;
38
39 namespace lld {
40
41 bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
42   result = 0;
43
44   if (str.empty())
45     return false;
46
47   SmallVector<StringRef, 3> parts;
48   llvm::SplitString(str, parts, ".");
49
50   unsigned long long num;
51   if (llvm::getAsUnsignedInteger(parts[0], 10, num))
52     return true;
53   if (num > 65535)
54     return true;
55   result = num << 16;
56
57   if (parts.size() > 1) {
58     if (llvm::getAsUnsignedInteger(parts[1], 10, num))
59       return true;
60     if (num > 255)
61       return true;
62     result |= (num << 8);
63   }
64
65   if (parts.size() > 2) {
66     if (llvm::getAsUnsignedInteger(parts[2], 10, num))
67       return true;
68     if (num > 255)
69       return true;
70     result |= num;
71   }
72
73   return false;
74 }
75
76 bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
77   result = 0;
78
79   if (str.empty())
80     return false;
81
82   SmallVector<StringRef, 5> parts;
83   llvm::SplitString(str, parts, ".");
84
85   unsigned long long num;
86   if (llvm::getAsUnsignedInteger(parts[0], 10, num))
87     return true;
88   if (num > 0xFFFFFF)
89     return true;
90   result = num << 40;
91
92   unsigned Shift = 30;
93   for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
94     if (llvm::getAsUnsignedInteger(str, 10, num))
95       return true;
96     if (num > 0x3FF)
97       return true;
98     result |= (num << Shift);
99     Shift -= 10;
100   }
101
102   return false;
103 }
104
105 MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
106   { "x86_64", arch_x86_64, true,  CPU_TYPE_X86_64,  CPU_SUBTYPE_X86_64_ALL },
107   { "i386",   arch_x86,    true,  CPU_TYPE_I386,    CPU_SUBTYPE_X86_ALL },
108   { "ppc",    arch_ppc,    false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
109   { "armv6",  arch_armv6,  true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V6 },
110   { "armv7",  arch_armv7,  true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V7 },
111   { "armv7s", arch_armv7s, true,  CPU_TYPE_ARM,     CPU_SUBTYPE_ARM_V7S },
112   { "arm64",  arch_arm64,  true,  CPU_TYPE_ARM64,   CPU_SUBTYPE_ARM64_ALL },
113   { "",       arch_unknown,false, 0,                0 }
114 };
115
116 MachOLinkingContext::Arch
117 MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
118   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
119     if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
120       return info->arch;
121   }
122   return arch_unknown;
123 }
124
125 MachOLinkingContext::Arch
126 MachOLinkingContext::archFromName(StringRef archName) {
127   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
128     if (info->archName.equals(archName))
129       return info->arch;
130   }
131   return arch_unknown;
132 }
133
134 StringRef MachOLinkingContext::nameFromArch(Arch arch) {
135   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
136     if (info->arch == arch)
137       return info->archName;
138   }
139   return "<unknown>";
140 }
141
142 uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
143   assert(arch != arch_unknown);
144   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
145     if (info->arch == arch)
146       return info->cputype;
147   }
148   llvm_unreachable("Unknown arch type");
149 }
150
151 uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
152   assert(arch != arch_unknown);
153   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
154     if (info->arch == arch)
155       return info->cpusubtype;
156   }
157   llvm_unreachable("Unknown arch type");
158 }
159
160 bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
161   return mach_o::normalized::isThinObjectFile(path, arch);
162 }
163
164 bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
165                                            uint32_t &size) {
166   return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
167 }
168
169 MachOLinkingContext::MachOLinkingContext() {}
170
171 MachOLinkingContext::~MachOLinkingContext() {
172   // Atoms are allocated on BumpPtrAllocator's on File's.
173   // As we transfer atoms from one file to another, we need to clear all of the
174   // atoms before we remove any of the BumpPtrAllocator's.
175   auto &nodes = getNodes();
176   for (unsigned i = 0, e = nodes.size(); i != e; ++i) {
177     FileNode *node = dyn_cast<FileNode>(nodes[i].get());
178     if (!node)
179       continue;
180     File *file = node->getFile();
181     file->clearAtoms();
182   }
183 }
184
185 void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
186                                     uint32_t minOSVersion,
187                                     bool exportDynamicSymbols) {
188   _outputMachOType = type;
189   _arch = arch;
190   _os = os;
191   _osMinVersion = minOSVersion;
192
193   // If min OS not specified on command line, use reasonable defaults.
194   // Note that we only do sensible defaults when emitting something other than
195   // object and preload.
196   if (_outputMachOType != llvm::MachO::MH_OBJECT &&
197       _outputMachOType != llvm::MachO::MH_PRELOAD) {
198     if (minOSVersion == 0) {
199       switch (_arch) {
200       case arch_x86_64:
201       case arch_x86:
202         parsePackedVersion("10.8", _osMinVersion);
203         _os = MachOLinkingContext::OS::macOSX;
204         break;
205       case arch_armv6:
206       case arch_armv7:
207       case arch_armv7s:
208       case arch_arm64:
209         parsePackedVersion("7.0", _osMinVersion);
210         _os = MachOLinkingContext::OS::iOS;
211         break;
212       default:
213         break;
214       }
215     }
216   }
217
218   switch (_outputMachOType) {
219   case llvm::MachO::MH_EXECUTE:
220     // If targeting newer OS, use _main
221     if (minOS("10.8", "6.0")) {
222       _entrySymbolName = "_main";
223     } else {
224       // If targeting older OS, use start (in crt1.o)
225       _entrySymbolName = "start";
226     }
227
228     // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
229     // support) and 4KB on 32-bit.
230     if (is64Bit(_arch)) {
231       _pageZeroSize = 0x100000000;
232     } else {
233       _pageZeroSize = 0x1000;
234     }
235
236     // Initial base address is __PAGEZERO size.
237     _baseAddress = _pageZeroSize;
238
239     // Make PIE by default when targetting newer OSs.
240     switch (os) {
241       case OS::macOSX:
242         if (minOSVersion >= 0x000A0700) // MacOSX 10.7
243           _pie = true;
244         break;
245       case OS::iOS:
246         if (minOSVersion >= 0x00040300) // iOS 4.3
247           _pie = true;
248        break;
249        case OS::iOS_simulator:
250         _pie = true;
251        break;
252        case OS::unknown:
253        break;
254     }
255     setGlobalsAreDeadStripRoots(exportDynamicSymbols);
256     break;
257   case llvm::MachO::MH_DYLIB:
258     setGlobalsAreDeadStripRoots(exportDynamicSymbols);
259     break;
260   case llvm::MachO::MH_BUNDLE:
261     break;
262   case llvm::MachO::MH_OBJECT:
263     _printRemainingUndefines = false;
264     _allowRemainingUndefines = true;
265   default:
266     break;
267   }
268
269   // Set default segment page sizes based on arch.
270   if (arch == arch_arm64)
271     _pageSize = 4*4096;
272 }
273
274 uint32_t MachOLinkingContext::getCPUType() const {
275   return cpuTypeFromArch(_arch);
276 }
277
278 uint32_t MachOLinkingContext::getCPUSubType() const {
279   return cpuSubtypeFromArch(_arch);
280 }
281
282 bool MachOLinkingContext::is64Bit(Arch arch) {
283   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
284     if (info->arch == arch) {
285       return (info->cputype & CPU_ARCH_ABI64);
286     }
287   }
288   // unknown archs are not 64-bit.
289   return false;
290 }
291
292 bool MachOLinkingContext::isHostEndian(Arch arch) {
293   assert(arch != arch_unknown);
294   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
295     if (info->arch == arch) {
296       return (info->littleEndian == llvm::sys::IsLittleEndianHost);
297     }
298   }
299   llvm_unreachable("Unknown arch type");
300 }
301
302 bool MachOLinkingContext::isBigEndian(Arch arch) {
303   assert(arch != arch_unknown);
304   for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
305     if (info->arch == arch) {
306       return ! info->littleEndian;
307     }
308   }
309   llvm_unreachable("Unknown arch type");
310 }
311
312 bool MachOLinkingContext::is64Bit() const {
313   return is64Bit(_arch);
314 }
315
316 bool MachOLinkingContext::outputTypeHasEntry() const {
317   switch (_outputMachOType) {
318   case MH_EXECUTE:
319   case MH_DYLINKER:
320   case MH_PRELOAD:
321     return true;
322   default:
323     return false;
324   }
325 }
326
327 bool MachOLinkingContext::needsStubsPass() const {
328   switch (_outputMachOType) {
329   case MH_EXECUTE:
330     return !_outputMachOTypeStatic;
331   case MH_DYLIB:
332   case MH_BUNDLE:
333     return true;
334   default:
335     return false;
336   }
337 }
338
339 bool MachOLinkingContext::needsGOTPass() const {
340   // GOT pass not used in -r mode.
341   if (_outputMachOType == MH_OBJECT)
342     return false;
343   // Only some arches use GOT pass.
344   switch (_arch) {
345     case arch_x86_64:
346     case arch_arm64:
347       return true;
348     default:
349       return false;
350   }
351 }
352
353 bool MachOLinkingContext::needsCompactUnwindPass() const {
354   switch (_outputMachOType) {
355   case MH_EXECUTE:
356   case MH_DYLIB:
357   case MH_BUNDLE:
358     return archHandler().needsCompactUnwind();
359   default:
360     return false;
361   }
362 }
363
364 bool MachOLinkingContext::needsObjCPass() const {
365   // ObjC pass is only needed if any of the inputs were ObjC.
366   return _objcConstraint != objc_unknown;
367 }
368
369 bool MachOLinkingContext::needsShimPass() const {
370   // Shim pass only used in final executables.
371   if (_outputMachOType == MH_OBJECT)
372     return false;
373   // Only 32-bit arm arches use Shim pass.
374   switch (_arch) {
375   case arch_armv6:
376   case arch_armv7:
377   case arch_armv7s:
378     return true;
379   default:
380     return false;
381   }
382 }
383
384 bool MachOLinkingContext::needsTLVPass() const {
385   switch (_outputMachOType) {
386   case MH_BUNDLE:
387   case MH_EXECUTE:
388   case MH_DYLIB:
389     return true;
390   default:
391     return false;
392   }
393 }
394
395 StringRef MachOLinkingContext::binderSymbolName() const {
396   return archHandler().stubInfo().binderSymbolName;
397 }
398
399 bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
400   uint32_t parsedVersion;
401   switch (_os) {
402   case OS::macOSX:
403     if (parsePackedVersion(mac, parsedVersion))
404       return false;
405     return _osMinVersion >= parsedVersion;
406   case OS::iOS:
407   case OS::iOS_simulator:
408     if (parsePackedVersion(iOS, parsedVersion))
409       return false;
410     return _osMinVersion >= parsedVersion;
411   case OS::unknown:
412     // If we don't know the target, then assume that we don't meet the min OS.
413     // This matches the ld64 behaviour
414     return false;
415   }
416   llvm_unreachable("invalid OS enum");
417 }
418
419 bool MachOLinkingContext::addEntryPointLoadCommand() const {
420   if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
421     return minOS("10.8", "6.0");
422   }
423   return false;
424 }
425
426 bool MachOLinkingContext::addUnixThreadLoadCommand() const {
427   switch (_outputMachOType) {
428   case MH_EXECUTE:
429     if (_outputMachOTypeStatic)
430       return true;
431     else
432       return !minOS("10.8", "6.0");
433     break;
434   case MH_DYLINKER:
435   case MH_PRELOAD:
436     return true;
437   default:
438     return false;
439   }
440 }
441
442 bool MachOLinkingContext::pathExists(StringRef path) const {
443   if (!_testingFileUsage)
444     return llvm::sys::fs::exists(path.str());
445
446   // Otherwise, we're in test mode: only files explicitly provided on the
447   // command-line exist.
448   std::string key = path.str();
449   std::replace(key.begin(), key.end(), '\\', '/');
450   return _existingPaths.find(key) != _existingPaths.end();
451 }
452
453 bool MachOLinkingContext::fileExists(StringRef path) const {
454   bool found = pathExists(path);
455   // Log search misses.
456   if (!found)
457     addInputFileNotFound(path);
458
459   // When testing, file is never opened, so logging is done here.
460   if (_testingFileUsage && found)
461     addInputFileDependency(path);
462
463   return found;
464 }
465
466 void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
467   _syslibRoots = paths;
468 }
469
470 void MachOLinkingContext::addRpath(StringRef rpath) {
471   _rpaths.push_back(rpath);
472 }
473
474 void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
475                                                bool isSystemPath) {
476   bool addedModifiedPath = false;
477
478   // -syslibroot only applies to absolute paths.
479   if (libPath.startswith("/")) {
480     for (auto syslibRoot : _syslibRoots) {
481       SmallString<256> path(syslibRoot);
482       llvm::sys::path::append(path, libPath);
483       if (pathExists(path)) {
484         _searchDirs.push_back(path.str().copy(_allocator));
485         addedModifiedPath = true;
486       }
487     }
488   }
489
490   if (addedModifiedPath)
491     return;
492
493   // Finally, if only one -syslibroot is given, system paths which aren't in it
494   // get suppressed.
495   if (_syslibRoots.size() != 1 || !isSystemPath) {
496     if (pathExists(libPath)) {
497       _searchDirs.push_back(libPath);
498     }
499   }
500 }
501
502 void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
503                                                 bool isSystemPath) {
504   bool pathAdded = false;
505
506   // -syslibroot only used with to absolute framework search paths.
507   if (fwPath.startswith("/")) {
508     for (auto syslibRoot : _syslibRoots) {
509       SmallString<256> path(syslibRoot);
510       llvm::sys::path::append(path, fwPath);
511       if (pathExists(path)) {
512         _frameworkDirs.push_back(path.str().copy(_allocator));
513         pathAdded = true;
514       }
515     }
516   }
517   // If fwPath found in any -syslibroot, then done.
518   if (pathAdded)
519     return;
520
521   // If only one -syslibroot, system paths not in that SDK are suppressed.
522   if (isSystemPath && (_syslibRoots.size() == 1))
523     return;
524
525   // Only use raw fwPath if that directory exists.
526   if (pathExists(fwPath))
527     _frameworkDirs.push_back(fwPath);
528 }
529
530 llvm::Optional<StringRef>
531 MachOLinkingContext::searchDirForLibrary(StringRef path,
532                                          StringRef libName) const {
533   SmallString<256> fullPath;
534   if (libName.endswith(".o")) {
535     // A request ending in .o is special: just search for the file directly.
536     fullPath.assign(path);
537     llvm::sys::path::append(fullPath, libName);
538     if (fileExists(fullPath))
539       return fullPath.str().copy(_allocator);
540     return llvm::None;
541   }
542
543   // Search for dynamic library
544   fullPath.assign(path);
545   llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
546   if (fileExists(fullPath))
547     return fullPath.str().copy(_allocator);
548
549   // If not, try for a static library
550   fullPath.assign(path);
551   llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
552   if (fileExists(fullPath))
553     return fullPath.str().copy(_allocator);
554
555   return llvm::None;
556 }
557
558 llvm::Optional<StringRef>
559 MachOLinkingContext::searchLibrary(StringRef libName) const {
560   SmallString<256> path;
561   for (StringRef dir : searchDirs()) {
562     llvm::Optional<StringRef> searchDir = searchDirForLibrary(dir, libName);
563     if (searchDir)
564       return searchDir;
565   }
566
567   return llvm::None;
568 }
569
570 llvm::Optional<StringRef>
571 MachOLinkingContext::findPathForFramework(StringRef fwName) const{
572   SmallString<256> fullPath;
573   for (StringRef dir : frameworkDirs()) {
574     fullPath.assign(dir);
575     llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
576     if (fileExists(fullPath))
577       return fullPath.str().copy(_allocator);
578   }
579
580   return llvm::None;
581 }
582
583 bool MachOLinkingContext::validateImpl() {
584   // TODO: if -arch not specified, look at arch of first .o file.
585
586   if (_currentVersion && _outputMachOType != MH_DYLIB) {
587     error("-current_version can only be used with dylibs");
588     return false;
589   }
590
591   if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
592     error("-compatibility_version can only be used with dylibs");
593     return false;
594   }
595
596   if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
597     error("-mark_dead_strippable_dylib can only be used with dylibs");
598     return false;
599   }
600
601   if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
602     error("-bundle_loader can only be used with Mach-O bundles");
603     return false;
604   }
605
606   // If -exported_symbols_list used, all exported symbols must be defined.
607   if (_exportMode == ExportMode::whiteList) {
608     for (const auto &symbol : _exportedSymbols)
609       addInitialUndefinedSymbol(symbol.getKey());
610   }
611
612   // If -dead_strip, set up initial live symbols.
613   if (deadStrip()) {
614     // Entry point is live.
615     if (outputTypeHasEntry())
616       addDeadStripRoot(entrySymbolName());
617     // Lazy binding helper is live.
618     if (needsStubsPass())
619       addDeadStripRoot(binderSymbolName());
620     // If using -exported_symbols_list, make all exported symbols live.
621     if (_exportMode == ExportMode::whiteList) {
622       setGlobalsAreDeadStripRoots(false);
623       for (const auto &symbol : _exportedSymbols)
624         addDeadStripRoot(symbol.getKey());
625     }
626   }
627
628   addOutputFileDependency(outputPath());
629
630   return true;
631 }
632
633 void MachOLinkingContext::addPasses(PassManager &pm) {
634   // objc pass should be before layout pass.  Otherwise test cases may contain
635   // no atoms which confuses the layout pass.
636   if (needsObjCPass())
637     mach_o::addObjCPass(pm, *this);
638   mach_o::addLayoutPass(pm, *this);
639   if (needsStubsPass())
640     mach_o::addStubsPass(pm, *this);
641   if (needsCompactUnwindPass())
642     mach_o::addCompactUnwindPass(pm, *this);
643   if (needsGOTPass())
644     mach_o::addGOTPass(pm, *this);
645   if (needsTLVPass())
646     mach_o::addTLVPass(pm, *this);
647   if (needsShimPass())
648     mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
649 }
650
651 Writer &MachOLinkingContext::writer() const {
652   if (!_writer)
653     _writer = createWriterMachO(*this);
654   return *_writer;
655 }
656
657 ErrorOr<std::unique_ptr<MemoryBuffer>>
658 MachOLinkingContext::getMemoryBuffer(StringRef path) {
659   addInputFileDependency(path);
660
661   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
662     MemoryBuffer::getFileOrSTDIN(path);
663   if (std::error_code ec = mbOrErr.getError())
664     return ec;
665   std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
666
667   // If buffer contains a fat file, find required arch in fat buffer
668   // and switch buffer to point to just that required slice.
669   uint32_t offset;
670   uint32_t size;
671   if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
672     return MemoryBuffer::getFileSlice(path, size, offset);
673   return std::move(mb);
674 }
675
676 MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
677   ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
678   if (mbOrErr.getError())
679     return nullptr;
680
681   ErrorOr<std::unique_ptr<File>> fileOrErr =
682       registry().loadFile(std::move(mbOrErr.get()));
683   if (!fileOrErr)
684     return nullptr;
685   std::unique_ptr<File> &file = fileOrErr.get();
686   file->parse();
687   MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
688   // Node object now owned by _indirectDylibs vector.
689   _indirectDylibs.push_back(std::move(file));
690   return result;
691 }
692
693 MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
694   // See if already loaded.
695   auto pos = _pathToDylibMap.find(path);
696   if (pos != _pathToDylibMap.end())
697     return pos->second;
698
699   // Search -L paths if of the form "libXXX.dylib"
700   std::pair<StringRef, StringRef> split = path.rsplit('/');
701   StringRef leafName = split.second;
702   if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
703     // FIXME: Need to enhance searchLibrary() to only look for .dylib
704     auto libPath = searchLibrary(leafName);
705     if (libPath)
706       return loadIndirectDylib(libPath.getValue());
707   }
708
709   // Try full path with sysroot.
710   for (StringRef sysPath : _syslibRoots) {
711     SmallString<256> fullPath;
712     fullPath.assign(sysPath);
713     llvm::sys::path::append(fullPath, path);
714     if (pathExists(fullPath))
715       return loadIndirectDylib(fullPath);
716   }
717
718   // Try full path.
719   if (pathExists(path)) {
720     return loadIndirectDylib(path);
721   }
722
723   return nullptr;
724 }
725
726 uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
727   auto pos = _pathToDylibMap.find(installName);
728   if (pos != _pathToDylibMap.end())
729     return pos->second->currentVersion();
730   else
731     return 0x10000; // 1.0
732 }
733
734 uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
735   auto pos = _pathToDylibMap.find(installName);
736   if (pos != _pathToDylibMap.end())
737     return pos->second->compatVersion();
738   else
739     return 0x10000; // 1.0
740 }
741
742 void MachOLinkingContext::createImplicitFiles(
743                             std::vector<std::unique_ptr<File> > &result) {
744   // Add indirect dylibs by asking each linked dylib to add its indirects.
745   // Iterate until no more dylibs get loaded.
746   size_t dylibCount = 0;
747   while (dylibCount != _allDylibs.size()) {
748     dylibCount = _allDylibs.size();
749     for (MachODylibFile *dylib : _allDylibs) {
750       dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
751                                   return findIndirectDylib(path); });
752     }
753   }
754
755   // Let writer add output type specific extras.
756   writer().createImplicitFiles(result);
757
758   // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
759   // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
760   if (undefinedMode() != UndefinedMode::error) {
761     result.emplace_back(new mach_o::FlatNamespaceFile(*this));
762     _flatNamespaceFile = result.back().get();
763   }
764 }
765
766 void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
767                                         bool upward) const {
768   std::lock_guard<std::mutex> lock(_dylibsMutex);
769
770   if (std::find(_allDylibs.begin(),
771                 _allDylibs.end(), dylib) == _allDylibs.end())
772     _allDylibs.push_back(dylib);
773   _pathToDylibMap[dylib->installName()] = dylib;
774   // If path is different than install name, register path too.
775   if (!dylib->path().equals(dylib->installName()))
776     _pathToDylibMap[dylib->path()] = dylib;
777   if (upward)
778     _upwardDylibs.insert(dylib);
779 }
780
781 bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
782   for (MachODylibFile *dylib : _upwardDylibs) {
783     if (dylib->installName().equals(installName))
784       return true;
785   }
786   return false;
787 }
788
789 ArchHandler &MachOLinkingContext::archHandler() const {
790   if (!_archHandler)
791     _archHandler = ArchHandler::create(_arch);
792   return *_archHandler;
793 }
794
795 void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
796                                               uint16_t align) {
797   SectionAlign entry = { seg, sect, align };
798   _sectAligns.push_back(entry);
799 }
800
801 void MachOLinkingContext::addSectCreateSection(
802                                         StringRef seg, StringRef sect,
803                                         std::unique_ptr<MemoryBuffer> content) {
804
805   if (!_sectCreateFile) {
806     auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
807     _sectCreateFile = sectCreateFile.get();
808     getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
809   }
810
811   assert(_sectCreateFile && "sectcreate file does not exist.");
812   _sectCreateFile->addSection(seg, sect, std::move(content));
813 }
814
815 bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
816                                          uint16_t &align) const {
817   for (const SectionAlign &entry : _sectAligns) {
818     if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
819       align = entry.align;
820       return true;
821     }
822   }
823   return false;
824 }
825
826 void MachOLinkingContext::addExportSymbol(StringRef sym) {
827   // Support old crufty export lists with bogus entries.
828   if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
829     llvm::errs() << "warning: ignoring " << sym << " in export list\n";
830     return;
831   }
832   // Only i386 MacOSX uses old ABI, so don't change those.
833   if ((_os != OS::macOSX) || (_arch != arch_x86)) {
834     // ObjC has two differnent ABIs.  Be nice and allow one export list work for
835     // both ABIs by renaming symbols.
836     if (sym.startswith(".objc_class_name_")) {
837       std::string abi2className("_OBJC_CLASS_$_");
838       abi2className += sym.substr(17);
839       _exportedSymbols.insert(copy(abi2className));
840       std::string abi2metaclassName("_OBJC_METACLASS_$_");
841       abi2metaclassName += sym.substr(17);
842       _exportedSymbols.insert(copy(abi2metaclassName));
843       return;
844     }
845   }
846
847   // FIXME: Support wildcards.
848   _exportedSymbols.insert(sym);
849 }
850
851 bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
852   switch (_exportMode) {
853   case ExportMode::globals:
854     llvm_unreachable("exportSymbolNamed() should not be called in this mode");
855     break;
856   case ExportMode::whiteList:
857     return _exportedSymbols.count(sym);
858   case ExportMode::blackList:
859     return !_exportedSymbols.count(sym);
860   }
861   llvm_unreachable("_exportMode unknown enum value");
862 }
863
864 std::string MachOLinkingContext::demangle(StringRef symbolName) const {
865   // Only try to demangle symbols if -demangle on command line
866   if (!demangleSymbols())
867     return symbolName;
868
869   // Only try to demangle symbols that look like C++ symbols
870   if (!symbolName.startswith("__Z"))
871     return symbolName;
872
873   SmallString<256> symBuff;
874   StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
875   // Mach-O has extra leading underscore that needs to be removed.
876   const char *cstr = nullTermSym.data() + 1;
877   int status;
878   char *demangled = llvm::itaniumDemangle(cstr, nullptr, nullptr, &status);
879   if (demangled) {
880     std::string result(demangled);
881     // __cxa_demangle() always uses a malloc'ed buffer to return the result.
882     free(demangled);
883     return result;
884   }
885
886   return symbolName;
887 }
888
889 static void addDependencyInfoHelper(llvm::raw_fd_ostream *DepInfo,
890                                     char Opcode, StringRef Path) {
891   if (!DepInfo)
892     return;
893
894   *DepInfo << Opcode;
895   *DepInfo << Path;
896   *DepInfo << '\0';
897 }
898
899 std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
900   std::error_code ec;
901   _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
902                          llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
903   if (ec) {
904     _dependencyInfo.reset();
905     return ec;
906   }
907
908   addDependencyInfoHelper(_dependencyInfo.get(), 0x00, "lld" /*FIXME*/);
909   return std::error_code();
910 }
911
912 void MachOLinkingContext::addInputFileDependency(StringRef path) const {
913   addDependencyInfoHelper(_dependencyInfo.get(), 0x10, path);
914 }
915
916 void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
917   addDependencyInfoHelper(_dependencyInfo.get(), 0x11, path);
918 }
919
920 void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
921   addDependencyInfoHelper(_dependencyInfo.get(), 0x40, path);
922 }
923
924 void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
925                                               StringRef filename) {
926   // To support sorting static functions which may have the same name in
927   // multiple .o files, _orderFiles maps the symbol name to a vector
928   // of OrderFileNode each of which can specify a file prefix.
929   OrderFileNode info;
930   if (!filename.empty())
931     info.fileFilter = copy(filename);
932   info.order = _orderFileEntries++;
933   _orderFiles[symbol].push_back(info);
934 }
935
936 bool
937 MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
938                                       const DefinedAtom *atom,
939                                       unsigned &ordinal) {
940   const File *objFile = &atom->file();
941   assert(objFile);
942   StringRef objName = objFile->path();
943   std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
944   if (!dirAndLeaf.second.empty())
945     objName = dirAndLeaf.second;
946   for (const OrderFileNode &info : nodes) {
947     if (info.fileFilter.empty()) {
948       // Have unprefixed symbol name in order file that matches this atom.
949       ordinal = info.order;
950       return true;
951     }
952     if (info.fileFilter.equals(objName)) {
953       // Have prefixed symbol name in order file that matches atom's path.
954       ordinal = info.order;
955       return true;
956     }
957   }
958   return false;
959 }
960
961 bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
962                                             const DefinedAtom *right,
963                                             bool &leftBeforeRight) const {
964   // No custom sorting if no order file entries.
965   if (!_orderFileEntries)
966     return false;
967
968   // Order files can only order named atoms.
969   StringRef leftName = left->name();
970   StringRef rightName = right->name();
971   if (leftName.empty() || rightName.empty())
972     return false;
973
974   // If neither is in order file list, no custom sorter.
975   auto leftPos = _orderFiles.find(leftName);
976   auto rightPos = _orderFiles.find(rightName);
977   bool leftIsOrdered = (leftPos != _orderFiles.end());
978   bool rightIsOrdered = (rightPos != _orderFiles.end());
979   if (!leftIsOrdered && !rightIsOrdered)
980     return false;
981
982   // There could be multiple symbols with same name but different file prefixes.
983   unsigned leftOrder;
984   unsigned rightOrder;
985   bool foundLeft =
986       leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
987   bool foundRight = rightIsOrdered &&
988                     findOrderOrdinal(rightPos->getValue(), right, rightOrder);
989   if (!foundLeft && !foundRight)
990     return false;
991
992   // If only one is in order file list, ordered one goes first.
993   if (foundLeft != foundRight)
994     leftBeforeRight = foundLeft;
995   else
996     leftBeforeRight = (leftOrder < rightOrder);
997
998   return true;
999 }
1000
1001 static bool isLibrary(const std::unique_ptr<Node> &elem) {
1002   if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1003     File *file = node->getFile();
1004     return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1005   }
1006   return false;
1007 }
1008
1009 // The darwin linker processes input files in two phases.  The first phase
1010 // links in all object (.o) files in command line order. The second phase
1011 // links in libraries in command line order.
1012 // In this function we reorder the input files so that all the object files
1013 // comes before any library file. We also make a group for the library files
1014 // so that the Resolver will reiterate over the libraries as long as we find
1015 // new undefines from libraries.
1016 void MachOLinkingContext::finalizeInputFiles() {
1017   std::vector<std::unique_ptr<Node>> &elements = getNodes();
1018   std::stable_sort(elements.begin(), elements.end(),
1019                    [](const std::unique_ptr<Node> &a,
1020                       const std::unique_ptr<Node> &b) {
1021                      return !isLibrary(a) && isLibrary(b);
1022                    });
1023   size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1024   elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1025 }
1026
1027 llvm::Error MachOLinkingContext::handleLoadedFile(File &file) {
1028   auto *machoFile = dyn_cast<MachOFile>(&file);
1029   if (!machoFile)
1030     return llvm::Error::success();
1031
1032   // Check that the arch of the context matches that of the file.
1033   // Also set the arch of the context if it didn't have one.
1034   if (_arch == arch_unknown) {
1035     _arch = machoFile->arch();
1036   } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1037     // Archs are different.
1038     return llvm::make_error<GenericError>(file.path() +
1039                   Twine(" cannot be linked due to incompatible architecture"));
1040   }
1041
1042   // Check that the OS of the context matches that of the file.
1043   // Also set the OS of the context if it didn't have one.
1044   if (_os == OS::unknown) {
1045     _os = machoFile->OS();
1046   } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1047     // OSes are different.
1048     return llvm::make_error<GenericError>(file.path() +
1049               Twine(" cannot be linked due to incompatible operating systems"));
1050   }
1051
1052   // Check that if the objc info exists, that it is compatible with the target
1053   // OS.
1054   switch (machoFile->objcConstraint()) {
1055     case objc_unknown:
1056       // The file is not compiled with objc, so skip the checks.
1057       break;
1058     case objc_gc_only:
1059     case objc_supports_gc:
1060       llvm_unreachable("GC support should already have thrown an error");
1061     case objc_retainReleaseForSimulator:
1062       // The file is built with simulator objc, so make sure that the context
1063       // is also building with simulator support.
1064       if (_os != OS::iOS_simulator)
1065         return llvm::make_error<GenericError>(file.path() +
1066           Twine(" cannot be linked.  It contains ObjC built for the simulator"
1067                 " while we are linking a non-simulator target"));
1068       assert((_objcConstraint == objc_unknown ||
1069               _objcConstraint == objc_retainReleaseForSimulator) &&
1070              "Must be linking with retain/release for the simulator");
1071       _objcConstraint = objc_retainReleaseForSimulator;
1072       break;
1073     case objc_retainRelease:
1074       // The file is built without simulator objc, so make sure that the
1075       // context is also building without simulator support.
1076       if (_os == OS::iOS_simulator)
1077         return llvm::make_error<GenericError>(file.path() +
1078           Twine(" cannot be linked.  It contains ObjC built for a non-simulator"
1079                 " target while we are linking a simulator target"));
1080       assert((_objcConstraint == objc_unknown ||
1081               _objcConstraint == objc_retainRelease) &&
1082              "Must be linking with retain/release for a non-simulator target");
1083       _objcConstraint = objc_retainRelease;
1084       break;
1085   }
1086
1087   // Check that the swift version of the context matches that of the file.
1088   // Also set the swift version of the context if it didn't have one.
1089   if (!_swiftVersion) {
1090     _swiftVersion = machoFile->swiftVersion();
1091   } else if (machoFile->swiftVersion() &&
1092              machoFile->swiftVersion() != _swiftVersion) {
1093     // Swift versions are different.
1094     return llvm::make_error<GenericError>("different swift versions");
1095   }
1096
1097   return llvm::Error::success();
1098 }
1099
1100 } // end namespace lld