blob: 1cc87f0fac4a95f85149640c0c25b4dfbff30181 [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
Pete Cooperd5c0e4d2016-02-04 02:50:47 +000088 unsigned long long num;
Pete Cooper40576fa2016-02-04 02:45:23 +000089 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 Ueyama51502552016-03-02 19:06:20 +0000172MachOLinkingContext::MachOLinkingContext() {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000173
174MachOLinkingContext::~MachOLinkingContext() {}
175
Nick Kledzik6960b072013-12-21 01:47:17 +0000176void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
Pete Cooper35116452016-01-22 21:13:24 +0000177 uint32_t minOSVersion,
178 bool exportDynamicSymbols) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000179 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000180 _arch = arch;
181 _os = os;
182 _osMinVersion = minOSVersion;
183
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000184 // If min OS not specified on command line, use reasonable defaults.
Pete Cooper3dd478a2016-02-04 01:57:59 +0000185 // Note that we only do sensible defaults when emitting something other than
186 // object and preload.
187 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
188 _outputMachOType != llvm::MachO::MH_PRELOAD) {
189 if (minOSVersion == 0) {
190 switch (_arch) {
191 case arch_x86_64:
192 case arch_x86:
193 parsePackedVersion("10.8", _osMinVersion);
194 _os = MachOLinkingContext::OS::macOSX;
195 break;
196 case arch_armv6:
197 case arch_armv7:
198 case arch_armv7s:
199 case arch_arm64:
200 parsePackedVersion("7.0", _osMinVersion);
201 _os = MachOLinkingContext::OS::iOS;
202 break;
203 default:
204 break;
205 }
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000206 }
207 }
208
Tim Northoverd30a1f22014-06-20 15:59:00 +0000209 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000210 case llvm::MachO::MH_EXECUTE:
211 // If targeting newer OS, use _main
212 if (minOS("10.8", "6.0")) {
213 _entrySymbolName = "_main";
214 } else {
215 // If targeting older OS, use start (in crt1.o)
216 _entrySymbolName = "start";
217 }
218
219 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
220 // support) and 4KB on 32-bit.
221 if (is64Bit(_arch)) {
222 _pageZeroSize = 0x100000000;
223 } else {
224 _pageZeroSize = 0x1000;
225 }
226
Lang Hamesc80344282015-09-21 22:06:02 +0000227 // Initial base address is __PAGEZERO size.
228 _baseAddress = _pageZeroSize;
229
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000230 // Make PIE by default when targetting newer OSs.
231 switch (os) {
232 case OS::macOSX:
233 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
234 _pie = true;
235 break;
236 case OS::iOS:
237 if (minOSVersion >= 0x00040300) // iOS 4.3
238 _pie = true;
239 break;
240 case OS::iOS_simulator:
241 _pie = true;
242 break;
243 case OS::unknown:
244 break;
245 }
Pete Cooper35116452016-01-22 21:13:24 +0000246 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000247 break;
248 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000249 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000250 break;
251 case llvm::MachO::MH_BUNDLE:
252 break;
253 case llvm::MachO::MH_OBJECT:
254 _printRemainingUndefines = false;
255 _allowRemainingUndefines = true;
256 default:
257 break;
258 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000259
260 // Set default segment page sizes based on arch.
261 if (arch == arch_arm64)
262 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000263}
264
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000265uint32_t MachOLinkingContext::getCPUType() const {
266 return cpuTypeFromArch(_arch);
267}
268
269uint32_t MachOLinkingContext::getCPUSubType() const {
270 return cpuSubtypeFromArch(_arch);
271}
272
Nick Kledzike34182f2013-11-06 21:36:55 +0000273bool MachOLinkingContext::is64Bit(Arch arch) {
274 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
275 if (info->arch == arch) {
276 return (info->cputype & CPU_ARCH_ABI64);
277 }
278 }
279 // unknown archs are not 64-bit.
280 return false;
281}
282
283bool MachOLinkingContext::isHostEndian(Arch arch) {
284 assert(arch != arch_unknown);
285 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
286 if (info->arch == arch) {
287 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
288 }
289 }
290 llvm_unreachable("Unknown arch type");
291}
292
293bool MachOLinkingContext::isBigEndian(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;
298 }
299 }
300 llvm_unreachable("Unknown arch type");
301}
302
Nick Kledzike34182f2013-11-06 21:36:55 +0000303bool MachOLinkingContext::is64Bit() const {
304 return is64Bit(_arch);
305}
306
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000307bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000308 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000309 case MH_EXECUTE:
310 case MH_DYLINKER:
311 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000312 return true;
313 default:
314 return false;
315 }
316}
317
Nick Kledzik2458bec2014-07-16 19:49:02 +0000318bool MachOLinkingContext::needsStubsPass() const {
319 switch (_outputMachOType) {
320 case MH_EXECUTE:
321 return !_outputMachOTypeStatic;
322 case MH_DYLIB:
323 case MH_BUNDLE:
324 return true;
325 default:
326 return false;
327 }
328}
329
330bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000331 // GOT pass not used in -r mode.
332 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000333 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000334 // Only some arches use GOT pass.
335 switch (_arch) {
336 case arch_x86_64:
337 case arch_arm64:
338 return true;
339 default:
340 return false;
341 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000342}
343
Tim Northovercf78d372014-09-30 21:29:54 +0000344bool MachOLinkingContext::needsCompactUnwindPass() const {
345 switch (_outputMachOType) {
346 case MH_EXECUTE:
347 case MH_DYLIB:
348 case MH_BUNDLE:
349 return archHandler().needsCompactUnwind();
350 default:
351 return false;
352 }
353}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000354
Pete Cooper90dbab02016-01-19 21:54:21 +0000355bool MachOLinkingContext::needsObjCPass() const {
356 // ObjC pass is only needed if any of the inputs were ObjC.
357 return _objcConstraint != objc_unknown;
358}
359
Nick Kledzik4121bce2014-10-14 01:51:42 +0000360bool MachOLinkingContext::needsShimPass() const {
361 // Shim pass only used in final executables.
362 if (_outputMachOType == MH_OBJECT)
363 return false;
364 // Only 32-bit arm arches use Shim pass.
365 switch (_arch) {
366 case arch_armv6:
367 case arch_armv7:
368 case arch_armv7s:
369 return true;
370 default:
371 return false;
372 }
373}
374
Lang Hames49047032015-06-23 20:35:31 +0000375bool MachOLinkingContext::needsTLVPass() const {
376 switch (_outputMachOType) {
377 case MH_BUNDLE:
378 case MH_EXECUTE:
379 case MH_DYLIB:
380 return true;
381 default:
382 return false;
383 }
384}
385
Nick Kledzik2458bec2014-07-16 19:49:02 +0000386StringRef MachOLinkingContext::binderSymbolName() const {
387 return archHandler().stubInfo().binderSymbolName;
388}
389
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000390bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000391 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000392 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000393 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000394 if (parsePackedVersion(mac, parsedVersion))
395 return false;
396 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000397 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000398 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000399 if (parsePackedVersion(iOS, parsedVersion))
400 return false;
401 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000402 case OS::unknown:
Pete Cooper3dd478a2016-02-04 01:57:59 +0000403 // If we don't know the target, then assume that we don't meet the min OS.
404 // This matches the ld64 behaviour
405 return false;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000406 }
Reid Kleckner257102e2016-02-10 19:28:13 +0000407 llvm_unreachable("invalid OS enum");
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000408}
409
410bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000411 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000412 return minOS("10.8", "6.0");
413 }
414 return false;
415}
416
417bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000418 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000419 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000420 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000421 return true;
422 else
423 return !minOS("10.8", "6.0");
424 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000425 case MH_DYLINKER:
426 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000427 return true;
428 default:
429 return false;
430 }
431}
432
Tim Northover77d82202014-07-10 11:21:06 +0000433bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000434 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000435 return llvm::sys::fs::exists(path.str());
436
437 // Otherwise, we're in test mode: only files explicitly provided on the
438 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000439 std::string key = path.str();
440 std::replace(key.begin(), key.end(), '\\', '/');
441 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000442}
443
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000444bool MachOLinkingContext::fileExists(StringRef path) const {
445 bool found = pathExists(path);
446 // Log search misses.
447 if (!found)
448 addInputFileNotFound(path);
449
450 // When testing, file is never opened, so logging is done here.
451 if (_testingFileUsage && found)
452 addInputFileDependency(path);
453
454 return found;
455}
456
Nick Kledzik2d835da2014-08-14 22:20:41 +0000457void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
458 _syslibRoots = paths;
459}
460
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000461void MachOLinkingContext::addRpath(StringRef rpath) {
462 _rpaths.push_back(rpath);
463}
464
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000465void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
466 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000467 bool addedModifiedPath = false;
468
Nick Kledzik2d835da2014-08-14 22:20:41 +0000469 // -syslibroot only applies to absolute paths.
470 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000471 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000472 SmallString<256> path(syslibRoot);
473 llvm::sys::path::append(path, libPath);
474 if (pathExists(path)) {
475 _searchDirs.push_back(path.str().copy(_allocator));
476 addedModifiedPath = true;
477 }
478 }
479 }
480
481 if (addedModifiedPath)
482 return;
483
484 // Finally, if only one -syslibroot is given, system paths which aren't in it
485 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000486 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000487 if (pathExists(libPath)) {
488 _searchDirs.push_back(libPath);
489 }
490 }
491}
492
Nick Kledzik2d835da2014-08-14 22:20:41 +0000493void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
494 bool isSystemPath) {
495 bool pathAdded = false;
496
497 // -syslibroot only used with to absolute framework search paths.
498 if (fwPath.startswith("/")) {
499 for (auto syslibRoot : _syslibRoots) {
500 SmallString<256> path(syslibRoot);
501 llvm::sys::path::append(path, fwPath);
502 if (pathExists(path)) {
503 _frameworkDirs.push_back(path.str().copy(_allocator));
504 pathAdded = true;
505 }
506 }
507 }
508 // If fwPath found in any -syslibroot, then done.
509 if (pathAdded)
510 return;
511
512 // If only one -syslibroot, system paths not in that SDK are suppressed.
513 if (isSystemPath && (_syslibRoots.size() == 1))
514 return;
515
516 // Only use raw fwPath if that directory exists.
517 if (pathExists(fwPath))
518 _frameworkDirs.push_back(fwPath);
519}
520
Tim Northover77d82202014-07-10 11:21:06 +0000521ErrorOr<StringRef>
522MachOLinkingContext::searchDirForLibrary(StringRef path,
523 StringRef libName) const {
524 SmallString<256> fullPath;
525 if (libName.endswith(".o")) {
526 // A request ending in .o is special: just search for the file directly.
527 fullPath.assign(path);
528 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000529 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000530 return fullPath.str().copy(_allocator);
531 return make_error_code(llvm::errc::no_such_file_or_directory);
532 }
533
534 // Search for dynamic library
535 fullPath.assign(path);
536 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000537 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000538 return fullPath.str().copy(_allocator);
539
540 // If not, try for a static library
541 fullPath.assign(path);
542 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000543 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000544 return fullPath.str().copy(_allocator);
545
546 return make_error_code(llvm::errc::no_such_file_or_directory);
547}
548
Tim Northover77d82202014-07-10 11:21:06 +0000549ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
550 SmallString<256> path;
551 for (StringRef dir : searchDirs()) {
552 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
553 if (ec)
554 return ec;
555 }
556
557 return make_error_code(llvm::errc::no_such_file_or_directory);
558}
559
Nick Kledzik2d835da2014-08-14 22:20:41 +0000560ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
561 SmallString<256> fullPath;
562 for (StringRef dir : frameworkDirs()) {
563 fullPath.assign(dir);
564 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000565 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000566 return fullPath.str().copy(_allocator);
567 }
568
569 return make_error_code(llvm::errc::no_such_file_or_directory);
570}
571
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000572bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000573 // TODO: if -arch not specified, look at arch of first .o file.
574
Tim Northoverd30a1f22014-06-20 15:59:00 +0000575 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000576 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000577 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000578 }
579
Tim Northoverd30a1f22014-06-20 15:59:00 +0000580 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000581 diagnostics
582 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000583 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000584 }
585
Tim Northoverd30a1f22014-06-20 15:59:00 +0000586 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000587 diagnostics
588 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000589 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000590 }
591
Tim Northoverd30a1f22014-06-20 15:59:00 +0000592 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000593 diagnostics
594 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000595 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000596 }
597
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000598 // If -exported_symbols_list used, all exported symbols must be defined.
599 if (_exportMode == ExportMode::whiteList) {
600 for (const auto &symbol : _exportedSymbols)
601 addInitialUndefinedSymbol(symbol.getKey());
602 }
603
Nick Kledzik77afc712014-08-21 20:25:50 +0000604 // If -dead_strip, set up initial live symbols.
605 if (deadStrip()) {
606 // Entry point is live.
607 if (outputTypeHasEntry())
608 addDeadStripRoot(entrySymbolName());
609 // Lazy binding helper is live.
610 if (needsStubsPass())
611 addDeadStripRoot(binderSymbolName());
612 // If using -exported_symbols_list, make all exported symbols live.
613 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000614 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000615 for (const auto &symbol : _exportedSymbols)
616 addDeadStripRoot(symbol.getKey());
617 }
618 }
619
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000620 addOutputFileDependency(outputPath());
621
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000622 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000623}
624
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000625void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000626 // objc pass should be before layout pass. Otherwise test cases may contain
627 // no atoms which confuses the layout pass.
628 if (needsObjCPass())
629 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000630 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000631 if (needsStubsPass())
632 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000633 if (needsCompactUnwindPass())
634 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000635 if (needsGOTPass())
636 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000637 if (needsTLVPass())
638 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000639 if (needsShimPass())
640 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000641}
642
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000643Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000644 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000645 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000646 return *_writer;
647}
648
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000649ErrorOr<std::unique_ptr<MemoryBuffer>>
650MachOLinkingContext::getMemoryBuffer(StringRef path) {
651 addInputFileDependency(path);
652
Rui Ueyamadf230b22015-01-15 04:34:31 +0000653 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000654 MemoryBuffer::getFileOrSTDIN(path);
655 if (std::error_code ec = mbOrErr.getError())
656 return ec;
657 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
658
659 // If buffer contains a fat file, find required arch in fat buffer
660 // and switch buffer to point to just that required slice.
661 uint32_t offset;
662 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000663 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000664 return MemoryBuffer::getFileSlice(path, size, offset);
665 return std::move(mb);
666}
667
668MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
669 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000670 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000671 return nullptr;
672
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000673 ErrorOr<std::unique_ptr<File>> fileOrErr =
674 registry().loadFile(std::move(mbOrErr.get()));
675 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000676 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000677 std::unique_ptr<File> &file = fileOrErr.get();
678 file->parse();
679 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000680 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000681 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000682 return result;
683}
684
Nick Kledzik22c90732014-10-01 20:24:30 +0000685MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000686 // See if already loaded.
687 auto pos = _pathToDylibMap.find(path);
688 if (pos != _pathToDylibMap.end())
689 return pos->second;
690
691 // Search -L paths if of the form "libXXX.dylib"
692 std::pair<StringRef, StringRef> split = path.rsplit('/');
693 StringRef leafName = split.second;
694 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
695 // FIXME: Need to enhance searchLibrary() to only look for .dylib
696 auto libPath = searchLibrary(leafName);
697 if (!libPath.getError()) {
698 return loadIndirectDylib(libPath.get());
699 }
700 }
701
702 // Try full path with sysroot.
703 for (StringRef sysPath : _syslibRoots) {
704 SmallString<256> fullPath;
705 fullPath.assign(sysPath);
706 llvm::sys::path::append(fullPath, path);
707 if (pathExists(fullPath))
708 return loadIndirectDylib(fullPath);
709 }
710
711 // Try full path.
712 if (pathExists(path)) {
713 return loadIndirectDylib(path);
714 }
715
716 return nullptr;
717}
718
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000719uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
720 auto pos = _pathToDylibMap.find(installName);
721 if (pos != _pathToDylibMap.end())
722 return pos->second->currentVersion();
723 else
724 return 0x1000; // 1.0
725}
726
727uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
728 auto pos = _pathToDylibMap.find(installName);
729 if (pos != _pathToDylibMap.end())
730 return pos->second->compatVersion();
731 else
732 return 0x1000; // 1.0
733}
734
Simon Atanasyanc4378882015-04-06 20:43:35 +0000735void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000736 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000737 // Add indirect dylibs by asking each linked dylib to add its indirects.
738 // Iterate until no more dylibs get loaded.
739 size_t dylibCount = 0;
740 while (dylibCount != _allDylibs.size()) {
741 dylibCount = _allDylibs.size();
742 for (MachODylibFile *dylib : _allDylibs) {
743 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
744 return findIndirectDylib(path); });
745 }
746 }
747
748 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000749 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000750
Lang Hames9a4c94e2015-09-28 20:52:21 +0000751 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
752 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
753 if (undefinedMode() != UndefinedMode::error) {
754 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000755 _flatNamespaceFile = result.back().get();
756 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000757}
758
Nick Kledzik51720672014-10-16 19:31:28 +0000759void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
760 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000761 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000762 _allDylibs.insert(dylib);
763 _pathToDylibMap[dylib->installName()] = dylib;
764 // If path is different than install name, register path too.
765 if (!dylib->path().equals(dylib->installName()))
766 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000767 if (upward)
768 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000769}
770
Nick Kledzik51720672014-10-16 19:31:28 +0000771bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
772 for (MachODylibFile *dylib : _upwardDylibs) {
773 if (dylib->installName().equals(installName))
774 return true;
775 }
776 return false;
777}
778
Nick Kledzik2458bec2014-07-16 19:49:02 +0000779ArchHandler &MachOLinkingContext::archHandler() const {
780 if (!_archHandler)
781 _archHandler = ArchHandler::create(_arch);
782 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000783}
784
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000785void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000786 uint16_t align) {
787 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000788 _sectAligns.push_back(entry);
789}
790
Lang Hamesb1b67f42015-10-24 08:20:51 +0000791void MachOLinkingContext::addSectCreateSection(
792 StringRef seg, StringRef sect,
793 std::unique_ptr<MemoryBuffer> content) {
794
795 if (!_sectCreateFile) {
796 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
797 _sectCreateFile = sectCreateFile.get();
798 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
799 }
800
801 assert(_sectCreateFile && "sectcreate file does not exist.");
802 _sectCreateFile->addSection(seg, sect, std::move(content));
803}
804
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000805bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000806 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000807 for (const SectionAlign &entry : _sectAligns) {
808 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000809 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000810 return true;
811 }
812 }
813 return false;
814}
815
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000816void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000817 // Support old crufty export lists with bogus entries.
818 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
819 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
820 return;
821 }
822 // Only i386 MacOSX uses old ABI, so don't change those.
823 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
824 // ObjC has two differnent ABIs. Be nice and allow one export list work for
825 // both ABIs by renaming symbols.
826 if (sym.startswith(".objc_class_name_")) {
827 std::string abi2className("_OBJC_CLASS_$_");
828 abi2className += sym.substr(17);
829 _exportedSymbols.insert(copy(abi2className));
830 std::string abi2metaclassName("_OBJC_METACLASS_$_");
831 abi2metaclassName += sym.substr(17);
832 _exportedSymbols.insert(copy(abi2metaclassName));
833 return;
834 }
835 }
836
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000837 // FIXME: Support wildcards.
838 _exportedSymbols.insert(sym);
839}
840
841bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
842 switch (_exportMode) {
843 case ExportMode::globals:
844 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
845 break;
846 case ExportMode::whiteList:
847 return _exportedSymbols.count(sym);
848 case ExportMode::blackList:
849 return !_exportedSymbols.count(sym);
850 }
Yaron Keren9682c852014-09-21 05:07:44 +0000851 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000852}
853
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000854std::string MachOLinkingContext::demangle(StringRef symbolName) const {
855 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000856 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000857 return symbolName;
858
859 // Only try to demangle symbols that look like C++ symbols
860 if (!symbolName.startswith("__Z"))
861 return symbolName;
862
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000863#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000864 SmallString<256> symBuff;
865 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
866 // Mach-O has extra leading underscore that needs to be removed.
867 const char *cstr = nullTermSym.data() + 1;
868 int status;
869 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000870 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000871 std::string result(demangled);
872 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
873 free(demangled);
874 return result;
875 }
876#endif
877
878 return symbolName;
879}
880
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000881std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
882 std::error_code ec;
883 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
884 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
885 if (ec) {
886 _dependencyInfo.reset();
887 return ec;
888 }
889
890 char linkerVersionOpcode = 0x00;
891 *_dependencyInfo << linkerVersionOpcode;
892 *_dependencyInfo << "lld"; // FIXME
893 *_dependencyInfo << '\0';
894
895 return std::error_code();
896}
897
898void MachOLinkingContext::addInputFileDependency(StringRef path) const {
899 if (!_dependencyInfo)
900 return;
901
902 char inputFileOpcode = 0x10;
903 *_dependencyInfo << inputFileOpcode;
904 *_dependencyInfo << path;
905 *_dependencyInfo << '\0';
906}
907
908void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
909 if (!_dependencyInfo)
910 return;
911
912 char inputFileOpcode = 0x11;
913 *_dependencyInfo << inputFileOpcode;
914 *_dependencyInfo << path;
915 *_dependencyInfo << '\0';
916}
917
918void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
919 if (!_dependencyInfo)
920 return;
921
922 char outputFileOpcode = 0x40;
923 *_dependencyInfo << outputFileOpcode;
924 *_dependencyInfo << path;
925 *_dependencyInfo << '\0';
926}
927
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000928void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
929 StringRef filename) {
930 // To support sorting static functions which may have the same name in
931 // multiple .o files, _orderFiles maps the symbol name to a vector
932 // of OrderFileNode each of which can specify a file prefix.
933 OrderFileNode info;
934 if (!filename.empty())
935 info.fileFilter = copy(filename);
936 info.order = _orderFileEntries++;
937 _orderFiles[symbol].push_back(info);
938}
939
940bool
941MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
942 const DefinedAtom *atom,
943 unsigned &ordinal) {
944 const File *objFile = &atom->file();
945 assert(objFile);
946 StringRef objName = objFile->path();
947 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
948 if (!dirAndLeaf.second.empty())
949 objName = dirAndLeaf.second;
950 for (const OrderFileNode &info : nodes) {
951 if (info.fileFilter.empty()) {
952 // Have unprefixed symbol name in order file that matches this atom.
953 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000954 return true;
955 }
956 if (info.fileFilter.equals(objName)) {
957 // Have prefixed symbol name in order file that matches atom's path.
958 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000959 return true;
960 }
961 }
962 return false;
963}
964
965bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
966 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000967 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000968 // No custom sorting if no order file entries.
969 if (!_orderFileEntries)
970 return false;
971
972 // Order files can only order named atoms.
973 StringRef leftName = left->name();
974 StringRef rightName = right->name();
975 if (leftName.empty() || rightName.empty())
976 return false;
977
978 // If neither is in order file list, no custom sorter.
979 auto leftPos = _orderFiles.find(leftName);
980 auto rightPos = _orderFiles.find(rightName);
981 bool leftIsOrdered = (leftPos != _orderFiles.end());
982 bool rightIsOrdered = (rightPos != _orderFiles.end());
983 if (!leftIsOrdered && !rightIsOrdered)
984 return false;
985
986 // There could be multiple symbols with same name but different file prefixes.
987 unsigned leftOrder;
988 unsigned rightOrder;
989 bool foundLeft =
990 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
991 bool foundRight = rightIsOrdered &&
992 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
993 if (!foundLeft && !foundRight)
994 return false;
995
996 // If only one is in order file list, ordered one goes first.
997 if (foundLeft != foundRight)
998 leftBeforeRight = foundLeft;
999 else
1000 leftBeforeRight = (leftOrder < rightOrder);
1001
1002 return true;
1003}
Nick Kledzik8c0bf752014-08-21 01:59:11 +00001004
Rui Ueyama61635442015-01-15 08:31:46 +00001005static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +00001006 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1007 File *file = node->getFile();
1008 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1009 }
1010 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +00001011}
1012
1013// The darwin linker processes input files in two phases. The first phase
1014// links in all object (.o) files in command line order. The second phase
1015// links in libraries in command line order.
1016// In this function we reorder the input files so that all the object files
1017// comes before any library file. We also make a group for the library files
1018// so that the Resolver will reiterate over the libraries as long as we find
1019// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +00001020void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +00001021 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +00001022 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +00001023 [](const std::unique_ptr<Node> &a,
1024 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +00001025 return !isLibrary(a) && isLibrary(b);
1026 });
1027 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1028 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1029}
1030
Pete Cooper80c09742016-01-14 21:53:13 +00001031std::error_code MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001032 auto *machoFile = dyn_cast<MachOFile>(&file);
1033 if (!machoFile)
1034 return std::error_code();
1035
1036 // Check that the arch of the context matches that of the file.
1037 // Also set the arch of the context if it didn't have one.
1038 if (_arch == arch_unknown) {
1039 _arch = machoFile->arch();
1040 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1041 // Archs are different.
1042 return make_dynamic_error_code(file.path() +
1043 Twine(" cannot be linked due to incompatible architecture"));
1044 }
1045
1046 // Check that the OS of the context matches that of the file.
1047 // Also set the OS of the context if it didn't have one.
1048 if (_os == OS::unknown) {
1049 _os = machoFile->OS();
1050 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1051 // OSes are different.
1052 return make_dynamic_error_code(file.path() +
1053 Twine(" cannot be linked due to incompatible operating systems"));
1054 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001055
Pete Cooper0872e462016-01-19 19:46:41 +00001056 // Check that if the objc info exists, that it is compatible with the target
1057 // OS.
1058 switch (machoFile->objcConstraint()) {
1059 case objc_unknown:
1060 // The file is not compiled with objc, so skip the checks.
1061 break;
1062 case objc_gc_only:
1063 case objc_supports_gc:
1064 llvm_unreachable("GC support should already have thrown an error");
1065 case objc_retainReleaseForSimulator:
1066 // The file is built with simulator objc, so make sure that the context
1067 // is also building with simulator support.
1068 if (_os != OS::iOS_simulator)
1069 return make_dynamic_error_code(file.path() +
1070 Twine(" cannot be linked. It contains ObjC built for the simulator"
1071 " while we are linking a non-simulator target"));
1072 assert((_objcConstraint == objc_unknown ||
1073 _objcConstraint == objc_retainReleaseForSimulator) &&
1074 "Must be linking with retain/release for the simulator");
1075 _objcConstraint = objc_retainReleaseForSimulator;
1076 break;
1077 case objc_retainRelease:
1078 // The file is built without simulator objc, so make sure that the
1079 // context is also building without simulator support.
1080 if (_os == OS::iOS_simulator)
1081 return make_dynamic_error_code(file.path() +
1082 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1083 " target while we are linking a simulator target"));
1084 assert((_objcConstraint == objc_unknown ||
1085 _objcConstraint == objc_retainRelease) &&
1086 "Must be linking with retain/release for a non-simulator target");
1087 _objcConstraint = objc_retainRelease;
1088 break;
1089 }
1090
Pete Coopera014ffe2016-01-16 00:07:22 +00001091 // Check that the swift version of the context matches that of the file.
1092 // Also set the swift version of the context if it didn't have one.
1093 if (!_swiftVersion) {
1094 _swiftVersion = machoFile->swiftVersion();
1095 } else if (machoFile->swiftVersion() &&
1096 machoFile->swiftVersion() != _swiftVersion) {
1097 // Swift versions are different.
1098 return make_dynamic_error_code("different swift versions");
1099 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001100
Pete Cooper80c09742016-01-14 21:53:13 +00001101 return std::error_code();
1102}
1103
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001104} // end namespace lld