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>
39 #include <string_view>
45 #include "ImageLoader.h"
48 uint32_t ImageLoader::fgImagesUsedFromSharedCache
= 0;
49 uint32_t ImageLoader::fgImagesWithUsedPrebinding
= 0;
50 uint32_t ImageLoader::fgImagesRequiringCoalescing
= 0;
51 uint32_t ImageLoader::fgImagesHasWeakDefinitions
= 0;
52 uint32_t ImageLoader::fgTotalRebaseFixups
= 0;
53 uint32_t ImageLoader::fgTotalBindFixups
= 0;
54 uint32_t ImageLoader::fgTotalBindSymbolsResolved
= 0;
55 uint32_t ImageLoader::fgTotalBindImageSearches
= 0;
56 uint32_t ImageLoader::fgTotalLazyBindFixups
= 0;
57 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups
= 0;
58 uint32_t ImageLoader::fgTotalSegmentsMapped
= 0;
59 uint64_t ImageLoader::fgTotalBytesMapped
= 0;
60 uint64_t ImageLoader::fgTotalLoadLibrariesTime
;
61 uint64_t ImageLoader::fgTotalObjCSetupTime
= 0;
62 uint64_t ImageLoader::fgTotalDebuggerPausedTime
= 0;
63 uint64_t ImageLoader::fgTotalRebindCacheTime
= 0;
64 uint64_t ImageLoader::fgTotalRebaseTime
;
65 uint64_t ImageLoader::fgTotalBindTime
;
66 uint64_t ImageLoader::fgTotalWeakBindTime
;
67 uint64_t ImageLoader::fgTotalDOF
;
68 uint64_t ImageLoader::fgTotalInitTime
;
69 uint16_t ImageLoader::fgLoadOrdinal
= 0;
70 uint32_t ImageLoader::fgSymbolTrieSearchs
= 0;
71 std::vector
<ImageLoader::InterposeTuple
>ImageLoader::fgInterposingTuples
;
72 uintptr_t ImageLoader::fgNextPIEDylibAddress
= 0;
76 ImageLoader::ImageLoader(const char* path
, unsigned int libCount
)
77 : fPath(path
), fRealPath(NULL
), fDevice(0), fInode(0), fLastModified(0),
78 fPathHash(0), fDlopenReferenceCount(0), fInitializerRecursiveLock(NULL
),
79 fLoadOrder(fgLoadOrdinal
++), fDepth(0), fObjCMappedNotified(false), fState(0), fLibraryCount(libCount
),
80 fMadeReadOnly(false), fAllLibraryChecksumsAndLoadAddressesMatch(false), fLeaveMapped(false), fNeverUnload(false),
81 fHideSymbols(false), fMatchByInstallName(false),
82 fInterposed(false), fRegisteredDOF(false), fAllLazyPointersBound(false),
83 fBeingRemoved(false), fAddFuncNotified(false),
84 fPathOwnedByImage(false), fIsReferencedDownward(false),
85 fWeakSymbolsBound(false)
88 fPathHash
= hash(fPath
);
90 dyld::throwf("too many dependent dylibs in %s", path
);
94 void ImageLoader::deleteImage(ImageLoader
* image
)
100 ImageLoader::~ImageLoader()
102 if ( fRealPath
!= NULL
)
104 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
108 void ImageLoader::setFileInfo(dev_t device
, ino_t inode
, time_t modDate
)
112 fLastModified
= modDate
;
115 void ImageLoader::setMapped(const LinkContext
& context
)
117 fState
= dyld_image_state_mapped
;
118 context
.notifySingle(dyld_image_state_mapped
, this, NULL
); // note: can throw exception
121 int ImageLoader::compare(const ImageLoader
* right
) const
123 if ( this->fDepth
== right
->fDepth
) {
124 if ( this->fLoadOrder
== right
->fLoadOrder
)
126 else if ( this->fLoadOrder
< right
->fLoadOrder
)
132 if ( this->fDepth
< right
->fDepth
)
139 void ImageLoader::setPath(const char* path
)
141 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
143 fPath
= new char[strlen(path
)+1];
144 strcpy((char*)fPath
, path
);
145 fPathOwnedByImage
= true; // delete fPath when this image is destructed
146 fPathHash
= hash(fPath
);
147 if ( fRealPath
!= NULL
) {
153 void ImageLoader::setPathUnowned(const char* path
)
155 if ( fPathOwnedByImage
&& (fPath
!= NULL
) ) {
159 fPathOwnedByImage
= false;
160 fPathHash
= hash(fPath
);
163 void ImageLoader::setPaths(const char* path
, const char* realPath
)
166 fRealPath
= new char[strlen(realPath
)+1];
167 strcpy((char*)fRealPath
, realPath
);
171 const char* ImageLoader::getRealPath() const
173 if ( fRealPath
!= NULL
)
179 uint32_t ImageLoader::hash(const char* path
)
181 // this does not need to be a great hash
182 // it is just used to reduce the number of strcmp() calls
183 // of existing images when loading a new image
185 for (const char* s
=path
; *s
!= '\0'; ++s
)
190 bool ImageLoader::matchInstallPath() const
192 return fMatchByInstallName
;
195 void ImageLoader::setMatchInstallPath(bool match
)
197 fMatchByInstallName
= match
;
200 bool ImageLoader::statMatch(const struct stat
& stat_buf
) const
202 return ( (this->fDevice
== stat_buf
.st_dev
) && (this->fInode
== stat_buf
.st_ino
) );
205 const char* ImageLoader::shortName(const char* fullName
)
207 // try to return leaf name
208 if ( fullName
!= NULL
) {
209 const char* s
= strrchr(fullName
, '/');
216 const char* ImageLoader::getShortName() const
218 return shortName(fPath
);
221 void ImageLoader::setLeaveMapped()
226 void ImageLoader::setHideExports(bool hide
)
231 bool ImageLoader::hasHiddenExports() const
236 bool ImageLoader::isLinked() const
238 return (fState
>= dyld_image_state_bound
);
241 time_t ImageLoader::lastModified() const
243 return fLastModified
;
246 bool ImageLoader::containsAddress(const void* addr
) const
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
);
291 bool ImageLoader::dependsOn(ImageLoader
* image
) {
292 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
293 if ( libImage(i
) == image
)
300 static bool notInImgageList(const ImageLoader
* image
, const ImageLoader
** dsiStart
, const ImageLoader
** dsiCur
)
302 for (const ImageLoader
** p
= dsiStart
; p
< dsiCur
; ++p
)
308 bool ImageLoader::findExportedSymbolAddress(const LinkContext
& context
, const char* symbolName
,
309 const ImageLoader
* requestorImage
, int requestorOrdinalOfDef
,
310 bool runResolver
, const ImageLoader
** foundIn
, uintptr_t* address
) const
312 const Symbol
* sym
= this->findExportedSymbol(symbolName
, true, foundIn
);
314 *address
= (*foundIn
)->getExportedSymbolAddress(sym
, context
, requestorImage
, runResolver
);
321 // private method that handles circular dependencies by only search any image once
322 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name
,
323 const ImageLoader
** dsiStart
, const ImageLoader
**& dsiCur
, const ImageLoader
** dsiEnd
, const ImageLoader
** foundIn
) const
325 const ImageLoader::Symbol
* sym
;
327 if ( notInImgageList(this, dsiStart
, dsiCur
) ) {
328 sym
= this->findExportedSymbol(name
, false, this->getPath(), foundIn
);
334 // search directly dependent libraries
335 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
336 ImageLoader
* dependentImage
= libImage(i
);
337 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
338 sym
= dependentImage
->findExportedSymbol(name
, false, libPath(i
), foundIn
);
344 // search indirectly dependent libraries
345 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
346 ImageLoader
* dependentImage
= libImage(i
);
347 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
348 *dsiCur
++ = dependentImage
;
349 sym
= dependentImage
->findExportedSymbolInDependentImagesExcept(name
, dsiStart
, dsiCur
, dsiEnd
, foundIn
);
359 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
361 unsigned int imageCount
= context
.imageCount()+2;
362 const ImageLoader
* dontSearchImages
[imageCount
];
363 dontSearchImages
[0] = this; // don't search this image
364 const ImageLoader
** cur
= &dontSearchImages
[1];
365 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
368 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
370 unsigned int imageCount
= context
.imageCount()+2;
371 const ImageLoader
* dontSearchImages
[imageCount
];
372 const ImageLoader
** cur
= &dontSearchImages
[0];
373 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
376 // this is called by initializeMainExecutable() to interpose on the initial set of images
377 void ImageLoader::applyInterposing(const LinkContext
& context
)
379 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
380 if ( fgInterposingTuples
.size() != 0 )
381 this->recursiveApplyInterposing(context
);
385 uintptr_t ImageLoader::interposedAddress(const LinkContext
& context
, uintptr_t address
, const ImageLoader
* inImage
, const ImageLoader
* onlyInImage
)
387 //dyld::log("interposedAddress(0x%08llX), tupleCount=%lu\n", (uint64_t)address, fgInterposingTuples.size());
388 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
389 //dyld::log(" interposedAddress: replacee=0x%08llX, replacement=0x%08llX, neverImage=%p, onlyImage=%p, inImage=%p\n",
390 // (uint64_t)it->replacee, (uint64_t)it->replacement, it->neverImage, it->onlyImage, inImage);
391 // replace all references to 'replacee' with 'replacement'
392 if ( (address
== it
->replacee
) && (inImage
!= it
->neverImage
) && ((it
->onlyImage
== NULL
) || (inImage
== it
->onlyImage
)) ) {
393 if ( context
.verboseInterposing
) {
394 dyld::log("dyld interposing: replace 0x%lX with 0x%lX\n", it
->replacee
, it
->replacement
);
396 return it
->replacement
;
402 void ImageLoader::applyInterposingToDyldCache(const LinkContext
& context
) {
403 if (!context
.dyldCache
)
405 #if !__arm64e__ // until arm64e cache builder sets builtFromChainedFixups
406 if (!context
.dyldCache
->header
.builtFromChainedFixups
)
409 if (fgInterposingTuples
.empty())
411 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
412 // that image and apply its patch table to all uses.
413 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
414 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
415 if ( context
.verboseInterposing
)
416 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it
->replacee
);
418 uint32_t cacheOffsetOfReplacee
= (uint32_t)(it
->replacee
- cacheStart
);
419 if (!context
.dyldCache
->addressInText(cacheOffsetOfReplacee
, &imageIndex
))
421 dyld3::closure::ImageNum imageInCache
= imageIndex
+1;
422 if ( context
.verboseInterposing
)
423 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache
, (uint64_t)it
->replacee
);
424 context
.dyldCache
->forEachPatchableExport(imageIndex
, ^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
425 // Skip patching anything other than this symbol
426 if (cacheOffsetOfImpl
!= cacheOffsetOfReplacee
)
428 if ( context
.verboseInterposing
) {
429 const dyld3::closure::Image
* image
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageInCache
);
430 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName
, image
->path());
432 uintptr_t newLoc
= it
->replacement
;
433 context
.dyldCache
->forEachPatchableUseOfExport(imageIndex
, cacheOffsetOfImpl
, ^(dyld_cache_patchable_location patchLocation
) {
434 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
435 #if __has_feature(ptrauth_calls)
436 if ( patchLocation
.authenticated
) {
437 dyld3::MachOLoaded::ChainedFixupPointerOnDisk ptr
= *(dyld3::MachOLoaded::ChainedFixupPointerOnDisk
*)loc
;
438 ptr
.arm64e
.authRebase
.auth
= true;
439 ptr
.arm64e
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
440 ptr
.arm64e
.authRebase
.diversity
= patchLocation
.discriminator
;
441 ptr
.arm64e
.authRebase
.key
= patchLocation
.key
;
442 *loc
= ptr
.arm64e
.signPointer(loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
));
443 if ( context
.verboseInterposing
)
444 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
445 loc
, (void*)*loc
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, DyldSharedCache::keyName(patchLocation
));
449 if ( context
.verboseInterposing
)
450 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
), exportName
);
451 *loc
= newLoc
+ (uintptr_t)DyldSharedCache::getAddend(patchLocation
);
457 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array
[], size_t count
)
459 for(size_t i
=0; i
< count
; ++i
) {
460 ImageLoader::InterposeTuple tuple
;
461 tuple
.replacement
= (uintptr_t)array
[i
].replacement
;
462 tuple
.neverImage
= NULL
;
463 tuple
.onlyImage
= this;
464 tuple
.replacee
= (uintptr_t)array
[i
].replacee
;
465 // chain to any existing interpositions
466 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
467 if ( (it
->replacee
== tuple
.replacee
) && (it
->onlyImage
== this) ) {
468 tuple
.replacee
= it
->replacement
;
471 ImageLoader::fgInterposingTuples
.push_back(tuple
);
475 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
476 void ImageLoader::vmAccountingSetSuspended(const LinkContext
& context
, bool suspend
)
478 #if __arm__ || __arm64__
479 static bool sVmAccountingSuspended
= false;
480 if ( suspend
== sVmAccountingSuspended
)
482 if ( context
.verboseBind
)
483 dyld::log("set vm.footprint_suspend=%d\n", suspend
);
484 int newValue
= suspend
? 1 : 0;
486 size_t newlen
= sizeof(newValue
);
487 size_t oldlen
= sizeof(oldValue
);
488 int ret
= sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
489 if ( context
.verboseBind
&& (ret
!= 0) )
490 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
491 sVmAccountingSuspended
= suspend
;
496 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, bool neverUnload
, const RPathChain
& loaderRPaths
, const char* imagePath
)
498 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
500 // clear error strings
501 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
503 uint64_t t0
= mach_absolute_time();
504 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
, imagePath
);
505 context
.notifyBatch(dyld_image_state_dependents_mapped
, preflightOnly
);
507 // we only do the loading step for preflights
511 uint64_t t1
= mach_absolute_time();
512 context
.clearAllDepths();
513 this->recursiveUpdateDepth(context
.imageCount());
515 __block
uint64_t t2
, t3
, t4
, t5
;
517 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS
, 0, 0, 0);
518 t2
= mach_absolute_time();
519 this->recursiveRebaseWithAccounting(context
);
520 context
.notifyBatch(dyld_image_state_rebased
, false);
522 t3
= mach_absolute_time();
523 if ( !context
.linkingMainExecutable
)
524 this->recursiveBindWithAccounting(context
, forceLazysBound
, neverUnload
);
526 t4
= mach_absolute_time();
527 if ( !context
.linkingMainExecutable
)
528 this->weakBind(context
);
529 t5
= mach_absolute_time();
532 // interpose any dynamically loaded images
533 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
534 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
535 this->recursiveApplyInterposing(context
);
538 // now that all fixups are done, make __DATA_CONST segments read-only
539 if ( !context
.linkingMainExecutable
)
540 this->recursiveMakeDataReadOnly(context
);
542 if ( !context
.linkingMainExecutable
)
543 context
.notifyBatch(dyld_image_state_bound
, false);
544 uint64_t t6
= mach_absolute_time();
546 if ( context
.registerDOFs
!= NULL
) {
547 std::vector
<DOFInfo
> dofs
;
548 this->recursiveGetDOFSections(context
, dofs
);
549 context
.registerDOFs(dofs
);
551 uint64_t t7
= mach_absolute_time();
553 // clear error strings
554 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
556 fgTotalLoadLibrariesTime
+= t1
- t0
;
557 fgTotalRebaseTime
+= t3
- t2
;
558 fgTotalBindTime
+= t4
- t3
;
559 fgTotalWeakBindTime
+= t5
- t4
;
560 fgTotalDOF
+= t7
- t6
;
562 // done with initial dylib loads
563 fgNextPIEDylibAddress
= 0;
567 void ImageLoader::printReferenceCounts()
569 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount
, getPath() );
573 bool ImageLoader::decrementDlopenReferenceCount()
575 if ( fDlopenReferenceCount
== 0 )
577 --fDlopenReferenceCount
;
582 // <rdar://problem/14412057> upward dylib initializers can be run too soon
583 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
584 // have their initialization postponed until after the recursion through downward dylibs
586 void ImageLoader::processInitializers(const LinkContext
& context
, mach_port_t thisThread
,
587 InitializerTimingList
& timingInfo
, ImageLoader::UninitedUpwards
& images
)
589 uint32_t maxImageCount
= context
.imageCount()+2;
590 ImageLoader::UninitedUpwards upsBuffer
[maxImageCount
];
591 ImageLoader::UninitedUpwards
& ups
= upsBuffer
[0];
593 // Calling recursive init on all images in images list, building a new list of
594 // uninitialized upward dependencies.
595 for (uintptr_t i
=0; i
< images
.count
; ++i
) {
596 images
.imagesAndPaths
[i
].first
->recursiveInitialization(context
, thisThread
, images
.imagesAndPaths
[i
].second
, timingInfo
, ups
);
598 // If any upward dependencies remain, init them.
600 processInitializers(context
, thisThread
, timingInfo
, ups
);
604 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
606 uint64_t t1
= mach_absolute_time();
607 mach_port_t thisThread
= mach_thread_self();
608 ImageLoader::UninitedUpwards up
;
610 up
.imagesAndPaths
[0] = { this, this->getPath() };
611 processInitializers(context
, thisThread
, timingInfo
, up
);
612 context
.notifyBatch(dyld_image_state_initialized
, false);
613 mach_port_deallocate(mach_task_self(), thisThread
);
614 uint64_t t2
= mach_absolute_time();
615 fgTotalInitTime
+= (t2
- t1
);
619 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
621 if ( ! fAllLazyPointersBound
) {
622 fAllLazyPointersBound
= true;
625 // bind lower level libraries first
626 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
627 ImageLoader
* dependentImage
= libImage(i
);
628 if ( dependentImage
!= NULL
)
629 dependentImage
->bindAllLazyPointers(context
, recursive
);
632 // bind lazies in this image
633 this->doBindJustLazies(context
);
638 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
640 return fAllLibraryChecksumsAndLoadAddressesMatch
;
644 void ImageLoader::markedUsedRecursive(const std::vector
<DynamicReference
>& dynamicReferences
)
646 // already visited here
651 // clear mark on all statically dependent dylibs
652 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
653 ImageLoader
* dependentImage
= libImage(i
);
654 if ( dependentImage
!= NULL
) {
655 dependentImage
->markedUsedRecursive(dynamicReferences
);
659 // clear mark on all dynamically dependent dylibs
660 for (std::vector
<ImageLoader::DynamicReference
>::const_iterator it
=dynamicReferences
.begin(); it
!= dynamicReferences
.end(); ++it
) {
661 if ( it
->from
== this )
662 it
->to
->markedUsedRecursive(dynamicReferences
);
667 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
)
669 // the purpose of this phase is to make the images sortable such that
670 // in a sort list of images, every image that an image depends on
671 // occurs in the list before it.
676 // get depth of dependents
677 unsigned int minDependentDepth
= maxDepth
;
678 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
679 ImageLoader
* dependentImage
= libImage(i
);
680 if ( (dependentImage
!= NULL
) && !libIsUpward(i
) ) {
681 unsigned int d
= dependentImage
->recursiveUpdateDepth(maxDepth
);
682 if ( d
< minDependentDepth
)
683 minDependentDepth
= d
;
687 // make me less deep then all my dependents
688 fDepth
= minDependentDepth
- 1;
695 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
, const char* loadPath
)
697 if ( fState
< dyld_image_state_dependents_mapped
) {
699 fState
= dyld_image_state_dependents_mapped
;
701 // get list of libraries this image needs
702 DependentLibraryInfo libraryInfos
[fLibraryCount
];
703 this->doGetDependentLibraries(libraryInfos
);
705 // get list of rpaths that this image adds
706 std::vector
<const char*> rpathsFromThisImage
;
707 this->getRPaths(context
, rpathsFromThisImage
);
708 const RPathChain
thisRPaths(&loaderRPaths
, &rpathsFromThisImage
);
711 bool canUsePrelinkingInfo
= true;
712 for(unsigned int i
=0; i
< fLibraryCount
; ++i
){
713 ImageLoader
* dependentLib
;
714 bool depLibReExported
= false;
715 DependentLibraryInfo
& requiredLibInfo
= libraryInfos
[i
];
716 if ( preflightOnly
&& context
.inSharedCache(requiredLibInfo
.name
) ) {
717 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
718 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
719 setLibImage(i
, NULL
, false, false);
724 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, true, this->getPath(), &thisRPaths
, cacheIndex
);
725 if ( dependentLib
== this ) {
726 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
727 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, false, NULL
, NULL
, cacheIndex
);
728 if ( dependentLib
!= this )
729 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
732 dependentLib
->setNeverUnload();
733 if ( requiredLibInfo
.upward
) {
736 dependentLib
->fIsReferencedDownward
= true;
738 LibraryInfo actualInfo
= dependentLib
->doGetLibraryInfo(requiredLibInfo
.info
);
739 depLibReExported
= requiredLibInfo
.reExported
;
740 if ( ! depLibReExported
) {
741 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
742 depLibReExported
= dependentLib
->isSubframeworkOf(context
, this) || this->hasSubLibrary(context
, dependentLib
);
744 // check found library version is compatible
745 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
746 if ( (requiredLibInfo
.info
.minVersion
!= 0xFFFFFFFF) && (actualInfo
.minVersion
< requiredLibInfo
.info
.minVersion
)
747 && ((dyld3::MachOFile
*)(dependentLib
->machHeader()))->enforceCompatVersion() ) {
748 // record values for possible use by CrashReporter or Finder
749 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
750 this->getShortName(), requiredLibInfo
.info
.minVersion
>> 16, (requiredLibInfo
.info
.minVersion
>> 8) & 0xff, requiredLibInfo
.info
.minVersion
& 0xff,
751 dependentLib
->getShortName(), actualInfo
.minVersion
>> 16, (actualInfo
.minVersion
>> 8) & 0xff, actualInfo
.minVersion
& 0xff);
753 // prebinding for this image disabled if any dependent library changed
754 //if ( !depLibCheckSumsMatch )
755 // canUsePrelinkingInfo = false;
756 // prebinding for this image disabled unless both this and dependent are in the shared cache
757 if ( !dependentLib
->inSharedCache() || !this->inSharedCache() )
758 canUsePrelinkingInfo
= false;
760 //if ( context.verbosePrebinding ) {
761 // if ( !requiredLib.checksumMatches )
762 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
763 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
764 // if ( dependentLib->getSlide() != 0 )
765 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
768 catch (const char* msg
) {
769 //if ( context.verbosePrebinding )
770 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
771 if ( requiredLibInfo
.required
) {
772 fState
= dyld_image_state_mapped
;
773 // record values for possible use by CrashReporter or Finder
774 if ( strstr(msg
, "Incompatible library version") != NULL
)
775 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION
, this->getPath(), requiredLibInfo
.name
, NULL
);
776 else if ( strstr(msg
, "architecture") != NULL
)
777 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH
, this->getPath(), requiredLibInfo
.name
, NULL
);
778 else if ( strstr(msg
, "file system sandbox") != NULL
)
779 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX
, this->getPath(), requiredLibInfo
.name
, NULL
);
780 else if ( strstr(msg
, "code signature") != NULL
)
781 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_CODE_SIGNATURE
, this->getPath(), requiredLibInfo
.name
, NULL
);
782 else if ( strstr(msg
, "malformed") != NULL
)
783 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_MALFORMED_MACHO
, this->getPath(), requiredLibInfo
.name
, NULL
);
785 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_MISSING
, this->getPath(), requiredLibInfo
.name
, NULL
);
786 const char* newMsg
= dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo
.name
, this->getRealPath(), msg
);
787 free((void*)msg
); // our free() will do nothing if msg is a string literal
790 free((void*)msg
); // our free() will do nothing if msg is a string literal
791 // ok if weak library not found
793 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
795 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
797 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
799 // tell each to load its dependents
800 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
801 ImageLoader
* dependentImage
= libImage(i
);
802 if ( dependentImage
!= NULL
) {
803 dependentImage
->recursiveLoadLibraries(context
, preflightOnly
, thisRPaths
, libraryInfos
[i
].name
);
807 // do deep prebind check
808 if ( fAllLibraryChecksumsAndLoadAddressesMatch
) {
809 for(unsigned int i
=0; i
< libraryCount(); ++i
){
810 ImageLoader
* dependentImage
= libImage(i
);
811 if ( dependentImage
!= NULL
) {
812 if ( !dependentImage
->allDependentLibrariesAsWhenPreBound() )
813 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
818 // free rpaths (getRPaths() malloc'ed each string)
819 for(std::vector
<const char*>::iterator it
=rpathsFromThisImage
.begin(); it
!= rpathsFromThisImage
.end(); ++it
) {
820 const char* str
= *it
;
828 void ImageLoader::recursiveRebaseWithAccounting(const LinkContext
& context
)
830 this->recursiveRebase(context
);
831 vmAccountingSetSuspended(context
, false);
834 void ImageLoader::recursiveRebase(const LinkContext
& context
)
836 if ( fState
< dyld_image_state_rebased
) {
838 fState
= dyld_image_state_rebased
;
841 // rebase lower level libraries first
842 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
843 ImageLoader
* dependentImage
= libImage(i
);
844 if ( dependentImage
!= NULL
)
845 dependentImage
->recursiveRebase(context
);
852 context
.notifySingle(dyld_image_state_rebased
, this, NULL
);
854 catch (const char* msg
) {
855 // this image is not rebased
856 fState
= dyld_image_state_dependents_mapped
;
857 CRSetCrashLogMessage2(NULL
);
863 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
865 if ( ! fInterposed
) {
870 // interpose lower level libraries first
871 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
872 ImageLoader
* dependentImage
= libImage(i
);
873 if ( dependentImage
!= NULL
)
874 dependentImage
->recursiveApplyInterposing(context
);
877 // interpose this image
878 doInterpose(context
);
880 catch (const char* msg
) {
881 // this image is not interposed
888 void ImageLoader::recursiveMakeDataReadOnly(const LinkContext
& context
)
890 if ( ! fMadeReadOnly
) {
892 fMadeReadOnly
= true;
895 // handle lower level libraries first
896 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
897 ImageLoader
* dependentImage
= libImage(i
);
898 if ( dependentImage
!= NULL
)
899 dependentImage
->recursiveMakeDataReadOnly(context
);
902 // if this image has __DATA_CONST, make that segment read-only
905 catch (const char* msg
) {
906 fMadeReadOnly
= false;
913 void ImageLoader::recursiveBindWithAccounting(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
915 this->recursiveBind(context
, forceLazysBound
, neverUnload
);
916 vmAccountingSetSuspended(context
, false);
919 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
921 // Normally just non-lazy pointers are bound immediately.
922 // The exceptions are:
923 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
924 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
925 if ( fState
< dyld_image_state_bound
) {
927 fState
= dyld_image_state_bound
;
930 // bind lower level libraries first
931 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
932 ImageLoader
* dependentImage
= libImage(i
);
933 if ( dependentImage
!= NULL
)
934 dependentImage
->recursiveBind(context
, forceLazysBound
, neverUnload
);
937 this->doBind(context
, forceLazysBound
);
938 // mark if lazys are also bound
939 if ( forceLazysBound
|| this->usablePrebinding(context
) )
940 fAllLazyPointersBound
= true;
941 // mark as never-unload if requested
943 this->setNeverUnload();
945 context
.notifySingle(dyld_image_state_bound
, this, NULL
);
947 catch (const char* msg
) {
949 fState
= dyld_image_state_rebased
;
950 CRSetCrashLogMessage2(NULL
);
958 // These are mangled symbols for all the variants of operator new and delete
959 // which a main executable can define (non-weak) and override the
960 // weak-def implementation in the OS.
961 static const char* const sTreatAsWeak
[] = {
962 "__Znwm", "__ZnwmRKSt9nothrow_t",
963 "__Znam", "__ZnamRKSt9nothrow_t",
964 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
965 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
966 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
967 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
968 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
969 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
972 size_t ImageLoader::HashCString::hash(const char* v
) {
973 // FIXME: Use hash<string_view> when it has the correct visibility markup
974 return std::hash
<std::string_view
>{}(v
);
977 bool ImageLoader::EqualCString::equal(const char* s1
, const char* s2
) {
978 return strcmp(s1
, s2
) == 0;
981 void ImageLoader::weakBind(const LinkContext
& context
)
984 if (!context
.useNewWeakBind
) {
985 weakBindOld(context
);
989 if ( context
.verboseWeakBind
)
990 dyld::log("dyld: weak bind start:\n");
991 uint64_t t1
= mach_absolute_time();
993 // get set of ImageLoaders that participate in coalecsing
994 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
995 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
996 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
998 // count how many have not already had weakbinding done
999 int countNotYetWeakBound
= 0;
1000 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
1001 for(int i
=0; i
< count
; ++i
) {
1002 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1003 ++countNotYetWeakBound
;
1004 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1005 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1008 // don't need to do any coalescing if only one image has overrides, or all have already been done
1009 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1010 if (!context
.weakDefMapInitialized
) {
1011 // Initialize the weak def map as the link context doesn't run static initializers
1012 new (&context
.weakDefMap
) dyld3::Map
<const char*, std::pair
<const ImageLoader
*, uintptr_t>, ImageLoader::HashCString
, ImageLoader::EqualCString
>();
1013 context
.weakDefMapInitialized
= true;
1015 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1016 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1017 if ( !context
.linkingMainExecutable
) {
1018 // Don't take the memory hit of weak defs on the launch path until we hit a dlopen with more weak symbols to bind
1019 if (!context
.weakDefMapProcessedLaunchDefs
) {
1020 context
.weakDefMapProcessedLaunchDefs
= true;
1022 // Walk the nlist for all binaries from launch and fill in the map with any other weak defs
1023 for (int i
=0; i
< count
; ++i
) {
1024 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1025 // skip images without defs. We've processed launch time refs already
1026 if ( !image
->hasCoalescedExports() )
1028 // Only process binaries which have had their weak symbols bound, ie, not the new ones we are processing now
1030 if ( !image
->weakSymbolsBound(imageIndexes
[i
]) )
1034 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1035 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uintptr_t imageOffset
, bool isFromExportTrie
) {
1036 uintptr_t targetAddr
= (uintptr_t)ma
+ imageOffset
;
1037 if ( isFromExportTrie
) {
1038 // Avoid duplicating the string if we already have the symbol name
1039 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1041 symbolName
= strdup(symbolName
);
1043 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1048 // Walk the nlist for all binaries in dlopen and fill in the map with any other weak defs
1049 for (int i
=0; i
< count
; ++i
) {
1050 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1051 if ( image
->weakSymbolsBound(imageIndexes
[i
]) )
1053 // skip images without defs. We'll process refs later
1054 if ( !image
->hasCoalescedExports() )
1057 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1058 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uintptr_t imageOffset
, bool isFromExportTrie
) {
1059 uintptr_t targetAddr
= (uintptr_t)ma
+ imageOffset
;
1060 if ( isFromExportTrie
) {
1061 // Avoid duplicating the string if we already have the symbol name
1062 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1064 symbolName
= strdup(symbolName
);
1066 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1069 // for all images that need weak binding
1070 for (int i
=0; i
< count
; ++i
) {
1071 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1072 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1073 continue; // weak binding already completed
1074 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1076 if ( context
.verboseWeakBind
)
1077 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1078 // for all symbols that need weak binding in this image
1079 ImageLoader::CoalIterator coalIterator
;
1080 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1081 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1082 const char* nameToCoalesce
= coalIterator
.symbolName
;
1083 uintptr_t targetAddr
= 0;
1084 const ImageLoader
* targetImage
;
1085 // Seatch the map for a previous definition to use
1086 auto weakDefIt
= context
.weakDefMap
.find(nameToCoalesce
);
1087 if ( (weakDefIt
!= context
.weakDefMap
.end()) && (weakDefIt
->second
.first
!= nullptr) ) {
1088 // Found a previous defition
1089 targetImage
= weakDefIt
->second
.first
;
1090 targetAddr
= weakDefIt
->second
.second
;
1092 // scan all images looking for definition to use
1093 for (int j
=0; j
< count
; ++j
) {
1094 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1095 bool anImageInCache
= anImage
->inSharedCache();
1096 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1097 // already coalesced. Only images outside cache can potentially override something in cache.
1098 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1101 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1102 const ImageLoader
* foundIn
;
1103 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1104 if ( sym
!= NULL
) {
1105 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1106 targetImage
= foundIn
;
1107 if ( context
.verboseWeakBind
)
1108 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1113 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1114 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1115 if (weakDefIt
== context
.weakDefMap
.end()) {
1116 if (targetImage
->neverUnload()) {
1117 // Add never unload defs to the map for next time
1118 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1119 if ( context
.verboseWeakBind
) {
1120 dyld::log("dyld: weak binding adding %s to map\n", nameToCoalesce
);
1123 // Add a placeholder for unloadable symbols which makes us fall back to the regular search
1124 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1125 if ( context
.verboseWeakBind
) {
1126 dyld::log("dyld: weak binding adding unloadable placeholder %s to map\n", nameToCoalesce
);
1130 if ( context
.verboseWeakBind
)
1131 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1134 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1138 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1140 // make symbol iterators for each
1141 ImageLoader::CoalIterator iterators
[count
];
1142 ImageLoader::CoalIterator
* sortedIts
[count
];
1143 for(int i
=0; i
< count
; ++i
) {
1144 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1145 sortedIts
[i
] = &iterators
[i
];
1146 if ( context
.verboseWeakBind
)
1147 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1150 // walk all symbols keeping iterators in sync by
1151 // only ever incrementing the iterator with the lowest symbol
1153 while ( doneCount
!= count
) {
1154 //for(int i=0; i < count; ++i)
1155 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1157 // increment iterator with lowest symbol
1158 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1160 // re-sort iterators
1161 for(int i
=1; i
< count
; ++i
) {
1162 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1164 sortedIts
[i
-1]->symbolMatches
= true;
1166 // new one is bigger then next, so swap
1167 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1168 sortedIts
[i
-1] = sortedIts
[i
];
1169 sortedIts
[i
] = temp
;
1174 // process all matching symbols just before incrementing the lowest one that matches
1175 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1176 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1177 // pick first symbol in load order (and non-weak overrides weak)
1178 uintptr_t targetAddr
= 0;
1179 ImageLoader
* targetImage
= NULL
;
1180 unsigned targetImageIndex
= 0;
1181 for(int i
=0; i
< count
; ++i
) {
1182 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1183 if ( context
.verboseWeakBind
)
1184 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1185 if ( iterators
[i
].weakSymbol
) {
1186 if ( targetAddr
== 0 ) {
1187 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1188 if ( targetAddr
!= 0 ) {
1189 targetImage
= iterators
[i
].image
;
1190 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1195 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1196 if ( targetAddr
!= 0 ) {
1197 targetImage
= iterators
[i
].image
;
1198 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1199 // strong implementation found, stop searching
1205 // tell each to bind to this symbol (unless already bound)
1206 if ( targetAddr
!= 0 ) {
1207 if ( context
.verboseWeakBind
) {
1208 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1209 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1211 for(int i
=0; i
< count
; ++i
) {
1212 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1213 if ( context
.verboseWeakBind
) {
1214 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1215 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1216 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1218 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1219 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1220 iterators
[i
].symbolMatches
= false;
1223 if (targetImage
->neverUnload()) {
1224 // Add never unload defs to the map for next time
1225 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1226 if ( context
.verboseWeakBind
) {
1227 dyld::log("dyld: weak binding adding %s to map\n",
1236 for (int i
=0; i
< count
; ++i
) {
1237 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1238 continue; // skip images already processed
1240 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1241 // during binding of references to weak-def symbols, the dyld cache was patched
1242 // but if main executable has non-weak override of operator new or delete it needs is handled here
1243 for (const char* weakSymbolName
: sTreatAsWeak
) {
1244 const ImageLoader
* dummy
;
1245 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1250 // support traditional arm64 app on an arm64e device
1251 // look for weak def symbols in this image which may override the cache
1252 ImageLoader::CoalIterator coaler
;
1253 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1254 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1255 while ( !coaler
.done
) {
1256 const ImageLoader
* dummy
;
1257 // a side effect of resolveWeak() is to patch cache
1258 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1259 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1265 // mark all as having all weak symbols bound
1266 for(int i
=0; i
< count
; ++i
) {
1267 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1272 uint64_t t2
= mach_absolute_time();
1273 fgTotalWeakBindTime
+= t2
- t1
;
1275 if ( context
.verboseWeakBind
)
1276 dyld::log("dyld: weak bind end\n");
1280 void ImageLoader::weakBindOld(const LinkContext
& context
)
1282 if ( context
.verboseWeakBind
)
1283 dyld::log("dyld: weak bind start:\n");
1284 uint64_t t1
= mach_absolute_time();
1285 // get set of ImageLoaders that participate in coalecsing
1286 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
1287 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
1288 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
1290 // count how many have not already had weakbinding done
1291 int countNotYetWeakBound
= 0;
1292 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
1293 for(int i
=0; i
< count
; ++i
) {
1294 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1295 ++countNotYetWeakBound
;
1296 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1297 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1300 // don't need to do any coalescing if only one image has overrides, or all have already been done
1301 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1302 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1303 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1304 if ( !context
.linkingMainExecutable
) {
1305 // for all images that need weak binding
1306 for (int i
=0; i
< count
; ++i
) {
1307 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1308 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1309 continue; // weak binding already completed
1310 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1312 if ( context
.verboseWeakBind
)
1313 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1314 // for all symbols that need weak binding in this image
1315 ImageLoader::CoalIterator coalIterator
;
1316 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1317 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1318 const char* nameToCoalesce
= coalIterator
.symbolName
;
1319 uintptr_t targetAddr
= 0;
1320 const ImageLoader
* targetImage
;
1321 // scan all images looking for definition to use
1322 for (int j
=0; j
< count
; ++j
) {
1323 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1324 bool anImageInCache
= anImage
->inSharedCache();
1325 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1326 // already coalesced. Only images outside cache can potentially override something in cache.
1327 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1330 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1331 const ImageLoader
* foundIn
;
1332 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1333 if ( sym
!= NULL
) {
1334 if ( (foundIn
->getExportedSymbolInfo(sym
) & ImageLoader::kWeakDefinition
) == 0 ) {
1335 // found non-weak def, use it and stop looking
1336 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1337 targetImage
= foundIn
;
1338 if ( context
.verboseWeakBind
)
1339 dyld::log("dyld: found strong %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1343 // found weak-def, only use if no weak found yet
1344 if ( targetAddr
== 0 ) {
1345 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1346 targetImage
= foundIn
;
1347 if ( context
.verboseWeakBind
)
1348 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1353 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1354 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1355 if ( context
.verboseWeakBind
)
1356 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1359 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1363 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1365 // make symbol iterators for each
1366 ImageLoader::CoalIterator iterators
[count
];
1367 ImageLoader::CoalIterator
* sortedIts
[count
];
1368 for(int i
=0; i
< count
; ++i
) {
1369 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1370 sortedIts
[i
] = &iterators
[i
];
1371 if ( context
.verboseWeakBind
)
1372 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1375 // walk all symbols keeping iterators in sync by
1376 // only ever incrementing the iterator with the lowest symbol
1378 while ( doneCount
!= count
) {
1379 //for(int i=0; i < count; ++i)
1380 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1382 // increment iterator with lowest symbol
1383 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1385 // re-sort iterators
1386 for(int i
=1; i
< count
; ++i
) {
1387 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1389 sortedIts
[i
-1]->symbolMatches
= true;
1391 // new one is bigger then next, so swap
1392 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1393 sortedIts
[i
-1] = sortedIts
[i
];
1394 sortedIts
[i
] = temp
;
1399 // process all matching symbols just before incrementing the lowest one that matches
1400 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1401 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1402 // pick first symbol in load order (and non-weak overrides weak)
1403 uintptr_t targetAddr
= 0;
1404 ImageLoader
* targetImage
= NULL
;
1405 unsigned targetImageIndex
= 0;
1406 for(int i
=0; i
< count
; ++i
) {
1407 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1408 if ( context
.verboseWeakBind
)
1409 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1410 if ( iterators
[i
].weakSymbol
) {
1411 if ( targetAddr
== 0 ) {
1412 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1413 if ( targetAddr
!= 0 ) {
1414 targetImage
= iterators
[i
].image
;
1415 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1420 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1421 if ( targetAddr
!= 0 ) {
1422 targetImage
= iterators
[i
].image
;
1423 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1424 // strong implementation found, stop searching
1430 // tell each to bind to this symbol (unless already bound)
1431 if ( targetAddr
!= 0 ) {
1432 if ( context
.verboseWeakBind
) {
1433 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1434 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1436 for(int i
=0; i
< count
; ++i
) {
1437 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1438 if ( context
.verboseWeakBind
) {
1439 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1440 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1441 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1443 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1444 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1445 iterators
[i
].symbolMatches
= false;
1453 for (int i
=0; i
< count
; ++i
) {
1454 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1455 continue; // skip images already processed
1457 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1458 // during binding of references to weak-def symbols, the dyld cache was patched
1459 // but if main executable has non-weak override of operator new or delete it needs is handled here
1460 for (const char* weakSymbolName
: sTreatAsWeak
) {
1461 const ImageLoader
* dummy
;
1462 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1467 // support traditional arm64 app on an arm64e device
1468 // look for weak def symbols in this image which may override the cache
1469 ImageLoader::CoalIterator coaler
;
1470 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1471 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1472 while ( !coaler
.done
) {
1473 const ImageLoader
* dummy
;
1474 // a side effect of resolveWeak() is to patch cache
1475 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1476 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1482 // mark all as having all weak symbols bound
1483 for(int i
=0; i
< count
; ++i
) {
1484 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1489 uint64_t t2
= mach_absolute_time();
1490 fgTotalWeakBindTime
+= t2
- t1
;
1492 if ( context
.verboseWeakBind
)
1493 dyld::log("dyld: weak bind end\n");
1498 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
1500 if ( ! fRegisteredDOF
) {
1502 fRegisteredDOF
= true;
1504 // gather lower level libraries first
1505 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1506 ImageLoader
* dependentImage
= libImage(i
);
1507 if ( dependentImage
!= NULL
)
1508 dependentImage
->recursiveGetDOFSections(context
, dofs
);
1510 this->doGetDOFSections(context
, dofs
);
1514 void ImageLoader::setNeverUnloadRecursive() {
1515 if ( ! fNeverUnload
) {
1517 fNeverUnload
= true;
1519 // gather lower level libraries first
1520 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1521 ImageLoader
* dependentImage
= libImage(i
);
1522 if ( dependentImage
!= NULL
)
1523 dependentImage
->setNeverUnloadRecursive();
1528 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
1530 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1531 // keep trying until success (spin)
1532 #pragma clang diagnostic push
1533 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1534 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
1535 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1536 // the same thread we are on, the increment the lock count, otherwise continue to spin
1537 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
1540 #pragma clang diagnostic pop
1541 ++(fInitializerRecursiveLock
->count
);
1544 void ImageLoader::recursiveSpinUnLock()
1546 if ( --(fInitializerRecursiveLock
->count
) == 0 )
1547 fInitializerRecursiveLock
= NULL
;
1550 void ImageLoader::InitializerTimingList::addTime(const char* name
, uint64_t time
)
1552 for (int i
=0; i
< count
; ++i
) {
1553 if ( strcmp(images
[i
].shortName
, name
) == 0 ) {
1554 images
[i
].initTime
+= time
;
1558 images
[count
].initTime
= time
;
1559 images
[count
].shortName
= name
;
1563 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
, const char* pathToInitialize
,
1564 InitializerTimingList
& timingInfo
, UninitedUpwards
& uninitUps
)
1566 recursive_lock
lock_info(this_thread
);
1567 recursiveSpinLock(lock_info
);
1569 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
1570 uint8_t oldState
= fState
;
1572 fState
= dyld_image_state_dependents_initialized
-1;
1574 // initialize lower level libraries first
1575 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1576 ImageLoader
* dependentImage
= libImage(i
);
1577 if ( dependentImage
!= NULL
) {
1578 // don't try to initialize stuff "above" me yet
1579 if ( libIsUpward(i
) ) {
1580 uninitUps
.imagesAndPaths
[uninitUps
.count
] = { dependentImage
, libPath(i
) };
1583 else if ( dependentImage
->fDepth
>= fDepth
) {
1584 dependentImage
->recursiveInitialization(context
, this_thread
, libPath(i
), timingInfo
, uninitUps
);
1589 // record termination order
1590 if ( this->needsTermination() )
1591 context
.terminationRecorder(this);
1593 // let objc know we are about to initialize this image
1594 uint64_t t1
= mach_absolute_time();
1595 fState
= dyld_image_state_dependents_initialized
;
1597 context
.notifySingle(dyld_image_state_dependents_initialized
, this, &timingInfo
);
1599 // initialize this image
1600 bool hasInitializers
= this->doInitialization(context
);
1602 // let anyone know we finished initializing this image
1603 fState
= dyld_image_state_initialized
;
1605 context
.notifySingle(dyld_image_state_initialized
, this, NULL
);
1607 if ( hasInitializers
) {
1608 uint64_t t2
= mach_absolute_time();
1609 timingInfo
.addTime(this->getShortName(), t2
-t1
);
1612 catch (const char* msg
) {
1613 // this image is not initialized
1615 recursiveSpinUnLock();
1620 recursiveSpinUnLock();
1624 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
1626 static uint64_t sUnitsPerSecond
= 0;
1627 if ( sUnitsPerSecond
== 0 ) {
1628 struct mach_timebase_info timeBaseInfo
;
1629 if ( mach_timebase_info(&timeBaseInfo
) != KERN_SUCCESS
)
1631 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
1633 if ( partTime
< sUnitsPerSecond
) {
1634 uint32_t milliSecondsTimesHundred
= (uint32_t)((partTime
*100000)/sUnitsPerSecond
);
1635 uint32_t milliSeconds
= (uint32_t)(milliSecondsTimesHundred
/100);
1636 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1637 uint32_t percent
= percentTimesTen
/10;
1638 if ( milliSeconds
>= 100 )
1639 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1640 else if ( milliSeconds
>= 10 )
1641 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1643 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1646 uint32_t secondsTimeTen
= (uint32_t)((partTime
*10)/sUnitsPerSecond
);
1647 uint32_t seconds
= secondsTimeTen
/10;
1648 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1649 uint32_t percent
= percentTimesTen
/10;
1650 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
1654 static char* commatize(uint64_t in
, char* out
)
1656 uint64_t div10
= in
/ 10;
1657 uint8_t delta
= in
- div10
*10;
1661 *(--s
) = '0' + delta
;
1664 if ( (digitCount
% 3) == 0 )
1667 delta
= in
- div10
*10;
1668 *(--s
) = '0' + delta
;
1676 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1678 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1680 uint64_t totalDyldTime
= totalTime
- fgTotalDebuggerPausedTime
- fgTotalRebindCacheTime
;
1681 printTime("Total pre-main time", totalDyldTime
, totalDyldTime
);
1682 printTime(" dylib loading time", fgTotalLoadLibrariesTime
-fgTotalDebuggerPausedTime
, totalDyldTime
);
1683 printTime(" rebase/binding time", fgTotalRebaseTime
+fgTotalBindTime
+fgTotalWeakBindTime
-fgTotalRebindCacheTime
, totalDyldTime
);
1684 printTime(" ObjC setup time", fgTotalObjCSetupTime
, totalDyldTime
);
1685 printTime(" initializer time", fgTotalInitTime
-fgTotalObjCSetupTime
, totalDyldTime
);
1686 dyld::log(" slowest intializers :\n");
1687 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1688 uint64_t t
= timingInfo
.images
[i
].initTime
;
1689 if ( t
*50 < totalDyldTime
)
1691 dyld::log("%30s ", timingInfo
.images
[i
].shortName
);
1692 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1693 t
-= fgTotalObjCSetupTime
;
1694 printTime("", t
, totalDyldTime
);
1699 void ImageLoader::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1701 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1705 printTime(" total time", totalTime
, totalTime
);
1706 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1707 dyld::log(" total segments mapped: %u, into %llu pages\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096);
1708 printTime(" total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
1709 printTime(" total load time in ObjC", fgTotalObjCSetupTime
, totalTime
);
1710 printTime(" total debugger pause time", fgTotalDebuggerPausedTime
, totalTime
);
1711 printTime(" total dtrace DOF registration time", fgTotalDOF
, totalTime
);
1712 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
1713 printTime(" total rebase fixups time", fgTotalRebaseTime
, totalTime
);
1714 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
1715 if ( fgTotalBindSymbolsResolved
!= 0 ) {
1716 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
1717 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
1718 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
1719 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1720 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
1722 printTime(" total binding fixups time", fgTotalBindTime
, totalTime
);
1723 printTime(" total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
1724 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime
, totalTime
);
1725 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
1726 printTime(" total time in initializers and ObjC +load", fgTotalInitTime
-fgTotalObjCSetupTime
, totalTime
);
1727 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1728 uint64_t t
= timingInfo
.images
[i
].initTime
;
1729 if ( t
*1000 < totalTime
)
1731 dyld::log("%42s ", timingInfo
.images
[i
].shortName
);
1732 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1733 t
-= fgTotalObjCSetupTime
;
1734 printTime("", t
, totalTime
);
1741 // copy path and add suffix to result
1743 // /path/foo.dylib _debug => /path/foo_debug.dylib
1744 // foo.dylib _debug => foo_debug.dylib
1745 // foo _debug => foo_debug
1746 // /path/bar _debug => /path/bar_debug
1747 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1749 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1751 strcpy(result
, path
);
1753 char* start
= strrchr(result
, '/');
1754 if ( start
!= NULL
)
1759 char* dot
= strrchr(start
, '.');
1760 if ( dot
!= NULL
) {
1761 strcpy(dot
, suffix
);
1762 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1765 strcat(result
, suffix
);
1771 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1772 // to enable it to be re-written in assembler if needed.
1774 const uint8_t* ImageLoader::trieWalk(const uint8_t* start
, const uint8_t* end
, const char* s
)
1776 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1777 ++fgSymbolTrieSearchs
;
1778 const uint8_t* p
= start
;
1779 while ( p
!= NULL
) {
1780 uintptr_t terminalSize
= *p
++;
1781 if ( terminalSize
> 127 ) {
1782 // except for re-export-with-rename, all terminal sizes fit in one byte
1784 terminalSize
= read_uleb128(p
, end
);
1786 if ( (*s
== '\0') && (terminalSize
!= 0) ) {
1787 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1790 const uint8_t* children
= p
+ terminalSize
;
1791 if ( children
> end
) {
1792 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize
);
1795 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1796 uint8_t childrenRemaining
= *children
++;
1798 uintptr_t nodeOffset
= 0;
1799 for (; childrenRemaining
> 0; --childrenRemaining
) {
1801 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1802 bool wrongEdge
= false;
1803 // scan whole edge to get to next edge
1804 // if edge is longer than target symbol name, don't read past end of symbol name
1806 while ( c
!= '\0' ) {
1816 // advance to next child
1817 ++p
; // skip over zero terminator
1818 // skip over uleb128 until last byte is found
1819 while ( (*p
& 0x80) != 0 )
1821 ++p
; // skip over last byte of uleb128
1823 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1828 // the symbol so far matches this edge (child)
1829 // so advance to the child's node
1831 nodeOffset
= read_uleb128(p
, end
);
1832 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
1833 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset
);
1837 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1841 if ( nodeOffset
!= 0 )
1842 p
= &start
[nodeOffset
];
1846 //dyld::log("trieWalk(%p) return NULL\n", start);
1852 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p
, const uint8_t* end
)
1854 uint64_t result
= 0;
1858 dyld::throwf("malformed uleb128");
1860 uint64_t slice
= *p
& 0x7f;
1863 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit
, result
);
1865 result
|= (slice
<< bit
);
1868 } while (*p
++ & 0x80);
1869 return (uintptr_t)result
;
1873 intptr_t ImageLoader::read_sleb128(const uint8_t*& p
, const uint8_t* end
)
1880 throw "malformed sleb128";
1882 result
|= (((int64_t)(byte
& 0x7f)) << bit
);
1884 } while (byte
& 0x80);
1885 // sign extend negative numbers
1886 if ( (byte
& 0x40) != 0 )
1887 result
|= (~0ULL) << bit
;
1888 return (intptr_t)result
;
1892 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple
);
1893 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair
);