]> git.saurik.com Git - apple/dyld.git/blob - src/dyld.cpp
2fd37875d220e6c093568bd52cf068d58e14c946
[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 ) {
3611 return NULL;
3612 }
3613 else
3614 throw "image not found";
3615 }
3616 else {
3617 const char* msgStart = "no suitable image found. Did find:";
3618 const char* delim = "\n\t";
3619 size_t allsizes = strlen(msgStart)+8;
3620 for (size_t i=0; i < exceptions.size(); ++i)
3621 allsizes += (strlen(exceptions[i]) + strlen(delim));
3622 char* fullMsg = new char[allsizes];
3623 strcpy(fullMsg, msgStart);
3624 for (size_t i=0; i < exceptions.size(); ++i) {
3625 strcat(fullMsg, delim);
3626 strcat(fullMsg, exceptions[i]);
3627 free((void*)exceptions[i]);
3628 }
3629 throw (const char*)fullMsg;
3630 }
3631 }
3632
3633
3634
3635
3636
3637 static void mapSharedCache()
3638 {
3639 dyld3::SharedCacheOptions opts;
3640 opts.cacheDirOverride = sSharedCacheOverrideDir;
3641 opts.forcePrivate = (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion);
3642 #if __x86_64__ && !TARGET_IPHONE_SIMULATOR
3643 opts.useHaswell = sHaswell;
3644 #else
3645 opts.useHaswell = false;
3646 #endif
3647 opts.verbose = gLinkContext.verboseMapping;
3648 loadDyldCache(opts, &sSharedCacheLoadInfo);
3649
3650 // update global state
3651 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
3652 dyld::gProcessInfo->processDetachedFromSharedRegion = opts.forcePrivate;
3653 dyld::gProcessInfo->sharedCacheSlide = sSharedCacheLoadInfo.slide;
3654 dyld::gProcessInfo->sharedCacheBaseAddress = (unsigned long)sSharedCacheLoadInfo.loadAddress;
3655 sSharedCacheLoadInfo.loadAddress->getUUID(dyld::gProcessInfo->sharedCacheUUID);
3656 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_SHARED_CACHE_A, (const uuid_t *)&dyld::gProcessInfo->sharedCacheUUID[0], {0,0}, {{ 0, 0 }}, (const mach_header *)sSharedCacheLoadInfo.loadAddress);
3657 }
3658
3659 //#if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
3660 // RAM disk booting does not have shared cache yet
3661 // Don't make lack of a shared cache fatal in that case
3662 // if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
3663 // if ( sSharedCacheLoadInfo.errorMessage != nullptr )
3664 // halt(sSharedCacheLoadInfo.errorMessage);
3665 // else
3666 // halt("error loading dyld shared cache");
3667 // }
3668 //#endif
3669 }
3670
3671
3672
3673 // create when NSLinkModule is called for a second time on a bundle
3674 ImageLoader* cloneImage(ImageLoader* image)
3675 {
3676 // open file (automagically closed when this function exits)
3677 FileOpener file(image->getPath());
3678
3679 struct stat stat_buf;
3680 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
3681 throw "stat error";
3682
3683 dyld::LoadContext context;
3684 context.useSearchPaths = false;
3685 context.useFallbackPaths = false;
3686 context.useLdLibraryPath = false;
3687 context.implicitRPath = false;
3688 context.matchByInstallName = false;
3689 context.dontLoad = false;
3690 context.mustBeBundle = true;
3691 context.mustBeDylib = false;
3692 context.canBePIE = false;
3693 context.origin = NULL;
3694 context.rpath = NULL;
3695 return loadPhase6(file.getFileDescriptor(), stat_buf, image->getPath(), context);
3696 }
3697
3698
3699 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
3700 {
3701 // if fat wrapper, find usable sub-file
3702 const fat_header* memStartAsFat = (fat_header*)mem;
3703 uint64_t fileOffset = 0;
3704 uint64_t fileLength = len;
3705 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3706 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
3707 mem = &mem[fileOffset];
3708 len = fileLength;
3709 }
3710 else {
3711 throw "no matching architecture in universal wrapper";
3712 }
3713 }
3714
3715 // try each loader
3716 if ( isCompatibleMachO(mem, moduleName) ) {
3717 ImageLoader* image = ImageLoaderMachO::instantiateFromMemory(moduleName, (macho_header*)mem, len, gLinkContext);
3718 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3719 if ( ! image->isBundle() )
3720 addImage(image);
3721 return image;
3722 }
3723
3724 // try other file formats here...
3725
3726 // throw error about what was found
3727 switch (*(uint32_t*)mem) {
3728 case MH_MAGIC:
3729 case MH_CIGAM:
3730 case MH_MAGIC_64:
3731 case MH_CIGAM_64:
3732 throw "mach-o, but wrong architecture";
3733 default:
3734 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3735 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
3736 }
3737 }
3738
3739
3740 void registerAddCallback(ImageCallback func)
3741 {
3742 // now add to list to get notified when any more images are added
3743 sAddImageCallbacks.push_back(func);
3744
3745 // call callback with all existing images
3746 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3747 ImageLoader* image = *it;
3748 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated )
3749 (*func)(image->machHeader(), image->getSlide());
3750 }
3751 #if SUPPORT_ACCELERATE_TABLES
3752 if ( sAllCacheImagesProxy != NULL ) {
3753 dyld_image_info infos[allImagesCount()+1];
3754 unsigned cacheCount = sAllCacheImagesProxy->appendImagesToNotify(dyld_image_state_bound, true, infos);
3755 for (unsigned i=0; i < cacheCount; ++i) {
3756 (*func)(infos[i].imageLoadAddress, sSharedCacheLoadInfo.slide);
3757 }
3758 }
3759 #endif
3760 }
3761
3762 void registerRemoveCallback(ImageCallback func)
3763 {
3764 // <rdar://problem/15025198> ignore calls to register a notification during a notification
3765 if ( sRemoveImageCallbacksInUse )
3766 return;
3767 sRemoveImageCallbacks.push_back(func);
3768 }
3769
3770 void clearErrorMessage()
3771 {
3772 error_string[0] = '\0';
3773 }
3774
3775 void setErrorMessage(const char* message)
3776 {
3777 // save off error message in global buffer for CrashReporter to find
3778 strlcpy(error_string, message, sizeof(error_string));
3779 }
3780
3781 const char* getErrorMessage()
3782 {
3783 return error_string;
3784 }
3785
3786 void halt(const char* message)
3787 {
3788 dyld::log("dyld: %s\n", message);
3789 setErrorMessage(message);
3790 dyld::gProcessInfo->errorMessage = error_string;
3791 if ( !gLinkContext.startedInitializingMainExecutable )
3792 dyld::gProcessInfo->terminationFlags = 1;
3793 else
3794 dyld::gProcessInfo->terminationFlags = 0;
3795
3796 char payloadBuffer[EXIT_REASON_PAYLOAD_MAX_LEN];
3797 dyld_abort_payload* payload = (dyld_abort_payload*)payloadBuffer;
3798 payload->version = 1;
3799 payload->flags = gLinkContext.startedInitializingMainExecutable ? 0 : 1;
3800 payload->targetDylibPathOffset = 0;
3801 payload->clientPathOffset = 0;
3802 payload->symbolOffset = 0;
3803 int payloadSize = sizeof(dyld_abort_payload);
3804
3805 if ( dyld::gProcessInfo->errorTargetDylibPath != NULL ) {
3806 payload->targetDylibPathOffset = payloadSize;
3807 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorTargetDylibPath, sizeof(payloadBuffer)-payloadSize) + 1;
3808 }
3809 if ( dyld::gProcessInfo->errorClientOfDylibPath != NULL ) {
3810 payload->clientPathOffset = payloadSize;
3811 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorClientOfDylibPath, sizeof(payloadBuffer)-payloadSize) + 1;
3812 }
3813 if ( dyld::gProcessInfo->errorSymbol != NULL ) {
3814 payload->symbolOffset = payloadSize;
3815 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorSymbol, sizeof(payloadBuffer)-payloadSize) + 1;
3816 }
3817 char truncMessage[EXIT_REASON_USER_DESC_MAX_LEN];
3818 strlcpy(truncMessage, message, EXIT_REASON_USER_DESC_MAX_LEN);
3819 abort_with_payload(OS_REASON_DYLD, dyld::gProcessInfo->errorKind ? dyld::gProcessInfo->errorKind : DYLD_EXIT_REASON_OTHER, payloadBuffer, payloadSize, truncMessage, 0);
3820 }
3821
3822 static void setErrorStrings(unsigned errorCode, const char* errorClientOfDylibPath,
3823 const char* errorTargetDylibPath, const char* errorSymbol)
3824 {
3825 dyld::gProcessInfo->errorKind = errorCode;
3826 dyld::gProcessInfo->errorClientOfDylibPath = errorClientOfDylibPath;
3827 dyld::gProcessInfo->errorTargetDylibPath = errorTargetDylibPath;
3828 dyld::gProcessInfo->errorSymbol = errorSymbol;
3829 }
3830
3831
3832 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
3833 {
3834 uintptr_t result = 0;
3835 // acquire read-lock on dyld's data structures
3836 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
3837 if ( gLibSystemHelpers != NULL )
3838 (*gLibSystemHelpers->lockForReading)();
3839 #endif
3840 // lookup and bind lazy pointer and get target address
3841 try {
3842 ImageLoader* target;
3843 #if __i386__
3844 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
3845 if ( mh == NULL )
3846 target = dyld::findImageContainingAddress(lazyPointer);
3847 else
3848 target = dyld::findImageByMachHeader(mh);
3849 #else
3850 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
3851 target = dyld::findImageByMachHeader(mh);
3852 #endif
3853 if ( target == NULL )
3854 throwf("image not found for lazy pointer at %p", lazyPointer);
3855 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
3856 }
3857 catch (const char* message) {
3858 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3859 halt(message);
3860 }
3861 // release read-lock on dyld's data structures
3862 #if 0
3863 if ( gLibSystemHelpers != NULL )
3864 (*gLibSystemHelpers->unlockForReading)();
3865 #endif
3866 // return target address to glue which jumps to it with real parameters restored
3867 return result;
3868 }
3869
3870
3871 uintptr_t fastBindLazySymbol(ImageLoader** imageLoaderCache, uintptr_t lazyBindingInfoOffset)
3872 {
3873 uintptr_t result = 0;
3874 // get image
3875 if ( *imageLoaderCache == NULL ) {
3876 // save in cache
3877 *imageLoaderCache = dyld::findMappedRange((uintptr_t)imageLoaderCache);
3878 if ( *imageLoaderCache == NULL ) {
3879 #if SUPPORT_ACCELERATE_TABLES
3880 if ( sAllCacheImagesProxy != NULL ) {
3881 const mach_header* mh;
3882 const char* path;
3883 unsigned index;
3884 if ( sAllCacheImagesProxy->addressInCache(imageLoaderCache, &mh, &path, &index) ) {
3885 result = sAllCacheImagesProxy->bindLazy(lazyBindingInfoOffset, gLinkContext, mh, index);
3886 if ( result == 0 ) {
3887 halt("dyld: lazy symbol binding failed for image in dyld shared\n");
3888 }
3889 return result;
3890 }
3891 }
3892 #endif
3893 const char* message = "fast lazy binding from unknown image";
3894 dyld::log("dyld: %s\n", message);
3895 halt(message);
3896 }
3897 }
3898
3899 // bind lazy pointer and return it
3900 try {
3901 result = (*imageLoaderCache)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset, gLinkContext,
3902 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->acquireGlobalDyldLock : NULL,
3903 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->releaseGlobalDyldLock : NULL);
3904 }
3905 catch (const char* message) {
3906 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
3907 halt(message);
3908 }
3909
3910 // return target address to glue which jumps to it with real parameters restored
3911 return result;
3912 }
3913
3914
3915
3916 void registerUndefinedHandler(UndefinedHandler handler)
3917 {
3918 sUndefinedHandler = handler;
3919 }
3920
3921 static void undefinedHandler(const char* symboName)
3922 {
3923 if ( sUndefinedHandler != NULL ) {
3924 (*sUndefinedHandler)(symboName);
3925 }
3926 }
3927
3928 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image)
3929 {
3930 // search all images in order
3931 const ImageLoader* firstWeakImage = NULL;
3932 const ImageLoader::Symbol* firstWeakSym = NULL;
3933 const size_t imageCount = sAllImages.size();
3934 for(size_t i=0; i < imageCount; ++i) {
3935 ImageLoader* anImage = sAllImages[i];
3936 // the use of inserted libraries alters search order
3937 // so that inserted libraries are found before the main executable
3938 if ( sInsertedDylibCount > 0 ) {
3939 if ( i < sInsertedDylibCount )
3940 anImage = sAllImages[i+1];
3941 else if ( i == sInsertedDylibCount )
3942 anImage = sAllImages[0];
3943 }
3944 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
3945 *sym = anImage->findExportedSymbol(name, false, image);
3946 if ( *sym != NULL ) {
3947 // if weak definition found, record first one found
3948 if ( ((*image)->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
3949 if ( firstWeakImage == NULL ) {
3950 firstWeakImage = *image;
3951 firstWeakSym = *sym;
3952 }
3953 }
3954 else {
3955 // found non-weak, so immediately return with it
3956 return true;
3957 }
3958 }
3959 }
3960 }
3961 if ( firstWeakSym != NULL ) {
3962 // found a weak definition, but no non-weak, so return first weak found
3963 *sym = firstWeakSym;
3964 *image = firstWeakImage;
3965 return true;
3966 }
3967 #if SUPPORT_ACCELERATE_TABLES
3968 if ( sAllCacheImagesProxy != NULL ) {
3969 if ( sAllCacheImagesProxy->flatFindSymbol(name, onlyInCoalesced, sym, image) )
3970 return true;
3971 }
3972 #endif
3973
3974 return false;
3975 }
3976
3977 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3978 {
3979 return findExportedSymbol(name, false, sym, image);
3980 }
3981
3982 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
3983 {
3984 return findExportedSymbol(name, true, sym, image);
3985 }
3986
3987
3988 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
3989 {
3990 // search all images in order
3991 const size_t imageCount = sAllImages.size();
3992 for(size_t i=0; i < imageCount; ++i){
3993 ImageLoader* anImage = sAllImages[i];
3994 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
3995 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
3996 *sym = anImage->findExportedSymbol(name, false, image);
3997 if ( *sym != NULL ) {
3998 return true;
3999 }
4000 }
4001 }
4002 return false;
4003 }
4004
4005
4006 unsigned int getCoalescedImages(ImageLoader* images[], unsigned imageIndex[])
4007 {
4008 unsigned int count = 0;
4009 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4010 ImageLoader* image = *it;
4011 if ( image->participatesInCoalescing() ) {
4012 images[count] = *it;
4013 imageIndex[count] = 0;
4014 ++count;
4015 }
4016 }
4017 #if SUPPORT_ACCELERATE_TABLES
4018 if ( sAllCacheImagesProxy != NULL ) {
4019 sAllCacheImagesProxy->appendImagesNeedingCoalescing(images, imageIndex, count);
4020 }
4021 #endif
4022 return count;
4023 }
4024
4025
4026 static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
4027 {
4028 ImageLoader::MappedRegion* end = regions;
4029 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4030 (*it)->getMappedRegions(end);
4031 }
4032 return end;
4033 }
4034
4035 void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
4036 {
4037 // mark the image that the handler is in as never-unload because dyld has a reference into it
4038 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
4039 if ( handlerImage != NULL )
4040 handlerImage->setNeverUnload();
4041
4042 // add to list of handlers
4043 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
4044 if ( handlers != NULL ) {
4045 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
4046 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
4047 if ( state == dyld_image_state_mapped )
4048 handlers->insert(handlers->begin(), handler);
4049 else
4050 handlers->push_back(handler);
4051
4052 // call callback with all existing images
4053 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4054 ImageLoader* image = *it;
4055 dyld_image_info info;
4056 info.imageLoadAddress = image->machHeader();
4057 info.imageFilePath = image->getRealPath();
4058 info.imageFileModDate = image->lastModified();
4059 // should only call handler if state == image->state
4060 if ( image->getState() == state )
4061 (*handler)(state, 1, &info);
4062 // ignore returned string, too late to do anything
4063 }
4064 }
4065 }
4066
4067 void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
4068 {
4069 // mark the image that the handler is in as never-unload because dyld has a reference into it
4070 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
4071 if ( handlerImage != NULL )
4072 handlerImage->setNeverUnload();
4073
4074 // add to list of handlers
4075 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
4076 if ( handlers != NULL ) {
4077 // insert at front, so that gdb handler is always last
4078 handlers->insert(handlers->begin(), handler);
4079
4080 // call callback with all existing images
4081 try {
4082 notifyBatchPartial(state, true, handler, false, false);
4083 }
4084 catch (const char* msg) {
4085 // ignore request to abort during registration
4086 }
4087 }
4088 }
4089
4090
4091 void registerObjCNotifiers(_dyld_objc_notify_mapped mapped, _dyld_objc_notify_init init, _dyld_objc_notify_unmapped unmapped)
4092 {
4093 // record functions to call
4094 sNotifyObjCMapped = mapped;
4095 sNotifyObjCInit = init;
4096 sNotifyObjCUnmapped = unmapped;
4097
4098 // call 'mapped' function with all images mapped so far
4099 try {
4100 notifyBatchPartial(dyld_image_state_bound, true, NULL, false, true);
4101 }
4102 catch (const char* msg) {
4103 // ignore request to abort during registration
4104 }
4105
4106 // <rdar://problem/32209809> call 'init' function on all images already init'ed (below libSystem)
4107 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4108 ImageLoader* image = *it;
4109 if ( (image->getState() == dyld_image_state_initialized) && image->notifyObjC() ) {
4110 (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
4111 }
4112 }
4113 }
4114
4115 bool sharedCacheUUID(uuid_t uuid)
4116 {
4117 if ( sSharedCacheLoadInfo.loadAddress == nullptr )
4118 return false;
4119
4120 sSharedCacheLoadInfo.loadAddress->getUUID(uuid);
4121 return true;
4122 }
4123
4124 #if SUPPORT_ACCELERATE_TABLES
4125
4126 bool dlopenFromCache(const char* path, int mode, void** handle)
4127 {
4128 if ( sAllCacheImagesProxy == NULL )
4129 return false;
4130 char fallbackPath[PATH_MAX];
4131 bool result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, path, mode, handle);
4132 if ( !result && (strchr(path, '/') == NULL) ) {
4133 // POSIX says you can call dlopen() with a leaf name (e.g. dlopen("libz.dylb"))
4134 strcpy(fallbackPath, "/usr/lib/");
4135 strlcat(fallbackPath, path, PATH_MAX);
4136 result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, fallbackPath, mode, handle);
4137 if ( !result )
4138 path = fallbackPath;
4139 }
4140 if ( !result ) {
4141 // leaf name could be a symlink
4142 char resolvedPath[PATH_MAX];
4143 realpath(path, resolvedPath);
4144 int realpathErrno = errno;
4145 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
4146 if ( (realpathErrno == ENOENT) || (realpathErrno == 0) ) {
4147 result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, resolvedPath, mode, handle);
4148 }
4149 }
4150
4151 return result;
4152 }
4153
4154 bool makeCacheHandle(ImageLoader* image, unsigned cacheIndex, int mode, void** result)
4155 {
4156 if ( sAllCacheImagesProxy == NULL )
4157 return false;
4158 return sAllCacheImagesProxy->makeCacheHandle(gLinkContext, cacheIndex, mode, result);
4159 }
4160
4161 bool isCacheHandle(void* handle)
4162 {
4163 if ( sAllCacheImagesProxy == NULL )
4164 return false;
4165 return sAllCacheImagesProxy->isCacheHandle(handle, NULL, NULL);
4166 }
4167
4168 bool isPathInCache(const char* path)
4169 {
4170 if ( sAllCacheImagesProxy == NULL )
4171 return false;
4172 unsigned index;
4173 return sAllCacheImagesProxy->hasDylib(path, &index);
4174 }
4175
4176 const char* getPathFromIndex(unsigned cacheIndex)
4177 {
4178 if ( sAllCacheImagesProxy == NULL )
4179 return NULL;
4180 return sAllCacheImagesProxy->getIndexedPath(cacheIndex);
4181 }
4182
4183 void* dlsymFromCache(void* handle, const char* symName, unsigned index)
4184 {
4185 if ( sAllCacheImagesProxy == NULL )
4186 return NULL;
4187 return sAllCacheImagesProxy->dlsymFromCache(gLinkContext, handle, symName, index);
4188 }
4189
4190 bool addressInCache(const void* address, const mach_header** mh, const char** path, unsigned* index)
4191 {
4192 if ( sAllCacheImagesProxy == NULL )
4193 return false;
4194 unsigned ignore;
4195 return sAllCacheImagesProxy->addressInCache(address, mh, path, index ? index : &ignore);
4196 }
4197
4198 bool findUnwindSections(const void* addr, dyld_unwind_sections* info)
4199 {
4200 if ( sAllCacheImagesProxy == NULL )
4201 return false;
4202 return sAllCacheImagesProxy->findUnwindSections(addr, info);
4203 }
4204
4205 bool dladdrFromCache(const void* address, Dl_info* info)
4206 {
4207 if ( sAllCacheImagesProxy == NULL )
4208 return false;
4209 return sAllCacheImagesProxy->dladdrFromCache(address, info);
4210 }
4211 #endif
4212
4213 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const ImageLoader::RPathChain* rpaths, unsigned& cacheIndex)
4214 {
4215 dyld::LoadContext context;
4216 context.useSearchPaths = search;
4217 context.useFallbackPaths = search;
4218 context.useLdLibraryPath = false;
4219 context.implicitRPath = false;
4220 context.matchByInstallName = false;
4221 context.dontLoad = false;
4222 context.mustBeBundle = false;
4223 context.mustBeDylib = true;
4224 context.canBePIE = false;
4225 context.origin = origin;
4226 context.rpath = rpaths;
4227 return load(libraryName, context, cacheIndex);
4228 }
4229
4230 static const char* basename(const char* path)
4231 {
4232 const char* last = path;
4233 for (const char* s = path; *s != '\0'; s++) {
4234 if (*s == '/')
4235 last = s+1;
4236 }
4237 return last;
4238 }
4239
4240 static void setContext(const macho_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
4241 {
4242 gLinkContext.loadLibrary = &libraryLocator;
4243 gLinkContext.terminationRecorder = &terminationRecorder;
4244 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
4245 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
4246 gLinkContext.getCoalescedImages = &getCoalescedImages;
4247 gLinkContext.undefinedHandler = &undefinedHandler;
4248 gLinkContext.getAllMappedRegions = &getMappedRegions;
4249 gLinkContext.bindingHandler = NULL;
4250 gLinkContext.notifySingle = &notifySingle;
4251 gLinkContext.notifyBatch = &notifyBatch;
4252 gLinkContext.removeImage = &removeImage;
4253 gLinkContext.registerDOFs = &registerDOFs;
4254 gLinkContext.clearAllDepths = &clearAllDepths;
4255 gLinkContext.printAllDepths = &printAllDepths;
4256 gLinkContext.imageCount = &imageCount;
4257 gLinkContext.setNewProgramVars = &setNewProgramVars;
4258 gLinkContext.inSharedCache = &inSharedCache;
4259 gLinkContext.setErrorStrings = &setErrorStrings;
4260 #if SUPPORT_OLD_CRT_INITIALIZATION
4261 gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
4262 #endif
4263 gLinkContext.findImageContainingAddress = &findImageContainingAddress;
4264 gLinkContext.addDynamicReference = &addDynamicReference;
4265 #if SUPPORT_ACCELERATE_TABLES
4266 gLinkContext.notifySingleFromCache = &notifySingleFromCache;
4267 gLinkContext.getPreInitNotifyHandler= &getPreInitNotifyHandler;
4268 gLinkContext.getBoundBatchHandler = &getBoundBatchHandler;
4269 #endif
4270 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
4271 gLinkContext.argc = argc;
4272 gLinkContext.argv = argv;
4273 gLinkContext.envp = envp;
4274 gLinkContext.apple = apple;
4275 gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
4276 gLinkContext.programVars.mh = mainExecutableMH;
4277 gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
4278 gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
4279 gLinkContext.programVars.environPtr = &gLinkContext.envp;
4280 gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
4281 gLinkContext.mainExecutable = NULL;
4282 gLinkContext.imageSuffix = NULL;
4283 gLinkContext.dynamicInterposeArray = NULL;
4284 gLinkContext.dynamicInterposeCount = 0;
4285 gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
4286 #if TARGET_IPHONE_SIMULATOR
4287 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
4288 #else
4289 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
4290 #endif
4291 }
4292
4293
4294
4295 //
4296 // Look for a special segment in the mach header.
4297 // Its presences means that the binary wants to have DYLD ignore
4298 // DYLD_ environment variables.
4299 //
4300 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4301 static bool hasRestrictedSegment(const macho_header* mh)
4302 {
4303 const uint32_t cmd_count = mh->ncmds;
4304 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4305 const struct load_command* cmd = cmds;
4306 for (uint32_t i = 0; i < cmd_count; ++i) {
4307 switch (cmd->cmd) {
4308 case LC_SEGMENT_COMMAND:
4309 {
4310 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4311
4312 //dyld::log("seg name: %s\n", seg->segname);
4313 if (strcmp(seg->segname, "__RESTRICT") == 0) {
4314 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
4315 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
4316 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
4317 if (strcmp(sect->sectname, "__restrict") == 0)
4318 return true;
4319 }
4320 }
4321 }
4322 break;
4323 }
4324 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4325 }
4326
4327 return false;
4328 }
4329 #endif
4330
4331 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_IPHONE_SIMULATOR
4332 static bool isFairPlayEncrypted(const macho_header* mh)
4333 {
4334 const uint32_t cmd_count = mh->ncmds;
4335 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4336 const struct load_command* cmd = cmds;
4337 for (uint32_t i = 0; i < cmd_count; ++i) {
4338 if ( cmd->cmd == LC_ENCRYPT_COMMAND ) {
4339 const encryption_info_command* enc = (encryption_info_command*)cmd;
4340 return (enc->cryptid != 0);
4341 }
4342 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4343 }
4344
4345 return false;
4346 }
4347 #endif
4348
4349 #if SUPPORT_VERSIONED_PATHS
4350
4351 static bool readFirstPage(const char* dylibPath, uint8_t firstPage[4096])
4352 {
4353 firstPage[0] = 0;
4354 // open file (automagically closed when this function exits)
4355 FileOpener file(dylibPath);
4356
4357 if ( file.getFileDescriptor() == -1 )
4358 return false;
4359
4360 if ( pread(file.getFileDescriptor(), firstPage, 4096, 0) != 4096 )
4361 return false;
4362
4363 // if fat wrapper, find usable sub-file
4364 const fat_header* fileStartAsFat = (fat_header*)firstPage;
4365 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4366 uint64_t fileOffset;
4367 uint64_t fileLength;
4368 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
4369 if ( pread(file.getFileDescriptor(), firstPage, 4096, fileOffset) != 4096 )
4370 return false;
4371 }
4372 else {
4373 return false;
4374 }
4375 }
4376
4377 return true;
4378 }
4379
4380 //
4381 // Peeks at a dylib file and returns its current_version and install_name.
4382 // Returns false on error.
4383 //
4384 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
4385 {
4386 uint8_t firstPage[4096];
4387 const macho_header* mh = (macho_header*)firstPage;
4388 if ( !readFirstPage(dylibPath, firstPage) ) {
4389 // If file cannot be read, check to see if path is in shared cache
4390 const macho_header* mhInCache;
4391 const char* pathInCache;
4392 long slideInCache;
4393 if ( !findInSharedCacheImage(dylibPath, true, NULL, &mhInCache, &pathInCache, &slideInCache) )
4394 return false;
4395 mh = mhInCache;
4396 }
4397
4398 // check mach-o header
4399 if ( mh->magic != sMainExecutableMachHeader->magic )
4400 return false;
4401 if ( mh->cputype != sMainExecutableMachHeader->cputype )
4402 return false;
4403
4404 // scan load commands for LC_ID_DYLIB
4405 const uint32_t cmd_count = mh->ncmds;
4406 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4407 const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
4408 const struct load_command* cmd = cmds;
4409 for (uint32_t i = 0; i < cmd_count; ++i) {
4410 switch (cmd->cmd) {
4411 case LC_ID_DYLIB:
4412 {
4413 const struct dylib_command* id = (struct dylib_command*)cmd;
4414 *version = id->dylib.current_version;
4415 if ( installName != NULL )
4416 strlcpy(installName, (char *)id + id->dylib.name.offset, PATH_MAX);
4417 return true;
4418 }
4419 break;
4420 }
4421 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4422 if ( cmd > cmdsReadEnd )
4423 return false;
4424 }
4425
4426 return false;
4427 }
4428 #endif // SUPPORT_VERSIONED_PATHS
4429
4430
4431 #if 0
4432 static void printAllImages()
4433 {
4434 dyld::log("printAllImages()\n");
4435 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4436 ImageLoader* image = *it;
4437 dyld_image_states imageState = image->getState();
4438 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4439 imageState, image->dlopenCount(), image->neverUnload(), image->isMarkedInUse(), image->getShortName());
4440 }
4441 }
4442 #endif
4443
4444 void link(ImageLoader* image, bool forceLazysBound, bool neverUnload, const ImageLoader::RPathChain& loaderRPaths, unsigned cacheIndex)
4445 {
4446 // add to list of known images. This did not happen at creation time for bundles
4447 if ( image->isBundle() && !image->isLinked() )
4448 addImage(image);
4449
4450 // we detect root images as those not linked in yet
4451 if ( !image->isLinked() )
4452 addRootImage(image);
4453
4454 // process images
4455 try {
4456 const char* path = image->getPath();
4457 #if SUPPORT_ACCELERATE_TABLES
4458 if ( image == sAllCacheImagesProxy )
4459 path = sAllCacheImagesProxy->getIndexedPath(cacheIndex);
4460 #endif
4461 image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths, path);
4462 }
4463 catch (const char* msg) {
4464 garbageCollectImages();
4465 throw;
4466 }
4467 }
4468
4469
4470 void runInitializers(ImageLoader* image)
4471 {
4472 // do bottom up initialization
4473 ImageLoader::InitializerTimingList initializerTimes[allImagesCount()];
4474 initializerTimes[0].count = 0;
4475 image->runInitializers(gLinkContext, initializerTimes[0]);
4476 }
4477
4478 // This function is called at the end of dlclose() when the reference count goes to zero.
4479 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4480 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4481 // something else. We use a standard mark and sweep garbage collection.
4482 //
4483 // The tricky part is that when a dylib is unloaded it may have a termination function that
4484 // can run and itself call dlclose() on yet another dylib. The problem is that this
4485 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4486 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4487 // when the current pass is done.
4488 //
4489 // Also note that this is done within the dyld global lock, so it is always single threaded.
4490 //
4491 void garbageCollectImages()
4492 {
4493 static bool sDoingGC = false;
4494 static bool sRedo = false;
4495
4496 if ( sDoingGC ) {
4497 // GC is currently being run, just set a flag to have it run again.
4498 sRedo = true;
4499 return;
4500 }
4501
4502 sDoingGC = true;
4503 do {
4504 sRedo = false;
4505
4506 // mark phase: mark all images not-in-use
4507 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4508 ImageLoader* image = *it;
4509 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4510 image->markNotUsed();
4511 }
4512
4513 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4514 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4515 ImageLoader* image = *it;
4516 if ( (image->dlopenCount() != 0) || image->neverUnload() || (image == sMainExecutable) ) {
4517 OSSpinLockLock(&sDynamicReferencesLock);
4518 image->markedUsedRecursive(sDynamicReferences);
4519 OSSpinLockUnlock(&sDynamicReferencesLock);
4520 }
4521 }
4522
4523 // collect phase: build array of images not marked in-use
4524 ImageLoader* deadImages[sAllImages.size()];
4525 unsigned deadCount = 0;
4526 int maxRangeCount = 0;
4527 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4528 ImageLoader* image = *it;
4529 if ( ! image->isMarkedInUse() ) {
4530 deadImages[deadCount++] = image;
4531 if (gLogAPIs) dyld::log("dlclose(), found unused image %p %s\n", image, image->getShortName());
4532 maxRangeCount += image->segmentCount();
4533 }
4534 }
4535
4536 // collect phase: run termination routines for images not marked in-use
4537 __cxa_range_t ranges[maxRangeCount];
4538 int rangeCount = 0;
4539 for (unsigned i=0; i < deadCount; ++i) {
4540 ImageLoader* image = deadImages[i];
4541 for (unsigned int j=0; j < image->segmentCount(); ++j) {
4542 if ( !image->segExecutable(j) )
4543 continue;
4544 if ( rangeCount < maxRangeCount ) {
4545 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
4546 ranges[rangeCount].length = image->segSize(j);
4547 ++rangeCount;
4548 }
4549 }
4550 try {
4551 runImageStaticTerminators(image);
4552 }
4553 catch (const char* msg) {
4554 dyld::warn("problem running terminators for image: %s\n", msg);
4555 }
4556 }
4557
4558 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4559 if ( (rangeCount > 0) && (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 13) )
4560 (*gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
4561
4562 // collect phase: delete all images which are not marked in-use
4563 bool mightBeMore;
4564 do {
4565 mightBeMore = false;
4566 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4567 ImageLoader* image = *it;
4568 if ( ! image->isMarkedInUse() ) {
4569 try {
4570 if (gLogAPIs) dyld::log("dlclose(), deleting %p %s\n", image, image->getShortName());
4571 removeImage(image);
4572 ImageLoader::deleteImage(image);
4573 mightBeMore = true;
4574 break; // interator in invalidated by this removal
4575 }
4576 catch (const char* msg) {
4577 dyld::warn("problem deleting image: %s\n", msg);
4578 }
4579 }
4580 }
4581 } while ( mightBeMore );
4582 } while (sRedo);
4583 sDoingGC = false;
4584
4585 //printAllImages();
4586
4587 }
4588
4589
4590 static void preflight_finally(ImageLoader* image)
4591 {
4592 if ( image->isBundle() ) {
4593 removeImageFromAllImages(image->machHeader());
4594 ImageLoader::deleteImage(image);
4595 }
4596 sBundleBeingLoaded = NULL;
4597 dyld::garbageCollectImages();
4598 }
4599
4600
4601 void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths, unsigned cacheIndex)
4602 {
4603 try {
4604 if ( image->isBundle() )
4605 sBundleBeingLoaded = image; // hack
4606 const char* path = image->getPath();
4607 #if SUPPORT_ACCELERATE_TABLES
4608 if ( image == sAllCacheImagesProxy )
4609 path = sAllCacheImagesProxy->getIndexedPath(cacheIndex);
4610 #endif
4611 image->link(gLinkContext, false, true, false, loaderRPaths, path);
4612 }
4613 catch (const char* msg) {
4614 preflight_finally(image);
4615 throw;
4616 }
4617 preflight_finally(image);
4618 }
4619
4620 static void loadInsertedDylib(const char* path)
4621 {
4622 ImageLoader* image = NULL;
4623 unsigned cacheIndex;
4624 try {
4625 LoadContext context;
4626 context.useSearchPaths = false;
4627 context.useFallbackPaths = false;
4628 context.useLdLibraryPath = false;
4629 context.implicitRPath = false;
4630 context.matchByInstallName = false;
4631 context.dontLoad = false;
4632 context.mustBeBundle = false;
4633 context.mustBeDylib = true;
4634 context.canBePIE = false;
4635 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
4636 context.rpath = NULL;
4637 image = load(path, context, cacheIndex);
4638 }
4639 catch (const char* msg) {
4640 #if TARGET_IPHONE_SIMULATOR
4641 dyld::log("dyld: warning: could not load inserted library '%s' because %s\n", path, msg);
4642 #else
4643 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4644 if ( gLinkContext.processUsingLibraryValidation )
4645 dyld::log("dyld: warning: could not load inserted library '%s' into library validated process because %s\n", path, msg);
4646 else
4647 #endif
4648 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path, msg));
4649 #endif
4650 }
4651 catch (...) {
4652 halt(dyld::mkstringf("could not load inserted library '%s'\n", path));
4653 }
4654 }
4655
4656
4657 //
4658 // Sets:
4659 // sEnvMode
4660 // gLinkContext.requireCodeSignature
4661 // gLinkContext.processIsRestricted // Mac OS X only
4662 // gLinkContext.processUsingLibraryValidation // Mac OS X only
4663 //
4664 static void configureProcessRestrictions(const macho_header* mainExecutableMH)
4665 {
4666 #if TARGET_IPHONE_SIMULATOR
4667 sEnvMode = envAll;
4668 gLinkContext.requireCodeSignature = true;
4669 #elif __IPHONE_OS_VERSION_MIN_REQUIRED
4670 sEnvMode = envNone;
4671 gLinkContext.requireCodeSignature = true;
4672 uint32_t flags;
4673 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
4674 if ( flags & CS_ENFORCEMENT ) {
4675 if ( flags & CS_GET_TASK_ALLOW ) {
4676 // Xcode built app for Debug allowed to use DYLD_* variables
4677 sEnvMode = envAll;
4678 }
4679 else {
4680 // Development kernel can use DYLD_PRINT_* variables on any FairPlay encrypted app
4681 uint32_t secureValue = 0;
4682 size_t secureValueSize = sizeof(secureValue);
4683 if ( (sysctlbyname("kern.secure_kernel", &secureValue, &secureValueSize, NULL, 0) == 0) && (secureValue == 0) && isFairPlayEncrypted(mainExecutableMH) ) {
4684 sEnvMode = envPrintOnly;
4685 }
4686 }
4687 }
4688 else {
4689 // Development kernel can run unsigned code
4690 sEnvMode = envAll;
4691 gLinkContext.requireCodeSignature = false;
4692 }
4693 }
4694 if ( issetugid() ) {
4695 sEnvMode = envNone;
4696 }
4697 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
4698 sEnvMode = envAll;
4699 gLinkContext.requireCodeSignature = false;
4700 gLinkContext.processIsRestricted = false;
4701 gLinkContext.processUsingLibraryValidation = false;
4702 // any processes with setuid or setgid bit set or with __RESTRICT segment is restricted
4703 if ( issetugid() || hasRestrictedSegment(mainExecutableMH) ) {
4704 gLinkContext.processIsRestricted = true;
4705 }
4706 bool usingSIP = (csr_check(CSR_ALLOW_TASK_FOR_PID) != 0);
4707 uint32_t flags;
4708 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
4709 // On OS X CS_RESTRICT means the program was signed with entitlements
4710 if ( ((flags & CS_RESTRICT) == CS_RESTRICT) && usingSIP ) {
4711 gLinkContext.processIsRestricted = true;
4712 }
4713 // Library Validation loosens searching but requires everything to be code signed
4714 if ( flags & CS_REQUIRE_LV ) {
4715 gLinkContext.processIsRestricted = false;
4716 //gLinkContext.requireCodeSignature = true;
4717 gLinkContext.processUsingLibraryValidation = true;
4718 sSafeMode = usingSIP;
4719 }
4720 }
4721 #endif
4722 }
4723
4724
4725 bool processIsRestricted()
4726 {
4727 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4728 return gLinkContext.processIsRestricted;
4729 #else
4730 return false;
4731 #endif
4732 }
4733
4734
4735 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
4736 static void addDyldImageToUUIDList()
4737 {
4738 const struct macho_header* mh = (macho_header*)&__dso_handle;
4739 const uint32_t cmd_count = mh->ncmds;
4740 const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
4741 const struct load_command* cmd = cmds;
4742 for (uint32_t i = 0; i < cmd_count; ++i) {
4743 switch (cmd->cmd) {
4744 case LC_UUID: {
4745 uuid_command* uc = (uuid_command*)cmd;
4746 dyld_uuid_info info;
4747 info.imageLoadAddress = (mach_header*)mh;
4748 memcpy(info.imageUUID, uc->uuid, 16);
4749 addNonSharedCacheImageUUID(info);
4750 return;
4751 }
4752 }
4753 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4754 }
4755 }
4756
4757 void notifyKernelAboutImage(const struct macho_header* mh, const char* fileInfo)
4758 {
4759 const char *endptr = nullptr;
4760 uint64_t fsid_scalar = hexToUInt64(fileInfo, &endptr);
4761 uint64_t fsobj_id_scalar = 0;
4762 if (endptr != nullptr) {
4763 fsobj_id_scalar = hexToUInt64(endptr+1, &endptr);
4764 }
4765 const uint32_t cmd_count = mh->ncmds;
4766 const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
4767 const struct load_command* cmd = cmds;
4768 for (uint32_t i = 0; i < cmd_count; ++i) {
4769 switch (cmd->cmd) {
4770 case LC_UUID: {
4771 // Add dyld to the kernel image info
4772 uuid_command* uc = (uuid_command*)cmd;
4773 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A, (const uuid_t *)&uc->uuid[0], *reinterpret_cast<fsobj_id_t *>(&fsobj_id_scalar), *reinterpret_cast<fsid_t *>(&fsid_scalar), (const mach_header *)mh);
4774 return;
4775 }
4776 }
4777 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4778 }
4779 }
4780
4781 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4782 typedef int (*open_proc_t)(const char*, int, int);
4783 typedef int (*fcntl_proc_t)(int, int, void*);
4784 typedef int (*ioctl_proc_t)(int, unsigned long, void*);
4785 static void* getProcessInfo() { return dyld::gProcessInfo; }
4786 static SyscallHelpers sSysCalls = {
4787 8,
4788 // added in version 1
4789 (open_proc_t)&open,
4790 &close,
4791 &pread,
4792 &write,
4793 &mmap,
4794 &munmap,
4795 &madvise,
4796 &stat,
4797 (fcntl_proc_t)&fcntl,
4798 (ioctl_proc_t)&ioctl,
4799 &issetugid,
4800 &getcwd,
4801 &realpath,
4802 &vm_allocate,
4803 &vm_deallocate,
4804 &vm_protect,
4805 &vlog,
4806 &vwarn,
4807 &pthread_mutex_lock,
4808 &pthread_mutex_unlock,
4809 &mach_thread_self,
4810 &mach_port_deallocate,
4811 &task_self_trap,
4812 &mach_timebase_info,
4813 &OSAtomicCompareAndSwapPtrBarrier,
4814 &OSMemoryBarrier,
4815 &getProcessInfo,
4816 &__error,
4817 &mach_absolute_time,
4818 // added in version 2
4819 &thread_switch,
4820 // added in version 3
4821 &opendir,
4822 &readdir_r,
4823 &closedir,
4824 // added in version 4
4825 &coresymbolication_load_notifier,
4826 &coresymbolication_unload_notifier,
4827 // Added in version 5
4828 &proc_regionfilename,
4829 &getpid,
4830 &mach_port_insert_right,
4831 &mach_port_allocate,
4832 &mach_msg,
4833 // Added in version 6
4834 &abort_with_payload,
4835 // Added in version 7
4836 &task_register_dyld_image_infos,
4837 &task_unregister_dyld_image_infos,
4838 &task_get_dyld_image_infos,
4839 &task_register_dyld_shared_cache_image_info,
4840 &task_register_dyld_set_dyld_state,
4841 &task_register_dyld_get_process_state,
4842 // Added in version 8
4843 &task_info,
4844 &thread_info,
4845 &kdebug_is_enabled,
4846 &kdebug_trace
4847 };
4848
4849 __attribute__((noinline))
4850 static const char* useSimulatorDyld(int fd, const macho_header* mainExecutableMH, const char* dyldPath,
4851 int argc, const char* argv[], const char* envp[], const char* apple[],
4852 uintptr_t* startGlue, uintptr_t* mainAddr)
4853 {
4854 *startGlue = 0;
4855 *mainAddr = 0;
4856
4857 // <rdar://problem/25311921> simulator does not support restricted processes
4858 uint32_t flags;
4859 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) == -1 )
4860 return "csops() failed";
4861 if ( (flags & CS_RESTRICT) == CS_RESTRICT )
4862 return "dyld_sim cannot be loaded in a restricted process";
4863 if ( issetugid() )
4864 return "dyld_sim cannot be loaded in a setuid process";
4865 if ( hasRestrictedSegment(mainExecutableMH) )
4866 return "dyld_sim cannot be loaded in a restricted process";
4867
4868 // get file size of dyld_sim
4869 struct stat sb;
4870 if ( fstat(fd, &sb) == -1 )
4871 return "stat(dyld_sim) failed";
4872
4873 // read first page of dyld_sim file
4874 uint8_t firstPage[4096];
4875 if ( pread(fd, firstPage, 4096, 0) != 4096 )
4876 return "pread(dyld_sim) failed";
4877
4878 // if fat file, pick matching slice
4879 uint64_t fileOffset = 0;
4880 uint64_t fileLength = sb.st_size;
4881 const fat_header* fileStartAsFat = (fat_header*)firstPage;
4882 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4883 if ( !fatFindBest(fileStartAsFat, &fileOffset, &fileLength) )
4884 return "no matching arch in dyld_sim";
4885 // re-read buffer from start of mach-o slice in fat file
4886 if ( pread(fd, firstPage, 4096, fileOffset) != 4096 )
4887 return "pread(dyld_sim) failed";
4888 }
4889 else if ( !isCompatibleMachO(firstPage, dyldPath) ) {
4890 return "dyld_sim is not compatible with the loaded process, likely due to architecture mismatch";
4891 }
4892
4893 // calculate total size of dyld segments
4894 const macho_header* mh = (const macho_header*)firstPage;
4895 struct macho_segment_command* lastSeg = NULL;
4896 struct macho_segment_command* firstSeg = NULL;
4897 uintptr_t mappingSize = 0;
4898 uintptr_t preferredLoadAddress = 0;
4899 const uint32_t cmd_count = mh->ncmds;
4900 if ( mh->sizeofcmds > 4096 )
4901 return "dyld_sim load commands to large";
4902 if ( (sizeof(macho_header) + mh->sizeofcmds) > 4096 )
4903 return "dyld_sim load commands to large";
4904 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4905 const struct load_command* const endCmds = (struct load_command*)(((char*)mh) + sizeof(macho_header) + mh->sizeofcmds);
4906 const struct load_command* cmd = cmds;
4907 for (uint32_t i = 0; i < cmd_count; ++i) {
4908 uint32_t cmdLength = cmd->cmdsize;
4909 if ( cmdLength < 8 )
4910 return "dyld_sim load command too small";
4911 const struct load_command* const nextCmd = (const struct load_command*)(((char*)cmd)+cmdLength);
4912 if ( (nextCmd > endCmds) || (nextCmd < cmd) )
4913 return "dyld_sim load command too large";
4914 switch (cmd->cmd) {
4915 case LC_SEGMENT_COMMAND:
4916 {
4917 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4918 if ( seg->vmaddr + seg->vmsize < seg->vmaddr )
4919 return "dyld_sim seg wraps address space";
4920 if ( seg->vmsize < seg->filesize )
4921 return "dyld_sim seg vmsize too small";
4922 if ( (seg->fileoff + seg->filesize) < seg->fileoff )
4923 return "dyld_sim seg size wraps address space";
4924 if ( lastSeg == NULL ) {
4925 // first segment must be __TEXT and start at beginning of file/slice
4926 firstSeg = seg;
4927 if ( strcmp(seg->segname, "__TEXT") != 0 )
4928 return "dyld_sim first segment not __TEXT";
4929 if ( seg->fileoff != 0 )
4930 return "dyld_sim first segment not at file offset zero";
4931 if ( seg->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
4932 return "dyld_sim first segment smaller than load commands";
4933 preferredLoadAddress = seg->vmaddr;
4934 }
4935 else {
4936 // other sements must be continguous with previous segment and not executable
4937 if ( lastSeg->fileoff + lastSeg->filesize != seg->fileoff )
4938 return "dyld_sim segments not contiguous";
4939 if ( lastSeg->vmaddr + lastSeg->vmsize != seg->vmaddr )
4940 return "dyld_sim segments not address contiguous";
4941 if ( (seg->initprot & VM_PROT_EXECUTE) != 0 )
4942 return "dyld_sim non-first segment is executable";
4943 }
4944 mappingSize += seg->vmsize;
4945 lastSeg = seg;
4946 }
4947 break;
4948 case LC_SEGMENT_COMMAND_WRONG:
4949 return "dyld_sim wrong load segment load command";
4950 }
4951 cmd = nextCmd;
4952 }
4953 // last segment must be named __LINKEDIT and not writable
4954 if ( strcmp(lastSeg->segname, "__LINKEDIT") != 0 )
4955 return "dyld_sim last segment not __LINKEDIT";
4956 if ( lastSeg->initprot & VM_PROT_WRITE )
4957 return "dyld_sim __LINKEDIT segment writable";
4958
4959 // reserve space, then mmap each segment
4960 vm_address_t loadAddress = 0;
4961 if ( ::vm_allocate(mach_task_self(), &loadAddress, mappingSize, VM_FLAGS_ANYWHERE) != 0 )
4962 return "dyld_sim cannot allocate space";
4963 cmd = cmds;
4964 struct linkedit_data_command* codeSigCmd = NULL;
4965 struct source_version_command* dyldVersionCmd = NULL;
4966 for (uint32_t i = 0; i < cmd_count; ++i) {
4967 switch (cmd->cmd) {
4968 case LC_SEGMENT_COMMAND:
4969 {
4970 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4971 uintptr_t requestedLoadAddress = seg->vmaddr - preferredLoadAddress + loadAddress;
4972 void* segAddress = ::mmap((void*)requestedLoadAddress, seg->filesize, seg->initprot, MAP_FIXED | MAP_PRIVATE, fd, fileOffset + seg->fileoff);
4973 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
4974 if ( segAddress == (void*)(-1) )
4975 return "dyld_sim mmap() of segment failed";
4976 if ( ((uintptr_t)segAddress < loadAddress) || ((uintptr_t)segAddress+seg->filesize > loadAddress+mappingSize) )
4977 return "dyld_sim mmap() to wrong location";
4978 }
4979 break;
4980 case LC_CODE_SIGNATURE:
4981 codeSigCmd = (struct linkedit_data_command*)cmd;
4982 break;
4983 case LC_SOURCE_VERSION:
4984 dyldVersionCmd = (struct source_version_command*)cmd;
4985 break;
4986 }
4987 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4988 }
4989
4990 // must have code signature which is contained within LINKEDIT segment
4991 if ( codeSigCmd == NULL )
4992 return "dyld_sim not code signed";
4993 if ( codeSigCmd->dataoff < lastSeg->fileoff )
4994 return "dyld_sim code signature not in __LINKEDIT";
4995 if ( (codeSigCmd->dataoff + codeSigCmd->datasize) < codeSigCmd->dataoff )
4996 return "dyld_sim code signature size wraps";
4997 if ( (codeSigCmd->dataoff + codeSigCmd->datasize) > (lastSeg->fileoff + lastSeg->filesize) )
4998 return "dyld_sim code signature extends beyond __LINKEDIT";
4999
5000 fsignatures_t siginfo;
5001 siginfo.fs_file_start=fileOffset; // start of mach-o slice in fat file
5002 siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff); // start of code-signature in mach-o file
5003 siginfo.fs_blob_size=codeSigCmd->datasize; // size of code-signature
5004 int result = fcntl(fd, F_ADDFILESIGS_FOR_DYLD_SIM, &siginfo);
5005 if ( result == -1 ) {
5006 return mkstringf("dyld_sim fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d", errno);
5007 }
5008 close(fd);
5009 // file range covered by code signature must extend up to code signature itself
5010 if ( siginfo.fs_file_start < codeSigCmd->dataoff )
5011 return mkstringf("dyld_sim code signature does not cover all of dyld_sim. Signature covers up to 0x%08lX. Signature starts at 0x%08X", (unsigned long)siginfo.fs_file_start, codeSigCmd->dataoff);
5012
5013 // walk newly mapped dyld_sim __TEXT load commands to find entry point
5014 uintptr_t entry = 0;
5015 cmd = (struct load_command*)(((char*)loadAddress)+sizeof(macho_header));
5016 const uint32_t count = ((macho_header*)(loadAddress))->ncmds;
5017 for (uint32_t i = 0; i < count; ++i) {
5018 if (cmd->cmd == LC_UNIXTHREAD) {
5019 #if __i386__
5020 const i386_thread_state_t* registers = (i386_thread_state_t*)(((char*)cmd) + 16);
5021 // entry point must be in first segment
5022 if ( registers->__eip < firstSeg->vmaddr )
5023 return "dyld_sim entry point not in __TEXT segment";
5024 if ( registers->__eip > (firstSeg->vmaddr + firstSeg->vmsize) )
5025 return "dyld_sim entry point not in __TEXT segment";
5026 entry = (registers->__eip + loadAddress - preferredLoadAddress);
5027 #elif __x86_64__
5028 const x86_thread_state64_t* registers = (x86_thread_state64_t*)(((char*)cmd) + 16);
5029 // entry point must be in first segment
5030 if ( registers->__rip < firstSeg->vmaddr )
5031 return "dyld_sim entry point not in __TEXT segment";
5032 if ( registers->__rip > (firstSeg->vmaddr + firstSeg->vmsize) )
5033 return "dyld_sim entry point not in __TEXT segment";
5034 entry = (registers->__rip + loadAddress - preferredLoadAddress);
5035 #endif
5036 }
5037 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
5038 }
5039
5040 // notify debugger that dyld_sim is loaded
5041 dyld_image_info info;
5042 info.imageLoadAddress = (mach_header*)loadAddress;
5043 info.imageFilePath = strdup(dyldPath);
5044 info.imageFileModDate = sb.st_mtime;
5045 addImagesToAllImages(1, &info);
5046 dyld::gProcessInfo->notification(dyld_image_adding, 1, &info);
5047
5048 const char** appleParams = apple;
5049 // jump into new simulator dyld
5050 typedef uintptr_t (*sim_entry_proc_t)(int argc, const char* argv[], const char* envp[], const char* apple[],
5051 const macho_header* mainExecutableMH, const macho_header* dyldMH, uintptr_t dyldSlide,
5052 const dyld::SyscallHelpers* vtable, uintptr_t* startGlue);
5053 sim_entry_proc_t newDyld = (sim_entry_proc_t)entry;
5054 *mainAddr = (*newDyld)(argc, argv, envp, appleParams, mainExecutableMH, (macho_header*)loadAddress,
5055 loadAddress - preferredLoadAddress,
5056 &sSysCalls, startGlue);
5057 return NULL;
5058 }
5059 #endif
5060
5061 //
5062 // If the DYLD_SKIP_MAIN environment is set to 1, dyld will return the
5063 // address of this function instead of main() in the target program which
5064 // __dyld_start jumps to. Useful for qualifying dyld itself.
5065 //
5066 int
5067 fake_main()
5068 {
5069 return 0;
5070 }
5071
5072
5073
5074
5075 static bool envVarMatches(dyld3::launch_cache::Closure mainClosure, const char* envp[], const char* varName)
5076 {
5077 __block const char* valueFromClosure = nullptr;
5078 mainClosure.forEachEnvVar(^(const char* keyEqualValue, bool& stop) {
5079 size_t keyLen = strlen(varName);
5080 if ( (strncmp(varName, keyEqualValue, keyLen) == 0) && (keyEqualValue[keyLen] == '=') ) {
5081 valueFromClosure = &keyEqualValue[keyLen+1];
5082 stop = true;
5083 }
5084 });
5085
5086 const char* valueFromEnv = _simple_getenv(envp, varName);
5087
5088 bool inClosure = (valueFromClosure != nullptr);
5089 bool inEnv = (valueFromEnv != nullptr);
5090 if ( inClosure != inEnv )
5091 return false;
5092 if ( !inClosure && !inEnv )
5093 return true;
5094 return ( strcmp(valueFromClosure, valueFromEnv) == 0 );
5095 }
5096
5097 static const char* const sEnvVarsToCheck[] = {
5098 "DYLD_LIBRARY_PATH",
5099 "DYLD_FRAMEWORK_PATH",
5100 "DYLD_FALLBACK_LIBRARY_PATH",
5101 "DYLD_FALLBACK_FRAMEWORK_PATH",
5102 "DYLD_INSERT_LIBRARIES",
5103 "DYLD_IMAGE_SUFFIX",
5104 "DYLD_VERSIONED_FRAMEWORK_PATH",
5105 "DYLD_VERSIONED_LIBRARY_PATH",
5106 "DYLD_ROOT_PATH"
5107 };
5108
5109 static bool envVarsMatch(dyld3::launch_cache::Closure mainClosure, const char* envp[])
5110 {
5111 for (const char* envVar : sEnvVarsToCheck) {
5112 if ( !envVarMatches(mainClosure, envp, envVar) ) {
5113 if ( gLinkContext.verboseWarnings )
5114 dyld::log("dyld: closure %p not used because %s changed\n", mainClosure.binaryData(), envVar);
5115 return false;
5116 }
5117 }
5118
5119 return true;
5120 }
5121
5122 static bool closureValid(const dyld3::launch_cache::BinaryClosureData* mainClosureData, const mach_header* mainExecutableMH, const uint8_t* mainExecutableCDHash, bool closureInCache, const char* envp[])
5123 {
5124 const dyld3::launch_cache::Closure mainClosure(mainClosureData);
5125 const dyld3::launch_cache::ImageGroup mainGroup = mainClosure.group();
5126
5127 // verify current dyld cache is same as expected
5128 if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
5129 if ( gLinkContext.verboseWarnings )
5130 dyld::log("dyld: closure %p dyld cache not loaded\n", mainClosureData);
5131 return false;
5132 }
5133 if ( !closureInCache ) {
5134 // closures in cache don't have cache's UUID
5135 uuid_t cacheUUID;
5136 sSharedCacheLoadInfo.loadAddress->getUUID(cacheUUID);
5137 if ( memcmp(mainClosure.dyldCacheUUID(), cacheUUID, sizeof(uuid_t)) != 0 ) {
5138 if ( gLinkContext.verboseWarnings )
5139 dyld::log("dyld: closure %p not used because built against different dyld cache\n", mainClosureData);
5140 return false;
5141 }
5142 }
5143 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5144 else {
5145 // If the in-memory cache doesn't have the same UUID xattr as the on-disk cache then we must
5146 // have built a new cache but not rebooted. In this case, don't use dyld3.
5147 const char* sharedCachePath = getStandardSharedCacheFilePath();
5148 uuid_t inMemoryUUID;
5149 uuid_t onDiskUUID;
5150 sharedCacheUUID(inMemoryUUID);
5151 if (getxattr(sharedCachePath, "cacheUUID", (void*)&onDiskUUID, sizeof(uuid_t), 0, 0) != sizeof(uuid_t)) {
5152 if ( gLinkContext.verboseWarnings )
5153 dyld::log("dyld: closure %p on disk cache doesn't have a UUID xattr\n", mainClosureData);
5154 return false;
5155 }
5156 if (memcmp(&inMemoryUUID, &onDiskUUID, sizeof(uuid_t)) != 0) {
5157 if ( gLinkContext.verboseWarnings )
5158 dyld::log("dyld: closure %p not used because current cache on disk and in memory cache have UUID mismatches\n", mainClosureData);
5159 return false;
5160 }
5161 }
5162 #endif
5163
5164 // verify main executable file has not changed since closure was built
5165 const dyld3::launch_cache::Image mainImage = mainGroup.image(mainClosure.mainExecutableImageIndex());
5166 if ( mainImage.validateUsingModTimeAndInode() ) {
5167 struct stat statBuf;
5168 if ( ::stat(mainImage.path(), &statBuf) != 0 ) {
5169 if ( gLinkContext.verboseWarnings )
5170 dyld::log("dyld: closure %p not used because stat() failed on main executable\n", mainClosureData);
5171 return false;
5172 }
5173 else if ( (statBuf.st_mtime != mainImage.fileModTime()) || (statBuf.st_ino != mainImage.fileINode()) ) {
5174 if ( gLinkContext.verboseWarnings )
5175 dyld::log("dyld: closure %p not used because mtime/inode changed since closure was built\n", mainClosureData);
5176 return false;
5177 }
5178 }
5179
5180 // verify cdHash of main executable is same as recorded in closure
5181 if ( mainImage.validateUsingCdHash() ) {
5182 if ( mainExecutableCDHash == nullptr ) {
5183 if ( gLinkContext.verboseWarnings )
5184 dyld::log("dyld: closure %p not used because main executable is not code signed but was expected to be\n", mainClosureData);
5185 return false;
5186 }
5187 if ( memcmp(mainExecutableCDHash, mainClosure.cdHash(), 20) != 0 ) {
5188 if ( gLinkContext.verboseWarnings )
5189 dyld::log("dyld: closure %p not used because main executable cd-hash changed since closure was built\n", mainClosureData);
5190 return false;
5191 }
5192 }
5193
5194 // verify UUID of main executable is same as recorded in closure
5195 const uuid_t* closureMainUUID = mainImage.uuid();
5196 dyld3::MachOParser parser(mainExecutableMH);
5197 uuid_t actualUUID;
5198 parser.getUuid(actualUUID);
5199 if ( memcmp(actualUUID, closureMainUUID, sizeof(uuid_t)) != 0 ) {
5200 if ( gLinkContext.verboseWarnings )
5201 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosureData);
5202 return false;
5203 }
5204
5205 // verify DYLD_* env vars are same as when closure was built
5206 if ( !envVarsMatch(mainClosure, envp) ) {
5207 return false;
5208 }
5209
5210 // verify files that are supposed to be missing actually are missing
5211 __block bool foundFileThatInvalidatesClosure = false;
5212 mainClosure.forEachMustBeMissingFile(^(const char* path, bool& stop) {
5213 struct stat statBuf;
5214 if ( ::stat(path, &statBuf) == 0 ) {
5215 stop = true;
5216 foundFileThatInvalidatesClosure = true;
5217 if ( gLinkContext.verboseWarnings )
5218 dyld::log("dyld: closure %p not used because found unexpected file '%s'\n", mainClosureData, path);
5219 }
5220 });
5221
5222 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5223 // verify no key frameworks have been overridden since cache was built
5224 if ( dyld3::loader::internalInstall() ) {
5225 dyld3::loader::forEachLineInFile("/AppleInternal/Library/Preferences/dyld-potential-framework-overrides", ^(const char* path, bool& stop) {
5226 dyld3::SharedCacheFindDylibResults shareCacheResults;
5227 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &shareCacheResults) ) {
5228 dyld3::launch_cache::Image image(shareCacheResults.imageData);
5229 struct stat statBuf;
5230 if ( ::stat(path, &statBuf) == 0 ) {
5231 if ( (image.fileModTime() != statBuf.st_mtime) || (image.fileINode() != statBuf.st_ino)) {
5232 if ( gLinkContext.verboseWarnings )
5233 dyld::log("dyld: closure %p not used because framework has changed: '%s'\n", mainClosureData, path);
5234 foundFileThatInvalidatesClosure = true;
5235 stop = true;
5236 }
5237 }
5238 }
5239 });
5240 }
5241 #endif
5242
5243 return !foundFileThatInvalidatesClosure;
5244 }
5245
5246 static bool nolog(const char* format, ...)
5247 {
5248 return false;
5249 }
5250
5251 static bool dolog(const char* format, ...)
5252 {
5253 va_list list;
5254 va_start(list, format);
5255 vlog(format, list);
5256 va_end(list);
5257 return true;
5258 }
5259
5260 static bool launchWithClosure(const dyld3::launch_cache::BinaryClosureData* mainClosureData,
5261 const DyldSharedCache* dyldCache,
5262 const mach_header* mainExecutableMH, uintptr_t mainExecutableSlide,
5263 int argc, const char* argv[], const char* envp[], const char* apple[],
5264 uintptr_t* entry, uintptr_t* startGlue)
5265 {
5266 dyld3::launch_cache::Closure mainClosure(mainClosureData);
5267 const dyld3::launch_cache::ImageGroup mainGroup = mainClosure.group();
5268 const uint32_t mainExecutableIndex = mainClosure.mainExecutableImageIndex();
5269 const dyld3::launch_cache::Image mainImage = mainGroup.image(mainExecutableIndex);
5270 const uint32_t loadedImageCount = mainClosure.initialImageCount();
5271
5272 // construct array of groups
5273 dyld3::DyldCacheParser cacheParser(dyldCache, false);
5274 STACK_ALLOC_DYNARRAY(const dyld3::launch_cache::binary_format::ImageGroup*, 3, theGroups);
5275 theGroups[0] = cacheParser.cachedDylibsGroup();
5276 theGroups[1] = cacheParser.otherDylibsGroup();
5277 theGroups[2] = mainClosure.group().binaryData();
5278
5279 // construct array of all Image*, starting with any inserted dylibs, then main executable
5280 const dyld3::launch_cache::BinaryImageData* images[loadedImageCount];
5281 dyld3::launch_cache::SlowLoadSet imageSet(&images[0], &images[loadedImageCount]);
5282 for (uint32_t i=0; i <= mainExecutableIndex; ++i) {
5283 imageSet.add(mainGroup.image(i).binaryData());
5284 }
5285 // add all dependents of main executable
5286 if ( !mainImage.recurseAllDependentImages(theGroups, imageSet, nullptr) ) {
5287 dyld::log("initial image list overflow, expected only %d\n", loadedImageCount);
5288 return false;
5289 }
5290 // add dependents of any inserted dylibs
5291 for (uint32_t i=0; i < mainExecutableIndex; ++i) {
5292 if ( !mainGroup.image(i).recurseAllDependentImages(theGroups, imageSet, nullptr) ) {
5293 dyld::log("initial image list overflow in inserted libraries, expected only %d\n", loadedImageCount);
5294 return false;
5295 }
5296 }
5297 const uint32_t actualImageCount = (uint32_t)imageSet.count();
5298 // construct array of allImages
5299 STACK_ALLOC_DYNARRAY(dyld3::loader::ImageInfo, actualImageCount, allImages);
5300 for (int i=0; i < actualImageCount; ++i) {
5301 dyld3::launch_cache::Image img(images[i]);
5302 dyld3::launch_cache::ImageGroup grp = img.group();
5303 allImages[i].imageData = img.binaryData();
5304 allImages[i].loadAddress = nullptr;
5305 allImages[i].groupNum = grp.groupNum();
5306 allImages[i].indexInGroup = grp.indexInGroup(img.binaryData());
5307 allImages[i].previouslyFixedUp = false;
5308 allImages[i].justMapped = false;
5309 allImages[i].justUsedFromDyldCache = false;
5310 allImages[i].neverUnload = false;
5311 }
5312 // prefill address of main executable to mark it is already loaded
5313 allImages[mainExecutableIndex].loadAddress = mainExecutableMH;
5314
5315 // map new images and apply all fixups
5316 Diagnostics diag;
5317 mapAndFixupImages(diag, allImages, (const uint8_t*)dyldCache, (gLinkContext.verboseLoading ? &dolog : &nolog),
5318 (gLinkContext.verboseMapping ? &dolog : &nolog),
5319 (gLinkContext.verboseBind ? &dolog : &nolog),
5320 (gLinkContext.verboseDOF ? &dolog : &nolog));
5321 if ( diag.hasError() ) {
5322 if ( gLinkContext.verboseWarnings )
5323 dyld::log("dyld: %s\n", diag.errorMessage());
5324 return false;
5325 }
5326
5327 //dyld::log("loaded image list:\n");
5328 //for (int i=0; i < allImages.count(); ++i) {
5329 // dyld3::launch_cache::Image img(allImages[i].imageData);
5330 // dyld::log("binImage[%d]=%p, mh=%p, path=%s\n", i, allImages[i].imageData, allImages[i].loadAddress, img.path());
5331 //}
5332
5333 // find special images
5334 const dyld3::launch_cache::BinaryImageData* libSystemImage = mainClosure.libSystem(theGroups);
5335 const dyld3::launch_cache::BinaryImageData* libDyldImage = mainClosure.libDyld(theGroups);
5336 const mach_header* libdyldMH = nullptr;
5337 const mach_header* libSystemMH = nullptr;
5338 for (int i=0; i < allImages.count(); ++i) {
5339 if ( allImages[i].imageData == libSystemImage )
5340 libSystemMH = allImages[i].loadAddress;
5341 else if ( allImages[i].imageData == libDyldImage )
5342 libdyldMH = allImages[i].loadAddress;
5343 }
5344
5345 // send info on all images to libdyld.dylb
5346 const dyld3::LibDyldEntryVector* libDyldEntry = (dyld3::LibDyldEntryVector*)((uint8_t*)libdyldMH + mainClosure.libdyldVectorOffset());
5347 libDyldEntry->setVars(mainExecutableMH, argc, argv, envp, apple);
5348 libDyldEntry->setHaltFunction(&halt);
5349 if ( libDyldEntry->vectorVersion > 2 )
5350 libDyldEntry->setChildForkFunction(&_dyld_fork_child);
5351 #if !TARGET_IPHONE_SIMULATOR
5352 if ( libDyldEntry->vectorVersion > 3 )
5353 libDyldEntry->setLogFunction(&dyld::vlog);
5354 #endif
5355 libDyldEntry->setOldAllImageInfo(gProcessInfo);
5356 libDyldEntry->setInitialImageList(mainClosureData, dyldCache, sSharedCacheLoadInfo.path, allImages, libSystemMH, libSystemImage);
5357 // run initializers
5358 CRSetCrashLogMessage("dyld3: launch, running initializers");
5359 libDyldEntry->runInitialzersBottomUp((mach_header*)mainExecutableMH);
5360 //dyld::log("returned from runInitialzersBottomUp()\n");
5361
5362 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN, 0, 0);
5363 if ( mainClosure.mainExecutableUsesCRT() ) {
5364 // old style app linked with crt1.o
5365 // entry is "start" function in program
5366 *startGlue = 0;
5367 *entry = (uintptr_t)mainExecutableMH + mainClosure.mainExecutableEntryOffset();
5368 }
5369 else {
5370 // modern app with LC_MAIN
5371 // set startGlue to "start" function in libdyld.dylib
5372 // set entry to "main" function in program
5373 *startGlue = (uintptr_t)(libDyldEntry->startFunc);
5374 *entry =(uintptr_t)mainExecutableMH + mainClosure.mainExecutableEntryOffset();
5375 }
5376 CRSetCrashLogMessage(NULL);
5377 return true;
5378 }
5379
5380 static void putHexNibble(uint8_t value, char*& p)
5381 {
5382 if ( value < 10 )
5383 *p++ = '0' + value;
5384 else
5385 *p++ = 'A' + value - 10;
5386 }
5387
5388 static void putHexByte(uint8_t value, char*& p)
5389 {
5390 value &= 0xFF;
5391 putHexNibble(value >> 4, p);
5392 putHexNibble(value & 0x0F, p);
5393 }
5394
5395 static void makeHexLong(unsigned long value, char* p)
5396 {
5397 *p++ = '0';
5398 *p++ = 'x';
5399 #if __LP64__
5400 putHexByte(value >> 56, p);
5401 putHexByte(value >> 48, p);
5402 putHexByte(value >> 40, p);
5403 putHexByte(value >> 32, p);
5404 #endif
5405 putHexByte(value >> 24, p);
5406 putHexByte(value >> 16, p);
5407 putHexByte(value >> 8, p);
5408 putHexByte(value, p);
5409 *p = '\0';
5410 }
5411
5412 static void makeUUID(uint8_t uuid[16], char* p)
5413 {
5414 putHexByte(uuid[0], p);
5415 putHexByte(uuid[1], p);
5416 putHexByte(uuid[2], p);
5417 putHexByte(uuid[3], p);
5418 *p++ = '-';
5419 putHexByte(uuid[4], p);
5420 putHexByte(uuid[5], p);
5421 *p++ = '-';
5422 putHexByte(uuid[6], p);
5423 putHexByte(uuid[7], p);
5424 *p++ = '-';
5425 putHexByte(uuid[8], p);
5426 putHexByte(uuid[9], p);
5427 *p++ = '-';
5428 putHexByte(uuid[10], p);
5429 putHexByte(uuid[11], p);
5430 putHexByte(uuid[12], p);
5431 putHexByte(uuid[13], p);
5432 putHexByte(uuid[14], p);
5433 putHexByte(uuid[15], p);
5434 *p = '\0';
5435 }
5436
5437 #if !TARGET_IPHONE_SIMULATOR
5438 static const dyld3::launch_cache::BinaryClosureData* callClosureDaemon(const char* mainExecPath, const char* envp[])
5439 {
5440 // temp, until we can get a bootstrap_lookup that works from dyld
5441 #if 1
5442 // Create a pipe
5443 int sockets[2];
5444 if ( ::pipe(sockets) < 0 ) {
5445 dyld::log("error opening stream socket pair to closured\n");
5446 return NULL;
5447 }
5448 //dyld::log("created sockets %d and %d\n", sockets[0], sockets[1]);
5449 // use fork/exec to launch closured
5450 int child = ::__fork();
5451 if ( child == -1 ) {
5452 dyld::log("error forking, errno=%d\n", errno);
5453 return NULL;
5454 }
5455 if ( child ) {
5456 // parent side
5457 //dyld::log("parent side pid=%d\n", getpid());
5458 ::close(sockets[1]);
5459 SocketBasedClousureHeader header;
5460 long amount = ::read(sockets[0], &header, sizeof(SocketBasedClousureHeader));
5461 if ( amount != sizeof(SocketBasedClousureHeader) ) {
5462 dyld::log("error reading, errno=%d\n", errno);
5463 return NULL;
5464 }
5465 vm_address_t bufferAddress = 0;
5466 if ( ::vm_allocate(mach_task_self(), &bufferAddress, header.length, VM_FLAGS_ANYWHERE) != 0 ) {
5467 dyld::log("error allocating buffer\n");
5468 return NULL;
5469 }
5470 amount = ::read(sockets[0], (void*)bufferAddress, header.length);
5471 close(sockets[0]);
5472 if ( amount != header.length ) {
5473 dyld::log("dyld: error reading buffer header from closured, amount=%ld, errno=%d\n", amount, errno);
5474 return NULL;
5475 }
5476 if ( header.success ) {
5477 // make buffer read-only
5478 vm_protect(mach_task_self(), bufferAddress, header.length, VM_PROT_READ, VM_PROT_READ);
5479 return (const dyld3::launch_cache::BinaryClosureData*)bufferAddress;
5480 }
5481 else {
5482 // buffer contains error message as to why closure could not be built
5483 dyld::log("%s", (char*)bufferAddress);
5484 ::vm_deallocate(mach_task_self(), bufferAddress, header.length);
5485 return NULL;
5486 }
5487 }
5488 else {
5489 // child side
5490 //dyld::log("child side pid=%d\n", getpid());
5491 close(sockets[0]);
5492 const char* closuredPath = "/usr/libexec/closured";
5493 char pipeStr[8];
5494 pipeStr[0] = '0' + sockets[1];
5495 pipeStr[1] = '\0';
5496 const char* argv[32];
5497 char cacheUuidString[64];
5498 char cacheAddrString[64];
5499 char cacheSizeString[64];
5500 int i = 0;
5501 uuid_t cacheUUID;
5502 sSharedCacheLoadInfo.loadAddress->getUUID(cacheUUID);
5503 makeHexLong((long)sSharedCacheLoadInfo.loadAddress, cacheAddrString);
5504 makeHexLong((long)sSharedCacheLoadInfo.loadAddress->mappedSize(), cacheSizeString);
5505 makeUUID(cacheUUID, cacheUuidString);
5506 argv[i++] = closuredPath;
5507 argv[i++] = "-create_closure";
5508 argv[i++] = mainExecPath;
5509 argv[i++] = "-pipefd";
5510 argv[i++] = pipeStr;
5511 argv[i++] = "-cache_uuid";
5512 argv[i++] = cacheUuidString;
5513 argv[i++] = "-cache_address";
5514 argv[i++] = cacheAddrString;
5515 argv[i++] = "-cache_size";
5516 argv[i++] = cacheSizeString;
5517 for (const char**p=envp; *p != NULL; ++p) {
5518 const char* envToCheck = *p;
5519 for (const char* dyldEnvVar : sEnvVarsToCheck) {
5520 size_t dyldEnvVarLen = strlen(dyldEnvVar);
5521 if ( (strncmp(dyldEnvVar, envToCheck, dyldEnvVarLen) == 0) && (envToCheck[dyldEnvVarLen] == '=') ) {
5522 argv[i++] = "-env";
5523 argv[i++] = envToCheck;
5524 }
5525 }
5526 }
5527 argv[i] = nullptr;
5528 //dyld::log("closured args:\n");
5529 //for (int j=0; argv[j] != nullptr; ++j)
5530 // dyld::log(" argv[%d]=%s\n", j, argv[j]);
5531 execve(closuredPath, (char**)argv, nullptr);
5532 dyld::log("exec() of closured failed, errno=%d\n", errno);
5533 }
5534 return NULL;
5535
5536 #else
5537 // get port to closured
5538 mach_port_t serverPort = dyld3::loader::lookupClosuredPort();
5539 if ( serverPort == MACH_PORT_NULL )
5540 return NULL;
5541
5542 // build env var list
5543 char envBuffer[2048];
5544 char* s = envBuffer;
5545 for (const char* envVar : sEnvVarsToCheck) {
5546 if ( const char* valueFromEnv = _simple_getenv(envp, envVar) ) {
5547 strcpy(s, envVar);
5548 strcat(s, "=");
5549 strcat(s, valueFromEnv);
5550 s += strlen(s)+1;
5551 }
5552 }
5553 *s++ = '\0';
5554
5555 // get uuid of main executable
5556 dyld3::MachOParser mainParser((mach_header*)sMainExecutableMachHeader);
5557 uuid_t mainUuid;
5558 mainParser.getUuid(mainUuid);
5559
5560 // message closured to build closure
5561 bool success = false;
5562 vm_offset_t reply = 0;
5563 uint32_t replySize = 0;
5564 if ( closured_CreateLaunchClosure(serverPort, sExecPath, sSharedCachePath, mainUuid, envBuffer, &success, &reply, &replySize) != KERN_SUCCESS )
5565 return NULL;
5566
5567 // release server port
5568 mach_port_deallocate(mach_task_self(), serverPort);
5569
5570 if ( success )
5571 return (const dyld3::launch_cache::BinaryClosureData*)reply;
5572
5573 dyld::log("closure failed to build: %s\n", (char*)reply);
5574 return NULL;
5575 #endif
5576 }
5577 #endif // !TARGET_IPHONE_SIMULATOR
5578
5579
5580 #if !__MAC_OS_X_VERSION_MIN_REQUIRED
5581 static const char* sWhiteListDirs[] = {
5582 "/bin/",
5583 "/sbin/",
5584 "/usr/bin/"
5585 };
5586 #endif
5587
5588 static bool inWhiteList(const char* execPath)
5589 {
5590 // First test to see if we forced in dyld2 via a kernel boot-arg
5591 if ( dyld3::loader::bootArgsContains("force_dyld2=1") )
5592 return false;
5593
5594 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5595
5596 // rdar://problem/32701418: Don't use dyld3 for i386 for now.
5597 #if __i386__
5598 return false;
5599 #else
5600
5601
5602 return true;
5603 #endif // #if __i386__
5604
5605 #else
5606 // <rdar://problem/33171968> enable dyld3 mode for all OS programs when using customer dyld cache (no roots)
5607 if ( (sSharedCacheLoadInfo.loadAddress != nullptr) && (sSharedCacheLoadInfo.loadAddress->header.cacheType == kDyldSharedCacheTypeProduction) )
5608 return true;
5609
5610 for (const char* dir : sWhiteListDirs) {
5611 if ( strncmp(dir, sExecPath, strlen(dir)) == 0 ) {
5612 return true;
5613 }
5614 }
5615 return dyld3::loader::bootArgsContains("force_dyld3=1");
5616 #endif
5617 }
5618
5619 //
5620 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
5621 // sets up some registers and call this function.
5622 //
5623 // Returns address of main() in target program which __dyld_start jumps to
5624 //
5625 uintptr_t
5626 _main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide,
5627 int argc, const char* argv[], const char* envp[], const char* apple[],
5628 uintptr_t* startGlue)
5629 {
5630 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_DYLD, 0, 0);
5631
5632 // Grab the cdHash of the main executable from the environment
5633 uint8_t mainExecutableCDHashBuffer[20];
5634 const uint8_t* mainExecutableCDHash = nullptr;
5635 if ( hexToBytes(_simple_getenv(apple, "executable_cdhash"), 40, mainExecutableCDHashBuffer) )
5636 mainExecutableCDHash = mainExecutableCDHashBuffer;
5637
5638 // Trace dyld's load
5639 notifyKernelAboutImage((macho_header*)&__dso_handle, _simple_getenv(apple, "dyld_file"));
5640 #if !TARGET_IPHONE_SIMULATOR
5641 // Trace the main executable's load
5642 notifyKernelAboutImage(mainExecutableMH, _simple_getenv(apple, "executable_file"));
5643 #endif
5644
5645 uintptr_t result = 0;
5646 sMainExecutableMachHeader = mainExecutableMH;
5647 sMainExecutableSlide = mainExecutableSlide;
5648 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5649 // if this is host dyld, check to see if iOS simulator is being run
5650 const char* rootPath = _simple_getenv(envp, "DYLD_ROOT_PATH");
5651 if ( rootPath != NULL ) {
5652
5653 // look to see if simulator has its own dyld
5654 char simDyldPath[PATH_MAX];
5655 strlcpy(simDyldPath, rootPath, PATH_MAX);
5656 strlcat(simDyldPath, "/usr/lib/dyld_sim", PATH_MAX);
5657 int fd = my_open(simDyldPath, O_RDONLY, 0);
5658 if ( fd != -1 ) {
5659 const char* errMessage = useSimulatorDyld(fd, mainExecutableMH, simDyldPath, argc, argv, envp, apple, startGlue, &result);
5660 if ( errMessage != NULL )
5661 halt(errMessage);
5662 return result;
5663 }
5664 }
5665 #endif
5666
5667 CRSetCrashLogMessage("dyld: launch started");
5668
5669 setContext(mainExecutableMH, argc, argv, envp, apple);
5670
5671 // Pickup the pointer to the exec path.
5672 sExecPath = _simple_getenv(apple, "executable_path");
5673
5674 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
5675 if (!sExecPath) sExecPath = apple[0];
5676
5677 if ( sExecPath[0] != '/' ) {
5678 // have relative path, use cwd to make absolute
5679 char cwdbuff[MAXPATHLEN];
5680 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
5681 // maybe use static buffer to avoid calling malloc so early...
5682 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
5683 strcpy(s, cwdbuff);
5684 strcat(s, "/");
5685 strcat(s, sExecPath);
5686 sExecPath = s;
5687 }
5688 }
5689
5690 // Remember short name of process for later logging
5691 sExecShortName = ::strrchr(sExecPath, '/');
5692 if ( sExecShortName != NULL )
5693 ++sExecShortName;
5694 else
5695 sExecShortName = sExecPath;
5696
5697 configureProcessRestrictions(mainExecutableMH);
5698
5699 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5700 if ( gLinkContext.processIsRestricted ) {
5701 pruneEnvironmentVariables(envp, &apple);
5702 // set again because envp and apple may have changed or moved
5703 setContext(mainExecutableMH, argc, argv, envp, apple);
5704 }
5705 else
5706 #endif
5707 {
5708 checkEnvironmentVariables(envp);
5709 defaultUninitializedFallbackPaths(envp);
5710 }
5711 if ( sEnv.DYLD_PRINT_OPTS )
5712 printOptions(argv);
5713 if ( sEnv.DYLD_PRINT_ENV )
5714 printEnvironmentVariables(envp);
5715 getHostInfo(mainExecutableMH, mainExecutableSlide);
5716
5717 // load shared cache
5718 checkSharedRegionDisable((mach_header*)mainExecutableMH);
5719 #if TARGET_IPHONE_SIMULATOR
5720 // <HACK> until <rdar://30773711> is fixed
5721 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
5722 // </HACK>
5723 #endif
5724 if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion ) {
5725 mapSharedCache();
5726 }
5727
5728 if ( (sEnableClosures || inWhiteList(sExecPath)) && (sSharedCacheLoadInfo.loadAddress != nullptr) ) {
5729 if ( sSharedCacheLoadInfo.loadAddress->header.formatVersion == dyld3::launch_cache::binary_format::kFormatVersion ) {
5730 const dyld3::launch_cache::BinaryClosureData* mainClosureData;
5731 // check for closure in cache first
5732 dyld3::DyldCacheParser cacheParser(sSharedCacheLoadInfo.loadAddress, false);
5733 mainClosureData = cacheParser.findClosure(sExecPath);
5734 #if __IPHONE_OS_VERSION_MIN_REQUIRED
5735 if ( mainClosureData == nullptr ) {
5736 // see if this is an OS app that was moved
5737 if ( strncmp(sExecPath, "/var/containers/Bundle/Application/", 35) == 0 ) {
5738 dyld3::MachOParser mainParser((mach_header*)mainExecutableMH);
5739 uint32_t textOffset;
5740 uint32_t textSize;
5741 if ( !mainParser.isFairPlayEncrypted(textOffset, textSize) ) {
5742 __block bool hasEmbeddedDylibs = false;
5743 mainParser.forEachDependentDylib(^(const char* loadPath, bool, bool, bool, uint32_t, uint32_t, bool& stop) {
5744 if ( loadPath[0] == '@' ) {
5745 hasEmbeddedDylibs = true;
5746 stop = true;
5747 }
5748 });
5749 if ( !hasEmbeddedDylibs ) {
5750 char altPath[1024];
5751 const char* lastSlash = strrchr(sExecPath, '/');
5752 if ( lastSlash != nullptr ) {
5753 strlcpy(altPath, "/private/var/staged_system_apps", sizeof(altPath));
5754 strlcat(altPath, lastSlash, sizeof(altPath));
5755 strlcat(altPath, ".app", sizeof(altPath));
5756 strlcat(altPath, lastSlash, sizeof(altPath));
5757 if ( gLinkContext.verboseWarnings )
5758 dyld::log("try path: %s\n", altPath);
5759 mainClosureData = cacheParser.findClosure(altPath);
5760 }
5761 }
5762 }
5763 }
5764 }
5765 #endif
5766 if ( gLinkContext.verboseWarnings && (mainClosureData != nullptr) )
5767 dyld::log("dyld: found closure %p in dyld shared cache\n", mainClosureData);
5768 #if !TARGET_IPHONE_SIMULATOR
5769 if ( (mainClosureData == nullptr) || !closureValid(mainClosureData, (mach_header*)mainExecutableMH, mainExecutableCDHash, true, envp) ) {
5770 mainClosureData = nullptr;
5771 if ( sEnableClosures ) {
5772 // if forcing closures, and no closure in cache, or it is invalid, then RPC to closured
5773 mainClosureData = callClosureDaemon(sExecPath, envp);
5774 if ( gLinkContext.verboseWarnings )
5775 dyld::log("dyld: closured return %p for %s\n", mainClosureData, sExecPath);
5776 if ( (mainClosureData != nullptr) && !closureValid(mainClosureData, (mach_header*)mainExecutableMH, mainExecutableCDHash, false, envp) ) {
5777 // some how freshly generated closure is invalid...
5778 mainClosureData = nullptr;
5779 }
5780 }
5781 }
5782 #endif
5783 // try using launch closure
5784 if ( mainClosureData != nullptr ) {
5785 CRSetCrashLogMessage("dyld3: launch started");
5786 if ( launchWithClosure(mainClosureData, sSharedCacheLoadInfo.loadAddress, (mach_header*)mainExecutableMH, mainExecutableSlide,
5787 argc, argv, envp, apple, &result, startGlue) ) {
5788 if (sSkipMain)
5789 result = (uintptr_t)&fake_main;
5790 return result;
5791 }
5792 else {
5793 if ( gLinkContext.verboseWarnings )
5794 dyld::log("dyld: unable to use closure %p\n", mainClosureData);
5795 }
5796 }
5797 }
5798 else {
5799 if ( gLinkContext.verboseWarnings )
5800 dyld::log("dyld: not using closure because shared cache format version does not match dyld's\n");
5801 }
5802 // could not use closure info, launch old way
5803 }
5804
5805
5806 // install gdb notifier
5807 stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
5808 stateToHandlers(dyld_image_state_mapped, sSingleHandlers)->push_back(updateAllImages);
5809 // make initial allocations large enough that it is unlikely to need to be re-alloced
5810 sImageRoots.reserve(16);
5811 sAddImageCallbacks.reserve(4);
5812 sRemoveImageCallbacks.reserve(4);
5813 sImageFilesNeedingTermination.reserve(16);
5814 sImageFilesNeedingDOFUnregistration.reserve(8);
5815
5816 #if !TARGET_IPHONE_SIMULATOR
5817 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
5818 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
5819 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo->systemOrderFlag);
5820 #endif
5821 #endif
5822
5823
5824 try {
5825 // add dyld itself to UUID list
5826 addDyldImageToUUIDList();
5827
5828 #if SUPPORT_ACCELERATE_TABLES
5829 bool mainExcutableAlreadyRebased = false;
5830 if ( (sSharedCacheLoadInfo.loadAddress != nullptr) && !dylibsCanOverrideCache() && !sDisableAcceleratorTables && (sSharedCacheLoadInfo.loadAddress->header.accelerateInfoAddr != 0) ) {
5831 struct stat statBuf;
5832 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR "no-dyld2-accelerator-tables", &statBuf) != 0 )
5833 sAllCacheImagesProxy = ImageLoaderMegaDylib::makeImageLoaderMegaDylib(&sSharedCacheLoadInfo.loadAddress->header, sSharedCacheLoadInfo.slide, mainExecutableMH, gLinkContext);
5834 }
5835
5836 reloadAllImages:
5837 #endif
5838
5839 CRSetCrashLogMessage(sLoadingCrashMessage);
5840 // instantiate ImageLoader for main executable
5841 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
5842 gLinkContext.mainExecutable = sMainExecutable;
5843 gLinkContext.mainExecutableCodeSigned = hasCodeSignatureLoadCommand(mainExecutableMH);
5844
5845 #if TARGET_IPHONE_SIMULATOR
5846 // check main executable is not too new for this OS
5847 {
5848 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH, sExecPath) ) {
5849 throwf("program was built for a platform that is not supported by this runtime");
5850 }
5851 uint32_t mainMinOS = sMainExecutable->minOSVersion();
5852
5853 // dyld is always built for the current OS, so we can get the current OS version
5854 // from the load command in dyld itself.
5855 uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion((const mach_header*)&__dso_handle);
5856 if ( mainMinOS > dyldMinOS ) {
5857 #if TARGET_OS_WATCH
5858 throwf("app was built for watchOS %d.%d which is newer than this simulator %d.%d",
5859 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
5860 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
5861 #elif TARGET_OS_TV
5862 throwf("app was built for tvOS %d.%d which is newer than this simulator %d.%d",
5863 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
5864 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
5865 #else
5866 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
5867 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
5868 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
5869 #endif
5870 }
5871 }
5872 #endif
5873
5874
5875 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5876 // <rdar://problem/22805519> be less strict about old mach-o binaries
5877 uint32_t mainSDK = sMainExecutable->sdkVersion();
5878 gLinkContext.strictMachORequired = (mainSDK >= DYLD_MACOSX_VERSION_10_12) || gLinkContext.processUsingLibraryValidation;
5879 #else
5880 // simulators, iOS, tvOS, and watchOS are always strict
5881 gLinkContext.strictMachORequired = true;
5882 #endif
5883
5884 #if SUPPORT_ACCELERATE_TABLES
5885 sAllImages.reserve((sAllCacheImagesProxy != NULL) ? 16 : INITIAL_IMAGE_COUNT);
5886 #else
5887 sAllImages.reserve(INITIAL_IMAGE_COUNT);
5888 #endif
5889
5890 // Now that shared cache is loaded, setup an versioned dylib overrides
5891 #if SUPPORT_VERSIONED_PATHS
5892 checkVersionedPaths();
5893 #endif
5894
5895
5896 // dyld_all_image_infos image list does not contain dyld
5897 // add it as dyldPath field in dyld_all_image_infos
5898 // for simulator, dyld_sim is in image list, need host dyld added
5899 #if TARGET_IPHONE_SIMULATOR
5900 // get path of host dyld from table of syscall vectors in host dyld
5901 void* addressInDyld = gSyscallHelpers;
5902 #else
5903 // get path of dyld itself
5904 void* addressInDyld = (void*)&__dso_handle;
5905 #endif
5906 char dyldPathBuffer[MAXPATHLEN+1];
5907 int len = proc_regionfilename(getpid(), (uint64_t)(long)addressInDyld, dyldPathBuffer, MAXPATHLEN);
5908 if ( len > 0 ) {
5909 dyldPathBuffer[len] = '\0'; // proc_regionfilename() does not zero terminate returned string
5910 if ( strcmp(dyldPathBuffer, gProcessInfo->dyldPath) != 0 )
5911 gProcessInfo->dyldPath = strdup(dyldPathBuffer);
5912 }
5913
5914 // load any inserted libraries
5915 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
5916 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
5917 loadInsertedDylib(*lib);
5918 }
5919 // record count of inserted libraries so that a flat search will look at
5920 // inserted libraries, then main, then others.
5921 sInsertedDylibCount = sAllImages.size()-1;
5922
5923 // link main executable
5924 gLinkContext.linkingMainExecutable = true;
5925 #if SUPPORT_ACCELERATE_TABLES
5926 if ( mainExcutableAlreadyRebased ) {
5927 // previous link() on main executable has already adjusted its internal pointers for ASLR
5928 // work around that by rebasing by inverse amount
5929 sMainExecutable->rebase(gLinkContext, -mainExecutableSlide);
5930 }
5931 #endif
5932 link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
5933 sMainExecutable->setNeverUnloadRecursive();
5934 if ( sMainExecutable->forceFlat() ) {
5935 gLinkContext.bindFlat = true;
5936 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
5937 }
5938
5939 // link any inserted libraries
5940 // do this after linking main executable so that any dylibs pulled in by inserted
5941 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
5942 if ( sInsertedDylibCount > 0 ) {
5943 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
5944 ImageLoader* image = sAllImages[i+1];
5945 link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
5946 image->setNeverUnloadRecursive();
5947 }
5948 // only INSERTED libraries can interpose
5949 // register interposing info after all inserted libraries are bound so chaining works
5950 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
5951 ImageLoader* image = sAllImages[i+1];
5952 image->registerInterposing();
5953 }
5954 }
5955
5956 // <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
5957 for (long i=sInsertedDylibCount+1; i < sAllImages.size(); ++i) {
5958 ImageLoader* image = sAllImages[i];
5959 if ( image->inSharedCache() )
5960 continue;
5961 image->registerInterposing();
5962 }
5963 #if SUPPORT_ACCELERATE_TABLES
5964 if ( (sAllCacheImagesProxy != NULL) && ImageLoader::haveInterposingTuples() ) {
5965 // Accelerator tables cannot be used with implicit interposing, so relaunch with accelerator tables disabled
5966 ImageLoader::clearInterposingTuples();
5967 // unmap all loaded dylibs (but not main executable)
5968 for (long i=1; i < sAllImages.size(); ++i) {
5969 ImageLoader* image = sAllImages[i];
5970 if ( image == sMainExecutable )
5971 continue;
5972 if ( image == sAllCacheImagesProxy )
5973 continue;
5974 image->setCanUnload();
5975 ImageLoader::deleteImage(image);
5976 }
5977 // note: we don't need to worry about inserted images because if DYLD_INSERT_LIBRARIES was set we would not be using the accelerator table
5978 sAllImages.clear();
5979 sImageRoots.clear();
5980 sImageFilesNeedingTermination.clear();
5981 sImageFilesNeedingDOFUnregistration.clear();
5982 sAddImageCallbacks.clear();
5983 sRemoveImageCallbacks.clear();
5984 sDisableAcceleratorTables = true;
5985 sAllCacheImagesProxy = NULL;
5986 sMappedRangesStart = NULL;
5987 mainExcutableAlreadyRebased = true;
5988 gLinkContext.linkingMainExecutable = false;
5989 resetAllImages();
5990 goto reloadAllImages;
5991 }
5992 #endif
5993
5994 // apply interposing to initial set of images
5995 for(int i=0; i < sImageRoots.size(); ++i) {
5996 sImageRoots[i]->applyInterposing(gLinkContext);
5997 }
5998 gLinkContext.linkingMainExecutable = false;
5999
6000 // <rdar://problem/12186933> do weak binding only after all inserted images linked
6001 sMainExecutable->weakBind(gLinkContext);
6002
6003 // If cache has branch island dylibs, tell debugger about them
6004 if ( (sSharedCacheLoadInfo.loadAddress != NULL) && (sSharedCacheLoadInfo.loadAddress->header.mappingOffset >= 0x78) && (sSharedCacheLoadInfo.loadAddress->header.branchPoolsOffset != 0) ) {
6005 uint32_t count = sSharedCacheLoadInfo.loadAddress->header.branchPoolsCount;
6006 dyld_image_info info[count];
6007 const uint64_t* poolAddress = (uint64_t*)((char*)sSharedCacheLoadInfo.loadAddress + sSharedCacheLoadInfo.loadAddress->header.branchPoolsOffset);
6008 // <rdar://problem/20799203> empty branch pools can be in development cache
6009 if ( ((mach_header*)poolAddress)->magic == sMainExecutableMachHeader->magic ) {
6010 for (int poolIndex=0; poolIndex < count; ++poolIndex) {
6011 uint64_t poolAddr = poolAddress[poolIndex] + sSharedCacheLoadInfo.slide;
6012 info[poolIndex].imageLoadAddress = (mach_header*)(long)poolAddr;
6013 info[poolIndex].imageFilePath = "dyld_shared_cache_branch_islands";
6014 info[poolIndex].imageFileModDate = 0;
6015 }
6016 // add to all_images list
6017 addImagesToAllImages(count, info);
6018 // tell gdb about new branch island images
6019 gProcessInfo->notification(dyld_image_adding, count, info);
6020 }
6021 }
6022
6023 CRSetCrashLogMessage("dyld: launch, running initializers");
6024 #if SUPPORT_OLD_CRT_INITIALIZATION
6025 // Old way is to run initializers via a callback from crt1.o
6026 if ( ! gRunInitializersOldWay )
6027 initializeMainExecutable();
6028 #else
6029 // run all initializers
6030 initializeMainExecutable();
6031 #endif
6032
6033 // notify any montoring proccesses that this process is about to enter main()
6034 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN_DYLD2, 0, 0);
6035 notifyMonitoringDyldMain();
6036
6037 // find entry point for main executable
6038 result = (uintptr_t)sMainExecutable->getThreadPC();
6039 if ( result != 0 ) {
6040 // main executable uses LC_MAIN, needs to return to glue in libdyld.dylib
6041 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 9) )
6042 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
6043 else
6044 halt("libdyld.dylib support not present for LC_MAIN");
6045 }
6046 else {
6047 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
6048 result = (uintptr_t)sMainExecutable->getMain();
6049 *startGlue = 0;
6050 }
6051 }
6052 catch(const char* message) {
6053 syncAllImages();
6054 halt(message);
6055 }
6056 catch(...) {
6057 dyld::log("dyld: launch failed\n");
6058 }
6059
6060 CRSetCrashLogMessage(NULL);
6061
6062 if (sSkipMain) {
6063 dyld3::kdebug_trace_dyld_signpost(DBG_DYLD_SIGNPOST_START_MAIN, 0, 0);
6064 result = (uintptr_t)&fake_main;
6065 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
6066 }
6067
6068 return result;
6069 }
6070
6071
6072 } // namespace
6073
6074
6075