blob: c758612358d202d61f15f2b2ebb3f4e8ec224836 [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.
Pete Cooper3dd478a2016-02-04 01:57:59 +0000166 // Note that we only do sensible defaults when emitting something other than
167 // object and preload.
168 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
169 _outputMachOType != llvm::MachO::MH_PRELOAD) {
170 if (minOSVersion == 0) {
171 switch (_arch) {
172 case arch_x86_64:
173 case arch_x86:
174 parsePackedVersion("10.8", _osMinVersion);
175 _os = MachOLinkingContext::OS::macOSX;
176 break;
177 case arch_armv6:
178 case arch_armv7:
179 case arch_armv7s:
180 case arch_arm64:
181 parsePackedVersion("7.0", _osMinVersion);
182 _os = MachOLinkingContext::OS::iOS;
183 break;
184 default:
185 break;
186 }
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000187 }
188 }
189
Tim Northoverd30a1f22014-06-20 15:59:00 +0000190 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000191 case llvm::MachO::MH_EXECUTE:
192 // If targeting newer OS, use _main
193 if (minOS("10.8", "6.0")) {
194 _entrySymbolName = "_main";
195 } else {
196 // If targeting older OS, use start (in crt1.o)
197 _entrySymbolName = "start";
198 }
199
200 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
201 // support) and 4KB on 32-bit.
202 if (is64Bit(_arch)) {
203 _pageZeroSize = 0x100000000;
204 } else {
205 _pageZeroSize = 0x1000;
206 }
207
Lang Hamesc80344282015-09-21 22:06:02 +0000208 // Initial base address is __PAGEZERO size.
209 _baseAddress = _pageZeroSize;
210
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000211 // Make PIE by default when targetting newer OSs.
212 switch (os) {
213 case OS::macOSX:
214 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
215 _pie = true;
216 break;
217 case OS::iOS:
218 if (minOSVersion >= 0x00040300) // iOS 4.3
219 _pie = true;
220 break;
221 case OS::iOS_simulator:
222 _pie = true;
223 break;
224 case OS::unknown:
225 break;
226 }
Pete Cooper35116452016-01-22 21:13:24 +0000227 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000228 break;
229 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000230 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000231 break;
232 case llvm::MachO::MH_BUNDLE:
233 break;
234 case llvm::MachO::MH_OBJECT:
235 _printRemainingUndefines = false;
236 _allowRemainingUndefines = true;
237 default:
238 break;
239 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000240
241 // Set default segment page sizes based on arch.
242 if (arch == arch_arm64)
243 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000244}
245
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000246uint32_t MachOLinkingContext::getCPUType() const {
247 return cpuTypeFromArch(_arch);
248}
249
250uint32_t MachOLinkingContext::getCPUSubType() const {
251 return cpuSubtypeFromArch(_arch);
252}
253
Nick Kledzike34182f2013-11-06 21:36:55 +0000254bool MachOLinkingContext::is64Bit(Arch arch) {
255 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
256 if (info->arch == arch) {
257 return (info->cputype & CPU_ARCH_ABI64);
258 }
259 }
260 // unknown archs are not 64-bit.
261 return false;
262}
263
264bool MachOLinkingContext::isHostEndian(Arch arch) {
265 assert(arch != arch_unknown);
266 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
267 if (info->arch == arch) {
268 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
269 }
270 }
271 llvm_unreachable("Unknown arch type");
272}
273
274bool MachOLinkingContext::isBigEndian(Arch arch) {
275 assert(arch != arch_unknown);
276 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
277 if (info->arch == arch) {
278 return ! info->littleEndian;
279 }
280 }
281 llvm_unreachable("Unknown arch type");
282}
283
Nick Kledzike34182f2013-11-06 21:36:55 +0000284bool MachOLinkingContext::is64Bit() const {
285 return is64Bit(_arch);
286}
287
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000288bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000289 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000290 case MH_EXECUTE:
291 case MH_DYLINKER:
292 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000293 return true;
294 default:
295 return false;
296 }
297}
298
Nick Kledzik2458bec2014-07-16 19:49:02 +0000299bool MachOLinkingContext::needsStubsPass() const {
300 switch (_outputMachOType) {
301 case MH_EXECUTE:
302 return !_outputMachOTypeStatic;
303 case MH_DYLIB:
304 case MH_BUNDLE:
305 return true;
306 default:
307 return false;
308 }
309}
310
311bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000312 // GOT pass not used in -r mode.
313 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000314 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000315 // Only some arches use GOT pass.
316 switch (_arch) {
317 case arch_x86_64:
318 case arch_arm64:
319 return true;
320 default:
321 return false;
322 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000323}
324
Tim Northovercf78d372014-09-30 21:29:54 +0000325bool MachOLinkingContext::needsCompactUnwindPass() const {
326 switch (_outputMachOType) {
327 case MH_EXECUTE:
328 case MH_DYLIB:
329 case MH_BUNDLE:
330 return archHandler().needsCompactUnwind();
331 default:
332 return false;
333 }
334}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000335
Pete Cooper90dbab02016-01-19 21:54:21 +0000336bool MachOLinkingContext::needsObjCPass() const {
337 // ObjC pass is only needed if any of the inputs were ObjC.
338 return _objcConstraint != objc_unknown;
339}
340
Nick Kledzik4121bce2014-10-14 01:51:42 +0000341bool MachOLinkingContext::needsShimPass() const {
342 // Shim pass only used in final executables.
343 if (_outputMachOType == MH_OBJECT)
344 return false;
345 // Only 32-bit arm arches use Shim pass.
346 switch (_arch) {
347 case arch_armv6:
348 case arch_armv7:
349 case arch_armv7s:
350 return true;
351 default:
352 return false;
353 }
354}
355
Lang Hames49047032015-06-23 20:35:31 +0000356bool MachOLinkingContext::needsTLVPass() const {
357 switch (_outputMachOType) {
358 case MH_BUNDLE:
359 case MH_EXECUTE:
360 case MH_DYLIB:
361 return true;
362 default:
363 return false;
364 }
365}
366
Nick Kledzik2458bec2014-07-16 19:49:02 +0000367StringRef MachOLinkingContext::binderSymbolName() const {
368 return archHandler().stubInfo().binderSymbolName;
369}
370
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000371bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000372 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000373 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000374 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000375 if (parsePackedVersion(mac, parsedVersion))
376 return false;
377 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000378 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000379 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000380 if (parsePackedVersion(iOS, parsedVersion))
381 return false;
382 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000383 case OS::unknown:
Pete Cooper3dd478a2016-02-04 01:57:59 +0000384 // If we don't know the target, then assume that we don't meet the min OS.
385 // This matches the ld64 behaviour
386 return false;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000387 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000388}
389
390bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000391 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000392 return minOS("10.8", "6.0");
393 }
394 return false;
395}
396
397bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000398 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000399 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000400 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000401 return true;
402 else
403 return !minOS("10.8", "6.0");
404 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000405 case MH_DYLINKER:
406 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000407 return true;
408 default:
409 return false;
410 }
411}
412
Tim Northover77d82202014-07-10 11:21:06 +0000413bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000414 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000415 return llvm::sys::fs::exists(path.str());
416
417 // Otherwise, we're in test mode: only files explicitly provided on the
418 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000419 std::string key = path.str();
420 std::replace(key.begin(), key.end(), '\\', '/');
421 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000422}
423
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000424bool MachOLinkingContext::fileExists(StringRef path) const {
425 bool found = pathExists(path);
426 // Log search misses.
427 if (!found)
428 addInputFileNotFound(path);
429
430 // When testing, file is never opened, so logging is done here.
431 if (_testingFileUsage && found)
432 addInputFileDependency(path);
433
434 return found;
435}
436
Nick Kledzik2d835da2014-08-14 22:20:41 +0000437void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
438 _syslibRoots = paths;
439}
440
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000441void MachOLinkingContext::addRpath(StringRef rpath) {
442 _rpaths.push_back(rpath);
443}
444
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000445void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
446 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000447 bool addedModifiedPath = false;
448
Nick Kledzik2d835da2014-08-14 22:20:41 +0000449 // -syslibroot only applies to absolute paths.
450 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000451 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000452 SmallString<256> path(syslibRoot);
453 llvm::sys::path::append(path, libPath);
454 if (pathExists(path)) {
455 _searchDirs.push_back(path.str().copy(_allocator));
456 addedModifiedPath = true;
457 }
458 }
459 }
460
461 if (addedModifiedPath)
462 return;
463
464 // Finally, if only one -syslibroot is given, system paths which aren't in it
465 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000466 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000467 if (pathExists(libPath)) {
468 _searchDirs.push_back(libPath);
469 }
470 }
471}
472
Nick Kledzik2d835da2014-08-14 22:20:41 +0000473void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
474 bool isSystemPath) {
475 bool pathAdded = false;
476
477 // -syslibroot only used with to absolute framework search paths.
478 if (fwPath.startswith("/")) {
479 for (auto syslibRoot : _syslibRoots) {
480 SmallString<256> path(syslibRoot);
481 llvm::sys::path::append(path, fwPath);
482 if (pathExists(path)) {
483 _frameworkDirs.push_back(path.str().copy(_allocator));
484 pathAdded = true;
485 }
486 }
487 }
488 // If fwPath found in any -syslibroot, then done.
489 if (pathAdded)
490 return;
491
492 // If only one -syslibroot, system paths not in that SDK are suppressed.
493 if (isSystemPath && (_syslibRoots.size() == 1))
494 return;
495
496 // Only use raw fwPath if that directory exists.
497 if (pathExists(fwPath))
498 _frameworkDirs.push_back(fwPath);
499}
500
Tim Northover77d82202014-07-10 11:21:06 +0000501ErrorOr<StringRef>
502MachOLinkingContext::searchDirForLibrary(StringRef path,
503 StringRef libName) const {
504 SmallString<256> fullPath;
505 if (libName.endswith(".o")) {
506 // A request ending in .o is special: just search for the file directly.
507 fullPath.assign(path);
508 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000509 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000510 return fullPath.str().copy(_allocator);
511 return make_error_code(llvm::errc::no_such_file_or_directory);
512 }
513
514 // Search for dynamic library
515 fullPath.assign(path);
516 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
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 // If not, try for a static library
521 fullPath.assign(path);
522 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000523 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000524 return fullPath.str().copy(_allocator);
525
526 return make_error_code(llvm::errc::no_such_file_or_directory);
527}
528
Tim Northover77d82202014-07-10 11:21:06 +0000529ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
530 SmallString<256> path;
531 for (StringRef dir : searchDirs()) {
532 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
533 if (ec)
534 return ec;
535 }
536
537 return make_error_code(llvm::errc::no_such_file_or_directory);
538}
539
Nick Kledzik2d835da2014-08-14 22:20:41 +0000540ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
541 SmallString<256> fullPath;
542 for (StringRef dir : frameworkDirs()) {
543 fullPath.assign(dir);
544 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000545 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000546 return fullPath.str().copy(_allocator);
547 }
548
549 return make_error_code(llvm::errc::no_such_file_or_directory);
550}
551
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000552bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000553 // TODO: if -arch not specified, look at arch of first .o file.
554
Tim Northoverd30a1f22014-06-20 15:59:00 +0000555 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000556 diagnostics << "error: -current_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 (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000561 diagnostics
562 << "error: -compatibility_version 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 (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000567 diagnostics
568 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000569 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000570 }
571
Tim Northoverd30a1f22014-06-20 15:59:00 +0000572 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000573 diagnostics
574 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000575 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000576 }
577
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000578 // If -exported_symbols_list used, all exported symbols must be defined.
579 if (_exportMode == ExportMode::whiteList) {
580 for (const auto &symbol : _exportedSymbols)
581 addInitialUndefinedSymbol(symbol.getKey());
582 }
583
Nick Kledzik77afc712014-08-21 20:25:50 +0000584 // If -dead_strip, set up initial live symbols.
585 if (deadStrip()) {
586 // Entry point is live.
587 if (outputTypeHasEntry())
588 addDeadStripRoot(entrySymbolName());
589 // Lazy binding helper is live.
590 if (needsStubsPass())
591 addDeadStripRoot(binderSymbolName());
592 // If using -exported_symbols_list, make all exported symbols live.
593 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000594 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000595 for (const auto &symbol : _exportedSymbols)
596 addDeadStripRoot(symbol.getKey());
597 }
598 }
599
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000600 addOutputFileDependency(outputPath());
601
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000602 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000603}
604
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000605void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000606 // objc pass should be before layout pass. Otherwise test cases may contain
607 // no atoms which confuses the layout pass.
608 if (needsObjCPass())
609 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000610 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000611 if (needsStubsPass())
612 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000613 if (needsCompactUnwindPass())
614 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000615 if (needsGOTPass())
616 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000617 if (needsTLVPass())
618 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000619 if (needsShimPass())
620 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000621}
622
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000623Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000624 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000625 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000626 return *_writer;
627}
628
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000629ErrorOr<std::unique_ptr<MemoryBuffer>>
630MachOLinkingContext::getMemoryBuffer(StringRef path) {
631 addInputFileDependency(path);
632
Rui Ueyamadf230b22015-01-15 04:34:31 +0000633 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000634 MemoryBuffer::getFileOrSTDIN(path);
635 if (std::error_code ec = mbOrErr.getError())
636 return ec;
637 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
638
639 // If buffer contains a fat file, find required arch in fat buffer
640 // and switch buffer to point to just that required slice.
641 uint32_t offset;
642 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000643 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000644 return MemoryBuffer::getFileSlice(path, size, offset);
645 return std::move(mb);
646}
647
648MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
649 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000650 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000651 return nullptr;
652
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000653 ErrorOr<std::unique_ptr<File>> fileOrErr =
654 registry().loadFile(std::move(mbOrErr.get()));
655 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000656 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000657 std::unique_ptr<File> &file = fileOrErr.get();
658 file->parse();
659 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000660 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000661 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000662 return result;
663}
664
Nick Kledzik22c90732014-10-01 20:24:30 +0000665MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000666 // See if already loaded.
667 auto pos = _pathToDylibMap.find(path);
668 if (pos != _pathToDylibMap.end())
669 return pos->second;
670
671 // Search -L paths if of the form "libXXX.dylib"
672 std::pair<StringRef, StringRef> split = path.rsplit('/');
673 StringRef leafName = split.second;
674 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
675 // FIXME: Need to enhance searchLibrary() to only look for .dylib
676 auto libPath = searchLibrary(leafName);
677 if (!libPath.getError()) {
678 return loadIndirectDylib(libPath.get());
679 }
680 }
681
682 // Try full path with sysroot.
683 for (StringRef sysPath : _syslibRoots) {
684 SmallString<256> fullPath;
685 fullPath.assign(sysPath);
686 llvm::sys::path::append(fullPath, path);
687 if (pathExists(fullPath))
688 return loadIndirectDylib(fullPath);
689 }
690
691 // Try full path.
692 if (pathExists(path)) {
693 return loadIndirectDylib(path);
694 }
695
696 return nullptr;
697}
698
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000699uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
700 auto pos = _pathToDylibMap.find(installName);
701 if (pos != _pathToDylibMap.end())
702 return pos->second->currentVersion();
703 else
704 return 0x1000; // 1.0
705}
706
707uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
708 auto pos = _pathToDylibMap.find(installName);
709 if (pos != _pathToDylibMap.end())
710 return pos->second->compatVersion();
711 else
712 return 0x1000; // 1.0
713}
714
Simon Atanasyanc4378882015-04-06 20:43:35 +0000715void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000716 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000717 // Add indirect dylibs by asking each linked dylib to add its indirects.
718 // Iterate until no more dylibs get loaded.
719 size_t dylibCount = 0;
720 while (dylibCount != _allDylibs.size()) {
721 dylibCount = _allDylibs.size();
722 for (MachODylibFile *dylib : _allDylibs) {
723 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
724 return findIndirectDylib(path); });
725 }
726 }
727
728 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000729 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000730
Lang Hames9a4c94e2015-09-28 20:52:21 +0000731 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
732 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
733 if (undefinedMode() != UndefinedMode::error) {
734 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000735 _flatNamespaceFile = result.back().get();
736 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000737}
738
Nick Kledzik51720672014-10-16 19:31:28 +0000739void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
740 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000741 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000742 _allDylibs.insert(dylib);
743 _pathToDylibMap[dylib->installName()] = dylib;
744 // If path is different than install name, register path too.
745 if (!dylib->path().equals(dylib->installName()))
746 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000747 if (upward)
748 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000749}
750
Nick Kledzik51720672014-10-16 19:31:28 +0000751bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
752 for (MachODylibFile *dylib : _upwardDylibs) {
753 if (dylib->installName().equals(installName))
754 return true;
755 }
756 return false;
757}
758
Nick Kledzik2458bec2014-07-16 19:49:02 +0000759ArchHandler &MachOLinkingContext::archHandler() const {
760 if (!_archHandler)
761 _archHandler = ArchHandler::create(_arch);
762 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000763}
764
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000765void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000766 uint16_t align) {
767 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000768 _sectAligns.push_back(entry);
769}
770
Lang Hamesb1b67f42015-10-24 08:20:51 +0000771void MachOLinkingContext::addSectCreateSection(
772 StringRef seg, StringRef sect,
773 std::unique_ptr<MemoryBuffer> content) {
774
775 if (!_sectCreateFile) {
776 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
777 _sectCreateFile = sectCreateFile.get();
778 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
779 }
780
781 assert(_sectCreateFile && "sectcreate file does not exist.");
782 _sectCreateFile->addSection(seg, sect, std::move(content));
783}
784
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000785bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000786 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000787 for (const SectionAlign &entry : _sectAligns) {
788 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000789 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000790 return true;
791 }
792 }
793 return false;
794}
795
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000796void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000797 // Support old crufty export lists with bogus entries.
798 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
799 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
800 return;
801 }
802 // Only i386 MacOSX uses old ABI, so don't change those.
803 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
804 // ObjC has two differnent ABIs. Be nice and allow one export list work for
805 // both ABIs by renaming symbols.
806 if (sym.startswith(".objc_class_name_")) {
807 std::string abi2className("_OBJC_CLASS_$_");
808 abi2className += sym.substr(17);
809 _exportedSymbols.insert(copy(abi2className));
810 std::string abi2metaclassName("_OBJC_METACLASS_$_");
811 abi2metaclassName += sym.substr(17);
812 _exportedSymbols.insert(copy(abi2metaclassName));
813 return;
814 }
815 }
816
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000817 // FIXME: Support wildcards.
818 _exportedSymbols.insert(sym);
819}
820
821bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
822 switch (_exportMode) {
823 case ExportMode::globals:
824 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
825 break;
826 case ExportMode::whiteList:
827 return _exportedSymbols.count(sym);
828 case ExportMode::blackList:
829 return !_exportedSymbols.count(sym);
830 }
Yaron Keren9682c852014-09-21 05:07:44 +0000831 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000832}
833
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000834std::string MachOLinkingContext::demangle(StringRef symbolName) const {
835 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000836 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000837 return symbolName;
838
839 // Only try to demangle symbols that look like C++ symbols
840 if (!symbolName.startswith("__Z"))
841 return symbolName;
842
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000843#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000844 SmallString<256> symBuff;
845 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
846 // Mach-O has extra leading underscore that needs to be removed.
847 const char *cstr = nullTermSym.data() + 1;
848 int status;
849 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000850 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000851 std::string result(demangled);
852 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
853 free(demangled);
854 return result;
855 }
856#endif
857
858 return symbolName;
859}
860
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000861std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
862 std::error_code ec;
863 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
864 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
865 if (ec) {
866 _dependencyInfo.reset();
867 return ec;
868 }
869
870 char linkerVersionOpcode = 0x00;
871 *_dependencyInfo << linkerVersionOpcode;
872 *_dependencyInfo << "lld"; // FIXME
873 *_dependencyInfo << '\0';
874
875 return std::error_code();
876}
877
878void MachOLinkingContext::addInputFileDependency(StringRef path) const {
879 if (!_dependencyInfo)
880 return;
881
882 char inputFileOpcode = 0x10;
883 *_dependencyInfo << inputFileOpcode;
884 *_dependencyInfo << path;
885 *_dependencyInfo << '\0';
886}
887
888void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
889 if (!_dependencyInfo)
890 return;
891
892 char inputFileOpcode = 0x11;
893 *_dependencyInfo << inputFileOpcode;
894 *_dependencyInfo << path;
895 *_dependencyInfo << '\0';
896}
897
898void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
899 if (!_dependencyInfo)
900 return;
901
902 char outputFileOpcode = 0x40;
903 *_dependencyInfo << outputFileOpcode;
904 *_dependencyInfo << path;
905 *_dependencyInfo << '\0';
906}
907
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000908void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
909 StringRef filename) {
910 // To support sorting static functions which may have the same name in
911 // multiple .o files, _orderFiles maps the symbol name to a vector
912 // of OrderFileNode each of which can specify a file prefix.
913 OrderFileNode info;
914 if (!filename.empty())
915 info.fileFilter = copy(filename);
916 info.order = _orderFileEntries++;
917 _orderFiles[symbol].push_back(info);
918}
919
920bool
921MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
922 const DefinedAtom *atom,
923 unsigned &ordinal) {
924 const File *objFile = &atom->file();
925 assert(objFile);
926 StringRef objName = objFile->path();
927 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
928 if (!dirAndLeaf.second.empty())
929 objName = dirAndLeaf.second;
930 for (const OrderFileNode &info : nodes) {
931 if (info.fileFilter.empty()) {
932 // Have unprefixed symbol name in order file that matches this atom.
933 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000934 return true;
935 }
936 if (info.fileFilter.equals(objName)) {
937 // Have prefixed symbol name in order file that matches atom's path.
938 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000939 return true;
940 }
941 }
942 return false;
943}
944
945bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
946 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000947 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000948 // No custom sorting if no order file entries.
949 if (!_orderFileEntries)
950 return false;
951
952 // Order files can only order named atoms.
953 StringRef leftName = left->name();
954 StringRef rightName = right->name();
955 if (leftName.empty() || rightName.empty())
956 return false;
957
958 // If neither is in order file list, no custom sorter.
959 auto leftPos = _orderFiles.find(leftName);
960 auto rightPos = _orderFiles.find(rightName);
961 bool leftIsOrdered = (leftPos != _orderFiles.end());
962 bool rightIsOrdered = (rightPos != _orderFiles.end());
963 if (!leftIsOrdered && !rightIsOrdered)
964 return false;
965
966 // There could be multiple symbols with same name but different file prefixes.
967 unsigned leftOrder;
968 unsigned rightOrder;
969 bool foundLeft =
970 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
971 bool foundRight = rightIsOrdered &&
972 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
973 if (!foundLeft && !foundRight)
974 return false;
975
976 // If only one is in order file list, ordered one goes first.
977 if (foundLeft != foundRight)
978 leftBeforeRight = foundLeft;
979 else
980 leftBeforeRight = (leftOrder < rightOrder);
981
982 return true;
983}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000984
Rui Ueyama61635442015-01-15 08:31:46 +0000985static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000986 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
987 File *file = node->getFile();
988 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
989 }
990 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000991}
992
993// The darwin linker processes input files in two phases. The first phase
994// links in all object (.o) files in command line order. The second phase
995// links in libraries in command line order.
996// In this function we reorder the input files so that all the object files
997// comes before any library file. We also make a group for the library files
998// so that the Resolver will reiterate over the libraries as long as we find
999// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +00001000void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +00001001 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +00001002 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +00001003 [](const std::unique_ptr<Node> &a,
1004 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +00001005 return !isLibrary(a) && isLibrary(b);
1006 });
1007 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1008 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1009}
1010
Pete Cooper80c09742016-01-14 21:53:13 +00001011std::error_code MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001012 auto *machoFile = dyn_cast<MachOFile>(&file);
1013 if (!machoFile)
1014 return std::error_code();
1015
1016 // Check that the arch of the context matches that of the file.
1017 // Also set the arch of the context if it didn't have one.
1018 if (_arch == arch_unknown) {
1019 _arch = machoFile->arch();
1020 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1021 // Archs are different.
1022 return make_dynamic_error_code(file.path() +
1023 Twine(" cannot be linked due to incompatible architecture"));
1024 }
1025
1026 // Check that the OS of the context matches that of the file.
1027 // Also set the OS of the context if it didn't have one.
1028 if (_os == OS::unknown) {
1029 _os = machoFile->OS();
1030 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1031 // OSes are different.
1032 return make_dynamic_error_code(file.path() +
1033 Twine(" cannot be linked due to incompatible operating systems"));
1034 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001035
Pete Cooper0872e462016-01-19 19:46:41 +00001036 // Check that if the objc info exists, that it is compatible with the target
1037 // OS.
1038 switch (machoFile->objcConstraint()) {
1039 case objc_unknown:
1040 // The file is not compiled with objc, so skip the checks.
1041 break;
1042 case objc_gc_only:
1043 case objc_supports_gc:
1044 llvm_unreachable("GC support should already have thrown an error");
1045 case objc_retainReleaseForSimulator:
1046 // The file is built with simulator objc, so make sure that the context
1047 // is also building with simulator support.
1048 if (_os != OS::iOS_simulator)
1049 return make_dynamic_error_code(file.path() +
1050 Twine(" cannot be linked. It contains ObjC built for the simulator"
1051 " while we are linking a non-simulator target"));
1052 assert((_objcConstraint == objc_unknown ||
1053 _objcConstraint == objc_retainReleaseForSimulator) &&
1054 "Must be linking with retain/release for the simulator");
1055 _objcConstraint = objc_retainReleaseForSimulator;
1056 break;
1057 case objc_retainRelease:
1058 // The file is built without simulator objc, so make sure that the
1059 // context is also building without simulator support.
1060 if (_os == OS::iOS_simulator)
1061 return make_dynamic_error_code(file.path() +
1062 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1063 " target while we are linking a simulator target"));
1064 assert((_objcConstraint == objc_unknown ||
1065 _objcConstraint == objc_retainRelease) &&
1066 "Must be linking with retain/release for a non-simulator target");
1067 _objcConstraint = objc_retainRelease;
1068 break;
1069 }
1070
Pete Coopera014ffe2016-01-16 00:07:22 +00001071 // Check that the swift version of the context matches that of the file.
1072 // Also set the swift version of the context if it didn't have one.
1073 if (!_swiftVersion) {
1074 _swiftVersion = machoFile->swiftVersion();
1075 } else if (machoFile->swiftVersion() &&
1076 machoFile->swiftVersion() != _swiftVersion) {
1077 // Swift versions are different.
1078 return make_dynamic_error_code("different swift versions");
1079 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001080
Pete Cooper80c09742016-01-14 21:53:13 +00001081 return std::error_code();
1082}
1083
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001084} // end namespace lld