dyld-733.6.tar.gz
[apple/dyld.git] / src / dyld2.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 <stdlib.h>
31 #include <dirent.h>
32 #include <pthread.h>
33 #include <libproc.h>
34 #include <sys/param.h>
35 #include <mach/mach_time.h> // mach_absolute_time()
36 #include <mach/mach_init.h>
37 #include <sys/types.h>
38 #include <sys/stat.h>
39 #include <sys/syscall.h>
40 #include <sys/socket.h>
41 #include <sys/un.h>
42 #include <sys/syslog.h>
43 #include <sys/uio.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 <sys/attr.h>
64 #include <sys/fsgetpath.h>
65
66 #if TARGET_OS_SIMULATOR
67 enum {
68 AMFI_DYLD_INPUT_PROC_IN_SIMULATOR = (1 << 0),
69 };
70 enum amfi_dyld_policy_output_flag_set {
71 AMFI_DYLD_OUTPUT_ALLOW_AT_PATH = (1 << 0),
72 AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS = (1 << 1),
73 AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE = (1 << 2),
74 AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS = (1 << 3),
75 AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS = (1 << 4),
76 AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION = (1 << 5),
77 };
78 extern "C" int amfi_check_dyld_policy_self(uint64_t input_flags, uint64_t* output_flags);
79 #else
80 #include <libamfi.h>
81 #endif
82 #include <sandbox.h>
83 #include <sandbox/private.h>
84 #if __has_feature(ptrauth_calls)
85 #include <ptrauth.h>
86 #endif
87
88 extern "C" int __fork();
89
90 #include <array>
91 #include <algorithm>
92 #include <vector>
93
94
95 #include "dyld2.h"
96 #include "ImageLoader.h"
97 #include "ImageLoaderMachO.h"
98 #include "dyldLibSystemInterface.h"
99 #include "dyld_cache_format.h"
100 #include "dyld_process_info_internal.h"
101
102 #if SUPPORT_ACCELERATE_TABLES
103 #include "ImageLoaderMegaDylib.h"
104 #endif
105
106 #if TARGET_OS_SIMULATOR
107 extern "C" void* gSyscallHelpers;
108 #else
109 #include "dyldSyscallInterface.h"
110 #endif
111
112 #include "Closure.h"
113 #include "libdyldEntryVector.h"
114 #include "MachOLoaded.h"
115 #include "Loading.h"
116 #include "DyldSharedCache.h"
117 #include "SharedCacheRuntime.h"
118 #include "StringUtils.h"
119 #include "Tracing.h"
120 #include "ClosureBuilder.h"
121 #include "ClosureFileSystemPhysical.h"
122 #include "FileUtils.h"
123 #include "BootArgs.h"
124
125 #ifndef MH_HAS_OBJC
126 #define MH_HAS_OBJC 0x40000000
127 #endif
128
129 // not libc header for send() syscall interface
130 extern "C" ssize_t __sendto(int, const void *, size_t, int, const struct sockaddr *, socklen_t);
131
132
133 // ARM and x86_64 are the only architecture that use cpu-sub-types
134 #define CPU_SUBTYPES_SUPPORTED ((__arm__ || __arm64__ || __x86_64__) && !TARGET_OS_SIMULATOR)
135
136 #if __LP64__
137 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
138 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT
139 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO
140 #define macho_segment_command segment_command_64
141 #define macho_section section_64
142 #else
143 #define LC_SEGMENT_COMMAND LC_SEGMENT
144 #define LC_SEGMENT_COMMAND_WRONG LC_SEGMENT_64
145 #define LC_ENCRYPT_COMMAND LC_ENCRYPTION_INFO_64
146 #define macho_segment_command segment_command
147 #define macho_section section
148 #endif
149
150
151
152 #define CPU_TYPE_MASK 0x00FFFFFF /* complement of CPU_ARCH_MASK */
153
154
155 /* implemented in dyld_gdb.cpp */
156 extern void resetAllImages();
157 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
158 extern void removeImageFromAllImages(const mach_header* mh);
159 extern void addNonSharedCacheImageUUID(const dyld_uuid_info& info);
160 extern const char* notifyGDB(enum dyld_image_states state, uint32_t infoCount, const dyld_image_info info[]);
161 extern size_t allImagesCount();
162
163 // magic so CrashReporter logs message
164 extern "C" {
165 char error_string[1024];
166 }
167
168 // magic linker symbol for start of dyld binary
169 extern "C" const macho_header __dso_handle;
170
171
172 //
173 // The file contains the core of dyld used to get a process to main().
174 // The API's that dyld supports are implemented in dyldAPIs.cpp.
175 //
176 //
177 //
178 //
179 //
180 namespace dyld {
181 struct RegisteredDOF { const mach_header* mh; int registrationID; };
182 struct DylibOverride { const char* installName; const char* override; };
183 }
184
185
186 VECTOR_NEVER_DESTRUCTED(ImageLoader*);
187 VECTOR_NEVER_DESTRUCTED(dyld::RegisteredDOF);
188 VECTOR_NEVER_DESTRUCTED(dyld::ImageCallback);
189 VECTOR_NEVER_DESTRUCTED(dyld::DylibOverride);
190 VECTOR_NEVER_DESTRUCTED(ImageLoader::DynamicReference);
191
192 VECTOR_NEVER_DESTRUCTED(dyld_image_state_change_handler);
193
194 namespace dyld {
195
196
197 //
198 // state of all environment variables dyld uses
199 //
200 struct EnvironmentVariables {
201 const char* const * DYLD_FRAMEWORK_PATH;
202 const char* const * DYLD_FALLBACK_FRAMEWORK_PATH;
203 const char* const * DYLD_LIBRARY_PATH;
204 const char* const * DYLD_FALLBACK_LIBRARY_PATH;
205 const char* const * DYLD_INSERT_LIBRARIES;
206 const char* const * LD_LIBRARY_PATH; // for unix conformance
207 const char* const * DYLD_VERSIONED_LIBRARY_PATH;
208 const char* const * DYLD_VERSIONED_FRAMEWORK_PATH;
209 bool DYLD_PRINT_LIBRARIES_POST_LAUNCH;
210 bool DYLD_BIND_AT_LAUNCH;
211 bool DYLD_PRINT_STATISTICS;
212 bool DYLD_PRINT_STATISTICS_DETAILS;
213 bool DYLD_PRINT_OPTS;
214 bool DYLD_PRINT_ENV;
215 bool DYLD_DISABLE_DOFS;
216 bool hasOverride;
217 // DYLD_SHARED_CACHE_DIR ==> sSharedCacheOverrideDir
218 // DYLD_ROOT_PATH ==> gLinkContext.rootPaths
219 // DYLD_IMAGE_SUFFIX ==> gLinkContext.imageSuffix
220 // DYLD_PRINT_OPTS ==> gLinkContext.verboseOpts
221 // DYLD_PRINT_ENV ==> gLinkContext.verboseEnv
222 // DYLD_FORCE_FLAT_NAMESPACE ==> gLinkContext.bindFlat
223 // DYLD_PRINT_INITIALIZERS ==> gLinkContext.verboseInit
224 // DYLD_PRINT_SEGMENTS ==> gLinkContext.verboseMapping
225 // DYLD_PRINT_BINDINGS ==> gLinkContext.verboseBind
226 // DYLD_PRINT_WEAK_BINDINGS ==> gLinkContext.verboseWeakBind
227 // DYLD_PRINT_REBASINGS ==> gLinkContext.verboseRebase
228 // DYLD_PRINT_DOFS ==> gLinkContext.verboseDOF
229 // DYLD_PRINT_APIS ==> gLogAPIs
230 // DYLD_IGNORE_PREBINDING ==> gLinkContext.prebindUsage
231 // DYLD_PREBIND_DEBUG ==> gLinkContext.verbosePrebinding
232 // DYLD_NEW_LOCAL_SHARED_REGIONS ==> gLinkContext.sharedRegionMode
233 // DYLD_SHARED_REGION ==> gLinkContext.sharedRegionMode
234 // DYLD_PRINT_WARNINGS ==> gLinkContext.verboseWarnings
235 // DYLD_PRINT_RPATHS ==> gLinkContext.verboseRPaths
236 // DYLD_PRINT_INTERPOSING ==> gLinkContext.verboseInterposing
237 // DYLD_PRINT_LIBRARIES ==> gLinkContext.verboseLoading
238 };
239
240
241
242 typedef std::vector<dyld_image_state_change_handler> StateHandlers;
243
244
245 enum EnvVarMode { envNone, envPrintOnly, envAll };
246
247 // all global state
248 static const char* sExecPath = NULL;
249 static const char* sExecShortName = NULL;
250 static const macho_header* sMainExecutableMachHeader = NULL;
251 static uintptr_t sMainExecutableSlide = 0;
252 #if CPU_SUBTYPES_SUPPORTED
253 static cpu_type_t sHostCPU;
254 static cpu_subtype_t sHostCPUsubtype;
255 #endif
256 static ImageLoaderMachO* sMainExecutable = NULL;
257 static size_t sInsertedDylibCount = 0;
258 static std::vector<ImageLoader*> sAllImages;
259 static std::vector<ImageLoader*> sImageRoots;
260 static std::vector<ImageLoader*> sImageFilesNeedingTermination;
261 static std::vector<RegisteredDOF> sImageFilesNeedingDOFUnregistration;
262 static std::vector<ImageCallback> sAddImageCallbacks;
263 static std::vector<ImageCallback> sRemoveImageCallbacks;
264 static std::vector<LoadImageCallback> sAddLoadImageCallbacks;
265 static std::vector<LoadImageBulkCallback> sAddBulkLoadImageCallbacks;
266 static bool sRemoveImageCallbacksInUse = false;
267 static void* sSingleHandlers[7][3];
268 static void* sBatchHandlers[7][3];
269 static ImageLoader* sLastImageByAddressCache;
270 static EnvironmentVariables sEnv;
271 #if __MAC_OS_X_VERSION_MIN_REQUIRED
272 static const char* sFrameworkFallbackPaths[] = { "$HOME/Library/Frameworks", "/Library/Frameworks", "/Network/Library/Frameworks", "/System/Library/Frameworks", NULL };
273 static const char* sLibraryFallbackPaths[] = { "$HOME/lib", "/usr/local/lib", "/usr/lib", NULL };
274 static const char* sRestrictedFrameworkFallbackPaths[] = { "/System/Library/Frameworks", NULL };
275 static const char* sRestrictedLibraryFallbackPaths[] = { "/usr/lib", NULL };
276 #else
277 static const char* sFrameworkFallbackPaths[] = { "/System/Library/Frameworks", NULL };
278 static const char* sLibraryFallbackPaths[] = { "/usr/local/lib", "/usr/lib", NULL };
279 #endif
280 static UndefinedHandler sUndefinedHandler = NULL;
281 static ImageLoader* sBundleBeingLoaded = NULL; // hack until OFI is reworked
282 static dyld3::SharedCacheLoadInfo sSharedCacheLoadInfo;
283 static const char* sSharedCacheOverrideDir;
284 bool gSharedCacheOverridden = false;
285 ImageLoader::LinkContext gLinkContext;
286 bool gLogAPIs = false;
287 #if SUPPORT_ACCELERATE_TABLES
288 bool gLogAppAPIs = false;
289 #endif
290 const struct LibSystemHelpers* gLibSystemHelpers = NULL;
291 #if SUPPORT_OLD_CRT_INITIALIZATION
292 bool gRunInitializersOldWay = false;
293 #endif
294 static std::vector<DylibOverride> sDylibOverrides;
295 #if !TARGET_OS_SIMULATOR
296 static int sLogSocket = -1;
297 #endif
298 static bool sFrameworksFoundAsDylibs = false;
299 #if __x86_64__ && !TARGET_OS_SIMULATOR
300 static bool sHaswell = false;
301 #endif
302 static std::vector<ImageLoader::DynamicReference> sDynamicReferences;
303 #pragma clang diagnostic push
304 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
305 static OSSpinLock sDynamicReferencesLock = 0;
306 #pragma clang diagnostic pop
307 #if !TARGET_OS_SIMULATOR
308 static bool sLogToFile = false;
309 #endif
310 static char sLoadingCrashMessage[1024] = "dyld: launch, loading dependent libraries";
311 static _dyld_objc_notify_mapped sNotifyObjCMapped;
312 static _dyld_objc_notify_init sNotifyObjCInit;
313 static _dyld_objc_notify_unmapped sNotifyObjCUnmapped;
314
315 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
316 static bool sForceStderr = false;
317 #endif
318
319
320 #if SUPPORT_ACCELERATE_TABLES
321 static ImageLoaderMegaDylib* sAllCacheImagesProxy = NULL;
322 // Note these are now off by default as everything should use dyld3.
323 static bool sDisableAcceleratorTables = true;
324 #endif
325
326 bool gUseDyld3 = false;
327 static bool sSkipMain = false;
328 static void (*sEntryOveride)() = nullptr;
329 static bool sJustBuildClosure = false;
330 static bool sLogClosureFailure = false;
331
332 enum class ClosureMode {
333 // Unset means we haven't provided an env variable or boot-arg to explicitly choose a mode
334 Unset,
335 // On means we set DYLD_USE_CLOSURES=1, or we didn't have DYLD_USE_CLOSURES=0 but did have
336 // -force_dyld3=1 env variable or a customer cache on iOS
337 On,
338 // Off means we set DYLD_USE_CLOSURES=0, or we didn't have DYLD_USE_CLOSURES=1 but did have
339 // -force_dyld2=1 env variable or an internal cache on iOS
340 Off,
341 // PreBuiltOnly means only use a shared cache closure and don't try build a new one
342 PreBuiltOnly
343 };
344
345 static ClosureMode sClosureMode = ClosureMode::Unset;
346 static bool sForceInvalidSharedCacheClosureFormat = false;
347 static uint64_t launchTraceID = 0;
348
349 //
350 // The MappedRanges structure is used for fast address->image lookups.
351 // The table is only updated when the dyld lock is held, so we don't
352 // need to worry about multiple writers. But readers may look at this
353 // data without holding the lock. Therefore, all updates must be done
354 // in an order that will never cause readers to see inconsistent data.
355 // The general rule is that if the image field is non-NULL then
356 // the other fields are valid.
357 //
358 struct MappedRanges
359 {
360 MappedRanges* next;
361 unsigned long count;
362 struct {
363 ImageLoader* image;
364 uintptr_t start;
365 uintptr_t end;
366 } array[1];
367 };
368
369 static MappedRanges* sMappedRangesStart;
370
371 #pragma clang diagnostic push
372 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
373 void addMappedRange(ImageLoader* image, uintptr_t start, uintptr_t end)
374 {
375 //dyld::log("addMappedRange(0x%lX->0x%lX) for %s\n", start, end, image->getShortName());
376 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
377 for (unsigned long i=0; i < p->count; ++i) {
378 if ( p->array[i].image == NULL ) {
379 p->array[i].start = start;
380 p->array[i].end = end;
381 // add image field last with a barrier so that any reader will see consistent records
382 OSMemoryBarrier();
383 p->array[i].image = image;
384 return;
385 }
386 }
387 }
388 // table must be full, chain another
389 #if SUPPORT_ACCELERATE_TABLES
390 unsigned count = (sAllCacheImagesProxy != NULL) ? 16 : 400;
391 #else
392 unsigned count = 400;
393 #endif
394 size_t allocationSize = sizeof(MappedRanges) + (count-1)*3*sizeof(void*);
395 MappedRanges* newRanges = (MappedRanges*)malloc(allocationSize);
396 bzero(newRanges, allocationSize);
397 newRanges->count = count;
398 newRanges->array[0].start = start;
399 newRanges->array[0].end = end;
400 newRanges->array[0].image = image;
401 OSMemoryBarrier();
402 if ( sMappedRangesStart == NULL ) {
403 sMappedRangesStart = newRanges;
404 }
405 else {
406 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
407 if ( p->next == NULL ) {
408 OSMemoryBarrier();
409 p->next = newRanges;
410 break;
411 }
412 }
413 }
414 }
415
416 void removedMappedRanges(ImageLoader* image)
417 {
418 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
419 for (unsigned long i=0; i < p->count; ++i) {
420 if ( p->array[i].image == image ) {
421 // clear with a barrier so that any reader will see consistent records
422 OSMemoryBarrier();
423 p->array[i].image = NULL;
424 }
425 }
426 }
427 }
428 #pragma clang diagnostic pop
429
430 ImageLoader* findMappedRange(uintptr_t target)
431 {
432 for (MappedRanges* p = sMappedRangesStart; p != NULL; p = p->next) {
433 for (unsigned long i=0; i < p->count; ++i) {
434 if ( p->array[i].image != NULL ) {
435 if ( (p->array[i].start <= target) && (target < p->array[i].end) )
436 return p->array[i].image;
437 }
438 }
439 }
440 return NULL;
441 }
442
443
444
445 const char* mkstringf(const char* format, ...)
446 {
447 _SIMPLE_STRING buf = _simple_salloc();
448 if ( buf != NULL ) {
449 va_list list;
450 va_start(list, format);
451 _simple_vsprintf(buf, format, list);
452 va_end(list);
453 const char* t = strdup(_simple_string(buf));
454 _simple_sfree(buf);
455 if ( t != NULL )
456 return t;
457 }
458 return "mkstringf, out of memory error";
459 }
460
461
462 void throwf(const char* format, ...)
463 {
464 _SIMPLE_STRING buf = _simple_salloc();
465 if ( buf != NULL ) {
466 va_list list;
467 va_start(list, format);
468 _simple_vsprintf(buf, format, list);
469 va_end(list);
470 const char* t = strdup(_simple_string(buf));
471 _simple_sfree(buf);
472 if ( t != NULL )
473 throw t;
474 }
475 throw "throwf, out of memory error";
476 }
477
478
479 #if !TARGET_OS_SIMULATOR
480 static int sLogfile = STDERR_FILENO;
481 #endif
482
483 #if !TARGET_OS_SIMULATOR
484 // based on CFUtilities.c: also_do_stderr()
485 static bool useSyslog()
486 {
487 // Use syslog() for processes managed by launchd
488 static bool launchdChecked = false;
489 static bool launchdOwned = false;
490 if ( !launchdChecked && gProcessInfo->libSystemInitialized ) {
491 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 11) ) {
492 // <rdar://problem/23520449> only call isLaunchdOwned() after libSystem is initialized
493 launchdOwned = (*gLibSystemHelpers->isLaunchdOwned)();
494 launchdChecked = true;
495 }
496 }
497 if ( launchdChecked && launchdOwned )
498 return true;
499
500 // If stderr is not available, use syslog()
501 struct stat sb;
502 int result = fstat(STDERR_FILENO, &sb);
503 if ( result < 0 )
504 return true; // file descriptor 2 is closed
505
506 return false;
507 }
508
509
510 static void socket_syslogv(int priority, const char* format, va_list list)
511 {
512 // lazily create socket and connection to syslogd
513 if ( sLogSocket == -1 ) {
514 sLogSocket = ::socket(AF_UNIX, SOCK_DGRAM, 0);
515 if (sLogSocket == -1)
516 return; // cannot log
517 ::fcntl(sLogSocket, F_SETFD, 1);
518
519 struct sockaddr_un addr;
520 addr.sun_family = AF_UNIX;
521 strncpy(addr.sun_path, _PATH_LOG, sizeof(addr.sun_path));
522 if ( ::connect(sLogSocket, (struct sockaddr *)&addr, sizeof(addr)) == -1 ) {
523 ::close(sLogSocket);
524 sLogSocket = -1;
525 return;
526 }
527 }
528
529 // format message to syslogd like: "<priority>Process[pid]: message"
530 _SIMPLE_STRING buf = _simple_salloc();
531 if ( buf == NULL )
532 return;
533 if ( _simple_sprintf(buf, "<%d>%s[%d]: ", LOG_USER|LOG_NOTICE, sExecShortName, getpid()) == 0 ) {
534 if ( _simple_vsprintf(buf, format, list) == 0 ) {
535 const char* p = _simple_string(buf);
536 ::__sendto(sLogSocket, p, strlen(p), 0, NULL, 0);
537 }
538 }
539 _simple_sfree(buf);
540 }
541
542
543
544 void vlog(const char* format, va_list list)
545 {
546 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
547 // <rdar://problem/25965832> log to console when running iOS app from Xcode
548 if ( !sLogToFile && !sForceStderr && useSyslog() )
549 #else
550 if ( !sLogToFile && useSyslog() )
551 #endif
552 socket_syslogv(LOG_ERR, format, list);
553 else {
554 _simple_vdprintf(sLogfile, format, list);
555 }
556 }
557
558 void log(const char* format, ...)
559 {
560 va_list list;
561 va_start(list, format);
562 vlog(format, list);
563 va_end(list);
564 }
565
566
567 void vwarn(const char* format, va_list list)
568 {
569 _simple_dprintf(sLogfile, "dyld: warning, ");
570 _simple_vdprintf(sLogfile, format, list);
571 }
572
573 void warn(const char* format, ...)
574 {
575 va_list list;
576 va_start(list, format);
577 vwarn(format, list);
578 va_end(list);
579 }
580
581 #else
582 extern void vlog(const char* format, va_list list);
583 #endif // !TARGET_OS_SIMULATOR
584
585
586 #pragma clang diagnostic push
587 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
588 // <rdar://problem/8867781> control access to sAllImages through a lock
589 // because global dyld lock is not held during initialization phase of dlopen()
590 // <rdar://problem/16145518> Use OSSpinLockLock to allow yielding
591 static OSSpinLock sAllImagesLock = 0;
592
593 static void allImagesLock()
594 {
595 OSSpinLockLock(&sAllImagesLock);
596 }
597
598 static void allImagesUnlock()
599 {
600 OSSpinLockUnlock(&sAllImagesLock);
601 }
602 #pragma clang diagnostic pop
603
604
605 // utility class to assure files are closed when an exception is thrown
606 class FileOpener {
607 public:
608 FileOpener(const char* path);
609 ~FileOpener();
610 int getFileDescriptor() { return fd; }
611 private:
612 int fd;
613 };
614
615 FileOpener::FileOpener(const char* path)
616 : fd(-1)
617 {
618 fd = my_open(path, O_RDONLY, 0);
619 }
620
621 FileOpener::~FileOpener()
622 {
623 if ( fd != -1 )
624 close(fd);
625 }
626
627
628 static void registerDOFs(const std::vector<ImageLoader::DOFInfo>& dofs)
629 {
630 const size_t dofSectionCount = dofs.size();
631 if ( !sEnv.DYLD_DISABLE_DOFS && (dofSectionCount != 0) ) {
632 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
633 if ( fd < 0 ) {
634 //dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to register dtrace DOF sections\n");
635 }
636 else {
637 // allocate a buffer on the stack for the variable length dof_ioctl_data_t type
638 uint8_t buffer[sizeof(dof_ioctl_data_t) + dofSectionCount*sizeof(dof_helper_t)];
639 dof_ioctl_data_t* ioctlData = (dof_ioctl_data_t*)buffer;
640
641 // fill in buffer with one dof_helper_t per DOF section
642 ioctlData->dofiod_count = dofSectionCount;
643 for (unsigned int i=0; i < dofSectionCount; ++i) {
644 strlcpy(ioctlData->dofiod_helpers[i].dofhp_mod, dofs[i].imageShortName, DTRACE_MODNAMELEN);
645 ioctlData->dofiod_helpers[i].dofhp_dof = (uintptr_t)(dofs[i].dof);
646 ioctlData->dofiod_helpers[i].dofhp_addr = (uintptr_t)(dofs[i].dof);
647 }
648
649 // tell kernel about all DOF sections en mas
650 // pass pointer to ioctlData because ioctl() only copies a fixed size amount of data into kernel
651 user_addr_t val = (user_addr_t)(unsigned long)ioctlData;
652 if ( ioctl(fd, DTRACEHIOC_ADDDOF, &val) != -1 ) {
653 // kernel returns a unique identifier for each section in the dofiod_helpers[].dofhp_dof field.
654 for (unsigned int i=0; i < dofSectionCount; ++i) {
655 RegisteredDOF info;
656 info.mh = dofs[i].imageHeader;
657 info.registrationID = (int)(ioctlData->dofiod_helpers[i].dofhp_dof);
658 sImageFilesNeedingDOFUnregistration.push_back(info);
659 if ( gLinkContext.verboseDOF ) {
660 dyld::log("dyld: registering DOF section %p in %s with dtrace, ID=0x%08X\n",
661 dofs[i].dof, dofs[i].imageShortName, info.registrationID);
662 }
663 }
664 }
665 else {
666 //dyld::log( "dyld: ioctl to register dtrace DOF section failed\n");
667 }
668 close(fd);
669 }
670 }
671 }
672
673 static void unregisterDOF(int registrationID)
674 {
675 int fd = open("/dev/" DTRACEMNR_HELPER, O_RDWR);
676 if ( fd < 0 ) {
677 dyld::warn("can't open /dev/" DTRACEMNR_HELPER " to unregister dtrace DOF section\n");
678 }
679 else {
680 ioctl(fd, DTRACEHIOC_REMOVE, registrationID);
681 close(fd);
682 if ( gLinkContext.verboseInit )
683 dyld::warn("unregistering DOF section ID=0x%08X with dtrace\n", registrationID);
684 }
685 }
686
687
688 //
689 // _dyld_register_func_for_add_image() is implemented as part of the general image state change notification
690 // Returns true if we did call add image callbacks on this image
691 //
692 static bool notifyAddImageCallbacks(ImageLoader* image)
693 {
694 // use guard so that we cannot notify about the same image twice
695 if ( ! image->addFuncNotified() ) {
696 for (std::vector<ImageCallback>::iterator it=sAddImageCallbacks.begin(); it != sAddImageCallbacks.end(); it++) {
697 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)image->machHeader(), (uint64_t)(*it), 0);
698 (*it)(image->machHeader(), image->getSlide());
699 }
700 for (LoadImageCallback func : sAddLoadImageCallbacks) {
701 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)image->machHeader(), (uint64_t)(*func), 0);
702 (*func)(image->machHeader(), image->getPath(), !image->neverUnload());
703 }
704 image->setAddFuncNotified();
705 return true;
706 }
707 return false;
708 }
709
710
711
712 // notify gdb about these new images
713 static const char* updateAllImages(enum dyld_image_states state, uint32_t infoCount, const struct dyld_image_info info[])
714 {
715 // <rdar://problem/8812589> don't add images without paths to all-image-info-list
716 if ( info[0].imageFilePath != NULL )
717 addImagesToAllImages(infoCount, info);
718 return NULL;
719 }
720
721
722 static StateHandlers* stateToHandlers(dyld_image_states state, void* handlersArray[7][3])
723 {
724 switch ( state ) {
725 case dyld_image_state_mapped:
726 return reinterpret_cast<StateHandlers*>(&handlersArray[0]);
727
728 case dyld_image_state_dependents_mapped:
729 return reinterpret_cast<StateHandlers*>(&handlersArray[1]);
730
731 case dyld_image_state_rebased:
732 return reinterpret_cast<StateHandlers*>(&handlersArray[2]);
733
734 case dyld_image_state_bound:
735 return reinterpret_cast<StateHandlers*>(&handlersArray[3]);
736
737 case dyld_image_state_dependents_initialized:
738 return reinterpret_cast<StateHandlers*>(&handlersArray[4]);
739
740 case dyld_image_state_initialized:
741 return reinterpret_cast<StateHandlers*>(&handlersArray[5]);
742
743 case dyld_image_state_terminated:
744 return reinterpret_cast<StateHandlers*>(&handlersArray[6]);
745 }
746 return NULL;
747 }
748
749 #if SUPPORT_ACCELERATE_TABLES
750 static dyld_image_state_change_handler getPreInitNotifyHandler(unsigned index)
751 {
752 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(dyld_image_state_dependents_initialized, sSingleHandlers);
753 if ( index >= handlers->size() )
754 return NULL;
755 return (*handlers)[index];
756 }
757
758 static dyld_image_state_change_handler getBoundBatchHandler(unsigned index)
759 {
760 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(dyld_image_state_bound, sBatchHandlers);
761 if ( index >= handlers->size() )
762 return NULL;
763 return (*handlers)[index];
764 }
765
766 static void notifySingleFromCache(dyld_image_states state, const mach_header* mh, const char* path)
767 {
768 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
769 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
770 if ( handlers != NULL ) {
771 dyld_image_info info;
772 info.imageLoadAddress = mh;
773 info.imageFilePath = path;
774 info.imageFileModDate = 0;
775 for (dyld_image_state_change_handler handler : *handlers) {
776 const char* result = (*handler)(state, 1, &info);
777 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
778 //fprintf(stderr, " image rejected by handler=%p\n", *it);
779 // make copy of thrown string so that later catch clauses can free it
780 const char* str = strdup(result);
781 throw str;
782 }
783 }
784 }
785 if ( (state == dyld_image_state_dependents_initialized) && (sNotifyObjCInit != NULL) && (mh->flags & MH_HAS_OBJC) ) {
786 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)mh, 0, 0);
787 (*sNotifyObjCInit)(path, mh);
788 }
789 }
790 #endif
791
792 #if !TARGET_OS_SIMULATOR
793 static void sendMessage(unsigned portSlot, mach_msg_id_t msgId, mach_msg_size_t sendSize, mach_msg_header_t* buffer, mach_msg_size_t bufferSize) {
794 // Allocate a port to listen on in this monitoring task
795 mach_port_t sendPort = dyld::gProcessInfo->notifyPorts[portSlot];
796 if (sendPort == MACH_PORT_NULL) {
797 return;
798 }
799 mach_port_t replyPort = MACH_PORT_NULL;
800 mach_port_options_t options = { .flags = MPO_CONTEXT_AS_GUARD | MPO_STRICT,
801 .mpl = { 1 }};
802 kern_return_t kr = mach_port_construct(mach_task_self(), &options, (mach_port_context_t)&replyPort, &replyPort);
803 if (kr != KERN_SUCCESS) {
804 return;
805 }
806 // Assemble a message
807 mach_msg_header_t* h = buffer;
808 h->msgh_bits = MACH_MSGH_BITS(MACH_MSG_TYPE_COPY_SEND,MACH_MSG_TYPE_MAKE_SEND_ONCE);
809 h->msgh_id = msgId;
810 h->msgh_local_port = replyPort;
811 h->msgh_remote_port = sendPort;
812 h->msgh_reserved = 0;
813 h->msgh_size = sendSize;
814 kr = mach_msg(h, MACH_SEND_MSG | MACH_RCV_MSG, h->msgh_size, bufferSize, replyPort, 0, MACH_PORT_NULL);
815 mach_msg_destroy(h);
816 if ( kr == MACH_SEND_INVALID_DEST ) {
817 if (OSAtomicCompareAndSwap32(sendPort, 0, (volatile int32_t*)&dyld::gProcessInfo->notifyPorts[portSlot])) {
818 mach_port_deallocate(mach_task_self(), sendPort);
819 }
820 }
821 mach_port_destruct(mach_task_self(), replyPort, 0, (mach_port_context_t)&replyPort);
822 }
823
824 static void notifyMonitoringDyld(bool unloading, unsigned imageCount, const struct mach_header* loadAddresses[],
825 const char* imagePaths[])
826 {
827 dyld3::ScopedTimer(DBG_DYLD_REMOTE_IMAGE_NOTIFIER, 0, 0, 0);
828 for (int slot=0; slot < DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT; ++slot) {
829 if ( dyld::gProcessInfo->notifyPorts[slot] == 0) continue;
830 unsigned entriesSize = imageCount*sizeof(dyld_process_info_image_entry);
831 unsigned pathsSize = 0;
832 for (unsigned j=0; j < imageCount; ++j) {
833 pathsSize += (strlen(imagePaths[j]) + 1);
834 }
835 unsigned totalSize = (sizeof(dyld_process_info_notify_header) + entriesSize + pathsSize + 127) & -128; // align
836 if ( totalSize > DYLD_PROCESS_INFO_NOTIFY_MAX_BUFFER_SIZE ) {
837 // Putting all image paths into one message would make buffer too big.
838 // Instead split into two messages. Recurse as needed until paths fit in buffer.
839 unsigned imageHalfCount = imageCount/2;
840 notifyMonitoringDyld(unloading, imageHalfCount, loadAddresses, imagePaths);
841 notifyMonitoringDyld(unloading, imageCount - imageHalfCount, &loadAddresses[imageHalfCount], &imagePaths[imageHalfCount]);
842 return;
843 }
844 uint8_t buffer[totalSize + MAX_TRAILER_SIZE];
845 dyld_process_info_notify_header* header = (dyld_process_info_notify_header*)buffer;
846 header->version = 1;
847 header->imageCount = imageCount;
848 header->imagesOffset = sizeof(dyld_process_info_notify_header);
849 header->stringsOffset = sizeof(dyld_process_info_notify_header) + entriesSize;
850 header->timestamp = dyld::gProcessInfo->infoArrayChangeTimestamp;
851 dyld_process_info_image_entry* entries = (dyld_process_info_image_entry*)&buffer[header->imagesOffset];
852 char* const pathPoolStart = (char*)&buffer[header->stringsOffset];
853 char* pathPool = pathPoolStart;
854 for (unsigned j=0; j < imageCount; ++j) {
855 strcpy(pathPool, imagePaths[j]);
856 uint32_t len = (uint32_t)strlen(pathPool);
857 bzero(entries->uuid, 16);
858 dyld3::MachOFile* mf = (dyld3::MachOFile*)loadAddresses[j];
859 mf->getUuid(entries->uuid);
860 entries->loadAddress = (uint64_t)loadAddresses[j];
861 entries->pathStringOffset = (uint32_t)(pathPool - pathPoolStart);
862 entries->pathLength = len;
863 pathPool += (len +1);
864 ++entries;
865 }
866 if (unloading) {
867 sendMessage(slot, DYLD_PROCESS_INFO_NOTIFY_UNLOAD_ID, totalSize, (mach_msg_header_t*)buffer, totalSize+MAX_TRAILER_SIZE);
868 } else {
869 sendMessage(slot, DYLD_PROCESS_INFO_NOTIFY_LOAD_ID, totalSize, (mach_msg_header_t*)buffer, totalSize+MAX_TRAILER_SIZE);
870 }
871 }
872 }
873
874 static void notifyMonitoringDyldMain()
875 {
876 dyld3::ScopedTimer(DBG_DYLD_REMOTE_IMAGE_NOTIFIER, 0, 0, 0);
877 for (int slot=0; slot < DYLD_MAX_PROCESS_INFO_NOTIFY_COUNT; ++slot) {
878 if ( dyld::gProcessInfo->notifyPorts[slot] == 0) continue;
879 uint8_t buffer[sizeof(mach_msg_header_t) + MAX_TRAILER_SIZE];
880 sendMessage(slot, DYLD_PROCESS_INFO_NOTIFY_MAIN_ID, sizeof(mach_msg_header_t), (mach_msg_header_t*)buffer, sizeof(mach_msg_header_t) + MAX_TRAILER_SIZE);
881 }
882 }
883 #else
884 extern void notifyMonitoringDyldMain() VIS_HIDDEN;
885 extern void notifyMonitoringDyld(bool unloading, unsigned imageCount, const struct mach_header* loadAddresses[],
886 const char* imagePaths[]) VIS_HIDDEN;
887 #endif
888
889 void notifyKernel(const ImageLoader& image, bool loading) {
890 uint32_t baseCode = loading ? DBG_DYLD_UUID_MAP_A : DBG_DYLD_UUID_UNMAP_A;
891 uuid_t uuid;
892 image.getUUID(uuid);
893 if ( image.inSharedCache() ) {
894 dyld3::kdebug_trace_dyld_image(baseCode, image.getInstallPath(), (const uuid_t *)&uuid, {0}, {{ 0, 0 }}, image.machHeader());
895 } else {
896 fsid_t fsid = {{0, 0}};
897 fsobj_id_t fsobj = {0};
898 ino_t inode = image.getInode();
899 fsobj.fid_objno = (uint32_t)inode;
900 fsobj.fid_generation = (uint32_t)(inode>>32);
901 fsid.val[0] = image.getDevice();
902 dyld3::kdebug_trace_dyld_image(baseCode, image.getPath(), (const uuid_t *)&uuid, fsobj, fsid, image.machHeader());
903 }
904 }
905
906 static void notifySingle(dyld_image_states state, const ImageLoader* image, ImageLoader::InitializerTimingList* timingInfo)
907 {
908 //dyld::log("notifySingle(state=%d, image=%s)\n", state, image->getPath());
909 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
910 if ( handlers != NULL ) {
911 dyld_image_info info;
912 info.imageLoadAddress = image->machHeader();
913 info.imageFilePath = image->getRealPath();
914 info.imageFileModDate = image->lastModified();
915 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
916 const char* result = (*it)(state, 1, &info);
917 if ( (result != NULL) && (state == dyld_image_state_mapped) ) {
918 //fprintf(stderr, " image rejected by handler=%p\n", *it);
919 // make copy of thrown string so that later catch clauses can free it
920 const char* str = strdup(result);
921 throw str;
922 }
923 }
924 }
925 if ( state == dyld_image_state_mapped ) {
926 // <rdar://problem/7008875> Save load addr + UUID for images from outside the shared cache
927 if ( !image->inSharedCache() ) {
928 dyld_uuid_info info;
929 if ( image->getUUID(info.imageUUID) ) {
930 info.imageLoadAddress = image->machHeader();
931 addNonSharedCacheImageUUID(info);
932 }
933 }
934 }
935 if ( (state == dyld_image_state_dependents_initialized) && (sNotifyObjCInit != NULL) && image->notifyObjC() ) {
936 uint64_t t0 = mach_absolute_time();
937 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)image->machHeader(), 0, 0);
938 (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
939 uint64_t t1 = mach_absolute_time();
940 uint64_t t2 = mach_absolute_time();
941 uint64_t timeInObjC = t1-t0;
942 uint64_t emptyTime = (t2-t1)*100;
943 if ( (timeInObjC > emptyTime) && (timingInfo != NULL) ) {
944 timingInfo->addTime(image->getShortName(), timeInObjC);
945 }
946 }
947 // mach message csdlc about dynamically unloaded images
948 if ( image->addFuncNotified() && (state == dyld_image_state_terminated) ) {
949 notifyKernel(*image, false);
950 const struct mach_header* loadAddress[] = { image->machHeader() };
951 const char* loadPath[] = { image->getPath() };
952 notifyMonitoringDyld(true, 1, loadAddress, loadPath);
953 }
954 }
955
956
957 //
958 // Normally, dyld_all_image_infos is only updated in batches after an entire
959 // graph is loaded. But if there is an error loading the initial set of
960 // dylibs needed by the main executable, dyld_all_image_infos is not yet set
961 // up, leading to usually brief crash logs.
962 //
963 // This function manually adds the images loaded so far to dyld::gProcessInfo.
964 // It should only be called before terminating.
965 //
966 void syncAllImages()
967 {
968 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
969 dyld_image_info info;
970 ImageLoader* image = *it;
971 info.imageLoadAddress = image->machHeader();
972 info.imageFilePath = image->getRealPath();
973 info.imageFileModDate = image->lastModified();
974 // add to all_image_infos if not already there
975 bool found = false;
976 int existingCount = dyld::gProcessInfo->infoArrayCount;
977 const dyld_image_info* existing = dyld::gProcessInfo->infoArray;
978 if ( existing != NULL ) {
979 for (int i=0; i < existingCount; ++i) {
980 if ( existing[i].imageLoadAddress == info.imageLoadAddress ) {
981 //dyld::log("not adding %s\n", info.imageFilePath);
982 found = true;
983 break;
984 }
985 }
986 }
987 if ( ! found ) {
988 //dyld::log("adding %s\n", info.imageFilePath);
989 addImagesToAllImages(1, &info);
990 }
991 }
992 }
993
994
995 static int imageSorter(const void* l, const void* r)
996 {
997 const ImageLoader* left = *((ImageLoader**)l);
998 const ImageLoader* right= *((ImageLoader**)r);
999 return left->compare(right);
1000 }
1001
1002 static void notifyBatchPartial(dyld_image_states state, bool orLater, dyld_image_state_change_handler onlyHandler, bool preflightOnly, bool onlyObjCMappedNotification)
1003 {
1004 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
1005 if ( (handlers != NULL) || ((state == dyld_image_state_bound) && (sNotifyObjCMapped != NULL)) ) {
1006 // don't use a vector because it will use malloc/free and we want notifcation to be low cost
1007 allImagesLock();
1008 dyld_image_info infos[allImagesCount()+1];
1009 ImageLoader* images[allImagesCount()+1];
1010 ImageLoader** end = images;
1011 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1012 dyld_image_states imageState = (*it)->getState();
1013 if ( (imageState == state) || (orLater && (imageState > state)) )
1014 *end++ = *it;
1015 }
1016 if ( sBundleBeingLoaded != NULL ) {
1017 dyld_image_states imageState = sBundleBeingLoaded->getState();
1018 if ( (imageState == state) || (orLater && (imageState > state)) )
1019 *end++ = sBundleBeingLoaded;
1020 }
1021 const char* dontLoadReason = NULL;
1022 uint32_t imageCount = (uint32_t)(end-images);
1023 if ( imageCount != 0 ) {
1024 // sort bottom up
1025 qsort(images, imageCount, sizeof(ImageLoader*), &imageSorter);
1026
1027 const mach_header* mhs[imageCount];
1028 const char* paths[imageCount];
1029 uint32_t bulkNotifyImageCount = 0;
1030
1031 // build info array
1032 for (unsigned int i=0; i < imageCount; ++i) {
1033 dyld_image_info* p = &infos[i];
1034 ImageLoader* image = images[i];
1035 //dyld::log(" state=%d, name=%s\n", state, image->getPath());
1036 p->imageLoadAddress = image->machHeader();
1037 p->imageFilePath = image->getRealPath();
1038 p->imageFileModDate = image->lastModified();
1039 // get these registered with the kernel as early as possible
1040 if ( state == dyld_image_state_dependents_mapped)
1041 notifyKernel(*image, true);
1042 // special case for add_image hook
1043 if ( state == dyld_image_state_bound ) {
1044 if ( notifyAddImageCallbacks(image) ) {
1045 // Add this to the list of images to bulk notify
1046 mhs[bulkNotifyImageCount] = infos[i].imageLoadAddress;
1047 paths[bulkNotifyImageCount] = infos[i].imageFilePath;
1048 ++bulkNotifyImageCount;
1049 }
1050 }
1051 }
1052
1053 if ( (state == dyld_image_state_bound) && !sAddBulkLoadImageCallbacks.empty() && (bulkNotifyImageCount != 0) ) {
1054 for (LoadImageBulkCallback func : sAddBulkLoadImageCallbacks) {
1055 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)mhs[0], (uint64_t)func, 0);
1056 (*func)(bulkNotifyImageCount, mhs, paths);
1057 }
1058 }
1059 }
1060 #if SUPPORT_ACCELERATE_TABLES
1061 if ( sAllCacheImagesProxy != NULL ) {
1062 unsigned cacheCount = sAllCacheImagesProxy->appendImagesToNotify(state, orLater, &infos[imageCount]);
1063 // support _dyld_register_func_for_add_image()
1064 if ( state == dyld_image_state_bound ) {
1065 for (ImageCallback callback : sAddImageCallbacks) {
1066 for (unsigned i=0; i < cacheCount; ++i) {
1067 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)infos[imageCount+i].imageLoadAddress, (uint64_t)(*callback), 0);
1068 (*callback)(infos[imageCount+i].imageLoadAddress, sSharedCacheLoadInfo.slide);
1069 }
1070 }
1071 for (LoadImageCallback func : sAddLoadImageCallbacks) {
1072 for (unsigned i=0; i < cacheCount; ++i) {
1073 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)infos[imageCount+i].imageLoadAddress, (uint64_t)(*func), 0);
1074 (*func)(infos[imageCount+i].imageLoadAddress, infos[imageCount+i].imageFilePath, false);
1075 }
1076 }
1077 if ( !sAddBulkLoadImageCallbacks.empty() ) {
1078 const mach_header* bulk_mhs[cacheCount];
1079 const char* bulk_paths[cacheCount];
1080 for (int i=0; i < cacheCount; ++i) {
1081 bulk_mhs[i] = infos[imageCount+i].imageLoadAddress;
1082 bulk_paths[i] = infos[imageCount+i].imageFilePath;
1083 }
1084 for (LoadImageBulkCallback func : sAddBulkLoadImageCallbacks) {
1085 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)bulk_mhs[0], (uint64_t)func, 0);
1086 (*func)(cacheCount, bulk_mhs, bulk_paths);
1087 }
1088 }
1089 }
1090 imageCount += cacheCount;
1091 }
1092 #endif
1093 if ( imageCount != 0 ) {
1094 if ( !onlyObjCMappedNotification ) {
1095 if ( onlyHandler != NULL ) {
1096 const char* result = NULL;
1097 if ( result == NULL ) {
1098 result = (*onlyHandler)(state, imageCount, infos);
1099 }
1100 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
1101 //fprintf(stderr, " images rejected by handler=%p\n", onlyHandler);
1102 // make copy of thrown string so that later catch clauses can free it
1103 dontLoadReason = strdup(result);
1104 }
1105 }
1106 else {
1107 // call each handler with whole array
1108 if ( handlers != NULL ) {
1109 for (std::vector<dyld_image_state_change_handler>::iterator it = handlers->begin(); it != handlers->end(); ++it) {
1110 const char* result = (*it)(state, imageCount, infos);
1111 if ( (result != NULL) && (state == dyld_image_state_dependents_mapped) ) {
1112 //fprintf(stderr, " images rejected by handler=%p\n", *it);
1113 // make copy of thrown string so that later catch clauses can free it
1114 dontLoadReason = strdup(result);
1115 break;
1116 }
1117 }
1118 }
1119 }
1120 }
1121 // tell objc about new images
1122 if ( (onlyHandler == NULL) && ((state == dyld_image_state_bound) || (orLater && (dyld_image_state_bound > state))) && (sNotifyObjCMapped != NULL) ) {
1123 const char* paths[imageCount];
1124 const mach_header* mhs[imageCount];
1125 unsigned objcImageCount = 0;
1126 for (int i=0; i < imageCount; ++i) {
1127 ImageLoader* image = findImageByMachHeader(infos[i].imageLoadAddress);
1128 bool hasObjC = false;
1129 if ( image != NULL ) {
1130 if ( image->objCMappedNotified() )
1131 continue;
1132 hasObjC = image->notifyObjC();
1133 }
1134 #if SUPPORT_ACCELERATE_TABLES
1135 else if ( sAllCacheImagesProxy != NULL ) {
1136 const mach_header* mh;
1137 const char* path;
1138 unsigned index;
1139 if ( sAllCacheImagesProxy->addressInCache(infos[i].imageLoadAddress, &mh, &path, &index) ) {
1140 hasObjC = (mh->flags & MH_HAS_OBJC);
1141 }
1142 }
1143 #endif
1144 if ( hasObjC ) {
1145 paths[objcImageCount] = infos[i].imageFilePath;
1146 mhs[objcImageCount] = infos[i].imageLoadAddress;
1147 ++objcImageCount;
1148 if ( image != NULL )
1149 image->setObjCMappedNotified();
1150 }
1151 }
1152 if ( objcImageCount != 0 ) {
1153 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_MAP, 0, 0, 0);
1154 uint64_t t0 = mach_absolute_time();
1155 (*sNotifyObjCMapped)(objcImageCount, paths, mhs);
1156 uint64_t t1 = mach_absolute_time();
1157 ImageLoader::fgTotalObjCSetupTime += (t1-t0);
1158 }
1159 }
1160 }
1161 allImagesUnlock();
1162 if ( dontLoadReason != NULL )
1163 throw dontLoadReason;
1164 if ( !preflightOnly && (state == dyld_image_state_dependents_mapped) ) {
1165 const struct mach_header* loadAddresses[imageCount];
1166 const char* loadPaths[imageCount];
1167 for(uint32_t i = 0; i<imageCount; ++i) {
1168 loadAddresses[i] = infos[i].imageLoadAddress;
1169 loadPaths[i] = infos[i].imageFilePath;
1170 }
1171 notifyMonitoringDyld(false, imageCount, loadAddresses, loadPaths);
1172 }
1173 }
1174 }
1175
1176 static void notifyBatch(dyld_image_states state, bool preflightOnly)
1177 {
1178 notifyBatchPartial(state, false, NULL, preflightOnly, false);
1179 }
1180
1181 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1182 static
1183 void coresymbolication_load_notifier(void* connection, uint64_t timestamp, const char* path, const struct mach_header* mh)
1184 {
1185 const struct mach_header* loadAddress[] = { mh };
1186 const char* loadPath[] = { path };
1187 notifyMonitoringDyld(false, 1, loadAddress, loadPath);
1188 }
1189
1190 static
1191 void coresymbolication_unload_notifier(void* connection, uint64_t timestamp, const char* path, const struct mach_header* mh)
1192 {
1193 const struct mach_header* loadAddress = { mh };
1194 const char* loadPath = { path };
1195 notifyMonitoringDyld(true, 1, &loadAddress, &loadPath);
1196 }
1197
1198 static
1199 kern_return_t legacy_task_register_dyld_image_infos(task_t task, dyld_kernel_image_info_array_t dyld_images,
1200 mach_msg_type_number_t dyld_imagesCnt)
1201 {
1202 return KERN_SUCCESS;
1203 }
1204
1205 static
1206 kern_return_t legacy_task_unregister_dyld_image_infos(task_t task, dyld_kernel_image_info_array_t dyld_images,
1207 mach_msg_type_number_t dyld_imagesCnt)
1208 {
1209 return KERN_SUCCESS;
1210 }
1211
1212 static
1213 kern_return_t legacy_task_get_dyld_image_infos(task_inspect_t task, dyld_kernel_image_info_array_t *dyld_images,
1214 mach_msg_type_number_t *dyld_imagesCnt)
1215 {
1216 return KERN_SUCCESS;
1217 }
1218
1219 static
1220 kern_return_t legacy_task_register_dyld_shared_cache_image_info(task_t task, dyld_kernel_image_info_t dyld_cache_image,
1221 boolean_t no_cache, boolean_t private_cache)
1222 {
1223 return KERN_SUCCESS;
1224 }
1225
1226 static
1227 kern_return_t legacy_task_register_dyld_set_dyld_state(task_t task, uint8_t dyld_state)
1228 {
1229 return KERN_SUCCESS;
1230 }
1231
1232 static
1233 kern_return_t legacy_task_register_dyld_get_process_state(task_t task, dyld_kernel_process_info_t *dyld_process_state)
1234 {
1235 return KERN_SUCCESS;
1236 }
1237 #endif
1238
1239 // In order for register_func_for_add_image() callbacks to to be called bottom up,
1240 // we need to maintain a list of root images. The main executable is usally the
1241 // first root. Any images dynamically added are also roots (unless already loaded).
1242 // If DYLD_INSERT_LIBRARIES is used, those libraries are first.
1243 static void addRootImage(ImageLoader* image)
1244 {
1245 //dyld::log("addRootImage(%p, %s)\n", image, image->getPath());
1246 // add to list of roots
1247 sImageRoots.push_back(image);
1248 }
1249
1250
1251 static void clearAllDepths()
1252 {
1253 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
1254 (*it)->clearDepth();
1255 }
1256
1257 static void printAllDepths()
1258 {
1259 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++)
1260 dyld::log("%03d %s\n", (*it)->getDepth(), (*it)->getShortName());
1261 }
1262
1263
1264 static unsigned int imageCount()
1265 {
1266 allImagesLock();
1267 unsigned int result = (unsigned int)sAllImages.size();
1268 allImagesUnlock();
1269 return (result);
1270 }
1271
1272
1273 static void setNewProgramVars(const ProgramVars& newVars)
1274 {
1275 // make a copy of the pointers to program variables
1276 gLinkContext.programVars = newVars;
1277
1278 // now set each program global to their initial value
1279 *gLinkContext.programVars.NXArgcPtr = gLinkContext.argc;
1280 *gLinkContext.programVars.NXArgvPtr = gLinkContext.argv;
1281 *gLinkContext.programVars.environPtr = gLinkContext.envp;
1282 *gLinkContext.programVars.__prognamePtr = gLinkContext.progname;
1283 }
1284
1285 #if SUPPORT_OLD_CRT_INITIALIZATION
1286 static void setRunInitialzersOldWay()
1287 {
1288 gRunInitializersOldWay = true;
1289 }
1290 #endif
1291
1292 static bool sandboxBlocked(const char* path, const char* kind)
1293 {
1294 #if TARGET_OS_SIMULATOR
1295 // sandbox calls not yet supported in simulator runtime
1296 return false;
1297 #else
1298 sandbox_filter_type filter = (sandbox_filter_type)(SANDBOX_FILTER_PATH | SANDBOX_CHECK_NO_REPORT);
1299 return ( sandbox_check(getpid(), kind, filter, path) > 0 );
1300 #endif
1301 }
1302
1303 bool sandboxBlockedMmap(const char* path)
1304 {
1305 return sandboxBlocked(path, "file-map-executable");
1306 }
1307
1308 bool sandboxBlockedOpen(const char* path)
1309 {
1310 return sandboxBlocked(path, "file-read-data");
1311 }
1312
1313 bool sandboxBlockedStat(const char* path)
1314 {
1315 return sandboxBlocked(path, "file-read-metadata");
1316 }
1317
1318
1319 static void addDynamicReference(ImageLoader* from, ImageLoader* to) {
1320 // don't add dynamic reference if target is in the shared cache (since it can't be unloaded)
1321 if ( to->inSharedCache() )
1322 return;
1323
1324 // don't add dynamic reference if there already is a static one
1325 if ( from->dependsOn(to) )
1326 return;
1327
1328 #pragma clang diagnostic push
1329 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1330 // don't add if this combination already exists
1331 OSSpinLockLock(&sDynamicReferencesLock);
1332 for (std::vector<ImageLoader::DynamicReference>::iterator it=sDynamicReferences.begin(); it != sDynamicReferences.end(); ++it) {
1333 if ( (it->from == from) && (it->to == to) ) {
1334 OSSpinLockUnlock(&sDynamicReferencesLock);
1335 return;
1336 }
1337 }
1338
1339 //dyld::log("addDynamicReference(%s, %s\n", from->getShortName(), to->getShortName());
1340 ImageLoader::DynamicReference t;
1341 t.from = from;
1342 t.to = to;
1343 sDynamicReferences.push_back(t);
1344 OSSpinLockUnlock(&sDynamicReferencesLock);
1345 #pragma clang diagnostic pop
1346 }
1347
1348 static void addImage(ImageLoader* image)
1349 {
1350 // add to master list
1351 allImagesLock();
1352 sAllImages.push_back(image);
1353 allImagesUnlock();
1354
1355 // update mapped ranges
1356 uintptr_t lastSegStart = 0;
1357 uintptr_t lastSegEnd = 0;
1358 for(unsigned int i=0, e=image->segmentCount(); i < e; ++i) {
1359 if ( image->segUnaccessible(i) )
1360 continue;
1361 uintptr_t start = image->segActualLoadAddress(i);
1362 uintptr_t end = image->segActualEndAddress(i);
1363 if ( start == lastSegEnd ) {
1364 // two segments are contiguous, just record combined segments
1365 lastSegEnd = end;
1366 }
1367 else {
1368 // non-contiguous segments, record last (if any)
1369 if ( lastSegEnd != 0 )
1370 addMappedRange(image, lastSegStart, lastSegEnd);
1371 lastSegStart = start;
1372 lastSegEnd = end;
1373 }
1374 }
1375 if ( lastSegEnd != 0 )
1376 addMappedRange(image, lastSegStart, lastSegEnd);
1377
1378
1379 if ( gLinkContext.verboseLoading || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
1380 const char *imagePath = image->getPath();
1381 uuid_t imageUUID;
1382 if ( image->getUUID(imageUUID) ) {
1383 uuid_string_t imageUUIDStr;
1384 uuid_unparse_upper(imageUUID, imageUUIDStr);
1385 dyld::log("dyld: loaded: <%s> %s\n", imageUUIDStr, imagePath);
1386 }
1387 else {
1388 dyld::log("dyld: loaded: %s\n", imagePath);
1389 }
1390 }
1391
1392 }
1393
1394 //
1395 // Helper for std::remove_if
1396 //
1397 class RefUsesImage {
1398 public:
1399 RefUsesImage(ImageLoader* image) : _image(image) {}
1400 bool operator()(const ImageLoader::DynamicReference& ref) const {
1401 return ( (ref.from == _image) || (ref.to == _image) );
1402 }
1403 private:
1404 ImageLoader* _image;
1405 };
1406
1407
1408
1409 void removeImage(ImageLoader* image)
1410 {
1411 // if has dtrace DOF section, tell dtrace it is going away, then remove from sImageFilesNeedingDOFUnregistration
1412 for (std::vector<RegisteredDOF>::iterator it=sImageFilesNeedingDOFUnregistration.begin(); it != sImageFilesNeedingDOFUnregistration.end(); ) {
1413 if ( it->mh == image->machHeader() ) {
1414 unregisterDOF(it->registrationID);
1415 sImageFilesNeedingDOFUnregistration.erase(it);
1416 // don't increment iterator, the erase caused next element to be copied to where this iterator points
1417 }
1418 else {
1419 ++it;
1420 }
1421 }
1422
1423 // tell all registered remove image handlers about this
1424 // do this before removing image from internal data structures so that the callback can query dyld about the image
1425 if ( image->getState() >= dyld_image_state_bound ) {
1426 sRemoveImageCallbacksInUse = true; // This only runs inside dyld's global lock, so ok to use a global for the in-use flag.
1427 for (std::vector<ImageCallback>::iterator it=sRemoveImageCallbacks.begin(); it != sRemoveImageCallbacks.end(); it++) {
1428 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_REMOVE_IMAGE, (uint64_t)image->machHeader(), (uint64_t)(*it), 0);
1429 (*it)(image->machHeader(), image->getSlide());
1430 }
1431 sRemoveImageCallbacksInUse = false;
1432
1433 if ( sNotifyObjCUnmapped != NULL && image->notifyObjC() )
1434 (*sNotifyObjCUnmapped)(image->getRealPath(), image->machHeader());
1435 }
1436
1437 // notify
1438 notifySingle(dyld_image_state_terminated, image, NULL);
1439
1440 // remove from mapped images table
1441 removedMappedRanges(image);
1442
1443 // remove from master list
1444 allImagesLock();
1445 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
1446 if ( *it == image ) {
1447 sAllImages.erase(it);
1448 break;
1449 }
1450 }
1451 allImagesUnlock();
1452
1453 #pragma clang diagnostic push
1454 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
1455 // remove from sDynamicReferences
1456 OSSpinLockLock(&sDynamicReferencesLock);
1457 sDynamicReferences.erase(std::remove_if(sDynamicReferences.begin(), sDynamicReferences.end(), RefUsesImage(image)), sDynamicReferences.end());
1458 OSSpinLockUnlock(&sDynamicReferencesLock);
1459 #pragma clang diagnostic pop
1460
1461 // flush find-by-address cache (do this after removed from master list, so there is no chance it can come back)
1462 if ( sLastImageByAddressCache == image )
1463 sLastImageByAddressCache = NULL;
1464
1465 // if in root list, pull it out
1466 for (std::vector<ImageLoader*>::iterator it=sImageRoots.begin(); it != sImageRoots.end(); it++) {
1467 if ( *it == image ) {
1468 sImageRoots.erase(it);
1469 break;
1470 }
1471 }
1472
1473 // If this image is the potential canonical definition of any weak defs, then set them to a tombstone value
1474 if ( gLinkContext.weakDefMapInitialized && image->hasCoalescedExports() ) {
1475 Diagnostics diag;
1476 const dyld3::MachOAnalyzer* ma = (const dyld3::MachOAnalyzer*)image->machHeader();
1477 ma->forEachWeakDef(diag, ^(const char *symbolName, uintptr_t imageOffset, bool isFromExportTrie) {
1478 auto it = gLinkContext.weakDefMap.find(symbolName);
1479 assert(it != gLinkContext.weakDefMap.end());
1480 it->second = { nullptr, 0 };
1481 if ( !isFromExportTrie ) {
1482 // The string was already duplicated if we are an export trie
1483 // so only strdup as we are the nlist
1484 size_t hash1 = ImageLoader::HashCString::hash(it->first);
1485 it->first = strdup(it->first);
1486 size_t hash2 = ImageLoader::HashCString::hash(it->first);
1487 assert(hash1 == hash2);
1488 }
1489 });
1490 }
1491
1492 // log if requested
1493 if ( gLinkContext.verboseLoading || (sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH && (sMainExecutable!=NULL) && sMainExecutable->isLinked()) ) {
1494 const char *imagePath = image->getPath();
1495 uuid_t imageUUID;
1496 if ( image->getUUID(imageUUID) ) {
1497 uuid_string_t imageUUIDStr;
1498 uuid_unparse_upper(imageUUID, imageUUIDStr);
1499 dyld::log("dyld: unloaded: <%s> %s\n", imageUUIDStr, imagePath);
1500 }
1501 else {
1502 dyld::log("dyld: unloaded: %s\n", imagePath);
1503 }
1504 }
1505
1506 // tell gdb, new way
1507 removeImageFromAllImages(image->machHeader());
1508 }
1509
1510
1511 void runImageStaticTerminators(ImageLoader* image)
1512 {
1513 // if in termination list, pull it out and run terminator
1514 bool mightBeMore;
1515 do {
1516 mightBeMore = false;
1517 for (std::vector<ImageLoader*>::iterator it=sImageFilesNeedingTermination.begin(); it != sImageFilesNeedingTermination.end(); it++) {
1518 if ( *it == image ) {
1519 sImageFilesNeedingTermination.erase(it);
1520 if (gLogAPIs) dyld::log("dlclose(), running static terminators for %p %s\n", image, image->getShortName());
1521 image->doTermination(gLinkContext);
1522 mightBeMore = true;
1523 break;
1524 }
1525 }
1526 } while ( mightBeMore );
1527 }
1528
1529 static void terminationRecorder(ImageLoader* image)
1530 {
1531 sImageFilesNeedingTermination.push_back(image);
1532 }
1533
1534 const char* getExecutablePath()
1535 {
1536 return sExecPath;
1537 }
1538
1539 static void runAllStaticTerminators(void* extra)
1540 {
1541 try {
1542 const size_t imageCount = sImageFilesNeedingTermination.size();
1543 for(size_t i=imageCount; i > 0; --i){
1544 ImageLoader* image = sImageFilesNeedingTermination[i-1];
1545 image->doTermination(gLinkContext);
1546 }
1547 sImageFilesNeedingTermination.clear();
1548 notifyBatch(dyld_image_state_terminated, false);
1549 }
1550 catch (const char* msg) {
1551 halt(msg);
1552 }
1553 }
1554
1555 void initializeMainExecutable()
1556 {
1557 // record that we've reached this step
1558 gLinkContext.startedInitializingMainExecutable = true;
1559
1560 // run initialzers for any inserted dylibs
1561 ImageLoader::InitializerTimingList initializerTimes[allImagesCount()];
1562 initializerTimes[0].count = 0;
1563 const size_t rootCount = sImageRoots.size();
1564 if ( rootCount > 1 ) {
1565 for(size_t i=1; i < rootCount; ++i) {
1566 sImageRoots[i]->runInitializers(gLinkContext, initializerTimes[0]);
1567 }
1568 }
1569
1570 // run initializers for main executable and everything it brings up
1571 sMainExecutable->runInitializers(gLinkContext, initializerTimes[0]);
1572
1573 // register cxa_atexit() handler to run static terminators in all loaded images when this process exits
1574 if ( gLibSystemHelpers != NULL )
1575 (*gLibSystemHelpers->cxa_atexit)(&runAllStaticTerminators, NULL, NULL);
1576
1577 // dump info if requested
1578 if ( sEnv.DYLD_PRINT_STATISTICS )
1579 ImageLoader::printStatistics((unsigned int)allImagesCount(), initializerTimes[0]);
1580 if ( sEnv.DYLD_PRINT_STATISTICS_DETAILS )
1581 ImageLoaderMachO::printStatisticsDetails((unsigned int)allImagesCount(), initializerTimes[0]);
1582 }
1583
1584 bool mainExecutablePrebound()
1585 {
1586 return sMainExecutable->usablePrebinding(gLinkContext);
1587 }
1588
1589 ImageLoader* mainExecutable()
1590 {
1591 return sMainExecutable;
1592 }
1593
1594
1595
1596
1597 #if SUPPORT_VERSIONED_PATHS
1598
1599 // forward reference
1600 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName);
1601
1602
1603 //
1604 // Examines a dylib file and if its current_version is newer than the installed
1605 // dylib at its install_name, then add the dylib file to sDylibOverrides.
1606 //
1607 static void checkDylibOverride(const char* dylibFile)
1608 {
1609 //dyld::log("checkDylibOverride('%s')\n", dylibFile);
1610 uint32_t altVersion;
1611 char sysInstallName[PATH_MAX];
1612 if ( getDylibVersionAndInstallname(dylibFile, &altVersion, sysInstallName) && (sysInstallName[0] =='/') ) {
1613 //dyld::log("%s has version 0x%08X and install name %s\n", dylibFile, altVersion, sysInstallName);
1614 uint32_t sysVersion;
1615 if ( getDylibVersionAndInstallname(sysInstallName, &sysVersion, NULL) ) {
1616 //dyld::log("%s has version 0x%08X\n", sysInstallName, sysVersion);
1617 if ( altVersion > sysVersion ) {
1618 //dyld::log("override found: %s -> %s\n", sysInstallName, dylibFile);
1619 // see if there already is an override for this dylib
1620 bool entryExists = false;
1621 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
1622 if ( strcmp(it->installName, sysInstallName) == 0 ) {
1623 entryExists = true;
1624 uint32_t prevVersion;
1625 if ( getDylibVersionAndInstallname(it->override, &prevVersion, NULL) ) {
1626 if ( altVersion > prevVersion ) {
1627 // found an even newer override
1628 free((void*)(it->override));
1629 char resolvedPath[PATH_MAX];
1630 if ( realpath(dylibFile, resolvedPath) != NULL )
1631 it->override = strdup(resolvedPath);
1632 else
1633 it->override = strdup(dylibFile);
1634 break;
1635 }
1636 }
1637 }
1638 }
1639 if ( ! entryExists ) {
1640 DylibOverride entry;
1641 entry.installName = strdup(sysInstallName);
1642 char resolvedPath[PATH_MAX];
1643 if ( realpath(dylibFile, resolvedPath) != NULL )
1644 entry.override = strdup(resolvedPath);
1645 else
1646 entry.override = strdup(dylibFile);
1647 sDylibOverrides.push_back(entry);
1648 //dyld::log("added override: %s -> %s\n", entry.installName, entry.override);
1649 }
1650 }
1651 }
1652 }
1653
1654 }
1655
1656 static void checkDylibOverridesInDir(const char* dirPath)
1657 {
1658 //dyld::log("checkDylibOverridesInDir('%s')\n", dirPath);
1659 char dylibPath[PATH_MAX];
1660 long dirPathLen = strlcpy(dylibPath, dirPath, PATH_MAX-1);
1661 if ( dirPathLen >= PATH_MAX )
1662 return;
1663 DIR* dirp = opendir(dirPath);
1664 if ( dirp != NULL) {
1665 dirent entry;
1666 dirent* entp = NULL;
1667 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1668 if ( entp == NULL )
1669 break;
1670 if ( entp->d_type != DT_REG )
1671 continue;
1672 dylibPath[dirPathLen] = '/';
1673 dylibPath[dirPathLen+1] = '\0';
1674 if ( strlcat(dylibPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1675 continue;
1676 checkDylibOverride(dylibPath);
1677 }
1678 closedir(dirp);
1679 }
1680 }
1681
1682
1683 static void checkFrameworkOverridesInDir(const char* dirPath)
1684 {
1685 //dyld::log("checkFrameworkOverridesInDir('%s')\n", dirPath);
1686 char frameworkPath[PATH_MAX];
1687 long dirPathLen = strlcpy(frameworkPath, dirPath, PATH_MAX-1);
1688 if ( dirPathLen >= PATH_MAX )
1689 return;
1690 DIR* dirp = opendir(dirPath);
1691 if ( dirp != NULL) {
1692 dirent entry;
1693 dirent* entp = NULL;
1694 while ( readdir_r(dirp, &entry, &entp) == 0 ) {
1695 if ( entp == NULL )
1696 break;
1697 if ( entp->d_type != DT_DIR )
1698 continue;
1699 frameworkPath[dirPathLen] = '/';
1700 frameworkPath[dirPathLen+1] = '\0';
1701 int dirNameLen = (int)strlen(entp->d_name);
1702 if ( dirNameLen < 11 )
1703 continue;
1704 if ( strcmp(&entp->d_name[dirNameLen-10], ".framework") != 0 )
1705 continue;
1706 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1707 continue;
1708 if ( strlcat(frameworkPath, "/", PATH_MAX) >= PATH_MAX )
1709 continue;
1710 if ( strlcat(frameworkPath, entp->d_name, PATH_MAX) >= PATH_MAX )
1711 continue;
1712 frameworkPath[strlen(frameworkPath)-10] = '\0';
1713 checkDylibOverride(frameworkPath);
1714 }
1715 closedir(dirp);
1716 }
1717 }
1718 #endif // SUPPORT_VERSIONED_PATHS
1719
1720
1721 //
1722 // Turns a colon separated list of strings into a NULL terminated array
1723 // of string pointers. If mainExecutableDir param is not NULL,
1724 // substitutes @loader_path with main executable's dir.
1725 //
1726 static const char** parseColonList(const char* list, const char* mainExecutableDir)
1727 {
1728 static const char* sEmptyList[] = { NULL };
1729
1730 if ( list[0] == '\0' )
1731 return sEmptyList;
1732
1733 int colonCount = 0;
1734 for(const char* s=list; *s != '\0'; ++s) {
1735 if (*s == ':')
1736 ++colonCount;
1737 }
1738
1739 int index = 0;
1740 const char* start = list;
1741 char** result = new char*[colonCount+2];
1742 for(const char* s=list; *s != '\0'; ++s) {
1743 if (*s == ':') {
1744 size_t len = s-start;
1745 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1746 if ( !gLinkContext.allowAtPaths ) {
1747 dyld::log("dyld: warning: @loader_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1748 continue;
1749 }
1750 size_t mainExecDirLen = strlen(mainExecutableDir);
1751 char* str = new char[mainExecDirLen+len+1];
1752 strcpy(str, mainExecutableDir);
1753 strlcat(str, &start[13], mainExecDirLen+len+1);
1754 str[mainExecDirLen+len-13] = '\0';
1755 start = &s[1];
1756 result[index++] = str;
1757 }
1758 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1759 if ( !gLinkContext.allowAtPaths ) {
1760 dyld::log("dyld: warning: @executable_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1761 continue;
1762 }
1763 size_t mainExecDirLen = strlen(mainExecutableDir);
1764 char* str = new char[mainExecDirLen+len+1];
1765 strcpy(str, mainExecutableDir);
1766 strlcat(str, &start[17], mainExecDirLen+len+1);
1767 str[mainExecDirLen+len-17] = '\0';
1768 start = &s[1];
1769 result[index++] = str;
1770 }
1771 else {
1772 char* str = new char[len+1];
1773 strncpy(str, start, len);
1774 str[len] = '\0';
1775 start = &s[1];
1776 result[index++] = str;
1777 }
1778 }
1779 }
1780 size_t len = strlen(start);
1781 if ( (mainExecutableDir != NULL) && (strncmp(start, "@loader_path/", 13) == 0) ) {
1782 if ( !gLinkContext.allowAtPaths ) {
1783 dyld::log("dyld: warning: @loader_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1784 }
1785 else
1786 {
1787 size_t mainExecDirLen = strlen(mainExecutableDir);
1788 char* str = new char[mainExecDirLen+len+1];
1789 strcpy(str, mainExecutableDir);
1790 strlcat(str, &start[13], mainExecDirLen+len+1);
1791 str[mainExecDirLen+len-13] = '\0';
1792 result[index++] = str;
1793 }
1794 }
1795 else if ( (mainExecutableDir != NULL) && (strncmp(start, "@executable_path/", 17) == 0) ) {
1796 if ( !gLinkContext.allowAtPaths ) {
1797 dyld::log("dyld: warning: @executable_path/ ignored because of amfi policy (Codesign main executable with Library Validation to allow @ paths)\n");
1798 }
1799 else
1800 {
1801 size_t mainExecDirLen = strlen(mainExecutableDir);
1802 char* str = new char[mainExecDirLen+len+1];
1803 strcpy(str, mainExecutableDir);
1804 strlcat(str, &start[17], mainExecDirLen+len+1);
1805 str[mainExecDirLen+len-17] = '\0';
1806 result[index++] = str;
1807 }
1808 }
1809 else {
1810 char* str = new char[len+1];
1811 strcpy(str, start);
1812 result[index++] = str;
1813 }
1814 result[index] = NULL;
1815
1816 //dyld::log("parseColonList(%s)\n", list);
1817 //for(int i=0; result[i] != NULL; ++i)
1818 // dyld::log(" %s\n", result[i]);
1819 return (const char**)result;
1820 }
1821
1822 static void appendParsedColonList(const char* list, const char* mainExecutableDir, const char* const ** storage)
1823 {
1824 const char** newlist = parseColonList(list, mainExecutableDir);
1825 if ( *storage == NULL ) {
1826 // first time, just set
1827 *storage = newlist;
1828 }
1829 else {
1830 // need to append to existing list
1831 const char* const* existing = *storage;
1832 int count = 0;
1833 for(int i=0; existing[i] != NULL; ++i)
1834 ++count;
1835 for(int i=0; newlist[i] != NULL; ++i)
1836 ++count;
1837 const char** combinedList = new const char*[count+2];
1838 int index = 0;
1839 for(int i=0; existing[i] != NULL; ++i)
1840 combinedList[index++] = existing[i];
1841 for(int i=0; newlist[i] != NULL; ++i)
1842 combinedList[index++] = newlist[i];
1843 combinedList[index] = NULL;
1844 delete[] newlist; // free array, note: strings in newList may be leaked
1845 *storage = combinedList;
1846 }
1847 }
1848
1849 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1850 static void paths_expand_roots(const char **paths, const char *key, const char *val)
1851 {
1852 // assert(val != NULL);
1853 // assert(paths != NULL);
1854 if(NULL != key) {
1855 size_t keyLen = strlen(key);
1856 for(int i=0; paths[i] != NULL; ++i) {
1857 if ( strncmp(paths[i], key, keyLen) == 0 ) {
1858 char* newPath = new char[strlen(val) + (strlen(paths[i]) - keyLen) + 1];
1859 strcpy(newPath, val);
1860 strcat(newPath, &paths[i][keyLen]);
1861 paths[i] = newPath;
1862 }
1863 }
1864 }
1865 return;
1866 }
1867
1868 static void removePathWithPrefix(const char* paths[], const char* prefix)
1869 {
1870 size_t prefixLen = strlen(prefix);
1871 int skip = 0;
1872 int i;
1873 for(i = 0; paths[i] != NULL; ++i) {
1874 if ( strncmp(paths[i], prefix, prefixLen) == 0 )
1875 ++skip;
1876 else
1877 paths[i-skip] = paths[i];
1878 }
1879 paths[i-skip] = NULL;
1880 }
1881 #endif
1882
1883
1884 #if 0
1885 static void paths_dump(const char **paths)
1886 {
1887 // assert(paths != NULL);
1888 const char **strs = paths;
1889 while(*strs != NULL)
1890 {
1891 dyld::log("\"%s\"\n", *strs);
1892 strs++;
1893 }
1894 return;
1895 }
1896 #endif
1897
1898
1899
1900 static void printOptions(const char* argv[])
1901 {
1902 uint32_t i = 0;
1903 while ( NULL != argv[i] ) {
1904 dyld::log("opt[%i] = \"%s\"\n", i, argv[i]);
1905 i++;
1906 }
1907 }
1908
1909 static void printEnvironmentVariables(const char* envp[])
1910 {
1911 while ( NULL != *envp ) {
1912 dyld::log("%s\n", *envp);
1913 envp++;
1914 }
1915 }
1916
1917 void processDyldEnvironmentVariable(const char* key, const char* value, const char* mainExecutableDir)
1918 {
1919 if ( strcmp(key, "DYLD_FRAMEWORK_PATH") == 0 ) {
1920 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FRAMEWORK_PATH);
1921 sEnv.hasOverride = true;
1922 }
1923 else if ( strcmp(key, "DYLD_FALLBACK_FRAMEWORK_PATH") == 0 ) {
1924 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_FRAMEWORK_PATH);
1925 sEnv.hasOverride = true;
1926 }
1927 else if ( strcmp(key, "DYLD_LIBRARY_PATH") == 0 ) {
1928 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_LIBRARY_PATH);
1929 sEnv.hasOverride = true;
1930 }
1931 else if ( strcmp(key, "DYLD_FALLBACK_LIBRARY_PATH") == 0 ) {
1932 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_FALLBACK_LIBRARY_PATH);
1933 sEnv.hasOverride = true;
1934 }
1935 #if SUPPORT_ROOT_PATH
1936 else if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) ) {
1937 if ( strcmp(value, "/") != 0 ) {
1938 gLinkContext.rootPaths = parseColonList(value, mainExecutableDir);
1939 for (int i=0; gLinkContext.rootPaths[i] != NULL; ++i) {
1940 if ( gLinkContext.rootPaths[i][0] != '/' ) {
1941 dyld::warn("DYLD_ROOT_PATH not used because it contains a non-absolute path\n");
1942 gLinkContext.rootPaths = NULL;
1943 break;
1944 }
1945 }
1946 }
1947 sEnv.hasOverride = true;
1948 }
1949 #endif
1950 else if ( strcmp(key, "DYLD_IMAGE_SUFFIX") == 0 ) {
1951 gLinkContext.imageSuffix = parseColonList(value, NULL);
1952 sEnv.hasOverride = true;
1953 }
1954 else if ( strcmp(key, "DYLD_INSERT_LIBRARIES") == 0 ) {
1955 sEnv.DYLD_INSERT_LIBRARIES = parseColonList(value, NULL);
1956 #if SUPPORT_ACCELERATE_TABLES
1957 sDisableAcceleratorTables = true;
1958 #endif
1959 sEnv.hasOverride = true;
1960 }
1961 else if ( strcmp(key, "DYLD_PRINT_OPTS") == 0 ) {
1962 sEnv.DYLD_PRINT_OPTS = true;
1963 }
1964 else if ( strcmp(key, "DYLD_PRINT_ENV") == 0 ) {
1965 sEnv.DYLD_PRINT_ENV = true;
1966 }
1967 else if ( strcmp(key, "DYLD_DISABLE_DOFS") == 0 ) {
1968 sEnv.DYLD_DISABLE_DOFS = true;
1969 }
1970 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES") == 0 ) {
1971 gLinkContext.verboseLoading = true;
1972 }
1973 else if ( strcmp(key, "DYLD_PRINT_LIBRARIES_POST_LAUNCH") == 0 ) {
1974 sEnv.DYLD_PRINT_LIBRARIES_POST_LAUNCH = true;
1975 }
1976 else if ( strcmp(key, "DYLD_BIND_AT_LAUNCH") == 0 ) {
1977 sEnv.DYLD_BIND_AT_LAUNCH = true;
1978 }
1979 else if ( strcmp(key, "DYLD_FORCE_FLAT_NAMESPACE") == 0 ) {
1980 gLinkContext.bindFlat = true;
1981 }
1982 else if ( strcmp(key, "DYLD_NEW_LOCAL_SHARED_REGIONS") == 0 ) {
1983 // ignore, no longer relevant but some scripts still set it
1984 }
1985 else if ( strcmp(key, "DYLD_NO_FIX_PREBINDING") == 0 ) {
1986 }
1987 else if ( strcmp(key, "DYLD_PREBIND_DEBUG") == 0 ) {
1988 gLinkContext.verbosePrebinding = true;
1989 }
1990 else if ( strcmp(key, "DYLD_PRINT_INITIALIZERS") == 0 ) {
1991 gLinkContext.verboseInit = true;
1992 }
1993 else if ( strcmp(key, "DYLD_PRINT_DOFS") == 0 ) {
1994 gLinkContext.verboseDOF = true;
1995 }
1996 else if ( strcmp(key, "DYLD_PRINT_STATISTICS") == 0 ) {
1997 sEnv.DYLD_PRINT_STATISTICS = true;
1998 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
1999 // <rdar://problem/26614838> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
2000 sForceStderr = true;
2001 #endif
2002 }
2003 else if ( strcmp(key, "DYLD_PRINT_TO_STDERR") == 0 ) {
2004 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
2005 // <rdar://problem/26633440> DYLD_PRINT_STATISTICS no longer logs to xcode console for device apps
2006 sForceStderr = true;
2007 #endif
2008 }
2009 else if ( strcmp(key, "DYLD_PRINT_STATISTICS_DETAILS") == 0 ) {
2010 sEnv.DYLD_PRINT_STATISTICS_DETAILS = true;
2011 }
2012 else if ( strcmp(key, "DYLD_PRINT_SEGMENTS") == 0 ) {
2013 gLinkContext.verboseMapping = true;
2014 }
2015 else if ( strcmp(key, "DYLD_PRINT_BINDINGS") == 0 ) {
2016 gLinkContext.verboseBind = true;
2017 }
2018 else if ( strcmp(key, "DYLD_PRINT_WEAK_BINDINGS") == 0 ) {
2019 gLinkContext.verboseWeakBind = true;
2020 }
2021 else if ( strcmp(key, "DYLD_PRINT_REBASINGS") == 0 ) {
2022 gLinkContext.verboseRebase = true;
2023 }
2024 else if ( strcmp(key, "DYLD_PRINT_APIS") == 0 ) {
2025 gLogAPIs = true;
2026 }
2027 #if SUPPORT_ACCELERATE_TABLES
2028 else if ( strcmp(key, "DYLD_PRINT_APIS_APP") == 0 ) {
2029 gLogAppAPIs = true;
2030 }
2031 #endif
2032 else if ( strcmp(key, "DYLD_PRINT_WARNINGS") == 0 ) {
2033 gLinkContext.verboseWarnings = true;
2034 }
2035 else if ( strcmp(key, "DYLD_PRINT_RPATHS") == 0 ) {
2036 gLinkContext.verboseRPaths = true;
2037 }
2038 else if ( strcmp(key, "DYLD_PRINT_INTERPOSING") == 0 ) {
2039 gLinkContext.verboseInterposing = true;
2040 }
2041 else if ( strcmp(key, "DYLD_PRINT_CODE_SIGNATURES") == 0 ) {
2042 gLinkContext.verboseCodeSignatures = true;
2043 }
2044 else if ( (strcmp(key, "DYLD_SHARED_REGION") == 0) && gLinkContext.allowEnvVarsSharedCache ) {
2045 if ( strcmp(value, "private") == 0 ) {
2046 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
2047 }
2048 else if ( strcmp(value, "avoid") == 0 ) {
2049 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2050 }
2051 else if ( strcmp(value, "use") == 0 ) {
2052 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
2053 }
2054 else if ( value[0] == '\0' ) {
2055 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
2056 }
2057 else {
2058 dyld::warn("unknown option to DYLD_SHARED_REGION. Valid options are: use, private, avoid\n");
2059 }
2060 }
2061 else if ( (strcmp(key, "DYLD_SHARED_CACHE_DIR") == 0) && gLinkContext.allowEnvVarsSharedCache ) {
2062 sSharedCacheOverrideDir = value;
2063 }
2064 else if ( strcmp(key, "DYLD_USE_CLOSURES") == 0 ) {
2065 // Handled elsewhere
2066 }
2067 else if ( strcmp(key, "DYLD_FORCE_INVALID_CACHE_CLOSURES") == 0 ) {
2068 if ( dyld3::internalInstall() ) {
2069 sForceInvalidSharedCacheClosureFormat = true;
2070 }
2071 }
2072 else if ( strcmp(key, "DYLD_IGNORE_PREBINDING") == 0 ) {
2073 if ( strcmp(value, "all") == 0 ) {
2074 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
2075 }
2076 else if ( strcmp(value, "app") == 0 ) {
2077 gLinkContext.prebindUsage = ImageLoader::kUseAllButAppPredbinding;
2078 }
2079 else if ( strcmp(value, "nonsplit") == 0 ) {
2080 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
2081 }
2082 else if ( value[0] == '\0' ) {
2083 gLinkContext.prebindUsage = ImageLoader::kUseSplitSegPrebinding;
2084 }
2085 else {
2086 dyld::warn("unknown option to DYLD_IGNORE_PREBINDING. Valid options are: all, app, nonsplit\n");
2087 }
2088 }
2089 #if SUPPORT_VERSIONED_PATHS
2090 else if ( strcmp(key, "DYLD_VERSIONED_LIBRARY_PATH") == 0 ) {
2091 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_LIBRARY_PATH);
2092 #if SUPPORT_ACCELERATE_TABLES
2093 sDisableAcceleratorTables = true;
2094 #endif
2095 sEnv.hasOverride = true;
2096 }
2097 else if ( strcmp(key, "DYLD_VERSIONED_FRAMEWORK_PATH") == 0 ) {
2098 appendParsedColonList(value, mainExecutableDir, &sEnv.DYLD_VERSIONED_FRAMEWORK_PATH);
2099 #if SUPPORT_ACCELERATE_TABLES
2100 sDisableAcceleratorTables = true;
2101 #endif
2102 sEnv.hasOverride = true;
2103 }
2104 #endif
2105 #if !TARGET_OS_SIMULATOR
2106 else if ( (strcmp(key, "DYLD_PRINT_TO_FILE") == 0) && (mainExecutableDir == NULL) && gLinkContext.allowEnvVarsSharedCache ) {
2107 int fd = open(value, O_WRONLY | O_CREAT | O_APPEND, 0644);
2108 if ( fd != -1 ) {
2109 sLogfile = fd;
2110 sLogToFile = true;
2111 }
2112 else {
2113 dyld::log("dyld: could not open DYLD_PRINT_TO_FILE='%s', errno=%d\n", value, errno);
2114 }
2115 }
2116 else if ( (strcmp(key, "DYLD_SKIP_MAIN") == 0)) {
2117 if ( dyld3::internalInstall() )
2118 sSkipMain = true;
2119 }
2120 else if ( (strcmp(key, "DYLD_JUST_BUILD_CLOSURE") == 0) ) {
2121 // handled elsewhere
2122 }
2123 #endif
2124 else if (strcmp(key, "DYLD_FORCE_PLATFORM") == 0) {
2125 // handled elsewhere
2126 }
2127 else if (strcmp(key, "DYLD_AMFI_FAKE") == 0) {
2128 // handled elsewhere
2129 }
2130 else {
2131 dyld::warn("unknown environment variable: %s\n", key);
2132 }
2133 }
2134
2135
2136 #if SUPPORT_LC_DYLD_ENVIRONMENT
2137 static void checkLoadCommandEnvironmentVariables()
2138 {
2139 // <rdar://problem/8440934> Support augmenting dyld environment variables in load commands
2140 const uint32_t cmd_count = sMainExecutableMachHeader->ncmds;
2141 const struct load_command* const cmds = (struct load_command*)(((char*)sMainExecutableMachHeader)+sizeof(macho_header));
2142 const struct load_command* cmd = cmds;
2143 for (uint32_t i = 0; i < cmd_count; ++i) {
2144 switch (cmd->cmd) {
2145 case LC_DYLD_ENVIRONMENT:
2146 {
2147 const struct dylinker_command* envcmd = (struct dylinker_command*)cmd;
2148 const char* keyEqualsValue = (char*)envcmd + envcmd->name.offset;
2149 char mainExecutableDir[strlen(sExecPath)+2];
2150 strcpy(mainExecutableDir, sExecPath);
2151 char* lastSlash = strrchr(mainExecutableDir, '/');
2152 if ( lastSlash != NULL)
2153 lastSlash[1] = '\0';
2154 // only process variables that start with DYLD_ and end in _PATH
2155 if ( (strncmp(keyEqualsValue, "DYLD_", 5) == 0) ) {
2156 const char* equals = strchr(keyEqualsValue, '=');
2157 if ( equals != NULL ) {
2158 if ( strncmp(&equals[-5], "_PATH", 5) == 0 ) {
2159 const char* value = &equals[1];
2160 const size_t keyLen = equals-keyEqualsValue;
2161 // <rdar://problem/22799635> don't let malformed load command overflow stack
2162 if ( keyLen < 40 ) {
2163 char key[keyLen+1];
2164 strncpy(key, keyEqualsValue, keyLen);
2165 key[keyLen] = '\0';
2166 //dyld::log("processing: %s\n", keyEqualsValue);
2167 //dyld::log("mainExecutableDir: %s\n", mainExecutableDir);
2168 #if SUPPORT_ROOT_PATH
2169 if ( (strcmp(key, "DYLD_ROOT_PATH") == 0) || (strcmp(key, "DYLD_PATHS_ROOT") == 0) )
2170 continue;
2171 #endif
2172 processDyldEnvironmentVariable(key, value, mainExecutableDir);
2173 }
2174 }
2175 }
2176 }
2177 }
2178 break;
2179 }
2180 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2181 }
2182 }
2183 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2184
2185
2186 static bool hasCodeSignatureLoadCommand(const macho_header* mh)
2187 {
2188 const uint32_t cmd_count = mh->ncmds;
2189 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2190 const struct load_command* cmd = cmds;
2191 for (uint32_t i = 0; i < cmd_count; ++i) {
2192 if (cmd->cmd == LC_CODE_SIGNATURE)
2193 return true;
2194 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2195 }
2196 return false;
2197 }
2198
2199
2200 #if SUPPORT_VERSIONED_PATHS
2201 static void checkVersionedPaths()
2202 {
2203 // search DYLD_VERSIONED_LIBRARY_PATH directories for dylibs and check if they are newer
2204 if ( sEnv.DYLD_VERSIONED_LIBRARY_PATH != NULL ) {
2205 for(const char* const* lp = sEnv.DYLD_VERSIONED_LIBRARY_PATH; *lp != NULL; ++lp) {
2206 checkDylibOverridesInDir(*lp);
2207 }
2208 }
2209
2210 // search DYLD_VERSIONED_FRAMEWORK_PATH directories for dylibs and check if they are newer
2211 if ( sEnv.DYLD_VERSIONED_FRAMEWORK_PATH != NULL ) {
2212 for(const char* const* fp = sEnv.DYLD_VERSIONED_FRAMEWORK_PATH; *fp != NULL; ++fp) {
2213 checkFrameworkOverridesInDir(*fp);
2214 }
2215 }
2216 }
2217 #endif
2218
2219
2220 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2221 //
2222 // For security, setuid programs ignore DYLD_* environment variables.
2223 // Additionally, the DYLD_* enviroment variables are removed
2224 // from the environment, so that any child processes don't see them.
2225 //
2226 static void pruneEnvironmentVariables(const char* envp[], const char*** applep)
2227 {
2228 #if SUPPORT_LC_DYLD_ENVIRONMENT
2229 checkLoadCommandEnvironmentVariables();
2230 #endif
2231
2232 // Are we testing dyld on an internal config?
2233 if ( _simple_getenv(envp, "DYLD_SKIP_MAIN") != NULL ) {
2234 if ( dyld3::internalInstall() )
2235 sSkipMain = true;
2236 }
2237
2238 // delete all DYLD_* and LD_LIBRARY_PATH environment variables
2239 int removedCount = 0;
2240 const char** d = envp;
2241 for(const char** s = envp; *s != NULL; s++) {
2242
2243 if ( (strncmp(*s, "DYLD_", 5) != 0) && (strncmp(*s, "LD_LIBRARY_PATH=", 16) != 0) ) {
2244 *d++ = *s;
2245 }
2246 else {
2247 ++removedCount;
2248 }
2249 }
2250 *d++ = NULL;
2251 // slide apple parameters
2252 if ( removedCount > 0 ) {
2253 *applep = d;
2254 do {
2255 *d = d[removedCount];
2256 } while ( *d++ != NULL );
2257 for(int i=0; i < removedCount; ++i)
2258 *d++ = NULL;
2259 }
2260
2261 // disable framework and library fallback paths for setuid binaries rdar://problem/4589305
2262 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = NULL;
2263 sEnv.DYLD_FALLBACK_LIBRARY_PATH = NULL;
2264
2265 if ( removedCount > 0 )
2266 strlcat(sLoadingCrashMessage, ", ignoring DYLD_* env vars", sizeof(sLoadingCrashMessage));
2267 }
2268 #endif
2269
2270 static void defaultUninitializedFallbackPaths(const char* envp[])
2271 {
2272 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2273 if ( !gLinkContext.allowClassicFallbackPaths ) {
2274 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sRestrictedFrameworkFallbackPaths;
2275 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sRestrictedLibraryFallbackPaths;
2276 return;
2277 }
2278
2279 // default value for DYLD_FALLBACK_FRAMEWORK_PATH, if not set in environment
2280 const char* home = _simple_getenv(envp, "HOME");;
2281 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL ) {
2282 const char** fpaths = sFrameworkFallbackPaths;
2283 if ( home == NULL )
2284 removePathWithPrefix(fpaths, "$HOME");
2285 else
2286 paths_expand_roots(fpaths, "$HOME", home);
2287 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = fpaths;
2288 }
2289
2290 // default value for DYLD_FALLBACK_LIBRARY_PATH, if not set in environment
2291 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL ) {
2292 const char** lpaths = sLibraryFallbackPaths;
2293 if ( home == NULL )
2294 removePathWithPrefix(lpaths, "$HOME");
2295 else
2296 paths_expand_roots(lpaths, "$HOME", home);
2297 sEnv.DYLD_FALLBACK_LIBRARY_PATH = lpaths;
2298 }
2299 #else
2300 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == NULL )
2301 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sFrameworkFallbackPaths;
2302
2303 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == NULL )
2304 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sLibraryFallbackPaths;
2305 #endif
2306 }
2307
2308
2309 static void checkEnvironmentVariables(const char* envp[])
2310 {
2311 if ( !gLinkContext.allowEnvVarsPath && !gLinkContext.allowEnvVarsPrint )
2312 return;
2313 const char** p;
2314 for(p = envp; *p != NULL; p++) {
2315 const char* keyEqualsValue = *p;
2316 if ( strncmp(keyEqualsValue, "DYLD_", 5) == 0 ) {
2317 const char* equals = strchr(keyEqualsValue, '=');
2318 if ( equals != NULL ) {
2319 strlcat(sLoadingCrashMessage, "\n", sizeof(sLoadingCrashMessage));
2320 strlcat(sLoadingCrashMessage, keyEqualsValue, sizeof(sLoadingCrashMessage));
2321 const char* value = &equals[1];
2322 const size_t keyLen = equals-keyEqualsValue;
2323 char key[keyLen+1];
2324 strncpy(key, keyEqualsValue, keyLen);
2325 key[keyLen] = '\0';
2326 if ( (strncmp(key, "DYLD_PRINT_", 11) == 0) && !gLinkContext.allowEnvVarsPrint )
2327 continue;
2328 processDyldEnvironmentVariable(key, value, NULL);
2329 }
2330 }
2331 else if ( strncmp(keyEqualsValue, "LD_LIBRARY_PATH=", 16) == 0 ) {
2332 const char* path = &keyEqualsValue[16];
2333 sEnv.LD_LIBRARY_PATH = parseColonList(path, NULL);
2334 }
2335 }
2336
2337 #if SUPPORT_LC_DYLD_ENVIRONMENT
2338 checkLoadCommandEnvironmentVariables();
2339 #endif // SUPPORT_LC_DYLD_ENVIRONMENT
2340
2341 #if SUPPORT_ROOT_PATH
2342 // <rdar://problem/11281064> DYLD_IMAGE_SUFFIX and DYLD_ROOT_PATH cannot be used together
2343 if ( (gLinkContext.imageSuffix != NULL && *gLinkContext.imageSuffix != NULL) && (gLinkContext.rootPaths != NULL) ) {
2344 dyld::warn("Ignoring DYLD_IMAGE_SUFFIX because DYLD_ROOT_PATH is used.\n");
2345 gLinkContext.imageSuffix = NULL; // this leaks allocations from parseColonList
2346 }
2347 #endif
2348 }
2349
2350 #if __x86_64__ && !TARGET_OS_SIMULATOR
2351 static bool isGCProgram(const macho_header* mh, uintptr_t slide)
2352 {
2353 const uint32_t cmd_count = mh->ncmds;
2354 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
2355 const struct load_command* cmd = cmds;
2356 for (uint32_t i = 0; i < cmd_count; ++i) {
2357 switch (cmd->cmd) {
2358 case LC_SEGMENT_COMMAND:
2359 {
2360 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
2361 if (strcmp(seg->segname, "__DATA") == 0) {
2362 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
2363 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
2364 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
2365 if (strncmp(sect->sectname, "__objc_imageinfo", 16) == 0) {
2366 const uint32_t* objcInfo = (uint32_t*)(sect->addr + slide);
2367 return (objcInfo[1] & 6); // 6 = (OBJC_IMAGE_SUPPORTS_GC | OBJC_IMAGE_REQUIRES_GC)
2368 }
2369 }
2370 }
2371 }
2372 break;
2373 }
2374 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
2375 }
2376 return false;
2377 }
2378 #endif
2379
2380 static void getHostInfo(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide)
2381 {
2382 #if CPU_SUBTYPES_SUPPORTED
2383 #if __ARM_ARCH_7K__
2384 sHostCPU = CPU_TYPE_ARM;
2385 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7K;
2386 #elif __ARM_ARCH_7A__
2387 sHostCPU = CPU_TYPE_ARM;
2388 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7;
2389 #elif __ARM_ARCH_6K__
2390 sHostCPU = CPU_TYPE_ARM;
2391 sHostCPUsubtype = CPU_SUBTYPE_ARM_V6;
2392 #elif __ARM_ARCH_7F__
2393 sHostCPU = CPU_TYPE_ARM;
2394 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7F;
2395 #elif __ARM_ARCH_7S__
2396 sHostCPU = CPU_TYPE_ARM;
2397 sHostCPUsubtype = CPU_SUBTYPE_ARM_V7S;
2398 #elif __ARM64_ARCH_8_32__
2399 sHostCPU = CPU_TYPE_ARM64_32;
2400 sHostCPUsubtype = CPU_SUBTYPE_ARM64_32_V8;
2401 #elif __arm64e__
2402 sHostCPU = CPU_TYPE_ARM64;
2403 sHostCPUsubtype = CPU_SUBTYPE_ARM64E;
2404 #elif __arm64__
2405 sHostCPU = CPU_TYPE_ARM64;
2406 sHostCPUsubtype = CPU_SUBTYPE_ARM64_V8;
2407 #else
2408 struct host_basic_info info;
2409 mach_msg_type_number_t count = HOST_BASIC_INFO_COUNT;
2410 mach_port_t hostPort = mach_host_self();
2411 kern_return_t result = host_info(hostPort, HOST_BASIC_INFO, (host_info_t)&info, &count);
2412 if ( result != KERN_SUCCESS )
2413 throw "host_info() failed";
2414 sHostCPU = info.cpu_type;
2415 sHostCPUsubtype = info.cpu_subtype;
2416 mach_port_deallocate(mach_task_self(), hostPort);
2417 #if __x86_64__
2418 // host_info returns CPU_TYPE_I386 even for x86_64. Override that here so that
2419 // we don't need to mask the cpu type later.
2420 sHostCPU = CPU_TYPE_X86_64;
2421 #if !TARGET_OS_SIMULATOR
2422 sHaswell = (sHostCPUsubtype == CPU_SUBTYPE_X86_64_H);
2423 // <rdar://problem/18528074> x86_64h: Fall back to the x86_64 slice if an app requires GC.
2424 if ( sHaswell ) {
2425 if ( isGCProgram(mainExecutableMH, mainExecutableSlide) ) {
2426 // When running a GC program on a haswell machine, don't use and 'h slices
2427 sHostCPUsubtype = CPU_SUBTYPE_X86_64_ALL;
2428 sHaswell = false;
2429 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2430 }
2431 }
2432 #endif
2433 #endif
2434 #endif
2435 #endif
2436 }
2437
2438 static void checkSharedRegionDisable(const dyld3::MachOLoaded* mainExecutableMH, uintptr_t mainExecutableSlide)
2439 {
2440 #if __MAC_OS_X_VERSION_MIN_REQUIRED
2441 // if main executable has segments that overlap the shared region,
2442 // then disable using the shared region
2443 if ( mainExecutableMH->intersectsRange(SHARED_REGION_BASE, SHARED_REGION_SIZE) ) {
2444 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
2445 if ( gLinkContext.verboseMapping )
2446 dyld::warn("disabling shared region because main executable overlaps\n");
2447 }
2448 #if __i386__
2449 if ( !gLinkContext.allowEnvVarsPath ) {
2450 // <rdar://problem/15280847> use private or no shared region for suid processes
2451 gLinkContext.sharedRegionMode = ImageLoader::kUsePrivateSharedRegion;
2452 }
2453 #endif
2454 #endif
2455 // iOS cannot run without shared region
2456 }
2457
2458 bool validImage(const ImageLoader* possibleImage)
2459 {
2460 const size_t imageCount = sAllImages.size();
2461 for(size_t i=0; i < imageCount; ++i) {
2462 if ( possibleImage == sAllImages[i] ) {
2463 return true;
2464 }
2465 }
2466 return false;
2467 }
2468
2469 uint32_t getImageCount()
2470 {
2471 return (uint32_t)sAllImages.size();
2472 }
2473
2474 ImageLoader* getIndexedImage(unsigned int index)
2475 {
2476 if ( index < sAllImages.size() )
2477 return sAllImages[index];
2478 return NULL;
2479 }
2480
2481 ImageLoader* findImageByMachHeader(const struct mach_header* target)
2482 {
2483 return findMappedRange((uintptr_t)target);
2484 }
2485
2486
2487 ImageLoader* findImageContainingAddress(const void* addr)
2488 {
2489 #if SUPPORT_ACCELERATE_TABLES
2490 if ( sAllCacheImagesProxy != NULL ) {
2491 const mach_header* mh;
2492 const char* path;
2493 unsigned index;
2494 if ( sAllCacheImagesProxy->addressInCache(addr, &mh, &path, &index) )
2495 return sAllCacheImagesProxy;
2496 }
2497 #endif
2498 return findMappedRange((uintptr_t)addr);
2499 }
2500
2501
2502 ImageLoader* findImageContainingSymbol(const void* symbol)
2503 {
2504 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
2505 ImageLoader* anImage = *it;
2506 if ( anImage->containsSymbol(symbol) )
2507 return anImage;
2508 }
2509 return NULL;
2510 }
2511
2512
2513
2514 void forEachImageDo( void (*callback)(ImageLoader*, void* userData), void* userData)
2515 {
2516 const size_t imageCount = sAllImages.size();
2517 for(size_t i=0; i < imageCount; ++i) {
2518 ImageLoader* anImage = sAllImages[i];
2519 (*callback)(anImage, userData);
2520 }
2521 }
2522
2523 ImageLoader* findLoadedImage(const struct stat& stat_buf)
2524 {
2525 const size_t imageCount = sAllImages.size();
2526 for(size_t i=0; i < imageCount; ++i){
2527 ImageLoader* anImage = sAllImages[i];
2528 if ( anImage->statMatch(stat_buf) )
2529 return anImage;
2530 }
2531 return NULL;
2532 }
2533
2534 // based on ANSI-C strstr()
2535 static const char* strrstr(const char* str, const char* sub)
2536 {
2537 const size_t sublen = strlen(sub);
2538 for(const char* p = &str[strlen(str)]; p != str; --p) {
2539 if ( strncmp(p, sub, sublen) == 0 )
2540 return p;
2541 }
2542 return NULL;
2543 }
2544
2545
2546 //
2547 // Find framework path
2548 //
2549 // /path/foo.framework/foo => foo.framework/foo
2550 // /path/foo.framework/Versions/A/foo => foo.framework/Versions/A/foo
2551 // /path/foo.framework/Frameworks/bar.framework/bar => bar.framework/bar
2552 // /path/foo.framework/Libraries/bar.dylb => NULL
2553 // /path/foo.framework/bar => NULL
2554 //
2555 // Returns NULL if not a framework path
2556 //
2557 static const char* getFrameworkPartialPath(const char* path)
2558 {
2559 const char* dirDot = strrstr(path, ".framework/");
2560 if ( dirDot != NULL ) {
2561 const char* dirStart = dirDot;
2562 for ( ; dirStart >= path; --dirStart) {
2563 if ( (*dirStart == '/') || (dirStart == path) ) {
2564 const char* frameworkStart = &dirStart[1];
2565 if ( dirStart == path )
2566 --frameworkStart;
2567 size_t len = dirDot - frameworkStart;
2568 char framework[len+1];
2569 strncpy(framework, frameworkStart, len);
2570 framework[len] = '\0';
2571 const char* leaf = strrchr(path, '/');
2572 if ( leaf != NULL ) {
2573 if ( strcmp(framework, &leaf[1]) == 0 ) {
2574 return frameworkStart;
2575 }
2576 if ( gLinkContext.imageSuffix != NULL ) {
2577 // some debug frameworks have install names that end in _debug
2578 if ( strncmp(framework, &leaf[1], len) == 0 ) {
2579 for (const char* const* suffix=gLinkContext.imageSuffix; *suffix != NULL; ++suffix) {
2580 if ( strcmp(*suffix, &leaf[len+1]) == 0 )
2581 return frameworkStart;
2582 }
2583 }
2584 }
2585 }
2586 }
2587 }
2588 }
2589 return NULL;
2590 }
2591
2592
2593 static const char* getLibraryLeafName(const char* path)
2594 {
2595 const char* start = strrchr(path, '/');
2596 if ( start != NULL )
2597 return &start[1];
2598 else
2599 return path;
2600 }
2601
2602
2603 // only for architectures that use cpu-sub-types
2604 #if CPU_SUBTYPES_SUPPORTED
2605
2606 const cpu_subtype_t CPU_SUBTYPE_END_OF_LIST = -1;
2607
2608
2609 //
2610 // A fat file may contain multiple sub-images for the same CPU type.
2611 // In that case, dyld picks which sub-image to use by scanning a table
2612 // of preferred cpu-sub-types for the running cpu.
2613 //
2614 // There is one row in the table for each cpu-sub-type on which dyld might run.
2615 // The first entry in a row is that cpu-sub-type. It is followed by all
2616 // cpu-sub-types that can run on that cpu, if preferred order. Each row ends with
2617 // a "SUBTYPE_ALL" (to denote that images written to run on any cpu-sub-type are usable),
2618 // followed by one or more CPU_SUBTYPE_END_OF_LIST to pad out this row.
2619 //
2620
2621
2622 #if __arm__
2623 //
2624 // ARM sub-type lists
2625 //
2626 const int kARM_RowCount = 8;
2627 static const cpu_subtype_t kARM[kARM_RowCount][9] = {
2628
2629 // armv7f can run: v7f, v7, v6, v5, and v4
2630 { 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 },
2631
2632 // armv7k can run: v7k
2633 { CPU_SUBTYPE_ARM_V7K, CPU_SUBTYPE_END_OF_LIST },
2634
2635 // armv7s can run: v7s, v7, v7f, v7k, v6, v5, and v4
2636 { 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 },
2637
2638 // armv7 can run: v7, v6, v5, and v4
2639 { 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 },
2640
2641 // armv6 can run: v6, v5, and v4
2642 { 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 },
2643
2644 // xscale can run: xscale, v5, and v4
2645 { 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 },
2646
2647 // armv5 can run: v5 and v4
2648 { 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 },
2649
2650 // armv4 can run: v4
2651 { 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 },
2652 };
2653 #endif
2654
2655 #if __arm64__
2656 //
2657 // ARM64 sub-type lists
2658 //
2659 const int kARM64_RowCount = 2;
2660 static const cpu_subtype_t kARM64[kARM64_RowCount][4] = {
2661
2662 // armv64e can run: 64e, 64
2663 { CPU_SUBTYPE_ARM64E, CPU_SUBTYPE_ARM64_V8, CPU_SUBTYPE_ARM64_ALL, CPU_SUBTYPE_END_OF_LIST },
2664
2665 // armv64 can run: 64
2666 { CPU_SUBTYPE_ARM64_V8, CPU_SUBTYPE_ARM64_ALL, CPU_SUBTYPE_END_OF_LIST },
2667 };
2668
2669 #if __ARM64_ARCH_8_32__
2670 const int kARM64_32_RowCount = 2;
2671 static const cpu_subtype_t kARM64_32[kARM64_32_RowCount][4] = {
2672
2673 // armv64_32 can run: v8
2674 { CPU_SUBTYPE_ARM64_32_V8, CPU_SUBTYPE_END_OF_LIST },
2675
2676 // armv64 can run: 64
2677 { CPU_SUBTYPE_ARM64_V8, CPU_SUBTYPE_ARM64_ALL, CPU_SUBTYPE_END_OF_LIST },
2678 };
2679 #endif
2680
2681 #endif
2682
2683 #if __x86_64__
2684 //
2685 // x86_64 sub-type lists
2686 //
2687 const int kX86_64_RowCount = 2;
2688 static const cpu_subtype_t kX86_64[kX86_64_RowCount][5] = {
2689
2690 // x86_64h can run: x86_64h, x86_64h(lib), x86_64(lib), and x86_64
2691 { 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 },
2692
2693 // x86_64 can run: x86_64(lib) and x86_64
2694 { CPU_SUBTYPE_X86_64_ALL, (cpu_subtype_t)(CPU_SUBTYPE_LIB64|CPU_SUBTYPE_X86_64_ALL), CPU_SUBTYPE_END_OF_LIST },
2695
2696 };
2697 #endif
2698
2699
2700 // scan the tables above to find the cpu-sub-type-list for this machine
2701 static const cpu_subtype_t* findCPUSubtypeList(cpu_type_t cpu, cpu_subtype_t subtype)
2702 {
2703 switch (cpu) {
2704 #if __arm__
2705 case CPU_TYPE_ARM:
2706 for (int i=0; i < kARM_RowCount ; ++i) {
2707 if ( kARM[i][0] == subtype )
2708 return kARM[i];
2709 }
2710 break;
2711 #endif
2712 #if __arm64__
2713 case CPU_TYPE_ARM64:
2714 for (int i=0; i < kARM64_RowCount ; ++i) {
2715 if ( kARM64[i][0] == subtype )
2716 return kARM64[i];
2717 }
2718 break;
2719
2720 #if __ARM64_ARCH_8_32__
2721 case CPU_TYPE_ARM64_32:
2722 for (int i=0; i < kARM64_32_RowCount ; ++i) {
2723 if ( kARM64_32[i][0] == subtype )
2724 return kARM64_32[i];
2725 }
2726 break;
2727 #endif
2728
2729 #endif
2730 #if __x86_64__
2731 case CPU_TYPE_X86_64:
2732 for (int i=0; i < kX86_64_RowCount ; ++i) {
2733 if ( kX86_64[i][0] == subtype )
2734 return kX86_64[i];
2735 }
2736 break;
2737 #endif
2738 }
2739 return NULL;
2740 }
2741
2742
2743
2744
2745 // scan fat table-of-contents for best most preferred subtype
2746 static bool fatFindBestFromOrderedList(cpu_type_t cpu, const cpu_subtype_t list[], const fat_header* fh, uint64_t* offset, uint64_t* len)
2747 {
2748 const fat_arch* const archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2749 for (uint32_t subTypeIndex=0; list[subTypeIndex] != CPU_SUBTYPE_END_OF_LIST; ++subTypeIndex) {
2750 for(uint32_t fatIndex=0; fatIndex < OSSwapBigToHostInt32(fh->nfat_arch); ++fatIndex) {
2751 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[fatIndex].cputype) == cpu)
2752 && (list[subTypeIndex] == (cpu_subtype_t)OSSwapBigToHostInt32(archs[fatIndex].cpusubtype)) ) {
2753 *offset = OSSwapBigToHostInt32(archs[fatIndex].offset);
2754 *len = OSSwapBigToHostInt32(archs[fatIndex].size);
2755 return true;
2756 }
2757 }
2758 }
2759 return false;
2760 }
2761
2762 // scan fat table-of-contents for exact match of cpu and cpu-sub-type
2763 static bool fatFindExactMatch(cpu_type_t cpu, cpu_subtype_t subtype, const fat_header* fh, uint64_t* offset, uint64_t* len)
2764 {
2765 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2766 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2767 if ( ((cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu)
2768 && ((cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == subtype) ) {
2769 *offset = OSSwapBigToHostInt32(archs[i].offset);
2770 *len = OSSwapBigToHostInt32(archs[i].size);
2771 return true;
2772 }
2773 }
2774 return false;
2775 }
2776
2777 // scan fat table-of-contents for image with matching cpu-type and runs-on-all-sub-types
2778 static bool fatFindRunsOnAllCPUs(cpu_type_t cpu, const fat_header* fh, uint64_t* offset, uint64_t* len)
2779 {
2780 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2781 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2782 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == cpu) {
2783 switch (cpu) {
2784 #if __arm__
2785 case CPU_TYPE_ARM:
2786 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM_ALL ) {
2787 *offset = OSSwapBigToHostInt32(archs[i].offset);
2788 *len = OSSwapBigToHostInt32(archs[i].size);
2789 return true;
2790 }
2791 break;
2792 #endif
2793 #if __arm64__
2794 case CPU_TYPE_ARM64:
2795 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_ARM64_ALL ) {
2796 *offset = OSSwapBigToHostInt32(archs[i].offset);
2797 *len = OSSwapBigToHostInt32(archs[i].size);
2798 return true;
2799 }
2800 break;
2801 #endif
2802 #if __x86_64__
2803 case CPU_TYPE_X86_64:
2804 if ( (cpu_subtype_t)OSSwapBigToHostInt32(archs[i].cpusubtype) == CPU_SUBTYPE_X86_64_ALL ) {
2805 *offset = OSSwapBigToHostInt32(archs[i].offset);
2806 *len = OSSwapBigToHostInt32(archs[i].size);
2807 return true;
2808 }
2809 break;
2810 #endif
2811 }
2812 }
2813 }
2814 return false;
2815 }
2816
2817 #endif // CPU_SUBTYPES_SUPPORTED
2818
2819
2820 //
2821 // Validate the fat_header and fat_arch array:
2822 //
2823 // 1) arch count would not cause array to extend past 4096 byte read buffer
2824 // 2) no slice overlaps the fat_header and arch array
2825 // 3) arch list does not contain duplicate cputype/cpusubtype tuples
2826 // 4) arch list does not have two overlapping slices.
2827 //
2828 static bool fatValidate(const fat_header* fh)
2829 {
2830 if ( fh->magic != OSSwapBigToHostInt32(FAT_MAGIC) )
2831 return false;
2832
2833 // since only first 4096 bytes of file read, we can only handle up to 204 slices.
2834 const uint32_t sliceCount = OSSwapBigToHostInt32(fh->nfat_arch);
2835 if ( sliceCount > 204 )
2836 return false;
2837
2838 // compare all slices looking for conflicts
2839 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2840 for (uint32_t i=0; i < sliceCount; ++i) {
2841 uint32_t i_offset = OSSwapBigToHostInt32(archs[i].offset);
2842 uint32_t i_size = OSSwapBigToHostInt32(archs[i].size);
2843 uint32_t i_cputype = OSSwapBigToHostInt32(archs[i].cputype);
2844 uint32_t i_cpusubtype = OSSwapBigToHostInt32(archs[i].cpusubtype);
2845 uint32_t i_end = i_offset + i_size;
2846 // slice cannot overlap with header
2847 if ( i_offset < 4096 )
2848 return false;
2849 // slice size cannot overflow
2850 if ( i_end < i_offset )
2851 return false;
2852 for (uint32_t j=i+1; j < sliceCount; ++j) {
2853 uint32_t j_offset = OSSwapBigToHostInt32(archs[j].offset);
2854 uint32_t j_size = OSSwapBigToHostInt32(archs[j].size);
2855 uint32_t j_cputype = OSSwapBigToHostInt32(archs[j].cputype);
2856 uint32_t j_cpusubtype = OSSwapBigToHostInt32(archs[j].cpusubtype);
2857 uint32_t j_end = j_offset + j_size;
2858 // duplicate slices types not allowed
2859 if ( (i_cputype == j_cputype) && (i_cpusubtype == j_cpusubtype) )
2860 return false;
2861 // slice size cannot overflow
2862 if ( j_end < j_offset )
2863 return false;
2864 // check for overlap of slices
2865 if ( i_offset <= j_offset ) {
2866 if ( j_offset < i_end )
2867 return false; // j overlaps end of i
2868 }
2869 else {
2870 // j overlaps end of i
2871 if ( i_offset < j_end )
2872 return false; // i overlaps end of j
2873 }
2874 }
2875 }
2876 return true;
2877 }
2878
2879 //
2880 // A fat file may contain multiple sub-images for the same cpu-type,
2881 // each optimized for a different cpu-sub-type (e.g G3 or G5).
2882 // This routine picks the optimal sub-image.
2883 //
2884 static bool fatFindBest(const fat_header* fh, uint64_t* offset, uint64_t* len)
2885 {
2886 if ( !fatValidate(fh) )
2887 return false;
2888
2889 #if CPU_SUBTYPES_SUPPORTED
2890 // assume all dylibs loaded must have same cpu type as main executable
2891 const cpu_type_t cpu = sMainExecutableMachHeader->cputype;
2892
2893 // We only know the subtype to use if the main executable cpu type matches the host
2894 if ( cpu == sHostCPU ) {
2895 // get preference ordered list of subtypes
2896 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(cpu, sHostCPUsubtype);
2897
2898 // use ordered list to find best sub-image in fat file
2899 if ( subTypePreferenceList != NULL ) {
2900 if ( fatFindBestFromOrderedList(cpu, subTypePreferenceList, fh, offset, len) )
2901 return true;
2902 }
2903
2904 // if running cpu is not in list, try for an exact match
2905 if ( fatFindExactMatch(cpu, sHostCPUsubtype, fh, offset, len) )
2906 return true;
2907 }
2908
2909 // running on an uknown cpu, can only load generic code
2910 return fatFindRunsOnAllCPUs(cpu, fh, offset, len);
2911 #else
2912 // just find first slice with matching architecture
2913 const fat_arch* archs = (fat_arch*)(((char*)fh)+sizeof(fat_header));
2914 for(uint32_t i=0; i < OSSwapBigToHostInt32(fh->nfat_arch); ++i) {
2915 if ( (cpu_type_t)OSSwapBigToHostInt32(archs[i].cputype) == sMainExecutableMachHeader->cputype) {
2916 *offset = OSSwapBigToHostInt32(archs[i].offset);
2917 *len = OSSwapBigToHostInt32(archs[i].size);
2918 return true;
2919 }
2920 }
2921 return false;
2922 #endif
2923 }
2924
2925
2926
2927 //
2928 // This is used to validate if a non-fat (aka thin or raw) mach-o file can be used
2929 // on the current processor. //
2930 bool isCompatibleMachO(const uint8_t* firstPage, const char* path)
2931 {
2932 #if CPU_SUBTYPES_SUPPORTED
2933 // It is deemed compatible if any of the following are true:
2934 // 1) mach_header subtype is in list of compatible subtypes for running processor
2935 // 2) mach_header subtype is same as running processor subtype
2936 // 3) mach_header subtype runs on all processor variants
2937 const mach_header* mh = (mach_header*)firstPage;
2938 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2939 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2940 if ( mh->cputype == sHostCPU ) {
2941 // get preference ordered list of subtypes that this machine can use
2942 const cpu_subtype_t* subTypePreferenceList = findCPUSubtypeList(mh->cputype, sHostCPUsubtype);
2943 if ( subTypePreferenceList != NULL ) {
2944 // if image's subtype is in the list, it is compatible
2945 for (const cpu_subtype_t* p = subTypePreferenceList; *p != CPU_SUBTYPE_END_OF_LIST; ++p) {
2946 if ( *p == mh->cpusubtype )
2947 return true;
2948 }
2949 // have list and not in list, so not compatible
2950 throwf("incompatible cpu-subtype: 0x%08X in %s", mh->cpusubtype, path);
2951 }
2952 // unknown cpu sub-type, but if exact match for current subtype then ok to use
2953 if ( mh->cpusubtype == sHostCPUsubtype )
2954 return true;
2955 }
2956
2957 // cpu type has no ordered list of subtypes
2958 switch (mh->cputype) {
2959 case CPU_TYPE_I386:
2960 case CPU_TYPE_X86_64:
2961 // subtypes are not used or these architectures
2962 return true;
2963 }
2964 }
2965 }
2966 #else
2967 // For architectures that don't support cpu-sub-types
2968 // this just check the cpu type.
2969 const mach_header* mh = (mach_header*)firstPage;
2970 if ( mh->magic == sMainExecutableMachHeader->magic ) {
2971 if ( mh->cputype == sMainExecutableMachHeader->cputype ) {
2972 return true;
2973 }
2974 }
2975 #endif
2976 return false;
2977 }
2978
2979
2980
2981
2982 // The kernel maps in main executable before dyld gets control. We need to
2983 // make an ImageLoader* for the already mapped in main executable.
2984 static ImageLoaderMachO* instantiateFromLoadedImage(const macho_header* mh, uintptr_t slide, const char* path)
2985 {
2986 // try mach-o loader
2987 if ( isCompatibleMachO((const uint8_t*)mh, path) ) {
2988 ImageLoader* image = ImageLoaderMachO::instantiateMainExecutable(mh, slide, path, gLinkContext);
2989 addImage(image);
2990 return (ImageLoaderMachO*)image;
2991 }
2992
2993 throw "main executable not a known format";
2994 }
2995
2996 #if SUPPORT_ACCELERATE_TABLES
2997 static bool dylibsCanOverrideCache()
2998 {
2999 if ( !dyld3::internalInstall() )
3000 return false;
3001 return ( (sSharedCacheLoadInfo.loadAddress != nullptr) && (sSharedCacheLoadInfo.loadAddress->header.cacheType == kDyldSharedCacheTypeDevelopment) );
3002 }
3003 #endif
3004
3005 const void* imMemorySharedCacheHeader()
3006 {
3007 return sSharedCacheLoadInfo.loadAddress;
3008 }
3009
3010
3011 const char* getStandardSharedCacheFilePath()
3012 {
3013 if ( sSharedCacheLoadInfo.loadAddress != nullptr )
3014 return sSharedCacheLoadInfo.path;
3015 else
3016 return nullptr;
3017 }
3018
3019 bool hasInsertedOrInterposingLibraries() {
3020 return (sInsertedDylibCount > 0) || ImageLoader::haveInterposingTuples();
3021 }
3022
3023
3024 #if SUPPORT_VERSIONED_PATHS
3025 static bool findInSharedCacheImage(const char* path, bool searchByPath, const struct stat* stat_buf, const macho_header** mh, const char** pathInCache, long* slide)
3026 {
3027 dyld3::SharedCacheFindDylibResults results;
3028 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &results) ) {
3029 *mh = (macho_header*)results.mhInCache;
3030 *pathInCache = results.pathInCache;
3031 *slide = results.slideInCache;
3032 return true;
3033 }
3034 return false;
3035 }
3036 #endif
3037
3038 bool inSharedCache(const char* path)
3039 {
3040 return dyld3::pathIsInSharedCacheImage(sSharedCacheLoadInfo, path);
3041 }
3042
3043
3044 static ImageLoader* checkandAddImage(ImageLoader* image, const LoadContext& context)
3045 {
3046 // now sanity check that this loaded image does not have the same install path as any existing image
3047 const char* loadedImageInstallPath = image->getInstallPath();
3048 if ( image->isDylib() && (loadedImageInstallPath != NULL) && (loadedImageInstallPath[0] == '/') ) {
3049 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3050 ImageLoader* anImage = *it;
3051 const char* installPath = anImage->getInstallPath();
3052 if ( installPath != NULL) {
3053 if ( strcmp(loadedImageInstallPath, installPath) == 0 ) {
3054 //dyld::log("duplicate(%s) => %p\n", installPath, anImage);
3055 removeImage(image);
3056 ImageLoader::deleteImage(image);
3057 return anImage;
3058 }
3059 }
3060 }
3061 }
3062
3063 // some API's restrict what they can load
3064 if ( context.mustBeBundle && !image->isBundle() )
3065 throw "not a bundle";
3066 if ( context.mustBeDylib && !image->isDylib() )
3067 throw "not a dylib";
3068
3069 // regular main executables cannot be loaded
3070 if ( image->isExecutable() ) {
3071 if ( !context.canBePIE || !image->isPositionIndependentExecutable() )
3072 throw "can't load a main executable";
3073 }
3074
3075 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
3076 if ( ! image->isBundle() )
3077 addImage(image);
3078
3079 return image;
3080 }
3081
3082 #if TARGET_OS_SIMULATOR
3083 static bool isSimulatorBinary(const uint8_t* firstPages, const char* path)
3084 {
3085 const macho_header* mh = (macho_header*)firstPages;
3086 const uint32_t cmd_count = mh->ncmds;
3087 const load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
3088 const load_command* const cmdsEnd = (load_command*)((char*)cmds + mh->sizeofcmds);
3089 const struct load_command* cmd = cmds;
3090 for (uint32_t i = 0; i < cmd_count; ++i) {
3091 switch (cmd->cmd) {
3092 #if TARGET_OS_WATCH
3093 case LC_VERSION_MIN_WATCHOS:
3094 return true;
3095 #elif TARGET_OS_TV
3096 case LC_VERSION_MIN_TVOS:
3097 return true;
3098 #elif TARGET_OS_IOS
3099 case LC_VERSION_MIN_IPHONEOS:
3100 return true;
3101 #endif
3102 case LC_VERSION_MIN_MACOSX:
3103 // grandfather in a few libSystem dylibs
3104 if ((strcmp(path, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
3105 (strcmp(path, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
3106 (strcmp(path, "/usr/lib/system/libsystem_pthread.dylib") == 0) ||
3107 (strcmp(path, "/usr/lib/system/libsystem_platform_debug.dylib") == 0) ||
3108 (strcmp(path, "/usr/lib/system/libsystem_pthread_debug.dylib") == 0) ||
3109 (strcmp(path, "/sbin/launchd_sim_trampoline") == 0) ||
3110 (strcmp(path, "/usr/sbin/iokitsimd") == 0) ||
3111 (strcmp(path, "/usr/lib/system/host/liblaunch_sim.dylib") == 0))
3112 return true;
3113 return false;
3114 case LC_BUILD_VERSION:
3115 {
3116 // Same logic as above, but for LC_BUILD_VERSION instead of legacy load commands
3117 const struct build_version_command* buildVersionCmd = (build_version_command*)cmd;
3118 switch(buildVersionCmd->platform) {
3119 case PLATFORM_IOSSIMULATOR:
3120 case PLATFORM_TVOSSIMULATOR:
3121 case PLATFORM_WATCHOSSIMULATOR:
3122 case PLATFORM_WATCHOS:
3123 return true;
3124 #if TARGET_OS_IOSMAC
3125 case 6:
3126 return true;
3127 #endif
3128 case PLATFORM_MACOS:
3129 if ((strcmp(path, "/usr/lib/system/libsystem_kernel.dylib") == 0) ||
3130 (strcmp(path, "/usr/lib/system/libsystem_platform.dylib") == 0) ||
3131 (strcmp(path, "/usr/lib/system/libsystem_pthread.dylib") == 0) ||
3132 (strcmp(path, "/usr/lib/system/libsystem_platform_debug.dylib") == 0) ||
3133 (strcmp(path, "/usr/lib/system/libsystem_pthread_debug.dylib") == 0) ||
3134 (strcmp(path, "/sbin/launchd_sim_trampoline") == 0) ||
3135 (strcmp(path, "/usr/sbin/iokitsimd") == 0) ||
3136 (strcmp(path, "/usr/lib/system/host/liblaunch_sim.dylib") == 0))
3137 return true;
3138 }
3139 }
3140 }
3141 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
3142 if ( cmd > cmdsEnd )
3143 return false;
3144 }
3145 return false;
3146 }
3147 #endif
3148
3149 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3150 static bool iOSonMacDenied(const char* path)
3151 {
3152 static char* blackListBuffer = nullptr;
3153 static size_t blackListSize = 0;
3154 static bool tried = false;
3155 if ( !tried ) {
3156 // only try to map file once
3157 blackListBuffer = (char*)mapFileReadOnly("/System/iOSSupport/dyld/macOS-deny-list.txt", blackListSize);
3158 tried = true;
3159 }
3160 __block bool result = false;
3161 if ( blackListBuffer != nullptr ) {
3162 dyld3::forEachLineInFile(blackListBuffer, blackListSize, ^(const char* line, bool& stop) {
3163 // lines in the file are prefixes. Any path that starts with one of these lines is allowed to be unzippered
3164 size_t lineLen = strlen(line);
3165 if ( (*line == '/') && strncmp(line, path, lineLen) == 0 ) {
3166 result = true;
3167 stop = true;
3168 }
3169 });
3170 }
3171 return result;
3172 }
3173 #endif
3174
3175 // map in file and instantiate an ImageLoader
3176 static ImageLoader* loadPhase6(int fd, const struct stat& stat_buf, const char* path, const LoadContext& context)
3177 {
3178 //dyld::log("%s(%s)\n", __func__ , path);
3179 uint64_t fileOffset = 0;
3180 uint64_t fileLength = stat_buf.st_size;
3181
3182 // validate it is a file (not directory)
3183 if ( (stat_buf.st_mode & S_IFMT) != S_IFREG )
3184 throw "not a file";
3185
3186 uint8_t firstPages[MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE];
3187 uint8_t *firstPagesPtr = firstPages;
3188 bool shortPage = false;
3189
3190 // min mach-o file is 4K
3191 if ( fileLength < 4096 ) {
3192 if ( pread(fd, firstPages, (size_t)fileLength, 0) != (ssize_t)fileLength )
3193 throwf("pread of short file failed: %d", errno);
3194 shortPage = true;
3195 }
3196 else {
3197 // optimistically read only first 4KB
3198 if ( pread(fd, firstPages, 4096, 0) != 4096 )
3199 throwf("pread of first 4K failed: %d", errno);
3200 }
3201
3202 // if fat wrapper, find usable sub-file
3203 const fat_header* fileStartAsFat = (fat_header*)firstPages;
3204 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
3205 if ( OSSwapBigToHostInt32(fileStartAsFat->nfat_arch) > ((4096 - sizeof(fat_header)) / sizeof(fat_arch)) )
3206 throwf("fat header too large: %u entries", OSSwapBigToHostInt32(fileStartAsFat->nfat_arch));
3207 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
3208 if ( (fileOffset+fileLength) > (uint64_t)(stat_buf.st_size) )
3209 throwf("truncated fat file. file length=%llu, but needed slice goes to %llu", stat_buf.st_size, fileOffset+fileLength);
3210 if (pread(fd, firstPages, 4096, fileOffset) != 4096)
3211 throwf("pread of fat file failed: %d", errno);
3212 }
3213 else {
3214 throw "no matching architecture in universal wrapper";
3215 }
3216 }
3217
3218 // try mach-o loader
3219 if ( shortPage )
3220 throw "file too short";
3221
3222 if ( isCompatibleMachO(firstPages, path) ) {
3223
3224 // only MH_BUNDLE, MH_DYLIB, and some MH_EXECUTE can be dynamically loaded
3225 const mach_header* mh = (mach_header*)firstPages;
3226 switch ( mh->filetype ) {
3227 case MH_EXECUTE:
3228 case MH_DYLIB:
3229 case MH_BUNDLE:
3230 break;
3231 default:
3232 throw "mach-o, but wrong filetype";
3233 }
3234
3235 uint32_t headerAndLoadCommandsSize = sizeof(macho_header) + mh->sizeofcmds;
3236 if ( headerAndLoadCommandsSize > MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE )
3237 throwf("malformed mach-o: load commands size (%u) > %u", headerAndLoadCommandsSize, MAX_MACH_O_HEADER_AND_LOAD_COMMANDS_SIZE);
3238
3239 if ( headerAndLoadCommandsSize > fileLength )
3240 dyld::throwf("malformed mach-o: load commands size (%u) > mach-o file size (%llu)", headerAndLoadCommandsSize, fileLength);
3241
3242 if ( headerAndLoadCommandsSize > 4096 ) {
3243 // read more pages
3244 unsigned readAmount = headerAndLoadCommandsSize - 4096;
3245 if ( pread(fd, &firstPages[4096], readAmount, fileOffset+4096) != readAmount )
3246 throwf("pread of extra load commands past 4KB failed: %d", errno);
3247 }
3248
3249 #if TARGET_OS_SIMULATOR
3250 // <rdar://problem/14168872> dyld_sim should restrict loading osx binaries
3251 if ( !isSimulatorBinary(firstPages, path) ) {
3252 #if TARGET_OS_WATCH
3253 throw "mach-o, but not built for watchOS simulator";
3254 #elif TARGET_OS_TV
3255 throw "mach-o, but not built for tvOS simulator";
3256 #else
3257 throw "mach-o, but not built for iOS simulator";
3258 #endif
3259 }
3260 #endif
3261
3262 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3263 if ( gLinkContext.iOSonMac ) {
3264 const dyld3::MachOFile* mf = (dyld3::MachOFile*)firstPages;
3265 bool supportsiOSMac = mf->supportsPlatform(dyld3::Platform::iOSMac);
3266 if ( !supportsiOSMac && iOSonMacDenied(path) ) {
3267 throw "mach-o, but not built for UIKitForMac";
3268 }
3269 }
3270 else if ( gLinkContext.driverKit ) {
3271 const dyld3::MachOFile* mf = (dyld3::MachOFile*)firstPages;
3272 bool isDriverKitDylib = mf->supportsPlatform(dyld3::Platform::driverKit);
3273 if ( !isDriverKitDylib ) {
3274 throw "mach-o, but not built for driverkit";
3275 }
3276 }
3277 #endif
3278
3279 #if __arm64e__
3280 if ( (sMainExecutableMachHeader->cpusubtype == CPU_SUBTYPE_ARM64E) && (mh->cpusubtype != CPU_SUBTYPE_ARM64E) )
3281 throw "arm64 dylibs cannot be loaded into arm64e processes";
3282 #endif
3283 ImageLoader* image = nullptr;
3284 {
3285 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_MAP_IMAGE, path, 0, 0);
3286 image = ImageLoaderMachO::instantiateFromFile(path, fd, firstPagesPtr, headerAndLoadCommandsSize, fileOffset, fileLength, stat_buf, gLinkContext);
3287 timer.setData4((uint64_t)image->machHeader());
3288 }
3289
3290 // validate
3291 return checkandAddImage(image, context);
3292 }
3293
3294 // try other file formats here...
3295
3296
3297 // throw error about what was found
3298 switch (*(uint32_t*)firstPages) {
3299 case MH_MAGIC:
3300 case MH_CIGAM:
3301 case MH_MAGIC_64:
3302 case MH_CIGAM_64:
3303 throw "mach-o, but wrong architecture";
3304 default:
3305 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
3306 firstPages[0], firstPages[1], firstPages[2], firstPages[3], firstPages[4], firstPages[5], firstPages[6],firstPages[7]);
3307 }
3308 }
3309
3310
3311 static ImageLoader* loadPhase5open(const char* path, const LoadContext& context, const struct stat& stat_buf, std::vector<const char*>* exceptions)
3312 {
3313 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3314
3315 // open file (automagically closed when this function exits)
3316 FileOpener file(path);
3317
3318 // just return NULL if file not found, but record any other errors
3319 if ( file.getFileDescriptor() == -1 ) {
3320 int err = errno;
3321 if ( err != ENOENT ) {
3322 const char* newMsg;
3323 if ( (err == EPERM) && sandboxBlockedOpen(path) )
3324 newMsg = dyld::mkstringf("file system sandbox blocked open() of '%s'", path);
3325 else
3326 newMsg = dyld::mkstringf("%s: open() failed with errno=%d", path, err);
3327 exceptions->push_back(newMsg);
3328 }
3329 return NULL;
3330 }
3331
3332 try {
3333 return loadPhase6(file.getFileDescriptor(), stat_buf, path, context);
3334 }
3335 catch (const char* msg) {
3336 const char* newMsg = dyld::mkstringf("%s: %s", path, msg);
3337 exceptions->push_back(newMsg);
3338 free((void*)msg);
3339 return NULL;
3340 }
3341 }
3342
3343 static bool isFileRelativePath(const char* path)
3344 {
3345 if ( path[0] == '/' )
3346 return false;
3347 if ( path[0] != '.' )
3348 return true;
3349 if ( path[1] == '/' )
3350 return true;
3351 if ( (path[1] == '.') && (path[2] == '/') )
3352 return true;
3353 return false;
3354 }
3355
3356
3357 // try to open file
3358 static ImageLoader* loadPhase5load(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3359 {
3360 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3361
3362 // <rdar://problem/47682983> don't allow file system relative paths in hardened programs
3363 if ( (exceptions != NULL) && !gLinkContext.allowEnvVarsPath && isFileRelativePath(path) ) {
3364 exceptions->push_back("file system relative paths not allowed in hardened programs");
3365 return NULL;
3366 }
3367
3368 #if SUPPORT_ACCELERATE_TABLES
3369 if ( sAllCacheImagesProxy != NULL ) {
3370 if ( sAllCacheImagesProxy->hasDylib(path, &cacheIndex) )
3371 return sAllCacheImagesProxy;
3372 }
3373 #endif
3374 #if TARGET_OS_SIMULATOR
3375 // in simulators, 'path' has DYLD_ROOT_PATH prepended, but cache index does not have the prefix, so use orgPath
3376 const char* pathToFindInCache = orgPath;
3377 #else
3378 const char* pathToFindInCache = path;
3379 #endif
3380 uint statErrNo;
3381 struct stat statBuf;
3382 bool didStat = false;
3383 bool existsOnDisk;
3384 dyld3::SharedCacheFindDylibResults shareCacheResults;
3385 shareCacheResults.image = nullptr;
3386 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, pathToFindInCache, &shareCacheResults) ) {
3387 // see if this image in the cache was already loaded via a different path
3388 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); ++it) {
3389 ImageLoader* anImage = *it;
3390 if ( (const mach_header*)anImage->machHeader() == shareCacheResults.mhInCache )
3391 return anImage;
3392 }
3393 // if RTLD_NOLOAD, do nothing if not already loaded
3394 if ( context.dontLoad ) {
3395 // <rdar://33412890> possible that there is an override of cache
3396 if ( my_stat(path, &statBuf) == 0 ) {
3397 ImageLoader* imageLoader = findLoadedImage(statBuf);
3398 if ( imageLoader != NULL )
3399 return imageLoader;
3400 }
3401 return NULL;
3402 }
3403 bool useCache = false;
3404 if ( shareCacheResults.image == nullptr ) {
3405 // HACK to support old caches
3406 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3407 didStat = true;
3408 statErrNo = errno;
3409 useCache = !existsOnDisk;
3410 }
3411 else {
3412 // <rdar://problem/7014995> zero out stat buffer so mtime, etc are zero for items from the shared cache
3413 bzero(&statBuf, sizeof(statBuf));
3414 if ( shareCacheResults.image->overridableDylib() ) {
3415 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3416 didStat = true;
3417 statErrNo = errno;
3418 if ( sSharedCacheLoadInfo.loadAddress->header.dylibsExpectedOnDisk ) {
3419 uint64_t expectedINode;
3420 uint64_t expectedMtime;
3421 if ( shareCacheResults.image->hasFileModTimeAndInode(expectedINode, expectedMtime) ) {
3422 if ( (expectedMtime == statBuf.st_mtime) && (expectedINode == statBuf.st_ino) )
3423 useCache = true;
3424 }
3425 }
3426 else {
3427 if ( !existsOnDisk )
3428 useCache = true;
3429 }
3430 }
3431 else {
3432 useCache = true;
3433 }
3434 }
3435 if ( useCache ) {
3436 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3437 if ( gLinkContext.iOSonMac ) {
3438 const dyld3::MachOFile* mf = (dyld3::MachOFile*)shareCacheResults.mhInCache;
3439 bool supportsiOSMac = mf->supportsPlatform(dyld3::Platform::iOSMac);
3440 if ( !supportsiOSMac && iOSonMacDenied(path) ) {
3441 throw "mach-o, but not built for UIKitForMac";
3442 }
3443 }
3444 #endif
3445 ImageLoader* imageLoader = ImageLoaderMachO::instantiateFromCache((macho_header*)shareCacheResults.mhInCache, shareCacheResults.pathInCache, shareCacheResults.slideInCache, statBuf, gLinkContext);
3446 return checkandAddImage(imageLoader, context);
3447 }
3448 }
3449
3450 // not in cache or cache not usable
3451 if ( !didStat ) {
3452 existsOnDisk = ( my_stat(path, &statBuf) == 0 );
3453 statErrNo = errno;
3454 }
3455 if ( existsOnDisk ) {
3456 // in case image was renamed or found via symlinks, check for inode match
3457 ImageLoader* imageLoader = findLoadedImage(statBuf);
3458 if ( imageLoader != NULL )
3459 return imageLoader;
3460 // do nothing if not already loaded and if RTLD_NOLOAD
3461 if ( context.dontLoad )
3462 return NULL;
3463 // try opening file
3464 imageLoader = loadPhase5open(path, context, statBuf, exceptions);
3465 if ( imageLoader != NULL ) {
3466 if ( shareCacheResults.image != nullptr ) {
3467 // if image was found in cache, but is overridden by a newer file on disk, record what the image overrides
3468 imageLoader->setOverridesCachedDylib(shareCacheResults.image->imageNum());
3469 }
3470 return imageLoader;
3471 }
3472 }
3473
3474 // just return NULL if file not found, but record any other errors
3475 if ( (statErrNo != ENOENT) && (statErrNo != 0) ) {
3476 if ( (statErrNo == EPERM) && sandboxBlockedStat(path) )
3477 exceptions->push_back(dyld::mkstringf("%s: file system sandbox blocked stat()", path));
3478 else
3479 exceptions->push_back(dyld::mkstringf("%s: stat() failed with errno=%d", path, statErrNo));
3480 }
3481 return NULL;
3482 }
3483
3484 // look for path match with existing loaded images
3485 static ImageLoader* loadPhase5check(const char* path, const char* orgPath, const LoadContext& context)
3486 {
3487 //dyld::log("%s(%s, %s)\n", __func__ , path, orgPath);
3488 // search path against load-path and install-path of all already loaded images
3489 uint32_t hash = ImageLoader::hash(path);
3490 //dyld::log("check() hash=%d, path=%s\n", hash, path);
3491 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
3492 ImageLoader* anImage = *it;
3493 // check hash first to cut down on strcmp calls
3494 //dyld::log(" check() hash=%d, path=%s\n", anImage->getPathHash(), anImage->getPath());
3495 if ( anImage->getPathHash() == hash ) {
3496 if ( strcmp(path, anImage->getPath()) == 0 ) {
3497 // if we are looking for a dylib don't return something else
3498 if ( !context.mustBeDylib || anImage->isDylib() )
3499 return anImage;
3500 }
3501 }
3502 if ( context.matchByInstallName || anImage->matchInstallPath() ) {
3503 const char* installPath = anImage->getInstallPath();
3504 if ( installPath != NULL) {
3505 if ( strcmp(path, installPath) == 0 ) {
3506 // if we are looking for a dylib don't return something else
3507 if ( !context.mustBeDylib || anImage->isDylib() )
3508 return anImage;
3509 }
3510 }
3511 }
3512 // an install name starting with @rpath should match by install name, not just real path
3513 if ( (orgPath[0] == '@') && (strncmp(orgPath, "@rpath/", 7) == 0) ) {
3514 const char* installPath = anImage->getInstallPath();
3515 if ( installPath != NULL) {
3516 if ( !context.mustBeDylib || anImage->isDylib() ) {
3517 if ( strcmp(orgPath, installPath) == 0 )
3518 return anImage;
3519 }
3520 }
3521 }
3522 }
3523
3524 //dyld::log("%s(%s) => NULL\n", __func__, path);
3525 return NULL;
3526 }
3527
3528
3529 // open or check existing
3530 static ImageLoader* loadPhase5(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3531 {
3532 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3533
3534 // check for specific dylib overrides
3535 for (std::vector<DylibOverride>::iterator it = sDylibOverrides.begin(); it != sDylibOverrides.end(); ++it) {
3536 if ( strcmp(it->installName, path) == 0 ) {
3537 path = it->override;
3538 break;
3539 }
3540 }
3541
3542 if ( exceptions != NULL )
3543 return loadPhase5load(path, orgPath, context, cacheIndex, exceptions);
3544 else
3545 return loadPhase5check(path, orgPath, context);
3546 }
3547
3548 // try with and without image suffix
3549 static ImageLoader* loadPhase4(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3550 {
3551 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3552 ImageLoader* image = NULL;
3553 if ( gLinkContext.imageSuffix != NULL ) {
3554 for (const char* const* suffix=gLinkContext.imageSuffix; *suffix != NULL; ++suffix) {
3555 char pathWithSuffix[strlen(path)+strlen(*suffix)+2];
3556 ImageLoader::addSuffix(path, *suffix, pathWithSuffix);
3557 image = loadPhase5(pathWithSuffix, orgPath, context, cacheIndex, exceptions);
3558 if ( image != NULL )
3559 break;
3560 }
3561 if ( image != NULL ) {
3562 // if original path is in the dyld cache, then mark this one found as an override
3563 dyld3::SharedCacheFindDylibResults shareCacheResults;
3564 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &shareCacheResults) && (shareCacheResults.image != nullptr) )
3565 image->setOverridesCachedDylib(shareCacheResults.image->imageNum());
3566 }
3567 }
3568 if ( image == NULL )
3569 image = loadPhase5(path, orgPath, context, cacheIndex, exceptions);
3570 return image;
3571 }
3572
3573 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
3574 const char* const frameworkPaths[], const char* const libraryPaths[],
3575 unsigned& cacheIndex, std::vector<const char*>* exceptions); // forward reference
3576
3577
3578 // expand @ variables
3579 static ImageLoader* loadPhase3(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3580 {
3581 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3582 ImageLoader* image = NULL;
3583 if ( strncmp(path, "@executable_path/", 17) == 0 ) {
3584 // executable_path cannot be in used in any binary in a setuid process rdar://problem/4589305
3585 if ( !gLinkContext.allowAtPaths )
3586 throwf("unsafe use of @executable_path in %s with restricted binary (Codesign main executable with Library Validation to allow @ paths)", context.origin);
3587 // handle @executable_path path prefix
3588 const char* executablePath = sExecPath;
3589 char newPath[strlen(executablePath) + strlen(path)];
3590 strcpy(newPath, executablePath);
3591 char* addPoint = strrchr(newPath,'/');
3592 if ( addPoint != NULL )
3593 strcpy(&addPoint[1], &path[17]);
3594 else
3595 strcpy(newPath, &path[17]);
3596 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3597 if ( image != NULL )
3598 return image;
3599
3600 // perhaps main executable path is a sym link, find realpath and retry
3601 char resolvedPath[PATH_MAX];
3602 if ( realpath(sExecPath, resolvedPath) != NULL ) {
3603 char newRealPath[strlen(resolvedPath) + strlen(path)];
3604 strcpy(newRealPath, resolvedPath);
3605 addPoint = strrchr(newRealPath,'/');
3606 if ( addPoint != NULL )
3607 strcpy(&addPoint[1], &path[17]);
3608 else
3609 strcpy(newRealPath, &path[17]);
3610 image = loadPhase4(newRealPath, orgPath, context, cacheIndex, exceptions);
3611 if ( image != NULL )
3612 return image;
3613 }
3614 }
3615 else if ( (strncmp(path, "@loader_path/", 13) == 0) && (context.origin != NULL) ) {
3616 // @loader_path cannot be used from the main executable of a setuid process rdar://problem/4589305
3617 if ( !gLinkContext.allowAtPaths && (strcmp(context.origin, sExecPath) == 0) )
3618 throwf("unsafe use of @loader_path in %s with restricted binary (Codesign main executable with Library Validation to allow @ paths)", context.origin);
3619 // handle @loader_path path prefix
3620 char newPath[strlen(context.origin) + strlen(path)];
3621 strcpy(newPath, context.origin);
3622 char* addPoint = strrchr(newPath,'/');
3623 if ( addPoint != NULL )
3624 strcpy(&addPoint[1], &path[13]);
3625 else
3626 strcpy(newPath, &path[13]);
3627 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3628 if ( image != NULL )
3629 return image;
3630
3631 // perhaps loader path is a sym link, find realpath and retry
3632 char resolvedPath[PATH_MAX];
3633 if ( realpath(context.origin, resolvedPath) != NULL ) {
3634 char newRealPath[strlen(resolvedPath) + strlen(path)];
3635 strcpy(newRealPath, resolvedPath);
3636 addPoint = strrchr(newRealPath,'/');
3637 if ( addPoint != NULL )
3638 strcpy(&addPoint[1], &path[13]);
3639 else
3640 strcpy(newRealPath, &path[13]);
3641 image = loadPhase4(newRealPath, orgPath, context, cacheIndex, exceptions);
3642 if ( image != NULL )
3643 return image;
3644 }
3645 }
3646 else if ( context.implicitRPath || (strncmp(path, "@rpath/", 7) == 0) ) {
3647 const char* trailingPath = (strncmp(path, "@rpath/", 7) == 0) ? &path[7] : path;
3648 // substitute @rpath with all -rpath paths up the load chain
3649 for(const ImageLoader::RPathChain* rp=context.rpath; rp != NULL; rp=rp->next) {
3650 if (rp->paths != NULL ) {
3651 for(std::vector<const char*>::iterator it=rp->paths->begin(); it != rp->paths->end(); ++it) {
3652 const char* anRPath = *it;
3653 char newPath[strlen(anRPath) + strlen(trailingPath)+2];
3654 strcpy(newPath, anRPath);
3655 if ( newPath[strlen(newPath)-1] != '/' )
3656 strcat(newPath, "/");
3657 strcat(newPath, trailingPath);
3658 image = loadPhase4(newPath, orgPath, context, cacheIndex, exceptions);
3659 if ( gLinkContext.verboseRPaths && (exceptions != NULL) ) {
3660 if ( image != NULL )
3661 dyld::log("RPATH successful expansion of %s to: %s\n", orgPath, newPath);
3662 else
3663 dyld::log("RPATH failed expanding %s to: %s\n", orgPath, newPath);
3664 }
3665 if ( image != NULL )
3666 return image;
3667 }
3668 }
3669 }
3670
3671 // substitute @rpath with LD_LIBRARY_PATH
3672 if ( sEnv.LD_LIBRARY_PATH != NULL ) {
3673 image = loadPhase2(trailingPath, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, cacheIndex, exceptions);
3674 if ( image != NULL )
3675 return image;
3676 }
3677
3678 // if this is the "open" pass, don't try to open @rpath/... as a relative path
3679 if ( (exceptions != NULL) && (trailingPath != path) )
3680 return NULL;
3681 }
3682 else if ( !gLinkContext.allowEnvVarsPath && (path[0] != '/' ) ) {
3683 throwf("unsafe use of relative rpath %s in %s with restricted binary", path, context.origin);
3684 }
3685
3686 return loadPhase4(path, orgPath, context, cacheIndex, exceptions);
3687 }
3688
3689 static ImageLoader* loadPhase2cache(const char* path, const char *orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions) {
3690 ImageLoader* image = NULL;
3691 #if !TARGET_OS_SIMULATOR
3692 if ( (exceptions != NULL) && (gLinkContext.allowEnvVarsPath || !isFileRelativePath(path)) && (path[0] != '@') ) {
3693 char resolvedPath[PATH_MAX];
3694 realpath(path, resolvedPath);
3695 int myerr = errno;
3696 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
3697 if ( (myerr == ENOENT) || (myerr == 0) )
3698 {
3699 image = loadPhase4(resolvedPath, orgPath, context, cacheIndex, exceptions);
3700 }
3701 }
3702 #endif
3703 return image;
3704 }
3705
3706
3707 // try search paths
3708 static ImageLoader* loadPhase2(const char* path, const char* orgPath, const LoadContext& context,
3709 const char* const frameworkPaths[], const char* const libraryPaths[],
3710 unsigned& cacheIndex, std::vector<const char*>* exceptions)
3711 {
3712 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3713 ImageLoader* image = NULL;
3714 const char* frameworkPartialPath = getFrameworkPartialPath(path);
3715 if ( frameworkPaths != NULL ) {
3716 if ( frameworkPartialPath != NULL ) {
3717 const size_t frameworkPartialPathLen = strlen(frameworkPartialPath);
3718 for(const char* const* fp = frameworkPaths; *fp != NULL; ++fp) {
3719 char npath[strlen(*fp)+frameworkPartialPathLen+8];
3720 strcpy(npath, *fp);
3721 strcat(npath, "/");
3722 strcat(npath, frameworkPartialPath);
3723 //dyld::log("dyld: fallback framework path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, npath);
3724 image = loadPhase4(npath, orgPath, context, cacheIndex, exceptions);
3725 // Look in the cache if appropriate
3726 if ( image == NULL)
3727 image = loadPhase2cache(npath, orgPath, context, cacheIndex, exceptions);
3728 if ( image != NULL ) {
3729 // if original path is in the dyld cache, then mark this one found as an override
3730 dyld3::SharedCacheFindDylibResults shareCacheResults;
3731 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &shareCacheResults) && (shareCacheResults.image != nullptr) )
3732 image->setOverridesCachedDylib(shareCacheResults.image->imageNum());
3733 return image;
3734 }
3735 }
3736 }
3737 }
3738 // <rdar://problem/12649639> An executable with the same name as a framework & DYLD_LIBRARY_PATH pointing to it gets loaded twice
3739 // <rdar://problem/14160846> Some apps depend on frameworks being found via library paths
3740 if ( (libraryPaths != NULL) && ((frameworkPartialPath == NULL) || sFrameworksFoundAsDylibs) ) {
3741 const char* libraryLeafName = getLibraryLeafName(path);
3742 const size_t libraryLeafNameLen = strlen(libraryLeafName);
3743 for(const char* const* lp = libraryPaths; *lp != NULL; ++lp) {
3744 char libpath[strlen(*lp)+libraryLeafNameLen+8];
3745 strcpy(libpath, *lp);
3746 strcat(libpath, "/");
3747 strcat(libpath, libraryLeafName);
3748 //dyld::log("dyld: fallback library path used: %s() -> loadPhase4(\"%s\", ...)\n", __func__, libpath);
3749 image = loadPhase4(libpath, orgPath, context, cacheIndex, exceptions);
3750 // Look in the cache if appropriate
3751 if ( image == NULL)
3752 image = loadPhase2cache(libpath, orgPath, context, cacheIndex, exceptions);
3753 if ( image != NULL ) {
3754 // if original path is in the dyld cache, then mark this one found as an override
3755 dyld3::SharedCacheFindDylibResults shareCacheResults;
3756 if ( dyld3::findInSharedCacheImage(sSharedCacheLoadInfo, path, &shareCacheResults) && (shareCacheResults.image != nullptr) )
3757 image->setOverridesCachedDylib(shareCacheResults.image->imageNum());
3758 return image;
3759 }
3760 }
3761 }
3762 return NULL;
3763 }
3764
3765 // try search overrides and fallbacks
3766 static ImageLoader* loadPhase1(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3767 {
3768 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3769 ImageLoader* image = NULL;
3770
3771 bool pathIsInDyldCacheWhichCannotBeOverridden = false;
3772 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
3773 pathIsInDyldCacheWhichCannotBeOverridden = sSharedCacheLoadInfo.loadAddress->hasNonOverridablePath(path);
3774 }
3775
3776 // <rdar://problem/48490116> dyld customer cache cannot be overridden
3777 if ( !pathIsInDyldCacheWhichCannotBeOverridden ) {
3778 // handle LD_LIBRARY_PATH environment variables that force searching
3779 if ( context.useLdLibraryPath && (sEnv.LD_LIBRARY_PATH != NULL) ) {
3780 image = loadPhase2(path, orgPath, context, NULL, sEnv.LD_LIBRARY_PATH, cacheIndex,exceptions);
3781 if ( image != NULL )
3782 return image;
3783 }
3784
3785 // handle DYLD_ environment variables that force searching
3786 if ( context.useSearchPaths && ((sEnv.DYLD_FRAMEWORK_PATH != NULL) || (sEnv.DYLD_LIBRARY_PATH != NULL)) ) {
3787 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FRAMEWORK_PATH, sEnv.DYLD_LIBRARY_PATH, cacheIndex, exceptions);
3788 if ( image != NULL )
3789 return image;
3790 }
3791 }
3792
3793 // try raw path
3794 image = loadPhase3(path, orgPath, context, cacheIndex, exceptions);
3795 if ( image != NULL )
3796 return image;
3797
3798 // try fallback paths during second time (will open file)
3799 const char* const* fallbackLibraryPaths = sEnv.DYLD_FALLBACK_LIBRARY_PATH;
3800 if ( (fallbackLibraryPaths != NULL) && !context.useFallbackPaths )
3801 fallbackLibraryPaths = NULL;
3802 if ( !context.dontLoad && (exceptions != NULL) && ((sEnv.DYLD_FALLBACK_FRAMEWORK_PATH != NULL) || (fallbackLibraryPaths != NULL)) ) {
3803 image = loadPhase2(path, orgPath, context, sEnv.DYLD_FALLBACK_FRAMEWORK_PATH, fallbackLibraryPaths, cacheIndex, exceptions);
3804 if ( image != NULL )
3805 return image;
3806 }
3807
3808 // <rdar://problem/47682983> if hardened app calls dlopen() with a leaf path, dyld should only look in /usr/lib
3809 if ( context.useLdLibraryPath && (fallbackLibraryPaths == NULL) ) {
3810 const char* stdPaths[2] = { "/usr/lib", NULL };
3811 image = loadPhase2(path, orgPath, context, NULL, stdPaths, cacheIndex, exceptions);
3812 if ( image != NULL )
3813 return image;
3814 }
3815
3816 return NULL;
3817 }
3818
3819 // try root substitutions
3820 static ImageLoader* loadPhase0(const char* path, const char* orgPath, const LoadContext& context, unsigned& cacheIndex, std::vector<const char*>* exceptions)
3821 {
3822 //dyld::log("%s(%s, %p)\n", __func__ , path, exceptions);
3823
3824 #if __MAC_OS_X_VERSION_MIN_REQUIRED
3825 // handle macOS dylibs dlopen()ing versioned path which needs to map to flat path in mazipan simulator
3826 if ( gLinkContext.iOSonMac && strstr(path, ".framework/Versions/")) {
3827 uintptr_t sourceOffset = 0;
3828 uintptr_t destOffset = 0;
3829 size_t sourceLangth = strlen(path);
3830 char flatPath[sourceLangth];
3831 flatPath[0] = 0;
3832 const char* frameworkBase = NULL;
3833 while ((frameworkBase = strstr(&path[sourceOffset], ".framework/Versions/"))) {
3834 uintptr_t foundLength = (frameworkBase - &path[sourceOffset]) + strlen(".framework/") ;
3835 strlcat(&flatPath[destOffset], &path[sourceOffset], foundLength);
3836 sourceOffset += foundLength + strlen("Versions/") + 1;
3837 destOffset += foundLength - 1;
3838 }
3839 strlcat(&flatPath[destOffset], &path[sourceOffset], sourceLangth);
3840 ImageLoader* image = loadPhase0(flatPath, orgPath, context, cacheIndex, exceptions);
3841 if ( image != NULL )
3842 return image;
3843 }
3844 #endif
3845
3846 #if SUPPORT_ROOT_PATH
3847 // handle DYLD_ROOT_PATH which forces absolute paths to use a new root
3848 if ( (gLinkContext.rootPaths != NULL) && (path[0] == '/') ) {
3849 for(const char* const* rootPath = gLinkContext.rootPaths; *rootPath != NULL; ++rootPath) {
3850 size_t rootLen = strlen(*rootPath);
3851 if ( strncmp(path, *rootPath, rootLen) != 0 ) {
3852 char newPath[rootLen + strlen(path)+2];
3853 strcpy(newPath, *rootPath);
3854 strcat(newPath, path);
3855 ImageLoader* image = loadPhase1(newPath, orgPath, context, cacheIndex, exceptions);
3856 if ( image != NULL )
3857 return image;
3858 }
3859 }
3860 }
3861 #endif
3862
3863 // try raw path
3864 return loadPhase1(path, orgPath, context, cacheIndex, exceptions);
3865 }
3866
3867 //
3868 // Given all the DYLD_ environment variables, the general case for loading libraries
3869 // is that any given path expands into a list of possible locations to load. We
3870 // also must take care to ensure two copies of the "same" library are never loaded.
3871 //
3872 // The algorithm used here is that there is a separate function for each "phase" of the
3873 // path expansion. Each phase function calls the next phase with each possible expansion
3874 // of that phase. The result is the last phase is called with all possible paths.
3875 //
3876 // To catch duplicates the algorithm is run twice. The first time, the last phase checks
3877 // the path against all loaded images. The second time, the last phase calls open() on
3878 // the path. Either time, if an image is found, the phases all unwind without checking
3879 // for other paths.
3880 //
3881 ImageLoader* load(const char* path, const LoadContext& context, unsigned& cacheIndex)
3882 {
3883 CRSetCrashLogMessage2(path);
3884 const char* orgPath = path;
3885 cacheIndex = UINT32_MAX;
3886
3887 //dyld::log("%s(%s)\n", __func__ , path);
3888 char realPath[PATH_MAX];
3889 // when DYLD_IMAGE_SUFFIX is in used, do a realpath(), otherwise a load of "Foo.framework/Foo" will not match
3890 if ( context.useSearchPaths && ( gLinkContext.imageSuffix != NULL && *gLinkContext.imageSuffix != NULL) ) {
3891 if ( realpath(path, realPath) != NULL )
3892 path = realPath;
3893 }
3894
3895 // try all path permutations and check against existing loaded images
3896
3897 ImageLoader* image = loadPhase0(path, orgPath, context, cacheIndex, NULL);
3898 if ( image != NULL ) {
3899 CRSetCrashLogMessage2(NULL);
3900 return image;
3901 }
3902
3903 // try all path permutations and try open() until first success
3904 std::vector<const char*> exceptions;
3905 image = loadPhase0(path, orgPath, context, cacheIndex, &exceptions);
3906 #if !TARGET_OS_SIMULATOR
3907 // <rdar://problem/16704628> support symlinks on disk to a path in dyld shared cache
3908 if ( image == NULL)
3909 image = loadPhase2cache(path, orgPath, context, cacheIndex, &exceptions);
3910 #endif
3911 CRSetCrashLogMessage2(NULL);
3912 if ( image != NULL ) {
3913 // <rdar://problem/6916014> leak in dyld during dlopen when using DYLD_ variables
3914 for (std::vector<const char*>::iterator it = exceptions.begin(); it != exceptions.end(); ++it) {
3915 free((void*)(*it));
3916 }
3917 // if loaded image is not from cache, but original path is in cache
3918 // set gSharedCacheOverridden flag to disable some ObjC optimizations
3919 if ( !gSharedCacheOverridden && !image->inSharedCache() && image->isDylib() && dyld3::MachOFile::isSharedCacheEligiblePath(path) && inSharedCache(path) ) {
3920 gSharedCacheOverridden = true;
3921 }
3922 return image;
3923 }
3924 else if ( exceptions.size() == 0 ) {
3925 if ( context.dontLoad ) {
3926 return NULL;
3927 }
3928 else
3929 throw "image not found";
3930 }
3931 else {
3932 const char* msgStart = "no suitable image found. Did find:";
3933 const char* delim = "\n\t";
3934 size_t allsizes = strlen(msgStart)+8;
3935 for (size_t i=0; i < exceptions.size(); ++i)
3936 allsizes += (strlen(exceptions[i]) + strlen(delim));
3937 char* fullMsg = new char[allsizes];
3938 strcpy(fullMsg, msgStart);
3939 for (size_t i=0; i < exceptions.size(); ++i) {
3940 strcat(fullMsg, delim);
3941 strcat(fullMsg, exceptions[i]);
3942 free((void*)exceptions[i]);
3943 }
3944 throw (const char*)fullMsg;
3945 }
3946 }
3947
3948
3949
3950
3951
3952 static void mapSharedCache()
3953 {
3954 dyld3::SharedCacheOptions opts;
3955 opts.cacheDirOverride = sSharedCacheOverrideDir;
3956 opts.forcePrivate = (gLinkContext.sharedRegionMode == ImageLoader::kUsePrivateSharedRegion);
3957
3958
3959 #if __x86_64__ && !TARGET_OS_SIMULATOR
3960 opts.useHaswell = sHaswell;
3961 #else
3962 opts.useHaswell = false;
3963 #endif
3964 opts.verbose = gLinkContext.verboseMapping;
3965 loadDyldCache(opts, &sSharedCacheLoadInfo);
3966
3967 // update global state
3968 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
3969 gLinkContext.dyldCache = sSharedCacheLoadInfo.loadAddress;
3970 dyld::gProcessInfo->processDetachedFromSharedRegion = opts.forcePrivate;
3971 dyld::gProcessInfo->sharedCacheSlide = sSharedCacheLoadInfo.slide;
3972 dyld::gProcessInfo->sharedCacheBaseAddress = (unsigned long)sSharedCacheLoadInfo.loadAddress;
3973 sSharedCacheLoadInfo.loadAddress->getUUID(dyld::gProcessInfo->sharedCacheUUID);
3974 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_SHARED_CACHE_A, sSharedCacheLoadInfo.path, (const uuid_t *)&dyld::gProcessInfo->sharedCacheUUID[0], {0,0}, {{ 0, 0 }}, (const mach_header *)sSharedCacheLoadInfo.loadAddress);
3975 }
3976
3977 //#if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
3978 // RAM disk booting does not have shared cache yet
3979 // Don't make lack of a shared cache fatal in that case
3980 // if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
3981 // if ( sSharedCacheLoadInfo.errorMessage != nullptr )
3982 // halt(sSharedCacheLoadInfo.errorMessage);
3983 // else
3984 // halt("error loading dyld shared cache");
3985 // }
3986 //#endif
3987 }
3988
3989
3990
3991 // create when NSLinkModule is called for a second time on a bundle
3992 ImageLoader* cloneImage(ImageLoader* image)
3993 {
3994 // open file (automagically closed when this function exits)
3995 FileOpener file(image->getPath());
3996
3997 struct stat stat_buf;
3998 if ( fstat(file.getFileDescriptor(), &stat_buf) == -1)
3999 throw "stat error";
4000
4001 dyld::LoadContext context;
4002 context.useSearchPaths = false;
4003 context.useFallbackPaths = false;
4004 context.useLdLibraryPath = false;
4005 context.implicitRPath = false;
4006 context.matchByInstallName = false;
4007 context.dontLoad = false;
4008 context.mustBeBundle = true;
4009 context.mustBeDylib = false;
4010 context.canBePIE = false;
4011 context.origin = NULL;
4012 context.rpath = NULL;
4013 return loadPhase6(file.getFileDescriptor(), stat_buf, image->getPath(), context);
4014 }
4015
4016
4017 ImageLoader* loadFromMemory(const uint8_t* mem, uint64_t len, const char* moduleName)
4018 {
4019 // if fat wrapper, find usable sub-file
4020 const fat_header* memStartAsFat = (fat_header*)mem;
4021 uint64_t fileOffset = 0;
4022 uint64_t fileLength = len;
4023 if ( memStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4024 if ( fatFindBest(memStartAsFat, &fileOffset, &fileLength) ) {
4025 mem = &mem[fileOffset];
4026 len = fileLength;
4027 }
4028 else {
4029 throw "no matching architecture in universal wrapper";
4030 }
4031 }
4032
4033 // try each loader
4034 if ( isCompatibleMachO(mem, moduleName) ) {
4035 ImageLoader* image = ImageLoaderMachO::instantiateFromMemory(moduleName, (macho_header*)mem, len, gLinkContext);
4036 // don't add bundles to global list, they can be loaded but not linked. When linked it will be added to list
4037 if ( ! image->isBundle() )
4038 addImage(image);
4039 return image;
4040 }
4041
4042 // try other file formats here...
4043
4044 // throw error about what was found
4045 switch (*(uint32_t*)mem) {
4046 case MH_MAGIC:
4047 case MH_CIGAM:
4048 case MH_MAGIC_64:
4049 case MH_CIGAM_64:
4050 throw "mach-o, but wrong architecture";
4051 default:
4052 throwf("unknown file type, first eight bytes: 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X 0x%02X",
4053 mem[0], mem[1], mem[2], mem[3], mem[4], mem[5], mem[6],mem[7]);
4054 }
4055 }
4056
4057
4058 void registerAddCallback(ImageCallback func)
4059 {
4060 // now add to list to get notified when any more images are added
4061 sAddImageCallbacks.push_back(func);
4062
4063 // call callback with all existing images
4064 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4065 ImageLoader* image = *it;
4066 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated ) {
4067 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)image->machHeader(), (uint64_t)(*func), 0);
4068 (*func)(image->machHeader(), image->getSlide());
4069 }
4070 }
4071 #if SUPPORT_ACCELERATE_TABLES
4072 if ( sAllCacheImagesProxy != NULL ) {
4073 dyld_image_info infos[allImagesCount()+1];
4074 unsigned cacheCount = sAllCacheImagesProxy->appendImagesToNotify(dyld_image_state_bound, true, infos);
4075 for (unsigned i=0; i < cacheCount; ++i) {
4076 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)infos[i].imageLoadAddress, (uint64_t)(*func), 0);
4077 (*func)(infos[i].imageLoadAddress, sSharedCacheLoadInfo.slide);
4078 }
4079 }
4080 #endif
4081 }
4082
4083 void registerLoadCallback(LoadImageCallback func)
4084 {
4085 // now add to list to get notified when any more images are added
4086 sAddLoadImageCallbacks.push_back(func);
4087
4088 // call callback with all existing images
4089 for (ImageLoader* image : sAllImages) {
4090 if ( image->getState() >= dyld_image_state_bound && image->getState() < dyld_image_state_terminated ) {
4091 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)image->machHeader(), (uint64_t)(*func), 0);
4092 (*func)(image->machHeader(), image->getPath(), !image->neverUnload());
4093 }
4094 }
4095 #if SUPPORT_ACCELERATE_TABLES
4096 if ( sAllCacheImagesProxy != NULL ) {
4097 dyld_image_info infos[allImagesCount()+1];
4098 unsigned cacheCount = sAllCacheImagesProxy->appendImagesToNotify(dyld_image_state_bound, true, infos);
4099 for (unsigned i=0; i < cacheCount; ++i) {
4100 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)infos[i].imageLoadAddress, (uint64_t)(*func), 0);
4101 (*func)(infos[i].imageLoadAddress, infos[i].imageFilePath, false);
4102 }
4103 }
4104 #endif
4105 }
4106
4107 void registerBulkLoadCallback(LoadImageBulkCallback func)
4108 {
4109 // call callback with all existing images
4110 unsigned count = dyld::gProcessInfo->infoArrayCount;
4111 const dyld_image_info* infoArray = dyld::gProcessInfo->infoArray;
4112 if ( infoArray != NULL ) {
4113 const mach_header* mhs[count];
4114 const char* paths[count];
4115 for (unsigned i=0; i < count; ++i) {
4116 mhs[i] = infoArray[i].imageLoadAddress;
4117 paths[i] = infoArray[i].imageFilePath;
4118 }
4119 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_FUNC_FOR_ADD_IMAGE, (uint64_t)mhs[0], (uint64_t)func, 0);
4120 func(count, mhs, paths);
4121 }
4122
4123 // now add to list to get notified when any more images are added
4124 sAddBulkLoadImageCallbacks.push_back(func);
4125 }
4126
4127 void registerRemoveCallback(ImageCallback func)
4128 {
4129 // <rdar://problem/15025198> ignore calls to register a notification during a notification
4130 if ( sRemoveImageCallbacksInUse )
4131 return;
4132 sRemoveImageCallbacks.push_back(func);
4133 }
4134
4135 void clearErrorMessage()
4136 {
4137 error_string[0] = '\0';
4138 }
4139
4140 void setErrorMessage(const char* message)
4141 {
4142 // save off error message in global buffer for CrashReporter to find
4143 strlcpy(error_string, message, sizeof(error_string));
4144 }
4145
4146 const char* getErrorMessage()
4147 {
4148 return error_string;
4149 }
4150
4151 void halt(const char* message)
4152 {
4153 if ( sSharedCacheLoadInfo.errorMessage != nullptr ) {
4154 // <rdar://problem/45957449> if dyld fails with a missing dylib and there is no shared cache, display the shared cache load error message
4155 dyld::log("dyld: dyld cache load error: %s\n", sSharedCacheLoadInfo.errorMessage);
4156 dyld::log("dyld: %s\n", message);
4157 strlcpy(error_string, "dyld cache load error: ", sizeof(error_string));
4158 strlcat(error_string, sSharedCacheLoadInfo.errorMessage, sizeof(error_string));
4159 strlcat(error_string, "\n", sizeof(error_string));
4160 strlcat(error_string, message, sizeof(error_string));
4161 }
4162 else {
4163 dyld::log("dyld: %s\n", message);
4164 strlcpy(error_string, message, sizeof(error_string));
4165 }
4166
4167 dyld::gProcessInfo->errorMessage = error_string;
4168 if ( !gLinkContext.startedInitializingMainExecutable )
4169 dyld::gProcessInfo->terminationFlags = 1;
4170 else
4171 dyld::gProcessInfo->terminationFlags = 0;
4172
4173 char payloadBuffer[EXIT_REASON_PAYLOAD_MAX_LEN];
4174 dyld_abort_payload* payload = (dyld_abort_payload*)payloadBuffer;
4175 payload->version = 1;
4176 payload->flags = gLinkContext.startedInitializingMainExecutable ? 0 : 1;
4177 payload->targetDylibPathOffset = 0;
4178 payload->clientPathOffset = 0;
4179 payload->symbolOffset = 0;
4180 int payloadSize = sizeof(dyld_abort_payload);
4181
4182 if ( dyld::gProcessInfo->errorTargetDylibPath != NULL ) {
4183 payload->targetDylibPathOffset = payloadSize;
4184 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorTargetDylibPath, sizeof(payloadBuffer)-payloadSize) + 1;
4185 }
4186 if ( dyld::gProcessInfo->errorClientOfDylibPath != NULL ) {
4187 payload->clientPathOffset = payloadSize;
4188 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorClientOfDylibPath, sizeof(payloadBuffer)-payloadSize) + 1;
4189 }
4190 if ( dyld::gProcessInfo->errorSymbol != NULL ) {
4191 payload->symbolOffset = payloadSize;
4192 payloadSize += strlcpy(&payloadBuffer[payloadSize], dyld::gProcessInfo->errorSymbol, sizeof(payloadBuffer)-payloadSize) + 1;
4193 }
4194 char truncMessage[EXIT_REASON_USER_DESC_MAX_LEN];
4195 strlcpy(truncMessage, error_string, EXIT_REASON_USER_DESC_MAX_LEN);
4196 abort_with_payload(OS_REASON_DYLD, dyld::gProcessInfo->errorKind ? dyld::gProcessInfo->errorKind : DYLD_EXIT_REASON_OTHER, payloadBuffer, payloadSize, truncMessage, 0);
4197 }
4198
4199 static void setErrorStrings(unsigned errorCode, const char* errorClientOfDylibPath,
4200 const char* errorTargetDylibPath, const char* errorSymbol)
4201 {
4202 dyld::gProcessInfo->errorKind = errorCode;
4203 dyld::gProcessInfo->errorClientOfDylibPath = errorClientOfDylibPath;
4204 dyld::gProcessInfo->errorTargetDylibPath = errorTargetDylibPath;
4205 dyld::gProcessInfo->errorSymbol = errorSymbol;
4206 }
4207
4208
4209 uintptr_t bindLazySymbol(const mach_header* mh, uintptr_t* lazyPointer)
4210 {
4211 uintptr_t result = 0;
4212 // acquire read-lock on dyld's data structures
4213 #if 0 // rdar://problem/3811777 turn off locking until deadlock is resolved
4214 if ( gLibSystemHelpers != NULL )
4215 (*gLibSystemHelpers->lockForReading)();
4216 #endif
4217 // lookup and bind lazy pointer and get target address
4218 try {
4219 ImageLoader* target;
4220 #if __i386__
4221 // fast stubs pass NULL for mh and image is instead found via the location of stub (aka lazyPointer)
4222 if ( mh == NULL )
4223 target = dyld::findImageContainingAddress(lazyPointer);
4224 else
4225 target = dyld::findImageByMachHeader(mh);
4226 #else
4227 // note, target should always be mach-o, because only mach-o lazy handler wired up to this
4228 target = dyld::findImageByMachHeader(mh);
4229 #endif
4230 if ( target == NULL )
4231 throwf("image not found for lazy pointer at %p", lazyPointer);
4232 result = target->doBindLazySymbol(lazyPointer, gLinkContext);
4233 }
4234 catch (const char* message) {
4235 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
4236 halt(message);
4237 }
4238 // release read-lock on dyld's data structures
4239 #if 0
4240 if ( gLibSystemHelpers != NULL )
4241 (*gLibSystemHelpers->unlockForReading)();
4242 #endif
4243 // return target address to glue which jumps to it with real parameters restored
4244 return result;
4245 }
4246
4247
4248 uintptr_t fastBindLazySymbol(ImageLoader** imageLoaderCache, uintptr_t lazyBindingInfoOffset)
4249 {
4250 uintptr_t result = 0;
4251 // get image
4252 if ( *imageLoaderCache == NULL ) {
4253 // save in cache
4254 *imageLoaderCache = dyld::findMappedRange((uintptr_t)imageLoaderCache);
4255 if ( *imageLoaderCache == NULL ) {
4256 #if SUPPORT_ACCELERATE_TABLES
4257 if ( sAllCacheImagesProxy != NULL ) {
4258 const mach_header* mh;
4259 const char* path;
4260 unsigned index;
4261 if ( sAllCacheImagesProxy->addressInCache(imageLoaderCache, &mh, &path, &index) ) {
4262 result = sAllCacheImagesProxy->bindLazy(lazyBindingInfoOffset, gLinkContext, mh, index);
4263 if ( result == 0 ) {
4264 halt("dyld: lazy symbol binding failed for image in dyld shared\n");
4265 }
4266 return result;
4267 }
4268 }
4269 #endif
4270 const char* message = "fast lazy binding from unknown image";
4271 dyld::log("dyld: %s\n", message);
4272 halt(message);
4273 }
4274 }
4275
4276 // bind lazy pointer and return it
4277 try {
4278 result = (*imageLoaderCache)->doBindFastLazySymbol((uint32_t)lazyBindingInfoOffset, gLinkContext,
4279 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->acquireGlobalDyldLock : NULL,
4280 (dyld::gLibSystemHelpers != NULL) ? dyld::gLibSystemHelpers->releaseGlobalDyldLock : NULL);
4281 }
4282 catch (const char* message) {
4283 dyld::log("dyld: lazy symbol binding failed: %s\n", message);
4284 halt(message);
4285 }
4286
4287 // return target address to glue which jumps to it with real parameters restored
4288 return result;
4289 }
4290
4291
4292
4293 void registerUndefinedHandler(UndefinedHandler handler)
4294 {
4295 sUndefinedHandler = handler;
4296 }
4297
4298 static void undefinedHandler(const char* symboName)
4299 {
4300 if ( sUndefinedHandler != NULL ) {
4301 (*sUndefinedHandler)(symboName);
4302 }
4303 }
4304
4305 static bool findExportedSymbol(const char* name, bool onlyInCoalesced, const ImageLoader::Symbol** sym, const ImageLoader** image, ImageLoader::CoalesceNotifier notifier=NULL)
4306 {
4307 // search all images in order
4308 const ImageLoader* firstWeakImage = NULL;
4309 const ImageLoader::Symbol* firstWeakSym = NULL;
4310 const ImageLoader* firstNonWeakImage = NULL;
4311 const ImageLoader::Symbol* firstNonWeakSym = NULL;
4312 const size_t imageCount = sAllImages.size();
4313 for(size_t i=0; i < imageCount; ++i) {
4314 ImageLoader* anImage = sAllImages[i];
4315 // the use of inserted libraries alters search order
4316 // so that inserted libraries are found before the main executable
4317 if ( sInsertedDylibCount > 0 ) {
4318 if ( i < sInsertedDylibCount )
4319 anImage = sAllImages[i+1];
4320 else if ( i == sInsertedDylibCount )
4321 anImage = sAllImages[0];
4322 }
4323 //dyld::log("findExportedSymbol(%s) looking at %s\n", name, anImage->getPath());
4324 if ( ! anImage->hasHiddenExports() && (!onlyInCoalesced || anImage->hasCoalescedExports()) ) {
4325 const ImageLoader* foundInImage;
4326 *sym = anImage->findExportedSymbol(name, false, &foundInImage);
4327 //dyld::log("findExportedSymbol(%s) found: sym=%p, anImage=%p, foundInImage=%p\n", name, *sym, anImage, foundInImage /*, (foundInImage ? foundInImage->getPath() : "")*/);
4328 if ( *sym != NULL ) {
4329 if ( notifier && (foundInImage == anImage) )
4330 notifier(*sym, foundInImage, foundInImage->machHeader());
4331 // if weak definition found, record first one found
4332 if ( (foundInImage->getExportedSymbolInfo(*sym) & ImageLoader::kWeakDefinition) != 0 ) {
4333 if ( firstWeakImage == NULL ) {
4334 firstWeakImage = foundInImage;
4335 firstWeakSym = *sym;
4336 }
4337 }
4338 else {
4339 // found non-weak
4340 if ( !onlyInCoalesced ) {
4341 // for flat lookups, return first found
4342 *image = foundInImage;
4343 return true;
4344 }
4345 if ( firstNonWeakImage == NULL ) {
4346 firstNonWeakImage = foundInImage;
4347 firstNonWeakSym = *sym;
4348 }
4349 }
4350 }
4351 }
4352 }
4353 if ( firstNonWeakImage != NULL ) {
4354 // found a weak definition, but no non-weak, so return first weak found
4355 *sym = firstNonWeakSym;
4356 *image = firstNonWeakImage;
4357 return true;
4358 }
4359 if ( firstWeakSym != NULL ) {
4360 // found a weak definition, but no non-weak, so return first weak found
4361 *sym = firstWeakSym;
4362 *image = firstWeakImage;
4363 return true;
4364 }
4365 #if SUPPORT_ACCELERATE_TABLES
4366 if ( sAllCacheImagesProxy != NULL ) {
4367 if ( sAllCacheImagesProxy->flatFindSymbol(name, onlyInCoalesced, sym, image, notifier) )
4368 return true;
4369 }
4370 #endif
4371
4372 return false;
4373 }
4374
4375 bool flatFindExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image)
4376 {
4377 return findExportedSymbol(name, false, sym, image);
4378 }
4379
4380 bool findCoalescedExportedSymbol(const char* name, const ImageLoader::Symbol** sym, const ImageLoader** image, ImageLoader::CoalesceNotifier notifier)
4381 {
4382 return findExportedSymbol(name, true, sym, image, notifier);
4383 }
4384
4385
4386 bool flatFindExportedSymbolWithHint(const char* name, const char* librarySubstring, const ImageLoader::Symbol** sym, const ImageLoader** image)
4387 {
4388 // search all images in order
4389 const size_t imageCount = sAllImages.size();
4390 for(size_t i=0; i < imageCount; ++i){
4391 ImageLoader* anImage = sAllImages[i];
4392 // only look at images whose paths contain the hint string (NULL hint string is wildcard)
4393 if ( ! anImage->isBundle() && ((librarySubstring==NULL) || (strstr(anImage->getPath(), librarySubstring) != NULL)) ) {
4394 *sym = anImage->findExportedSymbol(name, false, image);
4395 if ( *sym != NULL ) {
4396 return true;
4397 }
4398 }
4399 }
4400 return false;
4401 }
4402
4403
4404 unsigned int getCoalescedImages(ImageLoader* images[], unsigned imageIndex[])
4405 {
4406 unsigned int count = 0;
4407 const size_t imageCount = sAllImages.size();
4408 for(size_t i=0; i < imageCount; ++i) {
4409 ImageLoader* anImage = sAllImages[i];
4410 // the use of inserted libraries alters search order
4411 // so that inserted libraries are found before the main executable
4412 if ( sInsertedDylibCount > 0 ) {
4413 if ( i < sInsertedDylibCount )
4414 anImage = sAllImages[i+1];
4415 else if ( i == sInsertedDylibCount )
4416 anImage = sAllImages[0];
4417 }
4418 if ( anImage->participatesInCoalescing() ) {
4419 images[count] = anImage;
4420 imageIndex[count] = 0;
4421 ++count;
4422 }
4423 }
4424 #if SUPPORT_ACCELERATE_TABLES
4425 if ( sAllCacheImagesProxy != NULL ) {
4426 sAllCacheImagesProxy->appendImagesNeedingCoalescing(images, imageIndex, count);
4427 }
4428 #endif
4429 return count;
4430 }
4431
4432
4433 static ImageLoader::MappedRegion* getMappedRegions(ImageLoader::MappedRegion* regions)
4434 {
4435 ImageLoader::MappedRegion* end = regions;
4436 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4437 (*it)->getMappedRegions(end);
4438 }
4439 return end;
4440 }
4441
4442 void registerImageStateSingleChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
4443 {
4444 // mark the image that the handler is in as never-unload because dyld has a reference into it
4445 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
4446 if ( handlerImage != NULL )
4447 handlerImage->setNeverUnload();
4448
4449 // add to list of handlers
4450 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sSingleHandlers);
4451 if ( handlers != NULL ) {
4452 // <rdar://problem/10332417> need updateAllImages() to be last in dyld_image_state_mapped list
4453 // so that if ObjC adds a handler that prevents a load, it happens before the gdb list is updated
4454 if ( state == dyld_image_state_mapped )
4455 handlers->insert(handlers->begin(), handler);
4456 else
4457 handlers->push_back(handler);
4458
4459 // call callback with all existing images
4460 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4461 ImageLoader* image = *it;
4462 dyld_image_info info;
4463 info.imageLoadAddress = image->machHeader();
4464 info.imageFilePath = image->getRealPath();
4465 info.imageFileModDate = image->lastModified();
4466 // should only call handler if state == image->state
4467 if ( image->getState() == state )
4468 (*handler)(state, 1, &info);
4469 // ignore returned string, too late to do anything
4470 }
4471 }
4472 }
4473
4474 void registerImageStateBatchChangeHandler(dyld_image_states state, dyld_image_state_change_handler handler)
4475 {
4476 // mark the image that the handler is in as never-unload because dyld has a reference into it
4477 ImageLoader* handlerImage = findImageContainingAddress((void*)handler);
4478 if ( handlerImage != NULL )
4479 handlerImage->setNeverUnload();
4480
4481 // add to list of handlers
4482 std::vector<dyld_image_state_change_handler>* handlers = stateToHandlers(state, sBatchHandlers);
4483 if ( handlers != NULL ) {
4484 // insert at front, so that gdb handler is always last
4485 handlers->insert(handlers->begin(), handler);
4486
4487 // call callback with all existing images
4488 try {
4489 notifyBatchPartial(state, true, handler, false, false);
4490 }
4491 catch (const char* msg) {
4492 // ignore request to abort during registration
4493 }
4494 }
4495 }
4496
4497
4498 void registerObjCNotifiers(_dyld_objc_notify_mapped mapped, _dyld_objc_notify_init init, _dyld_objc_notify_unmapped unmapped)
4499 {
4500 // record functions to call
4501 sNotifyObjCMapped = mapped;
4502 sNotifyObjCInit = init;
4503 sNotifyObjCUnmapped = unmapped;
4504
4505 // call 'mapped' function with all images mapped so far
4506 try {
4507 notifyBatchPartial(dyld_image_state_bound, true, NULL, false, true);
4508 }
4509 catch (const char* msg) {
4510 // ignore request to abort during registration
4511 }
4512
4513 // <rdar://problem/32209809> call 'init' function on all images already init'ed (below libSystem)
4514 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4515 ImageLoader* image = *it;
4516 if ( (image->getState() == dyld_image_state_initialized) && image->notifyObjC() ) {
4517 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_OBJC_INIT, (uint64_t)image->machHeader(), 0, 0);
4518 (*sNotifyObjCInit)(image->getRealPath(), image->machHeader());
4519 }
4520 }
4521 }
4522
4523 bool sharedCacheUUID(uuid_t uuid)
4524 {
4525 if ( sSharedCacheLoadInfo.loadAddress == nullptr )
4526 return false;
4527
4528 sSharedCacheLoadInfo.loadAddress->getUUID(uuid);
4529 return true;
4530 }
4531
4532 #if SUPPORT_ACCELERATE_TABLES
4533
4534 bool dlopenFromCache(const char* path, int mode, void** handle)
4535 {
4536 if ( sAllCacheImagesProxy == NULL )
4537 return false;
4538 char fallbackPath[PATH_MAX];
4539 bool result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, path, mode, handle);
4540 if ( !result && (strchr(path, '/') == NULL) ) {
4541 // POSIX says you can call dlopen() with a leaf name (e.g. dlopen("libz.dylb"))
4542 strcpy(fallbackPath, "/usr/lib/");
4543 strlcat(fallbackPath, path, PATH_MAX);
4544 result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, fallbackPath, mode, handle);
4545 if ( !result )
4546 path = fallbackPath;
4547 }
4548 if ( !result ) {
4549 // leaf name could be a symlink
4550 char resolvedPath[PATH_MAX];
4551 realpath(path, resolvedPath);
4552 int realpathErrno = errno;
4553 // If realpath() resolves to a path which does not exist on disk, errno is set to ENOENT
4554 if ( (realpathErrno == ENOENT) || (realpathErrno == 0) ) {
4555 result = sAllCacheImagesProxy->dlopenFromCache(gLinkContext, resolvedPath, mode, handle);
4556 }
4557 }
4558
4559 return result;
4560 }
4561
4562 bool makeCacheHandle(ImageLoader* image, unsigned cacheIndex, int mode, void** result)
4563 {
4564 if ( sAllCacheImagesProxy == NULL )
4565 return false;
4566 return sAllCacheImagesProxy->makeCacheHandle(gLinkContext, cacheIndex, mode, result);
4567 }
4568
4569 bool isCacheHandle(void* handle)
4570 {
4571 if ( sAllCacheImagesProxy == NULL )
4572 return false;
4573 return sAllCacheImagesProxy->isCacheHandle(handle, NULL, NULL);
4574 }
4575
4576 bool isPathInCache(const char* path)
4577 {
4578 if ( sAllCacheImagesProxy == NULL )
4579 return false;
4580 unsigned index;
4581 return sAllCacheImagesProxy->hasDylib(path, &index);
4582 }
4583
4584 const char* getPathFromIndex(unsigned cacheIndex)
4585 {
4586 if ( sAllCacheImagesProxy == NULL )
4587 return NULL;
4588 return sAllCacheImagesProxy->getIndexedPath(cacheIndex);
4589 }
4590
4591 void* dlsymFromCache(void* handle, const char* symName, unsigned index)
4592 {
4593 if ( sAllCacheImagesProxy == NULL )
4594 return NULL;
4595 return sAllCacheImagesProxy->dlsymFromCache(gLinkContext, handle, symName, index);
4596 }
4597
4598 bool addressInCache(const void* address, const mach_header** mh, const char** path, unsigned* index)
4599 {
4600 if ( sAllCacheImagesProxy == NULL )
4601 return false;
4602 unsigned ignore;
4603 return sAllCacheImagesProxy->addressInCache(address, mh, path, index ? index : &ignore);
4604 }
4605
4606 bool findUnwindSections(const void* addr, dyld_unwind_sections* info)
4607 {
4608 if ( sAllCacheImagesProxy == NULL )
4609 return false;
4610 return sAllCacheImagesProxy->findUnwindSections(addr, info);
4611 }
4612
4613 bool dladdrFromCache(const void* address, Dl_info* info)
4614 {
4615 if ( sAllCacheImagesProxy == NULL )
4616 return false;
4617 return sAllCacheImagesProxy->dladdrFromCache(address, info);
4618 }
4619 #endif
4620
4621 static ImageLoader* libraryLocator(const char* libraryName, bool search, const char* origin, const ImageLoader::RPathChain* rpaths, unsigned& cacheIndex)
4622 {
4623 dyld::LoadContext context;
4624 context.useSearchPaths = search;
4625 context.useFallbackPaths = search;
4626 context.useLdLibraryPath = false;
4627 context.implicitRPath = false;
4628 context.matchByInstallName = false;
4629 context.dontLoad = false;
4630 context.mustBeBundle = false;
4631 context.mustBeDylib = true;
4632 context.canBePIE = false;
4633 context.origin = origin;
4634 context.rpath = rpaths;
4635 return load(libraryName, context, cacheIndex);
4636 }
4637
4638 static const char* basename(const char* path)
4639 {
4640 const char* last = path;
4641 for (const char* s = path; *s != '\0'; s++) {
4642 if (*s == '/')
4643 last = s+1;
4644 }
4645 return last;
4646 }
4647
4648 static void setContext(const macho_header* mainExecutableMH, int argc, const char* argv[], const char* envp[], const char* apple[])
4649 {
4650 gLinkContext.loadLibrary = &libraryLocator;
4651 gLinkContext.terminationRecorder = &terminationRecorder;
4652 gLinkContext.flatExportFinder = &flatFindExportedSymbol;
4653 gLinkContext.coalescedExportFinder = &findCoalescedExportedSymbol;
4654 gLinkContext.getCoalescedImages = &getCoalescedImages;
4655 gLinkContext.undefinedHandler = &undefinedHandler;
4656 gLinkContext.getAllMappedRegions = &getMappedRegions;
4657 gLinkContext.bindingHandler = NULL;
4658 gLinkContext.notifySingle = &notifySingle;
4659 gLinkContext.notifyBatch = &notifyBatch;
4660 gLinkContext.removeImage = &removeImage;
4661 gLinkContext.registerDOFs = dyld3::Loader::dtraceUserProbesEnabled() ? &registerDOFs : NULL;
4662 gLinkContext.clearAllDepths = &clearAllDepths;
4663 gLinkContext.printAllDepths = &printAllDepths;
4664 gLinkContext.imageCount = &imageCount;
4665 gLinkContext.setNewProgramVars = &setNewProgramVars;
4666 gLinkContext.inSharedCache = &inSharedCache;
4667 gLinkContext.setErrorStrings = &setErrorStrings;
4668 #if SUPPORT_OLD_CRT_INITIALIZATION
4669 gLinkContext.setRunInitialzersOldWay= &setRunInitialzersOldWay;
4670 #endif
4671 gLinkContext.findImageContainingAddress = &findImageContainingAddress;
4672 gLinkContext.addDynamicReference = &addDynamicReference;
4673 #if SUPPORT_ACCELERATE_TABLES
4674 gLinkContext.notifySingleFromCache = &notifySingleFromCache;
4675 gLinkContext.getPreInitNotifyHandler= &getPreInitNotifyHandler;
4676 gLinkContext.getBoundBatchHandler = &getBoundBatchHandler;
4677 #endif
4678 gLinkContext.bindingOptions = ImageLoader::kBindingNone;
4679 gLinkContext.argc = argc;
4680 gLinkContext.argv = argv;
4681 gLinkContext.envp = envp;
4682 gLinkContext.apple = apple;
4683 gLinkContext.progname = (argv[0] != NULL) ? basename(argv[0]) : "";
4684 gLinkContext.programVars.mh = mainExecutableMH;
4685 gLinkContext.programVars.NXArgcPtr = &gLinkContext.argc;
4686 gLinkContext.programVars.NXArgvPtr = &gLinkContext.argv;
4687 gLinkContext.programVars.environPtr = &gLinkContext.envp;
4688 gLinkContext.programVars.__prognamePtr=&gLinkContext.progname;
4689 gLinkContext.mainExecutable = NULL;
4690 gLinkContext.imageSuffix = NULL;
4691 gLinkContext.dynamicInterposeArray = NULL;
4692 gLinkContext.dynamicInterposeCount = 0;
4693 gLinkContext.prebindUsage = ImageLoader::kUseAllPrebinding;
4694 gLinkContext.sharedRegionMode = ImageLoader::kUseSharedRegion;
4695 }
4696
4697
4698
4699 //
4700 // Look for a special segment in the mach header.
4701 // Its presences means that the binary wants to have DYLD ignore
4702 // DYLD_ environment variables.
4703 //
4704 #if __MAC_OS_X_VERSION_MIN_REQUIRED
4705 static bool hasRestrictedSegment(const macho_header* mh)
4706 {
4707 const uint32_t cmd_count = mh->ncmds;
4708 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4709 const struct load_command* cmd = cmds;
4710 for (uint32_t i = 0; i < cmd_count; ++i) {
4711 switch (cmd->cmd) {
4712 case LC_SEGMENT_COMMAND:
4713 {
4714 const struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
4715
4716 //dyld::log("seg name: %s\n", seg->segname);
4717 if (strcmp(seg->segname, "__RESTRICT") == 0) {
4718 const struct macho_section* const sectionsStart = (struct macho_section*)((char*)seg + sizeof(struct macho_segment_command));
4719 const struct macho_section* const sectionsEnd = &sectionsStart[seg->nsects];
4720 for (const struct macho_section* sect=sectionsStart; sect < sectionsEnd; ++sect) {
4721 if (strcmp(sect->sectname, "__restrict") == 0)
4722 return true;
4723 }
4724 }
4725 }
4726 break;
4727 }
4728 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4729 }
4730
4731 return false;
4732 }
4733 #endif
4734
4735 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
4736 static bool isFairPlayEncrypted(const macho_header* mh)
4737 {
4738 const uint32_t cmd_count = mh->ncmds;
4739 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4740 const struct load_command* cmd = cmds;
4741 for (uint32_t i = 0; i < cmd_count; ++i) {
4742 if ( cmd->cmd == LC_ENCRYPT_COMMAND ) {
4743 const encryption_info_command* enc = (encryption_info_command*)cmd;
4744 return (enc->cryptid != 0);
4745 }
4746 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4747 }
4748
4749 return false;
4750 }
4751 #endif
4752
4753 #if SUPPORT_VERSIONED_PATHS
4754
4755 static bool readFirstPage(const char* dylibPath, uint8_t firstPage[4096])
4756 {
4757 firstPage[0] = 0;
4758 // open file (automagically closed when this function exits)
4759 FileOpener file(dylibPath);
4760
4761 if ( file.getFileDescriptor() == -1 )
4762 return false;
4763
4764 if ( pread(file.getFileDescriptor(), firstPage, 4096, 0) != 4096 )
4765 return false;
4766
4767 // if fat wrapper, find usable sub-file
4768 const fat_header* fileStartAsFat = (fat_header*)firstPage;
4769 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
4770 uint64_t fileOffset;
4771 uint64_t fileLength;
4772 if ( fatFindBest(fileStartAsFat, &fileOffset, &fileLength) ) {
4773 if ( pread(file.getFileDescriptor(), firstPage, 4096, fileOffset) != 4096 )
4774 return false;
4775 }
4776 else {
4777 return false;
4778 }
4779 }
4780
4781 return true;
4782 }
4783
4784 //
4785 // Peeks at a dylib file and returns its current_version and install_name.
4786 // Returns false on error.
4787 //
4788 static bool getDylibVersionAndInstallname(const char* dylibPath, uint32_t* version, char* installName)
4789 {
4790 uint8_t firstPage[4096];
4791 const macho_header* mh = (macho_header*)firstPage;
4792 if ( !readFirstPage(dylibPath, firstPage) ) {
4793 // If file cannot be read, check to see if path is in shared cache
4794 const macho_header* mhInCache;
4795 const char* pathInCache;
4796 long slideInCache;
4797 if ( !findInSharedCacheImage(dylibPath, true, NULL, &mhInCache, &pathInCache, &slideInCache) )
4798 return false;
4799 mh = mhInCache;
4800 }
4801
4802 // check mach-o header
4803 if ( mh->magic != sMainExecutableMachHeader->magic )
4804 return false;
4805 if ( mh->cputype != sMainExecutableMachHeader->cputype )
4806 return false;
4807
4808 // scan load commands for LC_ID_DYLIB
4809 const uint32_t cmd_count = mh->ncmds;
4810 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
4811 const struct load_command* const cmdsReadEnd = (struct load_command*)(((char*)mh)+4096);
4812 const struct load_command* cmd = cmds;
4813 for (uint32_t i = 0; i < cmd_count; ++i) {
4814 switch (cmd->cmd) {
4815 case LC_ID_DYLIB:
4816 {
4817 const struct dylib_command* id = (struct dylib_command*)cmd;
4818 *version = id->dylib.current_version;
4819 if ( installName != NULL )
4820 strlcpy(installName, (char *)id + id->dylib.name.offset, PATH_MAX);
4821 return true;
4822 }
4823 break;
4824 }
4825 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
4826 if ( cmd > cmdsReadEnd )
4827 return false;
4828 }
4829
4830 return false;
4831 }
4832 #endif // SUPPORT_VERSIONED_PATHS
4833
4834
4835 #if 0
4836 static void printAllImages()
4837 {
4838 dyld::log("printAllImages()\n");
4839 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4840 ImageLoader* image = *it;
4841 dyld_image_states imageState = image->getState();
4842 dyld::log(" state=%d, dlopen-count=%d, never-unload=%d, in-use=%d, name=%s\n",
4843 imageState, image->dlopenCount(), image->neverUnload(), image->isMarkedInUse(), image->getShortName());
4844 }
4845 }
4846 #endif
4847
4848 void link(ImageLoader* image, bool forceLazysBound, bool neverUnload, const ImageLoader::RPathChain& loaderRPaths, unsigned cacheIndex)
4849 {
4850 // add to list of known images. This did not happen at creation time for bundles
4851 if ( image->isBundle() && !image->isLinked() )
4852 addImage(image);
4853
4854 // we detect root images as those not linked in yet
4855 if ( !image->isLinked() )
4856 addRootImage(image);
4857
4858 // process images
4859 try {
4860 const char* path = image->getPath();
4861 #if SUPPORT_ACCELERATE_TABLES
4862 if ( image == sAllCacheImagesProxy )
4863 path = sAllCacheImagesProxy->getIndexedPath(cacheIndex);
4864 #endif
4865 image->link(gLinkContext, forceLazysBound, false, neverUnload, loaderRPaths, path);
4866 }
4867 catch (const char* msg) {
4868 garbageCollectImages();
4869 throw;
4870 }
4871 }
4872
4873
4874 void runInitializers(ImageLoader* image)
4875 {
4876 // do bottom up initialization
4877 ImageLoader::InitializerTimingList initializerTimes[allImagesCount()];
4878 initializerTimes[0].count = 0;
4879 image->runInitializers(gLinkContext, initializerTimes[0]);
4880 }
4881
4882 // This function is called at the end of dlclose() when the reference count goes to zero.
4883 // The dylib being unloaded may have brought in other dependent dylibs when it was loaded.
4884 // Those dependent dylibs need to be unloaded, but only if they are not referenced by
4885 // something else. We use a standard mark and sweep garbage collection.
4886 //
4887 // The tricky part is that when a dylib is unloaded it may have a termination function that
4888 // can run and itself call dlclose() on yet another dylib. The problem is that this
4889 // sort of gabage collection is not re-entrant. Instead a terminator's call to dlclose()
4890 // which calls garbageCollectImages() will just set a flag to re-do the garbage collection
4891 // when the current pass is done.
4892 //
4893 // Also note that this is done within the dyld global lock, so it is always single threaded.
4894 //
4895 void garbageCollectImages()
4896 {
4897 static bool sDoingGC = false;
4898 static bool sRedo = false;
4899
4900 if ( sDoingGC ) {
4901 // GC is currently being run, just set a flag to have it run again.
4902 sRedo = true;
4903 return;
4904 }
4905
4906 sDoingGC = true;
4907 do {
4908 sRedo = false;
4909
4910 // mark phase: mark all images not-in-use
4911 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4912 ImageLoader* image = *it;
4913 //dyld::log("gc: neverUnload=%d name=%s\n", image->neverUnload(), image->getShortName());
4914 image->markNotUsed();
4915 }
4916
4917 #pragma clang diagnostic push
4918 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
4919 // sweep phase: mark as in-use, images reachable from never-unload or in-use image
4920 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4921 ImageLoader* image = *it;
4922 if ( (image->dlopenCount() != 0) || (image->neverUnload() && (image->getState() >= dyld_image_state_bound)) || (image == sMainExecutable) ) {
4923 OSSpinLockLock(&sDynamicReferencesLock);
4924 image->markedUsedRecursive(sDynamicReferences);
4925 OSSpinLockUnlock(&sDynamicReferencesLock);
4926 }
4927 }
4928 #pragma clang diagnostic pop
4929
4930 // collect phase: build array of images not marked in-use
4931 ImageLoader* deadImages[sAllImages.size()];
4932 unsigned deadCount = 0;
4933 int maxRangeCount = 0;
4934 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4935 ImageLoader* image = *it;
4936 if ( ! image->isMarkedInUse() ) {
4937 deadImages[deadCount++] = image;
4938 if (gLogAPIs) dyld::log("dlclose(), found unused image %p %s\n", image, image->getShortName());
4939 maxRangeCount += image->segmentCount();
4940 }
4941 }
4942
4943 // collect phase: run termination routines for images not marked in-use
4944 if ( maxRangeCount != 0 ) {
4945 __cxa_range_t ranges[maxRangeCount];
4946 int rangeCount = 0;
4947 for (unsigned i=0; i < deadCount; ++i) {
4948 ImageLoader* image = deadImages[i];
4949 for (unsigned int j=0; j < image->segmentCount(); ++j) {
4950 if ( !image->segExecutable(j) )
4951 continue;
4952 if ( rangeCount < maxRangeCount ) {
4953 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
4954 ranges[rangeCount].length = image->segSize(j);
4955 ++rangeCount;
4956 }
4957 }
4958 try {
4959 runImageStaticTerminators(image);
4960 }
4961 catch (const char* msg) {
4962 dyld::warn("problem running terminators for image: %s\n", msg);
4963 }
4964 }
4965
4966 // <rdar://problem/14718598> dyld should call __cxa_finalize_ranges()
4967 if ( (rangeCount > 0) && (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 13) )
4968 (*gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
4969 }
4970
4971 // collect phase: delete all images which are not marked in-use
4972 bool mightBeMore;
4973 do {
4974 mightBeMore = false;
4975 for (std::vector<ImageLoader*>::iterator it=sAllImages.begin(); it != sAllImages.end(); it++) {
4976 ImageLoader* image = *it;
4977 if ( ! image->isMarkedInUse() ) {
4978 try {
4979 if (gLogAPIs) dyld::log("dlclose(), deleting %p %s\n", image, image->getShortName());
4980 removeImage(image);
4981 ImageLoader::deleteImage(image);
4982 mightBeMore = true;
4983 break; // interator in invalidated by this removal
4984 }
4985 catch (const char* msg) {
4986 dyld::warn("problem deleting image: %s\n", msg);
4987 }
4988 }
4989 }
4990 } while ( mightBeMore );
4991 } while (sRedo);
4992 sDoingGC = false;
4993
4994 //printAllImages();
4995
4996 }
4997
4998
4999 static void preflight_finally(ImageLoader* image)
5000 {
5001 if ( image->isBundle() ) {
5002 removeImageFromAllImages(image->machHeader());
5003 ImageLoader::deleteImage(image);
5004 }
5005 sBundleBeingLoaded = NULL;
5006 dyld::garbageCollectImages();
5007 }
5008
5009
5010 void preflight(ImageLoader* image, const ImageLoader::RPathChain& loaderRPaths, unsigned cacheIndex)
5011 {
5012 try {
5013 if ( image->isBundle() )
5014 sBundleBeingLoaded = image; // hack
5015 const char* path = image->getPath();
5016 #if SUPPORT_ACCELERATE_TABLES
5017 if ( image == sAllCacheImagesProxy )
5018 path = sAllCacheImagesProxy->getIndexedPath(cacheIndex);
5019 #endif
5020 image->link(gLinkContext, false, true, false, loaderRPaths, path);
5021 }
5022 catch (const char* msg) {
5023 preflight_finally(image);
5024 throw;
5025 }
5026 preflight_finally(image);
5027 }
5028
5029 static void loadInsertedDylib(const char* path)
5030 {
5031 unsigned cacheIndex;
5032 try {
5033 LoadContext context;
5034 context.useSearchPaths = false;
5035 context.useFallbackPaths = false;
5036 context.useLdLibraryPath = false;
5037 context.implicitRPath = false;
5038 context.matchByInstallName = false;
5039 context.dontLoad = false;
5040 context.mustBeBundle = false;
5041 context.mustBeDylib = true;
5042 context.canBePIE = false;
5043 context.origin = NULL; // can't use @loader_path with DYLD_INSERT_LIBRARIES
5044 context.rpath = NULL;
5045 load(path, context, cacheIndex);
5046 }
5047 catch (const char* msg) {
5048 if ( gLinkContext.allowInsertFailures )
5049 dyld::log("dyld: warning: could not load inserted library '%s' into hardened process because %s\n", path, msg);
5050 else
5051 halt(dyld::mkstringf("could not load inserted library '%s' because %s\n", path, msg));
5052 }
5053 catch (...) {
5054 halt(dyld::mkstringf("could not load inserted library '%s'\n", path));
5055 }
5056 }
5057
5058
5059 static void configureProcessRestrictions(const macho_header* mainExecutableMH, const char* envp[])
5060 {
5061 uint64_t amfiInputFlags = 0;
5062 #if TARGET_OS_SIMULATOR
5063 amfiInputFlags |= AMFI_DYLD_INPUT_PROC_IN_SIMULATOR;
5064 #elif __MAC_OS_X_VERSION_MIN_REQUIRED
5065 if ( hasRestrictedSegment(mainExecutableMH) )
5066 amfiInputFlags |= AMFI_DYLD_INPUT_PROC_HAS_RESTRICT_SEG;
5067 #elif __IPHONE_OS_VERSION_MIN_REQUIRED
5068 if ( isFairPlayEncrypted(mainExecutableMH) )
5069 amfiInputFlags |= AMFI_DYLD_INPUT_PROC_IS_ENCRYPTED;
5070 #endif
5071 uint64_t amfiOutputFlags = 0;
5072 const char* amfiFake = nullptr;
5073 if ( dyld3::internalInstall() && dyld3::BootArgs::enableDyldTestMode() ) {
5074 amfiFake = _simple_getenv(envp, "DYLD_AMFI_FAKE");
5075 }
5076 if ( amfiFake != nullptr ) {
5077 amfiOutputFlags = hexToUInt64(amfiFake, nullptr);
5078 }
5079 if ( (amfiFake != nullptr) || (amfi_check_dyld_policy_self(amfiInputFlags, &amfiOutputFlags) == 0) ) {
5080 gLinkContext.allowAtPaths = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_AT_PATH);
5081 gLinkContext.allowEnvVarsPrint = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_PRINT_VARS);
5082 gLinkContext.allowEnvVarsPath = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_PATH_VARS);
5083 gLinkContext.allowEnvVarsSharedCache = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_CUSTOM_SHARED_CACHE);
5084 gLinkContext.allowClassicFallbackPaths = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_FALLBACK_PATHS);
5085 gLinkContext.allowInsertFailures = (amfiOutputFlags & AMFI_DYLD_OUTPUT_ALLOW_FAILED_LIBRARY_INSERTION);
5086 }
5087 else {
5088 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5089 // support chrooting from old kernel
5090 bool isRestricted = false;
5091 bool libraryValidation = false;
5092 // any processes with setuid or setgid bit set or with __RESTRICT segment is restricted
5093 if ( issetugid() || hasRestrictedSegment(mainExecutableMH) ) {
5094 isRestricted = true;
5095 }
5096 bool usingSIP = (csr_check(CSR_ALLOW_TASK_FOR_PID) != 0);
5097 uint32_t flags;
5098 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
5099 // On OS X CS_RESTRICT means the program was signed with entitlements
5100 if ( ((flags & CS_RESTRICT) == CS_RESTRICT) && usingSIP ) {
5101 isRestricted = true;
5102 }
5103 // Library Validation loosens searching but requires everything to be code signed
5104 if ( flags & CS_REQUIRE_LV ) {
5105 isRestricted = false;
5106 libraryValidation = true;
5107 }
5108 }
5109 gLinkContext.allowAtPaths = !isRestricted;
5110 gLinkContext.allowEnvVarsPrint = !isRestricted;
5111 gLinkContext.allowEnvVarsPath = !isRestricted;
5112 gLinkContext.allowEnvVarsSharedCache = !libraryValidation || !usingSIP;
5113 gLinkContext.allowClassicFallbackPaths = !isRestricted;
5114 gLinkContext.allowInsertFailures = false;
5115 #else
5116 halt("amfi_check_dyld_policy_self() failed\n");
5117 #endif
5118 }
5119 }
5120
5121 // called by _dyld_register_driverkit_main()
5122 void setMainEntry(void (*main)())
5123 {
5124 if ( sEntryOveride == nullptr )
5125 sEntryOveride = main;
5126 else
5127 halt("_dyld_register_driverkit_main() may only be called once");
5128 }
5129
5130 bool processIsRestricted()
5131 {
5132 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5133 return !gLinkContext.allowEnvVarsPath;
5134 #else
5135 return false;
5136 #endif
5137 }
5138
5139
5140 // <rdar://problem/10583252> Add dyld to uuidArray to enable symbolication of stackshots
5141 static void addDyldImageToUUIDList()
5142 {
5143 const struct macho_header* mh = (macho_header*)&__dso_handle;
5144 const uint32_t cmd_count = mh->ncmds;
5145 const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
5146 const struct load_command* cmd = cmds;
5147 for (uint32_t i = 0; i < cmd_count; ++i) {
5148 switch (cmd->cmd) {
5149 case LC_UUID: {
5150 uuid_command* uc = (uuid_command*)cmd;
5151 dyld_uuid_info info;
5152 info.imageLoadAddress = (mach_header*)mh;
5153 memcpy(info.imageUUID, uc->uuid, 16);
5154 addNonSharedCacheImageUUID(info);
5155 return;
5156 }
5157 }
5158 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
5159 }
5160 }
5161
5162 void notifyKernelAboutImage(const struct macho_header* mh, const char* fileInfo)
5163 {
5164 const char *endptr = nullptr;
5165 uint64_t tmp = hexToUInt64(fileInfo, &endptr);
5166 fsid_t fsid = *reinterpret_cast<fsid_t *>(&tmp);
5167 uint64_t fsobj_id_scalar = 0;
5168 fsobj_id_t fsobj_id = {0};
5169 if (endptr != nullptr) {
5170 fsobj_id_scalar = hexToUInt64(endptr+1, &endptr);
5171 fsobj_id = *reinterpret_cast<fsobj_id_t *>(&tmp);
5172 }
5173 const uint32_t cmd_count = mh->ncmds;
5174 const struct load_command* const cmds = (struct load_command*)((char*)mh + sizeof(macho_header));
5175 const struct load_command* cmd = cmds;
5176 for (uint32_t i = 0; i < cmd_count; ++i) {
5177 switch (cmd->cmd) {
5178 case LC_UUID: {
5179 // Add dyld to the kernel image info
5180 uuid_command* uc = (uuid_command*)cmd;
5181 char path[MAXPATHLEN];
5182 if (fsgetpath(path, MAXPATHLEN, &fsid, fsobj_id_scalar) < 0) {
5183 path[0] = 0;
5184 }
5185 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A, path, (const uuid_t *)&uc->uuid[0], fsobj_id, fsid, (const mach_header *)mh);
5186 return;
5187 }
5188 }
5189 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
5190 }
5191 }
5192
5193 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5194 typedef int (*open_proc_t)(const char*, int, int);
5195 typedef int (*fcntl_proc_t)(int, int, void*);
5196 typedef int (*ioctl_proc_t)(int, unsigned long, void*);
5197 static void* getProcessInfo() { return dyld::gProcessInfo; }
5198 static const SyscallHelpers sSysCalls = {
5199 12,
5200 // added in version 1
5201 (open_proc_t)&open,
5202 &close,
5203 &pread,
5204 &write,
5205 &mmap,
5206 &munmap,
5207 &madvise,
5208 &stat,
5209 (fcntl_proc_t)&fcntl,
5210 (ioctl_proc_t)&ioctl,
5211 &issetugid,
5212 &getcwd,
5213 &realpath,
5214 &vm_allocate,
5215 &vm_deallocate,
5216 &vm_protect,
5217 &vlog,
5218 &vwarn,
5219 &pthread_mutex_lock,
5220 &pthread_mutex_unlock,
5221 &mach_thread_self,
5222 &mach_port_deallocate,
5223 &task_self_trap,
5224 &mach_timebase_info,
5225 &OSAtomicCompareAndSwapPtrBarrier,
5226 &OSMemoryBarrier,
5227 &getProcessInfo,
5228 &__error,
5229 &mach_absolute_time,
5230 // added in version 2
5231 &thread_switch,
5232 // added in version 3
5233 &opendir,
5234 &readdir_r,
5235 &closedir,
5236 // added in version 4
5237 &coresymbolication_load_notifier,
5238 &coresymbolication_unload_notifier,
5239 // Added in version 5
5240 &proc_regionfilename,
5241 &getpid,
5242 &mach_port_insert_right,
5243 &mach_port_allocate,
5244 &mach_msg,
5245 // Added in version 6
5246 &abort_with_payload,
5247 // Added in version 7
5248 &legacy_task_register_dyld_image_infos,
5249 &legacy_task_unregister_dyld_image_infos,
5250 &legacy_task_get_dyld_image_infos,
5251 &legacy_task_register_dyld_shared_cache_image_info,
5252 &legacy_task_register_dyld_set_dyld_state,
5253 &legacy_task_register_dyld_get_process_state,
5254 // Added in version 8
5255 &task_info,
5256 &thread_info,
5257 &kdebug_is_enabled,
5258 &kdebug_trace,
5259 // Added in version 9
5260 &kdebug_trace_string,
5261 // Added in version 10
5262 &amfi_check_dyld_policy_self,
5263 // Added in version 11
5264 &notifyMonitoringDyldMain,
5265 &notifyMonitoringDyld,
5266 // Add in version 12
5267 &mach_msg_destroy,
5268 &mach_port_construct,
5269 &mach_port_destruct
5270 };
5271
5272 __attribute__((noinline))
5273 static const char* useSimulatorDyld(int fd, const macho_header* mainExecutableMH, const char* dyldPath,
5274 int argc, const char* argv[], const char* envp[], const char* apple[],
5275 uintptr_t* startGlue, uintptr_t* mainAddr)
5276 {
5277 *startGlue = 0;
5278 *mainAddr = 0;
5279
5280 // <rdar://problem/25311921> simulator does not support restricted processes
5281 uint32_t flags;
5282 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) == -1 )
5283 return "csops() failed";
5284 if ( (flags & CS_RESTRICT) == CS_RESTRICT )
5285 return "dyld_sim cannot be loaded in a restricted process";
5286 if ( issetugid() )
5287 return "dyld_sim cannot be loaded in a setuid process";
5288 if ( hasRestrictedSegment(mainExecutableMH) )
5289 return "dyld_sim cannot be loaded in a restricted process";
5290
5291 // get file size of dyld_sim
5292 struct stat sb;
5293 if ( fstat(fd, &sb) == -1 )
5294 return "stat(dyld_sim) failed";
5295
5296 // read first page of dyld_sim file
5297 uint8_t firstPage[4096];
5298 if ( pread(fd, firstPage, 4096, 0) != 4096 )
5299 return "pread(dyld_sim) failed";
5300
5301 // if fat file, pick matching slice
5302 uint64_t fileOffset = 0;
5303 uint64_t fileLength = sb.st_size;
5304 const fat_header* fileStartAsFat = (fat_header*)firstPage;
5305 if ( fileStartAsFat->magic == OSSwapBigToHostInt32(FAT_MAGIC) ) {
5306 if ( !fatFindBest(fileStartAsFat, &fileOffset, &fileLength) )
5307 return "no matching arch in dyld_sim";
5308 // re-read buffer from start of mach-o slice in fat file
5309 if ( pread(fd, firstPage, 4096, fileOffset) != 4096 )
5310 return "pread(dyld_sim) failed";
5311 }
5312 else if ( !isCompatibleMachO(firstPage, dyldPath) ) {
5313 return "dyld_sim is not compatible with the loaded process, likely due to architecture mismatch";
5314 }
5315
5316 // calculate total size of dyld segments
5317 const macho_header* mh = (const macho_header*)firstPage;
5318 struct macho_segment_command* lastSeg = NULL;
5319 struct macho_segment_command* firstSeg = NULL;
5320 uintptr_t mappingSize = 0;
5321 uintptr_t preferredLoadAddress = 0;
5322 const uint32_t cmd_count = mh->ncmds;
5323 if ( mh->sizeofcmds > 4096 )
5324 return "dyld_sim load commands to large";
5325 if ( (sizeof(macho_header) + mh->sizeofcmds) > 4096 )
5326 return "dyld_sim load commands to large";
5327 struct linkedit_data_command* codeSigCmd = NULL;
5328 const struct load_command* const cmds = (struct load_command*)(((char*)mh)+sizeof(macho_header));
5329 const struct load_command* const endCmds = (struct load_command*)(((char*)mh) + sizeof(macho_header) + mh->sizeofcmds);
5330 const struct load_command* cmd = cmds;
5331 for (uint32_t i = 0; i < cmd_count; ++i) {
5332 uint32_t cmdLength = cmd->cmdsize;
5333 if ( cmdLength < 8 )
5334 return "dyld_sim load command too small";
5335 const struct load_command* const nextCmd = (const struct load_command*)(((char*)cmd)+cmdLength);
5336 if ( (nextCmd > endCmds) || (nextCmd < cmd) )
5337 return "dyld_sim load command too large";
5338 switch (cmd->cmd) {
5339 case LC_SEGMENT_COMMAND:
5340 {
5341 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
5342 if ( seg->vmaddr + seg->vmsize < seg->vmaddr )
5343 return "dyld_sim seg wraps address space";
5344 if ( seg->vmsize < seg->filesize )
5345 return "dyld_sim seg vmsize too small";
5346 if ( (seg->fileoff + seg->filesize) < seg->fileoff )
5347 return "dyld_sim seg size wraps address space";
5348 if ( lastSeg == NULL ) {
5349 // first segment must be __TEXT and start at beginning of file/slice
5350 firstSeg = seg;
5351 if ( strcmp(seg->segname, "__TEXT") != 0 )
5352 return "dyld_sim first segment not __TEXT";
5353 if ( seg->fileoff != 0 )
5354 return "dyld_sim first segment not at file offset zero";
5355 if ( seg->filesize < (sizeof(macho_header) + mh->sizeofcmds) )
5356 return "dyld_sim first segment smaller than load commands";
5357 preferredLoadAddress = seg->vmaddr;
5358 }
5359 else {
5360 // other sements must be continguous with previous segment and not executable
5361 if ( lastSeg->fileoff + lastSeg->filesize != seg->fileoff )
5362 return "dyld_sim segments not contiguous";
5363 if ( lastSeg->vmaddr + lastSeg->vmsize != seg->vmaddr )
5364 return "dyld_sim segments not address contiguous";
5365 if ( (seg->initprot & VM_PROT_EXECUTE) != 0 )
5366 return "dyld_sim non-first segment is executable";
5367 }
5368 mappingSize += seg->vmsize;
5369 lastSeg = seg;
5370 }
5371 break;
5372 case LC_SEGMENT_COMMAND_WRONG:
5373 return "dyld_sim wrong load segment load command";
5374 case LC_CODE_SIGNATURE:
5375 codeSigCmd = (struct linkedit_data_command*)cmd;
5376 break;
5377 }
5378 cmd = nextCmd;
5379 }
5380 // last segment must be named __LINKEDIT and not writable
5381 if ( lastSeg == NULL )
5382 return "dyld_sim has no segments";
5383 if ( strcmp(lastSeg->segname, "__LINKEDIT") != 0 )
5384 return "dyld_sim last segment not __LINKEDIT";
5385 if ( lastSeg->initprot & VM_PROT_WRITE )
5386 return "dyld_sim __LINKEDIT segment writable";
5387
5388 // must have code signature which is contained within LINKEDIT segment
5389 if ( codeSigCmd == NULL )
5390 return "dyld_sim not code signed";
5391 if ( codeSigCmd->dataoff < lastSeg->fileoff )
5392 return "dyld_sim code signature not in __LINKEDIT";
5393 if ( (codeSigCmd->dataoff + codeSigCmd->datasize) < codeSigCmd->dataoff )
5394 return "dyld_sim code signature size wraps";
5395 if ( (codeSigCmd->dataoff + codeSigCmd->datasize) > (lastSeg->fileoff + lastSeg->filesize) )
5396 return "dyld_sim code signature extends beyond __LINKEDIT";
5397
5398 // register code signature with kernel before mmap()ing segments
5399 fsignatures_t siginfo;
5400 siginfo.fs_file_start=fileOffset; // start of mach-o slice in fat file
5401 siginfo.fs_blob_start=(void*)(long)(codeSigCmd->dataoff); // start of code-signature in mach-o file
5402 siginfo.fs_blob_size=codeSigCmd->datasize; // size of code-signature
5403 int result = fcntl(fd, F_ADDFILESIGS_FOR_DYLD_SIM, &siginfo);
5404 if ( result == -1 ) {
5405 return mkstringf("dyld_sim fcntl(F_ADDFILESIGS_FOR_DYLD_SIM) failed with errno=%d", errno);
5406 }
5407 // file range covered by code signature must extend up to code signature itself
5408 if ( siginfo.fs_file_start < codeSigCmd->dataoff )
5409 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);
5410
5411 // reserve space, then mmap each segment
5412 vm_address_t loadAddress = 0;
5413 if ( ::vm_allocate(mach_task_self(), &loadAddress, mappingSize, VM_FLAGS_ANYWHERE) != 0 )
5414 return "dyld_sim cannot allocate space";
5415 cmd = cmds;
5416 struct source_version_command* dyldVersionCmd = NULL;
5417 struct uuid_command* uuidCmd = NULL;
5418 for (uint32_t i = 0; i < cmd_count; ++i) {
5419 switch (cmd->cmd) {
5420 case LC_SEGMENT_COMMAND:
5421 {
5422 struct macho_segment_command* seg = (struct macho_segment_command*)cmd;
5423 uintptr_t requestedLoadAddress = seg->vmaddr - preferredLoadAddress + loadAddress;
5424 void* segAddress = ::mmap((void*)requestedLoadAddress, seg->filesize, seg->initprot, MAP_FIXED | MAP_PRIVATE, fd, fileOffset + seg->fileoff);
5425 //dyld::log("dyld_sim %s mapped at %p\n", seg->segname, segAddress);
5426 if ( segAddress == (void*)(-1) )
5427 return "dyld_sim mmap() of segment failed";
5428 if ( ((uintptr_t)segAddress < loadAddress) || ((uintptr_t)segAddress+seg->filesize > loadAddress+mappingSize) )
5429 return "dyld_sim mmap() to wrong location";
5430 }
5431 break;
5432 case LC_SOURCE_VERSION:
5433 dyldVersionCmd = (struct source_version_command*)cmd;
5434 break;
5435 case LC_UUID: {
5436 uuidCmd = (uuid_command*)cmd;
5437 break;
5438 }
5439 }
5440 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
5441 }
5442 close(fd);
5443
5444 // walk newly mapped dyld_sim __TEXT load commands to find entry point
5445 uintptr_t entry = 0;
5446 cmd = (struct load_command*)(((char*)loadAddress)+sizeof(macho_header));
5447 const uint32_t count = ((macho_header*)(loadAddress))->ncmds;
5448 for (uint32_t i = 0; i < count; ++i) {
5449 if (cmd->cmd == LC_UNIXTHREAD) {
5450 #if __i386__
5451 const i386_thread_state_t* registers = (i386_thread_state_t*)(((char*)cmd) + 16);
5452 // entry point must be in first segment
5453 if ( registers->__eip < firstSeg->vmaddr )
5454 return "dyld_sim entry point not in __TEXT segment";
5455 if ( registers->__eip > (firstSeg->vmaddr + firstSeg->vmsize) )
5456 return "dyld_sim entry point not in __TEXT segment";
5457 entry = (registers->__eip + loadAddress - preferredLoadAddress);
5458 #elif __x86_64__
5459 const x86_thread_state64_t* registers = (x86_thread_state64_t*)(((char*)cmd) + 16);
5460 // entry point must be in first segment
5461 if ( registers->__rip < firstSeg->vmaddr )
5462 return "dyld_sim entry point not in __TEXT segment";
5463 if ( registers->__rip > (firstSeg->vmaddr + firstSeg->vmsize) )
5464 return "dyld_sim entry point not in __TEXT segment";
5465 entry = (registers->__rip + loadAddress - preferredLoadAddress);
5466 #endif
5467 }
5468 cmd = (const struct load_command*)(((char*)cmd)+cmd->cmdsize);
5469 }
5470 if ( entry == 0 )
5471 return "dyld_sim entry not found";
5472
5473 // notify debugger that dyld_sim is loaded
5474 dyld_image_info info;
5475 info.imageLoadAddress = (mach_header*)loadAddress;
5476 info.imageFilePath = strdup(dyldPath);
5477 info.imageFileModDate = sb.st_mtime;
5478 addImagesToAllImages(1, &info);
5479 dyld::gProcessInfo->notification(dyld_image_adding, 1, &info);
5480
5481 fsid_t fsid = {{0, 0}};
5482 fsobj_id_t fsobj = {0};
5483 ino_t inode = sb.st_ino;
5484 fsobj.fid_objno = (uint32_t)inode;
5485 fsobj.fid_generation = (uint32_t)(inode>>32);
5486 fsid.val[0] = sb.st_dev;
5487 dyld3::kdebug_trace_dyld_image(DBG_DYLD_UUID_MAP_A, dyldPath, (const uuid_t *)&uuidCmd->uuid[0], fsobj, fsid, (const mach_header *)mh);
5488
5489 const char** appleParams = apple;
5490
5491 // <rdar://problem/5077374> have host dyld detach macOS shared cache from process before jumping into dyld_sim
5492 dyld3::deallocateExistingSharedCache();
5493
5494 // jump into new simulator dyld
5495 typedef uintptr_t (*sim_entry_proc_t)(int argc, const char* argv[], const char* envp[], const char* apple[],
5496 const macho_header* mainExecutableMH, const macho_header* dyldMH, uintptr_t dyldSlide,
5497 const dyld::SyscallHelpers* vtable, uintptr_t* startGlue);
5498 sim_entry_proc_t newDyld = (sim_entry_proc_t)entry;
5499 *mainAddr = (*newDyld)(argc, argv, envp, appleParams, mainExecutableMH, (macho_header*)loadAddress,
5500 loadAddress - preferredLoadAddress,
5501 &sSysCalls, startGlue);
5502 return NULL;
5503 }
5504 #endif
5505
5506 //
5507 // If the DYLD_SKIP_MAIN environment is set to 1, dyld will return the
5508 // address of this function instead of main() in the target program which
5509 // __dyld_start jumps to. Useful for qualifying dyld itself.
5510 //
5511 int
5512 fake_main()
5513 {
5514 return 0;
5515 }
5516
5517
5518
5519 #if !TARGET_OS_SIMULATOR
5520
5521 static bool envVarMatches(const dyld3::closure::LaunchClosure* mainClosure, const char* envp[], const char* varName)
5522 {
5523 __block const char* valueFromClosure = nullptr;
5524 mainClosure->forEachEnvVar(^(const char* keyEqualValue, bool& stop) {
5525 size_t keyLen = strlen(varName);
5526 if ( (strncmp(varName, keyEqualValue, keyLen) == 0) && (keyEqualValue[keyLen] == '=') ) {
5527 valueFromClosure = &keyEqualValue[keyLen+1];
5528 stop = true;
5529 }
5530 });
5531
5532 const char* valueFromEnv = _simple_getenv(envp, varName);
5533
5534 bool inClosure = (valueFromClosure != nullptr);
5535 bool inEnv = (valueFromEnv != nullptr);
5536 if ( inClosure != inEnv )
5537 return false;
5538 if ( !inClosure && !inEnv )
5539 return true;
5540 return ( strcmp(valueFromClosure, valueFromEnv) == 0 );
5541 }
5542
5543 static const char* const sEnvVarsToCheck[] = {
5544 "DYLD_LIBRARY_PATH",
5545 "DYLD_FRAMEWORK_PATH",
5546 "DYLD_FALLBACK_LIBRARY_PATH",
5547 "DYLD_FALLBACK_FRAMEWORK_PATH",
5548 "DYLD_INSERT_LIBRARIES",
5549 "DYLD_IMAGE_SUFFIX",
5550 "DYLD_VERSIONED_FRAMEWORK_PATH",
5551 "DYLD_VERSIONED_LIBRARY_PATH",
5552 "DYLD_ROOT_PATH"
5553 };
5554
5555 static bool envVarsMatch(const dyld3::closure::LaunchClosure* mainClosure, const char* envp[])
5556 {
5557 for (const char* envVar : sEnvVarsToCheck) {
5558 if ( !envVarMatches(mainClosure, envp, envVar) ) {
5559 if ( gLinkContext.verboseWarnings )
5560 dyld::log("dyld: closure %p not used because %s changed\n", mainClosure, envVar);
5561 return false;
5562 }
5563 }
5564
5565 // FIXME: dyld3 doesn't support versioned paths so we need to fall back to dyld2 if we have them.
5566 // <rdar://problem/37004660> dyld3: support DYLD_VERSIONED_*_PATHs ?
5567 if ( sEnv.DYLD_VERSIONED_LIBRARY_PATH != nullptr ) {
5568 if ( gLinkContext.verboseWarnings )
5569 dyld::log("dyld: closure %p not used because DYLD_VERSIONED_LIBRARY_PATH used\n", mainClosure);
5570 return false;
5571 }
5572 if ( sEnv.DYLD_VERSIONED_FRAMEWORK_PATH != nullptr ) {
5573 if ( gLinkContext.verboseWarnings )
5574 dyld::log("dyld: closure %p not used because DYLD_VERSIONED_FRAMEWORK_PATH used\n", mainClosure);
5575 return false;
5576 }
5577
5578 return true;
5579 }
5580
5581 static bool closureValid(const dyld3::closure::LaunchClosure* mainClosure, const dyld3::closure::LoadedFileInfo& mainFileInfo,
5582 const uint8_t* mainExecutableCDHash, bool closureInCache, const char* envp[])
5583 {
5584 if ( closureInCache ) {
5585 // We can only use the cache closure if the cache version is the same as dyld
5586 if (sSharedCacheLoadInfo.loadAddress->header.formatVersion != dyld3::closure::kFormatVersion) {
5587 if ( gLinkContext.verboseWarnings )
5588 dyld::log("dyld: dyld closure version 0x%08X does not match dyld cache version 0x%08X\n",
5589 dyld3::closure::kFormatVersion, sSharedCacheLoadInfo.loadAddress->header.formatVersion);
5590 return false;
5591 }
5592 if (sForceInvalidSharedCacheClosureFormat) {
5593 if ( gLinkContext.verboseWarnings )
5594 dyld::log("dyld: closure %p dyld cache version forced invalid\n", mainClosure);
5595 return false;
5596 }
5597 } else {
5598 // verify current dyld cache is same as expected
5599 uuid_t expectedCacheUUID;
5600 if ( mainClosure->builtAgainstDyldCache(expectedCacheUUID) ) {
5601 if ( sSharedCacheLoadInfo.loadAddress == nullptr ) {
5602 if ( gLinkContext.verboseWarnings )
5603 dyld::log("dyld: closure %p dyld cache not loaded\n", mainClosure);
5604 return false;
5605 }
5606 else {
5607 uuid_t actualCacheUUID;
5608 sSharedCacheLoadInfo.loadAddress->getUUID(actualCacheUUID);
5609 if ( memcmp(expectedCacheUUID, actualCacheUUID, sizeof(uuid_t)) != 0 ) {
5610 if ( gLinkContext.verboseWarnings )
5611 dyld::log("dyld: closure %p not used because built against different dyld cache\n", mainClosure);
5612 return false;
5613 }
5614 }
5615 }
5616 else {
5617 // closure built assume there is no dyld cache
5618 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
5619 if ( gLinkContext.verboseWarnings )
5620 dyld::log("dyld: closure %p built expecting no dyld cache\n", mainClosure);
5621 return false;
5622 }
5623 }
5624 #if __IPHONE_OS_VERSION_MIN_REQUIRED
5625 // verify this closure is not from a previous reboot
5626 const char* expectedBootUUID = mainClosure->bootUUID();
5627 char actualBootSessionUUID[256] = { 0 };
5628 size_t bootSize = sizeof(actualBootSessionUUID);
5629 bool gotActualBootUUID = (sysctlbyname("kern.bootsessionuuid", actualBootSessionUUID, &bootSize, NULL, 0) == 0);
5630 if ( gotActualBootUUID ) {
5631 // If we got a boot UUID then we should have also recorded it in the closure
5632 if ( expectedBootUUID == nullptr) {
5633 // The closure didn't have a UUID but now we do. This isn't valid.
5634 if ( gLinkContext.verboseWarnings )
5635 dyld::log("dyld: closure %p missing boot-UUID\n", mainClosure);
5636 return false;
5637 } else if ( strcmp(expectedBootUUID, actualBootSessionUUID) != 0 ) {
5638 if ( gLinkContext.verboseWarnings )
5639 dyld::log("dyld: closure %p built in different boot context\n", mainClosure);
5640 return false;
5641 }
5642 } else {
5643 // We didn't get a UUID now, which is ok so long as the closure also doesn't have one.
5644 if ( expectedBootUUID != nullptr) {
5645 if ( gLinkContext.verboseWarnings )
5646 dyld::log("dyld: closure %p has boot-UUID\n", mainClosure);
5647 return false;
5648 }
5649 }
5650 #endif
5651 }
5652
5653 // verify all mach-o files have not changed since closure was built
5654 __block bool foundFileThatInvalidatesClosure = false;
5655 mainClosure->images()->forEachImage(^(const dyld3::closure::Image* image, bool& stop) {
5656 __block uint64_t expectedInode;
5657 __block uint64_t expectedMtime;
5658 if ( image->hasFileModTimeAndInode(expectedInode, expectedMtime) ) {
5659 struct stat statBuf;
5660 if ( ::stat(image->path(), &statBuf) == 0 ) {
5661 if ( (statBuf.st_mtime != expectedMtime) || (statBuf.st_ino != expectedInode) ) {
5662 if ( gLinkContext.verboseWarnings )
5663 dyld::log("dyld: closure %p not used because mtime/inode for '%s' has changed since closure was built\n", mainClosure, image->path());
5664 foundFileThatInvalidatesClosure = true;
5665 stop = true;
5666 }
5667 }
5668 else {
5669 if ( gLinkContext.verboseWarnings )
5670 dyld::log("dyld: closure %p not used because '%s' is needed by closure but is missing\n", mainClosure, image->path());
5671 foundFileThatInvalidatesClosure = true;
5672 stop = true;
5673 }
5674 }
5675 });
5676 if ( foundFileThatInvalidatesClosure )
5677 return false;
5678
5679 // verify cdHash of main executable is same as recorded in closure
5680 const dyld3::closure::Image* mainImage = mainClosure->images()->imageForNum(mainClosure->topImage());
5681
5682 __block bool foundCDHash = false;
5683 __block bool foundValidCDHash = false;
5684 mainImage->forEachCDHash(^(const uint8_t *expectedHash, bool& stop) {
5685 if ( mainExecutableCDHash == nullptr ) {
5686 if ( gLinkContext.verboseWarnings )
5687 dyld::log("dyld: closure %p not used because main executable is not code signed but was expected to be\n", mainClosure);
5688 stop = true;
5689 return;
5690 }
5691 foundCDHash = true;
5692 if ( memcmp(mainExecutableCDHash, expectedHash, 20) == 0 ) {
5693 // found a match, so lets use this one.
5694 foundValidCDHash = true;
5695 stop = true;
5696 return;
5697 }
5698 });
5699
5700 // If we found cd hashes, but they were all invalid, then print them out
5701 if ( foundCDHash && !foundValidCDHash ) {
5702 auto getCDHashString = [](const uint8_t cdHash[20], char* cdHashBuffer) {
5703 for (int i=0; i < 20; ++i) {
5704 uint8_t byte = cdHash[i];
5705 uint8_t nibbleL = byte & 0x0F;
5706 uint8_t nibbleH = byte >> 4;
5707 if ( nibbleH < 10 ) {
5708 *cdHashBuffer = '0' + nibbleH;
5709 ++cdHashBuffer;
5710 } else {
5711 *cdHashBuffer = 'a' + (nibbleH-10);
5712 ++cdHashBuffer;
5713 }
5714 if ( nibbleL < 10 ) {
5715 *cdHashBuffer = '0' + nibbleL;
5716 ++cdHashBuffer;
5717 } else {
5718 *cdHashBuffer = 'a' + (nibbleL-10);
5719 ++cdHashBuffer;
5720 }
5721 }
5722 };
5723 if ( gLinkContext.verboseWarnings ) {
5724 mainImage->forEachCDHash(^(const uint8_t *expectedHash, bool &stop) {
5725 char mainExecutableCDHashBuffer[128] = { '\0' };
5726 char expectedCDHashBuffer[128] = { '\0' };
5727
5728 getCDHashString(mainExecutableCDHash, mainExecutableCDHashBuffer);
5729 getCDHashString(expectedHash, expectedCDHashBuffer);
5730
5731 dyld::log("dyld: closure %p not used because main executable cd-hash (%s) changed since closure was built with (%s)\n",
5732 mainClosure, mainExecutableCDHashBuffer, expectedCDHashBuffer);
5733 });
5734 }
5735
5736 return false;
5737 }
5738
5739 // verify UUID of main executable is same as recorded in closure
5740 uuid_t expectedUUID;
5741 bool hasExpect = mainImage->getUuid(expectedUUID);
5742 uuid_t actualUUID;
5743 const dyld3::MachOLoaded* mainExecutableMH = (const dyld3::MachOLoaded*)mainFileInfo.fileContent;
5744 bool hasActual = mainExecutableMH->getUuid(actualUUID);
5745 if ( hasExpect != hasActual ) {
5746 if ( gLinkContext.verboseWarnings )
5747 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosure);
5748 return false;
5749 }
5750 if ( hasExpect && hasActual && memcmp(actualUUID, expectedUUID, sizeof(uuid_t)) != 0 ) {
5751 if ( gLinkContext.verboseWarnings )
5752 dyld::log("dyld: closure %p not used because UUID of executable changed since closure was built\n", mainClosure);
5753 return false;
5754 }
5755
5756 // verify DYLD_* env vars are same as when closure was built
5757 if ( !envVarsMatch(mainClosure, envp) ) {
5758 return false;
5759 }
5760
5761 // verify files that are supposed to be missing actually are missing
5762 mainClosure->forEachMustBeMissingFile(^(const char* path, bool& stop) {
5763 struct stat statBuf;
5764 if ( ::stat(path, &statBuf) == 0 ) {
5765 stop = true;
5766 foundFileThatInvalidatesClosure = true;
5767 if ( gLinkContext.verboseWarnings )
5768 dyld::log("dyld: closure %p not used because found unexpected file '%s'\n", mainClosure, path);
5769 }
5770 });
5771
5772 // verify files that are supposed to exist are there with the
5773 mainClosure->forEachSkipIfExistsFile(^(const dyld3::closure::LaunchClosure::SkippedFile &file, bool &stop) {
5774 struct stat statBuf;
5775 if ( ::stat(file.path, &statBuf) == 0 ) {
5776 if ( (statBuf.st_mtime != file.mtime) || (statBuf.st_ino != file.inode) ) {
5777 if ( gLinkContext.verboseWarnings )
5778 dyld::log("dyld: closure %p not used because mtime/inode for '%s' has changed since closure was built\n", mainClosure, file.path);
5779 foundFileThatInvalidatesClosure = true;
5780 stop = true;
5781 }
5782 }
5783 });
5784
5785 // verify closure did not require anything unavailable
5786 if ( mainClosure->usedAtPaths() && !gLinkContext.allowAtPaths ) {
5787 if ( gLinkContext.verboseWarnings )
5788 dyld::log("dyld: closure %p not used because is used @paths, but process does not allow that\n", mainClosure);
5789 return false;
5790 }
5791 if ( mainClosure->usedFallbackPaths() && !gLinkContext.allowClassicFallbackPaths ) {
5792 if ( gLinkContext.verboseWarnings )
5793 dyld::log("dyld: closure %p not used because is used default fallback paths, but process does not allow that\n", mainClosure);
5794 return false;
5795 }
5796
5797 return !foundFileThatInvalidatesClosure;
5798 }
5799
5800 static bool nolog(const char* format, ...)
5801 {
5802 return false;
5803 }
5804
5805 static bool dolog(const char* format, ...)
5806 {
5807 va_list list;
5808 va_start(list, format);
5809 vlog(format, list);
5810 va_end(list);
5811 return true;
5812 }
5813
5814 static bool launchWithClosure(const dyld3::closure::LaunchClosure* mainClosure,
5815 const DyldSharedCache* dyldCache,
5816 const dyld3::MachOLoaded* mainExecutableMH, uintptr_t mainExecutableSlide,
5817 int argc, const char* argv[], const char* envp[], const char* apple[],
5818 uintptr_t* entry, uintptr_t* startGlue)
5819 {
5820 // build list of all known ImageArrays (at most three: cached dylibs, other OS dylibs, and main prog)
5821 STACK_ALLOC_ARRAY(const dyld3::closure::ImageArray*, imagesArrays, 3);
5822 const dyld3::closure::ImageArray* mainClosureImages = mainClosure->images();
5823 if ( dyldCache != nullptr ) {
5824 imagesArrays.push_back(dyldCache->cachedDylibsImageArray());
5825 if ( auto others = dyldCache->otherOSImageArray() )
5826 imagesArrays.push_back(others);
5827 }
5828 imagesArrays.push_back(mainClosureImages);
5829
5830 // allocate space for Array<LoadedImage>
5831 STACK_ALLOC_ARRAY(dyld3::LoadedImage, allImages, mainClosure->initialLoadCount());
5832
5833 // Get the pre-optimized Objective-C so that we can bind the selectors
5834 const dyld3::closure::ObjCSelectorOpt* selectorOpt = nullptr;
5835 dyld3::Array<dyld3::closure::Image::ObjCSelectorImage> selectorImages;
5836 mainClosure->selectorHashTable(selectorImages, selectorOpt);
5837
5838 __block dyld3::Loader loader({}, allImages, dyldCache, imagesArrays,
5839 selectorOpt, selectorImages,
5840 (gLinkContext.verboseLoading ? &dolog : &nolog),
5841 (gLinkContext.verboseMapping ? &dolog : &nolog),
5842 (gLinkContext.verboseBind ? &dolog : &nolog),
5843 (gLinkContext.verboseDOF ? &dolog : &nolog));
5844 dyld3::closure::ImageNum mainImageNum = mainClosure->topImage();
5845 mainClosureImages->forEachImage(^(const dyld3::closure::Image* image, bool& stop) {
5846 if ( image->imageNum() == mainImageNum ) {
5847 // add main executable (which is already mapped by kernel) to list
5848 dyld3::LoadedImage mainLoadedImage = dyld3::LoadedImage::make(image, mainExecutableMH);
5849 mainLoadedImage.setState(dyld3::LoadedImage::State::mapped);
5850 mainLoadedImage.markLeaveMapped();
5851 loader.addImage(mainLoadedImage);
5852 stop = true;
5853 }
5854 else {
5855 // add inserted library to initial list
5856 loader.addImage(dyld3::LoadedImage::make(image));
5857 }
5858 });
5859
5860 // recursively load all dependents and fill in allImages array
5861 bool someCacheImageOverridden = false;
5862 Diagnostics diag;
5863 loader.completeAllDependents(diag, someCacheImageOverridden);
5864 if ( diag.noError() )
5865 loader.mapAndFixupAllImages(diag, dyld3::Loader::dtraceUserProbesEnabled());
5866 if ( diag.hasError() ) {
5867 if ( gLinkContext.verboseWarnings )
5868 dyld::log("dyld: %s\n", diag.errorMessage());
5869 return false;
5870 }
5871
5872 //dyld::log("loaded image list:\n");
5873 //for (const dyld3::LoadedImage& info : allImages) {
5874 // dyld::log("mh=%p, path=%s\n", info.loadedAddress(), info.image()->path());
5875 //}
5876
5877 // find libdyld entry
5878 dyld3::closure::Image::ResolvedSymbolTarget dyldEntry;
5879 mainClosure->libDyldEntry(dyldEntry);
5880 const dyld3::LibDyldEntryVector* libDyldEntry = (dyld3::LibDyldEntryVector*)loader.resolveTarget(dyldEntry);
5881
5882 // send info on all images to libdyld.dylb
5883 libDyldEntry->setVars(mainExecutableMH, argc, argv, envp, apple);
5884 if ( libDyldEntry->vectorVersion > 4 )
5885 libDyldEntry->setRestrictions(gLinkContext.allowAtPaths, gLinkContext.allowEnvVarsPath, gLinkContext.allowClassicFallbackPaths);
5886 libDyldEntry->setHaltFunction(&halt);
5887 if ( libDyldEntry->vectorVersion > 5 ) {
5888 libDyldEntry->setNotifyMonitoringDyldMain(&notifyMonitoringDyldMain);
5889 libDyldEntry->setNotifyMonitoringDyld(&notifyMonitoringDyld);
5890 }
5891
5892 if ( libDyldEntry->vectorVersion > 6 )
5893 libDyldEntry->setHasCacheOverrides(someCacheImageOverridden);
5894
5895 if ( libDyldEntry->vectorVersion > 2 )
5896 libDyldEntry->setChildForkFunction(&_dyld_fork_child);
5897 #if !TARGET_OS_SIMULATOR
5898 if ( libDyldEntry->vectorVersion > 3 )
5899 libDyldEntry->setLogFunction(&dyld::vlog);
5900 #endif
5901 libDyldEntry->setOldAllImageInfo(gProcessInfo);
5902 dyld3::LoadedImage* libSys = loader.findImage(mainClosure->libSystemImageNum());
5903 libDyldEntry->setInitialImageList(mainClosure, dyldCache, sSharedCacheLoadInfo.path, allImages, *libSys);
5904 // run initializers
5905 CRSetCrashLogMessage("dyld3: launch, running initializers");
5906 libDyldEntry->runInitialzersBottomUp((mach_header*)mainExecutableMH);
5907 //dyld::log("returned from runInitialzersBottomUp()\n");
5908
5909 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE)) {
5910 dyld3::kdebug_trace_dyld_duration_end(launchTraceID, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE, 0, 0, 3);
5911 }
5912 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5913 if ( gLinkContext.driverKit ) {
5914 *entry = (uintptr_t)sEntryOveride;
5915 if ( *entry == 0 )
5916 halt("no entry point registered");
5917 *startGlue = (uintptr_t)(libDyldEntry->startFunc);
5918 }
5919 else
5920 #endif
5921 {
5922 dyld3::closure::Image::ResolvedSymbolTarget progEntry;
5923 if ( mainClosure->mainEntry(progEntry) ) {
5924 // modern app with LC_MAIN
5925 // set startGlue to "start" function in libdyld.dylib
5926 // set entry to "main" function in program
5927 *startGlue = (uintptr_t)(libDyldEntry->startFunc);
5928 *entry = loader.resolveTarget(progEntry);
5929 }
5930 else if ( mainClosure->startEntry(progEntry) ) {
5931 // old style app linked with crt1.o
5932 // entry is "start" function in program
5933 *startGlue = 0;
5934 *entry = loader.resolveTarget(progEntry);
5935 }
5936 else {
5937 assert(0);
5938 }
5939 }
5940 CRSetCrashLogMessage("dyld3 mode");
5941 return true;
5942 }
5943
5944
5945 static const char* getTempDir(const char* envp[])
5946 {
5947 if (const char* tempDir = _simple_getenv(envp, "TMPDIR"))
5948 return tempDir;
5949
5950 #if __MAC_OS_X_VERSION_MIN_REQUIRED
5951 return "/private/tmp/";
5952 #else
5953 return "/private/var/tmp/";
5954 #endif
5955 }
5956
5957 static const dyld3::closure::LaunchClosure* mapClosureFile(const char* closurePath)
5958 {
5959 struct stat statbuf;
5960 if ( ::stat(closurePath, &statbuf) == -1 )
5961 return nullptr;
5962
5963 // check for tombstone file
5964 if ( statbuf.st_size == 0 )
5965 return nullptr;
5966
5967 int fd = ::open(closurePath, O_RDONLY);
5968 if ( fd < 0 )
5969 return nullptr;
5970
5971 const dyld3::closure::LaunchClosure* closure = (dyld3::closure::LaunchClosure*)::mmap(NULL, (size_t)statbuf.st_size, PROT_READ, MAP_PRIVATE, fd, 0);
5972 ::close(fd);
5973
5974 if ( closure == MAP_FAILED )
5975 return nullptr;
5976
5977 return closure;
5978 }
5979
5980 static bool needsDyld2ErrorMessage(const char* msg)
5981 {
5982 if ( strcmp(msg, "lazy bind opcodes missing binds") == 0 )
5983 return true;
5984 return false;
5985 }
5986
5987
5988 // Note: buildLaunchClosure calls halt() if there is an error building the closure
5989 static const dyld3::closure::LaunchClosure* buildLaunchClosure(const uint8_t* mainExecutableCDHash,
5990 const dyld3::closure::LoadedFileInfo& mainFileInfo, const char* envp[])
5991 {
5992 const dyld3::MachOLoaded* mainExecutableMH = (const dyld3::MachOLoaded*)mainFileInfo.fileContent;
5993 dyld3::closure::PathOverrides pathOverrides;
5994 pathOverrides.setFallbackPathHandling(gLinkContext.allowClassicFallbackPaths ? dyld3::closure::PathOverrides::FallbackPathMode::classic : dyld3::closure::PathOverrides::FallbackPathMode::restricted);
5995 pathOverrides.setEnvVars(envp, mainExecutableMH, mainFileInfo.path);
5996 STACK_ALLOC_ARRAY(const dyld3::closure::ImageArray*, imagesArrays, 3);
5997 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
5998 imagesArrays.push_back(sSharedCacheLoadInfo.loadAddress->cachedDylibsImageArray());
5999 if ( auto others = sSharedCacheLoadInfo.loadAddress->otherOSImageArray() )
6000 imagesArrays.push_back(others);
6001 }
6002
6003 char closurePath[PATH_MAX];
6004 dyld3::closure::ClosureBuilder::LaunchErrorInfo* errorInfo = (dyld3::closure::ClosureBuilder::LaunchErrorInfo*)&gProcessInfo->errorKind;
6005 dyld3::closure::FileSystemPhysical fileSystem;
6006 const dyld3::GradedArchs& archs = dyld3::GradedArchs::forCurrentOS(mainExecutableMH);
6007 dyld3::closure::ClosureBuilder::AtPath atPathHanding = (gLinkContext.allowAtPaths ? dyld3::closure::ClosureBuilder::AtPath::all : dyld3::closure::ClosureBuilder::AtPath::none);
6008 dyld3::closure::ClosureBuilder builder(dyld3::closure::kFirstLaunchClosureImageNum, fileSystem, sSharedCacheLoadInfo.loadAddress, true,
6009 archs, pathOverrides, atPathHanding, gLinkContext.allowEnvVarsPath, errorInfo);
6010 if (sForceInvalidSharedCacheClosureFormat)
6011 builder.setDyldCacheInvalidFormatVersion();
6012 const dyld3::closure::LaunchClosure* result = builder.makeLaunchClosure(mainFileInfo, gLinkContext.allowInsertFailures);
6013 if ( builder.diagnostics().hasError() ) {
6014 const char* errMsg = builder.diagnostics().errorMessage();
6015 // let apps with this error fallback to dyld2 mode
6016 if ( needsDyld2ErrorMessage(errMsg) ) {
6017 if ( dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo.path, closurePath, getTempDir(envp), true) ) {
6018 // create empty file as a tombstone to not keep trying
6019 int fd = ::open(closurePath, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
6020 if ( fd != -1 ) {
6021 ::fchmod(fd, S_IRUSR);
6022 ::close(fd);
6023 if ( gLinkContext.verboseWarnings )
6024 dyld::log("dyld: just built tombstone closure for %s\n", sExecPath);
6025 // We only care about closure failures that do not also cause dyld2 to fail, so defer logging
6026 // until after dyld2 has tried to launch the binary
6027 sLogClosureFailure = true;
6028 }
6029 }
6030 return nullptr;
6031 }
6032 // terminate process
6033 halt(errMsg);
6034 }
6035
6036 if ( result == nullptr )
6037 return nullptr;
6038
6039 if ( !closureValid(result, mainFileInfo, mainExecutableCDHash, false, envp) ) {
6040 // some how the freshly generated closure is invalid...
6041 result->deallocate();
6042 if ( gLinkContext.verboseWarnings )
6043 dyld::log("dyld: somehow just built closure is invalid\n");
6044 return nullptr;
6045 }
6046 // try to atomically save closure to disk to speed up next launch
6047 if ( dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo.path, closurePath, getTempDir(envp), true) ) {
6048 char closurePathTemp[PATH_MAX];
6049 strlcpy(closurePathTemp, closurePath, PATH_MAX);
6050 int mypid = getpid();
6051 char pidBuf[16];
6052 char* s = pidBuf;
6053 *s++ = '.';
6054 putHexByte(mypid >> 24, s);
6055 putHexByte(mypid >> 16, s);
6056 putHexByte(mypid >> 8, s);
6057 putHexByte(mypid, s);
6058 *s = '\0';
6059 strlcat(closurePathTemp, pidBuf, PATH_MAX);
6060 int fd = ::open(closurePathTemp, O_WRONLY|O_CREAT, S_IRUSR|S_IWUSR);
6061 if ( fd != -1 ) {
6062 ::ftruncate(fd, result->size());
6063 ::write(fd, result, result->size());
6064 ::fchmod(fd, S_IRUSR);
6065 ::close(fd);
6066 ::rename(closurePathTemp, closurePath);
6067 // free built closure and mmap file() to reduce dirty memory
6068 result->deallocate();
6069 result = mapClosureFile(closurePath);
6070 }
6071 else if ( gLinkContext.verboseWarnings ) {
6072 dyld::log("could not save closure (errno=%d) to: %s\n", errno, closurePathTemp);
6073 }
6074 }
6075
6076 if ( gLinkContext.verboseWarnings )
6077 dyld::log("dyld: just built closure %p (size=%lu) for %s\n", result, result->size(), sExecPath);
6078
6079 return result;
6080 }
6081
6082 static const dyld3::closure::LaunchClosure* findCachedLaunchClosure(const uint8_t* mainExecutableCDHash,
6083 const dyld3::closure::LoadedFileInfo& mainFileInfo,
6084 const char* envp[])
6085 {
6086 char closurePath[PATH_MAX];
6087 // build base path of $TMPDIR/dyld/<prog-name>-
6088 if ( !dyld3::closure::LaunchClosure::buildClosureCachePath(mainFileInfo.path, closurePath, getTempDir(envp), false) )
6089 return nullptr;
6090 const dyld3::closure::LaunchClosure* closure = mapClosureFile(closurePath);
6091 if ( closure == nullptr )
6092 return nullptr;
6093
6094 if ( !closureValid(closure, mainFileInfo, mainExecutableCDHash, false, envp) ) {
6095 ::munmap((void*)closure, closure->size());
6096 return nullptr;
6097 }
6098
6099 if ( gLinkContext.verboseWarnings )
6100 dyld::log("dyld: used cached closure %p (size=%lu) for %s\n", closure, closure->size(), sExecPath);
6101
6102 return closure;
6103 }
6104
6105 #endif // !TARGET_OS_SIMULATOR
6106
6107
6108 static ClosureMode getPlatformDefaultClosureMode() {
6109 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6110 #if __i386__
6111 // rdar://problem/32701418: Don't use dyld3 for i386 for now.
6112 return ClosureMode::Off;
6113 #else
6114 // x86_64 defaults to using the shared cache closures
6115 return ClosureMode::PreBuiltOnly;
6116 #endif // __i386__
6117
6118 #else
6119 // <rdar://problem/33171968> enable dyld3 mode for all OS programs when using customer dyld cache (no roots)
6120 if ( (sSharedCacheLoadInfo.loadAddress != nullptr) && (sSharedCacheLoadInfo.loadAddress->header.cacheType == kDyldSharedCacheTypeProduction) )
6121 return ClosureMode::On;
6122 else
6123 return ClosureMode::Off;
6124 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
6125 }
6126
6127 //
6128 // Entry point for dyld. The kernel loads dyld and jumps to __dyld_start which
6129 // sets up some registers and call this function.
6130 //
6131 // Returns address of main() in target program which __dyld_start jumps to
6132 //
6133 uintptr_t
6134 _main(const macho_header* mainExecutableMH, uintptr_t mainExecutableSlide,
6135 int argc, const char* argv[], const char* envp[], const char* apple[],
6136 uintptr_t* startGlue)
6137 {
6138 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE)) {
6139 launchTraceID = dyld3::kdebug_trace_dyld_duration_start(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE, (uint64_t)mainExecutableMH, 0, 0);
6140 }
6141
6142 //Check and see if there are any kernel flags
6143 dyld3::BootArgs::setFlags(hexToUInt64(_simple_getenv(apple, "dyld_flags"), nullptr));
6144
6145 // Grab the cdHash of the main executable from the environment
6146 uint8_t mainExecutableCDHashBuffer[20];
6147 const uint8_t* mainExecutableCDHash = nullptr;
6148 if ( hexToBytes(_simple_getenv(apple, "executable_cdhash"), 40, mainExecutableCDHashBuffer) )
6149 mainExecutableCDHash = mainExecutableCDHashBuffer;
6150
6151 #if !TARGET_OS_SIMULATOR
6152 // Trace dyld's load
6153 notifyKernelAboutImage((macho_header*)&__dso_handle, _simple_getenv(apple, "dyld_file"));
6154 // Trace the main executable's load
6155 notifyKernelAboutImage(mainExecutableMH, _simple_getenv(apple, "executable_file"));
6156 #endif
6157
6158 uintptr_t result = 0;
6159 sMainExecutableMachHeader = mainExecutableMH;
6160 sMainExecutableSlide = mainExecutableSlide;
6161
6162
6163 // Set the platform ID in the all image infos so debuggers can tell the process type
6164 // FIXME: This can all be removed once we make the kernel handle it in rdar://43369446
6165 if (gProcessInfo->version >= 16) {
6166 __block bool platformFound = false;
6167 ((dyld3::MachOFile*)mainExecutableMH)->forEachSupportedPlatform(^(dyld3::Platform platform, uint32_t minOS, uint32_t sdk) {
6168 if (platformFound) {
6169 halt("MH_EXECUTE binaries may only specify one platform");
6170 }
6171 gProcessInfo->platform = (uint32_t)platform;
6172 platformFound = true;
6173 });
6174 if (gProcessInfo->platform == (uint32_t)dyld3::Platform::unknown) {
6175 // There were no platforms found in the binary. This may occur on macOS for alternate toolchains and old binaries.
6176 // It should never occur on any of our embedded platforms.
6177 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6178 gProcessInfo->platform = (uint32_t)dyld3::Platform::macOS;
6179 #else
6180 halt("MH_EXECUTE binaries must specify a minimum supported OS version");
6181 #endif
6182 }
6183 }
6184
6185 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6186 // Check to see if we need to override the platform
6187 const char* forcedPlatform = _simple_getenv(envp, "DYLD_FORCE_PLATFORM");
6188 if (forcedPlatform) {
6189 if (strncmp(forcedPlatform, "6", 1) != 0) {
6190 halt("DYLD_FORCE_PLATFORM is only supported for platform 6");
6191 }
6192 const dyld3::MachOFile* mf = (dyld3::MachOFile*)sMainExecutableMachHeader;
6193 if (mf->allowsAlternatePlatform()) {
6194 gProcessInfo->platform = PLATFORM_IOSMAC;
6195 }
6196 }
6197
6198 // if this is host dyld, check to see if iOS simulator is being run
6199 const char* rootPath = _simple_getenv(envp, "DYLD_ROOT_PATH");
6200 if ( (rootPath != NULL) ) {
6201 // look to see if simulator has its own dyld
6202 char simDyldPath[PATH_MAX];
6203 strlcpy(simDyldPath, rootPath, PATH_MAX);
6204 strlcat(simDyldPath, "/usr/lib/dyld_sim", PATH_MAX);
6205 int fd = my_open(simDyldPath, O_RDONLY, 0);
6206 if ( fd != -1 ) {
6207 const char* errMessage = useSimulatorDyld(fd, mainExecutableMH, simDyldPath, argc, argv, envp, apple, startGlue, &result);
6208 if ( errMessage != NULL )
6209 halt(errMessage);
6210 return result;
6211 }
6212 }
6213 else {
6214 ((dyld3::MachOFile*)mainExecutableMH)->forEachSupportedPlatform(^(dyld3::Platform platform, uint32_t minOS, uint32_t sdk) {
6215 if ( dyld3::MachOFile::isSimulatorPlatform(platform) )
6216 halt("attempt to run simulator program outside simulator (DYLD_ROOT_PATH not set)");
6217 });
6218 }
6219 #endif
6220
6221 CRSetCrashLogMessage("dyld: launch started");
6222
6223 setContext(mainExecutableMH, argc, argv, envp, apple);
6224
6225 // Pickup the pointer to the exec path.
6226 sExecPath = _simple_getenv(apple, "executable_path");
6227
6228 // <rdar://problem/13868260> Remove interim apple[0] transition code from dyld
6229 if (!sExecPath) sExecPath = apple[0];
6230
6231 #if __IPHONE_OS_VERSION_MIN_REQUIRED && !TARGET_OS_SIMULATOR
6232 // <rdar://54095622> kernel is not passing a real path for main executable
6233 if ( strncmp(sExecPath, "/var/containers/Bundle/Application/", 35) == 0 ) {
6234 if ( char* newPath = (char*)malloc(strlen(sExecPath)+10) ) {
6235 strcpy(newPath, "/private");
6236 strcat(newPath, sExecPath);
6237 sExecPath = newPath;
6238 }
6239 }
6240 #endif
6241
6242 if ( sExecPath[0] != '/' ) {
6243 // have relative path, use cwd to make absolute
6244 char cwdbuff[MAXPATHLEN];
6245 if ( getcwd(cwdbuff, MAXPATHLEN) != NULL ) {
6246 // maybe use static buffer to avoid calling malloc so early...
6247 char* s = new char[strlen(cwdbuff) + strlen(sExecPath) + 2];
6248 strcpy(s, cwdbuff);
6249 strcat(s, "/");
6250 strcat(s, sExecPath);
6251 sExecPath = s;
6252 }
6253 }
6254
6255 // Remember short name of process for later logging
6256 sExecShortName = ::strrchr(sExecPath, '/');
6257 if ( sExecShortName != NULL )
6258 ++sExecShortName;
6259 else
6260 sExecShortName = sExecPath;
6261
6262 configureProcessRestrictions(mainExecutableMH, envp);
6263
6264 // Check if we should force dyld3. Note we have to do this outside of the regular env parsing due to AMFI
6265 if ( dyld3::internalInstall() ) {
6266 if (const char* useClosures = _simple_getenv(envp, "DYLD_USE_CLOSURES")) {
6267 if ( strcmp(useClosures, "0") == 0 ) {
6268 sClosureMode = ClosureMode::Off;
6269 } else if ( strcmp(useClosures, "1") == 0 ) {
6270 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6271
6272 #if __i386__
6273 // don't support dyld3 for 32-bit macOS
6274 #else
6275 // Also don't support dyld3 for iOSMac right now
6276 if ( gProcessInfo->platform != PLATFORM_IOSMAC ) {
6277 sClosureMode = ClosureMode::On;
6278 }
6279 #endif // __i386__
6280
6281 #else
6282 sClosureMode = ClosureMode::On;
6283 #endif // __MAC_OS_X_VERSION_MIN_REQUIRED
6284 } else {
6285 dyld::warn("unknown option to DYLD_USE_CLOSURES. Valid options are: 0 and 1\n");
6286 }
6287
6288 }
6289 }
6290
6291 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6292 if ( !gLinkContext.allowEnvVarsPrint && !gLinkContext.allowEnvVarsPath && !gLinkContext.allowEnvVarsSharedCache ) {
6293 pruneEnvironmentVariables(envp, &apple);
6294 // set again because envp and apple may have changed or moved
6295 setContext(mainExecutableMH, argc, argv, envp, apple);
6296 }
6297 else
6298 #endif
6299 {
6300 checkEnvironmentVariables(envp);
6301 defaultUninitializedFallbackPaths(envp);
6302 }
6303 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6304 if ( gProcessInfo->platform == PLATFORM_IOSMAC ) {
6305 gLinkContext.rootPaths = parseColonList("/System/iOSSupport", NULL);
6306 gLinkContext.iOSonMac = true;
6307 if ( sEnv.DYLD_FALLBACK_LIBRARY_PATH == sLibraryFallbackPaths )
6308 sEnv.DYLD_FALLBACK_LIBRARY_PATH = sRestrictedLibraryFallbackPaths;
6309 if ( sEnv.DYLD_FALLBACK_FRAMEWORK_PATH == sFrameworkFallbackPaths )
6310 sEnv.DYLD_FALLBACK_FRAMEWORK_PATH = sRestrictedFrameworkFallbackPaths;
6311 }
6312 else if ( ((dyld3::MachOFile*)mainExecutableMH)->supportsPlatform(dyld3::Platform::driverKit) ) {
6313 gLinkContext.driverKit = true;
6314 gLinkContext.sharedRegionMode = ImageLoader::kDontUseSharedRegion;
6315 }
6316 #endif
6317 if ( sEnv.DYLD_PRINT_OPTS )
6318 printOptions(argv);
6319 if ( sEnv.DYLD_PRINT_ENV )
6320 printEnvironmentVariables(envp);
6321
6322 // Parse this envirionment variable outside of the regular logic as we want to accept
6323 // this on binaries without an entitelment
6324 #if !TARGET_OS_SIMULATOR
6325 if ( _simple_getenv(envp, "DYLD_JUST_BUILD_CLOSURE") != nullptr ) {
6326 #if TARGET_OS_IPHONE
6327 const char* tempDir = getTempDir(envp);
6328 if ( (tempDir != nullptr) && (geteuid() != 0) ) {
6329 // Use realpath to prevent something like TMPRIR=/tmp/../usr/bin
6330 char realPath[PATH_MAX];
6331 if ( realpath(tempDir, realPath) != NULL )
6332 tempDir = realPath;
6333 if (strncmp(tempDir, "/private/var/mobile/Containers/", strlen("/private/var/mobile/Containers/")) == 0) {
6334 sJustBuildClosure = true;
6335 }
6336 }
6337 #endif
6338 // If we didn't like the format of TMPDIR, just exit. We don't want to launch the app as that would bring up the UI
6339 if (!sJustBuildClosure) {
6340 _exit(EXIT_SUCCESS);
6341 }
6342 }
6343 #endif
6344
6345 if ( sJustBuildClosure )
6346 sClosureMode = ClosureMode::On;
6347 getHostInfo(mainExecutableMH, mainExecutableSlide);
6348
6349 // load shared cache
6350 checkSharedRegionDisable((dyld3::MachOLoaded*)mainExecutableMH, mainExecutableSlide);
6351 if ( gLinkContext.sharedRegionMode != ImageLoader::kDontUseSharedRegion ) {
6352 #if TARGET_OS_SIMULATOR
6353 if ( sSharedCacheOverrideDir)
6354 mapSharedCache();
6355 #else
6356 mapSharedCache();
6357 #endif
6358 }
6359
6360 // If we haven't got a closure mode yet, then check the environment and cache type
6361 if ( sClosureMode == ClosureMode::Unset ) {
6362 // First test to see if we forced in dyld2 via a kernel boot-arg
6363 if ( dyld3::BootArgs::forceDyld2() ) {
6364 sClosureMode = ClosureMode::Off;
6365 } else if ( inDenyList(sExecPath) ) {
6366 sClosureMode = ClosureMode::Off;
6367 } else if ( sEnv.hasOverride ) {
6368 sClosureMode = ClosureMode::Off;
6369 } else if ( dyld3::BootArgs::forceDyld3() ) {
6370 sClosureMode = ClosureMode::On;
6371 } else {
6372 sClosureMode = getPlatformDefaultClosureMode();
6373 }
6374 }
6375
6376 #if !TARGET_OS_SIMULATOR
6377 if ( sClosureMode == ClosureMode::Off ) {
6378 if ( gLinkContext.verboseWarnings )
6379 dyld::log("dyld: not using closure because of DYLD_USE_CLOSURES or -force_dyld2=1 override\n");
6380 } else {
6381 const dyld3::closure::LaunchClosure* mainClosure = nullptr;
6382 dyld3::closure::LoadedFileInfo mainFileInfo;
6383 mainFileInfo.fileContent = mainExecutableMH;
6384 mainFileInfo.path = sExecPath;
6385 // FIXME: If we are saving this closure, this slice offset/length is probably wrong in the case of FAT files.
6386 mainFileInfo.sliceOffset = 0;
6387 mainFileInfo.sliceLen = -1;
6388 struct stat mainExeStatBuf;
6389 if ( ::stat(sExecPath, &mainExeStatBuf) == 0 ) {
6390 mainFileInfo.inode = mainExeStatBuf.st_ino;
6391 mainFileInfo.mtime = mainExeStatBuf.st_mtime;
6392 }
6393 // check for closure in cache first
6394 if ( sSharedCacheLoadInfo.loadAddress != nullptr ) {
6395 mainClosure = sSharedCacheLoadInfo.loadAddress->findClosure(sExecPath);
6396 if ( gLinkContext.verboseWarnings && (mainClosure != nullptr) )
6397 dyld::log("dyld: found closure %p (size=%lu) in dyld shared cache\n", mainClosure, mainClosure->size());
6398 }
6399
6400 // We only want to try build a closure at runtime if its an iOS third party binary, or a macOS binary from the shared cache
6401 bool allowClosureRebuilds = false;
6402 if ( sClosureMode == ClosureMode::On ) {
6403 allowClosureRebuilds = true;
6404 } else if ( (sClosureMode == ClosureMode::PreBuiltOnly) && (mainClosure != nullptr) ) {
6405 allowClosureRebuilds = true;
6406 }
6407
6408 if ( (mainClosure != nullptr) && !closureValid(mainClosure, mainFileInfo, mainExecutableCDHash, true, envp) )
6409 mainClosure = nullptr;
6410
6411 // If we didn't find a valid cache closure then try build a new one
6412 if ( (mainClosure == nullptr) && allowClosureRebuilds ) {
6413 // if forcing closures, and no closure in cache, or it is invalid, check for cached closure
6414 if ( !sForceInvalidSharedCacheClosureFormat )
6415 mainClosure = findCachedLaunchClosure(mainExecutableCDHash, mainFileInfo, envp);
6416 if ( mainClosure == nullptr ) {
6417 // if no cached closure found, build new one
6418 mainClosure = buildLaunchClosure(mainExecutableCDHash, mainFileInfo, envp);
6419 }
6420 }
6421
6422 // exit dyld after closure is built, without running program
6423 if ( sJustBuildClosure )
6424 _exit(EXIT_SUCCESS);
6425
6426 // try using launch closure
6427 if ( mainClosure != nullptr ) {
6428 CRSetCrashLogMessage("dyld3: launch started");
6429 bool launched = launchWithClosure(mainClosure, sSharedCacheLoadInfo.loadAddress, (dyld3::MachOLoaded*)mainExecutableMH,
6430 mainExecutableSlide, argc, argv, envp, apple, &result, startGlue);
6431 if ( !launched && allowClosureRebuilds ) {
6432 // closure is out of date, build new one
6433 mainClosure = buildLaunchClosure(mainExecutableCDHash, mainFileInfo, envp);
6434 if ( mainClosure != nullptr ) {
6435 launched = launchWithClosure(mainClosure, sSharedCacheLoadInfo.loadAddress, (dyld3::MachOLoaded*)mainExecutableMH,
6436 mainExecutableSlide, argc, argv, envp, apple, &result, startGlue);
6437 }
6438 }
6439 if ( launched ) {
6440 #if __has_feature(ptrauth_calls)
6441 // start() calls the result pointer as a function pointer so we need to sign it.
6442 result = (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)result, 0, 0);
6443 #endif
6444 if (sSkipMain)
6445 result = (uintptr_t)&fake_main;
6446 return result;
6447 }
6448 else {
6449 if ( gLinkContext.verboseWarnings ) {
6450 dyld::log("dyld: unable to use closure %p\n", mainClosure);
6451 }
6452 }
6453 }
6454 }
6455 #endif // TARGET_OS_SIMULATOR
6456 // could not use closure info, launch old way
6457
6458
6459
6460 // install gdb notifier
6461 stateToHandlers(dyld_image_state_dependents_mapped, sBatchHandlers)->push_back(notifyGDB);
6462 stateToHandlers(dyld_image_state_mapped, sSingleHandlers)->push_back(updateAllImages);
6463 // make initial allocations large enough that it is unlikely to need to be re-alloced
6464 sImageRoots.reserve(16);
6465 sAddImageCallbacks.reserve(4);
6466 sRemoveImageCallbacks.reserve(4);
6467 sAddLoadImageCallbacks.reserve(4);
6468 sImageFilesNeedingTermination.reserve(16);
6469 sImageFilesNeedingDOFUnregistration.reserve(8);
6470
6471 #if !TARGET_OS_SIMULATOR
6472 #ifdef WAIT_FOR_SYSTEM_ORDER_HANDSHAKE
6473 // <rdar://problem/6849505> Add gating mechanism to dyld support system order file generation process
6474 WAIT_FOR_SYSTEM_ORDER_HANDSHAKE(dyld::gProcessInfo->systemOrderFlag);
6475 #endif
6476 #endif
6477
6478
6479 try {
6480 // add dyld itself to UUID list
6481 addDyldImageToUUIDList();
6482
6483 #if SUPPORT_ACCELERATE_TABLES
6484 #if __arm64e__
6485 // Disable accelerator tables when we have threaded rebase/bind, which is arm64e executables only for now.
6486 if (sMainExecutableMachHeader->cpusubtype == CPU_SUBTYPE_ARM64E)
6487 sDisableAcceleratorTables = true;
6488 #endif
6489 bool mainExcutableAlreadyRebased = false;
6490 if ( (sSharedCacheLoadInfo.loadAddress != nullptr) && !dylibsCanOverrideCache() && !sDisableAcceleratorTables && (sSharedCacheLoadInfo.loadAddress->header.accelerateInfoAddr != 0) ) {
6491 struct stat statBuf;
6492 if ( ::stat(IPHONE_DYLD_SHARED_CACHE_DIR "no-dyld2-accelerator-tables", &statBuf) != 0 )
6493 sAllCacheImagesProxy = ImageLoaderMegaDylib::makeImageLoaderMegaDylib(&sSharedCacheLoadInfo.loadAddress->header, sSharedCacheLoadInfo.slide, mainExecutableMH, gLinkContext);
6494 }
6495
6496 reloadAllImages:
6497 #endif
6498
6499
6500 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6501 gLinkContext.strictMachORequired = false;
6502 // <rdar://problem/22805519> be less strict about old macOS mach-o binaries
6503 ((dyld3::MachOFile*)mainExecutableMH)->forEachSupportedPlatform(^(dyld3::Platform platform, uint32_t minOS, uint32_t sdk) {
6504 if ( (platform == dyld3::Platform::macOS) && (sdk >= DYLD_PACKED_VERSION(10,15,0)) ) {
6505 gLinkContext.strictMachORequired = true;
6506 }
6507 });
6508 if ( gLinkContext.iOSonMac )
6509 gLinkContext.strictMachORequired = true;
6510 #else
6511 // simulators, iOS, tvOS, watchOS, are always strict
6512 gLinkContext.strictMachORequired = true;
6513 #endif
6514
6515
6516 CRSetCrashLogMessage(sLoadingCrashMessage);
6517 // instantiate ImageLoader for main executable
6518 sMainExecutable = instantiateFromLoadedImage(mainExecutableMH, mainExecutableSlide, sExecPath);
6519 gLinkContext.mainExecutable = sMainExecutable;
6520 gLinkContext.mainExecutableCodeSigned = hasCodeSignatureLoadCommand(mainExecutableMH);
6521
6522 #if TARGET_OS_SIMULATOR
6523 // check main executable is not too new for this OS
6524 {
6525 if ( ! isSimulatorBinary((uint8_t*)mainExecutableMH, sExecPath) ) {
6526 throwf("program was built for a platform that is not supported by this runtime");
6527 }
6528 uint32_t mainMinOS = sMainExecutable->minOSVersion();
6529
6530 // dyld is always built for the current OS, so we can get the current OS version
6531 // from the load command in dyld itself.
6532 uint32_t dyldMinOS = ImageLoaderMachO::minOSVersion((const mach_header*)&__dso_handle);
6533 if ( mainMinOS > dyldMinOS ) {
6534 #if TARGET_OS_WATCH
6535 throwf("app was built for watchOS %d.%d which is newer than this simulator %d.%d",
6536 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
6537 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
6538 #elif TARGET_OS_TV
6539 throwf("app was built for tvOS %d.%d which is newer than this simulator %d.%d",
6540 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
6541 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
6542 #else
6543 throwf("app was built for iOS %d.%d which is newer than this simulator %d.%d",
6544 mainMinOS >> 16, ((mainMinOS >> 8) & 0xFF),
6545 dyldMinOS >> 16, ((dyldMinOS >> 8) & 0xFF));
6546 #endif
6547 }
6548 }
6549 #endif
6550
6551
6552 #if SUPPORT_ACCELERATE_TABLES
6553 sAllImages.reserve((sAllCacheImagesProxy != NULL) ? 16 : INITIAL_IMAGE_COUNT);
6554 #else
6555 sAllImages.reserve(INITIAL_IMAGE_COUNT);
6556 #endif
6557
6558 // Now that shared cache is loaded, setup an versioned dylib overrides
6559 #if SUPPORT_VERSIONED_PATHS
6560 checkVersionedPaths();
6561 #endif
6562
6563
6564 // dyld_all_image_infos image list does not contain dyld
6565 // add it as dyldPath field in dyld_all_image_infos
6566 // for simulator, dyld_sim is in image list, need host dyld added
6567 #if TARGET_OS_SIMULATOR
6568 // get path of host dyld from table of syscall vectors in host dyld
6569 void* addressInDyld = gSyscallHelpers;
6570 #else
6571 // get path of dyld itself
6572 void* addressInDyld = (void*)&__dso_handle;
6573 #endif
6574 char dyldPathBuffer[MAXPATHLEN+1];
6575 int len = proc_regionfilename(getpid(), (uint64_t)(long)addressInDyld, dyldPathBuffer, MAXPATHLEN);
6576 if ( len > 0 ) {
6577 dyldPathBuffer[len] = '\0'; // proc_regionfilename() does not zero terminate returned string
6578 if ( strcmp(dyldPathBuffer, gProcessInfo->dyldPath) != 0 )
6579 gProcessInfo->dyldPath = strdup(dyldPathBuffer);
6580 }
6581
6582 // load any inserted libraries
6583 if ( sEnv.DYLD_INSERT_LIBRARIES != NULL ) {
6584 for (const char* const* lib = sEnv.DYLD_INSERT_LIBRARIES; *lib != NULL; ++lib)
6585 loadInsertedDylib(*lib);
6586 }
6587 // record count of inserted libraries so that a flat search will look at
6588 // inserted libraries, then main, then others.
6589 sInsertedDylibCount = sAllImages.size()-1;
6590
6591 // link main executable
6592 gLinkContext.linkingMainExecutable = true;
6593 #if SUPPORT_ACCELERATE_TABLES
6594 if ( mainExcutableAlreadyRebased ) {
6595 // previous link() on main executable has already adjusted its internal pointers for ASLR
6596 // work around that by rebasing by inverse amount
6597 sMainExecutable->rebase(gLinkContext, -mainExecutableSlide);
6598 }
6599 #endif
6600 link(sMainExecutable, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
6601 sMainExecutable->setNeverUnloadRecursive();
6602 if ( sMainExecutable->forceFlat() ) {
6603 gLinkContext.bindFlat = true;
6604 gLinkContext.prebindUsage = ImageLoader::kUseNoPrebinding;
6605 }
6606
6607 // link any inserted libraries
6608 // do this after linking main executable so that any dylibs pulled in by inserted
6609 // dylibs (e.g. libSystem) will not be in front of dylibs the program uses
6610 if ( sInsertedDylibCount > 0 ) {
6611 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
6612 ImageLoader* image = sAllImages[i+1];
6613 link(image, sEnv.DYLD_BIND_AT_LAUNCH, true, ImageLoader::RPathChain(NULL, NULL), -1);
6614 image->setNeverUnloadRecursive();
6615 }
6616 // only INSERTED libraries can interpose
6617 // register interposing info after all inserted libraries are bound so chaining works
6618 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
6619 ImageLoader* image = sAllImages[i+1];
6620 image->registerInterposing(gLinkContext);
6621 }
6622 }
6623
6624 // <rdar://problem/19315404> dyld should support interposition even without DYLD_INSERT_LIBRARIES
6625 for (long i=sInsertedDylibCount+1; i < sAllImages.size(); ++i) {
6626 ImageLoader* image = sAllImages[i];
6627 if ( image->inSharedCache() )
6628 continue;
6629 image->registerInterposing(gLinkContext);
6630 }
6631 #if SUPPORT_ACCELERATE_TABLES
6632 if ( (sAllCacheImagesProxy != NULL) && ImageLoader::haveInterposingTuples() ) {
6633 // Accelerator tables cannot be used with implicit interposing, so relaunch with accelerator tables disabled
6634 ImageLoader::clearInterposingTuples();
6635 // unmap all loaded dylibs (but not main executable)
6636 for (long i=1; i < sAllImages.size(); ++i) {
6637 ImageLoader* image = sAllImages[i];
6638 if ( image == sMainExecutable )
6639 continue;
6640 if ( image == sAllCacheImagesProxy )
6641 continue;
6642 image->setCanUnload();
6643 ImageLoader::deleteImage(image);
6644 }
6645 // 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
6646 sAllImages.clear();
6647 sImageRoots.clear();
6648 sImageFilesNeedingTermination.clear();
6649 sImageFilesNeedingDOFUnregistration.clear();
6650 sAddImageCallbacks.clear();
6651 sRemoveImageCallbacks.clear();
6652 sAddLoadImageCallbacks.clear();
6653 sAddBulkLoadImageCallbacks.clear();
6654 sDisableAcceleratorTables = true;
6655 sAllCacheImagesProxy = NULL;
6656 sMappedRangesStart = NULL;
6657 mainExcutableAlreadyRebased = true;
6658 gLinkContext.linkingMainExecutable = false;
6659 resetAllImages();
6660 goto reloadAllImages;
6661 }
6662 #endif
6663
6664 // apply interposing to initial set of images
6665 for(int i=0; i < sImageRoots.size(); ++i) {
6666 sImageRoots[i]->applyInterposing(gLinkContext);
6667 }
6668 ImageLoader::applyInterposingToDyldCache(gLinkContext);
6669
6670 // Bind and notify for the main executable now that interposing has been registered
6671 uint64_t bindMainExecutableStartTime = mach_absolute_time();
6672 sMainExecutable->recursiveBindWithAccounting(gLinkContext, sEnv.DYLD_BIND_AT_LAUNCH, true);
6673 uint64_t bindMainExecutableEndTime = mach_absolute_time();
6674 ImageLoaderMachO::fgTotalBindTime += bindMainExecutableEndTime - bindMainExecutableStartTime;
6675 gLinkContext.notifyBatch(dyld_image_state_bound, false);
6676
6677 // Bind and notify for the inserted images now interposing has been registered
6678 if ( sInsertedDylibCount > 0 ) {
6679 for(unsigned int i=0; i < sInsertedDylibCount; ++i) {
6680 ImageLoader* image = sAllImages[i+1];
6681 image->recursiveBind(gLinkContext, sEnv.DYLD_BIND_AT_LAUNCH, true);
6682 }
6683 }
6684
6685 // <rdar://problem/12186933> do weak binding only after all inserted images linked
6686 sMainExecutable->weakBind(gLinkContext);
6687 gLinkContext.linkingMainExecutable = false;
6688
6689 sMainExecutable->recursiveMakeDataReadOnly(gLinkContext);
6690
6691 CRSetCrashLogMessage("dyld: launch, running initializers");
6692 #if SUPPORT_OLD_CRT_INITIALIZATION
6693 // Old way is to run initializers via a callback from crt1.o
6694 if ( ! gRunInitializersOldWay )
6695 initializeMainExecutable();
6696 #else
6697 // run all initializers
6698 initializeMainExecutable();
6699 #endif
6700
6701 // notify any montoring proccesses that this process is about to enter main()
6702 notifyMonitoringDyldMain();
6703 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE)) {
6704 dyld3::kdebug_trace_dyld_duration_end(launchTraceID, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE, 0, 0, 2);
6705 }
6706 ARIADNEDBG_CODE(220, 1);
6707
6708 #if __MAC_OS_X_VERSION_MIN_REQUIRED
6709 if ( gLinkContext.driverKit ) {
6710 result = (uintptr_t)sEntryOveride;
6711 if ( result == 0 )
6712 halt("no entry point registered");
6713 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
6714 }
6715 else
6716 #endif
6717 {
6718 // find entry point for main executable
6719 result = (uintptr_t)sMainExecutable->getEntryFromLC_MAIN();
6720 if ( result != 0 ) {
6721 // main executable uses LC_MAIN, we need to use helper in libdyld to call into main()
6722 if ( (gLibSystemHelpers != NULL) && (gLibSystemHelpers->version >= 9) )
6723 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
6724 else
6725 halt("libdyld.dylib support not present for LC_MAIN");
6726 }
6727 else {
6728 // main executable uses LC_UNIXTHREAD, dyld needs to let "start" in program set up for main()
6729 result = (uintptr_t)sMainExecutable->getEntryFromLC_UNIXTHREAD();
6730 *startGlue = 0;
6731 }
6732 }
6733 #if __has_feature(ptrauth_calls)
6734 // start() calls the result pointer as a function pointer so we need to sign it.
6735 result = (uintptr_t)__builtin_ptrauth_sign_unauthenticated((void*)result, 0, 0);
6736 #endif
6737 }
6738 catch(const char* message) {
6739 syncAllImages();
6740 halt(message);
6741 }
6742 catch(...) {
6743 dyld::log("dyld: launch failed\n");
6744 }
6745
6746 CRSetCrashLogMessage("dyld2 mode");
6747 #if !TARGET_OS_SIMULATOR
6748 if (sLogClosureFailure) {
6749 // We failed to launch in dyld3, but dyld2 can handle it. synthesize a crash report for analytics
6750 dyld3::syntheticBacktrace("Could not generate launchClosure, falling back to dyld2", true);
6751 }
6752 #endif
6753
6754 if (sSkipMain) {
6755 notifyMonitoringDyldMain();
6756 if (dyld3::kdebug_trace_dyld_enabled(DBG_DYLD_TIMING_LAUNCH_EXECUTABLE)) {
6757 dyld3::kdebug_trace_dyld_duration_end(launchTraceID, DBG_DYLD_TIMING_LAUNCH_EXECUTABLE, 0, 0, 2);
6758 }
6759 ARIADNEDBG_CODE(220, 1);
6760 result = (uintptr_t)&fake_main;
6761 *startGlue = (uintptr_t)gLibSystemHelpers->startGlueToCallExit;
6762 }
6763
6764 return result;
6765 }
6766
6767
6768 } // namespace
6769
6770
6771