blob: 5e7db8f052dfbd7ac201fea5aafaaeda5cbcfa23 [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
Pete Cooper40576fa2016-02-04 02:45:23 +000079bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
80 result = 0;
81
82 if (str.empty())
83 return false;
84
85 SmallVector<StringRef, 5> parts;
86 llvm::SplitString(str, parts, ".");
87
88 uint64_t num;
89 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
90 return true;
91 if (num > 0xFFFFFF)
92 return true;
93 result = num << 40;
94
95 unsigned Shift = 30;
96 for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
97 if (llvm::getAsUnsignedInteger(str, 10, num))
98 return true;
99 if (num > 0x3FF)
100 return true;
101 result |= (num << Shift);
102 Shift -= 10;
103 }
104
105 return false;
106}
107
Nick Kledzike34182f2013-11-06 21:36:55 +0000108MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
109 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
110 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
111 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
112 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
113 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
114 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +0000115 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +0000116 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000117};
118
119MachOLinkingContext::Arch
120MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000121 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
122 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000123 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000124 }
125 return arch_unknown;
126}
127
128MachOLinkingContext::Arch
129MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000130 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
131 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000132 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000133 }
134 return arch_unknown;
135}
136
Nick Kledzike5552772013-12-19 21:58:00 +0000137StringRef MachOLinkingContext::nameFromArch(Arch arch) {
138 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
139 if (info->arch == arch)
140 return info->archName;
141 }
142 return "<unknown>";
143}
144
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000145uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
146 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000147 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
148 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000149 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000150 }
151 llvm_unreachable("Unknown arch type");
152}
153
154uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
155 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000156 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
157 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000158 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000159 }
160 llvm_unreachable("Unknown arch type");
161}
162
Nick Kledzik635f9c72014-09-04 20:08:30 +0000163bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
164 return mach_o::normalized::isThinObjectFile(path, arch);
165}
166
Rafael Espindolaed48e532015-04-27 22:48:51 +0000167bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000168 uint32_t &size) {
169 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
170}
171
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000172MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000173 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000174 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
175 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
Lang Hamesff4b13c2015-05-22 00:25:34 +0000176 _stackSize(0), _compatibilityVersion(0), _currentVersion(0),
Pete Cooperfeaa9672016-01-19 18:46:40 +0000177 _objcConstraint(objc_unknown), _swiftVersion(0), _flatNamespace(false),
178 _undefinedMode(UndefinedMode::error), _deadStrippableDylib(false),
179 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
180 _demangle(false), _archHandler(nullptr), _exportMode(ExportMode::globals),
Lang Hames5c692002015-09-28 20:25:14 +0000181 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0),
182 _flatNamespaceFile(nullptr) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000183
184MachOLinkingContext::~MachOLinkingContext() {}
185
Nick Kledzik6960b072013-12-21 01:47:17 +0000186void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
Pete Cooper35116452016-01-22 21:13:24 +0000187 uint32_t minOSVersion,
188 bool exportDynamicSymbols) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000189 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000190 _arch = arch;
191 _os = os;
192 _osMinVersion = minOSVersion;
193
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000194 // If min OS not specified on command line, use reasonable defaults.
Pete Cooper3dd478a2016-02-04 01:57:59 +0000195 // Note that we only do sensible defaults when emitting something other than
196 // object and preload.
197 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
198 _outputMachOType != llvm::MachO::MH_PRELOAD) {
199 if (minOSVersion == 0) {
200 switch (_arch) {
201 case arch_x86_64:
202 case arch_x86:
203 parsePackedVersion("10.8", _osMinVersion);
204 _os = MachOLinkingContext::OS::macOSX;
205 break;
206 case arch_armv6:
207 case arch_armv7:
208 case arch_armv7s:
209 case arch_arm64:
210 parsePackedVersion("7.0", _osMinVersion);
211 _os = MachOLinkingContext::OS::iOS;
212 break;
213 default:
214 break;
215 }
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000216 }
217 }
218
Tim Northoverd30a1f22014-06-20 15:59:00 +0000219 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000220 case llvm::MachO::MH_EXECUTE:
221 // If targeting newer OS, use _main
222 if (minOS("10.8", "6.0")) {
223 _entrySymbolName = "_main";
224 } else {
225 // If targeting older OS, use start (in crt1.o)
226 _entrySymbolName = "start";
227 }
228
229 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
230 // support) and 4KB on 32-bit.
231 if (is64Bit(_arch)) {
232 _pageZeroSize = 0x100000000;
233 } else {
234 _pageZeroSize = 0x1000;
235 }
236
Lang Hamesc80344282015-09-21 22:06:02 +0000237 // Initial base address is __PAGEZERO size.
238 _baseAddress = _pageZeroSize;
239
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000240 // Make PIE by default when targetting newer OSs.
241 switch (os) {
242 case OS::macOSX:
243 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
244 _pie = true;
245 break;
246 case OS::iOS:
247 if (minOSVersion >= 0x00040300) // iOS 4.3
248 _pie = true;
249 break;
250 case OS::iOS_simulator:
251 _pie = true;
252 break;
253 case OS::unknown:
254 break;
255 }
Pete Cooper35116452016-01-22 21:13:24 +0000256 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000257 break;
258 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000259 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000260 break;
261 case llvm::MachO::MH_BUNDLE:
262 break;
263 case llvm::MachO::MH_OBJECT:
264 _printRemainingUndefines = false;
265 _allowRemainingUndefines = true;
266 default:
267 break;
268 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000269
270 // Set default segment page sizes based on arch.
271 if (arch == arch_arm64)
272 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000273}
274
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000275uint32_t MachOLinkingContext::getCPUType() const {
276 return cpuTypeFromArch(_arch);
277}
278
279uint32_t MachOLinkingContext::getCPUSubType() const {
280 return cpuSubtypeFromArch(_arch);
281}
282
Nick Kledzike34182f2013-11-06 21:36:55 +0000283bool MachOLinkingContext::is64Bit(Arch arch) {
284 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
285 if (info->arch == arch) {
286 return (info->cputype & CPU_ARCH_ABI64);
287 }
288 }
289 // unknown archs are not 64-bit.
290 return false;
291}
292
293bool MachOLinkingContext::isHostEndian(Arch arch) {
294 assert(arch != arch_unknown);
295 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
296 if (info->arch == arch) {
297 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
298 }
299 }
300 llvm_unreachable("Unknown arch type");
301}
302
303bool MachOLinkingContext::isBigEndian(Arch arch) {
304 assert(arch != arch_unknown);
305 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
306 if (info->arch == arch) {
307 return ! info->littleEndian;
308 }
309 }
310 llvm_unreachable("Unknown arch type");
311}
312
Nick Kledzike34182f2013-11-06 21:36:55 +0000313bool MachOLinkingContext::is64Bit() const {
314 return is64Bit(_arch);
315}
316
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000317bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000318 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000319 case MH_EXECUTE:
320 case MH_DYLINKER:
321 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000322 return true;
323 default:
324 return false;
325 }
326}
327
Nick Kledzik2458bec2014-07-16 19:49:02 +0000328bool MachOLinkingContext::needsStubsPass() const {
329 switch (_outputMachOType) {
330 case MH_EXECUTE:
331 return !_outputMachOTypeStatic;
332 case MH_DYLIB:
333 case MH_BUNDLE:
334 return true;
335 default:
336 return false;
337 }
338}
339
340bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000341 // GOT pass not used in -r mode.
342 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000343 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000344 // Only some arches use GOT pass.
345 switch (_arch) {
346 case arch_x86_64:
347 case arch_arm64:
348 return true;
349 default:
350 return false;
351 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000352}
353
Tim Northovercf78d372014-09-30 21:29:54 +0000354bool MachOLinkingContext::needsCompactUnwindPass() const {
355 switch (_outputMachOType) {
356 case MH_EXECUTE:
357 case MH_DYLIB:
358 case MH_BUNDLE:
359 return archHandler().needsCompactUnwind();
360 default:
361 return false;
362 }
363}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000364
Pete Cooper90dbab02016-01-19 21:54:21 +0000365bool MachOLinkingContext::needsObjCPass() const {
366 // ObjC pass is only needed if any of the inputs were ObjC.
367 return _objcConstraint != objc_unknown;
368}
369
Nick Kledzik4121bce2014-10-14 01:51:42 +0000370bool MachOLinkingContext::needsShimPass() const {
371 // Shim pass only used in final executables.
372 if (_outputMachOType == MH_OBJECT)
373 return false;
374 // Only 32-bit arm arches use Shim pass.
375 switch (_arch) {
376 case arch_armv6:
377 case arch_armv7:
378 case arch_armv7s:
379 return true;
380 default:
381 return false;
382 }
383}
384
Lang Hames49047032015-06-23 20:35:31 +0000385bool MachOLinkingContext::needsTLVPass() const {
386 switch (_outputMachOType) {
387 case MH_BUNDLE:
388 case MH_EXECUTE:
389 case MH_DYLIB:
390 return true;
391 default:
392 return false;
393 }
394}
395
Nick Kledzik2458bec2014-07-16 19:49:02 +0000396StringRef MachOLinkingContext::binderSymbolName() const {
397 return archHandler().stubInfo().binderSymbolName;
398}
399
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000400bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000401 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000402 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000403 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000404 if (parsePackedVersion(mac, parsedVersion))
405 return false;
406 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000407 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000408 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000409 if (parsePackedVersion(iOS, parsedVersion))
410 return false;
411 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000412 case OS::unknown:
Pete Cooper3dd478a2016-02-04 01:57:59 +0000413 // If we don't know the target, then assume that we don't meet the min OS.
414 // This matches the ld64 behaviour
415 return false;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000416 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000417}
418
419bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000420 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000421 return minOS("10.8", "6.0");
422 }
423 return false;
424}
425
426bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000427 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000428 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000429 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000430 return true;
431 else
432 return !minOS("10.8", "6.0");
433 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000434 case MH_DYLINKER:
435 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000436 return true;
437 default:
438 return false;
439 }
440}
441
Tim Northover77d82202014-07-10 11:21:06 +0000442bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000443 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000444 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.
Rui Ueyama57a29532014-08-06 19:37:35 +0000448 std::string key = path.str();
449 std::replace(key.begin(), key.end(), '\\', '/');
450 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000451}
452
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000453bool 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
Nick Kledzik2d835da2014-08-14 22:20:41 +0000466void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
467 _syslibRoots = paths;
468}
469
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000470void MachOLinkingContext::addRpath(StringRef rpath) {
471 _rpaths.push_back(rpath);
472}
473
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000474void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
475 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000476 bool addedModifiedPath = false;
477
Nick Kledzik2d835da2014-08-14 22:20:41 +0000478 // -syslibroot only applies to absolute paths.
479 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000480 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000481 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.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000495 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000496 if (pathExists(libPath)) {
497 _searchDirs.push_back(libPath);
498 }
499 }
500}
501
Nick Kledzik2d835da2014-08-14 22:20:41 +0000502void 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
Tim Northover77d82202014-07-10 11:21:06 +0000530ErrorOr<StringRef>
531MachOLinkingContext::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);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000538 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000539 return fullPath.str().copy(_allocator);
540 return make_error_code(llvm::errc::no_such_file_or_directory);
541 }
542
543 // Search for dynamic library
544 fullPath.assign(path);
545 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000546 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000547 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");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000552 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000553 return fullPath.str().copy(_allocator);
554
555 return make_error_code(llvm::errc::no_such_file_or_directory);
556}
557
Tim Northover77d82202014-07-10 11:21:06 +0000558ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
559 SmallString<256> path;
560 for (StringRef dir : searchDirs()) {
561 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
562 if (ec)
563 return ec;
564 }
565
566 return make_error_code(llvm::errc::no_such_file_or_directory);
567}
568
Nick Kledzik2d835da2014-08-14 22:20:41 +0000569ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
570 SmallString<256> fullPath;
571 for (StringRef dir : frameworkDirs()) {
572 fullPath.assign(dir);
573 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000574 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000575 return fullPath.str().copy(_allocator);
576 }
577
578 return make_error_code(llvm::errc::no_such_file_or_directory);
579}
580
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000581bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000582 // TODO: if -arch not specified, look at arch of first .o file.
583
Tim Northoverd30a1f22014-06-20 15:59:00 +0000584 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000585 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000586 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000587 }
588
Tim Northoverd30a1f22014-06-20 15:59:00 +0000589 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000590 diagnostics
591 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000592 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000593 }
594
Tim Northoverd30a1f22014-06-20 15:59:00 +0000595 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000596 diagnostics
597 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000598 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000599 }
600
Tim Northoverd30a1f22014-06-20 15:59:00 +0000601 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000602 diagnostics
603 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000604 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000605 }
606
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000607 // If -exported_symbols_list used, all exported symbols must be defined.
608 if (_exportMode == ExportMode::whiteList) {
609 for (const auto &symbol : _exportedSymbols)
610 addInitialUndefinedSymbol(symbol.getKey());
611 }
612
Nick Kledzik77afc712014-08-21 20:25:50 +0000613 // If -dead_strip, set up initial live symbols.
614 if (deadStrip()) {
615 // Entry point is live.
616 if (outputTypeHasEntry())
617 addDeadStripRoot(entrySymbolName());
618 // Lazy binding helper is live.
619 if (needsStubsPass())
620 addDeadStripRoot(binderSymbolName());
621 // If using -exported_symbols_list, make all exported symbols live.
622 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000623 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000624 for (const auto &symbol : _exportedSymbols)
625 addDeadStripRoot(symbol.getKey());
626 }
627 }
628
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000629 addOutputFileDependency(outputPath());
630
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000631 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000632}
633
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000634void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000635 // objc pass should be before layout pass. Otherwise test cases may contain
636 // no atoms which confuses the layout pass.
637 if (needsObjCPass())
638 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000639 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000640 if (needsStubsPass())
641 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000642 if (needsCompactUnwindPass())
643 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000644 if (needsGOTPass())
645 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000646 if (needsTLVPass())
647 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000648 if (needsShimPass())
649 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000650}
651
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000652Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000653 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000654 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000655 return *_writer;
656}
657
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000658ErrorOr<std::unique_ptr<MemoryBuffer>>
659MachOLinkingContext::getMemoryBuffer(StringRef path) {
660 addInputFileDependency(path);
661
Rui Ueyamadf230b22015-01-15 04:34:31 +0000662 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000663 MemoryBuffer::getFileOrSTDIN(path);
664 if (std::error_code ec = mbOrErr.getError())
665 return ec;
666 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
667
668 // If buffer contains a fat file, find required arch in fat buffer
669 // and switch buffer to point to just that required slice.
670 uint32_t offset;
671 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000672 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000673 return MemoryBuffer::getFileSlice(path, size, offset);
674 return std::move(mb);
675}
676
677MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
678 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000679 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000680 return nullptr;
681
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000682 ErrorOr<std::unique_ptr<File>> fileOrErr =
683 registry().loadFile(std::move(mbOrErr.get()));
684 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000685 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000686 std::unique_ptr<File> &file = fileOrErr.get();
687 file->parse();
688 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000689 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000690 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000691 return result;
692}
693
Nick Kledzik22c90732014-10-01 20:24:30 +0000694MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000695 // See if already loaded.
696 auto pos = _pathToDylibMap.find(path);
697 if (pos != _pathToDylibMap.end())
698 return pos->second;
699
700 // Search -L paths if of the form "libXXX.dylib"
701 std::pair<StringRef, StringRef> split = path.rsplit('/');
702 StringRef leafName = split.second;
703 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
704 // FIXME: Need to enhance searchLibrary() to only look for .dylib
705 auto libPath = searchLibrary(leafName);
706 if (!libPath.getError()) {
707 return loadIndirectDylib(libPath.get());
708 }
709 }
710
711 // Try full path with sysroot.
712 for (StringRef sysPath : _syslibRoots) {
713 SmallString<256> fullPath;
714 fullPath.assign(sysPath);
715 llvm::sys::path::append(fullPath, path);
716 if (pathExists(fullPath))
717 return loadIndirectDylib(fullPath);
718 }
719
720 // Try full path.
721 if (pathExists(path)) {
722 return loadIndirectDylib(path);
723 }
724
725 return nullptr;
726}
727
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000728uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
729 auto pos = _pathToDylibMap.find(installName);
730 if (pos != _pathToDylibMap.end())
731 return pos->second->currentVersion();
732 else
733 return 0x1000; // 1.0
734}
735
736uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
737 auto pos = _pathToDylibMap.find(installName);
738 if (pos != _pathToDylibMap.end())
739 return pos->second->compatVersion();
740 else
741 return 0x1000; // 1.0
742}
743
Simon Atanasyanc4378882015-04-06 20:43:35 +0000744void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000745 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000746 // Add indirect dylibs by asking each linked dylib to add its indirects.
747 // Iterate until no more dylibs get loaded.
748 size_t dylibCount = 0;
749 while (dylibCount != _allDylibs.size()) {
750 dylibCount = _allDylibs.size();
751 for (MachODylibFile *dylib : _allDylibs) {
752 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
753 return findIndirectDylib(path); });
754 }
755 }
756
757 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000758 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000759
Lang Hames9a4c94e2015-09-28 20:52:21 +0000760 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
761 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
762 if (undefinedMode() != UndefinedMode::error) {
763 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000764 _flatNamespaceFile = result.back().get();
765 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000766}
767
Nick Kledzik51720672014-10-16 19:31:28 +0000768void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
769 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000770 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000771 _allDylibs.insert(dylib);
772 _pathToDylibMap[dylib->installName()] = dylib;
773 // If path is different than install name, register path too.
774 if (!dylib->path().equals(dylib->installName()))
775 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000776 if (upward)
777 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000778}
779
Nick Kledzik51720672014-10-16 19:31:28 +0000780bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
781 for (MachODylibFile *dylib : _upwardDylibs) {
782 if (dylib->installName().equals(installName))
783 return true;
784 }
785 return false;
786}
787
Nick Kledzik2458bec2014-07-16 19:49:02 +0000788ArchHandler &MachOLinkingContext::archHandler() const {
789 if (!_archHandler)
790 _archHandler = ArchHandler::create(_arch);
791 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000792}
793
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000794void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000795 uint16_t align) {
796 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000797 _sectAligns.push_back(entry);
798}
799
Lang Hamesb1b67f42015-10-24 08:20:51 +0000800void MachOLinkingContext::addSectCreateSection(
801 StringRef seg, StringRef sect,
802 std::unique_ptr<MemoryBuffer> content) {
803
804 if (!_sectCreateFile) {
805 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
806 _sectCreateFile = sectCreateFile.get();
807 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
808 }
809
810 assert(_sectCreateFile && "sectcreate file does not exist.");
811 _sectCreateFile->addSection(seg, sect, std::move(content));
812}
813
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000814bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000815 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000816 for (const SectionAlign &entry : _sectAligns) {
817 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000818 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000819 return true;
820 }
821 }
822 return false;
823}
824
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000825void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000826 // Support old crufty export lists with bogus entries.
827 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
828 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
829 return;
830 }
831 // Only i386 MacOSX uses old ABI, so don't change those.
832 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
833 // ObjC has two differnent ABIs. Be nice and allow one export list work for
834 // both ABIs by renaming symbols.
835 if (sym.startswith(".objc_class_name_")) {
836 std::string abi2className("_OBJC_CLASS_$_");
837 abi2className += sym.substr(17);
838 _exportedSymbols.insert(copy(abi2className));
839 std::string abi2metaclassName("_OBJC_METACLASS_$_");
840 abi2metaclassName += sym.substr(17);
841 _exportedSymbols.insert(copy(abi2metaclassName));
842 return;
843 }
844 }
845
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000846 // FIXME: Support wildcards.
847 _exportedSymbols.insert(sym);
848}
849
850bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
851 switch (_exportMode) {
852 case ExportMode::globals:
853 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
854 break;
855 case ExportMode::whiteList:
856 return _exportedSymbols.count(sym);
857 case ExportMode::blackList:
858 return !_exportedSymbols.count(sym);
859 }
Yaron Keren9682c852014-09-21 05:07:44 +0000860 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000861}
862
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000863std::string MachOLinkingContext::demangle(StringRef symbolName) const {
864 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000865 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000866 return symbolName;
867
868 // Only try to demangle symbols that look like C++ symbols
869 if (!symbolName.startswith("__Z"))
870 return symbolName;
871
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000872#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000873 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 = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000879 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000880 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#endif
886
887 return symbolName;
888}
889
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000890std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
891 std::error_code ec;
892 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
893 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
894 if (ec) {
895 _dependencyInfo.reset();
896 return ec;
897 }
898
899 char linkerVersionOpcode = 0x00;
900 *_dependencyInfo << linkerVersionOpcode;
901 *_dependencyInfo << "lld"; // FIXME
902 *_dependencyInfo << '\0';
903
904 return std::error_code();
905}
906
907void MachOLinkingContext::addInputFileDependency(StringRef path) const {
908 if (!_dependencyInfo)
909 return;
910
911 char inputFileOpcode = 0x10;
912 *_dependencyInfo << inputFileOpcode;
913 *_dependencyInfo << path;
914 *_dependencyInfo << '\0';
915}
916
917void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
918 if (!_dependencyInfo)
919 return;
920
921 char inputFileOpcode = 0x11;
922 *_dependencyInfo << inputFileOpcode;
923 *_dependencyInfo << path;
924 *_dependencyInfo << '\0';
925}
926
927void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
928 if (!_dependencyInfo)
929 return;
930
931 char outputFileOpcode = 0x40;
932 *_dependencyInfo << outputFileOpcode;
933 *_dependencyInfo << path;
934 *_dependencyInfo << '\0';
935}
936
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000937void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
938 StringRef filename) {
939 // To support sorting static functions which may have the same name in
940 // multiple .o files, _orderFiles maps the symbol name to a vector
941 // of OrderFileNode each of which can specify a file prefix.
942 OrderFileNode info;
943 if (!filename.empty())
944 info.fileFilter = copy(filename);
945 info.order = _orderFileEntries++;
946 _orderFiles[symbol].push_back(info);
947}
948
949bool
950MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
951 const DefinedAtom *atom,
952 unsigned &ordinal) {
953 const File *objFile = &atom->file();
954 assert(objFile);
955 StringRef objName = objFile->path();
956 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
957 if (!dirAndLeaf.second.empty())
958 objName = dirAndLeaf.second;
959 for (const OrderFileNode &info : nodes) {
960 if (info.fileFilter.empty()) {
961 // Have unprefixed symbol name in order file that matches this atom.
962 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000963 return true;
964 }
965 if (info.fileFilter.equals(objName)) {
966 // Have prefixed symbol name in order file that matches atom's path.
967 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000968 return true;
969 }
970 }
971 return false;
972}
973
974bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
975 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000976 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000977 // No custom sorting if no order file entries.
978 if (!_orderFileEntries)
979 return false;
980
981 // Order files can only order named atoms.
982 StringRef leftName = left->name();
983 StringRef rightName = right->name();
984 if (leftName.empty() || rightName.empty())
985 return false;
986
987 // If neither is in order file list, no custom sorter.
988 auto leftPos = _orderFiles.find(leftName);
989 auto rightPos = _orderFiles.find(rightName);
990 bool leftIsOrdered = (leftPos != _orderFiles.end());
991 bool rightIsOrdered = (rightPos != _orderFiles.end());
992 if (!leftIsOrdered && !rightIsOrdered)
993 return false;
994
995 // There could be multiple symbols with same name but different file prefixes.
996 unsigned leftOrder;
997 unsigned rightOrder;
998 bool foundLeft =
999 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
1000 bool foundRight = rightIsOrdered &&
1001 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
1002 if (!foundLeft && !foundRight)
1003 return false;
1004
1005 // If only one is in order file list, ordered one goes first.
1006 if (foundLeft != foundRight)
1007 leftBeforeRight = foundLeft;
1008 else
1009 leftBeforeRight = (leftOrder < rightOrder);
1010
1011 return true;
1012}
Nick Kledzik8c0bf752014-08-21 01:59:11 +00001013
Rui Ueyama61635442015-01-15 08:31:46 +00001014static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +00001015 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1016 File *file = node->getFile();
1017 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1018 }
1019 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +00001020}
1021
1022// The darwin linker processes input files in two phases. The first phase
1023// links in all object (.o) files in command line order. The second phase
1024// links in libraries in command line order.
1025// In this function we reorder the input files so that all the object files
1026// comes before any library file. We also make a group for the library files
1027// so that the Resolver will reiterate over the libraries as long as we find
1028// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +00001029void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +00001030 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +00001031 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +00001032 [](const std::unique_ptr<Node> &a,
1033 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +00001034 return !isLibrary(a) && isLibrary(b);
1035 });
1036 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1037 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1038}
1039
Pete Cooper80c09742016-01-14 21:53:13 +00001040std::error_code MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001041 auto *machoFile = dyn_cast<MachOFile>(&file);
1042 if (!machoFile)
1043 return std::error_code();
1044
1045 // Check that the arch of the context matches that of the file.
1046 // Also set the arch of the context if it didn't have one.
1047 if (_arch == arch_unknown) {
1048 _arch = machoFile->arch();
1049 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1050 // Archs are different.
1051 return make_dynamic_error_code(file.path() +
1052 Twine(" cannot be linked due to incompatible architecture"));
1053 }
1054
1055 // Check that the OS of the context matches that of the file.
1056 // Also set the OS of the context if it didn't have one.
1057 if (_os == OS::unknown) {
1058 _os = machoFile->OS();
1059 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1060 // OSes are different.
1061 return make_dynamic_error_code(file.path() +
1062 Twine(" cannot be linked due to incompatible operating systems"));
1063 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001064
Pete Cooper0872e462016-01-19 19:46:41 +00001065 // Check that if the objc info exists, that it is compatible with the target
1066 // OS.
1067 switch (machoFile->objcConstraint()) {
1068 case objc_unknown:
1069 // The file is not compiled with objc, so skip the checks.
1070 break;
1071 case objc_gc_only:
1072 case objc_supports_gc:
1073 llvm_unreachable("GC support should already have thrown an error");
1074 case objc_retainReleaseForSimulator:
1075 // The file is built with simulator objc, so make sure that the context
1076 // is also building with simulator support.
1077 if (_os != OS::iOS_simulator)
1078 return make_dynamic_error_code(file.path() +
1079 Twine(" cannot be linked. It contains ObjC built for the simulator"
1080 " while we are linking a non-simulator target"));
1081 assert((_objcConstraint == objc_unknown ||
1082 _objcConstraint == objc_retainReleaseForSimulator) &&
1083 "Must be linking with retain/release for the simulator");
1084 _objcConstraint = objc_retainReleaseForSimulator;
1085 break;
1086 case objc_retainRelease:
1087 // The file is built without simulator objc, so make sure that the
1088 // context is also building without simulator support.
1089 if (_os == OS::iOS_simulator)
1090 return make_dynamic_error_code(file.path() +
1091 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1092 " target while we are linking a simulator target"));
1093 assert((_objcConstraint == objc_unknown ||
1094 _objcConstraint == objc_retainRelease) &&
1095 "Must be linking with retain/release for a non-simulator target");
1096 _objcConstraint = objc_retainRelease;
1097 break;
1098 }
1099
Pete Coopera014ffe2016-01-16 00:07:22 +00001100 // Check that the swift version of the context matches that of the file.
1101 // Also set the swift version of the context if it didn't have one.
1102 if (!_swiftVersion) {
1103 _swiftVersion = machoFile->swiftVersion();
1104 } else if (machoFile->swiftVersion() &&
1105 machoFile->swiftVersion() != _swiftVersion) {
1106 // Swift versions are different.
1107 return make_dynamic_error_code("different swift versions");
1108 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001109
Pete Cooper80c09742016-01-14 21:53:13 +00001110 return std::error_code();
1111}
1112
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001113} // end namespace lld