dyld-851.27.tar.gz
[apple/dyld.git] / src / dyldAPIs.cpp
1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
2 *
3 * Copyright (c) 2004-2009 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 //
26 // This file implements that API's in <mach-o/dyld.h>
27 //
28 //
29
30 #define __STDC_LIMIT_MACROS
31 #include <stddef.h>
32 #include <stdint.h>
33 #include <string.h>
34 #include <sys/param.h>
35 #include <sys/mount.h>
36 #include <Availability.h>
37
38
39 #include <vector>
40 #include <map>
41 #include <algorithm>
42
43 #include <mach/mach.h>
44 #include <sys/time.h>
45 #include <sys/sysctl.h>
46 #include <mach/mach_traps.h> // for task_self_trap()
47
48 #include <mach-o/dyld_images.h>
49 #include <mach-o/dyld.h>
50 #include <mach-o/dyld_priv.h>
51
52 #include "ImageLoader.h"
53 #include "ImageLoaderMachO.h"
54 #include "dyld2.h"
55 #include "dyldLibSystemInterface.h"
56 #include "DyldSharedCache.h"
57 #include "MachOFile.h"
58
59 #undef _POSIX_C_SOURCE
60 #include <dlfcn.h>
61
62 #if __has_feature(ptrauth_calls)
63 #include <ptrauth.h>
64 #endif
65
66
67 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
68 #if __LP64__
69 #define RELOC_SIZE 3
70 #define LC_SEGMENT_COMMAND LC_SEGMENT_64
71 #define LC_ROUTINES_COMMAND LC_ROUTINES_64
72 struct macho_segment_command : public segment_command_64 {};
73 struct macho_section : public section_64 {};
74 struct macho_routines_command : public routines_command_64 {};
75 #else
76 #define RELOC_SIZE 2
77 #define LC_SEGMENT_COMMAND LC_SEGMENT
78 #define LC_ROUTINES_COMMAND LC_ROUTINES
79 struct macho_segment_command : public segment_command {};
80 struct macho_section : public section {};
81 struct macho_routines_command : public routines_command {};
82 #endif
83
84
85 // this was in dyld_priv.h but it is no longer exported
86 extern "C" {
87 const struct dyld_all_image_infos* _dyld_get_all_image_infos();
88 }
89
90 // from dyldExceptions.c
91 extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key);
92
93 // from dyld_gdb.cpp
94 extern void addImagesToAllImages(uint32_t infoCount, const dyld_image_info info[]);
95 extern uint32_t allImagesCount();
96 extern const mach_header* allImagesIndexedMachHeader(uint32_t index);
97 extern const char* allImagesIndexedPath(uint32_t index);
98
99 extern "C" int _dyld_func_lookup(const char* name, void** address);
100
101 extern "C" void* dlopen_internal(const char* path, int mode, void* callerAddress);
102 extern "C" bool dlopen_preflight_internal(const char* path, void* callerAddress);
103 extern "C" void* dlsym_internal(void* handle, const char* symbolName, void* callerAddress);
104
105 extern "C" void* dlopen_compat(const char* path, int mode);
106 extern "C" bool dlopen_preflight_compat(const char* path);
107 extern "C" void* dlsym_compat(void* handle, const char* symbolName);
108
109
110
111 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
112 #if TARGET_OS_OSX
113 #define DEPRECATED_APIS_SUPPORTED 1
114 #else
115 #define DEPRECATED_APIS_SUPPORTED 0
116 #endif
117
118 static bool sDynamicInterposing = false;
119
120 #if DEPRECATED_APIS_SUPPORTED
121 static char sLastErrorFilePath[1024];
122 static NSLinkEditErrors sLastErrorFileCode;
123 static int sLastErrorNo;
124 #endif
125
126 // In 10.3.x and earlier all the NSObjectFileImage API's were implemeneted in libSystem.dylib
127 // Beginning in 10.4 the NSObjectFileImage API's are implemented in dyld and libSystem just forwards
128 // This conditional keeps support for old libSystem's which needed some help implementing the API's
129 #define OLD_LIBSYSTEM_SUPPORT (__i386__)
130
131 // The following functions have no prototype in any header. They are special cases
132 // where _dyld_func_lookup() is used directly.
133 static void _dyld_make_delayed_module_initializer_calls();
134 static void registerThreadHelpers(const dyld::LibSystemHelpers*);
135 #if DEPRECATED_APIS_SUPPORTED
136 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit);
137 #if OLD_LIBSYSTEM_SUPPORT
138 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options);
139 #endif
140 static void _dyld_register_binding_handler(void * (*)(const char *, const char *, void *), ImageLoader::BindingOptions);
141 static bool NSMakePrivateModulePublic(NSModule module);
142 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header);
143
144 // The following functions are dyld API's, but since dyld links with a static copy of libc.a
145 // the public name cannot be used.
146 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module);
147 static bool client_NSIsSymbolNameDefined(const char* symbolName);
148 #endif // DEPRECATED_APIS_SUPPORTED
149 #if SUPPORT_ZERO_COST_EXCEPTIONS
150 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info);
151 #endif
152 #if DEPRECATED_APIS_SUPPORTED
153 #endif
154
155 static void unimplemented()
156 {
157 dyld::halt("unimplemented dyld function\n");
158 }
159
160 struct dyld_func {
161 const char* name;
162 void* implementation;
163 };
164
165 static const struct dyld_func dyld_funcs[] = {
166 {"__dyld_register_func_for_add_image", (void*)_dyld_register_func_for_add_image },
167 {"__dyld_register_func_for_remove_image", (void*)_dyld_register_func_for_remove_image },
168 {"__dyld_dladdr", (void*)dladdr },
169 {"__dyld_dlclose", (void*)dlclose },
170 {"__dyld_dlerror", (void*)dlerror },
171 {"__dyld_dlopen_internal", (void*)dlopen_internal },
172 {"__dyld_dlsym_internal", (void*)dlsym_internal },
173 {"__dyld_dlopen_preflight_internal", (void*)dlopen_preflight_internal },
174 {"__dyld_dlopen", (void*)dlopen_compat },
175 {"__dyld_dlsym", (void*)dlsym_compat },
176 {"__dyld_dlopen_preflight", (void*)dlopen_preflight_compat },
177 {"__dyld_image_count", (void*)_dyld_image_count },
178 {"__dyld_get_image_header", (void*)_dyld_get_image_header },
179 {"__dyld_get_image_vmaddr_slide", (void*)_dyld_get_image_vmaddr_slide },
180 {"__dyld_get_image_name", (void*)_dyld_get_image_name },
181 {"__dyld_get_image_slide", (void*)_dyld_get_image_slide },
182 {"__dyld_get_prog_image_header", (void*)_dyld_get_prog_image_header },
183 {"__dyld__NSGetExecutablePath", (void*)_NSGetExecutablePath },
184
185 // SPIs
186 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers },
187 {"__dyld_fork_child", (void*)_dyld_fork_child },
188 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls },
189 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos },
190 #if SUPPORT_ZERO_COST_EXCEPTIONS
191 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections },
192 #endif
193 #if __i386__ || __x86_64__ || __arm__ || __arm64__
194 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol },
195 #endif
196 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address },
197 {"__dyld_shared_cache_some_image_overridden", (void*)dyld_shared_cache_some_image_overridden },
198 {"__dyld_process_is_restricted", (void*)dyld::processIsRestricted },
199 {"__dyld_dynamic_interpose", (void*)dyld_dynamic_interpose },
200 {"__dyld_shared_cache_file_path", (void*)dyld::getStandardSharedCacheFilePath },
201 {"__dyld_has_inserted_or_interposing_libraries", (void*)dyld::hasInsertedOrInterposingLibraries },
202 {"__dyld_get_image_header_containing_address", (void*)dyld_image_header_containing_address },
203 {"__dyld_is_memory_immutable", (void*)_dyld_is_memory_immutable },
204 {"__dyld_objc_notify_register", (void*)_dyld_objc_notify_register },
205 {"__dyld_get_shared_cache_uuid", (void*)_dyld_get_shared_cache_uuid },
206 {"__dyld_get_shared_cache_range", (void*)_dyld_get_shared_cache_range },
207 {"__dyld_images_for_addresses", (void*)_dyld_images_for_addresses },
208 {"__dyld_register_for_image_loads", (void*)_dyld_register_for_image_loads },
209 {"__dyld_register_for_bulk_image_loads", (void*)_dyld_register_for_bulk_image_loads },
210 {"__dyld_register_driverkit_main", (void*)_dyld_register_driverkit_main },
211 {"__dyld_halt", (void*)dyld::halt },
212
213 #if DEPRECATED_APIS_SUPPORTED
214 #pragma clang diagnostic push
215 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
216 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind },
217 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint },
218 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully },
219 {"__dyld_install_handlers", (void*)_dyld_install_handlers },
220 {"__dyld_link_edit_error", (void*)NSLinkEditError },
221 {"__dyld_unlink_module", (void*)NSUnLinkModule },
222 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address },
223 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address },
224 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler },
225 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol },
226 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol },
227 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol },
228 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol },
229 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint },
230 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule},
231 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage},
232 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic},
233 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined},
234 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint },
235 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage},
236 {"__dyld_NSNameOfModule", (void*)NSNameOfModule },
237 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule },
238 {"__dyld_NSAddLibrary", (void*)NSAddLibrary },
239 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching },
240 {"__dyld_NSAddImage", (void*)NSAddImage },
241 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound },
242 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound },
243 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib },
244 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile },
245 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory },
246 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage },
247 {"__dyld_NSLinkModule", (void*)NSLinkModule },
248 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage },
249 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage },
250 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage },
251 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage },
252 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage },
253 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage },
254 #if OLD_LIBSYSTEM_SUPPORT
255 {"__dyld_link_module", (void*)_dyld_link_module },
256 #endif
257 #pragma clang diagnostic pop
258 #endif //DEPRECATED_APIS_SUPPORTED
259
260 {NULL, 0}
261 };
262
263
264
265 #if DEPRECATED_APIS_SUPPORTED
266
267 static void dyldAPIhalt(const char* apiName, const char* errorMsg)
268 {
269 dyld::log("dyld: %s() error\n", apiName);
270 dyld::halt(errorMsg);
271 }
272
273 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
274 inline NSSymbol SymbolToNSSymbol(const ImageLoader::Symbol* sym)
275 {
276 return (NSSymbol)sym;
277 }
278 inline const ImageLoader::Symbol* NSSymbolToSymbol(NSSymbol sym)
279 {
280 return (const ImageLoader::Symbol*)sym;
281 }
282
283 // dyld's abstract type NSModule is implemented as ImageLoader*
284 inline NSModule ImageLoaderToNSModule(const ImageLoader* image)
285 {
286 return (NSModule)image;
287 }
288 inline ImageLoader* NSModuleToImageLoader(NSModule module)
289 {
290 ImageLoader* image = (ImageLoader*)module;
291 if ( dyld::validImage(image) )
292 return image;
293 return NULL;
294 }
295
296 // actual definition for opaque type
297 struct __NSObjectFileImage
298 {
299 ImageLoader* image;
300 const void* imageBaseAddress; // not used with OFI created from files
301 size_t imageLength; // not used with OFI created from files
302 };
303 typedef __NSObjectFileImage* NSObjectFileImage;
304
305
306 VECTOR_NEVER_DESTRUCTED(NSObjectFileImage);
307 static std::vector<NSObjectFileImage> sObjectFileImages;
308
309
310
311 //
312 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
313 // The contained image is delete in one of two places:
314 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
315 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
316 //
317
318
319
320 static void setLastError(NSLinkEditErrors code, int errnum, const char* file, const char* message)
321 {
322 dyld::setErrorMessage(message);
323 strncpy(sLastErrorFilePath, file, 1024);
324 sLastErrorFilePath[1023] = '\0';
325 sLastErrorFileCode = code;
326 sLastErrorNo = errnum;
327 }
328
329 #endif // DEPRECATED_APIS_SUPPORTED
330
331 /*
332 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
333 * copies the path of the executable into the buffer and returns 0 if the path
334 * was successfully copied in the provided buffer. If the buffer is not large
335 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
336 * Note that _NSGetExecutablePath will return "a path" to the executable not a
337 * "real path" to the executable. That is the path may be a symbolic link and
338 * not the real file. And with deep directories the total bufsize needed could
339 * be more than MAXPATHLEN.
340 */
341 int _NSGetExecutablePath(char* buf, uint32_t *bufsize)
342 {
343 if ( dyld::gLogAPIs )
344 dyld::log("%s(...)\n", __func__);
345 const char* exePath = dyld::getExecutablePath();
346 if(*bufsize < strlen(exePath) + 1){
347 *bufsize = (uint32_t)(strlen(exePath) + 1);
348 return -1;
349 }
350 strcpy(buf, exePath);
351 return 0;
352 }
353
354 uint32_t _dyld_image_count(void)
355 {
356 if ( dyld::gLogAPIs )
357 dyld::log("%s()\n", __func__);
358 return allImagesCount();
359 }
360
361 const struct mach_header* _dyld_get_image_header(uint32_t image_index)
362 {
363 if ( dyld::gLogAPIs )
364 dyld::log("%s(%u)\n", __func__, image_index);
365 return allImagesIndexedMachHeader(image_index);
366 }
367
368 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index)
369 {
370 if ( dyld::gLogAPIs )
371 dyld::log("%s(%u)\n", __func__, image_index);
372 const struct mach_header* mh = allImagesIndexedMachHeader(image_index);
373 if ( mh != NULL )
374 return ImageLoaderMachO::computeSlide(mh);
375 else
376 return 0;
377 }
378
379 intptr_t _dyld_get_image_slide(const struct mach_header* mh)
380 {
381 if ( dyld::gLogAPIs )
382 dyld::log("%s(%p)\n", __func__, mh);
383 return ImageLoaderMachO::computeSlide(mh);
384 }
385
386
387 const char* _dyld_get_image_name(uint32_t image_index)
388 {
389 if ( dyld::gLogAPIs )
390 dyld::log("%s(%u)\n", __func__, image_index);
391 return allImagesIndexedPath(image_index);
392 }
393
394 const struct mach_header* _dyld_get_prog_image_header()
395 {
396 if ( dyld::gLogAPIs )
397 dyld::log("%s()\n", __func__);
398
399 return dyld::mainExecutable()->machHeader();
400 }
401
402 static const void *stripPointer(const void *ptr) {
403 #if __has_feature(ptrauth_calls)
404 return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
405 #else
406 return ptr;
407 #endif
408 }
409
410 static void *stripPointer(void *ptr) {
411 #if __has_feature(ptrauth_calls)
412 return __builtin_ptrauth_strip(ptr, ptrauth_key_asia);
413 #else
414 return ptr;
415 #endif
416 }
417
418 const struct mach_header * dyld_image_header_containing_address(const void* address)
419 {
420 if ( dyld::gLogAPIs )
421 dyld::log("%s(%p)\n", __func__, address);
422 address = stripPointer(address);
423 #if SUPPORT_ACCELERATE_TABLES
424 const mach_header* mh;
425 const char* path;
426 if ( dyld::addressInCache(address, &mh, &path) )
427 return mh;
428 #endif
429 ImageLoader* image = dyld::findImageContainingAddress(address);
430 if ( image != NULL )
431 return image->machHeader();
432 return NULL;
433 }
434
435
436 void _dyld_register_func_for_add_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
437 {
438 if ( dyld::gLogAPIs )
439 dyld::log("%s(%p)\n", __func__, (void *)func);
440 dyld::registerAddCallback(func);
441 }
442
443 void _dyld_register_func_for_remove_image(void (*func)(const struct mach_header *mh, intptr_t vmaddr_slide))
444 {
445 if ( dyld::gLogAPIs )
446 dyld::log("%s(%p)\n", __func__, (void *)func);
447 dyld::registerRemoveCallback(func);
448 }
449
450
451
452 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
453 static void _dyld_make_delayed_module_initializer_calls()
454 {
455 if ( dyld::gLogAPIs )
456 dyld::log("%s()\n", __func__);
457
458 #if SUPPORT_OLD_CRT_INITIALIZATION
459 if ( dyld::gRunInitializersOldWay )
460 dyld::initializeMainExecutable();
461 #endif
462 }
463
464
465
466 #if DEPRECATED_APIS_SUPPORTED
467
468 //
469 // _dyld_call_module_initializers_for_dylib() is the dyld side of
470 // __initialize_Cplusplus() which is in dylib1.o.
471 // It is intended to only be called inside -init rouintes.
472 // -init routines are called before module initializers (what C++
473 // initializers use). Calling __initialize_Cplusplus() in a -init
474 // routine causes the module initializers for an image to be called
475 // which then allows C++ to be used inside a -init routine
476 //
477 static void _dyld_call_module_initializers_for_dylib(const struct mach_header* mh_dylib_header)
478 {
479 if ( dyld::gLogAPIs )
480 dyld::log("__initialize_Cplusplus()\n");
481
482 // for now, do nothing...
483 }
484
485
486 void _dyld_lookup_and_bind_fully(const char* symbolName, void** address, NSModule* module)
487 {
488 if ( dyld::gLogAPIs )
489 dyld::log("%s(\"%s\", %p, %p)\n", __func__, symbolName, address, module);
490 ImageLoader* image;
491 const ImageLoader::Symbol* sym;
492 dyld::clearErrorMessage();
493 if ( dyld::flatFindExportedSymbol(symbolName, &sym, (const ImageLoader**)&image) ) {
494 try {
495 image->bindAllLazyPointers(dyld::gLinkContext, true);
496 if ( address != NULL)
497 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
498 if ( module != NULL)
499 *module = ImageLoaderToNSModule(image);
500 }
501 catch (const char* msg) {
502 dyldAPIhalt(__func__, msg);
503 }
504 }
505 else {
506 // on failure to find symbol return NULLs
507 if ( address != NULL)
508 *address = NULL;
509 if ( module != NULL)
510 *module = NULL;
511 }
512 }
513
514 // Note: This cannot have public name because dyld is built with a static copy of libc.a
515 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
516 static void client_dyld_lookup_and_bind(const char* symbolName, void** address, NSModule* module)
517 {
518 if ( dyld::gLogAPIs )
519 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName, address, module);
520 const ImageLoader* image;
521 const ImageLoader::Symbol* sym;
522 if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
523 if ( address != NULL)
524 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
525 if ( module != NULL)
526 *module = ImageLoaderToNSModule(image);
527 }
528 else {
529 // on failure to find symbol return NULLs
530 if ( address != NULL)
531 *address = NULL;
532 if ( module != NULL)
533 *module = NULL;
534 }
535 }
536
537 void _dyld_lookup_and_bind_with_hint(const char* symbolName, const char* library_name_hint, void** address, NSModule* module)
538 {
539 if ( dyld::gLogAPIs )
540 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__, symbolName, library_name_hint, address, module);
541 const ImageLoader* image;
542 const ImageLoader::Symbol* sym;
543 // Look for library whose path contains the hint. If that fails search everywhere
544 if ( dyld::flatFindExportedSymbolWithHint(symbolName, library_name_hint, &sym, &image)
545 || dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
546 if ( address != NULL)
547 *address = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext);
548 if ( module != NULL)
549 *module = ImageLoaderToNSModule(image);
550 }
551 else {
552 // on failure to find symbol return NULLs
553 if ( address != NULL)
554 *address = NULL;
555 if ( module != NULL)
556 *module = NULL;
557 }
558 }
559
560
561 NSSymbol NSLookupAndBindSymbol(const char *symbolName)
562 {
563 if ( dyld::gLogAPIs )
564 dyld::log("%s(\"%s\")\n", __func__, symbolName);
565 const ImageLoader* image;
566 const ImageLoader::Symbol* sym;
567 if ( dyld::flatFindExportedSymbol(symbolName, &sym, &image) ) {
568 return SymbolToNSSymbol(sym);
569 }
570 // return NULL on failure
571 return NULL;
572 }
573
574 NSSymbol NSLookupAndBindSymbolWithHint(const char* symbolName, const char* libraryNameHint)
575 {
576 if ( dyld::gLogAPIs )
577 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
578 const ImageLoader* image;
579 const ImageLoader::Symbol* sym;
580 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
581 if ( ! found ) {
582 // hint failed, do slow search of all images
583 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
584 }
585 if ( found )
586 return SymbolToNSSymbol(sym);
587
588 // return NULL on failure and log
589 if ( dyld::gLogAPIs )
590 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__, symbolName, libraryNameHint);
591 return NULL;
592 }
593
594
595
596
597 static __attribute__((noinline))
598 const struct mach_header* addImage(void* callerAddress, const char* path, bool search, bool dontLoad, bool matchInstallName, bool abortOnError)
599 {
600 ImageLoader* image = NULL;
601 std::vector<const char*> rpathsFromCallerImage;
602 try {
603 dyld::clearErrorMessage();
604 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
605 // like dlopen, use rpath from caller image and from main executable
606 if ( callerImage != NULL )
607 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
608 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
609 if ( callerImage != dyld::mainExecutable() ) {
610 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
611 }
612 dyld::LoadContext context;
613 context.useSearchPaths = search;
614 context.useFallbackPaths = search;
615 context.useLdLibraryPath = false;
616 context.implicitRPath = false;
617 context.matchByInstallName = matchInstallName;
618 context.dontLoad = dontLoad;
619 context.mustBeBundle = false;
620 context.mustBeDylib = true;
621 context.canBePIE = false;
622 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
623 context.rpath = &callersRPaths; // rpaths from caller and main executable
624
625 unsigned cacheIndex;
626 image = load(path, context, cacheIndex);
627 if ( image != NULL ) {
628 if ( context.matchByInstallName )
629 image->setMatchInstallPath(true);
630 dyld::link(image, false, false, callersRPaths, cacheIndex);
631 dyld::runInitializers(image);
632 // images added with NSAddImage() can never be unloaded
633 image->setNeverUnload();
634 }
635 }
636 catch (const char* msg) {
637 dyld::garbageCollectImages();
638 if ( abortOnError) {
639 char pathMsg[strlen(msg)+strlen(path)+4];
640 strcpy(pathMsg, msg);
641 strcat(pathMsg, " ");
642 strcat(pathMsg, path);
643 dyldAPIhalt("NSAddImage", pathMsg);
644 }
645 // not halting, so set error state for NSLinkEditError to find
646 setLastError(NSLinkEditOtherError, 0, path, msg);
647 free((void*)msg); // our free() will do nothing if msg is a string literal
648 image = NULL;
649 }
650 // free rpaths (getRPaths() malloc'ed each string)
651 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
652 const char* str = *it;
653 free((void*)str);
654 }
655 if ( image == NULL )
656 return NULL;
657 else
658 return image->machHeader();
659 }
660
661
662 const struct mach_header* NSAddImage(const char* path, uint32_t options)
663 {
664 if ( dyld::gLogAPIs )
665 dyld::log("%s(\"%s\", 0x%08X)\n", __func__, path, options);
666 const bool dontLoad = ( (options & NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED) != 0 );
667 const bool search = ( (options & NSADDIMAGE_OPTION_WITH_SEARCHING) != 0 );
668 const bool matchInstallName = ( (options & NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME) != 0 );
669 const bool abortOnError = ( (options & (NSADDIMAGE_OPTION_RETURN_ON_ERROR|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED)) == 0 );
670 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
671 return addImage(callerAddress, path, search, dontLoad, matchInstallName, abortOnError);
672 }
673
674 bool NSAddLibrary(const char* path)
675 {
676 if ( dyld::gLogAPIs )
677 dyld::log("%s(\"%s\")\n", __func__, path);
678 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
679 return (addImage(callerAddress, path, false, false, false, false) != NULL);
680 }
681
682 bool NSAddLibraryWithSearching(const char* path)
683 {
684 if ( dyld::gLogAPIs )
685 dyld::log("%s(\"%s\")\n", __func__, path);
686 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
687 return (addImage(callerAddress, path, true, false, false, false) != NULL);
688 }
689
690
691
692 //#define NSADDIMAGE_OPTION_NONE 0x0
693 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
694 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
695
696 bool NSIsSymbolNameDefinedInImage(const struct mach_header* mh, const char* symbolName)
697 {
698 if ( dyld::gLogAPIs )
699 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)mh, symbolName);
700 ImageLoader* image = dyld::findImageByMachHeader(mh);
701 if ( image != NULL ) {
702 if ( image->findExportedSymbol(symbolName, true, NULL) != NULL)
703 return true;
704 }
705 return false;
706 }
707
708
709 NSSymbol NSLookupSymbolInImage(const struct mach_header* mh, const char* symbolName, uint32_t options)
710 {
711 if ( dyld::gLogAPIs )
712 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, mh, symbolName, options);
713 const ImageLoader::Symbol* symbol = NULL;
714 dyld::clearErrorMessage();
715 ImageLoader* image = dyld::findImageByMachHeader(mh);
716 if ( image != NULL ) {
717 const char* symbolToFind = symbolName;
718 try {
719 if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY ) {
720 image->bindAllLazyPointers(dyld::gLinkContext, true);
721 }
722 else if ( options & NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW ) {
723 image->bindAllLazyPointers(dyld::gLinkContext, false);
724 }
725 }
726 catch (const char* msg) {
727 if ( (options & NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR) == 0 ) {
728 dyldAPIhalt(__func__, msg);
729 }
730 }
731 symbol = image->findExportedSymbol(symbolToFind, true, NULL);
732 }
733 if ( dyld::gLogAPIs && (symbol == NULL) )
734 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__, mh, symbolName, options);
735 return SymbolToNSSymbol(symbol);
736 }
737
738
739 // Note: This cannot have public name because dyld is built with a static copy of libc.a
740 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
741 static bool client_NSIsSymbolNameDefined(const char* symbolName)
742 {
743 if ( dyld::gLogAPIs )
744 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName);
745 const ImageLoader* image;
746 const ImageLoader::Symbol* sym;
747 return dyld::flatFindExportedSymbol(symbolName, &sym, &image);
748 }
749
750 bool NSIsSymbolNameDefinedWithHint(const char* symbolName, const char* libraryNameHint)
751 {
752 if ( dyld::gLogAPIs )
753 dyld::log("%s(\"%s\", \"%s\")\n", __func__, symbolName, libraryNameHint);
754 const ImageLoader* image;
755 const ImageLoader::Symbol* sym;
756 bool found = dyld::flatFindExportedSymbolWithHint(symbolName, libraryNameHint, &sym, &image);
757 if ( ! found ) {
758 // hint failed, do slow search of all images
759 found = dyld::flatFindExportedSymbol(symbolName, &sym, &image);
760 }
761 if ( !found && dyld::gLogAPIs )
762 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__, symbolName, libraryNameHint);
763 return found;
764 }
765
766 const char* NSNameOfSymbol(NSSymbol symbol)
767 {
768 if ( dyld::gLogAPIs )
769 dyld::log("%s(%p)\n", __func__, (void *)symbol);
770 const char* result = NULL;
771 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
772 if ( image != NULL )
773 result = image->getExportedSymbolName(NSSymbolToSymbol(symbol));
774 return result;
775 }
776
777 void* NSAddressOfSymbol(NSSymbol symbol)
778 {
779 if ( dyld::gLogAPIs )
780 dyld::log("%s(%p)\n", __func__, (void *)symbol);
781 if ( symbol == NULL )
782 return NULL;
783 void* result = NULL;
784 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
785 if ( image != NULL )
786 result = (void*)image->getExportedSymbolAddress(NSSymbolToSymbol(symbol), dyld::gLinkContext);
787
788 #if __has_feature(ptrauth_calls)
789 // Sign the pointer if it points to a function
790 if ( result ) {
791 const ImageLoader* symbolImage = image;
792 if (!symbolImage->containsAddress(result)) {
793 symbolImage = dyld::findImageContainingAddress(result);
794 }
795 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
796 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
797 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
798 }
799 #endif
800 return result;
801 }
802
803 NSModule NSModuleForSymbol(NSSymbol symbol)
804 {
805 if ( dyld::gLogAPIs )
806 dyld::log("%s(%p)\n", __func__, (void *)symbol);
807 NSModule result = NULL;
808 ImageLoader* image = dyld::findImageContainingSymbol(symbol);
809 if ( image != NULL )
810 result = ImageLoaderToNSModule(image);
811 return result;
812 }
813
814
815
816
817 bool _dyld_all_twolevel_modules_prebound(void)
818 {
819 if ( dyld::gLogAPIs )
820 dyld::log("%s()\n", __func__);
821 return FALSE;
822 }
823
824 bool _dyld_bind_fully_image_containing_address(const void* address)
825 {
826 if ( dyld::gLogAPIs )
827 dyld::log("%s(%p)\n", __func__, address);
828 address = stripPointer(address);
829 dyld::clearErrorMessage();
830 ImageLoader* image = dyld::findImageContainingAddress(address);
831 if ( image != NULL ) {
832 try {
833 image->bindAllLazyPointers(dyld::gLinkContext, true);
834 return true;
835 }
836 catch (const char* msg) {
837 dyldAPIhalt(__func__, msg);
838 }
839 }
840 return false;
841 }
842
843 bool _dyld_image_containing_address(const void* address)
844 {
845 if ( dyld::gLogAPIs )
846 dyld::log("%s(%p)\n", __func__, address);
847 ImageLoader *imageLoader = dyld::findImageContainingAddress(address);
848 return (NULL != imageLoader);
849 }
850
851 static NSObjectFileImage createObjectImageFile(ImageLoader* image, const void* address = NULL, size_t len=0)
852 {
853 NSObjectFileImage result = new __NSObjectFileImage();
854 result->image = image;
855 result->imageBaseAddress = address;
856 result->imageLength = len;
857 sObjectFileImages.push_back(result);
858 return result;
859 }
860
861 NSObjectFileImageReturnCode NSCreateObjectFileImageFromFile(const char* pathName, NSObjectFileImage *objectFileImage)
862 {
863 if ( dyld::gLogAPIs )
864 dyld::log("%s(\"%s\", ...)\n", __func__, pathName);
865 try {
866 void* callerAddress = __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
867 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
868
869 dyld::LoadContext context;
870 context.useSearchPaths = false;
871 context.useFallbackPaths = false;
872 context.useLdLibraryPath = false;
873 context.implicitRPath = false;
874 context.matchByInstallName = false;
875 context.dontLoad = false;
876 context.mustBeBundle = true;
877 context.mustBeDylib = false;
878 context.canBePIE = false;
879 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
880 context.rpath = NULL; // support not yet implemented
881
882 unsigned cacheIndex;
883 ImageLoader* image = dyld::load(pathName, context, cacheIndex);
884 // Note: We DO NOT link the image! NSLinkModule will do that
885 if ( image != NULL ) {
886 if ( !image->isBundle() ) {
887 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
888 return NSObjectFileImageInappropriateFile;
889 }
890 *objectFileImage = createObjectImageFile(image);
891 return NSObjectFileImageSuccess;
892 }
893 }
894 catch (const char* msg) {
895 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
896 dyld::garbageCollectImages();
897 free((void*)msg);
898 return NSObjectFileImageInappropriateFile;
899 }
900 return NSObjectFileImageFailure;
901 }
902
903
904 NSObjectFileImageReturnCode NSCreateObjectFileImageFromMemory(const void* address, size_t size, NSObjectFileImage *objectFileImage)
905 {
906 if ( dyld::gLogAPIs )
907 dyld::log("%s(%p, %lu, %p)\n", __func__, address, size, objectFileImage);
908
909 try {
910 ImageLoader* image = dyld::loadFromMemory((const uint8_t*)address, size, NULL);
911 if ( ! image->isBundle() ) {
912 // this API can only be used with bundles...
913 dyld::garbageCollectImages();
914 return NSObjectFileImageInappropriateFile;
915 }
916 // Note: We DO NOT link the image! NSLinkModule will do that
917 if ( image != NULL ) {
918 *objectFileImage = createObjectImageFile(image, address, size);
919 return NSObjectFileImageSuccess;
920 }
921 }
922 catch (const char* msg) {
923 free((void*)msg);
924 dyld::garbageCollectImages();
925 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
926 }
927 return NSObjectFileImageFailure;
928 }
929
930 static bool validOFI(NSObjectFileImage objectFileImage)
931 {
932 const size_t ofiCount = sObjectFileImages.size();
933 for (size_t i=0; i < ofiCount; ++i) {
934 if ( sObjectFileImages[i] == objectFileImage )
935 return true;
936 }
937 return false;
938 }
939
940 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage)
941 {
942 if ( dyld::gLogAPIs )
943 dyld::log("%s(%p)\n", __func__, objectFileImage);
944
945 if ( validOFI(objectFileImage) ) {
946 // a failure during NSLinkModule will delete the image
947 if ( objectFileImage->image != NULL ) {
948 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
949 // and we should delete it
950 bool linkedImage = dyld::validImage(objectFileImage->image);
951 if ( ! linkedImage ) {
952 ImageLoader::deleteImage(objectFileImage->image);
953 objectFileImage->image = NULL;
954 }
955 }
956
957 // remove from list of ofi's
958 for (std::vector<NSObjectFileImage>::iterator it=sObjectFileImages.begin(); it != sObjectFileImages.end(); it++) {
959 if ( *it == objectFileImage ) {
960 sObjectFileImages.erase(it);
961 break;
962 }
963 }
964
965 // if object was created from a memory, release that memory
966 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
967 if ( objectFileImage->imageBaseAddress != NULL ) {
968 bool freed = false;
969 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 6) ) {
970 size_t sz = (*dyld::gLibSystemHelpers->malloc_size)(objectFileImage->imageBaseAddress);
971 if ( sz != 0 ) {
972 (*dyld::gLibSystemHelpers->free)((void*)(objectFileImage->imageBaseAddress));
973 freed = true;
974 }
975 }
976 if ( ! freed )
977 vm_deallocate(mach_task_self(), (vm_address_t)objectFileImage->imageBaseAddress, objectFileImage->imageLength);
978 }
979
980 // free ofi object
981 delete objectFileImage;
982
983 return true;
984 }
985 return false;
986 }
987
988 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage)
989 {
990 if ( dyld::gLogAPIs )
991 dyld::log("%s(%p)\n", __func__, objectFileImage);
992 return objectFileImage->image->getExportedSymbolCount();
993 }
994
995 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal)
996 {
997 if ( dyld::gLogAPIs )
998 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
999 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedExportedSymbol(ordinal);
1000 return objectFileImage->image->getExportedSymbolName(sym);
1001 }
1002
1003 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage)
1004 {
1005 if ( dyld::gLogAPIs )
1006 dyld::log("%s(%p)\n", __func__, objectFileImage);
1007 return objectFileImage->image->getImportedSymbolCount();
1008 }
1009
1010 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage, uint32_t ordinal,
1011 bool* tentative_definition)
1012 {
1013 if ( dyld::gLogAPIs )
1014 dyld::log("%s(%p,%d)\n", __func__, objectFileImage, ordinal);
1015 const ImageLoader::Symbol* sym = objectFileImage->image->getIndexedImportedSymbol(ordinal);
1016 if ( tentative_definition != NULL ) {
1017 ImageLoader::ReferenceFlags flags = objectFileImage->image->getImportedSymbolInfo(sym);
1018 if ( (flags & ImageLoader::kTentativeDefinition) != 0 )
1019 *tentative_definition = true;
1020 else
1021 *tentative_definition = false;
1022 }
1023 return objectFileImage->image->getImportedSymbolName(sym);
1024 }
1025
1026 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage,
1027 const char* segmentName, const char* sectionName, unsigned long* size)
1028 {
1029 if ( dyld::gLogAPIs )
1030 dyld::log("%s(%p,%s, %s)\n", __func__, objectFileImage, segmentName, sectionName);
1031
1032 void* start;
1033 size_t length;
1034 if ( objectFileImage->image->getSectionContent(segmentName, sectionName, &start, &length) ) {
1035 if ( size != NULL )
1036 *size = length;
1037 return start;
1038 }
1039 return NULL;
1040 }
1041
1042
1043
1044 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage, const char* symbolName)
1045 {
1046 if ( dyld::gLogAPIs )
1047 dyld::log("%s(%p,%s)\n", __func__, objectFileImage, symbolName);
1048 const ImageLoader::Symbol* sym = objectFileImage->image->findExportedSymbol(symbolName, true, NULL);
1049 return ( sym != NULL );
1050 }
1051
1052
1053
1054 NSModule NSLinkModule(NSObjectFileImage objectFileImage, const char* moduleName, uint32_t options)
1055 {
1056 if ( dyld::gLogAPIs )
1057 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__, objectFileImage, moduleName, options);
1058
1059 dyld::clearErrorMessage();
1060 try {
1061 if ( (options & NSLINKMODULE_OPTION_CAN_UNLOAD) != 0 )
1062 objectFileImage->image->setCanUnload();
1063
1064 // NSLinkModule allows a bundle to be link multpile times
1065 // each link causes the bundle to be copied to a new address
1066 if ( objectFileImage->image->isLinked() ) {
1067 // already linked, so clone a new one and link it
1068 objectFileImage->image = dyld::cloneImage(objectFileImage->image);
1069 }
1070
1071 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
1072 if ( objectFileImage->image->getPath() == NULL ) {
1073 objectFileImage->image->setPath(moduleName);
1074 // <rdar://problem/8812589> dyld has NULL paths in image info array
1075 dyld_image_info info;
1076 info.imageLoadAddress = objectFileImage->image->machHeader();
1077 info.imageFilePath = moduleName;
1078 info.imageFileModDate = 0;
1079 addImagesToAllImages(1, &info);
1080 }
1081
1082 // support private bundles
1083 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1084 objectFileImage->image->setHideExports();
1085
1086 // set up linking options
1087 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1088
1089 // load libraries, rebase, bind, to make this image usable
1090 dyld::link(objectFileImage->image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1091
1092 // bump reference count to keep this bundle from being garbage collected
1093 objectFileImage->image->incrementDlopenReferenceCount();
1094
1095 // run initializers unless magic flag says not to
1096 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1097 dyld::runInitializers(objectFileImage->image);
1098
1099 return ImageLoaderToNSModule(objectFileImage->image);
1100 }
1101 catch (const char* msg) {
1102 dyld::garbageCollectImages();
1103 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1104 dyldAPIhalt(__func__, msg);
1105 // not halting, so set error state for NSLinkEditError to find
1106 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1107 // dyld::link() deleted the image so lose our reference
1108 objectFileImage->image = NULL;
1109 free((void*)msg);
1110 return NULL;
1111 }
1112 }
1113
1114
1115 #if OLD_LIBSYSTEM_SUPPORT
1116 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1117 static NSModule _dyld_link_module(NSObjectFileImage object_addr, size_t object_size, const char* moduleName, uint32_t options)
1118 {
1119 if ( dyld::gLogAPIs )
1120 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr, moduleName, options); // note name/args translation
1121 ImageLoader* image = NULL;
1122 dyld::clearErrorMessage();
1123 try {
1124 const char* imageName = moduleName;
1125 image = dyld::loadFromMemory((const uint8_t*)object_addr, object_size, imageName);
1126
1127 if ( image != NULL ) {
1128 // support private bundles
1129 if ( (options & NSLINKMODULE_OPTION_PRIVATE) != 0 )
1130 image->setHideExports();
1131
1132 // set up linking options
1133 bool forceLazysBound = ( (options & NSLINKMODULE_OPTION_BINDNOW) != 0 );
1134
1135 // load libraries, rebase, bind, to make this image usable
1136 dyld::link(image, forceLazysBound, false, ImageLoader::RPathChain(NULL,NULL), UINT32_MAX);
1137
1138 // run initializers unless magic flag says not to
1139 if ( (options & NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES) == 0 )
1140 dyld::runInitializers(image);
1141 }
1142 }
1143 catch (const char* msg) {
1144 if ( (options & NSLINKMODULE_OPTION_RETURN_ON_ERROR) == 0 )
1145 dyldAPIhalt("NSLinkModule", msg);
1146 // not halting, so set error state for NSLinkEditError to find
1147 setLastError(NSLinkEditOtherError, 0, moduleName, msg);
1148 // if image was created for this bundle, destroy it
1149 if ( image != NULL ) {
1150 dyld::removeImage(image);
1151 ImageLoader::deleteImage(image);
1152 }
1153 image = NULL;
1154 free((void*)msg);
1155 }
1156 return ImageLoaderToNSModule(image);
1157 }
1158 #endif
1159
1160 NSSymbol NSLookupSymbolInModule(NSModule module, const char* symbolName)
1161 {
1162 if ( dyld::gLogAPIs )
1163 dyld::log("%s(%p, \"%s\")\n", __func__, (void *)module, symbolName);
1164 ImageLoader* image = NSModuleToImageLoader(module);
1165 if ( image == NULL )
1166 return NULL;
1167 return SymbolToNSSymbol(image->findExportedSymbol(symbolName, false, NULL));
1168 }
1169
1170 const char* NSNameOfModule(NSModule module)
1171 {
1172 if ( dyld::gLogAPIs )
1173 dyld::log("%s(%p)\n", __func__, module);
1174 ImageLoader* image = NSModuleToImageLoader(module);
1175 if ( image == NULL )
1176 return NULL;
1177 return image->getPath();
1178 }
1179
1180 const char* NSLibraryNameForModule(NSModule module)
1181 {
1182 if ( dyld::gLogAPIs )
1183 dyld::log("%s(%p)\n", __func__, module);
1184 ImageLoader* image = NSModuleToImageLoader(module);
1185 if ( image == NULL )
1186 return NULL;
1187 return image->getPath();
1188 }
1189
1190 bool NSUnLinkModule(NSModule module, uint32_t options)
1191 {
1192 if ( dyld::gLogAPIs )
1193 dyld::log("%s(%p, 0x%08X)\n", __func__, module, options);
1194 if ( module == NULL )
1195 return false;
1196 ImageLoader* image = NSModuleToImageLoader(module);
1197 if ( image == NULL )
1198 return false;
1199 dyld::runImageStaticTerminators(image);
1200 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 13) ) {
1201 __cxa_range_t ranges[image->segmentCount()];
1202 int rangeCount = 0;
1203 for (unsigned int j=0; j < image->segmentCount(); ++j) {
1204 if ( !image->segExecutable(j) )
1205 continue;
1206 ranges[rangeCount].addr = (const void*)image->segActualLoadAddress(j);
1207 ranges[rangeCount].length = image->segSize(j);
1208 ++rangeCount;
1209 }
1210 (*dyld::gLibSystemHelpers->cxa_finalize_ranges)(ranges, rangeCount);
1211 }
1212 dyld::removeImage(image);
1213
1214 if ( (options & NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED) != 0 )
1215 image->setLeaveMapped();
1216
1217 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1218
1219 // Only delete image if there is no ofi referencing it
1220 // That means the ofi was destroyed after linking, so no one is left to delete this image
1221 const size_t ofiCount = sObjectFileImages.size();
1222 bool found = false;
1223 for (size_t i=0; i < ofiCount; ++i) {
1224 NSObjectFileImage ofi = sObjectFileImages[i];
1225 if ( ofi->image == image )
1226 found = true;
1227 }
1228 if ( !found )
1229 ImageLoader::deleteImage(image);
1230
1231 return true;
1232 }
1233
1234 // internal name and parameters do not match public name and parameters...
1235 static void _dyld_install_handlers(void* undefined, void* multiple, void* linkEdit)
1236 {
1237 if ( dyld::gLogAPIs )
1238 dyld::log("NSLinkEditErrorHandlers()\n");
1239
1240 dyld::registerUndefinedHandler((dyld::UndefinedHandler)undefined);
1241 // no support for multiple or linkedit handlers
1242 }
1243
1244
1245
1246
1247 void NSLinkEditError(NSLinkEditErrors* c, int* errorNumber, const char** fileName, const char** errorString)
1248 {
1249 // FIXME FIXME
1250 *c = sLastErrorFileCode;
1251 *errorNumber = sLastErrorNo;
1252 *fileName = sLastErrorFilePath;
1253 *errorString = dyld::getErrorMessage();
1254 }
1255
1256
1257
1258 static void _dyld_register_binding_handler(void * (*bindingHandler)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions)
1259 {
1260 if ( dyld::gLogAPIs )
1261 dyld::log("%s()\n", __func__);
1262 dyld::gLinkContext.bindingHandler = bindingHandler;
1263 dyld::gLinkContext.bindingOptions = bindingOptions;
1264 }
1265
1266 #endif //DEPRECATED_APIS_SUPPORTED
1267
1268
1269 // Call by fork() in libSystem after the kernel trap is done on the child side
1270 void _dyld_fork_child()
1271 {
1272 if ( dyld::gLogAPIs )
1273 dyld::log("%s()\n", __func__);
1274 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1275 // in libSystem for the child of a fork. But dyld is built with a static copy
1276 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1277 //
1278 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1279 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1280 //
1281 extern mach_port_t mach_task_self_;
1282 mach_task_self_ = task_self_trap();
1283
1284 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1285 // page is not copied on fork. <rdar://problem/6797342>
1286 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1287 dyld::gProcessInfo->coreSymbolicationShmPage = NULL;
1288 // for safety, make sure child starts with clean systemOrderFlag
1289 dyld::gProcessInfo->systemOrderFlag = 0;
1290 }
1291
1292
1293 #if DEPRECATED_APIS_SUPPORTED
1294 // returns true if prebinding was used in main executable
1295 bool _dyld_launched_prebound()
1296 {
1297 if ( dyld::gLogAPIs )
1298 dyld::log("%s()\n", __func__);
1299
1300 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1301 return dyld::mainExecutablePrebound();
1302 }
1303
1304
1305 //
1306 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1307 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1308 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1309 // flag on the image for this module. If the module was found and it was
1310 // private then everything worked and TRUE is returned else FALSE is returned.
1311 //
1312 static bool NSMakePrivateModulePublic(NSModule module)
1313 {
1314 ImageLoader* image = NSModuleToImageLoader(module);
1315 if ( image != NULL ) {
1316 if ( image->hasHiddenExports() ) {
1317 image->setHideExports(false);
1318 return true;
1319 }
1320 }
1321 return false;
1322 }
1323
1324 #endif // DEPRECATED_APIS_SUPPORTED
1325
1326 int _dyld_func_lookup(const char* name, void** address)
1327 {
1328 for (const dyld_func* p = dyld_funcs; p->name != NULL; ++p) {
1329 if ( strcmp(p->name, name) == 0 ) {
1330 if( p->implementation == unimplemented )
1331 dyld::log("unimplemented dyld function: %s\n", p->name);
1332 *address = p->implementation;
1333 return true;
1334 }
1335 }
1336 *address = 0;
1337 return false;
1338 }
1339
1340
1341 static void registerThreadHelpers(const dyld::LibSystemHelpers* helpers)
1342 {
1343 dyld::gLibSystemHelpers = helpers;
1344
1345 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1346 if ( helpers->version >= 5 ) {
1347 // create key use by dyld exception handling
1348 pthread_key_t key;
1349 int result = helpers->pthread_key_create(&key, NULL);
1350 if ( result == 0 )
1351 __Unwind_SjLj_SetThreadKey(key);
1352 }
1353 #endif
1354 }
1355
1356
1357 static void dlerrorClear()
1358 {
1359 if ( dyld::gLibSystemHelpers != NULL ) {
1360 // <rdar://problem/10595338> dlerror buffer leak
1361 // dlerrorClear() should not force allocation, but zero it if already allocated
1362 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1363 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1364 return;
1365 }
1366
1367 // first char of buffer is flag whether string (starting at second char) is valid
1368 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1369 buffer[0] = '\0';
1370 buffer[1] = '\0';
1371 }
1372 }
1373
1374 static void dlerrorSet(const char* msg)
1375 {
1376 if ( dyld::gLibSystemHelpers != NULL ) {
1377 // first char of buffer is flag whether string (starting at second char) is valid
1378 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(strlen(msg)+2);
1379 buffer[0] = '\1';
1380 strcpy(&buffer[1], msg);
1381 }
1382 }
1383
1384
1385 bool dlopen_preflight_internal(const char* path, void* callerAddress)
1386 {
1387 if ( dyld::gLogAPIs )
1388 dyld::log("%s(%s)\n", __func__, path);
1389
1390 dlerrorClear();
1391
1392 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1393
1394 const bool leafName = (strchr(path, '/') == NULL);
1395 const bool absolutePath = (path[0] == '/');
1396 #if TARGET_OS_IPHONE
1397 char canonicalPath[PATH_MAX];
1398 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1399 if ( !leafName ) {
1400 // make path canonical if it contains a // or ./
1401 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1402 const char* lastSlash = strrchr(path, '/');
1403 char dirPath[PATH_MAX];
1404 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1405 dirPath[lastSlash-path] = '\0';
1406 if ( realpath(dirPath, canonicalPath) ) {
1407 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1408 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1409 // if all fit in buffer, use new canonical path
1410 path = canonicalPath;
1411 }
1412 }
1413 }
1414 }
1415 }
1416 #endif
1417 #if SUPPORT_ACCELERATE_TABLES
1418 if ( dyld::isPathInCache(path) )
1419 return true;
1420 #endif
1421
1422 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1423 // if requested path is to something in the dyld shared cache, always succeed
1424 if ( dyld::inSharedCache(path) )
1425 return true;
1426
1427 #if TARGET_OS_OSX
1428 // <rdar://problem/47464387> dlopen_preflight() on symlink to image in shared cache leaves it half loaded
1429 if ( strncmp(path, "/System/Library/", 16) == 0 ) {
1430 char canonicalPath[PATH_MAX];
1431 if ( realpath(path, canonicalPath) ) {
1432 if ( dyld::inSharedCache(canonicalPath) )
1433 return true;
1434 }
1435 }
1436 #endif
1437
1438 bool result = false;
1439 std::vector<const char*> rpathsFromCallerImage;
1440 try {
1441 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1442 // for dlopen, use rpath from caller image and from main executable
1443 if ( callerImage != NULL )
1444 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1445 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1446 if ( callerImage != dyld::mainExecutable() ) {
1447 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1448 }
1449
1450 ImageLoader* image = NULL;
1451 dyld::LoadContext context;
1452 context.useSearchPaths = true;
1453 context.useFallbackPaths= leafName; // a partial path implies don't use fallback paths
1454 context.useLdLibraryPath= leafName; // a leafname implies should search
1455 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1456 context.matchByInstallName = true;
1457 context.dontLoad = false;
1458 context.mustBeBundle = false;
1459 context.mustBeDylib = false;
1460 context.canBePIE = true;
1461 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1462 context.rpath = &callersRPaths; // rpaths from caller and main executable
1463
1464 unsigned cacheIndex;
1465 image = load(path, context, cacheIndex);
1466 if ( image != NULL ) {
1467 dyld::preflight(image, callersRPaths, cacheIndex); // image object deleted by dyld::preflight()
1468 result = true;
1469 }
1470 }
1471 catch (const char* msg) {
1472 const char* str = dyld::mkstringf("dlopen_preflight(%s): %s", path, msg);
1473 dlerrorSet(str);
1474 free((void*)str);
1475 free((void*)msg); // our free() will do nothing if msg is a string literal
1476 }
1477 // free rpaths (getRPaths() malloc'ed each string)
1478 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1479 const char* str = *it;
1480 free((void*)str);
1481 }
1482 CRSetCrashLogMessage(NULL);
1483 return result;
1484 }
1485
1486 #if SUPPORT_ACCELERATE_TABLES
1487 bool static callerIsNonOSApp(void* callerAddress, const char** shortName)
1488 {
1489 *shortName = NULL;
1490 const mach_header* unusedMh;
1491 const char* unusedPath;
1492 unsigned unusedIndex;
1493 // any address in shared cache is not from app
1494 if ( dyld::addressInCache(callerAddress, &unusedMh, &unusedPath, &unusedIndex) )
1495 return false;
1496
1497 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1498 if ( callerImage == NULL )
1499 return false;
1500
1501 *shortName = callerImage->getShortName();
1502 return ( strncmp(callerImage->getPath(), "/var/containers/", 16) == 0 );
1503 }
1504 #endif
1505
1506 void* dlopen_internal(const char* path, int mode, void* callerAddress)
1507 {
1508 if ( dyld::gLogAPIs )
1509 dyld::log("%s(%s, 0x%08X)\n", __func__, ((path==NULL) ? "NULL" : path), mode);
1510
1511 #if SUPPORT_ACCELERATE_TABLES
1512 if ( dyld::gLogAppAPIs ) {
1513 const char* shortName;
1514 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1515 dyld::log("%s: %s(%s, 0x%08X)\n", shortName, __func__, ((path==NULL) ? "NULL" : path), mode);
1516 }
1517 }
1518 #endif
1519
1520 dlerrorClear();
1521
1522 // passing NULL for path means return magic object
1523 if ( path == NULL ) {
1524 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1525 if ( (mode & RTLD_FIRST) != 0 )
1526 return RTLD_MAIN_ONLY;
1527 else
1528 return RTLD_DEFAULT;
1529 }
1530
1531 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1532 bool lockHeld = false;
1533 if ( (dyld::gLibSystemHelpers != NULL) && (dyld::gLibSystemHelpers->version >= 4) ) {
1534 dyld::gLibSystemHelpers->acquireGlobalDyldLock();
1535 CRSetCrashLogMessage("dyld: in dlopen()");
1536 lockHeld = true;
1537 }
1538
1539 void* result = NULL;
1540 const bool leafName = (strchr(path, '/') == NULL);
1541 const bool absolutePath = (path[0] == '/');
1542 #if TARGET_OS_IPHONE
1543 char canonicalPath[PATH_MAX];
1544 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1545 if ( !leafName ) {
1546 // make path canonical if it contains a // or ./
1547 if ( (strstr(path, "//") != NULL) || (strstr(path, "./") != NULL) ) {
1548 const char* lastSlash = strrchr(path, '/');
1549 char dirPath[PATH_MAX];
1550 if ( strlcpy(dirPath, path, sizeof(dirPath)) < sizeof(dirPath) ) {
1551 dirPath[lastSlash-path] = '\0';
1552 if ( realpath(dirPath, canonicalPath) ) {
1553 strlcat(canonicalPath, "/", sizeof(canonicalPath));
1554 if ( strlcat(canonicalPath, lastSlash+1, sizeof(canonicalPath)) < sizeof(canonicalPath) ) {
1555 // if all fit in buffer, use new canonical path
1556 path = canonicalPath;
1557 }
1558 }
1559 }
1560 }
1561 }
1562 #endif
1563 #if SUPPORT_ACCELERATE_TABLES
1564 if ( dyld::dlopenFromCache(path, mode, &result) ) {
1565 // Note: dlopenFromCache() releases the lock
1566 if ( dyld::gLogAPIs )
1567 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1568 return result;
1569 }
1570 #endif
1571
1572 ImageLoader* image = NULL;
1573 std::vector<const char*> rpathsFromCallerImage;
1574 ImageLoader::RPathChain callersRPaths(NULL, &rpathsFromCallerImage);
1575 try {
1576 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1577 if ( (mode & RTLD_NOLOAD) == 0 ) {
1578 // for dlopen, use rpath from caller image and from main executable
1579 if ( callerImage != NULL )
1580 callerImage->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1581 if ( callerImage != dyld::mainExecutable() )
1582 dyld::mainExecutable()->getRPaths(dyld::gLinkContext, rpathsFromCallerImage);
1583 }
1584
1585 dyld::LoadContext context;
1586 context.useSearchPaths = true;
1587 context.useFallbackPaths= leafName; // a partial path means no fallback paths
1588 context.useLdLibraryPath= leafName; // a leafname implies should search
1589 context.implicitRPath = !absolutePath; // a non-absolute path implies try rpath searching
1590 context.matchByInstallName = true;
1591 context.dontLoad = ( (mode & RTLD_NOLOAD) != 0 );
1592 context.mustBeBundle = false;
1593 context.mustBeDylib = false;
1594 context.canBePIE = true;
1595 context.origin = callerImage != NULL ? callerImage->getPath() : NULL; // caller's image's path
1596 context.rpath = &callersRPaths; // rpaths from caller and main executable
1597
1598 unsigned cacheIndex;
1599 image = load(path, context, cacheIndex);
1600 #if SUPPORT_ACCELERATE_TABLES
1601 if ( (image != NULL) && (cacheIndex != UINT32_MAX) ) {
1602 // found in cache, but under a different path
1603 const char* betterPath = dyld::getPathFromIndex(cacheIndex);
1604 if ( (betterPath != NULL) && dyld::dlopenFromCache(betterPath, mode, &result) ) {
1605 // Note: dlopenFromCache() releases the lock
1606 if ( dyld::gLogAPIs )
1607 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1608 return result;
1609 }
1610 }
1611 #endif
1612 if ( image != NULL ) {
1613 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1614 // this image is not garbage collected
1615 image->incrementDlopenReferenceCount();
1616 // link in all dependents
1617 if ( (mode & RTLD_NOLOAD) == 0 ) {
1618 bool alreadyLinked = image->isLinked();
1619 bool forceLazysBound = ( (mode & RTLD_NOW) != 0 );
1620 dyld::link(image, forceLazysBound, false, callersRPaths, cacheIndex);
1621 if ( alreadyLinked ) {
1622 // upgrade
1623 if ( ((mode & RTLD_LOCAL) == 0) && image->hasHiddenExports() )
1624 image->setHideExports(false);
1625 }
1626 else {
1627 // only hide exports if image is not already in use
1628 if ( (mode & RTLD_LOCAL) != 0 )
1629 image->setHideExports(true);
1630 }
1631 }
1632
1633 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1634 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1635 // The subtle differences are:
1636 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1637 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1638 if ( (mode & RTLD_NODELETE) != 0 )
1639 image->setLeaveMapped();
1640
1641 // release global dyld lock early, this enables initializers to do threaded operations
1642 if ( lockHeld ) {
1643 CRSetCrashLogMessage(NULL);
1644 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1645 lockHeld = false;
1646 }
1647
1648 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1649 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1650 // called from within an initializer because it can cause initializers to run
1651 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1652 // to run, then don't use RTLD_NOLOAD.
1653 if ( (mode & RTLD_NOLOAD) == 0 ) {
1654 // run initializers
1655 dyld::runInitializers(image);
1656 }
1657
1658 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1659 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1660 if ( (mode & RTLD_FIRST) != 0 )
1661 result = (void*)(((uintptr_t)image)|1);
1662 else
1663 result = image;
1664 }
1665 }
1666 catch (const char* msg) {
1667 if ( image != NULL ) {
1668 // load() succeeded but, link() failed
1669 // back down reference count and do GC
1670 image->decrementDlopenReferenceCount();
1671 if ( image->dlopenCount() == 0 )
1672 dyld::garbageCollectImages();
1673 }
1674 const char* str = dyld::mkstringf("dlopen(%s, %d): %s", path, mode, msg);
1675 if ( dyld::gLogAPIs )
1676 dyld::log(" %s() failed, error: '%s'\n", __func__, str);
1677 dlerrorSet(str);
1678 free((void*)str);
1679 free((void*)msg); // our free() will do nothing if msg is a string literal
1680 result = NULL;
1681 }
1682 // free rpaths (getRPaths() malloc'ed each string)
1683 for(std::vector<const char*>::iterator it=rpathsFromCallerImage.begin(); it != rpathsFromCallerImage.end(); ++it) {
1684 const char* str = *it;
1685 free((void*)str);
1686 }
1687
1688 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1689 if ( (mode & RTLD_NOLOAD) && (result == NULL) ) {
1690 dlerrorSet("image not already loaded");
1691 }
1692
1693 if ( lockHeld ) {
1694 CRSetCrashLogMessage(NULL);
1695 dyld::gLibSystemHelpers->releaseGlobalDyldLock();
1696 }
1697 if ( dyld::gLogAPIs && (result != NULL) )
1698 dyld::log(" %s(%s) ==> %p\n", __func__, path, result);
1699 return result;
1700 }
1701
1702 int dlclose(void* handle)
1703 {
1704 if ( dyld::gLogAPIs )
1705 dyld::log("%s(%p)\n", __func__, handle);
1706
1707 // silently accept magic handles for main executable
1708 if ( handle == RTLD_MAIN_ONLY )
1709 return 0;
1710 if ( handle == RTLD_DEFAULT )
1711 return 0;
1712
1713 #if SUPPORT_ACCELERATE_TABLES
1714 if ( dyld::isCacheHandle(handle) ) {
1715 dlerrorClear();
1716 return 0;
1717 }
1718 #endif
1719
1720 ImageLoader* image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
1721 if ( dyld::validImage(image) ) {
1722 dlerrorClear();
1723 // decrement use count
1724 if ( image->decrementDlopenReferenceCount() ) {
1725 dlerrorSet("dlclose() called too many times");
1726 return -1;
1727 }
1728 // remove image if reference count went to zero
1729 if ( image->dlopenCount() == 0 )
1730 dyld::garbageCollectImages();
1731 return 0;
1732 }
1733 else {
1734 dlerrorSet("invalid handle passed to dlclose()");
1735 return -1;
1736 }
1737 }
1738
1739
1740
1741 int dladdr(const void* address, Dl_info* info)
1742 {
1743 if ( dyld::gLogAPIs )
1744 dyld::log("%s(%p, %p)\n", __func__, address, info);
1745
1746 // <rdar://problem/42171466> calling dladdr(xx,NULL) crashes
1747 if ( info == NULL )
1748 return 0; // failure
1749
1750 address = stripPointer(address);
1751
1752 CRSetCrashLogMessage("dyld: in dladdr()");
1753 #if SUPPORT_ACCELERATE_TABLES
1754 if ( dyld::dladdrFromCache(address, info) ) {
1755 CRSetCrashLogMessage(NULL);
1756 return 1; // success
1757 }
1758 #endif
1759
1760 ImageLoader* image = dyld::findImageContainingAddress(address);
1761 if ( image != NULL ) {
1762 info->dli_fname = image->getRealPath();
1763 info->dli_fbase = (void*)image->machHeader();
1764 if ( address == info->dli_fbase ) {
1765 // special case lookup of header
1766 info->dli_sname = "__dso_handle";
1767 info->dli_saddr = info->dli_fbase;
1768 CRSetCrashLogMessage(NULL);
1769 return 1; // success
1770 }
1771 // find closest symbol in the image
1772 info->dli_sname = image->findClosestSymbol(address, (const void**)&info->dli_saddr);
1773 // never return the mach_header symbol
1774 if ( info->dli_saddr == info->dli_fbase ) {
1775 info->dli_sname = NULL;
1776 info->dli_saddr = NULL;
1777 CRSetCrashLogMessage(NULL);
1778 return 1; // success
1779 }
1780 if ( info->dli_sname != NULL ) {
1781 if ( info->dli_sname[0] == '_' )
1782 info->dli_sname = info->dli_sname +1; // strip off leading underscore
1783 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1784 CRSetCrashLogMessage(NULL);
1785 return 1; // success
1786 }
1787 info->dli_sname = NULL;
1788 info->dli_saddr = NULL;
1789 CRSetCrashLogMessage(NULL);
1790 return 1; // success
1791 }
1792 CRSetCrashLogMessage(NULL);
1793 return 0; // failure
1794 }
1795
1796
1797 char* dlerror()
1798 {
1799 if ( dyld::gLogAPIs )
1800 dyld::log("%s()\n", __func__);
1801
1802 if ( dyld::gLibSystemHelpers != NULL ) {
1803 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1804 if ( dyld::gLibSystemHelpers->version >= 10 ) {
1805 if ( ! (*dyld::gLibSystemHelpers->hasPerThreadBufferFor_dlerror)() )
1806 return NULL;
1807 }
1808
1809 // first char of buffer is flag whether string (starting at second char) is valid
1810 char* buffer = (*dyld::gLibSystemHelpers->getThreadBufferFor_dlerror)(2);
1811 if ( buffer[0] != '\0' ) { // if valid buffer
1812 buffer[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1813 return &buffer[1]; // return message
1814 }
1815 }
1816 return NULL;
1817 }
1818
1819 void* dlsym_internal(void* handle, const char* symbolName, void* callerAddress)
1820 {
1821 if ( dyld::gLogAPIs )
1822 dyld::log("%s(%p, %s)\n", __func__, handle, symbolName);
1823
1824 #if SUPPORT_ACCELERATE_TABLES
1825 if ( dyld::gLogAppAPIs ) {
1826 const char* shortName;
1827 if ( callerIsNonOSApp(callerAddress, &shortName) ) {
1828 dyld::log("%s: %s(%p, %s)\n", shortName, __func__, handle, symbolName);
1829 }
1830 }
1831 #endif
1832
1833 CRSetCrashLogMessage("dyld: in dlsym()");
1834 dlerrorClear();
1835
1836 const ImageLoader* image;
1837 const ImageLoader::Symbol* sym;
1838 void* result;
1839
1840 // dlsym() assumes symbolName passed in is same as in C source code
1841 // dyld assumes all symbol names have an underscore prefix
1842 char underscoredName[strlen(symbolName)+2];
1843 underscoredName[0] = '_';
1844 strcpy(&underscoredName[1], symbolName);
1845
1846 // magic "search all" handle
1847 if ( handle == RTLD_DEFAULT ) {
1848 if ( dyld::flatFindExportedSymbol(underscoredName, &sym, &image) ) {
1849 CRSetCrashLogMessage(NULL);
1850 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1851 #if __has_feature(ptrauth_calls)
1852 // Sign the pointer if it points to a function
1853 // Note we only do this if the main executable is arm64e as otherwise we
1854 // may end up calling containsAddress on the accelerator tables.
1855 if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
1856 const ImageLoader* symbolImage = image;
1857 if (!symbolImage->containsAddress(result)) {
1858 symbolImage = dyld::findImageContainingAddress(result);
1859 }
1860 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
1861 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
1862 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
1863 }
1864 #endif
1865 if ( dyld::gLogAPIs )
1866 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__, symbolName, result);
1867 return result;
1868 }
1869 const char* str = dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName);
1870 dlerrorSet(str);
1871 free((void*)str);
1872 CRSetCrashLogMessage(NULL);
1873 if ( dyld::gLogAPIs )
1874 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__, symbolName);
1875 return NULL;
1876 }
1877
1878 // magic "search only main executable" handle
1879 else if ( handle == RTLD_MAIN_ONLY ) {
1880 image = dyld::mainExecutable();
1881 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
1882 if ( sym != NULL ) {
1883 CRSetCrashLogMessage(NULL);
1884 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, NULL, false, underscoredName);
1885 #if __has_feature(ptrauth_calls)
1886 // Sign the pointer if it points to a function
1887 // Note we only do this if the main executable is arm64e as otherwise we
1888 // may end up calling containsAddress on the accelerator tables.
1889 if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
1890 const ImageLoader* symbolImage = image;
1891 if (!symbolImage->containsAddress(result)) {
1892 symbolImage = dyld::findImageContainingAddress(result);
1893 }
1894 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
1895 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
1896 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
1897 }
1898 #endif
1899 if ( dyld::gLogAPIs )
1900 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__, symbolName, result);
1901 return result;
1902 }
1903 const char* str = dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName);
1904 dlerrorSet(str);
1905 free((void*)str);
1906 CRSetCrashLogMessage(NULL);
1907 if ( dyld::gLogAPIs )
1908 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__, symbolName);
1909 return NULL;
1910 }
1911
1912 // magic "search what I would see" handle
1913 else if ( handle == RTLD_NEXT ) {
1914 #if SUPPORT_ACCELERATE_TABLES
1915 const mach_header* mh;
1916 const char* path;
1917 unsigned index;
1918 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1919 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1920 result = dyld::dlsymFromCache(RTLD_NEXT, underscoredName, index);
1921 if ( dyld::gLogAPIs )
1922 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1923 return result;
1924 }
1925 #endif
1926 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1927 sym = callerImage->findExportedSymbolInDependentImages(underscoredName, dyld::gLinkContext, &image); // don't search image, but do search what it links against
1928 if ( sym != NULL ) {
1929 CRSetCrashLogMessage(NULL);
1930 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext , callerImage, false, underscoredName);
1931 #if __has_feature(ptrauth_calls)
1932 // Sign the pointer if it points to a function
1933 // Note we only do this if the main executable is arm64e as otherwise we
1934 // may end up calling containsAddress on the accelerator tables.
1935 if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
1936 const ImageLoader* symbolImage = image;
1937 if (!symbolImage->containsAddress(result)) {
1938 symbolImage = dyld::findImageContainingAddress(result);
1939 }
1940 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
1941 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
1942 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
1943 }
1944 #endif
1945 if ( dyld::gLogAPIs )
1946 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__, symbolName, result);
1947 return result;
1948 }
1949 const char* str = dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName);
1950 dlerrorSet(str);
1951 free((void*)str);
1952 CRSetCrashLogMessage(NULL);
1953 if ( dyld::gLogAPIs )
1954 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__, symbolName);
1955 return NULL;
1956 }
1957 // magic "search me, then what I would see" handle
1958 else if ( handle == RTLD_SELF ) {
1959 #if SUPPORT_ACCELERATE_TABLES
1960 const mach_header* mh;
1961 const char* path;
1962 unsigned index;
1963 if ( dyld::addressInCache(callerAddress, &mh, &path, &index) ) {
1964 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1965 result = dyld::dlsymFromCache(RTLD_SELF, underscoredName, index);
1966 if ( dyld::gLogAPIs )
1967 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1968 return result;
1969 }
1970 #endif
1971 ImageLoader* callerImage = dyld::findImageContainingAddress(callerAddress);
1972 sym = callerImage->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
1973 if ( sym != NULL ) {
1974 CRSetCrashLogMessage(NULL);
1975 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
1976 #if __has_feature(ptrauth_calls)
1977 // Sign the pointer if it points to a function
1978 // Note we only do this if the main executable is arm64e as otherwise we
1979 // may end up calling containsAddress on the accelerator tables.
1980 if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
1981 const ImageLoader* symbolImage = image;
1982 if (!symbolImage->containsAddress(result)) {
1983 symbolImage = dyld::findImageContainingAddress(result);
1984 }
1985 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
1986 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
1987 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
1988 }
1989 #endif
1990 if ( dyld::gLogAPIs )
1991 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__, symbolName, result);
1992 return result;
1993 }
1994 const char* str = dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName);
1995 dlerrorSet(str);
1996 free((void*)str);
1997 CRSetCrashLogMessage(NULL);
1998 if ( dyld::gLogAPIs )
1999 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__, symbolName);
2000 return NULL;
2001 }
2002 #if SUPPORT_ACCELERATE_TABLES
2003 // check for mega dylib handle
2004 else if ( dyld::isCacheHandle(handle) ) {
2005 result = dyld::dlsymFromCache(handle, underscoredName, 0);
2006 if ( dyld::gLogAPIs )
2007 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
2008 return result;
2009 }
2010 #endif
2011 // real handle
2012 image = (ImageLoader*)(((uintptr_t)handle) & (-4)); // clear mode bits
2013 if ( dyld::validImage(image) ) {
2014 if ( (((uintptr_t)handle) & 1) != 0 )
2015 sym = image->findExportedSymbol(underscoredName, true, &image); // search RTLD_FIRST way
2016 else
2017 sym = image->findExportedSymbolInImageOrDependentImages(underscoredName, dyld::gLinkContext, &image); // search image and what it links against
2018
2019 if ( sym != NULL ) {
2020 CRSetCrashLogMessage(NULL);
2021 ImageLoader* callerImage = NULL;
2022 if ( sDynamicInterposing ) {
2023 // only take time to look up caller, if dynamic interposing in use
2024 callerImage = dyld::findImageContainingAddress(callerAddress);
2025 }
2026 result = (void*)image->getExportedSymbolAddress(sym, dyld::gLinkContext, callerImage, false, underscoredName);
2027 #if __has_feature(ptrauth_calls)
2028 // Sign the pointer if it points to a function
2029 // Note we only do this if the main executable is arm64e as otherwise we
2030 // may end up calling containsAddress on the accelerator tables.
2031 if ( result && ((dyld::gLinkContext.mainExecutable->machHeader()->cpusubtype & ~CPU_SUBTYPE_MASK) == CPU_SUBTYPE_ARM64E) ) {
2032 const ImageLoader* symbolImage = image;
2033 if (!symbolImage->containsAddress(result)) {
2034 symbolImage = dyld::findImageContainingAddress(result);
2035 }
2036 const macho_section *sect = symbolImage ? symbolImage->findSection(result) : NULL;
2037 if ( sect && ((sect->flags & S_ATTR_PURE_INSTRUCTIONS) || (sect->flags & S_ATTR_SOME_INSTRUCTIONS)) )
2038 result = __builtin_ptrauth_sign_unauthenticated(result, ptrauth_key_asia, 0);
2039 }
2040 #endif
2041 if ( dyld::gLogAPIs )
2042 dyld::log(" %s(%p, %s) ==> %p\n", __func__, handle, symbolName, result);
2043 return result;
2044 }
2045 const char* str = dyld::mkstringf("dlsym(%p, %s): symbol not found", handle, symbolName);
2046 dlerrorSet(str);
2047 free((void*)str);
2048 }
2049 else {
2050 dlerrorSet("invalid handle passed to dlsym()");
2051 }
2052 CRSetCrashLogMessage(NULL);
2053 if ( dyld::gLogAPIs )
2054 dyld::log(" %s(%p, %s) ==> NULL\n", __func__, handle, symbolName);
2055 return NULL;
2056 }
2057
2058 // Note this is only here to support ___pthread_abort in libpthread.a
2059 void* dlsym(void* handle, const char* symbolName) {
2060 return dlsym_internal(handle, symbolName, __builtin_return_address(1));
2061 }
2062
2063
2064 // <rdar://problem/40352925> *_compat functions are for old binaries that have __dyld section and use it to bypass libdyld.dylib
2065 void* dlopen_compat(const char* path, int mode)
2066 {
2067 return dlopen_internal(path, mode, (void*)dyld::mainExecutable()->machHeader());
2068 }
2069 bool dlopen_preflight_compat(const char* path)
2070 {
2071 return dlopen_preflight_internal(path, (void*)dyld::mainExecutable()->machHeader());
2072 }
2073 void* dlsym_compat(void* handle, const char* symbolName)
2074 {
2075 return dlsym_internal(handle, symbolName, (void*)dyld::mainExecutable()->machHeader());
2076 }
2077
2078
2079
2080
2081 const struct dyld_all_image_infos* _dyld_get_all_image_infos()
2082 {
2083 return dyld::gProcessInfo;
2084 }
2085
2086
2087 #if SUPPORT_ZERO_COST_EXCEPTIONS
2088 static bool client_dyld_find_unwind_sections(void* addr, dyld_unwind_sections* info)
2089 {
2090 //if ( dyld::gLogAPIs )
2091 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
2092
2093 addr = stripPointer(addr);
2094
2095 #if SUPPORT_ACCELERATE_TABLES
2096 if ( dyld::findUnwindSections(addr, info) )
2097 return true;
2098 #endif
2099 ImageLoader* image = dyld::findImageContainingAddress(addr);
2100 if ( image != NULL ) {
2101 image->getUnwindInfo(info);
2102 return true;
2103 }
2104 return false;
2105 }
2106 #endif
2107
2108
2109 const char* dyld_image_path_containing_address(const void* address)
2110 {
2111 if ( dyld::gLogAPIs )
2112 dyld::log("%s(%p)\n", __func__, address);
2113
2114 address = (void*)stripPointer(address);
2115
2116 #if SUPPORT_ACCELERATE_TABLES
2117 const mach_header* mh;
2118 const char* path;
2119 if ( dyld::addressInCache(address, &mh, &path) )
2120 return path;
2121 #endif
2122
2123 ImageLoader* image = dyld::findImageContainingAddress(address);
2124 if ( image != NULL ) {
2125 return image->getRealPath();
2126 }
2127 return NULL;
2128 }
2129
2130
2131
2132 bool dyld_shared_cache_some_image_overridden()
2133 {
2134 return dyld::gSharedCacheOverridden;
2135 }
2136
2137
2138 void dyld_dynamic_interpose(const struct mach_header* mh, const struct dyld_interpose_tuple array[], size_t count)
2139 {
2140 if ( mh == NULL )
2141 return;
2142 if ( array == NULL )
2143 return;
2144 if ( count == 0 )
2145 return;
2146 ImageLoader* image = dyld::findImageByMachHeader(mh);
2147 if ( image == NULL )
2148 return;
2149
2150 // make the cache writable for this block
2151 DyldSharedCache::DataConstScopedWriter patcher(dyld::gLinkContext.dyldCache, mach_task_self(), (dyld::gLinkContext.verboseMapping ? &dyld::log : nullptr));
2152
2153 // make pass at bound references in this image and update them
2154 dyld::gLinkContext.dynamicInterposeArray = array;
2155 dyld::gLinkContext.dynamicInterposeCount = count;
2156 image->dynamicInterpose(dyld::gLinkContext);
2157 dyld::gLinkContext.dynamicInterposeArray = NULL;
2158 dyld::gLinkContext.dynamicInterposeCount = 0;
2159
2160 // leave interposing info so any future (lazy) binding will get it too
2161 image->addDynamicInterposingTuples(array, count);
2162
2163 sDynamicInterposing = true;
2164 }
2165
2166
2167 bool _dyld_is_memory_immutable(const void* addr, size_t length)
2168 {
2169 if ( dyld::gLogAPIs )
2170 dyld::log("%s(%p, %ld)\n", __func__, addr, length);
2171
2172 uintptr_t checkStart = (uintptr_t)addr;
2173 uintptr_t checkEnd = checkStart + length;
2174
2175 // quick check to see if in r/o region of shared cache. If so return true.
2176 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
2177 if ( cache != nullptr ) {
2178 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
2179 uintptr_t roStart = (uintptr_t)cache;
2180 uintptr_t roEnd = roStart + (uintptr_t)mappings[0].size;
2181 if ( (roStart < checkStart) && (checkEnd < roEnd) )
2182 return true;
2183 }
2184
2185 // Otherwise find if addr is in a dyld loaded image
2186 ImageLoader* image = dyld::findImageContainingAddress(addr);
2187 if ( image != NULL ) {
2188 // <rdar://problem/24091154> already checked for r/o portion of cache
2189 if ( image->inSharedCache() )
2190 return false;
2191 if ( !image->neverUnload() )
2192 return false;
2193 for (unsigned i=0, e=image->segmentCount(); i < e; ++i) {
2194 if ( (image->segActualLoadAddress(i) < checkStart) && (checkEnd < image->segActualEndAddress(i)) ) {
2195 return !image->segWriteable(i);
2196 }
2197 }
2198 }
2199 return false;
2200 }
2201
2202
2203
2204 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped,
2205 _dyld_objc_notify_init init,
2206 _dyld_objc_notify_unmapped unmapped)
2207 {
2208 dyld::registerObjCNotifiers(mapped, init, unmapped);
2209 }
2210
2211
2212 bool _dyld_get_shared_cache_uuid(uuid_t uuid)
2213 {
2214 return dyld::sharedCacheUUID(uuid);
2215 }
2216
2217 const void* _dyld_get_shared_cache_range(size_t* length)
2218 {
2219 const DyldSharedCache* cache = (DyldSharedCache*)dyld::imMemorySharedCacheHeader();
2220 if ( cache != nullptr ) {
2221 const dyld_cache_mapping_info* const mappings = (dyld_cache_mapping_info*)((char*)cache + cache->header.mappingOffset);
2222 const dyld_cache_mapping_info* lastMapping = &mappings[cache->header.mappingCount - 1];
2223 *length = (size_t)((lastMapping->address + lastMapping->size) - cache->unslidLoadAddress());
2224 return cache;
2225 }
2226 return nullptr;
2227 }
2228
2229 void _dyld_images_for_addresses(unsigned count, const void* addresses[], struct dyld_image_uuid_offset infos[])
2230 {
2231 for (unsigned i=0; i < count; ++i) {
2232 const void* addr = addresses[i];
2233 addr = stripPointer(addr);
2234 bzero(&infos[i], sizeof(dyld_image_uuid_offset));
2235 #if SUPPORT_ACCELERATE_TABLES
2236 const mach_header* mh;
2237 const char* path;
2238 if ( dyld::addressInCache(addr, &mh, &path) ) {
2239 infos[i].image = mh;
2240 infos[i].offsetInImage = (uintptr_t)addr - (uintptr_t)mh;
2241 ((dyld3::MachOFile*)mh)->getUuid(infos[i].uuid);
2242 continue;
2243 }
2244 #endif
2245 ImageLoader* image = dyld::findImageContainingAddress(addr);
2246 if ( image != nullptr ) {
2247 infos[i].image = image->machHeader();
2248 infos[i].offsetInImage = (uintptr_t)addr - (uintptr_t)(image->machHeader());
2249 image->getUUID(infos[i].uuid);
2250 }
2251 }
2252 }
2253
2254 void _dyld_register_for_image_loads(void (*func)(const mach_header* mh, const char* path, bool unloadable))
2255 {
2256 if ( dyld::gLogAPIs )
2257 dyld::log("%s(%p)\n", __func__, (void *)func);
2258 dyld::registerLoadCallback(func);
2259 }
2260
2261 void _dyld_register_for_bulk_image_loads(void (*func)(unsigned imageCount, const struct mach_header* mhs[], const char* paths[]))
2262 {
2263 if ( dyld::gLogAPIs )
2264 dyld::log("%s(%p)\n", __func__, (void *)func);
2265 dyld::registerBulkLoadCallback(func);
2266 }
2267
2268 void _dyld_register_driverkit_main(void (*mainFunc)())
2269 {
2270 dyld::setMainEntry(mainFunc);
2271 }
2272
2273