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
30 #include <mach/mach.h>
31 #include <mach-o/fat.h>
32 #include <sys/types.h>
35 #include <sys/param.h>
36 #include <sys/mount.h>
37 #include <libkern/OSAtomic.h>
39 #include "ImageLoader.h"
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;
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)
79 fPathHash
= hash(fPath
);
81 dyld::throwf("too many dependent dylibs in %s", path
);
85 void ImageLoader::deleteImage(ImageLoader
* image
)
91 ImageLoader::~ImageLoader()
93 if ( fRealPath
!= NULL
)
95 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
99 void ImageLoader::setFileInfo(dev_t device
, ino_t inode
, time_t modDate
)
103 fLastModified
= modDate
;
106 void ImageLoader::setMapped(const LinkContext
& context
)
108 fState
= dyld_image_state_mapped
;
109 context
.notifySingle(dyld_image_state_mapped
, this); // note: can throw exception
112 int ImageLoader::compare(const ImageLoader
* right
) const
114 if ( this->fDepth
== right
->fDepth
) {
115 if ( this->fLoadOrder
== right
->fLoadOrder
)
117 else if ( this->fLoadOrder
< right
->fLoadOrder
)
123 if ( this->fDepth
< right
->fDepth
)
130 void ImageLoader::setPath(const char* path
)
132 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
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
);
141 void ImageLoader::setPathUnowned(const char* path
)
143 if ( fPathOwnedByImage
&& (fPath
!= NULL
) ) {
147 fPathOwnedByImage
= false;
148 fPathHash
= hash(fPath
);
151 void ImageLoader::setPaths(const char* path
, const char* realPath
)
154 fRealPath
= new char[strlen(realPath
)+1];
155 strcpy((char*)fRealPath
, realPath
);
158 const char* ImageLoader::getRealPath() const
160 if ( fRealPath
!= NULL
)
167 uint32_t ImageLoader::hash(const char* path
)
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
173 for (const char* s
=path
; *s
!= '\0'; ++s
)
178 bool ImageLoader::matchInstallPath() const
180 return fMatchByInstallName
;
183 void ImageLoader::setMatchInstallPath(bool match
)
185 fMatchByInstallName
= match
;
188 bool ImageLoader::statMatch(const struct stat
& stat_buf
) const
190 return ( (this->fDevice
== stat_buf
.st_dev
) && (this->fInode
== stat_buf
.st_ino
) );
193 const char* ImageLoader::getShortName() const
195 // try to return leaf name
196 if ( fPath
!= NULL
) {
197 const char* s
= strrchr(fPath
, '/');
204 void ImageLoader::setLeaveMapped()
209 void ImageLoader::setHideExports(bool hide
)
214 bool ImageLoader::hasHiddenExports() const
219 bool ImageLoader::isLinked() const
221 return (fState
>= dyld_image_state_bound
);
224 time_t ImageLoader::lastModified() const
226 return fLastModified
;
229 bool ImageLoader::containsAddress(const void* addr
) const
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
) )
240 bool ImageLoader::overlapsWithAddressRange(const void* start
, const void* end
) const
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()
249 segStart
-= getSlide();
250 segEnd
-= getSlide();
252 if ( (start
<= segStart
) && (segStart
< end
) )
254 if ( (start
<= segEnd
) && (segEnd
< end
) )
256 if ( (segStart
< start
) && (end
< segEnd
) )
262 void ImageLoader::getMappedRegions(MappedRegion
*& regions
) const
264 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
266 region
.address
= segActualLoadAddress(i
);
267 region
.size
= segSize(i
);
274 bool ImageLoader::dependsOn(ImageLoader
* image
) {
275 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
276 if ( libImage(i
) == image
)
283 static bool notInImgageList(const ImageLoader
* image
, const ImageLoader
** dsiStart
, const ImageLoader
** dsiCur
)
285 for (const ImageLoader
** p
= dsiStart
; p
< dsiCur
; ++p
)
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
296 const ImageLoader::Symbol
* sym
;
298 if ( notInImgageList(this, dsiStart
, dsiCur
) ) {
299 sym
= this->findExportedSymbol(name
, false, foundIn
);
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
);
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
);
330 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
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
);
339 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
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
);
347 // this is called by initializeMainExecutable() to interpose on the initial set of images
348 void ImageLoader::applyInterposing(const LinkContext
& context
)
350 if ( fgInterposingTuples
.size() != 0 )
351 this->recursiveApplyInterposing(context
);
355 uintptr_t ImageLoader::interposedAddress(const LinkContext
& context
, uintptr_t address
, const ImageLoader
* inImage
, const ImageLoader
* onlyInImage
)
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
);
366 return it
->replacement
;
372 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array
[], size_t count
)
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
;
386 ImageLoader::fgInterposingTuples
.push_back(tuple
);
391 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, bool neverUnload
, const RPathChain
& loaderRPaths
)
393 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", this->getPath(), fDlopenReferenceCount, fNeverUnload);
395 // clear error strings
396 (*context
.setErrorStrings
)(dyld_error_kind_none
, NULL
, NULL
, NULL
);
398 uint64_t t0
= mach_absolute_time();
399 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
);
400 context
.notifyBatch(dyld_image_state_dependents_mapped
);
402 // we only do the loading step for preflights
406 uint64_t t1
= mach_absolute_time();
407 context
.clearAllDepths();
408 this->recursiveUpdateDepth(context
.imageCount());
410 uint64_t t2
= mach_absolute_time();
411 this->recursiveRebase(context
);
412 context
.notifyBatch(dyld_image_state_rebased
);
414 uint64_t t3
= mach_absolute_time();
415 this->recursiveBind(context
, forceLazysBound
, neverUnload
);
417 uint64_t t4
= mach_absolute_time();
418 if ( !context
.linkingMainExecutable
)
419 this->weakBind(context
);
420 uint64_t t5
= mach_absolute_time();
422 context
.notifyBatch(dyld_image_state_bound
);
423 uint64_t t6
= mach_absolute_time();
425 std::vector
<DOFInfo
> dofs
;
426 this->recursiveGetDOFSections(context
, dofs
);
427 context
.registerDOFs(dofs
);
428 uint64_t t7
= mach_absolute_time();
430 // interpose any dynamically loaded images
431 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
432 this->recursiveApplyInterposing(context
);
435 // clear error strings
436 (*context
.setErrorStrings
)(dyld_error_kind_none
, NULL
, NULL
, NULL
);
438 fgTotalLoadLibrariesTime
+= t1
- t0
;
439 fgTotalRebaseTime
+= t3
- t2
;
440 fgTotalBindTime
+= t4
- t3
;
441 fgTotalWeakBindTime
+= t5
- t4
;
442 fgTotalDOF
+= t7
- t6
;
444 // done with initial dylib loads
445 fgNextPIEDylibAddress
= 0;
449 void ImageLoader::printReferenceCounts()
451 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount
, getPath() );
455 bool ImageLoader::decrementDlopenReferenceCount()
457 if ( fDlopenReferenceCount
== 0 )
459 --fDlopenReferenceCount
;
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
468 void ImageLoader::processInitializers(const LinkContext
& context
, mach_port_t thisThread
,
469 InitializerTimingList
& timingInfo
, ImageLoader::UninitedUpwards
& images
)
471 uint32_t maxImageCount
= context
.imageCount();
472 ImageLoader::UninitedUpwards upsBuffer
[maxImageCount
];
473 ImageLoader::UninitedUpwards
& ups
= upsBuffer
[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
);
480 // If any upward dependencies remain, init them.
482 processInitializers(context
, thisThread
, timingInfo
, ups
);
486 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
488 uint64_t t1
= mach_absolute_time();
489 mach_port_t thisThread
= mach_thread_self();
490 ImageLoader::UninitedUpwards up
;
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
);
501 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
503 if ( ! fAllLazyPointersBound
) {
504 fAllLazyPointersBound
= true;
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
);
514 // bind lazies in this image
515 this->doBindJustLazies(context
);
520 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
522 return fAllLibraryChecksumsAndLoadAddressesMatch
;
526 void ImageLoader::markedUsedRecursive(const std::vector
<DynamicReference
>& dynamicReferences
)
528 // already visited here
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
);
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
);
549 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
)
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.
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
;
569 // make me less deep then all my dependents
570 fDepth
= minDependentDepth
- 1;
577 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
)
579 if ( fState
< dyld_image_state_dependents_mapped
) {
581 fState
= dyld_image_state_dependents_mapped
;
583 // get list of libraries this image needs
584 DependentLibraryInfo libraryInfos
[fLibraryCount
];
585 this->doGetDependentLibraries(libraryInfos
);
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
);
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);
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());
617 dependentLib
->setNeverUnload();
618 if ( requiredLibInfo
.upward
) {
621 dependentLib
->fIsReferencedDownward
= true;
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
);
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);
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;
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());
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
);
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
670 free((void*)msg
); // our free() will do nothing if msg is a string literal
671 // ok if weak library not found
673 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
675 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
677 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
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
);
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;
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
;
707 void ImageLoader::recursiveRebase(const LinkContext
& context
)
709 if ( fState
< dyld_image_state_rebased
) {
711 fState
= dyld_image_state_rebased
;
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
);
725 context
.notifySingle(dyld_image_state_rebased
, this);
727 catch (const char* msg
) {
728 // this image is not rebased
729 fState
= dyld_image_state_dependents_mapped
;
730 CRSetCrashLogMessage2(NULL
);
736 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
738 if ( ! fInterposed
) {
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
);
750 // interpose this image
751 doInterpose(context
);
753 catch (const char* msg
) {
754 // this image is not interposed
763 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
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
) {
771 fState
= dyld_image_state_bound
;
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
);
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
787 this->setNeverUnload();
789 context
.notifySingle(dyld_image_state_bound
, this);
791 catch (const char* msg
) {
793 fState
= dyld_image_state_rebased
;
794 CRSetCrashLogMessage2(NULL
);
800 void ImageLoader::weakBind(const LinkContext
& context
)
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
);
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
;
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());
835 // walk all symbols keeping iterators in sync by
836 // only ever incrementing the iterator with the lowest symbol
838 while ( doneCount
!= count
) {
839 //for(int i=0; i < count; ++i)
840 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
842 // increment iterator with lowest symbol
843 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
846 for(int i
=1; i
< count
; ++i
) {
847 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
849 sortedIts
[i
-1]->symbolMatches
= true;
851 // new one is bigger then next, so swap
852 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
853 sortedIts
[i
-1] = sortedIts
[i
];
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
;
877 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
878 if ( targetAddr
!= 0 ) {
879 targetImage
= iterators
[i
].image
;
880 // strong implementation found, stop searching
886 // tell each to bind to this symbol (unless already bound)
887 if ( targetAddr
!= 0 ) {
888 if ( context
.verboseWeakBind
)
889 dyld::log("dyld: weak binding all uses of %s to copy from %s\n", nameToCoalesce
, targetImage
->getShortName());
890 for(int i
=0; i
< count
; ++i
) {
891 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
892 if ( context
.verboseWeakBind
)
893 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());
894 if ( ! iterators
[i
].image
->fWeakSymbolsBound
)
895 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, context
);
896 iterators
[i
].symbolMatches
= false;
904 // mark all as having all weak symbols bound
905 for(int i
=0; i
< count
; ++i
) {
906 imagesNeedingCoalescing
[i
]->fWeakSymbolsBound
= true;
909 uint64_t t2
= mach_absolute_time();
910 fgTotalWeakBindTime
+= t2
- t1
;
912 if ( context
.verboseWeakBind
)
913 dyld::log("dyld: weak bind end\n");
918 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
920 if ( ! fRegisteredDOF
) {
922 fRegisteredDOF
= true;
924 // gather lower level libraries first
925 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
926 ImageLoader
* dependentImage
= libImage(i
);
927 if ( dependentImage
!= NULL
)
928 dependentImage
->recursiveGetDOFSections(context
, dofs
);
930 this->doGetDOFSections(context
, dofs
);
934 void ImageLoader::setNeverUnloadRecursive() {
935 if ( ! fNeverUnload
) {
939 // gather lower level libraries first
940 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
941 ImageLoader
* dependentImage
= libImage(i
);
942 if ( dependentImage
!= NULL
)
943 dependentImage
->setNeverUnloadRecursive();
948 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
950 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
951 // keep trying until success (spin)
952 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
953 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
954 // the same thread we are on, the increment the lock count, otherwise continue to spin
955 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
958 ++(fInitializerRecursiveLock
->count
);
961 void ImageLoader::recursiveSpinUnLock()
963 if ( --(fInitializerRecursiveLock
->count
) == 0 )
964 fInitializerRecursiveLock
= NULL
;
968 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
,
969 InitializerTimingList
& timingInfo
, UninitedUpwards
& uninitUps
)
971 recursive_lock
lock_info(this_thread
);
972 recursiveSpinLock(lock_info
);
974 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
975 uint8_t oldState
= fState
;
977 fState
= dyld_image_state_dependents_initialized
-1;
979 // initialize lower level libraries first
980 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
981 ImageLoader
* dependentImage
= libImage(i
);
982 if ( dependentImage
!= NULL
) {
983 // don't try to initialize stuff "above" me yet
984 if ( libIsUpward(i
) ) {
985 uninitUps
.images
[uninitUps
.count
] = dependentImage
;
988 else if ( dependentImage
->fDepth
>= fDepth
) {
989 dependentImage
->recursiveInitialization(context
, this_thread
, timingInfo
, uninitUps
);
994 // record termination order
995 if ( this->needsTermination() )
996 context
.terminationRecorder(this);
998 // let objc know we are about to initialize this image
999 uint64_t t1
= mach_absolute_time();
1000 fState
= dyld_image_state_dependents_initialized
;
1002 context
.notifySingle(dyld_image_state_dependents_initialized
, this);
1004 // initialize this image
1005 bool hasInitializers
= this->doInitialization(context
);
1007 // let anyone know we finished initializing this image
1008 fState
= dyld_image_state_initialized
;
1010 context
.notifySingle(dyld_image_state_initialized
, this);
1012 if ( hasInitializers
) {
1013 uint64_t t2
= mach_absolute_time();
1014 timingInfo
.images
[timingInfo
.count
].image
= this;
1015 timingInfo
.images
[timingInfo
.count
].initTime
= (t2
-t1
);
1019 catch (const char* msg
) {
1020 // this image is not initialized
1022 recursiveSpinUnLock();
1027 recursiveSpinUnLock();
1031 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
1033 static uint64_t sUnitsPerSecond
= 0;
1034 if ( sUnitsPerSecond
== 0 ) {
1035 struct mach_timebase_info timeBaseInfo
;
1036 if ( mach_timebase_info(&timeBaseInfo
) == KERN_SUCCESS
) {
1037 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
1040 if ( partTime
< sUnitsPerSecond
) {
1041 uint32_t milliSecondsTimesHundred
= (uint32_t)((partTime
*100000)/sUnitsPerSecond
);
1042 uint32_t milliSeconds
= (uint32_t)(milliSecondsTimesHundred
/100);
1043 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1044 uint32_t percent
= percentTimesTen
/10;
1045 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1048 uint32_t secondsTimeTen
= (uint32_t)((partTime
*10)/sUnitsPerSecond
);
1049 uint32_t seconds
= secondsTimeTen
/10;
1050 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1051 uint32_t percent
= percentTimesTen
/10;
1052 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
1056 static char* commatize(uint64_t in
, char* out
)
1058 uint64_t div10
= in
/ 10;
1059 uint8_t delta
= in
- div10
*10;
1063 *(--s
) = '0' + delta
;
1066 if ( (digitCount
% 3) == 0 )
1069 delta
= in
- div10
*10;
1070 *(--s
) = '0' + delta
;
1078 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1080 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1084 printTime("total time", totalTime
, totalTime
);
1085 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1086 if ( fgImagesUsedFromSharedCache
!= 0 )
1087 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1089 dyld::log("total images loaded: %d\n", imageCount
);
1091 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1093 dyld::log("total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096, fgTotalBytesPreFetched
/4096);
1094 printTime("total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
1095 printTime("total dtrace DOF registration time", fgTotalDOF
, totalTime
);
1096 dyld::log("total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
1097 printTime("total rebase fixups time", fgTotalRebaseTime
, totalTime
);
1098 dyld::log("total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
1099 if ( fgTotalBindSymbolsResolved
!= 0 ) {
1100 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
1101 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
1102 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
1103 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1104 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
1106 printTime("total binding fixups time", fgTotalBindTime
, totalTime
);
1107 printTime("total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
1108 dyld::log("total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
1109 printTime("total initializer time", fgTotalInitTime
, totalTime
);
1110 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1111 dyld::log("%21s ", timingInfo
.images
[i
].image
->getShortName());
1112 printTime("", timingInfo
.images
[i
].initTime
, totalTime
);
1119 // copy path and add suffix to result
1121 // /path/foo.dylib _debug => /path/foo_debug.dylib
1122 // foo.dylib _debug => foo_debug.dylib
1123 // foo _debug => foo_debug
1124 // /path/bar _debug => /path/bar_debug
1125 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1127 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1129 strcpy(result
, path
);
1131 char* start
= strrchr(result
, '/');
1132 if ( start
!= NULL
)
1137 char* dot
= strrchr(start
, '.');
1138 if ( dot
!= NULL
) {
1139 strcpy(dot
, suffix
);
1140 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1143 strcat(result
, suffix
);
1148 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple
);
1149 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair
);