dyld-832.7.1.tar.gz
[apple/dyld.git] / src / dyldAPIsInLibSystem.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2012 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 <stddef.h>
26 #include <string.h>
27 #include <malloc/malloc.h>
28 #include <sys/mman.h>
29 #include <execinfo.h>
30
31 #include <TargetConditionals.h>
32 #include <System/sys/csr.h>
33 #include <crt_externs.h>
34 #include <Availability.h>
35 #if !TARGET_OS_DRIVERKIT
36 #include <vproc_priv.h>
37 #endif
38 #include <dirent.h>
39 #include <sys/types.h>
40 #include <sys/stat.h>
41 #include <fcntl.h>
42 #include <System/sys/codesign.h>
43 #include <libc_private.h>
44
45 #include <mach-o/dyld_images.h>
46 #include <mach-o/dyld.h>
47 #include <mach-o/dyld_priv.h>
48
49 #include "dyld_cache_format.h"
50 #include "objc-shared-cache.h"
51
52 #include "ImageLoader.h"
53 #include "dyldLock.h"
54
55 #include "APIs.h"
56 #include "AllImages.h"
57 #include "StartGlue.h"
58 #include "Tracing.h"
59
60
61 // this was in dyld_priv.h but it is no longer exported
62 extern "C" {
63 const struct dyld_all_image_infos* _dyld_get_all_image_infos() __attribute__((visibility("hidden")));
64 }
65
66
67 extern "C" int __cxa_atexit(void (*func)(void *), void *arg, void *dso);
68 extern "C" void __cxa_finalize(const void *dso);
69 extern "C" void __cxa_finalize_ranges(const struct __cxa_range_t ranges[], int count);
70
71 //
72 // private interface between libSystem.dylib and dyld
73 //
74 extern "C" int _dyld_func_lookup(const char* dyld_func_name, void **address);
75
76 #if TARGET_OS_IOS && !TARGET_OS_SIMULATOR
77 namespace dyld3 {
78 extern int compatFuncLookup(const char* name, void** address) __API_AVAILABLE(ios(13.0));
79 }
80 extern "C" void setLookupFunc(void*);
81 #endif
82
83
84 extern bool gUseDyld3;
85
86
87 // <rdar://problem/61161069> libdyld.dylib should use abort_with_payload() for asserts
88 VIS_HIDDEN
89 void abort_report_np(const char* format, ...)
90 {
91 va_list list;
92 const char *str;
93 _SIMPLE_STRING s = _simple_salloc();
94 if ( s != NULL ) {
95 va_start(list, format);
96 _simple_vsprintf(s, format, list);
97 va_end(list);
98 str = _simple_string(s);
99 }
100 else {
101 // _simple_salloc failed, but at least format may have useful info by itself
102 str = format;
103 }
104 if ( gUseDyld3 ) {
105 dyld3::halt(str);
106 }
107 else {
108 void (*p)(const char* msg) __attribute__((__noreturn__));
109 _dyld_func_lookup("__dyld_halt", (void**)&p);
110 p(str);
111 }
112 // halt() doesn't return, so we can't call _simple_sfree
113 }
114
115 // libc uses assert()
116 #pragma clang diagnostic push
117 #pragma clang diagnostic ignored "-Winvalid-noreturn"
118 VIS_HIDDEN
119 void __assert_rtn(const char* func, const char* file, int line, const char* failedexpr)
120 {
121 if (func == NULL) {
122 abort_report_np("Assertion failed: (%s), file %s, line %d.\n", failedexpr, file, line);
123 } else {
124 abort_report_np("Assertion failed: (%s), function %s, file %s, line %d.\n", failedexpr, func, file, line);
125 }
126 }
127 #pragma clang diagnostic pop
128
129
130 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
131 #if TARGET_OS_OSX
132 #define DEPRECATED_APIS_SUPPORTED 1
133 #else
134 #define DEPRECATED_APIS_SUPPORTED 0
135 #endif
136
137 /*
138 * names_match() takes an install_name from an LC_LOAD_DYLIB command and a
139 * libraryName (which is -lx or -framework Foo argument passed to the static
140 * link editor for the same library) and determines if they match. This depends
141 * on conventional use of names including major versioning.
142 */
143 static
144 bool
145 names_match(
146 const char *install_name,
147 const char* libraryName)
148 {
149 const char *basename;
150 unsigned long n;
151
152 /*
153 * Conventional install names have these forms:
154 * /System/Library/Frameworks/AppKit.framework/Versions/A/Appkit
155 * /Local/Library/Frameworks/AppKit.framework/Appkit
156 * /lib/libsys_s.A.dylib
157 * /usr/lib/libsys_s.dylib
158 */
159 basename = strrchr(install_name, '/');
160 if(basename == NULL)
161 basename = install_name;
162 else
163 basename++;
164
165 /*
166 * By checking the base name matching the library name we take care
167 * of the -framework cases.
168 */
169 if(strcmp(basename, libraryName) == 0)
170 return true;
171
172 /*
173 * Now check the base name for "lib" if so proceed to check for the
174 * -lx case dealing with a possible .X.dylib and a .dylib extension.
175 */
176 if(strncmp(basename, "lib", 3) ==0){
177 n = strlen(libraryName);
178 if(strncmp(basename+3, libraryName, n) == 0){
179 if(strncmp(basename+3+n, ".dylib", 6) == 0)
180 return true;
181 if(basename[3+n] == '.' &&
182 basename[3+n+1] != '\0' &&
183 strncmp(basename+3+n+2, ".dylib", 6) == 0)
184 return true;
185 }
186 }
187 return false;
188 }
189
190 #if DEPRECATED_APIS_SUPPORTED
191
192 void NSInstallLinkEditErrorHandlers(
193 const NSLinkEditErrorHandlers* handlers)
194 {
195 if ( gUseDyld3 )
196 return dyld3::NSInstallLinkEditErrorHandlers(handlers);
197
198 DYLD_LOCK_THIS_BLOCK;
199 typedef void (*ucallback_t)(const char* symbol_name);
200 typedef NSModule (*mcallback_t)(NSSymbol s, NSModule old, NSModule newhandler);
201 typedef void (*lcallback_t)(NSLinkEditErrors c, int errorNumber,
202 const char* fileName, const char* errorString);
203 static void (*p)(ucallback_t undefined, mcallback_t multiple, lcallback_t linkEdit) = NULL;
204
205 if(p == NULL)
206 _dyld_func_lookup("__dyld_install_handlers", (void**)&p);
207 mcallback_t m = handlers->multiple;
208 p(handlers->undefined, m, handlers->linkEdit);
209 }
210
211 const char*
212 NSNameOfModule(
213 NSModule module)
214 {
215 if ( gUseDyld3 )
216 return dyld3::NSNameOfModule(module);
217
218 DYLD_LOCK_THIS_BLOCK;
219 static const char* (*p)(NSModule module) = NULL;
220
221 if(p == NULL)
222 _dyld_func_lookup("__dyld_NSNameOfModule", (void**)&p);
223 return(p(module));
224 }
225
226 const char*
227 NSLibraryNameForModule(
228 NSModule module)
229 {
230 if ( gUseDyld3 )
231 return dyld3::NSLibraryNameForModule(module);
232
233 DYLD_LOCK_THIS_BLOCK;
234 static const char* (*p)(NSModule module) = NULL;
235
236 if(p == NULL)
237 _dyld_func_lookup("__dyld_NSLibraryNameForModule", (void**)&p);
238 return(p(module));
239 }
240
241 bool
242 NSIsSymbolNameDefined(
243 const char* symbolName)
244 {
245 if ( gUseDyld3 )
246 return dyld3::NSIsSymbolNameDefined(symbolName);
247
248 DYLD_LOCK_THIS_BLOCK;
249 static bool (*p)(const char* symbolName) = NULL;
250
251 if(p == NULL)
252 _dyld_func_lookup("__dyld_NSIsSymbolNameDefined", (void**)&p);
253 return(p(symbolName));
254 }
255
256 bool
257 NSIsSymbolNameDefinedWithHint(
258 const char* symbolName,
259 const char* libraryNameHint)
260 {
261 if ( gUseDyld3 )
262 return dyld3::NSIsSymbolNameDefinedWithHint(symbolName, libraryNameHint);
263
264 DYLD_LOCK_THIS_BLOCK;
265 static bool (*p)(const char* symbolName,
266 const char* libraryNameHint) = NULL;
267
268 if(p == NULL)
269 _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedWithHint", (void**)&p);
270 return(p(symbolName, libraryNameHint));
271 }
272
273 bool
274 NSIsSymbolNameDefinedInImage(
275 const struct mach_header *image,
276 const char* symbolName)
277 {
278 if ( gUseDyld3 )
279 return dyld3::NSIsSymbolNameDefinedInImage(image, symbolName);
280
281 DYLD_LOCK_THIS_BLOCK;
282 static bool (*p)(const struct mach_header *image,
283 const char* symbolName) = NULL;
284
285 if(p == NULL)
286 _dyld_func_lookup("__dyld_NSIsSymbolNameDefinedInImage", (void**)&p);
287 return(p(image, symbolName));
288 }
289
290 NSSymbol
291 NSLookupAndBindSymbol(
292 const char* symbolName)
293 {
294 if ( gUseDyld3 )
295 return dyld3::NSLookupAndBindSymbol(symbolName);
296
297 DYLD_LOCK_THIS_BLOCK;
298 static NSSymbol (*p)(const char* symbolName) = NULL;
299
300 if(p == NULL)
301 _dyld_func_lookup("__dyld_NSLookupAndBindSymbol", (void**)&p);
302 return(p(symbolName));
303 }
304
305 NSSymbol
306 NSLookupAndBindSymbolWithHint(
307 const char* symbolName,
308 const char* libraryNameHint)
309 {
310 if ( gUseDyld3 )
311 return dyld3::NSLookupAndBindSymbolWithHint(symbolName, libraryNameHint);
312
313 DYLD_LOCK_THIS_BLOCK;
314 static NSSymbol (*p)(const char* symbolName,
315 const char* libraryNameHint) = NULL;
316
317 if(p == NULL)
318 _dyld_func_lookup("__dyld_NSLookupAndBindSymbolWithHint", (void**)&p);
319 return(p(symbolName, libraryNameHint));
320 }
321
322 NSSymbol
323 NSLookupSymbolInModule(
324 NSModule module,
325 const char* symbolName)
326 {
327 if ( gUseDyld3 )
328 return dyld3::NSLookupSymbolInModule(module, symbolName);
329
330 DYLD_LOCK_THIS_BLOCK;
331 static NSSymbol (*p)(NSModule module, const char* symbolName) = NULL;
332
333 if(p == NULL)
334 _dyld_func_lookup("__dyld_NSLookupSymbolInModule", (void**)&p);
335 return(p(module, symbolName));
336 }
337
338 NSSymbol
339 NSLookupSymbolInImage(
340 const struct mach_header *image,
341 const char* symbolName,
342 uint32_t options)
343 {
344 if ( gUseDyld3 )
345 return dyld3::NSLookupSymbolInImage(image, symbolName, options);
346
347 DYLD_LOCK_THIS_BLOCK;
348 static NSSymbol (*p)(const struct mach_header *image,
349 const char* symbolName,
350 uint32_t options) = NULL;
351
352 if(p == NULL)
353 _dyld_func_lookup("__dyld_NSLookupSymbolInImage", (void**)&p);
354 return(p(image, symbolName, options));
355 }
356
357 const char*
358 NSNameOfSymbol(
359 NSSymbol symbol)
360 {
361 if ( gUseDyld3 )
362 return dyld3::NSNameOfSymbol(symbol);
363
364 DYLD_LOCK_THIS_BLOCK;
365 static char * (*p)(NSSymbol symbol) = NULL;
366
367 if(p == NULL)
368 _dyld_func_lookup("__dyld_NSNameOfSymbol",(void**)&p);
369 return(p(symbol));
370 }
371
372 void *
373 NSAddressOfSymbol(
374 NSSymbol symbol)
375 {
376 if ( gUseDyld3 )
377 return dyld3::NSAddressOfSymbol(symbol);
378
379 DYLD_LOCK_THIS_BLOCK;
380 static void * (*p)(NSSymbol symbol) = NULL;
381
382 if(p == NULL)
383 _dyld_func_lookup("__dyld_NSAddressOfSymbol", (void**)&p);
384 return(p(symbol));
385 }
386
387 NSModule
388 NSModuleForSymbol(
389 NSSymbol symbol)
390 {
391 if ( gUseDyld3 )
392 return dyld3::NSModuleForSymbol(symbol);
393
394 DYLD_LOCK_THIS_BLOCK;
395 static NSModule (*p)(NSSymbol symbol) = NULL;
396
397 if(p == NULL)
398 _dyld_func_lookup("__dyld_NSModuleForSymbol", (void**)&p);
399 return(p(symbol));
400 }
401
402 bool
403 NSAddLibrary(
404 const char* pathName)
405 {
406 if ( gUseDyld3 )
407 return dyld3::NSAddLibrary(pathName);
408
409 DYLD_LOCK_THIS_BLOCK;
410 static bool (*p)(const char* pathName) = NULL;
411
412 if(p == NULL)
413 _dyld_func_lookup("__dyld_NSAddLibrary", (void**)&p);
414 return(p(pathName));
415 }
416
417 bool
418 NSAddLibraryWithSearching(
419 const char* pathName)
420 {
421 if ( gUseDyld3 )
422 return dyld3::NSAddLibrary(pathName);
423
424 DYLD_LOCK_THIS_BLOCK;
425 static bool (*p)(const char* pathName) = NULL;
426
427 if(p == NULL)
428 _dyld_func_lookup("__dyld_NSAddLibraryWithSearching", (void**)&p);
429 return(p(pathName));
430 }
431
432 const struct mach_header *
433 NSAddImage(
434 const char* image_name,
435 uint32_t options)
436 {
437 if ( gUseDyld3 )
438 return dyld3::NSAddImage(image_name, options);
439
440 DYLD_LOCK_THIS_BLOCK;
441 static const struct mach_header * (*p)(const char* image_name,
442 uint32_t options) = NULL;
443
444 if(p == NULL)
445 _dyld_func_lookup("__dyld_NSAddImage", (void**)&p);
446 return(p(image_name, options));
447 }
448 #endif // DEPRECATED_APIS_SUPPORTED
449
450 /*
451 * This routine returns the current version of the named shared library the
452 * executable it was built with. The libraryName parameter is the same as the
453 * -lx or -framework Foo argument passed to the static link editor when building
454 * the executable (with -lx it would be "x" and with -framework Foo it would be
455 * "Foo"). If this the executable was not built against the specified library
456 * it returns -1. It should be noted that if this only returns the value the
457 * current version of the named shared library the executable was built with
458 * and not a list of current versions that dependent libraries and bundles the
459 * program is using were built with.
460 */
461 int32_t NSVersionOfLinkTimeLibrary(const char* libraryName)
462 {
463 if ( gUseDyld3 )
464 return dyld3::NSVersionOfLinkTimeLibrary(libraryName);
465
466 // Lazily call _NSGetMachExecuteHeader() and cache result
467 #if __LP64__
468 static mach_header_64* mh = NULL;
469 #else
470 static mach_header* mh = NULL;
471 #endif
472 if ( mh == NULL )
473 mh = _NSGetMachExecuteHeader();
474 #if __LP64__
475 const load_command* lc = (load_command*)((char*)mh + sizeof(mach_header_64));
476 #else
477 const load_command* lc = (load_command*)((char*)mh + sizeof(mach_header));
478 #endif
479 for(uint32_t i = 0; i < mh->ncmds; i++){
480 switch ( lc->cmd ) {
481 case LC_LOAD_DYLIB:
482 case LC_LOAD_WEAK_DYLIB:
483 case LC_LOAD_UPWARD_DYLIB:
484 const dylib_command* dl = (dylib_command *)lc;
485 const char* install_name = (char*)dl + dl->dylib.name.offset;
486 if ( names_match(install_name, libraryName) )
487 return dl->dylib.current_version;
488 break;
489 }
490 lc = (load_command*)((char*)lc + lc->cmdsize);
491 }
492 return (-1);
493 }
494
495 /*
496 * This routine returns the current version of the named shared library the
497 * program it is running against. The libraryName parameter is the same as
498 * would be static link editor using the -lx or -framework Foo flags (with -lx
499 * it would be "x" and with -framework Foo it would be "Foo"). If the program
500 * is not using the specified library it returns -1.
501 */
502 int32_t NSVersionOfRunTimeLibrary(const char* libraryName)
503 {
504 if ( gUseDyld3 )
505 return dyld3::NSVersionOfRunTimeLibrary(libraryName);
506
507 uint32_t n = _dyld_image_count();
508 for(uint32_t i = 0; i < n; i++){
509 const mach_header* mh = _dyld_get_image_header(i);
510 if ( mh == NULL )
511 continue;
512 if ( mh->filetype != MH_DYLIB )
513 continue;
514 #if __LP64__
515 const load_command* lc = (load_command*)((char*)mh + sizeof(mach_header_64));
516 #else
517 const load_command* lc = (load_command*)((char*)mh + sizeof(mach_header));
518 #endif
519 for(uint32_t j = 0; j < mh->ncmds; j++){
520 if ( lc->cmd == LC_ID_DYLIB ) {
521 const dylib_command* dl = (dylib_command*)lc;
522 const char* install_name = (char *)dl + dl->dylib.name.offset;
523 if ( names_match(install_name, libraryName) )
524 return dl->dylib.current_version;
525 }
526 lc = (load_command*)((char*)lc + lc->cmdsize);
527 }
528 }
529 return (-1);
530 }
531
532 #if TARGET_OS_WATCH
533 uint32_t dyld_get_program_sdk_watch_os_version()
534 {
535 if (gUseDyld3)
536 return dyld3::dyld_get_program_sdk_watch_os_version();
537
538 __block uint32_t retval = 0;
539 __block bool versionFound = false;
540 dyld3::dyld_get_image_versions((mach_header*)_NSGetMachExecuteHeader(), ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
541 if (versionFound) return;
542
543 if (dyld_get_base_platform(platform) == PLATFORM_WATCHOS) {
544 versionFound = true;
545 retval = sdk_version;
546 }
547 });
548
549 return retval;
550 }
551
552 uint32_t dyld_get_program_min_watch_os_version()
553 {
554 if (gUseDyld3)
555 return dyld3::dyld_get_program_min_watch_os_version();
556
557 __block uint32_t retval = 0;
558 __block bool versionFound = false;
559 dyld3::dyld_get_image_versions((mach_header*)_NSGetMachExecuteHeader(), ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
560 if (versionFound) return;
561
562 if (dyld_get_base_platform(platform) == PLATFORM_WATCHOS) {
563 versionFound = true;
564 retval = min_version;
565 }
566 });
567
568 return retval;
569 }
570 #endif
571
572 #if TARGET_OS_BRIDGE
573 uint32_t dyld_get_program_sdk_bridge_os_version()
574 {
575 if (gUseDyld3)
576 return dyld3::dyld_get_program_sdk_bridge_os_version();
577
578 __block uint32_t retval = 0;
579 __block bool versionFound = false;
580 dyld3::dyld_get_image_versions((mach_header*)_NSGetMachExecuteHeader(), ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
581 if (versionFound) return;
582
583 if (dyld_get_base_platform(platform) == PLATFORM_BRIDGEOS) {
584 versionFound = true;
585 retval = sdk_version;
586 }
587 });
588
589 return retval;
590 }
591
592 uint32_t dyld_get_program_min_bridge_os_version()
593 {
594 if (gUseDyld3)
595 return dyld3::dyld_get_program_min_bridge_os_version();
596
597 __block uint32_t retval = 0;
598 __block bool versionFound = false;
599 dyld3::dyld_get_image_versions((mach_header*)_NSGetMachExecuteHeader(), ^(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version) {
600 if (versionFound) return;
601
602 if (dyld_get_base_platform(platform) == PLATFORM_BRIDGEOS) {
603 versionFound = true;
604 retval = min_version;
605 }
606 });
607
608 return retval;
609 }
610 #endif
611
612 /*
613 * Returns the sdk version (encode as nibble XXXX.YY.ZZ) the
614 * specified binary was built against.
615 *
616 * First looks for LC_VERSION_MIN_* in binary and if sdk field is
617 * not zero, return that value.
618 * Otherwise, looks for the libSystem.B.dylib the binary linked
619 * against and uses a table to convert that to an sdk version.
620 */
621 uint32_t dyld_get_sdk_version(const mach_header* mh)
622 {
623 return dyld3::dyld_get_sdk_version(mh);
624 }
625
626 uint32_t dyld_get_program_sdk_version()
627 {
628 return dyld3::dyld_get_sdk_version((mach_header*)_NSGetMachExecuteHeader());
629 }
630
631 uint32_t dyld_get_min_os_version(const struct mach_header* mh)
632 {
633 return dyld3::dyld_get_min_os_version(mh);
634 }
635
636
637 uint32_t dyld_get_program_min_os_version()
638 {
639 return dyld3::dyld_get_min_os_version((mach_header*)_NSGetMachExecuteHeader());
640 }
641
642
643 bool _dyld_get_image_uuid(const struct mach_header* mh, uuid_t uuid)
644 {
645 if ( gUseDyld3 )
646 return dyld3::_dyld_get_image_uuid(mh, uuid);
647
648 const load_command* startCmds = NULL;
649 if ( mh->magic == MH_MAGIC_64 )
650 startCmds = (load_command*)((char *)mh + sizeof(mach_header_64));
651 else if ( mh->magic == MH_MAGIC )
652 startCmds = (load_command*)((char *)mh + sizeof(mach_header));
653 else
654 return false; // not a mach-o file, or wrong endianness
655
656 const load_command* const cmdsEnd = (load_command*)((char*)startCmds + mh->sizeofcmds);
657 const load_command* cmd = startCmds;
658 for(uint32_t i = 0; i < mh->ncmds; ++i) {
659 const load_command* nextCmd = (load_command*)((char *)cmd + cmd->cmdsize);
660 if ( (cmd->cmdsize < 8) || (nextCmd > cmdsEnd) || (nextCmd < startCmds)) {
661 return false;
662 }
663 if ( cmd->cmd == LC_UUID ) {
664 const uuid_command* uuidCmd = (uuid_command*)cmd;
665 memcpy(uuid, uuidCmd->uuid, 16);
666 return true;
667 }
668 cmd = nextCmd;
669 }
670 bzero(uuid, 16);
671 return false;
672 }
673
674 dyld_platform_t dyld_get_active_platform(void) {
675 if (gUseDyld3)
676 return dyld3::dyld_get_active_platform();
677
678 return (dyld_platform_t)_dyld_get_all_image_infos()->platform;
679 }
680
681 dyld_platform_t dyld_get_base_platform(dyld_platform_t platform) {
682 return dyld3::dyld_get_base_platform(platform);
683 }
684
685 bool dyld_is_simulator_platform(dyld_platform_t platform) {
686 return dyld3::dyld_is_simulator_platform(platform);
687 }
688
689 bool dyld_sdk_at_least(const struct mach_header* mh, dyld_build_version_t version) {
690 return dyld3::dyld_sdk_at_least(mh, version);
691 }
692
693 bool dyld_minos_at_least(const struct mach_header* mh, dyld_build_version_t version) {
694 return dyld3::dyld_minos_at_least(mh, version);
695 }
696
697 bool dyld_program_sdk_at_least(dyld_build_version_t version) {
698 return dyld3::dyld_program_sdk_at_least(version);
699 }
700
701 bool dyld_program_minos_at_least(dyld_build_version_t version) {
702 return dyld3::dyld_program_minos_at_least(version);
703 }
704
705 // Function that walks through the load commands and calls the internal block for every version found
706 // Intended as a fallback for very complex (and rare) version checks, or for tools that need to
707 // print our everything for diagnostic reasons
708 void dyld_get_image_versions(const struct mach_header* mh, void (^callback)(dyld_platform_t platform, uint32_t sdk_version, uint32_t min_version)) {
709 dyld3::dyld_get_image_versions(mh, callback);
710 }
711
712
713
714 #if DEPRECATED_APIS_SUPPORTED
715 /*
716 * NSCreateObjectFileImageFromFile() creates an NSObjectFileImage for the
717 * specified file name if the file is a correct Mach-O file that can be loaded
718 * with NSloadModule(). For return codes of NSObjectFileImageFailure and
719 * NSObjectFileImageFormat an error message is printed to stderr. All
720 * other codes cause no printing.
721 */
722 NSObjectFileImageReturnCode
723 NSCreateObjectFileImageFromFile(
724 const char* pathName,
725 NSObjectFileImage *objectFileImage)
726 {
727 if ( gUseDyld3 )
728 return dyld3::NSCreateObjectFileImageFromFile(pathName, objectFileImage);
729
730 DYLD_LOCK_THIS_BLOCK;
731 static NSObjectFileImageReturnCode (*p)(const char*, NSObjectFileImage*) = NULL;
732
733 if(p == NULL)
734 _dyld_func_lookup("__dyld_NSCreateObjectFileImageFromFile", (void**)&p);
735 return p(pathName, objectFileImage);
736 }
737
738
739 /*
740 * NSCreateObjectFileImageFromMemory() creates an NSObjectFileImage for the
741 * object file mapped into memory at address of size length if the object file
742 * is a correct Mach-O file that can be loaded with NSloadModule(). For return
743 * codes of NSObjectFileImageFailure and NSObjectFileImageFormat an error
744 * message is printed to stderr. All other codes cause no printing.
745 */
746 NSObjectFileImageReturnCode
747 NSCreateObjectFileImageFromMemory(
748 const void* address,
749 size_t size,
750 NSObjectFileImage *objectFileImage)
751 {
752 // <rdar://problem/51812762> NSCreatObjectFileImageFromMemory fail opaquely if Hardened runtime is enabled
753 uint32_t flags;
754 if ( csops(0, CS_OPS_STATUS, &flags, sizeof(flags)) != -1 ) {
755 if ( (flags & (CS_ENFORCEMENT|CS_KILL)) == (CS_ENFORCEMENT|CS_KILL) ) {
756 //fprintf(stderr, "dyld: warning: NSCreatObjectFileImageFromMemory() cannot be used in harden process 0x%08X\n", flags);
757 return NSObjectFileImageAccess;
758 }
759 }
760
761 if ( gUseDyld3 )
762 return dyld3::NSCreateObjectFileImageFromMemory(address, size, objectFileImage);
763
764 DYLD_LOCK_THIS_BLOCK;
765 static NSObjectFileImageReturnCode (*p)(const void*, size_t, NSObjectFileImage*) = NULL;
766
767 if(p == NULL)
768 _dyld_func_lookup("__dyld_NSCreateObjectFileImageFromMemory", (void**)&p);
769 return p(address, size, objectFileImage);
770 }
771
772 #if OBSOLETE_DYLD_API
773 /*
774 * NSCreateCoreFileImageFromFile() creates an NSObjectFileImage for the
775 * specified core file name if the file is a correct Mach-O core file.
776 * For return codes of NSObjectFileImageFailure and NSObjectFileImageFormat
777 * an error message is printed to stderr. All other codes cause no printing.
778 */
779 NSObjectFileImageReturnCode
780 NSCreateCoreFileImageFromFile(
781 const char* pathName,
782 NSObjectFileImage *objectFileImage)
783 {
784 DYLD_LOCK_THIS_BLOCK;
785 static NSObjectFileImageReturnCode (*p)(const char*, NSObjectFileImage*) = NULL;
786
787 if(p == NULL)
788 _dyld_func_lookup("__dyld_NSCreateCoreFileImageFromFile", (void**)&p);
789 return p(pathName, objectFileImage);
790 }
791 #endif
792
793 bool
794 NSDestroyObjectFileImage(
795 NSObjectFileImage objectFileImage)
796 {
797 if ( gUseDyld3 )
798 return dyld3::NSDestroyObjectFileImage(objectFileImage);
799
800 DYLD_LOCK_THIS_BLOCK;
801 static bool (*p)(NSObjectFileImage) = NULL;
802
803 if(p == NULL)
804 _dyld_func_lookup("__dyld_NSDestroyObjectFileImage", (void**)&p);
805 return p(objectFileImage);
806 }
807
808
809 NSModule
810 NSLinkModule(
811 NSObjectFileImage objectFileImage,
812 const char* moduleName,
813 uint32_t options)
814 {
815 if ( gUseDyld3 )
816 return dyld3::NSLinkModule(objectFileImage, moduleName, options);
817
818 DYLD_LOCK_THIS_BLOCK;
819 static NSModule (*p)(NSObjectFileImage, const char*, unsigned long) = NULL;
820
821 if(p == NULL)
822 _dyld_func_lookup("__dyld_NSLinkModule", (void**)&p);
823
824 return p(objectFileImage, moduleName, options);
825 }
826
827
828
829
830 /*
831 * NSSymbolDefinitionCountInObjectFileImage() returns the number of symbol
832 * definitions in the NSObjectFileImage.
833 */
834 uint32_t
835 NSSymbolDefinitionCountInObjectFileImage(
836 NSObjectFileImage objectFileImage)
837 {
838 if ( gUseDyld3 )
839 return dyld3::NSSymbolDefinitionCountInObjectFileImage(objectFileImage);
840
841 DYLD_LOCK_THIS_BLOCK;
842 static uint32_t (*p)(NSObjectFileImage) = NULL;
843
844 if(p == NULL)
845 _dyld_func_lookup("__dyld_NSSymbolDefinitionCountInObjectFileImage", (void**)&p);
846
847 return p(objectFileImage);
848 }
849
850 /*
851 * NSSymbolDefinitionNameInObjectFileImage() returns the name of the i'th
852 * symbol definitions in the NSObjectFileImage. If the ordinal specified is
853 * outside the range [0..NSSymbolDefinitionCountInObjectFileImage], NULL will
854 * be returned.
855 */
856 const char*
857 NSSymbolDefinitionNameInObjectFileImage(
858 NSObjectFileImage objectFileImage,
859 uint32_t ordinal)
860 {
861 if ( gUseDyld3 )
862 return dyld3::NSSymbolDefinitionNameInObjectFileImage(objectFileImage, ordinal);
863
864 DYLD_LOCK_THIS_BLOCK;
865 static const char* (*p)(NSObjectFileImage, uint32_t) = NULL;
866
867 if(p == NULL)
868 _dyld_func_lookup("__dyld_NSSymbolDefinitionNameInObjectFileImage", (void**)&p);
869
870 return p(objectFileImage, ordinal);
871 }
872
873 /*
874 * NSSymbolReferenceCountInObjectFileImage() returns the number of references
875 * to undefined symbols the NSObjectFileImage.
876 */
877 uint32_t
878 NSSymbolReferenceCountInObjectFileImage(
879 NSObjectFileImage objectFileImage)
880 {
881 if ( gUseDyld3 )
882 return dyld3::NSSymbolReferenceCountInObjectFileImage(objectFileImage);
883
884 DYLD_LOCK_THIS_BLOCK;
885 static uint32_t (*p)(NSObjectFileImage) = NULL;
886
887 if(p == NULL)
888 _dyld_func_lookup("__dyld_NSSymbolReferenceCountInObjectFileImage", (void**)&p);
889
890 return p(objectFileImage);
891 }
892
893 /*
894 * NSSymbolReferenceNameInObjectFileImage() returns the name of the i'th
895 * undefined symbol in the NSObjectFileImage. If the ordinal specified is
896 * outside the range [0..NSSymbolReferenceCountInObjectFileImage], NULL will be
897 * returned.
898 */
899 const char*
900 NSSymbolReferenceNameInObjectFileImage(
901 NSObjectFileImage objectFileImage,
902 uint32_t ordinal,
903 bool *tentative_definition) /* can be NULL */
904 {
905 if ( gUseDyld3 )
906 return dyld3::NSSymbolReferenceNameInObjectFileImage(objectFileImage, ordinal, tentative_definition);
907
908 DYLD_LOCK_THIS_BLOCK;
909 static const char* (*p)(NSObjectFileImage, uint32_t, bool*) = NULL;
910
911 if(p == NULL)
912 _dyld_func_lookup("__dyld_NSSymbolReferenceNameInObjectFileImage", (void**)&p);
913
914 return p(objectFileImage, ordinal, tentative_definition);
915 }
916
917 /*
918 * NSIsSymbolDefinedInObjectFileImage() returns TRUE if the specified symbol
919 * name has a definition in the NSObjectFileImage and FALSE otherwise.
920 */
921 bool
922 NSIsSymbolDefinedInObjectFileImage(
923 NSObjectFileImage objectFileImage,
924 const char* symbolName)
925 {
926 if ( gUseDyld3 )
927 return dyld3::NSIsSymbolDefinedInObjectFileImage(objectFileImage, symbolName);
928
929 DYLD_LOCK_THIS_BLOCK;
930 static bool (*p)(NSObjectFileImage, const char*) = NULL;
931
932 if(p == NULL)
933 _dyld_func_lookup("__dyld_NSIsSymbolDefinedInObjectFileImage", (void**)&p);
934
935 return p(objectFileImage, symbolName);
936 }
937
938 /*
939 * NSGetSectionDataInObjectFileImage() returns a pointer to the section contents
940 * in the NSObjectFileImage for the specified segmentName and sectionName if
941 * it exists and it is not a zerofill section. If not it returns NULL. If
942 * the parameter size is not NULL the size of the section is also returned
943 * indirectly through that pointer.
944 */
945 void *
946 NSGetSectionDataInObjectFileImage(
947 NSObjectFileImage objectFileImage,
948 const char* segmentName,
949 const char* sectionName,
950 unsigned long *size) /* can be NULL */
951 {
952 if ( gUseDyld3 )
953 return dyld3::NSGetSectionDataInObjectFileImage(objectFileImage, segmentName, sectionName, size);
954
955 DYLD_LOCK_THIS_BLOCK;
956 static void* (*p)(NSObjectFileImage, const char*, const char*, unsigned long*) = NULL;
957
958 if(p == NULL)
959 _dyld_func_lookup("__dyld_NSGetSectionDataInObjectFileImage", (void**)&p);
960
961 return p(objectFileImage, segmentName, sectionName, size);
962 }
963
964
965 void
966 NSLinkEditError(
967 NSLinkEditErrors *c,
968 int *errorNumber,
969 const char* *fileName,
970 const char* *errorString)
971 {
972 if ( gUseDyld3 )
973 return dyld3::NSLinkEditError(c, errorNumber, fileName, errorString);
974
975 DYLD_LOCK_THIS_BLOCK;
976 static void (*p)(NSLinkEditErrors *c,
977 int *errorNumber,
978 const char* *fileName,
979 const char* *errorString) = NULL;
980
981 if(p == NULL)
982 _dyld_func_lookup("__dyld_link_edit_error", (void**)&p);
983 if(p != NULL)
984 p(c, errorNumber, fileName, errorString);
985 }
986
987 bool
988 NSUnLinkModule(
989 NSModule module,
990 uint32_t options)
991 {
992 if ( gUseDyld3 )
993 return dyld3::NSUnLinkModule(module, options);
994
995 DYLD_LOCK_THIS_BLOCK;
996 static bool (*p)(NSModule module, uint32_t options) = NULL;
997
998 if(p == NULL)
999 _dyld_func_lookup("__dyld_unlink_module", (void**)&p);
1000
1001 return p(module, options);
1002 }
1003
1004 #if OBSOLETE_DYLD_API
1005 NSModule
1006 NSReplaceModule(
1007 NSModule moduleToReplace,
1008 NSObjectFileImage newObjectFileImage,
1009 uint32_t options)
1010 {
1011 return(NULL);
1012 }
1013 #endif
1014
1015
1016 #endif // DEPRECATED_APIS_SUPPORTED
1017
1018 /*
1019 *_NSGetExecutablePath copies the path of the executable into the buffer and
1020 * returns 0 if the path was successfully copied in the provided buffer. If the
1021 * buffer is not large enough, -1 is returned and the expected buffer size is
1022 * copied in *bufsize. Note that _NSGetExecutablePath will return "a path" to
1023 * the executable not a "real path" to the executable. That is the path may be
1024 * a symbolic link and not the real file. And with deep directories the total
1025 * bufsize needed could be more than MAXPATHLEN.
1026 */
1027 int
1028 _NSGetExecutablePath(
1029 char *buf,
1030 uint32_t *bufsize)
1031 {
1032 if ( gUseDyld3 )
1033 return dyld3::_NSGetExecutablePath(buf, bufsize);
1034
1035 DYLD_NO_LOCK_THIS_BLOCK;
1036 static int (*p)(char *buf, uint32_t *bufsize) = NULL;
1037
1038 if(p == NULL)
1039 _dyld_func_lookup("__dyld__NSGetExecutablePath", (void**)&p);
1040 return(p(buf, bufsize));
1041 }
1042
1043 #if DEPRECATED_APIS_SUPPORTED
1044 void
1045 _dyld_lookup_and_bind(
1046 const char* symbol_name,
1047 void** address,
1048 NSModule* module)
1049 {
1050 if ( gUseDyld3 )
1051 return dyld3::_dyld_lookup_and_bind(symbol_name, address, module);
1052
1053 DYLD_LOCK_THIS_BLOCK;
1054 static void (*p)(const char*, void** , NSModule*) = NULL;
1055
1056 if(p == NULL)
1057 _dyld_func_lookup("__dyld_lookup_and_bind", (void**)&p);
1058 p(symbol_name, address, module);
1059 }
1060
1061 void
1062 _dyld_lookup_and_bind_with_hint(
1063 const char* symbol_name,
1064 const char* library_name_hint,
1065 void** address,
1066 NSModule* module)
1067 {
1068 DYLD_LOCK_THIS_BLOCK;
1069 static void (*p)(const char*, const char*, void**, NSModule*) = NULL;
1070
1071 if(p == NULL)
1072 _dyld_func_lookup("__dyld_lookup_and_bind_with_hint", (void**)&p);
1073 p(symbol_name, library_name_hint, address, module);
1074 }
1075
1076 #if OBSOLETE_DYLD_API
1077 void
1078 _dyld_lookup_and_bind_objc(
1079 const char* symbol_name,
1080 void** address,
1081 NSModule* module)
1082 {
1083 DYLD_LOCK_THIS_BLOCK;
1084 static void (*p)(const char* , void**, NSModule*) = NULL;
1085
1086 if(p == NULL)
1087 _dyld_func_lookup("__dyld_lookup_and_bind_objc", (void**)&p);
1088 p(symbol_name, address, module);
1089 }
1090 #endif
1091
1092 void
1093 _dyld_lookup_and_bind_fully(
1094 const char* symbol_name,
1095 void** address,
1096 NSModule* module)
1097 {
1098 DYLD_LOCK_THIS_BLOCK;
1099 static void (*p)(const char*, void**, NSModule*) = NULL;
1100
1101 if(p == NULL)
1102 _dyld_func_lookup("__dyld_lookup_and_bind_fully", (void**)&p);
1103 p(symbol_name, address, module);
1104 }
1105
1106 bool
1107 _dyld_bind_fully_image_containing_address(
1108 const void* address)
1109 {
1110 DYLD_LOCK_THIS_BLOCK;
1111 static bool (*p)(const void*) = NULL;
1112
1113 if(p == NULL)
1114 _dyld_func_lookup("__dyld_bind_fully_image_containing_address", (void**)&p);
1115 return p(address);
1116 }
1117 #endif // DEPRECATED_APIS_SUPPORTED
1118
1119
1120 /*
1121 * _dyld_register_func_for_add_image registers the specified function to be
1122 * called when a new image is added (a bundle or a dynamic shared library) to
1123 * the program. When this function is first registered it is called for once
1124 * for each image that is currently part of the program.
1125 */
1126 void
1127 _dyld_register_func_for_add_image(
1128 void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
1129 {
1130 if ( gUseDyld3 )
1131 return dyld3::_dyld_register_func_for_add_image(func);
1132
1133 DYLD_LOCK_THIS_BLOCK;
1134 typedef void (*callback_t)(const struct mach_header *mh, intptr_t vmaddr_slide);
1135 static void (*p)(callback_t func) = NULL;
1136
1137 if(p == NULL)
1138 _dyld_func_lookup("__dyld_register_func_for_add_image", (void**)&p);
1139 p(func);
1140 }
1141
1142 /*
1143 * _dyld_register_func_for_remove_image registers the specified function to be
1144 * called when an image is removed (a bundle or a dynamic shared library) from
1145 * the program.
1146 */
1147 void
1148 _dyld_register_func_for_remove_image(
1149 void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
1150 {
1151 if ( gUseDyld3 )
1152 return dyld3::_dyld_register_func_for_remove_image(func);
1153
1154 DYLD_LOCK_THIS_BLOCK;
1155 typedef void (*callback_t)(const struct mach_header *mh, intptr_t vmaddr_slide);
1156 static void (*p)(callback_t func) = NULL;
1157
1158 if(p == NULL)
1159 _dyld_func_lookup("__dyld_register_func_for_remove_image", (void**)&p);
1160 p(func);
1161 }
1162
1163 #if OBSOLETE_DYLD_API
1164 /*
1165 * _dyld_register_func_for_link_module registers the specified function to be
1166 * called when a module is bound into the program. When this function is first
1167 * registered it is called for once for each module that is currently bound into
1168 * the program.
1169 */
1170 void
1171 _dyld_register_func_for_link_module(
1172 void (*func)(NSModule module))
1173 {
1174 DYLD_LOCK_THIS_BLOCK;
1175 static void (*p)(void (*func)(NSModule module)) = NULL;
1176
1177 if(p == NULL)
1178 _dyld_func_lookup("__dyld_register_func_for_link_module", (void**)&p);
1179 p(func);
1180 }
1181
1182 /*
1183 * _dyld_register_func_for_unlink_module registers the specified function to be
1184 * called when a module is unbound from the program.
1185 */
1186 void
1187 _dyld_register_func_for_unlink_module(
1188 void (*func)(NSModule module))
1189 {
1190 DYLD_LOCK_THIS_BLOCK;
1191 static void (*p)(void (*func)(NSModule module)) = NULL;
1192
1193 if(p == NULL)
1194 _dyld_func_lookup("__dyld_register_func_for_unlink_module", (void**)&p);
1195 p(func);
1196 }
1197
1198 /*
1199 * _dyld_register_func_for_replace_module registers the specified function to be
1200 * called when a module is to be replace with another module in the program.
1201 */
1202 void
1203 _dyld_register_func_for_replace_module(
1204 void (*func)(NSModule oldmodule, NSModule newmodule))
1205 {
1206 DYLD_LOCK_THIS_BLOCK;
1207 static void (*p)(void (*func)(NSModule oldmodule,
1208 NSModule newmodule)) = NULL;
1209
1210 if(p == NULL)
1211 _dyld_func_lookup("__dyld_register_func_for_replace_module", (void**)&p);
1212 p(func);
1213 }
1214
1215
1216 /*
1217 * _dyld_get_objc_module_sect_for_module is passed a module and sets a
1218 * pointer to the (__OBJC,__module) section and its size for the specified
1219 * module.
1220 */
1221 void
1222 _dyld_get_objc_module_sect_for_module(
1223 NSModule module,
1224 void **objc_module,
1225 unsigned long *size)
1226 {
1227 DYLD_LOCK_THIS_BLOCK;
1228 static void (*p)(NSModule module,
1229 void **objc_module,
1230 unsigned long *size) = NULL;
1231
1232 if(p == NULL)
1233 _dyld_func_lookup("__dyld_get_objc_module_sect_for_module", (void**)&p);
1234 p(module, objc_module, size);
1235 }
1236
1237 #endif
1238
1239 #if DEPRECATED_APIS_SUPPORTED
1240 bool
1241 _dyld_present(void)
1242 {
1243 // this function exists for compatiblity only
1244 return true;
1245 }
1246 #endif
1247
1248 uint32_t
1249 _dyld_image_count(void)
1250 {
1251 if ( gUseDyld3 )
1252 return dyld3::_dyld_image_count();
1253
1254 DYLD_NO_LOCK_THIS_BLOCK;
1255 static uint32_t (*p)(void) = NULL;
1256
1257 if(p == NULL)
1258 _dyld_func_lookup("__dyld_image_count", (void**)&p);
1259 return(p());
1260 }
1261
1262 const struct mach_header *
1263 _dyld_get_image_header(uint32_t image_index)
1264 {
1265 if ( gUseDyld3 )
1266 return dyld3::_dyld_get_image_header(image_index);
1267
1268 DYLD_NO_LOCK_THIS_BLOCK;
1269 static struct mach_header * (*p)(uint32_t image_index) = NULL;
1270
1271 if(p == NULL)
1272 _dyld_func_lookup("__dyld_get_image_header", (void**)&p);
1273 return(p(image_index));
1274 }
1275
1276 intptr_t
1277 _dyld_get_image_vmaddr_slide(uint32_t image_index)
1278 {
1279 if ( gUseDyld3 )
1280 return dyld3::_dyld_get_image_vmaddr_slide(image_index);
1281
1282 DYLD_NO_LOCK_THIS_BLOCK;
1283 static unsigned long (*p)(uint32_t image_index) = NULL;
1284
1285 if(p == NULL)
1286 _dyld_func_lookup("__dyld_get_image_vmaddr_slide", (void**)&p);
1287 return(p(image_index));
1288 }
1289
1290 const char*
1291 _dyld_get_image_name(uint32_t image_index)
1292 {
1293 if ( gUseDyld3 )
1294 return dyld3::_dyld_get_image_name(image_index);
1295
1296 DYLD_NO_LOCK_THIS_BLOCK;
1297 static const char* (*p)(uint32_t image_index) = NULL;
1298
1299 if(p == NULL)
1300 _dyld_func_lookup("__dyld_get_image_name", (void**)&p);
1301 return(p(image_index));
1302 }
1303
1304 // SPI in Mac OS X 10.6
1305 intptr_t _dyld_get_image_slide(const struct mach_header* mh)
1306 {
1307 // always use dyld3 version because it does better error handling
1308 return dyld3::_dyld_get_image_slide(mh);
1309 }
1310
1311 const struct mach_header *
1312 _dyld_get_prog_image_header()
1313 {
1314 if ( gUseDyld3 )
1315 return dyld3::_dyld_get_prog_image_header();
1316
1317 DYLD_LOCK_THIS_BLOCK;
1318 static const struct mach_header * (*p)(void) = NULL;
1319
1320 if(p == NULL)
1321 _dyld_func_lookup("__dyld_get_prog_image_header", (void**)&p);
1322 return p();
1323 }
1324
1325 #if DEPRECATED_APIS_SUPPORTED
1326 bool
1327 _dyld_image_containing_address(const void* address)
1328 {
1329 if ( gUseDyld3 )
1330 return dyld3::_dyld_image_containing_address(address);
1331
1332 DYLD_LOCK_THIS_BLOCK;
1333 static bool (*p)(const void*) = NULL;
1334
1335 if(p == NULL)
1336 _dyld_func_lookup("__dyld_image_containing_address", (void**)&p);
1337 return(p(address));
1338 }
1339
1340 const struct mach_header *
1341 _dyld_get_image_header_containing_address(
1342 const void* address)
1343 {
1344 if ( gUseDyld3 )
1345 return dyld3::_dyld_get_image_header_containing_address(address);
1346
1347 DYLD_LOCK_THIS_BLOCK;
1348 static const struct mach_header * (*p)(const void*) = NULL;
1349
1350 if(p == NULL)
1351 _dyld_func_lookup("__dyld_get_image_header_containing_address", (void**)&p);
1352 return p(address);
1353 }
1354
1355 bool _dyld_launched_prebound(void)
1356 {
1357 DYLD_LOCK_THIS_BLOCK;
1358 static bool (*p)(void) = NULL;
1359
1360 if(p == NULL)
1361 _dyld_func_lookup("__dyld_launched_prebound", (void**)&p);
1362 return(p());
1363 }
1364
1365 bool _dyld_all_twolevel_modules_prebound(void)
1366 {
1367 DYLD_LOCK_THIS_BLOCK;
1368 static bool (*p)(void) = NULL;
1369
1370 if(p == NULL)
1371 _dyld_func_lookup("__dyld_all_twolevel_modules_prebound", (void**)&p);
1372 return(p());
1373 }
1374 #endif // DEPRECATED_APIS_SUPPORTED
1375
1376
1377 #include <dlfcn_private.h>
1378 #include <stddef.h>
1379 #include <pthread.h>
1380 #include <stdlib.h>
1381 #include <mach-o/dyld.h>
1382 #include "dyldLibSystemInterface.h"
1383
1384
1385 // pthread key used to access per-thread dlerror message
1386 static pthread_key_t dlerrorPerThreadKey;
1387 static bool dlerrorPerThreadKeyInitialized = false;
1388
1389 // data kept per-thread
1390 struct dlerrorPerThreadData
1391 {
1392 size_t sizeAllocated;
1393 char message[1];
1394 };
1395
1396 // function called by dyld to get buffer to store dlerror message
1397 static char* getPerThreadBufferFor_dlerror(size_t sizeRequired)
1398 {
1399 // ok to create key lazily because this function is called within dyld lock, so there is no race condition
1400 if (!dlerrorPerThreadKeyInitialized ) {
1401 // create key and tell pthread package to call free() on any data associated with key if thread dies
1402 pthread_key_create(&dlerrorPerThreadKey, &free);
1403 dlerrorPerThreadKeyInitialized = true;
1404 }
1405
1406 const size_t size = (sizeRequired < 256) ? 256 : sizeRequired;
1407 dlerrorPerThreadData* data = (dlerrorPerThreadData*)pthread_getspecific(dlerrorPerThreadKey);
1408 if ( data == NULL ) {
1409 //int mallocSize = offsetof(dlerrorPerThreadData, message[size]);
1410 const size_t mallocSize = sizeof(dlerrorPerThreadData)+size;
1411 data = (dlerrorPerThreadData*)malloc(mallocSize);
1412 data->sizeAllocated = size;
1413 pthread_setspecific(dlerrorPerThreadKey, data);
1414 }
1415 else if ( data->sizeAllocated < sizeRequired ) {
1416 free(data);
1417 //int mallocSize = offsetof(dlerrorPerThreadData, message[size]);
1418 const size_t mallocSize = sizeof(dlerrorPerThreadData)+size;
1419 data = (dlerrorPerThreadData*)malloc(mallocSize);
1420 data->sizeAllocated = size;
1421 pthread_setspecific(dlerrorPerThreadKey, data);
1422 }
1423 return data->message;
1424 }
1425
1426 // <rdar://problem/10595338> dlerror buffer leak
1427 // Only allocate buffer if an actual error message needs to be set
1428 static bool hasPerThreadBufferFor_dlerror()
1429 {
1430 if (!dlerrorPerThreadKeyInitialized )
1431 return false;
1432
1433 return (pthread_getspecific(dlerrorPerThreadKey) != NULL);
1434 }
1435
1436 #if TARGET_OS_DRIVERKIT
1437 static bool isLaunchdOwned()
1438 {
1439 return false;
1440 }
1441 #else
1442 // use non-lazy pointer to vproc_swap_integer so that lazy binding does not recurse
1443 typedef vproc_err_t (*vswapproc)(vproc_t vp, vproc_gsk_t key,int64_t *inval, int64_t *outval);
1444 static vswapproc swapProc = &vproc_swap_integer;
1445
1446 static bool isLaunchdOwned()
1447 {
1448 static bool checked = false;
1449 static bool result = false;
1450 if ( !checked ) {
1451 checked = true;
1452 int64_t val = 0;
1453 (*swapProc)(NULL, VPROC_GSK_IS_MANAGED, NULL, &val);
1454 result = ( val != 0 );
1455 }
1456 return result;
1457 }
1458 #endif
1459
1460 static void shared_cache_missing()
1461 {
1462 // leave until dyld's that might call this are rare
1463 }
1464
1465 static void shared_cache_out_of_date()
1466 {
1467 // leave until dyld's that might call this are rare
1468 }
1469
1470
1471 // the table passed to dyld containing thread helpers
1472 static dyld::LibSystemHelpers sHelpers = { 13, &dyldGlobalLockAcquire, &dyldGlobalLockRelease,
1473 &getPerThreadBufferFor_dlerror, &malloc, &free, &__cxa_atexit,
1474 &shared_cache_missing, &shared_cache_out_of_date,
1475 NULL, NULL,
1476 &pthread_key_create, &pthread_setspecific,
1477 &malloc_size,
1478 &pthread_getspecific,
1479 &__cxa_finalize,
1480 address_of_start,
1481 &hasPerThreadBufferFor_dlerror,
1482 &isLaunchdOwned,
1483 &vm_allocate,
1484 &mmap,
1485 &__cxa_finalize_ranges
1486 };
1487
1488 static const objc_opt::objc_opt_t* gObjCOpt = nullptr;
1489 //
1490 // during initialization of libSystem this routine will run
1491 // and call dyld, registering the helper functions.
1492 //
1493 extern "C" void tlv_initializer();
1494 void _dyld_initializer()
1495 {
1496 void (*p)(dyld::LibSystemHelpers*);
1497
1498 // Get the optimized objc pointer now that the cache is loaded
1499 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
1500 if ( allInfo != nullptr ) {
1501 const DyldSharedCache* cache = (const DyldSharedCache*)(allInfo->sharedCacheBaseAddress);
1502 if ( cache != nullptr )
1503 gObjCOpt = cache->objcOpt();
1504 }
1505
1506 if ( gUseDyld3 ) {
1507 dyld3::gAllImages.applyInitialImages();
1508 #if TARGET_OS_IOS && !TARGET_OS_SIMULATOR
1509 // For binaries built before 13.0, set the lookup function if they need it
1510 if (dyld_get_program_sdk_version() < DYLD_PACKED_VERSION(13,0,0))
1511 setLookupFunc((void*)&dyld3::compatFuncLookup);
1512 #endif
1513 }
1514 else {
1515 _dyld_func_lookup("__dyld_register_thread_helpers", (void**)&p);
1516 if(p != NULL)
1517 p(&sHelpers);
1518 }
1519
1520 tlv_initializer();
1521 }
1522
1523 int dladdr(const void* addr, Dl_info* info)
1524 {
1525 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_DLADDR, (uint64_t)addr, 0, 0);
1526 int result = 0;
1527 if ( gUseDyld3 ) {
1528 result = dyld3::dladdr(addr, info);
1529 } else {
1530 DYLD_LOCK_THIS_BLOCK;
1531 static int (*p)(const void* , Dl_info*) = NULL;
1532
1533 if(p == NULL)
1534 _dyld_func_lookup("__dyld_dladdr", (void**)&p);
1535 result = p(addr, info);
1536 }
1537 timer.setData4(result);
1538 timer.setData5(info != NULL ? info->dli_fbase : 0);
1539 timer.setData6(info != NULL ? info->dli_saddr : 0);
1540 return result;
1541 }
1542
1543 #if !TARGET_OS_DRIVERKIT
1544 char* dlerror()
1545 {
1546 if ( gUseDyld3 )
1547 return dyld3::dlerror();
1548
1549 DYLD_LOCK_THIS_BLOCK;
1550 static char* (*p)() = NULL;
1551
1552 if(p == NULL)
1553 _dyld_func_lookup("__dyld_dlerror", (void**)&p);
1554 return(p());
1555 }
1556
1557 int dlclose(void* handle)
1558 {
1559 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_DLCLOSE, (uint64_t)handle, 0, 0);
1560 int result = 0;
1561 if ( gUseDyld3 ) {
1562 timer.setData4(result);
1563 return dyld3::dlclose(handle);
1564 }
1565
1566 DYLD_LOCK_THIS_BLOCK;
1567 static int (*p)(void* handle) = NULL;
1568
1569 if(p == NULL)
1570 _dyld_func_lookup("__dyld_dlclose", (void**)&p);
1571 result = p(handle);
1572 timer.setData4(result);
1573 return result;
1574 }
1575
1576 static void* dlopen_internal(const char* path, int mode, void* callerAddress)
1577 {
1578 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_DLOPEN, path, mode, 0);
1579 void* result = nullptr;
1580 if ( gUseDyld3 ) {
1581 result = dyld3::dlopen_internal(path, mode, callerAddress);
1582 timer.setData4(result);
1583 return result;
1584 }
1585
1586 // dlopen is special. locking is done inside dyld to allow initializer to run without lock
1587 DYLD_NO_LOCK_THIS_BLOCK;
1588
1589 static void* (*p)(const char* path, int, void*) = NULL;
1590
1591 if(p == NULL)
1592 _dyld_func_lookup("__dyld_dlopen_internal", (void**)&p);
1593 result = p(path, mode, callerAddress);
1594 // use asm block to prevent tail call optimization
1595 // this is needed because dlopen uses __builtin_return_address() and depends on this glue being in the frame chain
1596 // <rdar://problem/5313172 dlopen() looks too far up stack, can cause crash>
1597 __asm__ volatile("");
1598 timer.setData4(result);
1599
1600 return result;
1601 }
1602
1603 void* dlopen(const char* path, int mode)
1604 {
1605 void* result = dlopen_internal(path, mode, __builtin_return_address(0));
1606 if ( result )
1607 return result;
1608
1609
1610 return nullptr;
1611 }
1612
1613 void* dlopen_from(const char* path, int mode, void* addressInCaller)
1614 {
1615 #if __has_feature(ptrauth_calls)
1616 addressInCaller = __builtin_ptrauth_strip(addressInCaller, ptrauth_key_asia);
1617 #endif
1618 return dlopen_internal(path, mode, addressInCaller);
1619 }
1620
1621 #if !__i386__
1622 void* dlopen_audited(const char* path, int mode)
1623 {
1624 return dlopen(path, mode);
1625 }
1626 #endif // !__i386__
1627
1628 bool dlopen_preflight(const char* path)
1629 {
1630 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_DLOPEN_PREFLIGHT, path, 0, 0);
1631 bool result = false;
1632
1633 if ( gUseDyld3 ) {
1634 result = dyld3::dlopen_preflight_internal(path);
1635 timer.setData4(result);
1636 return result;
1637 }
1638
1639 DYLD_LOCK_THIS_BLOCK;
1640 static bool (*p)(const char* path, void* callerAddress) = NULL;
1641
1642 if(p == NULL)
1643 _dyld_func_lookup("__dyld_dlopen_preflight_internal", (void**)&p);
1644 result = p(path, __builtin_return_address(0));
1645 timer.setData4(result);
1646 return result;
1647 }
1648
1649 void* dlsym(void* handle, const char* symbol)
1650 {
1651 dyld3::ScopedTimer timer(DBG_DYLD_TIMING_DLSYM, handle, symbol, 0);
1652 void* result = nullptr;
1653
1654 if ( gUseDyld3 ) {
1655 result = dyld3::dlsym_internal(handle, symbol, __builtin_return_address(0));
1656 timer.setData4(result);
1657 return result;
1658 }
1659
1660 DYLD_LOCK_THIS_BLOCK;
1661 static void* (*p)(void* handle, const char* symbol, void *callerAddress) = NULL;
1662
1663 if(p == NULL)
1664 _dyld_func_lookup("__dyld_dlsym_internal", (void**)&p);
1665 result = p(handle, symbol, __builtin_return_address(0));
1666 timer.setData4(result);
1667 return result;
1668 }
1669 #endif // !TARGET_OS_DRIVERKIT
1670
1671
1672 const struct dyld_all_image_infos* _dyld_get_all_image_infos()
1673 {
1674 if ( gUseDyld3 )
1675 return dyld3::_dyld_get_all_image_infos();
1676
1677 DYLD_NO_LOCK_THIS_BLOCK;
1678 static struct dyld_all_image_infos* (*p)() = NULL;
1679
1680 if(p == NULL)
1681 _dyld_func_lookup("__dyld_get_all_image_infos", (void**)&p);
1682 return p();
1683 }
1684
1685 #if SUPPORT_ZERO_COST_EXCEPTIONS
1686 bool _dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
1687 {
1688 if ( gUseDyld3 )
1689 return dyld3::_dyld_find_unwind_sections(addr, info);
1690
1691 DYLD_NO_LOCK_THIS_BLOCK;
1692 static void* (*p)(void*, dyld_unwind_sections*) = NULL;
1693
1694 if(p == NULL)
1695 _dyld_func_lookup("__dyld_find_unwind_sections", (void**)&p);
1696 return p(addr, info);
1697 }
1698 #endif
1699
1700
1701 #if __i386__ || __x86_64__ || __arm__ || __arm64__
1702 __attribute__((visibility("hidden")))
1703 void* _dyld_fast_stub_entry(void* loadercache, long lazyinfo)
1704 {
1705 DYLD_NO_LOCK_THIS_BLOCK;
1706 static void* (*p)(void*, long) = NULL;
1707
1708 if(p == NULL)
1709 _dyld_func_lookup("__dyld_fast_stub_entry", (void**)&p);
1710 return p(loadercache, lazyinfo);
1711 }
1712 #endif
1713
1714
1715 const char* dyld_image_path_containing_address(const void* addr)
1716 {
1717 if ( gUseDyld3 )
1718 return dyld3::dyld_image_path_containing_address(addr);
1719
1720 DYLD_NO_LOCK_THIS_BLOCK;
1721 static const char* (*p)(const void*) = NULL;
1722
1723 if(p == NULL)
1724 _dyld_func_lookup("__dyld_image_path_containing_address", (void**)&p);
1725 return p(addr);
1726 }
1727
1728 const struct mach_header* dyld_image_header_containing_address(const void* addr)
1729 {
1730 if ( gUseDyld3 )
1731 return dyld3::dyld_image_header_containing_address(addr);
1732
1733 DYLD_NO_LOCK_THIS_BLOCK;
1734 static const mach_header* (*p)(const void*) = NULL;
1735
1736 if(p == NULL)
1737 _dyld_func_lookup("__dyld_get_image_header_containing_address", (void**)&p);
1738 return p(addr);
1739 }
1740
1741
1742 bool dyld_shared_cache_some_image_overridden()
1743 {
1744 if ( gUseDyld3 )
1745 return dyld3::dyld_shared_cache_some_image_overridden();
1746
1747 DYLD_NO_LOCK_THIS_BLOCK;
1748 static bool (*p)() = NULL;
1749
1750 if(p == NULL)
1751 _dyld_func_lookup("__dyld_shared_cache_some_image_overridden", (void**)&p);
1752 return p();
1753 }
1754
1755 bool _dyld_get_shared_cache_uuid(uuid_t uuid)
1756 {
1757 if ( gUseDyld3 )
1758 return dyld3::_dyld_get_shared_cache_uuid(uuid);
1759
1760 DYLD_NO_LOCK_THIS_BLOCK;
1761 static bool (*p)(uuid_t) = NULL;
1762
1763 if(p == NULL)
1764 _dyld_func_lookup("__dyld_get_shared_cache_uuid", (void**)&p);
1765 return p(uuid);
1766 }
1767
1768 const void* _dyld_get_shared_cache_range(size_t* length)
1769 {
1770 if ( gUseDyld3 )
1771 return dyld3::_dyld_get_shared_cache_range(length);
1772
1773 DYLD_NO_LOCK_THIS_BLOCK;
1774 static const void* (*p)(size_t*) = NULL;
1775
1776 if(p == NULL)
1777 _dyld_func_lookup("__dyld_get_shared_cache_range", (void**)&p);
1778 return p(length);
1779 }
1780
1781 bool _dyld_shared_cache_optimized()
1782 {
1783 if ( gUseDyld3 )
1784 return dyld3::_dyld_shared_cache_optimized();
1785
1786 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
1787 if ( allInfo != nullptr ) {
1788 const dyld_cache_header* cacheHeader = (dyld_cache_header*)(allInfo->sharedCacheBaseAddress);
1789 if ( cacheHeader != nullptr )
1790 return (cacheHeader->cacheType == kDyldSharedCacheTypeProduction);
1791 }
1792 return false;
1793 }
1794
1795 bool _dyld_shared_cache_is_locally_built()
1796 {
1797 if ( gUseDyld3 )
1798 return dyld3::_dyld_shared_cache_is_locally_built();
1799
1800 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
1801 if ( allInfo != nullptr ) {
1802 const dyld_cache_header* cacheHeader = (dyld_cache_header*)(allInfo->sharedCacheBaseAddress);
1803 if ( cacheHeader != nullptr )
1804 return (cacheHeader->locallyBuiltCache == 1);
1805 }
1806 return false;
1807 }
1808
1809 const char* _dyld_shared_cache_real_path(const char* path)
1810 {
1811 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
1812 if ( allInfo != nullptr ) {
1813 const DyldSharedCache* cache = (const DyldSharedCache*)(allInfo->sharedCacheBaseAddress);
1814 if ( cache != nullptr )
1815 return cache->getCanonicalPath(path);
1816 }
1817 return nullptr;
1818 }
1819
1820 bool _dyld_shared_cache_contains_path(const char* path)
1821 {
1822 return _dyld_shared_cache_real_path(path) != nullptr;
1823 }
1824
1825
1826 uint32_t _dyld_launch_mode()
1827 {
1828 if ( gUseDyld3 )
1829 return dyld3::_dyld_launch_mode();
1830
1831 // in dyld2 mode all flag bits are zero
1832 return 0;
1833 }
1834
1835 void _dyld_images_for_addresses(unsigned count, const void* addresses[], struct dyld_image_uuid_offset infos[])
1836 {
1837 if ( gUseDyld3 )
1838 return dyld3::_dyld_images_for_addresses(count, addresses, infos);
1839
1840 DYLD_NO_LOCK_THIS_BLOCK;
1841 static const void (*p)(unsigned, const void*[], struct dyld_image_uuid_offset[]) = NULL;
1842
1843 if(p == NULL)
1844 _dyld_func_lookup("__dyld_images_for_addresses", (void**)&p);
1845 return p(count, addresses, infos);
1846 }
1847
1848 void _dyld_register_for_image_loads(void (*func)(const mach_header* mh, const char* path, bool unloadable))
1849 {
1850 if ( gUseDyld3 )
1851 return dyld3::_dyld_register_for_image_loads(func);
1852
1853 DYLD_NO_LOCK_THIS_BLOCK;
1854 static const void (*p)(void (*)(const mach_header* mh, const char* path, bool unloadable)) = NULL;
1855
1856 if(p == NULL)
1857 _dyld_func_lookup("__dyld_register_for_image_loads", (void**)&p);
1858 return p(func);
1859 }
1860
1861 void _dyld_register_for_bulk_image_loads(void (*func)(unsigned imageCount, const struct mach_header* mhs[], const char* paths[]))
1862 {
1863 if ( gUseDyld3 )
1864 return dyld3::_dyld_register_for_bulk_image_loads(func);
1865
1866 DYLD_NO_LOCK_THIS_BLOCK;
1867 static const void (*p)(void (*)(unsigned imageCount, const mach_header* mhs[], const char* paths[])) = NULL;
1868
1869 if(p == NULL)
1870 _dyld_func_lookup("__dyld_register_for_bulk_image_loads", (void**)&p);
1871 return p(func);
1872 }
1873
1874 bool dyld_need_closure(const char* execPath, const char* dataContainerRootDir)
1875 {
1876 return dyld3::dyld_need_closure(execPath, dataContainerRootDir);
1877 }
1878
1879 bool dyld_process_is_restricted()
1880 {
1881 if ( gUseDyld3 )
1882 return dyld3::dyld_process_is_restricted();
1883
1884 DYLD_NO_LOCK_THIS_BLOCK;
1885 static bool (*p)() = NULL;
1886
1887 if(p == NULL)
1888 _dyld_func_lookup("__dyld_process_is_restricted", (void**)&p);
1889 return p();
1890 }
1891
1892 const char* dyld_shared_cache_file_path()
1893 {
1894 if ( gUseDyld3 )
1895 return dyld3::dyld_shared_cache_file_path();
1896
1897 DYLD_NO_LOCK_THIS_BLOCK;
1898 static const char* (*p)() = NULL;
1899
1900 if(p == NULL)
1901 _dyld_func_lookup("__dyld_shared_cache_file_path", (void**)&p);
1902 return p();
1903 }
1904
1905 bool dyld_has_inserted_or_interposing_libraries()
1906 {
1907 if ( gUseDyld3 )
1908 return dyld3::dyld_has_inserted_or_interposing_libraries();
1909
1910 DYLD_NO_LOCK_THIS_BLOCK;
1911 static bool (*p)() = NULL;
1912
1913 if (p == NULL)
1914 _dyld_func_lookup("__dyld_has_inserted_or_interposing_libraries", (void**)&p);
1915 return p();
1916 }
1917
1918 bool _dyld_has_fix_for_radar(const char *rdar) {
1919 // There is no point in shimming this to dyld3, actual functionality can exist purely in libSystem for
1920 // both dyld2 and dyld3.
1921 return false;
1922 }
1923
1924
1925 void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
1926 {
1927 if ( gUseDyld3 )
1928 return dyld3::dyld_dynamic_interpose(mh, array, count);
1929
1930 DYLD_LOCK_THIS_BLOCK;
1931 static void (*p)(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count) = NULL;
1932
1933 if (p == NULL)
1934 _dyld_func_lookup("__dyld_dynamic_interpose", (void**)&p);
1935 p(mh, array, count);
1936 }
1937
1938 // SPI called __fork
1939 void _dyld_atfork_prepare()
1940 {
1941 if ( gUseDyld3 )
1942 return dyld3::_dyld_atfork_prepare();
1943 }
1944
1945 // SPI called __fork
1946 void _dyld_atfork_parent()
1947 {
1948 if ( gUseDyld3 )
1949 return dyld3::_dyld_atfork_parent();
1950 }
1951
1952 // SPI called __fork
1953 void _dyld_fork_child()
1954 {
1955 if ( gUseDyld3 )
1956 return dyld3::_dyld_fork_child();
1957
1958 DYLD_NO_LOCK_THIS_BLOCK;
1959 static void (*p)() = NULL;
1960
1961 if(p == NULL)
1962 _dyld_func_lookup("__dyld_fork_child", (void**)&p);
1963 return p();
1964 }
1965
1966
1967
1968 static void* mapStartOfCache(const char* path, size_t length)
1969 {
1970 struct stat statbuf;
1971 if ( dyld3::stat(path, &statbuf) == -1 )
1972 return NULL;
1973
1974 if ( (size_t)statbuf.st_size < length )
1975 return NULL;
1976
1977 int cache_fd = dyld3::open(path, O_RDONLY, 0);
1978 if ( cache_fd < 0 )
1979 return NULL;
1980
1981 void* result = ::mmap(NULL, length, PROT_READ, MAP_PRIVATE, cache_fd, 0);
1982 close(cache_fd);
1983
1984 if ( result == MAP_FAILED )
1985 return NULL;
1986
1987 return result;
1988 }
1989
1990
1991 static const dyld_cache_header* findCacheInDirAndMap(const uuid_t cacheUuid, const char* dirPath)
1992 {
1993 DIR* dirp = ::opendir(dirPath);
1994 if ( dirp != NULL) {
1995 dirent entry;
1996 dirent* entp = NULL;
1997 char cachePath[PATH_MAX];
1998 while ( ::readdir_r(dirp, &entry, &entp) == 0 ) {
1999 if ( entp == NULL )
2000 break;
2001 if ( entp->d_type != DT_REG )
2002 continue;
2003 if ( strlcpy(cachePath, dirPath, PATH_MAX) >= PATH_MAX )
2004 continue;
2005 if ( strlcat(cachePath, "/", PATH_MAX) >= PATH_MAX )
2006 continue;
2007 if ( strlcat(cachePath, entp->d_name, PATH_MAX) >= PATH_MAX )
2008 continue;
2009 if ( const dyld_cache_header* cacheHeader = (dyld_cache_header*)mapStartOfCache(cachePath, 0x00100000) ) {
2010 if ( (::memcmp(cacheHeader, "dyld_", 5) != 0) || (::memcmp(cacheHeader->uuid, cacheUuid, 16) != 0) ) {
2011 // wrong uuid, unmap and keep looking
2012 ::munmap((void*)cacheHeader, 0x00100000);
2013 }
2014 else {
2015 // found cache
2016 closedir(dirp);
2017 return cacheHeader;
2018 }
2019 }
2020 }
2021 closedir(dirp);
2022 }
2023 return NULL;
2024 }
2025
2026 int dyld_shared_cache_find_iterate_text(const uuid_t cacheUuid, const char* extraSearchDirs[], void (^callback)(const dyld_shared_cache_dylib_text_info* info))
2027 {
2028 if ( gUseDyld3 )
2029 return dyld3::dyld_shared_cache_find_iterate_text(cacheUuid, extraSearchDirs, callback);
2030
2031 const dyld_cache_header* cacheHeader = NULL;
2032 bool needToUnmap = true;
2033
2034 // get info from dyld about this process, to see if requested cache is already mapped into this process
2035 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
2036 if ( (allInfo != NULL) && (allInfo->sharedCacheBaseAddress != 0) && (memcmp(allInfo->sharedCacheUUID, cacheUuid, 16) == 0) ) {
2037 // requested cache is already mapped, just re-use it
2038 cacheHeader = (dyld_cache_header*)(allInfo->sharedCacheBaseAddress);
2039 needToUnmap = false;
2040 }
2041 else {
2042 // look first is default location for cache files
2043 #if TARGET_OS_IPHONE
2044 cacheHeader = findCacheInDirAndMap(cacheUuid, IPHONE_DYLD_SHARED_CACHE_DIR);
2045 #else
2046 cacheHeader = findCacheInDirAndMap(cacheUuid, MACOSX_MRM_DYLD_SHARED_CACHE_DIR);
2047 #endif
2048 // if not there, look in extra search locations
2049 if ( cacheHeader == NULL ) {
2050 for (const char** p = extraSearchDirs; *p != NULL; ++p) {
2051 cacheHeader = findCacheInDirAndMap(cacheUuid, *p);
2052 if ( cacheHeader != NULL )
2053 break;
2054 }
2055 }
2056 }
2057
2058 if ( cacheHeader == NULL )
2059 return -1;
2060
2061 if ( cacheHeader->mappingOffset <= __offsetof(dyld_cache_header, imagesTextOffset) ) {
2062 // old cache without imagesText array
2063 if ( needToUnmap )
2064 ::munmap((void*)cacheHeader, 0x00100000);
2065 return -1;
2066 }
2067
2068 // walk imageText table and call callback for each entry
2069 const dyld_cache_mapping_info* mappings = (dyld_cache_mapping_info*)((char*)cacheHeader + cacheHeader->mappingOffset);
2070 const uint64_t cacheUnslidBaseAddress = mappings[0].address;
2071 const dyld_cache_image_text_info* imagesText = (dyld_cache_image_text_info*)((char*)cacheHeader + cacheHeader->imagesTextOffset);
2072 const dyld_cache_image_text_info* imagesTextEnd = &imagesText[cacheHeader->imagesTextCount];
2073 for (const dyld_cache_image_text_info* p=imagesText; p < imagesTextEnd; ++p) {
2074 dyld_shared_cache_dylib_text_info dylibTextInfo;
2075 dylibTextInfo.version = 2;
2076 dylibTextInfo.loadAddressUnslid = p->loadAddress;
2077 dylibTextInfo.textSegmentSize = p->textSegmentSize;
2078 dylibTextInfo.path = (char*)cacheHeader + p->pathOffset;
2079 ::memcpy(dylibTextInfo.dylibUuid, p->uuid, 16);
2080 dylibTextInfo.textSegmentOffset = p->loadAddress - cacheUnslidBaseAddress;
2081 callback(&dylibTextInfo);
2082 }
2083
2084 if ( needToUnmap )
2085 ::munmap((void*)cacheHeader, 0x00100000);
2086
2087 return 0;
2088 }
2089
2090 int dyld_shared_cache_iterate_text(const uuid_t cacheUuid, void (^callback)(const dyld_shared_cache_dylib_text_info* info))
2091 {
2092 if ( gUseDyld3 )
2093 return dyld3::dyld_shared_cache_iterate_text(cacheUuid, callback);
2094
2095 const char* extraSearchDirs[] = { NULL };
2096 return dyld_shared_cache_find_iterate_text(cacheUuid, extraSearchDirs, callback);
2097 }
2098
2099
2100 bool _dyld_is_memory_immutable(const void* addr, size_t length)
2101 {
2102 if ( gUseDyld3 )
2103 return dyld3::_dyld_is_memory_immutable(addr, length);
2104
2105 DYLD_NO_LOCK_THIS_BLOCK;
2106 static bool (*p)(const void*, size_t) = NULL;
2107
2108 if(p == NULL)
2109 _dyld_func_lookup("__dyld_is_memory_immutable", (void**)&p);
2110 return p(addr, length);
2111 }
2112
2113
2114 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped,
2115 _dyld_objc_notify_init init,
2116 _dyld_objc_notify_unmapped unmapped)
2117 {
2118 if ( gUseDyld3 )
2119 return dyld3::_dyld_objc_notify_register(mapped, init, unmapped);
2120
2121 DYLD_LOCK_THIS_BLOCK;
2122 static bool (*p)(_dyld_objc_notify_mapped, _dyld_objc_notify_init, _dyld_objc_notify_unmapped) = NULL;
2123
2124 if(p == NULL)
2125 _dyld_func_lookup("__dyld_objc_notify_register", (void**)&p);
2126 p(mapped, init, unmapped);
2127 }
2128
2129 void _dyld_missing_symbol_abort()
2130 {
2131 return dyld3::_dyld_missing_symbol_abort();
2132 }
2133
2134 const char* _dyld_get_objc_selector(const char* selName)
2135 {
2136 // Check the shared cache table if it exists.
2137 if ( gObjCOpt != nullptr ) {
2138 if ( const objc_opt::objc_selopt_t* selopt = gObjCOpt->selopt() ) {
2139 const char* name = selopt->get(selName);
2140 if (name != nullptr)
2141 return name;
2142 }
2143 }
2144
2145 if ( gUseDyld3 )
2146 return dyld3::_dyld_get_objc_selector(selName);
2147
2148 return nullptr;
2149 }
2150
2151 void _dyld_for_each_objc_class(const char* className,
2152 void (^callback)(void* classPtr, bool isLoaded, bool* stop)) {
2153 if ( gUseDyld3 )
2154 return dyld3::_dyld_for_each_objc_class(className, callback);
2155 }
2156
2157 void _dyld_for_each_objc_protocol(const char* protocolName,
2158 void (^callback)(void* protocolPtr, bool isLoaded, bool* stop)) {
2159 if ( gUseDyld3 )
2160 return dyld3::_dyld_for_each_objc_protocol(protocolName, callback);
2161 }
2162
2163 void _dyld_register_driverkit_main(void (*mainFunc)(void))
2164 {
2165 if ( gUseDyld3 )
2166 return dyld3::_dyld_register_driverkit_main(mainFunc);
2167
2168 static bool (*p)(void (*mainFunc)(void)) = NULL;
2169
2170 if(p == NULL)
2171 _dyld_func_lookup("__dyld_register_driverkit_main", (void**)&p);
2172 p(mainFunc);
2173 }
2174
2175 // This is populated in the shared cache builder, so that the ranges are protected by __DATA_CONST
2176 // If we have a root, we can find this range in the shared cache libdyld at runtime
2177 typedef std::pair<const uint8_t*, const uint8_t*> ObjCConstantRange;
2178
2179 #if TARGET_OS_OSX
2180 __attribute__((section(("__DATA, __objc_ranges"))))
2181 #else
2182 __attribute__((section(("__DATA_CONST, __objc_ranges"))))
2183 #endif
2184 __attribute__((used))
2185 static ObjCConstantRange gSharedCacheObjCConstantRanges[dyld_objc_string_kind + 1];
2186
2187 static std::pair<const void*, uint64_t> getDyldCacheConstantRanges() {
2188 const dyld_all_image_infos* allInfo = _dyld_get_all_image_infos();
2189 if ( allInfo != nullptr ) {
2190 const DyldSharedCache* cache = (const DyldSharedCache*)(allInfo->sharedCacheBaseAddress);
2191 if ( cache != nullptr ) {
2192 return cache->getObjCConstantRange();
2193 }
2194 }
2195 return { nullptr, 0 };
2196 }
2197
2198 bool _dyld_is_objc_constant(DyldObjCConstantKind kind, const void* addr) {
2199 assert(kind <= dyld_objc_string_kind);
2200 // The common case should be that the value is in range, as this is a security
2201 // check, so first test against the values in the struct. If we have a root then
2202 // we'll take the slow path later
2203 if ( (addr >= gSharedCacheObjCConstantRanges[kind].first) && (addr < gSharedCacheObjCConstantRanges[kind].second) ) {
2204 // Make sure that we are pointing at the start of a constant object, not in to the middle of it
2205 uint64_t offset = (uint64_t)addr - (uint64_t)gSharedCacheObjCConstantRanges[kind].first;
2206 return (offset % (uint64_t)DyldSharedCache::ConstantClasses::cfStringAtomSize) == 0;
2207 }
2208
2209 // If we are in the shared cache, then the above check was sufficient, so this really isn't a valid constant address
2210 extern void* __dso_handle;
2211 const dyld3::MachOAnalyzer* ma = (const dyld3::MachOAnalyzer*)&__dso_handle;
2212 if ( ma->inDyldCache() )
2213 return false;
2214
2215 // We now know we are a root, so use the pointers in the shared cache libdyld version of gSharedCacheObjCConstantRanges
2216 static std::pair<const void*, uint64_t> sharedCacheRanges = { nullptr, ~0ULL };
2217
2218 // FIXME: Should we fold this in as an inititalizer above?
2219 // That would mean we need to link against somewhere to get ___cxa_guard_acquire/___cxa_guard_release
2220 if ( sharedCacheRanges.second == ~0ULL )
2221 sharedCacheRanges = getDyldCacheConstantRanges();
2222
2223 // We have the range of the section in libdyld in the shared cache, now get an array of ranges from it
2224 uint64_t numRanges = sharedCacheRanges.second / sizeof(ObjCConstantRange);
2225 if ( kind >= numRanges )
2226 return false;
2227
2228 const ObjCConstantRange* rangeArrayBase = (const ObjCConstantRange*)sharedCacheRanges.first;
2229 if ( (addr >= rangeArrayBase[kind].first) && (addr < rangeArrayBase[kind].second) ) {
2230 // Make sure that we are pointing at the start of a constant object, not in to the middle of it
2231 uint64_t offset = (uint64_t)addr - (uint64_t)rangeArrayBase[kind].first;
2232 return (offset % (uint64_t)DyldSharedCache::ConstantClasses::cfStringAtomSize) == 0;
2233 }
2234 return false;
2235 }