dyld-733.6.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 ( fPath != NULL )
88 fPathHash = hash(fPath);
89 if ( libCount > 512 )
90 dyld::throwf("too many dependent dylibs in %s", path);
91 }
92
93
94 void ImageLoader::deleteImage(ImageLoader* image)
95 {
96 delete image;
97 }
98
99
100 ImageLoader::~ImageLoader()
101 {
102 if ( fRealPath != NULL )
103 delete [] fRealPath;
104 if ( fPathOwnedByImage && (fPath != NULL) )
105 delete [] fPath;
106 }
107
108 void ImageLoader::setFileInfo(dev_t device, ino_t inode, time_t modDate)
109 {
110 fDevice = device;
111 fInode = inode;
112 fLastModified = modDate;
113 }
114
115 void ImageLoader::setMapped(const LinkContext& context)
116 {
117 fState = dyld_image_state_mapped;
118 context.notifySingle(dyld_image_state_mapped, this, NULL); // note: can throw exception
119 }
120
121 int ImageLoader::compare(const ImageLoader* right) const
122 {
123 if ( this->fDepth == right->fDepth ) {
124 if ( this->fLoadOrder == right->fLoadOrder )
125 return 0;
126 else if ( this->fLoadOrder < right->fLoadOrder )
127 return -1;
128 else
129 return 1;
130 }
131 else {
132 if ( this->fDepth < right->fDepth )
133 return -1;
134 else
135 return 1;
136 }
137 }
138
139 void ImageLoader::setPath(const char* path)
140 {
141 if ( fPathOwnedByImage && (fPath != NULL) )
142 delete [] fPath;
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 ) {
148 delete [] fRealPath;
149 fRealPath = NULL;
150 }
151 }
152
153 void ImageLoader::setPathUnowned(const char* path)
154 {
155 if ( fPathOwnedByImage && (fPath != NULL) ) {
156 delete [] fPath;
157 }
158 fPath = path;
159 fPathOwnedByImage = false;
160 fPathHash = hash(fPath);
161 }
162
163 void ImageLoader::setPaths(const char* path, const char* realPath)
164 {
165 this->setPath(path);
166 fRealPath = new char[strlen(realPath)+1];
167 strcpy((char*)fRealPath, realPath);
168 }
169
170
171 const char* ImageLoader::getRealPath() const
172 {
173 if ( fRealPath != NULL )
174 return fRealPath;
175 else
176 return fPath;
177 }
178
179 uint32_t ImageLoader::hash(const char* path)
180 {
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
184 uint32_t h = 0;
185 for (const char* s=path; *s != '\0'; ++s)
186 h = h*5 + *s;
187 return h;
188 }
189
190 bool ImageLoader::matchInstallPath() const
191 {
192 return fMatchByInstallName;
193 }
194
195 void ImageLoader::setMatchInstallPath(bool match)
196 {
197 fMatchByInstallName = match;
198 }
199
200 bool ImageLoader::statMatch(const struct stat& stat_buf) const
201 {
202 return ( (this->fDevice == stat_buf.st_dev) && (this->fInode == stat_buf.st_ino) );
203 }
204
205 const char* ImageLoader::shortName(const char* fullName)
206 {
207 // try to return leaf name
208 if ( fullName != NULL ) {
209 const char* s = strrchr(fullName, '/');
210 if ( s != NULL )
211 return &s[1];
212 }
213 return fullName;
214 }
215
216 const char* ImageLoader::getShortName() const
217 {
218 return shortName(fPath);
219 }
220
221 void ImageLoader::setLeaveMapped()
222 {
223 fLeaveMapped = true;
224 }
225
226 void ImageLoader::setHideExports(bool hide)
227 {
228 fHideSymbols = hide;
229 }
230
231 bool ImageLoader::hasHiddenExports() const
232 {
233 return fHideSymbols;
234 }
235
236 bool ImageLoader::isLinked() const
237 {
238 return (fState >= dyld_image_state_bound);
239 }
240
241 time_t ImageLoader::lastModified() const
242 {
243 return fLastModified;
244 }
245
246 bool ImageLoader::containsAddress(const void* addr) const
247 {
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) )
252 return true;
253 }
254 return false;
255 }
256
257 bool ImageLoader::overlapsWithAddressRange(const void* start, const void* end) const
258 {
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()
265 // is too expensive.
266 segStart -= getSlide();
267 segEnd -= getSlide();
268 }
269 if ( (start <= segStart) && (segStart < end) )
270 return true;
271 if ( (start <= segEnd) && (segEnd < end) )
272 return true;
273 if ( (segStart < start) && (end < segEnd) )
274 return true;
275 }
276 return false;
277 }
278
279 void ImageLoader::getMappedRegions(MappedRegion*& regions) const
280 {
281 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
282 MappedRegion region;
283 region.address = segActualLoadAddress(i);
284 region.size = segSize(i);
285 *regions++ = region;
286 }
287 }
288
289
290
291 bool ImageLoader::dependsOn(ImageLoader* image) {
292 for(unsigned int i=0; i < libraryCount(); ++i) {
293 if ( libImage(i) == image )
294 return true;
295 }
296 return false;
297 }
298
299
300 static bool notInImgageList(const ImageLoader* image, const ImageLoader** dsiStart, const ImageLoader** dsiCur)
301 {
302 for (const ImageLoader** p = dsiStart; p < dsiCur; ++p)
303 if ( *p == image )
304 return false;
305 return true;
306 }
307
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
311 {
312 const Symbol* sym = this->findExportedSymbol(symbolName, true, foundIn);
313 if ( sym != NULL ) {
314 *address = (*foundIn)->getExportedSymbolAddress(sym, context, requestorImage, runResolver);
315 return true;
316 }
317 return false;
318 }
319
320
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
324 {
325 const ImageLoader::Symbol* sym;
326 // search self
327 if ( notInImgageList(this, dsiStart, dsiCur) ) {
328 sym = this->findExportedSymbol(name, false, this->getPath(), foundIn);
329 if ( sym != NULL )
330 return sym;
331 *dsiCur++ = this;
332 }
333
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);
339 if ( sym != NULL )
340 return sym;
341 }
342 }
343
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);
350 if ( sym != NULL )
351 return sym;
352 }
353 }
354
355 return NULL;
356 }
357
358
359 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
360 {
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);
366 }
367
368 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
369 {
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);
374 }
375
376 // this is called by initializeMainExecutable() to interpose on the initial set of images
377 void ImageLoader::applyInterposing(const LinkContext& context)
378 {
379 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_APPLY_INTERPOSING, 0, 0, 0);
380 if ( fgInterposingTuples.size() != 0 )
381 this->recursiveApplyInterposing(context);
382 }
383
384
385 uintptr_t ImageLoader::interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* inImage, const ImageLoader* onlyInImage)
386 {
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);
395 }
396 return it->replacement;
397 }
398 }
399 return address;
400 }
401
402 void ImageLoader::applyInterposingToDyldCache(const LinkContext& context) {
403 if (!context.dyldCache)
404 return;
405 #if !__arm64e__ // until arm64e cache builder sets builtFromChainedFixups
406 if (!context.dyldCache->header.builtFromChainedFixups)
407 return;
408 #endif
409 if (fgInterposingTuples.empty())
410 return;
411 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
412 // that image and apply its patch table to all uses.
413 uintptr_t cacheStart = (uintptr_t)context.dyldCache;
414 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
415 if ( context.verboseInterposing )
416 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it->replacee);
417 uint32_t imageIndex;
418 uint32_t cacheOffsetOfReplacee = (uint32_t)(it->replacee - cacheStart);
419 if (!context.dyldCache->addressInText(cacheOffsetOfReplacee, &imageIndex))
420 continue;
421 dyld3::closure::ImageNum imageInCache = imageIndex+1;
422 if ( context.verboseInterposing )
423 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache, (uint64_t)it->replacee);
424 context.dyldCache->forEachPatchableExport(imageIndex, ^(uint32_t cacheOffsetOfImpl, const char* exportName) {
425 // Skip patching anything other than this symbol
426 if (cacheOffsetOfImpl != cacheOffsetOfReplacee)
427 return;
428 if ( context.verboseInterposing ) {
429 const dyld3::closure::Image* image = context.dyldCache->cachedDylibsImageArray()->imageForNum(imageInCache);
430 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName, image->path());
431 }
432 uintptr_t newLoc = it->replacement;
433 context.dyldCache->forEachPatchableUseOfExport(imageIndex, cacheOffsetOfImpl, ^(dyld_cache_patchable_location patchLocation) {
434 uintptr_t* loc = (uintptr_t*)(cacheStart+patchLocation.cacheOffset);
435 #if __has_feature(ptrauth_calls)
436 if ( patchLocation.authenticated ) {
437 dyld3::MachOLoaded::ChainedFixupPointerOnDisk ptr = *(dyld3::MachOLoaded::ChainedFixupPointerOnDisk*)loc;
438 ptr.arm64e.authRebase.auth = true;
439 ptr.arm64e.authRebase.addrDiv = patchLocation.usesAddressDiversity;
440 ptr.arm64e.authRebase.diversity = patchLocation.discriminator;
441 ptr.arm64e.authRebase.key = patchLocation.key;
442 *loc = ptr.arm64e.signPointer(loc, newLoc + DyldSharedCache::getAddend(patchLocation));
443 if ( context.verboseInterposing )
444 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
445 loc, (void*)*loc, patchLocation.discriminator, patchLocation.usesAddressDiversity, DyldSharedCache::keyName(patchLocation));
446 return;
447 }
448 #endif
449 if ( context.verboseInterposing )
450 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc, newLoc + DyldSharedCache::getAddend(patchLocation), exportName);
451 *loc = newLoc + (uintptr_t)DyldSharedCache::getAddend(patchLocation);
452 });
453 });
454 }
455 }
456
457 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count)
458 {
459 for(size_t i=0; i < count; ++i) {
460 ImageLoader::InterposeTuple tuple;
461 tuple.replacement = (uintptr_t)array[i].replacement;
462 tuple.neverImage = NULL;
463 tuple.onlyImage = this;
464 tuple.replacee = (uintptr_t)array[i].replacee;
465 // chain to any existing interpositions
466 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
467 if ( (it->replacee == tuple.replacee) && (it->onlyImage == this) ) {
468 tuple.replacee = it->replacement;
469 }
470 }
471 ImageLoader::fgInterposingTuples.push_back(tuple);
472 }
473 }
474
475 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
476 void ImageLoader::vmAccountingSetSuspended(const LinkContext& context, bool suspend)
477 {
478 #if __arm__ || __arm64__
479 static bool sVmAccountingSuspended = false;
480 if ( suspend == sVmAccountingSuspended )
481 return;
482 if ( context.verboseBind )
483 dyld::log("set vm.footprint_suspend=%d\n", suspend);
484 int newValue = suspend ? 1 : 0;
485 int oldValue = 0;
486 size_t newlen = sizeof(newValue);
487 size_t oldlen = sizeof(oldValue);
488 int ret = sysctlbyname("vm.footprint_suspend", &oldValue, &oldlen, &newValue, newlen);
489 if ( context.verboseBind && (ret != 0) )
490 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret, errno);
491 sVmAccountingSuspended = suspend;
492 #endif
493 }
494
495
496 void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, bool neverUnload, const RPathChain& loaderRPaths, const char* imagePath)
497 {
498 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
499
500 // clear error strings
501 (*context.setErrorStrings)(0, NULL, NULL, NULL);
502
503 uint64_t t0 = mach_absolute_time();
504 this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths, imagePath);
505 context.notifyBatch(dyld_image_state_dependents_mapped, preflightOnly);
506
507 // we only do the loading step for preflights
508 if ( preflightOnly )
509 return;
510
511 uint64_t t1 = mach_absolute_time();
512 context.clearAllDepths();
513 this->recursiveUpdateDepth(context.imageCount());
514
515 __block uint64_t t2, t3, t4, t5;
516 {
517 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS, 0, 0, 0);
518 t2 = mach_absolute_time();
519 this->recursiveRebaseWithAccounting(context);
520 context.notifyBatch(dyld_image_state_rebased, false);
521
522 t3 = mach_absolute_time();
523 if ( !context.linkingMainExecutable )
524 this->recursiveBindWithAccounting(context, forceLazysBound, neverUnload);
525
526 t4 = mach_absolute_time();
527 if ( !context.linkingMainExecutable )
528 this->weakBind(context);
529 t5 = mach_absolute_time();
530 }
531
532 // interpose any dynamically loaded images
533 if ( !context.linkingMainExecutable && (fgInterposingTuples.size() != 0) ) {
534 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_APPLY_INTERPOSING, 0, 0, 0);
535 this->recursiveApplyInterposing(context);
536 }
537
538 // now that all fixups are done, make __DATA_CONST segments read-only
539 if ( !context.linkingMainExecutable )
540 this->recursiveMakeDataReadOnly(context);
541
542 if ( !context.linkingMainExecutable )
543 context.notifyBatch(dyld_image_state_bound, false);
544 uint64_t t6 = mach_absolute_time();
545
546 if ( context.registerDOFs != NULL ) {
547 std::vector<DOFInfo> dofs;
548 this->recursiveGetDOFSections(context, dofs);
549 context.registerDOFs(dofs);
550 }
551 uint64_t t7 = mach_absolute_time();
552
553 // clear error strings
554 (*context.setErrorStrings)(0, NULL, NULL, NULL);
555
556 fgTotalLoadLibrariesTime += t1 - t0;
557 fgTotalRebaseTime += t3 - t2;
558 fgTotalBindTime += t4 - t3;
559 fgTotalWeakBindTime += t5 - t4;
560 fgTotalDOF += t7 - t6;
561
562 // done with initial dylib loads
563 fgNextPIEDylibAddress = 0;
564 }
565
566
567 void ImageLoader::printReferenceCounts()
568 {
569 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount, getPath() );
570 }
571
572
573 bool ImageLoader::decrementDlopenReferenceCount()
574 {
575 if ( fDlopenReferenceCount == 0 )
576 return true;
577 --fDlopenReferenceCount;
578 return false;
579 }
580
581
582 // <rdar://problem/14412057> upward dylib initializers can be run too soon
583 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
584 // have their initialization postponed until after the recursion through downward dylibs
585 // has completed.
586 void ImageLoader::processInitializers(const LinkContext& context, mach_port_t thisThread,
587 InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& images)
588 {
589 uint32_t maxImageCount = context.imageCount()+2;
590 ImageLoader::UninitedUpwards upsBuffer[maxImageCount];
591 ImageLoader::UninitedUpwards& ups = upsBuffer[0];
592 ups.count = 0;
593 // Calling recursive init on all images in images list, building a new list of
594 // uninitialized upward dependencies.
595 for (uintptr_t i=0; i < images.count; ++i) {
596 images.imagesAndPaths[i].first->recursiveInitialization(context, thisThread, images.imagesAndPaths[i].second, timingInfo, ups);
597 }
598 // If any upward dependencies remain, init them.
599 if ( ups.count > 0 )
600 processInitializers(context, thisThread, timingInfo, ups);
601 }
602
603
604 void ImageLoader::runInitializers(const LinkContext& context, InitializerTimingList& timingInfo)
605 {
606 uint64_t t1 = mach_absolute_time();
607 mach_port_t thisThread = mach_thread_self();
608 ImageLoader::UninitedUpwards up;
609 up.count = 1;
610 up.imagesAndPaths[0] = { this, this->getPath() };
611 processInitializers(context, thisThread, timingInfo, up);
612 context.notifyBatch(dyld_image_state_initialized, false);
613 mach_port_deallocate(mach_task_self(), thisThread);
614 uint64_t t2 = mach_absolute_time();
615 fgTotalInitTime += (t2 - t1);
616 }
617
618
619 void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
620 {
621 if ( ! fAllLazyPointersBound ) {
622 fAllLazyPointersBound = true;
623
624 if ( recursive ) {
625 // bind lower level libraries first
626 for(unsigned int i=0; i < libraryCount(); ++i) {
627 ImageLoader* dependentImage = libImage(i);
628 if ( dependentImage != NULL )
629 dependentImage->bindAllLazyPointers(context, recursive);
630 }
631 }
632 // bind lazies in this image
633 this->doBindJustLazies(context);
634 }
635 }
636
637
638 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
639 {
640 return fAllLibraryChecksumsAndLoadAddressesMatch;
641 }
642
643
644 void ImageLoader::markedUsedRecursive(const std::vector<DynamicReference>& dynamicReferences)
645 {
646 // already visited here
647 if ( fMarkedInUse )
648 return;
649 fMarkedInUse = true;
650
651 // clear mark on all statically dependent dylibs
652 for(unsigned int i=0; i < libraryCount(); ++i) {
653 ImageLoader* dependentImage = libImage(i);
654 if ( dependentImage != NULL ) {
655 dependentImage->markedUsedRecursive(dynamicReferences);
656 }
657 }
658
659 // clear mark on all dynamically dependent dylibs
660 for (std::vector<ImageLoader::DynamicReference>::const_iterator it=dynamicReferences.begin(); it != dynamicReferences.end(); ++it) {
661 if ( it->from == this )
662 it->to->markedUsedRecursive(dynamicReferences);
663 }
664
665 }
666
667 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth)
668 {
669 // the purpose of this phase is to make the images sortable such that
670 // in a sort list of images, every image that an image depends on
671 // occurs in the list before it.
672 if ( fDepth == 0 ) {
673 // break cycles
674 fDepth = maxDepth;
675
676 // get depth of dependents
677 unsigned int minDependentDepth = maxDepth;
678 for(unsigned int i=0; i < libraryCount(); ++i) {
679 ImageLoader* dependentImage = libImage(i);
680 if ( (dependentImage != NULL) && !libIsUpward(i) ) {
681 unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth);
682 if ( d < minDependentDepth )
683 minDependentDepth = d;
684 }
685 }
686
687 // make me less deep then all my dependents
688 fDepth = minDependentDepth - 1;
689 }
690
691 return fDepth;
692 }
693
694
695 void ImageLoader::recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths, const char* loadPath)
696 {
697 if ( fState < dyld_image_state_dependents_mapped ) {
698 // break cycles
699 fState = dyld_image_state_dependents_mapped;
700
701 // get list of libraries this image needs
702 DependentLibraryInfo libraryInfos[fLibraryCount];
703 this->doGetDependentLibraries(libraryInfos);
704
705 // get list of rpaths that this image adds
706 std::vector<const char*> rpathsFromThisImage;
707 this->getRPaths(context, rpathsFromThisImage);
708 const RPathChain thisRPaths(&loaderRPaths, &rpathsFromThisImage);
709
710 // try to load each
711 bool canUsePrelinkingInfo = true;
712 for(unsigned int i=0; i < fLibraryCount; ++i){
713 ImageLoader* dependentLib;
714 bool depLibReExported = false;
715 DependentLibraryInfo& requiredLibInfo = libraryInfos[i];
716 if ( preflightOnly && context.inSharedCache(requiredLibInfo.name) ) {
717 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
718 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
719 setLibImage(i, NULL, false, false);
720 continue;
721 }
722 try {
723 unsigned cacheIndex;
724 dependentLib = context.loadLibrary(requiredLibInfo.name, true, this->getPath(), &thisRPaths, cacheIndex);
725 if ( dependentLib == this ) {
726 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
727 dependentLib = context.loadLibrary(requiredLibInfo.name, false, NULL, NULL, cacheIndex);
728 if ( dependentLib != this )
729 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
730 }
731 if ( fNeverUnload )
732 dependentLib->setNeverUnload();
733 if ( requiredLibInfo.upward ) {
734 }
735 else {
736 dependentLib->fIsReferencedDownward = true;
737 }
738 LibraryInfo actualInfo = dependentLib->doGetLibraryInfo(requiredLibInfo.info);
739 depLibReExported = requiredLibInfo.reExported;
740 if ( ! depLibReExported ) {
741 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
742 depLibReExported = dependentLib->isSubframeworkOf(context, this) || this->hasSubLibrary(context, dependentLib);
743 }
744 // check found library version is compatible
745 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
746 if ( (requiredLibInfo.info.minVersion != 0xFFFFFFFF) && (actualInfo.minVersion < requiredLibInfo.info.minVersion)
747 && ((dyld3::MachOFile*)(dependentLib->machHeader()))->enforceCompatVersion() ) {
748 // record values for possible use by CrashReporter or Finder
749 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
750 this->getShortName(), requiredLibInfo.info.minVersion >> 16, (requiredLibInfo.info.minVersion >> 8) & 0xff, requiredLibInfo.info.minVersion & 0xff,
751 dependentLib->getShortName(), actualInfo.minVersion >> 16, (actualInfo.minVersion >> 8) & 0xff, actualInfo.minVersion & 0xff);
752 }
753 // prebinding for this image disabled if any dependent library changed
754 //if ( !depLibCheckSumsMatch )
755 // canUsePrelinkingInfo = false;
756 // prebinding for this image disabled unless both this and dependent are in the shared cache
757 if ( !dependentLib->inSharedCache() || !this->inSharedCache() )
758 canUsePrelinkingInfo = false;
759
760 //if ( context.verbosePrebinding ) {
761 // if ( !requiredLib.checksumMatches )
762 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
763 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
764 // if ( dependentLib->getSlide() != 0 )
765 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
766 //}
767 }
768 catch (const char* msg) {
769 //if ( context.verbosePrebinding )
770 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
771 if ( requiredLibInfo.required ) {
772 fState = dyld_image_state_mapped;
773 // record values for possible use by CrashReporter or Finder
774 if ( strstr(msg, "Incompatible library version") != NULL )
775 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION, this->getPath(), requiredLibInfo.name, NULL);
776 else if ( strstr(msg, "architecture") != NULL )
777 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH, this->getPath(), requiredLibInfo.name, NULL);
778 else if ( strstr(msg, "file system sandbox") != NULL )
779 (*context.setErrorStrings)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX, this->getPath(), requiredLibInfo.name, NULL);
780 else if ( strstr(msg, "code signature") != NULL )
781 (*context.setErrorStrings)(DYLD_EXIT_REASON_CODE_SIGNATURE, this->getPath(), requiredLibInfo.name, NULL);
782 else if ( strstr(msg, "malformed") != NULL )
783 (*context.setErrorStrings)(DYLD_EXIT_REASON_MALFORMED_MACHO, this->getPath(), requiredLibInfo.name, NULL);
784 else
785 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_MISSING, this->getPath(), requiredLibInfo.name, NULL);
786 const char* newMsg = dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo.name, this->getRealPath(), msg);
787 free((void*)msg); // our free() will do nothing if msg is a string literal
788 throw newMsg;
789 }
790 free((void*)msg); // our free() will do nothing if msg is a string literal
791 // ok if weak library not found
792 dependentLib = NULL;
793 canUsePrelinkingInfo = false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
794 }
795 setLibImage(i, dependentLib, depLibReExported, requiredLibInfo.upward);
796 }
797 fAllLibraryChecksumsAndLoadAddressesMatch = canUsePrelinkingInfo;
798
799 // tell each to load its dependents
800 for(unsigned int i=0; i < libraryCount(); ++i) {
801 ImageLoader* dependentImage = libImage(i);
802 if ( dependentImage != NULL ) {
803 dependentImage->recursiveLoadLibraries(context, preflightOnly, thisRPaths, libraryInfos[i].name);
804 }
805 }
806
807 // do deep prebind check
808 if ( fAllLibraryChecksumsAndLoadAddressesMatch ) {
809 for(unsigned int i=0; i < libraryCount(); ++i){
810 ImageLoader* dependentImage = libImage(i);
811 if ( dependentImage != NULL ) {
812 if ( !dependentImage->allDependentLibrariesAsWhenPreBound() )
813 fAllLibraryChecksumsAndLoadAddressesMatch = false;
814 }
815 }
816 }
817
818 // free rpaths (getRPaths() malloc'ed each string)
819 for(std::vector<const char*>::iterator it=rpathsFromThisImage.begin(); it != rpathsFromThisImage.end(); ++it) {
820 const char* str = *it;
821 free((void*)str);
822 }
823
824 }
825 }
826
827
828 void ImageLoader::recursiveRebaseWithAccounting(const LinkContext& context)
829 {
830 this->recursiveRebase(context);
831 vmAccountingSetSuspended(context, false);
832 }
833
834 void ImageLoader::recursiveRebase(const LinkContext& context)
835 {
836 if ( fState < dyld_image_state_rebased ) {
837 // break cycles
838 fState = dyld_image_state_rebased;
839
840 try {
841 // rebase lower level libraries first
842 for(unsigned int i=0; i < libraryCount(); ++i) {
843 ImageLoader* dependentImage = libImage(i);
844 if ( dependentImage != NULL )
845 dependentImage->recursiveRebase(context);
846 }
847
848 // rebase this image
849 doRebase(context);
850
851 // notify
852 context.notifySingle(dyld_image_state_rebased, this, NULL);
853 }
854 catch (const char* msg) {
855 // this image is not rebased
856 fState = dyld_image_state_dependents_mapped;
857 CRSetCrashLogMessage2(NULL);
858 throw;
859 }
860 }
861 }
862
863 void ImageLoader::recursiveApplyInterposing(const LinkContext& context)
864 {
865 if ( ! fInterposed ) {
866 // break cycles
867 fInterposed = true;
868
869 try {
870 // interpose lower level libraries first
871 for(unsigned int i=0; i < libraryCount(); ++i) {
872 ImageLoader* dependentImage = libImage(i);
873 if ( dependentImage != NULL )
874 dependentImage->recursiveApplyInterposing(context);
875 }
876
877 // interpose this image
878 doInterpose(context);
879 }
880 catch (const char* msg) {
881 // this image is not interposed
882 fInterposed = false;
883 throw;
884 }
885 }
886 }
887
888 void ImageLoader::recursiveMakeDataReadOnly(const LinkContext& context)
889 {
890 if ( ! fMadeReadOnly ) {
891 // break cycles
892 fMadeReadOnly = true;
893
894 try {
895 // handle lower level libraries first
896 for(unsigned int i=0; i < libraryCount(); ++i) {
897 ImageLoader* dependentImage = libImage(i);
898 if ( dependentImage != NULL )
899 dependentImage->recursiveMakeDataReadOnly(context);
900 }
901
902 // if this image has __DATA_CONST, make that segment read-only
903 makeDataReadOnly();
904 }
905 catch (const char* msg) {
906 fMadeReadOnly = false;
907 throw;
908 }
909 }
910 }
911
912
913 void ImageLoader::recursiveBindWithAccounting(const LinkContext& context, bool forceLazysBound, bool neverUnload)
914 {
915 this->recursiveBind(context, forceLazysBound, neverUnload);
916 vmAccountingSetSuspended(context, false);
917 }
918
919 void ImageLoader::recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload)
920 {
921 // Normally just non-lazy pointers are bound immediately.
922 // The exceptions are:
923 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
924 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
925 if ( fState < dyld_image_state_bound ) {
926 // break cycles
927 fState = dyld_image_state_bound;
928
929 try {
930 // bind lower level libraries first
931 for(unsigned int i=0; i < libraryCount(); ++i) {
932 ImageLoader* dependentImage = libImage(i);
933 if ( dependentImage != NULL )
934 dependentImage->recursiveBind(context, forceLazysBound, neverUnload);
935 }
936 // bind this image
937 this->doBind(context, forceLazysBound);
938 // mark if lazys are also bound
939 if ( forceLazysBound || this->usablePrebinding(context) )
940 fAllLazyPointersBound = true;
941 // mark as never-unload if requested
942 if ( neverUnload )
943 this->setNeverUnload();
944
945 context.notifySingle(dyld_image_state_bound, this, NULL);
946 }
947 catch (const char* msg) {
948 // restore state
949 fState = dyld_image_state_rebased;
950 CRSetCrashLogMessage2(NULL);
951 throw;
952 }
953 }
954 }
955
956
957
958 // These are mangled symbols for all the variants of operator new and delete
959 // which a main executable can define (non-weak) and override the
960 // weak-def implementation in the OS.
961 static const char* const sTreatAsWeak[] = {
962 "__Znwm", "__ZnwmRKSt9nothrow_t",
963 "__Znam", "__ZnamRKSt9nothrow_t",
964 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
965 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
966 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
967 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
968 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
969 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
970 };
971
972 size_t ImageLoader::HashCString::hash(const char* v) {
973 // FIXME: Use hash<string_view> when it has the correct visibility markup
974 return std::hash<std::string_view>{}(v);
975 }
976
977 bool ImageLoader::EqualCString::equal(const char* s1, const char* s2) {
978 return strcmp(s1, s2) == 0;
979 }
980
981 void ImageLoader::weakBind(const LinkContext& context)
982 {
983
984 if (!context.useNewWeakBind) {
985 weakBindOld(context);
986 return;
987 }
988
989 if ( context.verboseWeakBind )
990 dyld::log("dyld: weak bind start:\n");
991 uint64_t t1 = mach_absolute_time();
992
993 // get set of ImageLoaders that participate in coalecsing
994 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
995 unsigned imageIndexes[fgImagesRequiringCoalescing];
996 int count = context.getCoalescedImages(imagesNeedingCoalescing, imageIndexes);
997
998 // count how many have not already had weakbinding done
999 int countNotYetWeakBound = 0;
1000 int countOfImagesWithWeakDefinitionsNotInSharedCache = 0;
1001 for(int i=0; i < count; ++i) {
1002 if ( ! imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1003 ++countNotYetWeakBound;
1004 if ( ! imagesNeedingCoalescing[i]->inSharedCache() )
1005 ++countOfImagesWithWeakDefinitionsNotInSharedCache;
1006 }
1007
1008 // don't need to do any coalescing if only one image has overrides, or all have already been done
1009 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache > 0) && (countNotYetWeakBound > 0) ) {
1010 if (!context.weakDefMapInitialized) {
1011 // Initialize the weak def map as the link context doesn't run static initializers
1012 new (&context.weakDefMap) dyld3::Map<const char*, std::pair<const ImageLoader*, uintptr_t>, ImageLoader::HashCString, ImageLoader::EqualCString>();
1013 context.weakDefMapInitialized = true;
1014 }
1015 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1016 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1017 if ( !context.linkingMainExecutable ) {
1018 // Don't take the memory hit of weak defs on the launch path until we hit a dlopen with more weak symbols to bind
1019 if (!context.weakDefMapProcessedLaunchDefs) {
1020 context.weakDefMapProcessedLaunchDefs = true;
1021
1022 // Walk the nlist for all binaries from launch and fill in the map with any other weak defs
1023 for (int i=0; i < count; ++i) {
1024 const ImageLoader* image = imagesNeedingCoalescing[i];
1025 // skip images without defs. We've processed launch time refs already
1026 if ( !image->hasCoalescedExports() )
1027 continue;
1028 // Only process binaries which have had their weak symbols bound, ie, not the new ones we are processing now
1029 // from this dlopen
1030 if ( !image->weakSymbolsBound(imageIndexes[i]) )
1031 continue;
1032
1033 Diagnostics diag;
1034 const dyld3::MachOAnalyzer* ma = (const dyld3::MachOAnalyzer*)image->machHeader();
1035 ma->forEachWeakDef(diag, ^(const char *symbolName, uintptr_t imageOffset, bool isFromExportTrie) {
1036 uintptr_t targetAddr = (uintptr_t)ma + imageOffset;
1037 if ( isFromExportTrie ) {
1038 // Avoid duplicating the string if we already have the symbol name
1039 if ( context.weakDefMap.find(symbolName) != context.weakDefMap.end() )
1040 return;
1041 symbolName = strdup(symbolName);
1042 }
1043 context.weakDefMap.insert({ symbolName, { image, targetAddr } });
1044 });
1045 }
1046 }
1047
1048 // Walk the nlist for all binaries in dlopen and fill in the map with any other weak defs
1049 for (int i=0; i < count; ++i) {
1050 const ImageLoader* image = imagesNeedingCoalescing[i];
1051 if ( image->weakSymbolsBound(imageIndexes[i]) )
1052 continue;
1053 // skip images without defs. We'll process refs later
1054 if ( !image->hasCoalescedExports() )
1055 continue;
1056 Diagnostics diag;
1057 const dyld3::MachOAnalyzer* ma = (const dyld3::MachOAnalyzer*)image->machHeader();
1058 ma->forEachWeakDef(diag, ^(const char *symbolName, uintptr_t imageOffset, bool isFromExportTrie) {
1059 uintptr_t targetAddr = (uintptr_t)ma + imageOffset;
1060 if ( isFromExportTrie ) {
1061 // Avoid duplicating the string if we already have the symbol name
1062 if ( context.weakDefMap.find(symbolName) != context.weakDefMap.end() )
1063 return;
1064 symbolName = strdup(symbolName);
1065 }
1066 context.weakDefMap.insert({ symbolName, { image, targetAddr } });
1067 });
1068 }
1069 // for all images that need weak binding
1070 for (int i=0; i < count; ++i) {
1071 ImageLoader* imageBeingFixedUp = imagesNeedingCoalescing[i];
1072 if ( imageBeingFixedUp->weakSymbolsBound(imageIndexes[i]) )
1073 continue; // weak binding already completed
1074 bool imageBeingFixedUpInCache = imageBeingFixedUp->inSharedCache();
1075
1076 if ( context.verboseWeakBind )
1077 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp->getPath());
1078 // for all symbols that need weak binding in this image
1079 ImageLoader::CoalIterator coalIterator;
1080 imageBeingFixedUp->initializeCoalIterator(coalIterator, i, imageIndexes[i]);
1081 while ( !imageBeingFixedUp->incrementCoalIterator(coalIterator) ) {
1082 const char* nameToCoalesce = coalIterator.symbolName;
1083 uintptr_t targetAddr = 0;
1084 const ImageLoader* targetImage;
1085 // Seatch the map for a previous definition to use
1086 auto weakDefIt = context.weakDefMap.find(nameToCoalesce);
1087 if ( (weakDefIt != context.weakDefMap.end()) && (weakDefIt->second.first != nullptr) ) {
1088 // Found a previous defition
1089 targetImage = weakDefIt->second.first;
1090 targetAddr = weakDefIt->second.second;
1091 } else {
1092 // scan all images looking for definition to use
1093 for (int j=0; j < count; ++j) {
1094 const ImageLoader* anImage = imagesNeedingCoalescing[j];
1095 bool anImageInCache = anImage->inSharedCache();
1096 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1097 // already coalesced. Only images outside cache can potentially override something in cache.
1098 if ( anImageInCache && imageBeingFixedUpInCache )
1099 continue;
1100
1101 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1102 const ImageLoader* foundIn;
1103 const Symbol* sym = anImage->findExportedSymbol(nameToCoalesce, false, &foundIn);
1104 if ( sym != NULL ) {
1105 targetAddr = foundIn->getExportedSymbolAddress(sym, context);
1106 targetImage = foundIn;
1107 if ( context.verboseWeakBind )
1108 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce, targetAddr, foundIn->getPath());
1109 break;
1110 }
1111 }
1112 }
1113 if ( (targetAddr != 0) && (coalIterator.image != targetImage) ) {
1114 coalIterator.image->updateUsesCoalIterator(coalIterator, targetAddr, (ImageLoader*)targetImage, 0, context);
1115 if (weakDefIt == context.weakDefMap.end()) {
1116 if (targetImage->neverUnload()) {
1117 // Add never unload defs to the map for next time
1118 context.weakDefMap.insert({ nameToCoalesce, { targetImage, targetAddr } });
1119 if ( context.verboseWeakBind ) {
1120 dyld::log("dyld: weak binding adding %s to map\n", nameToCoalesce);
1121 }
1122 } else {
1123 // Add a placeholder for unloadable symbols which makes us fall back to the regular search
1124 context.weakDefMap.insert({ nameToCoalesce, { targetImage, targetAddr } });
1125 if ( context.verboseWeakBind ) {
1126 dyld::log("dyld: weak binding adding unloadable placeholder %s to map\n", nameToCoalesce);
1127 }
1128 }
1129 }
1130 if ( context.verboseWeakBind )
1131 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce, coalIterator.image->getPath(), targetImage->getPath());
1132 }
1133 }
1134 imageBeingFixedUp->setWeakSymbolsBound(imageIndexes[i]);
1135 }
1136 }
1137 else
1138 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1139 {
1140 // make symbol iterators for each
1141 ImageLoader::CoalIterator iterators[count];
1142 ImageLoader::CoalIterator* sortedIts[count];
1143 for(int i=0; i < count; ++i) {
1144 imagesNeedingCoalescing[i]->initializeCoalIterator(iterators[i], i, imageIndexes[i]);
1145 sortedIts[i] = &iterators[i];
1146 if ( context.verboseWeakBind )
1147 dyld::log("dyld: weak bind load order %d/%d for %s\n", i, count, imagesNeedingCoalescing[i]->getIndexedPath(imageIndexes[i]));
1148 }
1149
1150 // walk all symbols keeping iterators in sync by
1151 // only ever incrementing the iterator with the lowest symbol
1152 int doneCount = 0;
1153 while ( doneCount != count ) {
1154 //for(int i=0; i < count; ++i)
1155 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1156 //dyld::log("\n");
1157 // increment iterator with lowest symbol
1158 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
1159 ++doneCount;
1160 // re-sort iterators
1161 for(int i=1; i < count; ++i) {
1162 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
1163 if ( result == 0 )
1164 sortedIts[i-1]->symbolMatches = true;
1165 if ( result > 0 ) {
1166 // new one is bigger then next, so swap
1167 ImageLoader::CoalIterator* temp = sortedIts[i-1];
1168 sortedIts[i-1] = sortedIts[i];
1169 sortedIts[i] = temp;
1170 }
1171 if ( result < 0 )
1172 break;
1173 }
1174 // process all matching symbols just before incrementing the lowest one that matches
1175 if ( sortedIts[0]->symbolMatches && !sortedIts[0]->done ) {
1176 const char* nameToCoalesce = sortedIts[0]->symbolName;
1177 // pick first symbol in load order (and non-weak overrides weak)
1178 uintptr_t targetAddr = 0;
1179 ImageLoader* targetImage = NULL;
1180 unsigned targetImageIndex = 0;
1181 for(int i=0; i < count; ++i) {
1182 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1183 if ( context.verboseWeakBind )
1184 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce, iterators[i].weakSymbol, iterators[i].image->getIndexedPath((unsigned)iterators[i].imageIndex));
1185 if ( iterators[i].weakSymbol ) {
1186 if ( targetAddr == 0 ) {
1187 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1188 if ( targetAddr != 0 ) {
1189 targetImage = iterators[i].image;
1190 targetImageIndex = (unsigned)iterators[i].imageIndex;
1191 }
1192 }
1193 }
1194 else {
1195 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1196 if ( targetAddr != 0 ) {
1197 targetImage = iterators[i].image;
1198 targetImageIndex = (unsigned)iterators[i].imageIndex;
1199 // strong implementation found, stop searching
1200 break;
1201 }
1202 }
1203 }
1204 }
1205 // tell each to bind to this symbol (unless already bound)
1206 if ( targetAddr != 0 ) {
1207 if ( context.verboseWeakBind ) {
1208 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1209 nameToCoalesce, targetImage->getIndexedShortName(targetImageIndex));
1210 }
1211 for(int i=0; i < count; ++i) {
1212 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1213 if ( context.verboseWeakBind ) {
1214 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1215 nameToCoalesce, iterators[i].image->getIndexedShortName((unsigned)iterators[i].imageIndex),
1216 targetAddr, targetImage->getIndexedShortName(targetImageIndex));
1217 }
1218 if ( ! iterators[i].image->weakSymbolsBound(imageIndexes[i]) )
1219 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, targetImageIndex, context);
1220 iterators[i].symbolMatches = false;
1221 }
1222 }
1223 if (targetImage->neverUnload()) {
1224 // Add never unload defs to the map for next time
1225 context.weakDefMap.insert({ nameToCoalesce, { targetImage, targetAddr } });
1226 if ( context.verboseWeakBind ) {
1227 dyld::log("dyld: weak binding adding %s to map\n",
1228 nameToCoalesce);
1229 }
1230 }
1231 }
1232
1233 }
1234 }
1235
1236 for (int i=0; i < count; ++i) {
1237 if ( imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1238 continue; // skip images already processed
1239
1240 if ( imagesNeedingCoalescing[i]->usesChainedFixups() ) {
1241 // during binding of references to weak-def symbols, the dyld cache was patched
1242 // but if main executable has non-weak override of operator new or delete it needs is handled here
1243 for (const char* weakSymbolName : sTreatAsWeak) {
1244 const ImageLoader* dummy;
1245 imagesNeedingCoalescing[i]->resolveWeak(context, weakSymbolName, true, false, &dummy);
1246 }
1247 }
1248 #if __arm64e__
1249 else {
1250 // support traditional arm64 app on an arm64e device
1251 // look for weak def symbols in this image which may override the cache
1252 ImageLoader::CoalIterator coaler;
1253 imagesNeedingCoalescing[i]->initializeCoalIterator(coaler, i, 0);
1254 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1255 while ( !coaler.done ) {
1256 const ImageLoader* dummy;
1257 // a side effect of resolveWeak() is to patch cache
1258 imagesNeedingCoalescing[i]->resolveWeak(context, coaler.symbolName, true, false, &dummy);
1259 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1260 }
1261 }
1262 #endif
1263 }
1264
1265 // mark all as having all weak symbols bound
1266 for(int i=0; i < count; ++i) {
1267 imagesNeedingCoalescing[i]->setWeakSymbolsBound(imageIndexes[i]);
1268 }
1269 }
1270 }
1271
1272 uint64_t t2 = mach_absolute_time();
1273 fgTotalWeakBindTime += t2 - t1;
1274
1275 if ( context.verboseWeakBind )
1276 dyld::log("dyld: weak bind end\n");
1277 }
1278
1279
1280 void ImageLoader::weakBindOld(const LinkContext& context)
1281 {
1282 if ( context.verboseWeakBind )
1283 dyld::log("dyld: weak bind start:\n");
1284 uint64_t t1 = mach_absolute_time();
1285 // get set of ImageLoaders that participate in coalecsing
1286 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
1287 unsigned imageIndexes[fgImagesRequiringCoalescing];
1288 int count = context.getCoalescedImages(imagesNeedingCoalescing, imageIndexes);
1289
1290 // count how many have not already had weakbinding done
1291 int countNotYetWeakBound = 0;
1292 int countOfImagesWithWeakDefinitionsNotInSharedCache = 0;
1293 for(int i=0; i < count; ++i) {
1294 if ( ! imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1295 ++countNotYetWeakBound;
1296 if ( ! imagesNeedingCoalescing[i]->inSharedCache() )
1297 ++countOfImagesWithWeakDefinitionsNotInSharedCache;
1298 }
1299
1300 // don't need to do any coalescing if only one image has overrides, or all have already been done
1301 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache > 0) && (countNotYetWeakBound > 0) ) {
1302 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1303 // only do alternate algorithm for dlopen(). Use traditional algorithm for launch
1304 if ( !context.linkingMainExecutable ) {
1305 // for all images that need weak binding
1306 for (int i=0; i < count; ++i) {
1307 ImageLoader* imageBeingFixedUp = imagesNeedingCoalescing[i];
1308 if ( imageBeingFixedUp->weakSymbolsBound(imageIndexes[i]) )
1309 continue; // weak binding already completed
1310 bool imageBeingFixedUpInCache = imageBeingFixedUp->inSharedCache();
1311
1312 if ( context.verboseWeakBind )
1313 dyld::log("dyld: checking for weak symbols in %s\n", imageBeingFixedUp->getPath());
1314 // for all symbols that need weak binding in this image
1315 ImageLoader::CoalIterator coalIterator;
1316 imageBeingFixedUp->initializeCoalIterator(coalIterator, i, imageIndexes[i]);
1317 while ( !imageBeingFixedUp->incrementCoalIterator(coalIterator) ) {
1318 const char* nameToCoalesce = coalIterator.symbolName;
1319 uintptr_t targetAddr = 0;
1320 const ImageLoader* targetImage;
1321 // scan all images looking for definition to use
1322 for (int j=0; j < count; ++j) {
1323 const ImageLoader* anImage = imagesNeedingCoalescing[j];
1324 bool anImageInCache = anImage->inSharedCache();
1325 // <rdar://problem/47986398> Don't look at images in dyld cache because cache is
1326 // already coalesced. Only images outside cache can potentially override something in cache.
1327 if ( anImageInCache && imageBeingFixedUpInCache )
1328 continue;
1329
1330 //dyld::log("looking for %s in %s\n", nameToCoalesce, anImage->getPath());
1331 const ImageLoader* foundIn;
1332 const Symbol* sym = anImage->findExportedSymbol(nameToCoalesce, false, &foundIn);
1333 if ( sym != NULL ) {
1334 if ( (foundIn->getExportedSymbolInfo(sym) & ImageLoader::kWeakDefinition) == 0 ) {
1335 // found non-weak def, use it and stop looking
1336 targetAddr = foundIn->getExportedSymbolAddress(sym, context);
1337 targetImage = foundIn;
1338 if ( context.verboseWeakBind )
1339 dyld::log("dyld: found strong %s at 0x%lX in %s\n", nameToCoalesce, targetAddr, foundIn->getPath());
1340 break;
1341 }
1342 else {
1343 // found weak-def, only use if no weak found yet
1344 if ( targetAddr == 0 ) {
1345 targetAddr = foundIn->getExportedSymbolAddress(sym, context);
1346 targetImage = foundIn;
1347 if ( context.verboseWeakBind )
1348 dyld::log("dyld: found weak %s at 0x%lX in %s\n", nameToCoalesce, targetAddr, foundIn->getPath());
1349 }
1350 }
1351 }
1352 }
1353 if ( (targetAddr != 0) && (coalIterator.image != targetImage) ) {
1354 coalIterator.image->updateUsesCoalIterator(coalIterator, targetAddr, (ImageLoader*)targetImage, 0, context);
1355 if ( context.verboseWeakBind )
1356 dyld::log("dyld: adjusting uses of %s in %s to use definition from %s\n", nameToCoalesce, coalIterator.image->getPath(), targetImage->getPath());
1357 }
1358 }
1359 imageBeingFixedUp->setWeakSymbolsBound(imageIndexes[i]);
1360 }
1361 }
1362 else
1363 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
1364 {
1365 // make symbol iterators for each
1366 ImageLoader::CoalIterator iterators[count];
1367 ImageLoader::CoalIterator* sortedIts[count];
1368 for(int i=0; i < count; ++i) {
1369 imagesNeedingCoalescing[i]->initializeCoalIterator(iterators[i], i, imageIndexes[i]);
1370 sortedIts[i] = &iterators[i];
1371 if ( context.verboseWeakBind )
1372 dyld::log("dyld: weak bind load order %d/%d for %s\n", i, count, imagesNeedingCoalescing[i]->getIndexedPath(imageIndexes[i]));
1373 }
1374
1375 // walk all symbols keeping iterators in sync by
1376 // only ever incrementing the iterator with the lowest symbol
1377 int doneCount = 0;
1378 while ( doneCount != count ) {
1379 //for(int i=0; i < count; ++i)
1380 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
1381 //dyld::log("\n");
1382 // increment iterator with lowest symbol
1383 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
1384 ++doneCount;
1385 // re-sort iterators
1386 for(int i=1; i < count; ++i) {
1387 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
1388 if ( result == 0 )
1389 sortedIts[i-1]->symbolMatches = true;
1390 if ( result > 0 ) {
1391 // new one is bigger then next, so swap
1392 ImageLoader::CoalIterator* temp = sortedIts[i-1];
1393 sortedIts[i-1] = sortedIts[i];
1394 sortedIts[i] = temp;
1395 }
1396 if ( result < 0 )
1397 break;
1398 }
1399 // process all matching symbols just before incrementing the lowest one that matches
1400 if ( sortedIts[0]->symbolMatches && !sortedIts[0]->done ) {
1401 const char* nameToCoalesce = sortedIts[0]->symbolName;
1402 // pick first symbol in load order (and non-weak overrides weak)
1403 uintptr_t targetAddr = 0;
1404 ImageLoader* targetImage = NULL;
1405 unsigned targetImageIndex = 0;
1406 for(int i=0; i < count; ++i) {
1407 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1408 if ( context.verboseWeakBind )
1409 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce, iterators[i].weakSymbol, iterators[i].image->getIndexedPath((unsigned)iterators[i].imageIndex));
1410 if ( iterators[i].weakSymbol ) {
1411 if ( targetAddr == 0 ) {
1412 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1413 if ( targetAddr != 0 ) {
1414 targetImage = iterators[i].image;
1415 targetImageIndex = (unsigned)iterators[i].imageIndex;
1416 }
1417 }
1418 }
1419 else {
1420 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1421 if ( targetAddr != 0 ) {
1422 targetImage = iterators[i].image;
1423 targetImageIndex = (unsigned)iterators[i].imageIndex;
1424 // strong implementation found, stop searching
1425 break;
1426 }
1427 }
1428 }
1429 }
1430 // tell each to bind to this symbol (unless already bound)
1431 if ( targetAddr != 0 ) {
1432 if ( context.verboseWeakBind ) {
1433 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1434 nameToCoalesce, targetImage->getIndexedShortName(targetImageIndex));
1435 }
1436 for(int i=0; i < count; ++i) {
1437 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1438 if ( context.verboseWeakBind ) {
1439 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1440 nameToCoalesce, iterators[i].image->getIndexedShortName((unsigned)iterators[i].imageIndex),
1441 targetAddr, targetImage->getIndexedShortName(targetImageIndex));
1442 }
1443 if ( ! iterators[i].image->weakSymbolsBound(imageIndexes[i]) )
1444 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, targetImageIndex, context);
1445 iterators[i].symbolMatches = false;
1446 }
1447 }
1448 }
1449
1450 }
1451 }
1452
1453 for (int i=0; i < count; ++i) {
1454 if ( imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
1455 continue; // skip images already processed
1456
1457 if ( imagesNeedingCoalescing[i]->usesChainedFixups() ) {
1458 // during binding of references to weak-def symbols, the dyld cache was patched
1459 // but if main executable has non-weak override of operator new or delete it needs is handled here
1460 for (const char* weakSymbolName : sTreatAsWeak) {
1461 const ImageLoader* dummy;
1462 imagesNeedingCoalescing[i]->resolveWeak(context, weakSymbolName, true, false, &dummy);
1463 }
1464 }
1465 #if __arm64e__
1466 else {
1467 // support traditional arm64 app on an arm64e device
1468 // look for weak def symbols in this image which may override the cache
1469 ImageLoader::CoalIterator coaler;
1470 imagesNeedingCoalescing[i]->initializeCoalIterator(coaler, i, 0);
1471 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1472 while ( !coaler.done ) {
1473 const ImageLoader* dummy;
1474 // a side effect of resolveWeak() is to patch cache
1475 imagesNeedingCoalescing[i]->resolveWeak(context, coaler.symbolName, true, false, &dummy);
1476 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1477 }
1478 }
1479 #endif
1480 }
1481
1482 // mark all as having all weak symbols bound
1483 for(int i=0; i < count; ++i) {
1484 imagesNeedingCoalescing[i]->setWeakSymbolsBound(imageIndexes[i]);
1485 }
1486 }
1487 }
1488
1489 uint64_t t2 = mach_absolute_time();
1490 fgTotalWeakBindTime += t2 - t1;
1491
1492 if ( context.verboseWeakBind )
1493 dyld::log("dyld: weak bind end\n");
1494 }
1495
1496
1497
1498 void ImageLoader::recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs)
1499 {
1500 if ( ! fRegisteredDOF ) {
1501 // break cycles
1502 fRegisteredDOF = true;
1503
1504 // gather lower level libraries first
1505 for(unsigned int i=0; i < libraryCount(); ++i) {
1506 ImageLoader* dependentImage = libImage(i);
1507 if ( dependentImage != NULL )
1508 dependentImage->recursiveGetDOFSections(context, dofs);
1509 }
1510 this->doGetDOFSections(context, dofs);
1511 }
1512 }
1513
1514 void ImageLoader::setNeverUnloadRecursive() {
1515 if ( ! fNeverUnload ) {
1516 // break cycles
1517 fNeverUnload = true;
1518
1519 // gather lower level libraries first
1520 for(unsigned int i=0; i < libraryCount(); ++i) {
1521 ImageLoader* dependentImage = libImage(i);
1522 if ( dependentImage != NULL )
1523 dependentImage->setNeverUnloadRecursive();
1524 }
1525 }
1526 }
1527
1528 void ImageLoader::recursiveSpinLock(recursive_lock& rlock)
1529 {
1530 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1531 // keep trying until success (spin)
1532 #pragma clang diagnostic push
1533 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1534 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL, &rlock, (void**)&fInitializerRecursiveLock) ) {
1535 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1536 // the same thread we are on, the increment the lock count, otherwise continue to spin
1537 if ( (fInitializerRecursiveLock != NULL) && (fInitializerRecursiveLock->thread == rlock.thread) )
1538 break;
1539 }
1540 #pragma clang diagnostic pop
1541 ++(fInitializerRecursiveLock->count);
1542 }
1543
1544 void ImageLoader::recursiveSpinUnLock()
1545 {
1546 if ( --(fInitializerRecursiveLock->count) == 0 )
1547 fInitializerRecursiveLock = NULL;
1548 }
1549
1550 void ImageLoader::InitializerTimingList::addTime(const char* name, uint64_t time)
1551 {
1552 for (int i=0; i < count; ++i) {
1553 if ( strcmp(images[i].shortName, name) == 0 ) {
1554 images[i].initTime += time;
1555 return;
1556 }
1557 }
1558 images[count].initTime = time;
1559 images[count].shortName = name;
1560 ++count;
1561 }
1562
1563 void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread, const char* pathToInitialize,
1564 InitializerTimingList& timingInfo, UninitedUpwards& uninitUps)
1565 {
1566 recursive_lock lock_info(this_thread);
1567 recursiveSpinLock(lock_info);
1568
1569 if ( fState < dyld_image_state_dependents_initialized-1 ) {
1570 uint8_t oldState = fState;
1571 // break cycles
1572 fState = dyld_image_state_dependents_initialized-1;
1573 try {
1574 // initialize lower level libraries first
1575 for(unsigned int i=0; i < libraryCount(); ++i) {
1576 ImageLoader* dependentImage = libImage(i);
1577 if ( dependentImage != NULL ) {
1578 // don't try to initialize stuff "above" me yet
1579 if ( libIsUpward(i) ) {
1580 uninitUps.imagesAndPaths[uninitUps.count] = { dependentImage, libPath(i) };
1581 uninitUps.count++;
1582 }
1583 else if ( dependentImage->fDepth >= fDepth ) {
1584 dependentImage->recursiveInitialization(context, this_thread, libPath(i), timingInfo, uninitUps);
1585 }
1586 }
1587 }
1588
1589 // record termination order
1590 if ( this->needsTermination() )
1591 context.terminationRecorder(this);
1592
1593 // let objc know we are about to initialize this image
1594 uint64_t t1 = mach_absolute_time();
1595 fState = dyld_image_state_dependents_initialized;
1596 oldState = fState;
1597 context.notifySingle(dyld_image_state_dependents_initialized, this, &timingInfo);
1598
1599 // initialize this image
1600 bool hasInitializers = this->doInitialization(context);
1601
1602 // let anyone know we finished initializing this image
1603 fState = dyld_image_state_initialized;
1604 oldState = fState;
1605 context.notifySingle(dyld_image_state_initialized, this, NULL);
1606
1607 if ( hasInitializers ) {
1608 uint64_t t2 = mach_absolute_time();
1609 timingInfo.addTime(this->getShortName(), t2-t1);
1610 }
1611 }
1612 catch (const char* msg) {
1613 // this image is not initialized
1614 fState = oldState;
1615 recursiveSpinUnLock();
1616 throw;
1617 }
1618 }
1619
1620 recursiveSpinUnLock();
1621 }
1622
1623
1624 static void printTime(const char* msg, uint64_t partTime, uint64_t totalTime)
1625 {
1626 static uint64_t sUnitsPerSecond = 0;
1627 if ( sUnitsPerSecond == 0 ) {
1628 struct mach_timebase_info timeBaseInfo;
1629 if ( mach_timebase_info(&timeBaseInfo) != KERN_SUCCESS )
1630 return;
1631 sUnitsPerSecond = 1000000000ULL * timeBaseInfo.denom / timeBaseInfo.numer;
1632 }
1633 if ( partTime < sUnitsPerSecond ) {
1634 uint32_t milliSecondsTimesHundred = (uint32_t)((partTime*100000)/sUnitsPerSecond);
1635 uint32_t milliSeconds = (uint32_t)(milliSecondsTimesHundred/100);
1636 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1637 uint32_t percent = percentTimesTen/10;
1638 if ( milliSeconds >= 100 )
1639 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1640 else if ( milliSeconds >= 10 )
1641 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1642 else
1643 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1644 }
1645 else {
1646 uint32_t secondsTimeTen = (uint32_t)((partTime*10)/sUnitsPerSecond);
1647 uint32_t seconds = secondsTimeTen/10;
1648 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1649 uint32_t percent = percentTimesTen/10;
1650 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg, seconds, secondsTimeTen-seconds*10, percent, percentTimesTen-percent*10);
1651 }
1652 }
1653
1654 static char* commatize(uint64_t in, char* out)
1655 {
1656 uint64_t div10 = in / 10;
1657 uint8_t delta = in - div10*10;
1658 char* s = &out[32];
1659 int digitCount = 1;
1660 *s = '\0';
1661 *(--s) = '0' + delta;
1662 in = div10;
1663 while ( in != 0 ) {
1664 if ( (digitCount % 3) == 0 )
1665 *(--s) = ',';
1666 div10 = in / 10;
1667 delta = in - div10*10;
1668 *(--s) = '0' + delta;
1669 in = div10;
1670 ++digitCount;
1671 }
1672 return s;
1673 }
1674
1675
1676 void ImageLoader::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
1677 {
1678 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1679
1680 uint64_t totalDyldTime = totalTime - fgTotalDebuggerPausedTime - fgTotalRebindCacheTime;
1681 printTime("Total pre-main time", totalDyldTime, totalDyldTime);
1682 printTime(" dylib loading time", fgTotalLoadLibrariesTime-fgTotalDebuggerPausedTime, totalDyldTime);
1683 printTime(" rebase/binding time", fgTotalRebaseTime+fgTotalBindTime+fgTotalWeakBindTime-fgTotalRebindCacheTime, totalDyldTime);
1684 printTime(" ObjC setup time", fgTotalObjCSetupTime, totalDyldTime);
1685 printTime(" initializer time", fgTotalInitTime-fgTotalObjCSetupTime, totalDyldTime);
1686 dyld::log(" slowest intializers :\n");
1687 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1688 uint64_t t = timingInfo.images[i].initTime;
1689 if ( t*50 < totalDyldTime )
1690 continue;
1691 dyld::log("%30s ", timingInfo.images[i].shortName);
1692 if ( strncmp(timingInfo.images[i].shortName, "libSystem.", 10) == 0 )
1693 t -= fgTotalObjCSetupTime;
1694 printTime("", t, totalDyldTime);
1695 }
1696 dyld::log("\n");
1697 }
1698
1699 void ImageLoader::printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo)
1700 {
1701 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1702 char commaNum1[40];
1703 char commaNum2[40];
1704
1705 printTime(" total time", totalTime, totalTime);
1706 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
1707 dyld::log(" total segments mapped: %u, into %llu pages\n", fgTotalSegmentsMapped, fgTotalBytesMapped/4096);
1708 printTime(" total images loading time", fgTotalLoadLibrariesTime, totalTime);
1709 printTime(" total load time in ObjC", fgTotalObjCSetupTime, totalTime);
1710 printTime(" total debugger pause time", fgTotalDebuggerPausedTime, totalTime);
1711 printTime(" total dtrace DOF registration time", fgTotalDOF, totalTime);
1712 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups, commaNum1));
1713 printTime(" total rebase fixups time", fgTotalRebaseTime, totalTime);
1714 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups, commaNum1));
1715 if ( fgTotalBindSymbolsResolved != 0 ) {
1716 uint32_t avgTimesTen = (fgTotalBindImageSearches * 10) / fgTotalBindSymbolsResolved;
1717 uint32_t avgInt = fgTotalBindImageSearches / fgTotalBindSymbolsResolved;
1718 uint32_t avgTenths = avgTimesTen - (avgInt*10);
1719 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1720 commatize(fgTotalBindSymbolsResolved, commaNum1), avgInt, avgTenths);
1721 }
1722 printTime(" total binding fixups time", fgTotalBindTime, totalTime);
1723 printTime(" total weak binding fixups time", fgTotalWeakBindTime, totalTime);
1724 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime, totalTime);
1725 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups, commaNum1), commatize(fgTotalPossibleLazyBindFixups, commaNum2));
1726 printTime(" total time in initializers and ObjC +load", fgTotalInitTime-fgTotalObjCSetupTime, totalTime);
1727 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1728 uint64_t t = timingInfo.images[i].initTime;
1729 if ( t*1000 < totalTime )
1730 continue;
1731 dyld::log("%42s ", timingInfo.images[i].shortName);
1732 if ( strncmp(timingInfo.images[i].shortName, "libSystem.", 10) == 0 )
1733 t -= fgTotalObjCSetupTime;
1734 printTime("", t, totalTime);
1735 }
1736
1737 }
1738
1739
1740 //
1741 // copy path and add suffix to result
1742 //
1743 // /path/foo.dylib _debug => /path/foo_debug.dylib
1744 // foo.dylib _debug => foo_debug.dylib
1745 // foo _debug => foo_debug
1746 // /path/bar _debug => /path/bar_debug
1747 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1748 //
1749 void ImageLoader::addSuffix(const char* path, const char* suffix, char* result)
1750 {
1751 strcpy(result, path);
1752
1753 char* start = strrchr(result, '/');
1754 if ( start != NULL )
1755 start++;
1756 else
1757 start = result;
1758
1759 char* dot = strrchr(start, '.');
1760 if ( dot != NULL ) {
1761 strcpy(dot, suffix);
1762 strcat(&dot[strlen(suffix)], &path[dot-result]);
1763 }
1764 else {
1765 strcat(result, suffix);
1766 }
1767 }
1768
1769
1770 //
1771 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1772 // to enable it to be re-written in assembler if needed.
1773 //
1774 const uint8_t* ImageLoader::trieWalk(const uint8_t* start, const uint8_t* end, const char* s)
1775 {
1776 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1777 ++fgSymbolTrieSearchs;
1778 const uint8_t* p = start;
1779 while ( p != NULL ) {
1780 uintptr_t terminalSize = *p++;
1781 if ( terminalSize > 127 ) {
1782 // except for re-export-with-rename, all terminal sizes fit in one byte
1783 --p;
1784 terminalSize = read_uleb128(p, end);
1785 }
1786 if ( (*s == '\0') && (terminalSize != 0) ) {
1787 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1788 return p;
1789 }
1790 const uint8_t* children = p + terminalSize;
1791 if ( children > end ) {
1792 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize);
1793 return NULL;
1794 }
1795 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1796 uint8_t childrenRemaining = *children++;
1797 p = children;
1798 uintptr_t nodeOffset = 0;
1799 for (; childrenRemaining > 0; --childrenRemaining) {
1800 const char* ss = s;
1801 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1802 bool wrongEdge = false;
1803 // scan whole edge to get to next edge
1804 // if edge is longer than target symbol name, don't read past end of symbol name
1805 char c = *p;
1806 while ( c != '\0' ) {
1807 if ( !wrongEdge ) {
1808 if ( c != *ss )
1809 wrongEdge = true;
1810 ++ss;
1811 }
1812 ++p;
1813 c = *p;
1814 }
1815 if ( wrongEdge ) {
1816 // advance to next child
1817 ++p; // skip over zero terminator
1818 // skip over uleb128 until last byte is found
1819 while ( (*p & 0x80) != 0 )
1820 ++p;
1821 ++p; // skip over last byte of uleb128
1822 if ( p > end ) {
1823 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1824 return NULL;
1825 }
1826 }
1827 else {
1828 // the symbol so far matches this edge (child)
1829 // so advance to the child's node
1830 ++p;
1831 nodeOffset = read_uleb128(p, end);
1832 if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) {
1833 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset);
1834 return NULL;
1835 }
1836 s = ss;
1837 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1838 break;
1839 }
1840 }
1841 if ( nodeOffset != 0 )
1842 p = &start[nodeOffset];
1843 else
1844 p = NULL;
1845 }
1846 //dyld::log("trieWalk(%p) return NULL\n", start);
1847 return NULL;
1848 }
1849
1850
1851
1852 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p, const uint8_t* end)
1853 {
1854 uint64_t result = 0;
1855 int bit = 0;
1856 do {
1857 if (p == end)
1858 dyld::throwf("malformed uleb128");
1859
1860 uint64_t slice = *p & 0x7f;
1861
1862 if (bit > 63)
1863 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit, result);
1864 else {
1865 result |= (slice << bit);
1866 bit += 7;
1867 }
1868 } while (*p++ & 0x80);
1869 return (uintptr_t)result;
1870 }
1871
1872
1873 intptr_t ImageLoader::read_sleb128(const uint8_t*& p, const uint8_t* end)
1874 {
1875 int64_t result = 0;
1876 int bit = 0;
1877 uint8_t byte;
1878 do {
1879 if (p == end)
1880 throw "malformed sleb128";
1881 byte = *p++;
1882 result |= (((int64_t)(byte & 0x7f)) << bit);
1883 bit += 7;
1884 } while (byte & 0x80);
1885 // sign extend negative numbers
1886 if ( (byte & 0x40) != 0 )
1887 result |= (~0ULL) << bit;
1888 return (intptr_t)result;
1889 }
1890
1891
1892 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple);
1893 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair);
1894
1895
1896