blob: 7fb493088338288f520d833e74e9c36afa4e840d [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
12#include "ArchHandler.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000013#include "File.h"
Nick Kledzik635f9c72014-09-04 20:08:30 +000014#include "MachONormalizedFile.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000015#include "MachOPasses.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000016
17#include "lld/Core/PassManager.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000018#include "lld/Driver/DarwinInputGraph.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000019#include "lld/ReaderWriter/Reader.h"
20#include "lld/ReaderWriter/Writer.h"
21#include "lld/Passes/LayoutPass.h"
Shankar Easwaran2bc24922013-10-29 05:12:14 +000022#include "lld/Passes/RoundTripYAMLPass.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000023
24#include "llvm/ADT/StringExtras.h"
25#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000026#include "llvm/Config/config.h"
Tim Northover77d82202014-07-10 11:21:06 +000027#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000028#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000029#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000030#include "llvm/Support/Path.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000031
Rui Ueyama57a29532014-08-06 19:37:35 +000032#include <algorithm>
33
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000034#if HAVE_CXXABI_H
35#include <cxxabi.h>
36#endif
37
Nick Kledzik2458bec2014-07-16 19:49:02 +000038using lld::mach_o::ArchHandler;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000039using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000040using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000041
42namespace lld {
43
Nick Kledzike850d9d2013-09-10 23:46:57 +000044bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
45 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000046
47 if (str.empty())
48 return false;
49
50 SmallVector<StringRef, 3> parts;
51 llvm::SplitString(str, parts, ".");
52
53 unsigned long long num;
54 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
55 return true;
56 if (num > 65535)
57 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000058 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000059
60 if (parts.size() > 1) {
61 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
62 return true;
63 if (num > 255)
64 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000065 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000066 }
67
68 if (parts.size() > 2) {
69 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
70 return true;
71 if (num > 255)
72 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000073 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000074 }
75
76 return false;
77}
78
Rui Ueyama0ca149f2013-08-06 22:31:59 +000079
Nick Kledzike34182f2013-11-06 21:36:55 +000080MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
81 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
82 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
83 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
84 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
85 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
86 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000087 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000088 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000089};
90
91MachOLinkingContext::Arch
92MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000093 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
94 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000095 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000096 }
97 return arch_unknown;
98}
99
100MachOLinkingContext::Arch
101MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000102 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
103 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000104 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000105 }
106 return arch_unknown;
107}
108
Nick Kledzike5552772013-12-19 21:58:00 +0000109StringRef MachOLinkingContext::nameFromArch(Arch arch) {
110 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
111 if (info->arch == arch)
112 return info->archName;
113 }
114 return "<unknown>";
115}
116
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000117uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
118 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000119 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
120 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000121 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000122 }
123 llvm_unreachable("Unknown arch type");
124}
125
126uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
127 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000128 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
129 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000130 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000131 }
132 llvm_unreachable("Unknown arch type");
133}
134
Nick Kledzik635f9c72014-09-04 20:08:30 +0000135bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
136 return mach_o::normalized::isThinObjectFile(path, arch);
137}
138
Nick Kledzik14b5d202014-10-08 01:48:10 +0000139bool MachOLinkingContext::sliceFromFatFile(const MemoryBuffer &mb,
140 uint32_t &offset,
141 uint32_t &size) {
142 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
143}
144
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000145MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000146 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000147 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
148 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
149 _compatibilityVersion(0), _currentVersion(0), _deadStrippableDylib(false),
150 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000151 _demangle(false), _archHandler(nullptr),
152 _exportMode(ExportMode::globals) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000153
154MachOLinkingContext::~MachOLinkingContext() {}
155
Nick Kledzik6960b072013-12-21 01:47:17 +0000156void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
157 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000158 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000159 _arch = arch;
160 _os = os;
161 _osMinVersion = minOSVersion;
162
Tim Northoverd30a1f22014-06-20 15:59:00 +0000163 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000164 case llvm::MachO::MH_EXECUTE:
165 // If targeting newer OS, use _main
166 if (minOS("10.8", "6.0")) {
167 _entrySymbolName = "_main";
168 } else {
169 // If targeting older OS, use start (in crt1.o)
170 _entrySymbolName = "start";
171 }
172
173 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
174 // support) and 4KB on 32-bit.
175 if (is64Bit(_arch)) {
176 _pageZeroSize = 0x100000000;
177 } else {
178 _pageZeroSize = 0x1000;
179 }
180
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000181 // Make PIE by default when targetting newer OSs.
182 switch (os) {
183 case OS::macOSX:
184 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
185 _pie = true;
186 break;
187 case OS::iOS:
188 if (minOSVersion >= 0x00040300) // iOS 4.3
189 _pie = true;
190 break;
191 case OS::iOS_simulator:
192 _pie = true;
193 break;
194 case OS::unknown:
195 break;
196 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000197 break;
198 case llvm::MachO::MH_DYLIB:
199 _globalsAreDeadStripRoots = true;
200 break;
201 case llvm::MachO::MH_BUNDLE:
202 break;
203 case llvm::MachO::MH_OBJECT:
204 _printRemainingUndefines = false;
205 _allowRemainingUndefines = true;
206 default:
207 break;
208 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000209
210 // Set default segment page sizes based on arch.
211 if (arch == arch_arm64)
212 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000213}
214
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000215uint32_t MachOLinkingContext::getCPUType() const {
216 return cpuTypeFromArch(_arch);
217}
218
219uint32_t MachOLinkingContext::getCPUSubType() const {
220 return cpuSubtypeFromArch(_arch);
221}
222
Nick Kledzike34182f2013-11-06 21:36:55 +0000223bool MachOLinkingContext::is64Bit(Arch arch) {
224 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
225 if (info->arch == arch) {
226 return (info->cputype & CPU_ARCH_ABI64);
227 }
228 }
229 // unknown archs are not 64-bit.
230 return false;
231}
232
233bool MachOLinkingContext::isHostEndian(Arch arch) {
234 assert(arch != arch_unknown);
235 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
236 if (info->arch == arch) {
237 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
238 }
239 }
240 llvm_unreachable("Unknown arch type");
241}
242
243bool MachOLinkingContext::isBigEndian(Arch arch) {
244 assert(arch != arch_unknown);
245 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
246 if (info->arch == arch) {
247 return ! info->littleEndian;
248 }
249 }
250 llvm_unreachable("Unknown arch type");
251}
252
253
254
255bool MachOLinkingContext::is64Bit() const {
256 return is64Bit(_arch);
257}
258
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000259bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000260 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000261 case MH_EXECUTE:
262 case MH_DYLINKER:
263 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000264 return true;
265 default:
266 return false;
267 }
268}
269
Nick Kledzik2458bec2014-07-16 19:49:02 +0000270bool MachOLinkingContext::needsStubsPass() const {
271 switch (_outputMachOType) {
272 case MH_EXECUTE:
273 return !_outputMachOTypeStatic;
274 case MH_DYLIB:
275 case MH_BUNDLE:
276 return true;
277 default:
278 return false;
279 }
280}
281
282bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000283 // GOT pass not used in -r mode.
284 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000285 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000286 // Only some arches use GOT pass.
287 switch (_arch) {
288 case arch_x86_64:
289 case arch_arm64:
290 return true;
291 default:
292 return false;
293 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000294}
295
Tim Northovercf78d372014-09-30 21:29:54 +0000296bool MachOLinkingContext::needsCompactUnwindPass() const {
297 switch (_outputMachOType) {
298 case MH_EXECUTE:
299 case MH_DYLIB:
300 case MH_BUNDLE:
301 return archHandler().needsCompactUnwind();
302 default:
303 return false;
304 }
305}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000306
307StringRef MachOLinkingContext::binderSymbolName() const {
308 return archHandler().stubInfo().binderSymbolName;
309}
310
311
312
313
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000314bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000315 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000316 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000317 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000318 if (parsePackedVersion(mac, parsedVersion))
319 return false;
320 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000321 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000322 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000323 if (parsePackedVersion(iOS, parsedVersion))
324 return false;
325 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000326 case OS::unknown:
327 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000328 }
329 llvm_unreachable("target not configured for iOS or MacOSX");
330}
331
332bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000333 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000334 return minOS("10.8", "6.0");
335 }
336 return false;
337}
338
339bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000340 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000341 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000342 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000343 return true;
344 else
345 return !minOS("10.8", "6.0");
346 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000347 case MH_DYLINKER:
348 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000349 return true;
350 default:
351 return false;
352 }
353}
354
Tim Northover77d82202014-07-10 11:21:06 +0000355bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000356 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000357 return llvm::sys::fs::exists(path.str());
358
359 // Otherwise, we're in test mode: only files explicitly provided on the
360 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000361 std::string key = path.str();
362 std::replace(key.begin(), key.end(), '\\', '/');
363 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000364}
365
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000366bool MachOLinkingContext::fileExists(StringRef path) const {
367 bool found = pathExists(path);
368 // Log search misses.
369 if (!found)
370 addInputFileNotFound(path);
371
372 // When testing, file is never opened, so logging is done here.
373 if (_testingFileUsage && found)
374 addInputFileDependency(path);
375
376 return found;
377}
378
Nick Kledzik2d835da2014-08-14 22:20:41 +0000379void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
380 _syslibRoots = paths;
381}
382
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000383void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
384 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000385 bool addedModifiedPath = false;
386
Nick Kledzik2d835da2014-08-14 22:20:41 +0000387 // -syslibroot only applies to absolute paths.
388 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000389 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000390 SmallString<256> path(syslibRoot);
391 llvm::sys::path::append(path, libPath);
392 if (pathExists(path)) {
393 _searchDirs.push_back(path.str().copy(_allocator));
394 addedModifiedPath = true;
395 }
396 }
397 }
398
399 if (addedModifiedPath)
400 return;
401
402 // Finally, if only one -syslibroot is given, system paths which aren't in it
403 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000404 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000405 if (pathExists(libPath)) {
406 _searchDirs.push_back(libPath);
407 }
408 }
409}
410
Nick Kledzik2d835da2014-08-14 22:20:41 +0000411void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
412 bool isSystemPath) {
413 bool pathAdded = false;
414
415 // -syslibroot only used with to absolute framework search paths.
416 if (fwPath.startswith("/")) {
417 for (auto syslibRoot : _syslibRoots) {
418 SmallString<256> path(syslibRoot);
419 llvm::sys::path::append(path, fwPath);
420 if (pathExists(path)) {
421 _frameworkDirs.push_back(path.str().copy(_allocator));
422 pathAdded = true;
423 }
424 }
425 }
426 // If fwPath found in any -syslibroot, then done.
427 if (pathAdded)
428 return;
429
430 // If only one -syslibroot, system paths not in that SDK are suppressed.
431 if (isSystemPath && (_syslibRoots.size() == 1))
432 return;
433
434 // Only use raw fwPath if that directory exists.
435 if (pathExists(fwPath))
436 _frameworkDirs.push_back(fwPath);
437}
438
439
Tim Northover77d82202014-07-10 11:21:06 +0000440ErrorOr<StringRef>
441MachOLinkingContext::searchDirForLibrary(StringRef path,
442 StringRef libName) const {
443 SmallString<256> fullPath;
444 if (libName.endswith(".o")) {
445 // A request ending in .o is special: just search for the file directly.
446 fullPath.assign(path);
447 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000448 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000449 return fullPath.str().copy(_allocator);
450 return make_error_code(llvm::errc::no_such_file_or_directory);
451 }
452
453 // Search for dynamic library
454 fullPath.assign(path);
455 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000456 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000457 return fullPath.str().copy(_allocator);
458
459 // If not, try for a static library
460 fullPath.assign(path);
461 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000462 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000463 return fullPath.str().copy(_allocator);
464
465 return make_error_code(llvm::errc::no_such_file_or_directory);
466}
467
468
469
470ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
471 SmallString<256> path;
472 for (StringRef dir : searchDirs()) {
473 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
474 if (ec)
475 return ec;
476 }
477
478 return make_error_code(llvm::errc::no_such_file_or_directory);
479}
480
Nick Kledzik2d835da2014-08-14 22:20:41 +0000481
482ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
483 SmallString<256> fullPath;
484 for (StringRef dir : frameworkDirs()) {
485 fullPath.assign(dir);
486 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000487 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000488 return fullPath.str().copy(_allocator);
489 }
490
491 return make_error_code(llvm::errc::no_such_file_or_directory);
492}
493
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000494bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000495 // TODO: if -arch not specified, look at arch of first .o file.
496
Tim Northoverd30a1f22014-06-20 15:59:00 +0000497 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000498 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000499 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000500 }
501
Tim Northoverd30a1f22014-06-20 15:59:00 +0000502 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000503 diagnostics
504 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000505 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000506 }
507
Tim Northoverd30a1f22014-06-20 15:59:00 +0000508 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000509 diagnostics
510 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000511 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000512 }
513
Tim Northoverd30a1f22014-06-20 15:59:00 +0000514 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000515 diagnostics
516 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000517 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000518 }
519
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000520 // If -exported_symbols_list used, all exported symbols must be defined.
521 if (_exportMode == ExportMode::whiteList) {
522 for (const auto &symbol : _exportedSymbols)
523 addInitialUndefinedSymbol(symbol.getKey());
524 }
525
Nick Kledzik77afc712014-08-21 20:25:50 +0000526 // If -dead_strip, set up initial live symbols.
527 if (deadStrip()) {
528 // Entry point is live.
529 if (outputTypeHasEntry())
530 addDeadStripRoot(entrySymbolName());
531 // Lazy binding helper is live.
532 if (needsStubsPass())
533 addDeadStripRoot(binderSymbolName());
534 // If using -exported_symbols_list, make all exported symbols live.
535 if (_exportMode == ExportMode::whiteList) {
536 _globalsAreDeadStripRoots = false;
537 for (const auto &symbol : _exportedSymbols)
538 addDeadStripRoot(symbol.getKey());
539 }
540 }
541
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000542 addOutputFileDependency(outputPath());
543
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000544 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000545}
546
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000547void MachOLinkingContext::addPasses(PassManager &pm) {
Nico Rieckb9d84f42014-02-24 21:14:37 +0000548 pm.add(std::unique_ptr<Pass>(new LayoutPass(registry())));
Nick Kledzik2458bec2014-07-16 19:49:02 +0000549 if (needsStubsPass())
550 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000551 if (needsCompactUnwindPass())
552 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000553 if (needsGOTPass())
554 mach_o::addGOTPass(pm, *this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000555}
556
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000557Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000558 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000559 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000560 return *_writer;
561}
562
Nick Kledzik22c90732014-10-01 20:24:30 +0000563MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
564 std::unique_ptr<MachOFileNode> node(new MachOFileNode(path, false, *this));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000565 std::error_code ec = node->parse(*this, llvm::errs());
566 if (ec)
567 return nullptr;
568
569 assert(node->files().size() == 1 && "expected one file in dylib");
570 // lld::File object is owned by MachOFileNode object. This method returns
571 // an unowned pointer to the lld::File object.
572 MachODylibFile* result = reinterpret_cast<MachODylibFile*>(
573 node->files().front().get());
574
575 // Node object now owned by _indirectDylibs vector.
576 _indirectDylibs.push_back(std::move(node));
577
578 return result;
579}
580
581
Nick Kledzik22c90732014-10-01 20:24:30 +0000582MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000583 // See if already loaded.
584 auto pos = _pathToDylibMap.find(path);
585 if (pos != _pathToDylibMap.end())
586 return pos->second;
587
588 // Search -L paths if of the form "libXXX.dylib"
589 std::pair<StringRef, StringRef> split = path.rsplit('/');
590 StringRef leafName = split.second;
591 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
592 // FIXME: Need to enhance searchLibrary() to only look for .dylib
593 auto libPath = searchLibrary(leafName);
594 if (!libPath.getError()) {
595 return loadIndirectDylib(libPath.get());
596 }
597 }
598
599 // Try full path with sysroot.
600 for (StringRef sysPath : _syslibRoots) {
601 SmallString<256> fullPath;
602 fullPath.assign(sysPath);
603 llvm::sys::path::append(fullPath, path);
604 if (pathExists(fullPath))
605 return loadIndirectDylib(fullPath);
606 }
607
608 // Try full path.
609 if (pathExists(path)) {
610 return loadIndirectDylib(path);
611 }
612
613 return nullptr;
614}
615
616bool MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000617 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000618 // Add indirect dylibs by asking each linked dylib to add its indirects.
619 // Iterate until no more dylibs get loaded.
620 size_t dylibCount = 0;
621 while (dylibCount != _allDylibs.size()) {
622 dylibCount = _allDylibs.size();
623 for (MachODylibFile *dylib : _allDylibs) {
624 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
625 return findIndirectDylib(path); });
626 }
627 }
628
629 // Let writer add output type specific extras.
630 return writer().createImplicitFiles(result);
631}
632
633
Nick Kledzik14b5d202014-10-08 01:48:10 +0000634void MachOLinkingContext::registerDylib(MachODylibFile *dylib) const {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000635 _allDylibs.insert(dylib);
636 _pathToDylibMap[dylib->installName()] = dylib;
637 // If path is different than install name, register path too.
638 if (!dylib->path().equals(dylib->installName()))
639 _pathToDylibMap[dylib->path()] = dylib;
640}
641
642
Nick Kledzik2458bec2014-07-16 19:49:02 +0000643ArchHandler &MachOLinkingContext::archHandler() const {
644 if (!_archHandler)
645 _archHandler = ArchHandler::create(_arch);
646 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000647}
648
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000649
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000650void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
651 uint8_t align2) {
652 SectionAlign entry;
653 entry.segmentName = seg;
654 entry.sectionName = sect;
655 entry.align2 = align2;
656 _sectAligns.push_back(entry);
657}
658
659bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
660 uint8_t &align2) const {
661 for (const SectionAlign &entry : _sectAligns) {
662 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
663 align2 = entry.align2;
664 return true;
665 }
666 }
667 return false;
668}
669
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000670
671void MachOLinkingContext::addExportSymbol(StringRef sym) {
672 // FIXME: Support wildcards.
673 _exportedSymbols.insert(sym);
674}
675
676bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
677 switch (_exportMode) {
678 case ExportMode::globals:
679 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
680 break;
681 case ExportMode::whiteList:
682 return _exportedSymbols.count(sym);
683 case ExportMode::blackList:
684 return !_exportedSymbols.count(sym);
685 }
Yaron Keren9682c852014-09-21 05:07:44 +0000686 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000687}
688
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000689std::string MachOLinkingContext::demangle(StringRef symbolName) const {
690 // Only try to demangle symbols if -demangle on command line
691 if (!_demangle)
692 return symbolName;
693
694 // Only try to demangle symbols that look like C++ symbols
695 if (!symbolName.startswith("__Z"))
696 return symbolName;
697
698#if HAVE_CXXABI_H
699 SmallString<256> symBuff;
700 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
701 // Mach-O has extra leading underscore that needs to be removed.
702 const char *cstr = nullTermSym.data() + 1;
703 int status;
704 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
705 if (demangled != NULL) {
706 std::string result(demangled);
707 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
708 free(demangled);
709 return result;
710 }
711#endif
712
713 return symbolName;
714}
715
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000716std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
717 std::error_code ec;
718 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
719 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
720 if (ec) {
721 _dependencyInfo.reset();
722 return ec;
723 }
724
725 char linkerVersionOpcode = 0x00;
726 *_dependencyInfo << linkerVersionOpcode;
727 *_dependencyInfo << "lld"; // FIXME
728 *_dependencyInfo << '\0';
729
730 return std::error_code();
731}
732
733void MachOLinkingContext::addInputFileDependency(StringRef path) const {
734 if (!_dependencyInfo)
735 return;
736
737 char inputFileOpcode = 0x10;
738 *_dependencyInfo << inputFileOpcode;
739 *_dependencyInfo << path;
740 *_dependencyInfo << '\0';
741}
742
743void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
744 if (!_dependencyInfo)
745 return;
746
747 char inputFileOpcode = 0x11;
748 *_dependencyInfo << inputFileOpcode;
749 *_dependencyInfo << path;
750 *_dependencyInfo << '\0';
751}
752
753void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
754 if (!_dependencyInfo)
755 return;
756
757 char outputFileOpcode = 0x40;
758 *_dependencyInfo << outputFileOpcode;
759 *_dependencyInfo << path;
760 *_dependencyInfo << '\0';
761}
762
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000763
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000764} // end namespace lld