dyld-832.7.1.tar.gz
[apple/dyld.git] / src / ImageLoader.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2010 Apple Inc. All rights reserved.
4 *
5 * @APPLE_LICENSE_HEADER_START@
6 *
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
12 * file.
13 *
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.
21 *
22 * @APPLE_LICENSE_HEADER_END@
23 */
24
25 #define __STDC_LIMIT_MACROS
26 #include <stdint.h>
27 #include <stdlib.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <mach/mach.h>
31 #include <mach-o/fat.h>
32 #include <sys/types.h>
33 #include <sys/stat.h>
34 #include <sys/mman.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>
40
41 #include <atomic>
42
43 #include "Tracing.h"
44
45 #include "ImageLoader.h"
46
47
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;
73
74
75
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)
86 {
87 #if __x86_64__
88 fAotPath = NULL;
89 #endif
90 if ( fPath != NULL )
91 fPathHash = hash(fPath);
92 if ( libCount > 512 )
93 dyld::throwf("too many dependent dylibs in %s", path);
94 }
95
96
97 void ImageLoader::deleteImage(ImageLoader* image)
98 {
99 delete image;
100 }
101
102
103 ImageLoader::~ImageLoader()
104 {
105 if ( fRealPath != NULL )
106 delete [] fRealPath;
107 if ( fPathOwnedByImage && (fPath != NULL) )
108 delete [] fPath;
109 #if __x86_64__
110 if ( fAotPath != NULL )
111 delete [] fAotPath;
112 #endif
113 }
114
115 void ImageLoader::setFileInfo(dev_t device, ino_t inode, time_t modDate)
116 {
117 fDevice = device;
118 fInode = inode;
119 fLastModified = modDate;
120 }
121
122 void ImageLoader::setMapped(const LinkContext& context)
123 {
124 fState = dyld_image_state_mapped;
125 context.notifySingle(dyld_image_state_mapped, this, NULL); // note: can throw exception
126 }
127
128 int ImageLoader::compare(const ImageLoader* right) const
129 {
130 if ( this->fDepth == right->fDepth ) {
131 if ( this->fLoadOrder == right->fLoadOrder )
132 return 0;
133 else if ( this->fLoadOrder < right->fLoadOrder )
134 return -1;
135 else
136 return 1;
137 }
138 else {
139 if ( this->fDepth < right->fDepth )
140 return -1;
141 else
142 return 1;
143 }
144 }
145
146 void ImageLoader::setPath(const char* path)
147 {
148 if ( fPathOwnedByImage && (fPath != NULL) )
149 delete [] fPath;
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 ) {
155 delete [] fRealPath;
156 fRealPath = NULL;
157 }
158 }
159
160 void ImageLoader::setPathUnowned(const char* path)
161 {
162 if ( fPathOwnedByImage && (fPath != NULL) ) {
163 delete [] fPath;
164 }
165 fPath = path;
166 fPathOwnedByImage = false;
167 fPathHash = hash(fPath);
168 }
169
170 void ImageLoader::setPaths(const char* path, const char* realPath)
171 {
172 this->setPath(path);
173 fRealPath = new char[strlen(realPath)+1];
174 strcpy((char*)fRealPath, realPath);
175 }
176
177
178 const char* ImageLoader::getRealPath() const
179 {
180 if ( fRealPath != NULL )
181 return fRealPath;
182 else
183 return fPath;
184 }
185
186 uint32_t ImageLoader::hash(const char* path)
187 {
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
191 uint32_t h = 0;
192 for (const char* s=path; *s != '\0'; ++s)
193 h = h*5 + *s;
194 return h;
195 }
196
197 bool ImageLoader::matchInstallPath() const
198 {
199 return fMatchByInstallName;
200 }
201
202 void ImageLoader::setMatchInstallPath(bool match)
203 {
204 fMatchByInstallName = match;
205 }
206
207 bool ImageLoader::statMatch(const struct stat& stat_buf) const
208 {
209 return ( (this->fDevice == stat_buf.st_dev) && (this->fInode == stat_buf.st_ino) );
210 }
211
212 const char* ImageLoader::shortName(const char* fullName)
213 {
214 // try to return leaf name
215 if ( fullName != NULL ) {
216 const char* s = strrchr(fullName, '/');
217 if ( s != NULL )
218 return &s[1];
219 }
220 return fullName;
221 }
222
223 const char* ImageLoader::getShortName() const
224 {
225 return shortName(fPath);
226 }
227
228 void ImageLoader::setLeaveMapped()
229 {
230 fLeaveMapped = true;
231 }
232
233 void ImageLoader::setHideExports(bool hide)
234 {
235 fHideSymbols = hide;
236 }
237
238 bool ImageLoader::hasHiddenExports() const
239 {
240 return fHideSymbols;
241 }
242
243 bool ImageLoader::isLinked() const
244 {
245 return (fState >= dyld_image_state_bound);
246 }
247
248 time_t ImageLoader::lastModified() const
249 {
250 return fLastModified;
251 }
252
253 bool ImageLoader::containsAddress(const void* addr) const
254 {
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) )
259 return true;
260 }
261 return false;
262 }
263
264 bool ImageLoader::overlapsWithAddressRange(const void* start, const void* end) const
265 {
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()
272 // is too expensive.
273 segStart -= getSlide();
274 segEnd -= getSlide();
275 }
276 if ( (start <= segStart) && (segStart < end) )
277 return true;
278 if ( (start <= segEnd) && (segEnd < end) )
279 return true;
280 if ( (segStart < start) && (end < segEnd) )
281 return true;
282 }
283 return false;
284 }
285
286 void ImageLoader::getMappedRegions(MappedRegion*& regions) const
287 {
288 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
289 MappedRegion region;
290 region.address = segActualLoadAddress(i);
291 region.size = segSize(i);
292 *regions++ = region;
293 }
294 }
295
296
297
298 bool ImageLoader::dependsOn(ImageLoader* image) {
299 for(unsigned int i=0; i < libraryCount(); ++i) {
300 if ( libImage(i) == image )
301 return true;
302 }
303 return false;
304 }
305
306
307 static bool notInImgageList(const ImageLoader* image, const ImageLoader** dsiStart, const ImageLoader** dsiCur)
308 {
309 for (const ImageLoader** p = dsiStart; p < dsiCur; ++p)
310 if ( *p == image )
311 return false;
312 return true;
313 }
314
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
318 {
319 const Symbol* sym = this->findExportedSymbol(symbolName, true, foundIn);
320 if ( sym != NULL ) {
321 *address = (*foundIn)->getExportedSymbolAddress(sym, context, requestorImage, runResolver);
322 return true;
323 }
324 return false;
325 }
326
327
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
331 {
332 const ImageLoader::Symbol* sym;
333 // search self
334 if ( notInImgageList(this, dsiStart, dsiCur) ) {
335 sym = this->findExportedSymbol(name, false, this->getPath(), foundIn);
336 if ( sym != NULL )
337 return sym;
338 *dsiCur++ = this;
339 }
340
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);
346 if ( sym != NULL )
347 return sym;
348 }
349 }
350
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);
357 if ( sym != NULL )
358 return sym;
359 }
360 }
361
362 return NULL;
363 }
364
365
366 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
367 {
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);
373 }
374
375 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
376 {
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);
381 }
382
383 // this is called by initializeMainExecutable() to interpose on the initial set of images
384 void ImageLoader::applyInterposing(const LinkContext& context)
385 {
386 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_APPLY_INTERPOSING, 0, 0, 0);
387 if ( fgInterposingTuples.size() != 0 )
388 this->recursiveApplyInterposing(context);
389 }
390
391
392 uintptr_t ImageLoader::interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* inImage, const ImageLoader* onlyInImage)
393 {
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);
402 }
403 return it->replacement;
404 }
405 }
406 return address;
407 }
408
409 void ImageLoader::applyInterposingToDyldCache(const LinkContext& context) {
410 if (!context.dyldCache)
411 return;
412 if (!context.dyldCache->header.builtFromChainedFixups)
413 return;
414 if (fgInterposingTuples.empty())
415 return;
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);
422 uint32_t imageIndex;
423 uint32_t cacheOffsetOfReplacee = (uint32_t)(it->replacee - cacheStart);
424 if (!context.dyldCache->addressInText(cacheOffsetOfReplacee, &imageIndex))
425 continue;
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)
432 return;
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());
436 }
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));
451 return;
452 }
453 #endif
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);
457 });
458 });
459 }
460 }
461
462 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count)
463 {
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;
474 }
475 }
476 ImageLoader::fgInterposingTuples.push_back(tuple);
477 }
478 }
479
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)
482 {
483 #if TARGET_OS_IPHONE && !TARGET_OS_SIMULATOR
484 static bool sVmAccountingSuspended = false;
485 if ( suspend == sVmAccountingSuspended )
486 return;
487 if ( context.verboseBind )
488 dyld::log("set vm.footprint_suspend=%d\n", suspend);
489 int newValue = suspend ? 1 : 0;
490 int oldValue = 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;
497 #endif
498 }
499
500
501 void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, bool neverUnload, const RPathChain& loaderRPaths, const char* imagePath)
502 {
503 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
504
505 // clear error strings
506 (*context.setErrorStrings)(0, NULL, NULL, NULL);
507
508 uint64_t t0 = mach_absolute_time();
509 this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths, imagePath);
510 context.notifyBatch(dyld_image_state_dependents_mapped, preflightOnly);
511
512 // we only do the loading step for preflights
513 if ( preflightOnly )
514 return;
515
516 uint64_t t1 = mach_absolute_time();
517 context.clearAllDepths();
518 this->updateDepth(context.imageCount());
519
520 __block uint64_t t2, t3, t4, t5;
521 {
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);
526
527 t3 = mach_absolute_time();
528 if ( !context.linkingMainExecutable )
529 this->recursiveBindWithAccounting(context, forceLazysBound, neverUnload);
530
531 t4 = mach_absolute_time();
532 if ( !context.linkingMainExecutable )
533 this->weakBind(context);
534 t5 = mach_absolute_time();
535 }
536
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);
541 }
542
543 // now that all fixups are done, make __DATA_CONST segments read-only
544 if ( !context.linkingMainExecutable )
545 this->recursiveMakeDataReadOnly(context);
546
547 if ( !context.linkingMainExecutable )
548 context.notifyBatch(dyld_image_state_bound, false);
549 uint64_t t6 = mach_absolute_time();
550
551 if ( context.registerDOFs != NULL ) {
552 std::vector<DOFInfo> dofs;
553 this->recursiveGetDOFSections(context, dofs);
554 context.registerDOFs(dofs);
555 }
556 uint64_t t7 = mach_absolute_time();
557
558 // clear error strings
559 (*context.setErrorStrings)(0, NULL, NULL, NULL);
560
561 fgTotalLoadLibrariesTime += t1 - t0;
562 fgTotalRebaseTime += t3 - t2;
563 fgTotalBindTime += t4 - t3;
564 fgTotalWeakBindTime += t5 - t4;
565 fgTotalDOF += t7 - t6;
566
567 // done with initial dylib loads
568 fgNextPIEDylibAddress = 0;
569 }
570
571
572 void ImageLoader::printReferenceCounts()
573 {
574 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount, getPath() );
575 }
576
577
578 bool ImageLoader::decrementDlopenReferenceCount()
579 {
580 if ( fDlopenReferenceCount == 0 )
581 return true;
582 --fDlopenReferenceCount;
583 return false;
584 }
585
586
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
590 // has completed.
591 void ImageLoader::processInitializers(const LinkContext& context, mach_port_t thisThread,
592 InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& images)
593 {
594 uint32_t maxImageCount = context.imageCount()+2;
595 ImageLoader::UninitedUpwards upsBuffer[maxImageCount];
596 ImageLoader::UninitedUpwards& ups = upsBuffer[0];
597 ups.count = 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);
602 }
603 // If any upward dependencies remain, init them.
604 if ( ups.count > 0 )
605 processInitializers(context, thisThread, timingInfo, ups);
606 }
607
608
609 void ImageLoader::runInitializers(const LinkContext& context, InitializerTimingList& timingInfo)
610 {
611 uint64_t t1 = mach_absolute_time();
612 mach_port_t thisThread = mach_thread_self();
613 ImageLoader::UninitedUpwards up;
614 up.count = 1;
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);
621 }
622
623
624 void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
625 {
626 if ( ! fAllLazyPointersBound ) {
627 fAllLazyPointersBound = true;
628
629 if ( recursive ) {
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);
635 }
636 }
637 // bind lazies in this image
638 this->doBindJustLazies(context);
639 }
640 }
641
642
643 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
644 {
645 return fAllLibraryChecksumsAndLoadAddressesMatch;
646 }
647
648
649 void ImageLoader::markedUsedRecursive(const std::vector<DynamicReference>& dynamicReferences)
650 {
651 // already visited here
652 if ( fMarkedInUse )
653 return;
654 fMarkedInUse = true;
655
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);
661 }
662 }
663
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);
668 }
669
670 }
671
672 unsigned int ImageLoader::updateDepth(unsigned int maxDepth)
673 {
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)
678 continue;
679 danglingUpward->recursiveUpdateDepth(maxDepth, danglingUpwards);
680 }
681 return depth;
682 }
683
684 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth, dyld3::Array<ImageLoader*>& danglingUpwards)
685 {
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.
689 if ( fDepth == 0 ) {
690 // break cycles
691 fDepth = maxDepth;
692
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);
702 }
703 } else {
704 unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth, danglingUpwards);
705 if ( d < minDependentDepth )
706 minDependentDepth = d;
707 }
708 }
709 // <rdar://problem/60878811> make sure need to re-bind propagates up
710 if ( dependentImage != NULL ) {
711 if ( fAllLibraryChecksumsAndLoadAddressesMatch && !dependentImage->fAllLibraryChecksumsAndLoadAddressesMatch ) {
712 fAllLibraryChecksumsAndLoadAddressesMatch = false;
713 }
714 }
715 }
716 // make me less deep then all my dependents
717 fDepth = minDependentDepth - 1;
718
719 }
720 return fDepth;
721 }
722
723
724 void ImageLoader::recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths, const char* loadPath)
725 {
726 if ( fState < dyld_image_state_dependents_mapped ) {
727 // break cycles
728 fState = dyld_image_state_dependents_mapped;
729
730 // get list of libraries this image needs
731 DependentLibraryInfo libraryInfos[fLibraryCount];
732 this->doGetDependentLibraries(libraryInfos);
733
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);
738
739 // try to load each
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);
749 continue;
750 }
751 try {
752 unsigned cacheIndex;
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());
759 }
760 if ( fNeverUnload )
761 dependentLib->setNeverUnload();
762 if ( requiredLibInfo.upward ) {
763 }
764 else {
765 dependentLib->fIsReferencedDownward = true;
766 }
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);
772 }
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);
781 }
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;
788
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());
795 //}
796 }
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);
813 else
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
817 throw newMsg;
818 }
819 free((void*)msg); // our free() will do nothing if msg is a string literal
820 // ok if weak library not found
821 dependentLib = NULL;
822 canUsePrelinkingInfo = false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
823 }
824 setLibImage(i, dependentLib, depLibReExported, requiredLibInfo.upward);
825 }
826 fAllLibraryChecksumsAndLoadAddressesMatch = canUsePrelinkingInfo;
827
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);
833 }
834 }
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;
842 }
843 }
844 }
845
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;
849 free((void*)str);
850 }
851
852 }
853 }
854
855
856 void ImageLoader::recursiveRebaseWithAccounting(const LinkContext& context)
857 {
858 this->recursiveRebase(context);
859 vmAccountingSetSuspended(context, false);
860 }
861
862 void ImageLoader::recursiveRebase(const LinkContext& context)
863 {
864 if ( fState < dyld_image_state_rebased ) {
865 // break cycles
866 fState = dyld_image_state_rebased;
867
868 try {
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);
874 }
875
876 // rebase this image
877 doRebase(context);
878
879 // notify
880 context.notifySingle(dyld_image_state_rebased, this, NULL);
881 }
882 catch (const char* msg) {
883 // this image is not rebased
884 fState = dyld_image_state_dependents_mapped;
885 CRSetCrashLogMessage2(NULL);
886 throw;
887 }
888 }
889 }
890
891 void ImageLoader::recursiveApplyInterposing(const LinkContext& context)
892 {
893 if ( ! fInterposed ) {
894 // break cycles
895 fInterposed = true;
896
897 try {
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);
903 }
904
905 // interpose this image
906 doInterpose(context);
907 }
908 catch (const char* msg) {
909 // this image is not interposed
910 fInterposed = false;
911 throw;
912 }
913 }
914 }
915
916 void ImageLoader::recursiveMakeDataReadOnly(const LinkContext& context)
917 {
918 if ( ! fMadeReadOnly ) {
919 // break cycles
920 fMadeReadOnly = true;
921
922 try {
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);
928 }
929
930 // if this image has __DATA_CONST, make that segment read-only
931 makeDataReadOnly();
932 }
933 catch (const char* msg) {
934 fMadeReadOnly = false;
935 throw;
936 }
937 }
938 }
939
940
941 void ImageLoader::recursiveBindWithAccounting(const LinkContext& context, bool forceLazysBound, bool neverUnload)
942 {
943 this->recursiveBind(context, forceLazysBound, neverUnload, nullptr);
944 vmAccountingSetSuspended(context, false);
945 }
946
947 void ImageLoader::recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload, const ImageLoader* parent)
948 {
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 ) {
954 // break cycles
955 fState = dyld_image_state_bound;
956
957 try {
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);
966 }
967 }
968 // bind this image
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
974 if ( neverUnload )
975 this->setNeverUnload();
976
977 context.notifySingle(dyld_image_state_bound, this, NULL);
978 }
979 catch (const char* msg) {
980 // restore state
981 fState = dyld_image_state_rebased;
982 CRSetCrashLogMessage2(NULL);
983 throw;
984 }
985 }
986 }
987
988
989
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"
1002 };
1003
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);
1007 }
1008
1009 bool ImageLoader::EqualCString::equal(const char* s1, const char* s2) {
1010 return strcmp(s1, s2) == 0;
1011 }
1012
1013 void ImageLoader::weakBind(const LinkContext& context)
1014 {
1015
1016 if (!context.useNewWeakBind) {
1017 weakBindOld(context);
1018 return;
1019 }
1020
1021 if ( context.verboseWeakBind )
1022 dyld::log("dyld: weak bind start:\n");
1023 uint64_t t1 = mach_absolute_time();
1024
1025 // get set of ImageLoaders that participate in coalecsing
1026 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
1027 unsigned imageIndexes[fgImagesRequiringCoalescing];
1028 int count = context.getCoalescedImages(imagesNeedingCoalescing, imageIndexes);
1029
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;
1038 }
1039
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;
1046 }
1047 #if TARGET_OS_OSX
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;
1053
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() )
1059 continue;
1060 // Only process binaries which have had their weak symbols bound, ie, not the new ones we are processing now
1061 // from this dlopen
1062 if ( !image->weakSymbolsBound(imageIndexes[i]) )
1063 continue;
1064
1065 Diagnostics diag;
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() )
1072 return;
1073 symbolName = strdup(symbolName);
1074 }
1075 context.weakDefMap.insert({ symbolName, { image, targetAddr } });
1076 });
1077 }
1078 }
1079
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]) )
1084 continue;
1085 // skip images without defs. We'll process refs later
1086 if ( !image->hasCoalescedExports() )
1087 continue;
1088 Diagnostics diag;
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() )
1095 return;
1096 symbolName = strdup(symbolName);
1097 }
1098 context.weakDefMap.insert({ symbolName, { image, targetAddr } });
1099 });
1100 }
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();
1107
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;
1123 } else {
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 )
1131 continue;
1132
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());
1141 break;
1142 }
1143 }
1144 }
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);
1153 }
1154 } else {
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);
1159 }
1160 }
1161 }
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());
1164 }
1165 }
1166 imageBeingFixedUp->setWeakSymbolsBound(imageIndexes[i]);
1167 }
1168 }
1169 else
1170 #endif // TARGET_OS_OSX
1171 {
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]));
1180 }
1181
1182 // walk all symbols keeping iterators in sync by
1183 // only ever incrementing the iterator with the lowest symbol
1184 int doneCount = 0;
1185 while ( doneCount != count ) {
1186 //for(int i=0; i < count; ++i)
1187 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1188 //dyld::log("\n");
1189 // increment iterator with lowest symbol
1190 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
1191 ++doneCount;
1192 // re-sort iterators
1193 for(int i=1; i < count; ++i) {
1194 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
1195 if ( result == 0 )
1196 sortedIts[i-1]->symbolMatches = true;
1197 if ( result > 0 ) {
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;
1202 }
1203 if ( result < 0 )
1204 break;
1205 }
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;
1223 }
1224 }
1225 }
1226 else {
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
1232 break;
1233 }
1234 }
1235 }
1236 }
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));
1242 }
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));
1249 }
1250 if ( ! iterators[i].image->weakSymbolsBound(imageIndexes[i]) )
1251 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, targetImageIndex, context);
1252 iterators[i].symbolMatches = false;
1253 }
1254 }
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",
1260 nameToCoalesce);
1261 }
1262 }
1263 }
1264
1265 }
1266 }
1267
1268 for (int i=0; i < count; ++i) {
1269 if ( imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1270 continue; // skip images already processed
1271
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);
1278 }
1279 }
1280 #if __arm64e__
1281 else {
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);
1292 }
1293 }
1294 #endif
1295 }
1296
1297 // mark all as having all weak symbols bound
1298 for(int i=0; i < count; ++i) {
1299 imagesNeedingCoalescing[i]->setWeakSymbolsBound(imageIndexes[i]);
1300 }
1301 }
1302 }
1303
1304 uint64_t t2 = mach_absolute_time();
1305 fgTotalWeakBindTime += t2 - t1;
1306
1307 if ( context.verboseWeakBind )
1308 dyld::log("dyld: weak bind end\n");
1309 }
1310
1311
1312 void ImageLoader::weakBindOld(const LinkContext& context)
1313 {
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);
1321
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;
1330 }
1331
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) ) {
1334 #if TARGET_OS_OSX
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();
1343
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 )
1360 continue;
1361
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());
1372 break;
1373 }
1374 else {
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());
1381 }
1382 }
1383 }
1384 }
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());
1389 }
1390 }
1391 imageBeingFixedUp->setWeakSymbolsBound(imageIndexes[i]);
1392 }
1393 }
1394 else
1395 #endif // TARGET_OS_OSX
1396 {
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]));
1405 }
1406
1407 // walk all symbols keeping iterators in sync by
1408 // only ever incrementing the iterator with the lowest symbol
1409 int doneCount = 0;
1410 while ( doneCount != count ) {
1411 //for(int i=0; i < count; ++i)
1412 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1413 //dyld::log("\n");
1414 // increment iterator with lowest symbol
1415 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
1416 ++doneCount;
1417 // re-sort iterators
1418 for(int i=1; i < count; ++i) {
1419 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
1420 if ( result == 0 )
1421 sortedIts[i-1]->symbolMatches = true;
1422 if ( result > 0 ) {
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;
1427 }
1428 if ( result < 0 )
1429 break;
1430 }
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;
1448 }
1449 }
1450 }
1451 else {
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
1457 break;
1458 }
1459 }
1460 }
1461 }
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));
1467 }
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));
1474 }
1475 if ( ! iterators[i].image->weakSymbolsBound(imageIndexes[i]) )
1476 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, targetImageIndex, context);
1477 iterators[i].symbolMatches = false;
1478 }
1479 }
1480 }
1481
1482 }
1483 }
1484
1485 for (int i=0; i < count; ++i) {
1486 if ( imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1487 continue; // skip images already processed
1488
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);
1495 }
1496 }
1497 #if __arm64e__
1498 else {
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);
1509 }
1510 }
1511 #endif
1512 }
1513
1514 // mark all as having all weak symbols bound
1515 for(int i=0; i < count; ++i) {
1516 imagesNeedingCoalescing[i]->setWeakSymbolsBound(imageIndexes[i]);
1517 }
1518 }
1519 }
1520
1521 uint64_t t2 = mach_absolute_time();
1522 fgTotalWeakBindTime += t2 - t1;
1523
1524 if ( context.verboseWeakBind )
1525 dyld::log("dyld: weak bind end\n");
1526 }
1527
1528
1529
1530 void ImageLoader::recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs)
1531 {
1532 if ( ! fRegisteredDOF ) {
1533 // break cycles
1534 fRegisteredDOF = true;
1535
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);
1541 }
1542 this->doGetDOFSections(context, dofs);
1543 }
1544 }
1545
1546 void ImageLoader::setNeverUnloadRecursive() {
1547 if ( ! fNeverUnload ) {
1548 // break cycles
1549 fNeverUnload = true;
1550
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();
1556 }
1557 }
1558 }
1559
1560 void ImageLoader::recursiveSpinLock(recursive_lock& rlock)
1561 {
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) )
1570 break;
1571 }
1572 #pragma clang diagnostic pop
1573 ++(fInitializerRecursiveLock->count);
1574 }
1575
1576 void ImageLoader::recursiveSpinUnLock()
1577 {
1578 if ( --(fInitializerRecursiveLock->count) == 0 )
1579 fInitializerRecursiveLock = NULL;
1580 }
1581
1582 void ImageLoader::InitializerTimingList::addTime(const char* name, uint64_t time)
1583 {
1584 for (int i=0; i < count; ++i) {
1585 if ( strcmp(images[i].shortName, name) == 0 ) {
1586 images[i].initTime += time;
1587 return;
1588 }
1589 }
1590 images[count].initTime = time;
1591 images[count].shortName = name;
1592 ++count;
1593 }
1594
1595 void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread, const char* pathToInitialize,
1596 InitializerTimingList& timingInfo, UninitedUpwards& uninitUps)
1597 {
1598 recursive_lock lock_info(this_thread);
1599 recursiveSpinLock(lock_info);
1600
1601 if ( fState < dyld_image_state_dependents_initialized-1 ) {
1602 uint8_t oldState = fState;
1603 // break cycles
1604 fState = dyld_image_state_dependents_initialized-1;
1605 try {
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) };
1613 uninitUps.count++;
1614 }
1615 else if ( dependentImage->fDepth >= fDepth ) {
1616 dependentImage->recursiveInitialization(context, this_thread, libPath(i), timingInfo, uninitUps);
1617 }
1618 }
1619 }
1620
1621 // record termination order
1622 if ( this->needsTermination() )
1623 context.terminationRecorder(this);
1624
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;
1628 oldState = fState;
1629 context.notifySingle(dyld_image_state_dependents_initialized, this, &timingInfo);
1630
1631 // initialize this image
1632 bool hasInitializers = this->doInitialization(context);
1633
1634 // let anyone know we finished initializing this image
1635 fState = dyld_image_state_initialized;
1636 oldState = fState;
1637 context.notifySingle(dyld_image_state_initialized, this, NULL);
1638
1639 if ( hasInitializers ) {
1640 uint64_t t2 = mach_absolute_time();
1641 timingInfo.addTime(this->getShortName(), t2-t1);
1642 }
1643 }
1644 catch (const char* msg) {
1645 // this image is not initialized
1646 fState = oldState;
1647 recursiveSpinUnLock();
1648 throw;
1649 }
1650 }
1651
1652 recursiveSpinUnLock();
1653 }
1654
1655
1656 static void printTime(const char* msg, uint64_t partTime, uint64_t totalTime)
1657 {
1658 static uint64_t sUnitsPerSecond = 0;
1659 if ( sUnitsPerSecond == 0 ) {
1660 struct mach_timebase_info timeBaseInfo;
1661 if ( mach_timebase_info(&timeBaseInfo) != KERN_SUCCESS )
1662 return;
1663 sUnitsPerSecond = 1000000000ULL * timeBaseInfo.denom / timeBaseInfo.numer;
1664 }
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);
1674 else
1675 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1676 }
1677 else {
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);
1683 }
1684 }
1685
1686 static char* commatize(uint64_t in, char* out)
1687 {
1688 uint64_t div10 = in / 10;
1689 uint8_t delta = in - div10*10;
1690 char* s = &out[32];
1691 int digitCount = 1;
1692 *s = '\0';
1693 *(--s) = '0' + delta;
1694 in = div10;
1695 while ( in != 0 ) {
1696 if ( (digitCount % 3) == 0 )
1697 *(--s) = ',';
1698 div10 = in / 10;
1699 delta = in - div10*10;
1700 *(--s) = '0' + delta;
1701 in = div10;
1702 ++digitCount;
1703 }
1704 return s;
1705 }
1706
1707
1708 void ImageLoader::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
1709 {
1710 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1711
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 )
1722 continue;
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);
1727 }
1728 dyld::log("\n");
1729 }
1730
1731 void ImageLoader::printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo)
1732 {
1733 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1734 char commaNum1[40];
1735 char commaNum2[40];
1736
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);
1753 }
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 )
1762 continue;
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);
1767 }
1768
1769 }
1770
1771
1772 //
1773 // copy path and add suffix to result
1774 //
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
1780 //
1781 void ImageLoader::addSuffix(const char* path, const char* suffix, char* result)
1782 {
1783 strcpy(result, path);
1784
1785 char* start = strrchr(result, '/');
1786 if ( start != NULL )
1787 start++;
1788 else
1789 start = result;
1790
1791 char* dot = strrchr(start, '.');
1792 if ( dot != NULL ) {
1793 strcpy(dot, suffix);
1794 strcat(&dot[strlen(suffix)], &path[dot-result]);
1795 }
1796 else {
1797 strcat(result, suffix);
1798 }
1799 }
1800
1801
1802 //
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.
1805 //
1806 const uint8_t* ImageLoader::trieWalk(const uint8_t* start, const uint8_t* end, const char* s)
1807 {
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
1815 --p;
1816 terminalSize = read_uleb128(p, end);
1817 }
1818 if ( (*s == '\0') && (terminalSize != 0) ) {
1819 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1820 return p;
1821 }
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);
1825 return NULL;
1826 }
1827 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1828 uint8_t childrenRemaining = *children++;
1829 p = children;
1830 uintptr_t nodeOffset = 0;
1831 for (; childrenRemaining > 0; --childrenRemaining) {
1832 const char* ss = s;
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
1837 char c = *p;
1838 while ( c != '\0' ) {
1839 if ( !wrongEdge ) {
1840 if ( c != *ss )
1841 wrongEdge = true;
1842 ++ss;
1843 }
1844 ++p;
1845 c = *p;
1846 }
1847 if ( wrongEdge ) {
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 )
1852 ++p;
1853 ++p; // skip over last byte of uleb128
1854 if ( p > end ) {
1855 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1856 return NULL;
1857 }
1858 }
1859 else {
1860 // the symbol so far matches this edge (child)
1861 // so advance to the child's node
1862 ++p;
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);
1866 return NULL;
1867 }
1868 s = ss;
1869 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1870 break;
1871 }
1872 }
1873 if ( nodeOffset != 0 )
1874 p = &start[nodeOffset];
1875 else
1876 p = NULL;
1877 }
1878 //dyld::log("trieWalk(%p) return NULL\n", start);
1879 return NULL;
1880 }
1881
1882
1883
1884 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p, const uint8_t* end)
1885 {
1886 uint64_t result = 0;
1887 int bit = 0;
1888 do {
1889 if (p == end)
1890 dyld::throwf("malformed uleb128");
1891
1892 uint64_t slice = *p & 0x7f;
1893
1894 if (bit > 63)
1895 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit, result);
1896 else {
1897 result |= (slice << bit);
1898 bit += 7;
1899 }
1900 } while (*p++ & 0x80);
1901 return (uintptr_t)result;
1902 }
1903
1904
1905 intptr_t ImageLoader::read_sleb128(const uint8_t*& p, const uint8_t* end)
1906 {
1907 int64_t result = 0;
1908 int bit = 0;
1909 uint8_t byte;
1910 do {
1911 if (p == end)
1912 throw "malformed sleb128";
1913 byte = *p++;
1914 result |= (((int64_t)(byte & 0x7f)) << bit);
1915 bit += 7;
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;
1921 }
1922
1923 void ImageLoader::forEachReExportDependent( void (^callback)(const ImageLoader*, bool& stop)) const
1924 {
1925 bool stop = false;
1926 for (unsigned int i=0; i < libraryCount(); ++i) {
1927 if ( libReExported(i) ) {
1928 if ( ImageLoader* dependentImage = libImage(i) ) {
1929 callback(dependentImage, stop);
1930 }
1931 }
1932 if (stop)
1933 break;
1934 }
1935 }
1936
1937
1938 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple);
1939 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair);
1940
1941
1942