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 (!context
.dyldCache
->header
.builtFromChainedFixups
)
407 if (fgInterposingTuples
.empty())
409 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
410 // that image and apply its patch table to all uses.
411 uintptr_t cacheStart
= (uintptr_t)context
.dyldCache
;
412 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
413 if ( context
.verboseInterposing
)
414 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it
->replacee
);
416 uint32_t cacheOffsetOfReplacee
= (uint32_t)(it
->replacee
- cacheStart
);
417 if (!context
.dyldCache
->addressInText(cacheOffsetOfReplacee
, &imageIndex
))
419 dyld3::closure::ImageNum imageInCache
= imageIndex
+1;
420 if ( context
.verboseInterposing
)
421 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache
, (uint64_t)it
->replacee
);
422 context
.dyldCache
->forEachPatchableExport(imageIndex
, ^(uint32_t cacheOffsetOfImpl
, const char* exportName
) {
423 // Skip patching anything other than this symbol
424 if (cacheOffsetOfImpl
!= cacheOffsetOfReplacee
)
426 if ( context
.verboseInterposing
) {
427 const dyld3::closure::Image
* image
= context
.dyldCache
->cachedDylibsImageArray()->imageForNum(imageInCache
);
428 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName
, image
->path());
430 uintptr_t newLoc
= it
->replacement
;
431 context
.dyldCache
->forEachPatchableUseOfExport(imageIndex
, cacheOffsetOfImpl
, ^(dyld_cache_patchable_location patchLocation
) {
432 uintptr_t* loc
= (uintptr_t*)(cacheStart
+patchLocation
.cacheOffset
);
433 #if __has_feature(ptrauth_calls)
434 if ( patchLocation
.authenticated
) {
435 dyld3::MachOLoaded::ChainedFixupPointerOnDisk ptr
= *(dyld3::MachOLoaded::ChainedFixupPointerOnDisk
*)loc
;
436 ptr
.arm64e
.authRebase
.auth
= true;
437 ptr
.arm64e
.authRebase
.addrDiv
= patchLocation
.usesAddressDiversity
;
438 ptr
.arm64e
.authRebase
.diversity
= patchLocation
.discriminator
;
439 ptr
.arm64e
.authRebase
.key
= patchLocation
.key
;
440 *loc
= ptr
.arm64e
.signPointer(loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
));
441 if ( context
.verboseInterposing
)
442 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
443 loc
, (void*)*loc
, patchLocation
.discriminator
, patchLocation
.usesAddressDiversity
, DyldSharedCache::keyName(patchLocation
));
447 if ( context
.verboseInterposing
)
448 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc
, newLoc
+ DyldSharedCache::getAddend(patchLocation
), exportName
);
449 *loc
= newLoc
+ (uintptr_t)DyldSharedCache::getAddend(patchLocation
);
455 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array
[], size_t count
)
457 for(size_t i
=0; i
< count
; ++i
) {
458 ImageLoader::InterposeTuple tuple
;
459 tuple
.replacement
= (uintptr_t)array
[i
].replacement
;
460 tuple
.neverImage
= NULL
;
461 tuple
.onlyImage
= this;
462 tuple
.replacee
= (uintptr_t)array
[i
].replacee
;
463 // chain to any existing interpositions
464 for (std::vector
<InterposeTuple
>::iterator it
=fgInterposingTuples
.begin(); it
!= fgInterposingTuples
.end(); it
++) {
465 if ( (it
->replacee
== tuple
.replacee
) && (it
->onlyImage
== this) ) {
466 tuple
.replacee
= it
->replacement
;
469 ImageLoader::fgInterposingTuples
.push_back(tuple
);
473 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
474 void ImageLoader::vmAccountingSetSuspended(const LinkContext
& context
, bool suspend
)
476 #if __arm__ || __arm64__
477 static bool sVmAccountingSuspended
= false;
478 if ( suspend
== sVmAccountingSuspended
)
480 if ( context
.verboseBind
)
481 dyld::log("set vm.footprint_suspend=%d\n", suspend
);
482 int newValue
= suspend
? 1 : 0;
484 size_t newlen
= sizeof(newValue
);
485 size_t oldlen
= sizeof(oldValue
);
486 int ret
= sysctlbyname("vm.footprint_suspend", &oldValue
, &oldlen
, &newValue
, newlen
);
487 if ( context
.verboseBind
&& (ret
!= 0) )
488 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret
, errno
);
489 sVmAccountingSuspended
= suspend
;
494 void ImageLoader::link(const LinkContext
& context
, bool forceLazysBound
, bool preflightOnly
, bool neverUnload
, const RPathChain
& loaderRPaths
, const char* imagePath
)
496 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
498 // clear error strings
499 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
501 uint64_t t0
= mach_absolute_time();
502 this->recursiveLoadLibraries(context
, preflightOnly
, loaderRPaths
, imagePath
);
503 context
.notifyBatch(dyld_image_state_dependents_mapped
, preflightOnly
);
505 // we only do the loading step for preflights
509 uint64_t t1
= mach_absolute_time();
510 context
.clearAllDepths();
511 this->recursiveUpdateDepth(context
.imageCount());
513 __block
uint64_t t2
, t3
, t4
, t5
;
515 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS
, 0, 0, 0);
516 t2
= mach_absolute_time();
517 this->recursiveRebaseWithAccounting(context
);
518 context
.notifyBatch(dyld_image_state_rebased
, false);
520 t3
= mach_absolute_time();
521 if ( !context
.linkingMainExecutable
)
522 this->recursiveBindWithAccounting(context
, forceLazysBound
, neverUnload
);
524 t4
= mach_absolute_time();
525 if ( !context
.linkingMainExecutable
)
526 this->weakBind(context
);
527 t5
= mach_absolute_time();
530 // interpose any dynamically loaded images
531 if ( !context
.linkingMainExecutable
&& (fgInterposingTuples
.size() != 0) ) {
532 dyld3::ScopedTimer
timer(DBG_DYLD_TIMING_APPLY_INTERPOSING
, 0, 0, 0);
533 this->recursiveApplyInterposing(context
);
536 // now that all fixups are done, make __DATA_CONST segments read-only
537 if ( !context
.linkingMainExecutable
)
538 this->recursiveMakeDataReadOnly(context
);
540 if ( !context
.linkingMainExecutable
)
541 context
.notifyBatch(dyld_image_state_bound
, false);
542 uint64_t t6
= mach_absolute_time();
544 if ( context
.registerDOFs
!= NULL
) {
545 std::vector
<DOFInfo
> dofs
;
546 this->recursiveGetDOFSections(context
, dofs
);
547 context
.registerDOFs(dofs
);
549 uint64_t t7
= mach_absolute_time();
551 // clear error strings
552 (*context
.setErrorStrings
)(0, NULL
, NULL
, NULL
);
554 fgTotalLoadLibrariesTime
+= t1
- t0
;
555 fgTotalRebaseTime
+= t3
- t2
;
556 fgTotalBindTime
+= t4
- t3
;
557 fgTotalWeakBindTime
+= t5
- t4
;
558 fgTotalDOF
+= t7
- t6
;
560 // done with initial dylib loads
561 fgNextPIEDylibAddress
= 0;
565 void ImageLoader::printReferenceCounts()
567 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount
, getPath() );
571 bool ImageLoader::decrementDlopenReferenceCount()
573 if ( fDlopenReferenceCount
== 0 )
575 --fDlopenReferenceCount
;
580 // <rdar://problem/14412057> upward dylib initializers can be run too soon
581 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
582 // have their initialization postponed until after the recursion through downward dylibs
584 void ImageLoader::processInitializers(const LinkContext
& context
, mach_port_t thisThread
,
585 InitializerTimingList
& timingInfo
, ImageLoader::UninitedUpwards
& images
)
587 uint32_t maxImageCount
= context
.imageCount()+2;
588 ImageLoader::UninitedUpwards upsBuffer
[maxImageCount
];
589 ImageLoader::UninitedUpwards
& ups
= upsBuffer
[0];
591 // Calling recursive init on all images in images list, building a new list of
592 // uninitialized upward dependencies.
593 for (uintptr_t i
=0; i
< images
.count
; ++i
) {
594 images
.imagesAndPaths
[i
].first
->recursiveInitialization(context
, thisThread
, images
.imagesAndPaths
[i
].second
, timingInfo
, ups
);
596 // If any upward dependencies remain, init them.
598 processInitializers(context
, thisThread
, timingInfo
, ups
);
602 void ImageLoader::runInitializers(const LinkContext
& context
, InitializerTimingList
& timingInfo
)
604 uint64_t t1
= mach_absolute_time();
605 mach_port_t thisThread
= mach_thread_self();
606 ImageLoader::UninitedUpwards up
;
608 up
.imagesAndPaths
[0] = { this, this->getPath() };
609 processInitializers(context
, thisThread
, timingInfo
, up
);
610 context
.notifyBatch(dyld_image_state_initialized
, false);
611 mach_port_deallocate(mach_task_self(), thisThread
);
612 uint64_t t2
= mach_absolute_time();
613 fgTotalInitTime
+= (t2
- t1
);
617 void ImageLoader::bindAllLazyPointers(const LinkContext
& context
, bool recursive
)
619 if ( ! fAllLazyPointersBound
) {
620 fAllLazyPointersBound
= true;
623 // bind lower level libraries first
624 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
625 ImageLoader
* dependentImage
= libImage(i
);
626 if ( dependentImage
!= NULL
)
627 dependentImage
->bindAllLazyPointers(context
, recursive
);
630 // bind lazies in this image
631 this->doBindJustLazies(context
);
636 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
638 return fAllLibraryChecksumsAndLoadAddressesMatch
;
642 void ImageLoader::markedUsedRecursive(const std::vector
<DynamicReference
>& dynamicReferences
)
644 // already visited here
649 // clear mark on all statically dependent dylibs
650 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
651 ImageLoader
* dependentImage
= libImage(i
);
652 if ( dependentImage
!= NULL
) {
653 dependentImage
->markedUsedRecursive(dynamicReferences
);
657 // clear mark on all dynamically dependent dylibs
658 for (std::vector
<ImageLoader::DynamicReference
>::const_iterator it
=dynamicReferences
.begin(); it
!= dynamicReferences
.end(); ++it
) {
659 if ( it
->from
== this )
660 it
->to
->markedUsedRecursive(dynamicReferences
);
665 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth
)
667 // the purpose of this phase is to make the images sortable such that
668 // in a sort list of images, every image that an image depends on
669 // occurs in the list before it.
674 // get depth of dependents
675 unsigned int minDependentDepth
= maxDepth
;
676 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
677 ImageLoader
* dependentImage
= libImage(i
);
678 if ( (dependentImage
!= NULL
) && !libIsUpward(i
) ) {
679 unsigned int d
= dependentImage
->recursiveUpdateDepth(maxDepth
);
680 if ( d
< minDependentDepth
)
681 minDependentDepth
= d
;
685 // make me less deep then all my dependents
686 fDepth
= minDependentDepth
- 1;
693 void ImageLoader::recursiveLoadLibraries(const LinkContext
& context
, bool preflightOnly
, const RPathChain
& loaderRPaths
, const char* loadPath
)
695 if ( fState
< dyld_image_state_dependents_mapped
) {
697 fState
= dyld_image_state_dependents_mapped
;
699 // get list of libraries this image needs
700 DependentLibraryInfo libraryInfos
[fLibraryCount
];
701 this->doGetDependentLibraries(libraryInfos
);
703 // get list of rpaths that this image adds
704 std::vector
<const char*> rpathsFromThisImage
;
705 this->getRPaths(context
, rpathsFromThisImage
);
706 const RPathChain
thisRPaths(&loaderRPaths
, &rpathsFromThisImage
);
709 bool canUsePrelinkingInfo
= true;
710 for(unsigned int i
=0; i
< fLibraryCount
; ++i
){
711 ImageLoader
* dependentLib
;
712 bool depLibReExported
= false;
713 DependentLibraryInfo
& requiredLibInfo
= libraryInfos
[i
];
714 if ( preflightOnly
&& context
.inSharedCache(requiredLibInfo
.name
) ) {
715 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
716 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
717 setLibImage(i
, NULL
, false, false);
722 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, true, this->getPath(), &thisRPaths
, cacheIndex
);
723 if ( dependentLib
== this ) {
724 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
725 dependentLib
= context
.loadLibrary(requiredLibInfo
.name
, false, NULL
, NULL
, cacheIndex
);
726 if ( dependentLib
!= this )
727 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
730 dependentLib
->setNeverUnload();
731 if ( requiredLibInfo
.upward
) {
734 dependentLib
->fIsReferencedDownward
= true;
736 LibraryInfo actualInfo
= dependentLib
->doGetLibraryInfo(requiredLibInfo
.info
);
737 depLibReExported
= requiredLibInfo
.reExported
;
738 if ( ! depLibReExported
) {
739 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
740 depLibReExported
= dependentLib
->isSubframeworkOf(context
, this) || this->hasSubLibrary(context
, dependentLib
);
742 // check found library version is compatible
743 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
744 if ( (requiredLibInfo
.info
.minVersion
!= 0xFFFFFFFF) && (actualInfo
.minVersion
< requiredLibInfo
.info
.minVersion
)
745 && ((dyld3::MachOFile
*)(dependentLib
->machHeader()))->enforceCompatVersion() ) {
746 // record values for possible use by CrashReporter or Finder
747 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
748 this->getShortName(), requiredLibInfo
.info
.minVersion
>> 16, (requiredLibInfo
.info
.minVersion
>> 8) & 0xff, requiredLibInfo
.info
.minVersion
& 0xff,
749 dependentLib
->getShortName(), actualInfo
.minVersion
>> 16, (actualInfo
.minVersion
>> 8) & 0xff, actualInfo
.minVersion
& 0xff);
751 // prebinding for this image disabled if any dependent library changed
752 //if ( !depLibCheckSumsMatch )
753 // canUsePrelinkingInfo = false;
754 // prebinding for this image disabled unless both this and dependent are in the shared cache
755 if ( !dependentLib
->inSharedCache() || !this->inSharedCache() )
756 canUsePrelinkingInfo
= false;
758 //if ( context.verbosePrebinding ) {
759 // if ( !requiredLib.checksumMatches )
760 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
761 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
762 // if ( dependentLib->getSlide() != 0 )
763 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
766 catch (const char* msg
) {
767 //if ( context.verbosePrebinding )
768 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
769 if ( requiredLibInfo
.required
) {
770 fState
= dyld_image_state_mapped
;
771 // record values for possible use by CrashReporter or Finder
772 if ( strstr(msg
, "Incompatible library version") != NULL
)
773 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION
, this->getPath(), requiredLibInfo
.name
, NULL
);
774 else if ( strstr(msg
, "architecture") != NULL
)
775 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH
, this->getPath(), requiredLibInfo
.name
, NULL
);
776 else if ( strstr(msg
, "file system sandbox") != NULL
)
777 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX
, this->getPath(), requiredLibInfo
.name
, NULL
);
778 else if ( strstr(msg
, "code signature") != NULL
)
779 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_CODE_SIGNATURE
, this->getPath(), requiredLibInfo
.name
, NULL
);
780 else if ( strstr(msg
, "malformed") != NULL
)
781 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_MALFORMED_MACHO
, this->getPath(), requiredLibInfo
.name
, NULL
);
783 (*context
.setErrorStrings
)(DYLD_EXIT_REASON_DYLIB_MISSING
, this->getPath(), requiredLibInfo
.name
, NULL
);
784 const char* newMsg
= dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo
.name
, this->getRealPath(), msg
);
785 free((void*)msg
); // our free() will do nothing if msg is a string literal
788 free((void*)msg
); // our free() will do nothing if msg is a string literal
789 // ok if weak library not found
791 canUsePrelinkingInfo
= false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
793 setLibImage(i
, dependentLib
, depLibReExported
, requiredLibInfo
.upward
);
795 fAllLibraryChecksumsAndLoadAddressesMatch
= canUsePrelinkingInfo
;
797 // tell each to load its dependents
798 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
799 ImageLoader
* dependentImage
= libImage(i
);
800 if ( dependentImage
!= NULL
) {
801 dependentImage
->recursiveLoadLibraries(context
, preflightOnly
, thisRPaths
, libraryInfos
[i
].name
);
805 // do deep prebind check
806 if ( fAllLibraryChecksumsAndLoadAddressesMatch
) {
807 for(unsigned int i
=0; i
< libraryCount(); ++i
){
808 ImageLoader
* dependentImage
= libImage(i
);
809 if ( dependentImage
!= NULL
) {
810 if ( !dependentImage
->allDependentLibrariesAsWhenPreBound() )
811 fAllLibraryChecksumsAndLoadAddressesMatch
= false;
816 // free rpaths (getRPaths() malloc'ed each string)
817 for(std::vector
<const char*>::iterator it
=rpathsFromThisImage
.begin(); it
!= rpathsFromThisImage
.end(); ++it
) {
818 const char* str
= *it
;
826 void ImageLoader::recursiveRebaseWithAccounting(const LinkContext
& context
)
828 this->recursiveRebase(context
);
829 vmAccountingSetSuspended(context
, false);
832 void ImageLoader::recursiveRebase(const LinkContext
& context
)
834 if ( fState
< dyld_image_state_rebased
) {
836 fState
= dyld_image_state_rebased
;
839 // rebase lower level libraries first
840 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
841 ImageLoader
* dependentImage
= libImage(i
);
842 if ( dependentImage
!= NULL
)
843 dependentImage
->recursiveRebase(context
);
850 context
.notifySingle(dyld_image_state_rebased
, this, NULL
);
852 catch (const char* msg
) {
853 // this image is not rebased
854 fState
= dyld_image_state_dependents_mapped
;
855 CRSetCrashLogMessage2(NULL
);
861 void ImageLoader::recursiveApplyInterposing(const LinkContext
& context
)
863 if ( ! fInterposed
) {
868 // interpose lower level libraries first
869 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
870 ImageLoader
* dependentImage
= libImage(i
);
871 if ( dependentImage
!= NULL
)
872 dependentImage
->recursiveApplyInterposing(context
);
875 // interpose this image
876 doInterpose(context
);
878 catch (const char* msg
) {
879 // this image is not interposed
886 void ImageLoader::recursiveMakeDataReadOnly(const LinkContext
& context
)
888 if ( ! fMadeReadOnly
) {
890 fMadeReadOnly
= true;
893 // handle lower level libraries first
894 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
895 ImageLoader
* dependentImage
= libImage(i
);
896 if ( dependentImage
!= NULL
)
897 dependentImage
->recursiveMakeDataReadOnly(context
);
900 // if this image has __DATA_CONST, make that segment read-only
903 catch (const char* msg
) {
904 fMadeReadOnly
= false;
911 void ImageLoader::recursiveBindWithAccounting(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
913 this->recursiveBind(context
, forceLazysBound
, neverUnload
);
914 vmAccountingSetSuspended(context
, false);
917 void ImageLoader::recursiveBind(const LinkContext
& context
, bool forceLazysBound
, bool neverUnload
)
919 // Normally just non-lazy pointers are bound immediately.
920 // The exceptions are:
921 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
922 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
923 if ( fState
< dyld_image_state_bound
) {
925 fState
= dyld_image_state_bound
;
928 // bind lower level libraries first
929 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
930 ImageLoader
* dependentImage
= libImage(i
);
931 if ( dependentImage
!= NULL
)
932 dependentImage
->recursiveBind(context
, forceLazysBound
, neverUnload
);
935 this->doBind(context
, forceLazysBound
);
936 // mark if lazys are also bound
937 if ( forceLazysBound
|| this->usablePrebinding(context
) )
938 fAllLazyPointersBound
= true;
939 // mark as never-unload if requested
941 this->setNeverUnload();
943 context
.notifySingle(dyld_image_state_bound
, this, NULL
);
945 catch (const char* msg
) {
947 fState
= dyld_image_state_rebased
;
948 CRSetCrashLogMessage2(NULL
);
956 // These are mangled symbols for all the variants of operator new and delete
957 // which a main executable can define (non-weak) and override the
958 // weak-def implementation in the OS.
959 static const char* const sTreatAsWeak
[] = {
960 "__Znwm", "__ZnwmRKSt9nothrow_t",
961 "__Znam", "__ZnamRKSt9nothrow_t",
962 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
963 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
964 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
965 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
966 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
967 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
970 size_t ImageLoader::HashCString::hash(const char* v
) {
971 // FIXME: Use hash<string_view> when it has the correct visibility markup
972 return std::hash
<std::string_view
>{}(v
);
975 bool ImageLoader::EqualCString::equal(const char* s1
, const char* s2
) {
976 return strcmp(s1
, s2
) == 0;
979 void ImageLoader::weakBind(const LinkContext
& context
)
982 if (!context
.useNewWeakBind
) {
983 weakBindOld(context
);
987 if ( context
.verboseWeakBind
)
988 dyld::log("dyld: weak bind start:\n");
989 uint64_t t1
= mach_absolute_time();
991 // get set of ImageLoaders that participate in coalecsing
992 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
993 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
994 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
996 // count how many have not already had weakbinding done
997 int countNotYetWeakBound
= 0;
998 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
999 for(int i
=0; i
< count
; ++i
) {
1000 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1001 ++countNotYetWeakBound
;
1002 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1003 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1006 // don't need to do any coalescing if only one image has overrides, or all have already been done
1007 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1008 if (!context
.weakDefMapInitialized
) {
1009 // Initialize the weak def map as the link context doesn't run static initializers
1010 new (&context
.weakDefMap
) dyld3::Map
<const char*, std::pair
<const ImageLoader
*, uintptr_t>, ImageLoader::HashCString
, ImageLoader::EqualCString
>();
1011 context
.weakDefMapInitialized
= true;
1013 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1014 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1015 if ( !context
.linkingMainExecutable
) {
1016 // Don't take the memory hit of weak defs on the launch path until we hit a dlopen with more weak symbols to bind
1017 if (!context
.weakDefMapProcessedLaunchDefs
) {
1018 context
.weakDefMapProcessedLaunchDefs
= true;
1020 // Walk the nlist for all binaries from launch and fill in the map with any other weak defs
1021 for (int i
=0; i
< count
; ++i
) {
1022 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1023 // skip images without defs. We've processed launch time refs already
1024 if ( !image
->hasCoalescedExports() )
1026 // Only process binaries which have had their weak symbols bound, ie, not the new ones we are processing now
1028 if ( !image
->weakSymbolsBound(imageIndexes
[i
]) )
1032 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1033 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uintptr_t imageOffset
, bool isFromExportTrie
) {
1034 uintptr_t targetAddr
= (uintptr_t)ma
+ imageOffset
;
1035 if ( isFromExportTrie
) {
1036 // Avoid duplicating the string if we already have the symbol name
1037 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1039 symbolName
= strdup(symbolName
);
1041 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1046 // Walk the nlist for all binaries in dlopen and fill in the map with any other weak defs
1047 for (int i
=0; i
< count
; ++i
) {
1048 const ImageLoader
* image
= imagesNeedingCoalescing
[i
];
1049 if ( image
->weakSymbolsBound(imageIndexes
[i
]) )
1051 // skip images without defs. We'll process refs later
1052 if ( !image
->hasCoalescedExports() )
1055 const dyld3::MachOAnalyzer
* ma
= (const dyld3::MachOAnalyzer
*)image
->machHeader();
1056 ma
->forEachWeakDef(diag
, ^(const char *symbolName
, uintptr_t imageOffset
, bool isFromExportTrie
) {
1057 uintptr_t targetAddr
= (uintptr_t)ma
+ imageOffset
;
1058 if ( isFromExportTrie
) {
1059 // Avoid duplicating the string if we already have the symbol name
1060 if ( context
.weakDefMap
.find(symbolName
) != context
.weakDefMap
.end() )
1062 symbolName
= strdup(symbolName
);
1064 context
.weakDefMap
.insert({ symbolName
, { image
, targetAddr
} });
1067 // for all images that need weak binding
1068 for (int i
=0; i
< count
; ++i
) {
1069 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1070 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1071 continue; // weak binding already completed
1072 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1074 if ( context
.verboseWeakBind
)
1075 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1076 // for all symbols that need weak binding in this image
1077 ImageLoader::CoalIterator coalIterator
;
1078 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1079 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1080 const char* nameToCoalesce
= coalIterator
.symbolName
;
1081 uintptr_t targetAddr
= 0;
1082 const ImageLoader
* targetImage
;
1083 // Seatch the map for a previous definition to use
1084 auto weakDefIt
= context
.weakDefMap
.find(nameToCoalesce
);
1085 if ( (weakDefIt
!= context
.weakDefMap
.end()) && (weakDefIt
->second
.first
!= nullptr) ) {
1086 // Found a previous defition
1087 targetImage
= weakDefIt
->second
.first
;
1088 targetAddr
= weakDefIt
->second
.second
;
1090 // scan all images looking for definition to use
1091 for (int j
=0; j
< count
; ++j
) {
1092 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1093 bool anImageInCache
= anImage
->inSharedCache();
1094 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1095 // already coalesced. Only images outside cache can potentially override something in cache.
1096 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1099 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1100 const ImageLoader
* foundIn
;
1101 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1102 if ( sym
!= NULL
) {
1103 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1104 targetImage
= foundIn
;
1105 if ( context
.verboseWeakBind
)
1106 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1111 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1112 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1113 if (weakDefIt
== context
.weakDefMap
.end()) {
1114 if (targetImage
->neverUnload()) {
1115 // Add never unload defs to the map for next time
1116 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1117 if ( context
.verboseWeakBind
) {
1118 dyld::log("dyld: weak binding adding %s to map\n", nameToCoalesce
);
1121 // Add a placeholder for unloadable symbols which makes us fall back to the regular search
1122 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1123 if ( context
.verboseWeakBind
) {
1124 dyld::log("dyld: weak binding adding unloadable placeholder %s to map\n", nameToCoalesce
);
1128 if ( context
.verboseWeakBind
)
1129 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1132 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1136 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1138 // make symbol iterators for each
1139 ImageLoader::CoalIterator iterators
[count
];
1140 ImageLoader::CoalIterator
* sortedIts
[count
];
1141 for(int i
=0; i
< count
; ++i
) {
1142 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1143 sortedIts
[i
] = &iterators
[i
];
1144 if ( context
.verboseWeakBind
)
1145 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1148 // walk all symbols keeping iterators in sync by
1149 // only ever incrementing the iterator with the lowest symbol
1151 while ( doneCount
!= count
) {
1152 //for(int i=0; i < count; ++i)
1153 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1155 // increment iterator with lowest symbol
1156 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1158 // re-sort iterators
1159 for(int i
=1; i
< count
; ++i
) {
1160 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1162 sortedIts
[i
-1]->symbolMatches
= true;
1164 // new one is bigger then next, so swap
1165 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1166 sortedIts
[i
-1] = sortedIts
[i
];
1167 sortedIts
[i
] = temp
;
1172 // process all matching symbols just before incrementing the lowest one that matches
1173 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1174 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1175 // pick first symbol in load order (and non-weak overrides weak)
1176 uintptr_t targetAddr
= 0;
1177 ImageLoader
* targetImage
= NULL
;
1178 unsigned targetImageIndex
= 0;
1179 for(int i
=0; i
< count
; ++i
) {
1180 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1181 if ( context
.verboseWeakBind
)
1182 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1183 if ( iterators
[i
].weakSymbol
) {
1184 if ( targetAddr
== 0 ) {
1185 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1186 if ( targetAddr
!= 0 ) {
1187 targetImage
= iterators
[i
].image
;
1188 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1193 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1194 if ( targetAddr
!= 0 ) {
1195 targetImage
= iterators
[i
].image
;
1196 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1197 // strong implementation found, stop searching
1203 // tell each to bind to this symbol (unless already bound)
1204 if ( targetAddr
!= 0 ) {
1205 if ( context
.verboseWeakBind
) {
1206 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1207 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1209 for(int i
=0; i
< count
; ++i
) {
1210 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1211 if ( context
.verboseWeakBind
) {
1212 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1213 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1214 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1216 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1217 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1218 iterators
[i
].symbolMatches
= false;
1221 if (targetImage
->neverUnload()) {
1222 // Add never unload defs to the map for next time
1223 context
.weakDefMap
.insert({ nameToCoalesce
, { targetImage
, targetAddr
} });
1224 if ( context
.verboseWeakBind
) {
1225 dyld::log("dyld: weak binding adding %s to map\n",
1234 for (int i
=0; i
< count
; ++i
) {
1235 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1236 continue; // skip images already processed
1238 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1239 // during binding of references to weak-def symbols, the dyld cache was patched
1240 // but if main executable has non-weak override of operator new or delete it needs is handled here
1241 for (const char* weakSymbolName
: sTreatAsWeak
) {
1242 const ImageLoader
* dummy
;
1243 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1248 // support traditional arm64 app on an arm64e device
1249 // look for weak def symbols in this image which may override the cache
1250 ImageLoader::CoalIterator coaler
;
1251 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1252 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1253 while ( !coaler
.done
) {
1254 const ImageLoader
* dummy
;
1255 // a side effect of resolveWeak() is to patch cache
1256 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1257 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1263 // mark all as having all weak symbols bound
1264 for(int i
=0; i
< count
; ++i
) {
1265 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1270 uint64_t t2
= mach_absolute_time();
1271 fgTotalWeakBindTime
+= t2
- t1
;
1273 if ( context
.verboseWeakBind
)
1274 dyld::log("dyld: weak bind end\n");
1278 void ImageLoader::weakBindOld(const LinkContext
& context
)
1280 if ( context
.verboseWeakBind
)
1281 dyld::log("dyld: weak bind start:\n");
1282 uint64_t t1
= mach_absolute_time();
1283 // get set of ImageLoaders that participate in coalecsing
1284 ImageLoader
* imagesNeedingCoalescing
[fgImagesRequiringCoalescing
];
1285 unsigned imageIndexes
[fgImagesRequiringCoalescing
];
1286 int count
= context
.getCoalescedImages(imagesNeedingCoalescing
, imageIndexes
);
1288 // count how many have not already had weakbinding done
1289 int countNotYetWeakBound
= 0;
1290 int countOfImagesWithWeakDefinitionsNotInSharedCache
= 0;
1291 for(int i
=0; i
< count
; ++i
) {
1292 if ( ! imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1293 ++countNotYetWeakBound
;
1294 if ( ! imagesNeedingCoalescing
[i
]->inSharedCache() )
1295 ++countOfImagesWithWeakDefinitionsNotInSharedCache
;
1298 // don't need to do any coalescing if only one image has overrides, or all have already been done
1299 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache
> 0) && (countNotYetWeakBound
> 0) ) {
1300 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1301 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1302 if ( !context
.linkingMainExecutable
) {
1303 // for all images that need weak binding
1304 for (int i
=0; i
< count
; ++i
) {
1305 ImageLoader
* imageBeingFixedUp
= imagesNeedingCoalescing
[i
];
1306 if ( imageBeingFixedUp
->weakSymbolsBound(imageIndexes
[i
]) )
1307 continue; // weak binding already completed
1308 bool imageBeingFixedUpInCache
= imageBeingFixedUp
->inSharedCache();
1310 if ( context
.verboseWeakBind
)
1311 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp
->getPath());
1312 // for all symbols that need weak binding in this image
1313 ImageLoader::CoalIterator coalIterator
;
1314 imageBeingFixedUp
->initializeCoalIterator(coalIterator
, i
, imageIndexes
[i
]);
1315 while ( !imageBeingFixedUp
->incrementCoalIterator(coalIterator
) ) {
1316 const char* nameToCoalesce
= coalIterator
.symbolName
;
1317 uintptr_t targetAddr
= 0;
1318 const ImageLoader
* targetImage
;
1319 // scan all images looking for definition to use
1320 for (int j
=0; j
< count
; ++j
) {
1321 const ImageLoader
* anImage
= imagesNeedingCoalescing
[j
];
1322 bool anImageInCache
= anImage
->inSharedCache();
1323 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1324 // already coalesced. Only images outside cache can potentially override something in cache.
1325 if ( anImageInCache
&& imageBeingFixedUpInCache
)
1328 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1329 const ImageLoader
* foundIn
;
1330 const Symbol
* sym
= anImage
->findExportedSymbol(nameToCoalesce
, false, &foundIn
);
1331 if ( sym
!= NULL
) {
1332 if ( (foundIn
->getExportedSymbolInfo(sym
) & ImageLoader::kWeakDefinition
) == 0 ) {
1333 // found non-weak def, use it and stop looking
1334 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1335 targetImage
= foundIn
;
1336 if ( context
.verboseWeakBind
)
1337 dyld::log("dyld: found strong %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1341 // found weak-def, only use if no weak found yet
1342 if ( targetAddr
== 0 ) {
1343 targetAddr
= foundIn
->getExportedSymbolAddress(sym
, context
);
1344 targetImage
= foundIn
;
1345 if ( context
.verboseWeakBind
)
1346 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce
, targetAddr
, foundIn
->getPath());
1351 if ( (targetAddr
!= 0) && (coalIterator
.image
!= targetImage
) ) {
1352 coalIterator
.image
->updateUsesCoalIterator(coalIterator
, targetAddr
, (ImageLoader
*)targetImage
, 0, context
);
1353 if ( context
.verboseWeakBind
)
1354 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce
, coalIterator
.image
->getPath(), targetImage
->getPath());
1357 imageBeingFixedUp
->setWeakSymbolsBound(imageIndexes
[i
]);
1361 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1363 // make symbol iterators for each
1364 ImageLoader::CoalIterator iterators
[count
];
1365 ImageLoader::CoalIterator
* sortedIts
[count
];
1366 for(int i
=0; i
< count
; ++i
) {
1367 imagesNeedingCoalescing
[i
]->initializeCoalIterator(iterators
[i
], i
, imageIndexes
[i
]);
1368 sortedIts
[i
] = &iterators
[i
];
1369 if ( context
.verboseWeakBind
)
1370 dyld::log("dyld: weak bind load order %d/%d for %s\n", i
, count
, imagesNeedingCoalescing
[i
]->getIndexedPath(imageIndexes
[i
]));
1373 // walk all symbols keeping iterators in sync by
1374 // only ever incrementing the iterator with the lowest symbol
1376 while ( doneCount
!= count
) {
1377 //for(int i=0; i < count; ++i)
1378 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1380 // increment iterator with lowest symbol
1381 if ( sortedIts
[0]->image
->incrementCoalIterator(*sortedIts
[0]) )
1383 // re-sort iterators
1384 for(int i
=1; i
< count
; ++i
) {
1385 int result
= strcmp(sortedIts
[i
-1]->symbolName
, sortedIts
[i
]->symbolName
);
1387 sortedIts
[i
-1]->symbolMatches
= true;
1389 // new one is bigger then next, so swap
1390 ImageLoader::CoalIterator
* temp
= sortedIts
[i
-1];
1391 sortedIts
[i
-1] = sortedIts
[i
];
1392 sortedIts
[i
] = temp
;
1397 // process all matching symbols just before incrementing the lowest one that matches
1398 if ( sortedIts
[0]->symbolMatches
&& !sortedIts
[0]->done
) {
1399 const char* nameToCoalesce
= sortedIts
[0]->symbolName
;
1400 // pick first symbol in load order (and non-weak overrides weak)
1401 uintptr_t targetAddr
= 0;
1402 ImageLoader
* targetImage
= NULL
;
1403 unsigned targetImageIndex
= 0;
1404 for(int i
=0; i
< count
; ++i
) {
1405 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1406 if ( context
.verboseWeakBind
)
1407 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce
, iterators
[i
].weakSymbol
, iterators
[i
].image
->getIndexedPath((unsigned)iterators
[i
].imageIndex
));
1408 if ( iterators
[i
].weakSymbol
) {
1409 if ( targetAddr
== 0 ) {
1410 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1411 if ( targetAddr
!= 0 ) {
1412 targetImage
= iterators
[i
].image
;
1413 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1418 targetAddr
= iterators
[i
].image
->getAddressCoalIterator(iterators
[i
], context
);
1419 if ( targetAddr
!= 0 ) {
1420 targetImage
= iterators
[i
].image
;
1421 targetImageIndex
= (unsigned)iterators
[i
].imageIndex
;
1422 // strong implementation found, stop searching
1428 // tell each to bind to this symbol (unless already bound)
1429 if ( targetAddr
!= 0 ) {
1430 if ( context
.verboseWeakBind
) {
1431 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1432 nameToCoalesce
, targetImage
->getIndexedShortName(targetImageIndex
));
1434 for(int i
=0; i
< count
; ++i
) {
1435 if ( strcmp(iterators
[i
].symbolName
, nameToCoalesce
) == 0 ) {
1436 if ( context
.verboseWeakBind
) {
1437 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1438 nameToCoalesce
, iterators
[i
].image
->getIndexedShortName((unsigned)iterators
[i
].imageIndex
),
1439 targetAddr
, targetImage
->getIndexedShortName(targetImageIndex
));
1441 if ( ! iterators
[i
].image
->weakSymbolsBound(imageIndexes
[i
]) )
1442 iterators
[i
].image
->updateUsesCoalIterator(iterators
[i
], targetAddr
, targetImage
, targetImageIndex
, context
);
1443 iterators
[i
].symbolMatches
= false;
1451 for (int i
=0; i
< count
; ++i
) {
1452 if ( imagesNeedingCoalescing
[i
]->weakSymbolsBound(imageIndexes
[i
]) )
1453 continue; // skip images already processed
1455 if ( imagesNeedingCoalescing
[i
]->usesChainedFixups() ) {
1456 // during binding of references to weak-def symbols, the dyld cache was patched
1457 // but if main executable has non-weak override of operator new or delete it needs is handled here
1458 for (const char* weakSymbolName
: sTreatAsWeak
) {
1459 const ImageLoader
* dummy
;
1460 imagesNeedingCoalescing
[i
]->resolveWeak(context
, weakSymbolName
, true, false, &dummy
);
1465 // support traditional arm64 app on an arm64e device
1466 // look for weak def symbols in this image which may override the cache
1467 ImageLoader::CoalIterator coaler
;
1468 imagesNeedingCoalescing
[i
]->initializeCoalIterator(coaler
, i
, 0);
1469 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1470 while ( !coaler
.done
) {
1471 const ImageLoader
* dummy
;
1472 // a side effect of resolveWeak() is to patch cache
1473 imagesNeedingCoalescing
[i
]->resolveWeak(context
, coaler
.symbolName
, true, false, &dummy
);
1474 imagesNeedingCoalescing
[i
]->incrementCoalIterator(coaler
);
1480 // mark all as having all weak symbols bound
1481 for(int i
=0; i
< count
; ++i
) {
1482 imagesNeedingCoalescing
[i
]->setWeakSymbolsBound(imageIndexes
[i
]);
1487 uint64_t t2
= mach_absolute_time();
1488 fgTotalWeakBindTime
+= t2
- t1
;
1490 if ( context
.verboseWeakBind
)
1491 dyld::log("dyld: weak bind end\n");
1496 void ImageLoader::recursiveGetDOFSections(const LinkContext
& context
, std::vector
<DOFInfo
>& dofs
)
1498 if ( ! fRegisteredDOF
) {
1500 fRegisteredDOF
= true;
1502 // gather lower level libraries first
1503 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1504 ImageLoader
* dependentImage
= libImage(i
);
1505 if ( dependentImage
!= NULL
)
1506 dependentImage
->recursiveGetDOFSections(context
, dofs
);
1508 this->doGetDOFSections(context
, dofs
);
1512 void ImageLoader::setNeverUnloadRecursive() {
1513 if ( ! fNeverUnload
) {
1515 fNeverUnload
= true;
1517 // gather lower level libraries first
1518 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1519 ImageLoader
* dependentImage
= libImage(i
);
1520 if ( dependentImage
!= NULL
)
1521 dependentImage
->setNeverUnloadRecursive();
1526 void ImageLoader::recursiveSpinLock(recursive_lock
& rlock
)
1528 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1529 // keep trying until success (spin)
1530 #pragma clang diagnostic push
1531 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1532 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL
, &rlock
, (void**)&fInitializerRecursiveLock
) ) {
1533 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1534 // the same thread we are on, the increment the lock count, otherwise continue to spin
1535 if ( (fInitializerRecursiveLock
!= NULL
) && (fInitializerRecursiveLock
->thread
== rlock
.thread
) )
1538 #pragma clang diagnostic pop
1539 ++(fInitializerRecursiveLock
->count
);
1542 void ImageLoader::recursiveSpinUnLock()
1544 if ( --(fInitializerRecursiveLock
->count
) == 0 )
1545 fInitializerRecursiveLock
= NULL
;
1548 void ImageLoader::InitializerTimingList::addTime(const char* name
, uint64_t time
)
1550 for (int i
=0; i
< count
; ++i
) {
1551 if ( strcmp(images
[i
].shortName
, name
) == 0 ) {
1552 images
[i
].initTime
+= time
;
1556 images
[count
].initTime
= time
;
1557 images
[count
].shortName
= name
;
1561 void ImageLoader::recursiveInitialization(const LinkContext
& context
, mach_port_t this_thread
, const char* pathToInitialize
,
1562 InitializerTimingList
& timingInfo
, UninitedUpwards
& uninitUps
)
1564 recursive_lock
lock_info(this_thread
);
1565 recursiveSpinLock(lock_info
);
1567 if ( fState
< dyld_image_state_dependents_initialized
-1 ) {
1568 uint8_t oldState
= fState
;
1570 fState
= dyld_image_state_dependents_initialized
-1;
1572 // initialize lower level libraries first
1573 for(unsigned int i
=0; i
< libraryCount(); ++i
) {
1574 ImageLoader
* dependentImage
= libImage(i
);
1575 if ( dependentImage
!= NULL
) {
1576 // don't try to initialize stuff "above" me yet
1577 if ( libIsUpward(i
) ) {
1578 uninitUps
.imagesAndPaths
[uninitUps
.count
] = { dependentImage
, libPath(i
) };
1581 else if ( dependentImage
->fDepth
>= fDepth
) {
1582 dependentImage
->recursiveInitialization(context
, this_thread
, libPath(i
), timingInfo
, uninitUps
);
1587 // record termination order
1588 if ( this->needsTermination() )
1589 context
.terminationRecorder(this);
1591 // let objc know we are about to initialize this image
1592 uint64_t t1
= mach_absolute_time();
1593 fState
= dyld_image_state_dependents_initialized
;
1595 context
.notifySingle(dyld_image_state_dependents_initialized
, this, &timingInfo
);
1597 // initialize this image
1598 bool hasInitializers
= this->doInitialization(context
);
1600 // let anyone know we finished initializing this image
1601 fState
= dyld_image_state_initialized
;
1603 context
.notifySingle(dyld_image_state_initialized
, this, NULL
);
1605 if ( hasInitializers
) {
1606 uint64_t t2
= mach_absolute_time();
1607 timingInfo
.addTime(this->getShortName(), t2
-t1
);
1610 catch (const char* msg
) {
1611 // this image is not initialized
1613 recursiveSpinUnLock();
1618 recursiveSpinUnLock();
1622 static void printTime(const char* msg
, uint64_t partTime
, uint64_t totalTime
)
1624 static uint64_t sUnitsPerSecond
= 0;
1625 if ( sUnitsPerSecond
== 0 ) {
1626 struct mach_timebase_info timeBaseInfo
;
1627 if ( mach_timebase_info(&timeBaseInfo
) != KERN_SUCCESS
)
1629 sUnitsPerSecond
= 1000000000ULL * timeBaseInfo
.denom
/ timeBaseInfo
.numer
;
1631 if ( partTime
< sUnitsPerSecond
) {
1632 uint32_t milliSecondsTimesHundred
= (uint32_t)((partTime
*100000)/sUnitsPerSecond
);
1633 uint32_t milliSeconds
= (uint32_t)(milliSecondsTimesHundred
/100);
1634 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1635 uint32_t percent
= percentTimesTen
/10;
1636 if ( milliSeconds
>= 100 )
1637 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1638 else if ( milliSeconds
>= 10 )
1639 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1641 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg
, milliSeconds
, milliSecondsTimesHundred
-milliSeconds
*100, percent
, percentTimesTen
-percent
*10);
1644 uint32_t secondsTimeTen
= (uint32_t)((partTime
*10)/sUnitsPerSecond
);
1645 uint32_t seconds
= secondsTimeTen
/10;
1646 uint32_t percentTimesTen
= (uint32_t)((partTime
*1000)/totalTime
);
1647 uint32_t percent
= percentTimesTen
/10;
1648 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg
, seconds
, secondsTimeTen
-seconds
*10, percent
, percentTimesTen
-percent
*10);
1652 static char* commatize(uint64_t in
, char* out
)
1654 uint64_t div10
= in
/ 10;
1655 uint8_t delta
= in
- div10
*10;
1659 *(--s
) = '0' + delta
;
1662 if ( (digitCount
% 3) == 0 )
1665 delta
= in
- div10
*10;
1666 *(--s
) = '0' + delta
;
1674 void ImageLoader::printStatistics(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1676 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1678 uint64_t totalDyldTime
= totalTime
- fgTotalDebuggerPausedTime
- fgTotalRebindCacheTime
;
1679 printTime("Total pre-main time", totalDyldTime
, totalDyldTime
);
1680 printTime(" dylib loading time", fgTotalLoadLibrariesTime
-fgTotalDebuggerPausedTime
, totalDyldTime
);
1681 printTime(" rebase/binding time", fgTotalRebaseTime
+fgTotalBindTime
+fgTotalWeakBindTime
-fgTotalRebindCacheTime
, totalDyldTime
);
1682 printTime(" ObjC setup time", fgTotalObjCSetupTime
, totalDyldTime
);
1683 printTime(" initializer time", fgTotalInitTime
-fgTotalObjCSetupTime
, totalDyldTime
);
1684 dyld::log(" slowest intializers :\n");
1685 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1686 uint64_t t
= timingInfo
.images
[i
].initTime
;
1687 if ( t
*50 < totalDyldTime
)
1689 dyld::log("%30s ", timingInfo
.images
[i
].shortName
);
1690 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1691 t
-= fgTotalObjCSetupTime
;
1692 printTime("", t
, totalDyldTime
);
1697 void ImageLoader::printStatisticsDetails(unsigned int imageCount
, const InitializerTimingList
& timingInfo
)
1699 uint64_t totalTime
= fgTotalLoadLibrariesTime
+ fgTotalRebaseTime
+ fgTotalBindTime
+ fgTotalWeakBindTime
+ fgTotalDOF
+ fgTotalInitTime
;
1703 printTime(" total time", totalTime
, totalTime
);
1704 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount
, fgImagesUsedFromSharedCache
);
1705 dyld::log(" total segments mapped: %u, into %llu pages\n", fgTotalSegmentsMapped
, fgTotalBytesMapped
/4096);
1706 printTime(" total images loading time", fgTotalLoadLibrariesTime
, totalTime
);
1707 printTime(" total load time in ObjC", fgTotalObjCSetupTime
, totalTime
);
1708 printTime(" total debugger pause time", fgTotalDebuggerPausedTime
, totalTime
);
1709 printTime(" total dtrace DOF registration time", fgTotalDOF
, totalTime
);
1710 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups
, commaNum1
));
1711 printTime(" total rebase fixups time", fgTotalRebaseTime
, totalTime
);
1712 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups
, commaNum1
));
1713 if ( fgTotalBindSymbolsResolved
!= 0 ) {
1714 uint32_t avgTimesTen
= (fgTotalBindImageSearches
* 10) / fgTotalBindSymbolsResolved
;
1715 uint32_t avgInt
= fgTotalBindImageSearches
/ fgTotalBindSymbolsResolved
;
1716 uint32_t avgTenths
= avgTimesTen
- (avgInt
*10);
1717 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1718 commatize(fgTotalBindSymbolsResolved
, commaNum1
), avgInt
, avgTenths
);
1720 printTime(" total binding fixups time", fgTotalBindTime
, totalTime
);
1721 printTime(" total weak binding fixups time", fgTotalWeakBindTime
, totalTime
);
1722 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime
, totalTime
);
1723 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups
, commaNum1
), commatize(fgTotalPossibleLazyBindFixups
, commaNum2
));
1724 printTime(" total time in initializers and ObjC +load", fgTotalInitTime
-fgTotalObjCSetupTime
, totalTime
);
1725 for (uintptr_t i
=0; i
< timingInfo
.count
; ++i
) {
1726 uint64_t t
= timingInfo
.images
[i
].initTime
;
1727 if ( t
*1000 < totalTime
)
1729 dyld::log("%42s ", timingInfo
.images
[i
].shortName
);
1730 if ( strncmp(timingInfo
.images
[i
].shortName
, "libSystem.", 10) == 0 )
1731 t
-= fgTotalObjCSetupTime
;
1732 printTime("", t
, totalTime
);
1739 // copy path and add suffix to result
1741 // /path/foo.dylib _debug => /path/foo_debug.dylib
1742 // foo.dylib _debug => foo_debug.dylib
1743 // foo _debug => foo_debug
1744 // /path/bar _debug => /path/bar_debug
1745 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1747 void ImageLoader::addSuffix(const char* path
, const char* suffix
, char* result
)
1749 strcpy(result
, path
);
1751 char* start
= strrchr(result
, '/');
1752 if ( start
!= NULL
)
1757 char* dot
= strrchr(start
, '.');
1758 if ( dot
!= NULL
) {
1759 strcpy(dot
, suffix
);
1760 strcat(&dot
[strlen(suffix
)], &path
[dot
-result
]);
1763 strcat(result
, suffix
);
1769 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1770 // to enable it to be re-written in assembler if needed.
1772 const uint8_t* ImageLoader::trieWalk(const uint8_t* start
, const uint8_t* end
, const char* s
)
1774 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1775 ++fgSymbolTrieSearchs
;
1776 const uint8_t* p
= start
;
1777 while ( p
!= NULL
) {
1778 uintptr_t terminalSize
= *p
++;
1779 if ( terminalSize
> 127 ) {
1780 // except for re-export-with-rename, all terminal sizes fit in one byte
1782 terminalSize
= read_uleb128(p
, end
);
1784 if ( (*s
== '\0') && (terminalSize
!= 0) ) {
1785 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1788 const uint8_t* children
= p
+ terminalSize
;
1789 if ( children
> end
) {
1790 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize
);
1793 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1794 uint8_t childrenRemaining
= *children
++;
1796 uintptr_t nodeOffset
= 0;
1797 for (; childrenRemaining
> 0; --childrenRemaining
) {
1799 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1800 bool wrongEdge
= false;
1801 // scan whole edge to get to next edge
1802 // if edge is longer than target symbol name, don't read past end of symbol name
1804 while ( c
!= '\0' ) {
1814 // advance to next child
1815 ++p
; // skip over zero terminator
1816 // skip over uleb128 until last byte is found
1817 while ( (*p
& 0x80) != 0 )
1819 ++p
; // skip over last byte of uleb128
1821 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1826 // the symbol so far matches this edge (child)
1827 // so advance to the child's node
1829 nodeOffset
= read_uleb128(p
, end
);
1830 if ( (nodeOffset
== 0) || ( &start
[nodeOffset
] > end
) ) {
1831 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset
);
1835 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1839 if ( nodeOffset
!= 0 )
1840 p
= &start
[nodeOffset
];
1844 //dyld::log("trieWalk(%p) return NULL\n", start);
1850 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p
, const uint8_t* end
)
1852 uint64_t result
= 0;
1856 dyld::throwf("malformed uleb128");
1858 uint64_t slice
= *p
& 0x7f;
1861 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit
, result
);
1863 result
|= (slice
<< bit
);
1866 } while (*p
++ & 0x80);
1867 return (uintptr_t)result
;
1871 intptr_t ImageLoader::read_sleb128(const uint8_t*& p
, const uint8_t* end
)
1878 throw "malformed sleb128";
1880 result
|= (((int64_t)(byte
& 0x7f)) << bit
);
1882 } while (byte
& 0x80);
1883 // sign extend negative numbers
1884 if ( (byte
& 0x40) != 0 )
1885 result
|= (~0ULL) << bit
;
1886 return (intptr_t)result
;
1890 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple
);
1891 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair
);