blob: d8cc133cb5f5bf1909861da0b0d48ba249448be8 [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"
Rui Ueyamadf230b22015-01-15 04:34:31 +000016#include "lld/Core/ArchiveLibraryFile.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000017#include "lld/Core/PassManager.h"
Greg Fitzgerald4b6a7e32015-01-21 22:54:56 +000018#include "lld/Core/Reader.h"
19#include "lld/Core/Writer.h"
Rui Ueyamadf230b22015-01-15 04:34:31 +000020#include "lld/Driver/Driver.h"
Benjamin Kramer06a42af2015-03-02 00:48:06 +000021#include "llvm/ADT/STLExtras.h"
Rui Ueyama0ca149f2013-08-06 22:31:59 +000022#include "llvm/ADT/StringExtras.h"
23#include "llvm/ADT/Triple.h"
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000024#include "llvm/Config/config.h"
Rui Ueyama00eb2572014-12-10 00:33:00 +000025#include "llvm/Support/Debug.h"
Chandler Carruth89642a72015-01-14 11:26:52 +000026#include "llvm/Support/Errc.h"
Nick Kledzike34182f2013-11-06 21:36:55 +000027#include "llvm/Support/Host.h"
Nick Kledzik473933b2013-09-27 22:50:00 +000028#include "llvm/Support/MachO.h"
Tim Northover77d82202014-07-10 11:21:06 +000029#include "llvm/Support/Path.h"
Rui Ueyama57a29532014-08-06 19:37:35 +000030#include <algorithm>
31
Rui Ueyamafccf7ef2014-10-27 07:44:40 +000032#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +000033#include <cxxabi.h>
34#endif
35
Nick Kledzik2458bec2014-07-16 19:49:02 +000036using lld::mach_o::ArchHandler;
Nick Kledzik8fc67fb2014-08-13 23:55:41 +000037using lld::mach_o::MachODylibFile;
Nick Kledzike34182f2013-11-06 21:36:55 +000038using namespace llvm::MachO;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000039
40namespace lld {
41
Nick Kledzike850d9d2013-09-10 23:46:57 +000042bool MachOLinkingContext::parsePackedVersion(StringRef str, uint32_t &result) {
43 result = 0;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000044
45 if (str.empty())
46 return false;
47
48 SmallVector<StringRef, 3> parts;
49 llvm::SplitString(str, parts, ".");
50
51 unsigned long long num;
52 if (llvm::getAsUnsignedInteger(parts[0], 10, num))
53 return true;
54 if (num > 65535)
55 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000056 result = num << 16;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000057
58 if (parts.size() > 1) {
59 if (llvm::getAsUnsignedInteger(parts[1], 10, num))
60 return true;
61 if (num > 255)
62 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000063 result |= (num << 8);
Rui Ueyama0ca149f2013-08-06 22:31:59 +000064 }
65
66 if (parts.size() > 2) {
67 if (llvm::getAsUnsignedInteger(parts[2], 10, num))
68 return true;
69 if (num > 255)
70 return true;
Nick Kledzike850d9d2013-09-10 23:46:57 +000071 result |= num;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000072 }
73
74 return false;
75}
76
Rui Ueyama0ca149f2013-08-06 22:31:59 +000077
Nick Kledzike34182f2013-11-06 21:36:55 +000078MachOLinkingContext::ArchInfo MachOLinkingContext::_s_archInfos[] = {
79 { "x86_64", arch_x86_64, true, CPU_TYPE_X86_64, CPU_SUBTYPE_X86_64_ALL },
80 { "i386", arch_x86, true, CPU_TYPE_I386, CPU_SUBTYPE_X86_ALL },
81 { "ppc", arch_ppc, false, CPU_TYPE_POWERPC, CPU_SUBTYPE_POWERPC_ALL },
82 { "armv6", arch_armv6, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V6 },
83 { "armv7", arch_armv7, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7 },
84 { "armv7s", arch_armv7s, true, CPU_TYPE_ARM, CPU_SUBTYPE_ARM_V7S },
Nick Kledzik1bebb282014-09-09 23:52:59 +000085 { "arm64", arch_arm64, true, CPU_TYPE_ARM64, CPU_SUBTYPE_ARM64_ALL },
Nick Kledzike34182f2013-11-06 21:36:55 +000086 { "", arch_unknown,false, 0, 0 }
Rui Ueyama0ca149f2013-08-06 22:31:59 +000087};
88
89MachOLinkingContext::Arch
90MachOLinkingContext::archFromCpuType(uint32_t cputype, uint32_t cpusubtype) {
Nick Kledzike34182f2013-11-06 21:36:55 +000091 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
92 if ((info->cputype == cputype) && (info->cpusubtype == cpusubtype))
Rui Ueyama0ca149f2013-08-06 22:31:59 +000093 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +000094 }
95 return arch_unknown;
96}
97
98MachOLinkingContext::Arch
99MachOLinkingContext::archFromName(StringRef archName) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000100 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
101 if (info->archName.equals(archName))
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000102 return info->arch;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000103 }
104 return arch_unknown;
105}
106
Nick Kledzike5552772013-12-19 21:58:00 +0000107StringRef MachOLinkingContext::nameFromArch(Arch arch) {
108 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
109 if (info->arch == arch)
110 return info->archName;
111 }
112 return "<unknown>";
113}
114
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000115uint32_t MachOLinkingContext::cpuTypeFromArch(Arch arch) {
116 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000117 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
118 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000119 return info->cputype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000120 }
121 llvm_unreachable("Unknown arch type");
122}
123
124uint32_t MachOLinkingContext::cpuSubtypeFromArch(Arch arch) {
125 assert(arch != arch_unknown);
Nick Kledzike34182f2013-11-06 21:36:55 +0000126 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
127 if (info->arch == arch)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000128 return info->cpusubtype;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000129 }
130 llvm_unreachable("Unknown arch type");
131}
132
Nick Kledzik635f9c72014-09-04 20:08:30 +0000133bool MachOLinkingContext::isThinObjectFile(StringRef path, Arch &arch) {
134 return mach_o::normalized::isThinObjectFile(path, arch);
135}
136
Rafael Espindolaed48e532015-04-27 22:48:51 +0000137bool MachOLinkingContext::sliceFromFatFile(MemoryBufferRef mb, uint32_t &offset,
Nick Kledzik14b5d202014-10-08 01:48:10 +0000138 uint32_t &size) {
139 return mach_o::normalized::sliceFromFatFile(mb, _arch, offset, size);
140}
141
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000142MachOLinkingContext::MachOLinkingContext()
Tim Northoverd30a1f22014-06-20 15:59:00 +0000143 : _outputMachOType(MH_EXECUTE), _outputMachOTypeStatic(false),
Tim Northoveraf3075b2014-09-10 10:39:57 +0000144 _doNothing(false), _pie(false), _arch(arch_unknown), _os(OS::macOSX),
145 _osMinVersion(0), _pageZeroSize(0), _pageSize(4096), _baseAddress(0),
Lang Hamesff4b13c2015-05-22 00:25:34 +0000146 _stackSize(0), _compatibilityVersion(0), _currentVersion(0),
Lang Hames5c692002015-09-28 20:25:14 +0000147 _flatNamespace(false), _undefinedMode(UndefinedMode::error),
Lang Hames65a64c92015-05-20 22:10:50 +0000148 _deadStrippableDylib(false), _printAtoms(false), _testingFileUsage(false),
149 _keepPrivateExterns(false), _demangle(false), _archHandler(nullptr),
Nick Kledzik8f75da02014-11-06 03:03:42 +0000150 _exportMode(ExportMode::globals),
Lang Hames5c692002015-09-28 20:25:14 +0000151 _debugInfoMode(DebugInfoMode::addDebugMap), _orderFileEntries(0),
152 _flatNamespaceFile(nullptr) {}
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000153
154MachOLinkingContext::~MachOLinkingContext() {}
155
Nick Kledzik6960b072013-12-21 01:47:17 +0000156void MachOLinkingContext::configure(HeaderFileType type, Arch arch, OS os,
157 uint32_t minOSVersion) {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000158 _outputMachOType = type;
Nick Kledzik6960b072013-12-21 01:47:17 +0000159 _arch = arch;
160 _os = os;
161 _osMinVersion = minOSVersion;
162
Nick Kledzikcb2018f2014-10-09 01:01:16 +0000163 // If min OS not specified on command line, use reasonable defaults.
164 if (minOSVersion == 0) {
165 switch (_arch) {
166 case arch_x86_64:
167 case arch_x86:
168 parsePackedVersion("10.8", _osMinVersion);
169 _os = MachOLinkingContext::OS::macOSX;
170 break;
171 case arch_armv6:
172 case arch_armv7:
173 case arch_armv7s:
174 case arch_arm64:
175 parsePackedVersion("7.0", _osMinVersion);
176 _os = MachOLinkingContext::OS::iOS;
177 break;
178 default:
179 break;
180 }
181 }
182
Tim Northoverd30a1f22014-06-20 15:59:00 +0000183 switch (_outputMachOType) {
Nick Kledzik6960b072013-12-21 01:47:17 +0000184 case llvm::MachO::MH_EXECUTE:
185 // If targeting newer OS, use _main
186 if (minOS("10.8", "6.0")) {
187 _entrySymbolName = "_main";
188 } else {
189 // If targeting older OS, use start (in crt1.o)
190 _entrySymbolName = "start";
191 }
192
193 // __PAGEZERO defaults to 4GB on 64-bit (except for PP64 which lld does not
194 // support) and 4KB on 32-bit.
195 if (is64Bit(_arch)) {
196 _pageZeroSize = 0x100000000;
197 } else {
198 _pageZeroSize = 0x1000;
199 }
200
Lang Hamesc80344282015-09-21 22:06:02 +0000201 // Initial base address is __PAGEZERO size.
202 _baseAddress = _pageZeroSize;
203
Nick Kledzikb7035ae2014-09-09 00:17:52 +0000204 // Make PIE by default when targetting newer OSs.
205 switch (os) {
206 case OS::macOSX:
207 if (minOSVersion >= 0x000A0700) // MacOSX 10.7
208 _pie = true;
209 break;
210 case OS::iOS:
211 if (minOSVersion >= 0x00040300) // iOS 4.3
212 _pie = true;
213 break;
214 case OS::iOS_simulator:
215 _pie = true;
216 break;
217 case OS::unknown:
218 break;
219 }
Nick Kledzik6960b072013-12-21 01:47:17 +0000220 break;
221 case llvm::MachO::MH_DYLIB:
Davide Italiano7b68b902015-03-09 06:05:42 +0000222 setGlobalsAreDeadStripRoots(true);
Nick Kledzik6960b072013-12-21 01:47:17 +0000223 break;
224 case llvm::MachO::MH_BUNDLE:
225 break;
226 case llvm::MachO::MH_OBJECT:
227 _printRemainingUndefines = false;
228 _allowRemainingUndefines = true;
229 default:
230 break;
231 }
Nick Kledzik1bebb282014-09-09 23:52:59 +0000232
233 // Set default segment page sizes based on arch.
234 if (arch == arch_arm64)
235 _pageSize = 4*4096;
Nick Kledzik6960b072013-12-21 01:47:17 +0000236}
237
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000238uint32_t MachOLinkingContext::getCPUType() const {
239 return cpuTypeFromArch(_arch);
240}
241
242uint32_t MachOLinkingContext::getCPUSubType() const {
243 return cpuSubtypeFromArch(_arch);
244}
245
Nick Kledzike34182f2013-11-06 21:36:55 +0000246bool MachOLinkingContext::is64Bit(Arch arch) {
247 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
248 if (info->arch == arch) {
249 return (info->cputype & CPU_ARCH_ABI64);
250 }
251 }
252 // unknown archs are not 64-bit.
253 return false;
254}
255
256bool MachOLinkingContext::isHostEndian(Arch arch) {
257 assert(arch != arch_unknown);
258 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
259 if (info->arch == arch) {
260 return (info->littleEndian == llvm::sys::IsLittleEndianHost);
261 }
262 }
263 llvm_unreachable("Unknown arch type");
264}
265
266bool MachOLinkingContext::isBigEndian(Arch arch) {
267 assert(arch != arch_unknown);
268 for (ArchInfo *info = _s_archInfos; !info->archName.empty(); ++info) {
269 if (info->arch == arch) {
270 return ! info->littleEndian;
271 }
272 }
273 llvm_unreachable("Unknown arch type");
274}
275
276
277
278bool MachOLinkingContext::is64Bit() const {
279 return is64Bit(_arch);
280}
281
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000282bool MachOLinkingContext::outputTypeHasEntry() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000283 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000284 case MH_EXECUTE:
285 case MH_DYLINKER:
286 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000287 return true;
288 default:
289 return false;
290 }
291}
292
Nick Kledzik2458bec2014-07-16 19:49:02 +0000293bool MachOLinkingContext::needsStubsPass() const {
294 switch (_outputMachOType) {
295 case MH_EXECUTE:
296 return !_outputMachOTypeStatic;
297 case MH_DYLIB:
298 case MH_BUNDLE:
299 return true;
300 default:
301 return false;
302 }
303}
304
305bool MachOLinkingContext::needsGOTPass() const {
Nick Kledzik1bebb282014-09-09 23:52:59 +0000306 // GOT pass not used in -r mode.
307 if (_outputMachOType == MH_OBJECT)
Nick Kledzik2458bec2014-07-16 19:49:02 +0000308 return false;
Nick Kledzik1bebb282014-09-09 23:52:59 +0000309 // Only some arches use GOT pass.
310 switch (_arch) {
311 case arch_x86_64:
312 case arch_arm64:
313 return true;
314 default:
315 return false;
316 }
Nick Kledzik2458bec2014-07-16 19:49:02 +0000317}
318
Tim Northovercf78d372014-09-30 21:29:54 +0000319bool MachOLinkingContext::needsCompactUnwindPass() const {
320 switch (_outputMachOType) {
321 case MH_EXECUTE:
322 case MH_DYLIB:
323 case MH_BUNDLE:
324 return archHandler().needsCompactUnwind();
325 default:
326 return false;
327 }
328}
Nick Kledzik2458bec2014-07-16 19:49:02 +0000329
Nick Kledzik4121bce2014-10-14 01:51:42 +0000330bool MachOLinkingContext::needsShimPass() const {
331 // Shim pass only used in final executables.
332 if (_outputMachOType == MH_OBJECT)
333 return false;
334 // Only 32-bit arm arches use Shim pass.
335 switch (_arch) {
336 case arch_armv6:
337 case arch_armv7:
338 case arch_armv7s:
339 return true;
340 default:
341 return false;
342 }
343}
344
Lang Hames49047032015-06-23 20:35:31 +0000345bool MachOLinkingContext::needsTLVPass() const {
346 switch (_outputMachOType) {
347 case MH_BUNDLE:
348 case MH_EXECUTE:
349 case MH_DYLIB:
350 return true;
351 default:
352 return false;
353 }
354}
355
Nick Kledzik2458bec2014-07-16 19:49:02 +0000356StringRef MachOLinkingContext::binderSymbolName() const {
357 return archHandler().stubInfo().binderSymbolName;
358}
359
360
361
362
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000363bool MachOLinkingContext::minOS(StringRef mac, StringRef iOS) const {
Nick Kledzik30332b12013-10-08 00:43:34 +0000364 uint32_t parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000365 switch (_os) {
Nick Kledzik30332b12013-10-08 00:43:34 +0000366 case OS::macOSX:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000367 if (parsePackedVersion(mac, parsedVersion))
368 return false;
369 return _osMinVersion >= parsedVersion;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000370 case OS::iOS:
Nick Kledzik30332b12013-10-08 00:43:34 +0000371 case OS::iOS_simulator:
Nick Kledzike850d9d2013-09-10 23:46:57 +0000372 if (parsePackedVersion(iOS, parsedVersion))
373 return false;
374 return _osMinVersion >= parsedVersion;
Nick Kledzik30332b12013-10-08 00:43:34 +0000375 case OS::unknown:
376 break;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000377 }
378 llvm_unreachable("target not configured for iOS or MacOSX");
379}
380
381bool MachOLinkingContext::addEntryPointLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000382 if ((_outputMachOType == MH_EXECUTE) && !_outputMachOTypeStatic) {
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000383 return minOS("10.8", "6.0");
384 }
385 return false;
386}
387
388bool MachOLinkingContext::addUnixThreadLoadCommand() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000389 switch (_outputMachOType) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000390 case MH_EXECUTE:
Tim Northoverd30a1f22014-06-20 15:59:00 +0000391 if (_outputMachOTypeStatic)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000392 return true;
393 else
394 return !minOS("10.8", "6.0");
395 break;
Nick Kledzike34182f2013-11-06 21:36:55 +0000396 case MH_DYLINKER:
397 case MH_PRELOAD:
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000398 return true;
399 default:
400 return false;
401 }
402}
403
Tim Northover77d82202014-07-10 11:21:06 +0000404bool MachOLinkingContext::pathExists(StringRef path) const {
Nick Kledzik94174f72014-08-15 19:53:41 +0000405 if (!_testingFileUsage)
Tim Northover77d82202014-07-10 11:21:06 +0000406 return llvm::sys::fs::exists(path.str());
407
408 // Otherwise, we're in test mode: only files explicitly provided on the
409 // command-line exist.
Rui Ueyama57a29532014-08-06 19:37:35 +0000410 std::string key = path.str();
411 std::replace(key.begin(), key.end(), '\\', '/');
412 return _existingPaths.find(key) != _existingPaths.end();
Tim Northover77d82202014-07-10 11:21:06 +0000413}
414
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000415bool MachOLinkingContext::fileExists(StringRef path) const {
416 bool found = pathExists(path);
417 // Log search misses.
418 if (!found)
419 addInputFileNotFound(path);
420
421 // When testing, file is never opened, so logging is done here.
422 if (_testingFileUsage && found)
423 addInputFileDependency(path);
424
425 return found;
426}
427
Nick Kledzik2d835da2014-08-14 22:20:41 +0000428void MachOLinkingContext::setSysLibRoots(const StringRefVector &paths) {
429 _syslibRoots = paths;
430}
431
Jean-Daniel Dupas23dd15e2014-12-18 21:33:38 +0000432void MachOLinkingContext::addRpath(StringRef rpath) {
433 _rpaths.push_back(rpath);
434}
435
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000436void MachOLinkingContext::addModifiedSearchDir(StringRef libPath,
437 bool isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000438 bool addedModifiedPath = false;
439
Nick Kledzik2d835da2014-08-14 22:20:41 +0000440 // -syslibroot only applies to absolute paths.
441 if (libPath.startswith("/")) {
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000442 for (auto syslibRoot : _syslibRoots) {
Tim Northover77d82202014-07-10 11:21:06 +0000443 SmallString<256> path(syslibRoot);
444 llvm::sys::path::append(path, libPath);
445 if (pathExists(path)) {
446 _searchDirs.push_back(path.str().copy(_allocator));
447 addedModifiedPath = true;
448 }
449 }
450 }
451
452 if (addedModifiedPath)
453 return;
454
455 // Finally, if only one -syslibroot is given, system paths which aren't in it
456 // get suppressed.
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000457 if (_syslibRoots.size() != 1 || !isSystemPath) {
Tim Northover77d82202014-07-10 11:21:06 +0000458 if (pathExists(libPath)) {
459 _searchDirs.push_back(libPath);
460 }
461 }
462}
463
Nick Kledzik2d835da2014-08-14 22:20:41 +0000464void MachOLinkingContext::addFrameworkSearchDir(StringRef fwPath,
465 bool isSystemPath) {
466 bool pathAdded = false;
467
468 // -syslibroot only used with to absolute framework search paths.
469 if (fwPath.startswith("/")) {
470 for (auto syslibRoot : _syslibRoots) {
471 SmallString<256> path(syslibRoot);
472 llvm::sys::path::append(path, fwPath);
473 if (pathExists(path)) {
474 _frameworkDirs.push_back(path.str().copy(_allocator));
475 pathAdded = true;
476 }
477 }
478 }
479 // If fwPath found in any -syslibroot, then done.
480 if (pathAdded)
481 return;
482
483 // If only one -syslibroot, system paths not in that SDK are suppressed.
484 if (isSystemPath && (_syslibRoots.size() == 1))
485 return;
486
487 // Only use raw fwPath if that directory exists.
488 if (pathExists(fwPath))
489 _frameworkDirs.push_back(fwPath);
490}
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
521
522
523ErrorOr<StringRef> MachOLinkingContext::searchLibrary(StringRef libName) const {
524 SmallString<256> path;
525 for (StringRef dir : searchDirs()) {
526 ErrorOr<StringRef> ec = searchDirForLibrary(dir, libName);
527 if (ec)
528 return ec;
529 }
530
531 return make_error_code(llvm::errc::no_such_file_or_directory);
532}
533
Nick Kledzik2d835da2014-08-14 22:20:41 +0000534
535ErrorOr<StringRef> MachOLinkingContext::findPathForFramework(StringRef fwName) const{
536 SmallString<256> fullPath;
537 for (StringRef dir : frameworkDirs()) {
538 fullPath.assign(dir);
539 llvm::sys::path::append(fullPath, Twine(fwName) + ".framework", fwName);
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000540 if (fileExists(fullPath))
Nick Kledzik2d835da2014-08-14 22:20:41 +0000541 return fullPath.str().copy(_allocator);
542 }
543
544 return make_error_code(llvm::errc::no_such_file_or_directory);
545}
546
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000547bool MachOLinkingContext::validateImpl(raw_ostream &diagnostics) {
Nick Kledzike34182f2013-11-06 21:36:55 +0000548 // TODO: if -arch not specified, look at arch of first .o file.
549
Tim Northoverd30a1f22014-06-20 15:59:00 +0000550 if (_currentVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000551 diagnostics << "error: -current_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000552 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000553 }
554
Tim Northoverd30a1f22014-06-20 15:59:00 +0000555 if (_compatibilityVersion && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000556 diagnostics
557 << "error: -compatibility_version can only be used with dylibs\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000558 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000559 }
560
Tim Northoverd30a1f22014-06-20 15:59:00 +0000561 if (_deadStrippableDylib && _outputMachOType != MH_DYLIB) {
Nick Kledzike773e322013-09-10 23:55:14 +0000562 diagnostics
563 << "error: -mark_dead_strippable_dylib can only be used with dylibs.\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000564 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000565 }
566
Tim Northoverd30a1f22014-06-20 15:59:00 +0000567 if (!_bundleLoader.empty() && outputMachOType() != MH_BUNDLE) {
Nick Kledzike773e322013-09-10 23:55:14 +0000568 diagnostics
569 << "error: -bundle_loader can only be used with Mach-O bundles\n";
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000570 return false;
Nick Kledzike773e322013-09-10 23:55:14 +0000571 }
572
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000573 // If -exported_symbols_list used, all exported symbols must be defined.
574 if (_exportMode == ExportMode::whiteList) {
575 for (const auto &symbol : _exportedSymbols)
576 addInitialUndefinedSymbol(symbol.getKey());
577 }
578
Nick Kledzik77afc712014-08-21 20:25:50 +0000579 // If -dead_strip, set up initial live symbols.
580 if (deadStrip()) {
581 // Entry point is live.
582 if (outputTypeHasEntry())
583 addDeadStripRoot(entrySymbolName());
584 // Lazy binding helper is live.
585 if (needsStubsPass())
586 addDeadStripRoot(binderSymbolName());
587 // If using -exported_symbols_list, make all exported symbols live.
588 if (_exportMode == ExportMode::whiteList) {
Davide Italiano7b68b902015-03-09 06:05:42 +0000589 setGlobalsAreDeadStripRoots(false);
Nick Kledzik77afc712014-08-21 20:25:50 +0000590 for (const auto &symbol : _exportedSymbols)
591 addDeadStripRoot(symbol.getKey());
592 }
593 }
594
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000595 addOutputFileDependency(outputPath());
596
Rui Ueyama8db1edd2013-09-24 23:26:34 +0000597 return true;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000598}
599
Shankar Easwaran2bc24922013-10-29 05:12:14 +0000600void MachOLinkingContext::addPasses(PassManager &pm) {
Rui Ueyama00762152015-02-05 20:05:33 +0000601 mach_o::addLayoutPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000602 if (needsStubsPass())
603 mach_o::addStubsPass(pm, *this);
Tim Northovercf78d372014-09-30 21:29:54 +0000604 if (needsCompactUnwindPass())
605 mach_o::addCompactUnwindPass(pm, *this);
Nick Kledzik2458bec2014-07-16 19:49:02 +0000606 if (needsGOTPass())
607 mach_o::addGOTPass(pm, *this);
Lang Hames49047032015-06-23 20:35:31 +0000608 if (needsTLVPass())
609 mach_o::addTLVPass(pm, *this);
Nick Kledzik4121bce2014-10-14 01:51:42 +0000610 if (needsShimPass())
611 mach_o::addShimPass(pm, *this); // Shim pass must run after stubs pass.
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000612}
613
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000614Writer &MachOLinkingContext::writer() const {
Tim Northoverd30a1f22014-06-20 15:59:00 +0000615 if (!_writer)
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000616 _writer = createWriterMachO(*this);
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000617 return *_writer;
618}
619
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000620ErrorOr<std::unique_ptr<MemoryBuffer>>
621MachOLinkingContext::getMemoryBuffer(StringRef path) {
622 addInputFileDependency(path);
623
Rui Ueyamadf230b22015-01-15 04:34:31 +0000624 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr =
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000625 MemoryBuffer::getFileOrSTDIN(path);
626 if (std::error_code ec = mbOrErr.getError())
627 return ec;
628 std::unique_ptr<MemoryBuffer> mb = std::move(mbOrErr.get());
629
630 // If buffer contains a fat file, find required arch in fat buffer
631 // and switch buffer to point to just that required slice.
632 uint32_t offset;
633 uint32_t size;
Rafael Espindolaed48e532015-04-27 22:48:51 +0000634 if (sliceFromFatFile(mb->getMemBufferRef(), offset, size))
Greg Fitzgeraldb4eb64e2015-01-23 23:26:13 +0000635 return MemoryBuffer::getFileSlice(path, size, offset);
636 return std::move(mb);
637}
638
639MachODylibFile* MachOLinkingContext::loadIndirectDylib(StringRef path) {
640 ErrorOr<std::unique_ptr<MemoryBuffer>> mbOrErr = getMemoryBuffer(path);
Rui Ueyamadf230b22015-01-15 04:34:31 +0000641 if (mbOrErr.getError())
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000642 return nullptr;
643
Rafael Espindolaab5696b2015-04-24 18:51:30 +0000644 ErrorOr<std::unique_ptr<File>> fileOrErr =
645 registry().loadFile(std::move(mbOrErr.get()));
646 if (!fileOrErr)
Rui Ueyamadf230b22015-01-15 04:34:31 +0000647 return nullptr;
Rafael Espindola773a1592015-04-24 19:01:30 +0000648 std::unique_ptr<File> &file = fileOrErr.get();
649 file->parse();
650 MachODylibFile *result = reinterpret_cast<MachODylibFile *>(file.get());
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000651 // Node object now owned by _indirectDylibs vector.
Rafael Espindola773a1592015-04-24 19:01:30 +0000652 _indirectDylibs.push_back(std::move(file));
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000653 return result;
654}
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
731
Nick Kledzik51720672014-10-16 19:31:28 +0000732void MachOLinkingContext::registerDylib(MachODylibFile *dylib,
733 bool upward) const {
Lang Hames9bbc3652015-05-13 00:17:08 +0000734 std::lock_guard<std::mutex> lock(_dylibsMutex);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000735 _allDylibs.insert(dylib);
736 _pathToDylibMap[dylib->installName()] = dylib;
737 // If path is different than install name, register path too.
738 if (!dylib->path().equals(dylib->installName()))
739 _pathToDylibMap[dylib->path()] = dylib;
Nick Kledzik51720672014-10-16 19:31:28 +0000740 if (upward)
741 _upwardDylibs.insert(dylib);
Nick Kledzik8fc67fb2014-08-13 23:55:41 +0000742}
743
744
Nick Kledzik51720672014-10-16 19:31:28 +0000745bool MachOLinkingContext::isUpwardDylib(StringRef installName) const {
746 for (MachODylibFile *dylib : _upwardDylibs) {
747 if (dylib->installName().equals(installName))
748 return true;
749 }
750 return false;
751}
752
Nick Kledzik2458bec2014-07-16 19:49:02 +0000753ArchHandler &MachOLinkingContext::archHandler() const {
754 if (!_archHandler)
755 _archHandler = ArchHandler::create(_arch);
756 return *_archHandler;
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000757}
758
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000759
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000760void MachOLinkingContext::addSectionAlignment(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000761 uint16_t align) {
762 SectionAlign entry = { seg, sect, align };
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000763 _sectAligns.push_back(entry);
764}
765
766bool MachOLinkingContext::sectionAligned(StringRef seg, StringRef sect,
Rui Ueyamada74d572015-03-26 02:23:45 +0000767 uint16_t &align) const {
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000768 for (const SectionAlign &entry : _sectAligns) {
769 if (seg.equals(entry.segmentName) && sect.equals(entry.sectionName)) {
Rui Ueyamada74d572015-03-26 02:23:45 +0000770 align = entry.align;
Nick Kledzik2fcbe822014-07-30 00:58:06 +0000771 return true;
772 }
773 }
774 return false;
775}
776
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000777
778void MachOLinkingContext::addExportSymbol(StringRef sym) {
Nick Kledzik4183dbc2014-10-24 22:28:54 +0000779 // Support old crufty export lists with bogus entries.
780 if (sym.endswith(".eh") || sym.startswith(".objc_category_name_")) {
781 llvm::errs() << "warning: ignoring " << sym << " in export list\n";
782 return;
783 }
784 // Only i386 MacOSX uses old ABI, so don't change those.
785 if ((_os != OS::macOSX) || (_arch != arch_x86)) {
786 // ObjC has two differnent ABIs. Be nice and allow one export list work for
787 // both ABIs by renaming symbols.
788 if (sym.startswith(".objc_class_name_")) {
789 std::string abi2className("_OBJC_CLASS_$_");
790 abi2className += sym.substr(17);
791 _exportedSymbols.insert(copy(abi2className));
792 std::string abi2metaclassName("_OBJC_METACLASS_$_");
793 abi2metaclassName += sym.substr(17);
794 _exportedSymbols.insert(copy(abi2metaclassName));
795 return;
796 }
797 }
798
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000799 // FIXME: Support wildcards.
800 _exportedSymbols.insert(sym);
801}
802
803bool MachOLinkingContext::exportSymbolNamed(StringRef sym) const {
804 switch (_exportMode) {
805 case ExportMode::globals:
806 llvm_unreachable("exportSymbolNamed() should not be called in this mode");
807 break;
808 case ExportMode::whiteList:
809 return _exportedSymbols.count(sym);
810 case ExportMode::blackList:
811 return !_exportedSymbols.count(sym);
812 }
Yaron Keren9682c852014-09-21 05:07:44 +0000813 llvm_unreachable("_exportMode unknown enum value");
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000814}
815
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000816std::string MachOLinkingContext::demangle(StringRef symbolName) const {
817 // Only try to demangle symbols if -demangle on command line
Davide Italiano6d86bb22015-02-18 03:54:21 +0000818 if (!demangleSymbols())
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000819 return symbolName;
820
821 // Only try to demangle symbols that look like C++ symbols
822 if (!symbolName.startswith("__Z"))
823 return symbolName;
824
Rui Ueyamafccf7ef2014-10-27 07:44:40 +0000825#if defined(HAVE_CXXABI_H)
Nick Kledzikbe43d7e2014-09-30 23:15:39 +0000826 SmallString<256> symBuff;
827 StringRef nullTermSym = Twine(symbolName).toNullTerminatedStringRef(symBuff);
828 // Mach-O has extra leading underscore that needs to be removed.
829 const char *cstr = nullTermSym.data() + 1;
830 int status;
831 char *demangled = abi::__cxa_demangle(cstr, nullptr, nullptr, &status);
832 if (demangled != NULL) {
833 std::string result(demangled);
834 // __cxa_demangle() always uses a malloc'ed buffer to return the result.
835 free(demangled);
836 return result;
837 }
838#endif
839
840 return symbolName;
841}
842
Nick Kledzik09d00bb2014-10-04 00:16:13 +0000843std::error_code MachOLinkingContext::createDependencyFile(StringRef path) {
844 std::error_code ec;
845 _dependencyInfo = std::unique_ptr<llvm::raw_fd_ostream>(new
846 llvm::raw_fd_ostream(path, ec, llvm::sys::fs::F_None));
847 if (ec) {
848 _dependencyInfo.reset();
849 return ec;
850 }
851
852 char linkerVersionOpcode = 0x00;
853 *_dependencyInfo << linkerVersionOpcode;
854 *_dependencyInfo << "lld"; // FIXME
855 *_dependencyInfo << '\0';
856
857 return std::error_code();
858}
859
860void MachOLinkingContext::addInputFileDependency(StringRef path) const {
861 if (!_dependencyInfo)
862 return;
863
864 char inputFileOpcode = 0x10;
865 *_dependencyInfo << inputFileOpcode;
866 *_dependencyInfo << path;
867 *_dependencyInfo << '\0';
868}
869
870void MachOLinkingContext::addInputFileNotFound(StringRef path) const {
871 if (!_dependencyInfo)
872 return;
873
874 char inputFileOpcode = 0x11;
875 *_dependencyInfo << inputFileOpcode;
876 *_dependencyInfo << path;
877 *_dependencyInfo << '\0';
878}
879
880void MachOLinkingContext::addOutputFileDependency(StringRef path) const {
881 if (!_dependencyInfo)
882 return;
883
884 char outputFileOpcode = 0x40;
885 *_dependencyInfo << outputFileOpcode;
886 *_dependencyInfo << path;
887 *_dependencyInfo << '\0';
888}
889
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000890void MachOLinkingContext::appendOrderedSymbol(StringRef symbol,
891 StringRef filename) {
892 // To support sorting static functions which may have the same name in
893 // multiple .o files, _orderFiles maps the symbol name to a vector
894 // of OrderFileNode each of which can specify a file prefix.
895 OrderFileNode info;
896 if (!filename.empty())
897 info.fileFilter = copy(filename);
898 info.order = _orderFileEntries++;
899 _orderFiles[symbol].push_back(info);
900}
901
902bool
903MachOLinkingContext::findOrderOrdinal(const std::vector<OrderFileNode> &nodes,
904 const DefinedAtom *atom,
905 unsigned &ordinal) {
906 const File *objFile = &atom->file();
907 assert(objFile);
908 StringRef objName = objFile->path();
909 std::pair<StringRef, StringRef> dirAndLeaf = objName.rsplit('/');
910 if (!dirAndLeaf.second.empty())
911 objName = dirAndLeaf.second;
912 for (const OrderFileNode &info : nodes) {
913 if (info.fileFilter.empty()) {
914 // Have unprefixed symbol name in order file that matches this atom.
915 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000916 return true;
917 }
918 if (info.fileFilter.equals(objName)) {
919 // Have prefixed symbol name in order file that matches atom's path.
920 ordinal = info.order;
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000921 return true;
922 }
923 }
924 return false;
925}
926
927bool MachOLinkingContext::customAtomOrderer(const DefinedAtom *left,
928 const DefinedAtom *right,
Rui Ueyama00762152015-02-05 20:05:33 +0000929 bool &leftBeforeRight) const {
Nick Kledzik82d24bc2014-11-07 21:01:21 +0000930 // No custom sorting if no order file entries.
931 if (!_orderFileEntries)
932 return false;
933
934 // Order files can only order named atoms.
935 StringRef leftName = left->name();
936 StringRef rightName = right->name();
937 if (leftName.empty() || rightName.empty())
938 return false;
939
940 // If neither is in order file list, no custom sorter.
941 auto leftPos = _orderFiles.find(leftName);
942 auto rightPos = _orderFiles.find(rightName);
943 bool leftIsOrdered = (leftPos != _orderFiles.end());
944 bool rightIsOrdered = (rightPos != _orderFiles.end());
945 if (!leftIsOrdered && !rightIsOrdered)
946 return false;
947
948 // There could be multiple symbols with same name but different file prefixes.
949 unsigned leftOrder;
950 unsigned rightOrder;
951 bool foundLeft =
952 leftIsOrdered && findOrderOrdinal(leftPos->getValue(), left, leftOrder);
953 bool foundRight = rightIsOrdered &&
954 findOrderOrdinal(rightPos->getValue(), right, rightOrder);
955 if (!foundLeft && !foundRight)
956 return false;
957
958 // If only one is in order file list, ordered one goes first.
959 if (foundLeft != foundRight)
960 leftBeforeRight = foundLeft;
961 else
962 leftBeforeRight = (leftOrder < rightOrder);
963
964 return true;
965}
Nick Kledzik8c0bf752014-08-21 01:59:11 +0000966
Rui Ueyama61635442015-01-15 08:31:46 +0000967static bool isLibrary(const std::unique_ptr<Node> &elem) {
Rui Ueyamaae1daae2015-01-15 08:51:23 +0000968 if (FileNode *node = dyn_cast<FileNode>(const_cast<Node *>(elem.get()))) {
969 File *file = node->getFile();
970 return isa<SharedLibraryFile>(file) || isa<ArchiveLibraryFile>(file);
971 }
972 return false;
Rui Ueyama00eb2572014-12-10 00:33:00 +0000973}
974
975// The darwin linker processes input files in two phases. The first phase
976// links in all object (.o) files in command line order. The second phase
977// links in libraries in command line order.
978// In this function we reorder the input files so that all the object files
979// comes before any library file. We also make a group for the library files
980// so that the Resolver will reiterate over the libraries as long as we find
981// new undefines from libraries.
Denis Protivenskycd617152015-03-14 10:34:43 +0000982void MachOLinkingContext::finalizeInputFiles() {
Rui Ueyama883afba2015-01-15 08:46:36 +0000983 std::vector<std::unique_ptr<Node>> &elements = getNodes();
Rui Ueyama00eb2572014-12-10 00:33:00 +0000984 std::stable_sort(elements.begin(), elements.end(),
Rui Ueyama61635442015-01-15 08:31:46 +0000985 [](const std::unique_ptr<Node> &a,
986 const std::unique_ptr<Node> &b) {
Rui Ueyama00eb2572014-12-10 00:33:00 +0000987 return !isLibrary(a) && isLibrary(b);
988 });
989 size_t numLibs = std::count_if(elements.begin(), elements.end(), isLibrary);
990 elements.push_back(llvm::make_unique<GroupEnd>(numLibs));
991}
992
Rui Ueyama0ca149f2013-08-06 22:31:59 +0000993} // end namespace lld