blob: b60d2cb91b5518ac805f2e078d05f6f3e0649fcb [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"
Rafael Espindolad1942132016-09-06 19:17:14 +000026#include "llvm/Demangle/Demangle.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000027#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +000028#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000029#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000030#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000031#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000032#include <algorithm>
33
Nick Kledzik2458bec2014-07-16 19:49:02 +000034using lld::mach_o::ArchHandler;
Pete Cooper99f3b942016-01-14 23:25:06 +000035using lld::mach_o::MachOFile;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000036using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000037using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000038
39namespace lld {
40
Nick Kledzike850d9d2013-09-10 23:46:57 +000041bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
42 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000043
44 if (str.empty())
45 return false;
46
47 SmallVector<StringRef, 3> parts;
48 llvm::SplitString(str, parts, ".");
49
50 unsigned long long num;
51 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
52 return true;
53 if (num > 65535)
54 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000055 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000056
57 if (parts.size() > 1) {
58 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
59 return true;
60 if (num > 255)
61 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000062 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000063 }
64
65 if (parts.size() > 2) {
66 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
67 return true;
68 if (num > 255)
69 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000070 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000071 }
72
73 return false;
74}
75
Pete Cooper40576fa2016-02-04 02:45:23 +000076bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
77 result = 0;
78
79 if (str.empty())
80 return false;
81
82 SmallVector<StringRef, 5> parts;
83 llvm::SplitString(str, parts, ".");
84
Pete Cooperd5c0e4d2016-02-04 02:50:47 +000085 unsigned long long num;
Pete Cooper40576fa2016-02-04 02:45:23 +000086 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
87 return true;
88 if (num > 0xFFFFFF)
89 return true;
90 result = num << 40;
91
92 unsigned Shift = 30;
93 for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
94 if (llvm::getAsUnsignedInteger(str, 10, num))
95 return true;
96 if (num > 0x3FF)
97 return true;
98 result |= (num << Shift);
99 Shift -= 10;
100 }
101
102 return false;
103}
104
Nick Kledzike34182f2013-11-06 21:36:55 +0000105MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
106 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
107 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
108 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
109 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
110 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
111 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +0000112 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +0000113 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000114};
115
116MachOLinkingContext::Arch
117MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000118 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
119 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000120 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000121 }
122 return arch_unknown;
123}
124
125MachOLinkingContext::Arch
126MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000127 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
128 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000129 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000130 }
131 return arch_unknown;
132}
133
Nick Kledzike5552772013-12-19 21:58:00 +0000134StringRef MachOLinkingContext::nameFromArch(Arch arch) {
135 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
136 if (info->arch == arch)
137 return info->archName;
138 }
139 return "<unknown>";
140}
141
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000142uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
143 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000144 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
145 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000146 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000147 }
148 llvm_unreachable("Unknown arch type");
149}
150
151uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
152 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000153 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
154 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000155 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000156 }
157 llvm_unreachable("Unknown arch type");
158}
159
Nick Kledzik635f9c72014-09-04 20:08:30 +0000160bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
161 return mach_o::normalized::isThinObjectFile(path, arch);
162}
163
Rafael Espindolaed48e532015-04-27 22:48:51 +0000164bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000165 uint32_t &size) {
166 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
167}
168
Rui Ueyama51502552016-03-02 19:06:20 +0000169MachOLinkingContext::MachOLinkingContext() {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000170
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000171MachOLinkingContext::~MachOLinkingContext() {
172 // Atoms are allocated on BumpPtrAllocator's on File's.
173 // As we transfer atoms from one file to another, we need to clear all of the
174 // atoms before we remove any of the BumpPtrAllocator's.
175 auto &nodes = getNodes();
176 for (unsigned i = 0, e = nodes.size(); i != e; ++i) {
177 FileNode *node = dyn_cast<FileNode>(nodes[i].get());
178 if (!node)
179 continue;
180 File *file = node->getFile();
181 file->clearAtoms();
182 }
183}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000184
Nick Kledzik6960b072013-12-21 01:47:17 +0000185void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
Pete Cooper35116452016-01-22 21:13:24 +0000186 uint32_t minOSVersion,
187 bool exportDynamicSymbols) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000188 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000189 _arch = arch;
190 _os = os;
191 _osMinVersion = minOSVersion;
192
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000193 // If min OS not specified on command line, use reasonable defaults.
Pete Cooper3dd478a2016-02-04 01:57:59 +0000194 // Note that we only do sensible defaults when emitting something other than
195 // object and preload.
196 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
197 _outputMachOType != llvm::MachO::MH_PRELOAD) {
198 if (minOSVersion == 0) {
199 switch (_arch) {
200 case arch_x86_64:
201 case arch_x86:
202 parsePackedVersion("10.8", _osMinVersion);
203 _os = MachOLinkingContext::OS::macOSX;
204 break;
205 case arch_armv6:
206 case arch_armv7:
207 case arch_armv7s:
208 case arch_arm64:
209 parsePackedVersion("7.0", _osMinVersion);
210 _os = MachOLinkingContext::OS::iOS;
211 break;
212 default:
213 break;
214 }
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000215 }
216 }
217
Tim Northoverd30a1f22014-06-20 15:59:00 +0000218 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000219 case llvm::MachO::MH_EXECUTE:
220 // If targeting newer OS, use _main
221 if (minOS("10.8", "6.0")) {
222 _entrySymbolName = "_main";
223 } else {
224 // If targeting older OS, use start (in crt1.o)
225 _entrySymbolName = "start";
226 }
227
228 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
229 // support) and 4KB on 32-bit.
230 if (is64Bit(_arch)) {
231 _pageZeroSize = 0x100000000;
232 } else {
233 _pageZeroSize = 0x1000;
234 }
235
Lang Hamesc80344282015-09-21 22:06:02 +0000236 // Initial base address is __PAGEZERO size.
237 _baseAddress = _pageZeroSize;
238
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000239 // Make PIE by default when targetting newer OSs.
240 switch (os) {
241 case OS::macOSX:
242 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
243 _pie = true;
244 break;
245 case OS::iOS:
246 if (minOSVersion >= 0x00040300) // iOS 4.3
247 _pie = true;
248 break;
249 case OS::iOS_simulator:
250 _pie = true;
251 break;
252 case OS::unknown:
253 break;
254 }
Pete Cooper35116452016-01-22 21:13:24 +0000255 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000256 break;
257 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000258 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000259 break;
260 case llvm::MachO::MH_BUNDLE:
261 break;
262 case llvm::MachO::MH_OBJECT:
263 _printRemainingUndefines = false;
264 _allowRemainingUndefines = true;
265 default:
266 break;
267 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000268
269 // Set default segment page sizes based on arch.
270 if (arch == arch_arm64)
271 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000272}
273
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000274uint32_t MachOLinkingContext::getCPUType() const {
275 return cpuTypeFromArch(_arch);
276}
277
278uint32_t MachOLinkingContext::getCPUSubType() const {
279 return cpuSubtypeFromArch(_arch);
280}
281
Nick Kledzike34182f2013-11-06 21:36:55 +0000282bool MachOLinkingContext::is64Bit(Arch arch) {
283 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
284 if (info->arch == arch) {
285 return (info->cputype & CPU_ARCH_ABI64);
286 }
287 }
288 // unknown archs are not 64-bit.
289 return false;
290}
291
292bool MachOLinkingContext::isHostEndian(Arch arch) {
293 assert(arch != arch_unknown);
294 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
295 if (info->arch == arch) {
296 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
297 }
298 }
299 llvm_unreachable("Unknown arch type");
300}
301
302bool MachOLinkingContext::isBigEndian(Arch arch) {
303 assert(arch != arch_unknown);
304 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
305 if (info->arch == arch) {
306 return ! info->littleEndian;
307 }
308 }
309 llvm_unreachable("Unknown arch type");
310}
311
Nick Kledzike34182f2013-11-06 21:36:55 +0000312bool MachOLinkingContext::is64Bit() const {
313 return is64Bit(_arch);
314}
315
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000316bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000317 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000318 case MH_EXECUTE:
319 case MH_DYLINKER:
320 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000321 return true;
322 default:
323 return false;
324 }
325}
326
Nick Kledzik2458bec2014-07-16 19:49:02 +0000327bool MachOLinkingContext::needsStubsPass() const {
328 switch (_outputMachOType) {
329 case MH_EXECUTE:
330 return !_outputMachOTypeStatic;
331 case MH_DYLIB:
332 case MH_BUNDLE:
333 return true;
334 default:
335 return false;
336 }
337}
338
339bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000340 // GOT pass not used in -r mode.
341 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000342 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000343 // Only some arches use GOT pass.
344 switch (_arch) {
345 case arch_x86_64:
346 case arch_arm64:
347 return true;
348 default:
349 return false;
350 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000351}
352
Tim Northovercf78d372014-09-30 21:29:54 +0000353bool MachOLinkingContext::needsCompactUnwindPass() const {
354 switch (_outputMachOType) {
355 case MH_EXECUTE:
356 case MH_DYLIB:
357 case MH_BUNDLE:
358 return archHandler().needsCompactUnwind();
359 default:
360 return false;
361 }
362}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000363
Pete Cooper90dbab02016-01-19 21:54:21 +0000364bool MachOLinkingContext::needsObjCPass() const {
365 // ObjC pass is only needed if any of the inputs were ObjC.
366 return _objcConstraint != objc_unknown;
367}
368
Nick Kledzik4121bce2014-10-14 01:51:42 +0000369bool MachOLinkingContext::needsShimPass() const {
370 // Shim pass only used in final executables.
371 if (_outputMachOType == MH_OBJECT)
372 return false;
373 // Only 32-bit arm arches use Shim pass.
374 switch (_arch) {
375 case arch_armv6:
376 case arch_armv7:
377 case arch_armv7s:
378 return true;
379 default:
380 return false;
381 }
382}
383
Lang Hames49047032015-06-23 20:35:31 +0000384bool MachOLinkingContext::needsTLVPass() const {
385 switch (_outputMachOType) {
386 case MH_BUNDLE:
387 case MH_EXECUTE:
388 case MH_DYLIB:
389 return true;
390 default:
391 return false;
392 }
393}
394
Nick Kledzik2458bec2014-07-16 19:49:02 +0000395StringRef MachOLinkingContext::binderSymbolName() const {
396 return archHandler().stubInfo().binderSymbolName;
397}
398
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000399bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000400 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000401 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000402 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000403 if (parsePackedVersion(mac, parsedVersion))
404 return false;
405 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000406 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000407 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000408 if (parsePackedVersion(iOS, parsedVersion))
409 return false;
410 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000411 case OS::unknown:
Pete Cooper3dd478a2016-02-04 01:57:59 +0000412 // If we don't know the target, then assume that we don't meet the min OS.
413 // This matches the ld64 behaviour
414 return false;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000415 }
Reid Kleckner257102e2016-02-10 19:28:13 +0000416 llvm_unreachable("invalid OS enum");
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
Pete Cooperd0a643e2016-03-31 01:09:35 +0000530llvm::Optional<StringRef>
Tim Northover77d82202014-07-10 11:21:06 +0000531MachOLinkingContext::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);
Pete Cooperd0a643e2016-03-31 01:09:35 +0000540 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000541 }
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
Pete Cooperd0a643e2016-03-31 01:09:35 +0000555 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000556}
557
Pete Cooperd0a643e2016-03-31 01:09:35 +0000558llvm::Optional<StringRef>
559MachOLinkingContext::searchLibrary(StringRef libName) const {
Tim Northover77d82202014-07-10 11:21:06 +0000560 SmallString<256> path;
561 for (StringRef dir : searchDirs()) {
Pete Cooperd0a643e2016-03-31 01:09:35 +0000562 llvm::Optional<StringRef> searchDir = searchDirForLibrary(dir, libName);
563 if (searchDir)
564 return searchDir;
Tim Northover77d82202014-07-10 11:21:06 +0000565 }
566
Pete Cooperd0a643e2016-03-31 01:09:35 +0000567 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000568}
569
Pete Cooperd0a643e2016-03-31 01:09:35 +0000570llvm::Optional<StringRef>
571MachOLinkingContext::findPathForFramework(StringRef fwName) const{
Nick Kledzik2d835da2014-08-14 22:20:41 +0000572 SmallString<256> fullPath;
573 for (StringRef dir : frameworkDirs()) {
574 fullPath.assign(dir);
575 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000576 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000577 return fullPath.str().copy(_allocator);
578 }
579
Pete Cooperd0a643e2016-03-31 01:09:35 +0000580 return llvm::None;
Nick Kledzik2d835da2014-08-14 22:20:41 +0000581}
582
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000583bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000584 // TODO: if -arch not specified, look at arch of first .o file.
585
Tim Northoverd30a1f22014-06-20 15:59:00 +0000586 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000587 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000588 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000589 }
590
Tim Northoverd30a1f22014-06-20 15:59:00 +0000591 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000592 diagnostics
593 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000594 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000595 }
596
Tim Northoverd30a1f22014-06-20 15:59:00 +0000597 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000598 diagnostics
599 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000600 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000601 }
602
Tim Northoverd30a1f22014-06-20 15:59:00 +0000603 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000604 diagnostics
605 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000606 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000607 }
608
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000609 // If -exported_symbols_list used, all exported symbols must be defined.
610 if (_exportMode == ExportMode::whiteList) {
611 for (const auto &symbol : _exportedSymbols)
612 addInitialUndefinedSymbol(symbol.getKey());
613 }
614
Nick Kledzik77afc712014-08-21 20:25:50 +0000615 // If -dead_strip, set up initial live symbols.
616 if (deadStrip()) {
617 // Entry point is live.
618 if (outputTypeHasEntry())
619 addDeadStripRoot(entrySymbolName());
620 // Lazy binding helper is live.
621 if (needsStubsPass())
622 addDeadStripRoot(binderSymbolName());
623 // If using -exported_symbols_list, make all exported symbols live.
624 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000625 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000626 for (const auto &symbol : _exportedSymbols)
627 addDeadStripRoot(symbol.getKey());
628 }
629 }
630
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000631 addOutputFileDependency(outputPath());
632
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000633 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000634}
635
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000636void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000637 // objc pass should be before layout pass. Otherwise test cases may contain
638 // no atoms which confuses the layout pass.
639 if (needsObjCPass())
640 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000641 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000642 if (needsStubsPass())
643 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000644 if (needsCompactUnwindPass())
645 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000646 if (needsGOTPass())
647 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000648 if (needsTLVPass())
649 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000650 if (needsShimPass())
651 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000652}
653
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000654Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000655 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000656 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000657 return *_writer;
658}
659
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000660ErrorOr<std::unique_ptr<MemoryBuffer>>
661MachOLinkingContext::getMemoryBuffer(StringRef path) {
662 addInputFileDependency(path);
663
Rui Ueyamadf230b22015-01-15 04:34:31 +0000664 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000665 MemoryBuffer::getFileOrSTDIN(path);
666 if (std::error_code ec = mbOrErr.getError())
667 return ec;
668 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
669
670 // If buffer contains a fat file, find required arch in fat buffer
671 // and switch buffer to point to just that required slice.
672 uint32_t offset;
673 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000674 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000675 return MemoryBuffer::getFileSlice(path, size, offset);
676 return std::move(mb);
677}
678
679MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
680 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000681 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000682 return nullptr;
683
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000684 ErrorOr<std::unique_ptr<File>> fileOrErr =
685 registry().loadFile(std::move(mbOrErr.get()));
686 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000687 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000688 std::unique_ptr<File> &file = fileOrErr.get();
689 file->parse();
690 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000691 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000692 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000693 return result;
694}
695
Nick Kledzik22c90732014-10-01 20:24:30 +0000696MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000697 // See if already loaded.
698 auto pos = _pathToDylibMap.find(path);
699 if (pos != _pathToDylibMap.end())
700 return pos->second;
701
702 // Search -L paths if of the form "libXXX.dylib"
703 std::pair<StringRef, StringRef> split = path.rsplit('/');
704 StringRef leafName = split.second;
705 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
706 // FIXME: Need to enhance searchLibrary() to only look for .dylib
707 auto libPath = searchLibrary(leafName);
Pete Cooperd0a643e2016-03-31 01:09:35 +0000708 if (libPath)
709 return loadIndirectDylib(libPath.getValue());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000710 }
711
712 // Try full path with sysroot.
713 for (StringRef sysPath : _syslibRoots) {
714 SmallString<256> fullPath;
715 fullPath.assign(sysPath);
716 llvm::sys::path::append(fullPath, path);
717 if (pathExists(fullPath))
718 return loadIndirectDylib(fullPath);
719 }
720
721 // Try full path.
722 if (pathExists(path)) {
723 return loadIndirectDylib(path);
724 }
725
726 return nullptr;
727}
728
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000729uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
730 auto pos = _pathToDylibMap.find(installName);
731 if (pos != _pathToDylibMap.end())
732 return pos->second->currentVersion();
733 else
Pete Cooper932bce62016-08-11 18:41:14 +0000734 return 0x10000; // 1.0
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000735}
736
737uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
738 auto pos = _pathToDylibMap.find(installName);
739 if (pos != _pathToDylibMap.end())
740 return pos->second->compatVersion();
741 else
Pete Cooper932bce62016-08-11 18:41:14 +0000742 return 0x10000; // 1.0
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000743}
744
Simon Atanasyanc4378882015-04-06 20:43:35 +0000745void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000746 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000747 // Add indirect dylibs by asking each linked dylib to add its indirects.
748 // Iterate until no more dylibs get loaded.
749 size_t dylibCount = 0;
750 while (dylibCount != _allDylibs.size()) {
751 dylibCount = _allDylibs.size();
752 for (MachODylibFile *dylib : _allDylibs) {
753 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
754 return findIndirectDylib(path); });
755 }
756 }
757
758 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000759 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000760
Lang Hames9a4c94e2015-09-28 20:52:21 +0000761 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
762 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
763 if (undefinedMode() != UndefinedMode::error) {
764 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000765 _flatNamespaceFile = result.back().get();
766 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000767}
768
Nick Kledzik51720672014-10-16 19:31:28 +0000769void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
770 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000771 std::lock_guard<std::mutex> lock(_dylibsMutex);
Pete Cooper46cd1132016-08-11 20:10:14 +0000772
773 if (std::find(_allDylibs.begin(),
774 _allDylibs.end(), dylib) == _allDylibs.end())
775 _allDylibs.push_back(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000776 _pathToDylibMap[dylib->installName()] = dylib;
777 // If path is different than install name, register path too.
778 if (!dylib->path().equals(dylib->installName()))
779 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000780 if (upward)
781 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000782}
783
Nick Kledzik51720672014-10-16 19:31:28 +0000784bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
785 for (MachODylibFile *dylib : _upwardDylibs) {
786 if (dylib->installName().equals(installName))
787 return true;
788 }
789 return false;
790}
791
Nick Kledzik2458bec2014-07-16 19:49:02 +0000792ArchHandler &MachOLinkingContext::archHandler() const {
793 if (!_archHandler)
794 _archHandler = ArchHandler::create(_arch);
795 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000796}
797
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000798void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000799 uint16_t align) {
800 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000801 _sectAligns.push_back(entry);
802}
803
Lang Hamesb1b67f42015-10-24 08:20:51 +0000804void MachOLinkingContext::addSectCreateSection(
805 StringRef seg, StringRef sect,
806 std::unique_ptr<MemoryBuffer> content) {
807
808 if (!_sectCreateFile) {
809 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
810 _sectCreateFile = sectCreateFile.get();
811 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
812 }
813
814 assert(_sectCreateFile && "sectcreate file does not exist.");
815 _sectCreateFile->addSection(seg, sect, std::move(content));
816}
817
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000818bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000819 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000820 for (const SectionAlign &entry : _sectAligns) {
821 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000822 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000823 return true;
824 }
825 }
826 return false;
827}
828
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000829void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000830 // Support old crufty export lists with bogus entries.
831 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
832 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
833 return;
834 }
835 // Only i386 MacOSX uses old ABI, so don't change those.
836 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
837 // ObjC has two differnent ABIs. Be nice and allow one export list work for
838 // both ABIs by renaming symbols.
839 if (sym.startswith(".objc_class_name_")) {
840 std::string abi2className("_OBJC_CLASS_$_");
841 abi2className += sym.substr(17);
842 _exportedSymbols.insert(copy(abi2className));
843 std::string abi2metaclassName("_OBJC_METACLASS_$_");
844 abi2metaclassName += sym.substr(17);
845 _exportedSymbols.insert(copy(abi2metaclassName));
846 return;
847 }
848 }
849
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000850 // FIXME: Support wildcards.
851 _exportedSymbols.insert(sym);
852}
853
854bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
855 switch (_exportMode) {
856 case ExportMode::globals:
857 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
858 break;
859 case ExportMode::whiteList:
860 return _exportedSymbols.count(sym);
861 case ExportMode::blackList:
862 return !_exportedSymbols.count(sym);
863 }
Yaron Keren9682c852014-09-21 05:07:44 +0000864 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000865}
866
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000867std::string MachOLinkingContext::demangle(StringRef symbolName) const {
868 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000869 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000870 return symbolName;
871
872 // Only try to demangle symbols that look like C++ symbols
873 if (!symbolName.startswith("__Z"))
874 return symbolName;
875
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000876 SmallString<256> symBuff;
877 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
878 // Mach-O has extra leading underscore that needs to be removed.
879 const char *cstr = nullTermSym.data() + 1;
880 int status;
Rafael Espindolad1942132016-09-06 19:17:14 +0000881 char *demangled = llvm::itaniumDemangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000882 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000883 std::string result(demangled);
884 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
885 free(demangled);
886 return result;
887 }
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000888
889 return symbolName;
890}
891
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000892std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
893 std::error_code ec;
894 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
895 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
896 if (ec) {
897 _dependencyInfo.reset();
898 return ec;
899 }
900
901 char linkerVersionOpcode = 0x00;
902 *_dependencyInfo << linkerVersionOpcode;
903 *_dependencyInfo << "lld"; // FIXME
904 *_dependencyInfo << '\0';
905
906 return std::error_code();
907}
908
909void MachOLinkingContext::addInputFileDependency(StringRef path) const {
910 if (!_dependencyInfo)
911 return;
912
913 char inputFileOpcode = 0x10;
914 *_dependencyInfo << inputFileOpcode;
915 *_dependencyInfo << path;
916 *_dependencyInfo << '\0';
917}
918
919void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
920 if (!_dependencyInfo)
921 return;
922
923 char inputFileOpcode = 0x11;
924 *_dependencyInfo << inputFileOpcode;
925 *_dependencyInfo << path;
926 *_dependencyInfo << '\0';
927}
928
929void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
930 if (!_dependencyInfo)
931 return;
932
933 char outputFileOpcode = 0x40;
934 *_dependencyInfo << outputFileOpcode;
935 *_dependencyInfo << path;
936 *_dependencyInfo << '\0';
937}
938
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000939void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
940 StringRef filename) {
941 // To support sorting static functions which may have the same name in
942 // multiple .o files, _orderFiles maps the symbol name to a vector
943 // of OrderFileNode each of which can specify a file prefix.
944 OrderFileNode info;
945 if (!filename.empty())
946 info.fileFilter = copy(filename);
947 info.order = _orderFileEntries++;
948 _orderFiles[symbol].push_back(info);
949}
950
951bool
952MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
953 const DefinedAtom *atom,
954 unsigned &ordinal) {
955 const File *objFile = &atom->file();
956 assert(objFile);
957 StringRef objName = objFile->path();
958 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
959 if (!dirAndLeaf.second.empty())
960 objName = dirAndLeaf.second;
961 for (const OrderFileNode &info : nodes) {
962 if (info.fileFilter.empty()) {
963 // Have unprefixed symbol name in order file that matches this atom.
964 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000965 return true;
966 }
967 if (info.fileFilter.equals(objName)) {
968 // Have prefixed symbol name in order file that matches atom's path.
969 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000970 return true;
971 }
972 }
973 return false;
974}
975
976bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
977 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000978 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000979 // No custom sorting if no order file entries.
980 if (!_orderFileEntries)
981 return false;
982
983 // Order files can only order named atoms.
984 StringRef leftName = left->name();
985 StringRef rightName = right->name();
986 if (leftName.empty() || rightName.empty())
987 return false;
988
989 // If neither is in order file list, no custom sorter.
990 auto leftPos = _orderFiles.find(leftName);
991 auto rightPos = _orderFiles.find(rightName);
992 bool leftIsOrdered = (leftPos != _orderFiles.end());
993 bool rightIsOrdered = (rightPos != _orderFiles.end());
994 if (!leftIsOrdered && !rightIsOrdered)
995 return false;
996
997 // There could be multiple symbols with same name but different file prefixes.
998 unsigned leftOrder;
999 unsigned rightOrder;
1000 bool foundLeft =
1001 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
1002 bool foundRight = rightIsOrdered &&
1003 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
1004 if (!foundLeft && !foundRight)
1005 return false;
1006
1007 // If only one is in order file list, ordered one goes first.
1008 if (foundLeft != foundRight)
1009 leftBeforeRight = foundLeft;
1010 else
1011 leftBeforeRight = (leftOrder < rightOrder);
1012
1013 return true;
1014}
Nick Kledzik8c0bf752014-08-21 01:59:11 +00001015
Rui Ueyama61635442015-01-15 08:31:46 +00001016static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +00001017 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1018 File *file = node->getFile();
1019 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1020 }
1021 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +00001022}
1023
1024// The darwin linker processes input files in two phases. The first phase
1025// links in all object (.o) files in command line order. The second phase
1026// links in libraries in command line order.
1027// In this function we reorder the input files so that all the object files
1028// comes before any library file. We also make a group for the library files
1029// so that the Resolver will reiterate over the libraries as long as we find
1030// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +00001031void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +00001032 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +00001033 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +00001034 [](const std::unique_ptr<Node> &a,
1035 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +00001036 return !isLibrary(a) && isLibrary(b);
1037 });
1038 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1039 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1040}
1041
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001042llvm::Error MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001043 auto *machoFile = dyn_cast<MachOFile>(&file);
1044 if (!machoFile)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001045 return llvm::Error();
Pete Cooper99f3b942016-01-14 23:25:06 +00001046
1047 // Check that the arch of the context matches that of the file.
1048 // Also set the arch of the context if it didn't have one.
1049 if (_arch == arch_unknown) {
1050 _arch = machoFile->arch();
1051 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1052 // Archs are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001053 return llvm::make_error<GenericError>(file.path() +
Pete Cooper99f3b942016-01-14 23:25:06 +00001054 Twine(" cannot be linked due to incompatible architecture"));
1055 }
1056
1057 // Check that the OS of the context matches that of the file.
1058 // Also set the OS of the context if it didn't have one.
1059 if (_os == OS::unknown) {
1060 _os = machoFile->OS();
1061 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1062 // OSes are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001063 return llvm::make_error<GenericError>(file.path() +
Pete Cooper99f3b942016-01-14 23:25:06 +00001064 Twine(" cannot be linked due to incompatible operating systems"));
1065 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001066
Pete Cooper0872e462016-01-19 19:46:41 +00001067 // Check that if the objc info exists, that it is compatible with the target
1068 // OS.
1069 switch (machoFile->objcConstraint()) {
1070 case objc_unknown:
1071 // The file is not compiled with objc, so skip the checks.
1072 break;
1073 case objc_gc_only:
1074 case objc_supports_gc:
1075 llvm_unreachable("GC support should already have thrown an error");
1076 case objc_retainReleaseForSimulator:
1077 // The file is built with simulator objc, so make sure that the context
1078 // is also building with simulator support.
1079 if (_os != OS::iOS_simulator)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001080 return llvm::make_error<GenericError>(file.path() +
Pete Cooper0872e462016-01-19 19:46:41 +00001081 Twine(" cannot be linked. It contains ObjC built for the simulator"
1082 " while we are linking a non-simulator target"));
1083 assert((_objcConstraint == objc_unknown ||
1084 _objcConstraint == objc_retainReleaseForSimulator) &&
1085 "Must be linking with retain/release for the simulator");
1086 _objcConstraint = objc_retainReleaseForSimulator;
1087 break;
1088 case objc_retainRelease:
1089 // The file is built without simulator objc, so make sure that the
1090 // context is also building without simulator support.
1091 if (_os == OS::iOS_simulator)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001092 return llvm::make_error<GenericError>(file.path() +
Pete Cooper0872e462016-01-19 19:46:41 +00001093 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1094 " target while we are linking a simulator target"));
1095 assert((_objcConstraint == objc_unknown ||
1096 _objcConstraint == objc_retainRelease) &&
1097 "Must be linking with retain/release for a non-simulator target");
1098 _objcConstraint = objc_retainRelease;
1099 break;
1100 }
1101
Pete Coopera014ffe2016-01-16 00:07:22 +00001102 // Check that the swift version of the context matches that of the file.
1103 // Also set the swift version of the context if it didn't have one.
1104 if (!_swiftVersion) {
1105 _swiftVersion = machoFile->swiftVersion();
1106 } else if (machoFile->swiftVersion() &&
1107 machoFile->swiftVersion() != _swiftVersion) {
1108 // Swift versions are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001109 return llvm::make_error<GenericError>("different swift versions");
Pete Coopera014ffe2016-01-16 00:07:22 +00001110 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001111
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001112 return llvm::Error();
Pete Cooper80c09742016-01-14 21:53:13 +00001113}
1114
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001115} // end namespace lld