]> git.saurik.com Git - apple/ld64.git/blob - src/ld/passes/stubs/stubs.cpp
274878bdc8ee9da4758c337c0726184da7b7b43b
[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 "ld.hpp"
39
40 #include "make_stubs.h"
41
42
43 namespace ld {
44 namespace passes {
45 namespace stubs {
46
47 class Pass {
48 public:
49 Pass(const Options& opts);
50 void process(ld::Internal& internal);
51 void addAtom(const ld::Atom& atom) { _internal->addAtom(atom); }
52 bool usingCompressedLINKEDIT() const { return _compressedLINKEDIT; }
53 ld::Internal* internal() { return _internal; }
54
55 Atom* compressedHelperHelper;
56 Atom* compressedImageCache;
57 Atom* compressedFastBinderPointer;
58
59 private:
60
61 struct AtomByNameSorter
62 {
63 bool operator()(const ld::Atom* left, const ld::Atom* right)
64 {
65 return (strcmp(left->name(), right->name()) < 0);
66 }
67 };
68
69 const ld::Atom* stubableFixup(const ld::Fixup* fixup, ld::Internal&);
70 ld::Atom* makeStub(const ld::Atom& target, bool weakImport);
71 void verifyNoResolverFunctions(ld::Internal& state);
72
73 const Options& _options;
74 const cpu_type_t _architecture;
75 const bool _lazyDylibsInUuse;
76 const bool _compressedLINKEDIT;
77 const bool _prebind;
78 const bool _mightBeInSharedRegion;
79 const bool _pic;
80 const bool _flatNamespace;
81 ld::Internal* _internal;
82 uint32_t _stubCount;
83 bool _largeText;
84 };
85
86 #include "stub_x86_64.hpp"
87 #include "stub_x86_64_classic.hpp"
88 #include "stub_x86.hpp"
89 #include "stub_x86_classic.hpp"
90 #include "stub_arm.hpp"
91 #include "stub_arm_classic.hpp"
92 #include "stub_ppc_classic.hpp"
93
94
95
96 Pass::Pass(const Options& opts)
97 : compressedHelperHelper(NULL),
98 compressedImageCache(NULL),
99 compressedFastBinderPointer(NULL),
100 _options(opts),
101 _architecture(opts.architecture()),
102 _lazyDylibsInUuse(opts.usingLazyDylibLinking()),
103 _compressedLINKEDIT(opts.makeCompressedDyldInfo()),
104 _prebind(opts.prebind()),
105 _mightBeInSharedRegion(opts.sharedRegionEligible()),
106 _pic(opts.outputSlidable()),
107 _flatNamespace(opts.nameSpace() != Options::kTwoLevelNameSpace),
108 _internal(NULL), _stubCount(0), _largeText(false)
109 {
110
111 }
112
113
114 const ld::Atom* Pass::stubableFixup(const ld::Fixup* fixup, ld::Internal& state)
115 {
116 if ( fixup->binding == ld::Fixup::bindingsIndirectlyBound ) {
117 const ld::Atom* target = state.indirectBindingTable[fixup->u.bindingIndex];
118 switch ( fixup->kind ) {
119 case ld::Fixup::kindStoreTargetAddressPPCBranch24:
120 case ld::Fixup::kindStoreTargetAddressX86BranchPCRel32:
121 case ld::Fixup::kindStoreTargetAddressARMBranch24:
122 case ld::Fixup::kindStoreTargetAddressThumbBranch22:
123 // create stub if target is in a dylib
124 if ( target->definition() == ld::Atom::definitionProxy )
125 return target;
126 // use stub if target is a resolver function in same linkage unit
127 if ( target->contentType() == ld::Atom::typeResolver )
128 return target;
129 if ( target->scope() == ld::Atom::scopeGlobal ) {
130 // create stub if target is global weak definition in symbol table
131 if ( (target->definition() == ld::Atom::definitionRegular)
132 && (target->combine() == ld::Atom::combineByName)
133 && ((target->symbolTableInclusion() == ld::Atom::symbolTableIn)
134 || (target->symbolTableInclusion() == ld::Atom::symbolTableInAndNeverStrip)) )
135 return target;
136 // create stub if target is interposable
137 if ( _options.interposable(target->name()) )
138 return target;
139 if ( _flatNamespace ) {
140 // flat namespace does not indirect calls within main exectuables
141 if ( _options.outputKind() == Options::kDynamicExecutable )
142 return NULL;
143 // create stub if target is global and building -flat dylib or bundle
144 return target;
145 }
146 }
147 break;
148 default:
149 if ( target->contentType() == ld::Atom::typeResolver ) {
150 // any pointer to a resolver needs to change to pointer to stub
151 return target;
152 }
153 break;
154 }
155 }
156 return NULL;
157 }
158
159
160
161 ld::Atom* Pass::makeStub(const ld::Atom& target, bool weakImport)
162 {
163 //fprintf(stderr, "makeStub(target=%p %s in sect %s)\n", &target, target.name(), target.section().sectionName());
164 bool stubToGlobalWeakDef = ( (target.scope() == ld::Atom::scopeGlobal)
165 && (target.definition() == ld::Atom::definitionRegular)
166 && (target.combine() == ld::Atom::combineByName) );
167
168 bool forLazyDylib = false;
169 const ld::dylib::File* dylib = dynamic_cast<const ld::dylib::File*>(target.file());
170 if ( (dylib != NULL) && dylib->willBeLazyLoadedDylib() )
171 forLazyDylib = true;
172 bool stubToResolver = (target.contentType() == ld::Atom::typeResolver);
173
174 if ( usingCompressedLINKEDIT() && !forLazyDylib ) {
175 if ( _internal->compressedFastBinderProxy == NULL )
176 throwf("symbol dyld_stub_binder not found (normally in libSystem.dylib). Needed to perform lazy binding to function %s", target.name());
177 }
178
179 switch ( _architecture ) {
180 case CPU_TYPE_POWERPC:
181 if ( _pic )
182 return new ld::passes::stubs::ppc::classic::StubPICAtom(*this, target, forLazyDylib, false, weakImport);
183 else
184 return new ld::passes::stubs::ppc::classic::StubNoPICAtom(*this, target, forLazyDylib, false, weakImport);
185 break;
186 case CPU_TYPE_POWERPC64:
187 return new ld::passes::stubs::ppc::classic::StubPICAtom(*this, target, forLazyDylib, true, weakImport);
188 break;
189 case CPU_TYPE_I386:
190 if ( usingCompressedLINKEDIT() && !forLazyDylib )
191 return new ld::passes::stubs::x86::StubAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
192 else
193 return new ld::passes::stubs::x86::classic::StubAtom(*this, target, forLazyDylib, weakImport);
194 break;
195 case CPU_TYPE_X86_64:
196 if ( usingCompressedLINKEDIT() && !forLazyDylib )
197 return new ld::passes::stubs::x86_64::StubAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
198 else
199 return new ld::passes::stubs::x86_64::classic::StubAtom(*this, target, forLazyDylib, weakImport);
200 break;
201 case CPU_TYPE_ARM:
202 if ( usingCompressedLINKEDIT() && !forLazyDylib ) {
203 if ( (_stubCount < 900) && !_mightBeInSharedRegion && !_largeText )
204 return new ld::passes::stubs::arm::StubCloseAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
205 else if ( _pic )
206 return new ld::passes::stubs::arm::StubPICAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
207 else
208 return new ld::passes::stubs::arm::StubNoPICAtom(*this, target, stubToGlobalWeakDef, stubToResolver, weakImport);
209 }
210 else {
211 if ( _pic )
212 return new ld::passes::stubs::arm::classic::StubPICAtom(*this, target, forLazyDylib, weakImport);
213 else
214 return new ld::passes::stubs::arm::classic::StubNoPICAtom(*this, target, forLazyDylib, weakImport);
215 }
216 break;
217 }
218 throw "unsupported arch for stub";
219 }
220
221
222 void Pass::verifyNoResolverFunctions(ld::Internal& state)
223 {
224 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
225 ld::Internal::FinalSection* sect = *sit;
226 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
227 const ld::Atom* atom = *ait;
228 if ( atom->contentType() == ld::Atom::typeResolver )
229 throwf("resolver function '%s' not supported in type of output", atom->name());
230 }
231 }
232 }
233
234 void Pass::process(ld::Internal& state)
235 {
236 switch ( _options.outputKind() ) {
237 case Options::kObjectFile:
238 // these kinds don't use stubs and can have resolver functions
239 return;
240 case Options::kKextBundle:
241 case Options::kStaticExecutable:
242 case Options::kPreload:
243 case Options::kDyld:
244 // these kinds don't use stubs and cannot have resolver functions
245 verifyNoResolverFunctions(state);
246 return;
247 case Options::kDynamicLibrary:
248 // uses stubs and can have resolver functions
249 break;
250 case Options::kDynamicExecutable:
251 case Options::kDynamicBundle:
252 // these kinds do use stubs and cannot have resolver functions
253 verifyNoResolverFunctions(state);
254 break;
255 }
256
257 // walk all atoms and fixups looking for stubable references
258 // don't create stubs inline because that could invalidate the sections iterator
259 std::vector<const ld::Atom*> atomsCallingStubs;
260 std::map<const ld::Atom*,ld::Atom*> stubFor;
261 std::map<const ld::Atom*,bool> weakImportMap;
262 atomsCallingStubs.reserve(128);
263 uint64_t codeSize = 0;
264 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
265 ld::Internal::FinalSection* sect = *sit;
266 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
267 const ld::Atom* atom = *ait;
268 codeSize += atom->size();
269 bool atomNeedsStub = false;
270 for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) {
271 const ld::Atom* stubableTargetOfFixup = stubableFixup(fit, state);
272 if ( stubableTargetOfFixup != NULL ) {
273 if ( !atomNeedsStub ) {
274 atomsCallingStubs.push_back(atom);
275 atomNeedsStub = true;
276 }
277 stubFor[stubableTargetOfFixup] = NULL;
278 // record weak_import attribute
279 std::map<const ld::Atom*,bool>::iterator pos = weakImportMap.find(stubableTargetOfFixup);
280 if ( pos == weakImportMap.end() ) {
281 // target not in weakImportMap, so add
282 weakImportMap[stubableTargetOfFixup] = fit->weakImport;
283 }
284 else {
285 // target in weakImportMap, check for weakness mismatch
286 if ( pos->second != fit->weakImport ) {
287 // found mismatch
288 switch ( _options.weakReferenceMismatchTreatment() ) {
289 case Options::kWeakReferenceMismatchError:
290 throwf("mismatching weak references for symbol: %s", stubableTargetOfFixup->name());
291 case Options::kWeakReferenceMismatchWeak:
292 pos->second = true;
293 break;
294 case Options::kWeakReferenceMismatchNonWeak:
295 pos->second = false;
296 break;
297 }
298 }
299 }
300 }
301 }
302 // all resolver functions must have a corresponding stub
303 if ( atom->contentType() == ld::Atom::typeResolver ) {
304 if ( _options.outputKind() != Options::kDynamicLibrary )
305 throwf("resolver functions (%s) can only be used in dylibs", atom->name());
306 if ( !_options.makeCompressedDyldInfo() ) {
307 if ( _options.architecture() == CPU_TYPE_POWERPC )
308 throwf("resolver functions (%s) not supported for PowerPC", atom->name());
309 else if ( _options.architecture() == CPU_TYPE_ARM )
310 throwf("resolver functions (%s) can only be used when targeting iOS 4.2 or later", atom->name());
311 else
312 throwf("resolver functions (%s) can only be used when targeting Mac OS X 10.6 or later", atom->name());
313 }
314 stubFor[atom] = NULL;
315 }
316 }
317 }
318
319 // short circuit if no stubs needed
320 _internal = &state;
321 _stubCount = stubFor.size();
322 if ( _stubCount == 0 )
323 return;
324
325 // <rdar://problem/8553283> lazily check for helper
326 if ( !_options.makeCompressedDyldInfo() && (state.classicBindingHelper == NULL) )
327 throw "symbol dyld_stub_binding_helper not found, normally in crt1.o/dylib1.o/bundle1.o";
328
329 // disable arm close stubs in some cases
330 if ( _architecture == CPU_TYPE_ARM ) {
331 if ( codeSize > 4*1024*1024 )
332 _largeText = true;
333 else {
334 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
335 ld::Internal::FinalSection* sect = *sit;
336 if ( sect->type() == ld::Section::typeMachHeader )
337 continue;
338 if ( strcmp(sect->segmentName(), "__TEXT") == 0) {
339 for (std::vector<const ld::Atom*>::iterator ait=sect->atoms.begin(); ait != sect->atoms.end(); ++ait) {
340 const ld::Atom* atom = *ait;
341 if ( atom->alignment().powerOf2 > 10 ) {
342 // overaligned section means might not be able to keep closestubs sect pushed to end of __TEXT
343 //warning("alignment 1<<%d in atom %s in section %s disables close stubs optimization",
344 // atom->alignment().powerOf2, atom->name(), sect->segmentName());
345 _largeText = true;
346 break;
347 }
348 }
349 }
350 }
351 }
352 }
353
354 // make stub atoms
355 for (std::map<const ld::Atom*,ld::Atom*>::iterator it = stubFor.begin(); it != stubFor.end(); ++it) {
356 it->second = makeStub(*it->first, weakImportMap[it->first]);
357 }
358
359 // updated atoms to use stubs
360 for (std::vector<const ld::Atom*>::iterator it=atomsCallingStubs.begin(); it != atomsCallingStubs.end(); ++it) {
361 const ld::Atom* atom = *it;
362 for (ld::Fixup::iterator fit = atom->fixupsBegin(), end=atom->fixupsEnd(); fit != end; ++fit) {
363 const ld::Atom* stubableTargetOfFixup = stubableFixup(fit, state);
364 if ( stubableTargetOfFixup != NULL ) {
365 ld::Atom* stub = stubFor[stubableTargetOfFixup];
366 assert(stub != NULL && "stub not created");
367 fit->binding = ld::Fixup::bindingDirectlyBound;
368 fit->u.target = stub;
369 }
370 }
371 }
372
373 // sort new atoms so links are consistent
374 for (std::vector<ld::Internal::FinalSection*>::iterator sit=state.sections.begin(); sit != state.sections.end(); ++sit) {
375 ld::Internal::FinalSection* sect = *sit;
376 switch ( sect->type() ) {
377 case ld::Section::typeStubHelper:
378 case ld::Section::typeStub:
379 case ld::Section::typeStubClose:
380 case ld::Section::typeLazyPointer:
381 case ld::Section::typeLazyPointerClose:
382 std::sort(sect->atoms.begin(), sect->atoms.end(), AtomByNameSorter());
383 break;
384 default:
385 break;
386 }
387 }
388
389 }
390
391
392 void doPass(const Options& opts, ld::Internal& internal)
393 {
394 Pass pass(opts);
395 pass.process(internal);
396 }
397
398
399
400 } // namespace stubs
401 } // namespace passes
402 } // namespace ld
403