]> git.saurik.com Git - apple/dyld.git/blob - src/ImageLoader.cpp
dyld-195.5.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 <errno.h>
28 #include <fcntl.h>
29 #include <mach/mach.h>
30 #include <mach-o/fat.h>
31 #include <sys/types.h>
32 #include <sys/stat.h>
33 #include <sys/mman.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
36 #include <libkern/OSAtomic.h>
37
38 #include "ImageLoader.h"
39
40
41 uint32_t ImageLoader::fgImagesUsedFromSharedCache = 0;
42 uint32_t ImageLoader::fgImagesWithUsedPrebinding = 0;
43 uint32_t ImageLoader::fgImagesRequiringCoalescing = 0;
44 uint32_t ImageLoader::fgImagesHasWeakDefinitions = 0;
45 uint32_t ImageLoader::fgTotalRebaseFixups = 0;
46 uint32_t ImageLoader::fgTotalBindFixups = 0;
47 uint32_t ImageLoader::fgTotalBindSymbolsResolved = 0;
48 uint32_t ImageLoader::fgTotalBindImageSearches = 0;
49 uint32_t ImageLoader::fgTotalLazyBindFixups = 0;
50 uint32_t ImageLoader::fgTotalPossibleLazyBindFixups = 0;
51 uint32_t ImageLoader::fgTotalSegmentsMapped = 0;
52 uint64_t ImageLoader::fgTotalBytesMapped = 0;
53 uint64_t ImageLoader::fgTotalBytesPreFetched = 0;
54 uint64_t ImageLoader::fgTotalLoadLibrariesTime;
55 uint64_t ImageLoader::fgTotalRebaseTime;
56 uint64_t ImageLoader::fgTotalBindTime;
57 uint64_t ImageLoader::fgTotalWeakBindTime;
58 uint64_t ImageLoader::fgTotalDOF;
59 uint64_t ImageLoader::fgTotalInitTime;
60 uint16_t ImageLoader::fgLoadOrdinal = 0;
61 std::vector<ImageLoader::InterposeTuple>ImageLoader::fgInterposingTuples;
62 uintptr_t ImageLoader::fgNextPIEDylibAddress = 0;
63
64
65
66 ImageLoader::ImageLoader(const char* path, unsigned int libCount)
67 : fPath(path), fDevice(0), fInode(0), fLastModified(0),
68 fPathHash(0), fDlopenReferenceCount(0), fStaticReferenceCount(0),
69 fDynamicReferenceCount(0), fDynamicReferences(NULL), fInitializerRecursiveLock(NULL),
70 fDepth(0), fLoadOrder(fgLoadOrdinal++), fState(0), fLibraryCount(libCount),
71 fAllLibraryChecksumsAndLoadAddressesMatch(false), fLeaveMapped(false), fNeverUnload(false),
72 fHideSymbols(false), fMatchByInstallName(false),
73 fInterposed(false), fRegisteredDOF(false), fAllLazyPointersBound(false),
74 fBeingRemoved(false), fAddFuncNotified(false),
75 fPathOwnedByImage(false), fWeakSymbolsBound(false)
76 {
77 if ( fPath != NULL )
78 fPathHash = hash(fPath);
79 }
80
81
82 void ImageLoader::deleteImage(ImageLoader* image)
83 {
84 // this cannot be done in destructor because libImage() is implemented
85 // in a subclass
86 DependentLibraryInfo libraryInfos[image->libraryCount()];
87 image->doGetDependentLibraries(libraryInfos);
88 for(unsigned int i=0; i < image->libraryCount(); ++i) {
89 ImageLoader* lib = image->libImage(i);
90 if ( (lib != NULL) && ! libraryInfos[i].upward )
91 lib->fStaticReferenceCount--;
92 }
93 delete image;
94 }
95
96
97 ImageLoader::~ImageLoader()
98 {
99 if ( fPathOwnedByImage && (fPath != NULL) )
100 delete [] fPath;
101 if ( fDynamicReferences != NULL ) {
102 for (std::vector<const ImageLoader*>::iterator it = fDynamicReferences->begin(); it != fDynamicReferences->end(); ++it ) {
103 const_cast<ImageLoader*>(*it)->fDynamicReferenceCount--;
104 }
105 delete fDynamicReferences;
106 }
107 }
108
109 void ImageLoader::setFileInfo(dev_t device, ino_t inode, time_t modDate)
110 {
111 fDevice = device;
112 fInode = inode;
113 fLastModified = modDate;
114 }
115
116 void ImageLoader::setMapped(const LinkContext& context)
117 {
118 fState = dyld_image_state_mapped;
119 context.notifySingle(dyld_image_state_mapped, this); // note: can throw exception
120 }
121
122 void ImageLoader::addDynamicReference(const ImageLoader* target)
123 {
124 bool alreadyInVector = false;
125 if ( fDynamicReferences == NULL ) {
126 fDynamicReferences = new std::vector<const ImageLoader*>();
127 }
128 else {
129 for (std::vector<const ImageLoader*>::iterator it = fDynamicReferences->begin(); it != fDynamicReferences->end(); ++it ) {
130 if ( *it == target ) {
131 alreadyInVector = true;
132 break;
133 }
134 }
135 }
136 if ( ! alreadyInVector ) {
137 fDynamicReferences->push_back(target);
138 const_cast<ImageLoader*>(target)->fDynamicReferenceCount++;
139 }
140 //dyld::log("dyld: addDynamicReference() from %s to %s, fDynamicReferences->size()=%lu\n", this->getPath(), target->getPath(), fDynamicReferences->size());
141 }
142
143 int ImageLoader::compare(const ImageLoader* right) const
144 {
145 if ( this->fDepth == right->fDepth ) {
146 if ( this->fLoadOrder == right->fLoadOrder )
147 return 0;
148 else if ( this->fLoadOrder < right->fLoadOrder )
149 return -1;
150 else
151 return 1;
152 }
153 else {
154 if ( this->fDepth < right->fDepth )
155 return -1;
156 else
157 return 1;
158 }
159 }
160
161 void ImageLoader::setPath(const char* path)
162 {
163 if ( fPathOwnedByImage && (fPath != NULL) )
164 delete [] fPath;
165 fPath = new char[strlen(path)+1];
166 strcpy((char*)fPath, path);
167 fPathOwnedByImage = true; // delete fPath when this image is destructed
168 fPathHash = hash(fPath);
169 }
170
171 void ImageLoader::setPathUnowned(const char* path)
172 {
173 if ( fPathOwnedByImage && (fPath != NULL) ) {
174 delete [] fPath;
175 }
176 fPath = path;
177 fPathOwnedByImage = false;
178 fPathHash = hash(fPath);
179 }
180
181
182 uint32_t ImageLoader::hash(const char* path)
183 {
184 // this does not need to be a great hash
185 // it is just used to reduce the number of strcmp() calls
186 // of existing images when loading a new image
187 uint32_t h = 0;
188 for (const char* s=path; *s != '\0'; ++s)
189 h = h*5 + *s;
190 return h;
191 }
192
193 bool ImageLoader::matchInstallPath() const
194 {
195 return fMatchByInstallName;
196 }
197
198 void ImageLoader::setMatchInstallPath(bool match)
199 {
200 fMatchByInstallName = match;
201 }
202
203 bool ImageLoader::statMatch(const struct stat& stat_buf) const
204 {
205 return ( (this->fDevice == stat_buf.st_dev) && (this->fInode == stat_buf.st_ino) );
206 }
207
208 const char* ImageLoader::getShortName() const
209 {
210 // try to return leaf name
211 if ( fPath != NULL ) {
212 const char* s = strrchr(fPath, '/');
213 if ( s != NULL )
214 return &s[1];
215 }
216 return fPath;
217 }
218
219 void ImageLoader::setLeaveMapped()
220 {
221 fLeaveMapped = true;
222 }
223
224 void ImageLoader::setHideExports(bool hide)
225 {
226 fHideSymbols = hide;
227 }
228
229 bool ImageLoader::hasHiddenExports() const
230 {
231 return fHideSymbols;
232 }
233
234 bool ImageLoader::isLinked() const
235 {
236 return (fState >= dyld_image_state_bound);
237 }
238
239 time_t ImageLoader::lastModified() const
240 {
241 return fLastModified;
242 }
243
244 bool ImageLoader::containsAddress(const void* addr) const
245 {
246 if ( ! this->isLinked() )
247 return false;
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 static bool notInImgageList(const ImageLoader* image, const ImageLoader** dsiStart, const ImageLoader** dsiCur)
291 {
292 for (const ImageLoader** p = dsiStart; p < dsiCur; ++p)
293 if ( *p == image )
294 return false;
295 return true;
296 }
297
298
299 // private method that handles circular dependencies by only search any image once
300 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImagesExcept(const char* name,
301 const ImageLoader** dsiStart, const ImageLoader**& dsiCur, const ImageLoader** dsiEnd, const ImageLoader** foundIn) const
302 {
303 const ImageLoader::Symbol* sym;
304
305 // search self
306 if ( notInImgageList(this, dsiStart, dsiCur) ) {
307 sym = this->findExportedSymbol(name, false, foundIn);
308 if ( sym != NULL )
309 return sym;
310 *dsiCur++ = this;
311 }
312
313 // search directly dependent libraries
314 for(unsigned int i=0; i < libraryCount(); ++i) {
315 ImageLoader* dependentImage = libImage(i);
316 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
317 const ImageLoader::Symbol* sym = dependentImage->findExportedSymbol(name, false, foundIn);
318 if ( sym != NULL )
319 return sym;
320 }
321 }
322
323 // search indirectly dependent libraries
324 for(unsigned int i=0; i < libraryCount(); ++i) {
325 ImageLoader* dependentImage = libImage(i);
326 if ( (dependentImage != NULL) && notInImgageList(dependentImage, dsiStart, dsiCur) ) {
327 *dsiCur++ = dependentImage;
328 const ImageLoader::Symbol* sym = dependentImage->findExportedSymbolInDependentImagesExcept(name, dsiStart, dsiCur, dsiEnd, foundIn);
329 if ( sym != NULL )
330 return sym;
331 }
332 }
333
334 return NULL;
335 }
336
337
338 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
339 {
340 unsigned int imageCount = context.imageCount();
341 const ImageLoader* dontSearchImages[imageCount];
342 dontSearchImages[0] = this; // don't search this image
343 const ImageLoader** cur = &dontSearchImages[1];
344 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
345 }
346
347 const ImageLoader::Symbol* ImageLoader::findExportedSymbolInImageOrDependentImages(const char* name, const LinkContext& context, const ImageLoader** foundIn) const
348 {
349 unsigned int imageCount = context.imageCount();
350 const ImageLoader* dontSearchImages[imageCount];
351 const ImageLoader** cur = &dontSearchImages[0];
352 return this->findExportedSymbolInDependentImagesExcept(name, &dontSearchImages[0], cur, &dontSearchImages[imageCount], foundIn);
353 }
354
355 // this is called by initializeMainExecutable() to interpose on the initial set of images
356 void ImageLoader::applyInterposing(const LinkContext& context)
357 {
358 if ( fgInterposingTuples.size() != 0 )
359 this->recursiveApplyInterposing(context);
360 }
361
362 void ImageLoader::link(const LinkContext& context, bool forceLazysBound, bool preflightOnly, const RPathChain& loaderRPaths)
363 {
364 //dyld::log("ImageLoader::link(%s) refCount=%d, neverUnload=%d\n", this->getPath(), fStaticReferenceCount, fNeverUnload);
365
366 // clear error strings
367 (*context.setErrorStrings)(dyld_error_kind_none, NULL, NULL, NULL);
368
369 uint64_t t0 = mach_absolute_time();
370 this->recursiveLoadLibraries(context, preflightOnly, loaderRPaths);
371 context.notifyBatch(dyld_image_state_dependents_mapped);
372
373 // we only do the loading step for preflights
374 if ( preflightOnly )
375 return;
376
377 uint64_t t1 = mach_absolute_time();
378 context.clearAllDepths();
379 this->recursiveUpdateDepth(context.imageCount());
380
381 uint64_t t2 = mach_absolute_time();
382 this->recursiveRebase(context);
383 context.notifyBatch(dyld_image_state_rebased);
384
385 uint64_t t3 = mach_absolute_time();
386 this->recursiveBind(context, forceLazysBound);
387
388 uint64_t t4 = mach_absolute_time();
389 this->weakBind(context);
390 uint64_t t5 = mach_absolute_time();
391
392 context.notifyBatch(dyld_image_state_bound);
393 uint64_t t6 = mach_absolute_time();
394
395 std::vector<DOFInfo> dofs;
396 this->recursiveGetDOFSections(context, dofs);
397 context.registerDOFs(dofs);
398 uint64_t t7 = mach_absolute_time();
399
400 // interpose any dynamically loaded images
401 if ( !context.linkingMainExecutable && (fgInterposingTuples.size() != 0) ) {
402 this->recursiveApplyInterposing(context);
403 }
404
405 // clear error strings
406 (*context.setErrorStrings)(dyld_error_kind_none, NULL, NULL, NULL);
407
408 fgTotalLoadLibrariesTime += t1 - t0;
409 fgTotalRebaseTime += t3 - t2;
410 fgTotalBindTime += t4 - t3;
411 fgTotalWeakBindTime += t5 - t4;
412 fgTotalDOF += t7 - t6;
413
414 // done with initial dylib loads
415 fgNextPIEDylibAddress = 0;
416 }
417
418
419 void ImageLoader::printReferenceCounts()
420 {
421 dyld::log(" dlopen=%d, static=%d, dynamic=%d for %s\n",
422 fDlopenReferenceCount, fStaticReferenceCount, fDynamicReferenceCount, getPath() );
423 }
424
425
426 bool ImageLoader::decrementDlopenReferenceCount()
427 {
428 if ( fDlopenReferenceCount == 0 )
429 return true;
430 --fDlopenReferenceCount;
431 return false;
432 }
433
434 void ImageLoader::runInitializers(const LinkContext& context, InitializerTimingList& timingInfo)
435 {
436 uint64_t t1 = mach_absolute_time();
437 mach_port_t this_thread = mach_thread_self();
438 this->recursiveInitialization(context, this_thread, timingInfo);
439 context.notifyBatch(dyld_image_state_initialized);
440 mach_port_deallocate(mach_task_self(), this_thread);
441 uint64_t t2 = mach_absolute_time();
442 fgTotalInitTime += (t2 - t1);
443 }
444
445
446 void ImageLoader::bindAllLazyPointers(const LinkContext& context, bool recursive)
447 {
448 if ( ! fAllLazyPointersBound ) {
449 fAllLazyPointersBound = true;
450
451 if ( recursive ) {
452 // bind lower level libraries first
453 for(unsigned int i=0; i < libraryCount(); ++i) {
454 ImageLoader* dependentImage = libImage(i);
455 if ( dependentImage != NULL )
456 dependentImage->bindAllLazyPointers(context, recursive);
457 }
458 }
459 // bind lazies in this image
460 this->doBindJustLazies(context);
461 }
462 }
463
464
465 bool ImageLoader::allDependentLibrariesAsWhenPreBound() const
466 {
467 return fAllLibraryChecksumsAndLoadAddressesMatch;
468 }
469
470
471 unsigned int ImageLoader::recursiveUpdateDepth(unsigned int maxDepth)
472 {
473 // the purpose of this phase is to make the images sortable such that
474 // in a sort list of images, every image that an image depends on
475 // occurs in the list before it.
476 if ( fDepth == 0 ) {
477 // break cycles
478 fDepth = maxDepth;
479
480 // get depth of dependents
481 unsigned int minDependentDepth = maxDepth;
482 for(unsigned int i=0; i < libraryCount(); ++i) {
483 ImageLoader* dependentImage = libImage(i);
484 if ( dependentImage != NULL ) {
485 unsigned int d = dependentImage->recursiveUpdateDepth(maxDepth);
486 if ( d < minDependentDepth )
487 minDependentDepth = d;
488 }
489 }
490
491 // make me less deep then all my dependents
492 fDepth = minDependentDepth - 1;
493 }
494
495 return fDepth;
496 }
497
498
499 void ImageLoader::recursiveLoadLibraries(const LinkContext& context, bool preflightOnly, const RPathChain& loaderRPaths)
500 {
501 if ( fState < dyld_image_state_dependents_mapped ) {
502 // break cycles
503 fState = dyld_image_state_dependents_mapped;
504
505 // get list of libraries this image needs
506 //dyld::log("ImageLoader::recursiveLoadLibraries() %ld = %d*%ld\n", fLibrariesCount*sizeof(DependentLibrary), fLibrariesCount, sizeof(DependentLibrary));
507 DependentLibraryInfo libraryInfos[fLibraryCount];
508 this->doGetDependentLibraries(libraryInfos);
509
510 // get list of rpaths that this image adds
511 std::vector<const char*> rpathsFromThisImage;
512 this->getRPaths(context, rpathsFromThisImage);
513 const RPathChain thisRPaths(&loaderRPaths, &rpathsFromThisImage);
514
515 // try to load each
516 bool canUsePrelinkingInfo = true;
517 for(unsigned int i=0; i < fLibraryCount; ++i){
518 ImageLoader* dependentLib;
519 bool depLibReExported = false;
520 bool depLibReRequired = false;
521 bool depLibCheckSumsMatch = false;
522 DependentLibraryInfo& requiredLibInfo = libraryInfos[i];
523 #if DYLD_SHARED_CACHE_SUPPORT
524 if ( preflightOnly && context.inSharedCache(requiredLibInfo.name) ) {
525 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
526 // in preflight mode, don't even load dylib that are in the shared cache because they will never be unloaded
527 setLibImage(i, NULL, false, false);
528 continue;
529 }
530 #endif
531 try {
532 dependentLib = context.loadLibrary(requiredLibInfo.name, true, this->getPath(), &thisRPaths);
533 if ( dependentLib == this ) {
534 // found circular reference, perhaps DYLD_LIBARY_PATH is causing this rdar://problem/3684168
535 dependentLib = context.loadLibrary(requiredLibInfo.name, false, NULL, NULL);
536 if ( dependentLib != this )
537 dyld::warn("DYLD_ setting caused circular dependency in %s\n", this->getPath());
538 }
539 if ( fNeverUnload )
540 dependentLib->setNeverUnload();
541 if ( ! requiredLibInfo.upward )
542 dependentLib->fStaticReferenceCount += 1;
543 LibraryInfo actualInfo = dependentLib->doGetLibraryInfo();
544 depLibReRequired = requiredLibInfo.required;
545 depLibCheckSumsMatch = ( actualInfo.checksum == requiredLibInfo.info.checksum );
546 depLibReExported = requiredLibInfo.reExported;
547 if ( ! depLibReExported ) {
548 // for pre-10.5 binaries that did not use LC_REEXPORT_DYLIB
549 depLibReExported = dependentLib->isSubframeworkOf(context, this) || this->hasSubLibrary(context, dependentLib);
550 }
551 // check found library version is compatible
552 if ( actualInfo.minVersion < requiredLibInfo.info.minVersion ) {
553 // record values for possible use by CrashReporter or Finder
554 dyld::throwf("Incompatible library version: %s requires version %d.%d.%d or later, but %s provides version %d.%d.%d",
555 this->getShortName(), requiredLibInfo.info.minVersion >> 16, (requiredLibInfo.info.minVersion >> 8) & 0xff, requiredLibInfo.info.minVersion & 0xff,
556 dependentLib->getShortName(), actualInfo.minVersion >> 16, (actualInfo.minVersion >> 8) & 0xff, actualInfo.minVersion & 0xff);
557 }
558 // prebinding for this image disabled if any dependent library changed
559 if ( !depLibCheckSumsMatch )
560 canUsePrelinkingInfo = false;
561 // prebinding for this image disabled unless both this and dependent are in the shared cache
562 if ( !dependentLib->inSharedCache() || !this->inSharedCache() )
563 canUsePrelinkingInfo = false;
564
565 //if ( context.verbosePrebinding ) {
566 // if ( !requiredLib.checksumMatches )
567 // fprintf(stderr, "dyld: checksum mismatch, (%u v %u) for %s referencing %s\n",
568 // requiredLibInfo.info.checksum, actualInfo.checksum, this->getPath(), dependentLib->getPath());
569 // if ( dependentLib->getSlide() != 0 )
570 // fprintf(stderr, "dyld: dependent library slid for %s referencing %s\n", this->getPath(), dependentLib->getPath());
571 //}
572 }
573 catch (const char* msg) {
574 //if ( context.verbosePrebinding )
575 // fprintf(stderr, "dyld: exception during processing for %s referencing %s\n", this->getPath(), dependentLib->getPath());
576 if ( requiredLibInfo.required ) {
577 fState = dyld_image_state_mapped;
578 // record values for possible use by CrashReporter or Finder
579 if ( strstr(msg, "Incompatible") != NULL )
580 (*context.setErrorStrings)(dyld_error_kind_dylib_version, this->getPath(), requiredLibInfo.name, NULL);
581 else if ( strstr(msg, "architecture") != NULL )
582 (*context.setErrorStrings)(dyld_error_kind_dylib_wrong_arch, this->getPath(), requiredLibInfo.name, NULL);
583 else
584 (*context.setErrorStrings)(dyld_error_kind_dylib_missing, this->getPath(), requiredLibInfo.name, NULL);
585 dyld::throwf("Library not loaded: %s\n Referenced from: %s\n Reason: %s", requiredLibInfo.name, this->getPath(), msg);
586 }
587 // ok if weak library not found
588 dependentLib = NULL;
589 canUsePrelinkingInfo = false; // this disables all prebinding, we may want to just slam import vectors for this lib to zero
590 }
591 setLibImage(i, dependentLib, depLibReExported, requiredLibInfo.upward);
592 }
593 fAllLibraryChecksumsAndLoadAddressesMatch = canUsePrelinkingInfo;
594
595 // tell each to load its dependents
596 for(unsigned int i=0; i < libraryCount(); ++i) {
597 ImageLoader* dependentImage = libImage(i);
598 if ( dependentImage != NULL ) {
599 dependentImage->recursiveLoadLibraries(context, preflightOnly, thisRPaths);
600 }
601 }
602
603 // do deep prebind check
604 if ( fAllLibraryChecksumsAndLoadAddressesMatch ) {
605 for(unsigned int i=0; i < libraryCount(); ++i){
606 ImageLoader* dependentImage = libImage(i);
607 if ( dependentImage != NULL ) {
608 if ( !dependentImage->allDependentLibrariesAsWhenPreBound() )
609 fAllLibraryChecksumsAndLoadAddressesMatch = false;
610 }
611 }
612 }
613
614 // free rpaths (getRPaths() malloc'ed each string)
615 for(std::vector<const char*>::iterator it=rpathsFromThisImage.begin(); it != rpathsFromThisImage.end(); ++it) {
616 const char* str = *it;
617 free((void*)str);
618 }
619
620 }
621 }
622
623 void ImageLoader::recursiveRebase(const LinkContext& context)
624 {
625 if ( fState < dyld_image_state_rebased ) {
626 // break cycles
627 fState = dyld_image_state_rebased;
628
629 try {
630 // rebase lower level libraries first
631 for(unsigned int i=0; i < libraryCount(); ++i) {
632 ImageLoader* dependentImage = libImage(i);
633 if ( dependentImage != NULL )
634 dependentImage->recursiveRebase(context);
635 }
636
637 // rebase this image
638 doRebase(context);
639
640 // notify
641 context.notifySingle(dyld_image_state_rebased, this);
642 }
643 catch (const char* msg) {
644 // this image is not rebased
645 fState = dyld_image_state_dependents_mapped;
646 CRSetCrashLogMessage2(NULL);
647 throw;
648 }
649 }
650 }
651
652 void ImageLoader::recursiveApplyInterposing(const LinkContext& context)
653 {
654 if ( ! fInterposed ) {
655 // break cycles
656 fInterposed = true;
657
658 try {
659 // interpose lower level libraries first
660 for(unsigned int i=0; i < libraryCount(); ++i) {
661 ImageLoader* dependentImage = libImage(i);
662 if ( dependentImage != NULL )
663 dependentImage->recursiveApplyInterposing(context);
664 }
665
666 // interpose this image
667 doInterpose(context);
668 }
669 catch (const char* msg) {
670 // this image is not interposed
671 fInterposed = false;
672 throw;
673 }
674 }
675 }
676
677
678
679 void ImageLoader::recursiveBind(const LinkContext& context, bool forceLazysBound)
680 {
681 // Normally just non-lazy pointers are bound immediately.
682 // The exceptions are:
683 // 1) DYLD_BIND_AT_LAUNCH will cause lazy pointers to be bound immediately
684 // 2) some API's (e.g. RTLD_NOW) can cause lazy pointers to be bound immediately
685 if ( fState < dyld_image_state_bound ) {
686 // break cycles
687 fState = dyld_image_state_bound;
688
689 try {
690 // bind lower level libraries first
691 for(unsigned int i=0; i < libraryCount(); ++i) {
692 ImageLoader* dependentImage = libImage(i);
693 if ( dependentImage != NULL )
694 dependentImage->recursiveBind(context, forceLazysBound);
695 }
696 // bind this image
697 this->doBind(context, forceLazysBound);
698 // mark if lazys are also bound
699 if ( forceLazysBound || this->usablePrebinding(context) )
700 fAllLazyPointersBound = true;
701
702 context.notifySingle(dyld_image_state_bound, this);
703 }
704 catch (const char* msg) {
705 // restore state
706 fState = dyld_image_state_rebased;
707 CRSetCrashLogMessage2(NULL);
708 throw;
709 }
710 }
711 }
712
713 void ImageLoader::weakBind(const LinkContext& context)
714 {
715 if ( context.verboseWeakBind )
716 dyld::log("dyld: weak bind start:\n");
717 // get set of ImageLoaders that participate in coalecsing
718 ImageLoader* imagesNeedingCoalescing[fgImagesRequiringCoalescing];
719 int count = context.getCoalescedImages(imagesNeedingCoalescing);
720
721 // count how many have not already had weakbinding done
722 int countNotYetWeakBound = 0;
723 int countOfImagesWithWeakDefinitions = 0;
724 int countOfImagesWithWeakDefinitionsNotInSharedCache = 0;
725 for(int i=0; i < count; ++i) {
726 if ( ! imagesNeedingCoalescing[i]->fWeakSymbolsBound )
727 ++countNotYetWeakBound;
728 if ( imagesNeedingCoalescing[i]->hasCoalescedExports() ) {
729 ++countOfImagesWithWeakDefinitions;
730 if ( ! imagesNeedingCoalescing[i]->inSharedCache() )
731 ++countOfImagesWithWeakDefinitionsNotInSharedCache;
732 }
733 }
734
735 // don't need to do any coalescing if only one image has overrides, or all have already been done
736 if ( (countOfImagesWithWeakDefinitionsNotInSharedCache > 0) && (countNotYetWeakBound > 0) ) {
737 // make symbol iterators for each
738 ImageLoader::CoalIterator iterators[count];
739 ImageLoader::CoalIterator* sortedIts[count];
740 for(int i=0; i < count; ++i) {
741 imagesNeedingCoalescing[i]->initializeCoalIterator(iterators[i], i);
742 sortedIts[i] = &iterators[i];
743 if ( context.verboseWeakBind )
744 dyld::log("dyld: weak bind load order %d/%d for %s\n", i, count, imagesNeedingCoalescing[i]->getPath());
745 }
746
747 // walk all symbols keeping iterators in sync by
748 // only ever incrementing the iterator with the lowest symbol
749 int doneCount = 0;
750 while ( doneCount != count ) {
751 //for(int i=0; i < count; ++i)
752 // dyld::log("sym[%d]=%s ", sortedIts[i]->loadOrder, sortedIts[i]->symbolName);
753 //dyld::log("\n");
754 // increment iterator with lowest symbol
755 if ( sortedIts[0]->image->incrementCoalIterator(*sortedIts[0]) )
756 ++doneCount;
757 // re-sort iterators
758 for(int i=1; i < count; ++i) {
759 int result = strcmp(sortedIts[i-1]->symbolName, sortedIts[i]->symbolName);
760 if ( result == 0 )
761 sortedIts[i-1]->symbolMatches = true;
762 if ( result > 0 ) {
763 // new one is bigger then next, so swap
764 ImageLoader::CoalIterator* temp = sortedIts[i-1];
765 sortedIts[i-1] = sortedIts[i];
766 sortedIts[i] = temp;
767 }
768 if ( result < 0 )
769 break;
770 }
771 // process all matching symbols just before incrementing the lowest one that matches
772 if ( sortedIts[0]->symbolMatches && !sortedIts[0]->done ) {
773 const char* nameToCoalesce = sortedIts[0]->symbolName;
774 // pick first symbol in load order (and non-weak overrides weak)
775 uintptr_t targetAddr = 0;
776 ImageLoader* targetImage = NULL;
777 for(int i=0; i < count; ++i) {
778 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
779 if ( context.verboseWeakBind )
780 dyld::log("dyld: weak bind, found %s weak=%d in %s \n", nameToCoalesce, iterators[i].weakSymbol, iterators[i].image->getPath());
781 if ( iterators[i].weakSymbol ) {
782 if ( targetAddr == 0 ) {
783 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
784 if ( targetAddr != 0 )
785 targetImage = iterators[i].image;
786 }
787 }
788 else {
789 targetAddr = iterators[i].image->getAddressCoalIterator(iterators[i], context);
790 if ( targetAddr != 0 ) {
791 targetImage = iterators[i].image;
792 // strong implementation found, stop searching
793 break;
794 }
795 }
796 }
797 }
798 if ( context.verboseWeakBind )
799 dyld::log("dyld: weak binding all uses of %s to copy from %s\n", nameToCoalesce, targetImage->getShortName());
800
801 // tell each to bind to this symbol (unless already bound)
802 if ( targetAddr != 0 ) {
803 for(int i=0; i < count; ++i) {
804 if ( strcmp(iterators[i].symbolName, nameToCoalesce) == 0 ) {
805 if ( context.verboseWeakBind )
806 dyld::log("dyld: weak bind, setting all uses of %s in %s to 0x%lX from %s\n", nameToCoalesce, iterators[i].image->getShortName(), targetAddr, targetImage->getShortName());
807 if ( ! iterators[i].image->fWeakSymbolsBound )
808 iterators[i].image->updateUsesCoalIterator(iterators[i], targetAddr, targetImage, context);
809 iterators[i].symbolMatches = false;
810 }
811 }
812 }
813
814 }
815 }
816
817 // mark all as having all weak symbols bound
818 for(int i=0; i < count; ++i) {
819 imagesNeedingCoalescing[i]->fWeakSymbolsBound = true;
820 }
821 }
822 if ( context.verboseWeakBind )
823 dyld::log("dyld: weak bind end\n");
824 }
825
826
827
828 void ImageLoader::recursiveGetDOFSections(const LinkContext& context, std::vector<DOFInfo>& dofs)
829 {
830 if ( ! fRegisteredDOF ) {
831 // break cycles
832 fRegisteredDOF = true;
833
834 // gather lower level libraries first
835 for(unsigned int i=0; i < libraryCount(); ++i) {
836 ImageLoader* dependentImage = libImage(i);
837 if ( dependentImage != NULL )
838 dependentImage->recursiveGetDOFSections(context, dofs);
839 }
840 this->doGetDOFSections(context, dofs);
841 }
842 }
843
844
845 void ImageLoader::recursiveSpinLock(recursive_lock& rlock)
846 {
847 // try to set image's ivar fInitializerRecursiveLock to point to this lock_info
848 // keep trying until success (spin)
849 while ( ! OSAtomicCompareAndSwapPtrBarrier(NULL, &rlock, (void**)&fInitializerRecursiveLock) ) {
850 // if fInitializerRecursiveLock already points to a different lock_info, if it is for
851 // the same thread we are on, the increment the lock count, otherwise continue to spin
852 if ( (fInitializerRecursiveLock != NULL) && (fInitializerRecursiveLock->thread == rlock.thread) )
853 break;
854 }
855 ++(fInitializerRecursiveLock->count);
856 }
857
858 void ImageLoader::recursiveSpinUnLock()
859 {
860 if ( --(fInitializerRecursiveLock->count) == 0 )
861 fInitializerRecursiveLock = NULL;
862 }
863
864
865 void ImageLoader::recursiveInitialization(const LinkContext& context, mach_port_t this_thread, InitializerTimingList& timingInfo)
866 {
867 recursive_lock lock_info(this_thread);
868 recursiveSpinLock(lock_info);
869
870 if ( fState < dyld_image_state_dependents_initialized-1 ) {
871 uint8_t oldState = fState;
872 // break cycles
873 fState = dyld_image_state_dependents_initialized-1;
874 try {
875 // initialize lower level libraries first
876 for(unsigned int i=0; i < libraryCount(); ++i) {
877 ImageLoader* dependentImage = libImage(i);
878 if ( dependentImage != NULL )
879 // don't try to initialize stuff "above" me
880 if ( (dependentImage != NULL) && (dependentImage->fDepth >= fDepth) && !libIsUpward(i) )
881 dependentImage->recursiveInitialization(context, this_thread, timingInfo);
882 }
883
884 // record termination order
885 if ( this->needsTermination() )
886 context.terminationRecorder(this);
887
888 // let objc know we are about to initalize this image
889 uint64_t t1 = mach_absolute_time();
890 fState = dyld_image_state_dependents_initialized;
891 oldState = fState;
892 context.notifySingle(dyld_image_state_dependents_initialized, this);
893
894 // initialize this image
895 bool hasInitializers = this->doInitialization(context);
896
897 // let anyone know we finished initalizing this image
898 fState = dyld_image_state_initialized;
899 oldState = fState;
900 context.notifySingle(dyld_image_state_initialized, this);
901
902 if ( hasInitializers ) {
903 uint64_t t2 = mach_absolute_time();
904 timingInfo.images[timingInfo.count].image = this;
905 timingInfo.images[timingInfo.count].initTime = (t2-t1);
906 timingInfo.count++;
907 }
908 }
909 catch (const char* msg) {
910 // this image is not initialized
911 fState = oldState;
912 recursiveSpinUnLock();
913 throw;
914 }
915 }
916
917 recursiveSpinUnLock();
918 }
919
920
921 static void printTime(const char* msg, uint64_t partTime, uint64_t totalTime)
922 {
923 static uint64_t sUnitsPerSecond = 0;
924 if ( sUnitsPerSecond == 0 ) {
925 struct mach_timebase_info timeBaseInfo;
926 if ( mach_timebase_info(&timeBaseInfo) == KERN_SUCCESS ) {
927 sUnitsPerSecond = 1000000000ULL * timeBaseInfo.denom / timeBaseInfo.numer;
928 }
929 }
930 if ( partTime < sUnitsPerSecond ) {
931 uint32_t milliSecondsTimesHundred = (partTime*100000)/sUnitsPerSecond;
932 uint32_t milliSeconds = milliSecondsTimesHundred/100;
933 uint32_t percentTimesTen = (partTime*1000)/totalTime;
934 uint32_t percent = percentTimesTen/10;
935 dyld::log("%s: %u.%02u milliseconds (%u.%u%%)\n", msg, milliSeconds, milliSecondsTimesHundred-milliSeconds*100, percent, percentTimesTen-percent*10);
936 }
937 else {
938 uint32_t secondsTimeTen = (partTime*10)/sUnitsPerSecond;
939 uint32_t seconds = secondsTimeTen/10;
940 uint32_t percentTimesTen = (partTime*1000)/totalTime;
941 uint32_t percent = percentTimesTen/10;
942 dyld::log("%s: %u.%u seconds (%u.%u%%)\n", msg, seconds, secondsTimeTen-seconds*10, percent, percentTimesTen-percent*10);
943 }
944 }
945
946 static char* commatize(uint64_t in, char* out)
947 {
948 uint64_t div10 = in / 10;
949 uint8_t delta = in - div10*10;
950 char* s = &out[32];
951 int digitCount = 1;
952 *s = '\0';
953 *(--s) = '0' + delta;
954 in = div10;
955 while ( in != 0 ) {
956 if ( (digitCount % 3) == 0 )
957 *(--s) = ',';
958 div10 = in / 10;
959 delta = in - div10*10;
960 *(--s) = '0' + delta;
961 in = div10;
962 ++digitCount;
963 }
964 return s;
965 }
966
967
968 void ImageLoader::printStatistics(unsigned int imageCount, const InitializerTimingList& timingInfo)
969 {
970 uint64_t totalTime = fgTotalLoadLibrariesTime + fgTotalRebaseTime + fgTotalBindTime + fgTotalWeakBindTime + fgTotalDOF + fgTotalInitTime;
971 char commaNum1[40];
972 char commaNum2[40];
973
974 printTime("total time", totalTime, totalTime);
975 #if __IPHONE_OS_VERSION_MIN_REQUIRED
976 if ( fgImagesUsedFromSharedCache != 0 )
977 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
978 else
979 dyld::log("total images loaded: %d\n", imageCount);
980 #else
981 dyld::log("total images loaded: %d (%u from dyld shared cache)\n", imageCount, fgImagesUsedFromSharedCache);
982 #endif
983 dyld::log("total segments mapped: %u, into %llu pages with %llu pages pre-fetched\n", fgTotalSegmentsMapped, fgTotalBytesMapped/4096, fgTotalBytesPreFetched/4096);
984 printTime("total images loading time", fgTotalLoadLibrariesTime, totalTime);
985 printTime("total dtrace DOF registration time", fgTotalDOF, totalTime);
986 dyld::log("total rebase fixups: %s\n", commatize(fgTotalRebaseFixups, commaNum1));
987 printTime("total rebase fixups time", fgTotalRebaseTime, totalTime);
988 dyld::log("total binding fixups: %s\n", commatize(fgTotalBindFixups, commaNum1));
989 if ( fgTotalBindSymbolsResolved != 0 ) {
990 uint32_t avgTimesTen = (fgTotalBindImageSearches * 10) / fgTotalBindSymbolsResolved;
991 uint32_t avgInt = fgTotalBindImageSearches / fgTotalBindSymbolsResolved;
992 uint32_t avgTenths = avgTimesTen - (avgInt*10);
993 dyld::log("total binding symbol lookups: %s, average images searched per symbol: %u.%u\n",
994 commatize(fgTotalBindSymbolsResolved, commaNum1), avgInt, avgTenths);
995 }
996 printTime("total binding fixups time", fgTotalBindTime, totalTime);
997 printTime("total weak binding fixups time", fgTotalWeakBindTime, totalTime);
998 dyld::log("total bindings lazily fixed up: %s of %s\n", commatize(fgTotalLazyBindFixups, commaNum1), commatize(fgTotalPossibleLazyBindFixups, commaNum2));
999 printTime("total initializer time", fgTotalInitTime, totalTime);
1000 for (uintptr_t i=0; i < timingInfo.count; ++i) {
1001 dyld::log("%21s ", timingInfo.images[i].image->getShortName());
1002 printTime("", timingInfo.images[i].initTime, totalTime);
1003 }
1004
1005 }
1006
1007
1008 //
1009 // copy path and add suffix to result
1010 //
1011 // /path/foo.dylib _debug => /path/foo_debug.dylib
1012 // foo.dylib _debug => foo_debug.dylib
1013 // foo _debug => foo_debug
1014 // /path/bar _debug => /path/bar_debug
1015 // /path/bar.A.dylib _debug => /path/bar.A_debug.dylib
1016 //
1017 void ImageLoader::addSuffix(const char* path, const char* suffix, char* result)
1018 {
1019 strcpy(result, path);
1020
1021 char* start = strrchr(result, '/');
1022 if ( start != NULL )
1023 start++;
1024 else
1025 start = result;
1026
1027 char* dot = strrchr(start, '.');
1028 if ( dot != NULL ) {
1029 strcpy(dot, suffix);
1030 strcat(&dot[strlen(suffix)], &path[dot-result]);
1031 }
1032 else {
1033 strcat(result, suffix);
1034 }
1035 }
1036
1037
1038
1039