blob: ff788fd32bfddd37a552a0ee348b356159de29f1 [file] [log] [blame]
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001//===- lib/ReaderWriter/MachO/MachOLinkingContext.cpp ---------------------===//
2//
3// The LLVM Linker
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "lld/ReaderWriter/MachOLinkingContext.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000011#include "ArchHandler.h"
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000012#include "File.h"
Lang Hames5c692002015-09-28 20:25:14 +000013#include "FlatNamespaceFile.h"
Nick Kledzik635f9c72014-09-04 20:08:30 +000014#include "MachONormalizedFile.h"
Nick Kledzik2458bec2014-07-16 19:49:02 +000015#include "MachOPasses.h"
Lang Hamesb1b67f42015-10-24 08:20:51 +000016#include "SectCreateFile.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000017#include "lld/Core/ArchiveLibraryFile.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000018#include "lld/Core/PassManager.h"
Greg Fitzgerald4b6a7e32015-01-21 22:54:56 +000019#include "lld/Core/Reader.h"
20#include "lld/Core/Writer.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000021#include "lld/Driver/Driver.h"
Benjamin Kramer06a42af2015-03-02 00:48:06 +000022#include "llvm/ADT/STLExtras.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000023#include "llvm/ADT/StringExtras.h"
24#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000025#include "llvm/Config/config.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000026#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +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 Ueyama57a29532014-08-06 19:37:35 +000031#include <algorithm>
32
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000033#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000034#include <cxxabi.h>
35#endif
36
Nick Kledzik2458bec2014-07-16 19:49:02 +000037using lld::mach_o::ArchHandler;
Pete Cooper99f3b942016-01-14 23:25:06 +000038using lld::mach_o::MachOFile;
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
Nick Kledzike34182f2013-11-06 21:36:55 +000079MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
80 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
81 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
82 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
83 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
84 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
85 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000086 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000087 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000088};
89
90MachOLinkingContext::Arch
91MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000092 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
93 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000094 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000095 }
96 return arch_unknown;
97}
98
99MachOLinkingContext::Arch
100MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000101 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
102 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000103 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000104 }
105 return arch_unknown;
106}
107
Nick Kledzike5552772013-12-19 21:58:00 +0000108StringRef MachOLinkingContext::nameFromArch(Arch arch) {
109 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
110 if (info->arch == arch)
111 return info->archName;
112 }
113 return "<unknown>";
114}
115
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000116uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
117 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000118 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
119 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000120 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000121 }
122 llvm_unreachable("Unknown arch type");
123}
124
125uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
126 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000127 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
128 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000129 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000130 }
131 llvm_unreachable("Unknown arch type");
132}
133
Nick Kledzik635f9c72014-09-04 20:08:30 +0000134bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
135 return mach_o::normalized::isThinObjectFile(path, arch);
136}
137
Rafael Espindolaed48e532015-04-27 22:48:51 +0000138bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000139 uint32_t &size) {
140 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
141}
142
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000143MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000144 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000145 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
146 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
Lang Hamesff4b13c2015-05-22 00:25:34 +0000147 _stackSize(0), _compatibilityVersion(0), _currentVersion(0),
Pete Cooperfeaa9672016-01-19 18:46:40 +0000148 _objcConstraint(objc_unknown), _swiftVersion(0), _flatNamespace(false),
149 _undefinedMode(UndefinedMode::error), _deadStrippableDylib(false),
150 _printAtoms(false), _testingFileUsage(false), _keepPrivateExterns(false),
151 _demangle(false), _archHandler(nullptr), _exportMode(ExportMode::globals),
Lang Hames5c692002015-09-28 20:25:14 +0000152 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0),
153 _flatNamespaceFile(nullptr) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000154
155MachOLinkingContext::~MachOLinkingContext() {}
156
Nick Kledzik6960b072013-12-21 01:47:17 +0000157void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
158 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000159 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000160 _arch = arch;
161 _os = os;
162 _osMinVersion = minOSVersion;
163
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000164 // If min OS not specified on command line, use reasonable defaults.
165 if (minOSVersion == 0) {
166 switch (_arch) {
167 case arch_x86_64:
168 case arch_x86:
169 parsePackedVersion("10.8", _osMinVersion);
170 _os = MachOLinkingContext::OS::macOSX;
171 break;
172 case arch_armv6:
173 case arch_armv7:
174 case arch_armv7s:
175 case arch_arm64:
176 parsePackedVersion("7.0", _osMinVersion);
177 _os = MachOLinkingContext::OS::iOS;
178 break;
179 default:
180 break;
181 }
182 }
183
Tim Northoverd30a1f22014-06-20 15:59:00 +0000184 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000185 case llvm::MachO::MH_EXECUTE:
186 // If targeting newer OS, use _main
187 if (minOS("10.8", "6.0")) {
188 _entrySymbolName = "_main";
189 } else {
190 // If targeting older OS, use start (in crt1.o)
191 _entrySymbolName = "start";
192 }
193
194 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
195 // support) and 4KB on 32-bit.
196 if (is64Bit(_arch)) {
197 _pageZeroSize = 0x100000000;
198 } else {
199 _pageZeroSize = 0x1000;
200 }
201
Lang Hamesc80344282015-09-21 22:06:02 +0000202 // Initial base address is __PAGEZERO size.
203 _baseAddress = _pageZeroSize;
204
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000205 // Make PIE by default when targetting newer OSs.
206 switch (os) {
207 case OS::macOSX:
208 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
209 _pie = true;
210 break;
211 case OS::iOS:
212 if (minOSVersion >= 0x00040300) // iOS 4.3
213 _pie = true;
214 break;
215 case OS::iOS_simulator:
216 _pie = true;
217 break;
218 case OS::unknown:
219 break;
220 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000221 break;
222 case llvm::MachO::MH_DYLIB:
Davide Italiano7b68b902015-03-09 06:05:42 +0000223 setGlobalsAreDeadStripRoots(true);
Nick Kledzik6960b072013-12-21 01:47:17 +0000224 break;
225 case llvm::MachO::MH_BUNDLE:
226 break;
227 case llvm::MachO::MH_OBJECT:
228 _printRemainingUndefines = false;
229 _allowRemainingUndefines = true;
230 default:
231 break;
232 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000233
234 // Set default segment page sizes based on arch.
235 if (arch == arch_arm64)
236 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000237}
238
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000239uint32_t MachOLinkingContext::getCPUType() const {
240 return cpuTypeFromArch(_arch);
241}
242
243uint32_t MachOLinkingContext::getCPUSubType() const {
244 return cpuSubtypeFromArch(_arch);
245}
246
Nick Kledzike34182f2013-11-06 21:36:55 +0000247bool MachOLinkingContext::is64Bit(Arch arch) {
248 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
249 if (info->arch == arch) {
250 return (info->cputype & CPU_ARCH_ABI64);
251 }
252 }
253 // unknown archs are not 64-bit.
254 return false;
255}
256
257bool MachOLinkingContext::isHostEndian(Arch arch) {
258 assert(arch != arch_unknown);
259 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
260 if (info->arch == arch) {
261 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
262 }
263 }
264 llvm_unreachable("Unknown arch type");
265}
266
267bool MachOLinkingContext::isBigEndian(Arch arch) {
268 assert(arch != arch_unknown);
269 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
270 if (info->arch == arch) {
271 return ! info->littleEndian;
272 }
273 }
274 llvm_unreachable("Unknown arch type");
275}
276
Nick Kledzike34182f2013-11-06 21:36:55 +0000277bool MachOLinkingContext::is64Bit() const {
278 return is64Bit(_arch);
279}
280
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000281bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000282 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000283 case MH_EXECUTE:
284 case MH_DYLINKER:
285 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000286 return true;
287 default:
288 return false;
289 }
290}
291
Nick Kledzik2458bec2014-07-16 19:49:02 +0000292bool MachOLinkingContext::needsStubsPass() const {
293 switch (_outputMachOType) {
294 case MH_EXECUTE:
295 return !_outputMachOTypeStatic;
296 case MH_DYLIB:
297 case MH_BUNDLE:
298 return true;
299 default:
300 return false;
301 }
302}
303
304bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000305 // GOT pass not used in -r mode.
306 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000307 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000308 // Only some arches use GOT pass.
309 switch (_arch) {
310 case arch_x86_64:
311 case arch_arm64:
312 return true;
313 default:
314 return false;
315 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000316}
317
Tim Northovercf78d372014-09-30 21:29:54 +0000318bool MachOLinkingContext::needsCompactUnwindPass() const {
319 switch (_outputMachOType) {
320 case MH_EXECUTE:
321 case MH_DYLIB:
322 case MH_BUNDLE:
323 return archHandler().needsCompactUnwind();
324 default:
325 return false;
326 }
327}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000328
Pete Cooper90dbab02016-01-19 21:54:21 +0000329bool MachOLinkingContext::needsObjCPass() const {
330 // ObjC pass is only needed if any of the inputs were ObjC.
331 return _objcConstraint != objc_unknown;
332}
333
Nick Kledzik4121bce2014-10-14 01:51:42 +0000334bool MachOLinkingContext::needsShimPass() const {
335 // Shim pass only used in final executables.
336 if (_outputMachOType == MH_OBJECT)
337 return false;
338 // Only 32-bit arm arches use Shim pass.
339 switch (_arch) {
340 case arch_armv6:
341 case arch_armv7:
342 case arch_armv7s:
343 return true;
344 default:
345 return false;
346 }
347}
348
Lang Hames49047032015-06-23 20:35:31 +0000349bool MachOLinkingContext::needsTLVPass() const {
350 switch (_outputMachOType) {
351 case MH_BUNDLE:
352 case MH_EXECUTE:
353 case MH_DYLIB:
354 return true;
355 default:
356 return false;
357 }
358}
359
Nick Kledzik2458bec2014-07-16 19:49:02 +0000360StringRef MachOLinkingContext::binderSymbolName() const {
361 return archHandler().stubInfo().binderSymbolName;
362}
363
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000364bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000365 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000366 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000367 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000368 if (parsePackedVersion(mac, parsedVersion))
369 return false;
370 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000371 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000372 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000373 if (parsePackedVersion(iOS, parsedVersion))
374 return false;
375 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000376 case OS::unknown:
377 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000378 }
379 llvm_unreachable("target not configured for iOS or MacOSX");
380}
381
382bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000383 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000384 return minOS("10.8", "6.0");
385 }
386 return false;
387}
388
389bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000390 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000391 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000392 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000393 return true;
394 else
395 return !minOS("10.8", "6.0");
396 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000397 case MH_DYLINKER:
398 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000399 return true;
400 default:
401 return false;
402 }
403}
404
Tim Northover77d82202014-07-10 11:21:06 +0000405bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000406 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000407 return llvm::sys::fs::exists(path.str());
408
409 // Otherwise, we're in test mode: only files explicitly provided on the
410 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000411 std::string key = path.str();
412 std::replace(key.begin(), key.end(), '\\', '/');
413 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000414}
415
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000416bool MachOLinkingContext::fileExists(StringRef path) const {
417 bool found = pathExists(path);
418 // Log search misses.
419 if (!found)
420 addInputFileNotFound(path);
421
422 // When testing, file is never opened, so logging is done here.
423 if (_testingFileUsage && found)
424 addInputFileDependency(path);
425
426 return found;
427}
428
Nick Kledzik2d835da2014-08-14 22:20:41 +0000429void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
430 _syslibRoots = paths;
431}
432
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000433void MachOLinkingContext::addRpath(StringRef rpath) {
434 _rpaths.push_back(rpath);
435}
436
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000437void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
438 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000439 bool addedModifiedPath = false;
440
Nick Kledzik2d835da2014-08-14 22:20:41 +0000441 // -syslibroot only applies to absolute paths.
442 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000443 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000444 SmallString<256> path(syslibRoot);
445 llvm::sys::path::append(path, libPath);
446 if (pathExists(path)) {
447 _searchDirs.push_back(path.str().copy(_allocator));
448 addedModifiedPath = true;
449 }
450 }
451 }
452
453 if (addedModifiedPath)
454 return;
455
456 // Finally, if only one -syslibroot is given, system paths which aren't in it
457 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000458 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000459 if (pathExists(libPath)) {
460 _searchDirs.push_back(libPath);
461 }
462 }
463}
464
Nick Kledzik2d835da2014-08-14 22:20:41 +0000465void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
466 bool isSystemPath) {
467 bool pathAdded = false;
468
469 // -syslibroot only used with to absolute framework search paths.
470 if (fwPath.startswith("/")) {
471 for (auto syslibRoot : _syslibRoots) {
472 SmallString<256> path(syslibRoot);
473 llvm::sys::path::append(path, fwPath);
474 if (pathExists(path)) {
475 _frameworkDirs.push_back(path.str().copy(_allocator));
476 pathAdded = true;
477 }
478 }
479 }
480 // If fwPath found in any -syslibroot, then done.
481 if (pathAdded)
482 return;
483
484 // If only one -syslibroot, system paths not in that SDK are suppressed.
485 if (isSystemPath && (_syslibRoots.size() == 1))
486 return;
487
488 // Only use raw fwPath if that directory exists.
489 if (pathExists(fwPath))
490 _frameworkDirs.push_back(fwPath);
491}
492
Tim Northover77d82202014-07-10 11:21:06 +0000493ErrorOr<StringRef>
494MachOLinkingContext::searchDirForLibrary(StringRef path,
495 StringRef libName) const {
496 SmallString<256> fullPath;
497 if (libName.endswith(".o")) {
498 // A request ending in .o is special: just search for the file directly.
499 fullPath.assign(path);
500 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000501 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000502 return fullPath.str().copy(_allocator);
503 return make_error_code(llvm::errc::no_such_file_or_directory);
504 }
505
506 // Search for dynamic library
507 fullPath.assign(path);
508 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000509 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000510 return fullPath.str().copy(_allocator);
511
512 // If not, try for a static library
513 fullPath.assign(path);
514 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000515 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000516 return fullPath.str().copy(_allocator);
517
518 return make_error_code(llvm::errc::no_such_file_or_directory);
519}
520
Tim Northover77d82202014-07-10 11:21:06 +0000521ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
522 SmallString<256> path;
523 for (StringRef dir : searchDirs()) {
524 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
525 if (ec)
526 return ec;
527 }
528
529 return make_error_code(llvm::errc::no_such_file_or_directory);
530}
531
Nick Kledzik2d835da2014-08-14 22:20:41 +0000532ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
533 SmallString<256> fullPath;
534 for (StringRef dir : frameworkDirs()) {
535 fullPath.assign(dir);
536 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000537 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000538 return fullPath.str().copy(_allocator);
539 }
540
541 return make_error_code(llvm::errc::no_such_file_or_directory);
542}
543
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000544bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000545 // TODO: if -arch not specified, look at arch of first .o file.
546
Tim Northoverd30a1f22014-06-20 15:59:00 +0000547 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000548 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000549 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000550 }
551
Tim Northoverd30a1f22014-06-20 15:59:00 +0000552 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000553 diagnostics
554 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000555 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000556 }
557
Tim Northoverd30a1f22014-06-20 15:59:00 +0000558 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000559 diagnostics
560 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000561 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000562 }
563
Tim Northoverd30a1f22014-06-20 15:59:00 +0000564 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000565 diagnostics
566 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000567 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000568 }
569
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000570 // If -exported_symbols_list used, all exported symbols must be defined.
571 if (_exportMode == ExportMode::whiteList) {
572 for (const auto &symbol : _exportedSymbols)
573 addInitialUndefinedSymbol(symbol.getKey());
574 }
575
Nick Kledzik77afc712014-08-21 20:25:50 +0000576 // If -dead_strip, set up initial live symbols.
577 if (deadStrip()) {
578 // Entry point is live.
579 if (outputTypeHasEntry())
580 addDeadStripRoot(entrySymbolName());
581 // Lazy binding helper is live.
582 if (needsStubsPass())
583 addDeadStripRoot(binderSymbolName());
584 // If using -exported_symbols_list, make all exported symbols live.
585 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000586 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000587 for (const auto &symbol : _exportedSymbols)
588 addDeadStripRoot(symbol.getKey());
589 }
590 }
591
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000592 addOutputFileDependency(outputPath());
593
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000594 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000595}
596
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000597void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000598 // objc pass should be before layout pass. Otherwise test cases may contain
599 // no atoms which confuses the layout pass.
600 if (needsObjCPass())
601 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000602 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000603 if (needsStubsPass())
604 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000605 if (needsCompactUnwindPass())
606 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000607 if (needsGOTPass())
608 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000609 if (needsTLVPass())
610 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000611 if (needsShimPass())
612 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000613}
614
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000615Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000616 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000617 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000618 return *_writer;
619}
620
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000621ErrorOr<std::unique_ptr<MemoryBuffer>>
622MachOLinkingContext::getMemoryBuffer(StringRef path) {
623 addInputFileDependency(path);
624
Rui Ueyamadf230b22015-01-15 04:34:31 +0000625 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000626 MemoryBuffer::getFileOrSTDIN(path);
627 if (std::error_code ec = mbOrErr.getError())
628 return ec;
629 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
630
631 // If buffer contains a fat file, find required arch in fat buffer
632 // and switch buffer to point to just that required slice.
633 uint32_t offset;
634 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000635 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000636 return MemoryBuffer::getFileSlice(path, size, offset);
637 return std::move(mb);
638}
639
640MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
641 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000642 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000643 return nullptr;
644
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000645 ErrorOr<std::unique_ptr<File>> fileOrErr =
646 registry().loadFile(std::move(mbOrErr.get()));
647 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000648 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000649 std::unique_ptr<File> &file = fileOrErr.get();
650 file->parse();
651 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000652 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000653 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000654 return result;
655}
656
Nick Kledzik22c90732014-10-01 20:24:30 +0000657MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000658 // See if already loaded.
659 auto pos = _pathToDylibMap.find(path);
660 if (pos != _pathToDylibMap.end())
661 return pos->second;
662
663 // Search -L paths if of the form "libXXX.dylib"
664 std::pair<StringRef, StringRef> split = path.rsplit('/');
665 StringRef leafName = split.second;
666 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
667 // FIXME: Need to enhance searchLibrary() to only look for .dylib
668 auto libPath = searchLibrary(leafName);
669 if (!libPath.getError()) {
670 return loadIndirectDylib(libPath.get());
671 }
672 }
673
674 // Try full path with sysroot.
675 for (StringRef sysPath : _syslibRoots) {
676 SmallString<256> fullPath;
677 fullPath.assign(sysPath);
678 llvm::sys::path::append(fullPath, path);
679 if (pathExists(fullPath))
680 return loadIndirectDylib(fullPath);
681 }
682
683 // Try full path.
684 if (pathExists(path)) {
685 return loadIndirectDylib(path);
686 }
687
688 return nullptr;
689}
690
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000691uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
692 auto pos = _pathToDylibMap.find(installName);
693 if (pos != _pathToDylibMap.end())
694 return pos->second->currentVersion();
695 else
696 return 0x1000; // 1.0
697}
698
699uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
700 auto pos = _pathToDylibMap.find(installName);
701 if (pos != _pathToDylibMap.end())
702 return pos->second->compatVersion();
703 else
704 return 0x1000; // 1.0
705}
706
Simon Atanasyanc4378882015-04-06 20:43:35 +0000707void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000708 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000709 // Add indirect dylibs by asking each linked dylib to add its indirects.
710 // Iterate until no more dylibs get loaded.
711 size_t dylibCount = 0;
712 while (dylibCount != _allDylibs.size()) {
713 dylibCount = _allDylibs.size();
714 for (MachODylibFile *dylib : _allDylibs) {
715 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
716 return findIndirectDylib(path); });
717 }
718 }
719
720 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000721 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000722
Lang Hames9a4c94e2015-09-28 20:52:21 +0000723 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
724 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
725 if (undefinedMode() != UndefinedMode::error) {
726 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000727 _flatNamespaceFile = result.back().get();
728 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000729}
730
Nick Kledzik51720672014-10-16 19:31:28 +0000731void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
732 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000733 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000734 _allDylibs.insert(dylib);
735 _pathToDylibMap[dylib->installName()] = dylib;
736 // If path is different than install name, register path too.
737 if (!dylib->path().equals(dylib->installName()))
738 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000739 if (upward)
740 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000741}
742
Nick Kledzik51720672014-10-16 19:31:28 +0000743bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
744 for (MachODylibFile *dylib : _upwardDylibs) {
745 if (dylib->installName().equals(installName))
746 return true;
747 }
748 return false;
749}
750
Nick Kledzik2458bec2014-07-16 19:49:02 +0000751ArchHandler &MachOLinkingContext::archHandler() const {
752 if (!_archHandler)
753 _archHandler = ArchHandler::create(_arch);
754 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000755}
756
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000757void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000758 uint16_t align) {
759 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000760 _sectAligns.push_back(entry);
761}
762
Lang Hamesb1b67f42015-10-24 08:20:51 +0000763void MachOLinkingContext::addSectCreateSection(
764 StringRef seg, StringRef sect,
765 std::unique_ptr<MemoryBuffer> content) {
766
767 if (!_sectCreateFile) {
768 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
769 _sectCreateFile = sectCreateFile.get();
770 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
771 }
772
773 assert(_sectCreateFile && "sectcreate file does not exist.");
774 _sectCreateFile->addSection(seg, sect, std::move(content));
775}
776
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000777bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000778 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000779 for (const SectionAlign &entry : _sectAligns) {
780 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000781 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000782 return true;
783 }
784 }
785 return false;
786}
787
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000788void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000789 // Support old crufty export lists with bogus entries.
790 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
791 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
792 return;
793 }
794 // Only i386 MacOSX uses old ABI, so don't change those.
795 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
796 // ObjC has two differnent ABIs. Be nice and allow one export list work for
797 // both ABIs by renaming symbols.
798 if (sym.startswith(".objc_class_name_")) {
799 std::string abi2className("_OBJC_CLASS_$_");
800 abi2className += sym.substr(17);
801 _exportedSymbols.insert(copy(abi2className));
802 std::string abi2metaclassName("_OBJC_METACLASS_$_");
803 abi2metaclassName += sym.substr(17);
804 _exportedSymbols.insert(copy(abi2metaclassName));
805 return;
806 }
807 }
808
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000809 // FIXME: Support wildcards.
810 _exportedSymbols.insert(sym);
811}
812
813bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
814 switch (_exportMode) {
815 case ExportMode::globals:
816 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
817 break;
818 case ExportMode::whiteList:
819 return _exportedSymbols.count(sym);
820 case ExportMode::blackList:
821 return !_exportedSymbols.count(sym);
822 }
Yaron Keren9682c852014-09-21 05:07:44 +0000823 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000824}
825
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000826std::string MachOLinkingContext::demangle(StringRef symbolName) const {
827 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000828 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000829 return symbolName;
830
831 // Only try to demangle symbols that look like C++ symbols
832 if (!symbolName.startswith("__Z"))
833 return symbolName;
834
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000835#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000836 SmallString<256> symBuff;
837 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
838 // Mach-O has extra leading underscore that needs to be removed.
839 const char *cstr = nullTermSym.data() + 1;
840 int status;
841 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000842 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000843 std::string result(demangled);
844 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
845 free(demangled);
846 return result;
847 }
848#endif
849
850 return symbolName;
851}
852
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000853std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
854 std::error_code ec;
855 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
856 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
857 if (ec) {
858 _dependencyInfo.reset();
859 return ec;
860 }
861
862 char linkerVersionOpcode = 0x00;
863 *_dependencyInfo << linkerVersionOpcode;
864 *_dependencyInfo << "lld"; // FIXME
865 *_dependencyInfo << '\0';
866
867 return std::error_code();
868}
869
870void MachOLinkingContext::addInputFileDependency(StringRef path) const {
871 if (!_dependencyInfo)
872 return;
873
874 char inputFileOpcode = 0x10;
875 *_dependencyInfo << inputFileOpcode;
876 *_dependencyInfo << path;
877 *_dependencyInfo << '\0';
878}
879
880void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
881 if (!_dependencyInfo)
882 return;
883
884 char inputFileOpcode = 0x11;
885 *_dependencyInfo << inputFileOpcode;
886 *_dependencyInfo << path;
887 *_dependencyInfo << '\0';
888}
889
890void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
891 if (!_dependencyInfo)
892 return;
893
894 char outputFileOpcode = 0x40;
895 *_dependencyInfo << outputFileOpcode;
896 *_dependencyInfo << path;
897 *_dependencyInfo << '\0';
898}
899
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000900void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
901 StringRef filename) {
902 // To support sorting static functions which may have the same name in
903 // multiple .o files, _orderFiles maps the symbol name to a vector
904 // of OrderFileNode each of which can specify a file prefix.
905 OrderFileNode info;
906 if (!filename.empty())
907 info.fileFilter = copy(filename);
908 info.order = _orderFileEntries++;
909 _orderFiles[symbol].push_back(info);
910}
911
912bool
913MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
914 const DefinedAtom *atom,
915 unsigned &ordinal) {
916 const File *objFile = &atom->file();
917 assert(objFile);
918 StringRef objName = objFile->path();
919 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
920 if (!dirAndLeaf.second.empty())
921 objName = dirAndLeaf.second;
922 for (const OrderFileNode &info : nodes) {
923 if (info.fileFilter.empty()) {
924 // Have unprefixed symbol name in order file that matches this atom.
925 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000926 return true;
927 }
928 if (info.fileFilter.equals(objName)) {
929 // Have prefixed symbol name in order file that matches atom's path.
930 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000931 return true;
932 }
933 }
934 return false;
935}
936
937bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
938 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000939 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000940 // No custom sorting if no order file entries.
941 if (!_orderFileEntries)
942 return false;
943
944 // Order files can only order named atoms.
945 StringRef leftName = left->name();
946 StringRef rightName = right->name();
947 if (leftName.empty() || rightName.empty())
948 return false;
949
950 // If neither is in order file list, no custom sorter.
951 auto leftPos = _orderFiles.find(leftName);
952 auto rightPos = _orderFiles.find(rightName);
953 bool leftIsOrdered = (leftPos != _orderFiles.end());
954 bool rightIsOrdered = (rightPos != _orderFiles.end());
955 if (!leftIsOrdered && !rightIsOrdered)
956 return false;
957
958 // There could be multiple symbols with same name but different file prefixes.
959 unsigned leftOrder;
960 unsigned rightOrder;
961 bool foundLeft =
962 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
963 bool foundRight = rightIsOrdered &&
964 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
965 if (!foundLeft && !foundRight)
966 return false;
967
968 // If only one is in order file list, ordered one goes first.
969 if (foundLeft != foundRight)
970 leftBeforeRight = foundLeft;
971 else
972 leftBeforeRight = (leftOrder < rightOrder);
973
974 return true;
975}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000976
Rui Ueyama61635442015-01-15 08:31:46 +0000977static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000978 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
979 File *file = node->getFile();
980 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
981 }
982 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000983}
984
985// The darwin linker processes input files in two phases. The first phase
986// links in all object (.o) files in command line order. The second phase
987// links in libraries in command line order.
988// In this function we reorder the input files so that all the object files
989// comes before any library file. We also make a group for the library files
990// so that the Resolver will reiterate over the libraries as long as we find
991// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +0000992void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +0000993 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +0000994 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +0000995 [](const std::unique_ptr<Node> &a,
996 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +0000997 return !isLibrary(a) && isLibrary(b);
998 });
999 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1000 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1001}
1002
Pete Cooper80c09742016-01-14 21:53:13 +00001003std::error_code MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001004 auto *machoFile = dyn_cast<MachOFile>(&file);
1005 if (!machoFile)
1006 return std::error_code();
1007
1008 // Check that the arch of the context matches that of the file.
1009 // Also set the arch of the context if it didn't have one.
1010 if (_arch == arch_unknown) {
1011 _arch = machoFile->arch();
1012 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1013 // Archs are different.
1014 return make_dynamic_error_code(file.path() +
1015 Twine(" cannot be linked due to incompatible architecture"));
1016 }
1017
1018 // Check that the OS of the context matches that of the file.
1019 // Also set the OS of the context if it didn't have one.
1020 if (_os == OS::unknown) {
1021 _os = machoFile->OS();
1022 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1023 // OSes are different.
1024 return make_dynamic_error_code(file.path() +
1025 Twine(" cannot be linked due to incompatible operating systems"));
1026 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001027
Pete Cooper0872e462016-01-19 19:46:41 +00001028 // Check that if the objc info exists, that it is compatible with the target
1029 // OS.
1030 switch (machoFile->objcConstraint()) {
1031 case objc_unknown:
1032 // The file is not compiled with objc, so skip the checks.
1033 break;
1034 case objc_gc_only:
1035 case objc_supports_gc:
1036 llvm_unreachable("GC support should already have thrown an error");
1037 case objc_retainReleaseForSimulator:
1038 // The file is built with simulator objc, so make sure that the context
1039 // is also building with simulator support.
1040 if (_os != OS::iOS_simulator)
1041 return make_dynamic_error_code(file.path() +
1042 Twine(" cannot be linked. It contains ObjC built for the simulator"
1043 " while we are linking a non-simulator target"));
1044 assert((_objcConstraint == objc_unknown ||
1045 _objcConstraint == objc_retainReleaseForSimulator) &&
1046 "Must be linking with retain/release for the simulator");
1047 _objcConstraint = objc_retainReleaseForSimulator;
1048 break;
1049 case objc_retainRelease:
1050 // The file is built without simulator objc, so make sure that the
1051 // context is also building without simulator support.
1052 if (_os == OS::iOS_simulator)
1053 return make_dynamic_error_code(file.path() +
1054 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1055 " target while we are linking a simulator target"));
1056 assert((_objcConstraint == objc_unknown ||
1057 _objcConstraint == objc_retainRelease) &&
1058 "Must be linking with retain/release for a non-simulator target");
1059 _objcConstraint = objc_retainRelease;
1060 break;
1061 }
1062
Pete Coopera014ffe2016-01-16 00:07:22 +00001063 // Check that the swift version of the context matches that of the file.
1064 // Also set the swift version of the context if it didn't have one.
1065 if (!_swiftVersion) {
1066 _swiftVersion = machoFile->swiftVersion();
1067 } else if (machoFile->swiftVersion() &&
1068 machoFile->swiftVersion() != _swiftVersion) {
1069 // Swift versions are different.
1070 return make_dynamic_error_code("different swift versions");
1071 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001072
Pete Cooper80c09742016-01-14 21:53:13 +00001073 return std::error_code();
1074}
1075
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001076} // end namespace lld