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 <sys/sysctl.h>
38 #include <libkern/OSAtomic.h>
42 #include "ImageLoader.h"
45 uint32_t ImageLoader::fgImagesUsedFromSharedCache
= 0;
46 uint32_t ImageLoader::fgImagesWithUsedPrebinding
= 0;
47 uint32_t ImageLoader::fgImagesRequiringCoalescing
= 0;
48 uint32_t ImageLoader::fgImagesHasWeakDefinitions
= 0;
49 uint32_t ImageLoader::fgTotalRebaseFixups
= 0;
50 uint32_t ImageLoader::fgTotalBindFixups
= 0;
51 uint32_t ImageLoader::fgTotalBindSymbolsResolved
= 0;
52 uint32_t ImageLoader::fgTotalBindImageSearches
= 0;
53 uint32_t ImageLoader::fgTotalLazyBindFixups
= 0;
54 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups
= 0;
55 uint32_t ImageLoader::fgTotalSegmentsMapped
= 0;
56 uint64_t ImageLoader::fgTotalBytesMapped
= 0;
57 uint64_t ImageLoader::fgTotalBytesPreFetched
= 0;
58 uint64_t ImageLoader::fgTotalLoadLibrariesTime
;
59 uint64_t ImageLoader::fgTotalObjCSetupTime
= 0;
60 uint64_t ImageLoader::fgTotalDebuggerPausedTime
= 0;
61 uint64_t ImageLoader::fgTotalRebindCacheTime
= 0;
62 uint64_t ImageLoader::fgTotalRebaseTime
;
63 uint64_t ImageLoader::fgTotalBindTime
;
64 uint64_t ImageLoader::fgTotalWeakBindTime
;
65 uint64_t ImageLoader::fgTotalDOF
;
66 uint64_t ImageLoader::fgTotalInitTime
;
67 uint16_t ImageLoader::fgLoadOrdinal
= 0;
68 uint32_t ImageLoader::fgSymbolTrieSearchs
= 0;
69 std::vector
<ImageLoader::InterposeTuple
>ImageLoader::fgInterposingTuples
;
70 uintptr_t ImageLoader::fgNextPIEDylibAddress
= 0;
74 ImageLoader::ImageLoader(const char* path
, unsigned int libCount
)
75 : fPath(path
), fRealPath(NULL
), fDevice(0), fInode(0), fLastModified(0),
76 fPathHash(0), fDlopenReferenceCount(0), fInitializerRecursiveLock(NULL
),
77 fDepth(0), fLoadOrder(fgLoadOrdinal
++), fState(0), fLibraryCount(libCount
),
78 fAllLibraryChecksumsAndLoadAddressesMatch(false), fLeaveMapped(false), fNeverUnload(false),
79 fHideSymbols(false), fMatchByInstallName(false),
80 fInterposed(false), fRegisteredDOF(false), fAllLazyPointersBound(false),
81 fBeingRemoved(false), fAddFuncNotified(false),
82 fPathOwnedByImage(false), fIsReferencedDownward(false),
83 fWeakSymbolsBound(false)
86 fPathHash
= hash(fPath
);
88 dyld::throwf("too many dependent dylibs in %s", path
);
92 void ImageLoader::deleteImage(ImageLoader
* image
)
98 ImageLoader::~ImageLoader()
100 if ( fRealPath
!= NULL
)
102 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
106 void ImageLoader::setFileInfo(dev_t device
, ino_t inode
, time_t modDate
)
110 fLastModified
= modDate
;
113 void ImageLoader::setMapped(const LinkContext
& context
)
115 fState
= dyld_image_state_mapped
;
116 context
.notifySingle(dyld_image_state_mapped
, this, NULL
); // note: can throw exception
119 int ImageLoader::compare(const ImageLoader
* right
) const
121 if ( this->fDepth
== right
->fDepth
) {
122 if ( this->fLoadOrder
== right
->fLoadOrder
)
124 else if ( this->fLoadOrder
< right
->fLoadOrder
)
130 if ( this->fDepth
< right
->fDepth
)
137 void ImageLoader::setPath(const char* path
)
139 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
141 fPath
= new char[strlen(path
)+1];
142 strcpy((char*)fPath
, path
);
143 fPathOwnedByImage
= true; // delete fPath when this image is destructed
144 fPathHash
= hash(fPath
);
148 void ImageLoader::setPathUnowned(const char* path
)
150 if ( fPathOwnedByImage
&& (fPath
!= NULL
) ) {
154 fPathOwnedByImage
= false;
155 fPathHash
= hash(fPath
);
158 void ImageLoader::setPaths(const char* path
, const char* realPath
)
161 fRealPath
= new char[strlen(realPath
)+1];
162 strcpy((char*)fRealPath
, realPath
);
165 const char* ImageLoader::getRealPath() const
167 if ( fRealPath
!= NULL
)
174 uint32_t ImageLoader::hash(const char* path
)
176 // this does not need to be a great hash
177 // it is just used to reduce the number of strcmp() calls
178 // of existing images when loading a new image
180 for (const char* s
=path
; *s
!= '\0'; ++s
)
185 bool ImageLoader::matchInstallPath() const
187 return fMatchByInstallName
;
190 void ImageLoader::setMatchInstallPath(bool match
)
192 fMatchByInstallName
= match
;
195 bool ImageLoader::statMatch(const struct stat
& stat_buf
) const
197 return ( (this->fDevice
== stat_buf
.st_dev
) && (this->fInode
== stat_buf
.st_ino
) );
200 const char* ImageLoader::shortName(const char* fullName
)
202 // try to return leaf name
203 if ( fullName
!= NULL
) {
204 const char* s
= strrchr(fullName
, '/');
211 const char* ImageLoader::getShortName() const
213 return shortName(fPath
);
216 void ImageLoader::setLeaveMapped()
221 void ImageLoader::setHideExports(bool hide
)
226 bool ImageLoader::hasHiddenExports() const
231 bool ImageLoader::isLinked() const
233 return (fState
>= dyld_image_state_bound
);
236 time_t ImageLoader::lastModified() const
238 return fLastModified
;
241 bool ImageLoader::containsAddress(const void* addr
) const
243 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
244 const uint8_t* start
= (const uint8_t*)segActualLoadAddress(i
);
245 const uint8_t* end
= (const uint8_t*)segActualEndAddress(i
);
246 if ( (start
<= addr
) && (addr
< end
) && !segUnaccessible(i
) )
252 bool ImageLoader::overlapsWithAddressRange(const void* start
, const void* end
) const
254 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
255 const uint8_t* segStart
= (const uint8_t*)segActualLoadAddress(i
);
256 const uint8_t* segEnd
= (const uint8_t*)segActualEndAddress(i
);
257 if ( strcmp(segName(i
), "__UNIXSTACK") == 0 ) {
258 // __UNIXSTACK never slides. This is the only place that cares
259 // and checking for that segment name in segActualLoadAddress()
261 segStart
-= getSlide();
262 segEnd
-= getSlide();
264 if ( (start
<= segStart
) && (segStart
< end
) )
266 if ( (start
<= segEnd
) && (segEnd
< end
) )
268 if ( (segStart
< start
) && (end
< segEnd
) )
274 void ImageLoader::getMappedRegions(MappedRegion
*& regions
) const
276 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
278 region
.address
= segActualLoadAddress(i
);
279 region
.size
= segSize(i
);
286 bool ImageLoader::dependsOn(ImageLoader
* image
) {
287 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
288 if ( libImage(i
) == image
)
295 static bool notInImgageList(const ImageLoader
* image
, const ImageLoader
** dsiStart
, const ImageLoader
** dsiCur
)
297 for (const ImageLoader
** p
= dsiStart
; p
< dsiCur
; ++p
)
303 bool ImageLoader::findExportedSymbolAddress(const LinkContext
& context
, const char* symbolName
,
304 const ImageLoader
* requestorImage
, int requestorOrdinalOfDef
,
305 bool runResolver
, const ImageLoader
** foundIn
, uintptr_t* address
) const
307 const Symbol
* sym
= this->findExportedSymbol(symbolName
, true, foundIn
);
309 *address
= (*foundIn
)->getExportedSymbolAddress(sym
, context
, requestorImage
, runResolver
);
316 // private method that handles circular dependencies by only search any image once
317 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name
,
318 const ImageLoader
** dsiStart
, const ImageLoader
**& dsiCur
, const ImageLoader
** dsiEnd
, const ImageLoader
** foundIn
) const
320 const ImageLoader::Symbol
* sym
;
322 if ( notInImgageList(this, dsiStart
, dsiCur
) ) {
323 sym
= this->findExportedSymbol(name
, false, this->getPath(), foundIn
);
329 // search directly dependent libraries
330 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
331 ImageLoader
* dependentImage
= libImage(i
);
332 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
333 sym
= dependentImage
->findExportedSymbol(name
, false, libPath(i
), foundIn
);
339 // search indirectly dependent libraries
340 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
341 ImageLoader
* dependentImage
= libImage(i
);
342 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
343 *dsiCur
++ = dependentImage
;
344 sym
= dependentImage
->findExportedSymbolInDependentImagesExcept(name
, dsiStart
, dsiCur
, dsiEnd
, foundIn
);
354 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
356 unsigned int imageCount
= context
.imageCount()+2;
357 const ImageLoader
* dontSearchImages
[imageCount
];
358 dontSearchImages
[0] = this; // don't search this image
359 const ImageLoader
** cur
= &dontSearchImages
[1];
360 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
363 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
365 unsigned int imageCount
= context
.imageCount()+2;
366 const ImageLoader
* dontSearchImages
[imageCount
];
367 const ImageLoader
** cur
= &dontSearchImages
[0];
368 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
371 // this is called by initializeMainExecutable() to interpose on the initial set of images
372 void ImageLoader::applyInterposing(const LinkContext
& context
)
374 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
375 if ( fgInterposingTuples
.size() != 0 )
376 this->recursiveApplyInterposing(context
);
380 uintptr_t ImageLoader::interposedAddress(const LinkContext
& context
, uintptr_t address
, const ImageLoader
* inImage
, const ImageLoader
* onlyInImage
)
382 //dyld::log("interposedAddress(0x%08llX), tupleCount=%lu\n", (uint64_t)address, fgInterposingTuples.size());
383 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
384 //dyld::log(" interposedAddress: replacee=0x%08llX, replacement=0x%08llX, neverImage=%p, onlyImage=%p, inImage=%p\n",
385 // (uint64_t)it->replacee, (uint64_t)it->replacement, it->neverImage, it->onlyImage, inImage);
386 // replace all references to 'replacee' with 'replacement'
387 if ( (address
== it
->replacee
) && (inImage
!= it
->neverImage
) && ((it
->onlyImage
== NULL
) || (inImage
== it
->onlyImage
)) ) {
388 if ( context
.verboseInterposing
) {
389 dyld::log("dyld interposing: replace 0x%lX with 0x%lX\n", it
->replacee
, it
->replacement
);
391 return it
->replacement
;
397 void ImageLoader::applyInterposingToDyldCache(const LinkContext
& context
) {
398 #if USES_CHAINED_BINDS
399 if (!context
.dyldCache
)
401 if (fgInterposingTuples
.empty())
403 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
404 // that image and apply its patch table to all uses.
405 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
406 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
407 if ( context
.verboseInterposing
)
408 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it
->replacee
);
410 uint32_t cacheOffsetOfReplacee
= (uint32_t)(it
->replacee
- cacheStart
);
411 if (!context
.dyldCache
->addressInText(cacheOffsetOfReplacee
, &imageIndex
))
413 dyld3::closure::ImageNum imageInCache
= imageIndex
+1;
414 if ( context
.verboseInterposing
)
415 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache
, (uint64_t)it
->replacee
);
416 const dyld3::closure::Image
* image
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageInCache
);
417 image
->forEachPatchableExport(^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
418 // Skip patching anything other than this symbol
419 if (cacheOffsetOfImpl
!= cacheOffsetOfReplacee
)
421 if ( context
.verboseInterposing
)
422 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName
, image
->path());
423 uintptr_t newLoc
= it
->replacement
;
424 image
->forEachPatchableUseOfExport(cacheOffsetOfImpl
, ^(dyld3::closure::Image::PatchableExport::PatchLocation patchLocation
) {
425 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
426 #if __has_feature(ptrauth_calls)
427 if ( patchLocation
.authenticated
) {
428 dyld3::MachOLoaded::ChainedFixupPointerOnDisk fixupInfo
;
429 fixupInfo
.authRebase
.auth
= true;
430 fixupInfo
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
431 fixupInfo
.authRebase
.diversity
= patchLocation
.discriminator
;
432 fixupInfo
.authRebase
.key
= patchLocation
.key
;
433 *loc
= fixupInfo
.signPointer(loc
, newLoc
+ patchLocation
.getAddend());
434 if ( context
.verboseInterposing
)
435 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
436 loc
, (void*)*loc
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, patchLocation
.keyName());
440 if ( context
.verboseInterposing
)
441 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc
, newLoc
+ patchLocation
.getAddend(), exportName
);
442 *loc
= newLoc
+ patchLocation
.getAddend();
449 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array
[], size_t count
)
451 for(size_t i
=0; i
< count
; ++i
) {
452 ImageLoader::InterposeTuple tuple
;
453 tuple
.replacement
= (uintptr_t)array
[i
].replacement
;
454 tuple
.neverImage
= NULL
;
455 tuple
.onlyImage
= this;
456 tuple
.replacee
= (uintptr_t)array
[i
].replacee
;
457 // chain to any existing interpositions
458 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
459 if ( (it
->replacee
== tuple
.replacee
) && (it
->onlyImage
== this) ) {
460 tuple
.replacee
= it
->replacement
;
463 ImageLoader::fgInterposingTuples
.push_back(tuple
);
467 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
468 void ImageLoader::vmAccountingSetSuspended(const LinkContext
& context
, bool suspend
)
470 #if __arm__ || __arm64__
471 static bool sVmAccountingSuspended
= false;
472 if ( suspend
== sVmAccountingSuspended
)
474 if ( context
.verboseBind
)
475 dyld::log("set vm.footprint_suspend=%d\n", suspend
);
476 int newValue
= suspend
? 1 : 0;
478 size_t newlen
= sizeof(newValue
);
479 size_t oldlen
= sizeof(oldValue
);
480 int ret
= sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
481 if ( context
.verboseBind
&& (ret
!= 0) )
482 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
483 sVmAccountingSuspended
= suspend
;
488 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, bool neverUnload
, const RPathChain
& loaderRPaths
, const char* imagePath
)
490 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
492 // clear error strings
493 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
495 uint64_t t0
= mach_absolute_time();
496 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
, imagePath
);
497 context
.notifyBatch(dyld_image_state_dependents_mapped
, preflightOnly
);
499 // we only do the loading step for preflights
503 uint64_t t1
= mach_absolute_time();
504 context
.clearAllDepths();
505 this->recursiveUpdateDepth(context
.imageCount());
507 __block
uint64_t t2
, t3
, t4
, t5
;
509 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS
, 0, 0, 0);
510 t2
= mach_absolute_time();
511 this->recursiveRebase(context
);
512 context
.notifyBatch(dyld_image_state_rebased
, false);
514 t3
= mach_absolute_time();
515 if ( !context
.linkingMainExecutable
)
516 this->recursiveBindWithAccounting(context
, forceLazysBound
, neverUnload
);
518 t4
= mach_absolute_time();
519 if ( !context
.linkingMainExecutable
)
520 this->weakBind(context
);
521 t5
= mach_absolute_time();
524 if ( !context
.linkingMainExecutable
)
525 context
.notifyBatch(dyld_image_state_bound
, false);
526 uint64_t t6
= mach_absolute_time();
528 std::vector
<DOFInfo
> dofs
;
529 this->recursiveGetDOFSections(context
, dofs
);
530 context
.registerDOFs(dofs
);
531 uint64_t t7
= mach_absolute_time();
533 // interpose any dynamically loaded images
534 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
535 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
536 this->recursiveApplyInterposing(context
);
539 // clear error strings
540 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
542 fgTotalLoadLibrariesTime
+= t1
- t0
;
543 fgTotalRebaseTime
+= t3
- t2
;
544 fgTotalBindTime
+= t4
- t3
;
545 fgTotalWeakBindTime
+= t5
- t4
;
546 fgTotalDOF
+= t7
- t6
;
548 // done with initial dylib loads
549 fgNextPIEDylibAddress
= 0;
553 void ImageLoader::printReferenceCounts()
555 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount
, getPath() );
559 bool ImageLoader::decrementDlopenReferenceCount()
561 if ( fDlopenReferenceCount
== 0 )
563 --fDlopenReferenceCount
;
568 // <rdar://problem/14412057> upward dylib initializers can be run too soon
569 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
570 // have their initialization postponed until after the recursion through downward dylibs
572 void ImageLoader::processInitializers(const LinkContext
& context
, mach_port_t thisThread
,
573 InitializerTimingList
& timingInfo
, ImageLoader::UninitedUpwards
& images
)
575 uint32_t maxImageCount
= context
.imageCount()+2;
576 ImageLoader::UninitedUpwards upsBuffer
[maxImageCount
];
577 ImageLoader::UninitedUpwards
& ups
= upsBuffer
[0];
579 // Calling recursive init on all images in images list, building a new list of
580 // uninitialized upward dependencies.
581 for (uintptr_t i
=0; i
< images
.count
; ++i
) {
582 images
.images
[i
]->recursiveInitialization(context
, thisThread
, images
.images
[i
]->getPath(), timingInfo
, ups
);
584 // If any upward dependencies remain, init them.
586 processInitializers(context
, thisThread
, timingInfo
, ups
);
590 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
592 uint64_t t1
= mach_absolute_time();
593 mach_port_t thisThread
= mach_thread_self();
594 ImageLoader::UninitedUpwards up
;
597 processInitializers(context
, thisThread
, timingInfo
, up
);
598 context
.notifyBatch(dyld_image_state_initialized
, false);
599 mach_port_deallocate(mach_task_self(), thisThread
);
600 uint64_t t2
= mach_absolute_time();
601 fgTotalInitTime
+= (t2
- t1
);
605 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
607 if ( ! fAllLazyPointersBound
) {
608 fAllLazyPointersBound
= true;
611 // bind lower level libraries first
612 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
613 ImageLoader
* dependentImage
= libImage(i
);
614 if ( dependentImage
!= NULL
)
615 dependentImage
->bindAllLazyPointers(context
, recursive
);
618 // bind lazies in this image
619 this->doBindJustLazies(context
);
624 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
626 return fAllLibraryChecksumsAndLoadAddressesMatch
;
630 void ImageLoader::markedUsedRecursive(const std::vector
<DynamicReference
>& dynamicReferences
)
632 // already visited here
637 // clear mark on all statically dependent dylibs
638 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
639 ImageLoader
* dependentImage
= libImage(i
);
640 if ( dependentImage
!= NULL
) {
641 dependentImage
->markedUsedRecursive(dynamicReferences
);
645 // clear mark on all dynamically dependent dylibs
646 for (std::vector
<ImageLoader::DynamicReference
>::const_iterator it
=dynamicReferences
.begin(); it
!= dynamicReferences
.end(); ++it
) {
647 if ( it
->from
== this )
648 it
->to
->markedUsedRecursive(dynamicReferences
);
653 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
)
655 // the purpose of this phase is to make the images sortable such that
656 // in a sort list of images, every image that an image depends on
657 // occurs in the list before it.
662 // get depth of dependents
663 unsigned int minDependentDepth
= maxDepth
;
664 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
665 ImageLoader
* dependentImage
= libImage(i
);
666 if ( (dependentImage
!= NULL
) && !libIsUpward(i
) ) {
667 unsigned int d
= dependentImage
->recursiveUpdateDepth(maxDepth
);
668 if ( d
< minDependentDepth
)
669 minDependentDepth
= d
;
673 // make me less deep then all my dependents
674 fDepth
= minDependentDepth
- 1;
681 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
, const char* loadPath
)
683 if ( fState
< dyld_image_state_dependents_mapped
) {
685 fState
= dyld_image_state_dependents_mapped
;
687 // get list of libraries this image needs
688 DependentLibraryInfo libraryInfos
[fLibraryCount
];
689 this->doGetDependentLibraries(libraryInfos
);
691 // get list of rpaths that this image adds
692 std::vector
<const char*> rpathsFromThisImage
;
693 this->getRPaths(context
, rpathsFromThisImage
);
694 const RPathChain
thisRPaths(&loaderRPaths
, &rpathsFromThisImage
);
697 bool canUsePrelinkingInfo
= true;
698 for(unsigned int i
=0; i
< fLibraryCount
; ++i
){
699 ImageLoader
* dependentLib
;
700 bool depLibReExported
= false;
701 bool depLibRequired
= false;
702 bool depLibCheckSumsMatch
= false;
703 DependentLibraryInfo
& requiredLibInfo
= libraryInfos
[i
];
704 if ( preflightOnly
&& context
.inSharedCache(requiredLibInfo
.name
) ) {
705 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
706 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
707 setLibImage(i
, NULL
, false, false);
712 bool enforceIOSMac
= false;
713 #if __MAC_OS_X_VERSION_MIN_REQUIRED
714 const dyld3::MachOFile
* mf
= (dyld3::MachOFile
*)this->machHeader();
715 if ( mf
->supportsPlatform(dyld3::Platform::iOSMac
) && !mf
->supportsPlatform(dyld3::Platform::macOS
) )
716 enforceIOSMac
= true;
718 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, true, this->getPath(), &thisRPaths
, enforceIOSMac
, cacheIndex
);
719 if ( dependentLib
== this ) {
720 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
721 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, false, NULL
, NULL
, enforceIOSMac
, cacheIndex
);
722 if ( dependentLib
!= this )
723 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
726 dependentLib
->setNeverUnload();
727 if ( requiredLibInfo
.upward
) {
730 dependentLib
->fIsReferencedDownward
= true;
732 LibraryInfo actualInfo
= dependentLib
->doGetLibraryInfo(requiredLibInfo
.info
);
733 depLibRequired
= requiredLibInfo
.required
;
734 depLibCheckSumsMatch
= ( actualInfo
.checksum
== requiredLibInfo
.info
.checksum
);
735 depLibReExported
= requiredLibInfo
.reExported
;
736 if ( ! depLibReExported
) {
737 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
738 depLibReExported
= dependentLib
->isSubframeworkOf(context
, this) || this->hasSubLibrary(context
, dependentLib
);
740 // check found library version is compatible
741 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
742 if ( (requiredLibInfo
.info
.minVersion
!= 0xFFFFFFFF) && (actualInfo
.minVersion
< requiredLibInfo
.info
.minVersion
)
743 && ((dyld3::MachOFile
*)(dependentLib
->machHeader()))->enforceCompatVersion() ) {
744 // record values for possible use by CrashReporter or Finder
745 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
746 this->getShortName(), requiredLibInfo
.info
.minVersion
>> 16, (requiredLibInfo
.info
.minVersion
>> 8) & 0xff, requiredLibInfo
.info
.minVersion
& 0xff,
747 dependentLib
->getShortName(), actualInfo
.minVersion
>> 16, (actualInfo
.minVersion
>> 8) & 0xff, actualInfo
.minVersion
& 0xff);
749 // prebinding for this image disabled if any dependent library changed
750 //if ( !depLibCheckSumsMatch )
751 // canUsePrelinkingInfo = false;
752 // prebinding for this image disabled unless both this and dependent are in the shared cache
753 if ( !dependentLib
->inSharedCache() || !this->inSharedCache() )
754 canUsePrelinkingInfo
= false;
756 //if ( context.verbosePrebinding ) {
757 // if ( !requiredLib.checksumMatches )
758 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
759 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
760 // if ( dependentLib->getSlide() != 0 )
761 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
764 catch (const char* msg
) {
765 //if ( context.verbosePrebinding )
766 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
767 if ( requiredLibInfo
.required
) {
768 fState
= dyld_image_state_mapped
;
769 // record values for possible use by CrashReporter or Finder
770 if ( strstr(msg
, "Incompatible library version") != NULL
)
771 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION
, this->getPath(), requiredLibInfo
.name
, NULL
);
772 else if ( strstr(msg
, "architecture") != NULL
)
773 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH
, this->getPath(), requiredLibInfo
.name
, NULL
);
774 else if ( strstr(msg
, "file system sandbox") != NULL
)
775 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX
, this->getPath(), requiredLibInfo
.name
, NULL
);
776 else if ( strstr(msg
, "code signature") != NULL
)
777 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_CODE_SIGNATURE
, this->getPath(), requiredLibInfo
.name
, NULL
);
778 else if ( strstr(msg
, "malformed") != NULL
)
779 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_MALFORMED_MACHO
, this->getPath(), requiredLibInfo
.name
, NULL
);
781 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_MISSING
, this->getPath(), requiredLibInfo
.name
, NULL
);
782 const char* newMsg
= dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo
.name
, this->getRealPath(), msg
);
783 free((void*)msg
); // our free() will do nothing if msg is a string literal
786 free((void*)msg
); // our free() will do nothing if msg is a string literal
787 // ok if weak library not found
789 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
791 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
793 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
795 // tell each to load its dependents
796 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
797 ImageLoader
* dependentImage
= libImage(i
);
798 if ( dependentImage
!= NULL
) {
799 dependentImage
->recursiveLoadLibraries(context
, preflightOnly
, thisRPaths
, libraryInfos
[i
].name
);
803 // do deep prebind check
804 if ( fAllLibraryChecksumsAndLoadAddressesMatch
) {
805 for(unsigned int i
=0; i
< libraryCount(); ++i
){
806 ImageLoader
* dependentImage
= libImage(i
);
807 if ( dependentImage
!= NULL
) {
808 if ( !dependentImage
->allDependentLibrariesAsWhenPreBound() )
809 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
814 // free rpaths (getRPaths() malloc'ed each string)
815 for(std::vector
<const char*>::iterator it
=rpathsFromThisImage
.begin(); it
!= rpathsFromThisImage
.end(); ++it
) {
816 const char* str
= *it
;
823 void ImageLoader::recursiveRebase(const LinkContext
& context
)
825 if ( fState
< dyld_image_state_rebased
) {
827 fState
= dyld_image_state_rebased
;
830 // rebase lower level libraries first
831 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
832 ImageLoader
* dependentImage
= libImage(i
);
833 if ( dependentImage
!= NULL
)
834 dependentImage
->recursiveRebase(context
);
841 context
.notifySingle(dyld_image_state_rebased
, this, NULL
);
843 catch (const char* msg
) {
844 // this image is not rebased
845 fState
= dyld_image_state_dependents_mapped
;
846 CRSetCrashLogMessage2(NULL
);
852 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
854 if ( ! fInterposed
) {
859 // interpose lower level libraries first
860 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
861 ImageLoader
* dependentImage
= libImage(i
);
862 if ( dependentImage
!= NULL
)
863 dependentImage
->recursiveApplyInterposing(context
);
866 // interpose this image
867 doInterpose(context
);
869 catch (const char* msg
) {
870 // this image is not interposed
877 void ImageLoader::recursiveBindWithAccounting(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
879 this->recursiveBind(context
, forceLazysBound
, neverUnload
);
880 vmAccountingSetSuspended(context
, false);
883 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
885 // Normally just non-lazy pointers are bound immediately.
886 // The exceptions are:
887 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
888 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
889 if ( fState
< dyld_image_state_bound
) {
891 fState
= dyld_image_state_bound
;
894 // bind lower level libraries first
895 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
896 ImageLoader
* dependentImage
= libImage(i
);
897 if ( dependentImage
!= NULL
)
898 dependentImage
->recursiveBind(context
, forceLazysBound
, neverUnload
);
901 this->doBind(context
, forceLazysBound
);
902 // mark if lazys are also bound
903 if ( forceLazysBound
|| this->usablePrebinding(context
) )
904 fAllLazyPointersBound
= true;
905 // mark as never-unload if requested
907 this->setNeverUnload();
909 context
.notifySingle(dyld_image_state_bound
, this, NULL
);
911 catch (const char* msg
) {
913 fState
= dyld_image_state_rebased
;
914 CRSetCrashLogMessage2(NULL
);
921 // These are mangled symbols for all the variants of operator new and delete
922 // which a main executable can define (non-weak) and override the
923 // weak-def implementation in the OS.
924 static const char* sTreatAsWeak
[] = {
925 "__Znwm", "__ZnwmRKSt9nothrow_t",
926 "__Znam", "__ZnamRKSt9nothrow_t",
927 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
928 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
929 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
930 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
931 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
932 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
937 void ImageLoader::weakBind(const LinkContext
& context
)
939 if ( context
.verboseWeakBind
)
940 dyld::log("dyld: weak bind start:\n");
941 uint64_t t1
= mach_absolute_time();
942 // get set of ImageLoaders that participate in coalecsing
943 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
944 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
945 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
947 // count how many have not already had weakbinding done
948 int countNotYetWeakBound
= 0;
949 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
950 for(int i
=0; i
< count
; ++i
) {
951 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
952 ++countNotYetWeakBound
;
953 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
954 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
957 // don't need to do any coalescing if only one image has overrides, or all have already been done
958 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
959 // make symbol iterators for each
960 ImageLoader::CoalIterator iterators
[count
];
961 ImageLoader::CoalIterator
* sortedIts
[count
];
962 for(int i
=0; i
< count
; ++i
) {
963 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
964 sortedIts
[i
] = &iterators
[i
];
965 if ( context
.verboseWeakBind
)
966 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
969 // walk all symbols keeping iterators in sync by
970 // only ever incrementing the iterator with the lowest symbol
972 while ( doneCount
!= count
) {
973 //for(int i=0; i < count; ++i)
974 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
976 // increment iterator with lowest symbol
977 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
980 for(int i
=1; i
< count
; ++i
) {
981 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
983 sortedIts
[i
-1]->symbolMatches
= true;
985 // new one is bigger then next, so swap
986 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
987 sortedIts
[i
-1] = sortedIts
[i
];
993 // process all matching symbols just before incrementing the lowest one that matches
994 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
995 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
996 // pick first symbol in load order (and non-weak overrides weak)
997 uintptr_t targetAddr
= 0;
998 ImageLoader
* targetImage
= NULL
;
999 unsigned targetImageIndex
= 0;
1000 for(int i
=0; i
< count
; ++i
) {
1001 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1002 if ( context
.verboseWeakBind
)
1003 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1004 if ( iterators
[i
].weakSymbol
) {
1005 if ( targetAddr
== 0 ) {
1006 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1007 if ( targetAddr
!= 0 ) {
1008 targetImage
= iterators
[i
].image
;
1009 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1014 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1015 if ( targetAddr
!= 0 ) {
1016 targetImage
= iterators
[i
].image
;
1017 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1018 // strong implementation found, stop searching
1024 // tell each to bind to this symbol (unless already bound)
1025 if ( targetAddr
!= 0 ) {
1026 if ( context
.verboseWeakBind
) {
1027 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1028 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1030 for(int i
=0; i
< count
; ++i
) {
1031 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1032 if ( context
.verboseWeakBind
) {
1033 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1034 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1035 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1037 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1038 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1039 iterators
[i
].symbolMatches
= false;
1048 for (int i
=0; i
< count
; ++i
) {
1049 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1050 // during binding of references to weak-def symbols, the dyld cache was patched
1051 // but if main executable has non-weak override of operator new or delete it needs is handled here
1052 if ( !imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) ) {
1053 for (const char* weakSymbolName
: sTreatAsWeak
) {
1054 const ImageLoader
* dummy
;
1055 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1060 // look for weak def symbols in this image which may override the cache
1061 ImageLoader::CoalIterator coaler
;
1062 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1063 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1064 while ( !coaler
.done
) {
1065 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1066 const ImageLoader
* dummy
;
1067 // a side effect of resolveWeak() is to patch cache
1068 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1074 // mark all as having all weak symbols bound
1075 for(int i
=0; i
< count
; ++i
) {
1076 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1080 uint64_t t2
= mach_absolute_time();
1081 fgTotalWeakBindTime
+= t2
- t1
;
1083 if ( context
.verboseWeakBind
)
1084 dyld::log("dyld: weak bind end\n");
1089 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
1091 if ( ! fRegisteredDOF
) {
1093 fRegisteredDOF
= true;
1095 // gather lower level libraries first
1096 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1097 ImageLoader
* dependentImage
= libImage(i
);
1098 if ( dependentImage
!= NULL
)
1099 dependentImage
->recursiveGetDOFSections(context
, dofs
);
1101 this->doGetDOFSections(context
, dofs
);
1105 void ImageLoader::setNeverUnloadRecursive() {
1106 if ( ! fNeverUnload
) {
1108 fNeverUnload
= true;
1110 // gather lower level libraries first
1111 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1112 ImageLoader
* dependentImage
= libImage(i
);
1113 if ( dependentImage
!= NULL
)
1114 dependentImage
->setNeverUnloadRecursive();
1119 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
1121 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1122 // keep trying until success (spin)
1123 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
1124 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1125 // the same thread we are on, the increment the lock count, otherwise continue to spin
1126 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
1129 ++(fInitializerRecursiveLock
->count
);
1132 void ImageLoader::recursiveSpinUnLock()
1134 if ( --(fInitializerRecursiveLock
->count
) == 0 )
1135 fInitializerRecursiveLock
= NULL
;
1138 void ImageLoader::InitializerTimingList::addTime(const char* name
, uint64_t time
)
1140 for (int i
=0; i
< count
; ++i
) {
1141 if ( strcmp(images
[i
].shortName
, name
) == 0 ) {
1142 images
[i
].initTime
+= time
;
1146 images
[count
].initTime
= time
;
1147 images
[count
].shortName
= name
;
1151 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
, const char* pathToInitialize
,
1152 InitializerTimingList
& timingInfo
, UninitedUpwards
& uninitUps
)
1154 recursive_lock
lock_info(this_thread
);
1155 recursiveSpinLock(lock_info
);
1157 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
1158 uint8_t oldState
= fState
;
1160 fState
= dyld_image_state_dependents_initialized
-1;
1162 // initialize lower level libraries first
1163 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1164 ImageLoader
* dependentImage
= libImage(i
);
1165 if ( dependentImage
!= NULL
) {
1166 // don't try to initialize stuff "above" me yet
1167 if ( libIsUpward(i
) ) {
1168 uninitUps
.images
[uninitUps
.count
] = dependentImage
;
1171 else if ( dependentImage
->fDepth
>= fDepth
) {
1172 dependentImage
->recursiveInitialization(context
, this_thread
, libPath(i
), timingInfo
, uninitUps
);
1177 // record termination order
1178 if ( this->needsTermination() )
1179 context
.terminationRecorder(this);
1181 // let objc know we are about to initialize this image
1182 uint64_t t1
= mach_absolute_time();
1183 fState
= dyld_image_state_dependents_initialized
;
1185 context
.notifySingle(dyld_image_state_dependents_initialized
, this, &timingInfo
);
1187 // initialize this image
1188 bool hasInitializers
= this->doInitialization(context
);
1190 // let anyone know we finished initializing this image
1191 fState
= dyld_image_state_initialized
;
1193 context
.notifySingle(dyld_image_state_initialized
, this, NULL
);
1195 if ( hasInitializers
) {
1196 uint64_t t2
= mach_absolute_time();
1197 timingInfo
.addTime(this->getShortName(), t2
-t1
);
1200 catch (const char* msg
) {
1201 // this image is not initialized
1203 recursiveSpinUnLock();
1208 recursiveSpinUnLock();
1212 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
1214 static uint64_t sUnitsPerSecond
= 0;
1215 if ( sUnitsPerSecond
== 0 ) {
1216 struct mach_timebase_info timeBaseInfo
;
1217 if ( mach_timebase_info(&timeBaseInfo
) != KERN_SUCCESS
)
1219 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
1221 if ( partTime
< sUnitsPerSecond
) {
1222 uint32_t milliSecondsTimesHundred
= (uint32_t)((partTime
*100000)/sUnitsPerSecond
);
1223 uint32_t milliSeconds
= (uint32_t)(milliSecondsTimesHundred
/100);
1224 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1225 uint32_t percent
= percentTimesTen
/10;
1226 if ( milliSeconds
>= 100 )
1227 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1228 else if ( milliSeconds
>= 10 )
1229 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1231 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1234 uint32_t secondsTimeTen
= (uint32_t)((partTime
*10)/sUnitsPerSecond
);
1235 uint32_t seconds
= secondsTimeTen
/10;
1236 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1237 uint32_t percent
= percentTimesTen
/10;
1238 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
1242 static char* commatize(uint64_t in
, char* out
)
1244 uint64_t div10
= in
/ 10;
1245 uint8_t delta
= in
- div10
*10;
1249 *(--s
) = '0' + delta
;
1252 if ( (digitCount
% 3) == 0 )
1255 delta
= in
- div10
*10;
1256 *(--s
) = '0' + delta
;
1264 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1266 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1268 uint64_t totalDyldTime
= totalTime
- fgTotalDebuggerPausedTime
- fgTotalRebindCacheTime
;
1269 printTime("Total pre-main time", totalDyldTime
, totalDyldTime
);
1270 printTime(" dylib loading time", fgTotalLoadLibrariesTime
-fgTotalDebuggerPausedTime
, totalDyldTime
);
1271 printTime(" rebase/binding time", fgTotalRebaseTime
+fgTotalBindTime
+fgTotalWeakBindTime
-fgTotalRebindCacheTime
, totalDyldTime
);
1272 printTime(" ObjC setup time", fgTotalObjCSetupTime
, totalDyldTime
);
1273 printTime(" initializer time", fgTotalInitTime
-fgTotalObjCSetupTime
, totalDyldTime
);
1274 dyld::log(" slowest intializers :\n");
1275 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1276 uint64_t t
= timingInfo
.images
[i
].initTime
;
1277 if ( t
*50 < totalDyldTime
)
1279 dyld::log("%30s ", timingInfo
.images
[i
].shortName
);
1280 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1281 t
-= fgTotalObjCSetupTime
;
1282 printTime("", t
, totalDyldTime
);
1287 void ImageLoader::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1289 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1293 printTime(" total time", totalTime
, totalTime
);
1294 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1295 dyld::log(" total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096, fgTotalBytesPreFetched
/4096);
1296 printTime(" total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
1297 printTime(" total load time in ObjC", fgTotalObjCSetupTime
, totalTime
);
1298 printTime(" total debugger pause time", fgTotalDebuggerPausedTime
, totalTime
);
1299 printTime(" total dtrace DOF registration time", fgTotalDOF
, totalTime
);
1300 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
1301 printTime(" total rebase fixups time", fgTotalRebaseTime
, totalTime
);
1302 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
1303 if ( fgTotalBindSymbolsResolved
!= 0 ) {
1304 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
1305 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
1306 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
1307 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1308 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
1310 printTime(" total binding fixups time", fgTotalBindTime
, totalTime
);
1311 printTime(" total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
1312 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime
, totalTime
);
1313 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
1314 printTime(" total time in initializers and ObjC +load", fgTotalInitTime
-fgTotalObjCSetupTime
, totalTime
);
1315 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1316 uint64_t t
= timingInfo
.images
[i
].initTime
;
1317 if ( t
*1000 < totalTime
)
1319 dyld::log("%42s ", timingInfo
.images
[i
].shortName
);
1320 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1321 t
-= fgTotalObjCSetupTime
;
1322 printTime("", t
, totalTime
);
1329 // copy path and add suffix to result
1331 // /path/foo.dylib _debug => /path/foo_debug.dylib
1332 // foo.dylib _debug => foo_debug.dylib
1333 // foo _debug => foo_debug
1334 // /path/bar _debug => /path/bar_debug
1335 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1337 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1339 strcpy(result
, path
);
1341 char* start
= strrchr(result
, '/');
1342 if ( start
!= NULL
)
1347 char* dot
= strrchr(start
, '.');
1348 if ( dot
!= NULL
) {
1349 strcpy(dot
, suffix
);
1350 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1353 strcat(result
, suffix
);
1359 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1360 // to enable it to be re-written in assembler if needed.
1362 const uint8_t* ImageLoader::trieWalk(const uint8_t* start
, const uint8_t* end
, const char* s
)
1364 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1365 ++fgSymbolTrieSearchs
;
1366 const uint8_t* p
= start
;
1367 while ( p
!= NULL
) {
1368 uintptr_t terminalSize
= *p
++;
1369 if ( terminalSize
> 127 ) {
1370 // except for re-export-with-rename, all terminal sizes fit in one byte
1372 terminalSize
= read_uleb128(p
, end
);
1374 if ( (*s
== '\0') && (terminalSize
!= 0) ) {
1375 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1378 const uint8_t* children
= p
+ terminalSize
;
1379 if ( children
> end
) {
1380 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize
);
1383 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1384 uint8_t childrenRemaining
= *children
++;
1386 uintptr_t nodeOffset
= 0;
1387 for (; childrenRemaining
> 0; --childrenRemaining
) {
1389 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1390 bool wrongEdge
= false;
1391 // scan whole edge to get to next edge
1392 // if edge is longer than target symbol name, don't read past end of symbol name
1394 while ( c
!= '\0' ) {
1404 // advance to next child
1405 ++p
; // skip over zero terminator
1406 // skip over uleb128 until last byte is found
1407 while ( (*p
& 0x80) != 0 )
1409 ++p
; // skip over last byte of uleb128
1411 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1416 // the symbol so far matches this edge (child)
1417 // so advance to the child's node
1419 nodeOffset
= read_uleb128(p
, end
);
1420 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
1421 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset
);
1425 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1429 if ( nodeOffset
!= 0 )
1430 p
= &start
[nodeOffset
];
1434 //dyld::log("trieWalk(%p) return NULL\n", start);
1440 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p
, const uint8_t* end
)
1442 uint64_t result
= 0;
1446 dyld::throwf("malformed uleb128");
1448 uint64_t slice
= *p
& 0x7f;
1451 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit
, result
);
1453 result
|= (slice
<< bit
);
1456 } while (*p
++ & 0x80);
1457 return (uintptr_t)result
;
1461 intptr_t ImageLoader::read_sleb128(const uint8_t*& p
, const uint8_t* end
)
1468 throw "malformed sleb128";
1470 result
|= (((int64_t)(byte
& 0x7f)) << bit
);
1472 } while (byte
& 0x80);
1473 // sign extend negative numbers
1474 if ( (byte
& 0x40) != 0 )
1475 result
|= (~0ULL) << bit
;
1476 return (intptr_t)result
;
1480 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple
);
1481 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair
);