blob: c462891ef0d25885c883f9b32db1eb1b0eb2e62d [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"
Shankar Easwaran2bc24922013-10-29 05:12:14 +000020#include "lld/Passes/RoundTripYAMLPass.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000021#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000023#include "llvm/Config/config.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000024#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +000025#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000026#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000027#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000028#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000029#include <algorithm>
30
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000031#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000032#include <cxxabi.h>
33#endif
34
Nick Kledzik2458bec2014-07-16 19:49:02 +000035using lld::mach_o::ArchHandler;
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
Rui Ueyama0ca149f2013-08-06 22:31:59 +000076
Nick Kledzike34182f2013-11-06 21:36:55 +000077MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
78 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
79 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
80 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
81 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
82 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
83 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000084 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000085 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000086};
87
88MachOLinkingContext::Arch
89MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000090 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
91 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000092 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000093 }
94 return arch_unknown;
95}
96
97MachOLinkingContext::Arch
98MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +000099 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
100 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000101 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000102 }
103 return arch_unknown;
104}
105
Nick Kledzike5552772013-12-19 21:58:00 +0000106StringRef MachOLinkingContext::nameFromArch(Arch arch) {
107 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
108 if (info->arch == arch)
109 return info->archName;
110 }
111 return "<unknown>";
112}
113
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000114uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
115 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000116 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
117 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000118 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000119 }
120 llvm_unreachable("Unknown arch type");
121}
122
123uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
124 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000125 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
126 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000127 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000128 }
129 llvm_unreachable("Unknown arch type");
130}
131
Nick Kledzik635f9c72014-09-04 20:08:30 +0000132bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
133 return mach_o::normalized::isThinObjectFile(path, arch);
134}
135
Nick Kledzik14b5d202014-10-08 01:48:10 +0000136bool MachOLinkingContext::sliceFromFatFile(const MemoryBuffer &mb,
137 uint32_t &offset,
138 uint32_t &size) {
139 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
140}
141
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000142MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000143 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000144 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
145 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
146 _compatibilityVersion(0), _currentVersion(0), _deadStrippableDylib(false),
147 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000148 _demangle(false), _archHandler(nullptr),
Nick Kledzik8f75da02014-11-06 03:03:42 +0000149 _exportMode(ExportMode::globals),
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000150 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000151
152MachOLinkingContext::~MachOLinkingContext() {}
153
Nick Kledzik6960b072013-12-21 01:47:17 +0000154void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
155 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000156 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000157 _arch = arch;
158 _os = os;
159 _osMinVersion = minOSVersion;
160
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000161 // If min OS not specified on command line, use reasonable defaults.
162 if (minOSVersion == 0) {
163 switch (_arch) {
164 case arch_x86_64:
165 case arch_x86:
166 parsePackedVersion("10.8", _osMinVersion);
167 _os = MachOLinkingContext::OS::macOSX;
168 break;
169 case arch_armv6:
170 case arch_armv7:
171 case arch_armv7s:
172 case arch_arm64:
173 parsePackedVersion("7.0", _osMinVersion);
174 _os = MachOLinkingContext::OS::iOS;
175 break;
176 default:
177 break;
178 }
179 }
180
Tim Northoverd30a1f22014-06-20 15:59:00 +0000181 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000182 case llvm::MachO::MH_EXECUTE:
183 // If targeting newer OS, use _main
184 if (minOS("10.8", "6.0")) {
185 _entrySymbolName = "_main";
186 } else {
187 // If targeting older OS, use start (in crt1.o)
188 _entrySymbolName = "start";
189 }
190
191 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
192 // support) and 4KB on 32-bit.
193 if (is64Bit(_arch)) {
194 _pageZeroSize = 0x100000000;
195 } else {
196 _pageZeroSize = 0x1000;
197 }
198
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000199 // Make PIE by default when targetting newer OSs.
200 switch (os) {
201 case OS::macOSX:
202 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
203 _pie = true;
204 break;
205 case OS::iOS:
206 if (minOSVersion >= 0x00040300) // iOS 4.3
207 _pie = true;
208 break;
209 case OS::iOS_simulator:
210 _pie = true;
211 break;
212 case OS::unknown:
213 break;
214 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000215 break;
216 case llvm::MachO::MH_DYLIB:
217 _globalsAreDeadStripRoots = true;
218 break;
219 case llvm::MachO::MH_BUNDLE:
220 break;
221 case llvm::MachO::MH_OBJECT:
222 _printRemainingUndefines = false;
223 _allowRemainingUndefines = true;
224 default:
225 break;
226 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000227
228 // Set default segment page sizes based on arch.
229 if (arch == arch_arm64)
230 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000231}
232
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000233uint32_t MachOLinkingContext::getCPUType() const {
234 return cpuTypeFromArch(_arch);
235}
236
237uint32_t MachOLinkingContext::getCPUSubType() const {
238 return cpuSubtypeFromArch(_arch);
239}
240
Nick Kledzike34182f2013-11-06 21:36:55 +0000241bool MachOLinkingContext::is64Bit(Arch arch) {
242 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
243 if (info->arch == arch) {
244 return (info->cputype & CPU_ARCH_ABI64);
245 }
246 }
247 // unknown archs are not 64-bit.
248 return false;
249}
250
251bool MachOLinkingContext::isHostEndian(Arch arch) {
252 assert(arch != arch_unknown);
253 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
254 if (info->arch == arch) {
255 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
256 }
257 }
258 llvm_unreachable("Unknown arch type");
259}
260
261bool MachOLinkingContext::isBigEndian(Arch arch) {
262 assert(arch != arch_unknown);
263 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
264 if (info->arch == arch) {
265 return ! info->littleEndian;
266 }
267 }
268 llvm_unreachable("Unknown arch type");
269}
270
271
272
273bool MachOLinkingContext::is64Bit() const {
274 return is64Bit(_arch);
275}
276
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000277bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000278 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000279 case MH_EXECUTE:
280 case MH_DYLINKER:
281 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000282 return true;
283 default:
284 return false;
285 }
286}
287
Nick Kledzik2458bec2014-07-16 19:49:02 +0000288bool MachOLinkingContext::needsStubsPass() const {
289 switch (_outputMachOType) {
290 case MH_EXECUTE:
291 return !_outputMachOTypeStatic;
292 case MH_DYLIB:
293 case MH_BUNDLE:
294 return true;
295 default:
296 return false;
297 }
298}
299
300bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000301 // GOT pass not used in -r mode.
302 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000303 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000304 // Only some arches use GOT pass.
305 switch (_arch) {
306 case arch_x86_64:
307 case arch_arm64:
308 return true;
309 default:
310 return false;
311 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000312}
313
Tim Northovercf78d372014-09-30 21:29:54 +0000314bool MachOLinkingContext::needsCompactUnwindPass() const {
315 switch (_outputMachOType) {
316 case MH_EXECUTE:
317 case MH_DYLIB:
318 case MH_BUNDLE:
319 return archHandler().needsCompactUnwind();
320 default:
321 return false;
322 }
323}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000324
Nick Kledzik4121bce2014-10-14 01:51:42 +0000325bool MachOLinkingContext::needsShimPass() const {
326 // Shim pass only used in final executables.
327 if (_outputMachOType == MH_OBJECT)
328 return false;
329 // Only 32-bit arm arches use Shim pass.
330 switch (_arch) {
331 case arch_armv6:
332 case arch_armv7:
333 case arch_armv7s:
334 return true;
335 default:
336 return false;
337 }
338}
339
Nick Kledzik2458bec2014-07-16 19:49:02 +0000340StringRef MachOLinkingContext::binderSymbolName() const {
341 return archHandler().stubInfo().binderSymbolName;
342}
343
344
345
346
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000347bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000348 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000349 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000350 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000351 if (parsePackedVersion(mac, parsedVersion))
352 return false;
353 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000354 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000355 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000356 if (parsePackedVersion(iOS, parsedVersion))
357 return false;
358 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000359 case OS::unknown:
360 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000361 }
362 llvm_unreachable("target not configured for iOS or MacOSX");
363}
364
365bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000366 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000367 return minOS("10.8", "6.0");
368 }
369 return false;
370}
371
372bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000373 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000374 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000375 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000376 return true;
377 else
378 return !minOS("10.8", "6.0");
379 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000380 case MH_DYLINKER:
381 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000382 return true;
383 default:
384 return false;
385 }
386}
387
Tim Northover77d82202014-07-10 11:21:06 +0000388bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000389 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000390 return llvm::sys::fs::exists(path.str());
391
392 // Otherwise, we're in test mode: only files explicitly provided on the
393 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000394 std::string key = path.str();
395 std::replace(key.begin(), key.end(), '\\', '/');
396 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000397}
398
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000399bool MachOLinkingContext::fileExists(StringRef path) const {
400 bool found = pathExists(path);
401 // Log search misses.
402 if (!found)
403 addInputFileNotFound(path);
404
405 // When testing, file is never opened, so logging is done here.
406 if (_testingFileUsage && found)
407 addInputFileDependency(path);
408
409 return found;
410}
411
Nick Kledzik2d835da2014-08-14 22:20:41 +0000412void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
413 _syslibRoots = paths;
414}
415
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000416void MachOLinkingContext::addRpath(StringRef rpath) {
417 _rpaths.push_back(rpath);
418}
419
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000420void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
421 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000422 bool addedModifiedPath = false;
423
Nick Kledzik2d835da2014-08-14 22:20:41 +0000424 // -syslibroot only applies to absolute paths.
425 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000426 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000427 SmallString<256> path(syslibRoot);
428 llvm::sys::path::append(path, libPath);
429 if (pathExists(path)) {
430 _searchDirs.push_back(path.str().copy(_allocator));
431 addedModifiedPath = true;
432 }
433 }
434 }
435
436 if (addedModifiedPath)
437 return;
438
439 // Finally, if only one -syslibroot is given, system paths which aren't in it
440 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000441 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000442 if (pathExists(libPath)) {
443 _searchDirs.push_back(libPath);
444 }
445 }
446}
447
Nick Kledzik2d835da2014-08-14 22:20:41 +0000448void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
449 bool isSystemPath) {
450 bool pathAdded = false;
451
452 // -syslibroot only used with to absolute framework search paths.
453 if (fwPath.startswith("/")) {
454 for (auto syslibRoot : _syslibRoots) {
455 SmallString<256> path(syslibRoot);
456 llvm::sys::path::append(path, fwPath);
457 if (pathExists(path)) {
458 _frameworkDirs.push_back(path.str().copy(_allocator));
459 pathAdded = true;
460 }
461 }
462 }
463 // If fwPath found in any -syslibroot, then done.
464 if (pathAdded)
465 return;
466
467 // If only one -syslibroot, system paths not in that SDK are suppressed.
468 if (isSystemPath && (_syslibRoots.size() == 1))
469 return;
470
471 // Only use raw fwPath if that directory exists.
472 if (pathExists(fwPath))
473 _frameworkDirs.push_back(fwPath);
474}
475
476
Tim Northover77d82202014-07-10 11:21:06 +0000477ErrorOr<StringRef>
478MachOLinkingContext::searchDirForLibrary(StringRef path,
479 StringRef libName) const {
480 SmallString<256> fullPath;
481 if (libName.endswith(".o")) {
482 // A request ending in .o is special: just search for the file directly.
483 fullPath.assign(path);
484 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000485 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000486 return fullPath.str().copy(_allocator);
487 return make_error_code(llvm::errc::no_such_file_or_directory);
488 }
489
490 // Search for dynamic library
491 fullPath.assign(path);
492 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000493 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000494 return fullPath.str().copy(_allocator);
495
496 // If not, try for a static library
497 fullPath.assign(path);
498 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000499 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000500 return fullPath.str().copy(_allocator);
501
502 return make_error_code(llvm::errc::no_such_file_or_directory);
503}
504
505
506
507ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
508 SmallString<256> path;
509 for (StringRef dir : searchDirs()) {
510 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
511 if (ec)
512 return ec;
513 }
514
515 return make_error_code(llvm::errc::no_such_file_or_directory);
516}
517
Nick Kledzik2d835da2014-08-14 22:20:41 +0000518
519ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
520 SmallString<256> fullPath;
521 for (StringRef dir : frameworkDirs()) {
522 fullPath.assign(dir);
523 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000524 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000525 return fullPath.str().copy(_allocator);
526 }
527
528 return make_error_code(llvm::errc::no_such_file_or_directory);
529}
530
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000531bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000532 // TODO: if -arch not specified, look at arch of first .o file.
533
Tim Northoverd30a1f22014-06-20 15:59:00 +0000534 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000535 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000536 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000537 }
538
Tim Northoverd30a1f22014-06-20 15:59:00 +0000539 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000540 diagnostics
541 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000542 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000543 }
544
Tim Northoverd30a1f22014-06-20 15:59:00 +0000545 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000546 diagnostics
547 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000548 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000549 }
550
Tim Northoverd30a1f22014-06-20 15:59:00 +0000551 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000552 diagnostics
553 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000554 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000555 }
556
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000557 // If -exported_symbols_list used, all exported symbols must be defined.
558 if (_exportMode == ExportMode::whiteList) {
559 for (const auto &symbol : _exportedSymbols)
560 addInitialUndefinedSymbol(symbol.getKey());
561 }
562
Nick Kledzik77afc712014-08-21 20:25:50 +0000563 // If -dead_strip, set up initial live symbols.
564 if (deadStrip()) {
565 // Entry point is live.
566 if (outputTypeHasEntry())
567 addDeadStripRoot(entrySymbolName());
568 // Lazy binding helper is live.
569 if (needsStubsPass())
570 addDeadStripRoot(binderSymbolName());
571 // If using -exported_symbols_list, make all exported symbols live.
572 if (_exportMode == ExportMode::whiteList) {
573 _globalsAreDeadStripRoots = false;
574 for (const auto &symbol : _exportedSymbols)
575 addDeadStripRoot(symbol.getKey());
576 }
577 }
578
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000579 addOutputFileDependency(outputPath());
580
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000581 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000582}
583
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000584void MachOLinkingContext::addPasses(PassManager &pm) {
Rui Ueyama00762152015-02-05 20:05:33 +0000585 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000586 if (needsStubsPass())
587 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000588 if (needsCompactUnwindPass())
589 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000590 if (needsGOTPass())
591 mach_o::addGOTPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000592 if (needsShimPass())
593 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000594}
595
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000596Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000597 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000598 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000599 return *_writer;
600}
601
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000602ErrorOr<std::unique_ptr<MemoryBuffer>>
603MachOLinkingContext::getMemoryBuffer(StringRef path) {
604 addInputFileDependency(path);
605
Rui Ueyamadf230b22015-01-15 04:34:31 +0000606 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000607 MemoryBuffer::getFileOrSTDIN(path);
608 if (std::error_code ec = mbOrErr.getError())
609 return ec;
610 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
611
612 // If buffer contains a fat file, find required arch in fat buffer
613 // and switch buffer to point to just that required slice.
614 uint32_t offset;
615 uint32_t size;
616 if (sliceFromFatFile(*mb, offset, size))
617 return MemoryBuffer::getFileSlice(path, size, offset);
618 return std::move(mb);
619}
620
621MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
622 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000623 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000624 return nullptr;
625
Rui Ueyamadf230b22015-01-15 04:34:31 +0000626 std::vector<std::unique_ptr<File>> files;
627 if (registry().loadFile(std::move(mbOrErr.get()), files))
628 return nullptr;
629 assert(files.size() == 1 && "expected one file in dylib");
630 files[0]->parse();
631 MachODylibFile* result = reinterpret_cast<MachODylibFile*>(files[0].get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000632 // Node object now owned by _indirectDylibs vector.
Rui Ueyamadf230b22015-01-15 04:34:31 +0000633 _indirectDylibs.push_back(std::move(files[0]));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000634 return result;
635}
636
637
Nick Kledzik22c90732014-10-01 20:24:30 +0000638MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000639 // See if already loaded.
640 auto pos = _pathToDylibMap.find(path);
641 if (pos != _pathToDylibMap.end())
642 return pos->second;
643
644 // Search -L paths if of the form "libXXX.dylib"
645 std::pair<StringRef, StringRef> split = path.rsplit('/');
646 StringRef leafName = split.second;
647 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
648 // FIXME: Need to enhance searchLibrary() to only look for .dylib
649 auto libPath = searchLibrary(leafName);
650 if (!libPath.getError()) {
651 return loadIndirectDylib(libPath.get());
652 }
653 }
654
655 // Try full path with sysroot.
656 for (StringRef sysPath : _syslibRoots) {
657 SmallString<256> fullPath;
658 fullPath.assign(sysPath);
659 llvm::sys::path::append(fullPath, path);
660 if (pathExists(fullPath))
661 return loadIndirectDylib(fullPath);
662 }
663
664 // Try full path.
665 if (pathExists(path)) {
666 return loadIndirectDylib(path);
667 }
668
669 return nullptr;
670}
671
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000672uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
673 auto pos = _pathToDylibMap.find(installName);
674 if (pos != _pathToDylibMap.end())
675 return pos->second->currentVersion();
676 else
677 return 0x1000; // 1.0
678}
679
680uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
681 auto pos = _pathToDylibMap.find(installName);
682 if (pos != _pathToDylibMap.end())
683 return pos->second->compatVersion();
684 else
685 return 0x1000; // 1.0
686}
687
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000688bool MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000689 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000690 // Add indirect dylibs by asking each linked dylib to add its indirects.
691 // Iterate until no more dylibs get loaded.
692 size_t dylibCount = 0;
693 while (dylibCount != _allDylibs.size()) {
694 dylibCount = _allDylibs.size();
695 for (MachODylibFile *dylib : _allDylibs) {
696 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
697 return findIndirectDylib(path); });
698 }
699 }
700
701 // Let writer add output type specific extras.
702 return writer().createImplicitFiles(result);
703}
704
705
Nick Kledzik51720672014-10-16 19:31:28 +0000706void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
707 bool upward) const {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000708 _allDylibs.insert(dylib);
709 _pathToDylibMap[dylib->installName()] = dylib;
710 // If path is different than install name, register path too.
711 if (!dylib->path().equals(dylib->installName()))
712 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000713 if (upward)
714 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000715}
716
717
Nick Kledzik51720672014-10-16 19:31:28 +0000718bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
719 for (MachODylibFile *dylib : _upwardDylibs) {
720 if (dylib->installName().equals(installName))
721 return true;
722 }
723 return false;
724}
725
Nick Kledzik2458bec2014-07-16 19:49:02 +0000726ArchHandler &MachOLinkingContext::archHandler() const {
727 if (!_archHandler)
728 _archHandler = ArchHandler::create(_arch);
729 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000730}
731
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000732
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000733void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
734 uint8_t align2) {
735 SectionAlign entry;
736 entry.segmentName = seg;
737 entry.sectionName = sect;
738 entry.align2 = align2;
739 _sectAligns.push_back(entry);
740}
741
742bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
743 uint8_t &align2) const {
744 for (const SectionAlign &entry : _sectAligns) {
745 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
746 align2 = entry.align2;
747 return true;
748 }
749 }
750 return false;
751}
752
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000753
754void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000755 // Support old crufty export lists with bogus entries.
756 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
757 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
758 return;
759 }
760 // Only i386 MacOSX uses old ABI, so don't change those.
761 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
762 // ObjC has two differnent ABIs. Be nice and allow one export list work for
763 // both ABIs by renaming symbols.
764 if (sym.startswith(".objc_class_name_")) {
765 std::string abi2className("_OBJC_CLASS_$_");
766 abi2className += sym.substr(17);
767 _exportedSymbols.insert(copy(abi2className));
768 std::string abi2metaclassName("_OBJC_METACLASS_$_");
769 abi2metaclassName += sym.substr(17);
770 _exportedSymbols.insert(copy(abi2metaclassName));
771 return;
772 }
773 }
774
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000775 // FIXME: Support wildcards.
776 _exportedSymbols.insert(sym);
777}
778
779bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
780 switch (_exportMode) {
781 case ExportMode::globals:
782 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
783 break;
784 case ExportMode::whiteList:
785 return _exportedSymbols.count(sym);
786 case ExportMode::blackList:
787 return !_exportedSymbols.count(sym);
788 }
Yaron Keren9682c852014-09-21 05:07:44 +0000789 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000790}
791
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000792std::string MachOLinkingContext::demangle(StringRef symbolName) const {
793 // Only try to demangle symbols if -demangle on command line
794 if (!_demangle)
795 return symbolName;
796
797 // Only try to demangle symbols that look like C++ symbols
798 if (!symbolName.startswith("__Z"))
799 return symbolName;
800
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000801#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000802 SmallString<256> symBuff;
803 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
804 // Mach-O has extra leading underscore that needs to be removed.
805 const char *cstr = nullTermSym.data() + 1;
806 int status;
807 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
808 if (demangled != NULL) {
809 std::string result(demangled);
810 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
811 free(demangled);
812 return result;
813 }
814#endif
815
816 return symbolName;
817}
818
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000819std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
820 std::error_code ec;
821 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
822 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
823 if (ec) {
824 _dependencyInfo.reset();
825 return ec;
826 }
827
828 char linkerVersionOpcode = 0x00;
829 *_dependencyInfo << linkerVersionOpcode;
830 *_dependencyInfo << "lld"; // FIXME
831 *_dependencyInfo << '\0';
832
833 return std::error_code();
834}
835
836void MachOLinkingContext::addInputFileDependency(StringRef path) const {
837 if (!_dependencyInfo)
838 return;
839
840 char inputFileOpcode = 0x10;
841 *_dependencyInfo << inputFileOpcode;
842 *_dependencyInfo << path;
843 *_dependencyInfo << '\0';
844}
845
846void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
847 if (!_dependencyInfo)
848 return;
849
850 char inputFileOpcode = 0x11;
851 *_dependencyInfo << inputFileOpcode;
852 *_dependencyInfo << path;
853 *_dependencyInfo << '\0';
854}
855
856void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
857 if (!_dependencyInfo)
858 return;
859
860 char outputFileOpcode = 0x40;
861 *_dependencyInfo << outputFileOpcode;
862 *_dependencyInfo << path;
863 *_dependencyInfo << '\0';
864}
865
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000866void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
867 StringRef filename) {
868 // To support sorting static functions which may have the same name in
869 // multiple .o files, _orderFiles maps the symbol name to a vector
870 // of OrderFileNode each of which can specify a file prefix.
871 OrderFileNode info;
872 if (!filename.empty())
873 info.fileFilter = copy(filename);
874 info.order = _orderFileEntries++;
875 _orderFiles[symbol].push_back(info);
876}
877
878bool
879MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
880 const DefinedAtom *atom,
881 unsigned &ordinal) {
882 const File *objFile = &atom->file();
883 assert(objFile);
884 StringRef objName = objFile->path();
885 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
886 if (!dirAndLeaf.second.empty())
887 objName = dirAndLeaf.second;
888 for (const OrderFileNode &info : nodes) {
889 if (info.fileFilter.empty()) {
890 // Have unprefixed symbol name in order file that matches this atom.
891 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000892 return true;
893 }
894 if (info.fileFilter.equals(objName)) {
895 // Have prefixed symbol name in order file that matches atom's path.
896 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000897 return true;
898 }
899 }
900 return false;
901}
902
903bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
904 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000905 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000906 // No custom sorting if no order file entries.
907 if (!_orderFileEntries)
908 return false;
909
910 // Order files can only order named atoms.
911 StringRef leftName = left->name();
912 StringRef rightName = right->name();
913 if (leftName.empty() || rightName.empty())
914 return false;
915
916 // If neither is in order file list, no custom sorter.
917 auto leftPos = _orderFiles.find(leftName);
918 auto rightPos = _orderFiles.find(rightName);
919 bool leftIsOrdered = (leftPos != _orderFiles.end());
920 bool rightIsOrdered = (rightPos != _orderFiles.end());
921 if (!leftIsOrdered && !rightIsOrdered)
922 return false;
923
924 // There could be multiple symbols with same name but different file prefixes.
925 unsigned leftOrder;
926 unsigned rightOrder;
927 bool foundLeft =
928 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
929 bool foundRight = rightIsOrdered &&
930 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
931 if (!foundLeft && !foundRight)
932 return false;
933
934 // If only one is in order file list, ordered one goes first.
935 if (foundLeft != foundRight)
936 leftBeforeRight = foundLeft;
937 else
938 leftBeforeRight = (leftOrder < rightOrder);
939
940 return true;
941}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000942
Rui Ueyama61635442015-01-15 08:31:46 +0000943static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000944 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
945 File *file = node->getFile();
946 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
947 }
948 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000949}
950
951// The darwin linker processes input files in two phases. The first phase
952// links in all object (.o) files in command line order. The second phase
953// links in libraries in command line order.
954// In this function we reorder the input files so that all the object files
955// comes before any library file. We also make a group for the library files
956// so that the Resolver will reiterate over the libraries as long as we find
957// new undefines from libraries.
958void MachOLinkingContext::maybeSortInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +0000959 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +0000960 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +0000961 [](const std::unique_ptr<Node> &a,
962 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +0000963 return !isLibrary(a) && isLibrary(b);
964 });
965 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
966 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
967}
968
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000969} // end namespace lld