blob: e94a9090ae3313d36e6a07992bbbc72fc8a3fcb2 [file] [log] [blame]
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001//===- 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/ReaderWriter/MachOLinkingContext.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000011#include "ArchHandler.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000012#include "File.h"
Lang Hames5c692002015-09-28 20:25:14 +000013#include "FlatNamespaceFile.h"
Nick Kledzik635f9c72014-09-04 20:08:30 +000014#include "MachONormalizedFile.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000015#include "MachOPasses.h"
Lang Hamesb1b67f42015-10-24 08:20:51 +000016#include "SectCreateFile.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000017#include "lld/Core/ArchiveLibraryFile.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000018#include "lld/Core/PassManager.h"
Greg Fitzgerald4b6a7e32015-01-21 22:54:56 +000019#include "lld/Core/Reader.h"
20#include "lld/Core/Writer.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000021#include "lld/Driver/Driver.h"
Benjamin Kramer06a42af2015-03-02 00:48:06 +000022#include "llvm/ADT/STLExtras.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000023#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000025#include "llvm/Config/config.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000026#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +000027#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000028#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000029#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000030#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000031#include <algorithm>
32
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000033#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000034#include <cxxabi.h>
35#endif
36
Nick Kledzik2458bec2014-07-16 19:49:02 +000037using lld::mach_o::ArchHandler;
Pete Cooper99f3b942016-01-14 23:25:06 +000038using lld::mach_o::MachOFile;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000039using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000040using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000041
42namespace lld {
43
Nick Kledzike850d9d2013-09-10 23:46:57 +000044bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
45 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000046
47 if (str.empty())
48 return false;
49
50 SmallVector<StringRef, 3> parts;
51 llvm::SplitString(str, parts, ".");
52
53 unsigned long long num;
54 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
55 return true;
56 if (num > 65535)
57 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000058 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000059
60 if (parts.size() > 1) {
61 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
62 return true;
63 if (num > 255)
64 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000065 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000066 }
67
68 if (parts.size() > 2) {
69 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
70 return true;
71 if (num > 255)
72 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000073 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000074 }
75
76 return false;
77}
78
Nick Kledzike34182f2013-11-06 21:36:55 +000079MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
80 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
81 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
82 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
83 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
84 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
85 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000086 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000087 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000088};
89
90MachOLinkingContext::Arch
91MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000092 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
93 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000094 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000095 }
96 return arch_unknown;
97}
98
99MachOLinkingContext::Arch
100MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000101 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
102 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000103 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000104 }
105 return arch_unknown;
106}
107
Nick Kledzike5552772013-12-19 21:58:00 +0000108StringRef MachOLinkingContext::nameFromArch(Arch arch) {
109 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
110 if (info->arch == arch)
111 return info->archName;
112 }
113 return "<unknown>";
114}
115
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000116uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
117 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000118 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
119 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000120 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000121 }
122 llvm_unreachable("Unknown arch type");
123}
124
125uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
126 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000127 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
128 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000129 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000130 }
131 llvm_unreachable("Unknown arch type");
132}
133
Nick Kledzik635f9c72014-09-04 20:08:30 +0000134bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
135 return mach_o::normalized::isThinObjectFile(path, arch);
136}
137
Rafael Espindolaed48e532015-04-27 22:48:51 +0000138bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000139 uint32_t &size) {
140 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
141}
142
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000143MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000144 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000145 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
146 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
Lang Hamesff4b13c2015-05-22 00:25:34 +0000147 _stackSize(0), _compatibilityVersion(0), _currentVersion(0),
Pete Cooperfeaa9672016-01-19 18:46:40 +0000148 _objcConstraint(objc_unknown), _swiftVersion(0), _flatNamespace(false),
149 _undefinedMode(UndefinedMode::error), _deadStrippableDylib(false),
150 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
151 _demangle(false), _archHandler(nullptr), _exportMode(ExportMode::globals),
Lang Hames5c692002015-09-28 20:25:14 +0000152 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0),
153 _flatNamespaceFile(nullptr) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000154
155MachOLinkingContext::~MachOLinkingContext() {}
156
Nick Kledzik6960b072013-12-21 01:47:17 +0000157void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
Pete Cooper35116452016-01-22 21:13:24 +0000158 uint32_t minOSVersion,
159 bool exportDynamicSymbols) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000160 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000161 _arch = arch;
162 _os = os;
163 _osMinVersion = minOSVersion;
164
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000165 // If min OS not specified on command line, use reasonable defaults.
166 if (minOSVersion == 0) {
167 switch (_arch) {
168 case arch_x86_64:
169 case arch_x86:
170 parsePackedVersion("10.8", _osMinVersion);
171 _os = MachOLinkingContext::OS::macOSX;
172 break;
173 case arch_armv6:
174 case arch_armv7:
175 case arch_armv7s:
176 case arch_arm64:
177 parsePackedVersion("7.0", _osMinVersion);
178 _os = MachOLinkingContext::OS::iOS;
179 break;
180 default:
181 break;
182 }
183 }
184
Tim Northoverd30a1f22014-06-20 15:59:00 +0000185 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000186 case llvm::MachO::MH_EXECUTE:
187 // If targeting newer OS, use _main
188 if (minOS("10.8", "6.0")) {
189 _entrySymbolName = "_main";
190 } else {
191 // If targeting older OS, use start (in crt1.o)
192 _entrySymbolName = "start";
193 }
194
195 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
196 // support) and 4KB on 32-bit.
197 if (is64Bit(_arch)) {
198 _pageZeroSize = 0x100000000;
199 } else {
200 _pageZeroSize = 0x1000;
201 }
202
Lang Hamesc80344282015-09-21 22:06:02 +0000203 // Initial base address is __PAGEZERO size.
204 _baseAddress = _pageZeroSize;
205
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000206 // Make PIE by default when targetting newer OSs.
207 switch (os) {
208 case OS::macOSX:
209 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
210 _pie = true;
211 break;
212 case OS::iOS:
213 if (minOSVersion >= 0x00040300) // iOS 4.3
214 _pie = true;
215 break;
216 case OS::iOS_simulator:
217 _pie = true;
218 break;
219 case OS::unknown:
220 break;
221 }
Pete Cooper35116452016-01-22 21:13:24 +0000222 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000223 break;
224 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000225 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000226 break;
227 case llvm::MachO::MH_BUNDLE:
228 break;
229 case llvm::MachO::MH_OBJECT:
230 _printRemainingUndefines = false;
231 _allowRemainingUndefines = true;
232 default:
233 break;
234 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000235
236 // Set default segment page sizes based on arch.
237 if (arch == arch_arm64)
238 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000239}
240
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000241uint32_t MachOLinkingContext::getCPUType() const {
242 return cpuTypeFromArch(_arch);
243}
244
245uint32_t MachOLinkingContext::getCPUSubType() const {
246 return cpuSubtypeFromArch(_arch);
247}
248
Nick Kledzike34182f2013-11-06 21:36:55 +0000249bool MachOLinkingContext::is64Bit(Arch arch) {
250 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
251 if (info->arch == arch) {
252 return (info->cputype & CPU_ARCH_ABI64);
253 }
254 }
255 // unknown archs are not 64-bit.
256 return false;
257}
258
259bool MachOLinkingContext::isHostEndian(Arch arch) {
260 assert(arch != arch_unknown);
261 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
262 if (info->arch == arch) {
263 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
264 }
265 }
266 llvm_unreachable("Unknown arch type");
267}
268
269bool MachOLinkingContext::isBigEndian(Arch arch) {
270 assert(arch != arch_unknown);
271 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
272 if (info->arch == arch) {
273 return ! info->littleEndian;
274 }
275 }
276 llvm_unreachable("Unknown arch type");
277}
278
Nick Kledzike34182f2013-11-06 21:36:55 +0000279bool MachOLinkingContext::is64Bit() const {
280 return is64Bit(_arch);
281}
282
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000283bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000284 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000285 case MH_EXECUTE:
286 case MH_DYLINKER:
287 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000288 return true;
289 default:
290 return false;
291 }
292}
293
Nick Kledzik2458bec2014-07-16 19:49:02 +0000294bool MachOLinkingContext::needsStubsPass() const {
295 switch (_outputMachOType) {
296 case MH_EXECUTE:
297 return !_outputMachOTypeStatic;
298 case MH_DYLIB:
299 case MH_BUNDLE:
300 return true;
301 default:
302 return false;
303 }
304}
305
306bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000307 // GOT pass not used in -r mode.
308 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000309 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000310 // Only some arches use GOT pass.
311 switch (_arch) {
312 case arch_x86_64:
313 case arch_arm64:
314 return true;
315 default:
316 return false;
317 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000318}
319
Tim Northovercf78d372014-09-30 21:29:54 +0000320bool MachOLinkingContext::needsCompactUnwindPass() const {
321 switch (_outputMachOType) {
322 case MH_EXECUTE:
323 case MH_DYLIB:
324 case MH_BUNDLE:
325 return archHandler().needsCompactUnwind();
326 default:
327 return false;
328 }
329}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000330
Pete Cooper90dbab02016-01-19 21:54:21 +0000331bool MachOLinkingContext::needsObjCPass() const {
332 // ObjC pass is only needed if any of the inputs were ObjC.
333 return _objcConstraint != objc_unknown;
334}
335
Nick Kledzik4121bce2014-10-14 01:51:42 +0000336bool MachOLinkingContext::needsShimPass() const {
337 // Shim pass only used in final executables.
338 if (_outputMachOType == MH_OBJECT)
339 return false;
340 // Only 32-bit arm arches use Shim pass.
341 switch (_arch) {
342 case arch_armv6:
343 case arch_armv7:
344 case arch_armv7s:
345 return true;
346 default:
347 return false;
348 }
349}
350
Lang Hames49047032015-06-23 20:35:31 +0000351bool MachOLinkingContext::needsTLVPass() const {
352 switch (_outputMachOType) {
353 case MH_BUNDLE:
354 case MH_EXECUTE:
355 case MH_DYLIB:
356 return true;
357 default:
358 return false;
359 }
360}
361
Nick Kledzik2458bec2014-07-16 19:49:02 +0000362StringRef MachOLinkingContext::binderSymbolName() const {
363 return archHandler().stubInfo().binderSymbolName;
364}
365
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000366bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000367 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000368 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000369 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000370 if (parsePackedVersion(mac, parsedVersion))
371 return false;
372 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000373 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000374 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000375 if (parsePackedVersion(iOS, parsedVersion))
376 return false;
377 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000378 case OS::unknown:
379 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000380 }
381 llvm_unreachable("target not configured for iOS or MacOSX");
382}
383
384bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000385 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000386 return minOS("10.8", "6.0");
387 }
388 return false;
389}
390
391bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000392 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000393 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000394 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000395 return true;
396 else
397 return !minOS("10.8", "6.0");
398 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000399 case MH_DYLINKER:
400 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000401 return true;
402 default:
403 return false;
404 }
405}
406
Tim Northover77d82202014-07-10 11:21:06 +0000407bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000408 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000409 return llvm::sys::fs::exists(path.str());
410
411 // Otherwise, we're in test mode: only files explicitly provided on the
412 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000413 std::string key = path.str();
414 std::replace(key.begin(), key.end(), '\\', '/');
415 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000416}
417
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000418bool MachOLinkingContext::fileExists(StringRef path) const {
419 bool found = pathExists(path);
420 // Log search misses.
421 if (!found)
422 addInputFileNotFound(path);
423
424 // When testing, file is never opened, so logging is done here.
425 if (_testingFileUsage && found)
426 addInputFileDependency(path);
427
428 return found;
429}
430
Nick Kledzik2d835da2014-08-14 22:20:41 +0000431void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
432 _syslibRoots = paths;
433}
434
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000435void MachOLinkingContext::addRpath(StringRef rpath) {
436 _rpaths.push_back(rpath);
437}
438
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000439void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
440 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000441 bool addedModifiedPath = false;
442
Nick Kledzik2d835da2014-08-14 22:20:41 +0000443 // -syslibroot only applies to absolute paths.
444 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000445 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000446 SmallString<256> path(syslibRoot);
447 llvm::sys::path::append(path, libPath);
448 if (pathExists(path)) {
449 _searchDirs.push_back(path.str().copy(_allocator));
450 addedModifiedPath = true;
451 }
452 }
453 }
454
455 if (addedModifiedPath)
456 return;
457
458 // Finally, if only one -syslibroot is given, system paths which aren't in it
459 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000460 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000461 if (pathExists(libPath)) {
462 _searchDirs.push_back(libPath);
463 }
464 }
465}
466
Nick Kledzik2d835da2014-08-14 22:20:41 +0000467void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
468 bool isSystemPath) {
469 bool pathAdded = false;
470
471 // -syslibroot only used with to absolute framework search paths.
472 if (fwPath.startswith("/")) {
473 for (auto syslibRoot : _syslibRoots) {
474 SmallString<256> path(syslibRoot);
475 llvm::sys::path::append(path, fwPath);
476 if (pathExists(path)) {
477 _frameworkDirs.push_back(path.str().copy(_allocator));
478 pathAdded = true;
479 }
480 }
481 }
482 // If fwPath found in any -syslibroot, then done.
483 if (pathAdded)
484 return;
485
486 // If only one -syslibroot, system paths not in that SDK are suppressed.
487 if (isSystemPath && (_syslibRoots.size() == 1))
488 return;
489
490 // Only use raw fwPath if that directory exists.
491 if (pathExists(fwPath))
492 _frameworkDirs.push_back(fwPath);
493}
494
Tim Northover77d82202014-07-10 11:21:06 +0000495ErrorOr<StringRef>
496MachOLinkingContext::searchDirForLibrary(StringRef path,
497 StringRef libName) const {
498 SmallString<256> fullPath;
499 if (libName.endswith(".o")) {
500 // A request ending in .o is special: just search for the file directly.
501 fullPath.assign(path);
502 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000503 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000504 return fullPath.str().copy(_allocator);
505 return make_error_code(llvm::errc::no_such_file_or_directory);
506 }
507
508 // Search for dynamic library
509 fullPath.assign(path);
510 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000511 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000512 return fullPath.str().copy(_allocator);
513
514 // If not, try for a static library
515 fullPath.assign(path);
516 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000517 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000518 return fullPath.str().copy(_allocator);
519
520 return make_error_code(llvm::errc::no_such_file_or_directory);
521}
522
Tim Northover77d82202014-07-10 11:21:06 +0000523ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
524 SmallString<256> path;
525 for (StringRef dir : searchDirs()) {
526 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
527 if (ec)
528 return ec;
529 }
530
531 return make_error_code(llvm::errc::no_such_file_or_directory);
532}
533
Nick Kledzik2d835da2014-08-14 22:20:41 +0000534ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
535 SmallString<256> fullPath;
536 for (StringRef dir : frameworkDirs()) {
537 fullPath.assign(dir);
538 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000539 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000540 return fullPath.str().copy(_allocator);
541 }
542
543 return make_error_code(llvm::errc::no_such_file_or_directory);
544}
545
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000546bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000547 // TODO: if -arch not specified, look at arch of first .o file.
548
Tim Northoverd30a1f22014-06-20 15:59:00 +0000549 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000550 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000551 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000552 }
553
Tim Northoverd30a1f22014-06-20 15:59:00 +0000554 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000555 diagnostics
556 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000557 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000558 }
559
Tim Northoverd30a1f22014-06-20 15:59:00 +0000560 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000561 diagnostics
562 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000563 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000564 }
565
Tim Northoverd30a1f22014-06-20 15:59:00 +0000566 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000567 diagnostics
568 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000569 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000570 }
571
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000572 // If -exported_symbols_list used, all exported symbols must be defined.
573 if (_exportMode == ExportMode::whiteList) {
574 for (const auto &symbol : _exportedSymbols)
575 addInitialUndefinedSymbol(symbol.getKey());
576 }
577
Nick Kledzik77afc712014-08-21 20:25:50 +0000578 // If -dead_strip, set up initial live symbols.
579 if (deadStrip()) {
580 // Entry point is live.
581 if (outputTypeHasEntry())
582 addDeadStripRoot(entrySymbolName());
583 // Lazy binding helper is live.
584 if (needsStubsPass())
585 addDeadStripRoot(binderSymbolName());
586 // If using -exported_symbols_list, make all exported symbols live.
587 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000588 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000589 for (const auto &symbol : _exportedSymbols)
590 addDeadStripRoot(symbol.getKey());
591 }
592 }
593
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000594 addOutputFileDependency(outputPath());
595
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000596 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000597}
598
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000599void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000600 // objc pass should be before layout pass. Otherwise test cases may contain
601 // no atoms which confuses the layout pass.
602 if (needsObjCPass())
603 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000604 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000605 if (needsStubsPass())
606 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000607 if (needsCompactUnwindPass())
608 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000609 if (needsGOTPass())
610 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000611 if (needsTLVPass())
612 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000613 if (needsShimPass())
614 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000615}
616
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000617Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000618 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000619 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000620 return *_writer;
621}
622
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000623ErrorOr<std::unique_ptr<MemoryBuffer>>
624MachOLinkingContext::getMemoryBuffer(StringRef path) {
625 addInputFileDependency(path);
626
Rui Ueyamadf230b22015-01-15 04:34:31 +0000627 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000628 MemoryBuffer::getFileOrSTDIN(path);
629 if (std::error_code ec = mbOrErr.getError())
630 return ec;
631 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
632
633 // If buffer contains a fat file, find required arch in fat buffer
634 // and switch buffer to point to just that required slice.
635 uint32_t offset;
636 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000637 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000638 return MemoryBuffer::getFileSlice(path, size, offset);
639 return std::move(mb);
640}
641
642MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
643 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000644 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000645 return nullptr;
646
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000647 ErrorOr<std::unique_ptr<File>> fileOrErr =
648 registry().loadFile(std::move(mbOrErr.get()));
649 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000650 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000651 std::unique_ptr<File> &file = fileOrErr.get();
652 file->parse();
653 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000654 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000655 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000656 return result;
657}
658
Nick Kledzik22c90732014-10-01 20:24:30 +0000659MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000660 // See if already loaded.
661 auto pos = _pathToDylibMap.find(path);
662 if (pos != _pathToDylibMap.end())
663 return pos->second;
664
665 // Search -L paths if of the form "libXXX.dylib"
666 std::pair<StringRef, StringRef> split = path.rsplit('/');
667 StringRef leafName = split.second;
668 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
669 // FIXME: Need to enhance searchLibrary() to only look for .dylib
670 auto libPath = searchLibrary(leafName);
671 if (!libPath.getError()) {
672 return loadIndirectDylib(libPath.get());
673 }
674 }
675
676 // Try full path with sysroot.
677 for (StringRef sysPath : _syslibRoots) {
678 SmallString<256> fullPath;
679 fullPath.assign(sysPath);
680 llvm::sys::path::append(fullPath, path);
681 if (pathExists(fullPath))
682 return loadIndirectDylib(fullPath);
683 }
684
685 // Try full path.
686 if (pathExists(path)) {
687 return loadIndirectDylib(path);
688 }
689
690 return nullptr;
691}
692
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000693uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
694 auto pos = _pathToDylibMap.find(installName);
695 if (pos != _pathToDylibMap.end())
696 return pos->second->currentVersion();
697 else
698 return 0x1000; // 1.0
699}
700
701uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
702 auto pos = _pathToDylibMap.find(installName);
703 if (pos != _pathToDylibMap.end())
704 return pos->second->compatVersion();
705 else
706 return 0x1000; // 1.0
707}
708
Simon Atanasyanc4378882015-04-06 20:43:35 +0000709void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000710 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000711 // Add indirect dylibs by asking each linked dylib to add its indirects.
712 // Iterate until no more dylibs get loaded.
713 size_t dylibCount = 0;
714 while (dylibCount != _allDylibs.size()) {
715 dylibCount = _allDylibs.size();
716 for (MachODylibFile *dylib : _allDylibs) {
717 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
718 return findIndirectDylib(path); });
719 }
720 }
721
722 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000723 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000724
Lang Hames9a4c94e2015-09-28 20:52:21 +0000725 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
726 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
727 if (undefinedMode() != UndefinedMode::error) {
728 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000729 _flatNamespaceFile = result.back().get();
730 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000731}
732
Nick Kledzik51720672014-10-16 19:31:28 +0000733void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
734 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000735 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000736 _allDylibs.insert(dylib);
737 _pathToDylibMap[dylib->installName()] = dylib;
738 // If path is different than install name, register path too.
739 if (!dylib->path().equals(dylib->installName()))
740 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000741 if (upward)
742 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000743}
744
Nick Kledzik51720672014-10-16 19:31:28 +0000745bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
746 for (MachODylibFile *dylib : _upwardDylibs) {
747 if (dylib->installName().equals(installName))
748 return true;
749 }
750 return false;
751}
752
Nick Kledzik2458bec2014-07-16 19:49:02 +0000753ArchHandler &MachOLinkingContext::archHandler() const {
754 if (!_archHandler)
755 _archHandler = ArchHandler::create(_arch);
756 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000757}
758
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000759void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000760 uint16_t align) {
761 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000762 _sectAligns.push_back(entry);
763}
764
Lang Hamesb1b67f42015-10-24 08:20:51 +0000765void MachOLinkingContext::addSectCreateSection(
766 StringRef seg, StringRef sect,
767 std::unique_ptr<MemoryBuffer> content) {
768
769 if (!_sectCreateFile) {
770 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
771 _sectCreateFile = sectCreateFile.get();
772 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
773 }
774
775 assert(_sectCreateFile && "sectcreate file does not exist.");
776 _sectCreateFile->addSection(seg, sect, std::move(content));
777}
778
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000779bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000780 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000781 for (const SectionAlign &entry : _sectAligns) {
782 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000783 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000784 return true;
785 }
786 }
787 return false;
788}
789
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000790void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000791 // Support old crufty export lists with bogus entries.
792 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
793 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
794 return;
795 }
796 // Only i386 MacOSX uses old ABI, so don't change those.
797 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
798 // ObjC has two differnent ABIs. Be nice and allow one export list work for
799 // both ABIs by renaming symbols.
800 if (sym.startswith(".objc_class_name_")) {
801 std::string abi2className("_OBJC_CLASS_$_");
802 abi2className += sym.substr(17);
803 _exportedSymbols.insert(copy(abi2className));
804 std::string abi2metaclassName("_OBJC_METACLASS_$_");
805 abi2metaclassName += sym.substr(17);
806 _exportedSymbols.insert(copy(abi2metaclassName));
807 return;
808 }
809 }
810
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000811 // FIXME: Support wildcards.
812 _exportedSymbols.insert(sym);
813}
814
815bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
816 switch (_exportMode) {
817 case ExportMode::globals:
818 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
819 break;
820 case ExportMode::whiteList:
821 return _exportedSymbols.count(sym);
822 case ExportMode::blackList:
823 return !_exportedSymbols.count(sym);
824 }
Yaron Keren9682c852014-09-21 05:07:44 +0000825 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000826}
827
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000828std::string MachOLinkingContext::demangle(StringRef symbolName) const {
829 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000830 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000831 return symbolName;
832
833 // Only try to demangle symbols that look like C++ symbols
834 if (!symbolName.startswith("__Z"))
835 return symbolName;
836
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000837#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000838 SmallString<256> symBuff;
839 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
840 // Mach-O has extra leading underscore that needs to be removed.
841 const char *cstr = nullTermSym.data() + 1;
842 int status;
843 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000844 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000845 std::string result(demangled);
846 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
847 free(demangled);
848 return result;
849 }
850#endif
851
852 return symbolName;
853}
854
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000855std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
856 std::error_code ec;
857 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
858 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
859 if (ec) {
860 _dependencyInfo.reset();
861 return ec;
862 }
863
864 char linkerVersionOpcode = 0x00;
865 *_dependencyInfo << linkerVersionOpcode;
866 *_dependencyInfo << "lld"; // FIXME
867 *_dependencyInfo << '\0';
868
869 return std::error_code();
870}
871
872void MachOLinkingContext::addInputFileDependency(StringRef path) const {
873 if (!_dependencyInfo)
874 return;
875
876 char inputFileOpcode = 0x10;
877 *_dependencyInfo << inputFileOpcode;
878 *_dependencyInfo << path;
879 *_dependencyInfo << '\0';
880}
881
882void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
883 if (!_dependencyInfo)
884 return;
885
886 char inputFileOpcode = 0x11;
887 *_dependencyInfo << inputFileOpcode;
888 *_dependencyInfo << path;
889 *_dependencyInfo << '\0';
890}
891
892void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
893 if (!_dependencyInfo)
894 return;
895
896 char outputFileOpcode = 0x40;
897 *_dependencyInfo << outputFileOpcode;
898 *_dependencyInfo << path;
899 *_dependencyInfo << '\0';
900}
901
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000902void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
903 StringRef filename) {
904 // To support sorting static functions which may have the same name in
905 // multiple .o files, _orderFiles maps the symbol name to a vector
906 // of OrderFileNode each of which can specify a file prefix.
907 OrderFileNode info;
908 if (!filename.empty())
909 info.fileFilter = copy(filename);
910 info.order = _orderFileEntries++;
911 _orderFiles[symbol].push_back(info);
912}
913
914bool
915MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
916 const DefinedAtom *atom,
917 unsigned &ordinal) {
918 const File *objFile = &atom->file();
919 assert(objFile);
920 StringRef objName = objFile->path();
921 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
922 if (!dirAndLeaf.second.empty())
923 objName = dirAndLeaf.second;
924 for (const OrderFileNode &info : nodes) {
925 if (info.fileFilter.empty()) {
926 // Have unprefixed symbol name in order file that matches this atom.
927 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000928 return true;
929 }
930 if (info.fileFilter.equals(objName)) {
931 // Have prefixed symbol name in order file that matches atom's path.
932 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000933 return true;
934 }
935 }
936 return false;
937}
938
939bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
940 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000941 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000942 // No custom sorting if no order file entries.
943 if (!_orderFileEntries)
944 return false;
945
946 // Order files can only order named atoms.
947 StringRef leftName = left->name();
948 StringRef rightName = right->name();
949 if (leftName.empty() || rightName.empty())
950 return false;
951
952 // If neither is in order file list, no custom sorter.
953 auto leftPos = _orderFiles.find(leftName);
954 auto rightPos = _orderFiles.find(rightName);
955 bool leftIsOrdered = (leftPos != _orderFiles.end());
956 bool rightIsOrdered = (rightPos != _orderFiles.end());
957 if (!leftIsOrdered && !rightIsOrdered)
958 return false;
959
960 // There could be multiple symbols with same name but different file prefixes.
961 unsigned leftOrder;
962 unsigned rightOrder;
963 bool foundLeft =
964 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
965 bool foundRight = rightIsOrdered &&
966 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
967 if (!foundLeft && !foundRight)
968 return false;
969
970 // If only one is in order file list, ordered one goes first.
971 if (foundLeft != foundRight)
972 leftBeforeRight = foundLeft;
973 else
974 leftBeforeRight = (leftOrder < rightOrder);
975
976 return true;
977}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000978
Rui Ueyama61635442015-01-15 08:31:46 +0000979static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000980 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
981 File *file = node->getFile();
982 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
983 }
984 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000985}
986
987// The darwin linker processes input files in two phases. The first phase
988// links in all object (.o) files in command line order. The second phase
989// links in libraries in command line order.
990// In this function we reorder the input files so that all the object files
991// comes before any library file. We also make a group for the library files
992// so that the Resolver will reiterate over the libraries as long as we find
993// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +0000994void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +0000995 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +0000996 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +0000997 [](const std::unique_ptr<Node> &a,
998 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +0000999 return !isLibrary(a) && isLibrary(b);
1000 });
1001 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1002 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1003}
1004
Pete Cooper80c09742016-01-14 21:53:13 +00001005std::error_code MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001006 auto *machoFile = dyn_cast<MachOFile>(&file);
1007 if (!machoFile)
1008 return std::error_code();
1009
1010 // Check that the arch of the context matches that of the file.
1011 // Also set the arch of the context if it didn't have one.
1012 if (_arch == arch_unknown) {
1013 _arch = machoFile->arch();
1014 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1015 // Archs are different.
1016 return make_dynamic_error_code(file.path() +
1017 Twine(" cannot be linked due to incompatible architecture"));
1018 }
1019
1020 // Check that the OS of the context matches that of the file.
1021 // Also set the OS of the context if it didn't have one.
1022 if (_os == OS::unknown) {
1023 _os = machoFile->OS();
1024 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1025 // OSes are different.
1026 return make_dynamic_error_code(file.path() +
1027 Twine(" cannot be linked due to incompatible operating systems"));
1028 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001029
Pete Cooper0872e462016-01-19 19:46:41 +00001030 // Check that if the objc info exists, that it is compatible with the target
1031 // OS.
1032 switch (machoFile->objcConstraint()) {
1033 case objc_unknown:
1034 // The file is not compiled with objc, so skip the checks.
1035 break;
1036 case objc_gc_only:
1037 case objc_supports_gc:
1038 llvm_unreachable("GC support should already have thrown an error");
1039 case objc_retainReleaseForSimulator:
1040 // The file is built with simulator objc, so make sure that the context
1041 // is also building with simulator support.
1042 if (_os != OS::iOS_simulator)
1043 return make_dynamic_error_code(file.path() +
1044 Twine(" cannot be linked. It contains ObjC built for the simulator"
1045 " while we are linking a non-simulator target"));
1046 assert((_objcConstraint == objc_unknown ||
1047 _objcConstraint == objc_retainReleaseForSimulator) &&
1048 "Must be linking with retain/release for the simulator");
1049 _objcConstraint = objc_retainReleaseForSimulator;
1050 break;
1051 case objc_retainRelease:
1052 // The file is built without simulator objc, so make sure that the
1053 // context is also building without simulator support.
1054 if (_os == OS::iOS_simulator)
1055 return make_dynamic_error_code(file.path() +
1056 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1057 " target while we are linking a simulator target"));
1058 assert((_objcConstraint == objc_unknown ||
1059 _objcConstraint == objc_retainRelease) &&
1060 "Must be linking with retain/release for a non-simulator target");
1061 _objcConstraint = objc_retainRelease;
1062 break;
1063 }
1064
Pete Coopera014ffe2016-01-16 00:07:22 +00001065 // Check that the swift version of the context matches that of the file.
1066 // Also set the swift version of the context if it didn't have one.
1067 if (!_swiftVersion) {
1068 _swiftVersion = machoFile->swiftVersion();
1069 } else if (machoFile->swiftVersion() &&
1070 machoFile->swiftVersion() != _swiftVersion) {
1071 // Swift versions are different.
1072 return make_dynamic_error_code("different swift versions");
1073 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001074
Pete Cooper80c09742016-01-14 21:53:13 +00001075 return std::error_code();
1076}
1077
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001078} // end namespace lld