]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoader.cpp
dyld-353.2.1.tar.gz
[apple/dyld.git] / src / ImageLoader.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-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 #define __STDC_LIMIT_MACROS
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <mach/mach.h>
31 #include <mach-o/fat.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/mman.h>
35 #include <sys/param.h>
36 #include <sys/mount.h>
37 #include <libkern/OSAtomic.h>
38
39 #include "ImageLoader.h"
40
41
42 uint32_t ImageLoader::fgImagesUsedFromSharedCache = 0;
43 uint32_t ImageLoader::fgImagesWithUsedPrebinding = 0;
44 uint32_t ImageLoader::fgImagesRequiringCoalescing = 0;
45 uint32_t ImageLoader::fgImagesHasWeakDefinitions = 0;
46 uint32_t ImageLoader::fgTotalRebaseFixups = 0;
47 uint32_t ImageLoader::fgTotalBindFixups = 0;
48 uint32_t ImageLoader::fgTotalBindSymbolsResolved = 0;
49 uint32_t ImageLoader::fgTotalBindImageSearches = 0;
50 uint32_t ImageLoader::fgTotalLazyBindFixups = 0;
51 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups = 0;
52 uint32_t ImageLoader::fgTotalSegmentsMapped = 0;
53 uint64_t ImageLoader::fgTotalBytesMapped = 0;
54 uint64_t ImageLoader::fgTotalBytesPreFetched = 0;
55 uint64_t ImageLoader::fgTotalLoadLibrariesTime;
56 uint64_t ImageLoader::fgTotalRebaseTime;
57 uint64_t ImageLoader::fgTotalBindTime;
58 uint64_t ImageLoader::fgTotalWeakBindTime;
59 uint64_t ImageLoader::fgTotalDOF;
60 uint64_t ImageLoader::fgTotalInitTime;
61 uint16_t ImageLoader::fgLoadOrdinal = 0;
62 std::vector<ImageLoader::InterposeTuple>ImageLoader::fgInterposingTuples;
63 uintptr_t ImageLoader::fgNextPIEDylibAddress = 0;
64
65
66
67 ImageLoader::ImageLoader(const char* path, unsigned int libCount)
68 : fPath(path), fRealPath(NULL), fDevice(0), fInode(0), fLastModified(0),
69 fPathHash(0), fDlopenReferenceCount(0), fInitializerRecursiveLock(NULL),
70 fDepth(0), fLoadOrder(fgLoadOrdinal++), fState(0), fLibraryCount(libCount),
71 fAllLibraryChecksumsAndLoadAddressesMatch(false), fLeaveMapped(false), fNeverUnload(false),
72 fHideSymbols(false), fMatchByInstallName(false),
73 fInterposed(false), fRegisteredDOF(false), fAllLazyPointersBound(false),
74 fBeingRemoved(false), fAddFuncNotified(false),
75 fPathOwnedByImage(false), fIsReferencedDownward(false),
76 fWeakSymbolsBound(false)
77 {
78 if ( fPath != NULL )
79 fPathHash = hash(fPath);
80 if ( libCount > 512 )
81 dyld::throwf("too many dependent dylibs in %s", path);
82 }
83
84
85 void ImageLoader::deleteImage(ImageLoader* image)
86 {
87 delete image;
88 }
89
90
91 ImageLoader::~ImageLoader()
92 {
93 if ( fRealPath != NULL )
94 delete [] fRealPath;
95 if ( fPathOwnedByImage && (fPath != NULL) )
96 delete [] fPath;
97 }
98
99 void ImageLoader::setFileInfo(dev_t device, ino_t inode, time_t modDate)
100 {
101 fDevice = device;
102 fInode = inode;
103 fLastModified = modDate;
104 }
105
106 void ImageLoader::setMapped(const LinkContext& context)
107 {
108 fState = dyld_image_state_mapped;
109 context.notifySingle(dyld_image_state_mapped, this); // note: can throw exception
110 }
111
112 int ImageLoader::compare(const ImageLoader* right) const
113 {
114 if ( this->fDepth == right->fDepth ) {
115 if ( this->fLoadOrder == right->fLoadOrder )
116 return 0;
117 else if ( this->fLoadOrder < right->fLoadOrder )
118 return -1;
119 else
120 return 1;
121 }
122 else {
123 if ( this->fDepth < right->fDepth )
124 return -1;
125 else
126 return 1;
127 }
128 }
129
130 void ImageLoader::setPath(const char* path)
131 {
132 if ( fPathOwnedByImage && (fPath != NULL) )
133 delete [] fPath;
134 fPath = new char[strlen(path)+1];
135 strcpy((char*)fPath, path);
136 fPathOwnedByImage = true; // delete fPath when this image is destructed
137 fPathHash = hash(fPath);
138 fRealPath = NULL;
139 }
140
141 void ImageLoader::setPathUnowned(const char* path)
142 {
143 if ( fPathOwnedByImage && (fPath != NULL) ) {
144 delete [] fPath;
145 }
146 fPath = path;
147 fPathOwnedByImage = false;
148 fPathHash = hash(fPath);
149 }
150
151 void ImageLoader::setPaths(const char* path, const char* realPath)
152 {
153 this->setPath(path);
154 fRealPath = new char[strlen(realPath)+1];
155 strcpy((char*)fRealPath, realPath);
156 }
157
158 const char* ImageLoader::getRealPath() const
159 {
160 if ( fRealPath != NULL )
161 return fRealPath;
162 else
163 return fPath;
164 }
165
166
167 uint32_t ImageLoader::hash(const char* path)
168 {
169 // this does not need to be a great hash
170 // it is just used to reduce the number of strcmp() calls
171 // of existing images when loading a new image
172 uint32_t h = 0;
173 for (const char* s=path; *s != '\0'; ++s)
174 h = h*5 + *s;
175 return h;
176 }
177
178 bool ImageLoader::matchInstallPath() const
179 {
180 return fMatchByInstallName;
181 }
182
183 void ImageLoader::setMatchInstallPath(bool match)
184 {
185 fMatchByInstallName = match;
186 }
187
188 bool ImageLoader::statMatch(const struct stat& stat_buf) const
189 {
190 return ( (this->fDevice == stat_buf.st_dev) && (this->fInode == stat_buf.st_ino) );
191 }
192
193 const char* ImageLoader::getShortName() const
194 {
195 // try to return leaf name
196 if ( fPath != NULL ) {
197 const char* s = strrchr(fPath, '/');
198 if ( s != NULL )
199 return &s[1];
200 }
201 return fPath;
202 }
203
204 void ImageLoader::setLeaveMapped()
205 {
206 fLeaveMapped = true;
207 }
208
209 void ImageLoader::setHideExports(bool hide)
210 {
211 fHideSymbols = hide;
212 }
213
214 bool ImageLoader::hasHiddenExports() const
215 {
216 return fHideSymbols;
217 }
218
219 bool ImageLoader::isLinked() const
220 {
221 return (fState >= dyld_image_state_bound);
222 }
223
224 time_t ImageLoader::lastModified() const
225 {
226 return fLastModified;
227 }
228
229 bool ImageLoader::containsAddress(const void* addr) const
230 {
231 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
232 const uint8_t* start = (const uint8_t*)segActualLoadAddress(i);
233 const uint8_t* end = (const uint8_t*)segActualEndAddress(i);
234 if ( (start <= addr) && (addr < end) && !segUnaccessible(i) )
235 return true;
236 }
237 return false;
238 }
239
240 bool ImageLoader::overlapsWithAddressRange(const void* start, const void* end) const
241 {
242 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
243 const uint8_t* segStart = (const uint8_t*)segActualLoadAddress(i);
244 const uint8_t* segEnd = (const uint8_t*)segActualEndAddress(i);
245 if ( strcmp(segName(i), "__UNIXSTACK") == 0 ) {
246 // __UNIXSTACK never slides. This is the only place that cares
247 // and checking for that segment name in segActualLoadAddress()
248 // is too expensive.
249 segStart -= getSlide();
250 segEnd -= getSlide();
251 }
252 if ( (start <= segStart) && (segStart < end) )
253 return true;
254 if ( (start <= segEnd) && (segEnd < end) )
255 return true;
256 if ( (segStart < start) && (end < segEnd) )
257 return true;
258 }
259 return false;
260 }
261
262 void ImageLoader::getMappedRegions(MappedRegion*& regions) const
263 {
264 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
265 MappedRegion region;
266 region.address = segActualLoadAddress(i);
267 region.size = segSize(i);
268 *regions++ = region;
269 }
270 }
271
272
273
274 bool ImageLoader::dependsOn(ImageLoader* image) {
275 for(unsigned int i=0; i < libraryCount(); ++i) {
276 if ( libImage(i) == image )
277 return true;
278 }
279 return false;
280 }
281
282
283 static bool notInImgageList(const ImageLoader* image, const ImageLoader** dsiStart, const ImageLoader** dsiCur)
284 {
285 for (const ImageLoader** p = dsiStart; p < dsiCur; ++p)
286 if ( *p == image )
287 return false;
288 return true;
289 }
290
291
292 // private method that handles circular dependencies by only search any image once
293 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name,
294 const ImageLoader** dsiStart, const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const
295 {
296 const ImageLoader::Symbol* sym;
297 // search self
298 if ( notInImgageList(this, dsiStart, dsiCur) ) {
299 sym = this->findExportedSymbol(name, false, foundIn);
300 if ( sym != NULL )
301 return sym;
302 *dsiCur++ = this;
303 }
304
305 // search directly dependent libraries
306 for(unsigned int i=0; i < libraryCount(); ++i) {
307 ImageLoader* dependentImage = libImage(i);
308 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
309 const ImageLoader::Symbol* sym = dependentImage->findExportedSymbol(name, false, foundIn);
310 if ( sym != NULL )
311 return sym;
312 }
313 }
314
315 // search indirectly dependent libraries
316 for(unsigned int i=0; i < libraryCount(); ++i) {
317 ImageLoader* dependentImage = libImage(i);
318 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
319 *dsiCur++ = dependentImage;
320 const ImageLoader::Symbol* sym = dependentImage->findExportedSymbolInDependentImagesExcept(name, dsiStart, dsiCur, dsiEnd, foundIn);
321 if ( sym != NULL )
322 return sym;
323 }
324 }
325
326 return NULL;
327 }
328
329
330 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
331 {
332 unsigned int imageCount = context.imageCount();
333 const ImageLoader* dontSearchImages[imageCount];
334 dontSearchImages[0] = this; // don't search this image
335 const ImageLoader** cur = &dontSearchImages[1];
336 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
337 }
338
339 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
340 {
341 unsigned int imageCount = context.imageCount();
342 const ImageLoader* dontSearchImages[imageCount];
343 const ImageLoader** cur = &dontSearchImages[0];
344 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
345 }
346
347 // this is called by initializeMainExecutable() to interpose on the initial set of images
348 void ImageLoader::applyInterposing(const LinkContext& context)
349 {
350 if ( fgInterposingTuples.size() != 0 )
351 this->recursiveApplyInterposing(context);
352 }
353
354
355 uintptr_t ImageLoader::interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* inImage, const ImageLoader* onlyInImage)
356 {
357 //dyld::log("interposedAddress(0x%08llX), tupleCount=%lu\n", (uint64_t)address, fgInterposingTuples.size());
358 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
359 //dyld::log(" interposedAddress: replacee=0x%08llX, replacement=0x%08llX, neverImage=%p, onlyImage=%p, inImage=%p\n",
360 // (uint64_t)it->replacee, (uint64_t)it->replacement, it->neverImage, it->onlyImage, inImage);
361 // replace all references to 'replacee' with 'replacement'
362 if ( (address == it->replacee) && (inImage != it->neverImage) && ((it->onlyImage == NULL) || (inImage == it->onlyImage)) ) {
363 if ( context.verboseInterposing ) {
364 dyld::log("dyld interposing: replace 0x%lX with 0x%lX\n", it->replacee, it->replacement);
365 }
366 return it->replacement;
367 }
368 }
369 return address;
370 }
371
372 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count)
373 {
374 for(size_t i=0; i < count; ++i) {
375 ImageLoader::InterposeTuple tuple;
376 tuple.replacement = (uintptr_t)array[i].replacement;
377 tuple.neverImage = NULL;
378 tuple.onlyImage = this;
379 tuple.replacee = (uintptr_t)array[i].replacee;
380 // chain to any existing interpositions
381 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
382 if ( (it->replacee == tuple.replacee) && (it->onlyImage == this) ) {
383 tuple.replacee = it->replacement;
384 }
385 }
386 ImageLoader::fgInterposingTuples.push_back(tuple);
387 }
388 }
389
390
391 void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, bool neverUnload, const RPathChain& loaderRPaths)
392 {
393 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", this->getPath(), fDlopenReferenceCount, fNeverUnload);
394
395 // clear error strings
396 (*context.setErrorStrings)(dyld_error_kind_none, NULL, NULL, NULL);
397
398 uint64_t t0 = mach_absolute_time();
399 this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths);
400 context.notifyBatch(dyld_image_state_dependents_mapped);
401
402 // we only do the loading step for preflights
403 if ( preflightOnly )
404 return;
405
406 uint64_t t1 = mach_absolute_time();
407 context.clearAllDepths();
408 this->recursiveUpdateDepth(context.imageCount());
409
410 uint64_t t2 = mach_absolute_time();
411 this->recursiveRebase(context);
412 context.notifyBatch(dyld_image_state_rebased);
413
414 uint64_t t3 = mach_absolute_time();
415 this->recursiveBind(context, forceLazysBound, neverUnload);
416
417 uint64_t t4 = mach_absolute_time();
418 if ( !context.linkingMainExecutable )
419 this->weakBind(context);
420 uint64_t t5 = mach_absolute_time();
421
422 context.notifyBatch(dyld_image_state_bound);
423 uint64_t t6 = mach_absolute_time();
424
425 std::vector<DOFInfo> dofs;
426 this->recursiveGetDOFSections(context, dofs);
427 context.registerDOFs(dofs);
428 uint64_t t7 = mach_absolute_time();
429
430 // interpose any dynamically loaded images
431 if ( !context.linkingMainExecutable && (fgInterposingTuples.size() != 0) ) {
432 this->recursiveApplyInterposing(context);
433 }
434
435 // clear error strings
436 (*context.setErrorStrings)(dyld_error_kind_none, NULL, NULL, NULL);
437
438 fgTotalLoadLibrariesTime += t1 - t0;
439 fgTotalRebaseTime += t3 - t2;
440 fgTotalBindTime += t4 - t3;
441 fgTotalWeakBindTime += t5 - t4;
442 fgTotalDOF += t7 - t6;
443
444 // done with initial dylib loads
445 fgNextPIEDylibAddress = 0;
446 }
447
448
449 void ImageLoader::printReferenceCounts()
450 {
451 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount, getPath() );
452 }
453
454
455 bool ImageLoader::decrementDlopenReferenceCount()
456 {
457 if ( fDlopenReferenceCount == 0 )
458 return true;
459 --fDlopenReferenceCount;
460 return false;
461 }
462
463
464 // <rdar://problem/14412057> upward dylib initializers can be run too soon
465 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
466 // have their initialization postponed until after the recursion through downward dylibs
467 // has completed.
468 void ImageLoader::processInitializers(const LinkContext& context, mach_port_t thisThread,
469 InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& images)
470 {
471 uint32_t maxImageCount = context.imageCount();
472 ImageLoader::UninitedUpwards upsBuffer[maxImageCount];
473 ImageLoader::UninitedUpwards& ups = upsBuffer[0];
474 ups.count = 0;
475 // Calling recursive init on all images in images list, building a new list of
476 // uninitialized upward dependencies.
477 for (uintptr_t i=0; i < images.count; ++i) {
478 images.images[i]->recursiveInitialization(context, thisThread, timingInfo, ups);
479 }
480 // If any upward dependencies remain, init them.
481 if ( ups.count > 0 )
482 processInitializers(context, thisThread, timingInfo, ups);
483 }
484
485
486 void ImageLoader::runInitializers(const LinkContext& context, InitializerTimingList& timingInfo)
487 {
488 uint64_t t1 = mach_absolute_time();
489 mach_port_t thisThread = mach_thread_self();
490 ImageLoader::UninitedUpwards up;
491 up.count = 1;
492 up.images[0] = this;
493 processInitializers(context, thisThread, timingInfo, up);
494 context.notifyBatch(dyld_image_state_initialized);
495 mach_port_deallocate(mach_task_self(), thisThread);
496 uint64_t t2 = mach_absolute_time();
497 fgTotalInitTime += (t2 - t1);
498 }
499
500
501 void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
502 {
503 if ( ! fAllLazyPointersBound ) {
504 fAllLazyPointersBound = true;
505
506 if ( recursive ) {
507 // bind lower level libraries first
508 for(unsigned int i=0; i < libraryCount(); ++i) {
509 ImageLoader* dependentImage = libImage(i);
510 if ( dependentImage != NULL )
511 dependentImage->bindAllLazyPointers(context, recursive);
512 }
513 }
514 // bind lazies in this image
515 this->doBindJustLazies(context);
516 }
517 }
518
519
520 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
521 {
522 return fAllLibraryChecksumsAndLoadAddressesMatch;
523 }
524
525
526 void ImageLoader::markedUsedRecursive(const std::vector<DynamicReference>& dynamicReferences)
527 {
528 // already visited here
529 if ( fMarkedInUse )
530 return;
531 fMarkedInUse = true;
532
533 // clear mark on all statically dependent dylibs
534 for(unsigned int i=0; i < libraryCount(); ++i) {
535 ImageLoader* dependentImage = libImage(i);
536 if ( dependentImage != NULL ) {
537 dependentImage->markedUsedRecursive(dynamicReferences);
538 }
539 }
540
541 // clear mark on all dynamically dependent dylibs
542 for (std::vector<ImageLoader::DynamicReference>::const_iterator it=dynamicReferences.begin(); it != dynamicReferences.end(); ++it) {
543 if ( it->from == this )
544 it->to->markedUsedRecursive(dynamicReferences);
545 }
546
547 }
548
549 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth)
550 {
551 // the purpose of this phase is to make the images sortable such that
552 // in a sort list of images, every image that an image depends on
553 // occurs in the list before it.
554 if ( fDepth == 0 ) {
555 // break cycles
556 fDepth = maxDepth;
557
558 // get depth of dependents
559 unsigned int minDependentDepth = maxDepth;
560 for(unsigned int i=0; i < libraryCount(); ++i) {
561 ImageLoader* dependentImage = libImage(i);
562 if ( (dependentImage != NULL) && !libIsUpward(i) ) {
563 unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth);
564 if ( d < minDependentDepth )
565 minDependentDepth = d;
566 }
567 }
568
569 // make me less deep then all my dependents
570 fDepth = minDependentDepth - 1;
571 }
572
573 return fDepth;
574 }
575
576
577 void ImageLoader::recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths)
578 {
579 if ( fState < dyld_image_state_dependents_mapped ) {
580 // break cycles
581 fState = dyld_image_state_dependents_mapped;
582
583 // get list of libraries this image needs
584 DependentLibraryInfo libraryInfos[fLibraryCount];
585 this->doGetDependentLibraries(libraryInfos);
586
587 // get list of rpaths that this image adds
588 std::vector<const char*> rpathsFromThisImage;
589 this->getRPaths(context, rpathsFromThisImage);
590 const RPathChain thisRPaths(&loaderRPaths, &rpathsFromThisImage);
591
592 // try to load each
593 bool canUsePrelinkingInfo = true;
594 for(unsigned int i=0; i < fLibraryCount; ++i){
595 ImageLoader* dependentLib;
596 bool depLibReExported = false;
597 bool depLibReRequired = false;
598 bool depLibCheckSumsMatch = false;
599 DependentLibraryInfo& requiredLibInfo = libraryInfos[i];
600 #if DYLD_SHARED_CACHE_SUPPORT
601 if ( preflightOnly && context.inSharedCache(requiredLibInfo.name) ) {
602 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
603 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
604 setLibImage(i, NULL, false, false);
605 continue;
606 }
607 #endif
608 try {
609 dependentLib = context.loadLibrary(requiredLibInfo.name, true, this->getPath(), &thisRPaths);
610 if ( dependentLib == this ) {
611 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
612 dependentLib = context.loadLibrary(requiredLibInfo.name, false, NULL, NULL);
613 if ( dependentLib != this )
614 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
615 }
616 if ( fNeverUnload )
617 dependentLib->setNeverUnload();
618 if ( requiredLibInfo.upward ) {
619 }
620 else {
621 dependentLib->fIsReferencedDownward = true;
622 }
623 LibraryInfo actualInfo = dependentLib->doGetLibraryInfo();
624 depLibReRequired = requiredLibInfo.required;
625 depLibCheckSumsMatch = ( actualInfo.checksum == requiredLibInfo.info.checksum );
626 depLibReExported = requiredLibInfo.reExported;
627 if ( ! depLibReExported ) {
628 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
629 depLibReExported = dependentLib->isSubframeworkOf(context, this) || this->hasSubLibrary(context, dependentLib);
630 }
631 // check found library version is compatible
632 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
633 if ( (requiredLibInfo.info.minVersion != 0xFFFFFFFF) && (actualInfo.minVersion < requiredLibInfo.info.minVersion) ) {
634 // record values for possible use by CrashReporter or Finder
635 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
636 this->getShortName(), requiredLibInfo.info.minVersion >> 16, (requiredLibInfo.info.minVersion >> 8) & 0xff, requiredLibInfo.info.minVersion & 0xff,
637 dependentLib->getShortName(), actualInfo.minVersion >> 16, (actualInfo.minVersion >> 8) & 0xff, actualInfo.minVersion & 0xff);
638 }
639 // prebinding for this image disabled if any dependent library changed
640 if ( !depLibCheckSumsMatch )
641 canUsePrelinkingInfo = false;
642 // prebinding for this image disabled unless both this and dependent are in the shared cache
643 if ( !dependentLib->inSharedCache() || !this->inSharedCache() )
644 canUsePrelinkingInfo = false;
645
646 //if ( context.verbosePrebinding ) {
647 // if ( !requiredLib.checksumMatches )
648 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
649 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
650 // if ( dependentLib->getSlide() != 0 )
651 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
652 //}
653 }
654 catch (const char* msg) {
655 //if ( context.verbosePrebinding )
656 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
657 if ( requiredLibInfo.required ) {
658 fState = dyld_image_state_mapped;
659 // record values for possible use by CrashReporter or Finder
660 if ( strstr(msg, "Incompatible") != NULL )
661 (*context.setErrorStrings)(dyld_error_kind_dylib_version, this->getPath(), requiredLibInfo.name, NULL);
662 else if ( strstr(msg, "architecture") != NULL )
663 (*context.setErrorStrings)(dyld_error_kind_dylib_wrong_arch, this->getPath(), requiredLibInfo.name, NULL);
664 else
665 (*context.setErrorStrings)(dyld_error_kind_dylib_missing, this->getPath(), requiredLibInfo.name, NULL);
666 const char* newMsg = dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo.name, this->getRealPath(), msg);
667 free((void*)msg); // our free() will do nothing if msg is a string literal
668 throw newMsg;
669 }
670 free((void*)msg); // our free() will do nothing if msg is a string literal
671 // ok if weak library not found
672 dependentLib = NULL;
673 canUsePrelinkingInfo = false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
674 }
675 setLibImage(i, dependentLib, depLibReExported, requiredLibInfo.upward);
676 }
677 fAllLibraryChecksumsAndLoadAddressesMatch = canUsePrelinkingInfo;
678
679 // tell each to load its dependents
680 for(unsigned int i=0; i < libraryCount(); ++i) {
681 ImageLoader* dependentImage = libImage(i);
682 if ( dependentImage != NULL ) {
683 dependentImage->recursiveLoadLibraries(context, preflightOnly, thisRPaths);
684 }
685 }
686
687 // do deep prebind check
688 if ( fAllLibraryChecksumsAndLoadAddressesMatch ) {
689 for(unsigned int i=0; i < libraryCount(); ++i){
690 ImageLoader* dependentImage = libImage(i);
691 if ( dependentImage != NULL ) {
692 if ( !dependentImage->allDependentLibrariesAsWhenPreBound() )
693 fAllLibraryChecksumsAndLoadAddressesMatch = false;
694 }
695 }
696 }
697
698 // free rpaths (getRPaths() malloc'ed each string)
699 for(std::vector<const char*>::iterator it=rpathsFromThisImage.begin(); it != rpathsFromThisImage.end(); ++it) {
700 const char* str = *it;
701 free((void*)str);
702 }
703
704 }
705 }
706
707 void ImageLoader::recursiveRebase(const LinkContext& context)
708 {
709 if ( fState < dyld_image_state_rebased ) {
710 // break cycles
711 fState = dyld_image_state_rebased;
712
713 try {
714 // rebase lower level libraries first
715 for(unsigned int i=0; i < libraryCount(); ++i) {
716 ImageLoader* dependentImage = libImage(i);
717 if ( dependentImage != NULL )
718 dependentImage->recursiveRebase(context);
719 }
720
721 // rebase this image
722 doRebase(context);
723
724 // notify
725 context.notifySingle(dyld_image_state_rebased, this);
726 }
727 catch (const char* msg) {
728 // this image is not rebased
729 fState = dyld_image_state_dependents_mapped;
730 CRSetCrashLogMessage2(NULL);
731 throw;
732 }
733 }
734 }
735
736 void ImageLoader::recursiveApplyInterposing(const LinkContext& context)
737 {
738 if ( ! fInterposed ) {
739 // break cycles
740 fInterposed = true;
741
742 try {
743 // interpose lower level libraries first
744 for(unsigned int i=0; i < libraryCount(); ++i) {
745 ImageLoader* dependentImage = libImage(i);
746 if ( dependentImage != NULL )
747 dependentImage->recursiveApplyInterposing(context);
748 }
749
750 // interpose this image
751 doInterpose(context);
752 }
753 catch (const char* msg) {
754 // this image is not interposed
755 fInterposed = false;
756 throw;
757 }
758 }
759 }
760
761
762
763 void ImageLoader::recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload)
764 {
765 // Normally just non-lazy pointers are bound immediately.
766 // The exceptions are:
767 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
768 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
769 if ( fState < dyld_image_state_bound ) {
770 // break cycles
771 fState = dyld_image_state_bound;
772
773 try {
774 // bind lower level libraries first
775 for(unsigned int i=0; i < libraryCount(); ++i) {
776 ImageLoader* dependentImage = libImage(i);
777 if ( dependentImage != NULL )
778 dependentImage->recursiveBind(context, forceLazysBound, neverUnload);
779 }
780 // bind this image
781 this->doBind(context, forceLazysBound);
782 // mark if lazys are also bound
783 if ( forceLazysBound || this->usablePrebinding(context) )
784 fAllLazyPointersBound = true;
785 // mark as never-unload if requested
786 if ( neverUnload )
787 this->setNeverUnload();
788
789 context.notifySingle(dyld_image_state_bound, this);
790 }
791 catch (const char* msg) {
792 // restore state
793 fState = dyld_image_state_rebased;
794 CRSetCrashLogMessage2(NULL);
795 throw;
796 }
797 }
798 }
799
800 void ImageLoader::weakBind(const LinkContext& context)
801 {
802 if ( context.verboseWeakBind )
803 dyld::log("dyld: weak bind start:\n");
804 uint64_t t1 = mach_absolute_time();
805 // get set of ImageLoaders that participate in coalecsing
806 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
807 int count = context.getCoalescedImages(imagesNeedingCoalescing);
808
809 // count how many have not already had weakbinding done
810 int countNotYetWeakBound = 0;
811 int countOfImagesWithWeakDefinitions = 0;
812 int countOfImagesWithWeakDefinitionsNotInSharedCache = 0;
813 for(int i=0; i < count; ++i) {
814 if ( ! imagesNeedingCoalescing[i]->fWeakSymbolsBound )
815 ++countNotYetWeakBound;
816 if ( imagesNeedingCoalescing[i]->hasCoalescedExports() ) {
817 ++countOfImagesWithWeakDefinitions;
818 if ( ! imagesNeedingCoalescing[i]->inSharedCache() )
819 ++countOfImagesWithWeakDefinitionsNotInSharedCache;
820 }
821 }
822
823 // don't need to do any coalescing if only one image has overrides, or all have already been done
824 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache > 0) && (countNotYetWeakBound > 0) ) {
825 // make symbol iterators for each
826 ImageLoader::CoalIterator iterators[count];
827 ImageLoader::CoalIterator* sortedIts[count];
828 for(int i=0; i < count; ++i) {
829 imagesNeedingCoalescing[i]->initializeCoalIterator(iterators[i], i);
830 sortedIts[i] = &iterators[i];
831 if ( context.verboseWeakBind )
832 dyld::log("dyld: weak bind load order %d/%d for %s\n", i, count, imagesNeedingCoalescing[i]->getPath());
833 }
834
835 // walk all symbols keeping iterators in sync by
836 // only ever incrementing the iterator with the lowest symbol
837 int doneCount = 0;
838 while ( doneCount != count ) {
839 //for(int i=0; i < count; ++i)
840 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
841 //dyld::log("\n");
842 // increment iterator with lowest symbol
843 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
844 ++doneCount;
845 // re-sort iterators
846 for(int i=1; i < count; ++i) {
847 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
848 if ( result == 0 )
849 sortedIts[i-1]->symbolMatches = true;
850 if ( result > 0 ) {
851 // new one is bigger then next, so swap
852 ImageLoader::CoalIterator* temp = sortedIts[i-1];
853 sortedIts[i-1] = sortedIts[i];
854 sortedIts[i] = temp;
855 }
856 if ( result < 0 )
857 break;
858 }
859 // process all matching symbols just before incrementing the lowest one that matches
860 if ( sortedIts[0]->symbolMatches && !sortedIts[0]->done ) {
861 const char* nameToCoalesce = sortedIts[0]->symbolName;
862 // pick first symbol in load order (and non-weak overrides weak)
863 uintptr_t targetAddr = 0;
864 ImageLoader* targetImage = NULL;
865 for(int i=0; i < count; ++i) {
866 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
867 if ( context.verboseWeakBind )
868 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce, iterators[i].weakSymbol, iterators[i].image->getPath());
869 if ( iterators[i].weakSymbol ) {
870 if ( targetAddr == 0 ) {
871 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
872 if ( targetAddr != 0 )
873 targetImage = iterators[i].image;
874 }
875 }
876 else {
877 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
878 if ( targetAddr != 0 ) {
879 targetImage = iterators[i].image;
880 // strong implementation found, stop searching
881 break;
882 }
883 }
884 }
885 }
886 if ( context.verboseWeakBind )
887 dyld::log("dyld: weak binding all uses of %s to copy from %s\n", nameToCoalesce, targetImage->getShortName());
888
889 // tell each to bind to this symbol (unless already bound)
890 if ( targetAddr != 0 ) {
891 for(int i=0; i < count; ++i) {
892 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
893 if ( context.verboseWeakBind )
894 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n", nameToCoalesce, iterators[i].image->getShortName(), targetAddr, targetImage->getShortName());
895 if ( ! iterators[i].image->fWeakSymbolsBound )
896 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, context);
897 iterators[i].symbolMatches = false;
898 }
899 }
900 }
901
902 }
903 }
904
905 // mark all as having all weak symbols bound
906 for(int i=0; i < count; ++i) {
907 imagesNeedingCoalescing[i]->fWeakSymbolsBound = true;
908 }
909 }
910 uint64_t t2 = mach_absolute_time();
911 fgTotalWeakBindTime += t2 - t1;
912
913 if ( context.verboseWeakBind )
914 dyld::log("dyld: weak bind end\n");
915 }
916
917
918
919 void ImageLoader::recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs)
920 {
921 if ( ! fRegisteredDOF ) {
922 // break cycles
923 fRegisteredDOF = true;
924
925 // gather lower level libraries first
926 for(unsigned int i=0; i < libraryCount(); ++i) {
927 ImageLoader* dependentImage = libImage(i);
928 if ( dependentImage != NULL )
929 dependentImage->recursiveGetDOFSections(context, dofs);
930 }
931 this->doGetDOFSections(context, dofs);
932 }
933 }
934
935 void ImageLoader::setNeverUnloadRecursive() {
936 if ( ! fNeverUnload ) {
937 // break cycles
938 fNeverUnload = true;
939
940 // gather lower level libraries first
941 for(unsigned int i=0; i < libraryCount(); ++i) {
942 ImageLoader* dependentImage = libImage(i);
943 if ( dependentImage != NULL )
944 dependentImage->setNeverUnloadRecursive();
945 }
946 }
947 }
948
949 void ImageLoader::recursiveSpinLock(recursive_lock& rlock)
950 {
951 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
952 // keep trying until success (spin)
953 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL, &rlock, (void**)&fInitializerRecursiveLock) ) {
954 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
955 // the same thread we are on, the increment the lock count, otherwise continue to spin
956 if ( (fInitializerRecursiveLock != NULL) && (fInitializerRecursiveLock->thread == rlock.thread) )
957 break;
958 }
959 ++(fInitializerRecursiveLock->count);
960 }
961
962 void ImageLoader::recursiveSpinUnLock()
963 {
964 if ( --(fInitializerRecursiveLock->count) == 0 )
965 fInitializerRecursiveLock = NULL;
966 }
967
968
969 void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread,
970 InitializerTimingList& timingInfo, UninitedUpwards& uninitUps)
971 {
972 recursive_lock lock_info(this_thread);
973 recursiveSpinLock(lock_info);
974
975 if ( fState < dyld_image_state_dependents_initialized-1 ) {
976 uint8_t oldState = fState;
977 // break cycles
978 fState = dyld_image_state_dependents_initialized-1;
979 try {
980 // initialize lower level libraries first
981 for(unsigned int i=0; i < libraryCount(); ++i) {
982 ImageLoader* dependentImage = libImage(i);
983 if ( dependentImage != NULL ) {
984 // don't try to initialize stuff "above" me yet
985 if ( libIsUpward(i) ) {
986 uninitUps.images[uninitUps.count] = dependentImage;
987 uninitUps.count++;
988 }
989 else if ( dependentImage->fDepth >= fDepth ) {
990 dependentImage->recursiveInitialization(context, this_thread, timingInfo, uninitUps);
991 }
992 }
993 }
994
995 // record termination order
996 if ( this->needsTermination() )
997 context.terminationRecorder(this);
998
999 // let objc know we are about to initialize this image
1000 uint64_t t1 = mach_absolute_time();
1001 fState = dyld_image_state_dependents_initialized;
1002 oldState = fState;
1003 context.notifySingle(dyld_image_state_dependents_initialized, this);
1004
1005 // initialize this image
1006 bool hasInitializers = this->doInitialization(context);
1007
1008 // let anyone know we finished initializing this image
1009 fState = dyld_image_state_initialized;
1010 oldState = fState;
1011 context.notifySingle(dyld_image_state_initialized, this);
1012
1013 if ( hasInitializers ) {
1014 uint64_t t2 = mach_absolute_time();
1015 timingInfo.images[timingInfo.count].image = this;
1016 timingInfo.images[timingInfo.count].initTime = (t2-t1);
1017 timingInfo.count++;
1018 }
1019 }
1020 catch (const char* msg) {
1021 // this image is not initialized
1022 fState = oldState;
1023 recursiveSpinUnLock();
1024 throw;
1025 }
1026 }
1027
1028 recursiveSpinUnLock();
1029 }
1030
1031
1032 static void printTime(const char* msg, uint64_t partTime, uint64_t totalTime)
1033 {
1034 static uint64_t sUnitsPerSecond = 0;
1035 if ( sUnitsPerSecond == 0 ) {
1036 struct mach_timebase_info timeBaseInfo;
1037 if ( mach_timebase_info(&timeBaseInfo) == KERN_SUCCESS ) {
1038 sUnitsPerSecond = 1000000000ULL * timeBaseInfo.denom / timeBaseInfo.numer;
1039 }
1040 }
1041 if ( partTime < sUnitsPerSecond ) {
1042 uint32_t milliSecondsTimesHundred = (uint32_t)((partTime*100000)/sUnitsPerSecond);
1043 uint32_t milliSeconds = (uint32_t)(milliSecondsTimesHundred/100);
1044 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1045 uint32_t percent = percentTimesTen/10;
1046 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1047 }
1048 else {
1049 uint32_t secondsTimeTen = (uint32_t)((partTime*10)/sUnitsPerSecond);
1050 uint32_t seconds = secondsTimeTen/10;
1051 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1052 uint32_t percent = percentTimesTen/10;
1053 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg, seconds, secondsTimeTen-seconds*10, percent, percentTimesTen-percent*10);
1054 }
1055 }
1056
1057 static char* commatize(uint64_t in, char* out)
1058 {
1059 uint64_t div10 = in / 10;
1060 uint8_t delta = in - div10*10;
1061 char* s = &out[32];
1062 int digitCount = 1;
1063 *s = '\0';
1064 *(--s) = '0' + delta;
1065 in = div10;
1066 while ( in != 0 ) {
1067 if ( (digitCount % 3) == 0 )
1068 *(--s) = ',';
1069 div10 = in / 10;
1070 delta = in - div10*10;
1071 *(--s) = '0' + delta;
1072 in = div10;
1073 ++digitCount;
1074 }
1075 return s;
1076 }
1077
1078
1079 void ImageLoader::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
1080 {
1081 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1082 char commaNum1[40];
1083 char commaNum2[40];
1084
1085 printTime("total time", totalTime, totalTime);
1086 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1087 if ( fgImagesUsedFromSharedCache != 0 )
1088 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
1089 else
1090 dyld::log("total images loaded: %d\n", imageCount);
1091 #else
1092 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
1093 #endif
1094 dyld::log("total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped, fgTotalBytesMapped/4096, fgTotalBytesPreFetched/4096);
1095 printTime("total images loading time", fgTotalLoadLibrariesTime, totalTime);
1096 printTime("total dtrace DOF registration time", fgTotalDOF, totalTime);
1097 dyld::log("total rebase fixups: %s\n", commatize(fgTotalRebaseFixups, commaNum1));
1098 printTime("total rebase fixups time", fgTotalRebaseTime, totalTime);
1099 dyld::log("total binding fixups: %s\n", commatize(fgTotalBindFixups, commaNum1));
1100 if ( fgTotalBindSymbolsResolved != 0 ) {
1101 uint32_t avgTimesTen = (fgTotalBindImageSearches * 10) / fgTotalBindSymbolsResolved;
1102 uint32_t avgInt = fgTotalBindImageSearches / fgTotalBindSymbolsResolved;
1103 uint32_t avgTenths = avgTimesTen - (avgInt*10);
1104 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1105 commatize(fgTotalBindSymbolsResolved, commaNum1), avgInt, avgTenths);
1106 }
1107 printTime("total binding fixups time", fgTotalBindTime, totalTime);
1108 printTime("total weak binding fixups time", fgTotalWeakBindTime, totalTime);
1109 dyld::log("total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups, commaNum1), commatize(fgTotalPossibleLazyBindFixups, commaNum2));
1110 printTime("total initializer time", fgTotalInitTime, totalTime);
1111 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1112 dyld::log("%21s ", timingInfo.images[i].image->getShortName());
1113 printTime("", timingInfo.images[i].initTime, totalTime);
1114 }
1115
1116 }
1117
1118
1119 //
1120 // copy path and add suffix to result
1121 //
1122 // /path/foo.dylib _debug => /path/foo_debug.dylib
1123 // foo.dylib _debug => foo_debug.dylib
1124 // foo _debug => foo_debug
1125 // /path/bar _debug => /path/bar_debug
1126 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1127 //
1128 void ImageLoader::addSuffix(const char* path, const char* suffix, char* result)
1129 {
1130 strcpy(result, path);
1131
1132 char* start = strrchr(result, '/');
1133 if ( start != NULL )
1134 start++;
1135 else
1136 start = result;
1137
1138 char* dot = strrchr(start, '.');
1139 if ( dot != NULL ) {
1140 strcpy(dot, suffix);
1141 strcat(&dot[strlen(suffix)], &path[dot-result]);
1142 }
1143 else {
1144 strcat(result, suffix);
1145 }
1146 }
1147
1148
1149 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple);
1150 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair);
1151
1152
1153