blob: 41da4e7d126f4d5d77c57fa09f9c358aaeae1190 [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"
Nick Kledzik635f9c72014-09-04 20:08:30 +000013#include "MachONormalizedFile.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000014#include "MachOPasses.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000015#include "lld/Core/ArchiveLibraryFile.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000016#include "lld/Core/PassManager.h"
Greg Fitzgerald4b6a7e32015-01-21 22:54:56 +000017#include "lld/Core/Reader.h"
18#include "lld/Core/Writer.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000019#include "lld/Driver/Driver.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000020#include "lld/Passes/LayoutPass.h"
Shankar Easwaran2bc24922013-10-29 05:12:14 +000021#include "lld/Passes/RoundTripYAMLPass.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000022#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000024#include "llvm/Config/config.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000025#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +000026#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000027#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000028#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000029#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000030#include <algorithm>
31
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000032#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000033#include <cxxabi.h>
34#endif
35
Nick Kledzik2458bec2014-07-16 19:49:02 +000036using lld::mach_o::ArchHandler;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000037using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000038using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000039
40namespace lld {
41
Nick Kledzike850d9d2013-09-10 23:46:57 +000042bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
43 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000044
45 if (str.empty())
46 return false;
47
48 SmallVector<StringRef, 3> parts;
49 llvm::SplitString(str, parts, ".");
50
51 unsigned long long num;
52 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
53 return true;
54 if (num > 65535)
55 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000056 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000057
58 if (parts.size() > 1) {
59 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
60 return true;
61 if (num > 255)
62 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000063 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000064 }
65
66 if (parts.size() > 2) {
67 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
68 return true;
69 if (num > 255)
70 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000071 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000072 }
73
74 return false;
75}
76
Rui Ueyama0ca149f2013-08-06 22:31:59 +000077
Nick Kledzike34182f2013-11-06 21:36:55 +000078MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
79 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
80 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
81 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
82 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
83 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
84 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000085 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000086 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000087};
88
89MachOLinkingContext::Arch
90MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000091 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
92 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000093 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000094 }
95 return arch_unknown;
96}
97
98MachOLinkingContext::Arch
99MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000100 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
101 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000102 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000103 }
104 return arch_unknown;
105}
106
Nick Kledzike5552772013-12-19 21:58:00 +0000107StringRef MachOLinkingContext::nameFromArch(Arch arch) {
108 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
109 if (info->arch == arch)
110 return info->archName;
111 }
112 return "<unknown>";
113}
114
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000115uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
116 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000117 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
118 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000119 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000120 }
121 llvm_unreachable("Unknown arch type");
122}
123
124uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
125 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000126 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
127 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000128 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000129 }
130 llvm_unreachable("Unknown arch type");
131}
132
Nick Kledzik635f9c72014-09-04 20:08:30 +0000133bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
134 return mach_o::normalized::isThinObjectFile(path, arch);
135}
136
Nick Kledzik14b5d202014-10-08 01:48:10 +0000137bool MachOLinkingContext::sliceFromFatFile(const MemoryBuffer &mb,
138 uint32_t &offset,
139 uint32_t &size) {
140 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
141}
142
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000143MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000144 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000145 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
146 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
147 _compatibilityVersion(0), _currentVersion(0), _deadStrippableDylib(false),
148 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000149 _demangle(false), _archHandler(nullptr),
Nick Kledzik8f75da02014-11-06 03:03:42 +0000150 _exportMode(ExportMode::globals),
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000151 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000152
153MachOLinkingContext::~MachOLinkingContext() {}
154
Nick Kledzik6960b072013-12-21 01:47:17 +0000155void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
156 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000157 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000158 _arch = arch;
159 _os = os;
160 _osMinVersion = minOSVersion;
161
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000162 // If min OS not specified on command line, use reasonable defaults.
163 if (minOSVersion == 0) {
164 switch (_arch) {
165 case arch_x86_64:
166 case arch_x86:
167 parsePackedVersion("10.8", _osMinVersion);
168 _os = MachOLinkingContext::OS::macOSX;
169 break;
170 case arch_armv6:
171 case arch_armv7:
172 case arch_armv7s:
173 case arch_arm64:
174 parsePackedVersion("7.0", _osMinVersion);
175 _os = MachOLinkingContext::OS::iOS;
176 break;
177 default:
178 break;
179 }
180 }
181
Tim Northoverd30a1f22014-06-20 15:59:00 +0000182 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000183 case llvm::MachO::MH_EXECUTE:
184 // If targeting newer OS, use _main
185 if (minOS("10.8", "6.0")) {
186 _entrySymbolName = "_main";
187 } else {
188 // If targeting older OS, use start (in crt1.o)
189 _entrySymbolName = "start";
190 }
191
192 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
193 // support) and 4KB on 32-bit.
194 if (is64Bit(_arch)) {
195 _pageZeroSize = 0x100000000;
196 } else {
197 _pageZeroSize = 0x1000;
198 }
199
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000200 // Make PIE by default when targetting newer OSs.
201 switch (os) {
202 case OS::macOSX:
203 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
204 _pie = true;
205 break;
206 case OS::iOS:
207 if (minOSVersion >= 0x00040300) // iOS 4.3
208 _pie = true;
209 break;
210 case OS::iOS_simulator:
211 _pie = true;
212 break;
213 case OS::unknown:
214 break;
215 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000216 break;
217 case llvm::MachO::MH_DYLIB:
218 _globalsAreDeadStripRoots = true;
219 break;
220 case llvm::MachO::MH_BUNDLE:
221 break;
222 case llvm::MachO::MH_OBJECT:
223 _printRemainingUndefines = false;
224 _allowRemainingUndefines = true;
225 default:
226 break;
227 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000228
229 // Set default segment page sizes based on arch.
230 if (arch == arch_arm64)
231 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000232}
233
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000234uint32_t MachOLinkingContext::getCPUType() const {
235 return cpuTypeFromArch(_arch);
236}
237
238uint32_t MachOLinkingContext::getCPUSubType() const {
239 return cpuSubtypeFromArch(_arch);
240}
241
Nick Kledzike34182f2013-11-06 21:36:55 +0000242bool MachOLinkingContext::is64Bit(Arch arch) {
243 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
244 if (info->arch == arch) {
245 return (info->cputype & CPU_ARCH_ABI64);
246 }
247 }
248 // unknown archs are not 64-bit.
249 return false;
250}
251
252bool MachOLinkingContext::isHostEndian(Arch arch) {
253 assert(arch != arch_unknown);
254 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
255 if (info->arch == arch) {
256 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
257 }
258 }
259 llvm_unreachable("Unknown arch type");
260}
261
262bool MachOLinkingContext::isBigEndian(Arch arch) {
263 assert(arch != arch_unknown);
264 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
265 if (info->arch == arch) {
266 return ! info->littleEndian;
267 }
268 }
269 llvm_unreachable("Unknown arch type");
270}
271
272
273
274bool MachOLinkingContext::is64Bit() const {
275 return is64Bit(_arch);
276}
277
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000278bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000279 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000280 case MH_EXECUTE:
281 case MH_DYLINKER:
282 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000283 return true;
284 default:
285 return false;
286 }
287}
288
Nick Kledzik2458bec2014-07-16 19:49:02 +0000289bool MachOLinkingContext::needsStubsPass() const {
290 switch (_outputMachOType) {
291 case MH_EXECUTE:
292 return !_outputMachOTypeStatic;
293 case MH_DYLIB:
294 case MH_BUNDLE:
295 return true;
296 default:
297 return false;
298 }
299}
300
301bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000302 // GOT pass not used in -r mode.
303 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000304 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000305 // Only some arches use GOT pass.
306 switch (_arch) {
307 case arch_x86_64:
308 case arch_arm64:
309 return true;
310 default:
311 return false;
312 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000313}
314
Tim Northovercf78d372014-09-30 21:29:54 +0000315bool MachOLinkingContext::needsCompactUnwindPass() const {
316 switch (_outputMachOType) {
317 case MH_EXECUTE:
318 case MH_DYLIB:
319 case MH_BUNDLE:
320 return archHandler().needsCompactUnwind();
321 default:
322 return false;
323 }
324}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000325
Nick Kledzik4121bce2014-10-14 01:51:42 +0000326bool MachOLinkingContext::needsShimPass() const {
327 // Shim pass only used in final executables.
328 if (_outputMachOType == MH_OBJECT)
329 return false;
330 // Only 32-bit arm arches use Shim pass.
331 switch (_arch) {
332 case arch_armv6:
333 case arch_armv7:
334 case arch_armv7s:
335 return true;
336 default:
337 return false;
338 }
339}
340
Nick Kledzik2458bec2014-07-16 19:49:02 +0000341StringRef MachOLinkingContext::binderSymbolName() const {
342 return archHandler().stubInfo().binderSymbolName;
343}
344
345
346
347
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000348bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000349 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000350 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000351 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000352 if (parsePackedVersion(mac, parsedVersion))
353 return false;
354 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000355 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000356 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000357 if (parsePackedVersion(iOS, parsedVersion))
358 return false;
359 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000360 case OS::unknown:
361 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000362 }
363 llvm_unreachable("target not configured for iOS or MacOSX");
364}
365
366bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000367 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000368 return minOS("10.8", "6.0");
369 }
370 return false;
371}
372
373bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000374 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000375 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000376 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000377 return true;
378 else
379 return !minOS("10.8", "6.0");
380 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000381 case MH_DYLINKER:
382 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000383 return true;
384 default:
385 return false;
386 }
387}
388
Tim Northover77d82202014-07-10 11:21:06 +0000389bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000390 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000391 return llvm::sys::fs::exists(path.str());
392
393 // Otherwise, we're in test mode: only files explicitly provided on the
394 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000395 std::string key = path.str();
396 std::replace(key.begin(), key.end(), '\\', '/');
397 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000398}
399
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000400bool MachOLinkingContext::fileExists(StringRef path) const {
401 bool found = pathExists(path);
402 // Log search misses.
403 if (!found)
404 addInputFileNotFound(path);
405
406 // When testing, file is never opened, so logging is done here.
407 if (_testingFileUsage && found)
408 addInputFileDependency(path);
409
410 return found;
411}
412
Nick Kledzik2d835da2014-08-14 22:20:41 +0000413void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
414 _syslibRoots = paths;
415}
416
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000417void MachOLinkingContext::addRpath(StringRef rpath) {
418 _rpaths.push_back(rpath);
419}
420
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000421void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
422 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000423 bool addedModifiedPath = false;
424
Nick Kledzik2d835da2014-08-14 22:20:41 +0000425 // -syslibroot only applies to absolute paths.
426 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000427 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000428 SmallString<256> path(syslibRoot);
429 llvm::sys::path::append(path, libPath);
430 if (pathExists(path)) {
431 _searchDirs.push_back(path.str().copy(_allocator));
432 addedModifiedPath = true;
433 }
434 }
435 }
436
437 if (addedModifiedPath)
438 return;
439
440 // Finally, if only one -syslibroot is given, system paths which aren't in it
441 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000442 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000443 if (pathExists(libPath)) {
444 _searchDirs.push_back(libPath);
445 }
446 }
447}
448
Nick Kledzik2d835da2014-08-14 22:20:41 +0000449void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
450 bool isSystemPath) {
451 bool pathAdded = false;
452
453 // -syslibroot only used with to absolute framework search paths.
454 if (fwPath.startswith("/")) {
455 for (auto syslibRoot : _syslibRoots) {
456 SmallString<256> path(syslibRoot);
457 llvm::sys::path::append(path, fwPath);
458 if (pathExists(path)) {
459 _frameworkDirs.push_back(path.str().copy(_allocator));
460 pathAdded = true;
461 }
462 }
463 }
464 // If fwPath found in any -syslibroot, then done.
465 if (pathAdded)
466 return;
467
468 // If only one -syslibroot, system paths not in that SDK are suppressed.
469 if (isSystemPath && (_syslibRoots.size() == 1))
470 return;
471
472 // Only use raw fwPath if that directory exists.
473 if (pathExists(fwPath))
474 _frameworkDirs.push_back(fwPath);
475}
476
477
Tim Northover77d82202014-07-10 11:21:06 +0000478ErrorOr<StringRef>
479MachOLinkingContext::searchDirForLibrary(StringRef path,
480 StringRef libName) const {
481 SmallString<256> fullPath;
482 if (libName.endswith(".o")) {
483 // A request ending in .o is special: just search for the file directly.
484 fullPath.assign(path);
485 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000486 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000487 return fullPath.str().copy(_allocator);
488 return make_error_code(llvm::errc::no_such_file_or_directory);
489 }
490
491 // Search for dynamic library
492 fullPath.assign(path);
493 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000494 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000495 return fullPath.str().copy(_allocator);
496
497 // If not, try for a static library
498 fullPath.assign(path);
499 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000500 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000501 return fullPath.str().copy(_allocator);
502
503 return make_error_code(llvm::errc::no_such_file_or_directory);
504}
505
506
507
508ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
509 SmallString<256> path;
510 for (StringRef dir : searchDirs()) {
511 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
512 if (ec)
513 return ec;
514 }
515
516 return make_error_code(llvm::errc::no_such_file_or_directory);
517}
518
Nick Kledzik2d835da2014-08-14 22:20:41 +0000519
520ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
521 SmallString<256> fullPath;
522 for (StringRef dir : frameworkDirs()) {
523 fullPath.assign(dir);
524 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000525 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000526 return fullPath.str().copy(_allocator);
527 }
528
529 return make_error_code(llvm::errc::no_such_file_or_directory);
530}
531
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000532bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000533 // TODO: if -arch not specified, look at arch of first .o file.
534
Tim Northoverd30a1f22014-06-20 15:59:00 +0000535 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000536 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000537 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000538 }
539
Tim Northoverd30a1f22014-06-20 15:59:00 +0000540 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000541 diagnostics
542 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000543 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000544 }
545
Tim Northoverd30a1f22014-06-20 15:59:00 +0000546 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000547 diagnostics
548 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000549 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000550 }
551
Tim Northoverd30a1f22014-06-20 15:59:00 +0000552 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000553 diagnostics
554 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000555 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000556 }
557
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000558 // If -exported_symbols_list used, all exported symbols must be defined.
559 if (_exportMode == ExportMode::whiteList) {
560 for (const auto &symbol : _exportedSymbols)
561 addInitialUndefinedSymbol(symbol.getKey());
562 }
563
Nick Kledzik77afc712014-08-21 20:25:50 +0000564 // If -dead_strip, set up initial live symbols.
565 if (deadStrip()) {
566 // Entry point is live.
567 if (outputTypeHasEntry())
568 addDeadStripRoot(entrySymbolName());
569 // Lazy binding helper is live.
570 if (needsStubsPass())
571 addDeadStripRoot(binderSymbolName());
572 // If using -exported_symbols_list, make all exported symbols live.
573 if (_exportMode == ExportMode::whiteList) {
574 _globalsAreDeadStripRoots = false;
575 for (const auto &symbol : _exportedSymbols)
576 addDeadStripRoot(symbol.getKey());
577 }
578 }
579
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000580 addOutputFileDependency(outputPath());
581
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000582 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000583}
584
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000585void MachOLinkingContext::addPasses(PassManager &pm) {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000586 pm.add(std::unique_ptr<Pass>(new LayoutPass(
587 registry(), [&](const DefinedAtom * left, const DefinedAtom * right,
588 bool & leftBeforeRight)
589 ->bool {
590 return customAtomOrderer(left, right, leftBeforeRight);
591 })));
Nick Kledzik2458bec2014-07-16 19:49:02 +0000592 if (needsStubsPass())
593 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000594 if (needsCompactUnwindPass())
595 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000596 if (needsGOTPass())
597 mach_o::addGOTPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000598 if (needsShimPass())
599 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000600}
601
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000602Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000603 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000604 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000605 return *_writer;
606}
607
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000608ErrorOr<std::unique_ptr<MemoryBuffer>>
609MachOLinkingContext::getMemoryBuffer(StringRef path) {
610 addInputFileDependency(path);
611
Rui Ueyamadf230b22015-01-15 04:34:31 +0000612 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000613 MemoryBuffer::getFileOrSTDIN(path);
614 if (std::error_code ec = mbOrErr.getError())
615 return ec;
616 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
617
618 // If buffer contains a fat file, find required arch in fat buffer
619 // and switch buffer to point to just that required slice.
620 uint32_t offset;
621 uint32_t size;
622 if (sliceFromFatFile(*mb, offset, size))
623 return MemoryBuffer::getFileSlice(path, size, offset);
624 return std::move(mb);
625}
626
627MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
628 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000629 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000630 return nullptr;
631
Rui Ueyamadf230b22015-01-15 04:34:31 +0000632 std::vector<std::unique_ptr<File>> files;
633 if (registry().loadFile(std::move(mbOrErr.get()), files))
634 return nullptr;
635 assert(files.size() == 1 && "expected one file in dylib");
636 files[0]->parse();
637 MachODylibFile* result = reinterpret_cast<MachODylibFile*>(files[0].get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000638 // Node object now owned by _indirectDylibs vector.
Rui Ueyamadf230b22015-01-15 04:34:31 +0000639 _indirectDylibs.push_back(std::move(files[0]));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000640 return result;
641}
642
643
Nick Kledzik22c90732014-10-01 20:24:30 +0000644MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000645 // See if already loaded.
646 auto pos = _pathToDylibMap.find(path);
647 if (pos != _pathToDylibMap.end())
648 return pos->second;
649
650 // Search -L paths if of the form "libXXX.dylib"
651 std::pair<StringRef, StringRef> split = path.rsplit('/');
652 StringRef leafName = split.second;
653 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
654 // FIXME: Need to enhance searchLibrary() to only look for .dylib
655 auto libPath = searchLibrary(leafName);
656 if (!libPath.getError()) {
657 return loadIndirectDylib(libPath.get());
658 }
659 }
660
661 // Try full path with sysroot.
662 for (StringRef sysPath : _syslibRoots) {
663 SmallString<256> fullPath;
664 fullPath.assign(sysPath);
665 llvm::sys::path::append(fullPath, path);
666 if (pathExists(fullPath))
667 return loadIndirectDylib(fullPath);
668 }
669
670 // Try full path.
671 if (pathExists(path)) {
672 return loadIndirectDylib(path);
673 }
674
675 return nullptr;
676}
677
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000678uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
679 auto pos = _pathToDylibMap.find(installName);
680 if (pos != _pathToDylibMap.end())
681 return pos->second->currentVersion();
682 else
683 return 0x1000; // 1.0
684}
685
686uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
687 auto pos = _pathToDylibMap.find(installName);
688 if (pos != _pathToDylibMap.end())
689 return pos->second->compatVersion();
690 else
691 return 0x1000; // 1.0
692}
693
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000694bool MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000695 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000696 // Add indirect dylibs by asking each linked dylib to add its indirects.
697 // Iterate until no more dylibs get loaded.
698 size_t dylibCount = 0;
699 while (dylibCount != _allDylibs.size()) {
700 dylibCount = _allDylibs.size();
701 for (MachODylibFile *dylib : _allDylibs) {
702 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
703 return findIndirectDylib(path); });
704 }
705 }
706
707 // Let writer add output type specific extras.
708 return writer().createImplicitFiles(result);
709}
710
711
Nick Kledzik51720672014-10-16 19:31:28 +0000712void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
713 bool upward) const {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000714 _allDylibs.insert(dylib);
715 _pathToDylibMap[dylib->installName()] = dylib;
716 // If path is different than install name, register path too.
717 if (!dylib->path().equals(dylib->installName()))
718 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000719 if (upward)
720 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000721}
722
723
Nick Kledzik51720672014-10-16 19:31:28 +0000724bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
725 for (MachODylibFile *dylib : _upwardDylibs) {
726 if (dylib->installName().equals(installName))
727 return true;
728 }
729 return false;
730}
731
Nick Kledzik2458bec2014-07-16 19:49:02 +0000732ArchHandler &MachOLinkingContext::archHandler() const {
733 if (!_archHandler)
734 _archHandler = ArchHandler::create(_arch);
735 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000736}
737
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000738
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000739void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
740 uint8_t align2) {
741 SectionAlign entry;
742 entry.segmentName = seg;
743 entry.sectionName = sect;
744 entry.align2 = align2;
745 _sectAligns.push_back(entry);
746}
747
748bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
749 uint8_t &align2) const {
750 for (const SectionAlign &entry : _sectAligns) {
751 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
752 align2 = entry.align2;
753 return true;
754 }
755 }
756 return false;
757}
758
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000759
760void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000761 // Support old crufty export lists with bogus entries.
762 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
763 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
764 return;
765 }
766 // Only i386 MacOSX uses old ABI, so don't change those.
767 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
768 // ObjC has two differnent ABIs. Be nice and allow one export list work for
769 // both ABIs by renaming symbols.
770 if (sym.startswith(".objc_class_name_")) {
771 std::string abi2className("_OBJC_CLASS_$_");
772 abi2className += sym.substr(17);
773 _exportedSymbols.insert(copy(abi2className));
774 std::string abi2metaclassName("_OBJC_METACLASS_$_");
775 abi2metaclassName += sym.substr(17);
776 _exportedSymbols.insert(copy(abi2metaclassName));
777 return;
778 }
779 }
780
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000781 // FIXME: Support wildcards.
782 _exportedSymbols.insert(sym);
783}
784
785bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
786 switch (_exportMode) {
787 case ExportMode::globals:
788 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
789 break;
790 case ExportMode::whiteList:
791 return _exportedSymbols.count(sym);
792 case ExportMode::blackList:
793 return !_exportedSymbols.count(sym);
794 }
Yaron Keren9682c852014-09-21 05:07:44 +0000795 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000796}
797
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000798std::string MachOLinkingContext::demangle(StringRef symbolName) const {
799 // Only try to demangle symbols if -demangle on command line
800 if (!_demangle)
801 return symbolName;
802
803 // Only try to demangle symbols that look like C++ symbols
804 if (!symbolName.startswith("__Z"))
805 return symbolName;
806
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000807#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000808 SmallString<256> symBuff;
809 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
810 // Mach-O has extra leading underscore that needs to be removed.
811 const char *cstr = nullTermSym.data() + 1;
812 int status;
813 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
814 if (demangled != NULL) {
815 std::string result(demangled);
816 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
817 free(demangled);
818 return result;
819 }
820#endif
821
822 return symbolName;
823}
824
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000825std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
826 std::error_code ec;
827 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
828 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
829 if (ec) {
830 _dependencyInfo.reset();
831 return ec;
832 }
833
834 char linkerVersionOpcode = 0x00;
835 *_dependencyInfo << linkerVersionOpcode;
836 *_dependencyInfo << "lld"; // FIXME
837 *_dependencyInfo << '\0';
838
839 return std::error_code();
840}
841
842void MachOLinkingContext::addInputFileDependency(StringRef path) const {
843 if (!_dependencyInfo)
844 return;
845
846 char inputFileOpcode = 0x10;
847 *_dependencyInfo << inputFileOpcode;
848 *_dependencyInfo << path;
849 *_dependencyInfo << '\0';
850}
851
852void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
853 if (!_dependencyInfo)
854 return;
855
856 char inputFileOpcode = 0x11;
857 *_dependencyInfo << inputFileOpcode;
858 *_dependencyInfo << path;
859 *_dependencyInfo << '\0';
860}
861
862void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
863 if (!_dependencyInfo)
864 return;
865
866 char outputFileOpcode = 0x40;
867 *_dependencyInfo << outputFileOpcode;
868 *_dependencyInfo << path;
869 *_dependencyInfo << '\0';
870}
871
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000872void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
873 StringRef filename) {
874 // To support sorting static functions which may have the same name in
875 // multiple .o files, _orderFiles maps the symbol name to a vector
876 // of OrderFileNode each of which can specify a file prefix.
877 OrderFileNode info;
878 if (!filename.empty())
879 info.fileFilter = copy(filename);
880 info.order = _orderFileEntries++;
881 _orderFiles[symbol].push_back(info);
882}
883
884bool
885MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
886 const DefinedAtom *atom,
887 unsigned &ordinal) {
888 const File *objFile = &atom->file();
889 assert(objFile);
890 StringRef objName = objFile->path();
891 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
892 if (!dirAndLeaf.second.empty())
893 objName = dirAndLeaf.second;
894 for (const OrderFileNode &info : nodes) {
895 if (info.fileFilter.empty()) {
896 // Have unprefixed symbol name in order file that matches this atom.
897 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000898 return true;
899 }
900 if (info.fileFilter.equals(objName)) {
901 // Have prefixed symbol name in order file that matches atom's path.
902 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000903 return true;
904 }
905 }
906 return false;
907}
908
909bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
910 const DefinedAtom *right,
911 bool &leftBeforeRight) {
912 // No custom sorting if no order file entries.
913 if (!_orderFileEntries)
914 return false;
915
916 // Order files can only order named atoms.
917 StringRef leftName = left->name();
918 StringRef rightName = right->name();
919 if (leftName.empty() || rightName.empty())
920 return false;
921
922 // If neither is in order file list, no custom sorter.
923 auto leftPos = _orderFiles.find(leftName);
924 auto rightPos = _orderFiles.find(rightName);
925 bool leftIsOrdered = (leftPos != _orderFiles.end());
926 bool rightIsOrdered = (rightPos != _orderFiles.end());
927 if (!leftIsOrdered && !rightIsOrdered)
928 return false;
929
930 // There could be multiple symbols with same name but different file prefixes.
931 unsigned leftOrder;
932 unsigned rightOrder;
933 bool foundLeft =
934 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
935 bool foundRight = rightIsOrdered &&
936 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
937 if (!foundLeft && !foundRight)
938 return false;
939
940 // If only one is in order file list, ordered one goes first.
941 if (foundLeft != foundRight)
942 leftBeforeRight = foundLeft;
943 else
944 leftBeforeRight = (leftOrder < rightOrder);
945
946 return true;
947}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000948
Rui Ueyama61635442015-01-15 08:31:46 +0000949static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000950 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
951 File *file = node->getFile();
952 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
953 }
954 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000955}
956
957// The darwin linker processes input files in two phases. The first phase
958// links in all object (.o) files in command line order. The second phase
959// links in libraries in command line order.
960// In this function we reorder the input files so that all the object files
961// comes before any library file. We also make a group for the library files
962// so that the Resolver will reiterate over the libraries as long as we find
963// new undefines from libraries.
964void MachOLinkingContext::maybeSortInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +0000965 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +0000966 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +0000967 [](const std::unique_ptr<Node> &a,
968 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +0000969 return !isLibrary(a) && isLibrary(b);
970 });
971 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
972 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
973}
974
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000975} // end namespace lld