1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
25 #define __STDC_LIMIT_MACROS
29 #include <mach/mach.h>
30 #include <mach-o/fat.h>
31 #include <sys/types.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
36 #include <libkern/OSAtomic.h>
38 #include "ImageLoader.h"
41 uint32_t ImageLoader::fgImagesUsedFromSharedCache
= 0;
42 uint32_t ImageLoader::fgImagesWithUsedPrebinding
= 0;
43 uint32_t ImageLoader::fgImagesRequiringCoalescing
= 0;
44 uint32_t ImageLoader::fgImagesHasWeakDefinitions
= 0;
45 uint32_t ImageLoader::fgTotalRebaseFixups
= 0;
46 uint32_t ImageLoader::fgTotalBindFixups
= 0;
47 uint32_t ImageLoader::fgTotalBindSymbolsResolved
= 0;
48 uint32_t ImageLoader::fgTotalBindImageSearches
= 0;
49 uint32_t ImageLoader::fgTotalLazyBindFixups
= 0;
50 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups
= 0;
51 uint32_t ImageLoader::fgTotalSegmentsMapped
= 0;
52 uint64_t ImageLoader::fgTotalBytesMapped
= 0;
53 uint64_t ImageLoader::fgTotalBytesPreFetched
= 0;
54 uint64_t ImageLoader::fgTotalLoadLibrariesTime
;
55 uint64_t ImageLoader::fgTotalRebaseTime
;
56 uint64_t ImageLoader::fgTotalBindTime
;
57 uint64_t ImageLoader::fgTotalWeakBindTime
;
58 uint64_t ImageLoader::fgTotalDOF
;
59 uint64_t ImageLoader::fgTotalInitTime
;
60 uint16_t ImageLoader::fgLoadOrdinal
= 0;
61 std::vector
<ImageLoader::InterposeTuple
>ImageLoader::fgInterposingTuples
;
62 uintptr_t ImageLoader::fgNextPIEDylibAddress
= 0;
66 ImageLoader::ImageLoader(const char* path
, unsigned int libCount
)
67 : fPath(path
), fDevice(0), fInode(0), fLastModified(0),
68 fPathHash(0), fDlopenReferenceCount(0), fStaticReferenceCount(0),
69 fDynamicReferenceCount(0), fDynamicReferences(NULL
), 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), fWeakSymbolsBound(false)
78 fPathHash
= hash(fPath
);
82 void ImageLoader::deleteImage(ImageLoader
* image
)
84 // this cannot be done in destructor because libImage() is implemented
86 DependentLibraryInfo libraryInfos
[image
->libraryCount()];
87 image
->doGetDependentLibraries(libraryInfos
);
88 for(unsigned int i
=0; i
< image
->libraryCount(); ++i
) {
89 ImageLoader
* lib
= image
->libImage(i
);
90 if ( (lib
!= NULL
) && ! libraryInfos
[i
].upward
)
91 lib
->fStaticReferenceCount
--;
97 ImageLoader::~ImageLoader()
99 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
101 if ( fDynamicReferences
!= NULL
) {
102 for (std::vector
<const ImageLoader
*>::iterator it
= fDynamicReferences
->begin(); it
!= fDynamicReferences
->end(); ++it
) {
103 const_cast<ImageLoader
*>(*it
)->fDynamicReferenceCount
--;
105 delete fDynamicReferences
;
109 void ImageLoader::setFileInfo(dev_t device
, ino_t inode
, time_t modDate
)
113 fLastModified
= modDate
;
116 void ImageLoader::setMapped(const LinkContext
& context
)
118 fState
= dyld_image_state_mapped
;
119 context
.notifySingle(dyld_image_state_mapped
, this); // note: can throw exception
122 void ImageLoader::addDynamicReference(const ImageLoader
* target
)
124 bool alreadyInVector
= false;
125 if ( fDynamicReferences
== NULL
) {
126 fDynamicReferences
= new std::vector
<const ImageLoader
*>();
129 for (std::vector
<const ImageLoader
*>::iterator it
= fDynamicReferences
->begin(); it
!= fDynamicReferences
->end(); ++it
) {
130 if ( *it
== target
) {
131 alreadyInVector
= true;
136 if ( ! alreadyInVector
) {
137 fDynamicReferences
->push_back(target
);
138 const_cast<ImageLoader
*>(target
)->fDynamicReferenceCount
++;
140 //dyld::log("dyld: addDynamicReference() from %s to %s, fDynamicReferences->size()=%lu\n", this->getPath(), target->getPath(), fDynamicReferences->size());
143 int ImageLoader::compare(const ImageLoader
* right
) const
145 if ( this->fDepth
== right
->fDepth
) {
146 if ( this->fLoadOrder
== right
->fLoadOrder
)
148 else if ( this->fLoadOrder
< right
->fLoadOrder
)
154 if ( this->fDepth
< right
->fDepth
)
161 void ImageLoader::setPath(const char* path
)
163 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
165 fPath
= new char[strlen(path
)+1];
166 strcpy((char*)fPath
, path
);
167 fPathOwnedByImage
= true; // delete fPath when this image is destructed
168 fPathHash
= hash(fPath
);
171 void ImageLoader::setPathUnowned(const char* path
)
173 if ( fPathOwnedByImage
&& (fPath
!= NULL
) ) {
177 fPathOwnedByImage
= false;
178 fPathHash
= hash(fPath
);
182 uint32_t ImageLoader::hash(const char* path
)
184 // this does not need to be a great hash
185 // it is just used to reduce the number of strcmp() calls
186 // of existing images when loading a new image
188 for (const char* s
=path
; *s
!= '\0'; ++s
)
193 bool ImageLoader::matchInstallPath() const
195 return fMatchByInstallName
;
198 void ImageLoader::setMatchInstallPath(bool match
)
200 fMatchByInstallName
= match
;
203 bool ImageLoader::statMatch(const struct stat
& stat_buf
) const
205 return ( (this->fDevice
== stat_buf
.st_dev
) && (this->fInode
== stat_buf
.st_ino
) );
208 const char* ImageLoader::getShortName() const
210 // try to return leaf name
211 if ( fPath
!= NULL
) {
212 const char* s
= strrchr(fPath
, '/');
219 void ImageLoader::setLeaveMapped()
224 void ImageLoader::setHideExports(bool hide
)
229 bool ImageLoader::hasHiddenExports() const
234 bool ImageLoader::isLinked() const
236 return (fState
>= dyld_image_state_bound
);
239 time_t ImageLoader::lastModified() const
241 return fLastModified
;
244 bool ImageLoader::containsAddress(const void* addr
) const
246 if ( ! this->isLinked() )
248 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
249 const uint8_t* start
= (const uint8_t*)segActualLoadAddress(i
);
250 const uint8_t* end
= (const uint8_t*)segActualEndAddress(i
);
251 if ( (start
<= addr
) && (addr
< end
) && !segUnaccessible(i
) )
257 bool ImageLoader::overlapsWithAddressRange(const void* start
, const void* end
) const
259 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
260 const uint8_t* segStart
= (const uint8_t*)segActualLoadAddress(i
);
261 const uint8_t* segEnd
= (const uint8_t*)segActualEndAddress(i
);
262 if ( strcmp(segName(i
), "__UNIXSTACK") == 0 ) {
263 // __UNIXSTACK never slides. This is the only place that cares
264 // and checking for that segment name in segActualLoadAddress()
266 segStart
-= getSlide();
267 segEnd
-= getSlide();
269 if ( (start
<= segStart
) && (segStart
< end
) )
271 if ( (start
<= segEnd
) && (segEnd
< end
) )
273 if ( (segStart
< start
) && (end
< segEnd
) )
279 void ImageLoader::getMappedRegions(MappedRegion
*& regions
) const
281 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
283 region
.address
= segActualLoadAddress(i
);
284 region
.size
= segSize(i
);
290 static bool notInImgageList(const ImageLoader
* image
, const ImageLoader
** dsiStart
, const ImageLoader
** dsiCur
)
292 for (const ImageLoader
** p
= dsiStart
; p
< dsiCur
; ++p
)
299 // private method that handles circular dependencies by only search any image once
300 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name
,
301 const ImageLoader
** dsiStart
, const ImageLoader
**& dsiCur
, const ImageLoader
** dsiEnd
, const ImageLoader
** foundIn
) const
303 const ImageLoader::Symbol
* sym
;
306 if ( notInImgageList(this, dsiStart
, dsiCur
) ) {
307 sym
= this->findExportedSymbol(name
, false, foundIn
);
313 // search directly dependent libraries
314 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
315 ImageLoader
* dependentImage
= libImage(i
);
316 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
317 const ImageLoader::Symbol
* sym
= dependentImage
->findExportedSymbol(name
, false, foundIn
);
323 // search indirectly dependent libraries
324 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
325 ImageLoader
* dependentImage
= libImage(i
);
326 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
327 *dsiCur
++ = dependentImage
;
328 const ImageLoader::Symbol
* sym
= dependentImage
->findExportedSymbolInDependentImagesExcept(name
, dsiStart
, dsiCur
, dsiEnd
, foundIn
);
338 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
340 unsigned int imageCount
= context
.imageCount();
341 const ImageLoader
* dontSearchImages
[imageCount
];
342 dontSearchImages
[0] = this; // don't search this image
343 const ImageLoader
** cur
= &dontSearchImages
[1];
344 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
347 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
349 unsigned int imageCount
= context
.imageCount();
350 const ImageLoader
* dontSearchImages
[imageCount
];
351 const ImageLoader
** cur
= &dontSearchImages
[0];
352 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
355 // this is called by initializeMainExecutable() to interpose on the initial set of images
356 void ImageLoader::applyInterposing(const LinkContext
& context
)
358 if ( fgInterposingTuples
.size() != 0 )
359 this->recursiveApplyInterposing(context
);
362 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, const RPathChain
& loaderRPaths
)
364 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", this->getPath(), fStaticReferenceCount, fNeverUnload);
366 // clear error strings
367 (*context
.setErrorStrings
)(dyld_error_kind_none
, NULL
, NULL
, NULL
);
369 uint64_t t0
= mach_absolute_time();
370 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
);
371 context
.notifyBatch(dyld_image_state_dependents_mapped
);
373 // we only do the loading step for preflights
377 uint64_t t1
= mach_absolute_time();
378 context
.clearAllDepths();
379 this->recursiveUpdateDepth(context
.imageCount());
381 uint64_t t2
= mach_absolute_time();
382 this->recursiveRebase(context
);
383 context
.notifyBatch(dyld_image_state_rebased
);
385 uint64_t t3
= mach_absolute_time();
386 this->recursiveBind(context
, forceLazysBound
);
388 uint64_t t4
= mach_absolute_time();
389 this->weakBind(context
);
390 uint64_t t5
= mach_absolute_time();
392 context
.notifyBatch(dyld_image_state_bound
);
393 uint64_t t6
= mach_absolute_time();
395 std::vector
<DOFInfo
> dofs
;
396 this->recursiveGetDOFSections(context
, dofs
);
397 context
.registerDOFs(dofs
);
398 uint64_t t7
= mach_absolute_time();
400 // interpose any dynamically loaded images
401 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
402 this->recursiveApplyInterposing(context
);
405 // clear error strings
406 (*context
.setErrorStrings
)(dyld_error_kind_none
, NULL
, NULL
, NULL
);
408 fgTotalLoadLibrariesTime
+= t1
- t0
;
409 fgTotalRebaseTime
+= t3
- t2
;
410 fgTotalBindTime
+= t4
- t3
;
411 fgTotalWeakBindTime
+= t5
- t4
;
412 fgTotalDOF
+= t7
- t6
;
414 // done with initial dylib loads
415 fgNextPIEDylibAddress
= 0;
419 void ImageLoader::printReferenceCounts()
421 dyld::log(" dlopen=%d, static=%d, dynamic=%d for %s\n",
422 fDlopenReferenceCount
, fStaticReferenceCount
, fDynamicReferenceCount
, getPath() );
426 bool ImageLoader::decrementDlopenReferenceCount()
428 if ( fDlopenReferenceCount
== 0 )
430 --fDlopenReferenceCount
;
434 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
436 uint64_t t1
= mach_absolute_time();
437 mach_port_t this_thread
= mach_thread_self();
438 this->recursiveInitialization(context
, this_thread
, timingInfo
);
439 context
.notifyBatch(dyld_image_state_initialized
);
440 mach_port_deallocate(mach_task_self(), this_thread
);
441 uint64_t t2
= mach_absolute_time();
442 fgTotalInitTime
+= (t2
- t1
);
446 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
448 if ( ! fAllLazyPointersBound
) {
449 fAllLazyPointersBound
= true;
452 // bind lower level libraries first
453 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
454 ImageLoader
* dependentImage
= libImage(i
);
455 if ( dependentImage
!= NULL
)
456 dependentImage
->bindAllLazyPointers(context
, recursive
);
459 // bind lazies in this image
460 this->doBindJustLazies(context
);
465 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
467 return fAllLibraryChecksumsAndLoadAddressesMatch
;
471 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
)
473 // the purpose of this phase is to make the images sortable such that
474 // in a sort list of images, every image that an image depends on
475 // occurs in the list before it.
480 // get depth of dependents
481 unsigned int minDependentDepth
= maxDepth
;
482 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
483 ImageLoader
* dependentImage
= libImage(i
);
484 if ( dependentImage
!= NULL
) {
485 unsigned int d
= dependentImage
->recursiveUpdateDepth(maxDepth
);
486 if ( d
< minDependentDepth
)
487 minDependentDepth
= d
;
491 // make me less deep then all my dependents
492 fDepth
= minDependentDepth
- 1;
499 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
)
501 if ( fState
< dyld_image_state_dependents_mapped
) {
503 fState
= dyld_image_state_dependents_mapped
;
505 // get list of libraries this image needs
506 //dyld::log("ImageLoader::recursiveLoadLibraries() %ld = %d*%ld\n", fLibrariesCount*sizeof(DependentLibrary), fLibrariesCount, sizeof(DependentLibrary));
507 DependentLibraryInfo libraryInfos
[fLibraryCount
];
508 this->doGetDependentLibraries(libraryInfos
);
510 // get list of rpaths that this image adds
511 std::vector
<const char*> rpathsFromThisImage
;
512 this->getRPaths(context
, rpathsFromThisImage
);
513 const RPathChain
thisRPaths(&loaderRPaths
, &rpathsFromThisImage
);
516 bool canUsePrelinkingInfo
= true;
517 for(unsigned int i
=0; i
< fLibraryCount
; ++i
){
518 ImageLoader
* dependentLib
;
519 bool depLibReExported
= false;
520 bool depLibReRequired
= false;
521 bool depLibCheckSumsMatch
= false;
522 DependentLibraryInfo
& requiredLibInfo
= libraryInfos
[i
];
523 #if DYLD_SHARED_CACHE_SUPPORT
524 if ( preflightOnly
&& context
.inSharedCache(requiredLibInfo
.name
) ) {
525 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
526 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
527 setLibImage(i
, NULL
, false, false);
532 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, true, this->getPath(), &thisRPaths
);
533 if ( dependentLib
== this ) {
534 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
535 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, false, NULL
, NULL
);
536 if ( dependentLib
!= this )
537 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
540 dependentLib
->setNeverUnload();
541 if ( ! requiredLibInfo
.upward
)
542 dependentLib
->fStaticReferenceCount
+= 1;
543 LibraryInfo actualInfo
= dependentLib
->doGetLibraryInfo();
544 depLibReRequired
= requiredLibInfo
.required
;
545 depLibCheckSumsMatch
= ( actualInfo
.checksum
== requiredLibInfo
.info
.checksum
);
546 depLibReExported
= requiredLibInfo
.reExported
;
547 if ( ! depLibReExported
) {
548 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
549 depLibReExported
= dependentLib
->isSubframeworkOf(context
, this) || this->hasSubLibrary(context
, dependentLib
);
551 // check found library version is compatible
552 if ( actualInfo
.minVersion
< requiredLibInfo
.info
.minVersion
) {
553 // record values for possible use by CrashReporter or Finder
554 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
555 this->getShortName(), requiredLibInfo
.info
.minVersion
>> 16, (requiredLibInfo
.info
.minVersion
>> 8) & 0xff, requiredLibInfo
.info
.minVersion
& 0xff,
556 dependentLib
->getShortName(), actualInfo
.minVersion
>> 16, (actualInfo
.minVersion
>> 8) & 0xff, actualInfo
.minVersion
& 0xff);
558 // prebinding for this image disabled if any dependent library changed
559 if ( !depLibCheckSumsMatch
)
560 canUsePrelinkingInfo
= false;
561 // prebinding for this image disabled unless both this and dependent are in the shared cache
562 if ( !dependentLib
->inSharedCache() || !this->inSharedCache() )
563 canUsePrelinkingInfo
= false;
565 //if ( context.verbosePrebinding ) {
566 // if ( !requiredLib.checksumMatches )
567 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
568 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
569 // if ( dependentLib->getSlide() != 0 )
570 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
573 catch (const char* msg
) {
574 //if ( context.verbosePrebinding )
575 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
576 if ( requiredLibInfo
.required
) {
577 fState
= dyld_image_state_mapped
;
578 // record values for possible use by CrashReporter or Finder
579 if ( strstr(msg
, "Incompatible") != NULL
)
580 (*context
.setErrorStrings
)(dyld_error_kind_dylib_version
, this->getPath(), requiredLibInfo
.name
, NULL
);
581 else if ( strstr(msg
, "architecture") != NULL
)
582 (*context
.setErrorStrings
)(dyld_error_kind_dylib_wrong_arch
, this->getPath(), requiredLibInfo
.name
, NULL
);
584 (*context
.setErrorStrings
)(dyld_error_kind_dylib_missing
, this->getPath(), requiredLibInfo
.name
, NULL
);
585 dyld::throwf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo
.name
, this->getPath(), msg
);
587 // ok if weak library not found
589 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
591 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
593 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
595 // tell each to load its dependents
596 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
597 ImageLoader
* dependentImage
= libImage(i
);
598 if ( dependentImage
!= NULL
) {
599 dependentImage
->recursiveLoadLibraries(context
, preflightOnly
, thisRPaths
);
603 // do deep prebind check
604 if ( fAllLibraryChecksumsAndLoadAddressesMatch
) {
605 for(unsigned int i
=0; i
< libraryCount(); ++i
){
606 ImageLoader
* dependentImage
= libImage(i
);
607 if ( dependentImage
!= NULL
) {
608 if ( !dependentImage
->allDependentLibrariesAsWhenPreBound() )
609 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
614 // free rpaths (getRPaths() malloc'ed each string)
615 for(std::vector
<const char*>::iterator it
=rpathsFromThisImage
.begin(); it
!= rpathsFromThisImage
.end(); ++it
) {
616 const char* str
= *it
;
623 void ImageLoader::recursiveRebase(const LinkContext
& context
)
625 if ( fState
< dyld_image_state_rebased
) {
627 fState
= dyld_image_state_rebased
;
630 // rebase lower level libraries first
631 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
632 ImageLoader
* dependentImage
= libImage(i
);
633 if ( dependentImage
!= NULL
)
634 dependentImage
->recursiveRebase(context
);
641 context
.notifySingle(dyld_image_state_rebased
, this);
643 catch (const char* msg
) {
644 // this image is not rebased
645 fState
= dyld_image_state_dependents_mapped
;
646 CRSetCrashLogMessage2(NULL
);
652 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
654 if ( ! fInterposed
) {
659 // interpose lower level libraries first
660 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
661 ImageLoader
* dependentImage
= libImage(i
);
662 if ( dependentImage
!= NULL
)
663 dependentImage
->recursiveApplyInterposing(context
);
666 // interpose this image
667 doInterpose(context
);
669 catch (const char* msg
) {
670 // this image is not interposed
679 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
)
681 // Normally just non-lazy pointers are bound immediately.
682 // The exceptions are:
683 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
684 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
685 if ( fState
< dyld_image_state_bound
) {
687 fState
= dyld_image_state_bound
;
690 // bind lower level libraries first
691 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
692 ImageLoader
* dependentImage
= libImage(i
);
693 if ( dependentImage
!= NULL
)
694 dependentImage
->recursiveBind(context
, forceLazysBound
);
697 this->doBind(context
, forceLazysBound
);
698 // mark if lazys are also bound
699 if ( forceLazysBound
|| this->usablePrebinding(context
) )
700 fAllLazyPointersBound
= true;
702 context
.notifySingle(dyld_image_state_bound
, this);
704 catch (const char* msg
) {
706 fState
= dyld_image_state_rebased
;
707 CRSetCrashLogMessage2(NULL
);
713 void ImageLoader::weakBind(const LinkContext
& context
)
715 if ( context
.verboseWeakBind
)
716 dyld::log("dyld: weak bind start:\n");
717 // get set of ImageLoaders that participate in coalecsing
718 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
719 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
);
721 // count how many have not already had weakbinding done
722 int countNotYetWeakBound
= 0;
723 int countOfImagesWithWeakDefinitions
= 0;
724 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
725 for(int i
=0; i
< count
; ++i
) {
726 if ( ! imagesNeedingCoalescing
[i
]->fWeakSymbolsBound
)
727 ++countNotYetWeakBound
;
728 if ( imagesNeedingCoalescing
[i
]->hasCoalescedExports() ) {
729 ++countOfImagesWithWeakDefinitions
;
730 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
731 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
735 // don't need to do any coalescing if only one image has overrides, or all have already been done
736 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
737 // make symbol iterators for each
738 ImageLoader::CoalIterator iterators
[count
];
739 ImageLoader::CoalIterator
* sortedIts
[count
];
740 for(int i
=0; i
< count
; ++i
) {
741 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
);
742 sortedIts
[i
] = &iterators
[i
];
743 if ( context
.verboseWeakBind
)
744 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getPath());
747 // walk all symbols keeping iterators in sync by
748 // only ever incrementing the iterator with the lowest symbol
750 while ( doneCount
!= count
) {
751 //for(int i=0; i < count; ++i)
752 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
754 // increment iterator with lowest symbol
755 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
758 for(int i
=1; i
< count
; ++i
) {
759 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
761 sortedIts
[i
-1]->symbolMatches
= true;
763 // new one is bigger then next, so swap
764 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
765 sortedIts
[i
-1] = sortedIts
[i
];
771 // process all matching symbols just before incrementing the lowest one that matches
772 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
773 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
774 // pick first symbol in load order (and non-weak overrides weak)
775 uintptr_t targetAddr
= 0;
776 ImageLoader
* targetImage
= NULL
;
777 for(int i
=0; i
< count
; ++i
) {
778 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
779 if ( context
.verboseWeakBind
)
780 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getPath());
781 if ( iterators
[i
].weakSymbol
) {
782 if ( targetAddr
== 0 ) {
783 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
784 if ( targetAddr
!= 0 )
785 targetImage
= iterators
[i
].image
;
789 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
790 if ( targetAddr
!= 0 ) {
791 targetImage
= iterators
[i
].image
;
792 // strong implementation found, stop searching
798 if ( context
.verboseWeakBind
)
799 dyld::log("dyld: weak binding all uses of %s to copy from %s\n", nameToCoalesce
, targetImage
->getShortName());
801 // tell each to bind to this symbol (unless already bound)
802 if ( targetAddr
!= 0 ) {
803 for(int i
=0; i
< count
; ++i
) {
804 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
805 if ( context
.verboseWeakBind
)
806 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());
807 if ( ! iterators
[i
].image
->fWeakSymbolsBound
)
808 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, context
);
809 iterators
[i
].symbolMatches
= false;
817 // mark all as having all weak symbols bound
818 for(int i
=0; i
< count
; ++i
) {
819 imagesNeedingCoalescing
[i
]->fWeakSymbolsBound
= true;
822 if ( context
.verboseWeakBind
)
823 dyld::log("dyld: weak bind end\n");
828 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
830 if ( ! fRegisteredDOF
) {
832 fRegisteredDOF
= true;
834 // gather lower level libraries first
835 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
836 ImageLoader
* dependentImage
= libImage(i
);
837 if ( dependentImage
!= NULL
)
838 dependentImage
->recursiveGetDOFSections(context
, dofs
);
840 this->doGetDOFSections(context
, dofs
);
845 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
847 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
848 // keep trying until success (spin)
849 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
850 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
851 // the same thread we are on, the increment the lock count, otherwise continue to spin
852 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
855 ++(fInitializerRecursiveLock
->count
);
858 void ImageLoader::recursiveSpinUnLock()
860 if ( --(fInitializerRecursiveLock
->count
) == 0 )
861 fInitializerRecursiveLock
= NULL
;
865 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
, InitializerTimingList
& timingInfo
)
867 recursive_lock
lock_info(this_thread
);
868 recursiveSpinLock(lock_info
);
870 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
871 uint8_t oldState
= fState
;
873 fState
= dyld_image_state_dependents_initialized
-1;
875 // initialize lower level libraries first
876 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
877 ImageLoader
* dependentImage
= libImage(i
);
878 if ( dependentImage
!= NULL
)
879 // don't try to initialize stuff "above" me
880 if ( (dependentImage
!= NULL
) && (dependentImage
->fDepth
>= fDepth
) && !libIsUpward(i
) )
881 dependentImage
->recursiveInitialization(context
, this_thread
, timingInfo
);
884 // record termination order
885 if ( this->needsTermination() )
886 context
.terminationRecorder(this);
888 // let objc know we are about to initalize this image
889 uint64_t t1
= mach_absolute_time();
890 fState
= dyld_image_state_dependents_initialized
;
892 context
.notifySingle(dyld_image_state_dependents_initialized
, this);
894 // initialize this image
895 bool hasInitializers
= this->doInitialization(context
);
897 // let anyone know we finished initalizing this image
898 fState
= dyld_image_state_initialized
;
900 context
.notifySingle(dyld_image_state_initialized
, this);
902 if ( hasInitializers
) {
903 uint64_t t2
= mach_absolute_time();
904 timingInfo
.images
[timingInfo
.count
].image
= this;
905 timingInfo
.images
[timingInfo
.count
].initTime
= (t2
-t1
);
909 catch (const char* msg
) {
910 // this image is not initialized
912 recursiveSpinUnLock();
917 recursiveSpinUnLock();
921 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
923 static uint64_t sUnitsPerSecond
= 0;
924 if ( sUnitsPerSecond
== 0 ) {
925 struct mach_timebase_info timeBaseInfo
;
926 if ( mach_timebase_info(&timeBaseInfo
) == KERN_SUCCESS
) {
927 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
930 if ( partTime
< sUnitsPerSecond
) {
931 uint32_t milliSecondsTimesHundred
= (partTime
*100000)/sUnitsPerSecond
;
932 uint32_t milliSeconds
= milliSecondsTimesHundred
/100;
933 uint32_t percentTimesTen
= (partTime
*1000)/totalTime
;
934 uint32_t percent
= percentTimesTen
/10;
935 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
938 uint32_t secondsTimeTen
= (partTime
*10)/sUnitsPerSecond
;
939 uint32_t seconds
= secondsTimeTen
/10;
940 uint32_t percentTimesTen
= (partTime
*1000)/totalTime
;
941 uint32_t percent
= percentTimesTen
/10;
942 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
946 static char* commatize(uint64_t in
, char* out
)
948 uint64_t div10
= in
/ 10;
949 uint8_t delta
= in
- div10
*10;
953 *(--s
) = '0' + delta
;
956 if ( (digitCount
% 3) == 0 )
959 delta
= in
- div10
*10;
960 *(--s
) = '0' + delta
;
968 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
970 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
974 printTime("total time", totalTime
, totalTime
);
975 #if __IPHONE_OS_VERSION_MIN_REQUIRED
976 if ( fgImagesUsedFromSharedCache
!= 0 )
977 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
979 dyld::log("total images loaded: %d\n", imageCount
);
981 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
983 dyld::log("total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096, fgTotalBytesPreFetched
/4096);
984 printTime("total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
985 printTime("total dtrace DOF registration time", fgTotalDOF
, totalTime
);
986 dyld::log("total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
987 printTime("total rebase fixups time", fgTotalRebaseTime
, totalTime
);
988 dyld::log("total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
989 if ( fgTotalBindSymbolsResolved
!= 0 ) {
990 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
991 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
992 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
993 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
994 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
996 printTime("total binding fixups time", fgTotalBindTime
, totalTime
);
997 printTime("total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
998 dyld::log("total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
999 printTime("total initializer time", fgTotalInitTime
, totalTime
);
1000 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1001 dyld::log("%21s ", timingInfo
.images
[i
].image
->getShortName());
1002 printTime("", timingInfo
.images
[i
].initTime
, totalTime
);
1009 // copy path and add suffix to result
1011 // /path/foo.dylib _debug => /path/foo_debug.dylib
1012 // foo.dylib _debug => foo_debug.dylib
1013 // foo _debug => foo_debug
1014 // /path/bar _debug => /path/bar_debug
1015 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1017 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1019 strcpy(result
, path
);
1021 char* start
= strrchr(result
, '/');
1022 if ( start
!= NULL
)
1027 char* dot
= strrchr(start
, '.');
1028 if ( dot
!= NULL
) {
1029 strcpy(dot
, suffix
);
1030 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1033 strcat(result
, suffix
);