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
112 #if __IPHONE_OS_VERSION_MIN_REQUIRED
113 #define DEPRECATED_APIS_SUPPORTED 0
115 #define DEPRECATED_APIS_SUPPORTED 1
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__NSGetExecutablePath", (void*)_NSGetExecutablePath
},
185 {"__dyld_register_thread_helpers", (void*)registerThreadHelpers
},
186 {"__dyld_fork_child", (void*)_dyld_fork_child
},
187 {"__dyld_make_delayed_module_initializer_calls", (void*)_dyld_make_delayed_module_initializer_calls
},
188 {"__dyld_get_all_image_infos", (void*)_dyld_get_all_image_infos
},
189 #if SUPPORT_ZERO_COST_EXCEPTIONS
190 {"__dyld_find_unwind_sections", (void*)client_dyld_find_unwind_sections
},
192 #if __i386__ || __x86_64__ || __arm__ || __arm64__
193 {"__dyld_fast_stub_entry", (void*)dyld::fastBindLazySymbol
},
195 {"__dyld_image_path_containing_address", (void*)dyld_image_path_containing_address
},
196 {"__dyld_shared_cache_some_image_overridden", (void*)dyld_shared_cache_some_image_overridden
},
197 {"__dyld_process_is_restricted", (void*)dyld::processIsRestricted
},
198 {"__dyld_dynamic_interpose", (void*)dyld_dynamic_interpose
},
199 {"__dyld_shared_cache_file_path", (void*)dyld::getStandardSharedCacheFilePath
},
200 {"__dyld_has_inserted_or_interposing_libraries", (void*)dyld::hasInsertedOrInterposingLibraries
},
201 {"__dyld_get_image_header_containing_address", (void*)dyld_image_header_containing_address
},
202 {"__dyld_is_memory_immutable", (void*)_dyld_is_memory_immutable
},
203 {"__dyld_objc_notify_register", (void*)_dyld_objc_notify_register
},
204 {"__dyld_get_shared_cache_uuid", (void*)_dyld_get_shared_cache_uuid
},
205 {"__dyld_get_shared_cache_range", (void*)_dyld_get_shared_cache_range
},
206 {"__dyld_images_for_addresses", (void*)_dyld_images_for_addresses
},
207 {"__dyld_register_for_image_loads", (void*)_dyld_register_for_image_loads
},
208 {"__dyld_register_for_bulk_image_loads", (void*)_dyld_register_for_bulk_image_loads
},
209 {"__dyld_register_driverkit_main", (void*)_dyld_register_driverkit_main
},
212 #if DEPRECATED_APIS_SUPPORTED
213 #pragma clang diagnostic push
214 #pragma clang diagnostic ignored "-Wdeprecated-declarations"
215 {"__dyld_lookup_and_bind", (void*)client_dyld_lookup_and_bind
},
216 {"__dyld_lookup_and_bind_with_hint", (void*)_dyld_lookup_and_bind_with_hint
},
217 {"__dyld_lookup_and_bind_fully", (void*)_dyld_lookup_and_bind_fully
},
218 {"__dyld_install_handlers", (void*)_dyld_install_handlers
},
219 {"__dyld_link_edit_error", (void*)NSLinkEditError
},
220 {"__dyld_unlink_module", (void*)NSUnLinkModule
},
221 {"__dyld_bind_fully_image_containing_address", (void*)_dyld_bind_fully_image_containing_address
},
222 {"__dyld_image_containing_address", (void*)_dyld_image_containing_address
},
223 {"__dyld_register_binding_handler", (void*)_dyld_register_binding_handler
},
224 {"__dyld_NSNameOfSymbol", (void*)NSNameOfSymbol
},
225 {"__dyld_NSAddressOfSymbol", (void*)NSAddressOfSymbol
},
226 {"__dyld_NSModuleForSymbol", (void*)NSModuleForSymbol
},
227 {"__dyld_NSLookupAndBindSymbol", (void*)NSLookupAndBindSymbol
},
228 {"__dyld_NSLookupAndBindSymbolWithHint", (void*)NSLookupAndBindSymbolWithHint
},
229 {"__dyld_NSLookupSymbolInModule", (void*)NSLookupSymbolInModule
},
230 {"__dyld_NSLookupSymbolInImage", (void*)NSLookupSymbolInImage
},
231 {"__dyld_NSMakePrivateModulePublic", (void*)NSMakePrivateModulePublic
},
232 {"__dyld_NSIsSymbolNameDefined", (void*)client_NSIsSymbolNameDefined
},
233 {"__dyld_NSIsSymbolNameDefinedWithHint", (void*)NSIsSymbolNameDefinedWithHint
},
234 {"__dyld_NSIsSymbolNameDefinedInImage", (void*)NSIsSymbolNameDefinedInImage
},
235 {"__dyld_NSNameOfModule", (void*)NSNameOfModule
},
236 {"__dyld_NSLibraryNameForModule", (void*)NSLibraryNameForModule
},
237 {"__dyld_NSAddLibrary", (void*)NSAddLibrary
},
238 {"__dyld_NSAddLibraryWithSearching", (void*)NSAddLibraryWithSearching
},
239 {"__dyld_NSAddImage", (void*)NSAddImage
},
240 {"__dyld_launched_prebound", (void*)_dyld_launched_prebound
},
241 {"__dyld_all_twolevel_modules_prebound", (void*)_dyld_all_twolevel_modules_prebound
},
242 {"__dyld_call_module_initializers_for_dylib", (void*)_dyld_call_module_initializers_for_dylib
},
243 {"__dyld_NSCreateObjectFileImageFromFile", (void*)NSCreateObjectFileImageFromFile
},
244 {"__dyld_NSCreateObjectFileImageFromMemory", (void*)NSCreateObjectFileImageFromMemory
},
245 {"__dyld_NSDestroyObjectFileImage", (void*)NSDestroyObjectFileImage
},
246 {"__dyld_NSLinkModule", (void*)NSLinkModule
},
247 {"__dyld_NSSymbolDefinitionCountInObjectFileImage", (void*)NSSymbolDefinitionCountInObjectFileImage
},
248 {"__dyld_NSSymbolDefinitionNameInObjectFileImage", (void*)NSSymbolDefinitionNameInObjectFileImage
},
249 {"__dyld_NSIsSymbolDefinedInObjectFileImage", (void*)NSIsSymbolDefinedInObjectFileImage
},
250 {"__dyld_NSSymbolReferenceNameInObjectFileImage", (void*)NSSymbolReferenceNameInObjectFileImage
},
251 {"__dyld_NSSymbolReferenceCountInObjectFileImage", (void*)NSSymbolReferenceCountInObjectFileImage
},
252 {"__dyld_NSGetSectionDataInObjectFileImage", (void*)NSGetSectionDataInObjectFileImage
},
253 #if OLD_LIBSYSTEM_SUPPORT
254 {"__dyld_link_module", (void*)_dyld_link_module
},
256 #pragma clang diagnostic pop
257 #endif //DEPRECATED_APIS_SUPPORTED
264 #if DEPRECATED_APIS_SUPPORTED
266 static void dyldAPIhalt(const char* apiName
, const char* errorMsg
)
268 dyld::log("dyld: %s() error\n", apiName
);
269 dyld::halt(errorMsg
);
272 // dyld's abstract type NSSymbol is implemented as const ImageLoader::Symbol*
273 inline NSSymbol
SymbolToNSSymbol(const ImageLoader::Symbol
* sym
)
275 return (NSSymbol
)sym
;
277 inline const ImageLoader::Symbol
* NSSymbolToSymbol(NSSymbol sym
)
279 return (const ImageLoader::Symbol
*)sym
;
282 // dyld's abstract type NSModule is implemented as ImageLoader*
283 inline NSModule
ImageLoaderToNSModule(const ImageLoader
* image
)
285 return (NSModule
)image
;
287 inline ImageLoader
* NSModuleToImageLoader(NSModule
module)
289 ImageLoader
* image
= (ImageLoader
*)module;
290 if ( dyld::validImage(image
) )
295 // actual definition for opaque type
296 struct __NSObjectFileImage
299 const void* imageBaseAddress
; // not used with OFI created from files
300 size_t imageLength
; // not used with OFI created from files
302 typedef __NSObjectFileImage
* NSObjectFileImage
;
305 VECTOR_NEVER_DESTRUCTED(NSObjectFileImage
);
306 static std::vector
<NSObjectFileImage
> sObjectFileImages
;
311 // __NSObjectFileImage are deleted in NSDestroyObjectFileImage()
312 // The contained image is delete in one of two places:
313 // NSUnLinkModule deletes the image if there is no __NSObjectFileImage with a reference to it
314 // NSDestroyObjectFileImage deletes the image if image is not in list of valid images
319 static void setLastError(NSLinkEditErrors code
, int errnum
, const char* file
, const char* message
)
321 dyld::setErrorMessage(message
);
322 strncpy(sLastErrorFilePath
, file
, 1024);
323 sLastErrorFilePath
[1023] = '\0';
324 sLastErrorFileCode
= code
;
325 sLastErrorNo
= errnum
;
328 #endif // DEPRECATED_APIS_SUPPORTED
331 *_dyld_NSGetExecutablePath is the dyld side of _NSGetExecutablePath which
332 * copies the path of the executable into the buffer and returns 0 if the path
333 * was successfully copied in the provided buffer. If the buffer is not large
334 * enough, -1 is returned and the expected buffer size is copied in *bufsize.
335 * Note that _NSGetExecutablePath will return "a path" to the executable not a
336 * "real path" to the executable. That is the path may be a symbolic link and
337 * not the real file. And with deep directories the total bufsize needed could
338 * be more than MAXPATHLEN.
340 int _NSGetExecutablePath(char* buf
, uint32_t *bufsize
)
342 if ( dyld::gLogAPIs
)
343 dyld::log("%s(...)\n", __func__
);
344 const char* exePath
= dyld::getExecutablePath();
345 if(*bufsize
< strlen(exePath
) + 1){
346 *bufsize
= (uint32_t)(strlen(exePath
) + 1);
349 strcpy(buf
, exePath
);
353 uint32_t _dyld_image_count(void)
355 if ( dyld::gLogAPIs
)
356 dyld::log("%s()\n", __func__
);
357 return allImagesCount();
360 const struct mach_header
* _dyld_get_image_header(uint32_t image_index
)
362 if ( dyld::gLogAPIs
)
363 dyld::log("%s(%u)\n", __func__
, image_index
);
364 return allImagesIndexedMachHeader(image_index
);
367 intptr_t _dyld_get_image_vmaddr_slide(uint32_t image_index
)
369 if ( dyld::gLogAPIs
)
370 dyld::log("%s(%u)\n", __func__
, image_index
);
371 const struct mach_header
* mh
= allImagesIndexedMachHeader(image_index
);
373 return ImageLoaderMachO::computeSlide(mh
);
378 intptr_t _dyld_get_image_slide(const struct mach_header
* mh
)
380 if ( dyld::gLogAPIs
)
381 dyld::log("%s(%p)\n", __func__
, mh
);
382 return ImageLoaderMachO::computeSlide(mh
);
386 const char* _dyld_get_image_name(uint32_t image_index
)
388 if ( dyld::gLogAPIs
)
389 dyld::log("%s(%u)\n", __func__
, image_index
);
390 return allImagesIndexedPath(image_index
);
393 static const void *stripPointer(const void *ptr
) {
394 #if __has_feature(ptrauth_calls)
395 return __builtin_ptrauth_strip(ptr
, ptrauth_key_asia
);
401 static void *stripPointer(void *ptr
) {
402 #if __has_feature(ptrauth_calls)
403 return __builtin_ptrauth_strip(ptr
, ptrauth_key_asia
);
409 const struct mach_header
* dyld_image_header_containing_address(const void* address
)
411 if ( dyld::gLogAPIs
)
412 dyld::log("%s(%p)\n", __func__
, address
);
413 address
= stripPointer(address
);
414 #if SUPPORT_ACCELERATE_TABLES
415 const mach_header
* mh
;
417 if ( dyld::addressInCache(address
, &mh
, &path
) )
420 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
422 return image
->machHeader();
427 void _dyld_register_func_for_add_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
429 if ( dyld::gLogAPIs
)
430 dyld::log("%s(%p)\n", __func__
, (void *)func
);
431 dyld::registerAddCallback(func
);
434 void _dyld_register_func_for_remove_image(void (*func
)(const struct mach_header
*mh
, intptr_t vmaddr_slide
))
436 if ( dyld::gLogAPIs
)
437 dyld::log("%s(%p)\n", __func__
, (void *)func
);
438 dyld::registerRemoveCallback(func
);
443 // called by crt before main() by programs linked with 10.4 or earlier crt1.o
444 static void _dyld_make_delayed_module_initializer_calls()
446 if ( dyld::gLogAPIs
)
447 dyld::log("%s()\n", __func__
);
449 #if SUPPORT_OLD_CRT_INITIALIZATION
450 if ( dyld::gRunInitializersOldWay
)
451 dyld::initializeMainExecutable();
457 #if DEPRECATED_APIS_SUPPORTED
460 // _dyld_call_module_initializers_for_dylib() is the dyld side of
461 // __initialize_Cplusplus() which is in dylib1.o.
462 // It is intended to only be called inside -init rouintes.
463 // -init routines are called before module initializers (what C++
464 // initializers use). Calling __initialize_Cplusplus() in a -init
465 // routine causes the module initializers for an image to be called
466 // which then allows C++ to be used inside a -init routine
468 static void _dyld_call_module_initializers_for_dylib(const struct mach_header
* mh_dylib_header
)
470 if ( dyld::gLogAPIs
)
471 dyld::log("__initialize_Cplusplus()\n");
473 // for now, do nothing...
477 void _dyld_lookup_and_bind_fully(const char* symbolName
, void** address
, NSModule
* module)
479 if ( dyld::gLogAPIs
)
480 dyld::log("%s(\"%s\", %p, %p)\n", __func__
, symbolName
, address
, module);
482 const ImageLoader::Symbol
* sym
;
483 dyld::clearErrorMessage();
484 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, (const ImageLoader
**)&image
) ) {
486 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
487 if ( address
!= NULL
)
488 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
490 *module = ImageLoaderToNSModule(image
);
492 catch (const char* msg
) {
493 dyldAPIhalt(__func__
, msg
);
497 // on failure to find symbol return NULLs
498 if ( address
!= NULL
)
505 // Note: This cannot have public name because dyld is built with a static copy of libc.a
506 // which calls dyld_lookup_and_bind() and expects to find dyld's symbols not host process
507 static void client_dyld_lookup_and_bind(const char* symbolName
, void** address
, NSModule
* module)
509 if ( dyld::gLogAPIs
)
510 dyld::log("_dyld_lookup_and_bind(\"%s\", %p, %p)\n", symbolName
, address
, module);
511 const ImageLoader
* image
;
512 const ImageLoader::Symbol
* sym
;
513 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
514 if ( address
!= NULL
)
515 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
517 *module = ImageLoaderToNSModule(image
);
520 // on failure to find symbol return NULLs
521 if ( address
!= NULL
)
528 void _dyld_lookup_and_bind_with_hint(const char* symbolName
, const char* library_name_hint
, void** address
, NSModule
* module)
530 if ( dyld::gLogAPIs
)
531 dyld::log("%s(\"%s\", \"%s\", %p, %p)\n", __func__
, symbolName
, library_name_hint
, address
, module);
532 const ImageLoader
* image
;
533 const ImageLoader::Symbol
* sym
;
534 // Look for library whose path contains the hint. If that fails search everywhere
535 if ( dyld::flatFindExportedSymbolWithHint(symbolName
, library_name_hint
, &sym
, &image
)
536 || dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
537 if ( address
!= NULL
)
538 *address
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
);
540 *module = ImageLoaderToNSModule(image
);
543 // on failure to find symbol return NULLs
544 if ( address
!= NULL
)
552 NSSymbol
NSLookupAndBindSymbol(const char *symbolName
)
554 if ( dyld::gLogAPIs
)
555 dyld::log("%s(\"%s\")\n", __func__
, symbolName
);
556 const ImageLoader
* image
;
557 const ImageLoader::Symbol
* sym
;
558 if ( dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
) ) {
559 return SymbolToNSSymbol(sym
);
561 // return NULL on failure
565 NSSymbol
NSLookupAndBindSymbolWithHint(const char* symbolName
, const char* libraryNameHint
)
567 if ( dyld::gLogAPIs
)
568 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
569 const ImageLoader
* image
;
570 const ImageLoader::Symbol
* sym
;
571 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
573 // hint failed, do slow search of all images
574 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
577 return SymbolToNSSymbol(sym
);
579 // return NULL on failure and log
580 if ( dyld::gLogAPIs
)
581 dyld::log("%s(\"%s\", \"%s\") => NULL \n", __func__
, symbolName
, libraryNameHint
);
588 static __attribute__((noinline
))
589 const struct mach_header
* addImage(void* callerAddress
, const char* path
, bool search
, bool dontLoad
, bool matchInstallName
, bool abortOnError
)
591 ImageLoader
* image
= NULL
;
592 std::vector
<const char*> rpathsFromCallerImage
;
594 dyld::clearErrorMessage();
595 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
596 // like dlopen, use rpath from caller image and from main executable
597 if ( callerImage
!= NULL
)
598 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
599 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
600 if ( callerImage
!= dyld::mainExecutable() ) {
601 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
603 dyld::LoadContext context
;
604 context
.useSearchPaths
= search
;
605 context
.useFallbackPaths
= search
;
606 context
.useLdLibraryPath
= false;
607 context
.implicitRPath
= false;
608 context
.matchByInstallName
= matchInstallName
;
609 context
.dontLoad
= dontLoad
;
610 context
.mustBeBundle
= false;
611 context
.mustBeDylib
= true;
612 context
.canBePIE
= false;
613 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
614 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
617 image
= load(path
, context
, cacheIndex
);
618 if ( image
!= NULL
) {
619 if ( context
.matchByInstallName
)
620 image
->setMatchInstallPath(true);
621 dyld::link(image
, false, false, callersRPaths
, cacheIndex
);
622 dyld::runInitializers(image
);
623 // images added with NSAddImage() can never be unloaded
624 image
->setNeverUnload();
627 catch (const char* msg
) {
628 dyld::garbageCollectImages();
630 char pathMsg
[strlen(msg
)+strlen(path
)+4];
631 strcpy(pathMsg
, msg
);
632 strcat(pathMsg
, " ");
633 strcat(pathMsg
, path
);
634 dyldAPIhalt("NSAddImage", pathMsg
);
636 // not halting, so set error state for NSLinkEditError to find
637 setLastError(NSLinkEditOtherError
, 0, path
, msg
);
638 free((void*)msg
); // our free() will do nothing if msg is a string literal
641 // free rpaths (getRPaths() malloc'ed each string)
642 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
643 const char* str
= *it
;
649 return image
->machHeader();
653 const struct mach_header
* NSAddImage(const char* path
, uint32_t options
)
655 if ( dyld::gLogAPIs
)
656 dyld::log("%s(\"%s\", 0x%08X)\n", __func__
, path
, options
);
657 const bool dontLoad
= ( (options
& NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
) != 0 );
658 const bool search
= ( (options
& NSADDIMAGE_OPTION_WITH_SEARCHING
) != 0 );
659 const bool matchInstallName
= ( (options
& NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME
) != 0 );
660 const bool abortOnError
= ( (options
& (NSADDIMAGE_OPTION_RETURN_ON_ERROR
|NSADDIMAGE_OPTION_RETURN_ONLY_IF_LOADED
)) == 0 );
661 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
662 return addImage(callerAddress
, path
, search
, dontLoad
, matchInstallName
, abortOnError
);
665 bool NSAddLibrary(const char* path
)
667 if ( dyld::gLogAPIs
)
668 dyld::log("%s(\"%s\")\n", __func__
, path
);
669 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
670 return (addImage(callerAddress
, path
, false, false, false, false) != NULL
);
673 bool NSAddLibraryWithSearching(const char* path
)
675 if ( dyld::gLogAPIs
)
676 dyld::log("%s(\"%s\")\n", __func__
, path
);
677 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
678 return (addImage(callerAddress
, path
, true, false, false, false) != NULL
);
683 //#define NSADDIMAGE_OPTION_NONE 0x0
684 //#define NSADDIMAGE_OPTION_RETURN_ON_ERROR 0x1
685 //#define NSADDIMAGE_OPTION_MATCH_FILENAME_BY_INSTALLNAME 0x8
687 bool NSIsSymbolNameDefinedInImage(const struct mach_header
* mh
, const char* symbolName
)
689 if ( dyld::gLogAPIs
)
690 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)mh
, symbolName
);
691 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
692 if ( image
!= NULL
) {
693 if ( image
->findExportedSymbol(symbolName
, true, NULL
) != NULL
)
700 NSSymbol
NSLookupSymbolInImage(const struct mach_header
* mh
, const char* symbolName
, uint32_t options
)
702 if ( dyld::gLogAPIs
)
703 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, mh
, symbolName
, options
);
704 const ImageLoader::Symbol
* symbol
= NULL
;
705 dyld::clearErrorMessage();
706 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
707 if ( image
!= NULL
) {
708 const char* symbolToFind
= symbolName
;
710 if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_FULLY
) {
711 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
713 else if ( options
& NSLOOKUPSYMBOLINIMAGE_OPTION_BIND_NOW
) {
714 image
->bindAllLazyPointers(dyld::gLinkContext
, false);
717 catch (const char* msg
) {
718 if ( (options
& NSLOOKUPSYMBOLINIMAGE_OPTION_RETURN_ON_ERROR
) == 0 ) {
719 dyldAPIhalt(__func__
, msg
);
722 symbol
= image
->findExportedSymbol(symbolToFind
, true, NULL
);
724 if ( dyld::gLogAPIs
&& (symbol
== NULL
) )
725 dyld::log("%s(%p, \"%s\", 0x%08X) ==> NULL\n", __func__
, mh
, symbolName
, options
);
726 return SymbolToNSSymbol(symbol
);
730 // Note: This cannot have public name because dyld is built with a static copy of libc.a
731 // which calls NSIsSymbolNameDefined() and expects to find dyld's symbols not host process
732 static bool client_NSIsSymbolNameDefined(const char* symbolName
)
734 if ( dyld::gLogAPIs
)
735 dyld::log("NSIsSymbolNameDefined(\"%s\")\n", symbolName
);
736 const ImageLoader
* image
;
737 const ImageLoader::Symbol
* sym
;
738 return dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
741 bool NSIsSymbolNameDefinedWithHint(const char* symbolName
, const char* libraryNameHint
)
743 if ( dyld::gLogAPIs
)
744 dyld::log("%s(\"%s\", \"%s\")\n", __func__
, symbolName
, libraryNameHint
);
745 const ImageLoader
* image
;
746 const ImageLoader::Symbol
* sym
;
747 bool found
= dyld::flatFindExportedSymbolWithHint(symbolName
, libraryNameHint
, &sym
, &image
);
749 // hint failed, do slow search of all images
750 found
= dyld::flatFindExportedSymbol(symbolName
, &sym
, &image
);
752 if ( !found
&& dyld::gLogAPIs
)
753 dyld::log("%s(\"%s\", \"%s\") => false \n", __func__
, symbolName
, libraryNameHint
);
757 const char* NSNameOfSymbol(NSSymbol symbol
)
759 if ( dyld::gLogAPIs
)
760 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
761 const char* result
= NULL
;
762 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
764 result
= image
->getExportedSymbolName(NSSymbolToSymbol(symbol
));
768 void* NSAddressOfSymbol(NSSymbol symbol
)
770 if ( dyld::gLogAPIs
)
771 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
772 if ( symbol
== NULL
)
775 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
777 result
= (void*)image
->getExportedSymbolAddress(NSSymbolToSymbol(symbol
), dyld::gLinkContext
);
781 NSModule
NSModuleForSymbol(NSSymbol symbol
)
783 if ( dyld::gLogAPIs
)
784 dyld::log("%s(%p)\n", __func__
, (void *)symbol
);
785 NSModule result
= NULL
;
786 ImageLoader
* image
= dyld::findImageContainingSymbol(symbol
);
788 result
= ImageLoaderToNSModule(image
);
795 bool _dyld_all_twolevel_modules_prebound(void)
797 if ( dyld::gLogAPIs
)
798 dyld::log("%s()\n", __func__
);
802 bool _dyld_bind_fully_image_containing_address(const void* address
)
804 if ( dyld::gLogAPIs
)
805 dyld::log("%s(%p)\n", __func__
, address
);
806 address
= stripPointer(address
);
807 dyld::clearErrorMessage();
808 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
809 if ( image
!= NULL
) {
811 image
->bindAllLazyPointers(dyld::gLinkContext
, true);
814 catch (const char* msg
) {
815 dyldAPIhalt(__func__
, msg
);
821 bool _dyld_image_containing_address(const void* address
)
823 if ( dyld::gLogAPIs
)
824 dyld::log("%s(%p)\n", __func__
, address
);
825 ImageLoader
*imageLoader
= dyld::findImageContainingAddress(address
);
826 return (NULL
!= imageLoader
);
829 static NSObjectFileImage
createObjectImageFile(ImageLoader
* image
, const void* address
= NULL
, size_t len
=0)
831 NSObjectFileImage result
= new __NSObjectFileImage();
832 result
->image
= image
;
833 result
->imageBaseAddress
= address
;
834 result
->imageLength
= len
;
835 sObjectFileImages
.push_back(result
);
839 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromFile(const char* pathName
, NSObjectFileImage
*objectFileImage
)
841 if ( dyld::gLogAPIs
)
842 dyld::log("%s(\"%s\", ...)\n", __func__
, pathName
);
844 void* callerAddress
= __builtin_return_address(1); // note layers: 1: real client, 0: libSystem glue
845 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
847 dyld::LoadContext context
;
848 context
.useSearchPaths
= false;
849 context
.useFallbackPaths
= false;
850 context
.useLdLibraryPath
= false;
851 context
.implicitRPath
= false;
852 context
.matchByInstallName
= false;
853 context
.dontLoad
= false;
854 context
.mustBeBundle
= true;
855 context
.mustBeDylib
= false;
856 context
.canBePIE
= false;
857 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
858 context
.rpath
= NULL
; // support not yet implemented
861 ImageLoader
* image
= dyld::load(pathName
, context
, cacheIndex
);
862 // Note: We DO NOT link the image! NSLinkModule will do that
863 if ( image
!= NULL
) {
864 if ( !image
->isBundle() ) {
865 // the image must have been already loaded (since context.mustBeBundle will prevent it from being loaded)
866 return NSObjectFileImageInappropriateFile
;
868 *objectFileImage
= createObjectImageFile(image
);
869 return NSObjectFileImageSuccess
;
872 catch (const char* msg
) {
873 //dyld::log("dyld: NSCreateObjectFileImageFromFile() error: %s\n", msg);
874 dyld::garbageCollectImages();
876 return NSObjectFileImageInappropriateFile
;
878 return NSObjectFileImageFailure
;
882 NSObjectFileImageReturnCode
NSCreateObjectFileImageFromMemory(const void* address
, size_t size
, NSObjectFileImage
*objectFileImage
)
884 if ( dyld::gLogAPIs
)
885 dyld::log("%s(%p, %lu, %p)\n", __func__
, address
, size
, objectFileImage
);
888 ImageLoader
* image
= dyld::loadFromMemory((const uint8_t*)address
, size
, NULL
);
889 if ( ! image
->isBundle() ) {
890 // this API can only be used with bundles...
891 dyld::garbageCollectImages();
892 return NSObjectFileImageInappropriateFile
;
894 // Note: We DO NOT link the image! NSLinkModule will do that
895 if ( image
!= NULL
) {
896 *objectFileImage
= createObjectImageFile(image
, address
, size
);
897 return NSObjectFileImageSuccess
;
900 catch (const char* msg
) {
902 dyld::garbageCollectImages();
903 //dyld::log("dyld: NSCreateObjectFileImageFromMemory() error: %s\n", msg);
905 return NSObjectFileImageFailure
;
908 static bool validOFI(NSObjectFileImage objectFileImage
)
910 const size_t ofiCount
= sObjectFileImages
.size();
911 for (size_t i
=0; i
< ofiCount
; ++i
) {
912 if ( sObjectFileImages
[i
] == objectFileImage
)
918 bool NSDestroyObjectFileImage(NSObjectFileImage objectFileImage
)
920 if ( dyld::gLogAPIs
)
921 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
923 if ( validOFI(objectFileImage
) ) {
924 // a failure during NSLinkModule will delete the image
925 if ( objectFileImage
->image
!= NULL
) {
926 // if the image has never been linked or has been unlinked, the image is not in the list of valid images
927 // and we should delete it
928 bool linkedImage
= dyld::validImage(objectFileImage
->image
);
929 if ( ! linkedImage
) {
930 ImageLoader::deleteImage(objectFileImage
->image
);
931 objectFileImage
->image
= NULL
;
935 // remove from list of ofi's
936 for (std::vector
<NSObjectFileImage
>::iterator it
=sObjectFileImages
.begin(); it
!= sObjectFileImages
.end(); it
++) {
937 if ( *it
== objectFileImage
) {
938 sObjectFileImages
.erase(it
);
943 // if object was created from a memory, release that memory
944 // NOTE: this is the way dyld has always done this. NSCreateObjectFileImageFromMemory() hands over ownership of the memory to dyld
945 if ( objectFileImage
->imageBaseAddress
!= NULL
) {
947 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 6) ) {
948 size_t sz
= (*dyld::gLibSystemHelpers
->malloc_size
)(objectFileImage
->imageBaseAddress
);
950 (*dyld::gLibSystemHelpers
->free
)((void*)(objectFileImage
->imageBaseAddress
));
955 vm_deallocate(mach_task_self(), (vm_address_t
)objectFileImage
->imageBaseAddress
, objectFileImage
->imageLength
);
959 delete objectFileImage
;
966 uint32_t NSSymbolDefinitionCountInObjectFileImage(NSObjectFileImage objectFileImage
)
968 if ( dyld::gLogAPIs
)
969 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
970 return objectFileImage
->image
->getExportedSymbolCount();
973 const char* NSSymbolDefinitionNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
)
975 if ( dyld::gLogAPIs
)
976 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
977 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedExportedSymbol(ordinal
);
978 return objectFileImage
->image
->getExportedSymbolName(sym
);
981 uint32_t NSSymbolReferenceCountInObjectFileImage(NSObjectFileImage objectFileImage
)
983 if ( dyld::gLogAPIs
)
984 dyld::log("%s(%p)\n", __func__
, objectFileImage
);
985 return objectFileImage
->image
->getImportedSymbolCount();
988 const char * NSSymbolReferenceNameInObjectFileImage(NSObjectFileImage objectFileImage
, uint32_t ordinal
,
989 bool* tentative_definition
)
991 if ( dyld::gLogAPIs
)
992 dyld::log("%s(%p,%d)\n", __func__
, objectFileImage
, ordinal
);
993 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->getIndexedImportedSymbol(ordinal
);
994 if ( tentative_definition
!= NULL
) {
995 ImageLoader::ReferenceFlags flags
= objectFileImage
->image
->getImportedSymbolInfo(sym
);
996 if ( (flags
& ImageLoader::kTentativeDefinition
) != 0 )
997 *tentative_definition
= true;
999 *tentative_definition
= false;
1001 return objectFileImage
->image
->getImportedSymbolName(sym
);
1004 void* NSGetSectionDataInObjectFileImage(NSObjectFileImage objectFileImage
,
1005 const char* segmentName
, const char* sectionName
, unsigned long* size
)
1007 if ( dyld::gLogAPIs
)
1008 dyld::log("%s(%p,%s, %s)\n", __func__
, objectFileImage
, segmentName
, sectionName
);
1012 if ( objectFileImage
->image
->getSectionContent(segmentName
, sectionName
, &start
, &length
) ) {
1022 bool NSIsSymbolDefinedInObjectFileImage(NSObjectFileImage objectFileImage
, const char* symbolName
)
1024 if ( dyld::gLogAPIs
)
1025 dyld::log("%s(%p,%s)\n", __func__
, objectFileImage
, symbolName
);
1026 const ImageLoader::Symbol
* sym
= objectFileImage
->image
->findExportedSymbol(symbolName
, true, NULL
);
1027 return ( sym
!= NULL
);
1032 NSModule
NSLinkModule(NSObjectFileImage objectFileImage
, const char* moduleName
, uint32_t options
)
1034 if ( dyld::gLogAPIs
)
1035 dyld::log("%s(%p, \"%s\", 0x%08X)\n", __func__
, objectFileImage
, moduleName
, options
);
1037 dyld::clearErrorMessage();
1039 if ( (options
& NSLINKMODULE_OPTION_CAN_UNLOAD
) != 0 )
1040 objectFileImage
->image
->setCanUnload();
1042 // NSLinkModule allows a bundle to be link multpile times
1043 // each link causes the bundle to be copied to a new address
1044 if ( objectFileImage
->image
->isLinked() ) {
1045 // already linked, so clone a new one and link it
1046 objectFileImage
->image
= dyld::cloneImage(objectFileImage
->image
);
1049 // for memory based images, set moduleName as the name anyone calling _dyld_get_image_name() will see
1050 if ( objectFileImage
->image
->getPath() == NULL
) {
1051 objectFileImage
->image
->setPath(moduleName
);
1052 // <rdar://problem/8812589> dyld has NULL paths in image info array
1053 dyld_image_info info
;
1054 info
.imageLoadAddress
= objectFileImage
->image
->machHeader();
1055 info
.imageFilePath
= moduleName
;
1056 info
.imageFileModDate
= 0;
1057 addImagesToAllImages(1, &info
);
1060 // support private bundles
1061 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1062 objectFileImage
->image
->setHideExports();
1064 // set up linking options
1065 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1067 // load libraries, rebase, bind, to make this image usable
1068 dyld::link(objectFileImage
->image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1070 // bump reference count to keep this bundle from being garbage collected
1071 objectFileImage
->image
->incrementDlopenReferenceCount();
1073 // run initializers unless magic flag says not to
1074 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1075 dyld::runInitializers(objectFileImage
->image
);
1077 return ImageLoaderToNSModule(objectFileImage
->image
);
1079 catch (const char* msg
) {
1080 dyld::garbageCollectImages();
1081 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1082 dyldAPIhalt(__func__
, msg
);
1083 // not halting, so set error state for NSLinkEditError to find
1084 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1085 // dyld::link() deleted the image so lose our reference
1086 objectFileImage
->image
= NULL
;
1093 #if OLD_LIBSYSTEM_SUPPORT
1094 // This is for compatibility with old libSystems (libdyld.a) which process ObjectFileImages outside dyld
1095 static NSModule
_dyld_link_module(NSObjectFileImage object_addr
, size_t object_size
, const char* moduleName
, uint32_t options
)
1097 if ( dyld::gLogAPIs
)
1098 dyld::log("%s(%p, \"%s\", 0x%08X)\n", "NSLinkModule", object_addr
, moduleName
, options
); // note name/args translation
1099 ImageLoader
* image
= NULL
;
1100 dyld::clearErrorMessage();
1102 const char* imageName
= moduleName
;
1103 image
= dyld::loadFromMemory((const uint8_t*)object_addr
, object_size
, imageName
);
1105 if ( image
!= NULL
) {
1106 // support private bundles
1107 if ( (options
& NSLINKMODULE_OPTION_PRIVATE
) != 0 )
1108 image
->setHideExports();
1110 // set up linking options
1111 bool forceLazysBound
= ( (options
& NSLINKMODULE_OPTION_BINDNOW
) != 0 );
1113 // load libraries, rebase, bind, to make this image usable
1114 dyld::link(image
, forceLazysBound
, false, ImageLoader::RPathChain(NULL
,NULL
), UINT32_MAX
);
1116 // run initializers unless magic flag says not to
1117 if ( (options
& NSLINKMODULE_OPTION_DONT_CALL_MOD_INIT_ROUTINES
) == 0 )
1118 dyld::runInitializers(image
);
1121 catch (const char* msg
) {
1122 if ( (options
& NSLINKMODULE_OPTION_RETURN_ON_ERROR
) == 0 )
1123 dyldAPIhalt("NSLinkModule", msg
);
1124 // not halting, so set error state for NSLinkEditError to find
1125 setLastError(NSLinkEditOtherError
, 0, moduleName
, msg
);
1126 // if image was created for this bundle, destroy it
1127 if ( image
!= NULL
) {
1128 dyld::removeImage(image
);
1129 ImageLoader::deleteImage(image
);
1134 return ImageLoaderToNSModule(image
);
1138 NSSymbol
NSLookupSymbolInModule(NSModule
module, const char* symbolName
)
1140 if ( dyld::gLogAPIs
)
1141 dyld::log("%s(%p, \"%s\")\n", __func__
, (void *)module, symbolName
);
1142 ImageLoader
* image
= NSModuleToImageLoader(module);
1143 if ( image
== NULL
)
1145 return SymbolToNSSymbol(image
->findExportedSymbol(symbolName
, false, NULL
));
1148 const char* NSNameOfModule(NSModule
module)
1150 if ( dyld::gLogAPIs
)
1151 dyld::log("%s(%p)\n", __func__
, module);
1152 ImageLoader
* image
= NSModuleToImageLoader(module);
1153 if ( image
== NULL
)
1155 return image
->getPath();
1158 const char* NSLibraryNameForModule(NSModule
module)
1160 if ( dyld::gLogAPIs
)
1161 dyld::log("%s(%p)\n", __func__
, module);
1162 ImageLoader
* image
= NSModuleToImageLoader(module);
1163 if ( image
== NULL
)
1165 return image
->getPath();
1168 bool NSUnLinkModule(NSModule
module, uint32_t options
)
1170 if ( dyld::gLogAPIs
)
1171 dyld::log("%s(%p, 0x%08X)\n", __func__
, module, options
);
1172 if ( module == NULL
)
1174 ImageLoader
* image
= NSModuleToImageLoader(module);
1175 if ( image
== NULL
)
1177 dyld::runImageStaticTerminators(image
);
1178 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 13) ) {
1179 __cxa_range_t ranges
[image
->segmentCount()];
1181 for (unsigned int j
=0; j
< image
->segmentCount(); ++j
) {
1182 if ( !image
->segExecutable(j
) )
1184 ranges
[rangeCount
].addr
= (const void*)image
->segActualLoadAddress(j
);
1185 ranges
[rangeCount
].length
= image
->segSize(j
);
1188 (*dyld::gLibSystemHelpers
->cxa_finalize_ranges
)(ranges
, rangeCount
);
1190 dyld::removeImage(image
);
1192 if ( (options
& NSUNLINKMODULE_OPTION_KEEP_MEMORY_MAPPED
) != 0 )
1193 image
->setLeaveMapped();
1195 // TODO: NSUNLINKMODULE_OPTION_RESET_LAZY_REFERENCES
1197 // Only delete image if there is no ofi referencing it
1198 // That means the ofi was destroyed after linking, so no one is left to delete this image
1199 const size_t ofiCount
= sObjectFileImages
.size();
1201 for (size_t i
=0; i
< ofiCount
; ++i
) {
1202 NSObjectFileImage ofi
= sObjectFileImages
[i
];
1203 if ( ofi
->image
== image
)
1207 ImageLoader::deleteImage(image
);
1212 // internal name and parameters do not match public name and parameters...
1213 static void _dyld_install_handlers(void* undefined
, void* multiple
, void* linkEdit
)
1215 if ( dyld::gLogAPIs
)
1216 dyld::log("NSLinkEditErrorHandlers()\n");
1218 dyld::registerUndefinedHandler((dyld::UndefinedHandler
)undefined
);
1219 // no support for multiple or linkedit handlers
1225 void NSLinkEditError(NSLinkEditErrors
* c
, int* errorNumber
, const char** fileName
, const char** errorString
)
1228 *c
= sLastErrorFileCode
;
1229 *errorNumber
= sLastErrorNo
;
1230 *fileName
= sLastErrorFilePath
;
1231 *errorString
= dyld::getErrorMessage();
1236 static void _dyld_register_binding_handler(void * (*bindingHandler
)(const char *, const char *, void *), ImageLoader::BindingOptions bindingOptions
)
1238 if ( dyld::gLogAPIs
)
1239 dyld::log("%s()\n", __func__
);
1240 dyld::gLinkContext
.bindingHandler
= bindingHandler
;
1241 dyld::gLinkContext
.bindingOptions
= bindingOptions
;
1244 #endif //DEPRECATED_APIS_SUPPORTED
1247 // Call by fork() in libSystem after the kernel trap is done on the child side
1248 void _dyld_fork_child()
1250 if ( dyld::gLogAPIs
)
1251 dyld::log("%s()\n", __func__
);
1252 // The implementation of fork() in libSystem knows to reset the variable mach_task_self_
1253 // in libSystem for the child of a fork. But dyld is built with a static copy
1254 // of libc.a and has its own copy of mach_task_self_ which we reset here.
1256 // In mach_init.h mach_task_self() is #defined to mach_task_self_ and
1257 // in mach_init() mach_task_self_ is initialized to task_self_trap().
1259 extern mach_port_t mach_task_self_
;
1260 mach_task_self_
= task_self_trap();
1262 // If dyld is sending load/unload notices to CoreSymbolication, the shared memory
1263 // page is not copied on fork. <rdar://problem/6797342>
1264 // NULL the CoreSymbolication shared memory pointer to prevent a crash.
1265 dyld::gProcessInfo
->coreSymbolicationShmPage
= NULL
;
1266 // for safety, make sure child starts with clean systemOrderFlag
1267 dyld::gProcessInfo
->systemOrderFlag
= 0;
1271 #if DEPRECATED_APIS_SUPPORTED
1272 // returns true if prebinding was used in main executable
1273 bool _dyld_launched_prebound()
1275 if ( dyld::gLogAPIs
)
1276 dyld::log("%s()\n", __func__
);
1278 // ¥¥¥Êif we deprecate prebinding, we may want to consider always returning true or false here
1279 return dyld::mainExecutablePrebound();
1284 // _dyld_NSMakePrivateModulePublic() is the dyld side of the hack
1285 // NSMakePrivateModulePublic() needed for the dlopen() to turn it's
1286 // RTLD_LOCAL handles into RTLD_GLOBAL. It just simply turns off the private
1287 // flag on the image for this module. If the module was found and it was
1288 // private then everything worked and TRUE is returned else FALSE is returned.
1290 static bool NSMakePrivateModulePublic(NSModule
module)
1292 ImageLoader
* image
= NSModuleToImageLoader(module);
1293 if ( image
!= NULL
) {
1294 if ( image
->hasHiddenExports() ) {
1295 image
->setHideExports(false);
1302 #endif // DEPRECATED_APIS_SUPPORTED
1304 int _dyld_func_lookup(const char* name
, void** address
)
1306 for (const dyld_func
* p
= dyld_funcs
; p
->name
!= NULL
; ++p
) {
1307 if ( strcmp(p
->name
, name
) == 0 ) {
1308 if( p
->implementation
== unimplemented
)
1309 dyld::log("unimplemented dyld function: %s\n", p
->name
);
1310 *address
= p
->implementation
;
1319 static void registerThreadHelpers(const dyld::LibSystemHelpers
* helpers
)
1321 dyld::gLibSystemHelpers
= helpers
;
1323 #if !SUPPORT_ZERO_COST_EXCEPTIONS
1324 if ( helpers
->version
>= 5 ) {
1325 // create key use by dyld exception handling
1327 int result
= helpers
->pthread_key_create(&key
, NULL
);
1329 __Unwind_SjLj_SetThreadKey(key
);
1335 static void dlerrorClear()
1337 if ( dyld::gLibSystemHelpers
!= NULL
) {
1338 // <rdar://problem/10595338> dlerror buffer leak
1339 // dlerrorClear() should not force allocation, but zero it if already allocated
1340 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1341 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1345 // first char of buffer is flag whether string (starting at second char) is valid
1346 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1352 static void dlerrorSet(const char* msg
)
1354 if ( dyld::gLibSystemHelpers
!= NULL
) {
1355 // first char of buffer is flag whether string (starting at second char) is valid
1356 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(strlen(msg
)+2);
1358 strcpy(&buffer
[1], msg
);
1363 bool dlopen_preflight_internal(const char* path
, void* callerAddress
)
1365 if ( dyld::gLogAPIs
)
1366 dyld::log("%s(%s)\n", __func__
, path
);
1370 CRSetCrashLogMessage("dyld: in dlopen_preflight()");
1372 const bool leafName
= (strchr(path
, '/') == NULL
);
1373 const bool absolutePath
= (path
[0] == '/');
1374 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1375 char canonicalPath
[PATH_MAX
];
1376 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1378 // make path canonical if it contains a // or ./
1379 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1380 const char* lastSlash
= strrchr(path
, '/');
1381 char dirPath
[PATH_MAX
];
1382 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1383 dirPath
[lastSlash
-path
] = '\0';
1384 if ( realpath(dirPath
, canonicalPath
) ) {
1385 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1386 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1387 // if all fit in buffer, use new canonical path
1388 path
= canonicalPath
;
1395 #if SUPPORT_ACCELERATE_TABLES
1396 if ( dyld::isPathInCache(path
) )
1400 // <rdar://problem/5910137> dlopen_preflight() on image in shared cache leaves it loaded but not objc initialized
1401 // if requested path is to something in the dyld shared cache, always succeed
1402 if ( dyld::inSharedCache(path
) )
1405 #if __MAC_OS_X_VERSION_MIN_REQUIRED
1406 // <rdar://problem/47464387> dlopen_preflight() on symlink to image in shared cache leaves it half loaded
1407 if ( strncmp(path
, "/System/Library/", 16) == 0 ) {
1408 char canonicalPath
[PATH_MAX
];
1409 if ( realpath(path
, canonicalPath
) ) {
1410 if ( dyld::inSharedCache(canonicalPath
) )
1416 bool result
= false;
1417 std::vector
<const char*> rpathsFromCallerImage
;
1419 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1420 // for dlopen, use rpath from caller image and from main executable
1421 if ( callerImage
!= NULL
)
1422 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1423 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1424 if ( callerImage
!= dyld::mainExecutable() ) {
1425 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1428 ImageLoader
* image
= NULL
;
1429 dyld::LoadContext context
;
1430 context
.useSearchPaths
= true;
1431 context
.useFallbackPaths
= leafName
; // a partial path implies don't use fallback paths
1432 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1433 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1434 context
.matchByInstallName
= true;
1435 context
.dontLoad
= false;
1436 context
.mustBeBundle
= false;
1437 context
.mustBeDylib
= false;
1438 context
.canBePIE
= true;
1439 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1440 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1442 unsigned cacheIndex
;
1443 image
= load(path
, context
, cacheIndex
);
1444 if ( image
!= NULL
) {
1445 dyld::preflight(image
, callersRPaths
, cacheIndex
); // image object deleted by dyld::preflight()
1449 catch (const char* msg
) {
1450 const char* str
= dyld::mkstringf("dlopen_preflight(%s): %s", path
, msg
);
1453 free((void*)msg
); // our free() will do nothing if msg is a string literal
1455 // free rpaths (getRPaths() malloc'ed each string)
1456 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1457 const char* str
= *it
;
1460 CRSetCrashLogMessage(NULL
);
1464 #if SUPPORT_ACCELERATE_TABLES
1465 bool static callerIsNonOSApp(void* callerAddress
, const char** shortName
)
1468 const mach_header
* unusedMh
;
1469 const char* unusedPath
;
1470 unsigned unusedIndex
;
1471 // any address in shared cache is not from app
1472 if ( dyld::addressInCache(callerAddress
, &unusedMh
, &unusedPath
, &unusedIndex
) )
1475 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1476 if ( callerImage
== NULL
)
1479 *shortName
= callerImage
->getShortName();
1480 return ( strncmp(callerImage
->getPath(), "/var/containers/", 16) == 0 );
1484 void* dlopen_internal(const char* path
, int mode
, void* callerAddress
)
1486 if ( dyld::gLogAPIs
)
1487 dyld::log("%s(%s, 0x%08X)\n", __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1489 #if SUPPORT_ACCELERATE_TABLES
1490 if ( dyld::gLogAppAPIs
) {
1491 const char* shortName
;
1492 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1493 dyld::log("%s: %s(%s, 0x%08X)\n", shortName
, __func__
, ((path
==NULL
) ? "NULL" : path
), mode
);
1500 // passing NULL for path means return magic object
1501 if ( path
== NULL
) {
1502 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1503 if ( (mode
& RTLD_FIRST
) != 0 )
1504 return RTLD_MAIN_ONLY
;
1506 return RTLD_DEFAULT
;
1509 // acquire global dyld lock (dlopen is special - libSystem glue does not do locking)
1510 bool lockHeld
= false;
1511 if ( (dyld::gLibSystemHelpers
!= NULL
) && (dyld::gLibSystemHelpers
->version
>= 4) ) {
1512 dyld::gLibSystemHelpers
->acquireGlobalDyldLock();
1513 CRSetCrashLogMessage("dyld: in dlopen()");
1517 void* result
= NULL
;
1518 const bool leafName
= (strchr(path
, '/') == NULL
);
1519 const bool absolutePath
= (path
[0] == '/');
1520 #if __IPHONE_OS_VERSION_MIN_REQUIRED
1521 char canonicalPath
[PATH_MAX
];
1522 // <rdar://problem/7017050> dlopen() not opening frameworks from shared cache with // or ./ in path
1524 // make path canonical if it contains a // or ./
1525 if ( (strstr(path
, "//") != NULL
) || (strstr(path
, "./") != NULL
) ) {
1526 const char* lastSlash
= strrchr(path
, '/');
1527 char dirPath
[PATH_MAX
];
1528 if ( strlcpy(dirPath
, path
, sizeof(dirPath
)) < sizeof(dirPath
) ) {
1529 dirPath
[lastSlash
-path
] = '\0';
1530 if ( realpath(dirPath
, canonicalPath
) ) {
1531 strlcat(canonicalPath
, "/", sizeof(canonicalPath
));
1532 if ( strlcat(canonicalPath
, lastSlash
+1, sizeof(canonicalPath
)) < sizeof(canonicalPath
) ) {
1533 // if all fit in buffer, use new canonical path
1534 path
= canonicalPath
;
1541 #if SUPPORT_ACCELERATE_TABLES
1542 if ( dyld::dlopenFromCache(path
, mode
, &result
) ) {
1543 // Note: dlopenFromCache() releases the lock
1544 if ( dyld::gLogAPIs
)
1545 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1550 ImageLoader
* image
= NULL
;
1551 std::vector
<const char*> rpathsFromCallerImage
;
1552 ImageLoader::RPathChain
callersRPaths(NULL
, &rpathsFromCallerImage
);
1554 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1555 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1556 // for dlopen, use rpath from caller image and from main executable
1557 if ( callerImage
!= NULL
)
1558 callerImage
->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1559 if ( callerImage
!= dyld::mainExecutable() )
1560 dyld::mainExecutable()->getRPaths(dyld::gLinkContext
, rpathsFromCallerImage
);
1563 dyld::LoadContext context
;
1564 context
.useSearchPaths
= true;
1565 context
.useFallbackPaths
= leafName
; // a partial path means no fallback paths
1566 context
.useLdLibraryPath
= leafName
; // a leafname implies should search
1567 context
.implicitRPath
= !absolutePath
; // a non-absolute path implies try rpath searching
1568 context
.matchByInstallName
= true;
1569 context
.dontLoad
= ( (mode
& RTLD_NOLOAD
) != 0 );
1570 context
.mustBeBundle
= false;
1571 context
.mustBeDylib
= false;
1572 context
.canBePIE
= true;
1573 context
.origin
= callerImage
!= NULL
? callerImage
->getPath() : NULL
; // caller's image's path
1574 context
.rpath
= &callersRPaths
; // rpaths from caller and main executable
1576 unsigned cacheIndex
;
1577 image
= load(path
, context
, cacheIndex
);
1578 #if SUPPORT_ACCELERATE_TABLES
1579 if ( (image
!= NULL
) && (cacheIndex
!= UINT32_MAX
) ) {
1580 // found in cache, but under a different path
1581 const char* betterPath
= dyld::getPathFromIndex(cacheIndex
);
1582 if ( (betterPath
!= NULL
) && dyld::dlopenFromCache(betterPath
, mode
, &result
) ) {
1583 // Note: dlopenFromCache() releases the lock
1584 if ( dyld::gLogAPIs
)
1585 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1590 if ( image
!= NULL
) {
1591 // bump reference count. Do this before link() so that if an initializer calls dlopen and fails
1592 // this image is not garbage collected
1593 image
->incrementDlopenReferenceCount();
1594 // link in all dependents
1595 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1596 bool alreadyLinked
= image
->isLinked();
1597 bool forceLazysBound
= ( (mode
& RTLD_NOW
) != 0 );
1598 dyld::link(image
, forceLazysBound
, false, callersRPaths
, cacheIndex
);
1599 if ( alreadyLinked
) {
1601 if ( ((mode
& RTLD_LOCAL
) == 0) && image
->hasHiddenExports() )
1602 image
->setHideExports(false);
1605 // only hide exports if image is not already in use
1606 if ( (mode
& RTLD_LOCAL
) != 0 )
1607 image
->setHideExports(true);
1611 // RTLD_NODELETE means don't unmap image even after dlclosed. This is what dlcompat did on Mac OS X 10.3
1612 // On other *nix OS's, it means dlclose() should do nothing, but the handle should be invalidated.
1613 // The subtle differences are:
1614 // 1) if the image has any termination routines, whether they are run during dlclose or when the process terminates
1615 // 2) If someone does a supsequent dlopen() on the same image, whether the same address should be used.
1616 if ( (mode
& RTLD_NODELETE
) != 0 )
1617 image
->setLeaveMapped();
1619 // release global dyld lock early, this enables initializers to do threaded operations
1621 CRSetCrashLogMessage(NULL
);
1622 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1626 // RTLD_NOLOAD means dlopen should fail unless path is already loaded.
1627 // don't run initializers when RTLD_NOLOAD is set. This only matters if dlopen() is
1628 // called from within an initializer because it can cause initializers to run
1629 // out of order. Most uses of RTLD_NOLOAD are "probes". If they want initialzers
1630 // to run, then don't use RTLD_NOLOAD.
1631 if ( (mode
& RTLD_NOLOAD
) == 0 ) {
1633 dyld::runInitializers(image
);
1636 // RTLD_FIRST means any dlsym() calls on the handle should only search that handle and not subsequent images
1637 // this is tracked by setting the low bit of the handle, which is usually zero by malloc alignment
1638 if ( (mode
& RTLD_FIRST
) != 0 )
1639 result
= (void*)(((uintptr_t)image
)|1);
1644 catch (const char* msg
) {
1645 if ( image
!= NULL
) {
1646 // load() succeeded but, link() failed
1647 // back down reference count and do GC
1648 image
->decrementDlopenReferenceCount();
1649 if ( image
->dlopenCount() == 0 )
1650 dyld::garbageCollectImages();
1652 const char* str
= dyld::mkstringf("dlopen(%s, %d): %s", path
, mode
, msg
);
1653 if ( dyld::gLogAPIs
)
1654 dyld::log(" %s() failed, error: '%s'\n", __func__
, str
);
1657 free((void*)msg
); // our free() will do nothing if msg is a string literal
1660 // free rpaths (getRPaths() malloc'ed each string)
1661 for(std::vector
<const char*>::iterator it
=rpathsFromCallerImage
.begin(); it
!= rpathsFromCallerImage
.end(); ++it
) {
1662 const char* str
= *it
;
1666 // when context.dontLoad is set, load() returns NULL instead of throwing an exception
1667 if ( (mode
& RTLD_NOLOAD
) && (result
== NULL
) ) {
1668 dlerrorSet("image not already loaded");
1672 CRSetCrashLogMessage(NULL
);
1673 dyld::gLibSystemHelpers
->releaseGlobalDyldLock();
1675 if ( dyld::gLogAPIs
&& (result
!= NULL
) )
1676 dyld::log(" %s(%s) ==> %p\n", __func__
, path
, result
);
1680 int dlclose(void* handle
)
1682 if ( dyld::gLogAPIs
)
1683 dyld::log("%s(%p)\n", __func__
, handle
);
1685 // silently accept magic handles for main executable
1686 if ( handle
== RTLD_MAIN_ONLY
)
1688 if ( handle
== RTLD_DEFAULT
)
1691 #if SUPPORT_ACCELERATE_TABLES
1692 if ( dyld::isCacheHandle(handle
) ) {
1698 ImageLoader
* image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1699 if ( dyld::validImage(image
) ) {
1701 // decrement use count
1702 if ( image
->decrementDlopenReferenceCount() ) {
1703 dlerrorSet("dlclose() called too many times");
1706 // remove image if reference count went to zero
1707 if ( image
->dlopenCount() == 0 )
1708 dyld::garbageCollectImages();
1712 dlerrorSet("invalid handle passed to dlclose()");
1719 int dladdr(const void* address
, Dl_info
* info
)
1721 if ( dyld::gLogAPIs
)
1722 dyld::log("%s(%p, %p)\n", __func__
, address
, info
);
1724 // <rdar://problem/42171466> calling dladdr(xx,NULL) crashes
1726 return 0; // failure
1728 address
= stripPointer(address
);
1730 CRSetCrashLogMessage("dyld: in dladdr()");
1731 #if SUPPORT_ACCELERATE_TABLES
1732 if ( dyld::dladdrFromCache(address
, info
) ) {
1733 CRSetCrashLogMessage(NULL
);
1734 return 1; // success
1738 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
1739 if ( image
!= NULL
) {
1740 info
->dli_fname
= image
->getRealPath();
1741 info
->dli_fbase
= (void*)image
->machHeader();
1742 if ( address
== info
->dli_fbase
) {
1743 // special case lookup of header
1744 info
->dli_sname
= "__dso_handle";
1745 info
->dli_saddr
= info
->dli_fbase
;
1746 CRSetCrashLogMessage(NULL
);
1747 return 1; // success
1749 // find closest symbol in the image
1750 info
->dli_sname
= image
->findClosestSymbol(address
, (const void**)&info
->dli_saddr
);
1751 // never return the mach_header symbol
1752 if ( info
->dli_saddr
== info
->dli_fbase
) {
1753 info
->dli_sname
= NULL
;
1754 info
->dli_saddr
= NULL
;
1755 CRSetCrashLogMessage(NULL
);
1756 return 1; // success
1758 if ( info
->dli_sname
!= NULL
) {
1759 if ( info
->dli_sname
[0] == '_' )
1760 info
->dli_sname
= info
->dli_sname
+1; // strip off leading underscore
1761 //dyld::log("dladdr(%p) => %p %s\n", address, info->dli_saddr, info->dli_sname);
1762 CRSetCrashLogMessage(NULL
);
1763 return 1; // success
1765 info
->dli_sname
= NULL
;
1766 info
->dli_saddr
= NULL
;
1767 CRSetCrashLogMessage(NULL
);
1768 return 1; // success
1770 CRSetCrashLogMessage(NULL
);
1771 return 0; // failure
1777 if ( dyld::gLogAPIs
)
1778 dyld::log("%s()\n", __func__
);
1780 if ( dyld::gLibSystemHelpers
!= NULL
) {
1781 // if using newer libdyld.dylib and buffer if buffer not yet allocated, return NULL
1782 if ( dyld::gLibSystemHelpers
->version
>= 10 ) {
1783 if ( ! (*dyld::gLibSystemHelpers
->hasPerThreadBufferFor_dlerror
)() )
1787 // first char of buffer is flag whether string (starting at second char) is valid
1788 char* buffer
= (*dyld::gLibSystemHelpers
->getThreadBufferFor_dlerror
)(2);
1789 if ( buffer
[0] != '\0' ) { // if valid buffer
1790 buffer
[0] = '\0'; // mark invalid, so next call to dlerror returns NULL
1791 return &buffer
[1]; // return message
1797 void* dlsym_internal(void* handle
, const char* symbolName
, void* callerAddress
)
1799 if ( dyld::gLogAPIs
)
1800 dyld::log("%s(%p, %s)\n", __func__
, handle
, symbolName
);
1802 #if SUPPORT_ACCELERATE_TABLES
1803 if ( dyld::gLogAppAPIs
) {
1804 const char* shortName
;
1805 if ( callerIsNonOSApp(callerAddress
, &shortName
) ) {
1806 dyld::log("%s: %s(%p, %s)\n", shortName
, __func__
, handle
, symbolName
);
1811 CRSetCrashLogMessage("dyld: in dlsym()");
1814 const ImageLoader
* image
;
1815 const ImageLoader::Symbol
* sym
;
1818 // dlsym() assumes symbolName passed in is same as in C source code
1819 // dyld assumes all symbol names have an underscore prefix
1820 char underscoredName
[strlen(symbolName
)+2];
1821 underscoredName
[0] = '_';
1822 strcpy(&underscoredName
[1], symbolName
);
1824 // magic "search all" handle
1825 if ( handle
== RTLD_DEFAULT
) {
1826 if ( dyld::flatFindExportedSymbol(underscoredName
, &sym
, &image
) ) {
1827 CRSetCrashLogMessage(NULL
);
1828 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1829 #if __has_feature(ptrauth_calls)
1830 // Sign the pointer if it points to a function
1831 // Note we only do this if the main executable is arm64e as otherwise we
1832 // may end up calling containsAddress on the accelerator tables.
1833 if ( result
&& (dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64E
) ) {
1834 const ImageLoader
* symbolImage
= image
;
1835 if (!symbolImage
->containsAddress(result
)) {
1836 symbolImage
= dyld::findImageContainingAddress(result
);
1838 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1839 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1840 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1843 if ( dyld::gLogAPIs
)
1844 dyld::log(" %s(RTLD_DEFAULT, %s) ==> %p\n", __func__
, symbolName
, result
);
1847 const char* str
= dyld::mkstringf("dlsym(RTLD_DEFAULT, %s): symbol not found", symbolName
);
1850 CRSetCrashLogMessage(NULL
);
1851 if ( dyld::gLogAPIs
)
1852 dyld::log(" %s(RTLD_DEFAULT, %s) ==> NULL\n", __func__
, symbolName
);
1856 // magic "search only main executable" handle
1857 else if ( handle
== RTLD_MAIN_ONLY
) {
1858 image
= dyld::mainExecutable();
1859 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1860 if ( sym
!= NULL
) {
1861 CRSetCrashLogMessage(NULL
);
1862 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, NULL
, false, underscoredName
);
1863 #if __has_feature(ptrauth_calls)
1864 // Sign the pointer if it points to a function
1865 // Note we only do this if the main executable is arm64e as otherwise we
1866 // may end up calling containsAddress on the accelerator tables.
1867 if ( result
&& (dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64E
) ) {
1868 const ImageLoader
* symbolImage
= image
;
1869 if (!symbolImage
->containsAddress(result
)) {
1870 symbolImage
= dyld::findImageContainingAddress(result
);
1872 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1873 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1874 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1877 if ( dyld::gLogAPIs
)
1878 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> %p\n", __func__
, symbolName
, result
);
1881 const char* str
= dyld::mkstringf("dlsym(RTLD_MAIN_ONLY, %s): symbol not found", symbolName
);
1884 CRSetCrashLogMessage(NULL
);
1885 if ( dyld::gLogAPIs
)
1886 dyld::log(" %s(RTLD_MAIN_ONLY, %s) ==> NULL\n", __func__
, symbolName
);
1890 // magic "search what I would see" handle
1891 else if ( handle
== RTLD_NEXT
) {
1892 #if SUPPORT_ACCELERATE_TABLES
1893 const mach_header
* mh
;
1896 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1897 // if dylib in cache is calling dlsym(RTLD_NEXT,xxx) handle search differently
1898 result
= dyld::dlsymFromCache(RTLD_NEXT
, underscoredName
, index
);
1899 if ( dyld::gLogAPIs
)
1900 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1904 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1905 sym
= callerImage
->findExportedSymbolInDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // don't search image, but do search what it links against
1906 if ( sym
!= NULL
) {
1907 CRSetCrashLogMessage(NULL
);
1908 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1909 #if __has_feature(ptrauth_calls)
1910 // Sign the pointer if it points to a function
1911 // Note we only do this if the main executable is arm64e as otherwise we
1912 // may end up calling containsAddress on the accelerator tables.
1913 if ( result
&& (dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64E
) ) {
1914 const ImageLoader
* symbolImage
= image
;
1915 if (!symbolImage
->containsAddress(result
)) {
1916 symbolImage
= dyld::findImageContainingAddress(result
);
1918 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1919 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1920 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1923 if ( dyld::gLogAPIs
)
1924 dyld::log(" %s(RTLD_NEXT, %s) ==> %p\n", __func__
, symbolName
, result
);
1927 const char* str
= dyld::mkstringf("dlsym(RTLD_NEXT, %s): symbol not found", symbolName
);
1930 CRSetCrashLogMessage(NULL
);
1931 if ( dyld::gLogAPIs
)
1932 dyld::log(" %s(RTLD_NEXT, %s) ==> NULL\n", __func__
, symbolName
);
1935 // magic "search me, then what I would see" handle
1936 else if ( handle
== RTLD_SELF
) {
1937 #if SUPPORT_ACCELERATE_TABLES
1938 const mach_header
* mh
;
1941 if ( dyld::addressInCache(callerAddress
, &mh
, &path
, &index
) ) {
1942 // if dylib in cache is calling dlsym(RTLD_SELF,xxx) handle search differently
1943 result
= dyld::dlsymFromCache(RTLD_SELF
, underscoredName
, index
);
1944 if ( dyld::gLogAPIs
)
1945 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1949 ImageLoader
* callerImage
= dyld::findImageContainingAddress(callerAddress
);
1950 sym
= callerImage
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1951 if ( sym
!= NULL
) {
1952 CRSetCrashLogMessage(NULL
);
1953 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
1954 #if __has_feature(ptrauth_calls)
1955 // Sign the pointer if it points to a function
1956 // Note we only do this if the main executable is arm64e as otherwise we
1957 // may end up calling containsAddress on the accelerator tables.
1958 if ( result
&& (dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64E
) ) {
1959 const ImageLoader
* symbolImage
= image
;
1960 if (!symbolImage
->containsAddress(result
)) {
1961 symbolImage
= dyld::findImageContainingAddress(result
);
1963 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
1964 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
1965 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
1968 if ( dyld::gLogAPIs
)
1969 dyld::log(" %s(RTLD_SELF, %s) ==> %p\n", __func__
, symbolName
, result
);
1972 const char* str
= dyld::mkstringf("dlsym(RTLD_SELF, %s): symbol not found", symbolName
);
1975 CRSetCrashLogMessage(NULL
);
1976 if ( dyld::gLogAPIs
)
1977 dyld::log(" %s(RTLD_SELF, %s) ==> NULL\n", __func__
, symbolName
);
1980 #if SUPPORT_ACCELERATE_TABLES
1981 // check for mega dylib handle
1982 else if ( dyld::isCacheHandle(handle
) ) {
1983 result
= dyld::dlsymFromCache(handle
, underscoredName
, 0);
1984 if ( dyld::gLogAPIs
)
1985 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
1990 image
= (ImageLoader
*)(((uintptr_t)handle
) & (-4)); // clear mode bits
1991 if ( dyld::validImage(image
) ) {
1992 if ( (((uintptr_t)handle
) & 1) != 0 )
1993 sym
= image
->findExportedSymbol(underscoredName
, true, &image
); // search RTLD_FIRST way
1995 sym
= image
->findExportedSymbolInImageOrDependentImages(underscoredName
, dyld::gLinkContext
, &image
); // search image and what it links against
1997 if ( sym
!= NULL
) {
1998 CRSetCrashLogMessage(NULL
);
1999 ImageLoader
* callerImage
= NULL
;
2000 if ( sDynamicInterposing
) {
2001 // only take time to look up caller, if dynamic interposing in use
2002 callerImage
= dyld::findImageContainingAddress(callerAddress
);
2004 result
= (void*)image
->getExportedSymbolAddress(sym
, dyld::gLinkContext
, callerImage
, false, underscoredName
);
2005 #if __has_feature(ptrauth_calls)
2006 // Sign the pointer if it points to a function
2007 // Note we only do this if the main executable is arm64e as otherwise we
2008 // may end up calling containsAddress on the accelerator tables.
2009 if ( result
&& (dyld::gLinkContext
.mainExecutable
->machHeader()->cpusubtype
== CPU_SUBTYPE_ARM64E
) ) {
2010 const ImageLoader
* symbolImage
= image
;
2011 if (!symbolImage
->containsAddress(result
)) {
2012 symbolImage
= dyld::findImageContainingAddress(result
);
2014 const macho_section
*sect
= symbolImage
? symbolImage
->findSection(result
) : NULL
;
2015 if ( sect
&& ((sect
->flags
& S_ATTR_PURE_INSTRUCTIONS
) || (sect
->flags
& S_ATTR_SOME_INSTRUCTIONS
)) )
2016 result
= __builtin_ptrauth_sign_unauthenticated(result
, ptrauth_key_asia
, 0);
2019 if ( dyld::gLogAPIs
)
2020 dyld::log(" %s(%p, %s) ==> %p\n", __func__
, handle
, symbolName
, result
);
2023 const char* str
= dyld::mkstringf("dlsym(%p, %s): symbol not found", handle
, symbolName
);
2028 dlerrorSet("invalid handle passed to dlsym()");
2030 CRSetCrashLogMessage(NULL
);
2031 if ( dyld::gLogAPIs
)
2032 dyld::log(" %s(%p, %s) ==> NULL\n", __func__
, handle
, symbolName
);
2036 // Note this is only here to support ___pthread_abort in libpthread.a
2037 void* dlsym(void* handle
, const char* symbolName
) {
2038 return dlsym_internal(handle
, symbolName
, __builtin_return_address(1));
2042 // <rdar://problem/40352925> *_compat functions are for old binaries that have __dyld section and use it to bypass libdyld.dylib
2043 void* dlopen_compat(const char* path
, int mode
)
2045 return dlopen_internal(path
, mode
, (void*)dyld::mainExecutable()->machHeader());
2047 bool dlopen_preflight_compat(const char* path
)
2049 return dlopen_preflight_internal(path
, (void*)dyld::mainExecutable()->machHeader());
2051 void* dlsym_compat(void* handle
, const char* symbolName
)
2053 return dlsym_internal(handle
, symbolName
, (void*)dyld::mainExecutable()->machHeader());
2059 const struct dyld_all_image_infos
* _dyld_get_all_image_infos()
2061 return dyld::gProcessInfo
;
2065 #if SUPPORT_ZERO_COST_EXCEPTIONS
2066 static bool client_dyld_find_unwind_sections(void* addr
, dyld_unwind_sections
* info
)
2068 //if ( dyld::gLogAPIs )
2069 // dyld::log("%s(%p, %p)\n", __func__, addr, info);
2071 addr
= stripPointer(addr
);
2073 #if SUPPORT_ACCELERATE_TABLES
2074 if ( dyld::findUnwindSections(addr
, info
) )
2077 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2078 if ( image
!= NULL
) {
2079 image
->getUnwindInfo(info
);
2087 const char* dyld_image_path_containing_address(const void* address
)
2089 if ( dyld::gLogAPIs
)
2090 dyld::log("%s(%p)\n", __func__
, address
);
2092 address
= (void*)stripPointer(address
);
2094 #if SUPPORT_ACCELERATE_TABLES
2095 const mach_header
* mh
;
2097 if ( dyld::addressInCache(address
, &mh
, &path
) )
2101 ImageLoader
* image
= dyld::findImageContainingAddress(address
);
2102 if ( image
!= NULL
) {
2103 return image
->getRealPath();
2110 bool dyld_shared_cache_some_image_overridden()
2112 return dyld::gSharedCacheOverridden
;
2116 void dyld_dynamic_interpose(const struct mach_header
* mh
, const struct dyld_interpose_tuple array
[], size_t count
)
2120 if ( array
== NULL
)
2124 ImageLoader
* image
= dyld::findImageByMachHeader(mh
);
2125 if ( image
== NULL
)
2128 // make pass at bound references in this image and update them
2129 dyld::gLinkContext
.dynamicInterposeArray
= array
;
2130 dyld::gLinkContext
.dynamicInterposeCount
= count
;
2131 image
->dynamicInterpose(dyld::gLinkContext
);
2132 dyld::gLinkContext
.dynamicInterposeArray
= NULL
;
2133 dyld::gLinkContext
.dynamicInterposeCount
= 0;
2135 // leave interposing info so any future (lazy) binding will get it too
2136 image
->addDynamicInterposingTuples(array
, count
);
2138 sDynamicInterposing
= true;
2142 bool _dyld_is_memory_immutable(const void* addr
, size_t length
)
2144 if ( dyld::gLogAPIs
)
2145 dyld::log("%s(%p, %ld)\n", __func__
, addr
, length
);
2147 uintptr_t checkStart
= (uintptr_t)addr
;
2148 uintptr_t checkEnd
= checkStart
+ length
;
2150 // quick check to see if in r/o region of shared cache. If so return true.
2151 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2152 if ( cache
!= nullptr ) {
2153 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2154 uintptr_t roStart
= (uintptr_t)cache
;
2155 uintptr_t roEnd
= roStart
+ (uintptr_t)mappings
[0].size
;
2156 if ( (roStart
< checkStart
) && (checkEnd
< roEnd
) )
2160 // Otherwise find if addr is in a dyld loaded image
2161 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2162 if ( image
!= NULL
) {
2163 // <rdar://problem/24091154> already checked for r/o portion of cache
2164 if ( image
->inSharedCache() )
2166 if ( !image
->neverUnload() )
2168 for (unsigned i
=0, e
=image
->segmentCount(); i
< e
; ++i
) {
2169 if ( (image
->segActualLoadAddress(i
) < checkStart
) && (checkEnd
< image
->segActualEndAddress(i
)) ) {
2170 return !image
->segWriteable(i
);
2179 void _dyld_objc_notify_register(_dyld_objc_notify_mapped mapped
,
2180 _dyld_objc_notify_init init
,
2181 _dyld_objc_notify_unmapped unmapped
)
2183 dyld::registerObjCNotifiers(mapped
, init
, unmapped
);
2187 bool _dyld_get_shared_cache_uuid(uuid_t uuid
)
2189 return dyld::sharedCacheUUID(uuid
);
2192 const void* _dyld_get_shared_cache_range(size_t* length
)
2194 const DyldSharedCache
* cache
= (DyldSharedCache
*)dyld::imMemorySharedCacheHeader();
2195 if ( cache
!= nullptr ) {
2196 const dyld_cache_mapping_info
* const mappings
= (dyld_cache_mapping_info
*)((char*)cache
+ cache
->header
.mappingOffset
);
2197 *length
= (size_t)((mappings
[2].address
+ mappings
[2].size
) - mappings
[0].address
);
2203 void _dyld_images_for_addresses(unsigned count
, const void* addresses
[], struct dyld_image_uuid_offset infos
[])
2205 for (unsigned i
=0; i
< count
; ++i
) {
2206 const void* addr
= addresses
[i
];
2207 addr
= stripPointer(addr
);
2208 bzero(&infos
[i
], sizeof(dyld_image_uuid_offset
));
2209 #if SUPPORT_ACCELERATE_TABLES
2210 const mach_header
* mh
;
2212 if ( dyld::addressInCache(addr
, &mh
, &path
) ) {
2213 infos
[i
].image
= mh
;
2214 infos
[i
].offsetInImage
= (uintptr_t)addr
- (uintptr_t)mh
;
2215 ((dyld3::MachOFile
*)mh
)->getUuid(infos
[i
].uuid
);
2219 ImageLoader
* image
= dyld::findImageContainingAddress(addr
);
2220 if ( image
!= nullptr ) {
2221 infos
[i
].image
= image
->machHeader();
2222 infos
[i
].offsetInImage
= (uintptr_t)addr
- (uintptr_t)(image
->machHeader());
2223 image
->getUUID(infos
[i
].uuid
);
2228 void _dyld_register_for_image_loads(void (*func
)(const mach_header
* mh
, const char* path
, bool unloadable
))
2230 if ( dyld::gLogAPIs
)
2231 dyld::log("%s(%p)\n", __func__
, (void *)func
);
2232 dyld::registerLoadCallback(func
);
2235 void _dyld_register_for_bulk_image_loads(void (*func
)(unsigned imageCount
, const struct mach_header
* mhs
[], const char* paths
[]))
2237 if ( dyld::gLogAPIs
)
2238 dyld::log("%s(%p)\n", __func__
, (void *)func
);
2239 dyld::registerBulkLoadCallback(func
);
2242 void _dyld_register_driverkit_main(void (*mainFunc
)())
2244 dyld::setMainEntry(mainFunc
);