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)
91 fPathHash
= hash(fPath
);
93 dyld::throwf("too many dependent dylibs in %s", path
);
97 void ImageLoader::deleteImage(ImageLoader
* image
)
103 ImageLoader::~ImageLoader()
105 if ( fRealPath
!= NULL
)
107 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
110 if ( fAotPath
!= NULL
)
115 void ImageLoader::setFileInfo(dev_t device
, ino_t inode
, time_t modDate
)
119 fLastModified
= modDate
;
122 void ImageLoader::setMapped(const LinkContext
& context
)
124 fState
= dyld_image_state_mapped
;
125 context
.notifySingle(dyld_image_state_mapped
, this, NULL
); // note: can throw exception
128 int ImageLoader::compare(const ImageLoader
* right
) const
130 if ( this->fDepth
== right
->fDepth
) {
131 if ( this->fLoadOrder
== right
->fLoadOrder
)
133 else if ( this->fLoadOrder
< right
->fLoadOrder
)
139 if ( this->fDepth
< right
->fDepth
)
146 void ImageLoader::setPath(const char* path
)
148 if ( fPathOwnedByImage
&& (fPath
!= NULL
) )
150 fPath
= new char[strlen(path
)+1];
151 strcpy((char*)fPath
, path
);
152 fPathOwnedByImage
= true; // delete fPath when this image is destructed
153 fPathHash
= hash(fPath
);
154 if ( fRealPath
!= NULL
) {
160 void ImageLoader::setPathUnowned(const char* path
)
162 if ( fPathOwnedByImage
&& (fPath
!= NULL
) ) {
166 fPathOwnedByImage
= false;
167 fPathHash
= hash(fPath
);
170 void ImageLoader::setPaths(const char* path
, const char* realPath
)
173 fRealPath
= new char[strlen(realPath
)+1];
174 strcpy((char*)fRealPath
, realPath
);
178 const char* ImageLoader::getRealPath() const
180 if ( fRealPath
!= NULL
)
186 uint32_t ImageLoader::hash(const char* path
)
188 // this does not need to be a great hash
189 // it is just used to reduce the number of strcmp() calls
190 // of existing images when loading a new image
192 for (const char* s
=path
; *s
!= '\0'; ++s
)
197 bool ImageLoader::matchInstallPath() const
199 return fMatchByInstallName
;
202 void ImageLoader::setMatchInstallPath(bool match
)
204 fMatchByInstallName
= match
;
207 bool ImageLoader::statMatch(const struct stat
& stat_buf
) const
209 return ( (this->fDevice
== stat_buf
.st_dev
) && (this->fInode
== stat_buf
.st_ino
) );
212 const char* ImageLoader::shortName(const char* fullName
)
214 // try to return leaf name
215 if ( fullName
!= NULL
) {
216 const char* s
= strrchr(fullName
, '/');
223 const char* ImageLoader::getShortName() const
225 return shortName(fPath
);
228 void ImageLoader::setLeaveMapped()
233 void ImageLoader::setHideExports(bool hide
)
238 bool ImageLoader::hasHiddenExports() const
243 bool ImageLoader::isLinked() const
245 return (fState
>= dyld_image_state_bound
);
248 time_t ImageLoader::lastModified() const
250 return fLastModified
;
253 bool ImageLoader::containsAddress(const void* addr
) const
255 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
256 const uint8_t* start
= (const uint8_t*)segActualLoadAddress(i
);
257 const uint8_t* end
= (const uint8_t*)segActualEndAddress(i
);
258 if ( (start
<= addr
) && (addr
< end
) && !segUnaccessible(i
) )
264 bool ImageLoader::overlapsWithAddressRange(const void* start
, const void* end
) const
266 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
267 const uint8_t* segStart
= (const uint8_t*)segActualLoadAddress(i
);
268 const uint8_t* segEnd
= (const uint8_t*)segActualEndAddress(i
);
269 if ( strcmp(segName(i
), "__UNIXSTACK") == 0 ) {
270 // __UNIXSTACK never slides. This is the only place that cares
271 // and checking for that segment name in segActualLoadAddress()
273 segStart
-= getSlide();
274 segEnd
-= getSlide();
276 if ( (start
<= segStart
) && (segStart
< end
) )
278 if ( (start
<= segEnd
) && (segEnd
< end
) )
280 if ( (segStart
< start
) && (end
< segEnd
) )
286 void ImageLoader::getMappedRegions(MappedRegion
*& regions
) const
288 for(unsigned int i
=0, e
=segmentCount(); i
< e
; ++i
) {
290 region
.address
= segActualLoadAddress(i
);
291 region
.size
= segSize(i
);
298 bool ImageLoader::dependsOn(ImageLoader
* image
) {
299 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
300 if ( libImage(i
) == image
)
307 static bool notInImgageList(const ImageLoader
* image
, const ImageLoader
** dsiStart
, const ImageLoader
** dsiCur
)
309 for (const ImageLoader
** p
= dsiStart
; p
< dsiCur
; ++p
)
315 bool ImageLoader::findExportedSymbolAddress(const LinkContext
& context
, const char* symbolName
,
316 const ImageLoader
* requestorImage
, int requestorOrdinalOfDef
,
317 bool runResolver
, const ImageLoader
** foundIn
, uintptr_t* address
) const
319 const Symbol
* sym
= this->findExportedSymbol(symbolName
, true, foundIn
);
321 *address
= (*foundIn
)->getExportedSymbolAddress(sym
, context
, requestorImage
, runResolver
);
328 // private method that handles circular dependencies by only search any image once
329 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name
,
330 const ImageLoader
** dsiStart
, const ImageLoader
**& dsiCur
, const ImageLoader
** dsiEnd
, const ImageLoader
** foundIn
) const
332 const ImageLoader::Symbol
* sym
;
334 if ( notInImgageList(this, dsiStart
, dsiCur
) ) {
335 sym
= this->findExportedSymbol(name
, false, this->getPath(), foundIn
);
341 // search directly dependent libraries
342 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
343 ImageLoader
* dependentImage
= libImage(i
);
344 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
345 sym
= dependentImage
->findExportedSymbol(name
, false, libPath(i
), foundIn
);
351 // search indirectly dependent libraries
352 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
353 ImageLoader
* dependentImage
= libImage(i
);
354 if ( (dependentImage
!= NULL
) && notInImgageList(dependentImage
, dsiStart
, dsiCur
) ) {
355 *dsiCur
++ = dependentImage
;
356 sym
= dependentImage
->findExportedSymbolInDependentImagesExcept(name
, dsiStart
, dsiCur
, dsiEnd
, foundIn
);
366 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
368 unsigned int imageCount
= context
.imageCount()+2;
369 const ImageLoader
* dontSearchImages
[imageCount
];
370 dontSearchImages
[0] = this; // don't search this image
371 const ImageLoader
** cur
= &dontSearchImages
[1];
372 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
375 const ImageLoader::Symbol
* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name
, const LinkContext
& context
, const ImageLoader
** foundIn
) const
377 unsigned int imageCount
= context
.imageCount()+2;
378 const ImageLoader
* dontSearchImages
[imageCount
];
379 const ImageLoader
** cur
= &dontSearchImages
[0];
380 return this->findExportedSymbolInDependentImagesExcept(name
, &dontSearchImages
[0], cur
, &dontSearchImages
[imageCount
], foundIn
);
383 // this is called by initializeMainExecutable() to interpose on the initial set of images
384 void ImageLoader::applyInterposing(const LinkContext
& context
)
386 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
387 if ( fgInterposingTuples
.size() != 0 )
388 this->recursiveApplyInterposing(context
);
392 uintptr_t ImageLoader::interposedAddress(const LinkContext
& context
, uintptr_t address
, const ImageLoader
* inImage
, const ImageLoader
* onlyInImage
)
394 //dyld::log("interposedAddress(0x%08llX), tupleCount=%lu\n", (uint64_t)address, fgInterposingTuples.size());
395 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
396 //dyld::log(" interposedAddress: replacee=0x%08llX, replacement=0x%08llX, neverImage=%p, onlyImage=%p, inImage=%p\n",
397 // (uint64_t)it->replacee, (uint64_t)it->replacement, it->neverImage, it->onlyImage, inImage);
398 // replace all references to 'replacee' with 'replacement'
399 if ( (address
== it
->replacee
) && (inImage
!= it
->neverImage
) && ((it
->onlyImage
== NULL
) || (inImage
== it
->onlyImage
)) ) {
400 if ( context
.verboseInterposing
) {
401 dyld::log("dyld interposing: replace 0x%lX with 0x%lX\n", it
->replacee
, it
->replacement
);
403 return it
->replacement
;
409 void ImageLoader::applyInterposingToDyldCache(const LinkContext
& context
) {
410 if (!context
.dyldCache
)
412 if (!context
.dyldCache
->header
.builtFromChainedFixups
)
414 if (fgInterposingTuples
.empty())
416 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
417 // that image and apply its patch table to all uses.
418 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
419 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
420 if ( context
.verboseInterposing
)
421 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it
->replacee
);
423 uint32_t cacheOffsetOfReplacee
= (uint32_t)(it
->replacee
- cacheStart
);
424 if (!context
.dyldCache
->addressInText(cacheOffsetOfReplacee
, &imageIndex
))
426 dyld3::closure::ImageNum imageInCache
= imageIndex
+1;
427 if ( context
.verboseInterposing
)
428 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache
, (uint64_t)it
->replacee
);
429 context
.dyldCache
->forEachPatchableExport(imageIndex
, ^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
430 // Skip patching anything other than this symbol
431 if (cacheOffsetOfImpl
!= cacheOffsetOfReplacee
)
433 if ( context
.verboseInterposing
) {
434 const dyld3::closure::Image
* image
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageInCache
);
435 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName
, image
->path());
437 uintptr_t newLoc
= it
->replacement
;
438 context
.dyldCache
->forEachPatchableUseOfExport(imageIndex
, cacheOffsetOfImpl
, ^(dyld_cache_patchable_location patchLocation
) {
439 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
440 #if __has_feature(ptrauth_calls)
441 if ( patchLocation
.authenticated
) {
442 dyld3::MachOLoaded::ChainedFixupPointerOnDisk ptr
= *(dyld3::MachOLoaded::ChainedFixupPointerOnDisk
*)loc
;
443 ptr
.arm64e
.authRebase
.auth
= true;
444 ptr
.arm64e
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
445 ptr
.arm64e
.authRebase
.diversity
= patchLocation
.discriminator
;
446 ptr
.arm64e
.authRebase
.key
= patchLocation
.key
;
447 *loc
= ptr
.arm64e
.signPointer(loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
));
448 if ( context
.verboseInterposing
)
449 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
450 loc
, (void*)*loc
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, DyldSharedCache::keyName(patchLocation
));
454 if ( context
.verboseInterposing
)
455 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
), exportName
);
456 *loc
= newLoc
+ (uintptr_t)DyldSharedCache::getAddend(patchLocation
);
462 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array
[], size_t count
)
464 for(size_t i
=0; i
< count
; ++i
) {
465 ImageLoader::InterposeTuple tuple
;
466 tuple
.replacement
= (uintptr_t)array
[i
].replacement
;
467 tuple
.neverImage
= NULL
;
468 tuple
.onlyImage
= this;
469 tuple
.replacee
= (uintptr_t)array
[i
].replacee
;
470 // chain to any existing interpositions
471 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
472 if ( (it
->replacee
== tuple
.replacee
) && (it
->onlyImage
== this) ) {
473 tuple
.replacee
= it
->replacement
;
476 ImageLoader::fgInterposingTuples
.push_back(tuple
);
480 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
481 void ImageLoader::vmAccountingSetSuspended(const LinkContext
& context
, bool suspend
)
483 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
484 static bool sVmAccountingSuspended
= false;
485 if ( suspend
== sVmAccountingSuspended
)
487 if ( context
.verboseBind
)
488 dyld::log("set vm.footprint_suspend=%d\n", suspend
);
489 int newValue
= suspend
? 1 : 0;
491 size_t newlen
= sizeof(newValue
);
492 size_t oldlen
= sizeof(oldValue
);
493 int ret
= sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
494 if ( context
.verboseBind
&& (ret
!= 0) )
495 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
496 sVmAccountingSuspended
= suspend
;
501 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, bool neverUnload
, const RPathChain
& loaderRPaths
, const char* imagePath
)
503 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
505 // clear error strings
506 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
508 uint64_t t0
= mach_absolute_time();
509 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
, imagePath
);
510 context
.notifyBatch(dyld_image_state_dependents_mapped
, preflightOnly
);
512 // we only do the loading step for preflights
516 uint64_t t1
= mach_absolute_time();
517 context
.clearAllDepths();
518 this->updateDepth(context
.imageCount());
520 __block
uint64_t t2
, t3
, t4
, t5
;
522 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS
, 0, 0, 0);
523 t2
= mach_absolute_time();
524 this->recursiveRebaseWithAccounting(context
);
525 context
.notifyBatch(dyld_image_state_rebased
, false);
527 t3
= mach_absolute_time();
528 if ( !context
.linkingMainExecutable
)
529 this->recursiveBindWithAccounting(context
, forceLazysBound
, neverUnload
);
531 t4
= mach_absolute_time();
532 if ( !context
.linkingMainExecutable
)
533 this->weakBind(context
);
534 t5
= mach_absolute_time();
537 // interpose any dynamically loaded images
538 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
539 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
540 this->recursiveApplyInterposing(context
);
543 // now that all fixups are done, make __DATA_CONST segments read-only
544 if ( !context
.linkingMainExecutable
)
545 this->recursiveMakeDataReadOnly(context
);
547 if ( !context
.linkingMainExecutable
)
548 context
.notifyBatch(dyld_image_state_bound
, false);
549 uint64_t t6
= mach_absolute_time();
551 if ( context
.registerDOFs
!= NULL
) {
552 std::vector
<DOFInfo
> dofs
;
553 this->recursiveGetDOFSections(context
, dofs
);
554 context
.registerDOFs(dofs
);
556 uint64_t t7
= mach_absolute_time();
558 // clear error strings
559 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
561 fgTotalLoadLibrariesTime
+= t1
- t0
;
562 fgTotalRebaseTime
+= t3
- t2
;
563 fgTotalBindTime
+= t4
- t3
;
564 fgTotalWeakBindTime
+= t5
- t4
;
565 fgTotalDOF
+= t7
- t6
;
567 // done with initial dylib loads
568 fgNextPIEDylibAddress
= 0;
572 void ImageLoader::printReferenceCounts()
574 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount
, getPath() );
578 bool ImageLoader::decrementDlopenReferenceCount()
580 if ( fDlopenReferenceCount
== 0 )
582 --fDlopenReferenceCount
;
587 // <rdar://problem/14412057> upward dylib initializers can be run too soon
588 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
589 // have their initialization postponed until after the recursion through downward dylibs
591 void ImageLoader::processInitializers(const LinkContext
& context
, mach_port_t thisThread
,
592 InitializerTimingList
& timingInfo
, ImageLoader::UninitedUpwards
& images
)
594 uint32_t maxImageCount
= context
.imageCount()+2;
595 ImageLoader::UninitedUpwards upsBuffer
[maxImageCount
];
596 ImageLoader::UninitedUpwards
& ups
= upsBuffer
[0];
598 // Calling recursive init on all images in images list, building a new list of
599 // uninitialized upward dependencies.
600 for (uintptr_t i
=0; i
< images
.count
; ++i
) {
601 images
.imagesAndPaths
[i
].first
->recursiveInitialization(context
, thisThread
, images
.imagesAndPaths
[i
].second
, timingInfo
, ups
);
603 // If any upward dependencies remain, init them.
605 processInitializers(context
, thisThread
, timingInfo
, ups
);
609 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
611 uint64_t t1
= mach_absolute_time();
612 mach_port_t thisThread
= mach_thread_self();
613 ImageLoader::UninitedUpwards up
;
615 up
.imagesAndPaths
[0] = { this, this->getPath() };
616 processInitializers(context
, thisThread
, timingInfo
, up
);
617 context
.notifyBatch(dyld_image_state_initialized
, false);
618 mach_port_deallocate(mach_task_self(), thisThread
);
619 uint64_t t2
= mach_absolute_time();
620 fgTotalInitTime
+= (t2
- t1
);
624 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
626 if ( ! fAllLazyPointersBound
) {
627 fAllLazyPointersBound
= true;
630 // bind lower level libraries first
631 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
632 ImageLoader
* dependentImage
= libImage(i
);
633 if ( dependentImage
!= NULL
)
634 dependentImage
->bindAllLazyPointers(context
, recursive
);
637 // bind lazies in this image
638 this->doBindJustLazies(context
);
643 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
645 return fAllLibraryChecksumsAndLoadAddressesMatch
;
649 void ImageLoader::markedUsedRecursive(const std::vector
<DynamicReference
>& dynamicReferences
)
651 // already visited here
656 // clear mark on all statically dependent dylibs
657 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
658 ImageLoader
* dependentImage
= libImage(i
);
659 if ( dependentImage
!= NULL
) {
660 dependentImage
->markedUsedRecursive(dynamicReferences
);
664 // clear mark on all dynamically dependent dylibs
665 for (std::vector
<ImageLoader::DynamicReference
>::const_iterator it
=dynamicReferences
.begin(); it
!= dynamicReferences
.end(); ++it
) {
666 if ( it
->from
== this )
667 it
->to
->markedUsedRecursive(dynamicReferences
);
672 unsigned int ImageLoader::updateDepth(unsigned int maxDepth
)
674 STACK_ALLOC_ARRAY(ImageLoader
*, danglingUpwards
, maxDepth
);
675 unsigned int depth
= this->recursiveUpdateDepth(maxDepth
, danglingUpwards
);
676 for (auto& danglingUpward
: danglingUpwards
) {
677 if ( danglingUpward
->fDepth
!= 0)
679 danglingUpward
->recursiveUpdateDepth(maxDepth
, danglingUpwards
);
684 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
, dyld3::Array
<ImageLoader
*>& danglingUpwards
)
686 // the purpose of this phase is to make the images sortable such that
687 // in a sort list of images, every image that an image depends on
688 // occurs in the list before it.
693 // get depth of dependents
694 unsigned int minDependentDepth
= maxDepth
;
695 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
696 ImageLoader
* dependentImage
= libImage(i
);
697 if ( dependentImage
!= NULL
) {
698 if ( libIsUpward(i
) ) {
699 if ( dependentImage
->fDepth
== 0) {
700 if ( !danglingUpwards
.contains(dependentImage
) )
701 danglingUpwards
.push_back(dependentImage
);
704 unsigned int d
= dependentImage
->recursiveUpdateDepth(maxDepth
, danglingUpwards
);
705 if ( d
< minDependentDepth
)
706 minDependentDepth
= d
;
709 // <rdar://problem/60878811> make sure need to re-bind propagates up
710 if ( dependentImage
!= NULL
) {
711 if ( fAllLibraryChecksumsAndLoadAddressesMatch
&& !dependentImage
->fAllLibraryChecksumsAndLoadAddressesMatch
) {
712 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
716 // make me less deep then all my dependents
717 fDepth
= minDependentDepth
- 1;
724 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
, const char* loadPath
)
726 if ( fState
< dyld_image_state_dependents_mapped
) {
728 fState
= dyld_image_state_dependents_mapped
;
730 // get list of libraries this image needs
731 DependentLibraryInfo libraryInfos
[fLibraryCount
];
732 this->doGetDependentLibraries(libraryInfos
);
734 // get list of rpaths that this image adds
735 std::vector
<const char*> rpathsFromThisImage
;
736 this->getRPaths(context
, rpathsFromThisImage
);
737 const RPathChain
thisRPaths(&loaderRPaths
, &rpathsFromThisImage
);
740 bool canUsePrelinkingInfo
= true;
741 for(unsigned int i
=0; i
< fLibraryCount
; ++i
){
742 ImageLoader
* dependentLib
;
743 bool depLibReExported
= false;
744 DependentLibraryInfo
& requiredLibInfo
= libraryInfos
[i
];
745 if ( preflightOnly
&& context
.inSharedCache(requiredLibInfo
.name
) ) {
746 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
747 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
748 setLibImage(i
, NULL
, false, false);
753 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, true, this->getPath(), &thisRPaths
, cacheIndex
);
754 if ( dependentLib
== this ) {
755 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
756 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, false, NULL
, NULL
, cacheIndex
);
757 if ( dependentLib
!= this )
758 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
761 dependentLib
->setNeverUnload();
762 if ( requiredLibInfo
.upward
) {
765 dependentLib
->fIsReferencedDownward
= true;
767 LibraryInfo actualInfo
= dependentLib
->doGetLibraryInfo(requiredLibInfo
.info
);
768 depLibReExported
= requiredLibInfo
.reExported
;
769 if ( ! depLibReExported
) {
770 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
771 depLibReExported
= dependentLib
->isSubframeworkOf(context
, this) || this->hasSubLibrary(context
, dependentLib
);
773 // check found library version is compatible
774 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
775 if ( (requiredLibInfo
.info
.minVersion
!= 0xFFFFFFFF) && (actualInfo
.minVersion
< requiredLibInfo
.info
.minVersion
)
776 && ((dyld3::MachOFile
*)(dependentLib
->machHeader()))->enforceCompatVersion() ) {
777 // record values for possible use by CrashReporter or Finder
778 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
779 this->getShortName(), requiredLibInfo
.info
.minVersion
>> 16, (requiredLibInfo
.info
.minVersion
>> 8) & 0xff, requiredLibInfo
.info
.minVersion
& 0xff,
780 dependentLib
->getShortName(), actualInfo
.minVersion
>> 16, (actualInfo
.minVersion
>> 8) & 0xff, actualInfo
.minVersion
& 0xff);
782 // prebinding for this image disabled if any dependent library changed
783 //if ( !depLibCheckSumsMatch )
784 // canUsePrelinkingInfo = false;
785 // prebinding for this image disabled unless both this and dependent are in the shared cache
786 if ( !dependentLib
->inSharedCache() || !this->inSharedCache() )
787 canUsePrelinkingInfo
= false;
789 //if ( context.verbosePrebinding ) {
790 // if ( !requiredLib.checksumMatches )
791 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
792 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
793 // if ( dependentLib->getSlide() != 0 )
794 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
797 catch (const char* msg
) {
798 //if ( context.verbosePrebinding )
799 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
800 if ( requiredLibInfo
.required
) {
801 fState
= dyld_image_state_mapped
;
802 // record values for possible use by CrashReporter or Finder
803 if ( strstr(msg
, "Incompatible library version") != NULL
)
804 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION
, this->getPath(), requiredLibInfo
.name
, NULL
);
805 else if ( strstr(msg
, "architecture") != NULL
)
806 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH
, this->getPath(), requiredLibInfo
.name
, NULL
);
807 else if ( strstr(msg
, "file system sandbox") != NULL
)
808 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX
, this->getPath(), requiredLibInfo
.name
, NULL
);
809 else if ( strstr(msg
, "code signature") != NULL
)
810 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_CODE_SIGNATURE
, this->getPath(), requiredLibInfo
.name
, NULL
);
811 else if ( strstr(msg
, "malformed") != NULL
)
812 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_MALFORMED_MACHO
, this->getPath(), requiredLibInfo
.name
, NULL
);
814 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_MISSING
, this->getPath(), requiredLibInfo
.name
, NULL
);
815 const char* newMsg
= dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo
.name
, this->getRealPath(), msg
);
816 free((void*)msg
); // our free() will do nothing if msg is a string literal
819 free((void*)msg
); // our free() will do nothing if msg is a string literal
820 // ok if weak library not found
822 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
824 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
826 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
828 // tell each to load its dependents
829 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
830 ImageLoader
* dependentImage
= libImage(i
);
831 if ( dependentImage
!= NULL
) {
832 dependentImage
->recursiveLoadLibraries(context
, preflightOnly
, thisRPaths
, libraryInfos
[i
].name
);
835 // do deep prebind check
836 if ( fAllLibraryChecksumsAndLoadAddressesMatch
) {
837 for(unsigned int i
=0; i
< libraryCount(); ++i
){
838 ImageLoader
* dependentImage
= libImage(i
);
839 if ( dependentImage
!= NULL
) {
840 if ( !dependentImage
->allDependentLibrariesAsWhenPreBound() )
841 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
846 // free rpaths (getRPaths() malloc'ed each string)
847 for(std::vector
<const char*>::iterator it
=rpathsFromThisImage
.begin(); it
!= rpathsFromThisImage
.end(); ++it
) {
848 const char* str
= *it
;
856 void ImageLoader::recursiveRebaseWithAccounting(const LinkContext
& context
)
858 this->recursiveRebase(context
);
859 vmAccountingSetSuspended(context
, false);
862 void ImageLoader::recursiveRebase(const LinkContext
& context
)
864 if ( fState
< dyld_image_state_rebased
) {
866 fState
= dyld_image_state_rebased
;
869 // rebase lower level libraries first
870 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
871 ImageLoader
* dependentImage
= libImage(i
);
872 if ( dependentImage
!= NULL
)
873 dependentImage
->recursiveRebase(context
);
880 context
.notifySingle(dyld_image_state_rebased
, this, NULL
);
882 catch (const char* msg
) {
883 // this image is not rebased
884 fState
= dyld_image_state_dependents_mapped
;
885 CRSetCrashLogMessage2(NULL
);
891 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
893 if ( ! fInterposed
) {
898 // interpose lower level libraries first
899 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
900 ImageLoader
* dependentImage
= libImage(i
);
901 if ( dependentImage
!= NULL
)
902 dependentImage
->recursiveApplyInterposing(context
);
905 // interpose this image
906 doInterpose(context
);
908 catch (const char* msg
) {
909 // this image is not interposed
916 void ImageLoader::recursiveMakeDataReadOnly(const LinkContext
& context
)
918 if ( ! fMadeReadOnly
) {
920 fMadeReadOnly
= true;
923 // handle lower level libraries first
924 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
925 ImageLoader
* dependentImage
= libImage(i
);
926 if ( dependentImage
!= NULL
)
927 dependentImage
->recursiveMakeDataReadOnly(context
);
930 // if this image has __DATA_CONST, make that segment read-only
933 catch (const char* msg
) {
934 fMadeReadOnly
= false;
941 void ImageLoader::recursiveBindWithAccounting(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
943 this->recursiveBind(context
, forceLazysBound
, neverUnload
, nullptr);
944 vmAccountingSetSuspended(context
, false);
947 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
, const ImageLoader
* parent
)
949 // Normally just non-lazy pointers are bound immediately.
950 // The exceptions are:
951 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
952 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
953 if ( fState
< dyld_image_state_bound
) {
955 fState
= dyld_image_state_bound
;
958 // bind lower level libraries first
959 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
960 ImageLoader
* dependentImage
= libImage(i
);
961 if ( dependentImage
!= NULL
) {
962 const ImageLoader
* reExportParent
= nullptr;
963 if ( libReExported(i
) )
964 reExportParent
= this;
965 dependentImage
->recursiveBind(context
, forceLazysBound
, neverUnload
, reExportParent
);
969 this->doBind(context
, forceLazysBound
, parent
);
970 // mark if lazys are also bound
971 if ( forceLazysBound
|| this->usablePrebinding(context
) )
972 fAllLazyPointersBound
= true;
973 // mark as never-unload if requested
975 this->setNeverUnload();
977 context
.notifySingle(dyld_image_state_bound
, this, NULL
);
979 catch (const char* msg
) {
981 fState
= dyld_image_state_rebased
;
982 CRSetCrashLogMessage2(NULL
);
990 // These are mangled symbols for all the variants of operator new and delete
991 // which a main executable can define (non-weak) and override the
992 // weak-def implementation in the OS.
993 static const char* const sTreatAsWeak
[] = {
994 "__Znwm", "__ZnwmRKSt9nothrow_t",
995 "__Znam", "__ZnamRKSt9nothrow_t",
996 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
997 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
998 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
999 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
1000 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
1001 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
1004 size_t ImageLoader::HashCString::hash(const char* v
) {
1005 // FIXME: Use hash<string_view> when it has the correct visibility markup
1006 return std::hash
<std::string_view
>{}(v
);
1009 bool ImageLoader::EqualCString::equal(const char* s1
, const char* s2
) {
1010 return strcmp(s1
, s2
) == 0;
1013 void ImageLoader::weakBind(const LinkContext
& context
)
1016 if (!context
.useNewWeakBind
) {
1017 weakBindOld(context
);
1021 if ( context
.verboseWeakBind
)
1022 dyld::log("dyld: weak bind start:\n");
1023 uint64_t t1
= mach_absolute_time();
1025 // get set of ImageLoaders that participate in coalecsing
1026 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
1027 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
1028 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
1030 // count how many have not already had weakbinding done
1031 int countNotYetWeakBound
= 0;
1032 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
1033 for(int i
=0; i
< count
; ++i
) {
1034 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1035 ++countNotYetWeakBound
;
1036 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1037 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1040 // don't need to do any coalescing if only one image has overrides, or all have already been done
1041 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1042 if (!context
.weakDefMapInitialized
) {
1043 // Initialize the weak def map as the link context doesn't run static initializers
1044 new (&context
.weakDefMap
) dyld3::Map
<const char*, std::pair
<const ImageLoader
*, uintptr_t>, ImageLoader::HashCString
, ImageLoader::EqualCString
>();
1045 context
.weakDefMapInitialized
= true;
1048 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1049 if ( !context
.linkingMainExecutable
) {
1050 // Don't take the memory hit of weak defs on the launch path until we hit a dlopen with more weak symbols to bind
1051 if (!context
.weakDefMapProcessedLaunchDefs
) {
1052 context
.weakDefMapProcessedLaunchDefs
= true;
1054 // Walk the nlist for all binaries from launch and fill in the map with any other weak defs
1055 for (int i
=0; i
< count
; ++i
) {
1056 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1057 // skip images without defs. We've processed launch time refs already
1058 if ( !image
->hasCoalescedExports() )
1060 // Only process binaries which have had their weak symbols bound, ie, not the new ones we are processing now
1062 if ( !image
->weakSymbolsBound(imageIndexes
[i
]) )
1066 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1067 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uint64_t imageOffset
, bool isFromExportTrie
) {
1068 uintptr_t targetAddr
= (uintptr_t)ma
+ (uintptr_t)imageOffset
;
1069 if ( isFromExportTrie
) {
1070 // Avoid duplicating the string if we already have the symbol name
1071 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1073 symbolName
= strdup(symbolName
);
1075 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1080 // Walk the nlist for all binaries in dlopen and fill in the map with any other weak defs
1081 for (int i
=0; i
< count
; ++i
) {
1082 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1083 if ( image
->weakSymbolsBound(imageIndexes
[i
]) )
1085 // skip images without defs. We'll process refs later
1086 if ( !image
->hasCoalescedExports() )
1089 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1090 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uint64_t imageOffset
, bool isFromExportTrie
) {
1091 uintptr_t targetAddr
= (uintptr_t)ma
+ (uintptr_t)imageOffset
;
1092 if ( isFromExportTrie
) {
1093 // Avoid duplicating the string if we already have the symbol name
1094 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1096 symbolName
= strdup(symbolName
);
1098 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1101 // for all images that need weak binding
1102 for (int i
=0; i
< count
; ++i
) {
1103 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1104 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1105 continue; // weak binding already completed
1106 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1108 if ( context
.verboseWeakBind
)
1109 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1110 // for all symbols that need weak binding in this image
1111 ImageLoader::CoalIterator coalIterator
;
1112 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1113 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1114 const char* nameToCoalesce
= coalIterator
.symbolName
;
1115 uintptr_t targetAddr
= 0;
1116 const ImageLoader
* targetImage
;
1117 // Seatch the map for a previous definition to use
1118 auto weakDefIt
= context
.weakDefMap
.find(nameToCoalesce
);
1119 if ( (weakDefIt
!= context
.weakDefMap
.end()) && (weakDefIt
->second
.first
!= nullptr) ) {
1120 // Found a previous defition
1121 targetImage
= weakDefIt
->second
.first
;
1122 targetAddr
= weakDefIt
->second
.second
;
1124 // scan all images looking for definition to use
1125 for (int j
=0; j
< count
; ++j
) {
1126 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1127 bool anImageInCache
= anImage
->inSharedCache();
1128 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1129 // already coalesced. Only images outside cache can potentially override something in cache.
1130 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1133 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1134 const ImageLoader
* foundIn
;
1135 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1136 if ( sym
!= NULL
) {
1137 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1138 targetImage
= foundIn
;
1139 if ( context
.verboseWeakBind
)
1140 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1145 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1146 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1147 if (weakDefIt
== context
.weakDefMap
.end()) {
1148 if (targetImage
->neverUnload()) {
1149 // Add never unload defs to the map for next time
1150 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1151 if ( context
.verboseWeakBind
) {
1152 dyld::log("dyld: weak binding adding %s to map\n", nameToCoalesce
);
1155 // Add a placeholder for unloadable symbols which makes us fall back to the regular search
1156 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1157 if ( context
.verboseWeakBind
) {
1158 dyld::log("dyld: weak binding adding unloadable placeholder %s to map\n", nameToCoalesce
);
1162 if ( context
.verboseWeakBind
)
1163 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1166 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1170 #endif // TARGET_OS_OSX
1172 // make symbol iterators for each
1173 ImageLoader::CoalIterator iterators
[count
];
1174 ImageLoader::CoalIterator
* sortedIts
[count
];
1175 for(int i
=0; i
< count
; ++i
) {
1176 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1177 sortedIts
[i
] = &iterators
[i
];
1178 if ( context
.verboseWeakBind
)
1179 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1182 // walk all symbols keeping iterators in sync by
1183 // only ever incrementing the iterator with the lowest symbol
1185 while ( doneCount
!= count
) {
1186 //for(int i=0; i < count; ++i)
1187 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1189 // increment iterator with lowest symbol
1190 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1192 // re-sort iterators
1193 for(int i
=1; i
< count
; ++i
) {
1194 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1196 sortedIts
[i
-1]->symbolMatches
= true;
1198 // new one is bigger then next, so swap
1199 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1200 sortedIts
[i
-1] = sortedIts
[i
];
1201 sortedIts
[i
] = temp
;
1206 // process all matching symbols just before incrementing the lowest one that matches
1207 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1208 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1209 // pick first symbol in load order (and non-weak overrides weak)
1210 uintptr_t targetAddr
= 0;
1211 ImageLoader
* targetImage
= NULL
;
1212 unsigned targetImageIndex
= 0;
1213 for(int i
=0; i
< count
; ++i
) {
1214 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1215 if ( context
.verboseWeakBind
)
1216 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1217 if ( iterators
[i
].weakSymbol
) {
1218 if ( targetAddr
== 0 ) {
1219 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1220 if ( targetAddr
!= 0 ) {
1221 targetImage
= iterators
[i
].image
;
1222 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1227 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1228 if ( targetAddr
!= 0 ) {
1229 targetImage
= iterators
[i
].image
;
1230 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1231 // strong implementation found, stop searching
1237 // tell each to bind to this symbol (unless already bound)
1238 if ( targetAddr
!= 0 ) {
1239 if ( context
.verboseWeakBind
) {
1240 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1241 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1243 for(int i
=0; i
< count
; ++i
) {
1244 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1245 if ( context
.verboseWeakBind
) {
1246 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1247 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1248 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1250 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1251 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1252 iterators
[i
].symbolMatches
= false;
1255 if (targetImage
->neverUnload()) {
1256 // Add never unload defs to the map for next time
1257 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1258 if ( context
.verboseWeakBind
) {
1259 dyld::log("dyld: weak binding adding %s to map\n",
1268 for (int i
=0; i
< count
; ++i
) {
1269 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1270 continue; // skip images already processed
1272 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1273 // during binding of references to weak-def symbols, the dyld cache was patched
1274 // but if main executable has non-weak override of operator new or delete it needs is handled here
1275 for (const char* weakSymbolName
: sTreatAsWeak
) {
1276 const ImageLoader
* dummy
;
1277 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1282 // support traditional arm64 app on an arm64e device
1283 // look for weak def symbols in this image which may override the cache
1284 ImageLoader::CoalIterator coaler
;
1285 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1286 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1287 while ( !coaler
.done
) {
1288 const ImageLoader
* dummy
;
1289 // a side effect of resolveWeak() is to patch cache
1290 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1291 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1297 // mark all as having all weak symbols bound
1298 for(int i
=0; i
< count
; ++i
) {
1299 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1304 uint64_t t2
= mach_absolute_time();
1305 fgTotalWeakBindTime
+= t2
- t1
;
1307 if ( context
.verboseWeakBind
)
1308 dyld::log("dyld: weak bind end\n");
1312 void ImageLoader::weakBindOld(const LinkContext
& context
)
1314 if ( context
.verboseWeakBind
)
1315 dyld::log("dyld: weak bind start:\n");
1316 uint64_t t1
= mach_absolute_time();
1317 // get set of ImageLoaders that participate in coalecsing
1318 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
1319 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
1320 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
1322 // count how many have not already had weakbinding done
1323 int countNotYetWeakBound
= 0;
1324 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
1325 for(int i
=0; i
< count
; ++i
) {
1326 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1327 ++countNotYetWeakBound
;
1328 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1329 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1332 // don't need to do any coalescing if only one image has overrides, or all have already been done
1333 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1335 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1336 if ( !context
.linkingMainExecutable
) {
1337 // for all images that need weak binding
1338 for (int i
=0; i
< count
; ++i
) {
1339 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1340 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1341 continue; // weak binding already completed
1342 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1344 if ( context
.verboseWeakBind
)
1345 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1346 // for all symbols that need weak binding in this image
1347 ImageLoader::CoalIterator coalIterator
;
1348 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1349 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1350 const char* nameToCoalesce
= coalIterator
.symbolName
;
1351 uintptr_t targetAddr
= 0;
1352 const ImageLoader
* targetImage
;
1353 // scan all images looking for definition to use
1354 for (int j
=0; j
< count
; ++j
) {
1355 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1356 bool anImageInCache
= anImage
->inSharedCache();
1357 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1358 // already coalesced. Only images outside cache can potentially override something in cache.
1359 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1362 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1363 const ImageLoader
* foundIn
;
1364 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1365 if ( sym
!= NULL
) {
1366 if ( (foundIn
->getExportedSymbolInfo(sym
) & ImageLoader::kWeakDefinition
) == 0 ) {
1367 // found non-weak def, use it and stop looking
1368 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1369 targetImage
= foundIn
;
1370 if ( context
.verboseWeakBind
)
1371 dyld::log("dyld: found strong %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1375 // found weak-def, only use if no weak found yet
1376 if ( targetAddr
== 0 ) {
1377 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1378 targetImage
= foundIn
;
1379 if ( context
.verboseWeakBind
)
1380 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1385 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1386 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1387 if ( context
.verboseWeakBind
)
1388 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1391 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1395 #endif // TARGET_OS_OSX
1397 // make symbol iterators for each
1398 ImageLoader::CoalIterator iterators
[count
];
1399 ImageLoader::CoalIterator
* sortedIts
[count
];
1400 for(int i
=0; i
< count
; ++i
) {
1401 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1402 sortedIts
[i
] = &iterators
[i
];
1403 if ( context
.verboseWeakBind
)
1404 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1407 // walk all symbols keeping iterators in sync by
1408 // only ever incrementing the iterator with the lowest symbol
1410 while ( doneCount
!= count
) {
1411 //for(int i=0; i < count; ++i)
1412 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1414 // increment iterator with lowest symbol
1415 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1417 // re-sort iterators
1418 for(int i
=1; i
< count
; ++i
) {
1419 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1421 sortedIts
[i
-1]->symbolMatches
= true;
1423 // new one is bigger then next, so swap
1424 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1425 sortedIts
[i
-1] = sortedIts
[i
];
1426 sortedIts
[i
] = temp
;
1431 // process all matching symbols just before incrementing the lowest one that matches
1432 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1433 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1434 // pick first symbol in load order (and non-weak overrides weak)
1435 uintptr_t targetAddr
= 0;
1436 ImageLoader
* targetImage
= NULL
;
1437 unsigned targetImageIndex
= 0;
1438 for(int i
=0; i
< count
; ++i
) {
1439 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1440 if ( context
.verboseWeakBind
)
1441 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1442 if ( iterators
[i
].weakSymbol
) {
1443 if ( targetAddr
== 0 ) {
1444 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1445 if ( targetAddr
!= 0 ) {
1446 targetImage
= iterators
[i
].image
;
1447 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1452 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1453 if ( targetAddr
!= 0 ) {
1454 targetImage
= iterators
[i
].image
;
1455 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1456 // strong implementation found, stop searching
1462 // tell each to bind to this symbol (unless already bound)
1463 if ( targetAddr
!= 0 ) {
1464 if ( context
.verboseWeakBind
) {
1465 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1466 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1468 for(int i
=0; i
< count
; ++i
) {
1469 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1470 if ( context
.verboseWeakBind
) {
1471 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1472 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1473 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1475 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1476 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1477 iterators
[i
].symbolMatches
= false;
1485 for (int i
=0; i
< count
; ++i
) {
1486 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1487 continue; // skip images already processed
1489 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1490 // during binding of references to weak-def symbols, the dyld cache was patched
1491 // but if main executable has non-weak override of operator new or delete it needs is handled here
1492 for (const char* weakSymbolName
: sTreatAsWeak
) {
1493 const ImageLoader
* dummy
;
1494 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1499 // support traditional arm64 app on an arm64e device
1500 // look for weak def symbols in this image which may override the cache
1501 ImageLoader::CoalIterator coaler
;
1502 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1503 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1504 while ( !coaler
.done
) {
1505 const ImageLoader
* dummy
;
1506 // a side effect of resolveWeak() is to patch cache
1507 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1508 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1514 // mark all as having all weak symbols bound
1515 for(int i
=0; i
< count
; ++i
) {
1516 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1521 uint64_t t2
= mach_absolute_time();
1522 fgTotalWeakBindTime
+= t2
- t1
;
1524 if ( context
.verboseWeakBind
)
1525 dyld::log("dyld: weak bind end\n");
1530 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
1532 if ( ! fRegisteredDOF
) {
1534 fRegisteredDOF
= true;
1536 // gather lower level libraries first
1537 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1538 ImageLoader
* dependentImage
= libImage(i
);
1539 if ( dependentImage
!= NULL
)
1540 dependentImage
->recursiveGetDOFSections(context
, dofs
);
1542 this->doGetDOFSections(context
, dofs
);
1546 void ImageLoader::setNeverUnloadRecursive() {
1547 if ( ! fNeverUnload
) {
1549 fNeverUnload
= true;
1551 // gather lower level libraries first
1552 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1553 ImageLoader
* dependentImage
= libImage(i
);
1554 if ( dependentImage
!= NULL
)
1555 dependentImage
->setNeverUnloadRecursive();
1560 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
1562 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1563 // keep trying until success (spin)
1564 #pragma clang diagnostic push
1565 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1566 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
1567 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1568 // the same thread we are on, the increment the lock count, otherwise continue to spin
1569 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
1572 #pragma clang diagnostic pop
1573 ++(fInitializerRecursiveLock
->count
);
1576 void ImageLoader::recursiveSpinUnLock()
1578 if ( --(fInitializerRecursiveLock
->count
) == 0 )
1579 fInitializerRecursiveLock
= NULL
;
1582 void ImageLoader::InitializerTimingList::addTime(const char* name
, uint64_t time
)
1584 for (int i
=0; i
< count
; ++i
) {
1585 if ( strcmp(images
[i
].shortName
, name
) == 0 ) {
1586 images
[i
].initTime
+= time
;
1590 images
[count
].initTime
= time
;
1591 images
[count
].shortName
= name
;
1595 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
, const char* pathToInitialize
,
1596 InitializerTimingList
& timingInfo
, UninitedUpwards
& uninitUps
)
1598 recursive_lock
lock_info(this_thread
);
1599 recursiveSpinLock(lock_info
);
1601 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
1602 uint8_t oldState
= fState
;
1604 fState
= dyld_image_state_dependents_initialized
-1;
1606 // initialize lower level libraries first
1607 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1608 ImageLoader
* dependentImage
= libImage(i
);
1609 if ( dependentImage
!= NULL
) {
1610 // don't try to initialize stuff "above" me yet
1611 if ( libIsUpward(i
) ) {
1612 uninitUps
.imagesAndPaths
[uninitUps
.count
] = { dependentImage
, libPath(i
) };
1615 else if ( dependentImage
->fDepth
>= fDepth
) {
1616 dependentImage
->recursiveInitialization(context
, this_thread
, libPath(i
), timingInfo
, uninitUps
);
1621 // record termination order
1622 if ( this->needsTermination() )
1623 context
.terminationRecorder(this);
1625 // let objc know we are about to initialize this image
1626 uint64_t t1
= mach_absolute_time();
1627 fState
= dyld_image_state_dependents_initialized
;
1629 context
.notifySingle(dyld_image_state_dependents_initialized
, this, &timingInfo
);
1631 // initialize this image
1632 bool hasInitializers
= this->doInitialization(context
);
1634 // let anyone know we finished initializing this image
1635 fState
= dyld_image_state_initialized
;
1637 context
.notifySingle(dyld_image_state_initialized
, this, NULL
);
1639 if ( hasInitializers
) {
1640 uint64_t t2
= mach_absolute_time();
1641 timingInfo
.addTime(this->getShortName(), t2
-t1
);
1644 catch (const char* msg
) {
1645 // this image is not initialized
1647 recursiveSpinUnLock();
1652 recursiveSpinUnLock();
1656 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
1658 static uint64_t sUnitsPerSecond
= 0;
1659 if ( sUnitsPerSecond
== 0 ) {
1660 struct mach_timebase_info timeBaseInfo
;
1661 if ( mach_timebase_info(&timeBaseInfo
) != KERN_SUCCESS
)
1663 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
1665 if ( partTime
< sUnitsPerSecond
) {
1666 uint32_t milliSecondsTimesHundred
= (uint32_t)((partTime
*100000)/sUnitsPerSecond
);
1667 uint32_t milliSeconds
= (uint32_t)(milliSecondsTimesHundred
/100);
1668 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1669 uint32_t percent
= percentTimesTen
/10;
1670 if ( milliSeconds
>= 100 )
1671 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1672 else if ( milliSeconds
>= 10 )
1673 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1675 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1678 uint32_t secondsTimeTen
= (uint32_t)((partTime
*10)/sUnitsPerSecond
);
1679 uint32_t seconds
= secondsTimeTen
/10;
1680 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1681 uint32_t percent
= percentTimesTen
/10;
1682 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
1686 static char* commatize(uint64_t in
, char* out
)
1688 uint64_t div10
= in
/ 10;
1689 uint8_t delta
= in
- div10
*10;
1693 *(--s
) = '0' + delta
;
1696 if ( (digitCount
% 3) == 0 )
1699 delta
= in
- div10
*10;
1700 *(--s
) = '0' + delta
;
1708 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1710 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1712 uint64_t totalDyldTime
= totalTime
- fgTotalDebuggerPausedTime
- fgTotalRebindCacheTime
;
1713 printTime("Total pre-main time", totalDyldTime
, totalDyldTime
);
1714 printTime(" dylib loading time", fgTotalLoadLibrariesTime
-fgTotalDebuggerPausedTime
, totalDyldTime
);
1715 printTime(" rebase/binding time", fgTotalRebaseTime
+fgTotalBindTime
+fgTotalWeakBindTime
-fgTotalRebindCacheTime
, totalDyldTime
);
1716 printTime(" ObjC setup time", fgTotalObjCSetupTime
, totalDyldTime
);
1717 printTime(" initializer time", fgTotalInitTime
-fgTotalObjCSetupTime
, totalDyldTime
);
1718 dyld::log(" slowest intializers :\n");
1719 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1720 uint64_t t
= timingInfo
.images
[i
].initTime
;
1721 if ( t
*50 < totalDyldTime
)
1723 dyld::log("%30s ", timingInfo
.images
[i
].shortName
);
1724 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1725 t
-= fgTotalObjCSetupTime
;
1726 printTime("", t
, totalDyldTime
);
1731 void ImageLoader::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1733 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1737 printTime(" total time", totalTime
, totalTime
);
1738 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1739 dyld::log(" total segments mapped: %u, into %llu pages\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096);
1740 printTime(" total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
1741 printTime(" total load time in ObjC", fgTotalObjCSetupTime
, totalTime
);
1742 printTime(" total debugger pause time", fgTotalDebuggerPausedTime
, totalTime
);
1743 printTime(" total dtrace DOF registration time", fgTotalDOF
, totalTime
);
1744 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
1745 printTime(" total rebase fixups time", fgTotalRebaseTime
, totalTime
);
1746 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
1747 if ( fgTotalBindSymbolsResolved
!= 0 ) {
1748 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
1749 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
1750 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
1751 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1752 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
1754 printTime(" total binding fixups time", fgTotalBindTime
, totalTime
);
1755 printTime(" total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
1756 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime
, totalTime
);
1757 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
1758 printTime(" total time in initializers and ObjC +load", fgTotalInitTime
-fgTotalObjCSetupTime
, totalTime
);
1759 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1760 uint64_t t
= timingInfo
.images
[i
].initTime
;
1761 if ( t
*1000 < totalTime
)
1763 dyld::log("%42s ", timingInfo
.images
[i
].shortName
);
1764 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1765 t
-= fgTotalObjCSetupTime
;
1766 printTime("", t
, totalTime
);
1773 // copy path and add suffix to result
1775 // /path/foo.dylib _debug => /path/foo_debug.dylib
1776 // foo.dylib _debug => foo_debug.dylib
1777 // foo _debug => foo_debug
1778 // /path/bar _debug => /path/bar_debug
1779 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1781 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1783 strcpy(result
, path
);
1785 char* start
= strrchr(result
, '/');
1786 if ( start
!= NULL
)
1791 char* dot
= strrchr(start
, '.');
1792 if ( dot
!= NULL
) {
1793 strcpy(dot
, suffix
);
1794 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1797 strcat(result
, suffix
);
1803 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1804 // to enable it to be re-written in assembler if needed.
1806 const uint8_t* ImageLoader::trieWalk(const uint8_t* start
, const uint8_t* end
, const char* s
)
1808 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1809 ++fgSymbolTrieSearchs
;
1810 const uint8_t* p
= start
;
1811 while ( p
!= NULL
) {
1812 uintptr_t terminalSize
= *p
++;
1813 if ( terminalSize
> 127 ) {
1814 // except for re-export-with-rename, all terminal sizes fit in one byte
1816 terminalSize
= read_uleb128(p
, end
);
1818 if ( (*s
== '\0') && (terminalSize
!= 0) ) {
1819 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1822 const uint8_t* children
= p
+ terminalSize
;
1823 if ( children
> end
) {
1824 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize
);
1827 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1828 uint8_t childrenRemaining
= *children
++;
1830 uintptr_t nodeOffset
= 0;
1831 for (; childrenRemaining
> 0; --childrenRemaining
) {
1833 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1834 bool wrongEdge
= false;
1835 // scan whole edge to get to next edge
1836 // if edge is longer than target symbol name, don't read past end of symbol name
1838 while ( c
!= '\0' ) {
1848 // advance to next child
1849 ++p
; // skip over zero terminator
1850 // skip over uleb128 until last byte is found
1851 while ( (*p
& 0x80) != 0 )
1853 ++p
; // skip over last byte of uleb128
1855 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1860 // the symbol so far matches this edge (child)
1861 // so advance to the child's node
1863 nodeOffset
= read_uleb128(p
, end
);
1864 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
1865 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset
);
1869 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1873 if ( nodeOffset
!= 0 )
1874 p
= &start
[nodeOffset
];
1878 //dyld::log("trieWalk(%p) return NULL\n", start);
1884 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p
, const uint8_t* end
)
1886 uint64_t result
= 0;
1890 dyld::throwf("malformed uleb128");
1892 uint64_t slice
= *p
& 0x7f;
1895 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit
, result
);
1897 result
|= (slice
<< bit
);
1900 } while (*p
++ & 0x80);
1901 return (uintptr_t)result
;
1905 intptr_t ImageLoader::read_sleb128(const uint8_t*& p
, const uint8_t* end
)
1912 throw "malformed sleb128";
1914 result
|= (((int64_t)(byte
& 0x7f)) << bit
);
1916 } while (byte
& 0x80);
1917 // sign extend negative numbers
1918 if ( ((byte
& 0x40) != 0) && (bit
< 64) )
1919 result
|= (~0ULL) << bit
;
1920 return (intptr_t)result
;
1923 void ImageLoader::forEachReExportDependent( void (^callback
)(const ImageLoader
*, bool& stop
)) const
1926 for (unsigned int i
=0; i
< libraryCount(); ++i
) {
1927 if ( libReExported(i
) ) {
1928 if ( ImageLoader
* dependentImage
= libImage(i
) ) {
1929 callback(dependentImage
, stop
);
1938 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple
);
1939 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair
);