]> git.saurik.com Git - apple/ld64.git/blob - src/ld/passes/stubs/stubs.cpp
bee5f2f67c4f3f2432c4c4a8b8eb91a7525818e3
[apple/ld64.git] / src / ld / passes / stubs / stubs.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2009-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
7 * This file contains Original Code and/or Modifications of Original Code
8 * as defined in and that are subject to the Apple Public Source License
9 * Version 2.0 (the 'License'). You may not use this file except in
10 * compliance with the License. Please obtain a copy of the License at
11 * http://www.opensource.apple.com/apsl/ and read it before using this
12 * file.
13 *
14 * The Original Code and all software distributed under the License are
15 * distributed on an 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER
16 * EXPRESS OR IMPLIED, AND APPLE HEREBY DISCLAIMS ALL SUCH WARRANTIES,
17 * INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE, QUIET ENJOYMENT OR NON-INFRINGEMENT.
19 * Please see the License for the specific language governing rights and
20 * limitations under the License.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25
26
27 #include <stdint.h>
28 #include <math.h>
29 #include <unistd.h>
30 #include <assert.h>
31 #include <libkern/OSByteOrder.h>
32
33 #include <vector>
34 #include <set>
35 #include <map>
36
37 #include "Options.h"
38 #include "MachOFileAbstraction.hpp"
39 #include "ld.hpp"
40
41 #include "make_stubs.h"
42
43
44 namespace ld {
45 namespace passes {
46 namespace stubs {
47
48 class Pass {
49 public:
50 Pass(const Options& opts);
51 void process(ld::Internal& internal);
52 void addAtom(const ld::Atom& atom) { _internal->addAtom(atom); }
53 bool usingCompressedLINKEDIT() const { return _compressedLINKEDIT; }
54 ld::Internal* internal() { return _internal; }
55
56 Atom* compressedHelperHelper;
57 Atom* compressedImageCache;
58 Atom* compressedFastBinderPointer;
59
60 private:
61
62 struct AtomByNameSorter
63 {
64 bool operator()(const ld::Atom* left, const ld::Atom* right)
65 {
66 return (strcmp(left->name(), right->name()) < 0);
67 }
68 };
69
70 const ld::Atom* stubableFixup(const ld::Fixup* fixup, ld::Internal&);
71 ld::Atom* makeStub(const ld::Atom& target, bool weakImport);
72 void verifyNoResolverFunctions(ld::Internal& state);
73
74 const Options& _options;
75 const cpu_type_t _architecture;
76 const bool _lazyDylibsInUuse;
77 const bool _compressedLINKEDIT;
78 const bool _prebind;
79 const bool _mightBeInSharedRegion;
80 const bool _pic;
81 const bool _flatNamespace;
82 ld::Internal* _internal;
83 uint32_t _stubCount;
84 bool _largeText;
85 };
86
87 #include "stub_x86_64.hpp"
88 #include "stub_x86_64_classic.hpp"
89 #include "stub_x86.hpp"
90 #include "stub_x86_classic.hpp"
91 #include "stub_arm.hpp"
92 #include "stub_arm_classic.hpp"
93 #if SUPPORT_ARCH_arm64
94 #include "stub_arm64.hpp"
95 #endif
96
97 Pass::Pass(const Options& opts)
98 : compressedHelperHelper(NULL),
99 compressedImageCache(NULL),
100 compressedFastBinderPointer(NULL),
101 _options(opts),
102 _architecture(opts.architecture()),
103 _lazyDylibsInUuse(opts.usingLazyDylibLinking()),
104 _compressedLINKEDIT(opts.makeCompressedDyldInfo()),
105 _prebind(opts.prebind()),
106 _mightBeInSharedRegion(opts.sharedRegionEligible()),
107 _pic(opts.outputSlidable()),
108 _flatNamespace(opts.nameSpace() != Options::kTwoLevelNameSpace),
109 _internal(NULL), _stubCount(0), _largeText(false)
110 {
111
112 }
113
114
115 const ld::Atom* Pass::stubableFixup(const ld::Fixup* fixup, ld::Internal& state)
116 {
117 if ( fixup->binding == ld::Fixup::bindingsIndirectlyBound ) {
118 const ld::Atom* target = state.indirectBindingTable[fixup->u.bindingIndex];
119 switch ( fixup->kind ) {
120 case ld::Fixup::kindStoreTargetAddressX86BranchPCRel32:
121 case ld::Fixup::kindStoreTargetAddressARMBranch24:
122 case ld::Fixup::kindStoreTargetAddressThumbBranch22:
123 #if SUPPORT_ARCH_arm64
124 case ld::Fixup::kindStoreTargetAddressARM64Branch26:
125 #endif
126 assert(target != NULL);
127 // create stub if target is in a dylib
128 if ( target->definition() == ld::Atom::definitionProxy )
129 return target;
130 // use stub if target is a resolver function in same linkage unit
131 if ( target->contentType() == ld::Atom::typeResolver )
132 return target;
133 if ( target->scope() == ld::Atom::scopeGlobal ) {
134 // create stub if target is global weak definition in symbol table
135 if ( (target->definition() == ld::Atom::definitionRegular)
136 && (target->combine() == ld::Atom::combineByName)
137 && ((target->symbolTableInclusion() == ld::Atom::symbolTableIn)
138 || (target->symbolTableInclusion() == ld::Atom::symbolTableInAndNeverStrip)) )
139 return target;
140 // create stub if target is interposable
141 if ( _options.interposable(target->name()) )
142 return target;
143 if ( _flatNamespace ) {
144 // flat namespace does not indirect calls within main exectuables
145 if ( _options.outputKind() == Options::kDynamicExecutable )
146 return NULL;
147 // create stub if target is global and building -flat dylib or bundle
148 return target;
149 }
150 }
151 break;
152 default:
153 if ( target->contentType() == ld::Atom::typeResolver ) {
154 // any pointer to a resolver needs to change to pointer to stub
155 return target;
156 }
157 break;
158 }
159 }
160 return NULL;
161 }
162
163
164
165 ld::Atom* Pass::makeStub(const ld::Atom& target, bool weakImport)
166 {
167 //fprintf(stderr, "makeStub(target=%p %s in sect %s, def=%d)\n", &target, target.name(), target.section().sectionName(), target.definition());
168 bool stubToGlobalWeakDef = ( (target.combine() == ld::Atom::combineByName) &&
169 (((target.definition() == ld::Atom::definitionRegular) && (target.scope() == ld::Atom::scopeGlobal))
170 || (target.definition() == ld::Atom::definitionProxy)) );
171
172 bool forLazyDylib = false;
173 const ld::dylib::File* dylib = dynamic_cast<const ld::dylib::File*>(target.file());
174 if ( (dylib != NULL) && dylib->willBeLazyLoadedDylib() )
175 forLazyDylib = true;
176 bool stubToResolver = (target.contentType() == ld::Atom::typeResolver);
177 bool usingDataConst = _options.useDataConstSegment();
178
179 if ( usingCompressedLINKEDIT() && !forLazyDylib ) {
180 if ( _internal->compressedFastBinderProxy == NULL )
181 throwf("symbol dyld_stub_binder not found (normally in libSystem.dylib). Needed to perform lazy binding to function %s", target.name());
182 }
183
184 switch ( _architecture ) {
185 #if SUPPORT_ARCH_i386
186 case CPU_TYPE_I386:
187 if ( usingCompressedLINKEDIT() && !forLazyDylib )
188 return new ld::passes::stubs::x86::StubAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
189 else
190 return new ld::passes::stubs::x86::classic::StubAtom(*this, target, forLazyDylib, weakImport);
191 break;
192 #endif
193 #if SUPPORT_ARCH_x86_64
194 case CPU_TYPE_X86_64:
195 if ( (_options.outputKind() == Options::kKextBundle) && _options.kextsUseStubs() )
196 return new ld::passes::stubs::x86_64::KextStubAtom(*this, target);
197 else if ( usingCompressedLINKEDIT() && !forLazyDylib )
198 return new ld::passes::stubs::x86_64::StubAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
199 else
200 return new ld::passes::stubs::x86_64::classic::StubAtom(*this, target, forLazyDylib, weakImport);
201 break;
202 #endif
203 #if SUPPORT_ARCH_arm_any
204 case CPU_TYPE_ARM:
205 if ( (_options.outputKind() == Options::kKextBundle) && _options.kextsUseStubs() ) {
206 // if text relocs are not allows in kext bundles, then linker must create a stub
207 return new ld::passes::stubs::arm::StubPICKextAtom(*this, target);
208 }
209 else if ( usingCompressedLINKEDIT() && !forLazyDylib ) {
210 if ( (_stubCount < 900) && !_mightBeInSharedRegion && !_largeText )
211 return new ld::passes::stubs::arm::StubCloseAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
212 else if ( _pic )
213 return new ld::passes::stubs::arm::StubPICAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport, usingDataConst);
214 else
215 return new ld::passes::stubs::arm::StubNoPICAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
216 }
217 else {
218 if ( _pic )
219 return new ld::passes::stubs::arm::classic::StubPICAtom(*this, target, forLazyDylib, weakImport);
220 else
221 return new ld::passes::stubs::arm::classic::StubNoPICAtom(*this, target, forLazyDylib, weakImport);
222 }
223 break;
224 #endif
225 #if SUPPORT_ARCH_arm64
226 case CPU_TYPE_ARM64:
227 if ( (_options.outputKind() == Options::kKextBundle) && _options.kextsUseStubs() )
228 return new ld::passes::stubs::arm64::KextStubAtom(*this, target);
229 else
230 return new ld::passes::stubs::arm64::StubAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport, usingDataConst);
231 break;
232 #endif
233 }
234 throw "unsupported arch for stub";
235 }
236
237
238 void Pass::verifyNoResolverFunctions(ld::Internal& state)
239 {
240 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
241 ld::Internal::FinalSection* sect = *sit;
242 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
243 const ld::Atom* atom = *ait;
244 if ( atom->contentType() == ld::Atom::typeResolver )
245 throwf("resolver function '%s' not supported in type of output", atom->name());
246 }
247 }
248 }
249
250 void Pass::process(ld::Internal& state)
251 {
252 switch ( _options.outputKind() ) {
253 case Options::kObjectFile:
254 // these kinds don't use stubs and can have resolver functions
255 return;
256 case Options::kStaticExecutable:
257 case Options::kPreload:
258 case Options::kDyld:
259 // these kinds don't use stubs and cannot have resolver functions
260 verifyNoResolverFunctions(state);
261 return;
262 case Options::kDynamicLibrary:
263 // uses stubs and can have resolver functions
264 break;
265 case Options::kKextBundle:
266 verifyNoResolverFunctions(state);
267 // if kext don't use stubs, don't do this pass
268 if ( !_options.kextsUseStubs() )
269 return;
270 break;
271 case Options::kDynamicExecutable:
272 case Options::kDynamicBundle:
273 // these kinds do use stubs and cannot have resolver functions
274 verifyNoResolverFunctions(state);
275 break;
276 }
277
278 // walk all atoms and fixups looking for stubable references
279 // don't create stubs inline because that could invalidate the sections iterator
280 std::vector<const ld::Atom*> atomsCallingStubs;
281 std::map<const ld::Atom*,ld::Atom*> stubFor;
282 std::map<const ld::Atom*,bool> weakImportMap;
283 atomsCallingStubs.reserve(128);
284 uint64_t codeSize = 0;
285 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
286 ld::Internal::FinalSection* sect = *sit;
287 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
288 const ld::Atom* atom = *ait;
289 codeSize += atom->size();
290 bool atomNeedsStub = false;
291 for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) {
292 const ld::Atom* stubableTargetOfFixup = stubableFixup(fit, state);
293 if ( stubableTargetOfFixup != NULL ) {
294 if ( !atomNeedsStub ) {
295 atomsCallingStubs.push_back(atom);
296 atomNeedsStub = true;
297 }
298 stubFor[stubableTargetOfFixup] = NULL;
299 // record weak_import attribute
300 std::map<const ld::Atom*,bool>::iterator pos = weakImportMap.find(stubableTargetOfFixup);
301 if ( pos == weakImportMap.end() ) {
302 // target not in weakImportMap, so add
303 weakImportMap[stubableTargetOfFixup] = fit->weakImport;
304 }
305 else {
306 // target in weakImportMap, check for weakness mismatch
307 if ( pos->second != fit->weakImport ) {
308 // found mismatch
309 switch ( _options.weakReferenceMismatchTreatment() ) {
310 case Options::kWeakReferenceMismatchError:
311 throwf("mismatching weak references for symbol: %s", stubableTargetOfFixup->name());
312 case Options::kWeakReferenceMismatchWeak:
313 pos->second = true;
314 break;
315 case Options::kWeakReferenceMismatchNonWeak:
316 pos->second = false;
317 break;
318 }
319 }
320 }
321 }
322 }
323 // all resolver functions must have a corresponding stub
324 if ( atom->contentType() == ld::Atom::typeResolver ) {
325 if ( _options.outputKind() != Options::kDynamicLibrary )
326 throwf("resolver functions (%s) can only be used in dylibs", atom->name());
327 if ( !_options.makeCompressedDyldInfo() ) {
328 if ( _options.architecture() == CPU_TYPE_ARM )
329 throwf("resolver functions (%s) can only be used when targeting iOS 4.2 or later", atom->name());
330 else
331 throwf("resolver functions (%s) can only be used when targeting Mac OS X 10.6 or later", atom->name());
332 }
333 stubFor[atom] = NULL;
334 }
335 }
336 }
337
338 const bool needStubForMain = _options.needsEntryPointLoadCommand()
339 && (state.entryPoint != NULL)
340 && (state.entryPoint->definition() == ld::Atom::definitionProxy);
341 if ( needStubForMain ) {
342 // _main not found in any .o files. Currently have proxy to dylib
343 // Add to map, so that a stub will be made
344 stubFor[state.entryPoint] = NULL;
345 }
346
347 // short circuit if no stubs needed
348 _internal = &state;
349 _stubCount = stubFor.size();
350 if ( _stubCount == 0 )
351 return;
352
353 // <rdar://problem/8553283> lazily check for helper
354 if ( !_options.makeCompressedDyldInfo() && (state.classicBindingHelper == NULL) && (_options.outputKind() != Options::kKextBundle) )
355 throw "symbol dyld_stub_binding_helper not found, normally in crt1.o/dylib1.o/bundle1.o";
356
357 // disable arm close stubs in some cases
358 if ( _architecture == CPU_TYPE_ARM ) {
359 if ( codeSize > 4*1024*1024 )
360 _largeText = true;
361 else {
362 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
363 ld::Internal::FinalSection* sect = *sit;
364 if ( sect->type() == ld::Section::typeMachHeader )
365 continue;
366 if ( strcmp(sect->segmentName(), "__TEXT") == 0) {
367 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
368 const ld::Atom* atom = *ait;
369 if ( atom->alignment().powerOf2 > 10 ) {
370 // overaligned section means might not be able to keep closestubs sect pushed to end of __TEXT
371 //warning("alignment 1<<%d in atom %s in section %s disables close stubs optimization",
372 // atom->alignment().powerOf2, atom->name(), sect->segmentName());
373 _largeText = true;
374 break;
375 }
376 }
377 }
378 }
379 }
380 }
381
382 // make stub atoms
383 for (std::map<const ld::Atom*,ld::Atom*>::iterator it = stubFor.begin(); it != stubFor.end(); ++it) {
384 it->second = makeStub(*it->first, weakImportMap[it->first]);
385 }
386
387 // updated atoms to use stubs
388 for (std::vector<const ld::Atom*>::iterator it=atomsCallingStubs.begin(); it != atomsCallingStubs.end(); ++it) {
389 const ld::Atom* atom = *it;
390 for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) {
391 const ld::Atom* stubableTargetOfFixup = stubableFixup(fit, state);
392 if ( stubableTargetOfFixup != NULL ) {
393 ld::Atom* stub = stubFor[stubableTargetOfFixup];
394 assert(stub != NULL && "stub not created");
395 fit->binding = ld::Fixup::bindingDirectlyBound;
396 fit->u.target = stub;
397 }
398 }
399 }
400
401 // switch entry point from proxy to stub
402 if ( needStubForMain ) {
403 const ld::Atom* mainStub = stubFor[state.entryPoint];
404 assert(mainStub != NULL);
405 state.entryPoint = mainStub;
406 }
407
408 // sort new atoms so links are consistent
409 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
410 ld::Internal::FinalSection* sect = *sit;
411 switch ( sect->type() ) {
412 case ld::Section::typeStubHelper:
413 case ld::Section::typeStub:
414 case ld::Section::typeStubClose:
415 case ld::Section::typeLazyPointer:
416 case ld::Section::typeLazyPointerClose:
417 std::sort(sect->atoms.begin(), sect->atoms.end(), AtomByNameSorter());
418 break;
419 default:
420 break;
421 }
422 }
423
424 }
425
426
427 void doPass(const Options& opts, ld::Internal& internal)
428 {
429 Pass pass(opts);
430 pass.process(internal);
431 }
432
433
434
435 } // namespace stubs
436 } // namespace passes
437 } // namespace ld
438