blob: 85c20b3a9326ccc8231295b7bb78a0dbb5eb8325 [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 Ueyama0ca149f2013-08-06 22:31:59 +000015#include "lld/Core/PassManager.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000016#include "lld/Driver/DarwinInputGraph.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000017#include "lld/Passes/LayoutPass.h"
Shankar Easwaran2bc24922013-10-29 05:12:14 +000018#include "lld/Passes/RoundTripYAMLPass.h"
Shankar Easwaran2b67fca2014-10-18 05:33:55 +000019#include "lld/ReaderWriter/Reader.h"
20#include "lld/ReaderWriter/Writer.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"
Tim Northover77d82202014-07-10 11:21:06 +000024#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000025#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000026#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000027#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000028#include <algorithm>
29
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000030#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000031#include <cxxabi.h>
32#endif
33
Nick Kledzik2458bec2014-07-16 19:49:02 +000034using lld::mach_o::ArchHandler;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000035using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000036using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000037
38namespace lld {
39
Nick Kledzike850d9d2013-09-10 23:46:57 +000040bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
41 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000042
43 if (str.empty())
44 return false;
45
46 SmallVector<StringRef, 3> parts;
47 llvm::SplitString(str, parts, ".");
48
49 unsigned long long num;
50 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
51 return true;
52 if (num > 65535)
53 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000054 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000055
56 if (parts.size() > 1) {
57 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
58 return true;
59 if (num > 255)
60 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000061 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000062 }
63
64 if (parts.size() > 2) {
65 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
66 return true;
67 if (num > 255)
68 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000069 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000070 }
71
72 return false;
73}
74
Rui Ueyama0ca149f2013-08-06 22:31:59 +000075
Nick Kledzike34182f2013-11-06 21:36:55 +000076MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
77 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
78 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
79 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
80 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
81 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
82 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000083 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000084 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000085};
86
87MachOLinkingContext::Arch
88MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000089 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
90 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000091 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000092 }
93 return arch_unknown;
94}
95
96MachOLinkingContext::Arch
97MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +000098 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
99 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000100 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000101 }
102 return arch_unknown;
103}
104
Nick Kledzike5552772013-12-19 21:58:00 +0000105StringRef MachOLinkingContext::nameFromArch(Arch arch) {
106 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
107 if (info->arch == arch)
108 return info->archName;
109 }
110 return "<unknown>";
111}
112
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000113uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
114 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000115 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
116 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000117 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000118 }
119 llvm_unreachable("Unknown arch type");
120}
121
122uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
123 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000124 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
125 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000126 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000127 }
128 llvm_unreachable("Unknown arch type");
129}
130
Nick Kledzik635f9c72014-09-04 20:08:30 +0000131bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
132 return mach_o::normalized::isThinObjectFile(path, arch);
133}
134
Nick Kledzik14b5d202014-10-08 01:48:10 +0000135bool MachOLinkingContext::sliceFromFatFile(const MemoryBuffer &mb,
136 uint32_t &offset,
137 uint32_t &size) {
138 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
139}
140
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000141MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000142 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000143 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
144 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
145 _compatibilityVersion(0), _currentVersion(0), _deadStrippableDylib(false),
146 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000147 _demangle(false), _archHandler(nullptr),
Nick Kledzik8f75da02014-11-06 03:03:42 +0000148 _exportMode(ExportMode::globals),
149 _debugInfoMode(DebugInfoMode::addDebugMap) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000150
151MachOLinkingContext::~MachOLinkingContext() {}
152
Nick Kledzik6960b072013-12-21 01:47:17 +0000153void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
154 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000155 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000156 _arch = arch;
157 _os = os;
158 _osMinVersion = minOSVersion;
159
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000160 // If min OS not specified on command line, use reasonable defaults.
161 if (minOSVersion == 0) {
162 switch (_arch) {
163 case arch_x86_64:
164 case arch_x86:
165 parsePackedVersion("10.8", _osMinVersion);
166 _os = MachOLinkingContext::OS::macOSX;
167 break;
168 case arch_armv6:
169 case arch_armv7:
170 case arch_armv7s:
171 case arch_arm64:
172 parsePackedVersion("7.0", _osMinVersion);
173 _os = MachOLinkingContext::OS::iOS;
174 break;
175 default:
176 break;
177 }
178 }
179
Tim Northoverd30a1f22014-06-20 15:59:00 +0000180 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000181 case llvm::MachO::MH_EXECUTE:
182 // If targeting newer OS, use _main
183 if (minOS("10.8", "6.0")) {
184 _entrySymbolName = "_main";
185 } else {
186 // If targeting older OS, use start (in crt1.o)
187 _entrySymbolName = "start";
188 }
189
190 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
191 // support) and 4KB on 32-bit.
192 if (is64Bit(_arch)) {
193 _pageZeroSize = 0x100000000;
194 } else {
195 _pageZeroSize = 0x1000;
196 }
197
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000198 // Make PIE by default when targetting newer OSs.
199 switch (os) {
200 case OS::macOSX:
201 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
202 _pie = true;
203 break;
204 case OS::iOS:
205 if (minOSVersion >= 0x00040300) // iOS 4.3
206 _pie = true;
207 break;
208 case OS::iOS_simulator:
209 _pie = true;
210 break;
211 case OS::unknown:
212 break;
213 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000214 break;
215 case llvm::MachO::MH_DYLIB:
216 _globalsAreDeadStripRoots = true;
217 break;
218 case llvm::MachO::MH_BUNDLE:
219 break;
220 case llvm::MachO::MH_OBJECT:
221 _printRemainingUndefines = false;
222 _allowRemainingUndefines = true;
223 default:
224 break;
225 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000226
227 // Set default segment page sizes based on arch.
228 if (arch == arch_arm64)
229 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000230}
231
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000232uint32_t MachOLinkingContext::getCPUType() const {
233 return cpuTypeFromArch(_arch);
234}
235
236uint32_t MachOLinkingContext::getCPUSubType() const {
237 return cpuSubtypeFromArch(_arch);
238}
239
Nick Kledzike34182f2013-11-06 21:36:55 +0000240bool MachOLinkingContext::is64Bit(Arch arch) {
241 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
242 if (info->arch == arch) {
243 return (info->cputype & CPU_ARCH_ABI64);
244 }
245 }
246 // unknown archs are not 64-bit.
247 return false;
248}
249
250bool MachOLinkingContext::isHostEndian(Arch arch) {
251 assert(arch != arch_unknown);
252 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
253 if (info->arch == arch) {
254 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
255 }
256 }
257 llvm_unreachable("Unknown arch type");
258}
259
260bool MachOLinkingContext::isBigEndian(Arch arch) {
261 assert(arch != arch_unknown);
262 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
263 if (info->arch == arch) {
264 return ! info->littleEndian;
265 }
266 }
267 llvm_unreachable("Unknown arch type");
268}
269
270
271
272bool MachOLinkingContext::is64Bit() const {
273 return is64Bit(_arch);
274}
275
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000276bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000277 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000278 case MH_EXECUTE:
279 case MH_DYLINKER:
280 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000281 return true;
282 default:
283 return false;
284 }
285}
286
Nick Kledzik2458bec2014-07-16 19:49:02 +0000287bool MachOLinkingContext::needsStubsPass() const {
288 switch (_outputMachOType) {
289 case MH_EXECUTE:
290 return !_outputMachOTypeStatic;
291 case MH_DYLIB:
292 case MH_BUNDLE:
293 return true;
294 default:
295 return false;
296 }
297}
298
299bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000300 // GOT pass not used in -r mode.
301 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000302 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000303 // Only some arches use GOT pass.
304 switch (_arch) {
305 case arch_x86_64:
306 case arch_arm64:
307 return true;
308 default:
309 return false;
310 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000311}
312
Tim Northovercf78d372014-09-30 21:29:54 +0000313bool MachOLinkingContext::needsCompactUnwindPass() const {
314 switch (_outputMachOType) {
315 case MH_EXECUTE:
316 case MH_DYLIB:
317 case MH_BUNDLE:
318 return archHandler().needsCompactUnwind();
319 default:
320 return false;
321 }
322}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000323
Nick Kledzik4121bce2014-10-14 01:51:42 +0000324bool MachOLinkingContext::needsShimPass() const {
325 // Shim pass only used in final executables.
326 if (_outputMachOType == MH_OBJECT)
327 return false;
328 // Only 32-bit arm arches use Shim pass.
329 switch (_arch) {
330 case arch_armv6:
331 case arch_armv7:
332 case arch_armv7s:
333 return true;
334 default:
335 return false;
336 }
337}
338
Nick Kledzik2458bec2014-07-16 19:49:02 +0000339StringRef MachOLinkingContext::binderSymbolName() const {
340 return archHandler().stubInfo().binderSymbolName;
341}
342
343
344
345
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000346bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000347 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000348 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000349 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000350 if (parsePackedVersion(mac, parsedVersion))
351 return false;
352 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000353 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000354 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000355 if (parsePackedVersion(iOS, parsedVersion))
356 return false;
357 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000358 case OS::unknown:
359 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000360 }
361 llvm_unreachable("target not configured for iOS or MacOSX");
362}
363
364bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000365 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000366 return minOS("10.8", "6.0");
367 }
368 return false;
369}
370
371bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000372 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000373 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000374 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000375 return true;
376 else
377 return !minOS("10.8", "6.0");
378 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000379 case MH_DYLINKER:
380 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000381 return true;
382 default:
383 return false;
384 }
385}
386
Tim Northover77d82202014-07-10 11:21:06 +0000387bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000388 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000389 return llvm::sys::fs::exists(path.str());
390
391 // Otherwise, we're in test mode: only files explicitly provided on the
392 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000393 std::string key = path.str();
394 std::replace(key.begin(), key.end(), '\\', '/');
395 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000396}
397
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000398bool MachOLinkingContext::fileExists(StringRef path) const {
399 bool found = pathExists(path);
400 // Log search misses.
401 if (!found)
402 addInputFileNotFound(path);
403
404 // When testing, file is never opened, so logging is done here.
405 if (_testingFileUsage && found)
406 addInputFileDependency(path);
407
408 return found;
409}
410
Nick Kledzik2d835da2014-08-14 22:20:41 +0000411void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
412 _syslibRoots = paths;
413}
414
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000415void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
416 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000417 bool addedModifiedPath = false;
418
Nick Kledzik2d835da2014-08-14 22:20:41 +0000419 // -syslibroot only applies to absolute paths.
420 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000421 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000422 SmallString<256> path(syslibRoot);
423 llvm::sys::path::append(path, libPath);
424 if (pathExists(path)) {
425 _searchDirs.push_back(path.str().copy(_allocator));
426 addedModifiedPath = true;
427 }
428 }
429 }
430
431 if (addedModifiedPath)
432 return;
433
434 // Finally, if only one -syslibroot is given, system paths which aren't in it
435 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000436 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000437 if (pathExists(libPath)) {
438 _searchDirs.push_back(libPath);
439 }
440 }
441}
442
Nick Kledzik2d835da2014-08-14 22:20:41 +0000443void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
444 bool isSystemPath) {
445 bool pathAdded = false;
446
447 // -syslibroot only used with to absolute framework search paths.
448 if (fwPath.startswith("/")) {
449 for (auto syslibRoot : _syslibRoots) {
450 SmallString<256> path(syslibRoot);
451 llvm::sys::path::append(path, fwPath);
452 if (pathExists(path)) {
453 _frameworkDirs.push_back(path.str().copy(_allocator));
454 pathAdded = true;
455 }
456 }
457 }
458 // If fwPath found in any -syslibroot, then done.
459 if (pathAdded)
460 return;
461
462 // If only one -syslibroot, system paths not in that SDK are suppressed.
463 if (isSystemPath && (_syslibRoots.size() == 1))
464 return;
465
466 // Only use raw fwPath if that directory exists.
467 if (pathExists(fwPath))
468 _frameworkDirs.push_back(fwPath);
469}
470
471
Tim Northover77d82202014-07-10 11:21:06 +0000472ErrorOr<StringRef>
473MachOLinkingContext::searchDirForLibrary(StringRef path,
474 StringRef libName) const {
475 SmallString<256> fullPath;
476 if (libName.endswith(".o")) {
477 // A request ending in .o is special: just search for the file directly.
478 fullPath.assign(path);
479 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000480 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000481 return fullPath.str().copy(_allocator);
482 return make_error_code(llvm::errc::no_such_file_or_directory);
483 }
484
485 // Search for dynamic library
486 fullPath.assign(path);
487 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000488 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000489 return fullPath.str().copy(_allocator);
490
491 // If not, try for a static library
492 fullPath.assign(path);
493 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
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 return make_error_code(llvm::errc::no_such_file_or_directory);
498}
499
500
501
502ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
503 SmallString<256> path;
504 for (StringRef dir : searchDirs()) {
505 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
506 if (ec)
507 return ec;
508 }
509
510 return make_error_code(llvm::errc::no_such_file_or_directory);
511}
512
Nick Kledzik2d835da2014-08-14 22:20:41 +0000513
514ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
515 SmallString<256> fullPath;
516 for (StringRef dir : frameworkDirs()) {
517 fullPath.assign(dir);
518 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000519 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000520 return fullPath.str().copy(_allocator);
521 }
522
523 return make_error_code(llvm::errc::no_such_file_or_directory);
524}
525
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000526bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000527 // TODO: if -arch not specified, look at arch of first .o file.
528
Tim Northoverd30a1f22014-06-20 15:59:00 +0000529 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000530 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000531 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000532 }
533
Tim Northoverd30a1f22014-06-20 15:59:00 +0000534 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000535 diagnostics
536 << "error: -compatibility_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 (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000541 diagnostics
542 << "error: -mark_dead_strippable_dylib 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 (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000547 diagnostics
548 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000549 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000550 }
551
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000552 // If -exported_symbols_list used, all exported symbols must be defined.
553 if (_exportMode == ExportMode::whiteList) {
554 for (const auto &symbol : _exportedSymbols)
555 addInitialUndefinedSymbol(symbol.getKey());
556 }
557
Nick Kledzik77afc712014-08-21 20:25:50 +0000558 // If -dead_strip, set up initial live symbols.
559 if (deadStrip()) {
560 // Entry point is live.
561 if (outputTypeHasEntry())
562 addDeadStripRoot(entrySymbolName());
563 // Lazy binding helper is live.
564 if (needsStubsPass())
565 addDeadStripRoot(binderSymbolName());
566 // If using -exported_symbols_list, make all exported symbols live.
567 if (_exportMode == ExportMode::whiteList) {
568 _globalsAreDeadStripRoots = false;
569 for (const auto &symbol : _exportedSymbols)
570 addDeadStripRoot(symbol.getKey());
571 }
572 }
573
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000574 addOutputFileDependency(outputPath());
575
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000576 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000577}
578
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000579void MachOLinkingContext::addPasses(PassManager &pm) {
Nico Rieckb9d84f42014-02-24 21:14:37 +0000580 pm.add(std::unique_ptr<Pass>(new LayoutPass(registry())));
Nick Kledzik2458bec2014-07-16 19:49:02 +0000581 if (needsStubsPass())
582 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000583 if (needsCompactUnwindPass())
584 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000585 if (needsGOTPass())
586 mach_o::addGOTPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000587 if (needsShimPass())
588 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000589}
590
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000591Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000592 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000593 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000594 return *_writer;
595}
596
Nick Kledzik22c90732014-10-01 20:24:30 +0000597MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
Nick Kledzik51720672014-10-16 19:31:28 +0000598 std::unique_ptr<MachOFileNode> node(new MachOFileNode(path, *this));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000599 std::error_code ec = node->parse(*this, llvm::errs());
600 if (ec)
601 return nullptr;
602
603 assert(node->files().size() == 1 && "expected one file in dylib");
604 // lld::File object is owned by MachOFileNode object. This method returns
605 // an unowned pointer to the lld::File object.
606 MachODylibFile* result = reinterpret_cast<MachODylibFile*>(
607 node->files().front().get());
608
609 // Node object now owned by _indirectDylibs vector.
610 _indirectDylibs.push_back(std::move(node));
611
612 return result;
613}
614
615
Nick Kledzik22c90732014-10-01 20:24:30 +0000616MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000617 // See if already loaded.
618 auto pos = _pathToDylibMap.find(path);
619 if (pos != _pathToDylibMap.end())
620 return pos->second;
621
622 // Search -L paths if of the form "libXXX.dylib"
623 std::pair<StringRef, StringRef> split = path.rsplit('/');
624 StringRef leafName = split.second;
625 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
626 // FIXME: Need to enhance searchLibrary() to only look for .dylib
627 auto libPath = searchLibrary(leafName);
628 if (!libPath.getError()) {
629 return loadIndirectDylib(libPath.get());
630 }
631 }
632
633 // Try full path with sysroot.
634 for (StringRef sysPath : _syslibRoots) {
635 SmallString<256> fullPath;
636 fullPath.assign(sysPath);
637 llvm::sys::path::append(fullPath, path);
638 if (pathExists(fullPath))
639 return loadIndirectDylib(fullPath);
640 }
641
642 // Try full path.
643 if (pathExists(path)) {
644 return loadIndirectDylib(path);
645 }
646
647 return nullptr;
648}
649
650bool MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000651 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000652 // Add indirect dylibs by asking each linked dylib to add its indirects.
653 // Iterate until no more dylibs get loaded.
654 size_t dylibCount = 0;
655 while (dylibCount != _allDylibs.size()) {
656 dylibCount = _allDylibs.size();
657 for (MachODylibFile *dylib : _allDylibs) {
658 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
659 return findIndirectDylib(path); });
660 }
661 }
662
663 // Let writer add output type specific extras.
664 return writer().createImplicitFiles(result);
665}
666
667
Nick Kledzik51720672014-10-16 19:31:28 +0000668void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
669 bool upward) const {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000670 _allDylibs.insert(dylib);
671 _pathToDylibMap[dylib->installName()] = dylib;
672 // If path is different than install name, register path too.
673 if (!dylib->path().equals(dylib->installName()))
674 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000675 if (upward)
676 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000677}
678
679
Nick Kledzik51720672014-10-16 19:31:28 +0000680bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
681 for (MachODylibFile *dylib : _upwardDylibs) {
682 if (dylib->installName().equals(installName))
683 return true;
684 }
685 return false;
686}
687
Nick Kledzik2458bec2014-07-16 19:49:02 +0000688ArchHandler &MachOLinkingContext::archHandler() const {
689 if (!_archHandler)
690 _archHandler = ArchHandler::create(_arch);
691 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000692}
693
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000694
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000695void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
696 uint8_t align2) {
697 SectionAlign entry;
698 entry.segmentName = seg;
699 entry.sectionName = sect;
700 entry.align2 = align2;
701 _sectAligns.push_back(entry);
702}
703
704bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
705 uint8_t &align2) const {
706 for (const SectionAlign &entry : _sectAligns) {
707 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
708 align2 = entry.align2;
709 return true;
710 }
711 }
712 return false;
713}
714
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000715
716void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000717 // Support old crufty export lists with bogus entries.
718 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
719 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
720 return;
721 }
722 // Only i386 MacOSX uses old ABI, so don't change those.
723 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
724 // ObjC has two differnent ABIs. Be nice and allow one export list work for
725 // both ABIs by renaming symbols.
726 if (sym.startswith(".objc_class_name_")) {
727 std::string abi2className("_OBJC_CLASS_$_");
728 abi2className += sym.substr(17);
729 _exportedSymbols.insert(copy(abi2className));
730 std::string abi2metaclassName("_OBJC_METACLASS_$_");
731 abi2metaclassName += sym.substr(17);
732 _exportedSymbols.insert(copy(abi2metaclassName));
733 return;
734 }
735 }
736
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000737 // FIXME: Support wildcards.
738 _exportedSymbols.insert(sym);
739}
740
741bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
742 switch (_exportMode) {
743 case ExportMode::globals:
744 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
745 break;
746 case ExportMode::whiteList:
747 return _exportedSymbols.count(sym);
748 case ExportMode::blackList:
749 return !_exportedSymbols.count(sym);
750 }
Yaron Keren9682c852014-09-21 05:07:44 +0000751 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000752}
753
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000754std::string MachOLinkingContext::demangle(StringRef symbolName) const {
755 // Only try to demangle symbols if -demangle on command line
756 if (!_demangle)
757 return symbolName;
758
759 // Only try to demangle symbols that look like C++ symbols
760 if (!symbolName.startswith("__Z"))
761 return symbolName;
762
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000763#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000764 SmallString<256> symBuff;
765 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
766 // Mach-O has extra leading underscore that needs to be removed.
767 const char *cstr = nullTermSym.data() + 1;
768 int status;
769 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
770 if (demangled != NULL) {
771 std::string result(demangled);
772 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
773 free(demangled);
774 return result;
775 }
776#endif
777
778 return symbolName;
779}
780
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000781std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
782 std::error_code ec;
783 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
784 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
785 if (ec) {
786 _dependencyInfo.reset();
787 return ec;
788 }
789
790 char linkerVersionOpcode = 0x00;
791 *_dependencyInfo << linkerVersionOpcode;
792 *_dependencyInfo << "lld"; // FIXME
793 *_dependencyInfo << '\0';
794
795 return std::error_code();
796}
797
798void MachOLinkingContext::addInputFileDependency(StringRef path) const {
799 if (!_dependencyInfo)
800 return;
801
802 char inputFileOpcode = 0x10;
803 *_dependencyInfo << inputFileOpcode;
804 *_dependencyInfo << path;
805 *_dependencyInfo << '\0';
806}
807
808void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
809 if (!_dependencyInfo)
810 return;
811
812 char inputFileOpcode = 0x11;
813 *_dependencyInfo << inputFileOpcode;
814 *_dependencyInfo << path;
815 *_dependencyInfo << '\0';
816}
817
818void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
819 if (!_dependencyInfo)
820 return;
821
822 char outputFileOpcode = 0x40;
823 *_dependencyInfo << outputFileOpcode;
824 *_dependencyInfo << path;
825 *_dependencyInfo << '\0';
826}
827
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000828
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000829} // end namespace lld