dyld-551.3.tar.gz
[apple/dyld.git] / src / dyld.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2013 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 #include <stdint.h>
26 #include <string.h>
27 #include <unistd.h>
28 #include <errno.h>
29 #include <fcntl.h>
30 #include <dirent.h>
31 #include <pthread.h>
32 #include <libproc.h>
33 #include <sys/param.h>
34 #include <mach/mach_time.h> // mach_absolute_time()
35 #include <mach/mach_init.h>
36 #include <sys/types.h>
37 #include <sys/stat.h>
38 #include <sys/syscall.h>
39 #include <sys/socket.h>
40 #include <sys/un.h>
41 #include <sys/syslog.h>
42 #include <sys/uio.h>
43 #include <sys/xattr.h>
44 #include <mach/mach.h>
45 #include <mach-o/fat.h>
46 #include <mach-o/loader.h>
47 #include <mach-o/ldsyms.h>
48 #include <libkern/OSByteOrder.h>
49 #include <libkern/OSAtomic.h>
50 #include <mach/mach.h>
51 #include <sys/sysctl.h>
52 #include <sys/mman.h>
53 #include <sys/dtrace.h>
54 #include <libkern/OSAtomic.h>
55 #include <Availability.h>
56 #include <System/sys/codesign.h>
57 #include <System/sys/csr.h>
58 #include <_simple.h>
59 #include <os/lock_private.h>
60 #include <System/machine/cpu_capabilities.h>
61 #include <System/sys/reason.h>
62 #include <kern/kcdata.h>
63 #include <sandbox.h>
64 #include <sandbox/private.h>
65
66 extern "C" int __fork();
67
68 #include <array>
69 #include <algorithm>
70 #include <vector>
71
72 #ifndef CPU_SUBTYPE_ARM_V5TEJ
73 #define CPU_SUBTYPE_ARM_V5TEJ ((cpu_subtype_t) 7)
74 #endif
75 #ifndef CPU_SUBTYPE_ARM_XSCALE
76 #define CPU_SUBTYPE_ARM_XSCALE ((cpu_subtype_t) 8)
77 #endif
78 #ifndef CPU_SUBTYPE_ARM_V7
79 #define CPU_SUBTYPE_ARM_V7 ((cpu_subtype_t) 9)
80 #endif
81 #ifndef CPU_SUBTYPE_ARM_V7F
82 #define CPU_SUBTYPE_ARM_V7F ((cpu_subtype_t) 10)
83 #endif
84 #ifndef CPU_SUBTYPE_ARM_V7S
85 #define CPU_SUBTYPE_ARM_V7S ((cpu_subtype_t) 11)
86 #endif
87 #ifndef CPU_SUBTYPE_ARM_V7K
88 #define CPU_SUBTYPE_ARM_V7K ((cpu_subtype_t) 12)
89 #endif
90 #ifndef LC_DYLD_ENVIRONMENT
91 #define LC_DYLD_ENVIRONMENT 0x27
92 #endif
93
94 #ifndef CPU_SUBTYPE_X86_64_H
95 #define CPU_SUBTYPE_X86_64_H ((cpu_subtype_t) 8)
96 #endif
97
98 #ifndef CPU_SUBTYPE_ARM64_E
99 #define CPU_SUBTYPE_ARM64_E 2
100 #endif
101
102 #ifndef VM_PROT_SLIDE
103 #define VM_PROT_SLIDE 0x20
104 #endif
105
106 #include "mach-o/dyld_gdb.h"
107
108 #include "dyld.h"
109 #include "ImageLoader.h"
110 #include "ImageLoaderMachO.h"
111 #include "dyldLibSystemInterface.h"
112 #include "dyld_cache_format.h"
113 #include "dyld_process_info_internal.h"
114 #include <coreSymbolicationDyldSupport.h>
115 #if TARGET_IPHONE_SIMULATOR
116 extern "C" void xcoresymbolication_load_notifier(void *connection, uint64_t load_timestamp, const char *image_path, const struct mach_header *mach_header);
117 extern "C" void xcoresymbolication_unload_notifier(void *connection, uint64_t unload_timestamp, const char *image_path, const struct mach_header *mach_header);
118 #define coresymbolication_load_notifier(c, t, p, h) xcoresymbolication_load_notifier(c, t, p, h)
119 #define coresymbolication_unload_notifier(c, t, p, h) xcoresymbolication_unload_notifier(c, t, p, h)
120 #endif
121
122 #if SUPPORT_ACCELERATE_TABLES
123 #include "ImageLoaderMegaDylib.h"
124 #endif
125
126 #if TARGET_IPHONE_SIMULATOR
127 extern "C" void* gSyscallHelpers;
128 #else
129 #include "dyldSyscallInterface.h"
130 #endif
131
132 #include "LaunchCache.h"
133 #include "libdyldEntryVector.h"
134 #include "MachOParser.h"
135 #include "Loading.h"
136 #include "DyldSharedCache.h"
137 #include "SharedCacheRuntime.h"
138 #include "StringUtils.h"
139 #include "Tracing.h"
140 #include "DyldCacheParser.h"
141
142 extern "C" {
143 #include "closuredProtocol.h"
144 }
145
146
147 // not libc header for send() syscall interface
148 extern "C" ssize_t __sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
149
150
151 // ARM and x86_64 are the only architecture that use cpu-sub-types
152 #define CPU_SUBTYPES_SUPPORTED ((__arm__ || __arm64__ || __x86_64__) && !TARGET_IPHONE_SIMULATOR)
153
154 #if __LP64__
155 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
156 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
157 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO
158 #define macho_segment_command segment_command_64
159 #define macho_section section_64
160 #else
161 #define LC_SEGMENT_COMMAND LC_SEGMENT
162 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
163 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO_64
164 #define macho_segment_command segment_command
165 #define macho_section section
166 #endif
167
168
169
170 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
171
172
173 /* implemented in dyld_gdb.cpp */
174 extern void resetAllImages();
175 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
176 extern void removeImageFromAllImages(const mach_header* mh);
177 extern void addNonSharedCacheImageUUID(const dyld_uuid_info& info);
178 extern const char* notifyGDB(enum dyld_image_states state, uint32_t infoCount, const dyld_image_info info[]);
179 extern size_t allImagesCount();
180
181 // magic so CrashReporter logs message
182 extern "C" {
183 char error_string[1024];
184 }
185
186 // magic linker symbol for start of dyld binary
187 extern "C" const macho_header __dso_handle;
188
189
190 //
191 // The file contains the core of dyld used to get a process to main().
192 // The API's that dyld supports are implemented in dyldAPIs.cpp.
193 //
194 //
195 //
196 //
197 //
198 namespace dyld {
199 struct RegisteredDOF { const mach_header* mh; int registrationID; };
200 struct DylibOverride { const char* installName; const char* override; };
201 }
202
203
204 VECTOR_NEVER_DESTRUCTED(ImageLoader*);
205 VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF);
206 VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback);
207 VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride);
208 VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference);
209
210 VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler);
211
212 namespace dyld {
213
214
215 //
216 // state of all environment variables dyld uses
217 //
218 struct EnvironmentVariables {
219 const char* const * DYLD_FRAMEWORK_PATH;
220 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH;
221 const char* const * DYLD_LIBRARY_PATH;
222 const char* const * DYLD_FALLBACK_LIBRARY_PATH;
223 const char* const * DYLD_INSERT_LIBRARIES;
224 const char* const * LD_LIBRARY_PATH; // for unix conformance
225 const char* const * DYLD_VERSIONED_LIBRARY_PATH;
226 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH;
227 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH;
228 bool DYLD_BIND_AT_LAUNCH;
229 bool DYLD_PRINT_STATISTICS;
230 bool DYLD_PRINT_STATISTICS_DETAILS;
231 bool DYLD_PRINT_OPTS;
232 bool DYLD_PRINT_ENV;
233 bool DYLD_DISABLE_DOFS;
234 bool DYLD_PRINT_CS_NOTIFICATIONS;
235 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheOverrideDir
236 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
237 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
238 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
239 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
240 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
241 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
242 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
243 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
244 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
245 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
246 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
247 // DYLD_PRINT_APIS ==> gLogAPIs
248 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
249 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
250 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
251 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
252 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
253 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
254 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
255 // DYLD_PRINT_LIBRARIES ==> gLinkContext.verboseLoading
256 };
257
258
259
260 typedef std::vector<dyld_image_state_change_handler> StateHandlers;
261
262
263 enum EnvVarMode { envNone, envPrintOnly, envAll };
264
265 // all global state
266 static const char* sExecPath = NULL;
267 static const char* sExecShortName = NULL;
268 static const macho_header* sMainExecutableMachHeader = NULL;
269 static uintptr_t sMainExecutableSlide = 0;
270 #if CPU_SUBTYPES_SUPPORTED
271 static cpu_type_t sHostCPU;
272 static cpu_subtype_t sHostCPUsubtype;
273 #endif
274 static ImageLoaderMachO* sMainExecutable = NULL;
275 static EnvVarMode sEnvMode = envNone;
276 static size_t sInsertedDylibCount = 0;
277 static std::vector<ImageLoader*> sAllImages;
278 static std::vector<ImageLoader*> sImageRoots;
279 static std::vector<ImageLoader*> sImageFilesNeedingTermination;
280 static std::vector<RegisteredDOF> sImageFilesNeedingDOFUnregistration;
281 static std::vector<ImageCallback> sAddImageCallbacks;
282 static std::vector<ImageCallback> sRemoveImageCallbacks;
283 static bool sRemoveImageCallbacksInUse = false;
284 static void* sSingleHandlers[7][3];
285 static void* sBatchHandlers[7][3];
286 static ImageLoader* sLastImageByAddressCache;
287 static EnvironmentVariables sEnv;
288 #if __MAC_OS_X_VERSION_MIN_REQUIRED
289 static const char* sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
290 static const char* sLibraryFallbackPaths[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL };
291 static const char* sRestrictedFrameworkFallbackPaths[] = { "/System/Library/Frameworks", NULL };
292 static const char* sRestrictedLibraryFallbackPaths[] = { "/usr/lib", NULL };
293 #else
294 static const char* sFrameworkFallbackPaths[] = { "/System/Library/Frameworks", NULL };
295 static const char* sLibraryFallbackPaths[] = { "/usr/local/lib", "/usr/lib", NULL };
296 #endif
297 static UndefinedHandler sUndefinedHandler = NULL;
298 static ImageLoader* sBundleBeingLoaded = NULL; // hack until OFI is reworked
299 static dyld3::SharedCacheLoadInfo sSharedCacheLoadInfo;
300 static const char* sSharedCacheOverrideDir;
301 bool gSharedCacheOverridden = false;
302 ImageLoader::LinkContext gLinkContext;
303 bool gLogAPIs = false;
304 #if SUPPORT_ACCELERATE_TABLES
305 bool gLogAppAPIs = false;
306 #endif
307 const struct LibSystemHelpers* gLibSystemHelpers = NULL;
308 #if SUPPORT_OLD_CRT_INITIALIZATION
309 bool gRunInitializersOldWay = false;
310 #endif
311 static std::vector<DylibOverride> sDylibOverrides;
312 #if !TARGET_IPHONE_SIMULATOR
313 static int sLogSocket = -1;
314 #endif
315 static bool sFrameworksFoundAsDylibs = false;
316 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
317 static bool sHaswell = false;
318 #endif
319 static std::vector<ImageLoader::DynamicReference> sDynamicReferences;
320 static OSSpinLock sDynamicReferencesLock = 0;
321 #if !TARGET_IPHONE_SIMULATOR
322 static bool sLogToFile = false;
323 #endif
324 static char sLoadingCrashMessage[1024] = "dyld: launch, loading dependent libraries";
325 static bool sSafeMode = false;
326 static _dyld_objc_notify_mapped sNotifyObjCMapped;
327 static _dyld_objc_notify_init sNotifyObjCInit;
328 static _dyld_objc_notify_unmapped sNotifyObjCUnmapped;
329
330 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
331 static bool sForceStderr = false;
332 #endif
333
334
335 #if SUPPORT_ACCELERATE_TABLES
336 static ImageLoaderMegaDylib* sAllCacheImagesProxy = NULL;
337 static bool sDisableAcceleratorTables = false;
338 #endif
339
340 bool gUseDyld3 = false;
341 static bool sSkipMain = false;
342 static bool sEnableClosures = false;
343
344 //
345 // The MappedRanges structure is used for fast address->image lookups.
346 // The table is only updated when the dyld lock is held, so we don't
347 // need to worry about multiple writers. But readers may look at this
348 // data without holding the lock. Therefore, all updates must be done
349 // in an order that will never cause readers to see inconsistent data.
350 // The general rule is that if the image field is non-NULL then
351 // the other fields are valid.
352 //
353 struct MappedRanges
354 {
355 MappedRanges* next;
356 unsigned long count;
357 struct {
358 ImageLoader* image;
359 uintptr_t start;
360 uintptr_t end;
361 } array[1];
362 };
363
364 static MappedRanges* sMappedRangesStart;
365
366 void addMappedRange(ImageLoader* image, uintptr_t start, uintptr_t end)
367 {
368 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
369 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
370 for (unsigned long i=0; i < p->count; ++i) {
371 if ( p->array[i].image == NULL ) {
372 p->array[i].start = start;
373 p->array[i].end = end;
374 // add image field last with a barrier so that any reader will see consistent records
375 OSMemoryBarrier();
376 p->array[i].image = image;
377 return;
378 }
379 }
380 }
381 // table must be full, chain another
382 #if SUPPORT_ACCELERATE_TABLES
383 unsigned count = (sAllCacheImagesProxy != NULL) ? 16 : 400;
384 #else
385 unsigned count = 400;
386 #endif
387 size_t allocationSize = sizeof(MappedRanges) + (count-1)*3*sizeof(void*);
388 MappedRanges* newRanges = (MappedRanges*)malloc(allocationSize);
389 bzero(newRanges, allocationSize);
390 newRanges->count = count;
391 newRanges->array[0].start = start;
392 newRanges->array[0].end = end;
393 newRanges->array[0].image = image;
394 OSMemoryBarrier();
395 if ( sMappedRangesStart == NULL ) {
396 sMappedRangesStart = newRanges;
397 }
398 else {
399 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
400 if ( p->next == NULL ) {
401 OSMemoryBarrier();
402 p->next = newRanges;
403 break;
404 }
405 }
406 }
407 }
408
409 void removedMappedRanges(ImageLoader* image)
410 {
411 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
412 for (unsigned long i=0; i < p->count; ++i) {
413 if ( p->array[i].image == image ) {
414 // clear with a barrier so that any reader will see consistent records
415 OSMemoryBarrier();
416 p->array[i].image = NULL;
417 }
418 }
419 }
420 }
421
422 ImageLoader* findMappedRange(uintptr_t target)
423 {
424 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
425 for (unsigned long i=0; i < p->count; ++i) {
426 if ( p->array[i].image != NULL ) {
427 if ( (p->array[i].start <= target) && (target < p->array[i].end) )
428 return p->array[i].image;
429 }
430 }
431 }
432 return NULL;
433 }
434
435
436
437 const char* mkstringf(const char* format, ...)
438 {
439 _SIMPLE_STRING buf = _simple_salloc();
440 if ( buf != NULL ) {
441 va_list list;
442 va_start(list, format);
443 _simple_vsprintf(buf, format, list);
444 va_end(list);
445 const char* t = strdup(_simple_string(buf));
446 _simple_sfree(buf);
447 if ( t != NULL )
448 return t;
449 }
450 return "mkstringf, out of memory error";
451 }
452
453
454 void throwf(const char* format, ...)
455 {
456 _SIMPLE_STRING buf = _simple_salloc();
457 if ( buf != NULL ) {
458 va_list list;
459 va_start(list, format);
460 _simple_vsprintf(buf, format, list);
461 va_end(list);
462 const char* t = strdup(_simple_string(buf));
463 _simple_sfree(buf);
464 if ( t != NULL )
465 throw t;
466 }
467 throw "throwf, out of memory error";
468 }
469
470
471 #if !TARGET_IPHONE_SIMULATOR
472 static int sLogfile = STDERR_FILENO;
473 #endif
474
475 #if !TARGET_IPHONE_SIMULATOR
476 // based on CFUtilities.c: also_do_stderr()
477 static bool useSyslog()
478 {
479 // Use syslog() for processes managed by launchd
480 static bool launchdChecked = false;
481 static bool launchdOwned = false;
482 if ( !launchdChecked && gProcessInfo->libSystemInitialized ) {
483 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 11) ) {
484 // <rdar://problem/23520449> only call isLaunchdOwned() after libSystem is initialized
485 launchdOwned = (*gLibSystemHelpers->isLaunchdOwned)();
486 launchdChecked = true;
487 }
488 }
489 if ( launchdChecked && launchdOwned )
490 return true;
491
492 // If stderr is not available, use syslog()
493 struct stat sb;
494 int result = fstat(STDERR_FILENO, &sb);
495 if ( result < 0 )
496 return true; // file descriptor 2 is closed
497
498 return false;
499 }
500
501
502 static void socket_syslogv(int priority, const char* format, va_list list)
503 {
504 // lazily create socket and connection to syslogd
505 if ( sLogSocket == -1 ) {
506 sLogSocket = ::socket(AF_UNIX, SOCK_DGRAM, 0);
507 if (sLogSocket == -1)
508 return; // cannot log
509 ::fcntl(sLogSocket, F_SETFD, 1);
510
511 struct sockaddr_un addr;
512 addr.sun_family = AF_UNIX;
513 strncpy(addr.sun_path, _PATH_LOG, sizeof(addr.sun_path));
514 if ( ::connect(sLogSocket, (struct sockaddr *)&addr, sizeof(addr)) == -1 ) {
515 ::close(sLogSocket);
516 sLogSocket = -1;
517 return;
518 }
519 }
520
521 // format message to syslogd like: "<priority>Process[pid]: message"
522 _SIMPLE_STRING buf = _simple_salloc();
523 if ( buf == NULL )
524 return;
525 if ( _simple_sprintf(buf, "<%d>%s[%d]: ", LOG_USER|LOG_NOTICE, sExecShortName, getpid()) == 0 ) {
526 if ( _simple_vsprintf(buf, format, list) == 0 ) {
527 const char* p = _simple_string(buf);
528 ::__sendto(sLogSocket, p, strlen(p), 0, NULL, 0);
529 }
530 }
531 _simple_sfree(buf);
532 }
533
534
535
536 void vlog(const char* format, va_list list)
537 {
538 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
539 // <rdar://problem/25965832> log to console when running iOS app from Xcode
540 if ( !sLogToFile && !sForceStderr && useSyslog() )
541 #else
542 if ( !sLogToFile && useSyslog() )
543 #endif
544 socket_syslogv(LOG_ERR, format, list);
545 else {
546 _simple_vdprintf(sLogfile, format, list);
547 }
548 }
549
550 void log(const char* format, ...)
551 {
552 va_list list;
553 va_start(list, format);
554 vlog(format, list);
555 va_end(list);
556 }
557
558
559 void vwarn(const char* format, va_list list)
560 {
561 _simple_dprintf(sLogfile, "dyld: warning, ");
562 _simple_vdprintf(sLogfile, format, list);
563 }
564
565 void warn(const char* format, ...)
566 {
567 va_list list;
568 va_start(list, format);
569 vwarn(format, list);
570 va_end(list);
571 }
572
573 #else
574 extern void vlog(const char* format, va_list list);
575 #endif // !TARGET_IPHONE_SIMULATOR
576
577
578 // <rdar://problem/8867781> control access to sAllImages through a lock
579 // because global dyld lock is not held during initialization phase of dlopen()
580 // <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
581 static OSSpinLock sAllImagesLock = 0;
582
583 static void allImagesLock()
584 {
585 OSSpinLockLock(&sAllImagesLock);
586 }
587
588 static void allImagesUnlock()
589 {
590 OSSpinLockUnlock(&sAllImagesLock);
591 }
592
593
594 // utility class to assure files are closed when an exception is thrown
595 class FileOpener {
596 public:
597 FileOpener(const char* path);
598 ~FileOpener();
599 int getFileDescriptor() { return fd; }
600 private:
601 int fd;
602 };
603
604 FileOpener::FileOpener(const char* path)
605 : fd(-1)
606 {
607 fd = my_open(path, O_RDONLY, 0);
608 }
609
610 FileOpener::~FileOpener()
611 {
612 if ( fd != -1 )
613 close(fd);
614 }
615
616
617 static void registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
618 {
619 const size_t dofSectionCount = dofs.size();
620 if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
621 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
622 if ( fd < 0 ) {
623 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
624 }
625 else {
626 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
627 uint8_t buffer[sizeof(dof_ioctl_data_t) + dofSectionCount*sizeof(dof_helper_t)];
628 dof_ioctl_data_t* ioctlData = (dof_ioctl_data_t*)buffer;
629
630 // fill in buffer with one dof_helper_t per DOF section
631 ioctlData->dofiod_count = dofSectionCount;
632 for (unsigned int i=0; i < dofSectionCount; ++i) {
633 strlcpy(ioctlData->dofiod_helpers[i].dofhp_mod, dofs[i].imageShortName, DTRACE_MODNAMELEN);
634 ioctlData->dofiod_helpers[i].dofhp_dof = (uintptr_t)(dofs[i].dof);
635 ioctlData->dofiod_helpers[i].dofhp_addr = (uintptr_t)(dofs[i].dof);
636 }
637
638 // tell kernel about all DOF sections en mas
639 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
640 user_addr_t val = (user_addr_t)(unsigned long)ioctlData;
641 if ( ioctl(fd, DTRACEHIOC_ADDDOF, &val) != -1 ) {
642 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
643 for (unsigned int i=0; i < dofSectionCount; ++i) {
644 RegisteredDOF info;
645 info.mh = dofs[i].imageHeader;
646 info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
647 sImageFilesNeedingDOFUnregistration.push_back(info);
648 if ( gLinkContext.verboseDOF ) {
649 dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n",
650 dofs[i].dof, dofs[i].imageShortName, info.registrationID);
651 }
652 }
653 }
654 else {
655 //dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
656 }
657 close(fd);
658 }
659 }
660 }
661
662 static void unregisterDOF(int registrationID)
663 {
664 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
665 if ( fd < 0 ) {
666 dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to unregister dtrace DOF section\n");
667 }
668 else {
669 ioctl(fd, DTRACEHIOC_REMOVE, registrationID);
670 close(fd);
671 if ( gLinkContext.verboseInit )
672 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID);
673 }
674 }
675
676
677 //
678 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
679 //
680 static void notifyAddImageCallbacks(ImageLoader* image)
681 {
682 // use guard so that we cannot notify about the same image twice
683 if ( ! image->addFuncNotified() ) {
684 for (std::vector<ImageCallback>::iterator it=sAddImageCallbacks.begin(); it != sAddImageCallbacks.end(); it++)
685 (*it)(image->machHeader(), image->getSlide());
686 image->setAddFuncNotified();
687 }
688 }
689
690
691
692 // notify gdb about these new images
693 static const char* updateAllImages(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
694 {
695 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
696 if ( info[0].imageFilePath != NULL )
697 addImagesToAllImages(infoCount, info);
698 return NULL;
699 }
700
701
702 static StateHandlers* stateToHandlers(dyld_image_states state, void* handlersArray[7][3])
703 {
704 switch ( state ) {
705 case dyld_image_state_mapped:
706 return reinterpret_cast<StateHandlers*>(&handlersArray[0]);
707
708 case dyld_image_state_dependents_mapped:
709 return reinterpret_cast<StateHandlers*>(&handlersArray[1]);
710
711 case dyld_image_state_rebased:
712 return reinterpret_cast<StateHandlers*>(&handlersArray[2]);
713
714 case dyld_image_state_bound:
715 return reinterpret_cast<StateHandlers*>(&handlersArray[3]);
716
717 case dyld_image_state_dependents_initialized:
718 return reinterpret_cast<StateHandlers*>(&handlersArray[4]);
719
720 case dyld_image_state_initialized:
721 return reinterpret_cast<StateHandlers*>(&handlersArray[5]);
722
723 case dyld_image_state_terminated:
724 return reinterpret_cast<StateHandlers*>(&handlersArray[6]);
725 }
726 return NULL;
727 }
728
729 #if SUPPORT_ACCELERATE_TABLES
730 static dyld_image_state_change_handler getPreInitNotifyHandler(unsigned index)
731 {
732 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(dyld_image_state_dependents_initialized, sSingleHandlers);
733 if ( index >= handlers->size() )
734 return NULL;
735 return (*handlers)[index];
736 }
737
738 static dyld_image_state_change_handler getBoundBatchHandler(unsigned index)
739 {
740 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(dyld_image_state_bound, sBatchHandlers);
741 if ( index >= handlers->size() )
742 return NULL;
743 return (*handlers)[index];
744 }
745
746 static void notifySingleFromCache(dyld_image_states state, const mach_header* mh, const char* path)
747 {
748 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
749 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
750 if ( handlers != NULL ) {
751 dyld_image_info info;
752 info.imageLoadAddress = mh;
753 info.imageFilePath = path;
754 info.imageFileModDate = 0;
755 for (dyld_image_state_change_handler handler : *handlers) {
756 const char* result = (*handler)(state, 1, &info);
757 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
758 //fprintf(stderr, " image rejected by handler=%p\n", *it);
759 // make copy of thrown string so that later catch clauses can free it
760 const char* str = strdup(result);
761 throw str;
762 }
763 }
764 }
765 if ( (state == dyld_image_state_dependents_initialized) && (sNotifyObjCInit != NULL) && (mh->flags & MH_HAS_OBJC) ) {
766 (*sNotifyObjCInit)(path, mh);
767 }
768 }
769 #endif
770
771 static mach_port_t sNotifyReplyPorts[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT];
772 static bool sZombieNotifiers[DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT];
773
774 static void notifyMonitoringDyld(bool unloading, unsigned portSlot, unsigned imageCount, const dyld_image_info infos[])
775 {
776 if ( sZombieNotifiers[portSlot] )
777 return;
778
779 unsigned entriesSize = imageCount*sizeof(dyld_process_info_image_entry);
780 unsigned pathsSize = 0;
781 for (unsigned j=0; j < imageCount; ++j) {
782 pathsSize += (strlen(infos[j].imageFilePath) + 1);
783 }
784 unsigned totalSize = (sizeof(dyld_process_info_notify_header) + MAX_TRAILER_SIZE + entriesSize + pathsSize + 127) & -128; // align
785 if ( totalSize > DYLD_PROCESS_INFO_NOTIFY_MAX_BUFFER_SIZE ) {
786 // Putting all image paths into one message would make buffer too big.
787 // Instead split into two messages. Recurse as needed until paths fit in buffer.
788 unsigned imageHalfCount = imageCount/2;
789 notifyMonitoringDyld(unloading, portSlot, imageHalfCount, infos);
790 notifyMonitoringDyld(unloading, portSlot, imageCount - imageHalfCount, &infos[imageHalfCount]);
791 return;
792 }
793 uint8_t buffer[totalSize];
794 dyld_process_info_notify_header* header = (dyld_process_info_notify_header*)buffer;
795 header->version = 1;
796 header->imageCount = imageCount;
797 header->imagesOffset = sizeof(dyld_process_info_notify_header);
798 header->stringsOffset = sizeof(dyld_process_info_notify_header) + entriesSize;
799 header->timestamp = dyld::gProcessInfo->infoArrayChangeTimestamp;
800 dyld_process_info_image_entry* entries = (dyld_process_info_image_entry*)&buffer[header->imagesOffset];
801 char* const pathPoolStart = (char*)&buffer[header->stringsOffset];
802 char* pathPool = pathPoolStart;
803 for (unsigned j=0; j < imageCount; ++j) {
804 strcpy(pathPool, infos[j].imageFilePath);
805 uint32_t len = (uint32_t)strlen(pathPool);
806 bzero(entries->uuid, 16);
807 const ImageLoader* image = findImageByMachHeader(infos[j].imageLoadAddress);
808 if ( image != NULL ) {
809 image->getUUID(entries->uuid);
810 }
811 #if SUPPORT_ACCELERATE_TABLES
812 else if ( sAllCacheImagesProxy != NULL ) {
813 const mach_header* mh;
814 const char* path;
815 unsigned index;
816 if ( sAllCacheImagesProxy->addressInCache(infos[j].imageLoadAddress, &mh, &path, &index) ) {
817 sAllCacheImagesProxy->getDylibUUID(index, entries->uuid);
818 }
819 }
820 #endif
821 entries->loadAddress = (uint64_t)infos[j].imageLoadAddress;
822 entries->pathStringOffset = (uint32_t)(pathPool - pathPoolStart);
823 entries->pathLength = len;
824 pathPool += (len +1);
825 ++entries;
826 }
827
828 if ( sNotifyReplyPorts[portSlot] == 0 ) {
829 if ( !mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &sNotifyReplyPorts[portSlot]) )
830 mach_port_insert_right(mach_task_self(), sNotifyReplyPorts[portSlot], sNotifyReplyPorts[portSlot], MACH_MSG_TYPE_MAKE_SEND);
831 //dyld::log("allocated reply port %d\n", sNotifyReplyPorts[portSlot]);
832 }
833 //dyld::log("found port to send to\n");
834 mach_msg_header_t* h = (mach_msg_header_t*)buffer;
835 h->msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND,MACH_MSG_TYPE_MAKE_SEND); // MACH_MSG_TYPE_MAKE_SEND_ONCE
836 h->msgh_id = unloading ? DYLD_PROCESS_INFO_NOTIFY_UNLOAD_ID : DYLD_PROCESS_INFO_NOTIFY_LOAD_ID;
837 h->msgh_local_port = sNotifyReplyPorts[portSlot];
838 h->msgh_remote_port = dyld::gProcessInfo->notifyPorts[portSlot];
839 h->msgh_reserved = 0;
840 h->msgh_size = (mach_msg_size_t)sizeof(buffer);
841 //dyld::log("sending to port[%d]=%d, size=%d, reply port=%d, id=0x%X\n", portSlot, dyld::gProcessInfo->notifyPorts[portSlot], h->msgh_size, sNotifyReplyPorts[portSlot], h->msgh_id);
842 kern_return_t sendResult = mach_msg(h, MACH_SEND_MSG | MACH_RCV_MSG | MACH_RCV_TIMEOUT, h->msgh_size, h->msgh_size, sNotifyReplyPorts[portSlot], 5000, MACH_PORT_NULL);
843 //dyld::log("send result = 0x%X, msg_id=%d, msg_size=%d\n", sendResult, h->msgh_id, h->msgh_size);
844 if ( sendResult == MACH_SEND_INVALID_DEST ) {
845 // sender is not responding, detatch
846 //dyld::log("process requesting notification gone. deallocation send port %d and receive port %d\n", dyld::gProcessInfo->notifyPorts[portSlot], sNotifyReplyPorts[portSlot]);
847 mach_port_deallocate(mach_task_self(), dyld::gProcessInfo->notifyPorts[portSlot]);
848 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts[portSlot]);
849 dyld::gProcessInfo->notifyPorts[portSlot] = 0;
850 sNotifyReplyPorts[portSlot] = 0;
851 }
852 else if ( sendResult == MACH_RCV_TIMED_OUT ) {
853 // client took too long, ignore him from now on
854 sZombieNotifiers[portSlot] = true;
855 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts[portSlot]);
856 sNotifyReplyPorts[portSlot] = 0;
857 }
858 }
859
860 static void notifyMonitoringDyldMain()
861 {
862 for (int slot=0; slot < DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT; ++slot) {
863 if ( (dyld::gProcessInfo->notifyPorts[slot] != 0 ) && !sZombieNotifiers[slot] ) {
864 if ( sNotifyReplyPorts[slot] == 0 ) {
865 if ( !mach_port_allocate(mach_task_self(), MACH_PORT_RIGHT_RECEIVE, &sNotifyReplyPorts[slot]) )
866 mach_port_insert_right(mach_task_self(), sNotifyReplyPorts[slot], sNotifyReplyPorts[slot], MACH_MSG_TYPE_MAKE_SEND);
867 //dyld::log("allocated reply port %d\n", sNotifyReplyPorts[slot]);
868 }
869 //dyld::log("found port to send to\n");
870 uint8_t messageBuffer[sizeof(mach_msg_header_t) + MAX_TRAILER_SIZE];
871 mach_msg_header_t* h = (mach_msg_header_t*)messageBuffer;
872 h->msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND,MACH_MSG_TYPE_MAKE_SEND); // MACH_MSG_TYPE_MAKE_SEND_ONCE
873 h->msgh_id = DYLD_PROCESS_INFO_NOTIFY_MAIN_ID;
874 h->msgh_local_port = sNotifyReplyPorts[slot];
875 h->msgh_remote_port = dyld::gProcessInfo->notifyPorts[slot];
876 h->msgh_reserved = 0;
877 h->msgh_size = (mach_msg_size_t)sizeof(messageBuffer);
878 //dyld::log("sending to port[%d]=%d, size=%d, reply port=%d, id=0x%X\n", slot, dyld::gProcessInfo->notifyPorts[slot], h->msgh_size, sNotifyReplyPorts[slot], h->msgh_id);
879 kern_return_t sendResult = mach_msg(h, MACH_SEND_MSG | MACH_RCV_MSG | MACH_RCV_TIMEOUT, h->msgh_size, h->msgh_size, sNotifyReplyPorts[slot], 5000, MACH_PORT_NULL);
880 //dyld::log("send result = 0x%X, msg_id=%d, msg_size=%d\n", sendResult, h->msgh_id, h->msgh_size);
881 if ( sendResult == MACH_SEND_INVALID_DEST ) {
882 // sender is not responding, detatch
883 //dyld::log("process requesting notification gone. deallocation send port %d and receive port %d\n", dyld::gProcessInfo->notifyPorts[slot], sNotifyReplyPorts[slot]);
884 mach_port_deallocate(mach_task_self(), dyld::gProcessInfo->notifyPorts[slot]);
885 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts[slot]);
886 dyld::gProcessInfo->notifyPorts[slot] = 0;
887 sNotifyReplyPorts[slot] = 0;
888 }
889 else if ( sendResult == MACH_RCV_TIMED_OUT ) {
890 // client took too long, ignore him from now on
891 sZombieNotifiers[slot] = true;
892 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts[slot]);
893 sNotifyReplyPorts[slot] = 0;
894 }
895 }
896 }
897 }
898
899 void notifyKernel(const ImageLoader& image, bool loading) {
900 if ( !image.inSharedCache() ) {
901 uint32_t baseCode = loading ? DBG_DYLD_UUID_MAP_A : DBG_DYLD_UUID_UNMAP_A;
902 uuid_t uuid;
903 ino_t inode = image.getInode();
904 image.getUUID(uuid);
905 dyld3::kdebug_trace_dyld_image(baseCode, (const uuid_t *)&uuid, *(fsobj_id_t*)&inode, {{ image.getDevice(), 0 }}, image.machHeader());
906 }
907 }
908
909 static void notifySingle(dyld_image_states state, const ImageLoader* image, ImageLoader::InitializerTimingList* timingInfo)
910 {
911 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
912 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
913 if ( handlers != NULL ) {
914 dyld_image_info info;
915 info.imageLoadAddress = image->machHeader();
916 info.imageFilePath = image->getRealPath();
917 info.imageFileModDate = image->lastModified();
918 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
919 const char* result = (*it)(state, 1, &info);
920 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
921 //fprintf(stderr, " image rejected by handler=%p\n", *it);
922 // make copy of thrown string so that later catch clauses can free it
923 const char* str = strdup(result);
924 throw str;
925 }
926 }
927 }
928 if ( state == dyld_image_state_mapped ) {
929 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
930 if ( !image->inSharedCache() ) {
931 dyld_uuid_info info;
932 if ( image->getUUID(info.imageUUID) ) {
933 info.imageLoadAddress = image->machHeader();
934 addNonSharedCacheImageUUID(info);
935 }
936 }
937 }
938 if ( (state == dyld_image_state_dependents_initialized) && (sNotifyObjCInit != NULL) && image->notifyObjC() ) {
939 uint64_t t0 = mach_absolute_time();
940 (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
941 uint64_t t1 = mach_absolute_time();
942 uint64_t t2 = mach_absolute_time();
943 uint64_t timeInObjC = t1-t0;
944 uint64_t emptyTime = (t2-t1)*100;
945 if ( (timeInObjC > emptyTime) && (timingInfo != NULL) ) {
946 timingInfo->addTime(image->getShortName(), timeInObjC);
947 }
948 }
949 // mach message csdlc about dynamically unloaded images
950 if ( image->addFuncNotified() && (state == dyld_image_state_terminated) ) {
951 notifyKernel(*image, false);
952
953 uint64_t loadTimestamp = mach_absolute_time();
954 if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
955 dyld::log("dyld: coresymbolication_unload_notifier(%p, 0x%016llX, %p, %s)\n",
956 dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, image->machHeader(), image->getPath());
957 }
958 if ( dyld::gProcessInfo->coreSymbolicationShmPage != NULL) {
959 coresymbolication_unload_notifier(dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, image->getPath(), image->machHeader());
960 }
961 for (int slot=0; slot < DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT; ++slot) {
962 if ( dyld::gProcessInfo->notifyPorts[slot] != 0 ) {
963 dyld_image_info info;
964 info.imageLoadAddress = image->machHeader();
965 info.imageFilePath = image->getPath();
966 info.imageFileModDate = 0;
967 notifyMonitoringDyld(true, slot, 1, &info);
968 }
969 else if ( sNotifyReplyPorts[slot] != 0 ) {
970 // monitoring process detached from this process, so release reply port
971 //dyld::log("deallocated reply port %d\n", sNotifyReplyPorts[slot]);
972 mach_port_deallocate(mach_task_self(), sNotifyReplyPorts[slot]);
973 sNotifyReplyPorts[slot] = 0;
974 sZombieNotifiers[slot] = false;
975 }
976 }
977 }
978
979 }
980
981
982 //
983 // Normally, dyld_all_image_infos is only updated in batches after an entire
984 // graph is loaded. But if there is an error loading the initial set of
985 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
986 // up, leading to usually brief crash logs.
987 //
988 // This function manually adds the images loaded so far to dyld::gProcessInfo.
989 // It should only be called before terminating.
990 //
991 void syncAllImages()
992 {
993 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
994 dyld_image_info info;
995 ImageLoader* image = *it;
996 info.imageLoadAddress = image->machHeader();
997 info.imageFilePath = image->getRealPath();
998 info.imageFileModDate = image->lastModified();
999 // add to all_image_infos if not already there
1000 bool found = false;
1001 int existingCount = dyld::gProcessInfo->infoArrayCount;
1002 const dyld_image_info* existing = dyld::gProcessInfo->infoArray;
1003 if ( existing != NULL ) {
1004 for (int i=0; i < existingCount; ++i) {
1005 if ( existing[i].imageLoadAddress == info.imageLoadAddress ) {
1006 //dyld::log("not adding %s\n", info.imageFilePath);
1007 found = true;
1008 break;
1009 }
1010 }
1011 }
1012 if ( ! found ) {
1013 //dyld::log("adding %s\n", info.imageFilePath);
1014 addImagesToAllImages(1, &info);
1015 }
1016 }
1017 }
1018
1019
1020 static int imageSorter(const void* l, const void* r)
1021 {
1022 const ImageLoader* left = *((ImageLoader**)l);
1023 const ImageLoader* right= *((ImageLoader**)r);
1024 return left->compare(right);
1025 }
1026
1027 static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler, bool preflightOnly, bool onlyObjCMappedNotification)
1028 {
1029 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
1030 if ( (handlers != NULL) || ((state == dyld_image_state_bound) && (sNotifyObjCMapped != NULL)) ) {
1031 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
1032 allImagesLock();
1033 dyld_image_info infos[allImagesCount()+1];
1034 ImageLoader* images[allImagesCount()+1];
1035 ImageLoader** end = images;
1036 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1037 dyld_image_states imageState = (*it)->getState();
1038 if ( (imageState == state) || (orLater && (imageState > state)) )
1039 *end++ = *it;
1040 }
1041 if ( sBundleBeingLoaded != NULL ) {
1042 dyld_image_states imageState = sBundleBeingLoaded->getState();
1043 if ( (imageState == state) || (orLater && (imageState > state)) )
1044 *end++ = sBundleBeingLoaded;
1045 }
1046 const char* dontLoadReason = NULL;
1047 uint32_t imageCount = (uint32_t)(end-images);
1048 if ( imageCount != 0 ) {
1049 // sort bottom up
1050 qsort(images, imageCount, sizeof(ImageLoader*), &imageSorter);
1051 // build info array
1052 for (unsigned int i=0; i < imageCount; ++i) {
1053 dyld_image_info* p = &infos[i];
1054 ImageLoader* image = images[i];
1055 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
1056 p->imageLoadAddress = image->machHeader();
1057 p->imageFilePath = image->getRealPath();
1058 p->imageFileModDate = image->lastModified();
1059 // get these registered with the kernel as early as possible
1060 if ( state == dyld_image_state_dependents_mapped)
1061 notifyKernel(*image, true);
1062 // special case for add_image hook
1063 if ( state == dyld_image_state_bound )
1064 notifyAddImageCallbacks(image);
1065 }
1066 }
1067 #if SUPPORT_ACCELERATE_TABLES
1068 if ( sAllCacheImagesProxy != NULL ) {
1069 unsigned cacheCount = sAllCacheImagesProxy->appendImagesToNotify(state, orLater, &infos[imageCount]);
1070 // support _dyld_register_func_for_add_image()
1071 if ( state == dyld_image_state_bound ) {
1072 for (ImageCallback callback : sAddImageCallbacks) {
1073 for (unsigned i=0; i < cacheCount; ++i)
1074 (*callback)(infos[imageCount+i].imageLoadAddress, sSharedCacheLoadInfo.slide);
1075 }
1076 }
1077 imageCount += cacheCount;
1078 }
1079 #endif
1080 if ( imageCount != 0 ) {
1081 if ( !onlyObjCMappedNotification ) {
1082 if ( onlyHandler != NULL ) {
1083 const char* result = NULL;
1084 if ( result == NULL ) {
1085 result = (*onlyHandler)(state, imageCount, infos);
1086 }
1087 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
1088 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
1089 // make copy of thrown string so that later catch clauses can free it
1090 dontLoadReason = strdup(result);
1091 }
1092 }
1093 else {
1094 // call each handler with whole array
1095 if ( handlers != NULL ) {
1096 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
1097 const char* result = (*it)(state, imageCount, infos);
1098 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
1099 //fprintf(stderr, " images rejected by handler=%p\n", *it);
1100 // make copy of thrown string so that later catch clauses can free it
1101 dontLoadReason = strdup(result);
1102 break;
1103 }
1104 }
1105 }
1106 }
1107 }
1108 // tell objc about new images
1109 if ( (onlyHandler == NULL) && ((state == dyld_image_state_bound) || (orLater && (dyld_image_state_bound > state))) && (sNotifyObjCMapped != NULL) ) {
1110 const char* paths[imageCount];
1111 const mach_header* mhs[imageCount];
1112 unsigned objcImageCount = 0;
1113 for (int i=0; i < imageCount; ++i) {
1114 const ImageLoader* image = findImageByMachHeader(infos[i].imageLoadAddress);
1115 bool hasObjC = false;
1116 if ( image != NULL ) {
1117 hasObjC = image->notifyObjC();
1118 }
1119 #if SUPPORT_ACCELERATE_TABLES
1120 else if ( sAllCacheImagesProxy != NULL ) {
1121 const mach_header* mh;
1122 const char* path;
1123 unsigned index;
1124 if ( sAllCacheImagesProxy->addressInCache(infos[i].imageLoadAddress, &mh, &path, &index) ) {
1125 hasObjC = (mh->flags & MH_HAS_OBJC);
1126 }
1127 }
1128 #endif
1129 if ( hasObjC ) {
1130 paths[objcImageCount] = infos[i].imageFilePath;
1131 mhs[objcImageCount] = infos[i].imageLoadAddress;
1132 ++objcImageCount;
1133 }
1134 }
1135 if ( objcImageCount != 0 ) {
1136 uint64_t t0 = mach_absolute_time();
1137 (*sNotifyObjCMapped)(objcImageCount, paths, mhs);
1138 uint64_t t1 = mach_absolute_time();
1139 ImageLoader::fgTotalObjCSetupTime += (t1-t0);
1140 }
1141 }
1142 }
1143 allImagesUnlock();
1144 if ( dontLoadReason != NULL )
1145 throw dontLoadReason;
1146 if ( !preflightOnly && (state == dyld_image_state_dependents_mapped) ) {
1147 if ( (dyld::gProcessInfo->coreSymbolicationShmPage != NULL) || sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
1148 // mach message csdlc about loaded images
1149 uint64_t loadTimestamp = mach_absolute_time();
1150 for (unsigned j=0; j < imageCount; ++j) {
1151 if ( sEnv.DYLD_PRINT_CS_NOTIFICATIONS ) {
1152 dyld::log("dyld: coresymbolication_load_notifier(%p, 0x%016llX, %p, %s)\n",
1153 dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, infos[j].imageLoadAddress, infos[j].imageFilePath);
1154 }
1155 coresymbolication_load_notifier(dyld::gProcessInfo->coreSymbolicationShmPage, loadTimestamp, infos[j].imageFilePath, infos[j].imageLoadAddress);
1156 }
1157 }
1158 for (int slot=0; slot < DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT; ++slot) {
1159 if ( dyld::gProcessInfo->notifyPorts[slot] )
1160 notifyMonitoringDyld(false, slot, imageCount, infos);
1161 }
1162 }
1163 }
1164 }
1165
1166
1167
1168 static void notifyBatch(dyld_image_states state, bool preflightOnly)
1169 {
1170 notifyBatchPartial(state, false, NULL, preflightOnly, false);
1171 }
1172
1173 // In order for register_func_for_add_image() callbacks to to be called bottom up,
1174 // we need to maintain a list of root images. The main executable is usally the
1175 // first root. Any images dynamically added are also roots (unless already loaded).
1176 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
1177 static void addRootImage(ImageLoader* image)
1178 {
1179 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
1180 // add to list of roots
1181 sImageRoots.push_back(image);
1182 }
1183
1184
1185 static void clearAllDepths()
1186 {
1187 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
1188 (*it)->clearDepth();
1189 }
1190
1191 static void printAllDepths()
1192 {
1193 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
1194 dyld::log("%03d %s\n", (*it)->getDepth(), (*it)->getShortName());
1195 }
1196
1197
1198 static unsigned int imageCount()
1199 {
1200 allImagesLock();
1201 unsigned int result = (unsigned int)sAllImages.size();
1202 allImagesUnlock();
1203 return (result);
1204 }
1205
1206
1207 static void setNewProgramVars(const ProgramVars& newVars)
1208 {
1209 // make a copy of the pointers to program variables
1210 gLinkContext.programVars = newVars;
1211
1212 // now set each program global to their initial value
1213 *gLinkContext.programVars.NXArgcPtr = gLinkContext.argc;
1214 *gLinkContext.programVars.NXArgvPtr = gLinkContext.argv;
1215 *gLinkContext.programVars.environPtr = gLinkContext.envp;
1216 *gLinkContext.programVars.__prognamePtr = gLinkContext.progname;
1217 }
1218
1219 #if SUPPORT_OLD_CRT_INITIALIZATION
1220 static void setRunInitialzersOldWay()
1221 {
1222 gRunInitializersOldWay = true;
1223 }
1224 #endif
1225
1226 static bool sandboxBlocked(const char* path, const char* kind)
1227 {
1228 #if TARGET_IPHONE_SIMULATOR
1229 // sandbox calls not yet supported in simulator runtime
1230 return false;
1231 #else
1232 sandbox_filter_type filter = (sandbox_filter_type)(SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT);
1233 return ( sandbox_check(getpid(), kind, filter, path) > 0 );
1234 #endif
1235 }
1236
1237 bool sandboxBlockedMmap(const char* path)
1238 {
1239 return sandboxBlocked(path, "file-map-executable");
1240 }
1241
1242 bool sandboxBlockedOpen(const char* path)
1243 {
1244 return sandboxBlocked(path, "file-read-data");
1245 }
1246
1247 bool sandboxBlockedStat(const char* path)
1248 {
1249 return sandboxBlocked(path, "file-read-metadata");
1250 }
1251
1252
1253 static void addDynamicReference(ImageLoader* from, ImageLoader* to) {
1254 // don't add dynamic reference if target is in the shared cache (since it can't be unloaded)
1255 if ( to->inSharedCache() )
1256 return;
1257
1258 // don't add dynamic reference if there already is a static one
1259 if ( from->dependsOn(to) )
1260 return;
1261
1262 // don't add if this combination already exists
1263 OSSpinLockLock(&sDynamicReferencesLock);
1264 for (std::vector<ImageLoader::DynamicReference>::iterator it=sDynamicReferences.begin(); it != sDynamicReferences.end(); ++it) {
1265 if ( (it->from == from) && (it->to == to) ) {
1266 OSSpinLockUnlock(&sDynamicReferencesLock);
1267 return;
1268 }
1269 }
1270
1271 //dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
1272 ImageLoader::DynamicReference t;
1273 t.from = from;
1274 t.to = to;
1275 sDynamicReferences.push_back(t);
1276 OSSpinLockUnlock(&sDynamicReferencesLock);
1277 }
1278
1279 static void addImage(ImageLoader* image)
1280 {
1281 // add to master list
1282 allImagesLock();
1283 sAllImages.push_back(image);
1284 allImagesUnlock();
1285
1286 // update mapped ranges
1287 uintptr_t lastSegStart = 0;
1288 uintptr_t lastSegEnd = 0;
1289 for(unsigned int i=0, e=image->segmentCount(); i < e; ++i) {
1290 if ( image->segUnaccessible(i) )
1291 continue;
1292 uintptr_t start = image->segActualLoadAddress(i);
1293 uintptr_t end = image->segActualEndAddress(i);
1294 if ( start == lastSegEnd ) {
1295 // two segments are contiguous, just record combined segments
1296 lastSegEnd = end;
1297 }
1298 else {
1299 // non-contiguous segments, record last (if any)
1300 if ( lastSegEnd != 0 )
1301 addMappedRange(image, lastSegStart, lastSegEnd);
1302 lastSegStart = start;
1303 lastSegEnd = end;
1304 }
1305 }
1306 if ( lastSegEnd != 0 )
1307 addMappedRange(image, lastSegStart, lastSegEnd);
1308
1309
1310 if ( gLinkContext.verboseLoading || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
1311 dyld::log("dyld: loaded: %s\n", image->getPath());
1312 }
1313
1314 }
1315
1316 //
1317 // Helper for std::remove_if
1318 //
1319 class RefUsesImage {
1320 public:
1321 RefUsesImage(ImageLoader* image) : _image(image) {}
1322 bool operator()(const ImageLoader::DynamicReference& ref) const {
1323 return ( (ref.from == _image) || (ref.to == _image) );
1324 }
1325 private:
1326 ImageLoader* _image;
1327 };
1328
1329
1330
1331 void removeImage(ImageLoader* image)
1332 {
1333 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
1334 for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
1335 if ( it->mh == image->machHeader() ) {
1336 unregisterDOF(it->registrationID);
1337 sImageFilesNeedingDOFUnregistration.erase(it);
1338 // don't increment iterator, the erase caused next element to be copied to where this iterator points
1339 }
1340 else {
1341 ++it;
1342 }
1343 }
1344
1345 // tell all registered remove image handlers about this
1346 // do this before removing image from internal data structures so that the callback can query dyld about the image
1347 if ( image->getState() >= dyld_image_state_bound ) {
1348 sRemoveImageCallbacksInUse = true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
1349 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
1350 (*it)(image->machHeader(), image->getSlide());
1351 }
1352 sRemoveImageCallbacksInUse = false;
1353
1354 if ( sNotifyObjCUnmapped != NULL && image->notifyObjC() )
1355 (*sNotifyObjCUnmapped)(image->getRealPath(), image->machHeader());
1356 }
1357
1358 // notify
1359 notifySingle(dyld_image_state_terminated, image, NULL);
1360
1361 // remove from mapped images table
1362 removedMappedRanges(image);
1363
1364 // remove from master list
1365 allImagesLock();
1366 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1367 if ( *it == image ) {
1368 sAllImages.erase(it);
1369 break;
1370 }
1371 }
1372 allImagesUnlock();
1373
1374 // remove from sDynamicReferences
1375 OSSpinLockLock(&sDynamicReferencesLock);
1376 sDynamicReferences.erase(std::remove_if(sDynamicReferences.begin(), sDynamicReferences.end(), RefUsesImage(image)), sDynamicReferences.end());
1377 OSSpinLockUnlock(&sDynamicReferencesLock);
1378
1379 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
1380 if ( sLastImageByAddressCache == image )
1381 sLastImageByAddressCache = NULL;
1382
1383 // if in root list, pull it out
1384 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1385 if ( *it == image ) {
1386 sImageRoots.erase(it);
1387 break;
1388 }
1389 }
1390
1391 // log if requested
1392 if ( gLinkContext.verboseLoading || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
1393 dyld::log("dyld: unloaded: %s\n", image->getPath());
1394 }
1395
1396 // tell gdb, new way
1397 removeImageFromAllImages(image->machHeader());
1398 }
1399
1400
1401 void runImageStaticTerminators(ImageLoader* image)
1402 {
1403 // if in termination list, pull it out and run terminator
1404 bool mightBeMore;
1405 do {
1406 mightBeMore = false;
1407 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
1408 if ( *it == image ) {
1409 sImageFilesNeedingTermination.erase(it);
1410 if (gLogAPIs) dyld::log("dlclose(), running static terminators for %p %s\n", image, image->getShortName());
1411 image->doTermination(gLinkContext);
1412 mightBeMore = true;
1413 break;
1414 }
1415 }
1416 } while ( mightBeMore );
1417 }
1418
1419 static void terminationRecorder(ImageLoader* image)
1420 {
1421 sImageFilesNeedingTermination.push_back(image);
1422 }
1423
1424 const char* getExecutablePath()
1425 {
1426 return sExecPath;
1427 }
1428
1429 static void runAllStaticTerminators(void* extra)
1430 {
1431 try {
1432 const size_t imageCount = sImageFilesNeedingTermination.size();
1433 for(size_t i=imageCount; i > 0; --i){
1434 ImageLoader* image = sImageFilesNeedingTermination[i-1];
1435 image->doTermination(gLinkContext);
1436 }
1437 sImageFilesNeedingTermination.clear();
1438 notifyBatch(dyld_image_state_terminated, false);
1439 }
1440 catch (const char* msg) {
1441 halt(msg);
1442 }
1443 }
1444
1445 void initializeMainExecutable()
1446 {
1447 // record that we've reached this step
1448 gLinkContext.startedInitializingMainExecutable = true;
1449
1450 // run initialzers for any inserted dylibs
1451 ImageLoader::InitializerTimingList initializerTimes[allImagesCount()];
1452 initializerTimes[0].count = 0;
1453 const size_t rootCount = sImageRoots.size();
1454 if ( rootCount > 1 ) {
1455 for(size_t i=1; i < rootCount; ++i) {
1456 sImageRoots[i]->runInitializers(gLinkContext, initializerTimes[0]);
1457 }
1458 }
1459
1460 // run initializers for main executable and everything it brings up
1461 sMainExecutable->runInitializers(gLinkContext, initializerTimes[0]);
1462
1463 // register cxa_atexit() handler to run static terminators in all loaded images when this process exits
1464 if ( gLibSystemHelpers != NULL )
1465 (*gLibSystemHelpers->cxa_atexit)(&runAllStaticTerminators, NULL, NULL);
1466
1467 // dump info if requested
1468 if ( sEnv.DYLD_PRINT_STATISTICS )
1469 ImageLoader::printStatistics((unsigned int)allImagesCount(), initializerTimes[0]);
1470 if ( sEnv.DYLD_PRINT_STATISTICS_DETAILS )
1471 ImageLoaderMachO::printStatisticsDetails((unsigned int)allImagesCount(), initializerTimes[0]);
1472 }
1473
1474 bool mainExecutablePrebound()
1475 {
1476 return sMainExecutable->usablePrebinding(gLinkContext);
1477 }
1478
1479 ImageLoader* mainExecutable()
1480 {
1481 return sMainExecutable;
1482 }
1483
1484
1485
1486
1487 #if SUPPORT_VERSIONED_PATHS
1488
1489 // forward reference
1490 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName);
1491
1492
1493 //
1494 // Examines a dylib file and if its current_version is newer than the installed
1495 // dylib at its install_name, then add the dylib file to sDylibOverrides.
1496 //
1497 static void checkDylibOverride(const char* dylibFile)
1498 {
1499 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
1500 uint32_t altVersion;
1501 char sysInstallName[PATH_MAX];
1502 if ( getDylibVersionAndInstallname(dylibFile, &altVersion, sysInstallName) && (sysInstallName[0] =='/') ) {
1503 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
1504 uint32_t sysVersion;
1505 if ( getDylibVersionAndInstallname(sysInstallName, &sysVersion, NULL) ) {
1506 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
1507 if ( altVersion > sysVersion ) {
1508 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
1509 // see if there already is an override for this dylib
1510 bool entryExists = false;
1511 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
1512 if ( strcmp(it->installName, sysInstallName) == 0 ) {
1513 entryExists = true;
1514 uint32_t prevVersion;
1515 if ( getDylibVersionAndInstallname(it->override, &prevVersion, NULL) ) {
1516 if ( altVersion > prevVersion ) {
1517 // found an even newer override
1518 free((void*)(it->override));
1519 char resolvedPath[PATH_MAX];
1520 if ( realpath(dylibFile, resolvedPath) != NULL )
1521 it->override = strdup(resolvedPath);
1522 else
1523 it->override = strdup(dylibFile);
1524 break;
1525 }
1526 }
1527 }
1528 }
1529 if ( ! entryExists ) {
1530 DylibOverride entry;
1531 entry.installName = strdup(sysInstallName);
1532 char resolvedPath[PATH_MAX];
1533 if ( realpath(dylibFile, resolvedPath) != NULL )
1534 entry.override = strdup(resolvedPath);
1535 else
1536 entry.override = strdup(dylibFile);
1537 sDylibOverrides.push_back(entry);
1538 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1539 }
1540 }
1541 }
1542 }
1543
1544 }
1545
1546 static void checkDylibOverridesInDir(const char* dirPath)
1547 {
1548 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1549 char dylibPath[PATH_MAX];
1550 long dirPathLen = strlcpy(dylibPath, dirPath, PATH_MAX-1);
1551 if ( dirPathLen >= PATH_MAX )
1552 return;
1553 DIR* dirp = opendir(dirPath);
1554 if ( dirp != NULL) {
1555 dirent entry;
1556 dirent* entp = NULL;
1557 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1558 if ( entp == NULL )
1559 break;
1560 if ( entp->d_type != DT_REG )
1561 continue;
1562 dylibPath[dirPathLen] = '/';
1563 dylibPath[dirPathLen+1] = '\0';
1564 if ( strlcat(dylibPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1565 continue;
1566 checkDylibOverride(dylibPath);
1567 }
1568 closedir(dirp);
1569 }
1570 }
1571
1572
1573 static void checkFrameworkOverridesInDir(const char* dirPath)
1574 {
1575 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1576 char frameworkPath[PATH_MAX];
1577 long dirPathLen = strlcpy(frameworkPath, dirPath, PATH_MAX-1);
1578 if ( dirPathLen >= PATH_MAX )
1579 return;
1580 DIR* dirp = opendir(dirPath);
1581 if ( dirp != NULL) {
1582 dirent entry;
1583 dirent* entp = NULL;
1584 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1585 if ( entp == NULL )
1586 break;
1587 if ( entp->d_type != DT_DIR )
1588 continue;
1589 frameworkPath[dirPathLen] = '/';
1590 frameworkPath[dirPathLen+1] = '\0';
1591 int dirNameLen = (int)strlen(entp->d_name);
1592 if ( dirNameLen < 11 )
1593 continue;
1594 if ( strcmp(&entp->d_name[dirNameLen-10], ".framework") != 0 )
1595 continue;
1596 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1597 continue;
1598 if ( strlcat(frameworkPath, "/", PATH_MAX) >= PATH_MAX )
1599 continue;
1600 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1601 continue;
1602 frameworkPath[strlen(frameworkPath)-10] = '\0';
1603 checkDylibOverride(frameworkPath);
1604 }
1605 closedir(dirp);
1606 }
1607 }
1608 #endif // SUPPORT_VERSIONED_PATHS
1609
1610
1611 //
1612 // Turns a colon separated list of strings into a NULL terminated array
1613 // of string pointers. If mainExecutableDir param is not NULL,
1614 // substitutes @loader_path with main executable's dir.
1615 //
1616 static const char** parseColonList(const char* list, const char* mainExecutableDir)
1617 {
1618 static const char* sEmptyList[] = { NULL };
1619
1620 if ( list[0] == '\0' )
1621 return sEmptyList;
1622
1623 int colonCount = 0;
1624 for(const char* s=list; *s != '\0'; ++s) {
1625 if (*s == ':')
1626 ++colonCount;
1627 }
1628
1629 int index = 0;
1630 const char* start = list;
1631 char** result = new char*[colonCount+2];
1632 for(const char* s=list; *s != '\0'; ++s) {
1633 if (*s == ':') {
1634 size_t len = s-start;
1635 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1636 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1637 if ( gLinkContext.processIsRestricted ) {
1638 dyld::log("dyld: warning: @loader_path/ ignored in restricted process\n");
1639 continue;
1640 }
1641 #endif
1642 size_t mainExecDirLen = strlen(mainExecutableDir);
1643 char* str = new char[mainExecDirLen+len+1];
1644 strcpy(str, mainExecutableDir);
1645 strlcat(str, &start[13], mainExecDirLen+len+1);
1646 str[mainExecDirLen+len-13] = '\0';
1647 start = &s[1];
1648 result[index++] = str;
1649 }
1650 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1651 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1652 if ( gLinkContext.processIsRestricted ) {
1653 dyld::log("dyld: warning: @executable_path/ ignored in restricted process\n");
1654 continue;
1655 }
1656 #endif
1657 size_t mainExecDirLen = strlen(mainExecutableDir);
1658 char* str = new char[mainExecDirLen+len+1];
1659 strcpy(str, mainExecutableDir);
1660 strlcat(str, &start[17], mainExecDirLen+len+1);
1661 str[mainExecDirLen+len-17] = '\0';
1662 start = &s[1];
1663 result[index++] = str;
1664 }
1665 else {
1666 char* str = new char[len+1];
1667 strncpy(str, start, len);
1668 str[len] = '\0';
1669 start = &s[1];
1670 result[index++] = str;
1671 }
1672 }
1673 }
1674 size_t len = strlen(start);
1675 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1676 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1677 if ( gLinkContext.processIsRestricted ) {
1678 dyld::log("dyld: warning: @loader_path/ ignored in restricted process\n");
1679 }
1680 else
1681 #endif
1682 {
1683 size_t mainExecDirLen = strlen(mainExecutableDir);
1684 char* str = new char[mainExecDirLen+len+1];
1685 strcpy(str, mainExecutableDir);
1686 strlcat(str, &start[13], mainExecDirLen+len+1);
1687 str[mainExecDirLen+len-13] = '\0';
1688 result[index++] = str;
1689 }
1690 }
1691 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1692 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1693 if ( gLinkContext.processIsRestricted ) {
1694 dyld::log("dyld: warning: @executable_path/ ignored in restricted process\n");
1695 }
1696 else
1697 #endif
1698 {
1699 size_t mainExecDirLen = strlen(mainExecutableDir);
1700 char* str = new char[mainExecDirLen+len+1];
1701 strcpy(str, mainExecutableDir);
1702 strlcat(str, &start[17], mainExecDirLen+len+1);
1703 str[mainExecDirLen+len-17] = '\0';
1704 result[index++] = str;
1705 }
1706 }
1707 else {
1708 char* str = new char[len+1];
1709 strcpy(str, start);
1710 result[index++] = str;
1711 }
1712 result[index] = NULL;
1713
1714 //dyld::log("parseColonList(%s)\n", list);
1715 //for(int i=0; result[i] != NULL; ++i)
1716 // dyld::log(" %s\n", result[i]);
1717 return (const char**)result;
1718 }
1719
1720 static void appendParsedColonList(const char* list, const char* mainExecutableDir, const char* const ** storage)
1721 {
1722 const char** newlist = parseColonList(list, mainExecutableDir);
1723 if ( *storage == NULL ) {
1724 // first time, just set
1725 *storage = newlist;
1726 }
1727 else {
1728 // need to append to existing list
1729 const char* const* existing = *storage;
1730 int count = 0;
1731 for(int i=0; existing[i] != NULL; ++i)
1732 ++count;
1733 for(int i=0; newlist[i] != NULL; ++i)
1734 ++count;
1735 const char** combinedList = new const char*[count+2];
1736 int index = 0;
1737 for(int i=0; existing[i] != NULL; ++i)
1738 combinedList[index++] = existing[i];
1739 for(int i=0; newlist[i] != NULL; ++i)
1740 combinedList[index++] = newlist[i];
1741 combinedList[index] = NULL;
1742 // leak old arrays
1743 *storage = combinedList;
1744 }
1745 }
1746
1747 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1748 static void paths_expand_roots(const char **paths, const char *key, const char *val)
1749 {
1750 // assert(val != NULL);
1751 // assert(paths != NULL);
1752 if(NULL != key) {
1753 size_t keyLen = strlen(key);
1754 for(int i=0; paths[i] != NULL; ++i) {
1755 if ( strncmp(paths[i], key, keyLen) == 0 ) {
1756 char* newPath = new char[strlen(val) + (strlen(paths[i]) - keyLen) + 1];
1757 strcpy(newPath, val);
1758 strcat(newPath, &paths[i][keyLen]);
1759 paths[i] = newPath;
1760 }
1761 }
1762 }
1763 return;
1764 }
1765
1766 static void removePathWithPrefix(const char* paths[], const char* prefix)
1767 {
1768 size_t prefixLen = strlen(prefix);
1769 int skip = 0;
1770 int i;
1771 for(i = 0; paths[i] != NULL; ++i) {
1772 if ( strncmp(paths[i], prefix, prefixLen) == 0 )
1773 ++skip;
1774 else
1775 paths[i-skip] = paths[i];
1776 }
1777 paths[i-skip] = NULL;
1778 }
1779 #endif
1780
1781
1782 #if 0
1783 static void paths_dump(const char **paths)
1784 {
1785 // assert(paths != NULL);
1786 const char **strs = paths;
1787 while(*strs != NULL)
1788 {
1789 dyld::log("\"%s\"\n", *strs);
1790 strs++;
1791 }
1792 return;
1793 }
1794 #endif
1795
1796
1797
1798 static void printOptions(const char* argv[])
1799 {
1800 uint32_t i = 0;
1801 while ( NULL != argv[i] ) {
1802 dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
1803 i++;
1804 }
1805 }
1806
1807 static void printEnvironmentVariables(const char* envp[])
1808 {
1809 while ( NULL != *envp ) {
1810 dyld::log("%s\n", *envp);
1811 envp++;
1812 }
1813 }
1814
1815 void processDyldEnvironmentVariable(const char* key, const char* value, const char* mainExecutableDir)
1816 {
1817 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
1818 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FRAMEWORK_PATH);
1819 }
1820 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1821 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_FRAMEWORK_PATH);
1822 }
1823 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
1824 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_LIBRARY_PATH);
1825 }
1826 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1827 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_LIBRARY_PATH);
1828 }
1829 #if SUPPORT_ROOT_PATH
1830 else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
1831 if ( strcmp(value, "/") != 0 ) {
1832 gLinkContext.rootPaths = parseColonList(value, mainExecutableDir);
1833 for (int i=0; gLinkContext.rootPaths[i] != NULL; ++i) {
1834 if ( gLinkContext.rootPaths[i][0] != '/' ) {
1835 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1836 gLinkContext.rootPaths = NULL;
1837 break;
1838 }
1839 }
1840 }
1841 }
1842 #endif
1843 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
1844 gLinkContext.imageSuffix = value;
1845 }
1846 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
1847 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value, NULL);
1848 #if SUPPORT_ACCELERATE_TABLES
1849 sDisableAcceleratorTables = true;
1850 #endif
1851 }
1852 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
1853 sEnv.DYLD_PRINT_OPTS = true;
1854 }
1855 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
1856 sEnv.DYLD_PRINT_ENV = true;
1857 }
1858 else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
1859 sEnv.DYLD_DISABLE_DOFS = true;
1860 }
1861 else if ( strcmp(key, "DYLD_DISABLE_PREFETCH") == 0 ) {
1862 gLinkContext.preFetchDisabled = true;
1863 }
1864 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
1865 gLinkContext.verboseLoading = true;
1866 }
1867 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1868 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
1869 }
1870 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1871 sEnv.DYLD_BIND_AT_LAUNCH = true;
1872 }
1873 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1874 gLinkContext.bindFlat = true;
1875 }
1876 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1877 // ignore, no longer relevant but some scripts still set it
1878 }
1879 else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1880 }
1881 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
1882 gLinkContext.verbosePrebinding = true;
1883 }
1884 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1885 gLinkContext.verboseInit = true;
1886 }
1887 else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
1888 gLinkContext.verboseDOF = true;
1889 }
1890 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
1891 sEnv.DYLD_PRINT_STATISTICS = true;
1892 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
1893 // <rdar://problem/26614838> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1894 sForceStderr = true;
1895 #endif
1896 }
1897 else if ( strcmp(key, "DYLD_PRINT_TO_STDERR") == 0 ) {
1898 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
1899 // <rdar://problem/26633440> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
1900 sForceStderr = true;
1901 #endif
1902 }
1903 else if ( strcmp(key, "DYLD_PRINT_STATISTICS_DETAILS") == 0 ) {
1904 sEnv.DYLD_PRINT_STATISTICS_DETAILS = true;
1905 }
1906 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
1907 gLinkContext.verboseMapping = true;
1908 }
1909 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
1910 gLinkContext.verboseBind = true;
1911 }
1912 else if ( strcmp(key, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
1913 gLinkContext.verboseWeakBind = true;
1914 }
1915 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
1916 gLinkContext.verboseRebase = true;
1917 }
1918 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
1919 gLogAPIs = true;
1920 }
1921 #if SUPPORT_ACCELERATE_TABLES
1922 else if ( strcmp(key, "DYLD_PRINT_APIS_APP") == 0 ) {
1923 gLogAppAPIs = true;
1924 }
1925 #endif
1926 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
1927 gLinkContext.verboseWarnings = true;
1928 }
1929 else if ( strcmp(key, "DYLD_PRINT_RPATHS") == 0 ) {
1930 gLinkContext.verboseRPaths = true;
1931 }
1932 else if ( strcmp(key, "DYLD_PRINT_CS_NOTIFICATIONS") == 0 ) {
1933 sEnv.DYLD_PRINT_CS_NOTIFICATIONS = true;
1934 }
1935 else if ( strcmp(key, "DYLD_PRINT_INTERPOSING") == 0 ) {
1936 gLinkContext.verboseInterposing = true;
1937 }
1938 else if ( strcmp(key, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
1939 gLinkContext.verboseCodeSignatures = true;
1940 }
1941 else if ( (strcmp(key, "DYLD_SHARED_REGION") == 0) && !sSafeMode ) {
1942 if ( strcmp(value, "private") == 0 ) {
1943 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
1944 }
1945 else if ( strcmp(value, "avoid") == 0 ) {
1946 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
1947 }
1948 else if ( strcmp(value, "use") == 0 ) {
1949 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1950 }
1951 else if ( value[0] == '\0' ) {
1952 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
1953 }
1954 else {
1955 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
1956 }
1957 }
1958 else if ( (strcmp(key, "DYLD_SHARED_CACHE_DIR") == 0) && !sSafeMode ) {
1959 sSharedCacheOverrideDir = value;
1960 }
1961 else if ( strcmp(key, "DYLD_USE_CLOSURES") == 0 ) {
1962 if ( dyld3::loader::internalInstall() )
1963 sEnableClosures = true;
1964 }
1965 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
1966 if ( strcmp(value, "all") == 0 ) {
1967 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
1968 }
1969 else if ( strcmp(value, "app") == 0 ) {
1970 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
1971 }
1972 else if ( strcmp(value, "nonsplit") == 0 ) {
1973 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1974 }
1975 else if ( value[0] == '\0' ) {
1976 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
1977 }
1978 else {
1979 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
1980 }
1981 }
1982 #if SUPPORT_VERSIONED_PATHS
1983 else if ( strcmp(key, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
1984 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_LIBRARY_PATH);
1985 #if SUPPORT_ACCELERATE_TABLES
1986 sDisableAcceleratorTables = true;
1987 #endif
1988 }
1989 else if ( strcmp(key, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
1990 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_FRAMEWORK_PATH);
1991 #if SUPPORT_ACCELERATE_TABLES
1992 sDisableAcceleratorTables = true;
1993 #endif
1994 }
1995 #endif
1996 #if !TARGET_IPHONE_SIMULATOR
1997 else if ( (strcmp(key, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir == NULL) && !sSafeMode ) {
1998 int fd = open(value, O_WRONLY | O_CREAT | O_APPEND, 0644);
1999 if ( fd != -1 ) {
2000 sLogfile = fd;
2001 sLogToFile = true;
2002 }
2003 else {
2004 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value, errno);
2005 }
2006 }
2007 else if ( (strcmp(key, "DYLD_SKIP_MAIN") == 0)) {
2008 if ( dyld3::loader::internalInstall() )
2009 sSkipMain = true;
2010 }
2011 #endif
2012 else {
2013 dyld::warn("unknown environment variable: %s\n", key);
2014 }
2015 }
2016
2017
2018 #if SUPPORT_LC_DYLD_ENVIRONMENT
2019 static void checkLoadCommandEnvironmentVariables()
2020 {
2021 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
2022 const uint32_t cmd_count = sMainExecutableMachHeader->ncmds;
2023 const struct load_command* const cmds = (struct load_command*)(((char*)sMainExecutableMachHeader)+sizeof(macho_header));
2024 const struct load_command* cmd = cmds;
2025 for (uint32_t i = 0; i < cmd_count; ++i) {
2026 switch (cmd->cmd) {
2027 case LC_DYLD_ENVIRONMENT:
2028 {
2029 const struct dylinker_command* envcmd = (struct dylinker_command*)cmd;
2030 const char* keyEqualsValue = (char*)envcmd + envcmd->name.offset;
2031 char mainExecutableDir[strlen(sExecPath)+2];
2032 strcpy(mainExecutableDir, sExecPath);
2033 char* lastSlash = strrchr(mainExecutableDir, '/');
2034 if ( lastSlash != NULL)
2035 lastSlash[1] = '\0';
2036 // only process variables that start with DYLD_ and end in _PATH
2037 if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
2038 const char* equals = strchr(keyEqualsValue, '=');
2039 if ( equals != NULL ) {
2040 if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
2041 const char* value = &equals[1];
2042 const size_t keyLen = equals-keyEqualsValue;
2043 // <rdar://problem/22799635> don't let malformed load command overflow stack
2044 if ( keyLen < 40 ) {
2045 char key[keyLen+1];
2046 strncpy(key, keyEqualsValue, keyLen);
2047 key[keyLen] = '\0';
2048 //dyld::log("processing: %s\n", keyEqualsValue);
2049 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
2050 processDyldEnvironmentVariable(key, value, mainExecutableDir);
2051 }
2052 }
2053 }
2054 }
2055 }
2056 break;
2057 }
2058 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2059 }
2060 }
2061 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2062
2063
2064 static bool hasCodeSignatureLoadCommand(const macho_header* mh)
2065 {
2066 const uint32_t cmd_count = mh->ncmds;
2067 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2068 const struct load_command* cmd = cmds;
2069 for (uint32_t i = 0; i < cmd_count; ++i) {
2070 if (cmd->cmd == LC_CODE_SIGNATURE)
2071 return true;
2072 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2073 }
2074 return false;
2075 }
2076
2077
2078 #if SUPPORT_VERSIONED_PATHS
2079 static void checkVersionedPaths()
2080 {
2081 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
2082 if ( sEnv.DYLD_VERSIONED_LIBRARY_PATH != NULL ) {
2083 for(const char* const* lp = sEnv.DYLD_VERSIONED_LIBRARY_PATH; *lp != NULL; ++lp) {
2084 checkDylibOverridesInDir(*lp);
2085 }
2086 }
2087
2088 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
2089 if ( sEnv.DYLD_VERSIONED_FRAMEWORK_PATH != NULL ) {
2090 for(const char* const* fp = sEnv.DYLD_VERSIONED_FRAMEWORK_PATH; *fp != NULL; ++fp) {
2091 checkFrameworkOverridesInDir(*fp);
2092 }
2093 }
2094 }
2095 #endif
2096
2097
2098 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2099 //
2100 // For security, setuid programs ignore DYLD_* environment variables.
2101 // Additionally, the DYLD_* enviroment variables are removed
2102 // from the environment, so that any child processes don't see them.
2103 //
2104 static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
2105 {
2106 #if SUPPORT_LC_DYLD_ENVIRONMENT
2107 checkLoadCommandEnvironmentVariables();
2108 #endif
2109
2110 // Are we testing dyld on an internal config?
2111 if ( _simple_getenv(envp, "DYLD_SKIP_MAIN") != NULL ) {
2112 if ( dyld3::loader::internalInstall() )
2113 sSkipMain = true;
2114 }
2115
2116 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
2117 int removedCount = 0;
2118 const char** d = envp;
2119 for(const char** s = envp; *s != NULL; s++) {
2120
2121 if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
2122 *d++ = *s;
2123 }
2124 else {
2125 ++removedCount;
2126 }
2127 }
2128 *d++ = NULL;
2129 // slide apple parameters
2130 if ( removedCount > 0 ) {
2131 *applep = d;
2132 do {
2133 *d = d[removedCount];
2134 } while ( *d++ != NULL );
2135 for(int i=0; i < removedCount; ++i)
2136 *d++ = NULL;
2137 }
2138
2139 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
2140 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
2141 sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
2142
2143 if ( removedCount > 0 )
2144 strlcat(sLoadingCrashMessage, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage));
2145 }
2146 #endif
2147
2148 static void defaultUninitializedFallbackPaths(const char* envp[])
2149 {
2150 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2151 if ( gLinkContext.processIsRestricted ) {
2152 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sRestrictedFrameworkFallbackPaths;
2153 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sRestrictedLibraryFallbackPaths;
2154 return;
2155 }
2156
2157 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
2158 const char* home = _simple_getenv(envp, "HOME");;
2159 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
2160 const char** fpaths = sFrameworkFallbackPaths;
2161 if ( home == NULL )
2162 removePathWithPrefix(fpaths, "$HOME");
2163 else
2164 paths_expand_roots(fpaths, "$HOME", home);
2165 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = fpaths;
2166 }
2167
2168 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
2169 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
2170 const char** lpaths = sLibraryFallbackPaths;
2171 if ( home == NULL )
2172 removePathWithPrefix(lpaths, "$HOME");
2173 else
2174 paths_expand_roots(lpaths, "$HOME", home);
2175 sEnv.DYLD_FALLBACK_LIBRARY_PATH = lpaths;
2176 }
2177 #else
2178 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL )
2179 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sFrameworkFallbackPaths;
2180
2181 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL )
2182 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sLibraryFallbackPaths;
2183 #endif
2184 }
2185
2186
2187 static void checkEnvironmentVariables(const char* envp[])
2188 {
2189 if ( sEnvMode == envNone )
2190 return;
2191 const char** p;
2192 for(p = envp; *p != NULL; p++) {
2193 const char* keyEqualsValue = *p;
2194 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
2195 const char* equals = strchr(keyEqualsValue, '=');
2196 if ( equals != NULL ) {
2197 strlcat(sLoadingCrashMessage, "\n", sizeof(sLoadingCrashMessage));
2198 strlcat(sLoadingCrashMessage, keyEqualsValue, sizeof(sLoadingCrashMessage));
2199 const char* value = &equals[1];
2200 const size_t keyLen = equals-keyEqualsValue;
2201 char key[keyLen+1];
2202 strncpy(key, keyEqualsValue, keyLen);
2203 key[keyLen] = '\0';
2204 if ( (sEnvMode == envPrintOnly) && (strncmp(key, "DYLD_PRINT_", 11) != 0) )
2205 continue;
2206 processDyldEnvironmentVariable(key, value, NULL);
2207 }
2208 }
2209 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
2210 const char* path = &keyEqualsValue[16];
2211 sEnv.LD_LIBRARY_PATH = parseColonList(path, NULL);
2212 }
2213 }
2214
2215 #if SUPPORT_LC_DYLD_ENVIRONMENT
2216 checkLoadCommandEnvironmentVariables();
2217 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2218
2219 #if SUPPORT_ROOT_PATH
2220 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
2221 if ( (gLinkContext.imageSuffix != NULL) && (gLinkContext.rootPaths != NULL) ) {
2222 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
2223 gLinkContext.imageSuffix = NULL;
2224 }
2225 #endif
2226 }
2227
2228 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
2229 static bool isGCProgram(const macho_header* mh, uintptr_t slide)
2230 {
2231 const uint32_t cmd_count = mh->ncmds;
2232 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2233 const struct load_command* cmd = cmds;
2234 for (uint32_t i = 0; i < cmd_count; ++i) {
2235 switch (cmd->cmd) {
2236 case LC_SEGMENT_COMMAND:
2237 {
2238 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2239 if (strcmp(seg->segname, "__DATA") == 0) {
2240 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2241 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2242 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2243 if (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) {
2244 const uint32_t* objcInfo = (uint32_t*)(sect->addr + slide);
2245 return (objcInfo[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
2246 }
2247 }
2248 }
2249 }
2250 break;
2251 }
2252 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2253 }
2254 return false;
2255 }
2256 #endif
2257
2258 static void getHostInfo(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide)
2259 {
2260 #if CPU_SUBTYPES_SUPPORTED
2261 #if __ARM_ARCH_7K__
2262 sHostCPU = CPU_TYPE_ARM;
2263 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7K;
2264 #elif __ARM_ARCH_7A__
2265 sHostCPU = CPU_TYPE_ARM;
2266 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7;
2267 #elif __ARM_ARCH_6K__
2268 sHostCPU = CPU_TYPE_ARM;
2269 sHostCPUsubtype = CPU_SUBTYPE_ARM_V6;
2270 #elif __ARM_ARCH_7F__
2271 sHostCPU = CPU_TYPE_ARM;
2272 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7F;
2273 #elif __ARM_ARCH_7S__
2274 sHostCPU = CPU_TYPE_ARM;
2275 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7S;
2276 #elif __arm64e__
2277 sHostCPU = CPU_TYPE_ARM64;
2278 sHostCPUsubtype = CPU_SUBTYPE_ARM64_E;
2279 #elif __arm64__
2280 sHostCPU = CPU_TYPE_ARM64;
2281 sHostCPUsubtype = CPU_SUBTYPE_ARM64_V8;
2282 #else
2283 struct host_basic_info info;
2284 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
2285 mach_port_t hostPort = mach_host_self();
2286 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
2287 if ( result != KERN_SUCCESS )
2288 throw "host_info() failed";
2289 sHostCPU = info.cpu_type;
2290 sHostCPUsubtype = info.cpu_subtype;
2291 mach_port_deallocate(mach_task_self(), hostPort);
2292 #if __x86_64__
2293 // host_info returns CPU_TYPE_I386 even for x86_64. Override that here so that
2294 // we don't need to mask the cpu type later.
2295 sHostCPU = CPU_TYPE_X86_64;
2296 #if !TARGET_IPHONE_SIMULATOR
2297 sHaswell = (sHostCPUsubtype == CPU_SUBTYPE_X86_64_H);
2298 // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
2299 if ( sHaswell ) {
2300 if ( isGCProgram(mainExecutableMH, mainExecutableSlide) ) {
2301 // When running a GC program on a haswell machine, don't use and 'h slices
2302 sHostCPUsubtype = CPU_SUBTYPE_X86_64_ALL;
2303 sHaswell = false;
2304 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2305 }
2306 }
2307 #endif
2308 #endif
2309 #endif
2310 #endif
2311 }
2312
2313 static void checkSharedRegionDisable(const mach_header* mainExecutableMH)
2314 {
2315 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2316 // if main executable has segments that overlap the shared region,
2317 // then disable using the shared region
2318 dyld3::MachOParser parser(mainExecutableMH);
2319 uintptr_t slide = parser.getSlide();
2320 dyld3::launch_cache::MemoryRange sharedRegion = { (void*)(long)(SHARED_REGION_BASE), SHARED_REGION_SIZE };
2321 __block bool disable = false;
2322 parser.forEachSegment(^(const char *segName, uint32_t fileOffset, uint32_t fileSize, uint64_t vmAddr, uint64_t vmSize, uint8_t protections, bool &stop) {
2323 dyld3::launch_cache::MemoryRange segRegion = { (void*)(long)(vmAddr+slide), vmSize };
2324 if ( segRegion.intersects(sharedRegion) )
2325 disable = true;
2326 });
2327 if ( disable ) {
2328 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2329 if ( gLinkContext.verboseMapping )
2330 dyld::warn("disabling shared region because main executable overlaps\n");
2331 }
2332 #if __i386__
2333 if ( gLinkContext.processIsRestricted ) {
2334 // <rdar://problem/15280847> use private or no shared region for suid processes
2335 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
2336 }
2337 #endif
2338 #endif
2339 // iOS cannot run without shared region
2340 }
2341
2342 bool validImage(const ImageLoader* possibleImage)
2343 {
2344 const size_t imageCount = sAllImages.size();
2345 for(size_t i=0; i < imageCount; ++i) {
2346 if ( possibleImage == sAllImages[i] ) {
2347 return true;
2348 }
2349 }
2350 return false;
2351 }
2352
2353 uint32_t getImageCount()
2354 {
2355 return (uint32_t)sAllImages.size();
2356 }
2357
2358 ImageLoader* getIndexedImage(unsigned int index)
2359 {
2360 if ( index < sAllImages.size() )
2361 return sAllImages[index];
2362 return NULL;
2363 }
2364
2365 ImageLoader* findImageByMachHeader(const struct mach_header* target)
2366 {
2367 return findMappedRange((uintptr_t)target);
2368 }
2369
2370
2371 ImageLoader* findImageContainingAddress(const void* addr)
2372 {
2373 #if SUPPORT_ACCELERATE_TABLES
2374 if ( sAllCacheImagesProxy != NULL ) {
2375 const mach_header* mh;
2376 const char* path;
2377 unsigned index;
2378 if ( sAllCacheImagesProxy->addressInCache(addr, &mh, &path, &index) )
2379 return sAllCacheImagesProxy;
2380 }
2381 #endif
2382 return findMappedRange((uintptr_t)addr);
2383 }
2384
2385
2386 ImageLoader* findImageContainingSymbol(const void* symbol)
2387 {
2388 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2389 ImageLoader* anImage = *it;
2390 if ( anImage->containsSymbol(symbol) )
2391 return anImage;
2392 }
2393 return NULL;
2394 }
2395
2396
2397
2398 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
2399 {
2400 const size_t imageCount = sAllImages.size();
2401 for(size_t i=0; i < imageCount; ++i) {
2402 ImageLoader* anImage = sAllImages[i];
2403 (*callback)(anImage, userData);
2404 }
2405 }
2406
2407 ImageLoader* findLoadedImage(const struct stat& stat_buf)
2408 {
2409 const size_t imageCount = sAllImages.size();
2410 for(size_t i=0; i < imageCount; ++i){
2411 ImageLoader* anImage = sAllImages[i];
2412 if ( anImage->statMatch(stat_buf) )
2413 return anImage;
2414 }
2415 return NULL;
2416 }
2417
2418 // based on ANSI-C strstr()
2419 static const char* strrstr(const char* str, const char* sub)
2420 {
2421 const size_t sublen = strlen(sub);
2422 for(const char* p = &str[strlen(str)]; p != str; --p) {
2423 if ( strncmp(p, sub, sublen) == 0 )
2424 return p;
2425 }
2426 return NULL;
2427 }
2428
2429
2430 //
2431 // Find framework path
2432 //
2433 // /path/foo.framework/foo => foo.framework/foo
2434 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
2435 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
2436 // /path/foo.framework/Libraries/bar.dylb => NULL
2437 // /path/foo.framework/bar => NULL
2438 //
2439 // Returns NULL if not a framework path
2440 //
2441 static const char* getFrameworkPartialPath(const char* path)
2442 {
2443 const char* dirDot = strrstr(path, ".framework/");
2444 if ( dirDot != NULL ) {
2445 const char* dirStart = dirDot;
2446 for ( ; dirStart >= path; --dirStart) {
2447 if ( (*dirStart == '/') || (dirStart == path) ) {
2448 const char* frameworkStart = &dirStart[1];
2449 if ( dirStart == path )
2450 --frameworkStart;
2451 size_t len = dirDot - frameworkStart;
2452 char framework[len+1];
2453 strncpy(framework, frameworkStart, len);
2454 framework[len] = '\0';
2455 const char* leaf = strrchr(path, '/');
2456 if ( leaf != NULL ) {
2457 if ( strcmp(framework, &leaf[1]) == 0 ) {
2458 return frameworkStart;
2459 }
2460 if ( gLinkContext.imageSuffix != NULL ) {
2461 // some debug frameworks have install names that end in _debug
2462 if ( strncmp(framework, &leaf[1], len) == 0 ) {
2463 if ( strcmp( gLinkContext.imageSuffix, &leaf[len+1]) == 0 )
2464 return frameworkStart;
2465 }
2466 }
2467 }
2468 }
2469 }
2470 }
2471 return NULL;
2472 }
2473
2474
2475 static const char* getLibraryLeafName(const char* path)
2476 {
2477 const char* start = strrchr(path, '/');
2478 if ( start != NULL )
2479 return &start[1];
2480 else
2481 return path;
2482 }
2483
2484
2485 // only for architectures that use cpu-sub-types
2486 #if CPU_SUBTYPES_SUPPORTED
2487
2488 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
2489
2490
2491 //
2492 // A fat file may contain multiple sub-images for the same CPU type.
2493 // In that case, dyld picks which sub-image to use by scanning a table
2494 // of preferred cpu-sub-types for the running cpu.
2495 //
2496 // There is one row in the table for each cpu-sub-type on which dyld might run.
2497 // The first entry in a row is that cpu-sub-type. It is followed by all
2498 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2499 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2500 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2501 //
2502
2503
2504 #if __arm__
2505 //
2506 // ARM sub-type lists
2507 //
2508 const int kARM_RowCount = 8;
2509 static const cpu_subtype_t kARM[kARM_RowCount][9] = {
2510
2511 // armv7f can run: v7f, v7, v6, v5, and v4
2512 { CPU_SUBTYPE_ARM_V7F, CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST },
2513
2514 // armv7k can run: v7k
2515 { CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_END_OF_LIST },
2516
2517 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2518 { CPU_SUBTYPE_ARM_V7S, CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V7F, CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST },
2519
2520 // armv7 can run: v7, v6, v5, and v4
2521 { CPU_SUBTYPE_ARM_V7, CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST },
2522
2523 // armv6 can run: v6, v5, and v4
2524 { CPU_SUBTYPE_ARM_V6, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
2525
2526 // xscale can run: xscale, v5, and v4
2527 { CPU_SUBTYPE_ARM_XSCALE, CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
2528
2529 // armv5 can run: v5 and v4
2530 { CPU_SUBTYPE_ARM_V5TEJ, CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
2531
2532 // armv4 can run: v4
2533 { CPU_SUBTYPE_ARM_V4T, CPU_SUBTYPE_ARM_ALL, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST, CPU_SUBTYPE_END_OF_LIST },
2534 };
2535 #endif
2536
2537 #if __arm64__
2538 //
2539 // ARM64 sub-type lists
2540 //
2541 const int kARM64_RowCount = 2;
2542 static const cpu_subtype_t kARM64[kARM64_RowCount][4] = {
2543
2544 // armv64e can run: 64e, 64
2545 { CPU_SUBTYPE_ARM64_E, CPU_SUBTYPE_ARM64_V8, CPU_SUBTYPE_ARM64_ALL, CPU_SUBTYPE_END_OF_LIST },
2546
2547 // armv64 can run: 64
2548 { CPU_SUBTYPE_ARM64_V8, CPU_SUBTYPE_ARM64_ALL, CPU_SUBTYPE_END_OF_LIST },
2549 };
2550 #endif
2551
2552 #if __x86_64__
2553 //
2554 // x86_64 sub-type lists
2555 //
2556 const int kX86_64_RowCount = 2;
2557 static const cpu_subtype_t kX86_64[kX86_64_RowCount][5] = {
2558
2559 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2560 { CPU_SUBTYPE_X86_64_H, (cpu_subtype_t)(CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_H), (cpu_subtype_t)(CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL), CPU_SUBTYPE_X86_64_ALL, CPU_SUBTYPE_END_OF_LIST },
2561
2562 // x86_64 can run: x86_64(lib) and x86_64
2563 { CPU_SUBTYPE_X86_64_ALL, (cpu_subtype_t)(CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL), CPU_SUBTYPE_END_OF_LIST },
2564
2565 };
2566 #endif
2567
2568
2569 // scan the tables above to find the cpu-sub-type-list for this machine
2570 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
2571 {
2572 switch (cpu) {
2573 #if __arm__
2574 case CPU_TYPE_ARM:
2575 for (int i=0; i < kARM_RowCount ; ++i) {
2576 if ( kARM[i][0] == subtype )
2577 return kARM[i];
2578 }
2579 break;
2580 #endif
2581 #if __arm64__
2582 case CPU_TYPE_ARM64:
2583 for (int i=0; i < kARM64_RowCount ; ++i) {
2584 if ( kARM64[i][0] == subtype )
2585 return kARM64[i];
2586 }
2587 break;
2588 #endif
2589 #if __x86_64__
2590 case CPU_TYPE_X86_64:
2591 for (int i=0; i < kX86_64_RowCount ; ++i) {
2592 if ( kX86_64[i][0] == subtype )
2593 return kX86_64[i];
2594 }
2595 break;
2596 #endif
2597 }
2598 return NULL;
2599 }
2600
2601
2602
2603
2604 // scan fat table-of-contents for best most preferred subtype
2605 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
2606 {
2607 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2608 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
2609 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
2610 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
2611 && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
2612 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
2613 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
2614 return true;
2615 }
2616 }
2617 }
2618 return false;
2619 }
2620
2621 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2622 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
2623 {
2624 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2625 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2626 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
2627 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
2628 *offset = OSSwapBigToHostInt32(archs[i].offset);
2629 *len = OSSwapBigToHostInt32(archs[i].size);
2630 return true;
2631 }
2632 }
2633 return false;
2634 }
2635
2636 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2637 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
2638 {
2639 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2640 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2641 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
2642 switch (cpu) {
2643 #if __arm__
2644 case CPU_TYPE_ARM:
2645 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
2646 *offset = OSSwapBigToHostInt32(archs[i].offset);
2647 *len = OSSwapBigToHostInt32(archs[i].size);
2648 return true;
2649 }
2650 break;
2651 #endif
2652 #if __arm64__
2653 case CPU_TYPE_ARM64:
2654 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM64_ALL ) {
2655 *offset = OSSwapBigToHostInt32(archs[i].offset);
2656 *len = OSSwapBigToHostInt32(archs[i].size);
2657 return true;
2658 }
2659 break;
2660 #endif
2661 #if __x86_64__
2662 case CPU_TYPE_X86_64:
2663 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_X86_64_ALL ) {
2664 *offset = OSSwapBigToHostInt32(archs[i].offset);
2665 *len = OSSwapBigToHostInt32(archs[i].size);
2666 return true;
2667 }
2668 break;
2669 #endif
2670 }
2671 }
2672 }
2673 return false;
2674 }
2675
2676 #endif // CPU_SUBTYPES_SUPPORTED
2677
2678
2679 //
2680 // Validate the fat_header and fat_arch array:
2681 //
2682 // 1) arch count would not cause array to extend past 4096 byte read buffer
2683 // 2) no slice overlaps the fat_header and arch array
2684 // 3) arch list does not contain duplicate cputype/cpusubtype tuples
2685 // 4) arch list does not have two overlapping slices.
2686 //
2687 static bool fatValidate(const fat_header* fh)
2688 {
2689 if ( fh->magic != OSSwapBigToHostInt32(FAT_MAGIC) )
2690 return false;
2691
2692 // since only first 4096 bytes of file read, we can only handle up to 204 slices.
2693 const uint32_t sliceCount = OSSwapBigToHostInt32(fh->nfat_arch);
2694 if ( sliceCount > 204 )
2695 return false;
2696
2697 // compare all slices looking for conflicts
2698 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2699 for (uint32_t i=0; i < sliceCount; ++i) {
2700 uint32_t i_offset = OSSwapBigToHostInt32(archs[i].offset);
2701 uint32_t i_size = OSSwapBigToHostInt32(archs[i].size);
2702 uint32_t i_cputype = OSSwapBigToHostInt32(archs[i].cputype);
2703 uint32_t i_cpusubtype = OSSwapBigToHostInt32(archs[i].cpusubtype);
2704 uint32_t i_end = i_offset + i_size;
2705 // slice cannot overlap with header
2706 if ( i_offset < 4096 )
2707 return false;
2708 // slice size cannot overflow
2709 if ( i_end < i_offset )
2710 return false;
2711 for (uint32_t j=i+1; j < sliceCount; ++j) {
2712 uint32_t j_offset = OSSwapBigToHostInt32(archs[j].offset);
2713 uint32_t j_size = OSSwapBigToHostInt32(archs[j].size);
2714 uint32_t j_cputype = OSSwapBigToHostInt32(archs[j].cputype);
2715 uint32_t j_cpusubtype = OSSwapBigToHostInt32(archs[j].cpusubtype);
2716 uint32_t j_end = j_offset + j_size;
2717 // duplicate slices types not allowed
2718 if ( (i_cputype == j_cputype) && (i_cpusubtype == j_cpusubtype) )
2719 return false;
2720 // slice size cannot overflow
2721 if ( j_end < j_offset )
2722 return false;
2723 // check for overlap of slices
2724 if ( i_offset <= j_offset ) {
2725 if ( j_offset < i_end )
2726 return false; // j overlaps end of i
2727 }
2728 else {
2729 // j overlaps end of i
2730 if ( i_offset < j_end )
2731 return false; // i overlaps end of j
2732 }
2733 }
2734 }
2735 return true;
2736 }
2737
2738 //
2739 // A fat file may contain multiple sub-images for the same cpu-type,
2740 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2741 // This routine picks the optimal sub-image.
2742 //
2743 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
2744 {
2745 if ( !fatValidate(fh) )
2746 return false;
2747
2748 #if CPU_SUBTYPES_SUPPORTED
2749 // assume all dylibs loaded must have same cpu type as main executable
2750 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
2751
2752 // We only know the subtype to use if the main executable cpu type matches the host
2753 if ( cpu == sHostCPU ) {
2754 // get preference ordered list of subtypes
2755 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
2756
2757 // use ordered list to find best sub-image in fat file
2758 if ( subTypePreferenceList != NULL ) {
2759 if ( fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len) )
2760 return true;
2761 }
2762
2763 // if running cpu is not in list, try for an exact match
2764 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
2765 return true;
2766 }
2767
2768 // running on an uknown cpu, can only load generic code
2769 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
2770 #else
2771 // just find first slice with matching architecture
2772 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2773 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2774 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
2775 *offset = OSSwapBigToHostInt32(archs[i].offset);
2776 *len = OSSwapBigToHostInt32(archs[i].size);
2777 return true;
2778 }
2779 }
2780 return false;
2781 #endif
2782 }
2783
2784
2785
2786 //
2787 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2788 // on the current processor. //
2789 bool isCompatibleMachO(const uint8_t* firstPage, const char* path)
2790 {
2791 #if CPU_SUBTYPES_SUPPORTED
2792 // It is deemed compatible if any of the following are true:
2793 // 1) mach_header subtype is in list of compatible subtypes for running processor
2794 // 2) mach_header subtype is same as running processor subtype
2795 // 3) mach_header subtype runs on all processor variants
2796 const mach_header* mh = (mach_header*)firstPage;
2797 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2798 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2799 if ( mh->cputype == sHostCPU ) {
2800 // get preference ordered list of subtypes that this machine can use
2801 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
2802 if ( subTypePreferenceList != NULL ) {
2803 // if image's subtype is in the list, it is compatible
2804 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
2805 if ( *p == mh->cpusubtype )
2806 return true;
2807 }
2808 // have list and not in list, so not compatible
2809 throwf("incompatible cpu-subtype: 0x%08X in %s", mh->cpusubtype, path);
2810 }
2811 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2812 if ( mh->cpusubtype == sHostCPUsubtype )
2813 return true;
2814 }
2815
2816 // cpu type has no ordered list of subtypes
2817 switch (mh->cputype) {
2818 case CPU_TYPE_I386:
2819 case CPU_TYPE_X86_64:
2820 // subtypes are not used or these architectures
2821 return true;
2822 }
2823 }
2824 }
2825 #else
2826 // For architectures that don't support cpu-sub-types
2827 // this just check the cpu type.
2828 const mach_header* mh = (mach_header*)firstPage;
2829 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2830 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2831 return true;
2832 }
2833 }
2834 #endif
2835 return false;
2836 }
2837
2838
2839
2840
2841 // The kernel maps in main executable before dyld gets control. We need to
2842 // make an ImageLoader* for the already mapped in main executable.
2843 static ImageLoaderMachO* instantiateFromLoadedImage(const macho_header* mh, uintptr_t slide, const char* path)
2844 {
2845 // try mach-o loader
2846 if ( isCompatibleMachO((const uint8_t*)mh, path) ) {
2847 ImageLoader* image = ImageLoaderMachO::instantiateMainExecutable(mh, slide, path, gLinkContext);
2848 addImage(image);
2849 return (ImageLoaderMachO*)image;
2850 }
2851
2852 throw "main executable not a known format";
2853 }
2854
2855 #if SUPPORT_ACCELERATE_TABLES
2856 static bool dylibsCanOverrideCache()
2857 {
2858 if ( !dyld3::loader::internalInstall() )
2859 return false;
2860 return ( (sSharedCacheLoadInfo.loadAddress != nullptr) && (sSharedCacheLoadInfo.loadAddress->header.cacheType == kDyldSharedCacheTypeDevelopment) );
2861 }
2862 #endif
2863
2864 const void* imMemorySharedCacheHeader()
2865 {
2866 return sSharedCacheLoadInfo.loadAddress;
2867 }
2868
2869
2870 const char* getStandardSharedCacheFilePath()
2871 {
2872 if ( sSharedCacheLoadInfo.loadAddress != nullptr )
2873 return sSharedCacheLoadInfo.path;
2874 else
2875 return nullptr;
2876 }
2877
2878
2879 static bool findInSharedCacheImage(const char* path, bool searchByPath, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
2880 {
2881 dyld3::SharedCacheFindDylibResults results;
2882 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &results) ) {
2883 *mh = (macho_header*)results.mhInCache;
2884 *pathInCache = results.pathInCache;
2885 *slide = results.slideInCache;
2886 return true;
2887 }
2888 return false;
2889 }
2890
2891 bool inSharedCache(const char* path)
2892 {
2893 return dyld3::pathIsInSharedCacheImage(sSharedCacheLoadInfo, path);
2894 }
2895
2896
2897 static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
2898 {
2899 // now sanity check that this loaded image does not have the same install path as any existing image
2900 const char* loadedImageInstallPath = image->getInstallPath();
2901 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
2902 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2903 ImageLoader* anImage = *it;
2904 const char* installPath = anImage->getInstallPath();
2905 if ( installPath != NULL) {
2906 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
2907 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
2908 removeImage(image);
2909 ImageLoader::deleteImage(image);
2910 return anImage;
2911 }
2912 }
2913 }
2914 }
2915
2916 // some API's restrict what they can load
2917 if ( context.mustBeBundle && !image->isBundle() )
2918 throw "not a bundle";
2919 if ( context.mustBeDylib && !image->isDylib() )
2920 throw "not a dylib";
2921
2922 // regular main executables cannot be loaded
2923 if ( image->isExecutable() ) {
2924 if ( !context.canBePIE || !image->isPositionIndependentExecutable() )
2925 throw "can't load a main executable";
2926 }
2927
2928 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
2929 if ( ! image->isBundle() )
2930 addImage(image);
2931
2932 return image;
2933 }
2934
2935 #if TARGET_IPHONE_SIMULATOR
2936 static bool isSimulatorBinary(const uint8_t* firstPages, const char* path)
2937 {
2938 const macho_header* mh = (macho_header*)firstPages;
2939 const uint32_t cmd_count = mh->ncmds;
2940 const load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2941 const load_command* const cmdsEnd = (load_command*)((char*)cmds + mh->sizeofcmds);
2942 const struct load_command* cmd = cmds;
2943 for (uint32_t i = 0; i < cmd_count; ++i) {
2944 switch (cmd->cmd) {
2945 #if TARGET_OS_WATCH
2946 case LC_VERSION_MIN_WATCHOS:
2947 return true;
2948 #elif TARGET_OS_TV
2949 case LC_VERSION_MIN_TVOS:
2950 return true;
2951 #elif TARGET_OS_IOS
2952 case LC_VERSION_MIN_IPHONEOS:
2953 return true;
2954 #endif
2955 case LC_VERSION_MIN_MACOSX:
2956 // grandfather in a few libSystem dylibs
2957 if ((strcmp(path, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
2958 (strcmp(path, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
2959 (strcmp(path, "/usr/lib/system/libsystem_pthread.dylib") == 0))
2960 return true;
2961 return false;
2962 }
2963 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2964 if ( cmd > cmdsEnd )
2965 return false;
2966 }
2967 return false;
2968 }
2969 #endif
2970
2971 // map in file and instantiate an ImageLoader
2972 static ImageLoader* loadPhase6(int fd, const struct stat& stat_buf, const char* path, const LoadContext& context)
2973 {
2974 //dyld::log("%s(%s)\n", __func__ , path);
2975 uint64_t fileOffset = 0;
2976 uint64_t fileLength = stat_buf.st_size;
2977
2978 // validate it is a file (not directory)
2979 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
2980 throw "not a file";
2981
2982 uint8_t firstPages[MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE];
2983 bool shortPage = false;
2984
2985 // min mach-o file is 4K
2986 if ( fileLength < 4096 ) {
2987 if ( pread(fd, firstPages, (size_t)fileLength, 0) != (ssize_t)fileLength )
2988 throwf("pread of short file failed: %d", errno);
2989 shortPage = true;
2990 }
2991 else {
2992 // optimistically read only first 4KB
2993 if ( pread(fd, firstPages, 4096, 0) != 4096 )
2994 throwf("pread of first 4K failed: %d", errno);
2995 }
2996
2997 // if fat wrapper, find usable sub-file
2998 const fat_header* fileStartAsFat = (fat_header*)firstPages;
2999 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3000 if ( OSSwapBigToHostInt32(fileStartAsFat->nfat_arch) > ((4096 - sizeof(fat_header)) / sizeof(fat_arch)) )
3001 throwf("fat header too large: %u entries", OSSwapBigToHostInt32(fileStartAsFat->nfat_arch));
3002 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
3003 if ( (fileOffset+fileLength) > (uint64_t)(stat_buf.st_size) )
3004 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf.st_size, fileOffset+fileLength);
3005 if (pread(fd, firstPages, 4096, fileOffset) != 4096)
3006 throwf("pread of fat file failed: %d", errno);
3007 }
3008 else {
3009 throw "no matching architecture in universal wrapper";
3010 }
3011 }
3012
3013 // try mach-o loader
3014 if ( shortPage )
3015 throw "file too short";
3016 if ( isCompatibleMachO(firstPages, path) ) {
3017
3018 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
3019 const mach_header* mh = (mach_header*)firstPages;
3020 switch ( mh->filetype ) {
3021 case MH_EXECUTE:
3022 case MH_DYLIB:
3023 case MH_BUNDLE:
3024 break;
3025 default:
3026 throw "mach-o, but wrong filetype";
3027 }
3028
3029 uint32_t headerAndLoadCommandsSize = sizeof(macho_header) + mh->sizeofcmds;
3030 if ( headerAndLoadCommandsSize > MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE )
3031 throwf("malformed mach-o: load commands size (%u) > %u", headerAndLoadCommandsSize, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE);
3032
3033 if ( headerAndLoadCommandsSize > fileLength )
3034 dyld::throwf("malformed mach-o: load commands size (%u) > mach-o file size (%llu)", headerAndLoadCommandsSize, fileLength);
3035
3036 if ( headerAndLoadCommandsSize > 4096 ) {
3037 // read more pages
3038 unsigned readAmount = headerAndLoadCommandsSize - 4096;
3039 if ( pread(fd, &firstPages[4096], readAmount, fileOffset+4096) != readAmount )
3040 throwf("pread of extra load commands past 4KB failed: %d", errno);
3041 }
3042
3043 #if TARGET_IPHONE_SIMULATOR
3044 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
3045 if ( !isSimulatorBinary(firstPages, path) ) {
3046 #if TARGET_OS_WATCH
3047 throw "mach-o, but not built for watchOS simulator";
3048 #elif TARGET_OS_TV
3049 throw "mach-o, but not built for tvOS simulator";
3050 #else
3051 throw "mach-o, but not built for iOS simulator";
3052 #endif
3053 }
3054 #endif
3055
3056 // instantiate an image
3057 ImageLoader* image = ImageLoaderMachO::instantiateFromFile(path, fd, firstPages, headerAndLoadCommandsSize, fileOffset, fileLength, stat_buf, gLinkContext);
3058
3059 // validate
3060 return checkandAddImage(image, context);
3061 }
3062
3063 // try other file formats here...
3064
3065
3066 // throw error about what was found
3067 switch (*(uint32_t*)firstPages) {
3068 case MH_MAGIC:
3069 case MH_CIGAM:
3070 case MH_MAGIC_64:
3071 case MH_CIGAM_64:
3072 throw "mach-o, but wrong architecture";
3073 default:
3074 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3075 firstPages[0], firstPages[1], firstPages[2], firstPages[3], firstPages[4], firstPages[5], firstPages[6],firstPages[7]);
3076 }
3077 }
3078
3079
3080 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, const struct stat& stat_buf, std::vector<const char*>* exceptions)
3081 {
3082 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3083
3084 // open file (automagically closed when this function exits)
3085 FileOpener file(path);
3086
3087 // just return NULL if file not found, but record any other errors
3088 if ( file.getFileDescriptor() == -1 ) {
3089 int err = errno;
3090 if ( err != ENOENT ) {
3091 const char* newMsg;
3092 if ( (err == EPERM) && sandboxBlockedOpen(path) )
3093 newMsg = dyld::mkstringf("file system sandbox blocked open() of '%s'", path);
3094 else
3095 newMsg = dyld::mkstringf("%s: open() failed with errno=%d", path, err);
3096 exceptions->push_back(newMsg);
3097 }
3098 return NULL;
3099 }
3100
3101 try {
3102 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
3103 }
3104 catch (const char* msg) {
3105 const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
3106 exceptions->push_back(newMsg);
3107 free((void*)msg);
3108 return NULL;
3109 }
3110 }
3111
3112
3113
3114 // try to open file
3115 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3116 {
3117 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3118 #if SUPPORT_ACCELERATE_TABLES
3119 if ( sAllCacheImagesProxy != NULL ) {
3120 if ( sAllCacheImagesProxy->hasDylib(path, &cacheIndex) )
3121 return sAllCacheImagesProxy;
3122 }
3123 #endif
3124 #if TARGET_IPHONE_SIMULATOR
3125 // in simulators, 'path' has DYLD_ROOT_PATH prepended, but cache index does not have the prefix, so use orgPath
3126 const char* pathToFindInCache = orgPath;
3127 #else
3128 const char* pathToFindInCache = path;
3129 #endif
3130 uint statErrNo;
3131 struct stat statBuf;
3132 bool didStat = false;
3133 bool existsOnDisk;
3134 dyld3::SharedCacheFindDylibResults shareCacheResults;
3135 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, pathToFindInCache, &shareCacheResults) ) {
3136 // see if this image in the cache was already loaded via a different path
3137 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
3138 ImageLoader* anImage = *it;
3139 if ( (const mach_header*)anImage->machHeader() == shareCacheResults.mhInCache )
3140 return anImage;
3141 }
3142 // if RTLD_NOLOAD, do nothing if not already loaded
3143 if ( context.dontLoad ) {
3144 // <rdar://33412890> possible that there is an override of cache
3145 if ( my_stat(path, &statBuf) == 0 ) {
3146 ImageLoader* imageLoader = findLoadedImage(statBuf);
3147 if ( imageLoader != NULL )
3148 return imageLoader;
3149 }
3150 return NULL;
3151 }
3152 bool useCache = false;
3153 if ( shareCacheResults.imageData == nullptr ) {
3154 // HACK to support old caches
3155 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3156 didStat = true;
3157 statErrNo = errno;
3158 useCache = !existsOnDisk;
3159 }
3160 else {
3161 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
3162 bzero(&statBuf, sizeof(statBuf));
3163 dyld3::launch_cache::Image image(shareCacheResults.imageData);
3164 if ( image.overridableDylib() ) {
3165 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3166 didStat = true;
3167 statErrNo = errno;
3168 if ( sSharedCacheLoadInfo.loadAddress->header.dylibsExpectedOnDisk ) {
3169 if ( (image.fileModTime() == statBuf.st_mtime) && (image.fileINode() == statBuf.st_ino) )
3170 useCache = true;
3171 }
3172 else {
3173 if ( !existsOnDisk )
3174 useCache = true;
3175 }
3176 }
3177 else {
3178 useCache = true;
3179 }
3180 }
3181 if ( useCache ) {
3182 ImageLoader* imageLoader = ImageLoaderMachO::instantiateFromCache((macho_header*)shareCacheResults.mhInCache, shareCacheResults.pathInCache, shareCacheResults.slideInCache, statBuf, gLinkContext);
3183 return checkandAddImage(imageLoader, context);
3184 }
3185 }
3186
3187 // not in cache or cache not usable
3188 if ( !didStat ) {
3189 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3190 statErrNo = errno;
3191 }
3192 if ( existsOnDisk ) {
3193 // in case image was renamed or found via symlinks, check for inode match
3194 ImageLoader* imageLoader = findLoadedImage(statBuf);
3195 if ( imageLoader != NULL )
3196 return imageLoader;
3197 // do nothing if not already loaded and if RTLD_NOLOAD
3198 if ( context.dontLoad )
3199 return NULL;
3200 // try opening file
3201 imageLoader = loadPhase5open(path, context, statBuf, exceptions);
3202 if ( imageLoader != NULL )
3203 return imageLoader;
3204 }
3205
3206 // just return NULL if file not found, but record any other errors
3207 if ( (statErrNo != ENOENT) && (statErrNo != 0) ) {
3208 if ( (statErrNo == EPERM) && sandboxBlockedStat(path) )
3209 exceptions->push_back(dyld::mkstringf("%s: file system sandbox blocked stat()", path));
3210 else
3211 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, statErrNo));
3212 }
3213 return NULL;
3214 }
3215
3216 // look for path match with existing loaded images
3217 static ImageLoader* loadPhase5check(const char* path, const char* orgPath, const LoadContext& context)
3218 {
3219 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
3220 // search path against load-path and install-path of all already loaded images
3221 uint32_t hash = ImageLoader::hash(path);
3222 //dyld::log("check() hash=%d, path=%s\n", hash, path);
3223 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3224 ImageLoader* anImage = *it;
3225 // check hash first to cut down on strcmp calls
3226 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
3227 if ( anImage->getPathHash() == hash ) {
3228 if ( strcmp(path, anImage->getPath()) == 0 ) {
3229 // if we are looking for a dylib don't return something else
3230 if ( !context.mustBeDylib || anImage->isDylib() )
3231 return anImage;
3232 }
3233 }
3234 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
3235 const char* installPath = anImage->getInstallPath();
3236 if ( installPath != NULL) {
3237 if ( strcmp(path, installPath) == 0 ) {
3238 // if we are looking for a dylib don't return something else
3239 if ( !context.mustBeDylib || anImage->isDylib() )
3240 return anImage;
3241 }
3242 }
3243 }
3244 // an install name starting with @rpath should match by install name, not just real path
3245 if ( (orgPath[0] == '@') && (strncmp(orgPath, "@rpath/", 7) == 0) ) {
3246 const char* installPath = anImage->getInstallPath();
3247 if ( installPath != NULL) {
3248 if ( !context.mustBeDylib || anImage->isDylib() ) {
3249 if ( strcmp(orgPath, installPath) == 0 )
3250 return anImage;
3251 }
3252 }
3253 }
3254 }
3255
3256 //dyld::log("%s(%s) => NULL\n", __func__, path);
3257 return NULL;
3258 }
3259
3260
3261 // open or check existing
3262 static ImageLoader* loadPhase5(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3263 {
3264 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3265
3266 // check for specific dylib overrides
3267 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
3268 if ( strcmp(it->installName, path) == 0 ) {
3269 path = it->override;
3270 break;
3271 }
3272 }
3273
3274 if ( exceptions != NULL )
3275 return loadPhase5load(path, orgPath, context, cacheIndex, exceptions);
3276 else
3277 return loadPhase5check(path, orgPath, context);
3278 }
3279
3280 // try with and without image suffix
3281 static ImageLoader* loadPhase4(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3282 {
3283 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3284 ImageLoader* image = NULL;
3285 if ( gLinkContext.imageSuffix != NULL ) {
3286 char pathWithSuffix[strlen(path)+strlen( gLinkContext.imageSuffix)+2];
3287 ImageLoader::addSuffix(path, gLinkContext.imageSuffix, pathWithSuffix);
3288 image = loadPhase5(pathWithSuffix, orgPath, context, cacheIndex, exceptions);
3289 }
3290 if ( image == NULL )
3291 image = loadPhase5(path, orgPath, context, cacheIndex, exceptions);
3292 return image;
3293 }
3294
3295 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
3296 const char* const frameworkPaths[], const char* const libraryPaths[],
3297 unsigned& cacheIndex, std::vector<const char*>* exceptions); // forward reference
3298
3299
3300 // expand @ variables
3301 static ImageLoader* loadPhase3(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3302 {
3303 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3304 ImageLoader* image = NULL;
3305 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
3306 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3307 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
3308 if ( gLinkContext.processIsRestricted )
3309 throwf("unsafe use of @executable_path in %s with restricted binary", context.origin);
3310 #endif
3311 // handle @executable_path path prefix
3312 const char* executablePath = sExecPath;
3313 char newPath[strlen(executablePath) + strlen(path)];
3314 strcpy(newPath, executablePath);
3315 char* addPoint = strrchr(newPath,'/');
3316 if ( addPoint != NULL )
3317 strcpy(&addPoint[1], &path[17]);
3318 else
3319 strcpy(newPath, &path[17]);
3320 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3321 if ( image != NULL )
3322 return image;
3323
3324 // perhaps main executable path is a sym link, find realpath and retry
3325 char resolvedPath[PATH_MAX];
3326 if ( realpath(sExecPath, resolvedPath) != NULL ) {
3327 char newRealPath[strlen(resolvedPath) + strlen(path)];
3328 strcpy(newRealPath, resolvedPath);
3329 addPoint = strrchr(newRealPath,'/');
3330 if ( addPoint != NULL )
3331 strcpy(&addPoint[1], &path[17]);
3332 else
3333 strcpy(newRealPath, &path[17]);
3334 image = loadPhase4(newRealPath, orgPath, context, cacheIndex, exceptions);
3335 if ( image != NULL )
3336 return image;
3337 }
3338 }
3339 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
3340 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3341 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
3342 if ( gLinkContext.processIsRestricted && (strcmp(context.origin, sExecPath) == 0) )
3343 throwf("unsafe use of @loader_path in %s with restricted binary", context.origin);
3344 #endif
3345 // handle @loader_path path prefix
3346 char newPath[strlen(context.origin) + strlen(path)];
3347 strcpy(newPath, context.origin);
3348 char* addPoint = strrchr(newPath,'/');
3349 if ( addPoint != NULL )
3350 strcpy(&addPoint[1], &path[13]);
3351 else
3352 strcpy(newPath, &path[13]);
3353 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3354 if ( image != NULL )
3355 return image;
3356
3357 // perhaps loader path is a sym link, find realpath and retry
3358 char resolvedPath[PATH_MAX];
3359 if ( realpath(context.origin, resolvedPath) != NULL ) {
3360 char newRealPath[strlen(resolvedPath) + strlen(path)];
3361 strcpy(newRealPath, resolvedPath);
3362 addPoint = strrchr(newRealPath,'/');
3363 if ( addPoint != NULL )
3364 strcpy(&addPoint[1], &path[13]);
3365 else
3366 strcpy(newRealPath, &path[13]);
3367 image = loadPhase4(newRealPath, orgPath, context, cacheIndex, exceptions);
3368 if ( image != NULL )
3369 return image;
3370 }
3371 }
3372 else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
3373 const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
3374 // substitute @rpath with all -rpath paths up the load chain
3375 for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
3376 if (rp->paths != NULL ) {
3377 for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
3378 const char* anRPath = *it;
3379 char newPath[strlen(anRPath) + strlen(trailingPath)+2];
3380 strcpy(newPath, anRPath);
3381 if ( newPath[strlen(newPath)-1] != '/' )
3382 strcat(newPath, "/");
3383 strcat(newPath, trailingPath);
3384 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3385 if ( gLinkContext.verboseRPaths && (exceptions != NULL) ) {
3386 if ( image != NULL )
3387 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath, newPath);
3388 else
3389 dyld::log("RPATH failed to expanding %s to: %s\n", orgPath, newPath);
3390 }
3391 if ( image != NULL )
3392 return image;
3393 }
3394 }
3395 }
3396
3397 // substitute @rpath with LD_LIBRARY_PATH
3398 if ( sEnv.LD_LIBRARY_PATH != NULL ) {
3399 image = loadPhase2(trailingPath, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, cacheIndex, exceptions);
3400 if ( image != NULL )
3401 return image;
3402 }
3403
3404 // if this is the "open" pass, don't try to open @rpath/... as a relative path
3405 if ( (exceptions != NULL) && (trailingPath != path) )
3406 return NULL;
3407 }
3408 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3409 else if ( gLinkContext.processIsRestricted && (path[0] != '/' ) ) {
3410 throwf("unsafe use of relative rpath %s in %s with restricted binary", path, context.origin);
3411 }
3412 #endif
3413
3414 return loadPhase4(path, orgPath, context, cacheIndex, exceptions);
3415 }
3416
3417 static ImageLoader* loadPhase2cache(const char* path, const char *orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions) {
3418 ImageLoader* image = NULL;
3419 #if !TARGET_IPHONE_SIMULATOR
3420 if ( exceptions != NULL) {
3421 char resolvedPath[PATH_MAX];
3422 realpath(path, resolvedPath);
3423 int myerr = errno;
3424 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3425 if ( (myerr == ENOENT) || (myerr == 0) )
3426 {
3427 image = loadPhase4(resolvedPath, orgPath, context, cacheIndex, exceptions);
3428 }
3429 }
3430 #endif
3431 return image;
3432 }
3433
3434
3435 // try search paths
3436 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
3437 const char* const frameworkPaths[], const char* const libraryPaths[],
3438 unsigned& cacheIndex, std::vector<const char*>* exceptions)
3439 {
3440 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3441 ImageLoader* image = NULL;
3442 const char* frameworkPartialPath = getFrameworkPartialPath(path);
3443 if ( frameworkPaths != NULL ) {
3444 if ( frameworkPartialPath != NULL ) {
3445 const size_t frameworkPartialPathLen = strlen(frameworkPartialPath);
3446 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
3447 char npath[strlen(*fp)+frameworkPartialPathLen+8];
3448 strcpy(npath, *fp);
3449 strcat(npath, "/");
3450 strcat(npath, frameworkPartialPath);
3451 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
3452 image = loadPhase4(npath, orgPath, context, cacheIndex, exceptions);
3453 // Look in the cache if appropriate
3454 if ( image == NULL)
3455 image = loadPhase2cache(npath, orgPath, context, cacheIndex, exceptions);
3456 if ( image != NULL )
3457 return image;
3458 }
3459 }
3460 }
3461 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
3462 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
3463 if ( (libraryPaths != NULL) && ((frameworkPartialPath == NULL) || sFrameworksFoundAsDylibs) ) {
3464 const char* libraryLeafName = getLibraryLeafName(path);
3465 const size_t libraryLeafNameLen = strlen(libraryLeafName);
3466 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
3467 char libpath[strlen(*lp)+libraryLeafNameLen+8];
3468 strcpy(libpath, *lp);
3469 strcat(libpath, "/");
3470 strcat(libpath, libraryLeafName);
3471 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
3472 image = loadPhase4(libpath, orgPath, context, cacheIndex, exceptions);
3473 // Look in the cache if appropriate
3474 if ( image == NULL)
3475 image = loadPhase2cache(libpath, orgPath, context, cacheIndex, exceptions);
3476 if ( image != NULL )
3477 return image;
3478 }
3479 }
3480 return NULL;
3481 }
3482
3483 // try search overrides and fallbacks
3484 static ImageLoader* loadPhase1(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3485 {
3486 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3487 ImageLoader* image = NULL;
3488
3489 // handle LD_LIBRARY_PATH environment variables that force searching
3490 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
3491 image = loadPhase2(path, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, cacheIndex,exceptions);
3492 if ( image != NULL )
3493 return image;
3494 }
3495
3496 // handle DYLD_ environment variables that force searching
3497 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
3498 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, cacheIndex, exceptions);
3499 if ( image != NULL )
3500 return image;
3501 }
3502
3503 // try raw path
3504 image = loadPhase3(path, orgPath, context, cacheIndex, exceptions);
3505 if ( image != NULL )
3506 return image;
3507
3508 // try fallback paths during second time (will open file)
3509 const char* const* fallbackLibraryPaths = sEnv.DYLD_FALLBACK_LIBRARY_PATH;
3510 if ( (fallbackLibraryPaths != NULL) && !context.useFallbackPaths )
3511 fallbackLibraryPaths = NULL;
3512 if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (fallbackLibraryPaths != NULL)) ) {
3513 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, fallbackLibraryPaths, cacheIndex, exceptions);
3514 if ( image != NULL )
3515 return image;
3516 }
3517
3518 return NULL;
3519 }
3520
3521 // try root substitutions
3522 static ImageLoader* loadPhase0(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3523 {
3524 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3525
3526 #if SUPPORT_ROOT_PATH
3527 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
3528 if ( (gLinkContext.rootPaths != NULL) && (path[0] == '/') ) {
3529 for(const char* const* rootPath = gLinkContext.rootPaths ; *rootPath != NULL; ++rootPath) {
3530 char newPath[strlen(*rootPath) + strlen(path)+2];
3531 strcpy(newPath, *rootPath);
3532 strcat(newPath, path);
3533 ImageLoader* image = loadPhase1(newPath, orgPath, context, cacheIndex, exceptions);
3534 if ( image != NULL )
3535 return image;
3536 }
3537 }
3538 #endif
3539
3540 // try raw path
3541 return loadPhase1(path, orgPath, context, cacheIndex, exceptions);
3542 }
3543
3544 static bool cacheablePath(const char* path) {
3545 if (strncmp(path, "/usr/lib/", 9) == 0)
3546 return true;
3547 if (strncmp(path, "/System/Library/", 16) == 0)
3548 return true;
3549 return false;
3550 }
3551
3552 //
3553 // Given all the DYLD_ environment variables, the general case for loading libraries
3554 // is that any given path expands into a list of possible locations to load. We
3555 // also must take care to ensure two copies of the "same" library are never loaded.
3556 //
3557 // The algorithm used here is that there is a separate function for each "phase" of the
3558 // path expansion. Each phase function calls the next phase with each possible expansion
3559 // of that phase. The result is the last phase is called with all possible paths.
3560 //
3561 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
3562 // the path against all loaded images. The second time, the last phase calls open() on
3563 // the path. Either time, if an image is found, the phases all unwind without checking
3564 // for other paths.
3565 //
3566 ImageLoader* load(const char* path, const LoadContext& context, unsigned& cacheIndex)
3567 {
3568 CRSetCrashLogMessage2(path);
3569 const char* orgPath = path;
3570 cacheIndex = UINT32_MAX;
3571
3572 //dyld::log("%s(%s)\n", __func__ , path);
3573 char realPath[PATH_MAX];
3574 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
3575 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL) ) {
3576 if ( realpath(path, realPath) != NULL )
3577 path = realPath;
3578 }
3579
3580 // try all path permutations and check against existing loaded images
3581
3582 ImageLoader* image = loadPhase0(path, orgPath, context, cacheIndex, NULL);
3583 if ( image != NULL ) {
3584 CRSetCrashLogMessage2(NULL);
3585 return image;
3586 }
3587
3588 // try all path permutations and try open() until first success
3589 std::vector<const char*> exceptions;
3590 image = loadPhase0(path, orgPath, context, cacheIndex, &exceptions);
3591 #if !TARGET_IPHONE_SIMULATOR
3592 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
3593 if ( image == NULL)
3594 image = loadPhase2cache(path, orgPath, context, cacheIndex, &exceptions);
3595 #endif
3596 CRSetCrashLogMessage2(NULL);
3597 if ( image != NULL ) {
3598 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3599 for (std::vector<const char*>::iterator it = exceptions.begin(); it != exceptions.end(); ++it) {
3600 free((void*)(*it));
3601 }
3602 // if loaded image is not from cache, but original path is in cache
3603 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3604 if ( !gSharedCacheOverridden && !image->inSharedCache() && image->isDylib() && cacheablePath(path) && inSharedCache(path) ) {
3605 gSharedCacheOverridden = true;
3606 }
3607 return image;
3608 }
3609 else if ( exceptions.size() == 0 ) {
3610 if ( context.dontLoad ) {