]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoader.cpp
dyld-625.13.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
40 #include "Tracing.h"
41
42 #include "ImageLoader.h"
43
44
45 uint32_t ImageLoader::fgImagesUsedFromSharedCache = 0;
46 uint32_t ImageLoader::fgImagesWithUsedPrebinding = 0;
47 uint32_t ImageLoader::fgImagesRequiringCoalescing = 0;
48 uint32_t ImageLoader::fgImagesHasWeakDefinitions = 0;
49 uint32_t ImageLoader::fgTotalRebaseFixups = 0;
50 uint32_t ImageLoader::fgTotalBindFixups = 0;
51 uint32_t ImageLoader::fgTotalBindSymbolsResolved = 0;
52 uint32_t ImageLoader::fgTotalBindImageSearches = 0;
53 uint32_t ImageLoader::fgTotalLazyBindFixups = 0;
54 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups = 0;
55 uint32_t ImageLoader::fgTotalSegmentsMapped = 0;
56 uint64_t ImageLoader::fgTotalBytesMapped = 0;
57 uint64_t ImageLoader::fgTotalBytesPreFetched = 0;
58 uint64_t ImageLoader::fgTotalLoadLibrariesTime;
59 uint64_t ImageLoader::fgTotalObjCSetupTime = 0;
60 uint64_t ImageLoader::fgTotalDebuggerPausedTime = 0;
61 uint64_t ImageLoader::fgTotalRebindCacheTime = 0;
62 uint64_t ImageLoader::fgTotalRebaseTime;
63 uint64_t ImageLoader::fgTotalBindTime;
64 uint64_t ImageLoader::fgTotalWeakBindTime;
65 uint64_t ImageLoader::fgTotalDOF;
66 uint64_t ImageLoader::fgTotalInitTime;
67 uint16_t ImageLoader::fgLoadOrdinal = 0;
68 uint32_t ImageLoader::fgSymbolTrieSearchs = 0;
69 std::vector<ImageLoader::InterposeTuple>ImageLoader::fgInterposingTuples;
70 uintptr_t ImageLoader::fgNextPIEDylibAddress = 0;
71
72
73
74 ImageLoader::ImageLoader(const char* path, unsigned int libCount)
75 : fPath(path), fRealPath(NULL), fDevice(0), fInode(0), fLastModified(0),
76 fPathHash(0), fDlopenReferenceCount(0), fInitializerRecursiveLock(NULL),
77 fDepth(0), fLoadOrder(fgLoadOrdinal++), fState(0), fLibraryCount(libCount),
78 fAllLibraryChecksumsAndLoadAddressesMatch(false), fLeaveMapped(false), fNeverUnload(false),
79 fHideSymbols(false), fMatchByInstallName(false),
80 fInterposed(false), fRegisteredDOF(false), fAllLazyPointersBound(false),
81 fBeingRemoved(false), fAddFuncNotified(false),
82 fPathOwnedByImage(false), fIsReferencedDownward(false),
83 fWeakSymbolsBound(false)
84 {
85 if ( fPath != NULL )
86 fPathHash = hash(fPath);
87 if ( libCount > 512 )
88 dyld::throwf("too many dependent dylibs in %s", path);
89 }
90
91
92 void ImageLoader::deleteImage(ImageLoader* image)
93 {
94 delete image;
95 }
96
97
98 ImageLoader::~ImageLoader()
99 {
100 if ( fRealPath != NULL )
101 delete [] fRealPath;
102 if ( fPathOwnedByImage && (fPath != NULL) )
103 delete [] fPath;
104 }
105
106 void ImageLoader::setFileInfo(dev_t device, ino_t inode, time_t modDate)
107 {
108 fDevice = device;
109 fInode = inode;
110 fLastModified = modDate;
111 }
112
113 void ImageLoader::setMapped(const LinkContext& context)
114 {
115 fState = dyld_image_state_mapped;
116 context.notifySingle(dyld_image_state_mapped, this, NULL); // note: can throw exception
117 }
118
119 int ImageLoader::compare(const ImageLoader* right) const
120 {
121 if ( this->fDepth == right->fDepth ) {
122 if ( this->fLoadOrder == right->fLoadOrder )
123 return 0;
124 else if ( this->fLoadOrder < right->fLoadOrder )
125 return -1;
126 else
127 return 1;
128 }
129 else {
130 if ( this->fDepth < right->fDepth )
131 return -1;
132 else
133 return 1;
134 }
135 }
136
137 void ImageLoader::setPath(const char* path)
138 {
139 if ( fPathOwnedByImage && (fPath != NULL) )
140 delete [] fPath;
141 fPath = new char[strlen(path)+1];
142 strcpy((char*)fPath, path);
143 fPathOwnedByImage = true; // delete fPath when this image is destructed
144 fPathHash = hash(fPath);
145 fRealPath = NULL;
146 }
147
148 void ImageLoader::setPathUnowned(const char* path)
149 {
150 if ( fPathOwnedByImage && (fPath != NULL) ) {
151 delete [] fPath;
152 }
153 fPath = path;
154 fPathOwnedByImage = false;
155 fPathHash = hash(fPath);
156 }
157
158 void ImageLoader::setPaths(const char* path, const char* realPath)
159 {
160 this->setPath(path);
161 fRealPath = new char[strlen(realPath)+1];
162 strcpy((char*)fRealPath, realPath);
163 }
164
165 const char* ImageLoader::getRealPath() const
166 {
167 if ( fRealPath != NULL )
168 return fRealPath;
169 else
170 return fPath;
171 }
172
173
174 uint32_t ImageLoader::hash(const char* path)
175 {
176 // this does not need to be a great hash
177 // it is just used to reduce the number of strcmp() calls
178 // of existing images when loading a new image
179 uint32_t h = 0;
180 for (const char* s=path; *s != '\0'; ++s)
181 h = h*5 + *s;
182 return h;
183 }
184
185 bool ImageLoader::matchInstallPath() const
186 {
187 return fMatchByInstallName;
188 }
189
190 void ImageLoader::setMatchInstallPath(bool match)
191 {
192 fMatchByInstallName = match;
193 }
194
195 bool ImageLoader::statMatch(const struct stat& stat_buf) const
196 {
197 return ( (this->fDevice == stat_buf.st_dev) && (this->fInode == stat_buf.st_ino) );
198 }
199
200 const char* ImageLoader::shortName(const char* fullName)
201 {
202 // try to return leaf name
203 if ( fullName != NULL ) {
204 const char* s = strrchr(fullName, '/');
205 if ( s != NULL )
206 return &s[1];
207 }
208 return fullName;
209 }
210
211 const char* ImageLoader::getShortName() const
212 {
213 return shortName(fPath);
214 }
215
216 void ImageLoader::setLeaveMapped()
217 {
218 fLeaveMapped = true;
219 }
220
221 void ImageLoader::setHideExports(bool hide)
222 {
223 fHideSymbols = hide;
224 }
225
226 bool ImageLoader::hasHiddenExports() const
227 {
228 return fHideSymbols;
229 }
230
231 bool ImageLoader::isLinked() const
232 {
233 return (fState >= dyld_image_state_bound);
234 }
235
236 time_t ImageLoader::lastModified() const
237 {
238 return fLastModified;
239 }
240
241 bool ImageLoader::containsAddress(const void* addr) const
242 {
243 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
244 const uint8_t* start = (const uint8_t*)segActualLoadAddress(i);
245 const uint8_t* end = (const uint8_t*)segActualEndAddress(i);
246 if ( (start <= addr) && (addr < end) && !segUnaccessible(i) )
247 return true;
248 }
249 return false;
250 }
251
252 bool ImageLoader::overlapsWithAddressRange(const void* start, const void* end) const
253 {
254 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
255 const uint8_t* segStart = (const uint8_t*)segActualLoadAddress(i);
256 const uint8_t* segEnd = (const uint8_t*)segActualEndAddress(i);
257 if ( strcmp(segName(i), "__UNIXSTACK") == 0 ) {
258 // __UNIXSTACK never slides. This is the only place that cares
259 // and checking for that segment name in segActualLoadAddress()
260 // is too expensive.
261 segStart -= getSlide();
262 segEnd -= getSlide();
263 }
264 if ( (start <= segStart) && (segStart < end) )
265 return true;
266 if ( (start <= segEnd) && (segEnd < end) )
267 return true;
268 if ( (segStart < start) && (end < segEnd) )
269 return true;
270 }
271 return false;
272 }
273
274 void ImageLoader::getMappedRegions(MappedRegion*& regions) const
275 {
276 for(unsigned int i=0, e=segmentCount(); i < e; ++i) {
277 MappedRegion region;
278 region.address = segActualLoadAddress(i);
279 region.size = segSize(i);
280 *regions++ = region;
281 }
282 }
283
284
285
286 bool ImageLoader::dependsOn(ImageLoader* image) {
287 for(unsigned int i=0; i < libraryCount(); ++i) {
288 if ( libImage(i) == image )
289 return true;
290 }
291 return false;
292 }
293
294
295 static bool notInImgageList(const ImageLoader* image, const ImageLoader** dsiStart, const ImageLoader** dsiCur)
296 {
297 for (const ImageLoader** p = dsiStart; p < dsiCur; ++p)
298 if ( *p == image )
299 return false;
300 return true;
301 }
302
303 bool ImageLoader::findExportedSymbolAddress(const LinkContext& context, const char* symbolName,
304 const ImageLoader* requestorImage, int requestorOrdinalOfDef,
305 bool runResolver, const ImageLoader** foundIn, uintptr_t* address) const
306 {
307 const Symbol* sym = this->findExportedSymbol(symbolName, true, foundIn);
308 if ( sym != NULL ) {
309 *address = (*foundIn)->getExportedSymbolAddress(sym, context, requestorImage, runResolver);
310 return true;
311 }
312 return false;
313 }
314
315
316 // private method that handles circular dependencies by only search any image once
317 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name,
318 const ImageLoader** dsiStart, const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const
319 {
320 const ImageLoader::Symbol* sym;
321 // search self
322 if ( notInImgageList(this, dsiStart, dsiCur) ) {
323 sym = this->findExportedSymbol(name, false, this->getPath(), foundIn);
324 if ( sym != NULL )
325 return sym;
326 *dsiCur++ = this;
327 }
328
329 // search directly dependent libraries
330 for(unsigned int i=0; i < libraryCount(); ++i) {
331 ImageLoader* dependentImage = libImage(i);
332 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
333 sym = dependentImage->findExportedSymbol(name, false, libPath(i), foundIn);
334 if ( sym != NULL )
335 return sym;
336 }
337 }
338
339 // search indirectly dependent libraries
340 for(unsigned int i=0; i < libraryCount(); ++i) {
341 ImageLoader* dependentImage = libImage(i);
342 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
343 *dsiCur++ = dependentImage;
344 sym = dependentImage->findExportedSymbolInDependentImagesExcept(name, dsiStart, dsiCur, dsiEnd, foundIn);
345 if ( sym != NULL )
346 return sym;
347 }
348 }
349
350 return NULL;
351 }
352
353
354 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
355 {
356 unsigned int imageCount = context.imageCount()+2;
357 const ImageLoader* dontSearchImages[imageCount];
358 dontSearchImages[0] = this; // don't search this image
359 const ImageLoader** cur = &dontSearchImages[1];
360 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
361 }
362
363 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
364 {
365 unsigned int imageCount = context.imageCount()+2;
366 const ImageLoader* dontSearchImages[imageCount];
367 const ImageLoader** cur = &dontSearchImages[0];
368 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
369 }
370
371 // this is called by initializeMainExecutable() to interpose on the initial set of images
372 void ImageLoader::applyInterposing(const LinkContext& context)
373 {
374 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_APPLY_INTERPOSING, 0, 0, 0);
375 if ( fgInterposingTuples.size() != 0 )
376 this->recursiveApplyInterposing(context);
377 }
378
379
380 uintptr_t ImageLoader::interposedAddress(const LinkContext& context, uintptr_t address, const ImageLoader* inImage, const ImageLoader* onlyInImage)
381 {
382 //dyld::log("interposedAddress(0x%08llX), tupleCount=%lu\n", (uint64_t)address, fgInterposingTuples.size());
383 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
384 //dyld::log(" interposedAddress: replacee=0x%08llX, replacement=0x%08llX, neverImage=%p, onlyImage=%p, inImage=%p\n",
385 // (uint64_t)it->replacee, (uint64_t)it->replacement, it->neverImage, it->onlyImage, inImage);
386 // replace all references to 'replacee' with 'replacement'
387 if ( (address == it->replacee) && (inImage != it->neverImage) && ((it->onlyImage == NULL) || (inImage == it->onlyImage)) ) {
388 if ( context.verboseInterposing ) {
389 dyld::log("dyld interposing: replace 0x%lX with 0x%lX\n", it->replacee, it->replacement);
390 }
391 return it->replacement;
392 }
393 }
394 return address;
395 }
396
397 void ImageLoader::applyInterposingToDyldCache(const LinkContext& context) {
398 #if USES_CHAINED_BINDS
399 if (!context.dyldCache)
400 return;
401 if (fgInterposingTuples.empty())
402 return;
403 // For each of the interposed addresses, see if any of them are in the shared cache. If so, find
404 // that image and apply its patch table to all uses.
405 uintptr_t cacheStart = (uintptr_t)context.dyldCache;
406 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
407 if ( context.verboseInterposing )
408 dyld::log("dyld: interpose: Trying to interpose address 0x%08llx\n", (uint64_t)it->replacee);
409 uint32_t imageIndex;
410 uint32_t cacheOffsetOfReplacee = (uint32_t)(it->replacee - cacheStart);
411 if (!context.dyldCache->addressInText(cacheOffsetOfReplacee, &imageIndex))
412 continue;
413 dyld3::closure::ImageNum imageInCache = imageIndex+1;
414 if ( context.verboseInterposing )
415 dyld::log("dyld: interpose: Found shared cache image %d for 0x%08llx\n", imageInCache, (uint64_t)it->replacee);
416 const dyld3::closure::Image* image = context.dyldCache->cachedDylibsImageArray()->imageForNum(imageInCache);
417 image->forEachPatchableExport(^(uint32_t cacheOffsetOfImpl, const char* exportName) {
418 // Skip patching anything other than this symbol
419 if (cacheOffsetOfImpl != cacheOffsetOfReplacee)
420 return;
421 if ( context.verboseInterposing )
422 dyld::log("dyld: interpose: Patching uses of symbol %s in shared cache binary at %s\n", exportName, image->path());
423 uintptr_t newLoc = it->replacement;
424 image->forEachPatchableUseOfExport(cacheOffsetOfImpl, ^(dyld3::closure::Image::PatchableExport::PatchLocation patchLocation) {
425 uintptr_t* loc = (uintptr_t*)(cacheStart+patchLocation.cacheOffset);
426 #if __has_feature(ptrauth_calls)
427 if ( patchLocation.authenticated ) {
428 dyld3::MachOLoaded::ChainedFixupPointerOnDisk fixupInfo;
429 fixupInfo.authRebase.auth = true;
430 fixupInfo.authRebase.addrDiv = patchLocation.usesAddressDiversity;
431 fixupInfo.authRebase.diversity = patchLocation.discriminator;
432 fixupInfo.authRebase.key = patchLocation.key;
433 *loc = fixupInfo.signPointer(loc, newLoc + patchLocation.getAddend());
434 if ( context.verboseInterposing )
435 dyld::log("dyld: interpose: *%p = %p (JOP: diversity 0x%04X, addr-div=%d, key=%s)\n",
436 loc, (void*)*loc, patchLocation.discriminator, patchLocation.usesAddressDiversity, patchLocation.keyName());
437 return;
438 }
439 #endif
440 if ( context.verboseInterposing )
441 dyld::log("dyld: interpose: *%p = 0x%0llX (dyld cache patch) to %s\n", loc, newLoc + patchLocation.getAddend(), exportName);
442 *loc = newLoc + patchLocation.getAddend();
443 });
444 });
445 }
446 #endif
447 }
448
449 void ImageLoader::addDynamicInterposingTuples(const struct dyld_interpose_tuple array[], size_t count)
450 {
451 for(size_t i=0; i < count; ++i) {
452 ImageLoader::InterposeTuple tuple;
453 tuple.replacement = (uintptr_t)array[i].replacement;
454 tuple.neverImage = NULL;
455 tuple.onlyImage = this;
456 tuple.replacee = (uintptr_t)array[i].replacee;
457 // chain to any existing interpositions
458 for (std::vector<InterposeTuple>::iterator it=fgInterposingTuples.begin(); it != fgInterposingTuples.end(); it++) {
459 if ( (it->replacee == tuple.replacee) && (it->onlyImage == this) ) {
460 tuple.replacee = it->replacement;
461 }
462 }
463 ImageLoader::fgInterposingTuples.push_back(tuple);
464 }
465 }
466
467 // <rdar://problem/29099600> dyld should tell the kernel when it is doing root fix-ups
468 void ImageLoader::vmAccountingSetSuspended(const LinkContext& context, bool suspend)
469 {
470 #if __arm__ || __arm64__
471 static bool sVmAccountingSuspended = false;
472 if ( suspend == sVmAccountingSuspended )
473 return;
474 if ( context.verboseBind )
475 dyld::log("set vm.footprint_suspend=%d\n", suspend);
476 int newValue = suspend ? 1 : 0;
477 int oldValue = 0;
478 size_t newlen = sizeof(newValue);
479 size_t oldlen = sizeof(oldValue);
480 int ret = sysctlbyname("vm.footprint_suspend", &oldValue, &oldlen, &newValue, newlen);
481 if ( context.verboseBind && (ret != 0) )
482 dyld::log("vm.footprint_suspend => %d, errno=%d\n", ret, errno);
483 sVmAccountingSuspended = suspend;
484 #endif
485 }
486
487
488 void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, bool neverUnload, const RPathChain& loaderRPaths, const char* imagePath)
489 {
490 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", imagePath, fDlopenReferenceCount, fNeverUnload);
491
492 // clear error strings
493 (*context.setErrorStrings)(0, NULL, NULL, NULL);
494
495 uint64_t t0 = mach_absolute_time();
496 this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths, imagePath);
497 context.notifyBatch(dyld_image_state_dependents_mapped, preflightOnly);
498
499 // we only do the loading step for preflights
500 if ( preflightOnly )
501 return;
502
503 uint64_t t1 = mach_absolute_time();
504 context.clearAllDepths();
505 this->recursiveUpdateDepth(context.imageCount());
506
507 __block uint64_t t2, t3, t4, t5;
508 {
509 dyld3::ScopedTimer(DBG_DYLD_TIMING_APPLY_FIXUPS, 0, 0, 0);
510 t2 = mach_absolute_time();
511 this->recursiveRebase(context);
512 context.notifyBatch(dyld_image_state_rebased, false);
513
514 t3 = mach_absolute_time();
515 if ( !context.linkingMainExecutable )
516 this->recursiveBindWithAccounting(context, forceLazysBound, neverUnload);
517
518 t4 = mach_absolute_time();
519 if ( !context.linkingMainExecutable )
520 this->weakBind(context);
521 t5 = mach_absolute_time();
522 }
523
524 if ( !context.linkingMainExecutable )
525 context.notifyBatch(dyld_image_state_bound, false);
526 uint64_t t6 = mach_absolute_time();
527
528 std::vector<DOFInfo> dofs;
529 this->recursiveGetDOFSections(context, dofs);
530 context.registerDOFs(dofs);
531 uint64_t t7 = mach_absolute_time();
532
533 // interpose any dynamically loaded images
534 if ( !context.linkingMainExecutable && (fgInterposingTuples.size() != 0) ) {
535 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_APPLY_INTERPOSING, 0, 0, 0);
536 this->recursiveApplyInterposing(context);
537 }
538
539 // clear error strings
540 (*context.setErrorStrings)(0, NULL, NULL, NULL);
541
542 fgTotalLoadLibrariesTime += t1 - t0;
543 fgTotalRebaseTime += t3 - t2;
544 fgTotalBindTime += t4 - t3;
545 fgTotalWeakBindTime += t5 - t4;
546 fgTotalDOF += t7 - t6;
547
548 // done with initial dylib loads
549 fgNextPIEDylibAddress = 0;
550 }
551
552
553 void ImageLoader::printReferenceCounts()
554 {
555 dyld::log(" dlopen=%d for %s\n", fDlopenReferenceCount, getPath() );
556 }
557
558
559 bool ImageLoader::decrementDlopenReferenceCount()
560 {
561 if ( fDlopenReferenceCount == 0 )
562 return true;
563 --fDlopenReferenceCount;
564 return false;
565 }
566
567
568 // <rdar://problem/14412057> upward dylib initializers can be run too soon
569 // To handle dangling dylibs which are upward linked but not downward, all upward linked dylibs
570 // have their initialization postponed until after the recursion through downward dylibs
571 // has completed.
572 void ImageLoader::processInitializers(const LinkContext& context, mach_port_t thisThread,
573 InitializerTimingList& timingInfo, ImageLoader::UninitedUpwards& images)
574 {
575 uint32_t maxImageCount = context.imageCount()+2;
576 ImageLoader::UninitedUpwards upsBuffer[maxImageCount];
577 ImageLoader::UninitedUpwards& ups = upsBuffer[0];
578 ups.count = 0;
579 // Calling recursive init on all images in images list, building a new list of
580 // uninitialized upward dependencies.
581 for (uintptr_t i=0; i < images.count; ++i) {
582 images.images[i]->recursiveInitialization(context, thisThread, images.images[i]->getPath(), timingInfo, ups);
583 }
584 // If any upward dependencies remain, init them.
585 if ( ups.count > 0 )
586 processInitializers(context, thisThread, timingInfo, ups);
587 }
588
589
590 void ImageLoader::runInitializers(const LinkContext& context, InitializerTimingList& timingInfo)
591 {
592 uint64_t t1 = mach_absolute_time();
593 mach_port_t thisThread = mach_thread_self();
594 ImageLoader::UninitedUpwards up;
595 up.count = 1;
596 up.images[0] = this;
597 processInitializers(context, thisThread, timingInfo, up);
598 context.notifyBatch(dyld_image_state_initialized, false);
599 mach_port_deallocate(mach_task_self(), thisThread);
600 uint64_t t2 = mach_absolute_time();
601 fgTotalInitTime += (t2 - t1);
602 }
603
604
605 void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
606 {
607 if ( ! fAllLazyPointersBound ) {
608 fAllLazyPointersBound = true;
609
610 if ( recursive ) {
611 // bind lower level libraries first
612 for(unsigned int i=0; i < libraryCount(); ++i) {
613 ImageLoader* dependentImage = libImage(i);
614 if ( dependentImage != NULL )
615 dependentImage->bindAllLazyPointers(context, recursive);
616 }
617 }
618 // bind lazies in this image
619 this->doBindJustLazies(context);
620 }
621 }
622
623
624 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
625 {
626 return fAllLibraryChecksumsAndLoadAddressesMatch;
627 }
628
629
630 void ImageLoader::markedUsedRecursive(const std::vector<DynamicReference>& dynamicReferences)
631 {
632 // already visited here
633 if ( fMarkedInUse )
634 return;
635 fMarkedInUse = true;
636
637 // clear mark on all statically dependent dylibs
638 for(unsigned int i=0; i < libraryCount(); ++i) {
639 ImageLoader* dependentImage = libImage(i);
640 if ( dependentImage != NULL ) {
641 dependentImage->markedUsedRecursive(dynamicReferences);
642 }
643 }
644
645 // clear mark on all dynamically dependent dylibs
646 for (std::vector<ImageLoader::DynamicReference>::const_iterator it=dynamicReferences.begin(); it != dynamicReferences.end(); ++it) {
647 if ( it->from == this )
648 it->to->markedUsedRecursive(dynamicReferences);
649 }
650
651 }
652
653 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth)
654 {
655 // the purpose of this phase is to make the images sortable such that
656 // in a sort list of images, every image that an image depends on
657 // occurs in the list before it.
658 if ( fDepth == 0 ) {
659 // break cycles
660 fDepth = maxDepth;
661
662 // get depth of dependents
663 unsigned int minDependentDepth = maxDepth;
664 for(unsigned int i=0; i < libraryCount(); ++i) {
665 ImageLoader* dependentImage = libImage(i);
666 if ( (dependentImage != NULL) && !libIsUpward(i) ) {
667 unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth);
668 if ( d < minDependentDepth )
669 minDependentDepth = d;
670 }
671 }
672
673 // make me less deep then all my dependents
674 fDepth = minDependentDepth - 1;
675 }
676
677 return fDepth;
678 }
679
680
681 void ImageLoader::recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths, const char* loadPath)
682 {
683 if ( fState < dyld_image_state_dependents_mapped ) {
684 // break cycles
685 fState = dyld_image_state_dependents_mapped;
686
687 // get list of libraries this image needs
688 DependentLibraryInfo libraryInfos[fLibraryCount];
689 this->doGetDependentLibraries(libraryInfos);
690
691 // get list of rpaths that this image adds
692 std::vector<const char*> rpathsFromThisImage;
693 this->getRPaths(context, rpathsFromThisImage);
694 const RPathChain thisRPaths(&loaderRPaths, &rpathsFromThisImage);
695
696 // try to load each
697 bool canUsePrelinkingInfo = true;
698 for(unsigned int i=0; i < fLibraryCount; ++i){
699 ImageLoader* dependentLib;
700 bool depLibReExported = false;
701 bool depLibRequired = false;
702 bool depLibCheckSumsMatch = false;
703 DependentLibraryInfo& requiredLibInfo = libraryInfos[i];
704 if ( preflightOnly && context.inSharedCache(requiredLibInfo.name) ) {
705 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
706 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
707 setLibImage(i, NULL, false, false);
708 continue;
709 }
710 try {
711 unsigned cacheIndex;
712 bool enforceIOSMac = false;
713 #if __MAC_OS_X_VERSION_MIN_REQUIRED
714 const dyld3::MachOFile* mf = (dyld3::MachOFile*)this->machHeader();
715 if ( mf->supportsPlatform(dyld3::Platform::iOSMac) && !mf->supportsPlatform(dyld3::Platform::macOS) )
716 enforceIOSMac = true;
717 #endif
718 dependentLib = context.loadLibrary(requiredLibInfo.name, true, this->getPath(), &thisRPaths, enforceIOSMac, cacheIndex);
719 if ( dependentLib == this ) {
720 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
721 dependentLib = context.loadLibrary(requiredLibInfo.name, false, NULL, NULL, enforceIOSMac, cacheIndex);
722 if ( dependentLib != this )
723 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
724 }
725 if ( fNeverUnload )
726 dependentLib->setNeverUnload();
727 if ( requiredLibInfo.upward ) {
728 }
729 else {
730 dependentLib->fIsReferencedDownward = true;
731 }
732 LibraryInfo actualInfo = dependentLib->doGetLibraryInfo(requiredLibInfo.info);
733 depLibRequired = requiredLibInfo.required;
734 depLibCheckSumsMatch = ( actualInfo.checksum == requiredLibInfo.info.checksum );
735 depLibReExported = requiredLibInfo.reExported;
736 if ( ! depLibReExported ) {
737 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
738 depLibReExported = dependentLib->isSubframeworkOf(context, this) || this->hasSubLibrary(context, dependentLib);
739 }
740 // check found library version is compatible
741 // <rdar://problem/89200806> 0xFFFFFFFF is wildcard that matches any version
742 if ( (requiredLibInfo.info.minVersion != 0xFFFFFFFF) && (actualInfo.minVersion < requiredLibInfo.info.minVersion)
743 && ((dyld3::MachOFile*)(dependentLib->machHeader()))->enforceCompatVersion() ) {
744 // record values for possible use by CrashReporter or Finder
745 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
746 this->getShortName(), requiredLibInfo.info.minVersion >> 16, (requiredLibInfo.info.minVersion >> 8) & 0xff, requiredLibInfo.info.minVersion & 0xff,
747 dependentLib->getShortName(), actualInfo.minVersion >> 16, (actualInfo.minVersion >> 8) & 0xff, actualInfo.minVersion & 0xff);
748 }
749 // prebinding for this image disabled if any dependent library changed
750 //if ( !depLibCheckSumsMatch )
751 // canUsePrelinkingInfo = false;
752 // prebinding for this image disabled unless both this and dependent are in the shared cache
753 if ( !dependentLib->inSharedCache() || !this->inSharedCache() )
754 canUsePrelinkingInfo = false;
755
756 //if ( context.verbosePrebinding ) {
757 // if ( !requiredLib.checksumMatches )
758 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
759 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
760 // if ( dependentLib->getSlide() != 0 )
761 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
762 //}
763 }
764 catch (const char* msg) {
765 //if ( context.verbosePrebinding )
766 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
767 if ( requiredLibInfo.required ) {
768 fState = dyld_image_state_mapped;
769 // record values for possible use by CrashReporter or Finder
770 if ( strstr(msg, "Incompatible library version") != NULL )
771 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_WRONG_VERSION, this->getPath(), requiredLibInfo.name, NULL);
772 else if ( strstr(msg, "architecture") != NULL )
773 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_WRONG_ARCH, this->getPath(), requiredLibInfo.name, NULL);
774 else if ( strstr(msg, "file system sandbox") != NULL )
775 (*context.setErrorStrings)(DYLD_EXIT_REASON_FILE_SYSTEM_SANDBOX, this->getPath(), requiredLibInfo.name, NULL);
776 else if ( strstr(msg, "code signature") != NULL )
777 (*context.setErrorStrings)(DYLD_EXIT_REASON_CODE_SIGNATURE, this->getPath(), requiredLibInfo.name, NULL);
778 else if ( strstr(msg, "malformed") != NULL )
779 (*context.setErrorStrings)(DYLD_EXIT_REASON_MALFORMED_MACHO, this->getPath(), requiredLibInfo.name, NULL);
780 else
781 (*context.setErrorStrings)(DYLD_EXIT_REASON_DYLIB_MISSING, this->getPath(), requiredLibInfo.name, NULL);
782 const char* newMsg = dyld::mkstringf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo.name, this->getRealPath(), msg);
783 free((void*)msg); // our free() will do nothing if msg is a string literal
784 throw newMsg;
785 }
786 free((void*)msg); // our free() will do nothing if msg is a string literal
787 // ok if weak library not found
788 dependentLib = NULL;
789 canUsePrelinkingInfo = false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
790 }
791 setLibImage(i, dependentLib, depLibReExported, requiredLibInfo.upward);
792 }
793 fAllLibraryChecksumsAndLoadAddressesMatch = canUsePrelinkingInfo;
794
795 // tell each to load its dependents
796 for(unsigned int i=0; i < libraryCount(); ++i) {
797 ImageLoader* dependentImage = libImage(i);
798 if ( dependentImage != NULL ) {
799 dependentImage->recursiveLoadLibraries(context, preflightOnly, thisRPaths, libraryInfos[i].name);
800 }
801 }
802
803 // do deep prebind check
804 if ( fAllLibraryChecksumsAndLoadAddressesMatch ) {
805 for(unsigned int i=0; i < libraryCount(); ++i){
806 ImageLoader* dependentImage = libImage(i);
807 if ( dependentImage != NULL ) {
808 if ( !dependentImage->allDependentLibrariesAsWhenPreBound() )
809 fAllLibraryChecksumsAndLoadAddressesMatch = false;
810 }
811 }
812 }
813
814 // free rpaths (getRPaths() malloc'ed each string)
815 for(std::vector<const char*>::iterator it=rpathsFromThisImage.begin(); it != rpathsFromThisImage.end(); ++it) {
816 const char* str = *it;
817 free((void*)str);
818 }
819
820 }
821 }
822
823 void ImageLoader::recursiveRebase(const LinkContext& context)
824 {
825 if ( fState < dyld_image_state_rebased ) {
826 // break cycles
827 fState = dyld_image_state_rebased;
828
829 try {
830 // rebase lower level libraries first
831 for(unsigned int i=0; i < libraryCount(); ++i) {
832 ImageLoader* dependentImage = libImage(i);
833 if ( dependentImage != NULL )
834 dependentImage->recursiveRebase(context);
835 }
836
837 // rebase this image
838 doRebase(context);
839
840 // notify
841 context.notifySingle(dyld_image_state_rebased, this, NULL);
842 }
843 catch (const char* msg) {
844 // this image is not rebased
845 fState = dyld_image_state_dependents_mapped;
846 CRSetCrashLogMessage2(NULL);
847 throw;
848 }
849 }
850 }
851
852 void ImageLoader::recursiveApplyInterposing(const LinkContext& context)
853 {
854 if ( ! fInterposed ) {
855 // break cycles
856 fInterposed = true;
857
858 try {
859 // interpose lower level libraries first
860 for(unsigned int i=0; i < libraryCount(); ++i) {
861 ImageLoader* dependentImage = libImage(i);
862 if ( dependentImage != NULL )
863 dependentImage->recursiveApplyInterposing(context);
864 }
865
866 // interpose this image
867 doInterpose(context);
868 }
869 catch (const char* msg) {
870 // this image is not interposed
871 fInterposed = false;
872 throw;
873 }
874 }
875 }
876
877 void ImageLoader::recursiveBindWithAccounting(const LinkContext& context, bool forceLazysBound, bool neverUnload)
878 {
879 this->recursiveBind(context, forceLazysBound, neverUnload);
880 vmAccountingSetSuspended(context, false);
881 }
882
883 void ImageLoader::recursiveBind(const LinkContext& context, bool forceLazysBound, bool neverUnload)
884 {
885 // Normally just non-lazy pointers are bound immediately.
886 // The exceptions are:
887 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
888 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
889 if ( fState < dyld_image_state_bound ) {
890 // break cycles
891 fState = dyld_image_state_bound;
892
893 try {
894 // bind lower level libraries first
895 for(unsigned int i=0; i < libraryCount(); ++i) {
896 ImageLoader* dependentImage = libImage(i);
897 if ( dependentImage != NULL )
898 dependentImage->recursiveBind(context, forceLazysBound, neverUnload);
899 }
900 // bind this image
901 this->doBind(context, forceLazysBound);
902 // mark if lazys are also bound
903 if ( forceLazysBound || this->usablePrebinding(context) )
904 fAllLazyPointersBound = true;
905 // mark as never-unload if requested
906 if ( neverUnload )
907 this->setNeverUnload();
908
909 context.notifySingle(dyld_image_state_bound, this, NULL);
910 }
911 catch (const char* msg) {
912 // restore state
913 fState = dyld_image_state_rebased;
914 CRSetCrashLogMessage2(NULL);
915 throw;
916 }
917 }
918 }
919
920
921 // These are mangled symbols for all the variants of operator new and delete
922 // which a main executable can define (non-weak) and override the
923 // weak-def implementation in the OS.
924 static const char* sTreatAsWeak[] = {
925 "__Znwm", "__ZnwmRKSt9nothrow_t",
926 "__Znam", "__ZnamRKSt9nothrow_t",
927 "__ZdlPv", "__ZdlPvRKSt9nothrow_t", "__ZdlPvm",
928 "__ZdaPv", "__ZdaPvRKSt9nothrow_t", "__ZdaPvm",
929 "__ZnwmSt11align_val_t", "__ZnwmSt11align_val_tRKSt9nothrow_t",
930 "__ZnamSt11align_val_t", "__ZnamSt11align_val_tRKSt9nothrow_t",
931 "__ZdlPvSt11align_val_t", "__ZdlPvSt11align_val_tRKSt9nothrow_t", "__ZdlPvmSt11align_val_t",
932 "__ZdaPvSt11align_val_t", "__ZdaPvSt11align_val_tRKSt9nothrow_t", "__ZdaPvmSt11align_val_t"
933 };
934
935
936
937 void ImageLoader::weakBind(const LinkContext& context)
938 {
939 if ( context.verboseWeakBind )
940 dyld::log("dyld: weak bind start:\n");
941 uint64_t t1 = mach_absolute_time();
942 // get set of ImageLoaders that participate in coalecsing
943 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
944 unsigned imageIndexes[fgImagesRequiringCoalescing];
945 int count = context.getCoalescedImages(imagesNeedingCoalescing, imageIndexes);
946
947 // count how many have not already had weakbinding done
948 int countNotYetWeakBound = 0;
949 int countOfImagesWithWeakDefinitionsNotInSharedCache = 0;
950 for(int i=0; i < count; ++i) {
951 if ( ! imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) )
952 ++countNotYetWeakBound;
953 if ( ! imagesNeedingCoalescing[i]->inSharedCache() )
954 ++countOfImagesWithWeakDefinitionsNotInSharedCache;
955 }
956
957 // don't need to do any coalescing if only one image has overrides, or all have already been done
958 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache > 0) && (countNotYetWeakBound > 0) ) {
959 // make symbol iterators for each
960 ImageLoader::CoalIterator iterators[count];
961 ImageLoader::CoalIterator* sortedIts[count];
962 for(int i=0; i < count; ++i) {
963 imagesNeedingCoalescing[i]->initializeCoalIterator(iterators[i], i, imageIndexes[i]);
964 sortedIts[i] = &iterators[i];
965 if ( context.verboseWeakBind )
966 dyld::log("dyld: weak bind load order %d/%d for %s\n", i, count, imagesNeedingCoalescing[i]->getIndexedPath(imageIndexes[i]));
967 }
968
969 // walk all symbols keeping iterators in sync by
970 // only ever incrementing the iterator with the lowest symbol
971 int doneCount = 0;
972 while ( doneCount != count ) {
973 //for(int i=0; i < count; ++i)
974 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
975 //dyld::log("\n");
976 // increment iterator with lowest symbol
977 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
978 ++doneCount;
979 // re-sort iterators
980 for(int i=1; i < count; ++i) {
981 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
982 if ( result == 0 )
983 sortedIts[i-1]->symbolMatches = true;
984 if ( result > 0 ) {
985 // new one is bigger then next, so swap
986 ImageLoader::CoalIterator* temp = sortedIts[i-1];
987 sortedIts[i-1] = sortedIts[i];
988 sortedIts[i] = temp;
989 }
990 if ( result < 0 )
991 break;
992 }
993 // process all matching symbols just before incrementing the lowest one that matches
994 if ( sortedIts[0]->symbolMatches && !sortedIts[0]->done ) {
995 const char* nameToCoalesce = sortedIts[0]->symbolName;
996 // pick first symbol in load order (and non-weak overrides weak)
997 uintptr_t targetAddr = 0;
998 ImageLoader* targetImage = NULL;
999 unsigned targetImageIndex = 0;
1000 for(int i=0; i < count; ++i) {
1001 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1002 if ( context.verboseWeakBind )
1003 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce, iterators[i].weakSymbol, iterators[i].image->getIndexedPath((unsigned)iterators[i].imageIndex));
1004 if ( iterators[i].weakSymbol ) {
1005 if ( targetAddr == 0 ) {
1006 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1007 if ( targetAddr != 0 ) {
1008 targetImage = iterators[i].image;
1009 targetImageIndex = (unsigned)iterators[i].imageIndex;
1010 }
1011 }
1012 }
1013 else {
1014 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
1015 if ( targetAddr != 0 ) {
1016 targetImage = iterators[i].image;
1017 targetImageIndex = (unsigned)iterators[i].imageIndex;
1018 // strong implementation found, stop searching
1019 break;
1020 }
1021 }
1022 }
1023 }
1024 // tell each to bind to this symbol (unless already bound)
1025 if ( targetAddr != 0 ) {
1026 if ( context.verboseWeakBind ) {
1027 dyld::log("dyld: weak binding all uses of %s to copy from %s\n",
1028 nameToCoalesce, targetImage->getIndexedShortName(targetImageIndex));
1029 }
1030 for(int i=0; i < count; ++i) {
1031 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
1032 if ( context.verboseWeakBind ) {
1033 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n",
1034 nameToCoalesce, iterators[i].image->getIndexedShortName((unsigned)iterators[i].imageIndex),
1035 targetAddr, targetImage->getIndexedShortName(targetImageIndex));
1036 }
1037 if ( ! iterators[i].image->weakSymbolsBound(imageIndexes[i]) )
1038 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, targetImageIndex, context);
1039 iterators[i].symbolMatches = false;
1040 }
1041 }
1042 }
1043
1044 }
1045 }
1046
1047 #if __arm64e__
1048 for (int i=0; i < count; ++i) {
1049 if ( imagesNeedingCoalescing[i]->usesChainedFixups() ) {
1050 // during binding of references to weak-def symbols, the dyld cache was patched
1051 // but if main executable has non-weak override of operator new or delete it needs is handled here
1052 if ( !imagesNeedingCoalescing[i]->weakSymbolsBound(imageIndexes[i]) ) {
1053 for (const char* weakSymbolName : sTreatAsWeak) {
1054 const ImageLoader* dummy;
1055 imagesNeedingCoalescing[i]->resolveWeak(context, weakSymbolName, true, false, &dummy);
1056 }
1057 }
1058 }
1059 else {
1060 // look for weak def symbols in this image which may override the cache
1061 ImageLoader::CoalIterator coaler;
1062 imagesNeedingCoalescing[i]->initializeCoalIterator(coaler, i, 0);
1063 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1064 while ( !coaler.done ) {
1065 imagesNeedingCoalescing[i]->incrementCoalIterator(coaler);
1066 const ImageLoader* dummy;
1067 // a side effect of resolveWeak() is to patch cache
1068 imagesNeedingCoalescing[i]->resolveWeak(context, coaler.symbolName, true, false, &dummy);
1069 }
1070 }
1071 }
1072 #endif
1073
1074 // mark all as having all weak symbols bound
1075 for(int i=0; i < count; ++i) {
1076 imagesNeedingCoalescing[i]->setWeakSymbolsBound(imageIndexes[i]);
1077 }
1078 }
1079
1080 uint64_t t2 = mach_absolute_time();
1081 fgTotalWeakBindTime += t2 - t1;
1082
1083 if ( context.verboseWeakBind )
1084 dyld::log("dyld: weak bind end\n");
1085 }
1086
1087
1088
1089 void ImageLoader::recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs)
1090 {
1091 if ( ! fRegisteredDOF ) {
1092 // break cycles
1093 fRegisteredDOF = true;
1094
1095 // gather lower level libraries first
1096 for(unsigned int i=0; i < libraryCount(); ++i) {
1097 ImageLoader* dependentImage = libImage(i);
1098 if ( dependentImage != NULL )
1099 dependentImage->recursiveGetDOFSections(context, dofs);
1100 }
1101 this->doGetDOFSections(context, dofs);
1102 }
1103 }
1104
1105 void ImageLoader::setNeverUnloadRecursive() {
1106 if ( ! fNeverUnload ) {
1107 // break cycles
1108 fNeverUnload = true;
1109
1110 // gather lower level libraries first
1111 for(unsigned int i=0; i < libraryCount(); ++i) {
1112 ImageLoader* dependentImage = libImage(i);
1113 if ( dependentImage != NULL )
1114 dependentImage->setNeverUnloadRecursive();
1115 }
1116 }
1117 }
1118
1119 void ImageLoader::recursiveSpinLock(recursive_lock& rlock)
1120 {
1121 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
1122 // keep trying until success (spin)
1123 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL, &rlock, (void**)&fInitializerRecursiveLock) ) {
1124 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
1125 // the same thread we are on, the increment the lock count, otherwise continue to spin
1126 if ( (fInitializerRecursiveLock != NULL) && (fInitializerRecursiveLock->thread == rlock.thread) )
1127 break;
1128 }
1129 ++(fInitializerRecursiveLock->count);
1130 }
1131
1132 void ImageLoader::recursiveSpinUnLock()
1133 {
1134 if ( --(fInitializerRecursiveLock->count) == 0 )
1135 fInitializerRecursiveLock = NULL;
1136 }
1137
1138 void ImageLoader::InitializerTimingList::addTime(const char* name, uint64_t time)
1139 {
1140 for (int i=0; i < count; ++i) {
1141 if ( strcmp(images[i].shortName, name) == 0 ) {
1142 images[i].initTime += time;
1143 return;
1144 }
1145 }
1146 images[count].initTime = time;
1147 images[count].shortName = name;
1148 ++count;
1149 }
1150
1151 void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread, const char* pathToInitialize,
1152 InitializerTimingList& timingInfo, UninitedUpwards& uninitUps)
1153 {
1154 recursive_lock lock_info(this_thread);
1155 recursiveSpinLock(lock_info);
1156
1157 if ( fState < dyld_image_state_dependents_initialized-1 ) {
1158 uint8_t oldState = fState;
1159 // break cycles
1160 fState = dyld_image_state_dependents_initialized-1;
1161 try {
1162 // initialize lower level libraries first
1163 for(unsigned int i=0; i < libraryCount(); ++i) {
1164 ImageLoader* dependentImage = libImage(i);
1165 if ( dependentImage != NULL ) {
1166 // don't try to initialize stuff "above" me yet
1167 if ( libIsUpward(i) ) {
1168 uninitUps.images[uninitUps.count] = dependentImage;
1169 uninitUps.count++;
1170 }
1171 else if ( dependentImage->fDepth >= fDepth ) {
1172 dependentImage->recursiveInitialization(context, this_thread, libPath(i), timingInfo, uninitUps);
1173 }
1174 }
1175 }
1176
1177 // record termination order
1178 if ( this->needsTermination() )
1179 context.terminationRecorder(this);
1180
1181 // let objc know we are about to initialize this image
1182 uint64_t t1 = mach_absolute_time();
1183 fState = dyld_image_state_dependents_initialized;
1184 oldState = fState;
1185 context.notifySingle(dyld_image_state_dependents_initialized, this, &timingInfo);
1186
1187 // initialize this image
1188 bool hasInitializers = this->doInitialization(context);
1189
1190 // let anyone know we finished initializing this image
1191 fState = dyld_image_state_initialized;
1192 oldState = fState;
1193 context.notifySingle(dyld_image_state_initialized, this, NULL);
1194
1195 if ( hasInitializers ) {
1196 uint64_t t2 = mach_absolute_time();
1197 timingInfo.addTime(this->getShortName(), t2-t1);
1198 }
1199 }
1200 catch (const char* msg) {
1201 // this image is not initialized
1202 fState = oldState;
1203 recursiveSpinUnLock();
1204 throw;
1205 }
1206 }
1207
1208 recursiveSpinUnLock();
1209 }
1210
1211
1212 static void printTime(const char* msg, uint64_t partTime, uint64_t totalTime)
1213 {
1214 static uint64_t sUnitsPerSecond = 0;
1215 if ( sUnitsPerSecond == 0 ) {
1216 struct mach_timebase_info timeBaseInfo;
1217 if ( mach_timebase_info(&timeBaseInfo) != KERN_SUCCESS )
1218 return;
1219 sUnitsPerSecond = 1000000000ULL * timeBaseInfo.denom / timeBaseInfo.numer;
1220 }
1221 if ( partTime < sUnitsPerSecond ) {
1222 uint32_t milliSecondsTimesHundred = (uint32_t)((partTime*100000)/sUnitsPerSecond);
1223 uint32_t milliSeconds = (uint32_t)(milliSecondsTimesHundred/100);
1224 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1225 uint32_t percent = percentTimesTen/10;
1226 if ( milliSeconds >= 100 )
1227 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1228 else if ( milliSeconds >= 10 )
1229 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1230 else
1231 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
1232 }
1233 else {
1234 uint32_t secondsTimeTen = (uint32_t)((partTime*10)/sUnitsPerSecond);
1235 uint32_t seconds = secondsTimeTen/10;
1236 uint32_t percentTimesTen = (uint32_t)((partTime*1000)/totalTime);
1237 uint32_t percent = percentTimesTen/10;
1238 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg, seconds, secondsTimeTen-seconds*10, percent, percentTimesTen-percent*10);
1239 }
1240 }
1241
1242 static char* commatize(uint64_t in, char* out)
1243 {
1244 uint64_t div10 = in / 10;
1245 uint8_t delta = in - div10*10;
1246 char* s = &out[32];
1247 int digitCount = 1;
1248 *s = '\0';
1249 *(--s) = '0' + delta;
1250 in = div10;
1251 while ( in != 0 ) {
1252 if ( (digitCount % 3) == 0 )
1253 *(--s) = ',';
1254 div10 = in / 10;
1255 delta = in - div10*10;
1256 *(--s) = '0' + delta;
1257 in = div10;
1258 ++digitCount;
1259 }
1260 return s;
1261 }
1262
1263
1264 void ImageLoader::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
1265 {
1266 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1267
1268 uint64_t totalDyldTime = totalTime - fgTotalDebuggerPausedTime - fgTotalRebindCacheTime;
1269 printTime("Total pre-main time", totalDyldTime, totalDyldTime);
1270 printTime(" dylib loading time", fgTotalLoadLibrariesTime-fgTotalDebuggerPausedTime, totalDyldTime);
1271 printTime(" rebase/binding time", fgTotalRebaseTime+fgTotalBindTime+fgTotalWeakBindTime-fgTotalRebindCacheTime, totalDyldTime);
1272 printTime(" ObjC setup time", fgTotalObjCSetupTime, totalDyldTime);
1273 printTime(" initializer time", fgTotalInitTime-fgTotalObjCSetupTime, totalDyldTime);
1274 dyld::log(" slowest intializers :\n");
1275 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1276 uint64_t t = timingInfo.images[i].initTime;
1277 if ( t*50 < totalDyldTime )
1278 continue;
1279 dyld::log("%30s ", timingInfo.images[i].shortName);
1280 if ( strncmp(timingInfo.images[i].shortName, "libSystem.", 10) == 0 )
1281 t -= fgTotalObjCSetupTime;
1282 printTime("", t, totalDyldTime);
1283 }
1284 dyld::log("\n");
1285 }
1286
1287 void ImageLoader::printStatisticsDetails(unsigned int imageCount, const InitializerTimingList& timingInfo)
1288 {
1289 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
1290 char commaNum1[40];
1291 char commaNum2[40];
1292
1293 printTime(" total time", totalTime, totalTime);
1294 dyld::log(" total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
1295 dyld::log(" total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped, fgTotalBytesMapped/4096, fgTotalBytesPreFetched/4096);
1296 printTime(" total images loading time", fgTotalLoadLibrariesTime, totalTime);
1297 printTime(" total load time in ObjC", fgTotalObjCSetupTime, totalTime);
1298 printTime(" total debugger pause time", fgTotalDebuggerPausedTime, totalTime);
1299 printTime(" total dtrace DOF registration time", fgTotalDOF, totalTime);
1300 dyld::log(" total rebase fixups: %s\n", commatize(fgTotalRebaseFixups, commaNum1));
1301 printTime(" total rebase fixups time", fgTotalRebaseTime, totalTime);
1302 dyld::log(" total binding fixups: %s\n", commatize(fgTotalBindFixups, commaNum1));
1303 if ( fgTotalBindSymbolsResolved != 0 ) {
1304 uint32_t avgTimesTen = (fgTotalBindImageSearches * 10) / fgTotalBindSymbolsResolved;
1305 uint32_t avgInt = fgTotalBindImageSearches / fgTotalBindSymbolsResolved;
1306 uint32_t avgTenths = avgTimesTen - (avgInt*10);
1307 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
1308 commatize(fgTotalBindSymbolsResolved, commaNum1), avgInt, avgTenths);
1309 }
1310 printTime(" total binding fixups time", fgTotalBindTime, totalTime);
1311 printTime(" total weak binding fixups time", fgTotalWeakBindTime, totalTime);
1312 printTime(" total redo shared cached bindings time", fgTotalRebindCacheTime, totalTime);
1313 dyld::log(" total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups, commaNum1), commatize(fgTotalPossibleLazyBindFixups, commaNum2));
1314 printTime(" total time in initializers and ObjC +load", fgTotalInitTime-fgTotalObjCSetupTime, totalTime);
1315 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1316 uint64_t t = timingInfo.images[i].initTime;
1317 if ( t*1000 < totalTime )
1318 continue;
1319 dyld::log("%42s ", timingInfo.images[i].shortName);
1320 if ( strncmp(timingInfo.images[i].shortName, "libSystem.", 10) == 0 )
1321 t -= fgTotalObjCSetupTime;
1322 printTime("", t, totalTime);
1323 }
1324
1325 }
1326
1327
1328 //
1329 // copy path and add suffix to result
1330 //
1331 // /path/foo.dylib _debug => /path/foo_debug.dylib
1332 // foo.dylib _debug => foo_debug.dylib
1333 // foo _debug => foo_debug
1334 // /path/bar _debug => /path/bar_debug
1335 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1336 //
1337 void ImageLoader::addSuffix(const char* path, const char* suffix, char* result)
1338 {
1339 strcpy(result, path);
1340
1341 char* start = strrchr(result, '/');
1342 if ( start != NULL )
1343 start++;
1344 else
1345 start = result;
1346
1347 char* dot = strrchr(start, '.');
1348 if ( dot != NULL ) {
1349 strcpy(dot, suffix);
1350 strcat(&dot[strlen(suffix)], &path[dot-result]);
1351 }
1352 else {
1353 strcat(result, suffix);
1354 }
1355 }
1356
1357
1358 //
1359 // This function is the hotspot of symbol lookup. It was pulled out of findExportedSymbol()
1360 // to enable it to be re-written in assembler if needed.
1361 //
1362 const uint8_t* ImageLoader::trieWalk(const uint8_t* start, const uint8_t* end, const char* s)
1363 {
1364 //dyld::log("trieWalk(%p, %p, %s)\n", start, end, s);
1365 ++fgSymbolTrieSearchs;
1366 const uint8_t* p = start;
1367 while ( p != NULL ) {
1368 uintptr_t terminalSize = *p++;
1369 if ( terminalSize > 127 ) {
1370 // except for re-export-with-rename, all terminal sizes fit in one byte
1371 --p;
1372 terminalSize = read_uleb128(p, end);
1373 }
1374 if ( (*s == '\0') && (terminalSize != 0) ) {
1375 //dyld::log("trieWalk(%p) returning %p\n", start, p);
1376 return p;
1377 }
1378 const uint8_t* children = p + terminalSize;
1379 if ( children > end ) {
1380 dyld::log("trieWalk() malformed trie node, terminalSize=0x%lx extends past end of trie\n", terminalSize);
1381 return NULL;
1382 }
1383 //dyld::log("trieWalk(%p) sym=%s, terminalSize=%lu, children=%p\n", start, s, terminalSize, children);
1384 uint8_t childrenRemaining = *children++;
1385 p = children;
1386 uintptr_t nodeOffset = 0;
1387 for (; childrenRemaining > 0; --childrenRemaining) {
1388 const char* ss = s;
1389 //dyld::log("trieWalk(%p) child str=%s\n", start, (char*)p);
1390 bool wrongEdge = false;
1391 // scan whole edge to get to next edge
1392 // if edge is longer than target symbol name, don't read past end of symbol name
1393 char c = *p;
1394 while ( c != '\0' ) {
1395 if ( !wrongEdge ) {
1396 if ( c != *ss )
1397 wrongEdge = true;
1398 ++ss;
1399 }
1400 ++p;
1401 c = *p;
1402 }
1403 if ( wrongEdge ) {
1404 // advance to next child
1405 ++p; // skip over zero terminator
1406 // skip over uleb128 until last byte is found
1407 while ( (*p & 0x80) != 0 )
1408 ++p;
1409 ++p; // skip over last byte of uleb128
1410 if ( p > end ) {
1411 dyld::log("trieWalk() malformed trie node, child node extends past end of trie\n");
1412 return NULL;
1413 }
1414 }
1415 else {
1416 // the symbol so far matches this edge (child)
1417 // so advance to the child's node
1418 ++p;
1419 nodeOffset = read_uleb128(p, end);
1420 if ( (nodeOffset == 0) || ( &start[nodeOffset] > end) ) {
1421 dyld::log("trieWalk() malformed trie child, nodeOffset=0x%lx out of range\n", nodeOffset);
1422 return NULL;
1423 }
1424 s = ss;
1425 //dyld::log("trieWalk() found matching edge advancing to node 0x%lx\n", nodeOffset);
1426 break;
1427 }
1428 }
1429 if ( nodeOffset != 0 )
1430 p = &start[nodeOffset];
1431 else
1432 p = NULL;
1433 }
1434 //dyld::log("trieWalk(%p) return NULL\n", start);
1435 return NULL;
1436 }
1437
1438
1439
1440 uintptr_t ImageLoader::read_uleb128(const uint8_t*& p, const uint8_t* end)
1441 {
1442 uint64_t result = 0;
1443 int bit = 0;
1444 do {
1445 if (p == end)
1446 dyld::throwf("malformed uleb128");
1447
1448 uint64_t slice = *p & 0x7f;
1449
1450 if (bit > 63)
1451 dyld::throwf("uleb128 too big for uint64, bit=%d, result=0x%0llX", bit, result);
1452 else {
1453 result |= (slice << bit);
1454 bit += 7;
1455 }
1456 } while (*p++ & 0x80);
1457 return (uintptr_t)result;
1458 }
1459
1460
1461 intptr_t ImageLoader::read_sleb128(const uint8_t*& p, const uint8_t* end)
1462 {
1463 int64_t result = 0;
1464 int bit = 0;
1465 uint8_t byte;
1466 do {
1467 if (p == end)
1468 throw "malformed sleb128";
1469 byte = *p++;
1470 result |= (((int64_t)(byte & 0x7f)) << bit);
1471 bit += 7;
1472 } while (byte & 0x80);
1473 // sign extend negative numbers
1474 if ( (byte & 0x40) != 0 )
1475 result |= (~0ULL) << bit;
1476 return (intptr_t)result;
1477 }
1478
1479
1480 VECTOR_NEVER_DESTRUCTED_IMPL(ImageLoader::InterposeTuple);
1481 VECTOR_NEVER_DESTRUCTED_IMPL(ImagePair);
1482
1483
1484