blob: 05375f145d3411f116934b31bca5dbf8ca3fe13c [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
Pete Cooper40576fa2016-02-04 02:45:23 +000079bool MachOLinkingContext::parsePackedVersion(StringRef str, uint64_t &result) {
80 result = 0;
81
82 if (str.empty())
83 return false;
84
85 SmallVector<StringRef, 5> parts;
86 llvm::SplitString(str, parts, ".");
87
Pete Cooperd5c0e4d2016-02-04 02:50:47 +000088 unsigned long long num;
Pete Cooper40576fa2016-02-04 02:45:23 +000089 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
90 return true;
91 if (num > 0xFFFFFF)
92 return true;
93 result = num << 40;
94
95 unsigned Shift = 30;
96 for (StringRef str : llvm::makeArrayRef(parts).slice(1)) {
97 if (llvm::getAsUnsignedInteger(str, 10, num))
98 return true;
99 if (num > 0x3FF)
100 return true;
101 result |= (num << Shift);
102 Shift -= 10;
103 }
104
105 return false;
106}
107
Nick Kledzike34182f2013-11-06 21:36:55 +0000108MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
109 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
110 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
111 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
112 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
113 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
114 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +0000115 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +0000116 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000117};
118
119MachOLinkingContext::Arch
120MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000121 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
122 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000123 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000124 }
125 return arch_unknown;
126}
127
128MachOLinkingContext::Arch
129MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000130 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
131 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000132 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000133 }
134 return arch_unknown;
135}
136
Nick Kledzike5552772013-12-19 21:58:00 +0000137StringRef MachOLinkingContext::nameFromArch(Arch arch) {
138 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
139 if (info->arch == arch)
140 return info->archName;
141 }
142 return "<unknown>";
143}
144
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000145uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
146 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000147 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
148 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000149 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000150 }
151 llvm_unreachable("Unknown arch type");
152}
153
154uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
155 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000156 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
157 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000158 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000159 }
160 llvm_unreachable("Unknown arch type");
161}
162
Nick Kledzik635f9c72014-09-04 20:08:30 +0000163bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
164 return mach_o::normalized::isThinObjectFile(path, arch);
165}
166
Rafael Espindolaed48e532015-04-27 22:48:51 +0000167bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000168 uint32_t &size) {
169 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
170}
171
Rui Ueyama51502552016-03-02 19:06:20 +0000172MachOLinkingContext::MachOLinkingContext() {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000173
Pete Cooper8ad55fb2016-03-22 17:15:50 +0000174MachOLinkingContext::~MachOLinkingContext() {
175 // Atoms are allocated on BumpPtrAllocator's on File's.
176 // As we transfer atoms from one file to another, we need to clear all of the
177 // atoms before we remove any of the BumpPtrAllocator's.
178 auto &nodes = getNodes();
179 for (unsigned i = 0, e = nodes.size(); i != e; ++i) {
180 FileNode *node = dyn_cast<FileNode>(nodes[i].get());
181 if (!node)
182 continue;
183 File *file = node->getFile();
184 file->clearAtoms();
185 }
186}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000187
Nick Kledzik6960b072013-12-21 01:47:17 +0000188void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
Pete Cooper35116452016-01-22 21:13:24 +0000189 uint32_t minOSVersion,
190 bool exportDynamicSymbols) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000191 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000192 _arch = arch;
193 _os = os;
194 _osMinVersion = minOSVersion;
195
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000196 // If min OS not specified on command line, use reasonable defaults.
Pete Cooper3dd478a2016-02-04 01:57:59 +0000197 // Note that we only do sensible defaults when emitting something other than
198 // object and preload.
199 if (_outputMachOType != llvm::MachO::MH_OBJECT &&
200 _outputMachOType != llvm::MachO::MH_PRELOAD) {
201 if (minOSVersion == 0) {
202 switch (_arch) {
203 case arch_x86_64:
204 case arch_x86:
205 parsePackedVersion("10.8", _osMinVersion);
206 _os = MachOLinkingContext::OS::macOSX;
207 break;
208 case arch_armv6:
209 case arch_armv7:
210 case arch_armv7s:
211 case arch_arm64:
212 parsePackedVersion("7.0", _osMinVersion);
213 _os = MachOLinkingContext::OS::iOS;
214 break;
215 default:
216 break;
217 }
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000218 }
219 }
220
Tim Northoverd30a1f22014-06-20 15:59:00 +0000221 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000222 case llvm::MachO::MH_EXECUTE:
223 // If targeting newer OS, use _main
224 if (minOS("10.8", "6.0")) {
225 _entrySymbolName = "_main";
226 } else {
227 // If targeting older OS, use start (in crt1.o)
228 _entrySymbolName = "start";
229 }
230
231 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
232 // support) and 4KB on 32-bit.
233 if (is64Bit(_arch)) {
234 _pageZeroSize = 0x100000000;
235 } else {
236 _pageZeroSize = 0x1000;
237 }
238
Lang Hamesc80344282015-09-21 22:06:02 +0000239 // Initial base address is __PAGEZERO size.
240 _baseAddress = _pageZeroSize;
241
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000242 // Make PIE by default when targetting newer OSs.
243 switch (os) {
244 case OS::macOSX:
245 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
246 _pie = true;
247 break;
248 case OS::iOS:
249 if (minOSVersion >= 0x00040300) // iOS 4.3
250 _pie = true;
251 break;
252 case OS::iOS_simulator:
253 _pie = true;
254 break;
255 case OS::unknown:
256 break;
257 }
Pete Cooper35116452016-01-22 21:13:24 +0000258 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000259 break;
260 case llvm::MachO::MH_DYLIB:
Pete Cooper35116452016-01-22 21:13:24 +0000261 setGlobalsAreDeadStripRoots(exportDynamicSymbols);
Nick Kledzik6960b072013-12-21 01:47:17 +0000262 break;
263 case llvm::MachO::MH_BUNDLE:
264 break;
265 case llvm::MachO::MH_OBJECT:
266 _printRemainingUndefines = false;
267 _allowRemainingUndefines = true;
268 default:
269 break;
270 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000271
272 // Set default segment page sizes based on arch.
273 if (arch == arch_arm64)
274 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000275}
276
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000277uint32_t MachOLinkingContext::getCPUType() const {
278 return cpuTypeFromArch(_arch);
279}
280
281uint32_t MachOLinkingContext::getCPUSubType() const {
282 return cpuSubtypeFromArch(_arch);
283}
284
Nick Kledzike34182f2013-11-06 21:36:55 +0000285bool MachOLinkingContext::is64Bit(Arch arch) {
286 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
287 if (info->arch == arch) {
288 return (info->cputype & CPU_ARCH_ABI64);
289 }
290 }
291 // unknown archs are not 64-bit.
292 return false;
293}
294
295bool MachOLinkingContext::isHostEndian(Arch arch) {
296 assert(arch != arch_unknown);
297 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
298 if (info->arch == arch) {
299 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
300 }
301 }
302 llvm_unreachable("Unknown arch type");
303}
304
305bool MachOLinkingContext::isBigEndian(Arch arch) {
306 assert(arch != arch_unknown);
307 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
308 if (info->arch == arch) {
309 return ! info->littleEndian;
310 }
311 }
312 llvm_unreachable("Unknown arch type");
313}
314
Nick Kledzike34182f2013-11-06 21:36:55 +0000315bool MachOLinkingContext::is64Bit() const {
316 return is64Bit(_arch);
317}
318
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000319bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000320 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000321 case MH_EXECUTE:
322 case MH_DYLINKER:
323 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000324 return true;
325 default:
326 return false;
327 }
328}
329
Nick Kledzik2458bec2014-07-16 19:49:02 +0000330bool MachOLinkingContext::needsStubsPass() const {
331 switch (_outputMachOType) {
332 case MH_EXECUTE:
333 return !_outputMachOTypeStatic;
334 case MH_DYLIB:
335 case MH_BUNDLE:
336 return true;
337 default:
338 return false;
339 }
340}
341
342bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000343 // GOT pass not used in -r mode.
344 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000345 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000346 // Only some arches use GOT pass.
347 switch (_arch) {
348 case arch_x86_64:
349 case arch_arm64:
350 return true;
351 default:
352 return false;
353 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000354}
355
Tim Northovercf78d372014-09-30 21:29:54 +0000356bool MachOLinkingContext::needsCompactUnwindPass() const {
357 switch (_outputMachOType) {
358 case MH_EXECUTE:
359 case MH_DYLIB:
360 case MH_BUNDLE:
361 return archHandler().needsCompactUnwind();
362 default:
363 return false;
364 }
365}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000366
Pete Cooper90dbab02016-01-19 21:54:21 +0000367bool MachOLinkingContext::needsObjCPass() const {
368 // ObjC pass is only needed if any of the inputs were ObjC.
369 return _objcConstraint != objc_unknown;
370}
371
Nick Kledzik4121bce2014-10-14 01:51:42 +0000372bool MachOLinkingContext::needsShimPass() const {
373 // Shim pass only used in final executables.
374 if (_outputMachOType == MH_OBJECT)
375 return false;
376 // Only 32-bit arm arches use Shim pass.
377 switch (_arch) {
378 case arch_armv6:
379 case arch_armv7:
380 case arch_armv7s:
381 return true;
382 default:
383 return false;
384 }
385}
386
Lang Hames49047032015-06-23 20:35:31 +0000387bool MachOLinkingContext::needsTLVPass() const {
388 switch (_outputMachOType) {
389 case MH_BUNDLE:
390 case MH_EXECUTE:
391 case MH_DYLIB:
392 return true;
393 default:
394 return false;
395 }
396}
397
Nick Kledzik2458bec2014-07-16 19:49:02 +0000398StringRef MachOLinkingContext::binderSymbolName() const {
399 return archHandler().stubInfo().binderSymbolName;
400}
401
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000402bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000403 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000404 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000405 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000406 if (parsePackedVersion(mac, parsedVersion))
407 return false;
408 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000409 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000410 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000411 if (parsePackedVersion(iOS, parsedVersion))
412 return false;
413 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000414 case OS::unknown:
Pete Cooper3dd478a2016-02-04 01:57:59 +0000415 // If we don't know the target, then assume that we don't meet the min OS.
416 // This matches the ld64 behaviour
417 return false;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000418 }
Reid Kleckner257102e2016-02-10 19:28:13 +0000419 llvm_unreachable("invalid OS enum");
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000420}
421
422bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000423 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000424 return minOS("10.8", "6.0");
425 }
426 return false;
427}
428
429bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000430 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000431 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000432 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000433 return true;
434 else
435 return !minOS("10.8", "6.0");
436 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000437 case MH_DYLINKER:
438 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000439 return true;
440 default:
441 return false;
442 }
443}
444
Tim Northover77d82202014-07-10 11:21:06 +0000445bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000446 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000447 return llvm::sys::fs::exists(path.str());
448
449 // Otherwise, we're in test mode: only files explicitly provided on the
450 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000451 std::string key = path.str();
452 std::replace(key.begin(), key.end(), '\\', '/');
453 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000454}
455
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000456bool MachOLinkingContext::fileExists(StringRef path) const {
457 bool found = pathExists(path);
458 // Log search misses.
459 if (!found)
460 addInputFileNotFound(path);
461
462 // When testing, file is never opened, so logging is done here.
463 if (_testingFileUsage && found)
464 addInputFileDependency(path);
465
466 return found;
467}
468
Nick Kledzik2d835da2014-08-14 22:20:41 +0000469void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
470 _syslibRoots = paths;
471}
472
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000473void MachOLinkingContext::addRpath(StringRef rpath) {
474 _rpaths.push_back(rpath);
475}
476
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000477void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
478 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000479 bool addedModifiedPath = false;
480
Nick Kledzik2d835da2014-08-14 22:20:41 +0000481 // -syslibroot only applies to absolute paths.
482 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000483 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000484 SmallString<256> path(syslibRoot);
485 llvm::sys::path::append(path, libPath);
486 if (pathExists(path)) {
487 _searchDirs.push_back(path.str().copy(_allocator));
488 addedModifiedPath = true;
489 }
490 }
491 }
492
493 if (addedModifiedPath)
494 return;
495
496 // Finally, if only one -syslibroot is given, system paths which aren't in it
497 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000498 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000499 if (pathExists(libPath)) {
500 _searchDirs.push_back(libPath);
501 }
502 }
503}
504
Nick Kledzik2d835da2014-08-14 22:20:41 +0000505void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
506 bool isSystemPath) {
507 bool pathAdded = false;
508
509 // -syslibroot only used with to absolute framework search paths.
510 if (fwPath.startswith("/")) {
511 for (auto syslibRoot : _syslibRoots) {
512 SmallString<256> path(syslibRoot);
513 llvm::sys::path::append(path, fwPath);
514 if (pathExists(path)) {
515 _frameworkDirs.push_back(path.str().copy(_allocator));
516 pathAdded = true;
517 }
518 }
519 }
520 // If fwPath found in any -syslibroot, then done.
521 if (pathAdded)
522 return;
523
524 // If only one -syslibroot, system paths not in that SDK are suppressed.
525 if (isSystemPath && (_syslibRoots.size() == 1))
526 return;
527
528 // Only use raw fwPath if that directory exists.
529 if (pathExists(fwPath))
530 _frameworkDirs.push_back(fwPath);
531}
532
Pete Cooperd0a643e2016-03-31 01:09:35 +0000533llvm::Optional<StringRef>
Tim Northover77d82202014-07-10 11:21:06 +0000534MachOLinkingContext::searchDirForLibrary(StringRef path,
535 StringRef libName) const {
536 SmallString<256> fullPath;
537 if (libName.endswith(".o")) {
538 // A request ending in .o is special: just search for the file directly.
539 fullPath.assign(path);
540 llvm::sys::path::append(fullPath, libName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000541 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000542 return fullPath.str().copy(_allocator);
Pete Cooperd0a643e2016-03-31 01:09:35 +0000543 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000544 }
545
546 // Search for dynamic library
547 fullPath.assign(path);
548 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".dylib");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000549 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000550 return fullPath.str().copy(_allocator);
551
552 // If not, try for a static library
553 fullPath.assign(path);
554 llvm::sys::path::append(fullPath, Twine("lib") + libName + ".a");
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000555 if (fileExists(fullPath))
Tim Northover77d82202014-07-10 11:21:06 +0000556 return fullPath.str().copy(_allocator);
557
Pete Cooperd0a643e2016-03-31 01:09:35 +0000558 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000559}
560
Pete Cooperd0a643e2016-03-31 01:09:35 +0000561llvm::Optional<StringRef>
562MachOLinkingContext::searchLibrary(StringRef libName) const {
Tim Northover77d82202014-07-10 11:21:06 +0000563 SmallString<256> path;
564 for (StringRef dir : searchDirs()) {
Pete Cooperd0a643e2016-03-31 01:09:35 +0000565 llvm::Optional<StringRef> searchDir = searchDirForLibrary(dir, libName);
566 if (searchDir)
567 return searchDir;
Tim Northover77d82202014-07-10 11:21:06 +0000568 }
569
Pete Cooperd0a643e2016-03-31 01:09:35 +0000570 return llvm::None;
Tim Northover77d82202014-07-10 11:21:06 +0000571}
572
Pete Cooperd0a643e2016-03-31 01:09:35 +0000573llvm::Optional<StringRef>
574MachOLinkingContext::findPathForFramework(StringRef fwName) const{
Nick Kledzik2d835da2014-08-14 22:20:41 +0000575 SmallString<256> fullPath;
576 for (StringRef dir : frameworkDirs()) {
577 fullPath.assign(dir);
578 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000579 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000580 return fullPath.str().copy(_allocator);
581 }
582
Pete Cooperd0a643e2016-03-31 01:09:35 +0000583 return llvm::None;
Nick Kledzik2d835da2014-08-14 22:20:41 +0000584}
585
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000586bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000587 // TODO: if -arch not specified, look at arch of first .o file.
588
Tim Northoverd30a1f22014-06-20 15:59:00 +0000589 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000590 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000591 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000592 }
593
Tim Northoverd30a1f22014-06-20 15:59:00 +0000594 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000595 diagnostics
596 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000597 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000598 }
599
Tim Northoverd30a1f22014-06-20 15:59:00 +0000600 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000601 diagnostics
602 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000603 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000604 }
605
Tim Northoverd30a1f22014-06-20 15:59:00 +0000606 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000607 diagnostics
608 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000609 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000610 }
611
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000612 // If -exported_symbols_list used, all exported symbols must be defined.
613 if (_exportMode == ExportMode::whiteList) {
614 for (const auto &symbol : _exportedSymbols)
615 addInitialUndefinedSymbol(symbol.getKey());
616 }
617
Nick Kledzik77afc712014-08-21 20:25:50 +0000618 // If -dead_strip, set up initial live symbols.
619 if (deadStrip()) {
620 // Entry point is live.
621 if (outputTypeHasEntry())
622 addDeadStripRoot(entrySymbolName());
623 // Lazy binding helper is live.
624 if (needsStubsPass())
625 addDeadStripRoot(binderSymbolName());
626 // If using -exported_symbols_list, make all exported symbols live.
627 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000628 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000629 for (const auto &symbol : _exportedSymbols)
630 addDeadStripRoot(symbol.getKey());
631 }
632 }
633
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000634 addOutputFileDependency(outputPath());
635
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000636 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000637}
638
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000639void MachOLinkingContext::addPasses(PassManager &pm) {
Pete Cooper90dbab02016-01-19 21:54:21 +0000640 // objc pass should be before layout pass. Otherwise test cases may contain
641 // no atoms which confuses the layout pass.
642 if (needsObjCPass())
643 mach_o::addObjCPass(pm, *this);
Rui Ueyama00762152015-02-05 20:05:33 +0000644 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000645 if (needsStubsPass())
646 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000647 if (needsCompactUnwindPass())
648 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000649 if (needsGOTPass())
650 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000651 if (needsTLVPass())
652 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000653 if (needsShimPass())
654 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000655}
656
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000657Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000658 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000659 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000660 return *_writer;
661}
662
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000663ErrorOr<std::unique_ptr<MemoryBuffer>>
664MachOLinkingContext::getMemoryBuffer(StringRef path) {
665 addInputFileDependency(path);
666
Rui Ueyamadf230b22015-01-15 04:34:31 +0000667 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000668 MemoryBuffer::getFileOrSTDIN(path);
669 if (std::error_code ec = mbOrErr.getError())
670 return ec;
671 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
672
673 // If buffer contains a fat file, find required arch in fat buffer
674 // and switch buffer to point to just that required slice.
675 uint32_t offset;
676 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000677 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000678 return MemoryBuffer::getFileSlice(path, size, offset);
679 return std::move(mb);
680}
681
682MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
683 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000684 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000685 return nullptr;
686
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000687 ErrorOr<std::unique_ptr<File>> fileOrErr =
688 registry().loadFile(std::move(mbOrErr.get()));
689 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000690 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000691 std::unique_ptr<File> &file = fileOrErr.get();
692 file->parse();
693 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000694 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000695 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000696 return result;
697}
698
Nick Kledzik22c90732014-10-01 20:24:30 +0000699MachODylibFile* MachOLinkingContext::findIndirectDylib(StringRef path) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000700 // See if already loaded.
701 auto pos = _pathToDylibMap.find(path);
702 if (pos != _pathToDylibMap.end())
703 return pos->second;
704
705 // Search -L paths if of the form "libXXX.dylib"
706 std::pair<StringRef, StringRef> split = path.rsplit('/');
707 StringRef leafName = split.second;
708 if (leafName.startswith("lib") && leafName.endswith(".dylib")) {
709 // FIXME: Need to enhance searchLibrary() to only look for .dylib
710 auto libPath = searchLibrary(leafName);
Pete Cooperd0a643e2016-03-31 01:09:35 +0000711 if (libPath)
712 return loadIndirectDylib(libPath.getValue());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000713 }
714
715 // Try full path with sysroot.
716 for (StringRef sysPath : _syslibRoots) {
717 SmallString<256> fullPath;
718 fullPath.assign(sysPath);
719 llvm::sys::path::append(fullPath, path);
720 if (pathExists(fullPath))
721 return loadIndirectDylib(fullPath);
722 }
723
724 // Try full path.
725 if (pathExists(path)) {
726 return loadIndirectDylib(path);
727 }
728
729 return nullptr;
730}
731
Nick Kledzik5b9e48b2014-11-19 02:21:53 +0000732uint32_t MachOLinkingContext::dylibCurrentVersion(StringRef installName) const {
733 auto pos = _pathToDylibMap.find(installName);
734 if (pos != _pathToDylibMap.end())
735 return pos->second->currentVersion();
736 else
737 return 0x1000; // 1.0
738}
739
740uint32_t MachOLinkingContext::dylibCompatVersion(StringRef installName) const {
741 auto pos = _pathToDylibMap.find(installName);
742 if (pos != _pathToDylibMap.end())
743 return pos->second->compatVersion();
744 else
745 return 0x1000; // 1.0
746}
747
Simon Atanasyanc4378882015-04-06 20:43:35 +0000748void MachOLinkingContext::createImplicitFiles(
Nick Kledzik22c90732014-10-01 20:24:30 +0000749 std::vector<std::unique_ptr<File> > &result) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000750 // Add indirect dylibs by asking each linked dylib to add its indirects.
751 // Iterate until no more dylibs get loaded.
752 size_t dylibCount = 0;
753 while (dylibCount != _allDylibs.size()) {
754 dylibCount = _allDylibs.size();
755 for (MachODylibFile *dylib : _allDylibs) {
756 dylib->loadReExportedDylibs([this] (StringRef path) -> MachODylibFile* {
757 return findIndirectDylib(path); });
758 }
759 }
760
761 // Let writer add output type specific extras.
Simon Atanasyanc4378882015-04-06 20:43:35 +0000762 writer().createImplicitFiles(result);
Lang Hames5c692002015-09-28 20:25:14 +0000763
Lang Hames9a4c94e2015-09-28 20:52:21 +0000764 // If undefinedMode is != error, add a FlatNamespaceFile instance. This will
765 // provide a SharedLibraryAtom for symbols that aren't defined elsewhere.
766 if (undefinedMode() != UndefinedMode::error) {
767 result.emplace_back(new mach_o::FlatNamespaceFile(*this));
Lang Hames5c692002015-09-28 20:25:14 +0000768 _flatNamespaceFile = result.back().get();
769 }
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000770}
771
Nick Kledzik51720672014-10-16 19:31:28 +0000772void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
773 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000774 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000775 _allDylibs.insert(dylib);
776 _pathToDylibMap[dylib->installName()] = dylib;
777 // If path is different than install name, register path too.
778 if (!dylib->path().equals(dylib->installName()))
779 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000780 if (upward)
781 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000782}
783
Nick Kledzik51720672014-10-16 19:31:28 +0000784bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
785 for (MachODylibFile *dylib : _upwardDylibs) {
786 if (dylib->installName().equals(installName))
787 return true;
788 }
789 return false;
790}
791
Nick Kledzik2458bec2014-07-16 19:49:02 +0000792ArchHandler &MachOLinkingContext::archHandler() const {
793 if (!_archHandler)
794 _archHandler = ArchHandler::create(_arch);
795 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000796}
797
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000798void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000799 uint16_t align) {
800 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000801 _sectAligns.push_back(entry);
802}
803
Lang Hamesb1b67f42015-10-24 08:20:51 +0000804void MachOLinkingContext::addSectCreateSection(
805 StringRef seg, StringRef sect,
806 std::unique_ptr<MemoryBuffer> content) {
807
808 if (!_sectCreateFile) {
809 auto sectCreateFile = llvm::make_unique<mach_o::SectCreateFile>();
810 _sectCreateFile = sectCreateFile.get();
811 getNodes().push_back(llvm::make_unique<FileNode>(std::move(sectCreateFile)));
812 }
813
814 assert(_sectCreateFile && "sectcreate file does not exist.");
815 _sectCreateFile->addSection(seg, sect, std::move(content));
816}
817
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000818bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000819 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000820 for (const SectionAlign &entry : _sectAligns) {
821 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000822 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000823 return true;
824 }
825 }
826 return false;
827}
828
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000829void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000830 // Support old crufty export lists with bogus entries.
831 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
832 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
833 return;
834 }
835 // Only i386 MacOSX uses old ABI, so don't change those.
836 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
837 // ObjC has two differnent ABIs. Be nice and allow one export list work for
838 // both ABIs by renaming symbols.
839 if (sym.startswith(".objc_class_name_")) {
840 std::string abi2className("_OBJC_CLASS_$_");
841 abi2className += sym.substr(17);
842 _exportedSymbols.insert(copy(abi2className));
843 std::string abi2metaclassName("_OBJC_METACLASS_$_");
844 abi2metaclassName += sym.substr(17);
845 _exportedSymbols.insert(copy(abi2metaclassName));
846 return;
847 }
848 }
849
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000850 // FIXME: Support wildcards.
851 _exportedSymbols.insert(sym);
852}
853
854bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
855 switch (_exportMode) {
856 case ExportMode::globals:
857 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
858 break;
859 case ExportMode::whiteList:
860 return _exportedSymbols.count(sym);
861 case ExportMode::blackList:
862 return !_exportedSymbols.count(sym);
863 }
Yaron Keren9682c852014-09-21 05:07:44 +0000864 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000865}
866
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000867std::string MachOLinkingContext::demangle(StringRef symbolName) const {
868 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000869 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000870 return symbolName;
871
872 // Only try to demangle symbols that look like C++ symbols
873 if (!symbolName.startswith("__Z"))
874 return symbolName;
875
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000876#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000877 SmallString<256> symBuff;
878 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
879 // Mach-O has extra leading underscore that needs to be removed.
880 const char *cstr = nullTermSym.data() + 1;
881 int status;
882 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
Rui Ueyama43155d02015-10-02 00:36:00 +0000883 if (demangled) {
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000884 std::string result(demangled);
885 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
886 free(demangled);
887 return result;
888 }
889#endif
890
891 return symbolName;
892}
893
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000894std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
895 std::error_code ec;
896 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
897 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
898 if (ec) {
899 _dependencyInfo.reset();
900 return ec;
901 }
902
903 char linkerVersionOpcode = 0x00;
904 *_dependencyInfo << linkerVersionOpcode;
905 *_dependencyInfo << "lld"; // FIXME
906 *_dependencyInfo << '\0';
907
908 return std::error_code();
909}
910
911void MachOLinkingContext::addInputFileDependency(StringRef path) const {
912 if (!_dependencyInfo)
913 return;
914
915 char inputFileOpcode = 0x10;
916 *_dependencyInfo << inputFileOpcode;
917 *_dependencyInfo << path;
918 *_dependencyInfo << '\0';
919}
920
921void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
922 if (!_dependencyInfo)
923 return;
924
925 char inputFileOpcode = 0x11;
926 *_dependencyInfo << inputFileOpcode;
927 *_dependencyInfo << path;
928 *_dependencyInfo << '\0';
929}
930
931void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
932 if (!_dependencyInfo)
933 return;
934
935 char outputFileOpcode = 0x40;
936 *_dependencyInfo << outputFileOpcode;
937 *_dependencyInfo << path;
938 *_dependencyInfo << '\0';
939}
940
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000941void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
942 StringRef filename) {
943 // To support sorting static functions which may have the same name in
944 // multiple .o files, _orderFiles maps the symbol name to a vector
945 // of OrderFileNode each of which can specify a file prefix.
946 OrderFileNode info;
947 if (!filename.empty())
948 info.fileFilter = copy(filename);
949 info.order = _orderFileEntries++;
950 _orderFiles[symbol].push_back(info);
951}
952
953bool
954MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
955 const DefinedAtom *atom,
956 unsigned &ordinal) {
957 const File *objFile = &atom->file();
958 assert(objFile);
959 StringRef objName = objFile->path();
960 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
961 if (!dirAndLeaf.second.empty())
962 objName = dirAndLeaf.second;
963 for (const OrderFileNode &info : nodes) {
964 if (info.fileFilter.empty()) {
965 // Have unprefixed symbol name in order file that matches this atom.
966 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000967 return true;
968 }
969 if (info.fileFilter.equals(objName)) {
970 // Have prefixed symbol name in order file that matches atom's path.
971 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000972 return true;
973 }
974 }
975 return false;
976}
977
978bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
979 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000980 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000981 // No custom sorting if no order file entries.
982 if (!_orderFileEntries)
983 return false;
984
985 // Order files can only order named atoms.
986 StringRef leftName = left->name();
987 StringRef rightName = right->name();
988 if (leftName.empty() || rightName.empty())
989 return false;
990
991 // If neither is in order file list, no custom sorter.
992 auto leftPos = _orderFiles.find(leftName);
993 auto rightPos = _orderFiles.find(rightName);
994 bool leftIsOrdered = (leftPos != _orderFiles.end());
995 bool rightIsOrdered = (rightPos != _orderFiles.end());
996 if (!leftIsOrdered && !rightIsOrdered)
997 return false;
998
999 // There could be multiple symbols with same name but different file prefixes.
1000 unsigned leftOrder;
1001 unsigned rightOrder;
1002 bool foundLeft =
1003 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
1004 bool foundRight = rightIsOrdered &&
1005 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
1006 if (!foundLeft && !foundRight)
1007 return false;
1008
1009 // If only one is in order file list, ordered one goes first.
1010 if (foundLeft != foundRight)
1011 leftBeforeRight = foundLeft;
1012 else
1013 leftBeforeRight = (leftOrder < rightOrder);
1014
1015 return true;
1016}
Nick Kledzik8c0bf752014-08-21 01:59:11 +00001017
Rui Ueyama61635442015-01-15 08:31:46 +00001018static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +00001019 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
1020 File *file = node->getFile();
1021 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
1022 }
1023 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +00001024}
1025
1026// The darwin linker processes input files in two phases. The first phase
1027// links in all object (.o) files in command line order. The second phase
1028// links in libraries in command line order.
1029// In this function we reorder the input files so that all the object files
1030// comes before any library file. We also make a group for the library files
1031// so that the Resolver will reiterate over the libraries as long as we find
1032// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +00001033void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +00001034 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +00001035 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +00001036 [](const std::unique_ptr<Node> &a,
1037 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +00001038 return !isLibrary(a) && isLibrary(b);
1039 });
1040 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
1041 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
1042}
1043
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001044llvm::Error MachOLinkingContext::handleLoadedFile(File &file) {
Pete Cooper99f3b942016-01-14 23:25:06 +00001045 auto *machoFile = dyn_cast<MachOFile>(&file);
1046 if (!machoFile)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001047 return llvm::Error();
Pete Cooper99f3b942016-01-14 23:25:06 +00001048
1049 // Check that the arch of the context matches that of the file.
1050 // Also set the arch of the context if it didn't have one.
1051 if (_arch == arch_unknown) {
1052 _arch = machoFile->arch();
1053 } else if (machoFile->arch() != arch_unknown && machoFile->arch() != _arch) {
1054 // Archs are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001055 return llvm::make_error<GenericError>(file.path() +
Pete Cooper99f3b942016-01-14 23:25:06 +00001056 Twine(" cannot be linked due to incompatible architecture"));
1057 }
1058
1059 // Check that the OS of the context matches that of the file.
1060 // Also set the OS of the context if it didn't have one.
1061 if (_os == OS::unknown) {
1062 _os = machoFile->OS();
1063 } else if (machoFile->OS() != OS::unknown && machoFile->OS() != _os) {
1064 // OSes are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001065 return llvm::make_error<GenericError>(file.path() +
Pete Cooper99f3b942016-01-14 23:25:06 +00001066 Twine(" cannot be linked due to incompatible operating systems"));
1067 }
Pete Coopera014ffe2016-01-16 00:07:22 +00001068
Pete Cooper0872e462016-01-19 19:46:41 +00001069 // Check that if the objc info exists, that it is compatible with the target
1070 // OS.
1071 switch (machoFile->objcConstraint()) {
1072 case objc_unknown:
1073 // The file is not compiled with objc, so skip the checks.
1074 break;
1075 case objc_gc_only:
1076 case objc_supports_gc:
1077 llvm_unreachable("GC support should already have thrown an error");
1078 case objc_retainReleaseForSimulator:
1079 // The file is built with simulator objc, so make sure that the context
1080 // is also building with simulator support.
1081 if (_os != OS::iOS_simulator)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001082 return llvm::make_error<GenericError>(file.path() +
Pete Cooper0872e462016-01-19 19:46:41 +00001083 Twine(" cannot be linked. It contains ObjC built for the simulator"
1084 " while we are linking a non-simulator target"));
1085 assert((_objcConstraint == objc_unknown ||
1086 _objcConstraint == objc_retainReleaseForSimulator) &&
1087 "Must be linking with retain/release for the simulator");
1088 _objcConstraint = objc_retainReleaseForSimulator;
1089 break;
1090 case objc_retainRelease:
1091 // The file is built without simulator objc, so make sure that the
1092 // context is also building without simulator support.
1093 if (_os == OS::iOS_simulator)
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001094 return llvm::make_error<GenericError>(file.path() +
Pete Cooper0872e462016-01-19 19:46:41 +00001095 Twine(" cannot be linked. It contains ObjC built for a non-simulator"
1096 " target while we are linking a simulator target"));
1097 assert((_objcConstraint == objc_unknown ||
1098 _objcConstraint == objc_retainRelease) &&
1099 "Must be linking with retain/release for a non-simulator target");
1100 _objcConstraint = objc_retainRelease;
1101 break;
1102 }
1103
Pete Coopera014ffe2016-01-16 00:07:22 +00001104 // Check that the swift version of the context matches that of the file.
1105 // Also set the swift version of the context if it didn't have one.
1106 if (!_swiftVersion) {
1107 _swiftVersion = machoFile->swiftVersion();
1108 } else if (machoFile->swiftVersion() &&
1109 machoFile->swiftVersion() != _swiftVersion) {
1110 // Swift versions are different.
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001111 return llvm::make_error<GenericError>("different swift versions");
Pete Coopera014ffe2016-01-16 00:07:22 +00001112 }
Pete Cooper90dbab02016-01-19 21:54:21 +00001113
Pete Cooper3c40b5b2016-03-30 20:56:54 +00001114 return llvm::Error();
Pete Cooper80c09742016-01-14 21:53:13 +00001115}
1116
Rui Ueyama0ca149f2013-08-06 22:31:59 +00001117} // end namespace lld