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