1 /* -*- mode: C++; c-basic-offset: 4; tab-width: 4 -*-
3 * Copyright (c) 2004-2009 Apple Inc. All rights reserved.
5 * @APPLE_LICENSE_HEADER_START@
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
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.
22 * @APPLE_LICENSE_HEADER_END@
26 // This file implements that API's in <mach-o/dyld.h>
30 #define __STDC_LIMIT_MACROS
34 #include <sys/param.h>
35 #include <sys/mount.h>
36 #include <Availability.h>
43 #include <mach/mach.h>
45 #include <sys/sysctl.h>
46 #include <mach/mach_traps.h> // for task_self_trap()
48 #include <mach-o/dyld_images.h>
49 #include <mach-o/dyld.h>
50 #include <mach-o/dyld_priv.h>
52 #include "ImageLoader.h"
53 #include "ImageLoaderMachO.h"
55 #include "dyldLibSystemInterface.h"
56 #include "DyldSharedCache.h"
57 #include "MachOFile.h"
59 #undef _POSIX_C_SOURCE
62 #if __has_feature(ptrauth_calls)
67 // relocation_info.r_length field has value 3 for 64-bit executables and value 2 for 32-bit executables
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
{};
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
{};
85 // this was in dyld_priv.h but it is no longer exported
87 const struct dyld_all_image_infos
* _dyld_get_all_image_infos();
90 // from dyldExceptions.c
91 extern "C" void __Unwind_SjLj_SetThreadKey(pthread_key_t key
);
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
);
99 extern "C" int _dyld_func_lookup(const char* name
, void** address
);
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
);
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
);
111 // deprecated APIs are still availble on Mac OS X, but not on iPhone OS
113 #define DEPRECATED_APIS_SUPPORTED 1
115 #define DEPRECATED_APIS_SUPPORTED 0
118 static bool sDynamicInterposing
= false;
120 #if DEPRECATED_APIS_SUPPORTED
121 static char sLastErrorFilePath
[1024];
122 static NSLinkEditErrors sLastErrorFileCode
;
123 static int sLastErrorNo
;
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__)
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
);
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
);
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
);
152 #if DEPRECATED_APIS_SUPPORTED
155 static void unimplemented()
157 dyld
::halt("unimplemented dyld function\n");
162 void* implementation
;
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
},
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
},
193 #if __i386__ || __x86_64__ || __arm__ || __arm64__
194 {"__dyld_fast_stub_entry", (void*)dyld
::fastBindLazySymbol
},
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
},
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
},
257 #pragma clang diagnostic pop
258 #endif //DEPRECATED_APIS_SUPPORTED
265 #if DEPRECATED_APIS_SUPPORTED
267 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
269 dyld
::log("dyld: %s() error\n", apiName
);
270 dyld
::halt(errorMsg
);
273 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
274 inline NSSymbol
SymbolToNSSymbol(const ImageLoader
::Symbol
* sym
)
276 return (NSSymbol
)sym
;
278 inline const ImageLoader
::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
280 return (const ImageLoader
::Symbol
*)sym
;
283 // dyld's abstract type NSModule is implemented as ImageLoader*
284 inline NSModule
ImageLoaderToNSModule(const ImageLoader
* image
)
286 return (NSModule
)image
;
288 inline ImageLoader
* NSModuleToImageLoader(NSModule module
)
290 ImageLoader
* image
= (ImageLoader
*)module
;
291 if ( dyld
::validImage(image
) )
296 // actual definition for opaque type
297 struct __NSObjectFileImage
300 const void* imageBaseAddress
; // not used with OFI created from files
301 size_t imageLength
; // not used with OFI created from files
303 typedef __NSObjectFileImage
* NSObjectFileImage
;
306 VECTOR_NEVER_DESTRUCTED(NSObjectFileImage
);
307 static std
::vector
<NSObjectFileImage
> sObjectFileImages
;
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
320 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
322 dyld
::setErrorMessage(message
);
323 strncpy(sLastErrorFilePath
, file
, 1024);
324 sLastErrorFilePath
[1023] = '\0';
325 sLastErrorFileCode
= code
;
326 sLastErrorNo
= errnum
;
329 #endif // DEPRECATED_APIS_SUPPORTED
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.
341 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
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);
350 strcpy(buf
, exePath
);
354 uint32_t _dyld_image_count(void)
356 if ( dyld
::gLogAPIs
)
357 dyld
::log("%s()\n", __func__
);
358 return allImagesCount();
361 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
363 if ( dyld
::gLogAPIs
)
364 dyld
::log("%s(%u)\n", __func__
, image_index
);
365 return allImagesIndexedMachHeader(image_index
);
368 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
370 if ( dyld
::gLogAPIs
)
371 dyld
::log("%s(%u)\n", __func__
, image_index
);
372 const struct mach_header
* mh
= allImagesIndexedMachHeader(image_index
);
374 return ImageLoaderMachO
::computeSlide(mh
);
379 intptr_t _dyld_get_image_slide(const struct mach_header
* mh
)
381 if ( dyld
::gLogAPIs
)
382 dyld
::log("%s(%p)\n", __func__
, mh
);
383 return ImageLoaderMachO
::computeSlide(mh
);
387 const char* _dyld_get_image_name(uint32_t image_index
)
389 if ( dyld
::gLogAPIs
)
390 dyld
::log("%s(%u)\n", __func__
, image_index
);
391 return allImagesIndexedPath(image_index
);
394 const struct mach_header
* _dyld_get_prog_image_header()
396 if ( dyld
::gLogAPIs
)
397 dyld
::log("%s()\n", __func__
);
399 return dyld
::mainExecutable()->machHeader();
402 static const void *stripPointer(const void *ptr
) {
403 #if __has_feature(ptrauth_calls)
404 return __builtin_ptrauth_strip(ptr
, ptrauth_key_asia
);
410 static void *stripPointer(void *ptr
) {
411 #if __has_feature(ptrauth_calls)
412 return __builtin_ptrauth_strip(ptr
, ptrauth_key_asia
);
418 const struct mach_header
* dyld_image_header_containing_address(const void* address
)
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
;
426 if ( dyld
::addressInCache(address
, &mh
, &path
) )
429 ImageLoader
* image
= dyld
::findImageContainingAddress(address
);
431 return image
->machHeader();
436 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
438 if ( dyld
::gLogAPIs
)
439 dyld
::log("%s(%p)\n", __func__
, (void *)func
);
440 dyld
::registerAddCallback(func
);
443 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
445 if ( dyld
::gLogAPIs
)
446 dyld
::log("%s(%p)\n", __func__
, (void *)func
);
447 dyld
::registerRemoveCallback(func
);
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()
455 if ( dyld
::gLogAPIs
)
456 dyld
::log("%s()\n", __func__
);
458 #if SUPPORT_OLD_CRT_INITIALIZATION
459 if ( dyld
::gRunInitializersOldWay
)
460 dyld
::initializeMainExecutable();
466 #if DEPRECATED_APIS_SUPPORTED
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
477 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
479 if ( dyld
::gLogAPIs
)
480 dyld
::log("__initialize_Cplusplus()\n");
482 // for now, do nothing...
486 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module
)
488 if ( dyld
::gLogAPIs
)
489 dyld
::log("%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module
);
491 const ImageLoader
::Symbol
* sym
;
492 dyld
::clearErrorMessage();
493 if ( dyld
::flatFindExportedSymbol(symbolName
, &sym
, (const ImageLoader
**)&image
) ) {
495 image
->bindAllLazyPointers(dyld
::gLinkContext
, true);
496 if ( address
!= NULL
)
497 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld
::gLinkContext
);
499 *module
= ImageLoaderToNSModule(image
);
501 catch (const char* msg
) {
502 dyldAPIhalt(__func__
, msg
);
506 // on failure to find symbol return NULLs
507 if ( address
!= NULL
)
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
)
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
);
526 *module
= ImageLoaderToNSModule(image
);
529 // on failure to find symbol return NULLs
530 if ( address
!= NULL
)
537 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module
)
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
);
549 *module
= ImageLoaderToNSModule(image
);
552 // on failure to find symbol return NULLs
553 if ( address
!= NULL
)
561 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
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
);
570 // return NULL on failure
574 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
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
);
582 // hint failed, do slow search of all images
583 found
= dyld
::flatFindExportedSymbol(symbolName
, &sym
, &image
);
586 return SymbolToNSSymbol(sym
);
588 // return NULL on failure and log
589 if ( dyld
::gLogAPIs
)
590 dyld
::log("%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
597 static __attribute__((noinline
))
598 const struct mach_header
* addImage(void* callerAddress
, const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
600 ImageLoader
* image
= NULL
;
601 std
::vector
<const char*> rpathsFromCallerImage
;
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
);
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
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();
636 catch (const char* msg
) {
637 dyld
::garbageCollectImages();
639 char pathMsg
[strlen(msg
)+strlen(path
)+4];
640 strcpy(pathMsg
, msg
);
641 strcat(pathMsg
, " ");
642 strcat(pathMsg
, path
);
643 dyldAPIhalt("NSAddImage", pathMsg
);
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
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
;
658 return image
->machHeader();
662 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
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
);
674 bool NSAddLibrary(const char* path
)
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
);
682 bool NSAddLibraryWithSearching(const char* path
)
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
);
692 //#define NSADDIMAGE_OPTION_NONE 0x0
693 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
694 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
696 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
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
)
709 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
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
;
719 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
720 image
->bindAllLazyPointers(dyld
::gLinkContext
, true);
722 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
723 image
->bindAllLazyPointers(dyld
::gLinkContext
, false);
726 catch (const char* msg
) {
727 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
728 dyldAPIhalt(__func__
, msg
);
731 symbol
= image
->findExportedSymbol(symbolToFind
, true, NULL
);
733 if ( dyld
::gLogAPIs
&& (symbol
== NULL
) )
734 dyld
::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
735 return SymbolToNSSymbol(symbol
);
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
)
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
);
750 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
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
);
758 // hint failed, do slow search of all images
759 found
= dyld
::flatFindExportedSymbol(symbolName
, &sym
, &image
);
761 if ( !found
&& dyld
::gLogAPIs
)
762 dyld
::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
766 const char* NSNameOfSymbol(NSSymbol symbol
)
768 if ( dyld
::gLogAPIs
)
769 dyld
::log("%s(%p)\n", __func__
, (void *)symbol
);
770 const char* result
= NULL
;
771 ImageLoader
* image
= dyld
::findImageContainingSymbol(symbol
);
773 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
777 void* NSAddressOfSymbol(NSSymbol symbol
)
779 if ( dyld
::gLogAPIs
)
780 dyld
::log("%s(%p)\n", __func__
, (void *)symbol
);
781 if ( symbol
== NULL
)
784 ImageLoader
* image
= dyld
::findImageContainingSymbol(symbol
);
786 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld
::gLinkContext
);
788 #if __has_feature(ptrauth_calls)
789 // Sign the pointer if it points to a function
791 const ImageLoader
* symbolImage
= image
;
792 if (!symbolImage
->containsAddress(result
)) {
793 symbolImage
= dyld
::findImageContainingAddress(result
);
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);
803 NSModule
NSModuleForSymbol(NSSymbol symbol
)
805 if ( dyld
::gLogAPIs
)
806 dyld
::log("%s(%p)\n", __func__
, (void *)symbol
);
807 NSModule result
= NULL
;
808 ImageLoader
* image
= dyld
::findImageContainingSymbol(symbol
);
810 result
= ImageLoaderToNSModule(image
);
817 bool _dyld_all_twolevel_modules_prebound(void)
819 if ( dyld
::gLogAPIs
)
820 dyld
::log("%s()\n", __func__
);
824 bool _dyld_bind_fully_image_containing_address(const void* address
)
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
) {
833 image
->bindAllLazyPointers(dyld
::gLinkContext
, true);
836 catch (const char* msg
) {
837 dyldAPIhalt(__func__
, msg
);
843 bool _dyld_image_containing_address(const void* address
)
845 if ( dyld
::gLogAPIs
)
846 dyld
::log("%s(%p)\n", __func__
, address
);
847 ImageLoader
*imageLoader
= dyld
::findImageContainingAddress(address
);
848 return (NULL
!= imageLoader
);
851 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
853 NSObjectFileImage result
= new __NSObjectFileImage();
854 result
->image
= image
;
855 result
->imageBaseAddress
= address
;
856 result
->imageLength
= len
;
857 sObjectFileImages
.push_back(result
);
861 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
863 if ( dyld
::gLogAPIs
)
864 dyld
::log("%s(\"%s\", ...)\n", __func__
, pathName
);
866 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
867 ImageLoader
* callerImage
= dyld
::findImageContainingAddress(callerAddress
);
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
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
;
890 *objectFileImage
= createObjectImageFile(image
);
891 return NSObjectFileImageSuccess
;
894 catch (const char* msg
) {
895 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
896 dyld
::garbageCollectImages();
898 return NSObjectFileImageInappropriateFile
;
900 return NSObjectFileImageFailure
;
904 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
906 if ( dyld
::gLogAPIs
)
907 dyld
::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
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
;
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
;
922 catch (const char* msg
) {
924 dyld
::garbageCollectImages();
925 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
927 return NSObjectFileImageFailure
;
930 static bool validOFI(NSObjectFileImage objectFileImage
)
932 const size_t ofiCount
= sObjectFileImages
.size();
933 for (size_t i
=0; i
< ofiCount
; ++i
) {
934 if ( sObjectFileImages
[i
] == objectFileImage
)
940 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
942 if ( dyld
::gLogAPIs
)
943 dyld
::log("%s(%p)\n", __func__
, objectFileImage
);
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
;
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
);
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
) {
969 if ( (dyld
::gLibSystemHelpers
!= NULL
) && (dyld
::gLibSystemHelpers
->version
>= 6) ) {
970 size_t sz
= (*dyld
::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
972 (*dyld
::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
977 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
981 delete objectFileImage
;
988 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
990 if ( dyld
::gLogAPIs
)
991 dyld
::log("%s(%p)\n", __func__
, objectFileImage
);
992 return objectFileImage
->image
->getExportedSymbolCount();
995 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
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
);
1003 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
1005 if ( dyld
::gLogAPIs
)
1006 dyld
::log("%s(%p)\n", __func__
, objectFileImage
);
1007 return objectFileImage
->image
->getImportedSymbolCount();
1010 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
1011 bool* tentative_definition
)
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;
1021 *tentative_definition
= false;
1023 return objectFileImage
->image
->getImportedSymbolName(sym
);
1026 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
1027 const char* segmentName
, const char* sectionName
, unsigned long* size
)
1029 if ( dyld
::gLogAPIs
)
1030 dyld
::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
1034 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
1044 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
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
);
1054 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
1056 if ( dyld
::gLogAPIs
)
1057 dyld
::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
1059 dyld
::clearErrorMessage();
1061 if ( (options
& NSLINKMODULE_OPTION_CAN_UNLOAD
) != 0 )
1062 objectFileImage
->image
->setCanUnload();
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
);
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
);
1082 // support private bundles
1083 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1084 objectFileImage
->image
->setHideExports();
1086 // set up linking options
1087 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1089 // load libraries, rebase, bind, to make this image usable
1090 dyld
::link(objectFileImage
->image
, forceLazysBound
, false, ImageLoader
::RPathChain(NULL
,NULL
), UINT32_MAX
);
1092 // bump reference count to keep this bundle from being garbage collected
1093 objectFileImage
->image
->incrementDlopenReferenceCount();
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
);
1099 return ImageLoaderToNSModule(objectFileImage
->image
);
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
;
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
)
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();
1124 const char* imageName
= moduleName
;
1125 image
= dyld
::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1127 if ( image
!= NULL
) {
1128 // support private bundles
1129 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1130 image
->setHideExports();
1132 // set up linking options
1133 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1135 // load libraries, rebase, bind, to make this image usable
1136 dyld
::link(image
, forceLazysBound
, false, ImageLoader
::RPathChain(NULL
,NULL
), UINT32_MAX
);
1138 // run initializers unless magic flag says not to
1139 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1140 dyld
::runInitializers(image
);
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
);
1156 return ImageLoaderToNSModule(image
);
1160 NSSymbol
NSLookupSymbolInModule(NSModule module
, const char* symbolName
)
1162 if ( dyld
::gLogAPIs
)
1163 dyld
::log("%s(%p, \"%s\")\n", __func__
, (void *)module
, symbolName
);
1164 ImageLoader
* image
= NSModuleToImageLoader(module
);
1165 if ( image
== NULL
)
1167 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1170 const char* NSNameOfModule(NSModule module
)
1172 if ( dyld
::gLogAPIs
)
1173 dyld
::log("%s(%p)\n", __func__
, module
);
1174 ImageLoader
* image
= NSModuleToImageLoader(module
);
1175 if ( image
== NULL
)
1177 return image
->getPath();
1180 const char* NSLibraryNameForModule(NSModule module
)
1182 if ( dyld
::gLogAPIs
)
1183 dyld
::log("%s(%p)\n", __func__
, module
);
1184 ImageLoader
* image
= NSModuleToImageLoader(module
);
1185 if ( image
== NULL
)
1187 return image
->getPath();
1190 bool NSUnLinkModule(NSModule module
, uint32_t options
)
1192 if ( dyld
::gLogAPIs
)
1193 dyld
::log("%s(%p, 0x%08X)\n", __func__
, module
, options
);
1194 if ( module
== NULL
)
1196 ImageLoader
* image
= NSModuleToImageLoader(module
);
1197 if ( image
== NULL
)
1199 dyld
::runImageStaticTerminators(image
);
1200 if ( (dyld
::gLibSystemHelpers
!= NULL
) && (dyld
::gLibSystemHelpers
->version
>= 13) ) {
1201 __cxa_range_t ranges
[image
->segmentCount()];
1203 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
1204 if ( !image
->segExecutable(j
) )
1206 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
1207 ranges
[rangeCount
].length
= image
->segSize(j
);
1210 (*dyld
::gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
1212 dyld
::removeImage(image
);
1214 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1215 image
->setLeaveMapped();
1217 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
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();
1223 for (size_t i
=0; i
< ofiCount
; ++i
) {
1224 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1225 if ( ofi
->image
== image
)
1229 ImageLoader
::deleteImage(image
);
1234 // internal name and parameters do not match public name and parameters...
1235 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1237 if ( dyld
::gLogAPIs
)
1238 dyld
::log("NSLinkEditErrorHandlers()\n");
1240 dyld
::registerUndefinedHandler((dyld
::UndefinedHandler
)undefined
);
1241 // no support for multiple or linkedit handlers
1247 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1250 *c
= sLastErrorFileCode
;
1251 *errorNumber
= sLastErrorNo
;
1252 *fileName
= sLastErrorFilePath
;
1253 *errorString
= dyld
::getErrorMessage();
1258 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader
::BindingOptions bindingOptions
)
1260 if ( dyld
::gLogAPIs
)
1261 dyld
::log("%s()\n", __func__
);
1262 dyld
::gLinkContext
.bindingHandler
= bindingHandler
;
1263 dyld
::gLinkContext
.bindingOptions
= bindingOptions
;
1266 #endif //DEPRECATED_APIS_SUPPORTED
1269 // Call by fork() in libSystem after the kernel trap is done on the child side
1270 void _dyld_fork_child()
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.
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().
1281 extern mach_port_t mach_task_self_
;
1282 mach_task_self_
= task_self_trap();
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;
1293 #if DEPRECATED_APIS_SUPPORTED
1294 // returns true if prebinding was used in main executable
1295 bool _dyld_launched_prebound()
1297 if ( dyld
::gLogAPIs
)
1298 dyld
::log("%s()\n", __func__
);
1300 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1301 return dyld
::mainExecutablePrebound();
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.
1312 static bool NSMakePrivateModulePublic(NSModule module
)
1314 ImageLoader
* image
= NSModuleToImageLoader(module
);
1315 if ( image
!= NULL
) {
1316 if ( image
->hasHiddenExports() ) {
1317 image
->setHideExports(false);
1324 #endif // DEPRECATED_APIS_SUPPORTED
1326 int _dyld_func_lookup(const char* name
, void** address
)
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
;
1341 static void registerThreadHelpers(const dyld
::LibSystemHelpers
* helpers
)
1343 dyld
::gLibSystemHelpers
= helpers
;
1345 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1346 if ( helpers
->version
>= 5 ) {
1347 // create key use by dyld exception handling
1349 int result
= helpers
->pthread_key_create(&key
, NULL
);
1351 __Unwind_SjLj_SetThreadKey(key
);
1357 static void dlerrorClear()
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
)() )
1367 // first char of buffer is flag whether string (starting at second char) is valid
1368 char* buffer
= (*dyld
::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1374 static void dlerrorSet(const char* msg
)
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);
1380 strcpy(&buffer
[1], msg
);
1385 bool dlopen_preflight_internal(const char* path
, void* callerAddress
)
1387 if ( dyld
::gLogAPIs
)
1388 dyld
::log("%s(%s)\n", __func__
, path
);
1392 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
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
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
;
1417 #if SUPPORT_ACCELERATE_TABLES
1418 if ( dyld
::isPathInCache(path
) )
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
) )
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
) )
1438 bool result
= false;
1439 std
::vector
<const char*> rpathsFromCallerImage
;
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
);
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
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()
1471 catch (const char* msg
) {
1472 const char* str
= dyld
::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1475 free((void*)msg
); // our free() will do nothing if msg is a string literal
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
;
1482 CRSetCrashLogMessage(NULL
);
1486 #if SUPPORT_ACCELERATE_TABLES
1487 bool static callerIsNonOSApp(void* callerAddress
, const char** shortName
)
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
) )
1497 ImageLoader
* callerImage
= dyld
::findImageContainingAddress(callerAddress
);
1498 if ( callerImage
== NULL
)
1501 *shortName
= callerImage
->getShortName();
1502 return ( strncmp(callerImage
->getPath(), "/var/containers/", 16) == 0 );
1506 void* dlopen_internal(const char* path
, int mode
, void* callerAddress
)
1508 if ( dyld
::gLogAPIs
)
1509 dyld
::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ?
"NULL" : path
), mode
);
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
);
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
;
1528 return RTLD_DEFAULT
;
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()");
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
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
;
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
);
1572 ImageLoader
* image
= NULL
;
1573 std
::vector
<const char*> rpathsFromCallerImage
;
1574 ImageLoader
::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
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
);
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
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
);
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
) {
1623 if ( ((mode
& RTLD_LOCAL
) == 0) && image
->hasHiddenExports() )
1624 image
->setHideExports(false);
1627 // only hide exports if image is not already in use
1628 if ( (mode
& RTLD_LOCAL
) != 0 )
1629 image
->setHideExports(true);
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();
1641 // release global dyld lock early, this enables initializers to do threaded operations
1643 CRSetCrashLogMessage(NULL
);
1644 dyld
::gLibSystemHelpers
->releaseGlobalDyldLock();
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 ) {
1655 dyld
::runInitializers(image
);
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);
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();
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
);
1679 free((void*)msg
); // our free() will do nothing if msg is a string literal
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
;
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");
1694 CRSetCrashLogMessage(NULL
);
1695 dyld
::gLibSystemHelpers
->releaseGlobalDyldLock();
1697 if ( dyld
::gLogAPIs
&& (result
!= NULL
) )
1698 dyld
::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1702 int dlclose(void* handle
)
1704 if ( dyld
::gLogAPIs
)
1705 dyld
::log("%s(%p)\n", __func__
, handle
);
1707 // silently accept magic handles for main executable
1708 if ( handle
== RTLD_MAIN_ONLY
)
1710 if ( handle
== RTLD_DEFAULT
)
1713 #if SUPPORT_ACCELERATE_TABLES
1714 if ( dyld
::isCacheHandle(handle
) ) {
1720 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1721 if ( dyld
::validImage(image
) ) {
1723 // decrement use count
1724 if ( image
->decrementDlopenReferenceCount() ) {
1725 dlerrorSet("dlclose() called too many times");
1728 // remove image if reference count went to zero
1729 if ( image
->dlopenCount() == 0 )
1730 dyld
::garbageCollectImages();
1734 dlerrorSet("invalid handle passed to dlclose()");
1741 int dladdr(const void* address
, Dl_info
* info
)
1743 if ( dyld
::gLogAPIs
)
1744 dyld
::log("%s(%p, %p)\n", __func__
, address
, info
);
1746 // <rdar://problem/42171466> calling dladdr(xx,NULL) crashes
1748 return 0; // failure
1750 address
= stripPointer(address
);
1752 CRSetCrashLogMessage("dyld: in dladdr()");
1753 #if SUPPORT_ACCELERATE_TABLES
1754 if ( dyld
::dladdrFromCache(address
, info
) ) {
1755 CRSetCrashLogMessage(NULL
);
1756 return 1; // success
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
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
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
1787 info
->dli_sname
= NULL
;
1788 info
->dli_saddr
= NULL
;
1789 CRSetCrashLogMessage(NULL
);
1790 return 1; // success
1792 CRSetCrashLogMessage(NULL
);
1793 return 0; // failure
1799 if ( dyld
::gLogAPIs
)
1800 dyld
::log("%s()\n", __func__
);
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
)() )
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
1819 void* dlsym_internal(void* handle
, const char* symbolName
, void* callerAddress
)
1821 if ( dyld
::gLogAPIs
)
1822 dyld
::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
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
);
1833 CRSetCrashLogMessage("dyld: in dlsym()");
1836 const ImageLoader
* image
;
1837 const ImageLoader
::Symbol
* sym
;
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
);
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
);
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);
1865 if ( dyld
::gLogAPIs
)
1866 dyld
::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__
, symbolName
, result
);
1869 const char* str
= dyld
::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1872 CRSetCrashLogMessage(NULL
);
1873 if ( dyld
::gLogAPIs
)
1874 dyld
::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__
, symbolName
);
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
);
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);
1899 if ( dyld
::gLogAPIs
)
1900 dyld
::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__
, symbolName
, result
);
1903 const char* str
= dyld
::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1906 CRSetCrashLogMessage(NULL
);
1907 if ( dyld
::gLogAPIs
)
1908 dyld
::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__
, symbolName
);
1912 // magic "search what I would see" handle
1913 else if ( handle
== RTLD_NEXT
) {
1914 #if SUPPORT_ACCELERATE_TABLES
1915 const mach_header
* mh
;
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
);
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
);
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);
1945 if ( dyld
::gLogAPIs
)
1946 dyld
::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1949 const char* str
= dyld
::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1952 CRSetCrashLogMessage(NULL
);
1953 if ( dyld
::gLogAPIs
)
1954 dyld
::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__
, symbolName
);
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
;
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
);
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
);
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);
1990 if ( dyld
::gLogAPIs
)
1991 dyld
::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1994 const char* str
= dyld
::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1997 CRSetCrashLogMessage(NULL
);
1998 if ( dyld
::gLogAPIs
)
1999 dyld
::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__
, symbolName
);
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
);
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
2017 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld
::gLinkContext
, &image
); // search image and what it links against
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
);
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
);
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);
2041 if ( dyld
::gLogAPIs
)
2042 dyld
::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
2045 const char* str
= dyld
::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
2050 dlerrorSet("invalid handle passed to dlsym()");
2052 CRSetCrashLogMessage(NULL
);
2053 if ( dyld
::gLogAPIs
)
2054 dyld
::log(" %s(%p, %s) ==> NULL\n", __func__
, handle
, symbolName
);
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));
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
)
2067 return dlopen_internal(path
, mode
, (void*)dyld
::mainExecutable()->machHeader());
2069 bool dlopen_preflight_compat(const char* path
)
2071 return dlopen_preflight_internal(path
, (void*)dyld
::mainExecutable()->machHeader());
2073 void* dlsym_compat(void* handle
, const char* symbolName
)
2075 return dlsym_internal(handle
, symbolName
, (void*)dyld
::mainExecutable()->machHeader());
2081 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
2083 return dyld
::gProcessInfo
;
2087 #if SUPPORT_ZERO_COST_EXCEPTIONS
2088 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
2090 //if ( dyld::gLogAPIs )
2091 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
2093 addr
= stripPointer(addr
);
2095 #if SUPPORT_ACCELERATE_TABLES
2096 if ( dyld
::findUnwindSections(addr
, info
) )
2099 ImageLoader
* image
= dyld
::findImageContainingAddress(addr
);
2100 if ( image
!= NULL
) {
2101 image
->getUnwindInfo(info
);
2109 const char* dyld_image_path_containing_address(const void* address
)
2111 if ( dyld
::gLogAPIs
)
2112 dyld
::log("%s(%p)\n", __func__
, address
);
2114 address
= (void*)stripPointer(address
);
2116 #if SUPPORT_ACCELERATE_TABLES
2117 const mach_header
* mh
;
2119 if ( dyld
::addressInCache(address
, &mh
, &path
) )
2123 ImageLoader
* image
= dyld
::findImageContainingAddress(address
);
2124 if ( image
!= NULL
) {
2125 return image
->getRealPath();
2132 bool dyld_shared_cache_some_image_overridden()
2134 return dyld
::gSharedCacheOverridden
;
2138 void dyld_dynamic_interpose(const struct mach_header
* mh
, const struct dyld_interpose_tuple array
[], size_t count
)
2142 if ( array
== NULL
)
2146 ImageLoader
* image
= dyld
::findImageByMachHeader(mh
);
2147 if ( image
== NULL
)
2150 // make the cache writable for this block
2151 DyldSharedCache
::DataConstScopedWriter
patcher(dyld
::gLinkContext
.dyldCache
, mach_task_self(), (dyld
::gLinkContext
.verboseMapping ?
&dyld
::log
: nullptr));
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;
2160 // leave interposing info so any future (lazy) binding will get it too
2161 image
->addDynamicInterposingTuples(array
, count
);
2163 sDynamicInterposing
= true;
2167 bool _dyld_is_memory_immutable(const void* addr
, size_t length
)
2169 if ( dyld
::gLogAPIs
)
2170 dyld
::log("%s(%p, %ld)\n", __func__
, addr
, length
);
2172 uintptr_t checkStart
= (uintptr_t)addr
;
2173 uintptr_t checkEnd
= checkStart
+ length
;
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
) )
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() )
2191 if ( !image
->neverUnload() )
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
);
2204 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped
,
2205 _dyld_objc_notify_init init
,
2206 _dyld_objc_notify_unmapped unmapped
)
2208 dyld
::registerObjCNotifiers(mapped
, init
, unmapped
);
2212 bool _dyld_get_shared_cache_uuid(uuid_t uuid
)
2214 return dyld
::sharedCacheUUID(uuid
);
2217 const void* _dyld_get_shared_cache_range(size_t* length
)
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());
2229 void _dyld_images_for_addresses(unsigned count
, const void* addresses
[], struct dyld_image_uuid_offset infos
[])
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
;
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
);
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
);
2254 void _dyld_register_for_image_loads(void (*func
)(const mach_header
* mh
, const char* path
, bool unloadable
))
2256 if ( dyld
::gLogAPIs
)
2257 dyld
::log("%s(%p)\n", __func__
, (void *)func
);
2258 dyld
::registerLoadCallback(func
);
2261 void _dyld_register_for_bulk_image_loads(void (*func
)(unsigned imageCount
, const struct mach_header
* mhs
[], const char* paths
[]))
2263 if ( dyld
::gLogAPIs
)
2264 dyld
::log("%s(%p)\n", __func__
, (void *)func
);
2265 dyld
::registerBulkLoadCallback(func
);
2268 void _dyld_register_driverkit_main(void (*mainFunc
)())
2270 dyld
::setMainEntry(mainFunc
);